@tonder.io/ionic-lite-sdk 0.0.68-beta.DEV-2106.10 → 0.0.68-beta.DEV-2106.48d18dd
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 +3 -2
- package/dist/index.js +1 -1
- package/dist/shared/utils/appError.d.ts +2 -0
- package/package.json +1 -1
- package/src/classes/liteCheckout.ts +4 -5
- package/src/helpers/card_on_file.ts +11 -1
- package/src/shared/utils/appError.ts +48 -4
- package/dist/classes/SdkTelemetryClient.d.ts +0 -86
- package/dist/index.js.map +0 -1
- package/dist/types/jsx-web-components.d.ts +0 -17
- package/dist/ui/components/input/CardCVVInput.d.ts +0 -19
package/README.md
CHANGED
|
@@ -382,14 +382,15 @@ Public SDK methods that fail due to API/SDK execution return an `AppError` (with
|
|
|
382
382
|
Notes:
|
|
383
383
|
- `statusCode` comes from HTTP response when available; otherwise defaults to `500`.
|
|
384
384
|
- `details.systemError` comes from backend error code when available; otherwise defaults to `APP_INTERNAL_001`.
|
|
385
|
+
- In card-on-file flow failures, the SDK returns `CARD_ON_FILE_DECLINED`.
|
|
385
386
|
|
|
386
387
|
### Public method error mapping
|
|
387
388
|
|
|
388
389
|
| Method | Returned `error.code` |
|
|
389
390
|
|---|---|
|
|
390
|
-
| `payment(data)` | `PAYMENT_PROCESS_ERROR` |
|
|
391
|
+
| `payment(data)` | `PAYMENT_PROCESS_ERROR` or `CARD_ON_FILE_DECLINED` |
|
|
391
392
|
| `getCustomerCards()` | `FETCH_CARDS_ERROR` |
|
|
392
|
-
| `saveCustomerCard(cardData)` | `SAVE_CARD_ERROR` |
|
|
393
|
+
| `saveCustomerCard(cardData)` | `SAVE_CARD_ERROR` or `CARD_ON_FILE_DECLINED` |
|
|
393
394
|
| `removeCustomerCard(cardId)` | `REMOVE_CARD_ERROR` |
|
|
394
395
|
| `getCustomerPaymentMethods()` | `FETCH_PAYMENT_METHODS_ERROR` |
|
|
395
396
|
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{get as e}from"lodash";import t from"skyflow-js";function r(e,t,r,o){return new(r||(r=Promise))((function(n,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function o(e,t,r,o){if("a"===r&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?o:"a"===r?o.call(e):o?o.value:t.get(e)}function n(e,t,r,o,n){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?n.call(e,r):n?n.value=r:t.set(e,r),r}function i(e,t,o){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:o});return yield r.json()}))}var s;"function"==typeof SuppressedError&&SuppressedError,function(e){e.INIT_ERROR="INIT_ERROR",e.CREATE_ERROR="CREATE_ERROR",e.REMOVE_SDK_ERROR="REMOVE_SDK_ERROR",e.INVALID_TYPE="INVALID_TYPE",e.STATE_ERROR="STATE_ERROR",e.FETCH_BUSINESS_ERROR="FETCH_BUSINESS_ERROR",e.INVALID_CONFIG="INVALID_CONFIG",e.MERCHANT_CREDENTIAL_REQUIRED="MERCHANT_CREDENTIAL_REQUIRED",e.INVALID_PAYMENT_REQUEST="INVALID_PAYMENT_REQUEST",e.INVALID_PAYMENT_REQUEST_CARD_PM="INVALID_PAYMENT_REQUEST_CARD_PM",e.TYPE_SDK_REQUIRED="TYPE_SDK_REQUIRED",e.ENVIRONMENT_REQUIRED="ENVIRONMENT_REQUIRED",e.FETCH_CARDS_ERROR="FETCH_CARDS_ERROR",e.FETCH_TRANSACTION_ERROR="FETCH_TRANSACTION_ERROR",e.CUSTOMER_AUTH_TOKEN_NOT_VALID="CUSTOMER_AUTH_TOKEN_NOT_VALID",e.SAVE_CARD_ERROR="SAVE_CARD_ERROR",e.REMOVE_CARD_ERROR="REMOVE_CARD_ERROR",e.SUMMARY_CARD_ERROR="SUMMARY_CARD_ERROR",e.CREATE_PAYMENT_ERROR="CREATE_PAYMENT_ERROR",e.PAYMENT_PROCESS_ERROR="PAYMENT_PROCESS_ERROR",e.INVALID_CARD_DATA="INVALID_CARD_DATA",e.SAVE_CARD_PROCESS_ERROR="SAVE_CARD_PROCESS_ERROR",e.START_CHECKOUT_ERROR="START_CHECKOUT_ERROR",e.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",e.BUSINESS_ID_REQUIRED="BUSINESS_ID_REQUIRED",e.CLIENT_ID_REQUIRED="CLIENT_ID_REQUIRED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INVALID_ITEMS="INVALID_ITEMS",e.CUSTOMER_OPERATION_ERROR="CUSTOMER_OPERATION_ERROR",e.INVALID_EMAIL="INVALID_EMAIL",e.FETCH_PAYMENT_METHODS_ERROR="FETCH_PAYMENT_METHODS_ERROR",e.INVALID_VAULT_TOKEN="INVALID_VAULT_TOKEN",e.VAULT_TOKEN_ERROR="VAULT_TOKEN_ERROR",e.SECURE_TOKEN_ERROR="SECURE_TOKEN_ERROR",e.SECURE_TOKEN_INVALID="SECURE_TOKEN_INVALID",e.INVALID_SECRET_API_KEY="INVALID_SECRET_API_KEY",e.REMOVE_CARD="REMOVE_CARD",e.SKYFLOW_NOT_INITIALIZED="SKYFLOW_NOT_INITIALIZED",e.ERROR_LOAD_PAYMENT_FORM="ERROR_LOAD_PAYMENT_FORM",e.ERROR_LOAD_ENROLLMENT_FORM="ERROR_LOAD_ENROLLMENT_FORM",e.MOUNT_COLLECT_ERROR="MOUNT_COLLECT_ERROR",e.CARD_ON_FILE_DECLINED="CARD_ON_FILE_DECLINED",e.CARD_SAVED_SUCCESSFULLY="CARD_SAVED_SUCCESSFULLY",e.CARD_REMOVED_SUCCESSFULLY="CARD_REMOVED_SUCCESSFULLY",e.REQUEST_ABORTED="REQUEST_ABORTED",e.REQUEST_FAILED="REQUEST_FAILED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.THREEDS_REDIRECTION_ERROR="THREEDS_REDIRECTION_ERROR"}(s||(s={}));const a={[s.INIT_ERROR]:"Error initializing the SDK.",[s.INVALID_TYPE]:"SDK Type invalid.",[s.STATE_ERROR]:"Error updating SDK state.",[s.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[s.INVALID_CONFIG]:"Required configuration options.",[s.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[s.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[s.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[s.TYPE_SDK_REQUIRED]:"SDK type required.",[s.ENVIRONMENT_REQUIRED]:"Environment required.",[s.FETCH_CARDS_ERROR]:"Error retrieving cards.",[s.CUSTOMER_AUTH_TOKEN_NOT_VALID]:"The customer's auth token is invalid. Please verify that the customer's data was provided when creating the SDK (sdk.create) and try again.",[s.SAVE_CARD_ERROR]:"Error saving the card.",[s.REMOVE_CARD_ERROR]:"Error deleting the card.",[s.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[s.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[s.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[s.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[s.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[s.START_CHECKOUT_ERROR]:"Error processing the payment.",[s.CREATE_ORDER_ERROR]:"Error creating the order.",[s.BUSINESS_ID_REQUIRED]:"Business ID is required.",[s.CLIENT_ID_REQUIRED]:"Client ID is required.",[s.INVALID_AMOUNT]:"Invalid amount.",[s.INVALID_ITEMS]:"Invalid items.",[s.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[s.INVALID_EMAIL]:"Invalid email.",[s.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[s.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[s.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[s.SECURE_TOKEN_ERROR]:"Error getting secure token.",[s.SECURE_TOKEN_INVALID]:"Invalid secure token.",[s.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[s.REMOVE_CARD]:"Card deleted successfully",[s.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[s.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[s.INVALID_CARD_DATA]:"Invalid card data.",[s.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[s.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[s.CARD_ON_FILE_DECLINED]:"Transaction declined. Please verify your card details.",[s.REQUEST_ABORTED]:"Requests canceled.",[s.REQUEST_FAILED]:"Request failed.",[s.UNKNOWN_ERROR]:"An unexpected error occurred.",[s.CREATE_ERROR]:"Error creating the SDK.",[s.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[s.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[s.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};s.INIT_ERROR,s.STATE_ERROR,s.FETCH_BUSINESS_ERROR,s.INVALID_CONFIG,s.TYPE_SDK_REQUIRED,s.ENVIRONMENT_REQUIRED,s.FETCH_CARDS_ERROR,s.SAVE_CARD_ERROR,s.REMOVE_CARD_ERROR,s.CREATE_PAYMENT_ERROR,s.START_CHECKOUT_ERROR,s.CREATE_ORDER_ERROR,s.BUSINESS_ID_REQUIRED,s.CLIENT_ID_REQUIRED,s.INVALID_AMOUNT,s.INVALID_ITEMS,s.CUSTOMER_OPERATION_ERROR,s.INVALID_EMAIL,s.FETCH_PAYMENT_METHODS_ERROR,s.INVALID_VAULT_TOKEN,s.VAULT_TOKEN_ERROR,s.SECURE_TOKEN_ERROR,s.INVALID_SECRET_API_KEY,s.CUSTOMER_AUTH_TOKEN_NOT_VALID,s.SECURE_TOKEN_INVALID,s.REMOVE_CARD,s.SKYFLOW_NOT_INITIALIZED,s.INVALID_TYPE,s.PAYMENT_PROCESS_ERROR,s.INVALID_PAYMENT_REQUEST,s.INVALID_PAYMENT_REQUEST_CARD_PM,s.SAVE_CARD_PROCESS_ERROR,s.ERROR_LOAD_PAYMENT_FORM,s.INVALID_CARD_DATA,s.ERROR_LOAD_ENROLLMENT_FORM,s.MOUNT_COLLECT_ERROR,s.CARD_ON_FILE_DECLINED,s.CARD_SAVED_SUCCESSFULLY,s.CARD_REMOVED_SUCCESSFULLY,s.REQUEST_ABORTED,s.REQUEST_FAILED,s.UNKNOWN_ERROR,s.CREATE_ERROR,s.FETCH_TRANSACTION_ERROR,s.THREEDS_REDIRECTION_ERROR,s.REMOVE_SDK_ERROR;class d extends Error{constructor(e){var t,r;const o=e.message||a[e.code]||"Unknown error";super(o),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(r=e.details)||void 0===r?void 0:r.message)||o}}}const l=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),c=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""};class u extends Error{constructor(e){var t,r;const o=u.resolveStatusCode(e.statusCode,e.originalError),n=u.resolveMessage(e.errorCode,e.message),i=u.resolveSystemError(null===(t=e.details)||void 0===t?void 0:t.systemError,e.originalError);super(n),this.status="error",Object.setPrototypeOf(this,new.target.prototype),this.name="TonderError",this.code=e.errorCode,this.statusCode=o,this.originalError=e.originalError,this.details={code:e.errorCode,statusCode:o,systemError:i},null===(r=Error.captureStackTrace)||void 0===r||r.call(Error,this,u)}static isRecord(e){return"object"==typeof e&&null!==e}static parseStatusCode(e){const t=Number(e);return Number.isFinite(t)?t<100||t>599?500:Math.trunc(t):500}static resolveStatusCode(e,t){const r=[e];if(u.isRecord(t)){r.push(t.statusCode,t.status);const e=u.isRecord(t.body)?t.body:null;e&&r.push(e.statusCode,e.status)}for(const e of r)if(u.isHttpStatusCode(e))return Math.trunc(Number(e));return 500}static resolveMessage(e,t){return t||(a[e]||a[s.UNKNOWN_ERROR]||"An unexpected error occurred.")}static isHttpStatusCode(e){const t=Number(e);return Number.isFinite(t)&&t>=100&&t<=599}static normalizeSystemError(e){if("string"!=typeof e)return null;return e.trim()||null}static resolveSystemError(e,t){const r=[e];if(u.isRecord(t)){const e=u.isRecord(t.details)?t.details:null,o=u.isRecord(t.body)?t.body:null,n=o&&u.isRecord(o.details)?o.details:null;r.push(t.systemError,t.code,null==e?void 0:e.systemError,null==e?void 0:e.code,null==o?void 0:o.systemError,null==o?void 0:o.code,null==n?void 0:n.systemError,null==n?void 0:n.code)}for(const e of r){const t=u.normalizeSystemError(e);if(t)return t}return"APP_INTERNAL_001"}}function h(e){return e instanceof u&&void 0!==e.originalError?e.originalError:e}function _(e){var t,o;return r(this,void 0,void 0,(function*(){const n=yield function(e){return r(this,void 0,void 0,(function*(){try{return yield e.clone().json()}catch(e){}try{return(yield e.text())||void 0}catch(e){return}}))}(e.response),i={status:e.response.status};return e.response.statusText&&(i.statusText=e.response.statusText),void 0!==n&&(i.body=n),new u({errorCode:e.errorCode,message:e.message,statusCode:null!==(t=e.statusCode)&&void 0!==t?t:e.response.status,details:void 0!==(null===(o=e.details)||void 0===o?void 0:o.systemError)?{systemError:e.details.systemError}:void 0,originalError:i})}))}function E(e,t){return(null==e?void 0:e.response)?_(e):function(e,t){var r;if(!(null==e?void 0:e.errorCode))throw new Error("buildPublicAppError requires errorCode");const o=null===(r=e.details)||void 0===r?void 0:r.systemError,n=e.errorCode!==(null==t?void 0:t.code)||!!e.message||void 0!==e.statusCode||void 0!==o;return t instanceof u&&!n?t:new u({errorCode:e.errorCode,message:e.message,statusCode:e.statusCode,details:void 0!==o?{systemError:o}:void 0,originalError:h(t)})}(e,t)}class p{constructor({payload:e=null,apiKey:t,baseUrl:r,redirectOnComplete:o,tdsIframeId:n,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=r,this.apiKey=t,this.payload=e,this.tdsIframeId=n,this.tonderPayButtonId=i,this.redirectOnComplete=o,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,r,o,n,i;const s=null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(n=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===n?void 0:n.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,r;if(null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.iframe)return new Promise(((e,t)=>{var r,o,n;const i=null===(n=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===n?void 0:n.iframe;if(i){this.saveVerifyTransactionUrl();const r=document.createElement("div");r.innerHTML=i,document.body.appendChild(r);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',r.appendChild(o);const n=document.getElementById("tdsMmethodTgtFrame");n?n.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,r;return null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",e),t.setAttribute("style","display: block");const o=this,n=e=>r(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}t&&t.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),t.removeEventListener("load",n)},i=t=>r(this,void 0,void 0,(function*(){const n=yield new Promise(((e,r)=>e(t)));if(n){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(n))return e();{const e=setTimeout((()=>r(this,void 0,void 0,(function*(){clearTimeout(e),yield i(o.requestTransactionStatus())}))),7e3)}}}));yield i(o.requestTransactionStatus())}));t.addEventListener("load",n)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return r(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,r=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==r.status)return console.error("La verificación de la transacción falló."),null;return yield r.json()}))}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[r,o]of t)e[r]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return r(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const r=document.createElement("input");r.type="hidden",r.name=e.creq,r.value=e.creq,t.appendChild(r);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return r(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return r(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const m=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function R(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/checkout-router/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},n),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.ok)return yield i.json();throw yield E({response:i,errorCode:s.START_CHECKOUT_ERROR})}))}function y(e,t,o=!0,n=null){return r(this,void 0,void 0,(function*(){let r=yield window.OpenPay;return r.setId(e),r.setApiKey(t),r.setSandboxMode(o),yield r.deviceData.setup({signal:n})}))}const v=Object.freeze({production:"https://api.tonder.io",sandbox:"https://api-stage.tonder.io",stage:"https://api-stage.tonder.io",development:"https://api-stage.tonder.io"}),f=Object.freeze({TELEMETRY:"/telemetry/v1/events",ACQ_SUBSCRIPTION_TOKEN:"/acq-kushki/subscription/token",ACQ_SUBSCRIPTION_CREATE:"/acq-kushki/subscription/create"});function A(e="stage"){return`${v[e]}${f.TELEMETRY}`}const O="https://cdn.kushkipagos.com/kushki.min.js",C=s.CARD_ON_FILE_DECLINED;let T=!1,g=null;class S{constructor(e){var t;this.acquirerInstance=null,this.isTestEnvironment=null===(t=e.isTestEnvironment)||void 0===t||t;const r=this.isTestEnvironment?"stage":"production";this.apiUrl=function(e="stage"){return v[e]}(r),this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return r(this,void 0,void 0,(function*(){yield function(){return r(this,void 0,void 0,(function*(){return T?Promise.resolve():g||(g=new Promise(((e,t)=>{if(document.querySelector(`script[src="${O}"]`))return T=!0,void e();const r=document.createElement("script");r.src=O,r.async=!0,r.onload=()=>{T=!0,e()},r.onerror=()=>{g=null,t(E({errorCode:C,details:{step:"load_acquirer_script",message:"Failed to load acquirer script"}}))},document.head.appendChild(r)})),g)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw E({errorCode:C,details:{step:"create_acquirer_instance",message:"Acquirer script not loaded. Call initialize() first."}});return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw E({errorCode:C,details:{step:"get_acquirer_instance",message:"CardOnFile not initialized. Call initialize() first."}});return this.acquirerInstance}getJwt(e){return r(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((r,o)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void o(E({errorCode:C,details:{step:"get_jwt",acquirerResponse:e}}));const t=e;t.jwt?r(t.jwt):o(E({errorCode:C,details:{step:"get_jwt",message:"No JWT returned from acquirer",acquirerResponse:t}}))}))}))}))}generateToken(e){return r(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${f.ACQ_SUBSCRIPTION_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield E({response:t,errorCode:C,details:{step:"generate_token"}});return t.json()}))}createSubscription(e){return r(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${f.ACQ_SUBSCRIPTION_CREATE}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield E({response:t,errorCode:C,details:{step:"create_subscription"}});return t.json()}))}validate3DS(e,t){return r(this,void 0,void 0,(function*(){const r=this.getAcquirerInstance();return new Promise(((o,n)=>{r.requestValidate3DS({secureId:e,security:t},(e=>{const t=e;t.code&&"3DS000"!==t.code?n(E({errorCode:C,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}})):!1!==t.isValid?o(!0):n(E({errorCode:C,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}}))}))}))}))}process(e){var t,o;return r(this,void 0,void 0,(function*(){const r=yield this.getJwt(e.cardBin),n=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:r}),i=n.secureId||(null===(t=n.details)||void 0===t?void 0:t.secureId),s=n.security||(null===(o=n.details)||void 0===o?void 0:o.security);if(!i||!s)throw E({errorCode:C,details:{step:"process",message:"Missing secureId or security in token response",tokenResponse:n}});return yield this.validate3DS(i,s),this.createSubscription({token:"123",contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}class I{constructor(e){this.REQUEST_TIMEOUT_MS=5e3,this.MAX_MESSAGE_LENGTH=500,this.config=e}captureException(e,t){try{const r=this.buildEvent(e,t||{});this.sendEvent(r)}catch(e){}}extractErrorInfo(e){try{if(e instanceof Error)return{name:e.name||"Error",message:this.truncate(e.message||"Unknown error",this.MAX_MESSAGE_LENGTH),stack:e.stack||void 0};const t=this.safeStringify(e);return{name:"NonErrorException",message:this.truncate(t,this.MAX_MESSAGE_LENGTH),stack:void 0}}catch(e){return{name:"SerializationError",message:"Failed to serialize error",stack:void 0}}}safeStringify(e){try{const t=new WeakSet;return JSON.stringify(e,((e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return"[Circular]";t.add(r)}return r}))}catch(t){return String(e)}}buildEvent(e,t){const r=this.extractErrorInfo(e),o=Object.assign({},t.metadata||{});void 0===o.error&&(o.error=e),"undefined"!=typeof window&&(o.url=window.location.href);const n={platform:this.config.platform,platform_version:this.config.platform_version,env:this.config.mode,feature:t.feature||"unknown",level:"error",message:r.message,name:r.name,metadata:o};return t.tenant_id&&(n.tenant_id=t.tenant_id),t.request_id&&(n.request_id=t.request_id),t.process_id&&(n.process_id=t.process_id),t.user_id&&(n.user_id=t.user_id),r.stack&&(n.stack=r.stack),t.error_code&&(n.error_code=t.error_code),t.http_status&&(n.http_status=t.http_status),n}truncate(e,t){return e.length<=t?e:e.substring(0,t)+"..."}sendEvent(e){this.sendHttpRequest(e).then((()=>{})).catch((()=>{}))}sendHttpRequest(e){return r(this,void 0,void 0,(function*(){try{const t=JSON.stringify(e),r=new AbortController,o=setTimeout((()=>r.abort()),this.REQUEST_TIMEOUT_MS);try{const e=yield fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.config.apiKey}`},body:t,keepalive:!0,signal:r.signal});return clearTimeout(o),e.ok}catch(e){return clearTimeout(o),!1}}catch(e){return!1}}))}}const N=Object.freeze({name:"@tonder.io/ionic-lite-sdk",version:"0.0.68-beta.DEV-2106.10"});var D,b,M,U,k,L,P,w,j,V,K,F,x;class B{constructor({mode:e="stage",customization:t,apiKey:r,apiKeyTonder:o,returnUrl:n,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d,sdkInfo:l}){D.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,b.set(this,void 0),M.set(this,void 0),this.apiKeyTonder=o||r||"",this.returnUrl=n,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||m[this.mode]||m.stage,this.abortController=new AbortController,this.requestId=this.generateRequestId(),this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new p({apiKey:r,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i;const c=l||N;this.telemetry=new I({endpoint:A(this.mode),apiKey:this.apiKeyTonder,platform:c.name,platform_version:c.version,mode:this.mode||"stage"})}configureCheckout(e){"secureToken"in e&&o(this,D,"m",L).call(this,e.secureToken),o(this,D,"m",U).call(this,e)}getCustomerId(){var e,t;return null===(t=null===(e=o(this,M,"f"))||void 0===e?void 0:e.id)||void 0===t?void 0:t.toString()}reportSdkError(e,t){var r,o,n,i;try{const s=this.getCustomerId(),a=e instanceof u&&void 0!==e.originalError?e.originalError:e,d=Object.assign(Object.assign({},(null==t?void 0:t.metadata)||{}),void 0===(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.error)?{error:a}:{}),l=Object.assign(Object.assign({tenant_id:null===(i=null===(n=null===(o=this.merchantData)||void 0===o?void 0:o.business)||void 0===n?void 0:n.pk)||void 0===i?void 0:i.toString(),user_id:s},t||{}),{metadata:d,request_id:this.requestId});l.user_id||delete l.user_id,l.feature=(null==t?void 0:t.feature)||"unknown",this.telemetry.captureException(e,l)}catch(e){}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}verify3dsTransaction(){return r(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield o(this,D,"m",K).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,n)=>r(this,void 0,void 0,(function*(){var r,i;let a;try{o(this,D,"m",U).call(this,e),a=yield this._checkout(e),this.process3ds.setPayload(a);if(yield this._handle3dsRedirect(a)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(a),t(a)}}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==a?void 0:a.payment_id)||(null===(r=null==a?void 0:a.payment)||void 0===r?void 0:r.id)||(null===(i=null==a?void 0:a.payment)||void 0===i?void 0:i.pk),metadata:{step:"payment",request:e,response:a}}),n(E({errorCode:s.PAYMENT_PROCESS_ERROR},t))}}))))}getSecureToken(e){return r(this,void 0,void 0,(function*(){try{return yield function(e,t,o=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(r.ok)return yield r.json();throw yield E({response:r,errorCode:s.SECURE_TOKEN_ERROR})}))}(this.baseUrl,e)}catch(e){throw this.reportSdkError(e,{feature:"secure-token",metadata:{step:"getSecureToken"}}),E({errorCode:s.SECURE_TOKEN_ERROR},e)}}))}_initializeCheckout(){return r(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}(),this._hasCardOnFileKeys()&&(yield this._initializeCardOnFile())}))}_checkout(e){return r(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return r(this,void 0,void 0,(function*(){return o(this,M,"f")||n(this,M,yield function(e,t,o,n=null){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},a=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:n,body:JSON.stringify(i)});if(a.ok)return yield a.json();throw yield E({response:a,errorCode:s.CUSTOMER_OPERATION_ERROR})}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),o(this,M,"f")}))}_handleCheckout({card:t,payment_method:n,customer:i,isSandbox:a,enable_card_on_file:d,returnUrl:c}){return r(this,void 0,void 0,(function*(){const{openpay_keys:u,reference:h,business:_}=this.merchantData,p=Number(this.cartTotal);let m,v,f;try{let A;!A&&u.merchant_id&&u.public_key&&!n&&(A=yield y(u.merchant_id,u.public_key,a,this.abortController.signal));const{id:O,auth_token:C}=i;m={business:this.apiKeyTonder,client:C,billing_address_id:null,shipping_address_id:null,amount:p,status:"A",reference:h,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata};const T=yield function(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/orders/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(n)});if(i.ok)return yield i.json();throw yield E({response:i,errorCode:s.CREATE_ORDER_ERROR})}))}(this.baseUrl,this.apiKeyTonder,m),g=(new Date).toISOString();v={business_pk:_.pk,client_id:O,amount:p,date:g,order_id:T.id,customer_order_reference:this.order_reference?this.order_reference:h,items:this.cartItems,currency:this.currency,metadata:this.metadata};const S=yield function(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${o.business_pk}/payments/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(n)});if(i.ok)return yield i.json();throw yield E({response:i,errorCode:s.CREATE_PAYMENT_ERROR})}))}(this.baseUrl,this.apiKeyTonder,v);f=Object.assign(Object.assign(Object.assign(Object.assign({name:e(this.customer,"firstName",e(this.customer,"name","")),last_name:e(this.customer,"lastName",e(this.customer,"lastname","")),email_client:e(this.customer,"email",""),phone_number:e(this.customer,"phone",""),return_url:c||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:p,title_ship:"shipping",description:"transaction",device_session_id:A||null,token_id:"",order_id:T.id,business_id:_.pk,payment_id:S.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:l(),currency:this.currency},n?{payment_method:n}:{card:t}),{apm_config:o(this,b,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==d?{enable_card_on_file:d}:{});const I=yield R(this.baseUrl,this.apiKeyTonder,f);return I||!1}catch(e){throw this.reportSdkError(e,{feature:"payment",process_id:null==f?void 0:f.payment_id,metadata:{step:"_handleCheckout",orderItems:m,paymentItems:v,routerItems:f}}),e}}))}_fetchMerchantData(){return r(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.reportSdkError(e,{feature:"fetch-merchant-data",metadata:{step:"_fetchMerchantData"}}),this.merchantData}}))}_getCustomerCards(e,t){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n,i=null){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${n}/cards/`,a=yield fetch(r,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},signal:i});if(a.ok)return yield a.json();if(401===a.status)return{user_id:0,cards:[]};throw yield E({response:a,errorCode:s.FETCH_CARDS_ERROR})}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,o,n=!1){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n,i,a=!1){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${n}/cards/`,d=yield fetch(r,{method:"POST",headers:Object.assign({Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},a?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(i)});if(d.ok)return yield d.json();throw yield E({response:d,errorCode:s.SAVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,t,o,n)}))}_removeCustomerCard(e,t,o){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n="",i){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${i}/cards/${n}`,d=yield fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t}});if(204===d.status)return a[s.CARD_REMOVED_SUCCESSFULLY];if(d.ok&&"json"in d)return yield d.json();throw yield E({response:d,errorCode:s.REMOVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,o,t)}))}_fetchCustomerPaymentMethods(){return r(this,void 0,void 0,(function*(){return yield function(e,t,o={status:"active",pagesize:"10000"},n=null){return r(this,void 0,void 0,(function*(){const r=new URLSearchParams(o).toString(),i=yield fetch(`${e}/api/v1/payment_methods?${r}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:n});if(i.ok)return yield i.json();throw yield E({response:i,errorCode:s.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder)}))}_hasCardOnFileKeys(){var e,t;return!!(null===(t=null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys)||void 0===t?void 0:t.public_key)}_initializeCardOnFile(){var e;return r(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new S({merchantId:null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys.public_key,apiKey:this.apiKeyTonder,isTestEnvironment:"production"!==this.mode}),yield this.cardOnFileInstance.initialize()),this.cardOnFileInstance}))}_handle3dsRedirect(e){var t,o;return r(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t),this.reportSdkError(t,{feature:"3ds-verification",metadata:{step:"_handle3dsRedirect",response:e}})}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function Y(e,t,o=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${t}`},signal:o});if(r.ok){return(yield r.json()).token}throw yield E({response:r,errorCode:s.VAULT_TOKEN_ERROR})}))}b=new WeakMap,M=new WeakMap,D=new WeakSet,U=function(e){var t,r;!e||e&&0===Object.keys(e).length||(o(this,D,"m",k).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),o(this,D,"m",P).call(this,(null===(r=e.cart)||void 0===r?void 0:r.items)||[]),o(this,D,"m",w).call(this,e),o(this,D,"m",j).call(this,e),o(this,D,"m",V).call(this,e),o(this,D,"m",F).call(this,e))},k=function(e){e&&(this.customer=e)},L=function(e){this.secureToken=e},P=function(e){this.cartItems=e},w=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},j=function(e){this.currency=null==e?void 0:e.currency},V=function(e){this.card=null==e?void 0:e.card},K=function(e){var t,o,n,i,s;return r(this,void 0,void 0,(function*(){if("Hard"===(null===(t=null==e?void 0:e.decline)||void 0===t?void 0:t.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(n=e.checkout)||void 0===n?void 0:n.id)||(null==e?void 0:e.checkout_id)};try{return yield R(this.baseUrl,this.apiKeyTonder,t)}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==e?void 0:e.payment_id)||(null===(i=null==e?void 0:e.payment)||void 0===i?void 0:i.id)||(null===(s=null==e?void 0:e.payment)||void 0===s?void 0:s.pk),metadata:{step:"#resumeCheckout",response:e}})}return e}}))},F=function(e){n(this,b,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(x||(x={}));const $={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},H=RegExp("^(?!s*$).+"),z={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:H,error:"El campo es requerido"}},q="Titular de la tarjeta",Q="Número de tarjeta",W="CVC/CVV",X="Mes",J="Año",G="Fecha de expiración",Z="Nombre como aparece en la tarjeta",ee="1234 1234 1234 1234",te="3-4 dígitos",re="MM",oe="AA",ne={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},ie={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},se={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function ae({baseUrl:e,apiKey:o,vault_id:n,vault_url:i,data:a}){return r(this,void 0,void 0,(function*(){const d=t.init({vaultID:n,vaultURL:i,getBearerToken:()=>r(this,void 0,void 0,(function*(){return yield Y(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),l=yield function(e,o){return r(this,void 0,void 0,(function*(){const n=yield function(e,o){return r(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(e).map((e=>r(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,o);return n?n.map((t=>new Promise((r=>{var o;const n=document.createElement("div");n.hidden=!0,n.id=`id-${t.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(n),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const o=e[t.key];return t.element.setValue(o),r(t.element.isMounted())}}),120)}),120)})))):[]}))}(a,d);if((yield Promise.all(l)).some((e=>!e)))throw E({errorCode:s.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}});try{const e=yield d.collect();if(e)return e.records[0].fields;throw E({errorCode:s.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}})}catch(e){throw E({errorCode:s.SAVE_CARD_PROCESS_ERROR},e)}}))}function de(e){const{element:r,fieldMessage:o="",errorStyles:n={},requiredMessage:i="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in r&&(r.on(t.EventName.CHANGE,(e=>{ce({eventName:"onChange",data:e,events:a}),le({element:r,errorStyles:n,color:"transparent"})})),r.on(t.EventName.BLUR,(e=>{if(ce({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?i:""!=o?`El campo ${o} no es válido`:s;r.setError(t)}le({element:r,errorStyles:n})})),r.on(t.EventName.FOCUS,(e=>{ce({eventName:"onFocus",data:e,events:a}),le({element:r,errorStyles:n,color:"transparent"}),r.resetError()})))}function le(e){const{element:t,errorStyles:r={},color:o=""}=e;Object.keys(r).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base&&Object.assign({},r.base)),""!=o&&{color:o})})})}const ce=t=>{const{eventName:r,data:o,events:n}=t;if(n&&r in n){const t=n[r];"function"==typeof t&&t({elementType:e(o,"elementType",""),isEmpty:e(o,"isEmpty",""),isFocused:e(o,"isFocused",""),isValid:e(o,"isValid","")})}};function ue(e){return r(this,void 0,void 0,(function*(){const{element:t,containerId:r,retries:o=2,delay:n=30}=e;for(let e=0;e<=o;e++){if(document.querySelector(r))return void t.mount(r);e<o&&(yield new Promise((e=>setTimeout(e,n))))}console.warn(`[mountCardFields] Container ${r} was not found after ${o+1} attempts`)}))}const he=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),_e={[he.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[he.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[he.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[he.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[he.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[he.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[he.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[he.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[he.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[he.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[he.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[he.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[he.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[he.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[he.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[he.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[he.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[he.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[he.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[he.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[he.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[he.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[he.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[he.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[he.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[he.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[he.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[he.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[he.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[he.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[he.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[he.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[he.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},Ee=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return _e[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class pe extends B{constructor({apiKey:e,mode:t,returnUrl:r,callBack:o,apiKeyTonder:n,baseUrlTonder:i,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:r,callBack:o,apiKeyTonder:n,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe",sdkInfo:N}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return r(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return this.customerCardsCache=t,Object.assign(Object.assign({},t),{cards:t.cards.map((e=>{return Object.assign(Object.assign({},e),{fields:Object.assign(Object.assign({},e.fields),{subscription_id:this._hasCardOnFileKeys()?e.fields.subscription_id:void 0}),icon:(t=e.fields.card_scheme,"Visa"===t?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===t?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===t?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var t}))})}catch(e){throw this.reportSdkError(e,{feature:"get-cards",process_id:this.getCustomerId(),metadata:{step:"getCustomerCards"}}),E({errorCode:s.FETCH_CARDS_ERROR},e)}}))}saveCustomerCard(e){return r(this,void 0,void 0,(function*(){let t=null;try{yield this._fetchMerchantData();const r=yield this._getCustomer(),{auth_token:o,first_name:n="",last_name:i="",email:d=""}=r,{vault_id:l,vault_url:c,business:u}=this.merchantData,h=this._hasCardOnFileKeys(),_={card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")},p=yield ae({vault_id:l,vault_url:c,data:_,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),m=yield this._saveCustomerCard(o,null==u?void 0:u.pk,p,h);if(t=m.skyflow_id,h){const e=m.card_bin;if(!e)throw new Error("Card BIN not returned from save card");const t=yield this._initializeCardOnFile();let r;try{r=yield t.process({cardTokens:{name:p.cardholder_name,number:p.card_number,expiryMonth:p.expiration_month,expiryYear:p.expiration_year,cvv:p.cvv},cardBin:e,contactDetails:{firstName:n||"",lastName:i||"",email:d||""},customerId:o,currency:this.currency||"MXN"})}catch(e){throw E({errorCode:s.SAVE_CARD_ERROR,message:a[s.CARD_ON_FILE_DECLINED]},e)}const l={skyflow_id:p.skyflow_id,subscription_id:r.subscriptionId};yield this._saveCustomerCard(o,null==u?void 0:u.pk,l)}return m}catch(e){throw t&&(yield this.removeCustomerCard(t)),this.reportSdkError(e,{feature:"save-card",process_id:t||this.getCustomerId(),metadata:{step:"saveCustomerCard"}}),E({errorCode:s.SAVE_CARD_ERROR},e)}}))}removeCustomerCard(e){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:r}=this.merchantData;return yield this._removeCustomerCard(t,null==r?void 0:r.pk,e)}catch(t){throw this.reportSdkError(t,{feature:"remove-card",process_id:e,metadata:{step:"removeCustomerCard"}}),E({errorCode:s.REMOVE_CARD_ERROR},t)}}))}getCustomerPaymentMethods(){return r(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},Ee(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw this.reportSdkError(e,{feature:"get-payment-methods",metadata:{step:"getCustomerPaymentMethods"}}),E({errorCode:s.FETCH_PAYMENT_METHODS_ERROR},e)}}))}mountCardFields(e){var o;return r(this,void 0,void 0,(function*(){const n=e.card_id?`update:${e.card_id}`:"create",i=null!==(o=e.unmount_context)&&void 0!==o?o:"all";"none"!==i&&("current"===i?this.unmountCardFields(n):this.unmountCardFields(i)),yield this.createSkyflowInstance();const s=yield function(e){var o,n,i,s,a,d,l,c,u,h,_,E,p,m,R,y,v;return r(this,void 0,void 0,(function*(){const{skyflowInstance:r,data:f,customization:A,events:O}=e,C=r.container(t.ContainerType.COLLECT),T=[],g={[x.CVV]:t.ElementType.CVV,[x.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[x.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[x.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[x.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},S={[x.CVV]:[z],[x.CARD_NUMBER]:[z],[x.EXPIRATION_MONTH]:[z],[x.EXPIRATION_YEAR]:[z],[x.CARDHOLDER_NAME]:[$,z]},I={errorStyles:(null===(n=null===(o=null==A?void 0:A.styles)||void 0===o?void 0:o.cardForm)||void 0===n?void 0:n.errorStyles)||se,inputStyles:(null===(s=null===(i=null==A?void 0:A.styles)||void 0===i?void 0:i.cardForm)||void 0===s?void 0:s.inputStyles)||ne,labelStyles:(null===(d=null===(a=null==A?void 0:A.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||ie},N={name:(null===(l=null==A?void 0:A.labels)||void 0===l?void 0:l.name)||q,card_number:(null===(c=null==A?void 0:A.labels)||void 0===c?void 0:c.card_number)||Q,cvv:(null===(u=null==A?void 0:A.labels)||void 0===u?void 0:u.cvv)||W,expiration_date:(null===(h=null==A?void 0:A.labels)||void 0===h?void 0:h.expiry_date)||G,expiration_month:(null===(_=null==A?void 0:A.labels)||void 0===_?void 0:_.expiration_month)||X,expiration_year:(null===(E=null==A?void 0:A.labels)||void 0===E?void 0:E.expiration_year)||J},D={name:(null===(p=null==A?void 0:A.placeholders)||void 0===p?void 0:p.name)||Z,card_number:(null===(m=null==A?void 0:A.placeholders)||void 0===m?void 0:m.card_number)||ee,cvv:(null===(R=null==A?void 0:A.placeholders)||void 0===R?void 0:R.cvv)||te,expiration_month:(null===(y=null==A?void 0:A.placeholders)||void 0===y?void 0:y.expiration_month)||re,expiration_year:(null===(v=null==A?void 0:A.placeholders)||void 0===v?void 0:v.expiration_year)||oe},b={[x.CVV]:null==O?void 0:O.cvvEvents,[x.CARD_NUMBER]:null==O?void 0:O.cardNumberEvents,[x.EXPIRATION_MONTH]:null==O?void 0:O.monthEvents,[x.EXPIRATION_YEAR]:null==O?void 0:O.yearEvents,[x.CARDHOLDER_NAME]:null==O?void 0:O.cardHolderEvents};if("fields"in f&&Array.isArray(f.fields))if(f.fields.length>0&&"string"==typeof f.fields[0])for(const e of f.fields){const t=C.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:g[e],validations:S[e]},I),{label:N[e],placeholder:D[e]}),f.card_id?{skyflowID:f.card_id}:{}));de({element:t,errorStyles:I.errorStyles,fieldMessage:[x.CVV,x.EXPIRATION_MONTH,x.EXPIRATION_YEAR].includes(e)?"":N[e],events:b[e]});const r=`#collect_${String(e)}`+(f.card_id?`_${f.card_id}`:"");yield ue({element:t,containerId:r}),T.push({element:t,containerId:r})}else for(const e of f.fields){const t=e.field,r=C.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:g[t],validations:S[t]},I),{label:N[t],placeholder:D[t]}),f.card_id?{skyflowID:f.card_id}:{})),o=e.container_id||`#collect_${String(t)}`+(f.card_id?`_${f.card_id}`:"");yield ue({element:r,containerId:o}),T.push({element:r,containerId:o})}return{elements:T.map((e=>e.element)),container:C}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events});this.mountedElementsByContext.set(n,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const r=`update:${e}`,o=this.mountedElementsByContext.get(r);return(null===(t=null==o?void 0:o.container)||void 0===t?void 0:t.container)||null}collectCardTokens(e){var t,o,n;return r(this,void 0,void 0,(function*(){const r=this.getContainerByCardId(e);if(!r)return null;try{const e=yield r.collect();return(null===(o=null===(t=null==e?void 0:e.records)||void 0===t?void 0:t[0])||void 0===o?void 0:o.fields)||null}catch(t){const r=null===(n=null==t?void 0:t.error)||void 0===n?void 0:n.description;throw this.reportSdkError(t,{feature:"collect-card-tokens",process_id:e,metadata:{step:"collectCardTokens"}}),new d({code:s.MOUNT_COLLECT_ERROR,details:{message:r}})}}))}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:r}=t;r&&r.length>0&&r.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t),this.reportSdkError(t,{feature:"unmount-card-fields",metadata:{step:"unmountContext",context:e}})}}))}getBusiness(){return r(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw this.reportSdkError(e,{feature:"get-business",metadata:{step:"getBusiness"}}),E({errorCode:s.FETCH_BUSINESS_ERROR},e)}}))}createSkyflowInstance(){return r(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:e,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:o,vault_id:n,vault_url:i}){return r(this,void 0,void 0,(function*(){return t.init({vaultID:n,vaultURL:i,getBearerToken:()=>r(this,void 0,void 0,(function*(){return yield Y(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,o){return r(this,void 0,void 0,(function*(){try{return yield y(e,t,o)}catch(e){throw this.reportSdkError(e,{feature:"get-openpay-device-session",metadata:{step:"getOpenpayDeviceSessionID"}}),E({errorCode:s.START_CHECKOUT_ERROR},e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:o}){return r(this,void 0,void 0,(function*(){return yield ae({vault_id:e,vault_url:t,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:o,returnUrl:n}){var i,d;return r(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const l=yield this._getCustomer(this.abortController.signal),{vault_id:c,vault_url:u,business:h}=this.merchantData,{auth_token:_,first_name:p="",last_name:m="",email:R=""}=l,y=this._hasCardOnFileKeys();let v,f=null,A=null,O=null,C=!1;const T=()=>r(this,void 0,void 0,(function*(){var e,t;(null===(t=null===(e=this.customerCardsCache)||void 0===e?void 0:e.cards)||void 0===t?void 0:t.length)||(this.customerCardsCache=yield this._getCustomerCards(_,this.merchantData.business.pk))}));if(!t){if("string"==typeof e)if(A=e,v={skyflow_id:e},y){yield T();const t=null===(d=null===(i=this.customerCardsCache)||void 0===i?void 0:i.cards)||void 0===d?void 0:d.find((t=>t.fields.skyflow_id===e));if(!t)throw new Error("Card not found for card-on-file processing");const r=!!t.fields.subscription_id;r||(yield this.collectCardTokens(e)),r&&(f={subscriptionId:t.fields.subscription_id})}else yield this.collectCardTokens(e);else{const t=Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")});v=yield ae({vault_id:c,vault_url:u,data:t,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),A=v.skyflow_id,y&&(O={name:v.cardholder_name,number:v.card_number,expiryMonth:v.expiration_month,expiryYear:v.expiration_year,cvv:v.cvv},C=!0)}if(C){if(!A||!O)throw new Error("Missing card data for card-on-file processing");let e=null;try{const t=yield this._saveCustomerCard(_,null==h?void 0:h.pk,{skyflow_id:A},!0);e=t.skyflow_id;const r=t.card_bin;if(!r)throw new Error("Card BIN not returned from save card");const o=yield this._initializeCardOnFile();let n;try{n=yield o.process({cardTokens:O,cardBin:r,contactDetails:{firstName:p||"",lastName:m||"",email:R||""},customerId:_,currency:this.currency||"MXN"})}catch(e){throw E({errorCode:s.PAYMENT_PROCESS_ERROR,message:a[s.CARD_ON_FILE_DECLINED]},e)}f={subscriptionId:n.subscriptionId},yield this._saveCustomerCard(_,null==h?void 0:h.pk,{skyflow_id:A,subscription_id:f.subscriptionId})}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"payment",process_id:e||this.getCustomerId(),metadata:{step:"card_on_file"}}),t}}}return yield this._handleCheckout({card:v,payment_method:t,customer:l,isSandbox:o,returnUrl:n,enable_card_on_file:!!(null==f?void 0:f.subscriptionId)&&y})}))}customerRegister(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,r={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield E({response:o,errorCode:s.CUSTOMER_OPERATION_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"customer-register",metadata:{step:"customerRegister"}}),E({errorCode:s.CUSTOMER_OPERATION_ERROR},e)}}))}createOrder(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield E({response:o,errorCode:s.CREATE_ORDER_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-order",metadata:{step:"createOrder"}}),E({errorCode:s.CREATE_ORDER_ERROR},e)}}))}createPayment(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield E({response:o,errorCode:s.CREATE_PAYMENT_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-payment",metadata:{step:"createPayment"}}),E({errorCode:s.CREATE_PAYMENT_ERROR},e)}}))}startCheckoutRouter(e){return r(this,void 0,void 0,(function*(){const t=yield R(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return r(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return r(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:n,return_url:i,isSandbox:a,metadata:d,currency:c,payment_method:u}=e,h=yield this._fetchMerchantData(),_=yield this.customerRegister(o.email);if(!(_&&"auth_token"in _&&h&&"reference"in h))throw E({errorCode:s.START_CHECKOUT_ERROR,details:{message:"Merchant or customer reposne errors",merchantResult:h,customerResult:_}});{const e={business:this.apiKeyTonder,client:_.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:h.reference,is_oneclick:!0,items:t.items},p=yield this.createOrder(e),m=(new Date).toISOString();if(!("id"in p&&"id"in _&&"business"in h))throw E({errorCode:s.START_CHECKOUT_ERROR,details:{message:"Order response errors",orderResult:p}});{const e={business_pk:h.business.pk,amount:r,date:m,order_id:p.id,client_id:_.id},t=yield this.createPayment(e);let s;const{openpay_keys:E,business:v}=h;E.merchant_id&&E.public_key&&(s=yield y(E.merchant_id,E.public_key,a));const f=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:i,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:s||null,token_id:"",order_id:"id"in p&&p.id,business_id:v.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:l(),currency:c},u?{payment_method:u}:{card:n}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),A=yield R(this.baseUrl,this.apiKeyTonder,f);if(yield this.init3DSRedirect(A))return A}}}catch(e){throw this.reportSdkError(e,{feature:"start-checkout-router-full",metadata:{step:"startCheckoutRouterFull"}}),E({errorCode:s.START_CHECKOUT_ERROR},e)}}))}registerCustomerCard(e,t,o){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const r=yield fetch(`${this.baseUrl}/api/v1/business/${c(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(r.ok)return yield r.json();throw yield E({response:r,errorCode:s.SAVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"register-customer-card",metadata:{step:"registerCustomerCard"}}),E({errorCode:s.SAVE_CARD_ERROR},e)}}))}deleteCustomerCard(e,t=""){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const r=yield fetch(`${this.baseUrl}/api/v1/business/${c(this.merchantData)}/cards/${t}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(r.ok)return!0;throw yield E({response:r,errorCode:s.REMOVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"delete-customer-card",process_id:t,metadata:{step:"deleteCustomerCard"}}),E({errorCode:s.REMOVE_CARD_ERROR},e)}}))}getActiveAPMs(){return r(this,void 0,void 0,(function*(){try{const e=yield function(e,t,o="?status=active&page_size=10000&country=México",n=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:n});if(r.ok)return yield r.json();throw yield E({response:r,errorCode:s.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder),t=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=t.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},Ee(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function me(e){return/^\d{12,19}$/.test(e)&&Ae(e)}function Re(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function ye(e){return/^\d{3,4}$/.test(e)}function ve(e){return/^(0[1-9]|1[0-2])$/.test(e)}function fe(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const Ae=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),r=t.shift();let o=t.reduce(((e,t,r)=>r%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=r,o%10==0};export{u as AppError,B as BaseInlineCheckout,pe as LiteCheckout,I as SdkTelemetryClient,ye as validateCVV,me as validateCardNumber,Re as validateCardholderName,ve as validateExpirationMonth,fe as validateExpirationYear};
|
|
1
|
+
import{get as e}from"lodash";import t from"skyflow-js";function r(e,t,r,o){return new(r||(r=Promise))((function(n,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function o(e,t,r,o){if("a"===r&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?o:"a"===r?o.call(e):o?o.value:t.get(e)}function n(e,t,r,o,n){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?n.call(e,r):n?n.value=r:t.set(e,r),r}function i(e,t,o){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:o});return yield r.json()}))}var s;"function"==typeof SuppressedError&&SuppressedError,function(e){e.INIT_ERROR="INIT_ERROR",e.CREATE_ERROR="CREATE_ERROR",e.REMOVE_SDK_ERROR="REMOVE_SDK_ERROR",e.INVALID_TYPE="INVALID_TYPE",e.STATE_ERROR="STATE_ERROR",e.FETCH_BUSINESS_ERROR="FETCH_BUSINESS_ERROR",e.INVALID_CONFIG="INVALID_CONFIG",e.MERCHANT_CREDENTIAL_REQUIRED="MERCHANT_CREDENTIAL_REQUIRED",e.INVALID_PAYMENT_REQUEST="INVALID_PAYMENT_REQUEST",e.INVALID_PAYMENT_REQUEST_CARD_PM="INVALID_PAYMENT_REQUEST_CARD_PM",e.TYPE_SDK_REQUIRED="TYPE_SDK_REQUIRED",e.ENVIRONMENT_REQUIRED="ENVIRONMENT_REQUIRED",e.FETCH_CARDS_ERROR="FETCH_CARDS_ERROR",e.FETCH_TRANSACTION_ERROR="FETCH_TRANSACTION_ERROR",e.CUSTOMER_AUTH_TOKEN_NOT_VALID="CUSTOMER_AUTH_TOKEN_NOT_VALID",e.SAVE_CARD_ERROR="SAVE_CARD_ERROR",e.REMOVE_CARD_ERROR="REMOVE_CARD_ERROR",e.SUMMARY_CARD_ERROR="SUMMARY_CARD_ERROR",e.CREATE_PAYMENT_ERROR="CREATE_PAYMENT_ERROR",e.PAYMENT_PROCESS_ERROR="PAYMENT_PROCESS_ERROR",e.INVALID_CARD_DATA="INVALID_CARD_DATA",e.SAVE_CARD_PROCESS_ERROR="SAVE_CARD_PROCESS_ERROR",e.START_CHECKOUT_ERROR="START_CHECKOUT_ERROR",e.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",e.BUSINESS_ID_REQUIRED="BUSINESS_ID_REQUIRED",e.CLIENT_ID_REQUIRED="CLIENT_ID_REQUIRED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INVALID_ITEMS="INVALID_ITEMS",e.CUSTOMER_OPERATION_ERROR="CUSTOMER_OPERATION_ERROR",e.INVALID_EMAIL="INVALID_EMAIL",e.FETCH_PAYMENT_METHODS_ERROR="FETCH_PAYMENT_METHODS_ERROR",e.INVALID_VAULT_TOKEN="INVALID_VAULT_TOKEN",e.VAULT_TOKEN_ERROR="VAULT_TOKEN_ERROR",e.SECURE_TOKEN_ERROR="SECURE_TOKEN_ERROR",e.SECURE_TOKEN_INVALID="SECURE_TOKEN_INVALID",e.INVALID_SECRET_API_KEY="INVALID_SECRET_API_KEY",e.REMOVE_CARD="REMOVE_CARD",e.SKYFLOW_NOT_INITIALIZED="SKYFLOW_NOT_INITIALIZED",e.ERROR_LOAD_PAYMENT_FORM="ERROR_LOAD_PAYMENT_FORM",e.ERROR_LOAD_ENROLLMENT_FORM="ERROR_LOAD_ENROLLMENT_FORM",e.MOUNT_COLLECT_ERROR="MOUNT_COLLECT_ERROR",e.CARD_ON_FILE_DECLINED="CARD_ON_FILE_DECLINED",e.CARD_SAVED_SUCCESSFULLY="CARD_SAVED_SUCCESSFULLY",e.CARD_REMOVED_SUCCESSFULLY="CARD_REMOVED_SUCCESSFULLY",e.REQUEST_ABORTED="REQUEST_ABORTED",e.REQUEST_FAILED="REQUEST_FAILED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.THREEDS_REDIRECTION_ERROR="THREEDS_REDIRECTION_ERROR"}(s||(s={}));const a={[s.INIT_ERROR]:"Error initializing the SDK.",[s.INVALID_TYPE]:"SDK Type invalid.",[s.STATE_ERROR]:"Error updating SDK state.",[s.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[s.INVALID_CONFIG]:"Required configuration options.",[s.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[s.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[s.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[s.TYPE_SDK_REQUIRED]:"SDK type required.",[s.ENVIRONMENT_REQUIRED]:"Environment required.",[s.FETCH_CARDS_ERROR]:"Error retrieving cards.",[s.CUSTOMER_AUTH_TOKEN_NOT_VALID]:"The customer's auth token is invalid. Please verify that the customer's data was provided when creating the SDK (sdk.create) and try again.",[s.SAVE_CARD_ERROR]:"Error saving the card.",[s.REMOVE_CARD_ERROR]:"Error deleting the card.",[s.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[s.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[s.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[s.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[s.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[s.START_CHECKOUT_ERROR]:"Error processing the payment.",[s.CREATE_ORDER_ERROR]:"Error creating the order.",[s.BUSINESS_ID_REQUIRED]:"Business ID is required.",[s.CLIENT_ID_REQUIRED]:"Client ID is required.",[s.INVALID_AMOUNT]:"Invalid amount.",[s.INVALID_ITEMS]:"Invalid items.",[s.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[s.INVALID_EMAIL]:"Invalid email.",[s.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[s.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[s.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[s.SECURE_TOKEN_ERROR]:"Error getting secure token.",[s.SECURE_TOKEN_INVALID]:"Invalid secure token.",[s.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[s.REMOVE_CARD]:"Card deleted successfully",[s.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[s.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[s.INVALID_CARD_DATA]:"Invalid card data.",[s.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[s.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[s.CARD_ON_FILE_DECLINED]:"Transaction declined. Please verify your card details.",[s.REQUEST_ABORTED]:"Requests canceled.",[s.REQUEST_FAILED]:"Request failed.",[s.UNKNOWN_ERROR]:"An unexpected error occurred.",[s.CREATE_ERROR]:"Error creating the SDK.",[s.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[s.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[s.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};s.INIT_ERROR,s.STATE_ERROR,s.FETCH_BUSINESS_ERROR,s.INVALID_CONFIG,s.TYPE_SDK_REQUIRED,s.ENVIRONMENT_REQUIRED,s.FETCH_CARDS_ERROR,s.SAVE_CARD_ERROR,s.REMOVE_CARD_ERROR,s.CREATE_PAYMENT_ERROR,s.START_CHECKOUT_ERROR,s.CREATE_ORDER_ERROR,s.BUSINESS_ID_REQUIRED,s.CLIENT_ID_REQUIRED,s.INVALID_AMOUNT,s.INVALID_ITEMS,s.CUSTOMER_OPERATION_ERROR,s.INVALID_EMAIL,s.FETCH_PAYMENT_METHODS_ERROR,s.INVALID_VAULT_TOKEN,s.VAULT_TOKEN_ERROR,s.SECURE_TOKEN_ERROR,s.INVALID_SECRET_API_KEY,s.CUSTOMER_AUTH_TOKEN_NOT_VALID,s.SECURE_TOKEN_INVALID,s.REMOVE_CARD,s.SKYFLOW_NOT_INITIALIZED,s.INVALID_TYPE,s.PAYMENT_PROCESS_ERROR,s.INVALID_PAYMENT_REQUEST,s.INVALID_PAYMENT_REQUEST_CARD_PM,s.SAVE_CARD_PROCESS_ERROR,s.ERROR_LOAD_PAYMENT_FORM,s.INVALID_CARD_DATA,s.ERROR_LOAD_ENROLLMENT_FORM,s.MOUNT_COLLECT_ERROR,s.CARD_ON_FILE_DECLINED,s.CARD_SAVED_SUCCESSFULLY,s.CARD_REMOVED_SUCCESSFULLY,s.REQUEST_ABORTED,s.REQUEST_FAILED,s.UNKNOWN_ERROR,s.CREATE_ERROR,s.FETCH_TRANSACTION_ERROR,s.THREEDS_REDIRECTION_ERROR,s.REMOVE_SDK_ERROR;class d extends Error{constructor(e){var t,r;const o=e.message||a[e.code]||"Unknown error";super(o),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(r=e.details)||void 0===r?void 0:r.message)||o}}}const l=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),c=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},u="__tonderLockErrorCode__";function h(e){return"object"==typeof e&&null!==e}class _ extends Error{constructor(e){var t,r;const o=_.resolveStatusCode(e.statusCode,e.originalError),n=_.resolveMessage(e.errorCode,e.message),i=_.resolveSystemError(null===(t=e.details)||void 0===t?void 0:t.systemError,e.originalError);super(n),this.status="error",Object.setPrototypeOf(this,new.target.prototype),this.name="TonderError",this.code=e.errorCode,this.statusCode=o,this.originalError=e.originalError,this.details={code:e.errorCode,statusCode:o,systemError:i},e.lockErrorCode&&Object.defineProperty(this,u,{value:!0,enumerable:!1,configurable:!0}),null===(r=Error.captureStackTrace)||void 0===r||r.call(Error,this,_)}static isRecord(e){return"object"==typeof e&&null!==e}static parseStatusCode(e){const t=Number(e);return Number.isFinite(t)?t<100||t>599?500:Math.trunc(t):500}static resolveStatusCode(e,t){const r=[e];if(_.isRecord(t)){r.push(t.statusCode,t.status);const e=_.isRecord(t.body)?t.body:null;e&&r.push(e.statusCode,e.status)}for(const e of r)if(_.isHttpStatusCode(e))return Math.trunc(Number(e));return 500}static resolveMessage(e,t){return t||(a[e]||a[s.UNKNOWN_ERROR]||"An unexpected error occurred.")}static isHttpStatusCode(e){const t=Number(e);return Number.isFinite(t)&&t>=100&&t<=599}static normalizeSystemError(e){if("string"!=typeof e)return null;return e.trim()||null}static resolveSystemError(e,t){const r=[e];if(_.isRecord(t)){const e=_.isRecord(t.details)?t.details:null,o=_.isRecord(t.body)?t.body:null,n=o&&_.isRecord(o.details)?o.details:null;r.push(t.systemError,t.code,null==e?void 0:e.systemError,null==e?void 0:e.code,null==o?void 0:o.systemError,null==o?void 0:o.code,null==n?void 0:n.systemError,null==n?void 0:n.code)}for(const e of r){const t=_.normalizeSystemError(e);if(t)return t}return"APP_INTERNAL_001"}}function E(e){return h(e)&&!0===e[u]}function p(e){return e instanceof _&&void 0!==e.originalError?e.originalError:e}function m(e,t){var r;if(!(null==e?void 0:e.errorCode))throw new Error("buildPublicAppError requires errorCode");const o=null===(r=e.details)||void 0===r?void 0:r.systemError,n=!!e.message||void 0!==e.statusCode||void 0!==o;return!function(e){return h(e)&&"TonderError"===e.name&&"string"==typeof e.code}(t)||(e.lockErrorCode&&function(e){Object.defineProperty(e,u,{value:!0,enumerable:!1,configurable:!0})}(t),n||e.errorCode!==t.code&&!E(t))?new _({errorCode:e.errorCode,message:e.message,statusCode:e.statusCode,details:void 0!==o?{systemError:o}:void 0,originalError:p(t),lockErrorCode:e.lockErrorCode||E(t)}):t}function R(e){var t,o;return r(this,void 0,void 0,(function*(){const n=yield function(e){return r(this,void 0,void 0,(function*(){try{return yield e.clone().json()}catch(e){}try{return(yield e.text())||void 0}catch(e){return}}))}(e.response),i={status:e.response.status};return e.response.statusText&&(i.statusText=e.response.statusText),void 0!==n&&(i.body=n),new _({errorCode:e.errorCode,message:e.message,statusCode:null!==(t=e.statusCode)&&void 0!==t?t:e.response.status,details:void 0!==(null===(o=e.details)||void 0===o?void 0:o.systemError)?{systemError:e.details.systemError}:void 0,originalError:i,lockErrorCode:e.lockErrorCode})}))}function y(e,t){return(null==e?void 0:e.response)?R(e):m(e,t)}class v{constructor({payload:e=null,apiKey:t,baseUrl:r,redirectOnComplete:o,tdsIframeId:n,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=r,this.apiKey=t,this.payload=e,this.tdsIframeId=n,this.tonderPayButtonId=i,this.redirectOnComplete=o,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,r,o,n,i;const s=null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(n=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===n?void 0:n.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,r;if(null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.iframe)return new Promise(((e,t)=>{var r,o,n;const i=null===(n=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===n?void 0:n.iframe;if(i){this.saveVerifyTransactionUrl();const r=document.createElement("div");r.innerHTML=i,document.body.appendChild(r);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',r.appendChild(o);const n=document.getElementById("tdsMmethodTgtFrame");n?n.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,r;return null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",e),t.setAttribute("style","display: block");const o=this,n=e=>r(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}t&&t.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),t.removeEventListener("load",n)},i=t=>r(this,void 0,void 0,(function*(){const n=yield new Promise(((e,r)=>e(t)));if(n){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(n))return e();{const e=setTimeout((()=>r(this,void 0,void 0,(function*(){clearTimeout(e),yield i(o.requestTransactionStatus())}))),7e3)}}}));yield i(o.requestTransactionStatus())}));t.addEventListener("load",n)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return r(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,r=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==r.status)return console.error("La verificación de la transacción falló."),null;return yield r.json()}))}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[r,o]of t)e[r]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return r(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const r=document.createElement("input");r.type="hidden",r.name=e.creq,r.value=e.creq,t.appendChild(r);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return r(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return r(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const f=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function A(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/checkout-router/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},n),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.START_CHECKOUT_ERROR})}))}function C(e,t,o=!0,n=null){return r(this,void 0,void 0,(function*(){let r=yield window.OpenPay;return r.setId(e),r.setApiKey(t),r.setSandboxMode(o),yield r.deviceData.setup({signal:n})}))}const O=Object.freeze({production:"https://api.tonder.io",sandbox:"https://api-stage.tonder.io",stage:"https://api-stage.tonder.io",development:"https://api-stage.tonder.io"}),T=Object.freeze({TELEMETRY:"/telemetry/v1/events",ACQ_SUBSCRIPTION_TOKEN:"/acq-kushki/subscription/token",ACQ_SUBSCRIPTION_CREATE:"/acq-kushki/subscription/create"});function g(e="stage"){return`${O[e]}${T.TELEMETRY}`}const I="https://cdn.kushkipagos.com/kushki.min.js",S=s.CARD_ON_FILE_DECLINED;let N=!1,D=null;class b{constructor(e){var t;this.acquirerInstance=null,this.isTestEnvironment=null===(t=e.isTestEnvironment)||void 0===t||t;const r=this.isTestEnvironment?"stage":"production";this.apiUrl=function(e="stage"){return O[e]}(r),this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return r(this,void 0,void 0,(function*(){yield function(){return r(this,void 0,void 0,(function*(){return N?Promise.resolve():D||(D=new Promise(((e,t)=>{if(document.querySelector(`script[src="${I}"]`))return N=!0,void e();const r=document.createElement("script");r.src=I,r.async=!0,r.onload=()=>{N=!0,e()},r.onerror=()=>{D=null,t(y({errorCode:S,lockErrorCode:!0,details:{step:"load_acquirer_script",message:"Failed to load acquirer script"}}))},document.head.appendChild(r)})),D)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw y({errorCode:S,lockErrorCode:!0,details:{step:"create_acquirer_instance",message:"Acquirer script not loaded. Call initialize() first."}});return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw y({errorCode:S,lockErrorCode:!0,details:{step:"get_acquirer_instance",message:"CardOnFile not initialized. Call initialize() first."}});return this.acquirerInstance}getJwt(e){return r(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((r,o)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void o(y({errorCode:S,lockErrorCode:!0,details:{step:"get_jwt",acquirerResponse:e}}));const t=e;t.jwt?r(t.jwt):o(y({errorCode:S,lockErrorCode:!0,details:{step:"get_jwt",message:"No JWT returned from acquirer",acquirerResponse:t}}))}))}))}))}generateToken(e){return r(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${T.ACQ_SUBSCRIPTION_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield y({response:t,errorCode:S,lockErrorCode:!0,details:{step:"generate_token"}});return t.json()}))}createSubscription(e){return r(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${T.ACQ_SUBSCRIPTION_CREATE}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield y({response:t,errorCode:S,lockErrorCode:!0,details:{step:"create_subscription"}});return t.json()}))}validate3DS(e,t){return r(this,void 0,void 0,(function*(){const r=this.getAcquirerInstance();return new Promise(((o,n)=>{r.requestValidate3DS({secureId:e,security:t},(e=>{const t=e;t.code&&"3DS000"!==t.code?n(y({errorCode:S,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}})):!1!==t.isValid?o(!0):n(y({errorCode:S,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}}))}))}))}))}process(e){var t,o;return r(this,void 0,void 0,(function*(){const r=yield this.getJwt(e.cardBin),n=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:r}),i=n.secureId||(null===(t=n.details)||void 0===t?void 0:t.secureId),s=n.security||(null===(o=n.details)||void 0===o?void 0:o.security);if(!i||!s)throw y({errorCode:S,lockErrorCode:!0,details:{step:"process",message:"Missing secureId or security in token response",tokenResponse:n}});return yield this.validate3DS(i,s),this.createSubscription({token:n.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}class M{constructor(e){this.REQUEST_TIMEOUT_MS=5e3,this.MAX_MESSAGE_LENGTH=500,this.config=e}captureException(e,t){try{const r=this.buildEvent(e,t||{});this.sendEvent(r)}catch(e){}}extractErrorInfo(e){try{if(e instanceof Error)return{name:e.name||"Error",message:this.truncate(e.message||"Unknown error",this.MAX_MESSAGE_LENGTH),stack:e.stack||void 0};const t=this.safeStringify(e);return{name:"NonErrorException",message:this.truncate(t,this.MAX_MESSAGE_LENGTH),stack:void 0}}catch(e){return{name:"SerializationError",message:"Failed to serialize error",stack:void 0}}}safeStringify(e){try{const t=new WeakSet;return JSON.stringify(e,((e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return"[Circular]";t.add(r)}return r}))}catch(t){return String(e)}}buildEvent(e,t){const r=this.extractErrorInfo(e),o=Object.assign({},t.metadata||{});void 0===o.error&&(o.error=e),"undefined"!=typeof window&&(o.url=window.location.href);const n={platform:this.config.platform,platform_version:this.config.platform_version,env:this.config.mode,feature:t.feature||"unknown",level:"error",message:r.message,name:r.name,metadata:o};return t.tenant_id&&(n.tenant_id=t.tenant_id),t.request_id&&(n.request_id=t.request_id),t.process_id&&(n.process_id=t.process_id),t.user_id&&(n.user_id=t.user_id),r.stack&&(n.stack=r.stack),t.error_code&&(n.error_code=t.error_code),t.http_status&&(n.http_status=t.http_status),n}truncate(e,t){return e.length<=t?e:e.substring(0,t)+"..."}sendEvent(e){this.sendHttpRequest(e).then((()=>{})).catch((()=>{}))}sendHttpRequest(e){return r(this,void 0,void 0,(function*(){try{const t=JSON.stringify(e),r=new AbortController,o=setTimeout((()=>r.abort()),this.REQUEST_TIMEOUT_MS);try{const e=yield fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.config.apiKey}`},body:t,keepalive:!0,signal:r.signal});return clearTimeout(o),e.ok}catch(e){return clearTimeout(o),!1}}catch(e){return!1}}))}}const k=Object.freeze({name:"@tonder.io/ionic-lite-sdk",version:"0.0.68"});var U,L,P,w,j,V,K,F,x,B,Y,$,H;class z{constructor({mode:e="stage",customization:t,apiKey:r,apiKeyTonder:o,returnUrl:n,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d,sdkInfo:l}){U.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,L.set(this,void 0),P.set(this,void 0),this.apiKeyTonder=o||r||"",this.returnUrl=n,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||f[this.mode]||f.stage,this.abortController=new AbortController,this.requestId=this.generateRequestId(),this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new v({apiKey:r,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i;const c=l||k;this.telemetry=new M({endpoint:g(this.mode),apiKey:this.apiKeyTonder,platform:c.name,platform_version:c.version,mode:this.mode||"stage"})}configureCheckout(e){"secureToken"in e&&o(this,U,"m",V).call(this,e.secureToken),o(this,U,"m",w).call(this,e)}getCustomerId(){var e,t;return null===(t=null===(e=o(this,P,"f"))||void 0===e?void 0:e.id)||void 0===t?void 0:t.toString()}reportSdkError(e,t){var r,o,n,i;try{const s=this.getCustomerId(),a=e instanceof _&&void 0!==e.originalError?e.originalError:e,d=Object.assign(Object.assign({},(null==t?void 0:t.metadata)||{}),void 0===(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.error)?{error:a}:{}),l=Object.assign(Object.assign({tenant_id:null===(i=null===(n=null===(o=this.merchantData)||void 0===o?void 0:o.business)||void 0===n?void 0:n.pk)||void 0===i?void 0:i.toString(),user_id:s},t||{}),{metadata:d,request_id:this.requestId});l.user_id||delete l.user_id,l.feature=(null==t?void 0:t.feature)||"unknown",this.telemetry.captureException(e,l)}catch(e){}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}verify3dsTransaction(){return r(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield o(this,U,"m",Y).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,n)=>r(this,void 0,void 0,(function*(){var r,i;let a;try{o(this,U,"m",w).call(this,e),a=yield this._checkout(e),this.process3ds.setPayload(a);if(yield this._handle3dsRedirect(a)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(a),t(a)}}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==a?void 0:a.payment_id)||(null===(r=null==a?void 0:a.payment)||void 0===r?void 0:r.id)||(null===(i=null==a?void 0:a.payment)||void 0===i?void 0:i.pk),metadata:{step:"payment",request:e,response:a}}),n(y({errorCode:s.PAYMENT_PROCESS_ERROR},t))}}))))}getSecureToken(e){return r(this,void 0,void 0,(function*(){try{return yield function(e,t,o=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(r.ok)return yield r.json();throw yield y({response:r,errorCode:s.SECURE_TOKEN_ERROR})}))}(this.baseUrl,e)}catch(e){throw this.reportSdkError(e,{feature:"secure-token",metadata:{step:"getSecureToken"}}),y({errorCode:s.SECURE_TOKEN_ERROR},e)}}))}_initializeCheckout(){return r(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}(),this._hasCardOnFileKeys()&&(yield this._initializeCardOnFile())}))}_checkout(e){return r(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return r(this,void 0,void 0,(function*(){return o(this,P,"f")||n(this,P,yield function(e,t,o,n=null){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},a=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:n,body:JSON.stringify(i)});if(a.ok)return yield a.json();throw yield y({response:a,errorCode:s.CUSTOMER_OPERATION_ERROR})}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),o(this,P,"f")}))}_handleCheckout({card:t,payment_method:n,customer:i,isSandbox:a,enable_card_on_file:d,returnUrl:c}){return r(this,void 0,void 0,(function*(){const{openpay_keys:u,reference:h,business:_}=this.merchantData,E=Number(this.cartTotal);let p,m,R;try{let v;!v&&u.merchant_id&&u.public_key&&!n&&(v=yield C(u.merchant_id,u.public_key,a,this.abortController.signal));const{id:f,auth_token:O}=i;p={business:this.apiKeyTonder,client:O,billing_address_id:null,shipping_address_id:null,amount:E,status:"A",reference:h,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata};const T=yield function(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/orders/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(n)});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.CREATE_ORDER_ERROR})}))}(this.baseUrl,this.apiKeyTonder,p),g=(new Date).toISOString();m={business_pk:_.pk,client_id:f,amount:E,date:g,order_id:T.id,customer_order_reference:this.order_reference?this.order_reference:h,items:this.cartItems,currency:this.currency,metadata:this.metadata};const I=yield function(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${o.business_pk}/payments/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(n)});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.CREATE_PAYMENT_ERROR})}))}(this.baseUrl,this.apiKeyTonder,m);R=Object.assign(Object.assign(Object.assign(Object.assign({name:e(this.customer,"firstName",e(this.customer,"name","")),last_name:e(this.customer,"lastName",e(this.customer,"lastname","")),email_client:e(this.customer,"email",""),phone_number:e(this.customer,"phone",""),return_url:c||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:E,title_ship:"shipping",description:"transaction",device_session_id:v||null,token_id:"",order_id:T.id,business_id:_.pk,payment_id:I.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:l(),currency:this.currency},n?{payment_method:n}:{card:t}),{apm_config:o(this,L,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==d?{enable_card_on_file:d}:{});const S=yield A(this.baseUrl,this.apiKeyTonder,R);return S||!1}catch(e){throw this.reportSdkError(e,{feature:"payment",process_id:null==R?void 0:R.payment_id,metadata:{step:"_handleCheckout",orderItems:p,paymentItems:m,routerItems:R}}),e}}))}_fetchMerchantData(){return r(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.reportSdkError(e,{feature:"fetch-merchant-data",metadata:{step:"_fetchMerchantData"}}),this.merchantData}}))}_getCustomerCards(e,t){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n,i=null){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${n}/cards/`,a=yield fetch(r,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},signal:i});if(a.ok)return yield a.json();if(401===a.status)return{user_id:0,cards:[]};throw yield y({response:a,errorCode:s.FETCH_CARDS_ERROR})}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,o,n=!1){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n,i,a=!1){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${n}/cards/`,d=yield fetch(r,{method:"POST",headers:Object.assign({Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},a?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(i)});if(d.ok)return yield d.json();throw yield y({response:d,errorCode:s.SAVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,t,o,n)}))}_removeCustomerCard(e,t,o){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n="",i){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${i}/cards/${n}`,d=yield fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t}});if(204===d.status)return a[s.CARD_REMOVED_SUCCESSFULLY];if(d.ok&&"json"in d)return yield d.json();throw yield y({response:d,errorCode:s.REMOVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,o,t)}))}_fetchCustomerPaymentMethods(){return r(this,void 0,void 0,(function*(){return yield function(e,t,o={status:"active",pagesize:"10000"},n=null){return r(this,void 0,void 0,(function*(){const r=new URLSearchParams(o).toString(),i=yield fetch(`${e}/api/v1/payment_methods?${r}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:n});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder)}))}_hasCardOnFileKeys(){var e,t;return!!(null===(t=null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys)||void 0===t?void 0:t.public_key)}_initializeCardOnFile(){var e;return r(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new b({merchantId:null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys.public_key,apiKey:this.apiKeyTonder,isTestEnvironment:"production"!==this.mode}),yield this.cardOnFileInstance.initialize()),this.cardOnFileInstance}))}_handle3dsRedirect(e){var t,o;return r(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t),this.reportSdkError(t,{feature:"3ds-verification",metadata:{step:"_handle3dsRedirect",response:e}})}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function q(e,t,o=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${t}`},signal:o});if(r.ok){return(yield r.json()).token}throw yield y({response:r,errorCode:s.VAULT_TOKEN_ERROR})}))}L=new WeakMap,P=new WeakMap,U=new WeakSet,w=function(e){var t,r;!e||e&&0===Object.keys(e).length||(o(this,U,"m",j).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),o(this,U,"m",K).call(this,(null===(r=e.cart)||void 0===r?void 0:r.items)||[]),o(this,U,"m",F).call(this,e),o(this,U,"m",x).call(this,e),o(this,U,"m",B).call(this,e),o(this,U,"m",$).call(this,e))},j=function(e){e&&(this.customer=e)},V=function(e){this.secureToken=e},K=function(e){this.cartItems=e},F=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},x=function(e){this.currency=null==e?void 0:e.currency},B=function(e){this.card=null==e?void 0:e.card},Y=function(e){var t,o,n,i,s;return r(this,void 0,void 0,(function*(){if("Hard"===(null===(t=null==e?void 0:e.decline)||void 0===t?void 0:t.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(n=e.checkout)||void 0===n?void 0:n.id)||(null==e?void 0:e.checkout_id)};try{return yield A(this.baseUrl,this.apiKeyTonder,t)}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==e?void 0:e.payment_id)||(null===(i=null==e?void 0:e.payment)||void 0===i?void 0:i.id)||(null===(s=null==e?void 0:e.payment)||void 0===s?void 0:s.pk),metadata:{step:"#resumeCheckout",response:e}})}return e}}))},$=function(e){n(this,L,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(H||(H={}));const Q={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},W=RegExp("^(?!s*$).+"),X={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:W,error:"El campo es requerido"}},J="Titular de la tarjeta",G="Número de tarjeta",Z="CVC/CVV",ee="Mes",te="Año",re="Fecha de expiración",oe="Nombre como aparece en la tarjeta",ne="1234 1234 1234 1234",ie="3-4 dígitos",se="MM",ae="AA",de={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},le={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},ce={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function ue({baseUrl:e,apiKey:o,vault_id:n,vault_url:i,data:a}){return r(this,void 0,void 0,(function*(){const d=t.init({vaultID:n,vaultURL:i,getBearerToken:()=>r(this,void 0,void 0,(function*(){return yield q(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),l=yield function(e,o){return r(this,void 0,void 0,(function*(){const n=yield function(e,o){return r(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(e).map((e=>r(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,o);return n?n.map((t=>new Promise((r=>{var o;const n=document.createElement("div");n.hidden=!0,n.id=`id-${t.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(n),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const o=e[t.key];return t.element.setValue(o),r(t.element.isMounted())}}),120)}),120)})))):[]}))}(a,d);if((yield Promise.all(l)).some((e=>!e)))throw y({errorCode:s.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}});try{const e=yield d.collect();if(e)return e.records[0].fields;throw y({errorCode:s.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}})}catch(e){throw y({errorCode:s.SAVE_CARD_PROCESS_ERROR},e)}}))}function he(e){const{element:r,fieldMessage:o="",errorStyles:n={},requiredMessage:i="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in r&&(r.on(t.EventName.CHANGE,(e=>{Ee({eventName:"onChange",data:e,events:a}),_e({element:r,errorStyles:n,color:"transparent"})})),r.on(t.EventName.BLUR,(e=>{if(Ee({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?i:""!=o?`El campo ${o} no es válido`:s;r.setError(t)}_e({element:r,errorStyles:n})})),r.on(t.EventName.FOCUS,(e=>{Ee({eventName:"onFocus",data:e,events:a}),_e({element:r,errorStyles:n,color:"transparent"}),r.resetError()})))}function _e(e){const{element:t,errorStyles:r={},color:o=""}=e;Object.keys(r).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base&&Object.assign({},r.base)),""!=o&&{color:o})})})}const Ee=t=>{const{eventName:r,data:o,events:n}=t;if(n&&r in n){const t=n[r];"function"==typeof t&&t({elementType:e(o,"elementType",""),isEmpty:e(o,"isEmpty",""),isFocused:e(o,"isFocused",""),isValid:e(o,"isValid","")})}};function pe(e){return r(this,void 0,void 0,(function*(){const{element:t,containerId:r,retries:o=2,delay:n=30}=e;for(let e=0;e<=o;e++){if(document.querySelector(r))return void t.mount(r);e<o&&(yield new Promise((e=>setTimeout(e,n))))}console.warn(`[mountCardFields] Container ${r} was not found after ${o+1} attempts`)}))}const me=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),Re={[me.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[me.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[me.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[me.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[me.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[me.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[me.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[me.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[me.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[me.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[me.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[me.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[me.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[me.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[me.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[me.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[me.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[me.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[me.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[me.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[me.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[me.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[me.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[me.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[me.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[me.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[me.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[me.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[me.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[me.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[me.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[me.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},ye=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return Re[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class ve extends z{constructor({apiKey:e,mode:t,returnUrl:r,callBack:o,apiKeyTonder:n,baseUrlTonder:i,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:r,callBack:o,apiKeyTonder:n,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe",sdkInfo:k}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return r(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return this.customerCardsCache=t,Object.assign(Object.assign({},t),{cards:t.cards.map((e=>{return Object.assign(Object.assign({},e),{fields:Object.assign(Object.assign({},e.fields),{subscription_id:this._hasCardOnFileKeys()?e.fields.subscription_id:void 0}),icon:(t=e.fields.card_scheme,"Visa"===t?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===t?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===t?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var t}))})}catch(e){throw this.reportSdkError(e,{feature:"get-cards",process_id:this.getCustomerId(),metadata:{step:"getCustomerCards"}}),y({errorCode:s.FETCH_CARDS_ERROR},e)}}))}saveCustomerCard(e){return r(this,void 0,void 0,(function*(){let t=null;try{yield this._fetchMerchantData();const r=yield this._getCustomer(),{auth_token:o,first_name:n="",last_name:i="",email:a=""}=r,{vault_id:d,vault_url:l,business:c}=this.merchantData,u=this._hasCardOnFileKeys(),h={card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")},_=yield ue({vault_id:d,vault_url:l,data:h,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),E=yield this._saveCustomerCard(o,null==c?void 0:c.pk,_,u);if(t=E.skyflow_id,u){const e=E.card_bin;if(!e)throw new Error("Card BIN not returned from save card");const t=yield this._initializeCardOnFile();let r;try{r=yield t.process({cardTokens:{name:_.cardholder_name,number:_.card_number,expiryMonth:_.expiration_month,expiryYear:_.expiration_year,cvv:_.cvv},cardBin:e,contactDetails:{firstName:n||"",lastName:i||"",email:a||""},customerId:o,currency:this.currency||"MXN"})}catch(e){throw y({errorCode:s.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}const d={skyflow_id:_.skyflow_id,subscription_id:r.subscriptionId};yield this._saveCustomerCard(o,null==c?void 0:c.pk,d)}return E}catch(e){throw t&&(yield this.removeCustomerCard(t)),this.reportSdkError(e,{feature:"save-card",process_id:t||this.getCustomerId(),metadata:{step:"saveCustomerCard"}}),y({errorCode:s.SAVE_CARD_ERROR},e)}}))}removeCustomerCard(e){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:r}=this.merchantData;return yield this._removeCustomerCard(t,null==r?void 0:r.pk,e)}catch(t){throw this.reportSdkError(t,{feature:"remove-card",process_id:e,metadata:{step:"removeCustomerCard"}}),y({errorCode:s.REMOVE_CARD_ERROR},t)}}))}getCustomerPaymentMethods(){return r(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},ye(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw this.reportSdkError(e,{feature:"get-payment-methods",metadata:{step:"getCustomerPaymentMethods"}}),y({errorCode:s.FETCH_PAYMENT_METHODS_ERROR},e)}}))}mountCardFields(e){var o;return r(this,void 0,void 0,(function*(){const n=e.card_id?`update:${e.card_id}`:"create",i=null!==(o=e.unmount_context)&&void 0!==o?o:"all";"none"!==i&&("current"===i?this.unmountCardFields(n):this.unmountCardFields(i)),yield this.createSkyflowInstance();const s=yield function(e){var o,n,i,s,a,d,l,c,u,h,_,E,p,m,R,y,v;return r(this,void 0,void 0,(function*(){const{skyflowInstance:r,data:f,customization:A,events:C}=e,O=r.container(t.ContainerType.COLLECT),T=[],g={[H.CVV]:t.ElementType.CVV,[H.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[H.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[H.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[H.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},I={[H.CVV]:[X],[H.CARD_NUMBER]:[X],[H.EXPIRATION_MONTH]:[X],[H.EXPIRATION_YEAR]:[X],[H.CARDHOLDER_NAME]:[Q,X]},S={errorStyles:(null===(n=null===(o=null==A?void 0:A.styles)||void 0===o?void 0:o.cardForm)||void 0===n?void 0:n.errorStyles)||ce,inputStyles:(null===(s=null===(i=null==A?void 0:A.styles)||void 0===i?void 0:i.cardForm)||void 0===s?void 0:s.inputStyles)||de,labelStyles:(null===(d=null===(a=null==A?void 0:A.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||le},N={name:(null===(l=null==A?void 0:A.labels)||void 0===l?void 0:l.name)||J,card_number:(null===(c=null==A?void 0:A.labels)||void 0===c?void 0:c.card_number)||G,cvv:(null===(u=null==A?void 0:A.labels)||void 0===u?void 0:u.cvv)||Z,expiration_date:(null===(h=null==A?void 0:A.labels)||void 0===h?void 0:h.expiry_date)||re,expiration_month:(null===(_=null==A?void 0:A.labels)||void 0===_?void 0:_.expiration_month)||ee,expiration_year:(null===(E=null==A?void 0:A.labels)||void 0===E?void 0:E.expiration_year)||te},D={name:(null===(p=null==A?void 0:A.placeholders)||void 0===p?void 0:p.name)||oe,card_number:(null===(m=null==A?void 0:A.placeholders)||void 0===m?void 0:m.card_number)||ne,cvv:(null===(R=null==A?void 0:A.placeholders)||void 0===R?void 0:R.cvv)||ie,expiration_month:(null===(y=null==A?void 0:A.placeholders)||void 0===y?void 0:y.expiration_month)||se,expiration_year:(null===(v=null==A?void 0:A.placeholders)||void 0===v?void 0:v.expiration_year)||ae},b={[H.CVV]:null==C?void 0:C.cvvEvents,[H.CARD_NUMBER]:null==C?void 0:C.cardNumberEvents,[H.EXPIRATION_MONTH]:null==C?void 0:C.monthEvents,[H.EXPIRATION_YEAR]:null==C?void 0:C.yearEvents,[H.CARDHOLDER_NAME]:null==C?void 0:C.cardHolderEvents};if("fields"in f&&Array.isArray(f.fields))if(f.fields.length>0&&"string"==typeof f.fields[0])for(const e of f.fields){const t=O.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:g[e],validations:I[e]},S),{label:N[e],placeholder:D[e]}),f.card_id?{skyflowID:f.card_id}:{}));he({element:t,errorStyles:S.errorStyles,fieldMessage:[H.CVV,H.EXPIRATION_MONTH,H.EXPIRATION_YEAR].includes(e)?"":N[e],events:b[e]});const r=`#collect_${String(e)}`+(f.card_id?`_${f.card_id}`:"");yield pe({element:t,containerId:r}),T.push({element:t,containerId:r})}else for(const e of f.fields){const t=e.field,r=O.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:g[t],validations:I[t]},S),{label:N[t],placeholder:D[t]}),f.card_id?{skyflowID:f.card_id}:{})),o=e.container_id||`#collect_${String(t)}`+(f.card_id?`_${f.card_id}`:"");yield pe({element:r,containerId:o}),T.push({element:r,containerId:o})}return{elements:T.map((e=>e.element)),container:O}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events});this.mountedElementsByContext.set(n,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const r=`update:${e}`,o=this.mountedElementsByContext.get(r);return(null===(t=null==o?void 0:o.container)||void 0===t?void 0:t.container)||null}collectCardTokens(e){var t,o,n;return r(this,void 0,void 0,(function*(){const r=this.getContainerByCardId(e);if(!r)return null;try{const e=yield r.collect();return(null===(o=null===(t=null==e?void 0:e.records)||void 0===t?void 0:t[0])||void 0===o?void 0:o.fields)||null}catch(t){const r=null===(n=null==t?void 0:t.error)||void 0===n?void 0:n.description;throw this.reportSdkError(t,{feature:"collect-card-tokens",process_id:e,metadata:{step:"collectCardTokens"}}),new d({code:s.MOUNT_COLLECT_ERROR,details:{message:r}})}}))}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:r}=t;r&&r.length>0&&r.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t),this.reportSdkError(t,{feature:"unmount-card-fields",metadata:{step:"unmountContext",context:e}})}}))}getBusiness(){return r(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw this.reportSdkError(e,{feature:"get-business",metadata:{step:"getBusiness"}}),y({errorCode:s.FETCH_BUSINESS_ERROR},e)}}))}createSkyflowInstance(){return r(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:e,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:o,vault_id:n,vault_url:i}){return r(this,void 0,void 0,(function*(){return t.init({vaultID:n,vaultURL:i,getBearerToken:()=>r(this,void 0,void 0,(function*(){return yield q(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,o){return r(this,void 0,void 0,(function*(){try{return yield C(e,t,o)}catch(e){throw this.reportSdkError(e,{feature:"get-openpay-device-session",metadata:{step:"getOpenpayDeviceSessionID"}}),y({errorCode:s.START_CHECKOUT_ERROR},e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:o}){return r(this,void 0,void 0,(function*(){return yield ue({vault_id:e,vault_url:t,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:o,returnUrl:n}){var i,a;return r(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const d=yield this._getCustomer(this.abortController.signal),{vault_id:l,vault_url:c,business:u}=this.merchantData,{auth_token:h,first_name:_="",last_name:E="",email:p=""}=d,m=this._hasCardOnFileKeys();let R,v=null,f=null,A=null,C=!1;const O=()=>r(this,void 0,void 0,(function*(){var e,t;(null===(t=null===(e=this.customerCardsCache)||void 0===e?void 0:e.cards)||void 0===t?void 0:t.length)||(this.customerCardsCache=yield this._getCustomerCards(h,this.merchantData.business.pk))}));if(!t){if("string"==typeof e)if(f=e,R={skyflow_id:e},m){yield O();const t=null===(a=null===(i=this.customerCardsCache)||void 0===i?void 0:i.cards)||void 0===a?void 0:a.find((t=>t.fields.skyflow_id===e));if(!t)throw new Error("Card not found for card-on-file processing");const r=!!t.fields.subscription_id;r||(yield this.collectCardTokens(e)),r&&(v={subscriptionId:t.fields.subscription_id})}else yield this.collectCardTokens(e);else{const t=Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")});R=yield ue({vault_id:l,vault_url:c,data:t,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),f=R.skyflow_id,m&&(A={name:R.cardholder_name,number:R.card_number,expiryMonth:R.expiration_month,expiryYear:R.expiration_year,cvv:R.cvv},C=!0)}if(C){if(!f||!A)throw new Error("Missing card data for card-on-file processing");let e=null;try{const t=yield this._saveCustomerCard(h,null==u?void 0:u.pk,{skyflow_id:f},!0);e=t.skyflow_id;const r=t.card_bin;if(!r)throw new Error("Card BIN not returned from save card");const o=yield this._initializeCardOnFile();let n;try{n=yield o.process({cardTokens:A,cardBin:r,contactDetails:{firstName:_||"",lastName:E||"",email:p||""},customerId:h,currency:this.currency||"MXN"})}catch(e){throw y({errorCode:s.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}v={subscriptionId:n.subscriptionId},yield this._saveCustomerCard(h,null==u?void 0:u.pk,{skyflow_id:f,subscription_id:v.subscriptionId})}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"payment",process_id:e||this.getCustomerId(),metadata:{step:"card_on_file"}}),t}}}return yield this._handleCheckout({card:R,payment_method:t,customer:d,isSandbox:o,returnUrl:n,enable_card_on_file:!!(null==v?void 0:v.subscriptionId)&&m})}))}customerRegister(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,r={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:s.CUSTOMER_OPERATION_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"customer-register",metadata:{step:"customerRegister"}}),y({errorCode:s.CUSTOMER_OPERATION_ERROR},e)}}))}createOrder(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:s.CREATE_ORDER_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-order",metadata:{step:"createOrder"}}),y({errorCode:s.CREATE_ORDER_ERROR},e)}}))}createPayment(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:s.CREATE_PAYMENT_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-payment",metadata:{step:"createPayment"}}),y({errorCode:s.CREATE_PAYMENT_ERROR},e)}}))}startCheckoutRouter(e){return r(this,void 0,void 0,(function*(){const t=yield A(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return r(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return r(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:n,return_url:i,isSandbox:a,metadata:d,currency:c,payment_method:u}=e,h=yield this._fetchMerchantData(),_=yield this.customerRegister(o.email);if(!(_&&"auth_token"in _&&h&&"reference"in h))throw y({errorCode:s.START_CHECKOUT_ERROR,details:{message:"Merchant or customer reposne errors",merchantResult:h,customerResult:_}});{const e={business:this.apiKeyTonder,client:_.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:h.reference,is_oneclick:!0,items:t.items},E=yield this.createOrder(e),p=(new Date).toISOString();if(!("id"in E&&"id"in _&&"business"in h))throw y({errorCode:s.START_CHECKOUT_ERROR,details:{message:"Order response errors",orderResult:E}});{const e={business_pk:h.business.pk,amount:r,date:p,order_id:E.id,client_id:_.id},t=yield this.createPayment(e);let s;const{openpay_keys:m,business:R}=h;m.merchant_id&&m.public_key&&(s=yield C(m.merchant_id,m.public_key,a));const y=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:i,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:s||null,token_id:"",order_id:"id"in E&&E.id,business_id:R.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:l(),currency:c},u?{payment_method:u}:{card:n}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),v=yield A(this.baseUrl,this.apiKeyTonder,y);if(yield this.init3DSRedirect(v))return v}}}catch(e){throw this.reportSdkError(e,{feature:"start-checkout-router-full",metadata:{step:"startCheckoutRouterFull"}}),y({errorCode:s.START_CHECKOUT_ERROR},e)}}))}registerCustomerCard(e,t,o){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const r=yield fetch(`${this.baseUrl}/api/v1/business/${c(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(r.ok)return yield r.json();throw yield y({response:r,errorCode:s.SAVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"register-customer-card",metadata:{step:"registerCustomerCard"}}),y({errorCode:s.SAVE_CARD_ERROR},e)}}))}deleteCustomerCard(e,t=""){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const r=yield fetch(`${this.baseUrl}/api/v1/business/${c(this.merchantData)}/cards/${t}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(r.ok)return!0;throw yield y({response:r,errorCode:s.REMOVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"delete-customer-card",process_id:t,metadata:{step:"deleteCustomerCard"}}),y({errorCode:s.REMOVE_CARD_ERROR},e)}}))}getActiveAPMs(){return r(this,void 0,void 0,(function*(){try{const e=yield function(e,t,o="?status=active&page_size=10000&country=México",n=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:n});if(r.ok)return yield r.json();throw yield y({response:r,errorCode:s.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder),t=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=t.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},ye(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function fe(e){return/^\d{12,19}$/.test(e)&&ge(e)}function Ae(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function Ce(e){return/^\d{3,4}$/.test(e)}function Oe(e){return/^(0[1-9]|1[0-2])$/.test(e)}function Te(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const ge=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),r=t.shift();let o=t.reduce(((e,t,r)=>r%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=r,o%10==0};export{_ as AppError,z as BaseInlineCheckout,ve as LiteCheckout,M as SdkTelemetryClient,Ce as validateCVV,fe as validateCardNumber,Ae as validateCardholderName,Oe as validateExpirationMonth,Te as validateExpirationYear};
|
|
@@ -4,6 +4,7 @@ export interface IAppErrorInput {
|
|
|
4
4
|
statusCode?: number;
|
|
5
5
|
details?: Record<string, unknown>;
|
|
6
6
|
originalError?: unknown;
|
|
7
|
+
lockErrorCode?: boolean;
|
|
7
8
|
}
|
|
8
9
|
export declare class AppError extends Error {
|
|
9
10
|
readonly status: 'error';
|
|
@@ -26,6 +27,7 @@ export interface IBuildPublicAppErrorInput {
|
|
|
26
27
|
details?: Record<string, unknown>;
|
|
27
28
|
statusCode?: number;
|
|
28
29
|
response?: Response;
|
|
30
|
+
lockErrorCode?: boolean;
|
|
29
31
|
}
|
|
30
32
|
export declare function buildPublicAppError(data: IBuildPublicAppErrorInput & {
|
|
31
33
|
response: Response;
|
package/package.json
CHANGED
|
@@ -44,7 +44,6 @@ import {ILiteCheckout} from "../types/liteInlineCheckout";
|
|
|
44
44
|
import CollectorContainer from "skyflow-js/types/core/external/collect/collect-container";
|
|
45
45
|
import Skyflow from "skyflow-js";
|
|
46
46
|
import { buildPublicAppError } from "../shared/utils/appError";
|
|
47
|
-
import { MESSAGES_EN } from "../shared/constants/messages";
|
|
48
47
|
import { SDK_INFO } from "../helpers/sdkInfo";
|
|
49
48
|
|
|
50
49
|
declare const MP_DEVICE_SESSION_ID: string | undefined;
|
|
@@ -185,8 +184,8 @@ export class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout{
|
|
|
185
184
|
} catch (processError) {
|
|
186
185
|
throw buildPublicAppError(
|
|
187
186
|
{
|
|
188
|
-
errorCode: ErrorKeyEnum.
|
|
189
|
-
|
|
187
|
+
errorCode: ErrorKeyEnum.CARD_ON_FILE_DECLINED,
|
|
188
|
+
lockErrorCode: true,
|
|
190
189
|
},
|
|
191
190
|
processError,
|
|
192
191
|
);
|
|
@@ -602,8 +601,8 @@ export class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout{
|
|
|
602
601
|
} catch (processError) {
|
|
603
602
|
throw buildPublicAppError(
|
|
604
603
|
{
|
|
605
|
-
errorCode: ErrorKeyEnum.
|
|
606
|
-
|
|
604
|
+
errorCode: ErrorKeyEnum.CARD_ON_FILE_DECLINED,
|
|
605
|
+
lockErrorCode: true,
|
|
607
606
|
},
|
|
608
607
|
processError,
|
|
609
608
|
);
|
|
@@ -62,6 +62,7 @@ async function loadAcquirerScript(): Promise<void> {
|
|
|
62
62
|
reject(
|
|
63
63
|
buildPublicAppError({
|
|
64
64
|
errorCode: CARD_ON_FILE_ERROR_CODE,
|
|
65
|
+
lockErrorCode: true,
|
|
65
66
|
details: {
|
|
66
67
|
step: "load_acquirer_script",
|
|
67
68
|
message: "Failed to load acquirer script",
|
|
@@ -83,6 +84,7 @@ function createAcquirerInstance(
|
|
|
83
84
|
if (!window.Kushki) {
|
|
84
85
|
throw buildPublicAppError({
|
|
85
86
|
errorCode: CARD_ON_FILE_ERROR_CODE,
|
|
87
|
+
lockErrorCode: true,
|
|
86
88
|
details: {
|
|
87
89
|
step: "create_acquirer_instance",
|
|
88
90
|
message: "Acquirer script not loaded. Call initialize() first.",
|
|
@@ -130,6 +132,7 @@ export class CardOnFile {
|
|
|
130
132
|
if (!this.acquirerInstance) {
|
|
131
133
|
throw buildPublicAppError({
|
|
132
134
|
errorCode: CARD_ON_FILE_ERROR_CODE,
|
|
135
|
+
lockErrorCode: true,
|
|
133
136
|
details: {
|
|
134
137
|
step: "get_acquirer_instance",
|
|
135
138
|
message: "CardOnFile not initialized. Call initialize() first.",
|
|
@@ -158,6 +161,7 @@ export class CardOnFile {
|
|
|
158
161
|
reject(
|
|
159
162
|
buildPublicAppError({
|
|
160
163
|
errorCode: CARD_ON_FILE_ERROR_CODE,
|
|
164
|
+
lockErrorCode: true,
|
|
161
165
|
details: {
|
|
162
166
|
step: "get_jwt",
|
|
163
167
|
acquirerResponse: response as unknown as Record<string, unknown>,
|
|
@@ -172,6 +176,7 @@ export class CardOnFile {
|
|
|
172
176
|
reject(
|
|
173
177
|
buildPublicAppError({
|
|
174
178
|
errorCode: CARD_ON_FILE_ERROR_CODE,
|
|
179
|
+
lockErrorCode: true,
|
|
175
180
|
details: {
|
|
176
181
|
step: "get_jwt",
|
|
177
182
|
message: "No JWT returned from acquirer",
|
|
@@ -208,6 +213,7 @@ export class CardOnFile {
|
|
|
208
213
|
throw await buildPublicAppError({
|
|
209
214
|
response,
|
|
210
215
|
errorCode: CARD_ON_FILE_ERROR_CODE,
|
|
216
|
+
lockErrorCode: true,
|
|
211
217
|
details: {
|
|
212
218
|
step: "generate_token",
|
|
213
219
|
},
|
|
@@ -237,6 +243,7 @@ export class CardOnFile {
|
|
|
237
243
|
throw await buildPublicAppError({
|
|
238
244
|
response,
|
|
239
245
|
errorCode: CARD_ON_FILE_ERROR_CODE,
|
|
246
|
+
lockErrorCode: true,
|
|
240
247
|
details: {
|
|
241
248
|
step: "create_subscription",
|
|
242
249
|
},
|
|
@@ -269,6 +276,7 @@ export class CardOnFile {
|
|
|
269
276
|
reject(
|
|
270
277
|
buildPublicAppError({
|
|
271
278
|
errorCode: CARD_ON_FILE_ERROR_CODE,
|
|
279
|
+
lockErrorCode: true,
|
|
272
280
|
details: {
|
|
273
281
|
step: "validate_3ds",
|
|
274
282
|
message: "3DS validation failed",
|
|
@@ -284,6 +292,7 @@ export class CardOnFile {
|
|
|
284
292
|
reject(
|
|
285
293
|
buildPublicAppError({
|
|
286
294
|
errorCode: CARD_ON_FILE_ERROR_CODE,
|
|
295
|
+
lockErrorCode: true,
|
|
287
296
|
details: {
|
|
288
297
|
step: "validate_3ds",
|
|
289
298
|
message: "3DS validation failed",
|
|
@@ -318,6 +327,7 @@ export class CardOnFile {
|
|
|
318
327
|
if (!secureId || !security) {
|
|
319
328
|
throw buildPublicAppError({
|
|
320
329
|
errorCode: CARD_ON_FILE_ERROR_CODE,
|
|
330
|
+
lockErrorCode: true,
|
|
321
331
|
details: {
|
|
322
332
|
step: "process",
|
|
323
333
|
message: "Missing secureId or security in token response",
|
|
@@ -331,7 +341,7 @@ export class CardOnFile {
|
|
|
331
341
|
|
|
332
342
|
// Only continue to subscription if 3DS validation passed
|
|
333
343
|
return this.createSubscription({
|
|
334
|
-
token:
|
|
344
|
+
token: tokenResponse.token,
|
|
335
345
|
contactDetails: params.contactDetails,
|
|
336
346
|
metadata: {
|
|
337
347
|
customerId: params.customerId,
|
|
@@ -2,6 +2,11 @@ import { MESSAGES_EN } from '../constants/messages';
|
|
|
2
2
|
import { ErrorKeyEnum } from '../enum/ErrorKeyEnum';
|
|
3
3
|
|
|
4
4
|
const DEFAULT_SYSTEM_ERROR = 'APP_INTERNAL_001';
|
|
5
|
+
const LOCK_ERROR_CODE_KEY = '__tonderLockErrorCode__';
|
|
6
|
+
|
|
7
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
8
|
+
return typeof value === 'object' && value !== null;
|
|
9
|
+
}
|
|
5
10
|
|
|
6
11
|
export interface IAppErrorInput {
|
|
7
12
|
errorCode: string;
|
|
@@ -9,6 +14,7 @@ export interface IAppErrorInput {
|
|
|
9
14
|
statusCode?: number;
|
|
10
15
|
details?: Record<string, unknown>;
|
|
11
16
|
originalError?: unknown;
|
|
17
|
+
lockErrorCode?: boolean;
|
|
12
18
|
}
|
|
13
19
|
|
|
14
20
|
export class AppError extends Error {
|
|
@@ -46,6 +52,14 @@ export class AppError extends Error {
|
|
|
46
52
|
systemError: resolvedSystemError,
|
|
47
53
|
};
|
|
48
54
|
|
|
55
|
+
if (error.lockErrorCode) {
|
|
56
|
+
Object.defineProperty(this, LOCK_ERROR_CODE_KEY, {
|
|
57
|
+
value: true,
|
|
58
|
+
enumerable: false,
|
|
59
|
+
configurable: true,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
49
63
|
Error.captureStackTrace?.(this, AppError);
|
|
50
64
|
}
|
|
51
65
|
|
|
@@ -153,6 +167,27 @@ export interface IBuildPublicAppErrorInput {
|
|
|
153
167
|
details?: Record<string, unknown>;
|
|
154
168
|
statusCode?: number;
|
|
155
169
|
response?: Response;
|
|
170
|
+
lockErrorCode?: boolean;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function markErrorCodeLocked(error: Record<string, unknown>): void {
|
|
174
|
+
Object.defineProperty(error, LOCK_ERROR_CODE_KEY, {
|
|
175
|
+
value: true,
|
|
176
|
+
enumerable: false,
|
|
177
|
+
configurable: true,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function hasLockedErrorCode(error: unknown): boolean {
|
|
182
|
+
return isRecord(error) && error[LOCK_ERROR_CODE_KEY] === true;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function isTonderAppErrorLike(error: unknown): error is AppError {
|
|
186
|
+
return (
|
|
187
|
+
isRecord(error) &&
|
|
188
|
+
error.name === 'TonderError' &&
|
|
189
|
+
typeof error.code === 'string'
|
|
190
|
+
);
|
|
156
191
|
}
|
|
157
192
|
|
|
158
193
|
function getOriginalError(error: unknown): unknown {
|
|
@@ -187,14 +222,21 @@ function buildPublicAppErrorSync(
|
|
|
187
222
|
}
|
|
188
223
|
|
|
189
224
|
const explicitSystemError = data.details?.systemError;
|
|
190
|
-
const
|
|
191
|
-
data.errorCode !== (error as any)?.code ||
|
|
225
|
+
const hasExplicitOverrides =
|
|
192
226
|
!!data.message ||
|
|
193
227
|
data.statusCode !== undefined ||
|
|
194
228
|
explicitSystemError !== undefined;
|
|
195
229
|
|
|
196
|
-
if (error
|
|
197
|
-
|
|
230
|
+
if (isTonderAppErrorLike(error)) {
|
|
231
|
+
if (data.lockErrorCode) {
|
|
232
|
+
markErrorCodeLocked(error as unknown as Record<string, unknown>);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (!hasExplicitOverrides) {
|
|
236
|
+
if (data.errorCode === error.code || hasLockedErrorCode(error)) {
|
|
237
|
+
return error;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
198
240
|
}
|
|
199
241
|
|
|
200
242
|
return new AppError({
|
|
@@ -206,6 +248,7 @@ function buildPublicAppErrorSync(
|
|
|
206
248
|
? { systemError: explicitSystemError }
|
|
207
249
|
: undefined,
|
|
208
250
|
originalError: getOriginalError(error),
|
|
251
|
+
lockErrorCode: data.lockErrorCode || hasLockedErrorCode(error),
|
|
209
252
|
});
|
|
210
253
|
}
|
|
211
254
|
|
|
@@ -235,6 +278,7 @@ async function buildPublicAppErrorFromHttpResponse(
|
|
|
235
278
|
? { systemError: data.details.systemError }
|
|
236
279
|
: undefined,
|
|
237
280
|
originalError,
|
|
281
|
+
lockErrorCode: data.lockErrorCode,
|
|
238
282
|
});
|
|
239
283
|
}
|
|
240
284
|
|