@alviere/core 0.16.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("node-forge");class t{constructor(e){this.logger="CORE_LOGGER",this.isDebug=e}debug(e){this.isDebug&&console.debug}warning(e){this.isDebug&&console.warn}warn(e){this.warning(e)}info(e){this.isDebug&&console.info}error(e){this.isDebug&&console.error}isDebugEnabled(){return this.isDebug}}const r={domain:"https://api.dev.alviere.com",access_token:"",certificate:{id:"",public_key:""}};let s={...r};function n(e){s={...s,...e}}function a(e){if("undefined"!=typeof window&&window.VITE_DEBUG){return window[`VITE_${e}`]}}function i(){if(s.domain&&s.certificate)return;const e={},t=a("ALVIERE_DOMAIN"),r=a("CERTIFICATE");if(t&&(e.domain=t),r)try{const t=JSON.parse(r);t&&"string"==typeof t.id&&"string"==typeof t.public_key&&(e.certificate={id:t.id,public_key:t.public_key})}catch{}(e.domain||e.certificate)&&n(e)}const o=()=>(s.domain||i(),s.domain),c=()=>(s.certificate||i(),s.certificate.public_key.replace(/\\n/g,"").replace(/\r\n/g,"").replace(/\n/g,"").replace(/\r/g,"").trim()),u=()=>(s.certificate||i(),s.certificate.id),d=o(),l=c(),g=u();class h{constructor(e){this.logger=e,this.rsa_key=c(),this.key=this.generate_key(),this.nonce=this.generate_nonce(),this.logger?.debug("🔐 Cryptor initialized")}async encrypt(t){const r=(new TextEncoder).encode(JSON.stringify(t)),s={name:"AES-GCM",iv:this.nonce},n=await this.import_key(),a=await crypto.subtle.encrypt(s,n,r),i=this.bufferToStr(a),o=btoa(i),c=this.bufferToStr(this.key),d=btoa(c),l=this.bufferToStr(this.nonce),g=btoa(l);this.logger?.debug(`🔐 RSA_KEY: ${this.rsa_key.substring(0,50)}...`);const h=e.pki.publicKeyFromPem(this.rsa_key).encrypt(d+"::"+g),p={p:o,k:btoa(h),i:u()};return this.logger?.debug(`🔐 ENCRYPTED_REQUEST: p=${p.p.substring(0,20)}..., i=${p.i}`),p}async decrypt(e){const t=await crypto.subtle.decrypt({name:"AES-GCM",iv:this.nonce},await this.import_key(),Uint8Array.from(atob(e.p),e=>e.charCodeAt(0))),r=(new TextDecoder).decode(t);return this.logger?.debug(`🔐 DECRYPTED: ${r}`),JSON.parse(r)}generate_key(){return crypto.getRandomValues(new Uint8Array(32))}generate_nonce(){return crypto.getRandomValues(new Uint8Array(12))}async import_key(){return await crypto.subtle.importKey("raw",this.key,{name:"AES-GCM"},!0,["encrypt","decrypt"])}async rsa_encrypt(t){this.logger?.debug(`🔐 RSA_ENCRYPT: Data to encrypt: ${t.substring(0,50)}...`),this.logger?.debug(`🔐 RSA_KEY: ${this.rsa_key.substring(0,50)}...`);const r=e.pki.publicKeyFromPem(this.rsa_key);return btoa(r.encrypt(t))}bufferToStr(e){return Array.from(new Uint8Array(e)).map(e=>String.fromCharCode(e)).join("")}}class p{constructor(e){this.logger=e}credit_card_name(e){return this.logger.debug(`🔐 CREDIT_CARD_NAME: ${e}`),e&&"string"==typeof e?0===e.trim().length?"Card holder name cannot be empty.":null:"Card holder name cannot be empty."}credit_card_number(e){if(!e||"string"!=typeof e)return"Please enter a valid card number.";return/^(?:4[0-9]{12}(?:[0-9]{3})?)$/.test(e.replace(/\s/g,""))||/^(?:5[1-5][0-9]{14})$/.test(e.replace(/\s/g,""))||/^(?:3[47][0-9]{13})$/.test(e.replace(/\s/g,""))||/^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/.test(e.replace(/\s/g,""))?null:(this.logger.debug("🔐 card number is not a recognized brand"),"Please enter a valid card number.")}credit_card_expiry_date(e){if(!e||"string"!=typeof e)return"Expiry date cannot be empty.";if(0===e.trim().length)return"Expiry date cannot be empty.";return/^(0[1-9]|1[0-2])\/?([0-9]{4}|[0-9]{2})$/.test(e)?null:"Please enter a valid expiry date."}credit_card_sec_code(e){if(!e||"string"!=typeof e)return"Security code cannot be empty.";if(0===e.trim().length)return"Security code cannot be empty.";return/^[0-9]{3,4}$/.test(e)?null:"Please enter a valid security code."}credit_card_zip_code(e){return e&&"string"==typeof e?0===e.trim().length?"Zip code cannot be empty.":null:"Zip code cannot be empty."}credit_card_pin(e){if(!e||"string"!=typeof e)return"PIN cannot be empty.";if(0===e.trim().length)return"PIN cannot be empty.";return/^[0-9]{4}$/.test(e)?null:"Please enter a valid PIN."}is_valid_uuid(e){if(!e||"string"!=typeof e)return"UUID cannot be empty.";if(0===e.trim().length)return"UUID cannot be empty.";return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)?null:"Please enter a valid UUID."}required(e,t){return null==e||"string"==typeof e&&0===e.trim().length?t?`${t} is required.`:"This field is required.":null}email(e){if(!e||"string"!=typeof e)return"Please enter a valid email address.";const t=e.trim();if(t.includes(".."))return"Please enter a valid email address.";return/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/.test(t)?null:"Please enter a valid email address."}phone(e){if(!e||"string"!=typeof e)return"Please enter a valid phone number.";return/^\+[1-9]\d{1,14}$/.test(e.trim())?null:"Please enter a valid phone number."}date(e,t="YYYY-MM-DD"){if(!e||"string"!=typeof e)return"Please enter a valid date.";const r=/^([0-9]{4})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/;if(!r.test(e))return"Please enter a valid date in YYYY-MM-DD format";const[,s,n,a]=e.match(r)||[],i=parseInt(s),o=parseInt(n),c=parseInt(a);if(!this.isValidCalendarDate(i,o,c))return"Invalid date - this date does not exist";const u=new Date(e);return u>new Date?"Date cannot be in the future":u<new Date("1900-01-01")?"Date cannot be before 1900":null}isValidCalendarDate(e,t,r){const s=new Date(e,t-1,r);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===r}min_length(e,t,r){return e&&"string"==typeof e?e.length<t?r?`${r} must be at least ${t} characters long.`:`Must be at least ${t} characters long.`:null:r?`${r} is required.`:"This field is required."}max_length(e,t,r){return e&&"string"==typeof e&&e.length>t?r?`${r} must be no more than ${t} characters long.`:`Must be no more than ${t} characters long.`:null}pattern(e,t,r){return e&&"string"==typeof e&&t.test(e)?null:r||"Please enter a valid value."}numeric(e,t){return e&&"string"==typeof e?/^\d+$/.test(e.trim())?null:t?`${t} must contain only numbers.`:"Must contain only numbers.":t?`${t} is required.`:"This field is required."}alphabetic(e,t){return e&&"string"==typeof e?/^[a-zA-Z\s]+$/.test(e.trim())?null:t?`${t} must contain only letters and spaces.`:"Must contain only letters and spaces.":t?`${t} is required.`:"This field is required."}alphanumeric(e,t){return e&&"string"==typeof e?/^[a-zA-Z0-9\s]+$/.test(e.trim())?null:t?`${t} must contain only letters, numbers, and spaces.`:"Must contain only letters, numbers, and spaces.":t?`${t} is required.`:"This field is required."}url(e){if(!e||"string"!=typeof e)return"Please enter a valid URL.";const t=e.trim();try{const e=new URL(t);return""===e.hostname||e.hostname.startsWith(".")||e.hostname.endsWith(".")?"Please enter a valid URL.":null}catch{return"Please enter a valid URL."}}postal_code(e,t="US"){if(!e||"string"!=typeof e)return"Please enter a valid postal code.";const r=e.trim();switch(t.toUpperCase()){case"US":if(!/^\d{5}(-\d{4})?$/.test(r))return"Please enter a valid US ZIP code (e.g., 12345 or 12345-6789).";break;case"CA":if(!/^[A-Za-z]\d[A-Za-z] \d[A-Za-z]\d$/.test(r))return"Please enter a valid Canadian postal code (e.g., A1A 1A1).";break;case"UK":case"GB":if(!/^[A-Za-z]{1,2}\d[A-Za-z\d]?\s\d[A-Za-z]{2}$/.test(r))return"Please enter a valid UK postal code (e.g., SW1A 1AA).";break;default:if(!/^[A-Za-z0-9\s-]{3,10}$/.test(r))return"Please enter a valid postal code."}return null}}class y extends Error{constructor(e,t,r){super(`Alcore API Error ${e}: ${t}`),this.name="AlcoreApiError",this.errorCode=e,this.errorDescription=t,this.statusCode=r,Error.captureStackTrace&&Error.captureStackTrace(this,y)}isErrorCode(e){return this.errorCode===e}isAnyErrorCode(e){return e.includes(this.errorCode)}}const _={ALVIERE_CORE_NOT_INITIALIZED:"000000",UNPROCESSABLE_ENCRYPTED_DATA:"100011",WRONG_ENCRYPTED_ENDPOINT:"100012",UNDECRYPTABLE_DATA_AT_ENDPOINT:"100013",DECRYPTED_DATA_UNUSABLE_AT_ENDPOINT:"100014",WRONG_DECRYPTED_ENDPOINT:"100015",WRONG_VERSION_OR_ENDPOINT:"100016",OPERATION_HALTED:"100017",INVALID_REQUEST_PAYLOAD:"100300",INVALID_REQUEST_PAYLOAD_FIELD:"100301",INVALID_PATH_PARAMETER:"100302",INVALID_HEADER:"100303",INVALID_QUERY_PARAMETER:"100304",INVALID_JWT:"100305",AUTH_FAILED:"100306",SESSION_NOT_FOUND:"110000",PARENT_ACCOUNT_NOT_FOUND:"110001",NOT_FOUND:"110002",ACCOUNT_TYPE_NOT_SUPPORTED:"110004",UNDERLYING_API_ERROR:"115000",ACCOUNT_STATUS_NOT_ACTIVE:"115001",ACCOUNT_CHILD_FORBIDDEN:"320129",PARENT_ACCOUNT_NOT_ALLOWED:"320104",BANK_ACCOUNT_PRIMARY_REQUIRES_ACTIVE_STATUS:"340028",BANK_ACCOUNT_ALREADY_EXISTS:"340029"},m={[_.INVALID_JWT]:"Invalid authentication token. Please log in again.",[_.AUTH_FAILED]:"Authentication failed. Please check your credentials and try again.",[_.SESSION_NOT_FOUND]:"Session not found. Please log in again.",[_.PARENT_ACCOUNT_NOT_FOUND]:"Parent account not found.",[_.NOT_FOUND]:"Resource not found.",[_.ACCOUNT_TYPE_NOT_SUPPORTED]:"Account type not supported.",[_.INVALID_REQUEST_PAYLOAD]:"Invalid request payload. Please check your request and try again.",[_.INVALID_REQUEST_PAYLOAD_FIELD]:"Invalid request payload field. Please check your request and try again.",[_.INVALID_PATH_PARAMETER]:"Invalid path parameter. Please check your request and try again.",[_.INVALID_HEADER]:"Invalid header. Please check your request and try again.",[_.INVALID_QUERY_PARAMETER]:"Invalid query parameter. Please check your request and try again.",[_.UNPROCESSABLE_ENCRYPTED_DATA]:"Unprocessable encrypted data. Please check your request and try again.",[_.WRONG_ENCRYPTED_ENDPOINT]:"Wrong encrypted endpoint. Please check your request and try again.",[_.UNDECRYPTABLE_DATA_AT_ENDPOINT]:"Undecryptable data at endpoint. Please check your request and try again.",[_.DECRYPTED_DATA_UNUSABLE_AT_ENDPOINT]:"Decrypted data unusable at endpoint. Please check your request and try again.",[_.WRONG_DECRYPTED_ENDPOINT]:"Wrong decrypted endpoint. Please check your request and try again.",[_.WRONG_VERSION_OR_ENDPOINT]:"Wrong version or endpoint. Please check your request and try again.",[_.OPERATION_HALTED]:"Operation halted. Please check your request and try again.",[_.UNDERLYING_API_ERROR]:"Underlying API Error. ",[_.ACCOUNT_STATUS_NOT_ACTIVE]:"Account status not active. Please check your request and try again.",[_.ACCOUNT_CHILD_FORBIDDEN]:"Used Account can't be used to create a child account.",[_.PARENT_ACCOUNT_NOT_ALLOWED]:"Parent account not allowed. Please check your request and try again.",[_.BANK_ACCOUNT_PRIMARY_REQUIRES_ACTIVE_STATUS]:"Only ACTIVE bank accounts can be set as primary.",[_.BANK_ACCOUNT_ALREADY_EXISTS]:"This bank account has already been added to your account."};function f(e){return m[e]||"An unexpected error occurred. Please try again."}const w=[_.INVALID_JWT,_.AUTH_FAILED,_.SESSION_NOT_FOUND,_.UNPROCESSABLE_ENCRYPTED_DATA,_.WRONG_ENCRYPTED_ENDPOINT,_.UNDECRYPTABLE_DATA_AT_ENDPOINT,_.OPERATION_HALTED,_.ALVIERE_CORE_NOT_INITIALIZED,_.UNDERLYING_API_ERROR,_.ACCOUNT_STATUS_NOT_ACTIVE,_.ACCOUNT_CHILD_FORBIDDEN,_.PARENT_ACCOUNT_NOT_ALLOWED];class E{constructor(e,t,r){this.endpoint="/alcore",this.jwt=e,this.cryptor=t,this.domain=o(),this.logger=r,this.logger.debug(`🔐 AlcoreBase initialized with domain: ${this.domain}`)}async send(e,t,r){const s={method:e,endpoint:t,payload:JSON.stringify(r)};let n;this.logger.debug("🌐 AlcoreBase: Preparing to send request"),this.logger.debug("🌐 Method: "+e),this.logger.debug("🌐 Endpoint: "+t),this.logger.debug("🌐 Domain: "+(this.domain||"undefined")),this.logger.debug("🌐 JWT Token: "+(this.jwt?"✅ Present":"❌ Missing")),this.logger.debug("🌐 Payload size: "+JSON.stringify(r).length+" chars"),this.logger.debug(this.jwt),this.logger.debug("DATA TO SEND before encrypt"),this.logger.debug(r);try{n=await this.cryptor.encrypt(s),this.logger.debug("🔐 Encryption successful")}catch(i){throw this.logger.debug("❌ Encryption failed: "+(i instanceof Error?i.message:"Unknown error")),i}this.logger.debug("BASE GATEWAY: posting to "+this.endpoint),this.logger.debug(n);const a=this.domain+this.endpoint;this.logger.debug("🌐 Full URL: "+a);try{const e=await fetch(a,{method:"post",headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.jwt,Version:"2021-11-18"},body:JSON.stringify(n)});if(this.logger.debug("🌐 Response received - Status: "+e.status+" "+e.statusText),this.logger.debug("🌐 Response OK: "+e.ok),!e.ok){let t=await e.json();t.p&&(t=await this.decrypt(t));const r=500===e.status?_.UNDERLYING_API_ERROR:t.error_code,s=t.error_description||f(r);throw this.logger.debug(`❌ API Error - Code: ${r}, Description: ${s}`),new y(r,s,e.status)}return e}catch(o){throw this.logger.debug("❌ Fetch failed: "+(o instanceof Error?o.message:"Unknown error")),o}}async decrypt(e){return this.cryptor.decrypt(e)}}function A(e){const t={};for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const s=e[r];["",null,void 0].includes(s)||(t[r]=s)}return t}function T(e){if(e&&"object"==typeof e&&("error_code"in e||"error_description"in e)){const t=e.error_description||"Unknown API error",r=e.error_code||"UNKNOWN";throw new Error(`${r}: ${t}`)}return e}function b(e){try{const t=e.split(".");if(3!==t.length)return null;const r=t[1],s=atob(r.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(s)}catch(t){return null}}function P(e){const t=b(e);return t?{domain:t.api_domain||"https://api.dev.alviere.com"}:{}}function C(e){const t=b(e);return t&&t.sub||null}class N extends E{constructor(e,t,r){super(e,t,r)}async add_card(e,t){const r=`/accounts/${e}/payment-methods/cards`,s=await this.send("POST",r,t),n=await s.json();return T(await this.decrypt(n))}async add_bank_account(e,t){const r=`/accounts/${e}/payment-methods/bank-accounts`,s=await this.send("POST",r,t),n=await s.json();return T(await this.decrypt(n))}async get_bank_accounts(e){const t=`/accounts/${e}/payment-methods/bank-accounts`,r=await this.send("GET",t,{}),s=await r.json();return T(await this.decrypt(s))}async delete_bank_account(e,t){const r=`/accounts/${e}/payment-methods/bank-accounts/${t}`;return T(await this.send("DELETE",r,{}))}async update_bank_account(e,t,r){const s=`/payment-methods/bank-accounts/${t}`,n=await this.send("PATCH",s,r),a=await n.json();return T(await this.decrypt(a))}}class D extends E{constructor(e,t,r){super(e,t,r)}async listWallets(e,t){const r=`/accounts/${e}/wallets${t?"?"+new URLSearchParams(Object.entries(t).filter(([e,t])=>void 0!==t)):""}`,s=await this.send("GET",r,{}),n=await s.json();return T(await this.decrypt(n))}async loadFunds(e,t){const r=`/wallets/${e}/load`,s=await this.send("POST",r,t),n=await s.json();return T(await this.decrypt(n))}}class R extends E{constructor(e,t,r){super(e,t,r)}async createPaymentInstrument(e){const t=await this.send("POST","/payments/payment-instruments",e),r=await t.json();return T(await this.decrypt(r))}async getPaymentInstrument(e){const t=`/payments/payment-instruments/${e}`,r=await this.send("GET",t,{}),s=await r.json();return T(await this.decrypt(s))}async deletePaymentInstrument(e){const t=`/payments/payment-instruments/${e}`;await this.send("DELETE",t,{})}async debitFunds(e){const t=await this.send("POST","/payments/debit",e),r=await t.json();return T(await this.decrypt(r))}async listCards(e,t){const r=`/accounts/${e}/payment-methods/cards${t?"?"+new URLSearchParams(Object.entries(t).filter(([e,t])=>void 0!==t)):""}`,s=await this.send("GET",r,{}),n=await s.json();return T(await this.decrypt(n))}}class I extends E{constructor(e,t,r){super(e,t,r),this.logger.debug("🔐 AccountsGateway initialized")}async createAccount(e){const t=await this.send("POST","/accounts",e),r=await t.json();return T(await this.decrypt(r))}async getAccount(e){const t=`/accounts/${e}`,r=await this.send("GET",t,{}),s=await r.json();return T(await this.decrypt(s))}async updateAccount(e,t){const r=`/accounts/${e}`,s=await this.send("PATCH",r,t),n=await s.json();return T(await this.decrypt(n))}async deleteAccount(e){const t=`/accounts/${e}`;await this.send("DELETE",t,{})}async listAccounts(e){const t=`/accounts${e?"?"+new URLSearchParams(Object.entries(e).filter(([e,t])=>void 0!==t)):""}`,r=await this.send("GET",t,{}),s=await r.json();return T(await this.decrypt(s))}async activateAccount(e){const t=`/accounts/${e}/activate`;await this.send("POST",t,{})}async deactivateAccount(e){const t=`/accounts/${e}/deactivate`;await this.send("POST",t,{})}async manageOnboarding(e,t){const r=`/accounts/${e}/onboarding`;await this.send("PUT",r,{action:t})}async createAddress(e,t){const r=`/accounts/${e}/addresses`,s=await this.send("POST",r,t),n=await s.json();return T(await this.decrypt(n))}async getAddresses(e,t){const r=`/accounts/${e}/addresses${t?"?"+new URLSearchParams(Object.entries(t).filter(([e,t])=>void 0!==t)):""}`,s=await this.send("GET",r,{}),n=await s.json();return T(await this.decrypt(n))}async updateAddress(e,t,r){const s=`/accounts/${e}/addresses/${t}`,n=await this.send("PATCH",s,r),a=await n.json();return T(await this.decrypt(a))}async deleteAddress(e,t){const r=`/accounts/${e}/addresses/${t}`;await this.send("DELETE",r,{})}async createDossier(e,t){const r=`/accounts/${e}/dossiers`,s=await this.send("POST",r,t),n=await s.json();return T(await this.decrypt(n))}async getDossiers(e,t){const r=`/accounts/${e}/dossiers${t?"?"+new URLSearchParams(Object.entries(t).filter(([e,t])=>void 0!==t)):""}`,s=await this.send("GET",r,{}),n=await s.json();return T(await this.decrypt(n))}async getDossier(e,t){const r=`/accounts/${e}/dossiers/${t}`,s=await this.send("GET",r,{}),n=await s.json();return T(await this.decrypt(n))}async updateDossier(e,t,r){const s=`/accounts/${e}/dossiers/${t}`,n=await this.send("PUT",s,r),a=await n.json();return T(await this.decrypt(a))}async replaceDossier(e,t,r){const s=`/accounts/${e}/dossiers/${t}`,n=await this.send("PATCH",s,r),a=await n.json();return T(await this.decrypt(a))}async deleteDossier(e,t){const r=`/accounts/${e}/dossiers/${t}`;await this.send("DELETE",r,{})}}class O extends E{constructor(e,t,r){super(e,t,r),this.logger.debug("🔐 AuthGateway initialized")}async generateScopedToken(e){this.logger.debug("🔐 AuthGateway: Generating scoped token"),this.logger.debug("🌐 Endpoint: /v3/auth"),this.logger.debug("🌐 Account UUID: "+e.account_uuid);const t=await this.send("POST","/v3/auth",e),r=await this.decrypt(await t.json());return this.logger.debug("✅ Scoped token generated successfully"),r}}class S{constructor(e){this.gateway=e}async listWallets(e,t){return this.gateway.listWallets(e,t)}async loadFunds(e,t){return this.gateway.loadFunds(e,t)}}class v{constructor(e){this.gateway=e}async createPaymentInstrument(e){return this.gateway.createPaymentInstrument(e)}async getPaymentInstrument(e){return this.gateway.getPaymentInstrument(e)}async deletePaymentInstrument(e){return this.gateway.deletePaymentInstrument(e)}async debitFunds(e){return this.gateway.debitFunds(e)}async listCards(e,t){return this.gateway.listCards(e,t)}}class x{constructor(e){this.gateway=e}async createAccount(e){return this.gateway.createAccount(e)}async getAccount(e){return this.gateway.getAccount(e)}async updateAccount(e,t){return this.gateway.updateAccount(e,t)}async deleteAccount(e){return this.gateway.deleteAccount(e)}async listAccounts(e){return this.gateway.listAccounts(e)}async activateAccount(e){return this.gateway.activateAccount(e)}async deactivateAccount(e){return this.gateway.deactivateAccount(e)}async manageOnboarding(e,t){return this.gateway.manageOnboarding(e,t)}async createAddress(e,t){return this.gateway.createAddress(e,t)}async getAddresses(e,t){return this.gateway.getAddresses(e,t)}async updateAddress(e,t,r){return this.gateway.updateAddress(e,t,r)}async deleteAddress(e,t){return this.gateway.deleteAddress(e,t)}async createDossier(e,t){return this.gateway.createDossier(e,t)}async getDossiers(e,t){return this.gateway.getDossiers(e,t)}async getDossier(e,t){return this.gateway.getDossier(e,t)}async updateDossier(e,t,r){return this.gateway.updateDossier(e,t,r)}async replaceDossier(e,t,r){return this.gateway.replaceDossier(e,t,r)}async deleteDossier(e,t){return this.gateway.deleteDossier(e,t)}}class k{constructor(e,t){this.gateway=e,this.logger=t}async processAddCard(e,t){this.logger.debug("PaymentProcessor: Starting add card processing"),this.logger.debug("PaymentProcessor: Request data: "+JSON.stringify(t,null,2));try{const r=await this.gateway.add_card(e,t);return this.logger.debug("PaymentProcessor: Add card processing completed successfully"),r}catch(r){throw this.logger.debug("PaymentProcessor: Add card processing failed"),this.logger.debug("PaymentProcessor: Error details: "+JSON.stringify(r)),r}}validateRequest(e){const t=["external_id","pan","exp_year","exp_month","postal_code","security_code"];for(const r of t)if(!e[r])throw new Error(`Missing required field: ${r}`);this.logger.debug("PaymentProcessor: Request validation passed")}async processAddCardWithValidation(e,t){return this.logger.debug("PaymentProcessor: Starting add card processing with validation"),this.validateRequest(t),await this.processAddCard(e,t)}async processAddBankAccount(e,t){this.logger.debug("PaymentProcessor: Starting add bank account processing"),this.logger.debug("PaymentProcessor: Request data: "+JSON.stringify(t,null,2));try{const r=await this.gateway.add_bank_account(e,t);return this.logger.debug("PaymentProcessor: Add bank account processing completed successfully"),r}catch(r){throw this.logger.debug("PaymentProcessor: Add bank account processing failed"),this.logger.debug("PaymentProcessor: Error details: "+JSON.stringify(r)),r}}validateBankAccountRequest(e){const t=["external_id","country","currency","bank_account_details"];for(const r of t)if(!e[r])throw new Error(`Missing required field: ${r}`);this.logger.debug("PaymentProcessor: Bank account request validation passed")}async processAddBankAccountWithValidation(e,t){return this.logger.debug("PaymentProcessor: Starting add bank account processing with validation"),this.validateBankAccountRequest(t),await this.processAddBankAccount(e,t)}async processGetBankAccounts(e){this.logger.debug("PaymentProcessor: Starting get bank accounts processing");try{const t=await this.gateway.get_bank_accounts(e);return this.logger.debug("PaymentProcessor: Get bank accounts processing completed successfully"),t}catch(t){throw this.logger.debug("PaymentProcessor: Get bank accounts processing failed"),this.logger.debug("PaymentProcessor: Error details: "+JSON.stringify(t)),t}}async processDeleteBankAccount(e,t){this.logger.debug("PaymentProcessor: Starting delete bank account processing");try{const r=await this.gateway.delete_bank_account(e,t);return this.logger.debug("PaymentProcessor: Delete bank account processing completed successfully"),r}catch(r){throw this.logger.debug("PaymentProcessor: Delete bank account processing failed"),this.logger.debug("PaymentProcessor: Error details: "+JSON.stringify(r)),r}}async processUpdateBankAccount(e,t,r){this.logger.debug("PaymentProcessor: Starting update bank account processing"),this.logger.debug("PaymentProcessor: Request data: "+JSON.stringify(r,null,2));try{const s=await this.gateway.update_bank_account(e,t,r);return this.logger.debug("PaymentProcessor: Update bank account processing completed successfully"),s}catch(s){throw this.logger.debug("PaymentProcessor: Update bank account processing failed"),this.logger.debug("PaymentProcessor: Error details: "+JSON.stringify(s)),s}}}class U{constructor(e){this.gateway=e}async getBankInfo(e){return this.gateway.getBankInfo(e)}}class L{constructor(e){this.gateway=e}async getLegalTexts(e,t){return this.gateway.getLegalTexts(e,t)}}class $ extends E{constructor(e,t,r){super(e,t,r),this.logger.debug("🔐 BankInfoGateway initialized")}async getBankInfo(e){const t=`/v3/bank-info?routing_number=${e}`,r=await this.send("GET",t,{}),s=await r.json();return T(await this.decrypt(s))}}class F extends E{constructor(e,t,r){super(e,t,r),this.logger.debug("🔐 LegalTextsGateway initialized")}async getLegalTexts(e,t){const r=new URLSearchParams({type:e});t&&r.set("version",t);const s=`/v3/legal-texts?${r.toString()}`;this.logger.debug(`endpoint -> ${s}`);const n=await this.send("GET",s,{}),a=await n.json();return T(await this.decrypt(a))}}var V=(e=>(e.PASSPORT="PASSPORT",e.ID_DOCUMENT_FRONT="ID_DOCUMENT_FRONT",e.ID_DOCUMENT_BACK="ID_DOCUMENT_BACK",e.DRIVER_LICENSE_FRONT="DRIVER_LICENSE_FRONT",e.DRIVER_LICENSE_BACK="DRIVER_LICENSE_BACK",e.SELFIE="SELFIE",e.PROOF_OF_ADDRESS="PROOF_OF_ADDRESS",e.PROOF_OF_FUNDS="PROOF_OF_FUNDS",e.MC_DOCUMENT_FRONT="MC_DOCUMENT_FRONT",e.MC_DOCUMENT_BACK="MC_DOCUMENT_BACK",e.INE_FRONT="INE_FRONT",e.INE_BACK="INE_BACK",e.ARTICLES_OF_INCORPORATION="ARTICLES_OF_INCORPORATION",e.CERTIFICATE_OF_GOOD_STANDING="CERTIFICATE_OF_GOOD_STANDING",e.ORG_CHART="ORG_CHART",e.UBO_FORM="UBO_FORM",e.REG_GG_ATTESTATION="REG_GG_ATTESTATION",e))(V||{}),G=(e=>(e.CREATED="CREATED",e.PENDING="PENDING",e.MANUAL_REVIEW="MANUAL_REVIEW",e.VERIFIED="VERIFIED",e.EXPIRED="EXPIRED",e.REJECTED="REJECTED",e.FAILED="FAILED",e.DELETED="DELETED",e))(G||{});class M{constructor(){this.eventListeners=new Map,this.configs=new Map}sanitize(e,t){return e.trim()}getRawValue(e,t){return e.replace(/\s/g,"")}mount(e,t){const r={...this.getDefaultConfig(),...t};this.configs.set(e,r);const s=new Map;this.eventListeners.set(e,s),e instanceof HTMLInputElement&&this.setupInputElement(e,r),this.onMount?.(e,r)}unmount(e){const t=this.eventListeners.get(e);t&&(t.forEach((t,r)=>{e.removeEventListener(r,t)}),this.eventListeners.delete(e)),this.configs.delete(e),this.onUnmount?.(e)}setupInputElement(e,t){const r=this.eventListeners.get(e);if(t.formatOnType){const s=e=>{const r=e.target,s=this.format(r.value,t);s.formattedValue!==r.value&&(r.value=s.formattedValue,void 0!==s.cursorPosition&&r.setSelectionRange(s.cursorPosition,s.cursorPosition))};e.addEventListener("input",s),r.set("input",s)}if(t.validateOnBlur){const s=e=>{const r=e.target,s=this.validate(r.value,t);this.displayValidation(r,s,t)};e.addEventListener("blur",s),r.set("blur",s)}if(t.validateOnType){const s=e=>{const r=e.target,s=this.validate(r.value,t);this.displayValidation(r,s,t)};e.addEventListener("input",s),r.set("input-validate",s)}t.placeholder&&(e.placeholder=t.placeholder),t.maxLength&&(e.maxLength=t.maxLength),t.ariaLabel&&e.setAttribute("aria-label",t.ariaLabel),t.ariaDescribedBy&&e.setAttribute("aria-describedby",t.ariaDescribedBy)}displayValidation(e,t,r){r.showErrorsInline&&(r.errorClassName&&e.classList.remove(r.errorClassName),r.successClassName&&e.classList.remove(r.successClassName),t.isValid&&r.successClassName?e.classList.add(r.successClassName):!t.isValid&&r.errorClassName&&e.classList.add(r.errorClassName),this.updateErrorMessage(e,t.error))}updateErrorMessage(e,t){let r=e.parentElement?.querySelector(".alviere-field-error");t?(r||(r=document.createElement("div"),r.className="alviere-field-error",e.parentElement?.appendChild(r)),r.textContent=t,r.style.display="block"):r&&(r.style.display="none")}getDefaultConfig(){return{validateOnBlur:!0,formatOnType:!0,showErrorsInline:!0,errorClassName:"alviere-field-error",successClassName:"alviere-field-success"}}}const j={visa:{name:"Visa",pattern:/^4/,gaps:[4,8,12],lengths:[13,16,19],code:{name:"CVV",size:3}},mastercard:{name:"Mastercard",pattern:/^(5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)/,gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},amex:{name:"American Express",pattern:/^3[47]/,gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},diners:{name:"Diners Club",pattern:/^3[0689]/,gaps:[4,10],lengths:[14],code:{name:"CVV",size:3}},discover:{name:"Discover",pattern:/^6([045]|22)/,gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{name:"JCB",pattern:/^35/,gaps:[4,8,12],lengths:[16],code:{name:"CVV",size:3}}};class q{constructor(e={}){if(this.authToken="",this.business_uuid="",this.account_uuid="",this.cryptor=null,this.gateways=new Map,this.jwt=e.jwt||"",this.debug=e.debug||!1,this.publicCertificate=e.publicCertificate||"",this.publicCertificateId=e.publicCertificateId||"",this.business_uuid=e.business_uuid||"",this.logger=new t(this.debug),this.logger.debug(`🔐 AlviereCore constructor called with config: ${JSON.stringify(e)}`),this.jwt){const t=P(this.jwt);e.jwt&&n({...t,certificate:{id:this.publicCertificateId,public_key:this.publicCertificate}});const r=C(this.jwt);r?(this.account_uuid=r,this.logger.debug(`🔐 Extracted account_uuid from JWT sub field: ${this.account_uuid}`)):this.logger.debug("⚠️ No account_uuid found in JWT sub field"),this.authToken=this.jwt,this.logger.debug("🔐 Using JWT as auth token for API authentication")}e.alviere&&n(e.alviere)}configure(e){const r=e.jwt&&e.jwt!==this.jwt;if(e.jwt){this.jwt=e.jwt;const t=P(e.jwt);t.domain&&n(t);const r=C(e.jwt);this.logger.debug(`🔐 Extracted account_uuid from JWT sub field: ${r}`),r?(this.account_uuid=r,this.logger.debug(`🔐 Updated account_uuid from JWT sub field: ${this.account_uuid}`)):this.logger.debug("⚠️ No account_uuid found in new JWT sub field"),this.authToken=this.jwt,this.logger.debug("🔐 Updated JWT as auth token for API authentication")}return void 0!==e.business_uuid&&(this.business_uuid=e.business_uuid,this.logger.debug(`🔐 Updated business_uuid: ${this.business_uuid}`)),"boolean"==typeof e.debug&&e.debug!==this.debug&&(this.debug=e.debug,this.logger=new t(this.debug),this.logger.debug("🔐 Debug mode changed to: "+this.debug)),r&&(this.logger.debug("🔐 JWT changed - clearing gateway cache and cryptor"),this.gateways.clear(),this.cryptor=null),e.alviere&&n(e.alviere),this}getOrCreateCryptor(){if(!this.cryptor){const e=c();if(!e||""===e.trim())throw new Error('🔐 Cryptor initialization failed: RSA public key not available. Please ensure JWT is configured with a valid RSA key before attempting encryption operations. Call alviereCore.configure({ jwt: "your-jwt-with-rsa-key" }) first.');this.logger.debug("🔐 Creating Cryptor instance with RSA key"),this.cryptor=new h(this.logger)}return this.cryptor}createPaymentsGateway(){return this.gateways.has("payments")||this.gateways.set("payments",new N(this.authToken,this.getOrCreateCryptor(),this.logger)),this.gateways.get("payments")}createPaymentsService(){const e=this.createPaymentsGateway();return new k(e,this.logger)}createWalletsService(){return this.gateways.has("wallets")||this.gateways.set("wallets",new D(this.authToken,this.getOrCreateCryptor(),this.logger)),new S(this.gateways.get("wallets"))}createPaymentInstrumentsService(){return this.gateways.has("paymentInstruments")||this.gateways.set("paymentInstruments",new R(this.authToken,this.getOrCreateCryptor(),this.logger)),new v(this.gateways.get("paymentInstruments"))}createAccountsService(){return this.gateways.has("accounts")||this.gateways.set("accounts",new I(this.authToken,this.getOrCreateCryptor(),this.logger)),new x(this.gateways.get("accounts"))}createAuthGateway(){if(!this.gateways.has("auth")){if(!this.cryptor)throw new Error("Cryptor not initialized. Cannot create AuthGateway.");this.gateways.set("auth",new O(this.authToken,this.cryptor,this.logger))}return this.gateways.get("auth")}createBankInfoService(){return this.gateways.has("bankInfo")||this.gateways.set("bankInfo",new $(this.authToken,this.getOrCreateCryptor(),this.logger)),new U(this.gateways.get("bankInfo"))}createLegalTextsService(){return this.gateways.has("legalTexts")||this.gateways.set("legalTexts",new F(this.authToken,this.getOrCreateCryptor(),this.logger)),new L(this.gateways.get("legalTexts"))}async generateScopedToken(e,t=!0){this.logger.debug(`🔐 Generating scoped token for account: ${e}`),this.logger.debug(`🔐 Auto-update: ${t}`);const r=this.createAuthGateway(),s=await r.generateScopedToken({account_uuid:e});return this.logger.debug("✅ Scoped token generated successfully"),t&&s.access_token&&(this.logger.debug("🔄 Auto-updating SDK with new scoped token"),this.configure({jwt:s.access_token})),s.access_token}getLogger(){return this.logger}getCryptor(){return this.getOrCreateCryptor()}clearCache(){this.gateways.clear()}getAccountUuid(){return this.account_uuid}getBusinessUuid(){return this.business_uuid}isFirstTimeUser(){if(!this.account_uuid||!this.business_uuid)return this.logger.debug("🔐 Cannot determine first-time user status: missing account_uuid or business_uuid"),!1;const e=this.account_uuid===this.business_uuid;return this.logger.debug(`🔐 First-time user check: ${e} (account: ${this.account_uuid}, business: ${this.business_uuid})`),e}isScopedToPayee(){return!(!this.account_uuid||!this.business_uuid)&&this.account_uuid!==this.business_uuid}static createValidator(e=!1){const r=new t(e);return new p(r)}static createLogger(e=!1){return new t(e)}static createCryptor(e){return new h(e)}}exports.ALVIERE_DOMAIN=d,exports.AccountsApiService=x,exports.AccountsGateway=I,exports.AlcoreApiError=y,exports.AlcoreErrorCodes=_,exports.AlcoreErrorMessages=m,exports.AlviereCore=q,exports.AuthGateway=O,exports.BankInfoGateway=$,exports.BaseFieldPlugin=M,exports.CERTIFICATE_ID=g,exports.CardNumberPlugin=class extends M{constructor(){super(...arguments),this.name="card-number",this.version="1.0.0",this.description="Credit card number formatting and validation",this.currentCardType=null}validate(e,t){const r=this.sanitize(e);if(!r)return{isValid:!1,error:"Card number is required"};if(!/^\d+$/.test(r))return{isValid:!1,error:"Card number must contain only digits"};const s=this.detectCardType(r);if(this.currentCardType=s,!s)return{isValid:!1,error:"Invalid card number format"};if(!s.lengths.includes(r.length)){const e=s.lengths.join(" or ");return{isValid:!1,error:`${s.name} card numbers must be ${e} digits long`}}if(!this.luhnCheck(r))return{isValid:!1,error:"Invalid card number"};if(t?.customValidation){const r=t.customValidation(e);if(r)return{isValid:!1,error:r}}return{isValid:!0,suggestions:[`${s.name} ending in ${r.slice(-4)}`]}}format(e,t){const r=this.sanitize(e),s=this.detectCardType(r)||j.visa;let n="",a=0;for(let i=0;i<r.length;i++)s.gaps.includes(i)&&(n+=" ",a++),n+=r[i];return{formattedValue:n,cursorPosition:r.length+a}}sanitize(e,t){return e.replace(/\D/g,"")}getRawValue(e,t){return this.sanitize(e)}canHandle(e){return["card-number","cardNumber","pan","credit-card"].includes(e)}getDefaultConfig(){return{...super.getDefaultConfig(),validateOnType:!0,formatOnType:!0,placeholder:"1234 5678 9012 3456",maxLength:23,ariaLabel:"Credit card number"}}detectCardType(e){for(const[t,r]of Object.entries(j))if(r.pattern.test(e))return r;return null}getCardType(){return this.currentCardType}luhnCheck(e){let t=0,r=!1;for(let s=e.length-1;s>=0;s--){let n=parseInt(e.charAt(s),10);r&&(n*=2,n>9&&(n-=9)),t+=n,r=!r}return t%10==0}onMount(e,t){if(e instanceof HTMLInputElement){const t=t=>{const r=t.target,s=this.sanitize(r.value),n=this.detectCardType(s);if(n!==this.currentCardType&&(this.currentCardType=n,e.dispatchEvent(new CustomEvent("cardTypeChange",{detail:{cardType:n,element:e},bubbles:!0}))),n){const e=Math.max(...n.lengths)+n.gaps.length;r.maxLength=e}};e.addEventListener("input",t);const r=this.eventListeners.get(e);r&&r.set("cardTypeDetection",t)}}},exports.CriticalErrorCodes=w,exports.Cryptor=h,exports.DEFAULT_CONFIG=r,exports.DossierStatus=G,exports.DossierType=V,exports.FieldPluginRegistry=class{constructor(e={}){this.plugins=new Map,this.fieldTypeCache=new Map,this.config={autoRegisterBuiltins:!0,enablePluginValidation:!0,...e},this.logger=e.logger,this.config.autoRegisterBuiltins&&this.registerBuiltinPlugins(),this.logger?.debug("🔐 FieldPluginRegistry initialized")}register(e){this.config.enablePluginValidation&&this.validatePlugin(e),this.plugins.set(e.name,e),this.fieldTypeCache.clear(),this.logger?.debug(`FieldPluginRegistry: Registered plugin '${e.name}' v${e.version}`)}unregister(e){const t=this.plugins.delete(e);return t&&(this.fieldTypeCache.clear(),this.logger?.debug(`FieldPluginRegistry: Unregistered plugin '${e}'`)),t}getPlugin(e){return this.plugins.get(e)}getPluginForFieldType(e){if(this.fieldTypeCache.has(e))return this.fieldTypeCache.get(e);for(const r of this.plugins.values())if(r.canHandle(e))return this.fieldTypeCache.set(e,r),r;const t=this.plugins.get("text");return t?(this.fieldTypeCache.set(e,t),t):void 0}getAllPlugins(){return Array.from(this.plugins.values())}getPluginNames(){return Array.from(this.plugins.keys())}hasPlugin(e){return this.plugins.has(e)}getSupportedFieldTypes(){const e=new Set,t=["card-number","cardNumber","pan","expiry","expiry-date","expiryDate","cvv","cvc","code","zip","zip-code","postal-code","text","name","cardholder-name"];for(const r of t)this.getPluginForFieldType(r)&&e.add(r);return Array.from(e)}mountPlugin(e,t,r){const s=this.getPluginForFieldType(t);if(!s)return this.logger?.warn(`FieldPluginRegistry: No plugin found for field type '${t}'`),null;try{return s.mount(e,r),this.logger?.debug(`FieldPluginRegistry: Mounted '${s.name}' plugin on element for field type '${t}'`),s}catch(n){return this.logger?.error(`FieldPluginRegistry: Failed to mount plugin '${s.name}': ${n instanceof Error?n.message:String(n)}`),null}}unmountPlugin(e,t){const r=this.getPluginForFieldType(t);if(!r)return!1;try{return r.unmount(e),this.logger?.debug(`FieldPluginRegistry: Unmounted '${r.name}' plugin from element`),!0}catch(s){return this.logger?.error(`FieldPluginRegistry: Failed to unmount plugin '${r.name}': ${s instanceof Error?s.message:String(s)}`),!1}}getStats(){return{totalPlugins:this.plugins.size,pluginNames:this.getPluginNames(),supportedFieldTypes:this.getSupportedFieldTypes(),cacheSize:this.fieldTypeCache.size}}clearCaches(){this.fieldTypeCache.clear()}registerBuiltinPlugins(){const e=[];for(const t of e)this.register(t)}validatePlugin(e){if(!e.name||"string"!=typeof e.name)throw new Error("Plugin must have a valid name");if(!e.version||"string"!=typeof e.version)throw new Error("Plugin must have a valid version");if("function"!=typeof e.validate)throw new Error("Plugin must implement validate method");if("function"!=typeof e.format)throw new Error("Plugin must implement format method");if("function"!=typeof e.sanitize)throw new Error("Plugin must implement sanitize method");if("function"!=typeof e.canHandle)throw new Error("Plugin must implement canHandle method");if("function"!=typeof e.mount)throw new Error("Plugin must implement mount method");if("function"!=typeof e.unmount)throw new Error("Plugin must implement unmount method");this.plugins.has(e.name)&&this.logger?.warn(`FieldPluginRegistry: Plugin '${e.name}' is already registered and will be replaced`)}},exports.Logger=t,exports.NewAccountRequest=function(e){return A({external_id:e.external_id,account_type:e.account_type,profile:e.profile,information:e.information,primary_address:e.primary_address,business_account_uuid:e.business_account_uuid,parent_account_uuid:e.parent_account_uuid,metadata:e.metadata})},exports.NewAddBankAccountRequest=function(e){const{external_id:t,country:r,currency:s,bank_account_details:n,primary:a,metadata:i}=e;let o={external_id:t,country:r,currency:s,bank_account_details:n,primary:a,metadata:i};return o=A(o),o},exports.NewAddCardRequest=function(e){const{external_id:t,name:r,pan:s,expiry:n,code:a,zip:i}=e,o=n.split("/"),c=o[0];let u={external_id:t,pan:s,exp_year:o[1],exp_month:c,security_code:a,postal_code:i,name_on_card:r};return u=A(u),u},exports.NewAddressRequest=function(e){return A({label:e.label,line_1:e.line_1,line_2:e.line_2,city:e.city,state:e.state,postal_code:e.postal_code,country:e.country,primary:e.primary,external_id:e.external_id})},exports.NewCardInstrumentFromForm=function(e,t,r,s,n,a,i,o,c,u,d,l){const g=t.split("/"),h=g[0],p=g[1];return{pan:e.replace(/\s/g,""),exp_month:h,exp_year:p,security_code:r,name_on_card:s,phone_number:d,email_address:l,billing_address:{line_1:n,line_2:u,city:a,state:i,postal_code:o,country:c}}},exports.NewCreditFundsRequest=function(e){return A({amount:e.amount,currency:e.currency,external_id:e.external_id,vault_name:e.vault_name,metadata:e.metadata})},exports.NewDebitFundsRequest=function(e,t,r,s,n,a="AUTHCAP",i,o,c,u,d){return{wallet_uuid:e,external_id:t,amount:r,currency:s,auth_type:a,payment_instrument_uuid:i,payment_instrument:o,description:c,merchant_details:n,"3ds_options":u,metadata:d}},exports.NewDossierReplaceRequest=function(e){return A({external_id:e.external_id,documents:e.documents,metadata:e.metadata})},exports.NewDossierRequest=function(e){return A({external_id:e.external_id,documents:e.documents,metadata:e.metadata})},exports.NewGenerateMobileTokenRequest=function(e){return A({account_uuid:e.account_uuid,with_plaid_sdk_token:e.with_plaid_sdk_token})},exports.NewGeneratePdsTokenRequest=function(e){return A({wallet_uuid:e.wallet_uuid})},exports.NewGeneratePlaidTokenRequest=function(e){return A({account_uuid:e.account_uuid,platform:e.platform,payment_method_uuid:e.payment_method_uuid})},exports.NewGenerateScopedTokenRequest=function(e){return{account_uuid:e.account_uuid}},exports.NewGenerateWebSessionRequest=function(e){return A({account_uuid:e.account_uuid})},exports.NewLoadFundsRequest=function(e){return A({payment_method_uuid:e.payment_method_uuid,amount:e.amount,external_id:e.external_id,service_fees:e.service_fees,transaction_options:e.transaction_options,metadata:e.metadata})},exports.NewPaymentInstrumentRequest=function(e,t,r,s,n){return{account_uuid:e,external_id:s,payment_instrument_type:t,payment_instrument_details:{card:r},metadata:n}},exports.NewPromoFundsRequest=function(e){return A({amount:e.amount,external_id:e.external_id,description:e.description,metadata:e.metadata})},exports.NewSendFundsRequest=function(e){return A({destination_wallet_uuid:e.destination_wallet_uuid,external_id:e.external_id,amount:e.amount,service_fees:e.service_fees,description:e.description,metadata:e.metadata})},exports.NewTransferFundsRequest=function(e){return A({beneficiary_uuid:e.beneficiary_uuid,payout_method_uuid:e.payout_method_uuid,amount:e.amount,service_fees:e.service_fees,description:e.description,external_id:e.external_id,metadata:e.metadata})},exports.NewWithdrawFundsRequest=function(e){return A({payment_method_uuid:e.payment_method_uuid,amount:e.amount,external_id:e.external_id,service_fees:e.service_fees,transaction_options:e.transaction_options,metadata:e.metadata})},exports.PaymentInstrumentsApiService=v,exports.PaymentInstrumentsGateway=R,exports.PaymentProcessor=k,exports.PaymentsGateway=N,exports.RSA_PUB_KEY=l,exports.Validator=p,exports.WalletsApiService=S,exports.WalletsGateway=D,exports.createDefaultMerchantDetails=function(){return{name:"Demo Merchant Store",merchant_id:"DEMO_MERCHANT_001"}},exports.decodeJWTPayload=b,exports.default=q,exports.extractAccountUuidFromJWT=C,exports.extractAlviereConfigFromJWT=P,exports.getALVIERE_DOMAIN=o,exports.getCERTIFICATE_ID=u,exports.getErrorMessage=f,exports.getJWTExpiration=function(e){const t=b(e);return t&&t.exp?new Date(1e3*t.exp):null},exports.getJWTRefreshTime=function(e,t=.05){const r=b(e);if(!r||!r.exp)return null;const s=1e3*r.exp;if(r.iat){const e=s-1e3*r.iat;return e<=0?null:s-e*t}const n=Date.now(),a=s-n;return a<=0?null:n+a*(1-t)},exports.getRSA_PUB_KEY=c,exports.getRuntimeConfig=function(){return s},exports.getSanitizedBody=A,exports.initializeFromEnvironment=i,exports.isCriticalError=function(e){return w.includes(e)},exports.isJWTExpired=function(e){const t=b(e);if(!t||!t.exp)return!0;const r=Math.floor(Date.now()/1e3);return t.exp<r},exports.setRuntimeConfig=n,exports.throwIfApiError=T;
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("node-forge");class t{constructor(e){this.logger="CORE_LOGGER",this.isDebug=e}debug(e){this.isDebug&&console.debug}warning(e){this.isDebug&&console.warn}warn(e){this.warning(e)}info(e){this.isDebug&&console.info}error(e){this.isDebug&&console.error}isDebugEnabled(){return this.isDebug}}const s={domain:"https://api.dev.alviere.com",access_token:"",certificate:{id:"",public_key:""}};let r={...s};function n(e){r={...r,...e}}function a(e){if("undefined"!=typeof window&&window.VITE_DEBUG){return window[`VITE_${e}`]}}function i(){if(r.domain&&r.certificate)return;const e={},t=a("ALVIERE_DOMAIN"),s=a("CERTIFICATE");if(t&&(e.domain=t),s)try{const t=JSON.parse(s);t&&"string"==typeof t.id&&"string"==typeof t.public_key&&(e.certificate={id:t.id,public_key:t.public_key})}catch{}(e.domain||e.certificate)&&n(e)}const o=()=>(r.domain||i(),r.domain),c=()=>(r.certificate||i(),r.certificate.public_key.replace(/\\n/g,"").replace(/\r\n/g,"").replace(/\n/g,"").replace(/\r/g,"").trim()),u=()=>(r.certificate||i(),r.certificate.id),d=o(),l=c(),g=u();class h{constructor(e){this.logger=e,this.rsa_key=c(),this.key=this.generate_key(),this.nonce=this.generate_nonce(),this.logger?.debug("🔐 Cryptor initialized")}async encrypt(t){const s=(new TextEncoder).encode(JSON.stringify(t)),r={name:"AES-GCM",iv:this.nonce},n=await this.import_key(),a=await crypto.subtle.encrypt(r,n,s),i=this.bufferToStr(a),o=btoa(i),c=this.bufferToStr(this.key),d=btoa(c),l=this.bufferToStr(this.nonce),g=btoa(l);this.logger?.debug(`🔐 RSA_KEY: ${this.rsa_key.substring(0,50)}...`);const h=e.pki.publicKeyFromPem(this.rsa_key).encrypt(d+"::"+g),p={p:o,k:btoa(h),i:u()};return this.logger?.debug(`🔐 ENCRYPTED_REQUEST: p=${p.p.substring(0,20)}..., i=${p.i}`),p}async decrypt(e){const t=await crypto.subtle.decrypt({name:"AES-GCM",iv:this.nonce},await this.import_key(),Uint8Array.from(atob(e.p),e=>e.charCodeAt(0))),s=(new TextDecoder).decode(t);return this.logger?.debug(`🔐 DECRYPTED: ${s}`),JSON.parse(s)}generate_key(){return crypto.getRandomValues(new Uint8Array(32))}generate_nonce(){return crypto.getRandomValues(new Uint8Array(12))}async import_key(){return await crypto.subtle.importKey("raw",this.key,{name:"AES-GCM"},!0,["encrypt","decrypt"])}async rsa_encrypt(t){this.logger?.debug(`🔐 RSA_ENCRYPT: Data to encrypt: ${t.substring(0,50)}...`),this.logger?.debug(`🔐 RSA_KEY: ${this.rsa_key.substring(0,50)}...`);const s=e.pki.publicKeyFromPem(this.rsa_key);return btoa(s.encrypt(t))}bufferToStr(e){return Array.from(new Uint8Array(e)).map(e=>String.fromCharCode(e)).join("")}}class p{constructor(e){this.logger=e}credit_card_name(e){return this.logger.debug(`🔐 CREDIT_CARD_NAME: ${e}`),e&&"string"==typeof e?0===e.trim().length?"Card holder name cannot be empty.":null:"Card holder name cannot be empty."}credit_card_number(e){if(!e||"string"!=typeof e)return"Please enter a valid card number.";return/^(?:4[0-9]{12}(?:[0-9]{3})?)$/.test(e.replace(/\s/g,""))||/^(?:5[1-5][0-9]{14})$/.test(e.replace(/\s/g,""))||/^(?:3[47][0-9]{13})$/.test(e.replace(/\s/g,""))||/^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/.test(e.replace(/\s/g,""))?null:(this.logger.debug("🔐 card number is not a recognized brand"),"Please enter a valid card number.")}credit_card_expiry_date(e){if(!e||"string"!=typeof e)return"Expiry date cannot be empty.";if(0===e.trim().length)return"Expiry date cannot be empty.";return/^(0[1-9]|1[0-2])\/?([0-9]{4}|[0-9]{2})$/.test(e)?null:"Please enter a valid expiry date."}credit_card_sec_code(e){if(!e||"string"!=typeof e)return"Security code cannot be empty.";if(0===e.trim().length)return"Security code cannot be empty.";return/^[0-9]{3,4}$/.test(e)?null:"Please enter a valid security code."}credit_card_zip_code(e){return e&&"string"==typeof e?0===e.trim().length?"Zip code cannot be empty.":null:"Zip code cannot be empty."}credit_card_pin(e){if(!e||"string"!=typeof e)return"PIN cannot be empty.";if(0===e.trim().length)return"PIN cannot be empty.";return/^[0-9]{4}$/.test(e)?null:"Please enter a valid PIN."}is_valid_uuid(e){if(!e||"string"!=typeof e)return"UUID cannot be empty.";if(0===e.trim().length)return"UUID cannot be empty.";return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)?null:"Please enter a valid UUID."}required(e,t){return null==e||"string"==typeof e&&0===e.trim().length?t?`${t} is required.`:"This field is required.":null}email(e){if(!e||"string"!=typeof e)return"Please enter a valid email address.";const t=e.trim();if(t.includes(".."))return"Please enter a valid email address.";return/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/.test(t)?null:"Please enter a valid email address."}phone(e){if(!e||"string"!=typeof e)return"Please enter a valid phone number.";return/^\+[1-9]\d{1,14}$/.test(e.trim())?null:"Please enter a valid phone number."}date(e,t="YYYY-MM-DD"){if(!e||"string"!=typeof e)return"Please enter a valid date.";const s=/^([0-9]{4})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/;if(!s.test(e))return"Please enter a valid date in YYYY-MM-DD format";const[,r,n,a]=e.match(s)||[],i=parseInt(r),o=parseInt(n),c=parseInt(a);if(!this.isValidCalendarDate(i,o,c))return"Invalid date - this date does not exist";const u=new Date(e);return u>new Date?"Date cannot be in the future":u<new Date("1900-01-01")?"Date cannot be before 1900":null}isValidCalendarDate(e,t,s){const r=new Date(e,t-1,s);return r.getFullYear()===e&&r.getMonth()===t-1&&r.getDate()===s}min_length(e,t,s){return e&&"string"==typeof e?e.length<t?s?`${s} must be at least ${t} characters long.`:`Must be at least ${t} characters long.`:null:s?`${s} is required.`:"This field is required."}max_length(e,t,s){return e&&"string"==typeof e&&e.length>t?s?`${s} must be no more than ${t} characters long.`:`Must be no more than ${t} characters long.`:null}pattern(e,t,s){return e&&"string"==typeof e&&t.test(e)?null:s||"Please enter a valid value."}numeric(e,t){return e&&"string"==typeof e?/^\d+$/.test(e.trim())?null:t?`${t} must contain only numbers.`:"Must contain only numbers.":t?`${t} is required.`:"This field is required."}alphabetic(e,t){return e&&"string"==typeof e?/^[a-zA-Z\s]+$/.test(e.trim())?null:t?`${t} must contain only letters and spaces.`:"Must contain only letters and spaces.":t?`${t} is required.`:"This field is required."}alphanumeric(e,t){return e&&"string"==typeof e?/^[a-zA-Z0-9\s]+$/.test(e.trim())?null:t?`${t} must contain only letters, numbers, and spaces.`:"Must contain only letters, numbers, and spaces.":t?`${t} is required.`:"This field is required."}url(e){if(!e||"string"!=typeof e)return"Please enter a valid URL.";const t=e.trim();try{const e=new URL(t);return""===e.hostname||e.hostname.startsWith(".")||e.hostname.endsWith(".")?"Please enter a valid URL.":null}catch{return"Please enter a valid URL."}}postal_code(e,t="US"){if(!e||"string"!=typeof e)return"Please enter a valid postal code.";const s=e.trim();switch(t.toUpperCase()){case"US":if(!/^\d{5}(-\d{4})?$/.test(s))return"Please enter a valid US ZIP code (e.g., 12345 or 12345-6789).";break;case"CA":if(!/^[A-Za-z]\d[A-Za-z] \d[A-Za-z]\d$/.test(s))return"Please enter a valid Canadian postal code (e.g., A1A 1A1).";break;case"UK":case"GB":if(!/^[A-Za-z]{1,2}\d[A-Za-z\d]?\s\d[A-Za-z]{2}$/.test(s))return"Please enter a valid UK postal code (e.g., SW1A 1AA).";break;default:if(!/^[A-Za-z0-9\s-]{3,10}$/.test(s))return"Please enter a valid postal code."}return null}}class y extends Error{constructor(e,t,s){super(`Alcore API Error ${e}: ${t}`),this.name="AlcoreApiError",this.errorCode=e,this.errorDescription=t,this.statusCode=s,Error.captureStackTrace&&Error.captureStackTrace(this,y)}isErrorCode(e){return this.errorCode===e}isAnyErrorCode(e){return e.includes(this.errorCode)}}const _={ALVIERE_CORE_NOT_INITIALIZED:"000000",UNPROCESSABLE_ENCRYPTED_DATA:"100011",WRONG_ENCRYPTED_ENDPOINT:"100012",UNDECRYPTABLE_DATA_AT_ENDPOINT:"100013",DECRYPTED_DATA_UNUSABLE_AT_ENDPOINT:"100014",WRONG_DECRYPTED_ENDPOINT:"100015",WRONG_VERSION_OR_ENDPOINT:"100016",OPERATION_HALTED:"100017",INVALID_REQUEST_PAYLOAD:"100300",INVALID_REQUEST_PAYLOAD_FIELD:"100301",INVALID_PATH_PARAMETER:"100302",INVALID_HEADER:"100303",INVALID_QUERY_PARAMETER:"100304",INVALID_JWT:"100305",AUTH_FAILED:"100306",SESSION_NOT_FOUND:"110000",PARENT_ACCOUNT_NOT_FOUND:"110001",NOT_FOUND:"110002",ACCOUNT_TYPE_NOT_SUPPORTED:"110004",UNDERLYING_API_ERROR:"115000",ACCOUNT_STATUS_NOT_ACTIVE:"115001",ACCOUNT_CHILD_FORBIDDEN:"320129",PARENT_ACCOUNT_NOT_ALLOWED:"320104",BANK_ACCOUNT_PRIMARY_REQUIRES_ACTIVE_STATUS:"340028",BANK_ACCOUNT_ALREADY_EXISTS:"340029"},m={[_.INVALID_JWT]:"Invalid authentication token. Please log in again.",[_.AUTH_FAILED]:"Authentication failed. Please check your credentials and try again.",[_.SESSION_NOT_FOUND]:"Session not found. Please log in again.",[_.PARENT_ACCOUNT_NOT_FOUND]:"Parent account not found.",[_.NOT_FOUND]:"Resource not found.",[_.ACCOUNT_TYPE_NOT_SUPPORTED]:"Account type not supported.",[_.INVALID_REQUEST_PAYLOAD]:"Invalid request payload. Please check your request and try again.",[_.INVALID_REQUEST_PAYLOAD_FIELD]:"Invalid request payload field. Please check your request and try again.",[_.INVALID_PATH_PARAMETER]:"Invalid path parameter. Please check your request and try again.",[_.INVALID_HEADER]:"Invalid header. Please check your request and try again.",[_.INVALID_QUERY_PARAMETER]:"Invalid query parameter. Please check your request and try again.",[_.UNPROCESSABLE_ENCRYPTED_DATA]:"Unprocessable encrypted data. Please check your request and try again.",[_.WRONG_ENCRYPTED_ENDPOINT]:"Wrong encrypted endpoint. Please check your request and try again.",[_.UNDECRYPTABLE_DATA_AT_ENDPOINT]:"Undecryptable data at endpoint. Please check your request and try again.",[_.DECRYPTED_DATA_UNUSABLE_AT_ENDPOINT]:"Decrypted data unusable at endpoint. Please check your request and try again.",[_.WRONG_DECRYPTED_ENDPOINT]:"Wrong decrypted endpoint. Please check your request and try again.",[_.WRONG_VERSION_OR_ENDPOINT]:"Wrong version or endpoint. Please check your request and try again.",[_.OPERATION_HALTED]:"Operation halted. Please check your request and try again.",[_.UNDERLYING_API_ERROR]:"Underlying API Error. ",[_.ACCOUNT_STATUS_NOT_ACTIVE]:"Account status not active. Please check your request and try again.",[_.ACCOUNT_CHILD_FORBIDDEN]:"Used Account can't be used to create a child account.",[_.PARENT_ACCOUNT_NOT_ALLOWED]:"Parent account not allowed. Please check your request and try again.",[_.BANK_ACCOUNT_PRIMARY_REQUIRES_ACTIVE_STATUS]:"Only ACTIVE bank accounts can be set as primary.",[_.BANK_ACCOUNT_ALREADY_EXISTS]:"This bank account has already been added to your account."};function f(e){return m[e]||"An unexpected error occurred. Please try again."}const w=[_.INVALID_JWT,_.AUTH_FAILED,_.SESSION_NOT_FOUND,_.UNPROCESSABLE_ENCRYPTED_DATA,_.WRONG_ENCRYPTED_ENDPOINT,_.UNDECRYPTABLE_DATA_AT_ENDPOINT,_.OPERATION_HALTED,_.ALVIERE_CORE_NOT_INITIALIZED,_.UNDERLYING_API_ERROR,_.ACCOUNT_STATUS_NOT_ACTIVE,_.ACCOUNT_CHILD_FORBIDDEN,_.PARENT_ACCOUNT_NOT_ALLOWED];class E{constructor(e,t,s){this.endpoint="/alcore",this.jwt=e,this.cryptor=t,this.domain=o(),this.logger=s,this.logger.debug(`🔐 AlcoreBase initialized with domain: ${this.domain}`)}async send(e,t,s){const r={method:e,endpoint:t,payload:JSON.stringify(s)};let n;this.logger.debug("🌐 AlcoreBase: Preparing to send request"),this.logger.debug("🌐 Method: "+e),this.logger.debug("🌐 Endpoint: "+t),this.logger.debug("🌐 Domain: "+(this.domain||"undefined")),this.logger.debug("🌐 JWT Token: "+(this.jwt?"✅ Present":"❌ Missing")),this.logger.debug("🌐 Payload size: "+JSON.stringify(s).length+" chars"),this.logger.debug(this.jwt),this.logger.debug("DATA TO SEND before encrypt"),this.logger.debug(s);try{n=await this.cryptor.encrypt(r),this.logger.debug("🔐 Encryption successful")}catch(i){throw this.logger.debug("❌ Encryption failed: "+(i instanceof Error?i.message:"Unknown error")),i}this.logger.debug("BASE GATEWAY: posting to "+this.endpoint),this.logger.debug(n);const a=this.domain+this.endpoint;this.logger.debug("🌐 Full URL: "+a);try{const e=await fetch(a,{method:"post",headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.jwt,Version:"2021-11-18"},body:JSON.stringify(n)});if(this.logger.debug("🌐 Response received - Status: "+e.status+" "+e.statusText),this.logger.debug("🌐 Response OK: "+e.ok),!e.ok){let t=await e.json();t.p&&(t=await this.decrypt(t));const s=500===e.status?_.UNDERLYING_API_ERROR:t.error_code,r=t.error_description||f(s);throw this.logger.debug(`❌ API Error - Code: ${s}, Description: ${r}`),new y(s,r,e.status)}return e}catch(o){throw this.logger.debug("❌ Fetch failed: "+(o instanceof Error?o.message:"Unknown error")),o}}async decrypt(e){return this.cryptor.decrypt(e)}}function A(e){const t={};for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)){const r=e[s];["",null,void 0].includes(r)||(t[s]=r)}return t}function T(e){if(e&&"object"==typeof e&&("error_code"in e||"error_description"in e)){const t=e.error_description||"Unknown API error",s=e.error_code||"UNKNOWN";throw new Error(`${s}: ${t}`)}return e}function b(e){try{const t=e.split(".");if(3!==t.length)return null;const s=t[1],r=atob(s.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(r)}catch(t){return null}}function P(e){const t=b(e);return t?{domain:t.api_domain||"https://api.dev.alviere.com"}:{}}function C(e){const t=b(e);return t&&t.sub||null}class N extends E{constructor(e,t,s){super(e,t,s)}async add_card(e,t){const s=`/accounts/${e}/payment-methods/cards`,r=await this.send("POST",s,t),n=await r.json();return T(await this.decrypt(n))}async add_bank_account(e,t){const s=`/accounts/${e}/payment-methods/bank-accounts`,r=await this.send("POST",s,t),n=await r.json();return T(await this.decrypt(n))}async get_bank_accounts(e){const t=`/accounts/${e}/payment-methods/bank-accounts`,s=await this.send("GET",t,{}),r=await s.json();return T(await this.decrypt(r))}async delete_bank_account(e,t){const s=`/accounts/${e}/payment-methods/bank-accounts/${t}`;return T(await this.send("DELETE",s,{}))}async update_bank_account(e,t,s){const r=`/payment-methods/bank-accounts/${t}`,n=await this.send("PATCH",r,s),a=await n.json();return T(await this.decrypt(a))}}class D extends E{constructor(e,t,s){super(e,t,s)}async listWallets(e,t){const s=`/accounts/${e}/wallets${t?"?"+new URLSearchParams(Object.entries(t).filter(([e,t])=>void 0!==t)):""}`,r=await this.send("GET",s,{}),n=await r.json();return T(await this.decrypt(n))}async loadFunds(e,t){const s=`/wallets/${e}/load`,r=await this.send("POST",s,t),n=await r.json();return T(await this.decrypt(n))}}class R extends E{constructor(e,t,s){super(e,t,s)}async createPaymentInstrument(e){const t=await this.send("POST","/payments/payment-instruments",e),s=await t.json();return T(await this.decrypt(s))}async getPaymentInstrument(e){const t=`/payments/payment-instruments/${e}`,s=await this.send("GET",t,{}),r=await s.json();return T(await this.decrypt(r))}async deletePaymentInstrument(e){const t=`/payments/payment-instruments/${e}`;await this.send("DELETE",t,{})}async debitFunds(e){const t=await this.send("POST","/payments/debit",e),s=await t.json();return T(await this.decrypt(s))}async listCards(e,t){const s=`/accounts/${e}/payment-methods/cards${t?"?"+new URLSearchParams(Object.entries(t).filter(([e,t])=>void 0!==t)):""}`,r=await this.send("GET",s,{}),n=await r.json();return T(await this.decrypt(n))}}class I extends E{constructor(e,t,s){super(e,t,s),this.logger.debug("🔐 AccountsGateway initialized")}async createAccount(e){const t=await this.send("POST","/accounts",e),s=await t.json();return T(await this.decrypt(s))}async getAccount(e){const t=`/accounts/${e}`,s=await this.send("GET",t,{}),r=await s.json();return T(await this.decrypt(r))}async updateAccount(e,t){const s=`/accounts/${e}`,r=await this.send("PATCH",s,t),n=await r.json();return T(await this.decrypt(n))}async deleteAccount(e){const t=`/accounts/${e}`;await this.send("DELETE",t,{})}async listAccounts(e){const t=`/accounts${e?"?"+new URLSearchParams(Object.entries(e).filter(([e,t])=>void 0!==t)):""}`,s=await this.send("GET",t,{}),r=await s.json();return T(await this.decrypt(r))}async activateAccount(e){const t=`/accounts/${e}/activate`;await this.send("POST",t,{})}async deactivateAccount(e){const t=`/accounts/${e}/deactivate`;await this.send("POST",t,{})}async manageOnboarding(e,t){const s=`/accounts/${e}/onboarding`;await this.send("PUT",s,{action:t})}async createAddress(e,t){const s=`/accounts/${e}/addresses`,r=await this.send("POST",s,t),n=await r.json();return T(await this.decrypt(n))}async getAddresses(e,t){const s=`/accounts/${e}/addresses${t?"?"+new URLSearchParams(Object.entries(t).filter(([e,t])=>void 0!==t)):""}`,r=await this.send("GET",s,{}),n=await r.json();return T(await this.decrypt(n))}async updateAddress(e,t,s){const r=`/accounts/${e}/addresses/${t}`,n=await this.send("PATCH",r,s),a=await n.json();return T(await this.decrypt(a))}async deleteAddress(e,t){const s=`/accounts/${e}/addresses/${t}`;await this.send("DELETE",s,{})}async createDossier(e,t){const s=`/accounts/${e}/dossiers`,r=await this.send("POST",s,t),n=await r.json();return T(await this.decrypt(n))}async getDossiers(e,t){const s=`/accounts/${e}/dossiers${t?"?"+new URLSearchParams(Object.entries(t).filter(([e,t])=>void 0!==t)):""}`,r=await this.send("GET",s,{}),n=await r.json();return T(await this.decrypt(n))}async getDossier(e,t){const s=`/accounts/${e}/dossiers/${t}`,r=await this.send("GET",s,{}),n=await r.json();return T(await this.decrypt(n))}async updateDossier(e,t,s){const r=`/accounts/${e}/dossiers/${t}`,n=await this.send("PUT",r,s),a=await n.json();return T(await this.decrypt(a))}async replaceDossier(e,t,s){const r=`/accounts/${e}/dossiers/${t}`,n=await this.send("PATCH",r,s),a=await n.json();return T(await this.decrypt(a))}async deleteDossier(e,t){const s=`/accounts/${e}/dossiers/${t}`;await this.send("DELETE",s,{})}}class O extends E{constructor(e,t,s){super(e,t,s),this.logger.debug("🔐 AuthGateway initialized")}async generateScopedToken(e){this.logger.debug("🔐 AuthGateway: Generating scoped token"),this.logger.debug("🌐 Endpoint: /v3/auth"),this.logger.debug("🌐 Account UUID: "+e.account_uuid);const t=await this.send("POST","/v3/auth",e),s=await this.decrypt(await t.json());return this.logger.debug("✅ Scoped token generated successfully"),s}}class S{constructor(e){this.gateway=e}async listWallets(e,t){return this.gateway.listWallets(e,t)}async loadFunds(e,t){return this.gateway.loadFunds(e,t)}}class v{constructor(e){this.gateway=e}async createPaymentInstrument(e){return this.gateway.createPaymentInstrument(e)}async getPaymentInstrument(e){return this.gateway.getPaymentInstrument(e)}async deletePaymentInstrument(e){return this.gateway.deletePaymentInstrument(e)}async debitFunds(e){return this.gateway.debitFunds(e)}async listCards(e,t){return this.gateway.listCards(e,t)}}class x{constructor(e){this.gateway=e}async createAccount(e){return this.gateway.createAccount(e)}async getAccount(e){return this.gateway.getAccount(e)}async updateAccount(e,t){return this.gateway.updateAccount(e,t)}async deleteAccount(e){return this.gateway.deleteAccount(e)}async listAccounts(e){return this.gateway.listAccounts(e)}async activateAccount(e){return this.gateway.activateAccount(e)}async deactivateAccount(e){return this.gateway.deactivateAccount(e)}async manageOnboarding(e,t){return this.gateway.manageOnboarding(e,t)}async createAddress(e,t){return this.gateway.createAddress(e,t)}async getAddresses(e,t){return this.gateway.getAddresses(e,t)}async updateAddress(e,t,s){return this.gateway.updateAddress(e,t,s)}async deleteAddress(e,t){return this.gateway.deleteAddress(e,t)}async createDossier(e,t){return this.gateway.createDossier(e,t)}async getDossiers(e,t){return this.gateway.getDossiers(e,t)}async getDossier(e,t){return this.gateway.getDossier(e,t)}async updateDossier(e,t,s){return this.gateway.updateDossier(e,t,s)}async replaceDossier(e,t,s){return this.gateway.replaceDossier(e,t,s)}async deleteDossier(e,t){return this.gateway.deleteDossier(e,t)}}class k{constructor(e,t){this.gateway=e,this.logger=t}async processAddCard(e,t){this.logger.debug("PaymentProcessor: Starting add card processing"),this.logger.debug("PaymentProcessor: Request data: "+JSON.stringify(t,null,2));try{const s=await this.gateway.add_card(e,t);return this.logger.debug("PaymentProcessor: Add card processing completed successfully"),s}catch(s){throw this.logger.debug("PaymentProcessor: Add card processing failed"),this.logger.debug("PaymentProcessor: Error details: "+JSON.stringify(s)),s}}validateRequest(e){const t=["external_id","pan","exp_year","exp_month","postal_code","security_code"];for(const s of t)if(!e[s])throw new Error(`Missing required field: ${s}`);this.logger.debug("PaymentProcessor: Request validation passed")}async processAddCardWithValidation(e,t){return this.logger.debug("PaymentProcessor: Starting add card processing with validation"),this.validateRequest(t),await this.processAddCard(e,t)}async processAddBankAccount(e,t){this.logger.debug("PaymentProcessor: Starting add bank account processing"),this.logger.debug("PaymentProcessor: Request data: "+JSON.stringify(t,null,2));try{const s=await this.gateway.add_bank_account(e,t);return this.logger.debug("PaymentProcessor: Add bank account processing completed successfully"),s}catch(s){throw this.logger.debug("PaymentProcessor: Add bank account processing failed"),this.logger.debug("PaymentProcessor: Error details: "+JSON.stringify(s)),s}}validateBankAccountRequest(e){const t=["external_id","country","currency","bank_account_details"];for(const s of t)if(!e[s])throw new Error(`Missing required field: ${s}`);this.logger.debug("PaymentProcessor: Bank account request validation passed")}async processAddBankAccountWithValidation(e,t){return this.logger.debug("PaymentProcessor: Starting add bank account processing with validation"),this.validateBankAccountRequest(t),await this.processAddBankAccount(e,t)}async processGetBankAccounts(e){this.logger.debug("PaymentProcessor: Starting get bank accounts processing");try{const t=await this.gateway.get_bank_accounts(e);return this.logger.debug("PaymentProcessor: Get bank accounts processing completed successfully"),t}catch(t){throw this.logger.debug("PaymentProcessor: Get bank accounts processing failed"),this.logger.debug("PaymentProcessor: Error details: "+JSON.stringify(t)),t}}async processDeleteBankAccount(e,t){this.logger.debug("PaymentProcessor: Starting delete bank account processing");try{const s=await this.gateway.delete_bank_account(e,t);return this.logger.debug("PaymentProcessor: Delete bank account processing completed successfully"),s}catch(s){throw this.logger.debug("PaymentProcessor: Delete bank account processing failed"),this.logger.debug("PaymentProcessor: Error details: "+JSON.stringify(s)),s}}async processUpdateBankAccount(e,t,s){this.logger.debug("PaymentProcessor: Starting update bank account processing"),this.logger.debug("PaymentProcessor: Request data: "+JSON.stringify(s,null,2));try{const r=await this.gateway.update_bank_account(e,t,s);return this.logger.debug("PaymentProcessor: Update bank account processing completed successfully"),r}catch(r){throw this.logger.debug("PaymentProcessor: Update bank account processing failed"),this.logger.debug("PaymentProcessor: Error details: "+JSON.stringify(r)),r}}}class U{constructor(e){this.gateway=e}async getBankInfo(e){return this.gateway.getBankInfo(e)}}class L{constructor(e){this.gateway=e}async getLegalTexts(e,t){return this.gateway.getLegalTexts(e,t)}}class $ extends E{constructor(e,t,s){super(e,t,s),this.logger.debug("🔐 BankInfoGateway initialized")}async getBankInfo(e){const t=`/v3/bank-info?routing_number=${e}`,s=await this.send("GET",t,{}),r=await s.json();return T(await this.decrypt(r))}}class F extends E{constructor(e,t,s){super(e,t,s),this.logger.debug("🔐 LegalTextsGateway initialized")}async getLegalTexts(e,t){const s=new URLSearchParams({type:e});t&&s.set("version",t);const r=`/v3/legal-texts?${s.toString()}`;this.logger.debug(`endpoint -> ${r}`);const n=await this.send("GET",r,{}),a=await n.json();return T(await this.decrypt(a))}}var V=(e=>(e.PASSPORT="PASSPORT",e.ID_DOCUMENT_FRONT="ID_DOCUMENT_FRONT",e.ID_DOCUMENT_BACK="ID_DOCUMENT_BACK",e.DRIVER_LICENSE_FRONT="DRIVER_LICENSE_FRONT",e.DRIVER_LICENSE_BACK="DRIVER_LICENSE_BACK",e.SELFIE="SELFIE",e.PROOF_OF_ADDRESS="PROOF_OF_ADDRESS",e.PROOF_OF_FUNDS="PROOF_OF_FUNDS",e.MC_DOCUMENT_FRONT="MC_DOCUMENT_FRONT",e.MC_DOCUMENT_BACK="MC_DOCUMENT_BACK",e.INE_FRONT="INE_FRONT",e.INE_BACK="INE_BACK",e.ARTICLES_OF_INCORPORATION="ARTICLES_OF_INCORPORATION",e.CERTIFICATE_OF_GOOD_STANDING="CERTIFICATE_OF_GOOD_STANDING",e.ORG_CHART="ORG_CHART",e.UBO_FORM="UBO_FORM",e.REG_GG_ATTESTATION="REG_GG_ATTESTATION",e))(V||{}),G=(e=>(e.CREATED="CREATED",e.PENDING="PENDING",e.MANUAL_REVIEW="MANUAL_REVIEW",e.VERIFIED="VERIFIED",e.EXPIRED="EXPIRED",e.REJECTED="REJECTED",e.FAILED="FAILED",e.DELETED="DELETED",e))(G||{});class M{constructor(){this.eventListeners=new Map,this.configs=new Map}sanitize(e,t){return e.trim()}getRawValue(e,t){return e.replace(/\s/g,"")}mount(e,t){const s={...this.getDefaultConfig(),...t};this.configs.set(e,s);const r=new Map;this.eventListeners.set(e,r),e instanceof HTMLInputElement&&this.setupInputElement(e,s),this.onMount?.(e,s)}unmount(e){const t=this.eventListeners.get(e);t&&(t.forEach((t,s)=>{e.removeEventListener(s,t)}),this.eventListeners.delete(e)),this.configs.delete(e),this.onUnmount?.(e)}setupInputElement(e,t){const s=this.eventListeners.get(e);if(t.formatOnType){const r=e=>{const s=e.target,r=this.format(s.value,t);r.formattedValue!==s.value&&(s.value=r.formattedValue,void 0!==r.cursorPosition&&s.setSelectionRange(r.cursorPosition,r.cursorPosition))};e.addEventListener("input",r),s.set("input",r)}if(t.validateOnBlur){const r=e=>{const s=e.target,r=this.validate(s.value,t);this.displayValidation(s,r,t)};e.addEventListener("blur",r),s.set("blur",r)}if(t.validateOnType){const r=e=>{const s=e.target,r=this.validate(s.value,t);this.displayValidation(s,r,t)};e.addEventListener("input",r),s.set("input-validate",r)}t.placeholder&&(e.placeholder=t.placeholder),t.maxLength&&(e.maxLength=t.maxLength),t.ariaLabel&&e.setAttribute("aria-label",t.ariaLabel),t.ariaDescribedBy&&e.setAttribute("aria-describedby",t.ariaDescribedBy)}displayValidation(e,t,s){s.showErrorsInline&&(s.errorClassName&&e.classList.remove(s.errorClassName),s.successClassName&&e.classList.remove(s.successClassName),t.isValid&&s.successClassName?e.classList.add(s.successClassName):!t.isValid&&s.errorClassName&&e.classList.add(s.errorClassName),this.updateErrorMessage(e,t.error))}updateErrorMessage(e,t){let s=e.parentElement?.querySelector(".alviere-field-error");t?(s||(s=document.createElement("div"),s.className="alviere-field-error",e.parentElement?.appendChild(s)),s.textContent=t,s.style.display="block"):s&&(s.style.display="none")}getDefaultConfig(){return{validateOnBlur:!0,formatOnType:!0,showErrorsInline:!0,errorClassName:"alviere-field-error",successClassName:"alviere-field-success"}}}const j={visa:{name:"Visa",pattern:/^4/,gaps:[4,8,12],lengths:[13,16,19],code:{name:"CVV",size:3}},mastercard:{name:"Mastercard",pattern:/^(5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)/,gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},amex:{name:"American Express",pattern:/^3[47]/,gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},diners:{name:"Diners Club",pattern:/^3[0689]/,gaps:[4,10],lengths:[14],code:{name:"CVV",size:3}},discover:{name:"Discover",pattern:/^6([045]|22)/,gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{name:"JCB",pattern:/^35/,gaps:[4,8,12],lengths:[16],code:{name:"CVV",size:3}}};class q{constructor(e={}){if(this.authToken="",this.business_uuid="",this.account_uuid="",this.cryptor=null,this.gateways=new Map,this.jwt=e.jwt||"",this.debug=e.debug||!1,this.publicCertificate=e.publicCertificate||"",this.publicCertificateId=e.publicCertificateId||"",this.business_uuid=e.business_uuid||"",this.logger=new t(this.debug),this.logger.debug(`🔐 AlviereCore constructor called with config: ${JSON.stringify(e)}`),this.jwt){const t=P(this.jwt);e.jwt&&n({...t,certificate:{id:this.publicCertificateId,public_key:this.publicCertificate}});const s=C(this.jwt);s?(this.account_uuid=s,this.logger.debug(`🔐 Extracted account_uuid from JWT sub field: ${this.account_uuid}`)):this.logger.debug("⚠️ No account_uuid found in JWT sub field"),this.authToken=this.jwt,this.logger.debug("🔐 Using JWT as auth token for API authentication")}e.alviere&&n(e.alviere)}configure(e){const s=e.jwt&&e.jwt!==this.jwt;if(e.jwt){this.jwt=e.jwt;const t=P(e.jwt);t.domain&&n(t);const s=C(e.jwt);this.logger.debug(`🔐 Extracted account_uuid from JWT sub field: ${s}`),s?(this.account_uuid=s,this.logger.debug(`🔐 Updated account_uuid from JWT sub field: ${this.account_uuid}`)):this.logger.debug("⚠️ No account_uuid found in new JWT sub field"),this.authToken=this.jwt,this.logger.debug("🔐 Updated JWT as auth token for API authentication")}return void 0!==e.business_uuid&&(this.business_uuid=e.business_uuid,this.logger.debug(`🔐 Updated business_uuid: ${this.business_uuid}`)),"boolean"==typeof e.debug&&e.debug!==this.debug&&(this.debug=e.debug,this.logger=new t(this.debug),this.logger.debug("🔐 Debug mode changed to: "+this.debug)),s&&(this.logger.debug("🔐 JWT changed - clearing gateway cache and cryptor"),this.gateways.clear(),this.cryptor=null),e.alviere&&n(e.alviere),this}getOrCreateCryptor(){if(!this.cryptor){const e=c();if(!e||""===e.trim())throw new Error('🔐 Cryptor initialization failed: RSA public key not available. Please ensure JWT is configured with a valid RSA key before attempting encryption operations. Call alviereCore.configure({ jwt: "your-jwt-with-rsa-key" }) first.');this.logger.debug("🔐 Creating Cryptor instance with RSA key"),this.cryptor=new h(this.logger)}return this.cryptor}createPaymentsGateway(){return this.gateways.has("payments")||this.gateways.set("payments",new N(this.authToken,this.getOrCreateCryptor(),this.logger)),this.gateways.get("payments")}createPaymentsService(){const e=this.createPaymentsGateway();return new k(e,this.logger)}createWalletsService(){return this.gateways.has("wallets")||this.gateways.set("wallets",new D(this.authToken,this.getOrCreateCryptor(),this.logger)),new S(this.gateways.get("wallets"))}createPaymentInstrumentsService(){return this.gateways.has("paymentInstruments")||this.gateways.set("paymentInstruments",new R(this.authToken,this.getOrCreateCryptor(),this.logger)),new v(this.gateways.get("paymentInstruments"))}createAccountsService(){return this.gateways.has("accounts")||this.gateways.set("accounts",new I(this.authToken,this.getOrCreateCryptor(),this.logger)),new x(this.gateways.get("accounts"))}createAuthGateway(){return this.gateways.has("auth")||this.gateways.set("auth",new O(this.authToken,this.getOrCreateCryptor(),this.logger)),this.gateways.get("auth")}createBankInfoService(){return this.gateways.has("bankInfo")||this.gateways.set("bankInfo",new $(this.authToken,this.getOrCreateCryptor(),this.logger)),new U(this.gateways.get("bankInfo"))}createLegalTextsService(){return this.gateways.has("legalTexts")||this.gateways.set("legalTexts",new F(this.authToken,this.getOrCreateCryptor(),this.logger)),new L(this.gateways.get("legalTexts"))}async generateScopedToken(e,t=!0){this.logger.debug(`🔐 Generating scoped token for account: ${e}`),this.logger.debug(`🔐 Auto-update: ${t}`);const s=this.createAuthGateway(),r=await s.generateScopedToken({account_uuid:e});return this.logger.debug("✅ Scoped token generated successfully"),t&&r.access_token&&(this.logger.debug("🔄 Auto-updating SDK with new scoped token"),this.configure({jwt:r.access_token})),r.access_token}getLogger(){return this.logger}getCryptor(){return this.getOrCreateCryptor()}clearCache(){this.gateways.clear()}getAccountUuid(){return this.account_uuid}getBusinessUuid(){return this.business_uuid}isFirstTimeUser(){if(!this.account_uuid||!this.business_uuid)return this.logger.debug("🔐 Cannot determine first-time user status: missing account_uuid or business_uuid"),!1;const e=this.account_uuid===this.business_uuid;return this.logger.debug(`🔐 First-time user check: ${e} (account: ${this.account_uuid}, business: ${this.business_uuid})`),e}isScopedToPayee(){return!(!this.account_uuid||!this.business_uuid)&&this.account_uuid!==this.business_uuid}static createValidator(e=!1){const s=new t(e);return new p(s)}static createLogger(e=!1){return new t(e)}static createCryptor(e){return new h(e)}}exports.ALVIERE_DOMAIN=d,exports.AccountsApiService=x,exports.AccountsGateway=I,exports.AlcoreApiError=y,exports.AlcoreErrorCodes=_,exports.AlcoreErrorMessages=m,exports.AlviereCore=q,exports.AuthGateway=O,exports.BankInfoGateway=$,exports.BaseFieldPlugin=M,exports.CERTIFICATE_ID=g,exports.CardNumberPlugin=class extends M{constructor(){super(...arguments),this.name="card-number",this.version="1.0.0",this.description="Credit card number formatting and validation",this.currentCardType=null}validate(e,t){const s=this.sanitize(e);if(!s)return{isValid:!1,error:"Card number is required"};if(!/^\d+$/.test(s))return{isValid:!1,error:"Card number must contain only digits"};const r=this.detectCardType(s);if(this.currentCardType=r,!r)return{isValid:!1,error:"Invalid card number format"};if(!r.lengths.includes(s.length)){const e=r.lengths.join(" or ");return{isValid:!1,error:`${r.name} card numbers must be ${e} digits long`}}if(!this.luhnCheck(s))return{isValid:!1,error:"Invalid card number"};if(t?.customValidation){const s=t.customValidation(e);if(s)return{isValid:!1,error:s}}return{isValid:!0,suggestions:[`${r.name} ending in ${s.slice(-4)}`]}}format(e,t){const s=this.sanitize(e),r=this.detectCardType(s)||j.visa;let n="",a=0;for(let i=0;i<s.length;i++)r.gaps.includes(i)&&(n+=" ",a++),n+=s[i];return{formattedValue:n,cursorPosition:s.length+a}}sanitize(e,t){return e.replace(/\D/g,"")}getRawValue(e,t){return this.sanitize(e)}canHandle(e){return["card-number","cardNumber","pan","credit-card"].includes(e)}getDefaultConfig(){return{...super.getDefaultConfig(),validateOnType:!0,formatOnType:!0,placeholder:"1234 5678 9012 3456",maxLength:23,ariaLabel:"Credit card number"}}detectCardType(e){for(const[t,s]of Object.entries(j))if(s.pattern.test(e))return s;return null}getCardType(){return this.currentCardType}luhnCheck(e){let t=0,s=!1;for(let r=e.length-1;r>=0;r--){let n=parseInt(e.charAt(r),10);s&&(n*=2,n>9&&(n-=9)),t+=n,s=!s}return t%10==0}onMount(e,t){if(e instanceof HTMLInputElement){const t=t=>{const s=t.target,r=this.sanitize(s.value),n=this.detectCardType(r);if(n!==this.currentCardType&&(this.currentCardType=n,e.dispatchEvent(new CustomEvent("cardTypeChange",{detail:{cardType:n,element:e},bubbles:!0}))),n){const e=Math.max(...n.lengths)+n.gaps.length;s.maxLength=e}};e.addEventListener("input",t);const s=this.eventListeners.get(e);s&&s.set("cardTypeDetection",t)}}},exports.CriticalErrorCodes=w,exports.Cryptor=h,exports.DEFAULT_CONFIG=s,exports.DossierStatus=G,exports.DossierType=V,exports.FieldPluginRegistry=class{constructor(e={}){this.plugins=new Map,this.fieldTypeCache=new Map,this.config={autoRegisterBuiltins:!0,enablePluginValidation:!0,...e},this.logger=e.logger,this.config.autoRegisterBuiltins&&this.registerBuiltinPlugins(),this.logger?.debug("🔐 FieldPluginRegistry initialized")}register(e){this.config.enablePluginValidation&&this.validatePlugin(e),this.plugins.set(e.name,e),this.fieldTypeCache.clear(),this.logger?.debug(`FieldPluginRegistry: Registered plugin '${e.name}' v${e.version}`)}unregister(e){const t=this.plugins.delete(e);return t&&(this.fieldTypeCache.clear(),this.logger?.debug(`FieldPluginRegistry: Unregistered plugin '${e}'`)),t}getPlugin(e){return this.plugins.get(e)}getPluginForFieldType(e){if(this.fieldTypeCache.has(e))return this.fieldTypeCache.get(e);for(const s of this.plugins.values())if(s.canHandle(e))return this.fieldTypeCache.set(e,s),s;const t=this.plugins.get("text");return t?(this.fieldTypeCache.set(e,t),t):void 0}getAllPlugins(){return Array.from(this.plugins.values())}getPluginNames(){return Array.from(this.plugins.keys())}hasPlugin(e){return this.plugins.has(e)}getSupportedFieldTypes(){const e=new Set,t=["card-number","cardNumber","pan","expiry","expiry-date","expiryDate","cvv","cvc","code","zip","zip-code","postal-code","text","name","cardholder-name"];for(const s of t)this.getPluginForFieldType(s)&&e.add(s);return Array.from(e)}mountPlugin(e,t,s){const r=this.getPluginForFieldType(t);if(!r)return this.logger?.warn(`FieldPluginRegistry: No plugin found for field type '${t}'`),null;try{return r.mount(e,s),this.logger?.debug(`FieldPluginRegistry: Mounted '${r.name}' plugin on element for field type '${t}'`),r}catch(n){return this.logger?.error(`FieldPluginRegistry: Failed to mount plugin '${r.name}': ${n instanceof Error?n.message:String(n)}`),null}}unmountPlugin(e,t){const s=this.getPluginForFieldType(t);if(!s)return!1;try{return s.unmount(e),this.logger?.debug(`FieldPluginRegistry: Unmounted '${s.name}' plugin from element`),!0}catch(r){return this.logger?.error(`FieldPluginRegistry: Failed to unmount plugin '${s.name}': ${r instanceof Error?r.message:String(r)}`),!1}}getStats(){return{totalPlugins:this.plugins.size,pluginNames:this.getPluginNames(),supportedFieldTypes:this.getSupportedFieldTypes(),cacheSize:this.fieldTypeCache.size}}clearCaches(){this.fieldTypeCache.clear()}registerBuiltinPlugins(){const e=[];for(const t of e)this.register(t)}validatePlugin(e){if(!e.name||"string"!=typeof e.name)throw new Error("Plugin must have a valid name");if(!e.version||"string"!=typeof e.version)throw new Error("Plugin must have a valid version");if("function"!=typeof e.validate)throw new Error("Plugin must implement validate method");if("function"!=typeof e.format)throw new Error("Plugin must implement format method");if("function"!=typeof e.sanitize)throw new Error("Plugin must implement sanitize method");if("function"!=typeof e.canHandle)throw new Error("Plugin must implement canHandle method");if("function"!=typeof e.mount)throw new Error("Plugin must implement mount method");if("function"!=typeof e.unmount)throw new Error("Plugin must implement unmount method");this.plugins.has(e.name)&&this.logger?.warn(`FieldPluginRegistry: Plugin '${e.name}' is already registered and will be replaced`)}},exports.Logger=t,exports.NewAccountRequest=function(e){return A({external_id:e.external_id,account_type:e.account_type,profile:e.profile,information:e.information,primary_address:e.primary_address,business_account_uuid:e.business_account_uuid,parent_account_uuid:e.parent_account_uuid,metadata:e.metadata})},exports.NewAddBankAccountRequest=function(e){const{external_id:t,country:s,currency:r,bank_account_details:n,primary:a,metadata:i}=e;let o={external_id:t,country:s,currency:r,bank_account_details:n,primary:a,metadata:i};return o=A(o),o},exports.NewAddCardRequest=function(e){const{external_id:t,name:s,pan:r,expiry:n,code:a,zip:i}=e,o=n.split("/"),c=o[0];let u={external_id:t,pan:r,exp_year:o[1],exp_month:c,security_code:a,postal_code:i,name_on_card:s};return u=A(u),u},exports.NewAddressRequest=function(e){return A({label:e.label,line_1:e.line_1,line_2:e.line_2,city:e.city,state:e.state,postal_code:e.postal_code,country:e.country,primary:e.primary,external_id:e.external_id})},exports.NewCardInstrumentFromForm=function(e,t,s,r,n,a,i,o,c,u,d,l){const g=t.split("/"),h=g[0],p=g[1];return{pan:e.replace(/\s/g,""),exp_month:h,exp_year:p,security_code:s,name_on_card:r,phone_number:d,email_address:l,billing_address:{line_1:n,line_2:u,city:a,state:i,postal_code:o,country:c}}},exports.NewCreditFundsRequest=function(e){return A({amount:e.amount,currency:e.currency,external_id:e.external_id,vault_name:e.vault_name,metadata:e.metadata})},exports.NewDebitFundsRequest=function(e,t,s,r,n,a="AUTHCAP",i,o,c,u,d){return{wallet_uuid:e,external_id:t,amount:s,currency:r,auth_type:a,payment_instrument_uuid:i,payment_instrument:o,description:c,merchant_details:n,"3ds_options":u,metadata:d}},exports.NewDossierReplaceRequest=function(e){return A({external_id:e.external_id,documents:e.documents,metadata:e.metadata})},exports.NewDossierRequest=function(e){return A({external_id:e.external_id,documents:e.documents,metadata:e.metadata})},exports.NewGenerateMobileTokenRequest=function(e){return A({account_uuid:e.account_uuid,with_plaid_sdk_token:e.with_plaid_sdk_token})},exports.NewGeneratePdsTokenRequest=function(e){return A({wallet_uuid:e.wallet_uuid})},exports.NewGeneratePlaidTokenRequest=function(e){return A({account_uuid:e.account_uuid,platform:e.platform,payment_method_uuid:e.payment_method_uuid})},exports.NewGenerateScopedTokenRequest=function(e){return{account_uuid:e.account_uuid}},exports.NewGenerateWebSessionRequest=function(e){return A({account_uuid:e.account_uuid})},exports.NewLoadFundsRequest=function(e){return A({payment_method_uuid:e.payment_method_uuid,amount:e.amount,external_id:e.external_id,service_fees:e.service_fees,transaction_options:e.transaction_options,metadata:e.metadata})},exports.NewPaymentInstrumentRequest=function(e,t,s,r,n){return{account_uuid:e,external_id:r,payment_instrument_type:t,payment_instrument_details:{card:s},metadata:n}},exports.NewPromoFundsRequest=function(e){return A({amount:e.amount,external_id:e.external_id,description:e.description,metadata:e.metadata})},exports.NewSendFundsRequest=function(e){return A({destination_wallet_uuid:e.destination_wallet_uuid,external_id:e.external_id,amount:e.amount,service_fees:e.service_fees,description:e.description,metadata:e.metadata})},exports.NewTransferFundsRequest=function(e){return A({beneficiary_uuid:e.beneficiary_uuid,payout_method_uuid:e.payout_method_uuid,amount:e.amount,service_fees:e.service_fees,description:e.description,external_id:e.external_id,metadata:e.metadata})},exports.NewWithdrawFundsRequest=function(e){return A({payment_method_uuid:e.payment_method_uuid,amount:e.amount,external_id:e.external_id,service_fees:e.service_fees,transaction_options:e.transaction_options,metadata:e.metadata})},exports.PaymentInstrumentsApiService=v,exports.PaymentInstrumentsGateway=R,exports.PaymentProcessor=k,exports.PaymentsGateway=N,exports.RSA_PUB_KEY=l,exports.Validator=p,exports.WalletsApiService=S,exports.WalletsGateway=D,exports.createDefaultMerchantDetails=function(){return{name:"Demo Merchant Store",merchant_id:"DEMO_MERCHANT_001"}},exports.decodeJWTPayload=b,exports.default=q,exports.extractAccountUuidFromJWT=C,exports.extractAlviereConfigFromJWT=P,exports.getALVIERE_DOMAIN=o,exports.getCERTIFICATE_ID=u,exports.getErrorMessage=f,exports.getJWTExpiration=function(e){const t=b(e);return t&&t.exp?new Date(1e3*t.exp):null},exports.getJWTRefreshTime=function(e,t=.05){const s=b(e);if(!s||!s.exp)return null;const r=1e3*s.exp;if(s.iat){const e=r-1e3*s.iat;return e<=0?null:r-e*t}const n=Date.now(),a=r-n;return a<=0?null:n+a*(1-t)},exports.getRSA_PUB_KEY=c,exports.getRuntimeConfig=function(){return r},exports.getSanitizedBody=A,exports.initializeFromEnvironment=i,exports.isCriticalError=function(e){return w.includes(e)},exports.isJWTExpired=function(e){const t=b(e);if(!t||!t.exp)return!0;const s=Math.floor(Date.now()/1e3);return t.exp<s},exports.setRuntimeConfig=n,exports.throwIfApiError=T;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|