@verapay/verapay-js 1.5.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -85,13 +85,13 @@ const verapay = new VerapayClient({
85
85
  });
86
86
  ```
87
87
 
88
- If your Merchant account is associated with a Partner, include `partnerFee` — the fee you are taking from the payment, which you are responsible for calculating. It must not exceed the payment `amount`:
88
+ If your Merchant account is associated with a Partner, include `platformFee` — the partner's margin taken from the payment, which you are responsible for calculating. It must not exceed the payment `amount`. VeraPay's own fee is computed server-side from your partner pricing config and must not be passed here:
89
89
 
90
90
  ```typescript
91
91
  const verapay = new VerapayClient({
92
92
  apiKey: 'vpy_pk_test_...',
93
93
  merchantId: 'your-merchant-id',
94
- paymentData: { amount: 5000, currency: 'gbp', partnerFee: 250 },
94
+ paymentData: { amount: 5000, currency: 'gbp', platformFee: 250 },
95
95
  });
96
96
 
97
97
  await verapay.mountPaymentForm('#payment-form');
@@ -527,7 +527,7 @@ new VerapayClient(config: VerapayConfig)
527
527
  |---|---|---|---|
528
528
  | `amount` | `number` | Yes | Amount in the smallest currency unit (e.g., pence for GBP) |
529
529
  | `currency` | `string` | Yes | ISO 4217 currency code (e.g., `'gbp'`) |
530
- | `partnerFee` | `number` | No | Your fee in the smallest currency unit, taken from the payment amount. Only applicable if your Merchant account is associated with a Partner — ignored otherwise. You are responsible for calculating this value. Must not exceed `amount`. |
530
+ | `platformFee` | `number` | No | The partner's margin in the smallest currency unit, taken from the payment amount. Only applicable if your Merchant account is associated with a Partner — ignored otherwise. You are responsible for calculating this value. Must not exceed `amount`. VeraPay's own fee is computed server-side from your partner pricing config and must not be passed here. |
531
531
 
532
532
  #### Methods
533
533
 
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var stripeJs=require('@stripe/stripe-js'),tsMoney=require('ts-money');var a=class s extends Error{constructor(e,t="PAYMENT_FAILED",n){super(e),this.name="VerapayError",this.code=t,this.details={code:t,message:e,formattedMessage:this.formatMessage(e,t),...n},Error.captureStackTrace&&Error.captureStackTrace(this,s);}formatMessage(e,t){return {VALIDATION_ERROR:"Please check your payment information and try again.",PAYMENT_FAILED:"Your payment could not be processed. Please try again.",AUTHENTICATION_FAILED:"Payment authentication failed. Please try again.",NETWORK_ERROR:"Network error. Please check your connection and try again.",STRIPE_ERROR:"Payment service error. Please try again later.",CONFIGURATION_ERROR:"Configuration error. Please contact support.",CARD_DECLINED:"Your card was declined. Please use a different payment method.",INSUFFICIENT_FUNDS:"Insufficient funds. Please use a different payment method.",EXPIRED_CARD:"Your card has expired. Please use a different payment method."}[t]||e}toJSON(){return {name:this.name,code:this.code,message:this.message,details:this.details}}};var l=class extends a{constructor(e,t,n){super(e,"VALIDATION_ERROR",{field:t,metadata:n}),this.name="ValidationError";}};var o=class s extends a{constructor(e,t,n){let i=s.mapStripeCode(t);super(e,i,{stripeCode:t,metadata:n}),this.name="PaymentError";}static mapStripeCode(e){return e?{card_declined:"CARD_DECLINED",insufficient_funds:"INSUFFICIENT_FUNDS",expired_card:"EXPIRED_CARD",incorrect_cvc:"VALIDATION_ERROR",processing_error:"PAYMENT_FAILED",authentication_failed:"AUTHENTICATION_FAILED"}[e]||"PAYMENT_FAILED":"PAYMENT_FAILED"}};var u=class{static formatForUser(e){return "formattedMessage"in e?e.formattedMessage:"details"in e&&e.details&&typeof e.details=="object"&&"formattedMessage"in e.details&&typeof e.details.formattedMessage=="string"?e.details.formattedMessage:"An unexpected error occurred. Please try again."}static formatForDeveloper(e){return "code"in e&&"message"in e?`[${e.code}] ${e.message}`:e.message||"Unknown error"}static toJSON(e){return "toJSON"in e&&typeof e.toJSON=="function"?e.toJSON():{name:e.name||"Error",message:e.message,..."code"in e&&{code:e.code},..."details"in e&&{details:e.details}}}};var y=class{constructor(e){this.stripe=e;}async confirmPayment(e,t){let n=await this.stripe.confirmPayment({clientSecret:t,confirmParams:{payment_method:e,return_url:window.location.href},redirect:"if_required"});if(n.error)throw new o(n.error.message||"Payment failed",n.error.code);return n}async confirmCardPayment(e,t){let n=await this.stripe.confirmCardPayment(t,{payment_method:e});if(n.error)throw new o(n.error.message||"Payment failed",n.error.code);return n}async createPaymentMethod(e,t=false){let n;if(!t)n=await this.stripe.createPaymentMethod({elements:e});else {let r=(await e.getElement("address",{mode:"billing"}).getValue()).value;n=await this.stripe.createPaymentMethod({type:"card",card:e.getElement("cardNumber"),billing_details:{name:r.name,address:{...r.address,line2:r.address.line2??void 0}}});}if(n.error||!n.paymentMethod)throw new o(n.error?.message||"Failed to create payment method",n.error?.code);return n.paymentMethod.id}async retrievePaymentIntent(e){let t=await this.stripe.retrievePaymentIntent(e);if(t.error)throw new o(t.error.message||"Failed to retrieve payment intent",t.error.code);return t}async confirmCardSetup(e,t){let n=await this.stripe.confirmCardSetup(t,{payment_method:e});if(n.error)throw new o(n.error.message||"Card setup failed",n.error.code);return n}async retrieveSetupIntent(e){let t=await this.stripe.retrieveSetupIntent(e);if(t.error)throw new o(t.error.message||"Failed to retrieve setup intent",t.error.code);return t}};var p={showIcon:true,iconStyle:"solid",placeholders:{cardNumber:"1234 1234 1234 1234",cardExpiry:"MM / YY - TESTING",cardCvc:"CVC"},style:{base:{color:"#333333",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"16px","::placeholder":{color:"#aab7c4"}},complete:{color:"#333333"},empty:{},invalid:{color:"#df1b41"}}},S={cardNumber:"Card number",cardExpiry:"Expiry date",cardCvc:"CVC",address:"Address"},h=class{constructor(e,t,n){this.stripe=e;this.config=t;this.clientSecret=n;this.elements=null;this.mountedElements=new Map;this.elementStates=new Map;if(!n)throw new a("Client secret not initialized","CONFIGURATION_ERROR")}mountPaymentElement(e){if(!this.elements){let i={clientSecret:this.clientSecret,appearance:this.config.appearance,locale:this.config.locale,fonts:this.config.fonts,paymentMethodCreation:"manual"};this.elements=this.stripe.elements(i);}if(!document.querySelector(e))throw new a(`Element not found: ${e}`,"CONFIGURATION_ERROR");let n=this.elements.create("payment",{layout:"tabs",wallets:{link:"never"}});n.mount(e),this.mountedElements.set("payment",n);}mountCardNumberElement(e){this.mountIndividualFormElement(e,"cardNumber",this.cardElementOptions("cardNumber"));}mountCardExpiryElement(e){this.mountIndividualFormElement(e,"cardExpiry",this.cardElementOptions("cardExpiry"));}mountCardCvcElement(e){this.mountIndividualFormElement(e,"cardCvc",this.cardElementOptions("cardCvc"));}mountAddressElement(e,t){this.mountIndividualFormElement(e,"address",{mode:t});}cardElementOptions(e){let{elementsConfig:t}=this.config,n={placeholder:t?.placeholders?.[e]??p.placeholders[e],style:{base:{...p.style.base,...t?.style?.base},complete:{...p.style.complete,...t?.style?.complete},empty:{...p.style.empty,...t?.style?.empty},invalid:{...p.style.invalid,...t?.style?.invalid}}};return e==="cardNumber"&&(n.showIcon=t?.showIcon??p.showIcon,n.iconStyle=t?.iconStyle??p.iconStyle),n}mountIndividualFormElement(e,t,n){if(!document.querySelector(e))throw new a(`Element not found: ${e}`,"CONFIGURATION_ERROR");let r=this.createIndividualFormElement(t,n);r.mount(e),this.mountedElements.set(t,r),this.trackElementState(t,r);}createIndividualFormElement(e,t){return this.elements||(this.elements=this.stripe.elements({appearance:this.config.appearance,locale:this.config.locale,fonts:this.config.fonts,paymentMethodCreation:"manual"})),this.elements.create(e,t)}async validate(){let e=[];for(let[t,n]of this.elementStates.entries())n.complete||e.push({field:t,message:n.error??`${S[t]??t} failed validation`});return {isValid:e.length===0,errors:e}}getElements(){return this.elements}unmountAll(){for(let e of this.mountedElements.values())e.unmount();this.mountedElements.clear(),this.elementStates.clear();}trackElementState(e,t){this.elementStates.set(e,{complete:false});let n=i=>{this.elementStates.set(e,{complete:i.complete,error:i.error?.message});};t.on("change",n);}};var g=class{constructor(){this.extensions=[];}add(e){this.extensions.push(e);}async runBeforePayment(e){let t=e;for(let n of this.extensions)n.beforePayment&&(t=await n.beforePayment(t));return t}async runAfterPayment(e){await Promise.all(this.extensions.filter(t=>t.afterPayment).map(t=>t.afterPayment(e)));}async runOnError(e){await Promise.all(this.extensions.filter(t=>t.onPaymentError).map(t=>t.onPaymentError(e)));}};var f=class{constructor(e,t,n){this.stripeAdapter=e;this.elementsManager=t;this.verapayService=n;}async process(e,t){let n=this.elementsManager.getElements();await this.validatePaymentCanProceed(n,t),await n.submit();let i=await this.stripeAdapter.createPaymentMethod(n,t.isUsingIndividualFormElements);return await this.verapayService.processPrePayment({merchantId:t.merchantId,paymentIntentId:t.paymentIntentId,paymentMethodId:i,amount:t.amount,currency:t.currency,customerData:{email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName},description:e.description,metadata:e.metadata}),this.confirm(t.clientSecret,{paymentMethodId:i,isUsingStripePaymentElement:t.isUsingStripePaymentElement,isUsingIndividualFormElements:t.isUsingIndividualFormElements})}async validatePaymentCanProceed(e,t){if(!e)throw new a("Payment form not mounted","CONFIGURATION_ERROR");if(t.isUsingStripePaymentElement&&t.isUsingIndividualFormElements)throw new a("Both forms of payment form in use");if(t.isUsingIndividualFormElements){let n=await this.elementsManager.validate();if(!n.isValid)throw new a(n.errors[0].message,"VALIDATION_ERROR")}}async confirm(e,t={}){let n;return t.isUsingStripePaymentElement?n=await this.stripeAdapter.confirmPayment(t.paymentMethodId||"",e):t.isUsingIndividualFormElements?n=await this.stripeAdapter.confirmCardPayment(t.paymentMethodId||"",e):n=await this.stripeAdapter.confirmPayment(t.paymentMethodId||"",e),this.formatPaymentResult(n)}async retrievePaymentIntent(e){let t=await this.stripeAdapter.retrievePaymentIntent(e);return this.formatPaymentResult(t)}formatPaymentResult(e){let t=e.paymentIntent,n="failed";return t.status==="succeeded"?n="succeeded":["processing","requires_action","requires_confirmation"].includes(t.status)&&(n="processing"),{success:t.status==="succeeded",paymentIntentId:t.id,status:n}}};var I=class{constructor(e,t){this.stripeAdapter=e;this.elementsManager=t;}async save(e,t){let n=this.elementsManager.getElements();await this.validateSetupCanProceed(n,t),await n.submit();let i=await this.stripeAdapter.createPaymentMethod(n,t.isUsingIndividualFormElements),r=await this.stripeAdapter.confirmCardSetup(i,e);return this.formatSetupResult(r)}async retrieve(e){let t=await this.stripeAdapter.retrieveSetupIntent(e);return this.formatSetupResult(t)}async validateSetupCanProceed(e,t){if(!e)throw new a("Card form not mounted","CONFIGURATION_ERROR");if(t.isUsingStripePaymentElement&&t.isUsingIndividualFormElements)throw new a("Both forms of card form in use","CONFIGURATION_ERROR");if(t.isUsingIndividualFormElements){let n=await this.elementsManager.validate();if(!n.isValid)throw new a(n.errors[0].message,"VALIDATION_ERROR")}}formatSetupResult(e){let t=e.setupIntent,n="failed";t.status==="succeeded"?n="succeeded":t.status==="processing"?n="processing":(t.status==="requires_action"||t.status==="requires_confirmation")&&(n="requires_action");let i=t.payment_method,r=typeof i=="string"?i:i?.id;return {success:t.status==="succeeded",savedPaymentMethodId:r,setupIntentId:t.id,status:n}}};var d=class{constructor(e,t){this.baseUrl=e,this.apiKey=t;}setApiKey(e){this.apiKey=e;}async getPaymentIntentConfig(e){try{let t=await fetch(`${this.baseUrl}/v1/payment_intents/config?client_secret=${encodeURIComponent(e)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new a("Failed to fetch provider config","CONFIGURATION_ERROR");return t.json()}catch(t){throw t instanceof a?t:new a("Error connecting to Verapay API","NETWORK_ERROR")}}async getSetupIntentConfig(e){try{let t=await fetch(`${this.baseUrl}/v1/setup_intents/config?client_secret=${encodeURIComponent(e)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new a("Failed to fetch setup config","CONFIGURATION_ERROR");return t.json()}catch(t){throw t instanceof a?t:new a("Error connecting to Verapay API","NETWORK_ERROR")}}async initialisePayment(e){let{merchantId:t,paymentData:n}=e;try{let i=await fetch(`${this.baseUrl}/api/initialise-payment`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey?{"x-api-key":this.apiKey}:{}},body:JSON.stringify({merchantId:t,paymentData:{...n,paymentMethodType:"card"}})});if(!i.ok){let m=await i.json().catch(()=>({}));throw new a(this.extractErrorMessage(m,i.status),"CONFIGURATION_ERROR")}let r=await i.json();if(!r.clientSecret||!r.paymentIntentId)throw new a("Missing clientSecret or paymentIntentId in server response","CONFIGURATION_ERROR");return {paymentIntentId:r.paymentIntentId,clientSecret:r.clientSecret,connectAccountId:r.connectAccountId,stripePublishableKey:r.stripePublishableKey}}catch(i){throw i instanceof a?i:new a(i instanceof Error?i.message:"Unknown error occurred","CONFIGURATION_ERROR")}}async processPrePayment(e){try{let t=await fetch(`${this.baseUrl}/api/process-prepayment`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey?{"x-api-key":this.apiKey}:{}},body:JSON.stringify({merchantId:e.merchantId,paymentIntentId:e.paymentIntentId,paymentMethodId:e.paymentMethodId,amount:e.amount,currency:e.currency,customerData:e.customerData,description:e.description,metadata:e.metadata})});if(!t.ok){let n=await t.json().catch(()=>({}));throw new a(this.extractErrorMessage(n,t.status),"CONFIGURATION_ERROR")}}catch(t){throw t instanceof a?t:new a(t instanceof Error?t.message:"Unknown error occurred","CONFIGURATION_ERROR")}}extractErrorMessage(e,t){if(!e||typeof e!="object")return `HTTP error! status: ${t}`;let n=e,i=[n.error,n.message,n.details];for(let r of i){if(typeof r=="string"&&r.trim().length>0)return r;if(r&&typeof r=="object")try{return JSON.stringify(r)}catch{}}return `HTTP error! status: ${t}`}};function R(s){return s.startsWith("vpy_cs_test_")?s.replace("vpy_cs_test_",""):s.startsWith("vpy_cs_live_")?s.replace("vpy_cs_live_",""):s}var E=class E{constructor(e){this.stripeAdapter=null;this.elementsManager=null;this.paymentService=null;this.setupService=null;this.initializationPromise=null;this.isUsingStripePaymentElement=false;this.isUsingIndividualFormElements=false;this.intentKind="payment";this.rawSecret=null;this.paymentIntentId=null;this.amount=null;this.currency=null;this.merchantId=null;if(!e.apiKey&&!e.clientSecret)throw new a("Either apiKey or clientSecret is required.","CONFIGURATION_ERROR");if(e.apiKey&&e.clientSecret)throw new a("Cannot provide both apiKey and clientSecret. Use apiKey for frontend-initialized flows or clientSecret for backend-initialized flows.","CONFIGURATION_ERROR");e.apiKey&&!e.apiKey.includes("_pk_")&&typeof window<"u"&&console.warn("Verapay Security Warning: You are using a Secret Key in a frontend environment. Please use a Publishable Key (vpy_pk_...) instead."),this.config=e;let t=this.config.apiUrlOverride||E.BACKEND_URL;this.verapayService=new d(t,this.config.apiKey||""),this.extensionsManager=new g;}async initialize(){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{let e,t,n;if(this.config.clientSecret)if(this.intentKind=R(this.config.clientSecret).startsWith("seti_")?"setup":"payment",this.intentKind==="setup"){let r=await this.verapayService.getSetupIntentConfig(this.config.clientSecret);if(r.object!=="setup_intent_config")throw new a("Unexpected configuration returned for setup intent","CONFIGURATION_ERROR");e=this.config.clientSecret,t="",n=r.publishableKey,this.merchantId=r.merchantId,r.verapayPublishableKey&&this.verapayService.setApiKey(r.verapayPublishableKey);}else {let r=await this.verapayService.getPaymentIntentConfig(this.config.clientSecret);e=this.config.clientSecret,t=r.paymentIntentId,n=r.publishableKey,this.amount=r.amount,this.currency=r.currency,this.merchantId=r.merchantId,r.verapayPublishableKey&&this.verapayService.setApiKey(r.verapayPublishableKey);}else {this.validatePaymentInitialisation();let r=await this.verapayService.initialisePayment({merchantId:this.config.merchantId??"",paymentData:this.config.paymentData});e=r.clientSecret,t=r.paymentIntentId,n=r.stripePublishableKey,this.amount=this.config.paymentData.amount,this.currency=this.config.paymentData.currency,this.merchantId=this.config.merchantId??"";}this.rawSecret=R(e),this.paymentIntentId=t;let i=await stripeJs.loadStripe(n);if(!i)throw new a("Failed to load Stripe","CONFIGURATION_ERROR");this.stripeAdapter=new y(i),this.elementsManager=new h(i,this.config,this.rawSecret),this.paymentService=new f(this.stripeAdapter,this.elementsManager,this.verapayService),this.setupService=new I(this.stripeAdapter,this.elementsManager);})().catch(e=>{throw this.initializationPromise=null,e}),this.initializationPromise)}async confirmPayment(){return await this.ensureInitialized(),this.assertIntentKind("payment","confirmPayment"),this.paymentService.confirm(this.rawSecret,{isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements})}async saveCard(){await this.ensureInitialized(),this.assertIntentKind("setup","saveCard");try{return await this.setupService.save(this.rawSecret,{isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements})}catch(e){throw this.handlePaymentError(e)}}async retrieveSetupIntent(){return await this.ensureInitialized(),this.assertIntentKind("setup","retrieveSetupIntent"),this.setupService.retrieve(this.rawSecret)}teardown(){this.elementsManager?.unmountAll(),this.stripeAdapter=null,this.elementsManager=null,this.paymentService=null,this.setupService=null,this.initializationPromise=null,this.isUsingStripePaymentElement=false,this.isUsingIndividualFormElements=false,this.intentKind="payment",this.rawSecret=null,this.paymentIntentId=null,this.amount=null,this.currency=null,this.merchantId=null;}async retrievePaymentIntent(){return await this.ensureInitialized(),this.paymentService.retrievePaymentIntent(this.rawSecret)}async processPayment(e){await this.ensureInitialized(),this.assertIntentKind("payment","processPayment");let t=await this.extensionsManager.runBeforePayment(e);try{let n=await this.paymentService.process(t,{merchantId:this.merchantId,paymentIntentId:this.paymentIntentId,clientSecret:this.rawSecret,amount:this.amount,currency:this.currency,isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements});return await this.extensionsManager.runAfterPayment(n),n}catch(n){throw await this.extensionsManager.runOnError(n),this.handlePaymentError(n)}}async mountPaymentForm(e){await this.ensureInitialized(),this.elementsManager.mountPaymentElement(e),this.isUsingStripePaymentElement=true;}async mountCardNumber(e){await this.ensureInitialized(),this.elementsManager.mountCardNumberElement(e),this.isUsingIndividualFormElements=true;}async mountCardExpiry(e){await this.ensureInitialized(),this.elementsManager.mountCardExpiryElement(e),this.isUsingIndividualFormElements=true;}async mountCardCvc(e){await this.ensureInitialized(),this.elementsManager.mountCardCvcElement(e),this.isUsingIndividualFormElements=true;}async mountAddress(e,t){await this.ensureInitialized(),this.elementsManager.mountAddressElement(e,t),this.isUsingIndividualFormElements=true;}addExtension(e){this.extensionsManager.add(e);}async ensureInitialized(){this.stripeAdapter||await this.initialize();}assertIntentKind(e,t){if(this.intentKind!==e)throw new a(`${t} requires a ${e} intent client secret`,"CONFIGURATION_ERROR")}validatePaymentInitialisation(){if(!this.config.paymentData)throw new a("paymentData is required for frontend-initialized flows.","CONFIGURATION_ERROR");let{amount:e,currency:t,partnerFee:n}=this.config.paymentData;if(!t)throw new l("Currency is required","currency");let i=t.toUpperCase(),r=this.toMoney(e,i,"amount");if(r.isZero()||r.isNegative())throw new l("Amount must be greater than 0","amount");if(n!==void 0){let m=this.toMoney(n,i,"partnerFee");if(m.isNegative())throw new l("partnerFee cannot be negative","partnerFee");if(m.greaterThan(r))throw new l("partnerFee cannot exceed the payment amount","partnerFee")}}toMoney(e,t,n){try{return tsMoney.Money.fromInteger(e,t)}catch{throw new l(`${n} must be an integer in the smallest currency unit (e.g., cents for USD)`,n)}}handlePaymentError(e){if(e instanceof a)return e;let t=e instanceof Error?e.message:"Payment failed",n=e?.code;return new o(t,n)}};E.BACKEND_URL="https://api.verapay.app";var w=E;var P=class{validateCardNumber(e){let t=e.replace(/\D/g,"");if(t.length<13||t.length>19)return false;let n=0,i=false;for(let r=t.length-1;r>=0;r--){let m=parseInt(t[r],10);i&&(m*=2,m>9&&(m-=9)),n+=m,i=!i;}return n%10===0}detectCardType(e){let t=e.replace(/\D/g,"");return /^4/.test(t)?"visa":/^5[1-5]/.test(t)?"mastercard":/^3[47]/.test(t)?"amex":/^6(?:011|5)/.test(t)?"discover":"unknown"}validateExpiry(e,t){let n=new Date,i=n.getFullYear(),r=n.getMonth()+1;if(e<1||e>12)return false;let m=t<100?2e3+t:t;return !(m<i||m===i&&e<r)}validateCVC(e,t="unknown"){let n=e.replace(/\D/g,"");return t==="amex"?n.length===4:n.length===3||n.length===4}validateAll(e,t,n,i){let r=this.detectCardType(e);return {number:{isValid:this.validateCardNumber(e),cardType:r},expiry:{isValid:this.validateExpiry(t,n),month:t,year:n},cvc:{isValid:this.validateCVC(i,r),length:i.replace(/\D/g,"").length}}}};var v=class{static sanitizeCardNumber(e){return e.replace(/\D/g,"")}static formatCardNumber(e){return this.sanitizeCardNumber(e).replace(/(\d{4})/g,"$1 ").trim()}static sanitizeCVC(e){return e.replace(/\D/g,"").slice(0,4)}static sanitizeExpiry(e){let t=e.replace(/\D/g,"");return t.length===4?{month:parseInt(t.slice(0,2),10),year:parseInt(t.slice(2,4),10)}:t.length===6?{month:parseInt(t.slice(0,2),10),year:parseInt(t.slice(2,6),10)}:null}};var ve="1.4.0";
1
+ 'use strict';var stripeJs=require('@stripe/stripe-js'),tsMoney=require('ts-money');var a=class s extends Error{constructor(e,t="PAYMENT_FAILED",n){super(e),this.name="VerapayError",this.code=t,this.details={code:t,message:e,formattedMessage:this.formatMessage(e,t),...n},Error.captureStackTrace&&Error.captureStackTrace(this,s);}formatMessage(e,t){return {VALIDATION_ERROR:"Please check your payment information and try again.",PAYMENT_FAILED:"Your payment could not be processed. Please try again.",AUTHENTICATION_FAILED:"Payment authentication failed. Please try again.",NETWORK_ERROR:"Network error. Please check your connection and try again.",STRIPE_ERROR:"Payment service error. Please try again later.",CONFIGURATION_ERROR:"Configuration error. Please contact support.",CARD_DECLINED:"Your card was declined. Please use a different payment method.",INSUFFICIENT_FUNDS:"Insufficient funds. Please use a different payment method.",EXPIRED_CARD:"Your card has expired. Please use a different payment method."}[t]||e}toJSON(){return {name:this.name,code:this.code,message:this.message,details:this.details}}};var l=class extends a{constructor(e,t,n){super(e,"VALIDATION_ERROR",{field:t,metadata:n}),this.name="ValidationError";}};var o=class s extends a{constructor(e,t,n){let i=s.mapStripeCode(t);super(e,i,{stripeCode:t,metadata:n}),this.name="PaymentError";}static mapStripeCode(e){return e?{card_declined:"CARD_DECLINED",insufficient_funds:"INSUFFICIENT_FUNDS",expired_card:"EXPIRED_CARD",incorrect_cvc:"VALIDATION_ERROR",processing_error:"PAYMENT_FAILED",authentication_failed:"AUTHENTICATION_FAILED"}[e]||"PAYMENT_FAILED":"PAYMENT_FAILED"}};var u=class{static formatForUser(e){return "formattedMessage"in e?e.formattedMessage:"details"in e&&e.details&&typeof e.details=="object"&&"formattedMessage"in e.details&&typeof e.details.formattedMessage=="string"?e.details.formattedMessage:"An unexpected error occurred. Please try again."}static formatForDeveloper(e){return "code"in e&&"message"in e?`[${e.code}] ${e.message}`:e.message||"Unknown error"}static toJSON(e){return "toJSON"in e&&typeof e.toJSON=="function"?e.toJSON():{name:e.name||"Error",message:e.message,..."code"in e&&{code:e.code},..."details"in e&&{details:e.details}}}};var y=class{constructor(e){this.stripe=e;}async confirmPayment(e,t){let n=await this.stripe.confirmPayment({clientSecret:t,confirmParams:{payment_method:e,return_url:window.location.href},redirect:"if_required"});if(n.error)throw new o(n.error.message||"Payment failed",n.error.code);return n}async confirmCardPayment(e,t){let n=await this.stripe.confirmCardPayment(t,{payment_method:e});if(n.error)throw new o(n.error.message||"Payment failed",n.error.code);return n}async createPaymentMethod(e,t=false){let n;if(!t)n=await this.stripe.createPaymentMethod({elements:e});else {let r=(await e.getElement("address",{mode:"billing"}).getValue()).value;n=await this.stripe.createPaymentMethod({type:"card",card:e.getElement("cardNumber"),billing_details:{name:r.name,address:{...r.address,line2:r.address.line2??void 0}}});}if(n.error||!n.paymentMethod)throw new o(n.error?.message||"Failed to create payment method",n.error?.code);return n.paymentMethod.id}async retrievePaymentIntent(e){let t=await this.stripe.retrievePaymentIntent(e);if(t.error)throw new o(t.error.message||"Failed to retrieve payment intent",t.error.code);return t}async confirmCardSetup(e,t){let n=await this.stripe.confirmCardSetup(t,{payment_method:e});if(n.error)throw new o(n.error.message||"Card setup failed",n.error.code);return n}async retrieveSetupIntent(e){let t=await this.stripe.retrieveSetupIntent(e);if(t.error)throw new o(t.error.message||"Failed to retrieve setup intent",t.error.code);return t}};var p={showIcon:true,iconStyle:"solid",placeholders:{cardNumber:"1234 1234 1234 1234",cardExpiry:"MM / YY - TESTING",cardCvc:"CVC"},style:{base:{color:"#333333",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"16px","::placeholder":{color:"#aab7c4"}},complete:{color:"#333333"},empty:{},invalid:{color:"#df1b41"}}},S={cardNumber:"Card number",cardExpiry:"Expiry date",cardCvc:"CVC",address:"Address"},h=class{constructor(e,t,n){this.stripe=e;this.config=t;this.clientSecret=n;this.elements=null;this.mountedElements=new Map;this.elementStates=new Map;if(!n)throw new a("Client secret not initialized","CONFIGURATION_ERROR")}mountPaymentElement(e){if(!this.elements){let i={clientSecret:this.clientSecret,appearance:this.config.appearance,locale:this.config.locale,fonts:this.config.fonts,paymentMethodCreation:"manual"};this.elements=this.stripe.elements(i);}if(!document.querySelector(e))throw new a(`Element not found: ${e}`,"CONFIGURATION_ERROR");let n=this.elements.create("payment",{layout:"tabs",wallets:{link:"never"}});n.mount(e),this.mountedElements.set("payment",n);}mountCardNumberElement(e){this.mountIndividualFormElement(e,"cardNumber",this.cardElementOptions("cardNumber"));}mountCardExpiryElement(e){this.mountIndividualFormElement(e,"cardExpiry",this.cardElementOptions("cardExpiry"));}mountCardCvcElement(e){this.mountIndividualFormElement(e,"cardCvc",this.cardElementOptions("cardCvc"));}mountAddressElement(e,t){this.mountIndividualFormElement(e,"address",{mode:t});}cardElementOptions(e){let{elementsConfig:t}=this.config,n={placeholder:t?.placeholders?.[e]??p.placeholders[e],style:{base:{...p.style.base,...t?.style?.base},complete:{...p.style.complete,...t?.style?.complete},empty:{...p.style.empty,...t?.style?.empty},invalid:{...p.style.invalid,...t?.style?.invalid}}};return e==="cardNumber"&&(n.showIcon=t?.showIcon??p.showIcon,n.iconStyle=t?.iconStyle??p.iconStyle),n}mountIndividualFormElement(e,t,n){if(!document.querySelector(e))throw new a(`Element not found: ${e}`,"CONFIGURATION_ERROR");let r=this.createIndividualFormElement(t,n);r.mount(e),this.mountedElements.set(t,r),this.trackElementState(t,r);}createIndividualFormElement(e,t){return this.elements||(this.elements=this.stripe.elements({appearance:this.config.appearance,locale:this.config.locale,fonts:this.config.fonts,paymentMethodCreation:"manual"})),this.elements.create(e,t)}async validate(){let e=[];for(let[t,n]of this.elementStates.entries())n.complete||e.push({field:t,message:n.error??`${S[t]??t} failed validation`});return {isValid:e.length===0,errors:e}}getElements(){return this.elements}unmountAll(){for(let e of this.mountedElements.values())e.unmount();this.mountedElements.clear(),this.elementStates.clear();}trackElementState(e,t){this.elementStates.set(e,{complete:false});let n=i=>{this.elementStates.set(e,{complete:i.complete,error:i.error?.message});};t.on("change",n);}};var f=class{constructor(){this.extensions=[];}add(e){this.extensions.push(e);}async runBeforePayment(e){let t=e;for(let n of this.extensions)n.beforePayment&&(t=await n.beforePayment(t));return t}async runAfterPayment(e){await Promise.all(this.extensions.filter(t=>t.afterPayment).map(t=>t.afterPayment(e)));}async runOnError(e){await Promise.all(this.extensions.filter(t=>t.onPaymentError).map(t=>t.onPaymentError(e)));}};var g=class{constructor(e,t,n){this.stripeAdapter=e;this.elementsManager=t;this.verapayService=n;}async process(e,t){let n=this.elementsManager.getElements();await this.validatePaymentCanProceed(n,t),await n.submit();let i=await this.stripeAdapter.createPaymentMethod(n,t.isUsingIndividualFormElements);return await this.verapayService.processPrePayment({merchantId:t.merchantId,paymentIntentId:t.paymentIntentId,paymentMethodId:i,amount:t.amount,currency:t.currency,customerData:{email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName},description:e.description,metadata:e.metadata}),this.confirm(t.clientSecret,{paymentMethodId:i,isUsingStripePaymentElement:t.isUsingStripePaymentElement,isUsingIndividualFormElements:t.isUsingIndividualFormElements})}async validatePaymentCanProceed(e,t){if(!e)throw new a("Payment form not mounted","CONFIGURATION_ERROR");if(t.isUsingStripePaymentElement&&t.isUsingIndividualFormElements)throw new a("Both forms of payment form in use");if(t.isUsingIndividualFormElements){let n=await this.elementsManager.validate();if(!n.isValid)throw new a(n.errors[0].message,"VALIDATION_ERROR")}}async confirm(e,t={}){let n;return t.isUsingStripePaymentElement?n=await this.stripeAdapter.confirmPayment(t.paymentMethodId||"",e):t.isUsingIndividualFormElements?n=await this.stripeAdapter.confirmCardPayment(t.paymentMethodId||"",e):n=await this.stripeAdapter.confirmPayment(t.paymentMethodId||"",e),this.formatPaymentResult(n)}async retrievePaymentIntent(e){let t=await this.stripeAdapter.retrievePaymentIntent(e);return this.formatPaymentResult(t)}formatPaymentResult(e){let t=e.paymentIntent,n="failed";return t.status==="succeeded"?n="succeeded":["processing","requires_action","requires_confirmation"].includes(t.status)&&(n="processing"),{success:t.status==="succeeded",paymentIntentId:t.id,status:n}}};var I=class{constructor(e,t){this.stripeAdapter=e;this.elementsManager=t;}async save(e,t){let n=this.elementsManager.getElements();await this.validateSetupCanProceed(n,t),await n.submit();let i=await this.stripeAdapter.createPaymentMethod(n,t.isUsingIndividualFormElements),r=await this.stripeAdapter.confirmCardSetup(i,e);return this.formatSetupResult(r)}async retrieve(e){let t=await this.stripeAdapter.retrieveSetupIntent(e);return this.formatSetupResult(t)}async validateSetupCanProceed(e,t){if(!e)throw new a("Card form not mounted","CONFIGURATION_ERROR");if(t.isUsingStripePaymentElement&&t.isUsingIndividualFormElements)throw new a("Both forms of card form in use","CONFIGURATION_ERROR");if(t.isUsingIndividualFormElements){let n=await this.elementsManager.validate();if(!n.isValid)throw new a(n.errors[0].message,"VALIDATION_ERROR")}}formatSetupResult(e){let t=e.setupIntent,n="failed";t.status==="succeeded"?n="succeeded":t.status==="processing"?n="processing":(t.status==="requires_action"||t.status==="requires_confirmation")&&(n="requires_action");let i=t.payment_method,r=typeof i=="string"?i:i?.id;return {success:t.status==="succeeded",savedPaymentMethodId:r,setupIntentId:t.id,status:n}}};var d=class{constructor(e,t){this.baseUrl=e,this.apiKey=t;}setApiKey(e){this.apiKey=e;}async getPaymentIntentConfig(e){try{let t=await fetch(`${this.baseUrl}/v1/payment_intents/config?client_secret=${encodeURIComponent(e)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new a("Failed to fetch provider config","CONFIGURATION_ERROR");return t.json()}catch(t){throw t instanceof a?t:new a("Error connecting to Verapay API","NETWORK_ERROR")}}async getSetupIntentConfig(e){try{let t=await fetch(`${this.baseUrl}/v1/setup_intents/config?client_secret=${encodeURIComponent(e)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new a("Failed to fetch setup config","CONFIGURATION_ERROR");return t.json()}catch(t){throw t instanceof a?t:new a("Error connecting to Verapay API","NETWORK_ERROR")}}async initialisePayment(e){let{merchantId:t,paymentData:n}=e;try{let i=await fetch(`${this.baseUrl}/api/initialise-payment`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey?{"x-api-key":this.apiKey}:{}},body:JSON.stringify({merchantId:t,paymentData:{...n,paymentMethodType:"card"}})});if(!i.ok){let m=await i.json().catch(()=>({}));throw new a(this.extractErrorMessage(m,i.status),"CONFIGURATION_ERROR")}let r=await i.json();if(!r.clientSecret||!r.paymentIntentId)throw new a("Missing clientSecret or paymentIntentId in server response","CONFIGURATION_ERROR");return {paymentIntentId:r.paymentIntentId,clientSecret:r.clientSecret,connectAccountId:r.connectAccountId,stripePublishableKey:r.stripePublishableKey}}catch(i){throw i instanceof a?i:new a(i instanceof Error?i.message:"Unknown error occurred","CONFIGURATION_ERROR")}}async processPrePayment(e){try{let t=await fetch(`${this.baseUrl}/api/process-prepayment`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey?{"x-api-key":this.apiKey}:{}},body:JSON.stringify({merchantId:e.merchantId,paymentIntentId:e.paymentIntentId,paymentMethodId:e.paymentMethodId,amount:e.amount,currency:e.currency,customerData:e.customerData,description:e.description,metadata:e.metadata})});if(!t.ok){let n=await t.json().catch(()=>({}));throw new a(this.extractErrorMessage(n,t.status),"CONFIGURATION_ERROR")}}catch(t){throw t instanceof a?t:new a(t instanceof Error?t.message:"Unknown error occurred","CONFIGURATION_ERROR")}}extractErrorMessage(e,t){if(!e||typeof e!="object")return `HTTP error! status: ${t}`;let n=e,i=[n.error,n.message,n.details];for(let r of i){if(typeof r=="string"&&r.trim().length>0)return r;if(r&&typeof r=="object")try{return JSON.stringify(r)}catch{}}return `HTTP error! status: ${t}`}};function R(s){return s.startsWith("vpy_cs_test_")?s.replace("vpy_cs_test_",""):s.startsWith("vpy_cs_live_")?s.replace("vpy_cs_live_",""):s}var E=class E{constructor(e){this.stripeAdapter=null;this.elementsManager=null;this.paymentService=null;this.setupService=null;this.initializationPromise=null;this.isUsingStripePaymentElement=false;this.isUsingIndividualFormElements=false;this.intentKind="payment";this.rawSecret=null;this.paymentIntentId=null;this.amount=null;this.currency=null;this.merchantId=null;if(!e.apiKey&&!e.clientSecret)throw new a("Either apiKey or clientSecret is required.","CONFIGURATION_ERROR");if(e.apiKey&&e.clientSecret)throw new a("Cannot provide both apiKey and clientSecret. Use apiKey for frontend-initialized flows or clientSecret for backend-initialized flows.","CONFIGURATION_ERROR");e.apiKey&&!e.apiKey.includes("_pk_")&&typeof window<"u"&&console.warn("Verapay Security Warning: You are using a Secret Key in a frontend environment. Please use a Publishable Key (vpy_pk_...) instead."),this.config=e;let t=this.config.apiUrlOverride||E.BACKEND_URL;this.verapayService=new d(t,this.config.apiKey||""),this.extensionsManager=new f;}async initialize(){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{let e,t,n;if(this.config.clientSecret)if(this.intentKind=R(this.config.clientSecret).startsWith("seti_")?"setup":"payment",this.intentKind==="setup"){let r=await this.verapayService.getSetupIntentConfig(this.config.clientSecret);if(r.object!=="setup_intent_config")throw new a("Unexpected configuration returned for setup intent","CONFIGURATION_ERROR");e=this.config.clientSecret,t="",n=r.publishableKey,this.merchantId=r.merchantId,r.verapayPublishableKey&&this.verapayService.setApiKey(r.verapayPublishableKey);}else {let r=await this.verapayService.getPaymentIntentConfig(this.config.clientSecret);e=this.config.clientSecret,t=r.paymentIntentId,n=r.publishableKey,this.amount=r.amount,this.currency=r.currency,this.merchantId=r.merchantId,r.verapayPublishableKey&&this.verapayService.setApiKey(r.verapayPublishableKey);}else {this.validatePaymentInitialisation();let r=await this.verapayService.initialisePayment({merchantId:this.config.merchantId??"",paymentData:this.config.paymentData});e=r.clientSecret,t=r.paymentIntentId,n=r.stripePublishableKey,this.amount=this.config.paymentData.amount,this.currency=this.config.paymentData.currency,this.merchantId=this.config.merchantId??"";}this.rawSecret=R(e),this.paymentIntentId=t;let i=await stripeJs.loadStripe(n);if(!i)throw new a("Failed to load Stripe","CONFIGURATION_ERROR");this.stripeAdapter=new y(i),this.elementsManager=new h(i,this.config,this.rawSecret),this.paymentService=new g(this.stripeAdapter,this.elementsManager,this.verapayService),this.setupService=new I(this.stripeAdapter,this.elementsManager);})().catch(e=>{throw this.initializationPromise=null,e}),this.initializationPromise)}async confirmPayment(){return await this.ensureInitialized(),this.assertIntentKind("payment","confirmPayment"),this.paymentService.confirm(this.rawSecret,{isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements})}async saveCard(){await this.ensureInitialized(),this.assertIntentKind("setup","saveCard");try{return await this.setupService.save(this.rawSecret,{isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements})}catch(e){throw this.handlePaymentError(e)}}async retrieveSetupIntent(){return await this.ensureInitialized(),this.assertIntentKind("setup","retrieveSetupIntent"),this.setupService.retrieve(this.rawSecret)}teardown(){this.elementsManager?.unmountAll(),this.stripeAdapter=null,this.elementsManager=null,this.paymentService=null,this.setupService=null,this.initializationPromise=null,this.isUsingStripePaymentElement=false,this.isUsingIndividualFormElements=false,this.intentKind="payment",this.rawSecret=null,this.paymentIntentId=null,this.amount=null,this.currency=null,this.merchantId=null;}async retrievePaymentIntent(){return await this.ensureInitialized(),this.paymentService.retrievePaymentIntent(this.rawSecret)}async processPayment(e){await this.ensureInitialized(),this.assertIntentKind("payment","processPayment");let t=await this.extensionsManager.runBeforePayment(e);try{let n=await this.paymentService.process(t,{merchantId:this.merchantId,paymentIntentId:this.paymentIntentId,clientSecret:this.rawSecret,amount:this.amount,currency:this.currency,isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements});return await this.extensionsManager.runAfterPayment(n),n}catch(n){throw await this.extensionsManager.runOnError(n),this.handlePaymentError(n)}}async mountPaymentForm(e){await this.ensureInitialized(),this.elementsManager.mountPaymentElement(e),this.isUsingStripePaymentElement=true;}async mountCardNumber(e){await this.ensureInitialized(),this.elementsManager.mountCardNumberElement(e),this.isUsingIndividualFormElements=true;}async mountCardExpiry(e){await this.ensureInitialized(),this.elementsManager.mountCardExpiryElement(e),this.isUsingIndividualFormElements=true;}async mountCardCvc(e){await this.ensureInitialized(),this.elementsManager.mountCardCvcElement(e),this.isUsingIndividualFormElements=true;}async mountAddress(e,t){await this.ensureInitialized(),this.elementsManager.mountAddressElement(e,t),this.isUsingIndividualFormElements=true;}addExtension(e){this.extensionsManager.add(e);}async ensureInitialized(){this.stripeAdapter||await this.initialize();}assertIntentKind(e,t){if(this.intentKind!==e)throw new a(`${t} requires a ${e} intent client secret`,"CONFIGURATION_ERROR")}validatePaymentInitialisation(){if(!this.config.paymentData)throw new a("paymentData is required for frontend-initialized flows.","CONFIGURATION_ERROR");let{amount:e,currency:t,platformFee:n}=this.config.paymentData;if(!t)throw new l("Currency is required","currency");let i=t.toUpperCase(),r=this.toMoney(e,i,"amount");if(r.isZero()||r.isNegative())throw new l("Amount must be greater than 0","amount");if(n!==void 0){let m=this.toMoney(n,i,"platformFee");if(m.isNegative())throw new l("platformFee cannot be negative","platformFee");if(m.greaterThan(r))throw new l("platformFee cannot exceed the payment amount","platformFee")}}toMoney(e,t,n){try{return tsMoney.Money.fromInteger(e,t)}catch{throw new l(`${n} must be an integer in the smallest currency unit (e.g., cents for USD)`,n)}}handlePaymentError(e){if(e instanceof a)return e;let t=e instanceof Error?e.message:"Payment failed",n=e?.code;return new o(t,n)}};E.BACKEND_URL="https://api.verapay.app";var w=E;var P=class{validateCardNumber(e){let t=e.replace(/\D/g,"");if(t.length<13||t.length>19)return false;let n=0,i=false;for(let r=t.length-1;r>=0;r--){let m=parseInt(t[r],10);i&&(m*=2,m>9&&(m-=9)),n+=m,i=!i;}return n%10===0}detectCardType(e){let t=e.replace(/\D/g,"");return /^4/.test(t)?"visa":/^5[1-5]/.test(t)?"mastercard":/^3[47]/.test(t)?"amex":/^6(?:011|5)/.test(t)?"discover":"unknown"}validateExpiry(e,t){let n=new Date,i=n.getFullYear(),r=n.getMonth()+1;if(e<1||e>12)return false;let m=t<100?2e3+t:t;return !(m<i||m===i&&e<r)}validateCVC(e,t="unknown"){let n=e.replace(/\D/g,"");return t==="amex"?n.length===4:n.length===3||n.length===4}validateAll(e,t,n,i){let r=this.detectCardType(e);return {number:{isValid:this.validateCardNumber(e),cardType:r},expiry:{isValid:this.validateExpiry(t,n),month:t,year:n},cvc:{isValid:this.validateCVC(i,r),length:i.replace(/\D/g,"").length}}}};var v=class{static sanitizeCardNumber(e){return e.replace(/\D/g,"")}static formatCardNumber(e){return this.sanitizeCardNumber(e).replace(/(\d{4})/g,"$1 ").trim()}static sanitizeCVC(e){return e.replace(/\D/g,"").slice(0,4)}static sanitizeExpiry(e){let t=e.replace(/\D/g,"");return t.length===4?{month:parseInt(t.slice(0,2),10),year:parseInt(t.slice(2,4),10)}:t.length===6?{month:parseInt(t.slice(0,2),10),year:parseInt(t.slice(2,6),10)}:null}};var ve="1.4.0";
2
2
  exports.CardValidator=P;exports.ErrorFormatter=u;exports.InputSanitizer=v;exports.PaymentError=o;exports.VERSION=ve;exports.ValidationError=l;exports.VerapayClient=w;exports.VerapayError=a;exports.VerapayService=d;//# sourceMappingURL=index.cjs.map
3
3
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors/verapay-error.ts","../src/errors/validation-error.ts","../src/errors/payment-error.ts","../src/errors/error-formatter.ts","../src/client/stripe-adapter.ts","../src/client/elements-manager.ts","../src/client/payment-extensions-manager.ts","../src/services/payment-service.ts","../src/services/setup-service.ts","../src/services/verapay-service.ts","../src/utils/secret.util.ts","../src/client/verapay-client.ts","../src/validation/card-validator.ts","../src/validation/input-sanitizer.ts","../src/index.ts"],"names":["VerapayError","_VerapayError","message","code","details","ValidationError","field","metadata","PaymentError","_PaymentError","stripeCode","ErrorFormatter","error","StripeAdapter","stripe","paymentMethodId","clientSecret","result","elements","isUsingIndividualFormElements","address","DEFAULT_CARD_ELEMENT_CONFIG","FIELD_LABELS","ElementsManager","config","selector","elementsConfig","element","mode","fieldType","options","formFieldType","elementType","errors","state","handleElementChange","event","PaymentExtensionsManager","extension","request","modifiedRequest","ext","PaymentService","stripeAdapter","elementsManager","verapayService","context","validation","paymentIntent","status","SetupService","setupIntent","paymentMethod","savedPaymentMethodId","VerapayService","baseUrl","apiKey","response","merchantId","paymentData","errorData","data","record","candidates","candidate","unwrapClientSecret","wrappedSecret","_VerapayClient","backendUrl","paymentIntentId","stripePublishableKey","loadStripe","paymentResult","expected","method","amount","currency","partnerFee","uppercaseCurrency","paymentAmount","partnerFeeAmount","value","fieldName","Money","VerapayClient","CardValidator","cardNumber","cleaned","sum","isEven","i","digit","month","year","now","currentYear","currentMonth","fullYear","cvc","cardType","expiryMonth","expiryYear","InputSanitizer","input","VERSION"],"mappings":"uFAGaA,CAAAA,CAAN,MAAMC,UAAqB,KAAM,CAItC,YACEC,CAAAA,CACAC,CAAAA,CAAAA,gBAAAA,CACAC,EACA,CACA,KAAA,CAAMF,CAAO,CAAA,CACb,IAAA,CAAK,KAAO,cAAA,CACZ,IAAA,CAAK,KAAOC,CAAAA,CACZ,IAAA,CAAK,QAAU,CACb,IAAA,CAAAA,EACA,OAAA,CAAAD,CAAAA,CACA,iBAAkB,IAAA,CAAK,aAAA,CAAcA,EAASC,CAAI,CAAA,CAClD,GAAGC,CACL,CAAA,CAEI,KAAA,CAAM,iBAAA,EACR,KAAA,CAAM,iBAAA,CAAkB,KAAMH,CAAY,EAE9C,CAEQ,aAAA,CAAcC,CAAAA,CAAiBC,EAAyB,C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,MAAO,EAAE,CAAA,CAAE,MAAM,CAAA,CAAG,CAAC,CAC5C,CAEA,OAAO,eAAeA,CAAAA,CAAuD,CAC3E,IAAMhB,CAAAA,CAAUgB,CAAAA,CAAM,QAAQ,KAAA,CAAO,EAAE,CAAA,CAEvC,OAAIhB,CAAAA,CAAQ,MAAA,GAAW,EACd,CACL,KAAA,CAAO,SAASA,CAAAA,CAAQ,KAAA,CAAM,EAAG,CAAC,CAAA,CAAG,EAAE,CAAA,CACvC,IAAA,CAAM,SAASA,CAAAA,CAAQ,KAAA,CAAM,EAAG,CAAC,CAAA,CAAG,EAAE,CACxC,CAAA,CACSA,CAAAA,CAAQ,MAAA,GAAW,CAAA,CACrB,CACL,MAAO,QAAA,CAASA,CAAAA,CAAQ,MAAM,CAAA,CAAG,CAAC,EAAG,EAAE,CAAA,CACvC,KAAM,QAAA,CAASA,CAAAA,CAAQ,MAAM,CAAA,CAAG,CAAC,EAAG,EAAE,CACxC,EAGK,IACT,CACF,ECIO,IAAMiB,EAAAA,CAAU","file":"index.cjs","sourcesContent":["import type { ErrorDetails } from '../types';\nimport { ErrorCode } from '../types';\n\nexport class VerapayError extends Error {\n public readonly code: ErrorCode;\n public readonly details: ErrorDetails;\n\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.PAYMENT_FAILED,\n details?: Partial<ErrorDetails>\n ) {\n super(message);\n this.name = 'VerapayError';\n this.code = code;\n this.details = {\n code,\n message,\n formattedMessage: this.formatMessage(message, code),\n ...details,\n };\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, VerapayError);\n }\n }\n\n private formatMessage(message: string, code: ErrorCode): string {\n const messageMap: Record<ErrorCode, string> = {\n [ErrorCode.VALIDATION_ERROR]:\n 'Please check your payment information and try again.',\n [ErrorCode.PAYMENT_FAILED]:\n 'Your payment could not be processed. Please try again.',\n [ErrorCode.AUTHENTICATION_FAILED]:\n 'Payment authentication failed. Please try again.',\n [ErrorCode.NETWORK_ERROR]:\n 'Network error. Please check your connection and try again.',\n [ErrorCode.STRIPE_ERROR]:\n 'Payment service error. Please try again later.',\n [ErrorCode.CONFIGURATION_ERROR]:\n 'Configuration error. Please contact support.',\n [ErrorCode.CARD_DECLINED]:\n 'Your card was declined. Please use a different payment method.',\n [ErrorCode.INSUFFICIENT_FUNDS]:\n 'Insufficient funds. Please use a different payment method.',\n [ErrorCode.EXPIRED_CARD]:\n 'Your card has expired. Please use a different payment method.',\n };\n\n return messageMap[code] || message;\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n details: this.details,\n };\n }\n}\n","import { VerapayError } from './verapay-error';\nimport { ErrorCode } from '../types';\n\nexport class ValidationError extends VerapayError {\n constructor(message: string, field?: string, metadata?: Record<string, unknown>) {\n\n super(message, ErrorCode.VALIDATION_ERROR, {\n field,\n metadata,\n });\n this.name = 'ValidationError';\n }\n}\n","import { VerapayError } from './verapay-error';\nimport { ErrorCode } from '../types';\n\nexport class PaymentError extends VerapayError {\n constructor(\n message: string,\n stripeCode?: string,\n metadata?: Record<string, unknown>\n ) {\n const code = PaymentError.mapStripeCode(stripeCode);\n super(message, code, {\n stripeCode,\n metadata,\n });\n this.name = 'PaymentError';\n }\n\n private static mapStripeCode(stripeCode?: string): ErrorCode {\n if (!stripeCode) return ErrorCode.PAYMENT_FAILED;\n\n const codeMap: Record<string, ErrorCode> = {\n card_declined: ErrorCode.CARD_DECLINED,\n insufficient_funds: ErrorCode.INSUFFICIENT_FUNDS,\n expired_card: ErrorCode.EXPIRED_CARD,\n incorrect_cvc: ErrorCode.VALIDATION_ERROR,\n processing_error: ErrorCode.PAYMENT_FAILED,\n authentication_failed: ErrorCode.AUTHENTICATION_FAILED,\n };\n\n return codeMap[stripeCode] || ErrorCode.PAYMENT_FAILED;\n }\n}\n","import type { ErrorDetails } from '../types';\n\nexport class ErrorFormatter {\n static formatForUser(error: Error | ErrorDetails): string {\n if ('formattedMessage' in error) {\n return error.formattedMessage;\n }\n if (\n 'details' in error &&\n error.details &&\n typeof error.details === 'object' &&\n 'formattedMessage' in error.details &&\n typeof error.details.formattedMessage === 'string'\n ) {\n return error.details.formattedMessage;\n }\n return 'An unexpected error occurred. Please try again.';\n }\n\n static formatForDeveloper(error: Error | ErrorDetails): string {\n if ('code' in error && 'message' in error) {\n return `[${error.code}] ${error.message}`;\n }\n return error.message || 'Unknown error';\n }\n\n static toJSON(error: Error | ErrorDetails): Record<string, unknown> {\n\n if ('toJSON' in error && typeof error.toJSON === 'function') {\n return error.toJSON();\n }\n\n return {\n name: (error as Error).name || 'Error',\n message: error.message,\n ...('code' in error && { code: error.code }),\n ...('details' in error && { details: error.details }),\n };\n }\n}\n","import type { PaymentIntent, SetupIntent, Stripe, StripeElements } from '@stripe/stripe-js';\nimport { PaymentError } from '../errors';\n\nexport class StripeAdapter {\n constructor(private stripe: Stripe) {}\n\n async confirmPayment(\n paymentMethodId: string,\n clientSecret: string\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.confirmPayment({\n clientSecret,\n confirmParams: {\n payment_method: paymentMethodId,\n return_url: window.location.href,\n },\n redirect: 'if_required',\n });\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Payment failed',\n result.error.code\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async confirmCardPayment(\n paymentMethodId: string,\n clientSecret: string\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.confirmCardPayment(clientSecret, {\n payment_method: paymentMethodId,\n });\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Payment failed',\n result.error.code\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async createPaymentMethod(\n elements: StripeElements,\n isUsingIndividualFormElements: boolean = false\n ): Promise<string> {\n let result;\n\n if (!isUsingIndividualFormElements) {\n result = await this.stripe.createPaymentMethod({\n elements,\n });\n } else {\n // @ts-expect-error - Stripe types don't include mode parameter for getElement\n const addressElement = await elements.getElement('address', { mode: 'billing' })!.getValue();\n\n const address = addressElement!.value;\n\n result = await this.stripe.createPaymentMethod({\n type: 'card',\n card: elements.getElement('cardNumber')!,\n billing_details: {\n name: address.name,\n address: {\n ...address.address,\n line2: address.address.line2 ?? undefined,\n },\n },\n });\n }\n\n if (result.error || !result.paymentMethod) {\n throw new PaymentError(\n result.error?.message || 'Failed to create payment method',\n result.error?.code\n );\n }\n\n return result.paymentMethod.id;\n }\n\n async retrievePaymentIntent(\n clientSecret: string,\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.retrievePaymentIntent(clientSecret);\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Failed to retrieve payment intent',\n result.error.code,\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async confirmCardSetup(\n paymentMethodId: string,\n clientSecret: string,\n ): Promise<{ setupIntent: SetupIntent }> {\n const result = await this.stripe.confirmCardSetup(clientSecret, {\n payment_method: paymentMethodId,\n });\n\n if (result.error) {\n throw new PaymentError(result.error.message || 'Card setup failed', result.error.code);\n }\n\n return result as { setupIntent: SetupIntent };\n }\n\n async retrieveSetupIntent(clientSecret: string): Promise<{ setupIntent: SetupIntent }> {\n const result = await this.stripe.retrieveSetupIntent(clientSecret);\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Failed to retrieve setup intent',\n result.error.code,\n );\n }\n\n return result as { setupIntent: SetupIntent };\n }\n}\n\n","import type {\n Stripe,\n StripeElements,\n StripeElement,\n StripePaymentElement,\n StripeCardNumberElement,\n PaymentWalletsOption,\n} from '@stripe/stripe-js';\nimport type { VerapayConfig, ValidationError, ValidationResult } from '../types';\nimport { VerapayError, ErrorCode } from '../errors';\n\ntype ElementState = { complete: boolean; error?: string }\n\nconst DEFAULT_CARD_ELEMENT_CONFIG = {\n showIcon: true,\n iconStyle: 'solid' as const,\n placeholders: {\n cardNumber: '1234 1234 1234 1234',\n cardExpiry: 'MM / YY - TESTING',\n cardCvc: 'CVC',\n },\n style: {\n base: {\n color: '#333333',\n fontFamily: 'system-ui, -apple-system, sans-serif',\n fontSize: '16px',\n '::placeholder': { color: '#aab7c4' },\n },\n complete: {\n color: '#333333',\n },\n empty: {},\n invalid: {\n color: '#df1b41',\n },\n },\n}\n\nconst FIELD_LABELS: Record<string, string> = {\n cardNumber: 'Card number',\n cardExpiry: 'Expiry date',\n cardCvc: 'CVC',\n address: 'Address',\n}\n\nexport class ElementsManager {\n private elements: StripeElements | null = null;\n private mountedElements: Map<string, StripeElement> = new Map();\n private elementStates: Map<string, ElementState> = new Map();\n\n constructor(\n private stripe: Stripe,\n private config: VerapayConfig,\n private clientSecret: string,\n ) {\n if (!clientSecret) {\n throw new VerapayError(\n 'Client secret not initialized',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n }\n\n\n mountPaymentElement(selector: string): void {\n if (!this.elements) {\n const elementsConfig = {\n clientSecret: this.clientSecret,\n appearance: this.config.appearance,\n locale: this.config.locale,\n fonts: this.config.fonts,\n paymentMethodCreation: 'manual',\n };\n\n this.elements = this.stripe.elements(elementsConfig);\n }\n\n const container = document.querySelector(selector);\n\n if (!container) {\n throw new VerapayError(\n `Element not found: ${selector}`,\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const element = this.elements.create('payment', {\n layout: 'tabs',\n wallets: { link: 'never' } as unknown as PaymentWalletsOption,\n }) as StripePaymentElement;\n\n element.mount(selector);\n this.mountedElements.set('payment', element);\n }\n\n mountCardNumberElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardNumber', this.cardElementOptions('cardNumber'));\n }\n\n mountCardExpiryElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardExpiry', this.cardElementOptions('cardExpiry'));\n }\n\n mountCardCvcElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardCvc', this.cardElementOptions('cardCvc'));\n }\n\n mountAddressElement(selector: string, mode: 'billing' | 'shipping'): void {\n this.mountIndividualFormElement(selector, 'address', { mode });\n }\n\n private cardElementOptions(fieldType: 'cardNumber' | 'cardExpiry' | 'cardCvc'): Record<string, unknown> {\n const { elementsConfig } = this.config;\n const options: Record<string, unknown> = {\n placeholder: elementsConfig?.placeholders?.[fieldType] ?? DEFAULT_CARD_ELEMENT_CONFIG.placeholders[fieldType],\n style: {\n base: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.base, ...elementsConfig?.style?.base },\n complete: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.complete, ...elementsConfig?.style?.complete },\n empty: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.empty, ...elementsConfig?.style?.empty },\n invalid: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.invalid, ...elementsConfig?.style?.invalid },\n },\n };\n\n if (fieldType === 'cardNumber') {\n options.showIcon = elementsConfig?.showIcon ?? DEFAULT_CARD_ELEMENT_CONFIG.showIcon;\n options.iconStyle = elementsConfig?.iconStyle ?? DEFAULT_CARD_ELEMENT_CONFIG.iconStyle;\n }\n\n return options;\n }\n\n private mountIndividualFormElement(selector: string, formFieldType: 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'address', options?: Record<string, unknown>) {\n const container = document.querySelector(selector);\n\n if (!container) {\n throw new VerapayError(\n `Element not found: ${selector}`,\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const element = this.createIndividualFormElement(formFieldType, options) as StripeCardNumberElement;\n element.mount(selector);\n\n this.mountedElements.set(formFieldType, element);\n this.trackElementState(formFieldType, element);\n }\n\n private createIndividualFormElement(\n elementType: 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'address',\n options?: Record<string, unknown>,\n ): StripeElement {\n if (!this.elements) {\n this.elements = this.stripe.elements({\n appearance: this.config.appearance,\n locale: this.config.locale,\n fonts: this.config.fonts,\n paymentMethodCreation: 'manual',\n });\n }\n\n return this.elements.create(elementType as 'cardNumber', options);\n }\n\n\n\n async validate(): Promise<ValidationResult> {\n const errors: ValidationError[] = []\n\n for (const [field, state] of this.elementStates.entries()) {\n if (!state.complete) {\n errors.push({\n field,\n message: state.error ?? `${FIELD_LABELS[field] ?? field} failed validation`,\n })\n }\n }\n\n return { isValid: errors.length === 0, errors }\n }\n\n getElements(): StripeElements | null {\n return this.elements;\n }\n\n unmountAll(): void {\n for (const element of this.mountedElements.values()) {\n element.unmount();\n }\n this.mountedElements.clear();\n this.elementStates.clear();\n }\n\n private trackElementState(field: string, element: StripeElement): void {\n this.elementStates.set(field, { complete: false })\n\n const handleElementChange = (event: { complete: boolean; error?: { message: string } }) => {\n this.elementStates.set(field, { complete: event.complete, error: event.error?.message })\n };\n\n (element as unknown as { on: (event: string, handler: (e: unknown) => void) => void }).on(\n 'change',\n handleElementChange as (e: unknown) => void,\n );\n }\n}\n\n\n","import type { ProcessPaymentRequest, PaymentResult } from '../types'\nimport type { PaymentExtension } from '../extensions'\n\nexport class PaymentExtensionsManager {\n private extensions: PaymentExtension[] = []\n\n add(extension: PaymentExtension): void {\n this.extensions.push(extension)\n }\n\n async runBeforePayment(request: ProcessPaymentRequest): Promise<ProcessPaymentRequest> {\n let modifiedRequest = request\n for (const ext of this.extensions) {\n if (ext.beforePayment) {\n modifiedRequest = await ext.beforePayment(modifiedRequest)\n }\n }\n return modifiedRequest\n }\n\n async runAfterPayment(result: PaymentResult): Promise<void> {\n await Promise.all(\n this.extensions\n .filter((ext) => ext.afterPayment)\n .map((ext) => ext.afterPayment!(result)),\n )\n }\n\n async runOnError(error: Error): Promise<void> {\n await Promise.all(\n this.extensions\n .filter((ext) => ext.onPaymentError)\n .map((ext) => ext.onPaymentError!(error)),\n )\n }\n}\n","import { StripeAdapter } from '../client/stripe-adapter'\nimport { ElementsManager } from '../client/elements-manager'\nimport { ErrorCode, VerapayError } from '../errors'\nimport { VerapayService } from './verapay-service'\nimport type { ProcessPaymentRequest, PaymentResult } from '../types'\nimport { StripeElements } from '@stripe/stripe-js';\n\nexport interface ProcessPaymentContext {\n merchantId: string\n paymentIntentId: string\n clientSecret: string\n amount: number\n currency: string\n isUsingStripePaymentElement: boolean\n isUsingIndividualFormElements: boolean\n}\n\nexport class PaymentService {\n constructor(\n private stripeAdapter: StripeAdapter,\n private elementsManager: ElementsManager,\n private verapayService: VerapayService,\n ) {}\n\n async process(request: ProcessPaymentRequest, context: ProcessPaymentContext): Promise<PaymentResult> {\n const elements = this.elementsManager.getElements()\n\n await this.validatePaymentCanProceed(elements, context);\n\n await elements!.submit()\n\n const paymentMethodId = await this.stripeAdapter.createPaymentMethod(\n elements!,\n context.isUsingIndividualFormElements,\n )\n\n await this.verapayService.processPrePayment({\n merchantId: context.merchantId,\n paymentIntentId: context.paymentIntentId,\n paymentMethodId,\n amount: context.amount,\n currency: context.currency,\n customerData: {\n email: request.customerEmail,\n firstName: request.customerFirstName,\n lastName: request.customerLastName,\n },\n description: request.description,\n metadata: request.metadata,\n })\n\n return this.confirm(context.clientSecret, {\n paymentMethodId,\n isUsingStripePaymentElement: context.isUsingStripePaymentElement,\n isUsingIndividualFormElements: context.isUsingIndividualFormElements,\n });\n }\n\n private async validatePaymentCanProceed(\n elements: StripeElements | null,\n context: ProcessPaymentContext,\n ) {\n if (!elements) {\n throw new VerapayError('Payment form not mounted', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingStripePaymentElement && context.isUsingIndividualFormElements) {\n throw new VerapayError('Both forms of payment form in use');\n }\n\n if (context.isUsingIndividualFormElements) {\n const validation = await this.elementsManager.validate();\n if (!validation.isValid) {\n throw new VerapayError(validation.errors[0].message, ErrorCode.VALIDATION_ERROR);\n }\n }\n }\n\n async confirm(\n clientSecret: string,\n options: {\n isUsingStripePaymentElement?: boolean;\n isUsingIndividualFormElements?: boolean;\n paymentMethodId?: string;\n } = {},\n ): Promise<PaymentResult> {\n let result;\n\n if (options.isUsingStripePaymentElement) {\n result = await this.stripeAdapter.confirmPayment(options.paymentMethodId || '', clientSecret);\n } else if (options.isUsingIndividualFormElements) {\n result = await this.stripeAdapter.confirmCardPayment(\n options.paymentMethodId || '',\n clientSecret,\n );\n } else {\n result = await this.stripeAdapter.confirmPayment(options.paymentMethodId || '', clientSecret);\n }\n\n return this.formatPaymentResult(result);\n }\n\n async retrievePaymentIntent(clientSecret: string): Promise<PaymentResult> {\n const result = await this.stripeAdapter.retrievePaymentIntent(clientSecret);\n return this.formatPaymentResult(result);\n }\n\n private formatPaymentResult(result: unknown): PaymentResult {\n const paymentIntent = (result as { paymentIntent: { status: string; id: string } })\n .paymentIntent\n\n let status: 'succeeded' | 'processing' | 'failed' = 'failed'\n if (paymentIntent.status === 'succeeded') {\n status = 'succeeded'\n } else if (\n ['processing', 'requires_action', 'requires_confirmation'].includes(\n paymentIntent.status,\n )\n ) {\n status = 'processing'\n }\n\n return {\n success: paymentIntent.status === 'succeeded',\n paymentIntentId: paymentIntent.id,\n status,\n }\n }\n\n}\n\n\n","import { StripeAdapter } from '../client/stripe-adapter';\nimport { ElementsManager } from '../client/elements-manager';\nimport { ErrorCode, VerapayError } from '../errors';\nimport type { SetupResult } from '../types';\nimport { StripeElements } from '@stripe/stripe-js';\n\nexport interface SaveCardContext {\n isUsingStripePaymentElement: boolean;\n isUsingIndividualFormElements: boolean;\n}\n\nexport class SetupService {\n constructor(\n private stripeAdapter: StripeAdapter,\n private elementsManager: ElementsManager,\n ) {}\n\n async save(clientSecret: string, context: SaveCardContext): Promise<SetupResult> {\n const elements = this.elementsManager.getElements();\n\n await this.validateSetupCanProceed(elements, context);\n\n await elements!.submit();\n\n const paymentMethodId = await this.stripeAdapter.createPaymentMethod(\n elements!,\n context.isUsingIndividualFormElements,\n );\n\n const result = await this.stripeAdapter.confirmCardSetup(paymentMethodId, clientSecret);\n\n return this.formatSetupResult(result);\n }\n\n async retrieve(clientSecret: string): Promise<SetupResult> {\n const result = await this.stripeAdapter.retrieveSetupIntent(clientSecret);\n return this.formatSetupResult(result);\n }\n\n private async validateSetupCanProceed(\n elements: StripeElements | null,\n context: SaveCardContext,\n ): Promise<void> {\n if (!elements) {\n throw new VerapayError('Card form not mounted', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingStripePaymentElement && context.isUsingIndividualFormElements) {\n throw new VerapayError('Both forms of card form in use', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingIndividualFormElements) {\n const validation = await this.elementsManager.validate();\n if (!validation.isValid) {\n throw new VerapayError(validation.errors[0].message, ErrorCode.VALIDATION_ERROR);\n }\n }\n }\n\n private formatSetupResult(result: unknown): SetupResult {\n const setupIntent = (\n result as { setupIntent: { status: string; id: string; payment_method?: unknown } }\n ).setupIntent;\n\n let status: SetupResult['status'] = 'failed';\n if (setupIntent.status === 'succeeded') {\n status = 'succeeded';\n } else if (setupIntent.status === 'processing') {\n status = 'processing';\n } else if (\n setupIntent.status === 'requires_action' ||\n setupIntent.status === 'requires_confirmation'\n ) {\n status = 'requires_action';\n }\n\n const paymentMethod = setupIntent.payment_method;\n const savedPaymentMethodId =\n typeof paymentMethod === 'string'\n ? paymentMethod\n : (paymentMethod as { id?: string } | undefined)?.id;\n\n return {\n success: setupIntent.status === 'succeeded',\n savedPaymentMethodId,\n setupIntentId: setupIntent.id,\n status,\n };\n }\n}\n","import { ErrorCode, VerapayError } from '../errors';\nimport { PaymentData } from '../types';\n\nexport interface InitialisePaymentRequest {\n merchantId: string;\n paymentData: PaymentData;\n}\n\nexport interface InitialisePaymentResponse {\n paymentIntentId: string;\n clientSecret: string;\n connectAccountId: string;\n stripePublishableKey: string;\n}\n\nexport interface ProcessPrePaymentRequest {\n merchantId: string;\n paymentIntentId: string;\n paymentMethodId: string;\n amount: number;\n currency: string;\n customerData: Record<string, unknown>;\n\n description?: string;\n metadata?: Record<string, string>;\n}\n\nexport class VerapayService {\n private readonly baseUrl: string;\n private apiKey?: string;\n\n constructor(baseUrl: string, apiKey?: string) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n }\n\n setApiKey(apiKey: string): void {\n this.apiKey = apiKey;\n }\n\n\n async getPaymentIntentConfig(clientSecret: string): Promise<Record<string, unknown>> {\n\n try {\n const response = await fetch(\n `${this.baseUrl}/v1/payment_intents/config?client_secret=${encodeURIComponent(\n clientSecret,\n )}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n );\n\n if (!response.ok) {\n throw new VerapayError('Failed to fetch provider config', ErrorCode.CONFIGURATION_ERROR);\n }\n\n return response.json();\n } catch (error) {\n if (error instanceof VerapayError) throw error;\n throw new VerapayError('Error connecting to Verapay API', ErrorCode.NETWORK_ERROR);\n }\n }\n\n async getSetupIntentConfig(clientSecret: string): Promise<Record<string, unknown>> {\n try {\n const response = await fetch(\n `${this.baseUrl}/v1/setup_intents/config?client_secret=${encodeURIComponent(\n clientSecret,\n )}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n );\n\n if (!response.ok) {\n throw new VerapayError('Failed to fetch setup config', ErrorCode.CONFIGURATION_ERROR);\n }\n\n return response.json();\n } catch (error) {\n if (error instanceof VerapayError) throw error;\n throw new VerapayError('Error connecting to Verapay API', ErrorCode.NETWORK_ERROR);\n }\n }\n\n\n async initialisePayment(\n request: InitialisePaymentRequest\n ): Promise<InitialisePaymentResponse> {\n const { merchantId, paymentData } = request;\n\n try {\n const response = await fetch(`${this.baseUrl}/api/initialise-payment`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n\n body: JSON.stringify({\n merchantId,\n paymentData: { ...paymentData, paymentMethodType: 'card' },\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new VerapayError(\n this.extractErrorMessage(errorData, response.status),\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const data = await response.json();\n\n if (!data.clientSecret || !data.paymentIntentId) {\n throw new VerapayError(\n 'Missing clientSecret or paymentIntentId in server response',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n return {\n paymentIntentId: data.paymentIntentId,\n clientSecret: data.clientSecret,\n connectAccountId: data.connectAccountId,\n stripePublishableKey: data.stripePublishableKey,\n };\n } catch (error) {\n if (error instanceof VerapayError) {\n throw error;\n }\n throw new VerapayError(\n error instanceof Error ? error.message : 'Unknown error occurred',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n }\n\n async processPrePayment(request: ProcessPrePaymentRequest): Promise<void> {\n try {\n const response = await fetch(`${this.baseUrl}/api/process-prepayment`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n\n body: JSON.stringify({\n merchantId: request.merchantId,\n paymentIntentId: request.paymentIntentId,\n paymentMethodId: request.paymentMethodId,\n amount: request.amount,\n currency: request.currency,\n customerData: request.customerData,\n description: request.description,\n metadata: request.metadata,\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new VerapayError(\n this.extractErrorMessage(errorData, response.status),\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n } catch (error) {\n if (error instanceof VerapayError) {\n throw error;\n }\n throw new VerapayError(\n error instanceof Error ? error.message : 'Unknown error occurred',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n }\n\n private extractErrorMessage(errorData: unknown, status: number): string {\n if (!errorData || typeof errorData !== 'object') {\n return `HTTP error! status: ${status}`;\n }\n\n const record = errorData as Record<string, unknown>;\n const candidates = [record.error, record.message, record.details];\n\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate;\n }\n\n if (candidate && typeof candidate === 'object') {\n try {\n return JSON.stringify(candidate);\n } catch {\n // Ignore serialization issues and continue trying fallback messages.\n }\n }\n }\n\n return `HTTP error! status: ${status}`;\n }\n}\n","export function unwrapClientSecret(wrappedSecret: string): string {\n if (wrappedSecret.startsWith('vpy_cs_test_')) {\n return wrappedSecret.replace('vpy_cs_test_', '');\n }\n if (wrappedSecret.startsWith('vpy_cs_live_')) {\n return wrappedSecret.replace('vpy_cs_live_', '');\n }\n return wrappedSecret;\n}\n","import { loadStripe } from '@stripe/stripe-js';\nimport { Money } from 'ts-money';\nimport { StripeAdapter } from './stripe-adapter';\nimport { ElementsManager } from './elements-manager';\nimport type { PaymentExtension } from '../extensions';\nimport { PaymentExtensionsManager } from './payment-extensions-manager';\nimport { PaymentService } from '../services/payment-service';\nimport { SetupService } from '../services/setup-service';\nimport {\n ErrorCode,\n VerapayError,\n PaymentError,\n ValidationError,\n} from '../errors';\nimport { VerapayService } from '../services/verapay-service';\nimport { unwrapClientSecret } from '../utils/secret.util';\nimport type {\n VerapayConfig,\n ProcessPaymentRequest,\n PaymentResult,\n SetupResult,\n} from '../types';\n\ntype IntentKind = 'payment' | 'setup';\n\nexport class VerapayClient {\n private static readonly BACKEND_URL = 'https://api.verapay.app';\n\n private config: VerapayConfig;\n private verapayService: VerapayService;\n private extensionsManager: PaymentExtensionsManager;\n\n private stripeAdapter: StripeAdapter | null = null;\n private elementsManager: ElementsManager | null = null;\n private paymentService: PaymentService | null = null;\n private setupService: SetupService | null = null;\n private initializationPromise: Promise<void> | null = null;\n\n private isUsingStripePaymentElement: boolean = false;\n private isUsingIndividualFormElements: boolean = false;\n\n private intentKind: IntentKind = 'payment';\n private rawSecret: string | null = null;\n private paymentIntentId: string | null = null;\n private amount: number | null = null;\n private currency: string | null = null;\n private merchantId: string | null = null;\n\n constructor(config: VerapayConfig) {\n if (!config.apiKey && !config.clientSecret) {\n throw new VerapayError(\n 'Either apiKey or clientSecret is required.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n if (config.apiKey && config.clientSecret) {\n throw new VerapayError(\n 'Cannot provide both apiKey and clientSecret. Use apiKey for frontend-initialized flows or clientSecret for backend-initialized flows.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n if (config.apiKey && !config.apiKey.includes(\"_pk_\") && typeof window !== \"undefined\") {\n console.warn(\n \"Verapay Security Warning: You are using a Secret Key in a frontend environment. Please use a Publishable Key (vpy_pk_...) instead.\"\n );\n }\n\n this.config = config;\n\n const backendUrl = this.config.apiUrlOverride || VerapayClient.BACKEND_URL;\n\n this.verapayService = new VerapayService(backendUrl, this.config.apiKey || '');\n this.extensionsManager = new PaymentExtensionsManager();\n }\n\n async initialize(): Promise<void> {\n if (this.initializationPromise) {\n return this.initializationPromise;\n }\n\n this.initializationPromise = (async () => {\n let clientSecret: string;\n let paymentIntentId: string;\n let stripePublishableKey: string;\n\n\n if (this.config.clientSecret) {\n this.intentKind = unwrapClientSecret(this.config.clientSecret).startsWith('seti_')\n ? 'setup'\n : 'payment';\n\n if (this.intentKind === 'setup') {\n const config = (await this.verapayService.getSetupIntentConfig(\n this.config.clientSecret,\n )) as Record<string, any>;\n\n if (config.object !== 'setup_intent_config') {\n throw new VerapayError(\n 'Unexpected configuration returned for setup intent',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n clientSecret = this.config.clientSecret;\n paymentIntentId = '';\n stripePublishableKey = config.publishableKey;\n this.merchantId = config.merchantId;\n\n if (config.verapayPublishableKey) {\n this.verapayService.setApiKey(config.verapayPublishableKey);\n }\n } else {\n const config = (await this.verapayService.getPaymentIntentConfig(\n this.config.clientSecret,\n )) as Record<string, any>;\n clientSecret = this.config.clientSecret;\n paymentIntentId = config.paymentIntentId;\n stripePublishableKey = config.publishableKey;\n this.amount = config.amount;\n this.currency = config.currency;\n this.merchantId = config.merchantId;\n\n if (config.verapayPublishableKey) {\n this.verapayService.setApiKey(config.verapayPublishableKey);\n }\n }\n } else {\n this.validatePaymentInitialisation();\n\n const response = await this.verapayService.initialisePayment({\n merchantId: this.config.merchantId ?? '',\n paymentData: this.config.paymentData!,\n });\n clientSecret = response.clientSecret;\n paymentIntentId = response.paymentIntentId;\n stripePublishableKey = response.stripePublishableKey;\n this.amount = this.config.paymentData!.amount;\n this.currency = this.config.paymentData!.currency;\n this.merchantId = this.config.merchantId ?? '';\n }\n\n this.rawSecret = unwrapClientSecret(clientSecret);\n this.paymentIntentId = paymentIntentId;\n\n const stripe = await loadStripe(stripePublishableKey);\n\n if (!stripe) {\n throw new VerapayError(\n 'Failed to load Stripe',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n this.stripeAdapter = new StripeAdapter(stripe);\n this.elementsManager = new ElementsManager(stripe, this.config, this.rawSecret!);\n this.paymentService = new PaymentService(\n this.stripeAdapter,\n this.elementsManager,\n this.verapayService,\n );\n this.setupService = new SetupService(this.stripeAdapter, this.elementsManager);\n })().catch((error) => {\n this.initializationPromise = null;\n throw error;\n });\n\n return this.initializationPromise;\n }\n\n async confirmPayment(): Promise<PaymentResult> {\n await this.ensureInitialized();\n this.assertIntentKind('payment', 'confirmPayment');\n return this.paymentService!.confirm(this.rawSecret!, {\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n }\n\n async saveCard(): Promise<SetupResult> {\n await this.ensureInitialized();\n this.assertIntentKind('setup', 'saveCard');\n try {\n return await this.setupService!.save(this.rawSecret!, {\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n } catch (error) {\n throw this.handlePaymentError(error);\n }\n }\n\n async retrieveSetupIntent(): Promise<SetupResult> {\n await this.ensureInitialized();\n this.assertIntentKind('setup', 'retrieveSetupIntent');\n return this.setupService!.retrieve(this.rawSecret!);\n }\n\n teardown(): void {\n this.elementsManager?.unmountAll();\n this.stripeAdapter = null;\n this.elementsManager = null;\n this.paymentService = null;\n this.setupService = null;\n this.initializationPromise = null;\n this.isUsingStripePaymentElement = false;\n this.isUsingIndividualFormElements = false;\n this.intentKind = 'payment';\n this.rawSecret = null;\n this.paymentIntentId = null;\n this.amount = null;\n this.currency = null;\n this.merchantId = null;\n }\n\n async retrievePaymentIntent(): Promise<PaymentResult> {\n await this.ensureInitialized();\n return this.paymentService!.retrievePaymentIntent(this.rawSecret!);\n }\n\n async processPayment(request: ProcessPaymentRequest): Promise<PaymentResult> {\n await this.ensureInitialized();\n this.assertIntentKind('payment', 'processPayment');\n\n const modifiedRequest =\n await this.extensionsManager.runBeforePayment(request);\n\n try {\n const paymentResult = await this.paymentService!.process(modifiedRequest, {\n merchantId: this.merchantId!,\n paymentIntentId: this.paymentIntentId!,\n clientSecret: this.rawSecret!,\n amount: this.amount!,\n currency: this.currency!,\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n\n\n await this.extensionsManager.runAfterPayment(paymentResult);\n\n return paymentResult;\n } catch (error) {\n await this.extensionsManager.runOnError(error as Error);\n throw this.handlePaymentError(error);\n }\n }\n\n async mountPaymentForm(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountPaymentElement(selector);\n this.isUsingStripePaymentElement = true;\n }\n\n async mountCardNumber(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardNumberElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountCardExpiry(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardExpiryElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountCardCvc(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardCvcElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountAddress(\n selector: string,\n mode: 'billing' | 'shipping'\n ): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountAddressElement(selector, mode);\n this.isUsingIndividualFormElements = true;\n }\n\n addExtension(extension: PaymentExtension): void {\n this.extensionsManager.add(extension);\n }\n\n private async ensureInitialized(): Promise<void> {\n if (!this.stripeAdapter) {\n await this.initialize();\n }\n }\n\n private assertIntentKind(expected: IntentKind, method: string): void {\n if (this.intentKind !== expected) {\n throw new VerapayError(\n `${method} requires a ${expected} intent client secret`,\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n }\n\n private validatePaymentInitialisation(): void {\n if (!this.config.paymentData) {\n throw new VerapayError(\n 'paymentData is required for frontend-initialized flows.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n const { amount, currency, partnerFee } = this.config.paymentData;\n\n\n if (!currency) {\n throw new ValidationError('Currency is required', 'currency');\n }\n\n const uppercaseCurrency = currency.toUpperCase();\n\n const paymentAmount = this.toMoney(amount, uppercaseCurrency, 'amount');\n\n if (paymentAmount.isZero() || paymentAmount.isNegative()) {\n throw new ValidationError('Amount must be greater than 0', 'amount');\n }\n\n if (partnerFee !== undefined) {\n const partnerFeeAmount = this.toMoney(partnerFee, uppercaseCurrency, 'partnerFee');\n\n if (partnerFeeAmount.isNegative()) {\n throw new ValidationError('partnerFee cannot be negative', 'partnerFee');\n }\n\n if (partnerFeeAmount.greaterThan(paymentAmount)) {\n throw new ValidationError('partnerFee cannot exceed the payment amount', 'partnerFee');\n }\n }\n }\n\n private toMoney(value: number, currency: string, fieldName: string): Money {\n try {\n return Money.fromInteger(value, currency);\n } catch {\n throw new ValidationError(\n `${fieldName} must be an integer in the smallest currency unit (e.g., cents for USD)`,\n fieldName\n );\n }\n }\n\n\n private handlePaymentError(error: unknown): Error {\n if (error instanceof VerapayError) {\n return error;\n }\n const message = error instanceof Error ? error.message : 'Payment failed';\n const code = (error as Record<string, unknown>)?.code as string | undefined;\n\n return new PaymentError(message, code);\n }\n}\n\n","import type { CardValidation } from '../types';\n\nexport class CardValidator {\n validateCardNumber(cardNumber: string): boolean {\n const cleaned = cardNumber.replace(/\\D/g, '');\n\n if (cleaned.length < 13 || cleaned.length > 19) {\n return false;\n }\n\n let sum = 0;\n let isEven = false;\n\n for (let i = cleaned.length - 1; i >= 0; i--) {\n let digit = parseInt(cleaned[i], 10);\n\n if (isEven) {\n digit *= 2;\n if (digit > 9) {\n digit -= 9;\n }\n }\n\n sum += digit;\n isEven = !isEven;\n }\n\n return sum % 10 === 0;\n }\n\n detectCardType(cardNumber: string): string {\n const cleaned = cardNumber.replace(/\\D/g, '');\n\n if (/^4/.test(cleaned)) return 'visa';\n if (/^5[1-5]/.test(cleaned)) return 'mastercard';\n if (/^3[47]/.test(cleaned)) return 'amex';\n if (/^6(?:011|5)/.test(cleaned)) return 'discover';\n\n return 'unknown';\n }\n\n validateExpiry(month: number, year: number): boolean {\n const now = new Date();\n const currentYear = now.getFullYear();\n const currentMonth = now.getMonth() + 1;\n\n if (month < 1 || month > 12) {\n return false;\n }\n\n const fullYear = year < 100 ? 2000 + year : year;\n\n if (fullYear < currentYear) {\n return false;\n }\n\n if (fullYear === currentYear && month < currentMonth) {\n return false;\n }\n\n return true;\n }\n\n validateCVC(cvc: string, cardType: string = 'unknown'): boolean {\n const cleaned = cvc.replace(/\\D/g, '');\n\n if (cardType === 'amex') {\n return cleaned.length === 4;\n }\n\n return cleaned.length === 3 || cleaned.length === 4;\n }\n\n validateAll(\n cardNumber: string,\n expiryMonth: number,\n expiryYear: number,\n cvc: string\n ): CardValidation {\n const cardType = this.detectCardType(cardNumber);\n\n return {\n number: {\n isValid: this.validateCardNumber(cardNumber),\n cardType: cardType as 'visa' | 'mastercard' | 'amex' | 'discover' | 'unknown',\n\n },\n expiry: {\n isValid: this.validateExpiry(expiryMonth, expiryYear),\n month: expiryMonth,\n year: expiryYear,\n },\n cvc: {\n isValid: this.validateCVC(cvc, cardType),\n length: cvc.replace(/\\D/g, '').length,\n },\n };\n }\n}\n","export class InputSanitizer {\n static sanitizeCardNumber(input: string): string {\n return input.replace(/\\D/g, '');\n }\n\n static formatCardNumber(input: string): string {\n const cleaned = this.sanitizeCardNumber(input);\n return cleaned.replace(/(\\d{4})/g, '$1 ').trim();\n }\n\n static sanitizeCVC(input: string): string {\n return input.replace(/\\D/g, '').slice(0, 4);\n }\n\n static sanitizeExpiry(input: string): { month: number; year: number } | null {\n const cleaned = input.replace(/\\D/g, '');\n\n if (cleaned.length === 4) {\n return {\n month: parseInt(cleaned.slice(0, 2), 10),\n year: parseInt(cleaned.slice(2, 4), 10),\n };\n } else if (cleaned.length === 6) {\n return {\n month: parseInt(cleaned.slice(0, 2), 10),\n year: parseInt(cleaned.slice(2, 6), 10),\n };\n }\n\n return null;\n }\n}\n","export { VerapayClient } from './client/verapay-client';\nexport { VerapayService } from './services/verapay-service';\n\nexport type {\n InitialisePaymentRequest,\n InitialisePaymentResponse,\n ProcessPrePaymentRequest,\n} from './services/verapay-service';\n\nexport type {\n VerapayConfig,\n ElementsConfig,\n ProcessPaymentRequest,\n PaymentResult,\n SetupResult,\n CardValidation,\n ErrorDetails,\n ErrorCode,\n} from './types';\n\nexport {\n VerapayError,\n ValidationError,\n PaymentError,\n ErrorFormatter,\n} from './errors';\n\nexport { CardValidator, InputSanitizer } from './validation';\n\nexport type {\n PaymentExtension,\n DatabaseExtension,\n AnalyticsExtension,\n} from './extensions';\n\nexport const VERSION = '1.4.0';\n"]}
1
+ {"version":3,"sources":["../src/errors/verapay-error.ts","../src/errors/validation-error.ts","../src/errors/payment-error.ts","../src/errors/error-formatter.ts","../src/client/stripe-adapter.ts","../src/client/elements-manager.ts","../src/client/payment-extensions-manager.ts","../src/services/payment-service.ts","../src/services/setup-service.ts","../src/services/verapay-service.ts","../src/utils/secret.util.ts","../src/client/verapay-client.ts","../src/validation/card-validator.ts","../src/validation/input-sanitizer.ts","../src/index.ts"],"names":["VerapayError","_VerapayError","message","code","details","ValidationError","field","metadata","PaymentError","_PaymentError","stripeCode","ErrorFormatter","error","StripeAdapter","stripe","paymentMethodId","clientSecret","result","elements","isUsingIndividualFormElements","address","DEFAULT_CARD_ELEMENT_CONFIG","FIELD_LABELS","ElementsManager","config","selector","elementsConfig","element","mode","fieldType","options","formFieldType","elementType","errors","state","handleElementChange","event","PaymentExtensionsManager","extension","request","modifiedRequest","ext","PaymentService","stripeAdapter","elementsManager","verapayService","context","validation","paymentIntent","status","SetupService","setupIntent","paymentMethod","savedPaymentMethodId","VerapayService","baseUrl","apiKey","response","merchantId","paymentData","errorData","data","record","candidates","candidate","unwrapClientSecret","wrappedSecret","_VerapayClient","backendUrl","paymentIntentId","stripePublishableKey","loadStripe","paymentResult","expected","method","amount","currency","platformFee","uppercaseCurrency","paymentAmount","platformFeeAmount","value","fieldName","Money","VerapayClient","CardValidator","cardNumber","cleaned","sum","isEven","i","digit","month","year","now","currentYear","currentMonth","fullYear","cvc","cardType","expiryMonth","expiryYear","InputSanitizer","input","VERSION"],"mappings":"uFAGaA,CAAAA,CAAN,MAAMC,UAAqB,KAAM,CAItC,YACEC,CAAAA,CACAC,CAAAA,CAAAA,gBAAAA,CACAC,EACA,CACA,KAAA,CAAMF,CAAO,CAAA,CACb,IAAA,CAAK,KAAO,cAAA,CACZ,IAAA,CAAK,KAAOC,CAAAA,CACZ,IAAA,CAAK,QAAU,CACb,IAAA,CAAAA,EACA,OAAA,CAAAD,CAAAA,CACA,iBAAkB,IAAA,CAAK,aAAA,CAAcA,EAASC,CAAI,CAAA,CAClD,GAAGC,CACL,CAAA,CAEI,KAAA,CAAM,iBAAA,EACR,KAAA,CAAM,iBAAA,CAAkB,KAAMH,CAAY,EAE9C,CAEQ,aAAA,CAAcC,CAAAA,CAAiBC,EAAyB,CAsB9D,OArB8C,CAC3C,gBAAA,CACC,sDAAA,CACD,eACC,wDAAA,CACD,qBAAA,CACC,mDACD,aAAA,CACC,4DAAA,CACD,aACC,gDAAA,CACD,mBAAA,CACC,8CAAA,CACD,aAAA,CACC,gEAAA,CACD,kBAAA,CACC,6DACD,YAAA,CACC,+DACJ,EAEkBA,CAAI,CAAA,EAAKD,CAC7B,CAEA,MAAA,EAAS,CACP,OAAO,CACL,KAAM,IAAA,CAAK,IAAA,CACX,KAAM,IAAA,CAAK,IAAA,CACX,QAAS,IAAA,CAAK,OAAA,CACd,OAAA,CAAS,IAAA,CAAK,OAChB,CACF,CACF,ECzDO,IAAMG,EAAN,cAA8BL,CAAa,CAChD,WAAA,CAAYE,CAAAA,CAAiBI,EAAgBC,CAAAA,CAAoC,CAE/E,MAAML,CAAAA,CAAAA,kBAAAA,CAAqC,CACzC,MAAAI,CAAAA,CACA,QAAA,CAAAC,CACF,CAAC,CAAA,CACD,IAAA,CAAK,IAAA,CAAO,kBACd,CACF,ECTO,IAAMC,CAAAA,CAAN,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Content":["import type { ErrorDetails } from '../types';\nimport { ErrorCode } from '../types';\n\nexport class VerapayError extends Error {\n public readonly code: ErrorCode;\n public readonly details: ErrorDetails;\n\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.PAYMENT_FAILED,\n details?: Partial<ErrorDetails>\n ) {\n super(message);\n this.name = 'VerapayError';\n this.code = code;\n this.details = {\n code,\n message,\n formattedMessage: this.formatMessage(message, code),\n ...details,\n };\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, VerapayError);\n }\n }\n\n private formatMessage(message: string, code: ErrorCode): string {\n const messageMap: Record<ErrorCode, string> = {\n [ErrorCode.VALIDATION_ERROR]:\n 'Please check your payment information and try again.',\n [ErrorCode.PAYMENT_FAILED]:\n 'Your payment could not be processed. Please try again.',\n [ErrorCode.AUTHENTICATION_FAILED]:\n 'Payment authentication failed. Please try again.',\n [ErrorCode.NETWORK_ERROR]:\n 'Network error. Please check your connection and try again.',\n [ErrorCode.STRIPE_ERROR]:\n 'Payment service error. Please try again later.',\n [ErrorCode.CONFIGURATION_ERROR]:\n 'Configuration error. Please contact support.',\n [ErrorCode.CARD_DECLINED]:\n 'Your card was declined. Please use a different payment method.',\n [ErrorCode.INSUFFICIENT_FUNDS]:\n 'Insufficient funds. Please use a different payment method.',\n [ErrorCode.EXPIRED_CARD]:\n 'Your card has expired. Please use a different payment method.',\n };\n\n return messageMap[code] || message;\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n details: this.details,\n };\n }\n}\n","import { VerapayError } from './verapay-error';\nimport { ErrorCode } from '../types';\n\nexport class ValidationError extends VerapayError {\n constructor(message: string, field?: string, metadata?: Record<string, unknown>) {\n\n super(message, ErrorCode.VALIDATION_ERROR, {\n field,\n metadata,\n });\n this.name = 'ValidationError';\n }\n}\n","import { VerapayError } from './verapay-error';\nimport { ErrorCode } from '../types';\n\nexport class PaymentError extends VerapayError {\n constructor(\n message: string,\n stripeCode?: string,\n metadata?: Record<string, unknown>\n ) {\n const code = PaymentError.mapStripeCode(stripeCode);\n super(message, code, {\n stripeCode,\n metadata,\n });\n this.name = 'PaymentError';\n }\n\n private static mapStripeCode(stripeCode?: string): ErrorCode {\n if (!stripeCode) return ErrorCode.PAYMENT_FAILED;\n\n const codeMap: Record<string, ErrorCode> = {\n card_declined: ErrorCode.CARD_DECLINED,\n insufficient_funds: ErrorCode.INSUFFICIENT_FUNDS,\n expired_card: ErrorCode.EXPIRED_CARD,\n incorrect_cvc: ErrorCode.VALIDATION_ERROR,\n processing_error: ErrorCode.PAYMENT_FAILED,\n authentication_failed: ErrorCode.AUTHENTICATION_FAILED,\n };\n\n return codeMap[stripeCode] || ErrorCode.PAYMENT_FAILED;\n }\n}\n","import type { ErrorDetails } from '../types';\n\nexport class ErrorFormatter {\n static formatForUser(error: Error | ErrorDetails): string {\n if ('formattedMessage' in error) {\n return error.formattedMessage;\n }\n if (\n 'details' in error &&\n error.details &&\n typeof error.details === 'object' &&\n 'formattedMessage' in error.details &&\n typeof error.details.formattedMessage === 'string'\n ) {\n return error.details.formattedMessage;\n }\n return 'An unexpected error occurred. Please try again.';\n }\n\n static formatForDeveloper(error: Error | ErrorDetails): string {\n if ('code' in error && 'message' in error) {\n return `[${error.code}] ${error.message}`;\n }\n return error.message || 'Unknown error';\n }\n\n static toJSON(error: Error | ErrorDetails): Record<string, unknown> {\n\n if ('toJSON' in error && typeof error.toJSON === 'function') {\n return error.toJSON();\n }\n\n return {\n name: (error as Error).name || 'Error',\n message: error.message,\n ...('code' in error && { code: error.code }),\n ...('details' in error && { details: error.details }),\n };\n }\n}\n","import type { PaymentIntent, SetupIntent, Stripe, StripeElements } from '@stripe/stripe-js';\nimport { PaymentError } from '../errors';\n\nexport class StripeAdapter {\n constructor(private stripe: Stripe) {}\n\n async confirmPayment(\n paymentMethodId: string,\n clientSecret: string\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.confirmPayment({\n clientSecret,\n confirmParams: {\n payment_method: paymentMethodId,\n return_url: window.location.href,\n },\n redirect: 'if_required',\n });\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Payment failed',\n result.error.code\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async confirmCardPayment(\n paymentMethodId: string,\n clientSecret: string\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.confirmCardPayment(clientSecret, {\n payment_method: paymentMethodId,\n });\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Payment failed',\n result.error.code\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async createPaymentMethod(\n elements: StripeElements,\n isUsingIndividualFormElements: boolean = false\n ): Promise<string> {\n let result;\n\n if (!isUsingIndividualFormElements) {\n result = await this.stripe.createPaymentMethod({\n elements,\n });\n } else {\n // @ts-expect-error - Stripe types don't include mode parameter for getElement\n const addressElement = await elements.getElement('address', { mode: 'billing' })!.getValue();\n\n const address = addressElement!.value;\n\n result = await this.stripe.createPaymentMethod({\n type: 'card',\n card: elements.getElement('cardNumber')!,\n billing_details: {\n name: address.name,\n address: {\n ...address.address,\n line2: address.address.line2 ?? undefined,\n },\n },\n });\n }\n\n if (result.error || !result.paymentMethod) {\n throw new PaymentError(\n result.error?.message || 'Failed to create payment method',\n result.error?.code\n );\n }\n\n return result.paymentMethod.id;\n }\n\n async retrievePaymentIntent(\n clientSecret: string,\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.retrievePaymentIntent(clientSecret);\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Failed to retrieve payment intent',\n result.error.code,\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async confirmCardSetup(\n paymentMethodId: string,\n clientSecret: string,\n ): Promise<{ setupIntent: SetupIntent }> {\n const result = await this.stripe.confirmCardSetup(clientSecret, {\n payment_method: paymentMethodId,\n });\n\n if (result.error) {\n throw new PaymentError(result.error.message || 'Card setup failed', result.error.code);\n }\n\n return result as { setupIntent: SetupIntent };\n }\n\n async retrieveSetupIntent(clientSecret: string): Promise<{ setupIntent: SetupIntent }> {\n const result = await this.stripe.retrieveSetupIntent(clientSecret);\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Failed to retrieve setup intent',\n result.error.code,\n );\n }\n\n return result as { setupIntent: SetupIntent };\n }\n}\n\n","import type {\n Stripe,\n StripeElements,\n StripeElement,\n StripePaymentElement,\n StripeCardNumberElement,\n PaymentWalletsOption,\n} from '@stripe/stripe-js';\nimport type { VerapayConfig, ValidationError, ValidationResult } from '../types';\nimport { VerapayError, ErrorCode } from '../errors';\n\ntype ElementState = { complete: boolean; error?: string }\n\nconst DEFAULT_CARD_ELEMENT_CONFIG = {\n showIcon: true,\n iconStyle: 'solid' as const,\n placeholders: {\n cardNumber: '1234 1234 1234 1234',\n cardExpiry: 'MM / YY - TESTING',\n cardCvc: 'CVC',\n },\n style: {\n base: {\n color: '#333333',\n fontFamily: 'system-ui, -apple-system, sans-serif',\n fontSize: '16px',\n '::placeholder': { color: '#aab7c4' },\n },\n complete: {\n color: '#333333',\n },\n empty: {},\n invalid: {\n color: '#df1b41',\n },\n },\n}\n\nconst FIELD_LABELS: Record<string, string> = {\n cardNumber: 'Card number',\n cardExpiry: 'Expiry date',\n cardCvc: 'CVC',\n address: 'Address',\n}\n\nexport class ElementsManager {\n private elements: StripeElements | null = null;\n private mountedElements: Map<string, StripeElement> = new Map();\n private elementStates: Map<string, ElementState> = new Map();\n\n constructor(\n private stripe: Stripe,\n private config: VerapayConfig,\n private clientSecret: string,\n ) {\n if (!clientSecret) {\n throw new VerapayError(\n 'Client secret not initialized',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n }\n\n\n mountPaymentElement(selector: string): void {\n if (!this.elements) {\n const elementsConfig = {\n clientSecret: this.clientSecret,\n appearance: this.config.appearance,\n locale: this.config.locale,\n fonts: this.config.fonts,\n paymentMethodCreation: 'manual',\n };\n\n this.elements = this.stripe.elements(elementsConfig);\n }\n\n const container = document.querySelector(selector);\n\n if (!container) {\n throw new VerapayError(\n `Element not found: ${selector}`,\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const element = this.elements.create('payment', {\n layout: 'tabs',\n wallets: { link: 'never' } as unknown as PaymentWalletsOption,\n }) as StripePaymentElement;\n\n element.mount(selector);\n this.mountedElements.set('payment', element);\n }\n\n mountCardNumberElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardNumber', this.cardElementOptions('cardNumber'));\n }\n\n mountCardExpiryElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardExpiry', this.cardElementOptions('cardExpiry'));\n }\n\n mountCardCvcElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardCvc', this.cardElementOptions('cardCvc'));\n }\n\n mountAddressElement(selector: string, mode: 'billing' | 'shipping'): void {\n this.mountIndividualFormElement(selector, 'address', { mode });\n }\n\n private cardElementOptions(fieldType: 'cardNumber' | 'cardExpiry' | 'cardCvc'): Record<string, unknown> {\n const { elementsConfig } = this.config;\n const options: Record<string, unknown> = {\n placeholder: elementsConfig?.placeholders?.[fieldType] ?? DEFAULT_CARD_ELEMENT_CONFIG.placeholders[fieldType],\n style: {\n base: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.base, ...elementsConfig?.style?.base },\n complete: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.complete, ...elementsConfig?.style?.complete },\n empty: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.empty, ...elementsConfig?.style?.empty },\n invalid: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.invalid, ...elementsConfig?.style?.invalid },\n },\n };\n\n if (fieldType === 'cardNumber') {\n options.showIcon = elementsConfig?.showIcon ?? DEFAULT_CARD_ELEMENT_CONFIG.showIcon;\n options.iconStyle = elementsConfig?.iconStyle ?? DEFAULT_CARD_ELEMENT_CONFIG.iconStyle;\n }\n\n return options;\n }\n\n private mountIndividualFormElement(selector: string, formFieldType: 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'address', options?: Record<string, unknown>) {\n const container = document.querySelector(selector);\n\n if (!container) {\n throw new VerapayError(\n `Element not found: ${selector}`,\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const element = this.createIndividualFormElement(formFieldType, options) as StripeCardNumberElement;\n element.mount(selector);\n\n this.mountedElements.set(formFieldType, element);\n this.trackElementState(formFieldType, element);\n }\n\n private createIndividualFormElement(\n elementType: 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'address',\n options?: Record<string, unknown>,\n ): StripeElement {\n if (!this.elements) {\n this.elements = this.stripe.elements({\n appearance: this.config.appearance,\n locale: this.config.locale,\n fonts: this.config.fonts,\n paymentMethodCreation: 'manual',\n });\n }\n\n return this.elements.create(elementType as 'cardNumber', options);\n }\n\n\n\n async validate(): Promise<ValidationResult> {\n const errors: ValidationError[] = []\n\n for (const [field, state] of this.elementStates.entries()) {\n if (!state.complete) {\n errors.push({\n field,\n message: state.error ?? `${FIELD_LABELS[field] ?? field} failed validation`,\n })\n }\n }\n\n return { isValid: errors.length === 0, errors }\n }\n\n getElements(): StripeElements | null {\n return this.elements;\n }\n\n unmountAll(): void {\n for (const element of this.mountedElements.values()) {\n element.unmount();\n }\n this.mountedElements.clear();\n this.elementStates.clear();\n }\n\n private trackElementState(field: string, element: StripeElement): void {\n this.elementStates.set(field, { complete: false })\n\n const handleElementChange = (event: { complete: boolean; error?: { message: string } }) => {\n this.elementStates.set(field, { complete: event.complete, error: event.error?.message })\n };\n\n (element as unknown as { on: (event: string, handler: (e: unknown) => void) => void }).on(\n 'change',\n handleElementChange as (e: unknown) => void,\n );\n }\n}\n\n\n","import type { ProcessPaymentRequest, PaymentResult } from '../types'\nimport type { PaymentExtension } from '../extensions'\n\nexport class PaymentExtensionsManager {\n private extensions: PaymentExtension[] = []\n\n add(extension: PaymentExtension): void {\n this.extensions.push(extension)\n }\n\n async runBeforePayment(request: ProcessPaymentRequest): Promise<ProcessPaymentRequest> {\n let modifiedRequest = request\n for (const ext of this.extensions) {\n if (ext.beforePayment) {\n modifiedRequest = await ext.beforePayment(modifiedRequest)\n }\n }\n return modifiedRequest\n }\n\n async runAfterPayment(result: PaymentResult): Promise<void> {\n await Promise.all(\n this.extensions\n .filter((ext) => ext.afterPayment)\n .map((ext) => ext.afterPayment!(result)),\n )\n }\n\n async runOnError(error: Error): Promise<void> {\n await Promise.all(\n this.extensions\n .filter((ext) => ext.onPaymentError)\n .map((ext) => ext.onPaymentError!(error)),\n )\n }\n}\n","import { StripeAdapter } from '../client/stripe-adapter'\nimport { ElementsManager } from '../client/elements-manager'\nimport { ErrorCode, VerapayError } from '../errors'\nimport { VerapayService } from './verapay-service'\nimport type { ProcessPaymentRequest, PaymentResult } from '../types'\nimport { StripeElements } from '@stripe/stripe-js';\n\nexport interface ProcessPaymentContext {\n merchantId: string\n paymentIntentId: string\n clientSecret: string\n amount: number\n currency: string\n isUsingStripePaymentElement: boolean\n isUsingIndividualFormElements: boolean\n}\n\nexport class PaymentService {\n constructor(\n private stripeAdapter: StripeAdapter,\n private elementsManager: ElementsManager,\n private verapayService: VerapayService,\n ) {}\n\n async process(request: ProcessPaymentRequest, context: ProcessPaymentContext): Promise<PaymentResult> {\n const elements = this.elementsManager.getElements()\n\n await this.validatePaymentCanProceed(elements, context);\n\n await elements!.submit()\n\n const paymentMethodId = await this.stripeAdapter.createPaymentMethod(\n elements!,\n context.isUsingIndividualFormElements,\n )\n\n await this.verapayService.processPrePayment({\n merchantId: context.merchantId,\n paymentIntentId: context.paymentIntentId,\n paymentMethodId,\n amount: context.amount,\n currency: context.currency,\n customerData: {\n email: request.customerEmail,\n firstName: request.customerFirstName,\n lastName: request.customerLastName,\n },\n description: request.description,\n metadata: request.metadata,\n })\n\n return this.confirm(context.clientSecret, {\n paymentMethodId,\n isUsingStripePaymentElement: context.isUsingStripePaymentElement,\n isUsingIndividualFormElements: context.isUsingIndividualFormElements,\n });\n }\n\n private async validatePaymentCanProceed(\n elements: StripeElements | null,\n context: ProcessPaymentContext,\n ) {\n if (!elements) {\n throw new VerapayError('Payment form not mounted', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingStripePaymentElement && context.isUsingIndividualFormElements) {\n throw new VerapayError('Both forms of payment form in use');\n }\n\n if (context.isUsingIndividualFormElements) {\n const validation = await this.elementsManager.validate();\n if (!validation.isValid) {\n throw new VerapayError(validation.errors[0].message, ErrorCode.VALIDATION_ERROR);\n }\n }\n }\n\n async confirm(\n clientSecret: string,\n options: {\n isUsingStripePaymentElement?: boolean;\n isUsingIndividualFormElements?: boolean;\n paymentMethodId?: string;\n } = {},\n ): Promise<PaymentResult> {\n let result;\n\n if (options.isUsingStripePaymentElement) {\n result = await this.stripeAdapter.confirmPayment(options.paymentMethodId || '', clientSecret);\n } else if (options.isUsingIndividualFormElements) {\n result = await this.stripeAdapter.confirmCardPayment(\n options.paymentMethodId || '',\n clientSecret,\n );\n } else {\n result = await this.stripeAdapter.confirmPayment(options.paymentMethodId || '', clientSecret);\n }\n\n return this.formatPaymentResult(result);\n }\n\n async retrievePaymentIntent(clientSecret: string): Promise<PaymentResult> {\n const result = await this.stripeAdapter.retrievePaymentIntent(clientSecret);\n return this.formatPaymentResult(result);\n }\n\n private formatPaymentResult(result: unknown): PaymentResult {\n const paymentIntent = (result as { paymentIntent: { status: string; id: string } })\n .paymentIntent\n\n let status: 'succeeded' | 'processing' | 'failed' = 'failed'\n if (paymentIntent.status === 'succeeded') {\n status = 'succeeded'\n } else if (\n ['processing', 'requires_action', 'requires_confirmation'].includes(\n paymentIntent.status,\n )\n ) {\n status = 'processing'\n }\n\n return {\n success: paymentIntent.status === 'succeeded',\n paymentIntentId: paymentIntent.id,\n status,\n }\n }\n\n}\n\n\n","import { StripeAdapter } from '../client/stripe-adapter';\nimport { ElementsManager } from '../client/elements-manager';\nimport { ErrorCode, VerapayError } from '../errors';\nimport type { SetupResult } from '../types';\nimport { StripeElements } from '@stripe/stripe-js';\n\nexport interface SaveCardContext {\n isUsingStripePaymentElement: boolean;\n isUsingIndividualFormElements: boolean;\n}\n\nexport class SetupService {\n constructor(\n private stripeAdapter: StripeAdapter,\n private elementsManager: ElementsManager,\n ) {}\n\n async save(clientSecret: string, context: SaveCardContext): Promise<SetupResult> {\n const elements = this.elementsManager.getElements();\n\n await this.validateSetupCanProceed(elements, context);\n\n await elements!.submit();\n\n const paymentMethodId = await this.stripeAdapter.createPaymentMethod(\n elements!,\n context.isUsingIndividualFormElements,\n );\n\n const result = await this.stripeAdapter.confirmCardSetup(paymentMethodId, clientSecret);\n\n return this.formatSetupResult(result);\n }\n\n async retrieve(clientSecret: string): Promise<SetupResult> {\n const result = await this.stripeAdapter.retrieveSetupIntent(clientSecret);\n return this.formatSetupResult(result);\n }\n\n private async validateSetupCanProceed(\n elements: StripeElements | null,\n context: SaveCardContext,\n ): Promise<void> {\n if (!elements) {\n throw new VerapayError('Card form not mounted', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingStripePaymentElement && context.isUsingIndividualFormElements) {\n throw new VerapayError('Both forms of card form in use', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingIndividualFormElements) {\n const validation = await this.elementsManager.validate();\n if (!validation.isValid) {\n throw new VerapayError(validation.errors[0].message, ErrorCode.VALIDATION_ERROR);\n }\n }\n }\n\n private formatSetupResult(result: unknown): SetupResult {\n const setupIntent = (\n result as { setupIntent: { status: string; id: string; payment_method?: unknown } }\n ).setupIntent;\n\n let status: SetupResult['status'] = 'failed';\n if (setupIntent.status === 'succeeded') {\n status = 'succeeded';\n } else if (setupIntent.status === 'processing') {\n status = 'processing';\n } else if (\n setupIntent.status === 'requires_action' ||\n setupIntent.status === 'requires_confirmation'\n ) {\n status = 'requires_action';\n }\n\n const paymentMethod = setupIntent.payment_method;\n const savedPaymentMethodId =\n typeof paymentMethod === 'string'\n ? paymentMethod\n : (paymentMethod as { id?: string } | undefined)?.id;\n\n return {\n success: setupIntent.status === 'succeeded',\n savedPaymentMethodId,\n setupIntentId: setupIntent.id,\n status,\n };\n }\n}\n","import { ErrorCode, VerapayError } from '../errors';\nimport { PaymentData } from '../types';\n\nexport interface InitialisePaymentRequest {\n merchantId: string;\n paymentData: PaymentData;\n}\n\nexport interface InitialisePaymentResponse {\n paymentIntentId: string;\n clientSecret: string;\n connectAccountId: string;\n stripePublishableKey: string;\n}\n\nexport interface ProcessPrePaymentRequest {\n merchantId: string;\n paymentIntentId: string;\n paymentMethodId: string;\n amount: number;\n currency: string;\n customerData: Record<string, unknown>;\n\n description?: string;\n metadata?: Record<string, string>;\n}\n\nexport class VerapayService {\n private readonly baseUrl: string;\n private apiKey?: string;\n\n constructor(baseUrl: string, apiKey?: string) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n }\n\n setApiKey(apiKey: string): void {\n this.apiKey = apiKey;\n }\n\n\n async getPaymentIntentConfig(clientSecret: string): Promise<Record<string, unknown>> {\n\n try {\n const response = await fetch(\n `${this.baseUrl}/v1/payment_intents/config?client_secret=${encodeURIComponent(\n clientSecret,\n )}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n );\n\n if (!response.ok) {\n throw new VerapayError('Failed to fetch provider config', ErrorCode.CONFIGURATION_ERROR);\n }\n\n return response.json();\n } catch (error) {\n if (error instanceof VerapayError) throw error;\n throw new VerapayError('Error connecting to Verapay API', ErrorCode.NETWORK_ERROR);\n }\n }\n\n async getSetupIntentConfig(clientSecret: string): Promise<Record<string, unknown>> {\n try {\n const response = await fetch(\n `${this.baseUrl}/v1/setup_intents/config?client_secret=${encodeURIComponent(\n clientSecret,\n )}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n );\n\n if (!response.ok) {\n throw new VerapayError('Failed to fetch setup config', ErrorCode.CONFIGURATION_ERROR);\n }\n\n return response.json();\n } catch (error) {\n if (error instanceof VerapayError) throw error;\n throw new VerapayError('Error connecting to Verapay API', ErrorCode.NETWORK_ERROR);\n }\n }\n\n\n async initialisePayment(\n request: InitialisePaymentRequest\n ): Promise<InitialisePaymentResponse> {\n const { merchantId, paymentData } = request;\n\n try {\n const response = await fetch(`${this.baseUrl}/api/initialise-payment`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n\n body: JSON.stringify({\n merchantId,\n paymentData: { ...paymentData, paymentMethodType: 'card' },\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new VerapayError(\n this.extractErrorMessage(errorData, response.status),\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const data = await response.json();\n\n if (!data.clientSecret || !data.paymentIntentId) {\n throw new VerapayError(\n 'Missing clientSecret or paymentIntentId in server response',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n return {\n paymentIntentId: data.paymentIntentId,\n clientSecret: data.clientSecret,\n connectAccountId: data.connectAccountId,\n stripePublishableKey: data.stripePublishableKey,\n };\n } catch (error) {\n if (error instanceof VerapayError) {\n throw error;\n }\n throw new VerapayError(\n error instanceof Error ? error.message : 'Unknown error occurred',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n }\n\n async processPrePayment(request: ProcessPrePaymentRequest): Promise<void> {\n try {\n const response = await fetch(`${this.baseUrl}/api/process-prepayment`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n\n body: JSON.stringify({\n merchantId: request.merchantId,\n paymentIntentId: request.paymentIntentId,\n paymentMethodId: request.paymentMethodId,\n amount: request.amount,\n currency: request.currency,\n customerData: request.customerData,\n description: request.description,\n metadata: request.metadata,\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new VerapayError(\n this.extractErrorMessage(errorData, response.status),\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n } catch (error) {\n if (error instanceof VerapayError) {\n throw error;\n }\n throw new VerapayError(\n error instanceof Error ? error.message : 'Unknown error occurred',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n }\n\n private extractErrorMessage(errorData: unknown, status: number): string {\n if (!errorData || typeof errorData !== 'object') {\n return `HTTP error! status: ${status}`;\n }\n\n const record = errorData as Record<string, unknown>;\n const candidates = [record.error, record.message, record.details];\n\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate;\n }\n\n if (candidate && typeof candidate === 'object') {\n try {\n return JSON.stringify(candidate);\n } catch {\n // Ignore serialization issues and continue trying fallback messages.\n }\n }\n }\n\n return `HTTP error! status: ${status}`;\n }\n}\n","export function unwrapClientSecret(wrappedSecret: string): string {\n if (wrappedSecret.startsWith('vpy_cs_test_')) {\n return wrappedSecret.replace('vpy_cs_test_', '');\n }\n if (wrappedSecret.startsWith('vpy_cs_live_')) {\n return wrappedSecret.replace('vpy_cs_live_', '');\n }\n return wrappedSecret;\n}\n","import { loadStripe } from '@stripe/stripe-js';\nimport { Money } from 'ts-money';\nimport { StripeAdapter } from './stripe-adapter';\nimport { ElementsManager } from './elements-manager';\nimport type { PaymentExtension } from '../extensions';\nimport { PaymentExtensionsManager } from './payment-extensions-manager';\nimport { PaymentService } from '../services/payment-service';\nimport { SetupService } from '../services/setup-service';\nimport {\n ErrorCode,\n VerapayError,\n PaymentError,\n ValidationError,\n} from '../errors';\nimport { VerapayService } from '../services/verapay-service';\nimport { unwrapClientSecret } from '../utils/secret.util';\nimport type {\n VerapayConfig,\n ProcessPaymentRequest,\n PaymentResult,\n SetupResult,\n} from '../types';\n\ntype IntentKind = 'payment' | 'setup';\n\nexport class VerapayClient {\n private static readonly BACKEND_URL = 'https://api.verapay.app';\n\n private config: VerapayConfig;\n private verapayService: VerapayService;\n private extensionsManager: PaymentExtensionsManager;\n\n private stripeAdapter: StripeAdapter | null = null;\n private elementsManager: ElementsManager | null = null;\n private paymentService: PaymentService | null = null;\n private setupService: SetupService | null = null;\n private initializationPromise: Promise<void> | null = null;\n\n private isUsingStripePaymentElement: boolean = false;\n private isUsingIndividualFormElements: boolean = false;\n\n private intentKind: IntentKind = 'payment';\n private rawSecret: string | null = null;\n private paymentIntentId: string | null = null;\n private amount: number | null = null;\n private currency: string | null = null;\n private merchantId: string | null = null;\n\n constructor(config: VerapayConfig) {\n if (!config.apiKey && !config.clientSecret) {\n throw new VerapayError(\n 'Either apiKey or clientSecret is required.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n if (config.apiKey && config.clientSecret) {\n throw new VerapayError(\n 'Cannot provide both apiKey and clientSecret. Use apiKey for frontend-initialized flows or clientSecret for backend-initialized flows.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n if (config.apiKey && !config.apiKey.includes(\"_pk_\") && typeof window !== \"undefined\") {\n console.warn(\n \"Verapay Security Warning: You are using a Secret Key in a frontend environment. Please use a Publishable Key (vpy_pk_...) instead.\"\n );\n }\n\n this.config = config;\n\n const backendUrl = this.config.apiUrlOverride || VerapayClient.BACKEND_URL;\n\n this.verapayService = new VerapayService(backendUrl, this.config.apiKey || '');\n this.extensionsManager = new PaymentExtensionsManager();\n }\n\n async initialize(): Promise<void> {\n if (this.initializationPromise) {\n return this.initializationPromise;\n }\n\n this.initializationPromise = (async () => {\n let clientSecret: string;\n let paymentIntentId: string;\n let stripePublishableKey: string;\n\n\n if (this.config.clientSecret) {\n this.intentKind = unwrapClientSecret(this.config.clientSecret).startsWith('seti_')\n ? 'setup'\n : 'payment';\n\n if (this.intentKind === 'setup') {\n const config = (await this.verapayService.getSetupIntentConfig(\n this.config.clientSecret,\n )) as Record<string, any>;\n\n if (config.object !== 'setup_intent_config') {\n throw new VerapayError(\n 'Unexpected configuration returned for setup intent',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n clientSecret = this.config.clientSecret;\n paymentIntentId = '';\n stripePublishableKey = config.publishableKey;\n this.merchantId = config.merchantId;\n\n if (config.verapayPublishableKey) {\n this.verapayService.setApiKey(config.verapayPublishableKey);\n }\n } else {\n const config = (await this.verapayService.getPaymentIntentConfig(\n this.config.clientSecret,\n )) as Record<string, any>;\n clientSecret = this.config.clientSecret;\n paymentIntentId = config.paymentIntentId;\n stripePublishableKey = config.publishableKey;\n this.amount = config.amount;\n this.currency = config.currency;\n this.merchantId = config.merchantId;\n\n if (config.verapayPublishableKey) {\n this.verapayService.setApiKey(config.verapayPublishableKey);\n }\n }\n } else {\n this.validatePaymentInitialisation();\n\n const response = await this.verapayService.initialisePayment({\n merchantId: this.config.merchantId ?? '',\n paymentData: this.config.paymentData!,\n });\n clientSecret = response.clientSecret;\n paymentIntentId = response.paymentIntentId;\n stripePublishableKey = response.stripePublishableKey;\n this.amount = this.config.paymentData!.amount;\n this.currency = this.config.paymentData!.currency;\n this.merchantId = this.config.merchantId ?? '';\n }\n\n this.rawSecret = unwrapClientSecret(clientSecret);\n this.paymentIntentId = paymentIntentId;\n\n const stripe = await loadStripe(stripePublishableKey);\n\n if (!stripe) {\n throw new VerapayError(\n 'Failed to load Stripe',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n this.stripeAdapter = new StripeAdapter(stripe);\n this.elementsManager = new ElementsManager(stripe, this.config, this.rawSecret!);\n this.paymentService = new PaymentService(\n this.stripeAdapter,\n this.elementsManager,\n this.verapayService,\n );\n this.setupService = new SetupService(this.stripeAdapter, this.elementsManager);\n })().catch((error) => {\n this.initializationPromise = null;\n throw error;\n });\n\n return this.initializationPromise;\n }\n\n async confirmPayment(): Promise<PaymentResult> {\n await this.ensureInitialized();\n this.assertIntentKind('payment', 'confirmPayment');\n return this.paymentService!.confirm(this.rawSecret!, {\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n }\n\n async saveCard(): Promise<SetupResult> {\n await this.ensureInitialized();\n this.assertIntentKind('setup', 'saveCard');\n try {\n return await this.setupService!.save(this.rawSecret!, {\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n } catch (error) {\n throw this.handlePaymentError(error);\n }\n }\n\n async retrieveSetupIntent(): Promise<SetupResult> {\n await this.ensureInitialized();\n this.assertIntentKind('setup', 'retrieveSetupIntent');\n return this.setupService!.retrieve(this.rawSecret!);\n }\n\n teardown(): void {\n this.elementsManager?.unmountAll();\n this.stripeAdapter = null;\n this.elementsManager = null;\n this.paymentService = null;\n this.setupService = null;\n this.initializationPromise = null;\n this.isUsingStripePaymentElement = false;\n this.isUsingIndividualFormElements = false;\n this.intentKind = 'payment';\n this.rawSecret = null;\n this.paymentIntentId = null;\n this.amount = null;\n this.currency = null;\n this.merchantId = null;\n }\n\n async retrievePaymentIntent(): Promise<PaymentResult> {\n await this.ensureInitialized();\n return this.paymentService!.retrievePaymentIntent(this.rawSecret!);\n }\n\n async processPayment(request: ProcessPaymentRequest): Promise<PaymentResult> {\n await this.ensureInitialized();\n this.assertIntentKind('payment', 'processPayment');\n\n const modifiedRequest =\n await this.extensionsManager.runBeforePayment(request);\n\n try {\n const paymentResult = await this.paymentService!.process(modifiedRequest, {\n merchantId: this.merchantId!,\n paymentIntentId: this.paymentIntentId!,\n clientSecret: this.rawSecret!,\n amount: this.amount!,\n currency: this.currency!,\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n\n\n await this.extensionsManager.runAfterPayment(paymentResult);\n\n return paymentResult;\n } catch (error) {\n await this.extensionsManager.runOnError(error as Error);\n throw this.handlePaymentError(error);\n }\n }\n\n async mountPaymentForm(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountPaymentElement(selector);\n this.isUsingStripePaymentElement = true;\n }\n\n async mountCardNumber(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardNumberElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountCardExpiry(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardExpiryElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountCardCvc(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardCvcElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountAddress(\n selector: string,\n mode: 'billing' | 'shipping'\n ): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountAddressElement(selector, mode);\n this.isUsingIndividualFormElements = true;\n }\n\n addExtension(extension: PaymentExtension): void {\n this.extensionsManager.add(extension);\n }\n\n private async ensureInitialized(): Promise<void> {\n if (!this.stripeAdapter) {\n await this.initialize();\n }\n }\n\n private assertIntentKind(expected: IntentKind, method: string): void {\n if (this.intentKind !== expected) {\n throw new VerapayError(\n `${method} requires a ${expected} intent client secret`,\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n }\n\n private validatePaymentInitialisation(): void {\n if (!this.config.paymentData) {\n throw new VerapayError(\n 'paymentData is required for frontend-initialized flows.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n const { amount, currency, platformFee } = this.config.paymentData;\n\n\n if (!currency) {\n throw new ValidationError('Currency is required', 'currency');\n }\n\n const uppercaseCurrency = currency.toUpperCase();\n\n const paymentAmount = this.toMoney(amount, uppercaseCurrency, 'amount');\n\n if (paymentAmount.isZero() || paymentAmount.isNegative()) {\n throw new ValidationError('Amount must be greater than 0', 'amount');\n }\n\n if (platformFee !== undefined) {\n const platformFeeAmount = this.toMoney(platformFee, uppercaseCurrency, 'platformFee');\n\n if (platformFeeAmount.isNegative()) {\n throw new ValidationError('platformFee cannot be negative', 'platformFee');\n }\n\n if (platformFeeAmount.greaterThan(paymentAmount)) {\n throw new ValidationError('platformFee cannot exceed the payment amount', 'platformFee');\n }\n }\n }\n\n private toMoney(value: number, currency: string, fieldName: string): Money {\n try {\n return Money.fromInteger(value, currency);\n } catch {\n throw new ValidationError(\n `${fieldName} must be an integer in the smallest currency unit (e.g., cents for USD)`,\n fieldName\n );\n }\n }\n\n\n private handlePaymentError(error: unknown): Error {\n if (error instanceof VerapayError) {\n return error;\n }\n const message = error instanceof Error ? error.message : 'Payment failed';\n const code = (error as Record<string, unknown>)?.code as string | undefined;\n\n return new PaymentError(message, code);\n }\n}\n\n","import type { CardValidation } from '../types';\n\nexport class CardValidator {\n validateCardNumber(cardNumber: string): boolean {\n const cleaned = cardNumber.replace(/\\D/g, '');\n\n if (cleaned.length < 13 || cleaned.length > 19) {\n return false;\n }\n\n let sum = 0;\n let isEven = false;\n\n for (let i = cleaned.length - 1; i >= 0; i--) {\n let digit = parseInt(cleaned[i], 10);\n\n if (isEven) {\n digit *= 2;\n if (digit > 9) {\n digit -= 9;\n }\n }\n\n sum += digit;\n isEven = !isEven;\n }\n\n return sum % 10 === 0;\n }\n\n detectCardType(cardNumber: string): string {\n const cleaned = cardNumber.replace(/\\D/g, '');\n\n if (/^4/.test(cleaned)) return 'visa';\n if (/^5[1-5]/.test(cleaned)) return 'mastercard';\n if (/^3[47]/.test(cleaned)) return 'amex';\n if (/^6(?:011|5)/.test(cleaned)) return 'discover';\n\n return 'unknown';\n }\n\n validateExpiry(month: number, year: number): boolean {\n const now = new Date();\n const currentYear = now.getFullYear();\n const currentMonth = now.getMonth() + 1;\n\n if (month < 1 || month > 12) {\n return false;\n }\n\n const fullYear = year < 100 ? 2000 + year : year;\n\n if (fullYear < currentYear) {\n return false;\n }\n\n if (fullYear === currentYear && month < currentMonth) {\n return false;\n }\n\n return true;\n }\n\n validateCVC(cvc: string, cardType: string = 'unknown'): boolean {\n const cleaned = cvc.replace(/\\D/g, '');\n\n if (cardType === 'amex') {\n return cleaned.length === 4;\n }\n\n return cleaned.length === 3 || cleaned.length === 4;\n }\n\n validateAll(\n cardNumber: string,\n expiryMonth: number,\n expiryYear: number,\n cvc: string\n ): CardValidation {\n const cardType = this.detectCardType(cardNumber);\n\n return {\n number: {\n isValid: this.validateCardNumber(cardNumber),\n cardType: cardType as 'visa' | 'mastercard' | 'amex' | 'discover' | 'unknown',\n\n },\n expiry: {\n isValid: this.validateExpiry(expiryMonth, expiryYear),\n month: expiryMonth,\n year: expiryYear,\n },\n cvc: {\n isValid: this.validateCVC(cvc, cardType),\n length: cvc.replace(/\\D/g, '').length,\n },\n };\n }\n}\n","export class InputSanitizer {\n static sanitizeCardNumber(input: string): string {\n return input.replace(/\\D/g, '');\n }\n\n static formatCardNumber(input: string): string {\n const cleaned = this.sanitizeCardNumber(input);\n return cleaned.replace(/(\\d{4})/g, '$1 ').trim();\n }\n\n static sanitizeCVC(input: string): string {\n return input.replace(/\\D/g, '').slice(0, 4);\n }\n\n static sanitizeExpiry(input: string): { month: number; year: number } | null {\n const cleaned = input.replace(/\\D/g, '');\n\n if (cleaned.length === 4) {\n return {\n month: parseInt(cleaned.slice(0, 2), 10),\n year: parseInt(cleaned.slice(2, 4), 10),\n };\n } else if (cleaned.length === 6) {\n return {\n month: parseInt(cleaned.slice(0, 2), 10),\n year: parseInt(cleaned.slice(2, 6), 10),\n };\n }\n\n return null;\n }\n}\n","export { VerapayClient } from './client/verapay-client';\nexport { VerapayService } from './services/verapay-service';\n\nexport type {\n InitialisePaymentRequest,\n InitialisePaymentResponse,\n ProcessPrePaymentRequest,\n} from './services/verapay-service';\n\nexport type {\n VerapayConfig,\n ElementsConfig,\n ProcessPaymentRequest,\n PaymentResult,\n SetupResult,\n CardValidation,\n ErrorDetails,\n ErrorCode,\n} from './types';\n\nexport {\n VerapayError,\n ValidationError,\n PaymentError,\n ErrorFormatter,\n} from './errors';\n\nexport { CardValidator, InputSanitizer } from './validation';\n\nexport type {\n PaymentExtension,\n DatabaseExtension,\n AnalyticsExtension,\n} from './extensions';\n\nexport const VERSION = '1.4.0';\n"]}
package/dist/index.d.cts CHANGED
@@ -22,7 +22,7 @@ interface BackendConfig extends BaseConfig {
22
22
  interface PaymentData {
23
23
  amount: number;
24
24
  currency: string;
25
- partnerFee?: number;
25
+ platformFee?: number;
26
26
  }
27
27
  interface ElementsConfig {
28
28
  style?: {
package/dist/index.d.ts CHANGED
@@ -22,7 +22,7 @@ interface BackendConfig extends BaseConfig {
22
22
  interface PaymentData {
23
23
  amount: number;
24
24
  currency: string;
25
- partnerFee?: number;
25
+ platformFee?: number;
26
26
  }
27
27
  interface ElementsConfig {
28
28
  style?: {
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import {loadStripe}from'@stripe/stripe-js';import {Money}from'ts-money';var a=class s extends Error{constructor(e,t="PAYMENT_FAILED",n){super(e),this.name="VerapayError",this.code=t,this.details={code:t,message:e,formattedMessage:this.formatMessage(e,t),...n},Error.captureStackTrace&&Error.captureStackTrace(this,s);}formatMessage(e,t){return {VALIDATION_ERROR:"Please check your payment information and try again.",PAYMENT_FAILED:"Your payment could not be processed. Please try again.",AUTHENTICATION_FAILED:"Payment authentication failed. Please try again.",NETWORK_ERROR:"Network error. Please check your connection and try again.",STRIPE_ERROR:"Payment service error. Please try again later.",CONFIGURATION_ERROR:"Configuration error. Please contact support.",CARD_DECLINED:"Your card was declined. Please use a different payment method.",INSUFFICIENT_FUNDS:"Insufficient funds. Please use a different payment method.",EXPIRED_CARD:"Your card has expired. Please use a different payment method."}[t]||e}toJSON(){return {name:this.name,code:this.code,message:this.message,details:this.details}}};var l=class extends a{constructor(e,t,n){super(e,"VALIDATION_ERROR",{field:t,metadata:n}),this.name="ValidationError";}};var o=class s extends a{constructor(e,t,n){let i=s.mapStripeCode(t);super(e,i,{stripeCode:t,metadata:n}),this.name="PaymentError";}static mapStripeCode(e){return e?{card_declined:"CARD_DECLINED",insufficient_funds:"INSUFFICIENT_FUNDS",expired_card:"EXPIRED_CARD",incorrect_cvc:"VALIDATION_ERROR",processing_error:"PAYMENT_FAILED",authentication_failed:"AUTHENTICATION_FAILED"}[e]||"PAYMENT_FAILED":"PAYMENT_FAILED"}};var u=class{static formatForUser(e){return "formattedMessage"in e?e.formattedMessage:"details"in e&&e.details&&typeof e.details=="object"&&"formattedMessage"in e.details&&typeof e.details.formattedMessage=="string"?e.details.formattedMessage:"An unexpected error occurred. Please try again."}static formatForDeveloper(e){return "code"in e&&"message"in e?`[${e.code}] ${e.message}`:e.message||"Unknown error"}static toJSON(e){return "toJSON"in e&&typeof e.toJSON=="function"?e.toJSON():{name:e.name||"Error",message:e.message,..."code"in e&&{code:e.code},..."details"in e&&{details:e.details}}}};var y=class{constructor(e){this.stripe=e;}async confirmPayment(e,t){let n=await this.stripe.confirmPayment({clientSecret:t,confirmParams:{payment_method:e,return_url:window.location.href},redirect:"if_required"});if(n.error)throw new o(n.error.message||"Payment failed",n.error.code);return n}async confirmCardPayment(e,t){let n=await this.stripe.confirmCardPayment(t,{payment_method:e});if(n.error)throw new o(n.error.message||"Payment failed",n.error.code);return n}async createPaymentMethod(e,t=false){let n;if(!t)n=await this.stripe.createPaymentMethod({elements:e});else {let r=(await e.getElement("address",{mode:"billing"}).getValue()).value;n=await this.stripe.createPaymentMethod({type:"card",card:e.getElement("cardNumber"),billing_details:{name:r.name,address:{...r.address,line2:r.address.line2??void 0}}});}if(n.error||!n.paymentMethod)throw new o(n.error?.message||"Failed to create payment method",n.error?.code);return n.paymentMethod.id}async retrievePaymentIntent(e){let t=await this.stripe.retrievePaymentIntent(e);if(t.error)throw new o(t.error.message||"Failed to retrieve payment intent",t.error.code);return t}async confirmCardSetup(e,t){let n=await this.stripe.confirmCardSetup(t,{payment_method:e});if(n.error)throw new o(n.error.message||"Card setup failed",n.error.code);return n}async retrieveSetupIntent(e){let t=await this.stripe.retrieveSetupIntent(e);if(t.error)throw new o(t.error.message||"Failed to retrieve setup intent",t.error.code);return t}};var p={showIcon:true,iconStyle:"solid",placeholders:{cardNumber:"1234 1234 1234 1234",cardExpiry:"MM / YY - TESTING",cardCvc:"CVC"},style:{base:{color:"#333333",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"16px","::placeholder":{color:"#aab7c4"}},complete:{color:"#333333"},empty:{},invalid:{color:"#df1b41"}}},S={cardNumber:"Card number",cardExpiry:"Expiry date",cardCvc:"CVC",address:"Address"},h=class{constructor(e,t,n){this.stripe=e;this.config=t;this.clientSecret=n;this.elements=null;this.mountedElements=new Map;this.elementStates=new Map;if(!n)throw new a("Client secret not initialized","CONFIGURATION_ERROR")}mountPaymentElement(e){if(!this.elements){let i={clientSecret:this.clientSecret,appearance:this.config.appearance,locale:this.config.locale,fonts:this.config.fonts,paymentMethodCreation:"manual"};this.elements=this.stripe.elements(i);}if(!document.querySelector(e))throw new a(`Element not found: ${e}`,"CONFIGURATION_ERROR");let n=this.elements.create("payment",{layout:"tabs",wallets:{link:"never"}});n.mount(e),this.mountedElements.set("payment",n);}mountCardNumberElement(e){this.mountIndividualFormElement(e,"cardNumber",this.cardElementOptions("cardNumber"));}mountCardExpiryElement(e){this.mountIndividualFormElement(e,"cardExpiry",this.cardElementOptions("cardExpiry"));}mountCardCvcElement(e){this.mountIndividualFormElement(e,"cardCvc",this.cardElementOptions("cardCvc"));}mountAddressElement(e,t){this.mountIndividualFormElement(e,"address",{mode:t});}cardElementOptions(e){let{elementsConfig:t}=this.config,n={placeholder:t?.placeholders?.[e]??p.placeholders[e],style:{base:{...p.style.base,...t?.style?.base},complete:{...p.style.complete,...t?.style?.complete},empty:{...p.style.empty,...t?.style?.empty},invalid:{...p.style.invalid,...t?.style?.invalid}}};return e==="cardNumber"&&(n.showIcon=t?.showIcon??p.showIcon,n.iconStyle=t?.iconStyle??p.iconStyle),n}mountIndividualFormElement(e,t,n){if(!document.querySelector(e))throw new a(`Element not found: ${e}`,"CONFIGURATION_ERROR");let r=this.createIndividualFormElement(t,n);r.mount(e),this.mountedElements.set(t,r),this.trackElementState(t,r);}createIndividualFormElement(e,t){return this.elements||(this.elements=this.stripe.elements({appearance:this.config.appearance,locale:this.config.locale,fonts:this.config.fonts,paymentMethodCreation:"manual"})),this.elements.create(e,t)}async validate(){let e=[];for(let[t,n]of this.elementStates.entries())n.complete||e.push({field:t,message:n.error??`${S[t]??t} failed validation`});return {isValid:e.length===0,errors:e}}getElements(){return this.elements}unmountAll(){for(let e of this.mountedElements.values())e.unmount();this.mountedElements.clear(),this.elementStates.clear();}trackElementState(e,t){this.elementStates.set(e,{complete:false});let n=i=>{this.elementStates.set(e,{complete:i.complete,error:i.error?.message});};t.on("change",n);}};var g=class{constructor(){this.extensions=[];}add(e){this.extensions.push(e);}async runBeforePayment(e){let t=e;for(let n of this.extensions)n.beforePayment&&(t=await n.beforePayment(t));return t}async runAfterPayment(e){await Promise.all(this.extensions.filter(t=>t.afterPayment).map(t=>t.afterPayment(e)));}async runOnError(e){await Promise.all(this.extensions.filter(t=>t.onPaymentError).map(t=>t.onPaymentError(e)));}};var f=class{constructor(e,t,n){this.stripeAdapter=e;this.elementsManager=t;this.verapayService=n;}async process(e,t){let n=this.elementsManager.getElements();await this.validatePaymentCanProceed(n,t),await n.submit();let i=await this.stripeAdapter.createPaymentMethod(n,t.isUsingIndividualFormElements);return await this.verapayService.processPrePayment({merchantId:t.merchantId,paymentIntentId:t.paymentIntentId,paymentMethodId:i,amount:t.amount,currency:t.currency,customerData:{email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName},description:e.description,metadata:e.metadata}),this.confirm(t.clientSecret,{paymentMethodId:i,isUsingStripePaymentElement:t.isUsingStripePaymentElement,isUsingIndividualFormElements:t.isUsingIndividualFormElements})}async validatePaymentCanProceed(e,t){if(!e)throw new a("Payment form not mounted","CONFIGURATION_ERROR");if(t.isUsingStripePaymentElement&&t.isUsingIndividualFormElements)throw new a("Both forms of payment form in use");if(t.isUsingIndividualFormElements){let n=await this.elementsManager.validate();if(!n.isValid)throw new a(n.errors[0].message,"VALIDATION_ERROR")}}async confirm(e,t={}){let n;return t.isUsingStripePaymentElement?n=await this.stripeAdapter.confirmPayment(t.paymentMethodId||"",e):t.isUsingIndividualFormElements?n=await this.stripeAdapter.confirmCardPayment(t.paymentMethodId||"",e):n=await this.stripeAdapter.confirmPayment(t.paymentMethodId||"",e),this.formatPaymentResult(n)}async retrievePaymentIntent(e){let t=await this.stripeAdapter.retrievePaymentIntent(e);return this.formatPaymentResult(t)}formatPaymentResult(e){let t=e.paymentIntent,n="failed";return t.status==="succeeded"?n="succeeded":["processing","requires_action","requires_confirmation"].includes(t.status)&&(n="processing"),{success:t.status==="succeeded",paymentIntentId:t.id,status:n}}};var I=class{constructor(e,t){this.stripeAdapter=e;this.elementsManager=t;}async save(e,t){let n=this.elementsManager.getElements();await this.validateSetupCanProceed(n,t),await n.submit();let i=await this.stripeAdapter.createPaymentMethod(n,t.isUsingIndividualFormElements),r=await this.stripeAdapter.confirmCardSetup(i,e);return this.formatSetupResult(r)}async retrieve(e){let t=await this.stripeAdapter.retrieveSetupIntent(e);return this.formatSetupResult(t)}async validateSetupCanProceed(e,t){if(!e)throw new a("Card form not mounted","CONFIGURATION_ERROR");if(t.isUsingStripePaymentElement&&t.isUsingIndividualFormElements)throw new a("Both forms of card form in use","CONFIGURATION_ERROR");if(t.isUsingIndividualFormElements){let n=await this.elementsManager.validate();if(!n.isValid)throw new a(n.errors[0].message,"VALIDATION_ERROR")}}formatSetupResult(e){let t=e.setupIntent,n="failed";t.status==="succeeded"?n="succeeded":t.status==="processing"?n="processing":(t.status==="requires_action"||t.status==="requires_confirmation")&&(n="requires_action");let i=t.payment_method,r=typeof i=="string"?i:i?.id;return {success:t.status==="succeeded",savedPaymentMethodId:r,setupIntentId:t.id,status:n}}};var d=class{constructor(e,t){this.baseUrl=e,this.apiKey=t;}setApiKey(e){this.apiKey=e;}async getPaymentIntentConfig(e){try{let t=await fetch(`${this.baseUrl}/v1/payment_intents/config?client_secret=${encodeURIComponent(e)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new a("Failed to fetch provider config","CONFIGURATION_ERROR");return t.json()}catch(t){throw t instanceof a?t:new a("Error connecting to Verapay API","NETWORK_ERROR")}}async getSetupIntentConfig(e){try{let t=await fetch(`${this.baseUrl}/v1/setup_intents/config?client_secret=${encodeURIComponent(e)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new a("Failed to fetch setup config","CONFIGURATION_ERROR");return t.json()}catch(t){throw t instanceof a?t:new a("Error connecting to Verapay API","NETWORK_ERROR")}}async initialisePayment(e){let{merchantId:t,paymentData:n}=e;try{let i=await fetch(`${this.baseUrl}/api/initialise-payment`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey?{"x-api-key":this.apiKey}:{}},body:JSON.stringify({merchantId:t,paymentData:{...n,paymentMethodType:"card"}})});if(!i.ok){let m=await i.json().catch(()=>({}));throw new a(this.extractErrorMessage(m,i.status),"CONFIGURATION_ERROR")}let r=await i.json();if(!r.clientSecret||!r.paymentIntentId)throw new a("Missing clientSecret or paymentIntentId in server response","CONFIGURATION_ERROR");return {paymentIntentId:r.paymentIntentId,clientSecret:r.clientSecret,connectAccountId:r.connectAccountId,stripePublishableKey:r.stripePublishableKey}}catch(i){throw i instanceof a?i:new a(i instanceof Error?i.message:"Unknown error occurred","CONFIGURATION_ERROR")}}async processPrePayment(e){try{let t=await fetch(`${this.baseUrl}/api/process-prepayment`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey?{"x-api-key":this.apiKey}:{}},body:JSON.stringify({merchantId:e.merchantId,paymentIntentId:e.paymentIntentId,paymentMethodId:e.paymentMethodId,amount:e.amount,currency:e.currency,customerData:e.customerData,description:e.description,metadata:e.metadata})});if(!t.ok){let n=await t.json().catch(()=>({}));throw new a(this.extractErrorMessage(n,t.status),"CONFIGURATION_ERROR")}}catch(t){throw t instanceof a?t:new a(t instanceof Error?t.message:"Unknown error occurred","CONFIGURATION_ERROR")}}extractErrorMessage(e,t){if(!e||typeof e!="object")return `HTTP error! status: ${t}`;let n=e,i=[n.error,n.message,n.details];for(let r of i){if(typeof r=="string"&&r.trim().length>0)return r;if(r&&typeof r=="object")try{return JSON.stringify(r)}catch{}}return `HTTP error! status: ${t}`}};function R(s){return s.startsWith("vpy_cs_test_")?s.replace("vpy_cs_test_",""):s.startsWith("vpy_cs_live_")?s.replace("vpy_cs_live_",""):s}var E=class E{constructor(e){this.stripeAdapter=null;this.elementsManager=null;this.paymentService=null;this.setupService=null;this.initializationPromise=null;this.isUsingStripePaymentElement=false;this.isUsingIndividualFormElements=false;this.intentKind="payment";this.rawSecret=null;this.paymentIntentId=null;this.amount=null;this.currency=null;this.merchantId=null;if(!e.apiKey&&!e.clientSecret)throw new a("Either apiKey or clientSecret is required.","CONFIGURATION_ERROR");if(e.apiKey&&e.clientSecret)throw new a("Cannot provide both apiKey and clientSecret. Use apiKey for frontend-initialized flows or clientSecret for backend-initialized flows.","CONFIGURATION_ERROR");e.apiKey&&!e.apiKey.includes("_pk_")&&typeof window<"u"&&console.warn("Verapay Security Warning: You are using a Secret Key in a frontend environment. Please use a Publishable Key (vpy_pk_...) instead."),this.config=e;let t=this.config.apiUrlOverride||E.BACKEND_URL;this.verapayService=new d(t,this.config.apiKey||""),this.extensionsManager=new g;}async initialize(){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{let e,t,n;if(this.config.clientSecret)if(this.intentKind=R(this.config.clientSecret).startsWith("seti_")?"setup":"payment",this.intentKind==="setup"){let r=await this.verapayService.getSetupIntentConfig(this.config.clientSecret);if(r.object!=="setup_intent_config")throw new a("Unexpected configuration returned for setup intent","CONFIGURATION_ERROR");e=this.config.clientSecret,t="",n=r.publishableKey,this.merchantId=r.merchantId,r.verapayPublishableKey&&this.verapayService.setApiKey(r.verapayPublishableKey);}else {let r=await this.verapayService.getPaymentIntentConfig(this.config.clientSecret);e=this.config.clientSecret,t=r.paymentIntentId,n=r.publishableKey,this.amount=r.amount,this.currency=r.currency,this.merchantId=r.merchantId,r.verapayPublishableKey&&this.verapayService.setApiKey(r.verapayPublishableKey);}else {this.validatePaymentInitialisation();let r=await this.verapayService.initialisePayment({merchantId:this.config.merchantId??"",paymentData:this.config.paymentData});e=r.clientSecret,t=r.paymentIntentId,n=r.stripePublishableKey,this.amount=this.config.paymentData.amount,this.currency=this.config.paymentData.currency,this.merchantId=this.config.merchantId??"";}this.rawSecret=R(e),this.paymentIntentId=t;let i=await loadStripe(n);if(!i)throw new a("Failed to load Stripe","CONFIGURATION_ERROR");this.stripeAdapter=new y(i),this.elementsManager=new h(i,this.config,this.rawSecret),this.paymentService=new f(this.stripeAdapter,this.elementsManager,this.verapayService),this.setupService=new I(this.stripeAdapter,this.elementsManager);})().catch(e=>{throw this.initializationPromise=null,e}),this.initializationPromise)}async confirmPayment(){return await this.ensureInitialized(),this.assertIntentKind("payment","confirmPayment"),this.paymentService.confirm(this.rawSecret,{isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements})}async saveCard(){await this.ensureInitialized(),this.assertIntentKind("setup","saveCard");try{return await this.setupService.save(this.rawSecret,{isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements})}catch(e){throw this.handlePaymentError(e)}}async retrieveSetupIntent(){return await this.ensureInitialized(),this.assertIntentKind("setup","retrieveSetupIntent"),this.setupService.retrieve(this.rawSecret)}teardown(){this.elementsManager?.unmountAll(),this.stripeAdapter=null,this.elementsManager=null,this.paymentService=null,this.setupService=null,this.initializationPromise=null,this.isUsingStripePaymentElement=false,this.isUsingIndividualFormElements=false,this.intentKind="payment",this.rawSecret=null,this.paymentIntentId=null,this.amount=null,this.currency=null,this.merchantId=null;}async retrievePaymentIntent(){return await this.ensureInitialized(),this.paymentService.retrievePaymentIntent(this.rawSecret)}async processPayment(e){await this.ensureInitialized(),this.assertIntentKind("payment","processPayment");let t=await this.extensionsManager.runBeforePayment(e);try{let n=await this.paymentService.process(t,{merchantId:this.merchantId,paymentIntentId:this.paymentIntentId,clientSecret:this.rawSecret,amount:this.amount,currency:this.currency,isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements});return await this.extensionsManager.runAfterPayment(n),n}catch(n){throw await this.extensionsManager.runOnError(n),this.handlePaymentError(n)}}async mountPaymentForm(e){await this.ensureInitialized(),this.elementsManager.mountPaymentElement(e),this.isUsingStripePaymentElement=true;}async mountCardNumber(e){await this.ensureInitialized(),this.elementsManager.mountCardNumberElement(e),this.isUsingIndividualFormElements=true;}async mountCardExpiry(e){await this.ensureInitialized(),this.elementsManager.mountCardExpiryElement(e),this.isUsingIndividualFormElements=true;}async mountCardCvc(e){await this.ensureInitialized(),this.elementsManager.mountCardCvcElement(e),this.isUsingIndividualFormElements=true;}async mountAddress(e,t){await this.ensureInitialized(),this.elementsManager.mountAddressElement(e,t),this.isUsingIndividualFormElements=true;}addExtension(e){this.extensionsManager.add(e);}async ensureInitialized(){this.stripeAdapter||await this.initialize();}assertIntentKind(e,t){if(this.intentKind!==e)throw new a(`${t} requires a ${e} intent client secret`,"CONFIGURATION_ERROR")}validatePaymentInitialisation(){if(!this.config.paymentData)throw new a("paymentData is required for frontend-initialized flows.","CONFIGURATION_ERROR");let{amount:e,currency:t,partnerFee:n}=this.config.paymentData;if(!t)throw new l("Currency is required","currency");let i=t.toUpperCase(),r=this.toMoney(e,i,"amount");if(r.isZero()||r.isNegative())throw new l("Amount must be greater than 0","amount");if(n!==void 0){let m=this.toMoney(n,i,"partnerFee");if(m.isNegative())throw new l("partnerFee cannot be negative","partnerFee");if(m.greaterThan(r))throw new l("partnerFee cannot exceed the payment amount","partnerFee")}}toMoney(e,t,n){try{return Money.fromInteger(e,t)}catch{throw new l(`${n} must be an integer in the smallest currency unit (e.g., cents for USD)`,n)}}handlePaymentError(e){if(e instanceof a)return e;let t=e instanceof Error?e.message:"Payment failed",n=e?.code;return new o(t,n)}};E.BACKEND_URL="https://api.verapay.app";var w=E;var P=class{validateCardNumber(e){let t=e.replace(/\D/g,"");if(t.length<13||t.length>19)return false;let n=0,i=false;for(let r=t.length-1;r>=0;r--){let m=parseInt(t[r],10);i&&(m*=2,m>9&&(m-=9)),n+=m,i=!i;}return n%10===0}detectCardType(e){let t=e.replace(/\D/g,"");return /^4/.test(t)?"visa":/^5[1-5]/.test(t)?"mastercard":/^3[47]/.test(t)?"amex":/^6(?:011|5)/.test(t)?"discover":"unknown"}validateExpiry(e,t){let n=new Date,i=n.getFullYear(),r=n.getMonth()+1;if(e<1||e>12)return false;let m=t<100?2e3+t:t;return !(m<i||m===i&&e<r)}validateCVC(e,t="unknown"){let n=e.replace(/\D/g,"");return t==="amex"?n.length===4:n.length===3||n.length===4}validateAll(e,t,n,i){let r=this.detectCardType(e);return {number:{isValid:this.validateCardNumber(e),cardType:r},expiry:{isValid:this.validateExpiry(t,n),month:t,year:n},cvc:{isValid:this.validateCVC(i,r),length:i.replace(/\D/g,"").length}}}};var v=class{static sanitizeCardNumber(e){return e.replace(/\D/g,"")}static formatCardNumber(e){return this.sanitizeCardNumber(e).replace(/(\d{4})/g,"$1 ").trim()}static sanitizeCVC(e){return e.replace(/\D/g,"").slice(0,4)}static sanitizeExpiry(e){let t=e.replace(/\D/g,"");return t.length===4?{month:parseInt(t.slice(0,2),10),year:parseInt(t.slice(2,4),10)}:t.length===6?{month:parseInt(t.slice(0,2),10),year:parseInt(t.slice(2,6),10)}:null}};var ve="1.4.0";
1
+ import {loadStripe}from'@stripe/stripe-js';import {Money}from'ts-money';var a=class s extends Error{constructor(e,t="PAYMENT_FAILED",n){super(e),this.name="VerapayError",this.code=t,this.details={code:t,message:e,formattedMessage:this.formatMessage(e,t),...n},Error.captureStackTrace&&Error.captureStackTrace(this,s);}formatMessage(e,t){return {VALIDATION_ERROR:"Please check your payment information and try again.",PAYMENT_FAILED:"Your payment could not be processed. Please try again.",AUTHENTICATION_FAILED:"Payment authentication failed. Please try again.",NETWORK_ERROR:"Network error. Please check your connection and try again.",STRIPE_ERROR:"Payment service error. Please try again later.",CONFIGURATION_ERROR:"Configuration error. Please contact support.",CARD_DECLINED:"Your card was declined. Please use a different payment method.",INSUFFICIENT_FUNDS:"Insufficient funds. Please use a different payment method.",EXPIRED_CARD:"Your card has expired. Please use a different payment method."}[t]||e}toJSON(){return {name:this.name,code:this.code,message:this.message,details:this.details}}};var l=class extends a{constructor(e,t,n){super(e,"VALIDATION_ERROR",{field:t,metadata:n}),this.name="ValidationError";}};var o=class s extends a{constructor(e,t,n){let i=s.mapStripeCode(t);super(e,i,{stripeCode:t,metadata:n}),this.name="PaymentError";}static mapStripeCode(e){return e?{card_declined:"CARD_DECLINED",insufficient_funds:"INSUFFICIENT_FUNDS",expired_card:"EXPIRED_CARD",incorrect_cvc:"VALIDATION_ERROR",processing_error:"PAYMENT_FAILED",authentication_failed:"AUTHENTICATION_FAILED"}[e]||"PAYMENT_FAILED":"PAYMENT_FAILED"}};var u=class{static formatForUser(e){return "formattedMessage"in e?e.formattedMessage:"details"in e&&e.details&&typeof e.details=="object"&&"formattedMessage"in e.details&&typeof e.details.formattedMessage=="string"?e.details.formattedMessage:"An unexpected error occurred. Please try again."}static formatForDeveloper(e){return "code"in e&&"message"in e?`[${e.code}] ${e.message}`:e.message||"Unknown error"}static toJSON(e){return "toJSON"in e&&typeof e.toJSON=="function"?e.toJSON():{name:e.name||"Error",message:e.message,..."code"in e&&{code:e.code},..."details"in e&&{details:e.details}}}};var y=class{constructor(e){this.stripe=e;}async confirmPayment(e,t){let n=await this.stripe.confirmPayment({clientSecret:t,confirmParams:{payment_method:e,return_url:window.location.href},redirect:"if_required"});if(n.error)throw new o(n.error.message||"Payment failed",n.error.code);return n}async confirmCardPayment(e,t){let n=await this.stripe.confirmCardPayment(t,{payment_method:e});if(n.error)throw new o(n.error.message||"Payment failed",n.error.code);return n}async createPaymentMethod(e,t=false){let n;if(!t)n=await this.stripe.createPaymentMethod({elements:e});else {let r=(await e.getElement("address",{mode:"billing"}).getValue()).value;n=await this.stripe.createPaymentMethod({type:"card",card:e.getElement("cardNumber"),billing_details:{name:r.name,address:{...r.address,line2:r.address.line2??void 0}}});}if(n.error||!n.paymentMethod)throw new o(n.error?.message||"Failed to create payment method",n.error?.code);return n.paymentMethod.id}async retrievePaymentIntent(e){let t=await this.stripe.retrievePaymentIntent(e);if(t.error)throw new o(t.error.message||"Failed to retrieve payment intent",t.error.code);return t}async confirmCardSetup(e,t){let n=await this.stripe.confirmCardSetup(t,{payment_method:e});if(n.error)throw new o(n.error.message||"Card setup failed",n.error.code);return n}async retrieveSetupIntent(e){let t=await this.stripe.retrieveSetupIntent(e);if(t.error)throw new o(t.error.message||"Failed to retrieve setup intent",t.error.code);return t}};var p={showIcon:true,iconStyle:"solid",placeholders:{cardNumber:"1234 1234 1234 1234",cardExpiry:"MM / YY - TESTING",cardCvc:"CVC"},style:{base:{color:"#333333",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"16px","::placeholder":{color:"#aab7c4"}},complete:{color:"#333333"},empty:{},invalid:{color:"#df1b41"}}},S={cardNumber:"Card number",cardExpiry:"Expiry date",cardCvc:"CVC",address:"Address"},h=class{constructor(e,t,n){this.stripe=e;this.config=t;this.clientSecret=n;this.elements=null;this.mountedElements=new Map;this.elementStates=new Map;if(!n)throw new a("Client secret not initialized","CONFIGURATION_ERROR")}mountPaymentElement(e){if(!this.elements){let i={clientSecret:this.clientSecret,appearance:this.config.appearance,locale:this.config.locale,fonts:this.config.fonts,paymentMethodCreation:"manual"};this.elements=this.stripe.elements(i);}if(!document.querySelector(e))throw new a(`Element not found: ${e}`,"CONFIGURATION_ERROR");let n=this.elements.create("payment",{layout:"tabs",wallets:{link:"never"}});n.mount(e),this.mountedElements.set("payment",n);}mountCardNumberElement(e){this.mountIndividualFormElement(e,"cardNumber",this.cardElementOptions("cardNumber"));}mountCardExpiryElement(e){this.mountIndividualFormElement(e,"cardExpiry",this.cardElementOptions("cardExpiry"));}mountCardCvcElement(e){this.mountIndividualFormElement(e,"cardCvc",this.cardElementOptions("cardCvc"));}mountAddressElement(e,t){this.mountIndividualFormElement(e,"address",{mode:t});}cardElementOptions(e){let{elementsConfig:t}=this.config,n={placeholder:t?.placeholders?.[e]??p.placeholders[e],style:{base:{...p.style.base,...t?.style?.base},complete:{...p.style.complete,...t?.style?.complete},empty:{...p.style.empty,...t?.style?.empty},invalid:{...p.style.invalid,...t?.style?.invalid}}};return e==="cardNumber"&&(n.showIcon=t?.showIcon??p.showIcon,n.iconStyle=t?.iconStyle??p.iconStyle),n}mountIndividualFormElement(e,t,n){if(!document.querySelector(e))throw new a(`Element not found: ${e}`,"CONFIGURATION_ERROR");let r=this.createIndividualFormElement(t,n);r.mount(e),this.mountedElements.set(t,r),this.trackElementState(t,r);}createIndividualFormElement(e,t){return this.elements||(this.elements=this.stripe.elements({appearance:this.config.appearance,locale:this.config.locale,fonts:this.config.fonts,paymentMethodCreation:"manual"})),this.elements.create(e,t)}async validate(){let e=[];for(let[t,n]of this.elementStates.entries())n.complete||e.push({field:t,message:n.error??`${S[t]??t} failed validation`});return {isValid:e.length===0,errors:e}}getElements(){return this.elements}unmountAll(){for(let e of this.mountedElements.values())e.unmount();this.mountedElements.clear(),this.elementStates.clear();}trackElementState(e,t){this.elementStates.set(e,{complete:false});let n=i=>{this.elementStates.set(e,{complete:i.complete,error:i.error?.message});};t.on("change",n);}};var f=class{constructor(){this.extensions=[];}add(e){this.extensions.push(e);}async runBeforePayment(e){let t=e;for(let n of this.extensions)n.beforePayment&&(t=await n.beforePayment(t));return t}async runAfterPayment(e){await Promise.all(this.extensions.filter(t=>t.afterPayment).map(t=>t.afterPayment(e)));}async runOnError(e){await Promise.all(this.extensions.filter(t=>t.onPaymentError).map(t=>t.onPaymentError(e)));}};var g=class{constructor(e,t,n){this.stripeAdapter=e;this.elementsManager=t;this.verapayService=n;}async process(e,t){let n=this.elementsManager.getElements();await this.validatePaymentCanProceed(n,t),await n.submit();let i=await this.stripeAdapter.createPaymentMethod(n,t.isUsingIndividualFormElements);return await this.verapayService.processPrePayment({merchantId:t.merchantId,paymentIntentId:t.paymentIntentId,paymentMethodId:i,amount:t.amount,currency:t.currency,customerData:{email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName},description:e.description,metadata:e.metadata}),this.confirm(t.clientSecret,{paymentMethodId:i,isUsingStripePaymentElement:t.isUsingStripePaymentElement,isUsingIndividualFormElements:t.isUsingIndividualFormElements})}async validatePaymentCanProceed(e,t){if(!e)throw new a("Payment form not mounted","CONFIGURATION_ERROR");if(t.isUsingStripePaymentElement&&t.isUsingIndividualFormElements)throw new a("Both forms of payment form in use");if(t.isUsingIndividualFormElements){let n=await this.elementsManager.validate();if(!n.isValid)throw new a(n.errors[0].message,"VALIDATION_ERROR")}}async confirm(e,t={}){let n;return t.isUsingStripePaymentElement?n=await this.stripeAdapter.confirmPayment(t.paymentMethodId||"",e):t.isUsingIndividualFormElements?n=await this.stripeAdapter.confirmCardPayment(t.paymentMethodId||"",e):n=await this.stripeAdapter.confirmPayment(t.paymentMethodId||"",e),this.formatPaymentResult(n)}async retrievePaymentIntent(e){let t=await this.stripeAdapter.retrievePaymentIntent(e);return this.formatPaymentResult(t)}formatPaymentResult(e){let t=e.paymentIntent,n="failed";return t.status==="succeeded"?n="succeeded":["processing","requires_action","requires_confirmation"].includes(t.status)&&(n="processing"),{success:t.status==="succeeded",paymentIntentId:t.id,status:n}}};var I=class{constructor(e,t){this.stripeAdapter=e;this.elementsManager=t;}async save(e,t){let n=this.elementsManager.getElements();await this.validateSetupCanProceed(n,t),await n.submit();let i=await this.stripeAdapter.createPaymentMethod(n,t.isUsingIndividualFormElements),r=await this.stripeAdapter.confirmCardSetup(i,e);return this.formatSetupResult(r)}async retrieve(e){let t=await this.stripeAdapter.retrieveSetupIntent(e);return this.formatSetupResult(t)}async validateSetupCanProceed(e,t){if(!e)throw new a("Card form not mounted","CONFIGURATION_ERROR");if(t.isUsingStripePaymentElement&&t.isUsingIndividualFormElements)throw new a("Both forms of card form in use","CONFIGURATION_ERROR");if(t.isUsingIndividualFormElements){let n=await this.elementsManager.validate();if(!n.isValid)throw new a(n.errors[0].message,"VALIDATION_ERROR")}}formatSetupResult(e){let t=e.setupIntent,n="failed";t.status==="succeeded"?n="succeeded":t.status==="processing"?n="processing":(t.status==="requires_action"||t.status==="requires_confirmation")&&(n="requires_action");let i=t.payment_method,r=typeof i=="string"?i:i?.id;return {success:t.status==="succeeded",savedPaymentMethodId:r,setupIntentId:t.id,status:n}}};var d=class{constructor(e,t){this.baseUrl=e,this.apiKey=t;}setApiKey(e){this.apiKey=e;}async getPaymentIntentConfig(e){try{let t=await fetch(`${this.baseUrl}/v1/payment_intents/config?client_secret=${encodeURIComponent(e)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new a("Failed to fetch provider config","CONFIGURATION_ERROR");return t.json()}catch(t){throw t instanceof a?t:new a("Error connecting to Verapay API","NETWORK_ERROR")}}async getSetupIntentConfig(e){try{let t=await fetch(`${this.baseUrl}/v1/setup_intents/config?client_secret=${encodeURIComponent(e)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new a("Failed to fetch setup config","CONFIGURATION_ERROR");return t.json()}catch(t){throw t instanceof a?t:new a("Error connecting to Verapay API","NETWORK_ERROR")}}async initialisePayment(e){let{merchantId:t,paymentData:n}=e;try{let i=await fetch(`${this.baseUrl}/api/initialise-payment`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey?{"x-api-key":this.apiKey}:{}},body:JSON.stringify({merchantId:t,paymentData:{...n,paymentMethodType:"card"}})});if(!i.ok){let m=await i.json().catch(()=>({}));throw new a(this.extractErrorMessage(m,i.status),"CONFIGURATION_ERROR")}let r=await i.json();if(!r.clientSecret||!r.paymentIntentId)throw new a("Missing clientSecret or paymentIntentId in server response","CONFIGURATION_ERROR");return {paymentIntentId:r.paymentIntentId,clientSecret:r.clientSecret,connectAccountId:r.connectAccountId,stripePublishableKey:r.stripePublishableKey}}catch(i){throw i instanceof a?i:new a(i instanceof Error?i.message:"Unknown error occurred","CONFIGURATION_ERROR")}}async processPrePayment(e){try{let t=await fetch(`${this.baseUrl}/api/process-prepayment`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey?{"x-api-key":this.apiKey}:{}},body:JSON.stringify({merchantId:e.merchantId,paymentIntentId:e.paymentIntentId,paymentMethodId:e.paymentMethodId,amount:e.amount,currency:e.currency,customerData:e.customerData,description:e.description,metadata:e.metadata})});if(!t.ok){let n=await t.json().catch(()=>({}));throw new a(this.extractErrorMessage(n,t.status),"CONFIGURATION_ERROR")}}catch(t){throw t instanceof a?t:new a(t instanceof Error?t.message:"Unknown error occurred","CONFIGURATION_ERROR")}}extractErrorMessage(e,t){if(!e||typeof e!="object")return `HTTP error! status: ${t}`;let n=e,i=[n.error,n.message,n.details];for(let r of i){if(typeof r=="string"&&r.trim().length>0)return r;if(r&&typeof r=="object")try{return JSON.stringify(r)}catch{}}return `HTTP error! status: ${t}`}};function R(s){return s.startsWith("vpy_cs_test_")?s.replace("vpy_cs_test_",""):s.startsWith("vpy_cs_live_")?s.replace("vpy_cs_live_",""):s}var E=class E{constructor(e){this.stripeAdapter=null;this.elementsManager=null;this.paymentService=null;this.setupService=null;this.initializationPromise=null;this.isUsingStripePaymentElement=false;this.isUsingIndividualFormElements=false;this.intentKind="payment";this.rawSecret=null;this.paymentIntentId=null;this.amount=null;this.currency=null;this.merchantId=null;if(!e.apiKey&&!e.clientSecret)throw new a("Either apiKey or clientSecret is required.","CONFIGURATION_ERROR");if(e.apiKey&&e.clientSecret)throw new a("Cannot provide both apiKey and clientSecret. Use apiKey for frontend-initialized flows or clientSecret for backend-initialized flows.","CONFIGURATION_ERROR");e.apiKey&&!e.apiKey.includes("_pk_")&&typeof window<"u"&&console.warn("Verapay Security Warning: You are using a Secret Key in a frontend environment. Please use a Publishable Key (vpy_pk_...) instead."),this.config=e;let t=this.config.apiUrlOverride||E.BACKEND_URL;this.verapayService=new d(t,this.config.apiKey||""),this.extensionsManager=new f;}async initialize(){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{let e,t,n;if(this.config.clientSecret)if(this.intentKind=R(this.config.clientSecret).startsWith("seti_")?"setup":"payment",this.intentKind==="setup"){let r=await this.verapayService.getSetupIntentConfig(this.config.clientSecret);if(r.object!=="setup_intent_config")throw new a("Unexpected configuration returned for setup intent","CONFIGURATION_ERROR");e=this.config.clientSecret,t="",n=r.publishableKey,this.merchantId=r.merchantId,r.verapayPublishableKey&&this.verapayService.setApiKey(r.verapayPublishableKey);}else {let r=await this.verapayService.getPaymentIntentConfig(this.config.clientSecret);e=this.config.clientSecret,t=r.paymentIntentId,n=r.publishableKey,this.amount=r.amount,this.currency=r.currency,this.merchantId=r.merchantId,r.verapayPublishableKey&&this.verapayService.setApiKey(r.verapayPublishableKey);}else {this.validatePaymentInitialisation();let r=await this.verapayService.initialisePayment({merchantId:this.config.merchantId??"",paymentData:this.config.paymentData});e=r.clientSecret,t=r.paymentIntentId,n=r.stripePublishableKey,this.amount=this.config.paymentData.amount,this.currency=this.config.paymentData.currency,this.merchantId=this.config.merchantId??"";}this.rawSecret=R(e),this.paymentIntentId=t;let i=await loadStripe(n);if(!i)throw new a("Failed to load Stripe","CONFIGURATION_ERROR");this.stripeAdapter=new y(i),this.elementsManager=new h(i,this.config,this.rawSecret),this.paymentService=new g(this.stripeAdapter,this.elementsManager,this.verapayService),this.setupService=new I(this.stripeAdapter,this.elementsManager);})().catch(e=>{throw this.initializationPromise=null,e}),this.initializationPromise)}async confirmPayment(){return await this.ensureInitialized(),this.assertIntentKind("payment","confirmPayment"),this.paymentService.confirm(this.rawSecret,{isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements})}async saveCard(){await this.ensureInitialized(),this.assertIntentKind("setup","saveCard");try{return await this.setupService.save(this.rawSecret,{isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements})}catch(e){throw this.handlePaymentError(e)}}async retrieveSetupIntent(){return await this.ensureInitialized(),this.assertIntentKind("setup","retrieveSetupIntent"),this.setupService.retrieve(this.rawSecret)}teardown(){this.elementsManager?.unmountAll(),this.stripeAdapter=null,this.elementsManager=null,this.paymentService=null,this.setupService=null,this.initializationPromise=null,this.isUsingStripePaymentElement=false,this.isUsingIndividualFormElements=false,this.intentKind="payment",this.rawSecret=null,this.paymentIntentId=null,this.amount=null,this.currency=null,this.merchantId=null;}async retrievePaymentIntent(){return await this.ensureInitialized(),this.paymentService.retrievePaymentIntent(this.rawSecret)}async processPayment(e){await this.ensureInitialized(),this.assertIntentKind("payment","processPayment");let t=await this.extensionsManager.runBeforePayment(e);try{let n=await this.paymentService.process(t,{merchantId:this.merchantId,paymentIntentId:this.paymentIntentId,clientSecret:this.rawSecret,amount:this.amount,currency:this.currency,isUsingStripePaymentElement:this.isUsingStripePaymentElement,isUsingIndividualFormElements:this.isUsingIndividualFormElements});return await this.extensionsManager.runAfterPayment(n),n}catch(n){throw await this.extensionsManager.runOnError(n),this.handlePaymentError(n)}}async mountPaymentForm(e){await this.ensureInitialized(),this.elementsManager.mountPaymentElement(e),this.isUsingStripePaymentElement=true;}async mountCardNumber(e){await this.ensureInitialized(),this.elementsManager.mountCardNumberElement(e),this.isUsingIndividualFormElements=true;}async mountCardExpiry(e){await this.ensureInitialized(),this.elementsManager.mountCardExpiryElement(e),this.isUsingIndividualFormElements=true;}async mountCardCvc(e){await this.ensureInitialized(),this.elementsManager.mountCardCvcElement(e),this.isUsingIndividualFormElements=true;}async mountAddress(e,t){await this.ensureInitialized(),this.elementsManager.mountAddressElement(e,t),this.isUsingIndividualFormElements=true;}addExtension(e){this.extensionsManager.add(e);}async ensureInitialized(){this.stripeAdapter||await this.initialize();}assertIntentKind(e,t){if(this.intentKind!==e)throw new a(`${t} requires a ${e} intent client secret`,"CONFIGURATION_ERROR")}validatePaymentInitialisation(){if(!this.config.paymentData)throw new a("paymentData is required for frontend-initialized flows.","CONFIGURATION_ERROR");let{amount:e,currency:t,platformFee:n}=this.config.paymentData;if(!t)throw new l("Currency is required","currency");let i=t.toUpperCase(),r=this.toMoney(e,i,"amount");if(r.isZero()||r.isNegative())throw new l("Amount must be greater than 0","amount");if(n!==void 0){let m=this.toMoney(n,i,"platformFee");if(m.isNegative())throw new l("platformFee cannot be negative","platformFee");if(m.greaterThan(r))throw new l("platformFee cannot exceed the payment amount","platformFee")}}toMoney(e,t,n){try{return Money.fromInteger(e,t)}catch{throw new l(`${n} must be an integer in the smallest currency unit (e.g., cents for USD)`,n)}}handlePaymentError(e){if(e instanceof a)return e;let t=e instanceof Error?e.message:"Payment failed",n=e?.code;return new o(t,n)}};E.BACKEND_URL="https://api.verapay.app";var w=E;var P=class{validateCardNumber(e){let t=e.replace(/\D/g,"");if(t.length<13||t.length>19)return false;let n=0,i=false;for(let r=t.length-1;r>=0;r--){let m=parseInt(t[r],10);i&&(m*=2,m>9&&(m-=9)),n+=m,i=!i;}return n%10===0}detectCardType(e){let t=e.replace(/\D/g,"");return /^4/.test(t)?"visa":/^5[1-5]/.test(t)?"mastercard":/^3[47]/.test(t)?"amex":/^6(?:011|5)/.test(t)?"discover":"unknown"}validateExpiry(e,t){let n=new Date,i=n.getFullYear(),r=n.getMonth()+1;if(e<1||e>12)return false;let m=t<100?2e3+t:t;return !(m<i||m===i&&e<r)}validateCVC(e,t="unknown"){let n=e.replace(/\D/g,"");return t==="amex"?n.length===4:n.length===3||n.length===4}validateAll(e,t,n,i){let r=this.detectCardType(e);return {number:{isValid:this.validateCardNumber(e),cardType:r},expiry:{isValid:this.validateExpiry(t,n),month:t,year:n},cvc:{isValid:this.validateCVC(i,r),length:i.replace(/\D/g,"").length}}}};var v=class{static sanitizeCardNumber(e){return e.replace(/\D/g,"")}static formatCardNumber(e){return this.sanitizeCardNumber(e).replace(/(\d{4})/g,"$1 ").trim()}static sanitizeCVC(e){return e.replace(/\D/g,"").slice(0,4)}static sanitizeExpiry(e){let t=e.replace(/\D/g,"");return t.length===4?{month:parseInt(t.slice(0,2),10),year:parseInt(t.slice(2,4),10)}:t.length===6?{month:parseInt(t.slice(0,2),10),year:parseInt(t.slice(2,6),10)}:null}};var ve="1.4.0";
2
2
  export{P as CardValidator,u as ErrorFormatter,v as InputSanitizer,o as PaymentError,ve as VERSION,l as ValidationError,w as VerapayClient,a as VerapayError,d as VerapayService};//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors/verapay-error.ts","../src/errors/validation-error.ts","../src/errors/payment-error.ts","../src/errors/error-formatter.ts","../src/client/stripe-adapter.ts","../src/client/elements-manager.ts","../src/client/payment-extensions-manager.ts","../src/services/payment-service.ts","../src/services/setup-service.ts","../src/services/verapay-service.ts","../src/utils/secret.util.ts","../src/client/verapay-client.ts","../src/validation/card-validator.ts","../src/validation/input-sanitizer.ts","../src/index.ts"],"names":["VerapayError","_VerapayError","message","code","details","ValidationError","field","metadata","PaymentError","_PaymentError","stripeCode","ErrorFormatter","error","StripeAdapter","stripe","paymentMethodId","clientSecret","result","elements","isUsingIndividualFormElements","address","DEFAULT_CARD_ELEMENT_CONFIG","FIELD_LABELS","ElementsManager","config","selector","elementsConfig","element","mode","fieldType","options","formFieldType","elementType","errors","state","handleElementChange","event","PaymentExtensionsManager","extension","request","modifiedRequest","ext","PaymentService","stripeAdapter","elementsManager","verapayService","context","validation","paymentIntent","status","SetupService","setupIntent","paymentMethod","savedPaymentMethodId","VerapayService","baseUrl","apiKey","response","merchantId","paymentData","errorData","data","record","candidates","candidate","unwrapClientSecret","wrappedSecret","_VerapayClient","backendUrl","paymentIntentId","stripePublishableKey","loadStripe","paymentResult","expected","method","amount","currency","partnerFee","uppercaseCurrency","paymentAmount","partnerFeeAmount","value","fieldName","Money","VerapayClient","CardValidator","cardNumber","cleaned","sum","isEven","i","digit","month","year","now","currentYear","currentMonth","fullYear","cvc","cardType","expiryMonth","expiryYear","InputSanitizer","input","VERSION"],"mappings":"4EAGaA,CAAAA,CAAN,MAAMC,UAAqB,KAAM,CAItC,YACEC,CAAAA,CACAC,CAAAA,CAAAA,gBAAAA,CACAC,EACA,CACA,KAAA,CAAMF,CAAO,CAAA,CACb,IAAA,CAAK,KAAO,cAAA,CACZ,IAAA,CAAK,KAAOC,CAAAA,CACZ,IAAA,CAAK,QAAU,CACb,IAAA,CAAAA,EACA,OAAA,CAAAD,CAAAA,CACA,iBAAkB,IAAA,CAAK,a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ADgB,IAAA,CAAK,kBAAA,CAAmBA,CAAK,CAAA,CAC9B,OAAA,CAAQ,WAAY,KAAK,CAAA,CAAE,MAC5C,CAEA,OAAO,WAAA,CAAYA,CAAAA,CAAuB,CACxC,OAAOA,CAAAA,CAAM,OAAA,CAAQ,MAAO,EAAE,CAAA,CAAE,MAAM,CAAA,CAAG,CAAC,CAC5C,CAEA,OAAO,eAAeA,CAAAA,CAAuD,CAC3E,IAAMhB,CAAAA,CAAUgB,CAAAA,CAAM,QAAQ,KAAA,CAAO,EAAE,CAAA,CAEvC,OAAIhB,CAAAA,CAAQ,MAAA,GAAW,EACd,CACL,KAAA,CAAO,SAASA,CAAAA,CAAQ,KAAA,CAAM,EAAG,CAAC,CAAA,CAAG,EAAE,CAAA,CACvC,IAAA,CAAM,SAASA,CAAAA,CAAQ,KAAA,CAAM,EAAG,CAAC,CAAA,CAAG,EAAE,CACxC,CAAA,CACSA,CAAAA,CAAQ,MAAA,GAAW,CAAA,CACrB,CACL,MAAO,QAAA,CAASA,CAAAA,CAAQ,MAAM,CAAA,CAAG,CAAC,EAAG,EAAE,CAAA,CACvC,KAAM,QAAA,CAASA,CAAAA,CAAQ,MAAM,CAAA,CAAG,CAAC,EAAG,EAAE,CACxC,EAGK,IACT,CACF,ECIO,IAAMiB,EAAAA,CAAU","file":"index.js","sourcesContent":["import type { ErrorDetails } from '../types';\nimport { ErrorCode } from '../types';\n\nexport class VerapayError extends Error {\n public readonly code: ErrorCode;\n public readonly details: ErrorDetails;\n\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.PAYMENT_FAILED,\n details?: Partial<ErrorDetails>\n ) {\n super(message);\n this.name = 'VerapayError';\n this.code = code;\n this.details = {\n code,\n message,\n formattedMessage: this.formatMessage(message, code),\n ...details,\n };\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, VerapayError);\n }\n }\n\n private formatMessage(message: string, code: ErrorCode): string {\n const messageMap: Record<ErrorCode, string> = {\n [ErrorCode.VALIDATION_ERROR]:\n 'Please check your payment information and try again.',\n [ErrorCode.PAYMENT_FAILED]:\n 'Your payment could not be processed. Please try again.',\n [ErrorCode.AUTHENTICATION_FAILED]:\n 'Payment authentication failed. Please try again.',\n [ErrorCode.NETWORK_ERROR]:\n 'Network error. Please check your connection and try again.',\n [ErrorCode.STRIPE_ERROR]:\n 'Payment service error. Please try again later.',\n [ErrorCode.CONFIGURATION_ERROR]:\n 'Configuration error. Please contact support.',\n [ErrorCode.CARD_DECLINED]:\n 'Your card was declined. Please use a different payment method.',\n [ErrorCode.INSUFFICIENT_FUNDS]:\n 'Insufficient funds. Please use a different payment method.',\n [ErrorCode.EXPIRED_CARD]:\n 'Your card has expired. Please use a different payment method.',\n };\n\n return messageMap[code] || message;\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n details: this.details,\n };\n }\n}\n","import { VerapayError } from './verapay-error';\nimport { ErrorCode } from '../types';\n\nexport class ValidationError extends VerapayError {\n constructor(message: string, field?: string, metadata?: Record<string, unknown>) {\n\n super(message, ErrorCode.VALIDATION_ERROR, {\n field,\n metadata,\n });\n this.name = 'ValidationError';\n }\n}\n","import { VerapayError } from './verapay-error';\nimport { ErrorCode } from '../types';\n\nexport class PaymentError extends VerapayError {\n constructor(\n message: string,\n stripeCode?: string,\n metadata?: Record<string, unknown>\n ) {\n const code = PaymentError.mapStripeCode(stripeCode);\n super(message, code, {\n stripeCode,\n metadata,\n });\n this.name = 'PaymentError';\n }\n\n private static mapStripeCode(stripeCode?: string): ErrorCode {\n if (!stripeCode) return ErrorCode.PAYMENT_FAILED;\n\n const codeMap: Record<string, ErrorCode> = {\n card_declined: ErrorCode.CARD_DECLINED,\n insufficient_funds: ErrorCode.INSUFFICIENT_FUNDS,\n expired_card: ErrorCode.EXPIRED_CARD,\n incorrect_cvc: ErrorCode.VALIDATION_ERROR,\n processing_error: ErrorCode.PAYMENT_FAILED,\n authentication_failed: ErrorCode.AUTHENTICATION_FAILED,\n };\n\n return codeMap[stripeCode] || ErrorCode.PAYMENT_FAILED;\n }\n}\n","import type { ErrorDetails } from '../types';\n\nexport class ErrorFormatter {\n static formatForUser(error: Error | ErrorDetails): string {\n if ('formattedMessage' in error) {\n return error.formattedMessage;\n }\n if (\n 'details' in error &&\n error.details &&\n typeof error.details === 'object' &&\n 'formattedMessage' in error.details &&\n typeof error.details.formattedMessage === 'string'\n ) {\n return error.details.formattedMessage;\n }\n return 'An unexpected error occurred. Please try again.';\n }\n\n static formatForDeveloper(error: Error | ErrorDetails): string {\n if ('code' in error && 'message' in error) {\n return `[${error.code}] ${error.message}`;\n }\n return error.message || 'Unknown error';\n }\n\n static toJSON(error: Error | ErrorDetails): Record<string, unknown> {\n\n if ('toJSON' in error && typeof error.toJSON === 'function') {\n return error.toJSON();\n }\n\n return {\n name: (error as Error).name || 'Error',\n message: error.message,\n ...('code' in error && { code: error.code }),\n ...('details' in error && { details: error.details }),\n };\n }\n}\n","import type { PaymentIntent, SetupIntent, Stripe, StripeElements } from '@stripe/stripe-js';\nimport { PaymentError } from '../errors';\n\nexport class StripeAdapter {\n constructor(private stripe: Stripe) {}\n\n async confirmPayment(\n paymentMethodId: string,\n clientSecret: string\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.confirmPayment({\n clientSecret,\n confirmParams: {\n payment_method: paymentMethodId,\n return_url: window.location.href,\n },\n redirect: 'if_required',\n });\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Payment failed',\n result.error.code\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async confirmCardPayment(\n paymentMethodId: string,\n clientSecret: string\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.confirmCardPayment(clientSecret, {\n payment_method: paymentMethodId,\n });\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Payment failed',\n result.error.code\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async createPaymentMethod(\n elements: StripeElements,\n isUsingIndividualFormElements: boolean = false\n ): Promise<string> {\n let result;\n\n if (!isUsingIndividualFormElements) {\n result = await this.stripe.createPaymentMethod({\n elements,\n });\n } else {\n // @ts-expect-error - Stripe types don't include mode parameter for getElement\n const addressElement = await elements.getElement('address', { mode: 'billing' })!.getValue();\n\n const address = addressElement!.value;\n\n result = await this.stripe.createPaymentMethod({\n type: 'card',\n card: elements.getElement('cardNumber')!,\n billing_details: {\n name: address.name,\n address: {\n ...address.address,\n line2: address.address.line2 ?? undefined,\n },\n },\n });\n }\n\n if (result.error || !result.paymentMethod) {\n throw new PaymentError(\n result.error?.message || 'Failed to create payment method',\n result.error?.code\n );\n }\n\n return result.paymentMethod.id;\n }\n\n async retrievePaymentIntent(\n clientSecret: string,\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.retrievePaymentIntent(clientSecret);\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Failed to retrieve payment intent',\n result.error.code,\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async confirmCardSetup(\n paymentMethodId: string,\n clientSecret: string,\n ): Promise<{ setupIntent: SetupIntent }> {\n const result = await this.stripe.confirmCardSetup(clientSecret, {\n payment_method: paymentMethodId,\n });\n\n if (result.error) {\n throw new PaymentError(result.error.message || 'Card setup failed', result.error.code);\n }\n\n return result as { setupIntent: SetupIntent };\n }\n\n async retrieveSetupIntent(clientSecret: string): Promise<{ setupIntent: SetupIntent }> {\n const result = await this.stripe.retrieveSetupIntent(clientSecret);\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Failed to retrieve setup intent',\n result.error.code,\n );\n }\n\n return result as { setupIntent: SetupIntent };\n }\n}\n\n","import type {\n Stripe,\n StripeElements,\n StripeElement,\n StripePaymentElement,\n StripeCardNumberElement,\n PaymentWalletsOption,\n} from '@stripe/stripe-js';\nimport type { VerapayConfig, ValidationError, ValidationResult } from '../types';\nimport { VerapayError, ErrorCode } from '../errors';\n\ntype ElementState = { complete: boolean; error?: string }\n\nconst DEFAULT_CARD_ELEMENT_CONFIG = {\n showIcon: true,\n iconStyle: 'solid' as const,\n placeholders: {\n cardNumber: '1234 1234 1234 1234',\n cardExpiry: 'MM / YY - TESTING',\n cardCvc: 'CVC',\n },\n style: {\n base: {\n color: '#333333',\n fontFamily: 'system-ui, -apple-system, sans-serif',\n fontSize: '16px',\n '::placeholder': { color: '#aab7c4' },\n },\n complete: {\n color: '#333333',\n },\n empty: {},\n invalid: {\n color: '#df1b41',\n },\n },\n}\n\nconst FIELD_LABELS: Record<string, string> = {\n cardNumber: 'Card number',\n cardExpiry: 'Expiry date',\n cardCvc: 'CVC',\n address: 'Address',\n}\n\nexport class ElementsManager {\n private elements: StripeElements | null = null;\n private mountedElements: Map<string, StripeElement> = new Map();\n private elementStates: Map<string, ElementState> = new Map();\n\n constructor(\n private stripe: Stripe,\n private config: VerapayConfig,\n private clientSecret: string,\n ) {\n if (!clientSecret) {\n throw new VerapayError(\n 'Client secret not initialized',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n }\n\n\n mountPaymentElement(selector: string): void {\n if (!this.elements) {\n const elementsConfig = {\n clientSecret: this.clientSecret,\n appearance: this.config.appearance,\n locale: this.config.locale,\n fonts: this.config.fonts,\n paymentMethodCreation: 'manual',\n };\n\n this.elements = this.stripe.elements(elementsConfig);\n }\n\n const container = document.querySelector(selector);\n\n if (!container) {\n throw new VerapayError(\n `Element not found: ${selector}`,\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const element = this.elements.create('payment', {\n layout: 'tabs',\n wallets: { link: 'never' } as unknown as PaymentWalletsOption,\n }) as StripePaymentElement;\n\n element.mount(selector);\n this.mountedElements.set('payment', element);\n }\n\n mountCardNumberElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardNumber', this.cardElementOptions('cardNumber'));\n }\n\n mountCardExpiryElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardExpiry', this.cardElementOptions('cardExpiry'));\n }\n\n mountCardCvcElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardCvc', this.cardElementOptions('cardCvc'));\n }\n\n mountAddressElement(selector: string, mode: 'billing' | 'shipping'): void {\n this.mountIndividualFormElement(selector, 'address', { mode });\n }\n\n private cardElementOptions(fieldType: 'cardNumber' | 'cardExpiry' | 'cardCvc'): Record<string, unknown> {\n const { elementsConfig } = this.config;\n const options: Record<string, unknown> = {\n placeholder: elementsConfig?.placeholders?.[fieldType] ?? DEFAULT_CARD_ELEMENT_CONFIG.placeholders[fieldType],\n style: {\n base: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.base, ...elementsConfig?.style?.base },\n complete: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.complete, ...elementsConfig?.style?.complete },\n empty: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.empty, ...elementsConfig?.style?.empty },\n invalid: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.invalid, ...elementsConfig?.style?.invalid },\n },\n };\n\n if (fieldType === 'cardNumber') {\n options.showIcon = elementsConfig?.showIcon ?? DEFAULT_CARD_ELEMENT_CONFIG.showIcon;\n options.iconStyle = elementsConfig?.iconStyle ?? DEFAULT_CARD_ELEMENT_CONFIG.iconStyle;\n }\n\n return options;\n }\n\n private mountIndividualFormElement(selector: string, formFieldType: 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'address', options?: Record<string, unknown>) {\n const container = document.querySelector(selector);\n\n if (!container) {\n throw new VerapayError(\n `Element not found: ${selector}`,\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const element = this.createIndividualFormElement(formFieldType, options) as StripeCardNumberElement;\n element.mount(selector);\n\n this.mountedElements.set(formFieldType, element);\n this.trackElementState(formFieldType, element);\n }\n\n private createIndividualFormElement(\n elementType: 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'address',\n options?: Record<string, unknown>,\n ): StripeElement {\n if (!this.elements) {\n this.elements = this.stripe.elements({\n appearance: this.config.appearance,\n locale: this.config.locale,\n fonts: this.config.fonts,\n paymentMethodCreation: 'manual',\n });\n }\n\n return this.elements.create(elementType as 'cardNumber', options);\n }\n\n\n\n async validate(): Promise<ValidationResult> {\n const errors: ValidationError[] = []\n\n for (const [field, state] of this.elementStates.entries()) {\n if (!state.complete) {\n errors.push({\n field,\n message: state.error ?? `${FIELD_LABELS[field] ?? field} failed validation`,\n })\n }\n }\n\n return { isValid: errors.length === 0, errors }\n }\n\n getElements(): StripeElements | null {\n return this.elements;\n }\n\n unmountAll(): void {\n for (const element of this.mountedElements.values()) {\n element.unmount();\n }\n this.mountedElements.clear();\n this.elementStates.clear();\n }\n\n private trackElementState(field: string, element: StripeElement): void {\n this.elementStates.set(field, { complete: false })\n\n const handleElementChange = (event: { complete: boolean; error?: { message: string } }) => {\n this.elementStates.set(field, { complete: event.complete, error: event.error?.message })\n };\n\n (element as unknown as { on: (event: string, handler: (e: unknown) => void) => void }).on(\n 'change',\n handleElementChange as (e: unknown) => void,\n );\n }\n}\n\n\n","import type { ProcessPaymentRequest, PaymentResult } from '../types'\nimport type { PaymentExtension } from '../extensions'\n\nexport class PaymentExtensionsManager {\n private extensions: PaymentExtension[] = []\n\n add(extension: PaymentExtension): void {\n this.extensions.push(extension)\n }\n\n async runBeforePayment(request: ProcessPaymentRequest): Promise<ProcessPaymentRequest> {\n let modifiedRequest = request\n for (const ext of this.extensions) {\n if (ext.beforePayment) {\n modifiedRequest = await ext.beforePayment(modifiedRequest)\n }\n }\n return modifiedRequest\n }\n\n async runAfterPayment(result: PaymentResult): Promise<void> {\n await Promise.all(\n this.extensions\n .filter((ext) => ext.afterPayment)\n .map((ext) => ext.afterPayment!(result)),\n )\n }\n\n async runOnError(error: Error): Promise<void> {\n await Promise.all(\n this.extensions\n .filter((ext) => ext.onPaymentError)\n .map((ext) => ext.onPaymentError!(error)),\n )\n }\n}\n","import { StripeAdapter } from '../client/stripe-adapter'\nimport { ElementsManager } from '../client/elements-manager'\nimport { ErrorCode, VerapayError } from '../errors'\nimport { VerapayService } from './verapay-service'\nimport type { ProcessPaymentRequest, PaymentResult } from '../types'\nimport { StripeElements } from '@stripe/stripe-js';\n\nexport interface ProcessPaymentContext {\n merchantId: string\n paymentIntentId: string\n clientSecret: string\n amount: number\n currency: string\n isUsingStripePaymentElement: boolean\n isUsingIndividualFormElements: boolean\n}\n\nexport class PaymentService {\n constructor(\n private stripeAdapter: StripeAdapter,\n private elementsManager: ElementsManager,\n private verapayService: VerapayService,\n ) {}\n\n async process(request: ProcessPaymentRequest, context: ProcessPaymentContext): Promise<PaymentResult> {\n const elements = this.elementsManager.getElements()\n\n await this.validatePaymentCanProceed(elements, context);\n\n await elements!.submit()\n\n const paymentMethodId = await this.stripeAdapter.createPaymentMethod(\n elements!,\n context.isUsingIndividualFormElements,\n )\n\n await this.verapayService.processPrePayment({\n merchantId: context.merchantId,\n paymentIntentId: context.paymentIntentId,\n paymentMethodId,\n amount: context.amount,\n currency: context.currency,\n customerData: {\n email: request.customerEmail,\n firstName: request.customerFirstName,\n lastName: request.customerLastName,\n },\n description: request.description,\n metadata: request.metadata,\n })\n\n return this.confirm(context.clientSecret, {\n paymentMethodId,\n isUsingStripePaymentElement: context.isUsingStripePaymentElement,\n isUsingIndividualFormElements: context.isUsingIndividualFormElements,\n });\n }\n\n private async validatePaymentCanProceed(\n elements: StripeElements | null,\n context: ProcessPaymentContext,\n ) {\n if (!elements) {\n throw new VerapayError('Payment form not mounted', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingStripePaymentElement && context.isUsingIndividualFormElements) {\n throw new VerapayError('Both forms of payment form in use');\n }\n\n if (context.isUsingIndividualFormElements) {\n const validation = await this.elementsManager.validate();\n if (!validation.isValid) {\n throw new VerapayError(validation.errors[0].message, ErrorCode.VALIDATION_ERROR);\n }\n }\n }\n\n async confirm(\n clientSecret: string,\n options: {\n isUsingStripePaymentElement?: boolean;\n isUsingIndividualFormElements?: boolean;\n paymentMethodId?: string;\n } = {},\n ): Promise<PaymentResult> {\n let result;\n\n if (options.isUsingStripePaymentElement) {\n result = await this.stripeAdapter.confirmPayment(options.paymentMethodId || '', clientSecret);\n } else if (options.isUsingIndividualFormElements) {\n result = await this.stripeAdapter.confirmCardPayment(\n options.paymentMethodId || '',\n clientSecret,\n );\n } else {\n result = await this.stripeAdapter.confirmPayment(options.paymentMethodId || '', clientSecret);\n }\n\n return this.formatPaymentResult(result);\n }\n\n async retrievePaymentIntent(clientSecret: string): Promise<PaymentResult> {\n const result = await this.stripeAdapter.retrievePaymentIntent(clientSecret);\n return this.formatPaymentResult(result);\n }\n\n private formatPaymentResult(result: unknown): PaymentResult {\n const paymentIntent = (result as { paymentIntent: { status: string; id: string } })\n .paymentIntent\n\n let status: 'succeeded' | 'processing' | 'failed' = 'failed'\n if (paymentIntent.status === 'succeeded') {\n status = 'succeeded'\n } else if (\n ['processing', 'requires_action', 'requires_confirmation'].includes(\n paymentIntent.status,\n )\n ) {\n status = 'processing'\n }\n\n return {\n success: paymentIntent.status === 'succeeded',\n paymentIntentId: paymentIntent.id,\n status,\n }\n }\n\n}\n\n\n","import { StripeAdapter } from '../client/stripe-adapter';\nimport { ElementsManager } from '../client/elements-manager';\nimport { ErrorCode, VerapayError } from '../errors';\nimport type { SetupResult } from '../types';\nimport { StripeElements } from '@stripe/stripe-js';\n\nexport interface SaveCardContext {\n isUsingStripePaymentElement: boolean;\n isUsingIndividualFormElements: boolean;\n}\n\nexport class SetupService {\n constructor(\n private stripeAdapter: StripeAdapter,\n private elementsManager: ElementsManager,\n ) {}\n\n async save(clientSecret: string, context: SaveCardContext): Promise<SetupResult> {\n const elements = this.elementsManager.getElements();\n\n await this.validateSetupCanProceed(elements, context);\n\n await elements!.submit();\n\n const paymentMethodId = await this.stripeAdapter.createPaymentMethod(\n elements!,\n context.isUsingIndividualFormElements,\n );\n\n const result = await this.stripeAdapter.confirmCardSetup(paymentMethodId, clientSecret);\n\n return this.formatSetupResult(result);\n }\n\n async retrieve(clientSecret: string): Promise<SetupResult> {\n const result = await this.stripeAdapter.retrieveSetupIntent(clientSecret);\n return this.formatSetupResult(result);\n }\n\n private async validateSetupCanProceed(\n elements: StripeElements | null,\n context: SaveCardContext,\n ): Promise<void> {\n if (!elements) {\n throw new VerapayError('Card form not mounted', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingStripePaymentElement && context.isUsingIndividualFormElements) {\n throw new VerapayError('Both forms of card form in use', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingIndividualFormElements) {\n const validation = await this.elementsManager.validate();\n if (!validation.isValid) {\n throw new VerapayError(validation.errors[0].message, ErrorCode.VALIDATION_ERROR);\n }\n }\n }\n\n private formatSetupResult(result: unknown): SetupResult {\n const setupIntent = (\n result as { setupIntent: { status: string; id: string; payment_method?: unknown } }\n ).setupIntent;\n\n let status: SetupResult['status'] = 'failed';\n if (setupIntent.status === 'succeeded') {\n status = 'succeeded';\n } else if (setupIntent.status === 'processing') {\n status = 'processing';\n } else if (\n setupIntent.status === 'requires_action' ||\n setupIntent.status === 'requires_confirmation'\n ) {\n status = 'requires_action';\n }\n\n const paymentMethod = setupIntent.payment_method;\n const savedPaymentMethodId =\n typeof paymentMethod === 'string'\n ? paymentMethod\n : (paymentMethod as { id?: string } | undefined)?.id;\n\n return {\n success: setupIntent.status === 'succeeded',\n savedPaymentMethodId,\n setupIntentId: setupIntent.id,\n status,\n };\n }\n}\n","import { ErrorCode, VerapayError } from '../errors';\nimport { PaymentData } from '../types';\n\nexport interface InitialisePaymentRequest {\n merchantId: string;\n paymentData: PaymentData;\n}\n\nexport interface InitialisePaymentResponse {\n paymentIntentId: string;\n clientSecret: string;\n connectAccountId: string;\n stripePublishableKey: string;\n}\n\nexport interface ProcessPrePaymentRequest {\n merchantId: string;\n paymentIntentId: string;\n paymentMethodId: string;\n amount: number;\n currency: string;\n customerData: Record<string, unknown>;\n\n description?: string;\n metadata?: Record<string, string>;\n}\n\nexport class VerapayService {\n private readonly baseUrl: string;\n private apiKey?: string;\n\n constructor(baseUrl: string, apiKey?: string) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n }\n\n setApiKey(apiKey: string): void {\n this.apiKey = apiKey;\n }\n\n\n async getPaymentIntentConfig(clientSecret: string): Promise<Record<string, unknown>> {\n\n try {\n const response = await fetch(\n `${this.baseUrl}/v1/payment_intents/config?client_secret=${encodeURIComponent(\n clientSecret,\n )}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n );\n\n if (!response.ok) {\n throw new VerapayError('Failed to fetch provider config', ErrorCode.CONFIGURATION_ERROR);\n }\n\n return response.json();\n } catch (error) {\n if (error instanceof VerapayError) throw error;\n throw new VerapayError('Error connecting to Verapay API', ErrorCode.NETWORK_ERROR);\n }\n }\n\n async getSetupIntentConfig(clientSecret: string): Promise<Record<string, unknown>> {\n try {\n const response = await fetch(\n `${this.baseUrl}/v1/setup_intents/config?client_secret=${encodeURIComponent(\n clientSecret,\n )}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n );\n\n if (!response.ok) {\n throw new VerapayError('Failed to fetch setup config', ErrorCode.CONFIGURATION_ERROR);\n }\n\n return response.json();\n } catch (error) {\n if (error instanceof VerapayError) throw error;\n throw new VerapayError('Error connecting to Verapay API', ErrorCode.NETWORK_ERROR);\n }\n }\n\n\n async initialisePayment(\n request: InitialisePaymentRequest\n ): Promise<InitialisePaymentResponse> {\n const { merchantId, paymentData } = request;\n\n try {\n const response = await fetch(`${this.baseUrl}/api/initialise-payment`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n\n body: JSON.stringify({\n merchantId,\n paymentData: { ...paymentData, paymentMethodType: 'card' },\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new VerapayError(\n this.extractErrorMessage(errorData, response.status),\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const data = await response.json();\n\n if (!data.clientSecret || !data.paymentIntentId) {\n throw new VerapayError(\n 'Missing clientSecret or paymentIntentId in server response',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n return {\n paymentIntentId: data.paymentIntentId,\n clientSecret: data.clientSecret,\n connectAccountId: data.connectAccountId,\n stripePublishableKey: data.stripePublishableKey,\n };\n } catch (error) {\n if (error instanceof VerapayError) {\n throw error;\n }\n throw new VerapayError(\n error instanceof Error ? error.message : 'Unknown error occurred',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n }\n\n async processPrePayment(request: ProcessPrePaymentRequest): Promise<void> {\n try {\n const response = await fetch(`${this.baseUrl}/api/process-prepayment`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n\n body: JSON.stringify({\n merchantId: request.merchantId,\n paymentIntentId: request.paymentIntentId,\n paymentMethodId: request.paymentMethodId,\n amount: request.amount,\n currency: request.currency,\n customerData: request.customerData,\n description: request.description,\n metadata: request.metadata,\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new VerapayError(\n this.extractErrorMessage(errorData, response.status),\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n } catch (error) {\n if (error instanceof VerapayError) {\n throw error;\n }\n throw new VerapayError(\n error instanceof Error ? error.message : 'Unknown error occurred',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n }\n\n private extractErrorMessage(errorData: unknown, status: number): string {\n if (!errorData || typeof errorData !== 'object') {\n return `HTTP error! status: ${status}`;\n }\n\n const record = errorData as Record<string, unknown>;\n const candidates = [record.error, record.message, record.details];\n\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate;\n }\n\n if (candidate && typeof candidate === 'object') {\n try {\n return JSON.stringify(candidate);\n } catch {\n // Ignore serialization issues and continue trying fallback messages.\n }\n }\n }\n\n return `HTTP error! status: ${status}`;\n }\n}\n","export function unwrapClientSecret(wrappedSecret: string): string {\n if (wrappedSecret.startsWith('vpy_cs_test_')) {\n return wrappedSecret.replace('vpy_cs_test_', '');\n }\n if (wrappedSecret.startsWith('vpy_cs_live_')) {\n return wrappedSecret.replace('vpy_cs_live_', '');\n }\n return wrappedSecret;\n}\n","import { loadStripe } from '@stripe/stripe-js';\nimport { Money } from 'ts-money';\nimport { StripeAdapter } from './stripe-adapter';\nimport { ElementsManager } from './elements-manager';\nimport type { PaymentExtension } from '../extensions';\nimport { PaymentExtensionsManager } from './payment-extensions-manager';\nimport { PaymentService } from '../services/payment-service';\nimport { SetupService } from '../services/setup-service';\nimport {\n ErrorCode,\n VerapayError,\n PaymentError,\n ValidationError,\n} from '../errors';\nimport { VerapayService } from '../services/verapay-service';\nimport { unwrapClientSecret } from '../utils/secret.util';\nimport type {\n VerapayConfig,\n ProcessPaymentRequest,\n PaymentResult,\n SetupResult,\n} from '../types';\n\ntype IntentKind = 'payment' | 'setup';\n\nexport class VerapayClient {\n private static readonly BACKEND_URL = 'https://api.verapay.app';\n\n private config: VerapayConfig;\n private verapayService: VerapayService;\n private extensionsManager: PaymentExtensionsManager;\n\n private stripeAdapter: StripeAdapter | null = null;\n private elementsManager: ElementsManager | null = null;\n private paymentService: PaymentService | null = null;\n private setupService: SetupService | null = null;\n private initializationPromise: Promise<void> | null = null;\n\n private isUsingStripePaymentElement: boolean = false;\n private isUsingIndividualFormElements: boolean = false;\n\n private intentKind: IntentKind = 'payment';\n private rawSecret: string | null = null;\n private paymentIntentId: string | null = null;\n private amount: number | null = null;\n private currency: string | null = null;\n private merchantId: string | null = null;\n\n constructor(config: VerapayConfig) {\n if (!config.apiKey && !config.clientSecret) {\n throw new VerapayError(\n 'Either apiKey or clientSecret is required.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n if (config.apiKey && config.clientSecret) {\n throw new VerapayError(\n 'Cannot provide both apiKey and clientSecret. Use apiKey for frontend-initialized flows or clientSecret for backend-initialized flows.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n if (config.apiKey && !config.apiKey.includes(\"_pk_\") && typeof window !== \"undefined\") {\n console.warn(\n \"Verapay Security Warning: You are using a Secret Key in a frontend environment. Please use a Publishable Key (vpy_pk_...) instead.\"\n );\n }\n\n this.config = config;\n\n const backendUrl = this.config.apiUrlOverride || VerapayClient.BACKEND_URL;\n\n this.verapayService = new VerapayService(backendUrl, this.config.apiKey || '');\n this.extensionsManager = new PaymentExtensionsManager();\n }\n\n async initialize(): Promise<void> {\n if (this.initializationPromise) {\n return this.initializationPromise;\n }\n\n this.initializationPromise = (async () => {\n let clientSecret: string;\n let paymentIntentId: string;\n let stripePublishableKey: string;\n\n\n if (this.config.clientSecret) {\n this.intentKind = unwrapClientSecret(this.config.clientSecret).startsWith('seti_')\n ? 'setup'\n : 'payment';\n\n if (this.intentKind === 'setup') {\n const config = (await this.verapayService.getSetupIntentConfig(\n this.config.clientSecret,\n )) as Record<string, any>;\n\n if (config.object !== 'setup_intent_config') {\n throw new VerapayError(\n 'Unexpected configuration returned for setup intent',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n clientSecret = this.config.clientSecret;\n paymentIntentId = '';\n stripePublishableKey = config.publishableKey;\n this.merchantId = config.merchantId;\n\n if (config.verapayPublishableKey) {\n this.verapayService.setApiKey(config.verapayPublishableKey);\n }\n } else {\n const config = (await this.verapayService.getPaymentIntentConfig(\n this.config.clientSecret,\n )) as Record<string, any>;\n clientSecret = this.config.clientSecret;\n paymentIntentId = config.paymentIntentId;\n stripePublishableKey = config.publishableKey;\n this.amount = config.amount;\n this.currency = config.currency;\n this.merchantId = config.merchantId;\n\n if (config.verapayPublishableKey) {\n this.verapayService.setApiKey(config.verapayPublishableKey);\n }\n }\n } else {\n this.validatePaymentInitialisation();\n\n const response = await this.verapayService.initialisePayment({\n merchantId: this.config.merchantId ?? '',\n paymentData: this.config.paymentData!,\n });\n clientSecret = response.clientSecret;\n paymentIntentId = response.paymentIntentId;\n stripePublishableKey = response.stripePublishableKey;\n this.amount = this.config.paymentData!.amount;\n this.currency = this.config.paymentData!.currency;\n this.merchantId = this.config.merchantId ?? '';\n }\n\n this.rawSecret = unwrapClientSecret(clientSecret);\n this.paymentIntentId = paymentIntentId;\n\n const stripe = await loadStripe(stripePublishableKey);\n\n if (!stripe) {\n throw new VerapayError(\n 'Failed to load Stripe',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n this.stripeAdapter = new StripeAdapter(stripe);\n this.elementsManager = new ElementsManager(stripe, this.config, this.rawSecret!);\n this.paymentService = new PaymentService(\n this.stripeAdapter,\n this.elementsManager,\n this.verapayService,\n );\n this.setupService = new SetupService(this.stripeAdapter, this.elementsManager);\n })().catch((error) => {\n this.initializationPromise = null;\n throw error;\n });\n\n return this.initializationPromise;\n }\n\n async confirmPayment(): Promise<PaymentResult> {\n await this.ensureInitialized();\n this.assertIntentKind('payment', 'confirmPayment');\n return this.paymentService!.confirm(this.rawSecret!, {\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n }\n\n async saveCard(): Promise<SetupResult> {\n await this.ensureInitialized();\n this.assertIntentKind('setup', 'saveCard');\n try {\n return await this.setupService!.save(this.rawSecret!, {\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n } catch (error) {\n throw this.handlePaymentError(error);\n }\n }\n\n async retrieveSetupIntent(): Promise<SetupResult> {\n await this.ensureInitialized();\n this.assertIntentKind('setup', 'retrieveSetupIntent');\n return this.setupService!.retrieve(this.rawSecret!);\n }\n\n teardown(): void {\n this.elementsManager?.unmountAll();\n this.stripeAdapter = null;\n this.elementsManager = null;\n this.paymentService = null;\n this.setupService = null;\n this.initializationPromise = null;\n this.isUsingStripePaymentElement = false;\n this.isUsingIndividualFormElements = false;\n this.intentKind = 'payment';\n this.rawSecret = null;\n this.paymentIntentId = null;\n this.amount = null;\n this.currency = null;\n this.merchantId = null;\n }\n\n async retrievePaymentIntent(): Promise<PaymentResult> {\n await this.ensureInitialized();\n return this.paymentService!.retrievePaymentIntent(this.rawSecret!);\n }\n\n async processPayment(request: ProcessPaymentRequest): Promise<PaymentResult> {\n await this.ensureInitialized();\n this.assertIntentKind('payment', 'processPayment');\n\n const modifiedRequest =\n await this.extensionsManager.runBeforePayment(request);\n\n try {\n const paymentResult = await this.paymentService!.process(modifiedRequest, {\n merchantId: this.merchantId!,\n paymentIntentId: this.paymentIntentId!,\n clientSecret: this.rawSecret!,\n amount: this.amount!,\n currency: this.currency!,\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n\n\n await this.extensionsManager.runAfterPayment(paymentResult);\n\n return paymentResult;\n } catch (error) {\n await this.extensionsManager.runOnError(error as Error);\n throw this.handlePaymentError(error);\n }\n }\n\n async mountPaymentForm(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountPaymentElement(selector);\n this.isUsingStripePaymentElement = true;\n }\n\n async mountCardNumber(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardNumberElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountCardExpiry(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardExpiryElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountCardCvc(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardCvcElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountAddress(\n selector: string,\n mode: 'billing' | 'shipping'\n ): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountAddressElement(selector, mode);\n this.isUsingIndividualFormElements = true;\n }\n\n addExtension(extension: PaymentExtension): void {\n this.extensionsManager.add(extension);\n }\n\n private async ensureInitialized(): Promise<void> {\n if (!this.stripeAdapter) {\n await this.initialize();\n }\n }\n\n private assertIntentKind(expected: IntentKind, method: string): void {\n if (this.intentKind !== expected) {\n throw new VerapayError(\n `${method} requires a ${expected} intent client secret`,\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n }\n\n private validatePaymentInitialisation(): void {\n if (!this.config.paymentData) {\n throw new VerapayError(\n 'paymentData is required for frontend-initialized flows.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n const { amount, currency, partnerFee } = this.config.paymentData;\n\n\n if (!currency) {\n throw new ValidationError('Currency is required', 'currency');\n }\n\n const uppercaseCurrency = currency.toUpperCase();\n\n const paymentAmount = this.toMoney(amount, uppercaseCurrency, 'amount');\n\n if (paymentAmount.isZero() || paymentAmount.isNegative()) {\n throw new ValidationError('Amount must be greater than 0', 'amount');\n }\n\n if (partnerFee !== undefined) {\n const partnerFeeAmount = this.toMoney(partnerFee, uppercaseCurrency, 'partnerFee');\n\n if (partnerFeeAmount.isNegative()) {\n throw new ValidationError('partnerFee cannot be negative', 'partnerFee');\n }\n\n if (partnerFeeAmount.greaterThan(paymentAmount)) {\n throw new ValidationError('partnerFee cannot exceed the payment amount', 'partnerFee');\n }\n }\n }\n\n private toMoney(value: number, currency: string, fieldName: string): Money {\n try {\n return Money.fromInteger(value, currency);\n } catch {\n throw new ValidationError(\n `${fieldName} must be an integer in the smallest currency unit (e.g., cents for USD)`,\n fieldName\n );\n }\n }\n\n\n private handlePaymentError(error: unknown): Error {\n if (error instanceof VerapayError) {\n return error;\n }\n const message = error instanceof Error ? error.message : 'Payment failed';\n const code = (error as Record<string, unknown>)?.code as string | undefined;\n\n return new PaymentError(message, code);\n }\n}\n\n","import type { CardValidation } from '../types';\n\nexport class CardValidator {\n validateCardNumber(cardNumber: string): boolean {\n const cleaned = cardNumber.replace(/\\D/g, '');\n\n if (cleaned.length < 13 || cleaned.length > 19) {\n return false;\n }\n\n let sum = 0;\n let isEven = false;\n\n for (let i = cleaned.length - 1; i >= 0; i--) {\n let digit = parseInt(cleaned[i], 10);\n\n if (isEven) {\n digit *= 2;\n if (digit > 9) {\n digit -= 9;\n }\n }\n\n sum += digit;\n isEven = !isEven;\n }\n\n return sum % 10 === 0;\n }\n\n detectCardType(cardNumber: string): string {\n const cleaned = cardNumber.replace(/\\D/g, '');\n\n if (/^4/.test(cleaned)) return 'visa';\n if (/^5[1-5]/.test(cleaned)) return 'mastercard';\n if (/^3[47]/.test(cleaned)) return 'amex';\n if (/^6(?:011|5)/.test(cleaned)) return 'discover';\n\n return 'unknown';\n }\n\n validateExpiry(month: number, year: number): boolean {\n const now = new Date();\n const currentYear = now.getFullYear();\n const currentMonth = now.getMonth() + 1;\n\n if (month < 1 || month > 12) {\n return false;\n }\n\n const fullYear = year < 100 ? 2000 + year : year;\n\n if (fullYear < currentYear) {\n return false;\n }\n\n if (fullYear === currentYear && month < currentMonth) {\n return false;\n }\n\n return true;\n }\n\n validateCVC(cvc: string, cardType: string = 'unknown'): boolean {\n const cleaned = cvc.replace(/\\D/g, '');\n\n if (cardType === 'amex') {\n return cleaned.length === 4;\n }\n\n return cleaned.length === 3 || cleaned.length === 4;\n }\n\n validateAll(\n cardNumber: string,\n expiryMonth: number,\n expiryYear: number,\n cvc: string\n ): CardValidation {\n const cardType = this.detectCardType(cardNumber);\n\n return {\n number: {\n isValid: this.validateCardNumber(cardNumber),\n cardType: cardType as 'visa' | 'mastercard' | 'amex' | 'discover' | 'unknown',\n\n },\n expiry: {\n isValid: this.validateExpiry(expiryMonth, expiryYear),\n month: expiryMonth,\n year: expiryYear,\n },\n cvc: {\n isValid: this.validateCVC(cvc, cardType),\n length: cvc.replace(/\\D/g, '').length,\n },\n };\n }\n}\n","export class InputSanitizer {\n static sanitizeCardNumber(input: string): string {\n return input.replace(/\\D/g, '');\n }\n\n static formatCardNumber(input: string): string {\n const cleaned = this.sanitizeCardNumber(input);\n return cleaned.replace(/(\\d{4})/g, '$1 ').trim();\n }\n\n static sanitizeCVC(input: string): string {\n return input.replace(/\\D/g, '').slice(0, 4);\n }\n\n static sanitizeExpiry(input: string): { month: number; year: number } | null {\n const cleaned = input.replace(/\\D/g, '');\n\n if (cleaned.length === 4) {\n return {\n month: parseInt(cleaned.slice(0, 2), 10),\n year: parseInt(cleaned.slice(2, 4), 10),\n };\n } else if (cleaned.length === 6) {\n return {\n month: parseInt(cleaned.slice(0, 2), 10),\n year: parseInt(cleaned.slice(2, 6), 10),\n };\n }\n\n return null;\n }\n}\n","export { VerapayClient } from './client/verapay-client';\nexport { VerapayService } from './services/verapay-service';\n\nexport type {\n InitialisePaymentRequest,\n InitialisePaymentResponse,\n ProcessPrePaymentRequest,\n} from './services/verapay-service';\n\nexport type {\n VerapayConfig,\n ElementsConfig,\n ProcessPaymentRequest,\n PaymentResult,\n SetupResult,\n CardValidation,\n ErrorDetails,\n ErrorCode,\n} from './types';\n\nexport {\n VerapayError,\n ValidationError,\n PaymentError,\n ErrorFormatter,\n} from './errors';\n\nexport { CardValidator, InputSanitizer } from './validation';\n\nexport type {\n PaymentExtension,\n DatabaseExtension,\n AnalyticsExtension,\n} from './extensions';\n\nexport const VERSION = '1.4.0';\n"]}
1
+ {"version":3,"sources":["../src/errors/verapay-error.ts","../src/errors/validation-error.ts","../src/errors/payment-error.ts","../src/errors/error-formatter.ts","../src/client/stripe-adapter.ts","../src/client/elements-manager.ts","../src/client/payment-extensions-manager.ts","../src/services/payment-service.ts","../src/services/setup-service.ts","../src/services/verapay-service.ts","../src/utils/secret.util.ts","../src/client/verapay-client.ts","../src/validation/card-validator.ts","../src/validation/input-sanitizer.ts","../src/index.ts"],"names":["VerapayError","_VerapayError","message","code","details","ValidationError","field","metadata","PaymentError","_PaymentError","stripeCode","ErrorFormatter","error","StripeAdapter","stripe","paymentMethodId","clientSecret","result","elements","isUsingIndividualFormElements","address","DEFAULT_CARD_ELEMENT_CONFIG","FIELD_LABELS","ElementsManager","config","selector","elementsConfig","element","mode","fieldType","options","formFieldType","elementType","errors","state","handleElementChange","event","PaymentExtensionsManager","extension","request","modifiedRequest","ext","PaymentService","stripeAdapter","elementsManager","verapayService","context","validation","paymentIntent","status","SetupService","setupIntent","paymentMethod","savedPaymentMethodId","VerapayService","baseUrl","apiKey","response","merchantId","paymentData","errorData","data","record","candidates","candidate","unwrapClientSecret","wrappedSecret","_VerapayClient","backendUrl","paymentIntentId","stripePublishableKey","loadStripe","paymentResult","expected","method","amount","currency","platformFee","uppercaseCurrency","paymentAmount","platformFeeAmount","value","fieldName","Money","VerapayClient","CardValidator","cardNumber","cleaned","sum","isEven","i","digit","month","year","now","currentYear","currentMonth","fullYear","cvc","cardType","expiryMonth","expiryYear","InputSanitizer","input","VERSION"],"mappings":"4EAGaA,CAAAA,CAAN,MAAMC,UAAqB,KAAM,CAItC,YACEC,CAAAA,CACAC,CAAAA,CAAAA,gBAAAA,CACAC,EACA,CACA,KAAA,CAAMF,CAAO,CAAA,CACb,IAAA,CAAK,KAAO,cAAA,CACZ,IAAA,CAAK,KAAOC,CAAAA,CACZ,IAAA,CAAK,QAAU,CACb,IAAA,CAAAA,EACA,OAAA,CAAAD,CAAAA,CACA,iBAAkB,IAAA,CAAK,aAAA,CAAcA,EAASC,CAAI,CAAA,CAClD,GAAGC,CACL,CAAA,CAEI,KAAA,CAAM,iBAAA,EACR,KAAA,CAAM,iBAAA,CAAkB,KAAMH,CAAY,EAE9C,CAEQ,aAAA,CAAcC,CAAAA,CAAiBC,EAAyB,CAsB9D,OArB8C,CAC3C,gBAAA,CACC,sDAAA,CACD,eACC,wDAAA,CACD,qBAAA,CACC,mDACD,aAAA,CACC,4DAAA,CACD,aACC,gDAAA,CACD,mBAAA,CACC,8CAAA,CACD,aAAA,CACC,gEAAA,CACD,kBAAA,CACC,6DACD,YAAA,CACC,+DACJ,EAEkBA,CAAI,CAAA,EAAKD,CAC7B,CAEA,MAAA,EAAS,CACP,OAAO,CACL,KAAM,IAAA,CAAK,IAAA,CACX,KAAM,IAAA,CAAK,IAAA,CACX,QAAS,IAAA,CAAK,OAAA,CACd,OAAA,CAAS,IAAA,CAAK,OAChB,CACF,CACF,ECzDO,IAAMG,EAAN,cAA8BL,CAAa,CAChD,WAAA,CAAYE,CAAAA,CAAiBI,EAAgBC,CAAAA,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,CAAG,CAAC,EAAG,EAAE,CAAA,CACvC,KAAM,QAAA,CAASA,CAAAA,CAAQ,MAAM,CAAA,CAAG,CAAC,EAAG,EAAE,CACxC,EAGK,IACT,CACF,ECIO,IAAMiB,EAAAA,CAAU","file":"index.js","sourcesContent":["import type { ErrorDetails } from '../types';\nimport { ErrorCode } from '../types';\n\nexport class VerapayError extends Error {\n public readonly code: ErrorCode;\n public readonly details: ErrorDetails;\n\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.PAYMENT_FAILED,\n details?: Partial<ErrorDetails>\n ) {\n super(message);\n this.name = 'VerapayError';\n this.code = code;\n this.details = {\n code,\n message,\n formattedMessage: this.formatMessage(message, code),\n ...details,\n };\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, VerapayError);\n }\n }\n\n private formatMessage(message: string, code: ErrorCode): string {\n const messageMap: Record<ErrorCode, string> = {\n [ErrorCode.VALIDATION_ERROR]:\n 'Please check your payment information and try again.',\n [ErrorCode.PAYMENT_FAILED]:\n 'Your payment could not be processed. Please try again.',\n [ErrorCode.AUTHENTICATION_FAILED]:\n 'Payment authentication failed. Please try again.',\n [ErrorCode.NETWORK_ERROR]:\n 'Network error. Please check your connection and try again.',\n [ErrorCode.STRIPE_ERROR]:\n 'Payment service error. Please try again later.',\n [ErrorCode.CONFIGURATION_ERROR]:\n 'Configuration error. Please contact support.',\n [ErrorCode.CARD_DECLINED]:\n 'Your card was declined. Please use a different payment method.',\n [ErrorCode.INSUFFICIENT_FUNDS]:\n 'Insufficient funds. Please use a different payment method.',\n [ErrorCode.EXPIRED_CARD]:\n 'Your card has expired. Please use a different payment method.',\n };\n\n return messageMap[code] || message;\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n details: this.details,\n };\n }\n}\n","import { VerapayError } from './verapay-error';\nimport { ErrorCode } from '../types';\n\nexport class ValidationError extends VerapayError {\n constructor(message: string, field?: string, metadata?: Record<string, unknown>) {\n\n super(message, ErrorCode.VALIDATION_ERROR, {\n field,\n metadata,\n });\n this.name = 'ValidationError';\n }\n}\n","import { VerapayError } from './verapay-error';\nimport { ErrorCode } from '../types';\n\nexport class PaymentError extends VerapayError {\n constructor(\n message: string,\n stripeCode?: string,\n metadata?: Record<string, unknown>\n ) {\n const code = PaymentError.mapStripeCode(stripeCode);\n super(message, code, {\n stripeCode,\n metadata,\n });\n this.name = 'PaymentError';\n }\n\n private static mapStripeCode(stripeCode?: string): ErrorCode {\n if (!stripeCode) return ErrorCode.PAYMENT_FAILED;\n\n const codeMap: Record<string, ErrorCode> = {\n card_declined: ErrorCode.CARD_DECLINED,\n insufficient_funds: ErrorCode.INSUFFICIENT_FUNDS,\n expired_card: ErrorCode.EXPIRED_CARD,\n incorrect_cvc: ErrorCode.VALIDATION_ERROR,\n processing_error: ErrorCode.PAYMENT_FAILED,\n authentication_failed: ErrorCode.AUTHENTICATION_FAILED,\n };\n\n return codeMap[stripeCode] || ErrorCode.PAYMENT_FAILED;\n }\n}\n","import type { ErrorDetails } from '../types';\n\nexport class ErrorFormatter {\n static formatForUser(error: Error | ErrorDetails): string {\n if ('formattedMessage' in error) {\n return error.formattedMessage;\n }\n if (\n 'details' in error &&\n error.details &&\n typeof error.details === 'object' &&\n 'formattedMessage' in error.details &&\n typeof error.details.formattedMessage === 'string'\n ) {\n return error.details.formattedMessage;\n }\n return 'An unexpected error occurred. Please try again.';\n }\n\n static formatForDeveloper(error: Error | ErrorDetails): string {\n if ('code' in error && 'message' in error) {\n return `[${error.code}] ${error.message}`;\n }\n return error.message || 'Unknown error';\n }\n\n static toJSON(error: Error | ErrorDetails): Record<string, unknown> {\n\n if ('toJSON' in error && typeof error.toJSON === 'function') {\n return error.toJSON();\n }\n\n return {\n name: (error as Error).name || 'Error',\n message: error.message,\n ...('code' in error && { code: error.code }),\n ...('details' in error && { details: error.details }),\n };\n }\n}\n","import type { PaymentIntent, SetupIntent, Stripe, StripeElements } from '@stripe/stripe-js';\nimport { PaymentError } from '../errors';\n\nexport class StripeAdapter {\n constructor(private stripe: Stripe) {}\n\n async confirmPayment(\n paymentMethodId: string,\n clientSecret: string\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.confirmPayment({\n clientSecret,\n confirmParams: {\n payment_method: paymentMethodId,\n return_url: window.location.href,\n },\n redirect: 'if_required',\n });\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Payment failed',\n result.error.code\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async confirmCardPayment(\n paymentMethodId: string,\n clientSecret: string\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.confirmCardPayment(clientSecret, {\n payment_method: paymentMethodId,\n });\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Payment failed',\n result.error.code\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async createPaymentMethod(\n elements: StripeElements,\n isUsingIndividualFormElements: boolean = false\n ): Promise<string> {\n let result;\n\n if (!isUsingIndividualFormElements) {\n result = await this.stripe.createPaymentMethod({\n elements,\n });\n } else {\n // @ts-expect-error - Stripe types don't include mode parameter for getElement\n const addressElement = await elements.getElement('address', { mode: 'billing' })!.getValue();\n\n const address = addressElement!.value;\n\n result = await this.stripe.createPaymentMethod({\n type: 'card',\n card: elements.getElement('cardNumber')!,\n billing_details: {\n name: address.name,\n address: {\n ...address.address,\n line2: address.address.line2 ?? undefined,\n },\n },\n });\n }\n\n if (result.error || !result.paymentMethod) {\n throw new PaymentError(\n result.error?.message || 'Failed to create payment method',\n result.error?.code\n );\n }\n\n return result.paymentMethod.id;\n }\n\n async retrievePaymentIntent(\n clientSecret: string,\n ): Promise<{ paymentIntent: PaymentIntent }> {\n const result = await this.stripe.retrievePaymentIntent(clientSecret);\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Failed to retrieve payment intent',\n result.error.code,\n );\n }\n\n return result as { paymentIntent: PaymentIntent };\n }\n\n async confirmCardSetup(\n paymentMethodId: string,\n clientSecret: string,\n ): Promise<{ setupIntent: SetupIntent }> {\n const result = await this.stripe.confirmCardSetup(clientSecret, {\n payment_method: paymentMethodId,\n });\n\n if (result.error) {\n throw new PaymentError(result.error.message || 'Card setup failed', result.error.code);\n }\n\n return result as { setupIntent: SetupIntent };\n }\n\n async retrieveSetupIntent(clientSecret: string): Promise<{ setupIntent: SetupIntent }> {\n const result = await this.stripe.retrieveSetupIntent(clientSecret);\n\n if (result.error) {\n throw new PaymentError(\n result.error.message || 'Failed to retrieve setup intent',\n result.error.code,\n );\n }\n\n return result as { setupIntent: SetupIntent };\n }\n}\n\n","import type {\n Stripe,\n StripeElements,\n StripeElement,\n StripePaymentElement,\n StripeCardNumberElement,\n PaymentWalletsOption,\n} from '@stripe/stripe-js';\nimport type { VerapayConfig, ValidationError, ValidationResult } from '../types';\nimport { VerapayError, ErrorCode } from '../errors';\n\ntype ElementState = { complete: boolean; error?: string }\n\nconst DEFAULT_CARD_ELEMENT_CONFIG = {\n showIcon: true,\n iconStyle: 'solid' as const,\n placeholders: {\n cardNumber: '1234 1234 1234 1234',\n cardExpiry: 'MM / YY - TESTING',\n cardCvc: 'CVC',\n },\n style: {\n base: {\n color: '#333333',\n fontFamily: 'system-ui, -apple-system, sans-serif',\n fontSize: '16px',\n '::placeholder': { color: '#aab7c4' },\n },\n complete: {\n color: '#333333',\n },\n empty: {},\n invalid: {\n color: '#df1b41',\n },\n },\n}\n\nconst FIELD_LABELS: Record<string, string> = {\n cardNumber: 'Card number',\n cardExpiry: 'Expiry date',\n cardCvc: 'CVC',\n address: 'Address',\n}\n\nexport class ElementsManager {\n private elements: StripeElements | null = null;\n private mountedElements: Map<string, StripeElement> = new Map();\n private elementStates: Map<string, ElementState> = new Map();\n\n constructor(\n private stripe: Stripe,\n private config: VerapayConfig,\n private clientSecret: string,\n ) {\n if (!clientSecret) {\n throw new VerapayError(\n 'Client secret not initialized',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n }\n\n\n mountPaymentElement(selector: string): void {\n if (!this.elements) {\n const elementsConfig = {\n clientSecret: this.clientSecret,\n appearance: this.config.appearance,\n locale: this.config.locale,\n fonts: this.config.fonts,\n paymentMethodCreation: 'manual',\n };\n\n this.elements = this.stripe.elements(elementsConfig);\n }\n\n const container = document.querySelector(selector);\n\n if (!container) {\n throw new VerapayError(\n `Element not found: ${selector}`,\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const element = this.elements.create('payment', {\n layout: 'tabs',\n wallets: { link: 'never' } as unknown as PaymentWalletsOption,\n }) as StripePaymentElement;\n\n element.mount(selector);\n this.mountedElements.set('payment', element);\n }\n\n mountCardNumberElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardNumber', this.cardElementOptions('cardNumber'));\n }\n\n mountCardExpiryElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardExpiry', this.cardElementOptions('cardExpiry'));\n }\n\n mountCardCvcElement(selector: string): void {\n this.mountIndividualFormElement(selector, 'cardCvc', this.cardElementOptions('cardCvc'));\n }\n\n mountAddressElement(selector: string, mode: 'billing' | 'shipping'): void {\n this.mountIndividualFormElement(selector, 'address', { mode });\n }\n\n private cardElementOptions(fieldType: 'cardNumber' | 'cardExpiry' | 'cardCvc'): Record<string, unknown> {\n const { elementsConfig } = this.config;\n const options: Record<string, unknown> = {\n placeholder: elementsConfig?.placeholders?.[fieldType] ?? DEFAULT_CARD_ELEMENT_CONFIG.placeholders[fieldType],\n style: {\n base: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.base, ...elementsConfig?.style?.base },\n complete: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.complete, ...elementsConfig?.style?.complete },\n empty: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.empty, ...elementsConfig?.style?.empty },\n invalid: { ...DEFAULT_CARD_ELEMENT_CONFIG.style.invalid, ...elementsConfig?.style?.invalid },\n },\n };\n\n if (fieldType === 'cardNumber') {\n options.showIcon = elementsConfig?.showIcon ?? DEFAULT_CARD_ELEMENT_CONFIG.showIcon;\n options.iconStyle = elementsConfig?.iconStyle ?? DEFAULT_CARD_ELEMENT_CONFIG.iconStyle;\n }\n\n return options;\n }\n\n private mountIndividualFormElement(selector: string, formFieldType: 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'address', options?: Record<string, unknown>) {\n const container = document.querySelector(selector);\n\n if (!container) {\n throw new VerapayError(\n `Element not found: ${selector}`,\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const element = this.createIndividualFormElement(formFieldType, options) as StripeCardNumberElement;\n element.mount(selector);\n\n this.mountedElements.set(formFieldType, element);\n this.trackElementState(formFieldType, element);\n }\n\n private createIndividualFormElement(\n elementType: 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'address',\n options?: Record<string, unknown>,\n ): StripeElement {\n if (!this.elements) {\n this.elements = this.stripe.elements({\n appearance: this.config.appearance,\n locale: this.config.locale,\n fonts: this.config.fonts,\n paymentMethodCreation: 'manual',\n });\n }\n\n return this.elements.create(elementType as 'cardNumber', options);\n }\n\n\n\n async validate(): Promise<ValidationResult> {\n const errors: ValidationError[] = []\n\n for (const [field, state] of this.elementStates.entries()) {\n if (!state.complete) {\n errors.push({\n field,\n message: state.error ?? `${FIELD_LABELS[field] ?? field} failed validation`,\n })\n }\n }\n\n return { isValid: errors.length === 0, errors }\n }\n\n getElements(): StripeElements | null {\n return this.elements;\n }\n\n unmountAll(): void {\n for (const element of this.mountedElements.values()) {\n element.unmount();\n }\n this.mountedElements.clear();\n this.elementStates.clear();\n }\n\n private trackElementState(field: string, element: StripeElement): void {\n this.elementStates.set(field, { complete: false })\n\n const handleElementChange = (event: { complete: boolean; error?: { message: string } }) => {\n this.elementStates.set(field, { complete: event.complete, error: event.error?.message })\n };\n\n (element as unknown as { on: (event: string, handler: (e: unknown) => void) => void }).on(\n 'change',\n handleElementChange as (e: unknown) => void,\n );\n }\n}\n\n\n","import type { ProcessPaymentRequest, PaymentResult } from '../types'\nimport type { PaymentExtension } from '../extensions'\n\nexport class PaymentExtensionsManager {\n private extensions: PaymentExtension[] = []\n\n add(extension: PaymentExtension): void {\n this.extensions.push(extension)\n }\n\n async runBeforePayment(request: ProcessPaymentRequest): Promise<ProcessPaymentRequest> {\n let modifiedRequest = request\n for (const ext of this.extensions) {\n if (ext.beforePayment) {\n modifiedRequest = await ext.beforePayment(modifiedRequest)\n }\n }\n return modifiedRequest\n }\n\n async runAfterPayment(result: PaymentResult): Promise<void> {\n await Promise.all(\n this.extensions\n .filter((ext) => ext.afterPayment)\n .map((ext) => ext.afterPayment!(result)),\n )\n }\n\n async runOnError(error: Error): Promise<void> {\n await Promise.all(\n this.extensions\n .filter((ext) => ext.onPaymentError)\n .map((ext) => ext.onPaymentError!(error)),\n )\n }\n}\n","import { StripeAdapter } from '../client/stripe-adapter'\nimport { ElementsManager } from '../client/elements-manager'\nimport { ErrorCode, VerapayError } from '../errors'\nimport { VerapayService } from './verapay-service'\nimport type { ProcessPaymentRequest, PaymentResult } from '../types'\nimport { StripeElements } from '@stripe/stripe-js';\n\nexport interface ProcessPaymentContext {\n merchantId: string\n paymentIntentId: string\n clientSecret: string\n amount: number\n currency: string\n isUsingStripePaymentElement: boolean\n isUsingIndividualFormElements: boolean\n}\n\nexport class PaymentService {\n constructor(\n private stripeAdapter: StripeAdapter,\n private elementsManager: ElementsManager,\n private verapayService: VerapayService,\n ) {}\n\n async process(request: ProcessPaymentRequest, context: ProcessPaymentContext): Promise<PaymentResult> {\n const elements = this.elementsManager.getElements()\n\n await this.validatePaymentCanProceed(elements, context);\n\n await elements!.submit()\n\n const paymentMethodId = await this.stripeAdapter.createPaymentMethod(\n elements!,\n context.isUsingIndividualFormElements,\n )\n\n await this.verapayService.processPrePayment({\n merchantId: context.merchantId,\n paymentIntentId: context.paymentIntentId,\n paymentMethodId,\n amount: context.amount,\n currency: context.currency,\n customerData: {\n email: request.customerEmail,\n firstName: request.customerFirstName,\n lastName: request.customerLastName,\n },\n description: request.description,\n metadata: request.metadata,\n })\n\n return this.confirm(context.clientSecret, {\n paymentMethodId,\n isUsingStripePaymentElement: context.isUsingStripePaymentElement,\n isUsingIndividualFormElements: context.isUsingIndividualFormElements,\n });\n }\n\n private async validatePaymentCanProceed(\n elements: StripeElements | null,\n context: ProcessPaymentContext,\n ) {\n if (!elements) {\n throw new VerapayError('Payment form not mounted', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingStripePaymentElement && context.isUsingIndividualFormElements) {\n throw new VerapayError('Both forms of payment form in use');\n }\n\n if (context.isUsingIndividualFormElements) {\n const validation = await this.elementsManager.validate();\n if (!validation.isValid) {\n throw new VerapayError(validation.errors[0].message, ErrorCode.VALIDATION_ERROR);\n }\n }\n }\n\n async confirm(\n clientSecret: string,\n options: {\n isUsingStripePaymentElement?: boolean;\n isUsingIndividualFormElements?: boolean;\n paymentMethodId?: string;\n } = {},\n ): Promise<PaymentResult> {\n let result;\n\n if (options.isUsingStripePaymentElement) {\n result = await this.stripeAdapter.confirmPayment(options.paymentMethodId || '', clientSecret);\n } else if (options.isUsingIndividualFormElements) {\n result = await this.stripeAdapter.confirmCardPayment(\n options.paymentMethodId || '',\n clientSecret,\n );\n } else {\n result = await this.stripeAdapter.confirmPayment(options.paymentMethodId || '', clientSecret);\n }\n\n return this.formatPaymentResult(result);\n }\n\n async retrievePaymentIntent(clientSecret: string): Promise<PaymentResult> {\n const result = await this.stripeAdapter.retrievePaymentIntent(clientSecret);\n return this.formatPaymentResult(result);\n }\n\n private formatPaymentResult(result: unknown): PaymentResult {\n const paymentIntent = (result as { paymentIntent: { status: string; id: string } })\n .paymentIntent\n\n let status: 'succeeded' | 'processing' | 'failed' = 'failed'\n if (paymentIntent.status === 'succeeded') {\n status = 'succeeded'\n } else if (\n ['processing', 'requires_action', 'requires_confirmation'].includes(\n paymentIntent.status,\n )\n ) {\n status = 'processing'\n }\n\n return {\n success: paymentIntent.status === 'succeeded',\n paymentIntentId: paymentIntent.id,\n status,\n }\n }\n\n}\n\n\n","import { StripeAdapter } from '../client/stripe-adapter';\nimport { ElementsManager } from '../client/elements-manager';\nimport { ErrorCode, VerapayError } from '../errors';\nimport type { SetupResult } from '../types';\nimport { StripeElements } from '@stripe/stripe-js';\n\nexport interface SaveCardContext {\n isUsingStripePaymentElement: boolean;\n isUsingIndividualFormElements: boolean;\n}\n\nexport class SetupService {\n constructor(\n private stripeAdapter: StripeAdapter,\n private elementsManager: ElementsManager,\n ) {}\n\n async save(clientSecret: string, context: SaveCardContext): Promise<SetupResult> {\n const elements = this.elementsManager.getElements();\n\n await this.validateSetupCanProceed(elements, context);\n\n await elements!.submit();\n\n const paymentMethodId = await this.stripeAdapter.createPaymentMethod(\n elements!,\n context.isUsingIndividualFormElements,\n );\n\n const result = await this.stripeAdapter.confirmCardSetup(paymentMethodId, clientSecret);\n\n return this.formatSetupResult(result);\n }\n\n async retrieve(clientSecret: string): Promise<SetupResult> {\n const result = await this.stripeAdapter.retrieveSetupIntent(clientSecret);\n return this.formatSetupResult(result);\n }\n\n private async validateSetupCanProceed(\n elements: StripeElements | null,\n context: SaveCardContext,\n ): Promise<void> {\n if (!elements) {\n throw new VerapayError('Card form not mounted', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingStripePaymentElement && context.isUsingIndividualFormElements) {\n throw new VerapayError('Both forms of card form in use', ErrorCode.CONFIGURATION_ERROR);\n }\n\n if (context.isUsingIndividualFormElements) {\n const validation = await this.elementsManager.validate();\n if (!validation.isValid) {\n throw new VerapayError(validation.errors[0].message, ErrorCode.VALIDATION_ERROR);\n }\n }\n }\n\n private formatSetupResult(result: unknown): SetupResult {\n const setupIntent = (\n result as { setupIntent: { status: string; id: string; payment_method?: unknown } }\n ).setupIntent;\n\n let status: SetupResult['status'] = 'failed';\n if (setupIntent.status === 'succeeded') {\n status = 'succeeded';\n } else if (setupIntent.status === 'processing') {\n status = 'processing';\n } else if (\n setupIntent.status === 'requires_action' ||\n setupIntent.status === 'requires_confirmation'\n ) {\n status = 'requires_action';\n }\n\n const paymentMethod = setupIntent.payment_method;\n const savedPaymentMethodId =\n typeof paymentMethod === 'string'\n ? paymentMethod\n : (paymentMethod as { id?: string } | undefined)?.id;\n\n return {\n success: setupIntent.status === 'succeeded',\n savedPaymentMethodId,\n setupIntentId: setupIntent.id,\n status,\n };\n }\n}\n","import { ErrorCode, VerapayError } from '../errors';\nimport { PaymentData } from '../types';\n\nexport interface InitialisePaymentRequest {\n merchantId: string;\n paymentData: PaymentData;\n}\n\nexport interface InitialisePaymentResponse {\n paymentIntentId: string;\n clientSecret: string;\n connectAccountId: string;\n stripePublishableKey: string;\n}\n\nexport interface ProcessPrePaymentRequest {\n merchantId: string;\n paymentIntentId: string;\n paymentMethodId: string;\n amount: number;\n currency: string;\n customerData: Record<string, unknown>;\n\n description?: string;\n metadata?: Record<string, string>;\n}\n\nexport class VerapayService {\n private readonly baseUrl: string;\n private apiKey?: string;\n\n constructor(baseUrl: string, apiKey?: string) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n }\n\n setApiKey(apiKey: string): void {\n this.apiKey = apiKey;\n }\n\n\n async getPaymentIntentConfig(clientSecret: string): Promise<Record<string, unknown>> {\n\n try {\n const response = await fetch(\n `${this.baseUrl}/v1/payment_intents/config?client_secret=${encodeURIComponent(\n clientSecret,\n )}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n );\n\n if (!response.ok) {\n throw new VerapayError('Failed to fetch provider config', ErrorCode.CONFIGURATION_ERROR);\n }\n\n return response.json();\n } catch (error) {\n if (error instanceof VerapayError) throw error;\n throw new VerapayError('Error connecting to Verapay API', ErrorCode.NETWORK_ERROR);\n }\n }\n\n async getSetupIntentConfig(clientSecret: string): Promise<Record<string, unknown>> {\n try {\n const response = await fetch(\n `${this.baseUrl}/v1/setup_intents/config?client_secret=${encodeURIComponent(\n clientSecret,\n )}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n );\n\n if (!response.ok) {\n throw new VerapayError('Failed to fetch setup config', ErrorCode.CONFIGURATION_ERROR);\n }\n\n return response.json();\n } catch (error) {\n if (error instanceof VerapayError) throw error;\n throw new VerapayError('Error connecting to Verapay API', ErrorCode.NETWORK_ERROR);\n }\n }\n\n\n async initialisePayment(\n request: InitialisePaymentRequest\n ): Promise<InitialisePaymentResponse> {\n const { merchantId, paymentData } = request;\n\n try {\n const response = await fetch(`${this.baseUrl}/api/initialise-payment`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n\n body: JSON.stringify({\n merchantId,\n paymentData: { ...paymentData, paymentMethodType: 'card' },\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new VerapayError(\n this.extractErrorMessage(errorData, response.status),\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n const data = await response.json();\n\n if (!data.clientSecret || !data.paymentIntentId) {\n throw new VerapayError(\n 'Missing clientSecret or paymentIntentId in server response',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n return {\n paymentIntentId: data.paymentIntentId,\n clientSecret: data.clientSecret,\n connectAccountId: data.connectAccountId,\n stripePublishableKey: data.stripePublishableKey,\n };\n } catch (error) {\n if (error instanceof VerapayError) {\n throw error;\n }\n throw new VerapayError(\n error instanceof Error ? error.message : 'Unknown error occurred',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n }\n\n async processPrePayment(request: ProcessPrePaymentRequest): Promise<void> {\n try {\n const response = await fetch(`${this.baseUrl}/api/process-prepayment`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n\n body: JSON.stringify({\n merchantId: request.merchantId,\n paymentIntentId: request.paymentIntentId,\n paymentMethodId: request.paymentMethodId,\n amount: request.amount,\n currency: request.currency,\n customerData: request.customerData,\n description: request.description,\n metadata: request.metadata,\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new VerapayError(\n this.extractErrorMessage(errorData, response.status),\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n } catch (error) {\n if (error instanceof VerapayError) {\n throw error;\n }\n throw new VerapayError(\n error instanceof Error ? error.message : 'Unknown error occurred',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n }\n\n private extractErrorMessage(errorData: unknown, status: number): string {\n if (!errorData || typeof errorData !== 'object') {\n return `HTTP error! status: ${status}`;\n }\n\n const record = errorData as Record<string, unknown>;\n const candidates = [record.error, record.message, record.details];\n\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate;\n }\n\n if (candidate && typeof candidate === 'object') {\n try {\n return JSON.stringify(candidate);\n } catch {\n // Ignore serialization issues and continue trying fallback messages.\n }\n }\n }\n\n return `HTTP error! status: ${status}`;\n }\n}\n","export function unwrapClientSecret(wrappedSecret: string): string {\n if (wrappedSecret.startsWith('vpy_cs_test_')) {\n return wrappedSecret.replace('vpy_cs_test_', '');\n }\n if (wrappedSecret.startsWith('vpy_cs_live_')) {\n return wrappedSecret.replace('vpy_cs_live_', '');\n }\n return wrappedSecret;\n}\n","import { loadStripe } from '@stripe/stripe-js';\nimport { Money } from 'ts-money';\nimport { StripeAdapter } from './stripe-adapter';\nimport { ElementsManager } from './elements-manager';\nimport type { PaymentExtension } from '../extensions';\nimport { PaymentExtensionsManager } from './payment-extensions-manager';\nimport { PaymentService } from '../services/payment-service';\nimport { SetupService } from '../services/setup-service';\nimport {\n ErrorCode,\n VerapayError,\n PaymentError,\n ValidationError,\n} from '../errors';\nimport { VerapayService } from '../services/verapay-service';\nimport { unwrapClientSecret } from '../utils/secret.util';\nimport type {\n VerapayConfig,\n ProcessPaymentRequest,\n PaymentResult,\n SetupResult,\n} from '../types';\n\ntype IntentKind = 'payment' | 'setup';\n\nexport class VerapayClient {\n private static readonly BACKEND_URL = 'https://api.verapay.app';\n\n private config: VerapayConfig;\n private verapayService: VerapayService;\n private extensionsManager: PaymentExtensionsManager;\n\n private stripeAdapter: StripeAdapter | null = null;\n private elementsManager: ElementsManager | null = null;\n private paymentService: PaymentService | null = null;\n private setupService: SetupService | null = null;\n private initializationPromise: Promise<void> | null = null;\n\n private isUsingStripePaymentElement: boolean = false;\n private isUsingIndividualFormElements: boolean = false;\n\n private intentKind: IntentKind = 'payment';\n private rawSecret: string | null = null;\n private paymentIntentId: string | null = null;\n private amount: number | null = null;\n private currency: string | null = null;\n private merchantId: string | null = null;\n\n constructor(config: VerapayConfig) {\n if (!config.apiKey && !config.clientSecret) {\n throw new VerapayError(\n 'Either apiKey or clientSecret is required.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n if (config.apiKey && config.clientSecret) {\n throw new VerapayError(\n 'Cannot provide both apiKey and clientSecret. Use apiKey for frontend-initialized flows or clientSecret for backend-initialized flows.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n if (config.apiKey && !config.apiKey.includes(\"_pk_\") && typeof window !== \"undefined\") {\n console.warn(\n \"Verapay Security Warning: You are using a Secret Key in a frontend environment. Please use a Publishable Key (vpy_pk_...) instead.\"\n );\n }\n\n this.config = config;\n\n const backendUrl = this.config.apiUrlOverride || VerapayClient.BACKEND_URL;\n\n this.verapayService = new VerapayService(backendUrl, this.config.apiKey || '');\n this.extensionsManager = new PaymentExtensionsManager();\n }\n\n async initialize(): Promise<void> {\n if (this.initializationPromise) {\n return this.initializationPromise;\n }\n\n this.initializationPromise = (async () => {\n let clientSecret: string;\n let paymentIntentId: string;\n let stripePublishableKey: string;\n\n\n if (this.config.clientSecret) {\n this.intentKind = unwrapClientSecret(this.config.clientSecret).startsWith('seti_')\n ? 'setup'\n : 'payment';\n\n if (this.intentKind === 'setup') {\n const config = (await this.verapayService.getSetupIntentConfig(\n this.config.clientSecret,\n )) as Record<string, any>;\n\n if (config.object !== 'setup_intent_config') {\n throw new VerapayError(\n 'Unexpected configuration returned for setup intent',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n clientSecret = this.config.clientSecret;\n paymentIntentId = '';\n stripePublishableKey = config.publishableKey;\n this.merchantId = config.merchantId;\n\n if (config.verapayPublishableKey) {\n this.verapayService.setApiKey(config.verapayPublishableKey);\n }\n } else {\n const config = (await this.verapayService.getPaymentIntentConfig(\n this.config.clientSecret,\n )) as Record<string, any>;\n clientSecret = this.config.clientSecret;\n paymentIntentId = config.paymentIntentId;\n stripePublishableKey = config.publishableKey;\n this.amount = config.amount;\n this.currency = config.currency;\n this.merchantId = config.merchantId;\n\n if (config.verapayPublishableKey) {\n this.verapayService.setApiKey(config.verapayPublishableKey);\n }\n }\n } else {\n this.validatePaymentInitialisation();\n\n const response = await this.verapayService.initialisePayment({\n merchantId: this.config.merchantId ?? '',\n paymentData: this.config.paymentData!,\n });\n clientSecret = response.clientSecret;\n paymentIntentId = response.paymentIntentId;\n stripePublishableKey = response.stripePublishableKey;\n this.amount = this.config.paymentData!.amount;\n this.currency = this.config.paymentData!.currency;\n this.merchantId = this.config.merchantId ?? '';\n }\n\n this.rawSecret = unwrapClientSecret(clientSecret);\n this.paymentIntentId = paymentIntentId;\n\n const stripe = await loadStripe(stripePublishableKey);\n\n if (!stripe) {\n throw new VerapayError(\n 'Failed to load Stripe',\n ErrorCode.CONFIGURATION_ERROR\n );\n }\n\n this.stripeAdapter = new StripeAdapter(stripe);\n this.elementsManager = new ElementsManager(stripe, this.config, this.rawSecret!);\n this.paymentService = new PaymentService(\n this.stripeAdapter,\n this.elementsManager,\n this.verapayService,\n );\n this.setupService = new SetupService(this.stripeAdapter, this.elementsManager);\n })().catch((error) => {\n this.initializationPromise = null;\n throw error;\n });\n\n return this.initializationPromise;\n }\n\n async confirmPayment(): Promise<PaymentResult> {\n await this.ensureInitialized();\n this.assertIntentKind('payment', 'confirmPayment');\n return this.paymentService!.confirm(this.rawSecret!, {\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n }\n\n async saveCard(): Promise<SetupResult> {\n await this.ensureInitialized();\n this.assertIntentKind('setup', 'saveCard');\n try {\n return await this.setupService!.save(this.rawSecret!, {\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n } catch (error) {\n throw this.handlePaymentError(error);\n }\n }\n\n async retrieveSetupIntent(): Promise<SetupResult> {\n await this.ensureInitialized();\n this.assertIntentKind('setup', 'retrieveSetupIntent');\n return this.setupService!.retrieve(this.rawSecret!);\n }\n\n teardown(): void {\n this.elementsManager?.unmountAll();\n this.stripeAdapter = null;\n this.elementsManager = null;\n this.paymentService = null;\n this.setupService = null;\n this.initializationPromise = null;\n this.isUsingStripePaymentElement = false;\n this.isUsingIndividualFormElements = false;\n this.intentKind = 'payment';\n this.rawSecret = null;\n this.paymentIntentId = null;\n this.amount = null;\n this.currency = null;\n this.merchantId = null;\n }\n\n async retrievePaymentIntent(): Promise<PaymentResult> {\n await this.ensureInitialized();\n return this.paymentService!.retrievePaymentIntent(this.rawSecret!);\n }\n\n async processPayment(request: ProcessPaymentRequest): Promise<PaymentResult> {\n await this.ensureInitialized();\n this.assertIntentKind('payment', 'processPayment');\n\n const modifiedRequest =\n await this.extensionsManager.runBeforePayment(request);\n\n try {\n const paymentResult = await this.paymentService!.process(modifiedRequest, {\n merchantId: this.merchantId!,\n paymentIntentId: this.paymentIntentId!,\n clientSecret: this.rawSecret!,\n amount: this.amount!,\n currency: this.currency!,\n isUsingStripePaymentElement: this.isUsingStripePaymentElement,\n isUsingIndividualFormElements: this.isUsingIndividualFormElements,\n });\n\n\n await this.extensionsManager.runAfterPayment(paymentResult);\n\n return paymentResult;\n } catch (error) {\n await this.extensionsManager.runOnError(error as Error);\n throw this.handlePaymentError(error);\n }\n }\n\n async mountPaymentForm(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountPaymentElement(selector);\n this.isUsingStripePaymentElement = true;\n }\n\n async mountCardNumber(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardNumberElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountCardExpiry(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardExpiryElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountCardCvc(selector: string): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountCardCvcElement(selector);\n this.isUsingIndividualFormElements = true;\n }\n\n async mountAddress(\n selector: string,\n mode: 'billing' | 'shipping'\n ): Promise<void> {\n await this.ensureInitialized();\n this.elementsManager!.mountAddressElement(selector, mode);\n this.isUsingIndividualFormElements = true;\n }\n\n addExtension(extension: PaymentExtension): void {\n this.extensionsManager.add(extension);\n }\n\n private async ensureInitialized(): Promise<void> {\n if (!this.stripeAdapter) {\n await this.initialize();\n }\n }\n\n private assertIntentKind(expected: IntentKind, method: string): void {\n if (this.intentKind !== expected) {\n throw new VerapayError(\n `${method} requires a ${expected} intent client secret`,\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n }\n\n private validatePaymentInitialisation(): void {\n if (!this.config.paymentData) {\n throw new VerapayError(\n 'paymentData is required for frontend-initialized flows.',\n ErrorCode.CONFIGURATION_ERROR,\n );\n }\n\n const { amount, currency, platformFee } = this.config.paymentData;\n\n\n if (!currency) {\n throw new ValidationError('Currency is required', 'currency');\n }\n\n const uppercaseCurrency = currency.toUpperCase();\n\n const paymentAmount = this.toMoney(amount, uppercaseCurrency, 'amount');\n\n if (paymentAmount.isZero() || paymentAmount.isNegative()) {\n throw new ValidationError('Amount must be greater than 0', 'amount');\n }\n\n if (platformFee !== undefined) {\n const platformFeeAmount = this.toMoney(platformFee, uppercaseCurrency, 'platformFee');\n\n if (platformFeeAmount.isNegative()) {\n throw new ValidationError('platformFee cannot be negative', 'platformFee');\n }\n\n if (platformFeeAmount.greaterThan(paymentAmount)) {\n throw new ValidationError('platformFee cannot exceed the payment amount', 'platformFee');\n }\n }\n }\n\n private toMoney(value: number, currency: string, fieldName: string): Money {\n try {\n return Money.fromInteger(value, currency);\n } catch {\n throw new ValidationError(\n `${fieldName} must be an integer in the smallest currency unit (e.g., cents for USD)`,\n fieldName\n );\n }\n }\n\n\n private handlePaymentError(error: unknown): Error {\n if (error instanceof VerapayError) {\n return error;\n }\n const message = error instanceof Error ? error.message : 'Payment failed';\n const code = (error as Record<string, unknown>)?.code as string | undefined;\n\n return new PaymentError(message, code);\n }\n}\n\n","import type { CardValidation } from '../types';\n\nexport class CardValidator {\n validateCardNumber(cardNumber: string): boolean {\n const cleaned = cardNumber.replace(/\\D/g, '');\n\n if (cleaned.length < 13 || cleaned.length > 19) {\n return false;\n }\n\n let sum = 0;\n let isEven = false;\n\n for (let i = cleaned.length - 1; i >= 0; i--) {\n let digit = parseInt(cleaned[i], 10);\n\n if (isEven) {\n digit *= 2;\n if (digit > 9) {\n digit -= 9;\n }\n }\n\n sum += digit;\n isEven = !isEven;\n }\n\n return sum % 10 === 0;\n }\n\n detectCardType(cardNumber: string): string {\n const cleaned = cardNumber.replace(/\\D/g, '');\n\n if (/^4/.test(cleaned)) return 'visa';\n if (/^5[1-5]/.test(cleaned)) return 'mastercard';\n if (/^3[47]/.test(cleaned)) return 'amex';\n if (/^6(?:011|5)/.test(cleaned)) return 'discover';\n\n return 'unknown';\n }\n\n validateExpiry(month: number, year: number): boolean {\n const now = new Date();\n const currentYear = now.getFullYear();\n const currentMonth = now.getMonth() + 1;\n\n if (month < 1 || month > 12) {\n return false;\n }\n\n const fullYear = year < 100 ? 2000 + year : year;\n\n if (fullYear < currentYear) {\n return false;\n }\n\n if (fullYear === currentYear && month < currentMonth) {\n return false;\n }\n\n return true;\n }\n\n validateCVC(cvc: string, cardType: string = 'unknown'): boolean {\n const cleaned = cvc.replace(/\\D/g, '');\n\n if (cardType === 'amex') {\n return cleaned.length === 4;\n }\n\n return cleaned.length === 3 || cleaned.length === 4;\n }\n\n validateAll(\n cardNumber: string,\n expiryMonth: number,\n expiryYear: number,\n cvc: string\n ): CardValidation {\n const cardType = this.detectCardType(cardNumber);\n\n return {\n number: {\n isValid: this.validateCardNumber(cardNumber),\n cardType: cardType as 'visa' | 'mastercard' | 'amex' | 'discover' | 'unknown',\n\n },\n expiry: {\n isValid: this.validateExpiry(expiryMonth, expiryYear),\n month: expiryMonth,\n year: expiryYear,\n },\n cvc: {\n isValid: this.validateCVC(cvc, cardType),\n length: cvc.replace(/\\D/g, '').length,\n },\n };\n }\n}\n","export class InputSanitizer {\n static sanitizeCardNumber(input: string): string {\n return input.replace(/\\D/g, '');\n }\n\n static formatCardNumber(input: string): string {\n const cleaned = this.sanitizeCardNumber(input);\n return cleaned.replace(/(\\d{4})/g, '$1 ').trim();\n }\n\n static sanitizeCVC(input: string): string {\n return input.replace(/\\D/g, '').slice(0, 4);\n }\n\n static sanitizeExpiry(input: string): { month: number; year: number } | null {\n const cleaned = input.replace(/\\D/g, '');\n\n if (cleaned.length === 4) {\n return {\n month: parseInt(cleaned.slice(0, 2), 10),\n year: parseInt(cleaned.slice(2, 4), 10),\n };\n } else if (cleaned.length === 6) {\n return {\n month: parseInt(cleaned.slice(0, 2), 10),\n year: parseInt(cleaned.slice(2, 6), 10),\n };\n }\n\n return null;\n }\n}\n","export { VerapayClient } from './client/verapay-client';\nexport { VerapayService } from './services/verapay-service';\n\nexport type {\n InitialisePaymentRequest,\n InitialisePaymentResponse,\n ProcessPrePaymentRequest,\n} from './services/verapay-service';\n\nexport type {\n VerapayConfig,\n ElementsConfig,\n ProcessPaymentRequest,\n PaymentResult,\n SetupResult,\n CardValidation,\n ErrorDetails,\n ErrorCode,\n} from './types';\n\nexport {\n VerapayError,\n ValidationError,\n PaymentError,\n ErrorFormatter,\n} from './errors';\n\nexport { CardValidator, InputSanitizer } from './validation';\n\nexport type {\n PaymentExtension,\n DatabaseExtension,\n AnalyticsExtension,\n} from './extensions';\n\nexport const VERSION = '1.4.0';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verapay/verapay-js",
3
- "version": "1.5.0",
3
+ "version": "2.0.0",
4
4
  "description": "Simple TypeScript SDK for Stripe payment processing",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",