@tonder.io/ionic-lite-sdk 0.0.67 → 0.0.68-beta.DEV-2106.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/classes/BaseInlineCheckout.d.ts +11 -0
  2. package/dist/classes/SdkTelemetryClient.d.ts +86 -0
  3. package/dist/helpers/SdkTelemetryClient.d.ts +47 -0
  4. package/dist/helpers/sdkInfo.d.ts +4 -0
  5. package/dist/helpers/utils.d.ts +1 -7
  6. package/dist/index.d.ts +3 -1
  7. package/dist/index.js +1 -1
  8. package/dist/shared/constants/apiEndpoints.d.ts +25 -0
  9. package/dist/shared/constants/messages.d.ts +1 -0
  10. package/dist/shared/enum/ErrorKeyEnum.d.ts +1 -0
  11. package/dist/shared/utils/appError.d.ts +25 -0
  12. package/dist/types/checkout.d.ts +2 -0
  13. package/dist/types/commons.d.ts +3 -2
  14. package/dist/types/jsx-web-components.d.ts +17 -0
  15. package/dist/types/requests.d.ts +7 -0
  16. package/dist/types/telemetry.d.ts +51 -0
  17. package/dist/ui/components/input/CardCVVInput.d.ts +19 -0
  18. package/package.json +3 -1
  19. package/rollup.config.js +9 -0
  20. package/src/classes/BaseInlineCheckout.ts +111 -13
  21. package/src/classes/liteCheckout.ts +160 -41
  22. package/src/data/cardApi.ts +3 -2
  23. package/src/helpers/SdkTelemetryClient.ts +191 -0
  24. package/src/helpers/card_on_file.ts +6 -8
  25. package/src/helpers/sdkInfo.ts +11 -0
  26. package/src/helpers/utils.ts +0 -24
  27. package/src/index.ts +5 -1
  28. package/src/shared/constants/apiEndpoints.ts +37 -0
  29. package/src/shared/constants/messages.ts +4 -0
  30. package/src/shared/enum/ErrorKeyEnum.ts +1 -0
  31. package/src/shared/utils/appError.ts +146 -0
  32. package/src/types/checkout.ts +2 -0
  33. package/src/types/commons.ts +4 -3
  34. package/src/types/requests.ts +7 -0
  35. package/src/types/telemetry.ts +54 -0
  36. package/tsconfig.json +1 -0
@@ -7,6 +7,7 @@ import { IPaymentMethodResponse } from "../types/paymentMethod";
7
7
  import { ITransaction } from "../types/transaction";
8
8
  import { GetSecureTokenResponse } from "../types/responses";
9
9
  import { CardOnFile } from "../helpers/card_on_file";
10
+ import { SdkTelemetryClient } from "../helpers/SdkTelemetryClient";
10
11
  export declare class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOptions> {
11
12
  #private;
12
13
  baseUrl: string;
@@ -31,8 +32,18 @@ export declare class BaseInlineCheckout<T extends CustomizationOptions = Customi
31
32
  card?: {} | undefined;
32
33
  currency?: string;
33
34
  protected cardOnFileInstance: CardOnFile | null;
35
+ protected telemetry: SdkTelemetryClient;
34
36
  constructor({ mode, customization, apiKey, apiKeyTonder, returnUrl, tdsIframeId, callBack, baseUrlTonder, tonderPayButtonId }: IInlineCheckoutBaseOptions);
35
37
  configureCheckout(data: IConfigureCheckout): void;
38
+ /**
39
+ * Get customer ID for telemetry (if available)
40
+ */
41
+ protected getCustomerId(): string | undefined;
42
+ /**
43
+ * Report SDK errors to telemetry endpoint
44
+ * NEVER throws - completely silent on failure
45
+ */
46
+ protected reportSdkError(err: unknown, extra?: Record<string, any>): void;
36
47
  verify3dsTransaction(): Promise<ITransaction | IStartCheckoutResponse | void>;
37
48
  payment(data: IProcessPaymentRequest): Promise<IStartCheckoutResponse>;
38
49
  getSecureToken(secretApikey: string): Promise<GetSecureTokenResponse>;
@@ -0,0 +1,86 @@
1
+ import { ITelemetryConfig, ITelemetryContext } from "../types/telemetry";
2
+ /**
3
+ * SdkTelemetryClient - Internal SDK error reporting
4
+ *
5
+ * Features:
6
+ * - Ring buffer (max 100 events)
7
+ * - Batching (flush every 5s or 10 events)
8
+ * - Circuit breaker (3 consecutive failures = 10 min pause)
9
+ * - Non-blocking (never throws)
10
+ * - Sanitization (truncate message/stack, allowlist context)
11
+ * - Retry with backoff (max 1 retry)
12
+ */
13
+ export declare class SdkTelemetryClient {
14
+ private config;
15
+ private buffer;
16
+ private readonly MAX_BUFFER_SIZE;
17
+ private readonly BATCH_SIZE;
18
+ private readonly FLUSH_INTERVAL_MS;
19
+ private readonly REQUEST_TIMEOUT_MS;
20
+ private readonly MAX_MESSAGE_LENGTH;
21
+ private readonly MAX_STACK_LENGTH;
22
+ private readonly MAX_RETRIES;
23
+ private readonly CIRCUIT_BREAKER_THRESHOLD;
24
+ private readonly CIRCUIT_BREAKER_TIMEOUT_MS;
25
+ private flushTimer;
26
+ private circuitBreaker;
27
+ constructor(config: ITelemetryConfig);
28
+ /**
29
+ * Capture an exception and queue it for sending
30
+ * @param error - Error object or any thrown value
31
+ * @param context - Additional context (tenant_id, feature, process_id, user_id, metadata, etc.)
32
+ */
33
+ captureException(error: unknown, context?: ITelemetryContext): void;
34
+ /**
35
+ * Extract error information from error object
36
+ */
37
+ private extractErrorInfo;
38
+ /**
39
+ * Safe stringify with circular reference protection
40
+ */
41
+ private safeStringify;
42
+ /**
43
+ * Build telemetry event with API format
44
+ */
45
+ private buildEvent;
46
+ /**
47
+ * Truncate string to max length
48
+ */
49
+ private truncate;
50
+ /**
51
+ * Start automatic flush timer
52
+ */
53
+ private startFlushTimer;
54
+ /**
55
+ * Flush buffer - send all pending events
56
+ */
57
+ private flush;
58
+ /**
59
+ * Send a single event with retry logic
60
+ */
61
+ private sendEvent;
62
+ /**
63
+ * Send HTTP request to telemetry endpoint
64
+ */
65
+ private sendHttpRequest;
66
+ /**
67
+ * Handle successful send
68
+ */
69
+ private onSendSuccess;
70
+ /**
71
+ * Handle send failure with retry logic
72
+ */
73
+ private onSendFailure;
74
+ /**
75
+ * Open circuit breaker
76
+ */
77
+ private openCircuitBreaker;
78
+ /**
79
+ * Check if circuit breaker is open
80
+ */
81
+ private isCircuitBreakerOpen;
82
+ /**
83
+ * Cleanup - stop flush timer
84
+ */
85
+ destroy(): void;
86
+ }
@@ -0,0 +1,47 @@
1
+ import { ITelemetryConfig, ITelemetryContext } from "../types/telemetry";
2
+ /**
3
+ * SdkTelemetryClient - Internal SDK error reporting (Simplified)
4
+ *
5
+ * Features:
6
+ * - Immediate send (no batching or buffer)
7
+ * - Non-blocking (never throws)
8
+ * - Sanitization (truncate message/stack)
9
+ * - Fire-and-forget with timeout
10
+ */
11
+ export declare class SdkTelemetryClient {
12
+ private config;
13
+ private readonly REQUEST_TIMEOUT_MS;
14
+ private readonly MAX_MESSAGE_LENGTH;
15
+ private readonly MAX_STACK_LENGTH;
16
+ constructor(config: ITelemetryConfig);
17
+ /**
18
+ * Capture an exception and send immediately
19
+ * @param error - Error object or any thrown value
20
+ * @param context - Additional context (tenant_id, feature, process_id, user_id, metadata, etc.)
21
+ */
22
+ captureException(error: unknown, context?: ITelemetryContext): void;
23
+ /**
24
+ * Extract error information from error object
25
+ */
26
+ private extractErrorInfo;
27
+ /**
28
+ * Safe stringify with circular reference protection
29
+ */
30
+ private safeStringify;
31
+ /**
32
+ * Build telemetry event with API format
33
+ */
34
+ private buildEvent;
35
+ /**
36
+ * Truncate string to max length
37
+ */
38
+ private truncate;
39
+ /**
40
+ * Send event immediately (fire-and-forget)
41
+ */
42
+ private sendEvent;
43
+ /**
44
+ * Send HTTP request to telemetry endpoint
45
+ */
46
+ private sendHttpRequest;
47
+ }
@@ -0,0 +1,4 @@
1
+ export declare const SDK_INFO: Readonly<{
2
+ name: string;
3
+ version: string;
4
+ }>;
@@ -11,12 +11,6 @@ export declare const getBrowserInfo: () => {
11
11
  export declare const getBusinessId: (merchantData: any) => any;
12
12
  declare const buildErrorResponseFromCatch: (e: any) => ErrorResponse;
13
13
  declare const buildErrorResponse: (response: Response, stack?: string | undefined) => Promise<ErrorResponse>;
14
- declare function formatPublicErrorResponse(data: Record<string, any>, error: any): {
15
- status: string;
16
- code: number;
17
- message: string;
18
- detail: any;
19
- };
20
14
  declare const clearSpace: (text: string) => string;
21
15
  declare const getCardType: (scheme: string) => "https://d35a75syrgujp0.cloudfront.net/cards/visa.png" | "https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png" | "https://d35a75syrgujp0.cloudfront.net/cards/american_express.png" | "https://d35a75syrgujp0.cloudfront.net/cards/default_card.png";
22
- export { buildErrorResponseFromCatch, buildErrorResponse, getCardType, formatPublicErrorResponse, clearSpace, };
16
+ export { buildErrorResponseFromCatch, buildErrorResponse, getCardType, clearSpace, };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { LiteCheckout } from './classes/liteCheckout';
2
2
  import { BaseInlineCheckout } from './classes/BaseInlineCheckout';
3
+ import { SdkTelemetryClient } from './helpers/SdkTelemetryClient';
4
+ import { AppError } from './shared/utils/appError';
3
5
  import { validateCVV, validateCardNumber, validateExpirationMonth, validateCardholderName, validateExpirationYear } from './helpers/validations';
4
- export { LiteCheckout, BaseInlineCheckout, validateCVV, validateCardNumber, validateCardholderName, validateExpirationMonth, validateExpirationYear };
6
+ export { LiteCheckout, BaseInlineCheckout, SdkTelemetryClient, AppError, validateCVV, validateCardNumber, validateCardholderName, validateExpirationMonth, validateExpirationYear };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{get as e}from"lodash";import t from"skyflow-js";function n(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{d(r.next(e))}catch(e){o(e)}}function a(e){try{d(r.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((r=r.apply(e,t||[])).next())}))}function r(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function i(e,t,n,r,i){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?i.call(e,n):i?i.value=n:t.set(e,n),n}function o(e,t,r){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:r});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:e,body:t,name:n,message:r,stack:i}){this.code=e,this.body=t,this.name=n,this.message=r,this.stack=i}}var a;!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_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"}(a||(a={}));const d=Object.freeze({saveCardError:"Ha ocurrido un error guardando la tarjeta. Inténtalo nuevamente.",removeCardError:"Ha ocurrido un error eliminado la tarjeta. Inténtalo nuevamente.",getCardsError:"Ha ocurrido un error obteniendo las tarjetas del customer. Inténtalo nuevamente.",cardExist:"La tarjeta fue registrada previamente.",removedCard:"Card deleted successfully",errorCheckout:"No se ha podido procesar el pago",cardSaved:"Tarjeta registrada con éxito.",getPaymentMethodsError:"Ha ocurrido un error obteniendo las métodos de pago del customer. Inténtalo nuevamente.",getBusinessError:"Ha ocurrido un error obteniendo los datos del comercio. Inténtalo nuevamente.",secureTokenError:"Ha ocurrido un error obteniendo el token de seguridad."}),l={[a.INIT_ERROR]:"Error initializing the SDK.",[a.INVALID_TYPE]:"SDK Type invalid.",[a.STATE_ERROR]:"Error updating SDK state.",[a.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[a.INVALID_CONFIG]:"Required configuration options.",[a.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[a.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[a.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[a.TYPE_SDK_REQUIRED]:"SDK type required.",[a.ENVIRONMENT_REQUIRED]:"Environment required.",[a.FETCH_CARDS_ERROR]:"Error retrieving cards.",[a.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.",[a.SAVE_CARD_ERROR]:"Error saving the card.",[a.REMOVE_CARD_ERROR]:"Error deleting the card.",[a.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[a.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[a.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[a.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[a.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[a.START_CHECKOUT_ERROR]:"Error processing the payment.",[a.CREATE_ORDER_ERROR]:"Error creating the order.",[a.BUSINESS_ID_REQUIRED]:"Business ID is required.",[a.CLIENT_ID_REQUIRED]:"Client ID is required.",[a.INVALID_AMOUNT]:"Invalid amount.",[a.INVALID_ITEMS]:"Invalid items.",[a.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[a.INVALID_EMAIL]:"Invalid email.",[a.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[a.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[a.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[a.SECURE_TOKEN_ERROR]:"Error getting secure token.",[a.SECURE_TOKEN_INVALID]:"Invalid secure token.",[a.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[a.REMOVE_CARD]:"Card deleted successfully",[a.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[a.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[a.INVALID_CARD_DATA]:"Invalid card data.",[a.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[a.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[a.REQUEST_ABORTED]:"Requests canceled.",[a.REQUEST_FAILED]:"Request failed.",[a.UNKNOWN_ERROR]:"An unexpected error occurred.",[a.CREATE_ERROR]:"Error creating the SDK.",[a.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[a.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[a.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};a.INIT_ERROR,a.STATE_ERROR,a.FETCH_BUSINESS_ERROR,a.INVALID_CONFIG,a.TYPE_SDK_REQUIRED,a.ENVIRONMENT_REQUIRED,a.FETCH_CARDS_ERROR,a.SAVE_CARD_ERROR,a.REMOVE_CARD_ERROR,a.CREATE_PAYMENT_ERROR,a.START_CHECKOUT_ERROR,a.CREATE_ORDER_ERROR,a.BUSINESS_ID_REQUIRED,a.CLIENT_ID_REQUIRED,a.INVALID_AMOUNT,a.INVALID_ITEMS,a.CUSTOMER_OPERATION_ERROR,a.INVALID_EMAIL,a.FETCH_PAYMENT_METHODS_ERROR,a.INVALID_VAULT_TOKEN,a.VAULT_TOKEN_ERROR,a.SECURE_TOKEN_ERROR,a.INVALID_SECRET_API_KEY,a.CUSTOMER_AUTH_TOKEN_NOT_VALID,a.SECURE_TOKEN_INVALID,a.REMOVE_CARD,a.SKYFLOW_NOT_INITIALIZED,a.INVALID_TYPE,a.PAYMENT_PROCESS_ERROR,a.INVALID_PAYMENT_REQUEST,a.INVALID_PAYMENT_REQUEST_CARD_PM,a.SAVE_CARD_PROCESS_ERROR,a.ERROR_LOAD_PAYMENT_FORM,a.INVALID_CARD_DATA,a.ERROR_LOAD_ENROLLMENT_FORM,a.MOUNT_COLLECT_ERROR,a.CARD_SAVED_SUCCESSFULLY,a.CARD_REMOVED_SUCCESSFULLY,a.REQUEST_ABORTED,a.REQUEST_FAILED,a.UNKNOWN_ERROR,a.CREATE_ERROR,a.FETCH_TRANSACTION_ERROR,a.THREEDS_REDIRECTION_ERROR,a.REMOVE_SDK_ERROR;class c extends Error{constructor(e){var t,n;const r=e.message||l[e.code]||"Unknown error";super(r),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===(n=e.details)||void 0===n?void 0:n.message)||r}}}const u=()=>({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}),h=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},_=e=>new s({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack}),p=(e,t=void 0)=>n(void 0,void 0,void 0,(function*(){let n,r,i="Error";e&&"json"in e&&(n=yield null==e?void 0:e.json()),e&&"status"in e&&(r=e.status.toString()),!n&&e&&"text"in e&&(i=yield e.text()),(null==n?void 0:n.detail)&&(i=n.detail);return new s({code:r,body:n,name:r,message:i,stack:t})}));function m(e,t){var n,r;let i=200;try{i=Number((null==t?void 0:t.code)||200)}catch(e){}const o={status:"error",code:i,message:"",detail:(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.detail)||(null===(r=null==t?void 0:t.body)||void 0===r?void 0:r.error)||t.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},o),e)}class E{constructor({payload:e=null,apiKey:t,baseUrl:n,redirectOnComplete:r,tdsIframeId:i,tonderPayButtonId:o,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=n,this.apiKey=t,this.payload=e,this.tdsIframeId=i,this.tonderPayButtonId=o,this.redirectOnComplete=r,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,n,r,i,o;const s=null===(n=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===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(o=null===(i=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===i?void 0:i.iframe_resources)||void 0===o?void 0:o.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,n;if(null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((e,t)=>{var n,r,i;const o=null===(i=null===(r=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.iframe;if(o){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=o,document.body.appendChild(n);const r=document.createElement("script");r.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(r);const i=document.getElementById("tdsMmethodTgtFrame");i?i.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,n;return null===(n=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===n?void 0:n.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 r=this,i=e=>n(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"),r.callBack&&r.callBack(r.payload),t.removeEventListener("load",i)},o=t=>n(this,void 0,void 0,(function*(){const i=yield new Promise(((e,n)=>e(t)));if(i){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(i))return e();{const e=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(e),yield o(r.requestTransactionStatus())}))),7e3)}}}));yield o(r.requestTransactionStatus())}));t.addEventListener("load",i)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,n=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==n.status)return console.error("La verificación de la transacción falló."),null;return yield n.json()}))}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[n,r]of t)e[n]=r;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return n(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=e.creq,n.value=e.creq,t.appendChild(n);const r=document.createElement("input");r.type="hidden",r.name=e.term_url,r.value=e.TermUrl,t.appendChild(r),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return n(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 n(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 y=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,r){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/checkout-router/`,i=r,o=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},i),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(o.status>=200&&o.status<=299)return yield o.json();{const e=yield o.json(),t=new Error("Failed to start checkout router");throw t.details=e,t}}catch(e){throw e}}))}function v(e,t,r=!0,i=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(e),n.setApiKey(t),n.setSandboxMode(r),yield n.deviceData.setup({signal:i})}))}const A="https://cdn.kushkipagos.com/kushki.min.js";let f=!1,O=null;class T{constructor(e){var t;this.acquirerInstance=null,this.isTestEnvironment=null===(t=e.isTestEnvironment)||void 0===t||t,this.apiUrl=this.isTestEnvironment?"https://api-stage.tonder.io":"https://api.tonder.io",this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return n(this,void 0,void 0,(function*(){yield function(){return n(this,void 0,void 0,(function*(){return f?Promise.resolve():O||(O=new Promise(((e,t)=>{if(document.querySelector(`script[src="${A}"]`))return f=!0,void e();const n=document.createElement("script");n.src=A,n.async=!0,n.onload=()=>{f=!0,e()},n.onerror=()=>{O=null,t(new Error("Failed to load acquirer script"))},document.head.appendChild(n)})),O)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw new Error("Acquirer script not loaded. Call initialize() first.");return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw new Error("CardOnFile not initialized. Call initialize() first.");return this.acquirerInstance}getJwt(e){return n(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((n,r)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void r(new Error(`Error getting JWT: ${e.message}`));const t=e;t.jwt?n(t.jwt):r(new Error("No JWT returned from acquirer"))}))}))}))}generateToken(e){return n(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}/acq-kushki/subscription/token`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok){const e=yield t.text();throw new Error(`Failed to generate token: ${t.status} - ${e}`)}return t.json()}))}createSubscription(e){return n(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}/acq-kushki/subscription/create`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok){const e=yield t.text();throw new Error(`Failed to create subscription: ${t.status} - ${e}`)}return t.json()}))}validate3DS(e,t){return n(this,void 0,void 0,(function*(){const n=this.getAcquirerInstance();return new Promise(((r,i)=>{n.requestValidate3DS({secureId:e,security:t},(e=>{const t=e;t.code&&"3DS000"!==t.code?i(new Error("3DS validation failed}")):!1!==t.isValid?r(!0):i(new Error("3DS validation failed"))}))}))}))}process(e){var t,r;return n(this,void 0,void 0,(function*(){const n=yield this.getJwt(e.cardBin),i=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:n}),o=i.secureId||(null===(t=i.details)||void 0===t?void 0:t.secureId),s=i.security||(null===(r=i.details)||void 0===r?void 0:r.security);if(!o||!s)throw new Error("Missing secureId or security in token response");return yield this.validate3DS(o,s),this.createSubscription({token:i.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}var g,C,I,S,N,b,D,M,U,L,w,k,P;class j{constructor({mode:e="stage",customization:t,apiKey:n,apiKeyTonder:r,returnUrl:i,tdsIframeId:o,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){g.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,C.set(this,void 0),I.set(this,void 0),this.apiKeyTonder=r||n||"",this.returnUrl=i,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||y[this.mode]||y.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new E({apiKey:n,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:o,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=o}configureCheckout(e){"secureToken"in e&&r(this,g,"m",b).call(this,e.secureToken),r(this,g,"m",S).call(this,e)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield r(this,g,"m",w).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,i)=>n(this,void 0,void 0,(function*(){try{r(this,g,"m",S).call(this,e);const n=yield this._checkout(e);this.process3ds.setPayload(n);if(yield this._handle3dsRedirect(n)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(n),t(n)}}catch(e){i(e)}}))))}getSecureToken(e){return n(this,void 0,void 0,(function*(){try{return yield function(e,t,r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw _(e)}}))}(this.baseUrl,e)}catch(e){throw m({message:d.secureTokenError},e)}}))}_initializeCheckout(){return n(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 n(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 n(this,void 0,void 0,(function*(){return r(this,I,"f")||i(this,I,yield function(e,t,r,i=null){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/customer/`,o={email:r.email,first_name:null==r?void 0:r.firstName,last_name:null==r?void 0:r.lastName,phone:null==r?void 0:r.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:i,body:JSON.stringify(o)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),r(this,I,"f")}))}_handleCheckout({card:t,payment_method:i,customer:o,isSandbox:s,enable_card_on_file:a,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:h}=this.merchantData,_=Number(this.cartTotal);try{let p;!p&&l.merchant_id&&l.public_key&&!i&&(p=yield v(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:m,auth_token:E}=o,y={business:this.apiKeyTonder,client:E,billing_address_id:null,shipping_address_id:null,amount:_,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata},A=yield function(e,t,r){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/orders/`,i=r,o=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(i)});if(201===o.status)return yield o.json();throw new Error(`Error: ${o.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,y),f=(new Date).toISOString(),O={business_pk:h.pk,client_id:m,amount:_,date:f,order_id:A.id,customer_order_reference:this.order_reference?this.order_reference:c,items:this.cartItems,currency:this.currency,metadata:this.metadata},T=yield function(e,t,r){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/business/${r.business_pk}/payments/`,i=r,o=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(i)});if(o.status>=200&&o.status<=299)return yield o.json();throw new Error(`Error: ${o.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,O),g=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:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:_,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:h.pk,payment_id:T.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:u(),currency:this.currency},i?{payment_method:i}:{card:t}),{apm_config:r(this,C,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==a?{enable_card_on_file:a}:{}),I=yield R(this.baseUrl,this.apiKeyTonder,g);return I||!1}catch(e){throw console.log(e),e}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield o(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.merchantData}}))}_getCustomerCards(e,t){return n(this,void 0,void 0,(function*(){return yield function(e,t,r,i,o=null){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${i}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","User-token":t},signal:o});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield p(s)}catch(e){throw _(e)}}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,r,i=!1){return n(this,void 0,void 0,(function*(){return yield function(e,t,r,i,o,s=!1){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${i}/cards/`,a=yield fetch(n,{method:"POST",headers:Object.assign({Authorization:`Bearer ${r}`,"Content-Type":"application/json","User-token":t},s?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(o)});if(a.ok)return yield a.json();throw yield p(a)}catch(e){throw _(e)}}))}(this.baseUrl,e,this.secureToken,t,r,i)}))}_removeCustomerCard(e,t,r){return n(this,void 0,void 0,(function*(){return yield function(e,t,r,i="",o){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${o}/cards/${i}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","User-token":t}});if(204===s.status)return d.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield p(s)}catch(e){throw _(e)}}))}(this.baseUrl,e,this.secureToken,r,t)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(e,t,r={status:"active",pagesize:"10000"},i=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(r).toString(),o=yield fetch(`${e}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:i});if(o.ok)return yield o.json();throw yield p(o)}catch(e){throw _(e)}}))}(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 n(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new T({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,r;return n(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(r=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function V(e,t,r=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${t}`},signal:r});if(n.ok){return(yield n.json()).token}throw new Error("Failed to retrieve bearer token")}))}C=new WeakMap,I=new WeakMap,g=new WeakSet,S=function(e){var t,n;!e||e&&0===Object.keys(e).length||(r(this,g,"m",N).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),r(this,g,"m",D).call(this,(null===(n=e.cart)||void 0===n?void 0:n.items)||[]),r(this,g,"m",M).call(this,e),r(this,g,"m",U).call(this,e),r(this,g,"m",L).call(this,e),r(this,g,"m",k).call(this,e))},N=function(e){e&&(this.customer=e)},b=function(e){this.secureToken=e},D=function(e){this.cartItems=e},M=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},U=function(e){this.currency=null==e?void 0:e.currency},L=function(e){this.card=null==e?void 0:e.card},w=function(e){var t,r,i;return n(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===(r=null==e?void 0:e.checkout)||void 0===r?void 0:r.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===(i=e.checkout)||void 0===i?void 0:i.id)||(null==e?void 0:e.checkout_id)};try{return yield R(this.baseUrl,this.apiKeyTonder,t)}catch(e){}return e}}))},k=function(e){i(this,C,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"}(P||(P={}));const K={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},F=RegExp("^(?!s*$).+"),x={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:F,error:"El campo es requerido"}},B="Titular de la tarjeta",Y="Número de tarjeta",$="CVC/CVV",H="Mes",z="Año",W="Fecha de expiración",Q="Nombre como aparece en la tarjeta",q="1234 1234 1234 1234",X="3-4 dígitos",J="MM",G="AA",Z={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")'}},ee={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},te={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function ne({baseUrl:e,apiKey:r,vault_id:i,vault_url:o,data:s}){return n(this,void 0,void 0,(function*(){const a=t.init({vaultID:i,vaultURL:o,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield V(e,r)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),d=yield function(e,r){return n(this,void 0,void 0,(function*(){const i=yield function(e,r){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(e).map((e=>n(this,void 0,void 0,(function*(){return{element:yield r.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,r);return i?i.map((t=>new Promise((n=>{var r;const i=document.createElement("div");i.hidden=!0,i.id=`id-${t.key}`,null===(r=document.querySelector("body"))||void 0===r||r.appendChild(i),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const r=e[t.key];return t.element.setValue(r),n(t.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(d)).some((e=>!e)))throw _(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield a.collect();if(e)return e.records[0].fields;throw _(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw _(e)}}))}function re(e){const{element:n,fieldMessage:r="",errorStyles:i={},requiredMessage:o="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in n&&(n.on(t.EventName.CHANGE,(e=>{oe({eventName:"onChange",data:e,events:a}),ie({element:n,errorStyles:i,color:"transparent"})})),n.on(t.EventName.BLUR,(e=>{if(oe({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?o:""!=r?`El campo ${r} no es válido`:s;n.setError(t)}ie({element:n,errorStyles:i})})),n.on(t.EventName.FOCUS,(e=>{oe({eventName:"onFocus",data:e,events:a}),ie({element:n,errorStyles:i,color:"transparent"}),n.resetError()})))}function ie(e){const{element:t,errorStyles:n={},color:r=""}=e;Object.keys(n).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},n),{base:Object.assign(Object.assign({},n.base&&Object.assign({},n.base)),""!=r&&{color:r})})})}const oe=t=>{const{eventName:n,data:r,events:i}=t;if(i&&n in i){const t=i[n];"function"==typeof t&&t({elementType:e(r,"elementType",""),isEmpty:e(r,"isEmpty",""),isFocused:e(r,"isFocused",""),isValid:e(r,"isValid","")})}};function se(e){return n(this,void 0,void 0,(function*(){const{element:t,containerId:n,retries:r=2,delay:i=30}=e;for(let e=0;e<=r;e++){if(document.querySelector(n))return void t.mount(n);e<r&&(yield new Promise((e=>setTimeout(e,i))))}console.warn(`[mountCardFields] Container ${n} was not found after ${r+1} attempts`)}))}const ae=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"}),de={[ae.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[ae.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[ae.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[ae.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[ae.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[ae.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[ae.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[ae.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[ae.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[ae.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[ae.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[ae.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[ae.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[ae.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[ae.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[ae.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[ae.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[ae.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[ae.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[ae.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[ae.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[ae.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[ae.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[ae.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[ae.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[ae.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[ae.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[ae.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[ae.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[ae.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[ae.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[ae.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},le=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return de[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class ce extends j{constructor({apiKey:e,mode:t,returnUrl:n,callBack:r,apiKeyTonder:i,baseUrlTonder:o,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:n,callBack:r,apiKeyTonder:i,baseUrlTonder:o,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return n(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return n(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 m({message:d.getCardsError},e)}}))}saveCustomerCard(e){return n(this,void 0,void 0,(function*(){let t=null;try{yield this._fetchMerchantData();const n=yield this._getCustomer(),{auth_token:r,first_name:i="",last_name:o="",email:s=""}=n,{vault_id:a,vault_url:d,business:l}=this.merchantData,c=this._hasCardOnFileKeys(),u={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,"")},h=yield ne({vault_id:a,vault_url:d,data:u,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),_=yield this._saveCustomerCard(r,null==l?void 0:l.pk,h,c);if(t=_.skyflow_id,c){const e=_.card_bin;if(!e)throw new Error("Card BIN not returned from save card");const t=yield this._initializeCardOnFile(),n=yield t.process({cardTokens:{name:h.cardholder_name,number:h.card_number,expiryMonth:h.expiration_month,expiryYear:h.expiration_year,cvv:h.cvv},cardBin:e,contactDetails:{firstName:i||"",lastName:o||"",email:s||""},customerId:r,currency:this.currency||"MXN"}),a={skyflow_id:h.skyflow_id,subscription_id:n.subscriptionId};yield this._saveCustomerCard(r,null==l?void 0:l.pk,a)}return _}catch(e){throw t&&(yield this.removeCustomerCard(t)),m({message:d.saveCardError},e)}}))}removeCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(t,null==n?void 0:n.pk,e)}catch(e){throw m({message:d.removeCardError},e)}}))}getCustomerPaymentMethods(){return n(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},le(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw m({message:d.getPaymentMethodsError},e)}}))}mountCardFields(e){var r;return n(this,void 0,void 0,(function*(){const i=e.card_id?`update:${e.card_id}`:"create",o=null!==(r=e.unmount_context)&&void 0!==r?r:"all";"none"!==o&&("current"===o?this.unmountCardFields(i):this.unmountCardFields(o)),yield this.createSkyflowInstance();const s=yield function(e){var r,i,o,s,a,d,l,c,u,h,_,p,m,E,y,R,v;return n(this,void 0,void 0,(function*(){const{skyflowInstance:n,data:A,customization:f,events:O}=e,T=n.container(t.ContainerType.COLLECT),g=[],C={[P.CVV]:t.ElementType.CVV,[P.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[P.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[P.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[P.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},I={[P.CVV]:[x],[P.CARD_NUMBER]:[x],[P.EXPIRATION_MONTH]:[x],[P.EXPIRATION_YEAR]:[x],[P.CARDHOLDER_NAME]:[K,x]},S={errorStyles:(null===(i=null===(r=null==f?void 0:f.styles)||void 0===r?void 0:r.cardForm)||void 0===i?void 0:i.errorStyles)||te,inputStyles:(null===(s=null===(o=null==f?void 0:f.styles)||void 0===o?void 0:o.cardForm)||void 0===s?void 0:s.inputStyles)||Z,labelStyles:(null===(d=null===(a=null==f?void 0:f.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||ee},N={name:(null===(l=null==f?void 0:f.labels)||void 0===l?void 0:l.name)||B,card_number:(null===(c=null==f?void 0:f.labels)||void 0===c?void 0:c.card_number)||Y,cvv:(null===(u=null==f?void 0:f.labels)||void 0===u?void 0:u.cvv)||$,expiration_date:(null===(h=null==f?void 0:f.labels)||void 0===h?void 0:h.expiry_date)||W,expiration_month:(null===(_=null==f?void 0:f.labels)||void 0===_?void 0:_.expiration_month)||H,expiration_year:(null===(p=null==f?void 0:f.labels)||void 0===p?void 0:p.expiration_year)||z},b={name:(null===(m=null==f?void 0:f.placeholders)||void 0===m?void 0:m.name)||Q,card_number:(null===(E=null==f?void 0:f.placeholders)||void 0===E?void 0:E.card_number)||q,cvv:(null===(y=null==f?void 0:f.placeholders)||void 0===y?void 0:y.cvv)||X,expiration_month:(null===(R=null==f?void 0:f.placeholders)||void 0===R?void 0:R.expiration_month)||J,expiration_year:(null===(v=null==f?void 0:f.placeholders)||void 0===v?void 0:v.expiration_year)||G},D={[P.CVV]:null==O?void 0:O.cvvEvents,[P.CARD_NUMBER]:null==O?void 0:O.cardNumberEvents,[P.EXPIRATION_MONTH]:null==O?void 0:O.monthEvents,[P.EXPIRATION_YEAR]:null==O?void 0:O.yearEvents,[P.CARDHOLDER_NAME]:null==O?void 0:O.cardHolderEvents};if("fields"in A&&Array.isArray(A.fields))if(A.fields.length>0&&"string"==typeof A.fields[0])for(const e of A.fields){const t=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:C[e],validations:I[e]},S),{label:N[e],placeholder:b[e]}),A.card_id?{skyflowID:A.card_id}:{}));re({element:t,errorStyles:S.errorStyles,fieldMessage:[P.CVV,P.EXPIRATION_MONTH,P.EXPIRATION_YEAR].includes(e)?"":N[e],events:D[e]});const n=`#collect_${String(e)}`+(A.card_id?`_${A.card_id}`:"");yield se({element:t,containerId:n}),g.push({element:t,containerId:n})}else for(const e of A.fields){const t=e.field,n=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:C[t],validations:I[t]},S),{label:N[t],placeholder:b[t]}),A.card_id?{skyflowID:A.card_id}:{})),r=e.container_id||`#collect_${String(t)}`+(A.card_id?`_${A.card_id}`:"");yield se({element:n,containerId:r}),g.push({element:n,containerId:r})}return{elements:g.map((e=>e.element)),container:T}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events});this.mountedElementsByContext.set(i,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const n=`update:${e}`,r=this.mountedElementsByContext.get(n);return(null===(t=null==r?void 0:r.container)||void 0===t?void 0:t.container)||null}collectCardTokens(e){var t,r,i;return n(this,void 0,void 0,(function*(){const n=this.getContainerByCardId(e);if(!n)return null;try{const e=yield n.collect();return(null===(r=null===(t=null==e?void 0:e.records)||void 0===t?void 0:t[0])||void 0===r?void 0:r.fields)||null}catch(e){const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.description;throw new c({code:a.MOUNT_COLLECT_ERROR,details:{message:t}})}}))}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:n}=t;n&&n.length>0&&n.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield o(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw m({message:d.getBusinessError},e)}}))}createSkyflowInstance(){return n(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:e,vault_url:r}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:r,vault_id:i,vault_url:o}){return n(this,void 0,void 0,(function*(){return t.init({vaultID:i,vaultURL:o,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield V(e,r)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:r,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,r){return n(this,void 0,void 0,(function*(){try{return yield v(e,t,r)}catch(e){throw _(e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:r}){return n(this,void 0,void 0,(function*(){return yield ne({vault_id:e,vault_url:t,data:r,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:r,returnUrl:i}){var o,s;return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const a=yield this._getCustomer(this.abortController.signal),{vault_id:d,vault_url:l,business:c}=this.merchantData,{auth_token:u,first_name:h="",last_name:_="",email:p=""}=a,m=this._hasCardOnFileKeys();let E,y=null,R=null,v=null,A=!1;const f=()=>n(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(u,this.merchantData.business.pk))}));if(!t){if("string"==typeof e)if(R=e,E={skyflow_id:e},m){yield f();const t=null===(s=null===(o=this.customerCardsCache)||void 0===o?void 0:o.cards)||void 0===s?void 0:s.find((t=>t.fields.skyflow_id===e));if(!t)throw new Error("Card not found for card-on-file processing");const n=!!t.fields.subscription_id;n||(yield this.collectCardTokens(e)),n&&(y={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,"")});E=yield ne({vault_id:d,vault_url:l,data:t,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),R=E.skyflow_id,m&&(v={name:E.cardholder_name,number:E.card_number,expiryMonth:E.expiration_month,expiryYear:E.expiration_year,cvv:E.cvv},A=!0)}if(A){if(!R||!v)throw new Error("Missing card data for card-on-file processing");let e=null;try{const t=yield this._saveCustomerCard(u,null==c?void 0:c.pk,{skyflow_id:R},!0);e=t.skyflow_id;const n=t.card_bin;if(!n)throw new Error("Card BIN not returned from save card");const r=yield this._initializeCardOnFile();y={subscriptionId:(yield r.process({cardTokens:v,cardBin:n,contactDetails:{firstName:h||"",lastName:_||"",email:p||""},customerId:u,currency:this.currency||"MXN"})).subscriptionId},yield this._saveCustomerCard(u,null==c?void 0:c.pk,{skyflow_id:R,subscription_id:y.subscriptionId})}catch(t){throw e&&(yield this.removeCustomerCard(e)),new Error("Error processing card-on-file subscription")}}}return yield this._handleCheckout({card:E,payment_method:t,customer:a,isSandbox:r,returnUrl:i,enable_card_on_file:!!(null==y?void 0:y.subscriptionId)&&m})}))}customerRegister(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,n={email:e},r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw _(e)}}))}createOrder(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,n=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw _(e)}}))}createPayment(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,n=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw _(e)}}))}startCheckoutRouter(e){return n(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 n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return n(this,void 0,void 0,(function*(){try{const{order:t,total:n,customer:r,skyflowTokens:i,return_url:o,isSandbox:a,metadata:d,currency:l,payment_method:c}=e,h=yield this._fetchMerchantData(),_=yield this.customerRegister(r.email);if(!(_&&"auth_token"in _&&h&&"reference"in h))throw new s({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:_.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,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 new s({code:"500",body:p,name:"Keys error",message:"Order response errors"});{const e={business_pk:h.business.pk,amount:n,date:m,order_id:p.id,client_id:_.id},t=yield this.createPayment(e);let s;const{openpay_keys:E,business:y}=h;E.merchant_id&&E.public_key&&(s=yield v(E.merchant_id,E.public_key,a));const A=Object.assign(Object.assign({name:r.name,last_name:r.lastname,email_client:r.email,phone_number:r.phone,return_url:o,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:s||null,token_id:"",order_id:"id"in p&&p.id,business_id:y.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:u(),currency:l},c?{payment_method:c}:{card:i}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),f=yield R(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(f))return f}}}catch(e){throw _(e)}}))}registerCustomerCard(e,t,r){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${h(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},r))});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw _(e)}}))}deleteCustomerCard(e,t=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${h(this.merchantData)}/cards/${t}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield p(n)}catch(e){throw _(e)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const e=yield function(e,t,r="?status=active&page_size=10000&country=México",i=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/v1/payment_methods${r}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:i});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw _(e)}}))}(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},le(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function ue(e){return/^\d{12,19}$/.test(e)&&Ee(e)}function he(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function _e(e){return/^\d{3,4}$/.test(e)}function pe(e){return/^(0[1-9]|1[0-2])$/.test(e)}function me(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const Ee=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),n=t.shift();let r=t.reduce(((e,t,n)=>n%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return r+=n,r%10==0};export{j as BaseInlineCheckout,ce as LiteCheckout,_e as validateCVV,ue as validateCardNumber,he as validateCardholderName,pe as validateExpirationMonth,me as validateExpirationYear};
1
+ import{get as e}from"lodash";import t from"skyflow-js";function r(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{d(n.next(e))}catch(e){o(e)}}function a(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}d((n=n.apply(e,t||[])).next())}))}function n(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}function i(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r}function o(e,t,n){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:n});return yield r.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:e,body:t,name:r,message:n,stack:i}){this.code=e,this.body=t,this.name=r,this.message=n,this.stack=i}}var a;!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"}(a||(a={}));const d={[a.INIT_ERROR]:"Error initializing the SDK.",[a.INVALID_TYPE]:"SDK Type invalid.",[a.STATE_ERROR]:"Error updating SDK state.",[a.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[a.INVALID_CONFIG]:"Required configuration options.",[a.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[a.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[a.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[a.TYPE_SDK_REQUIRED]:"SDK type required.",[a.ENVIRONMENT_REQUIRED]:"Environment required.",[a.FETCH_CARDS_ERROR]:"Error retrieving cards.",[a.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.",[a.SAVE_CARD_ERROR]:"Error saving the card.",[a.REMOVE_CARD_ERROR]:"Error deleting the card.",[a.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[a.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[a.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[a.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[a.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[a.START_CHECKOUT_ERROR]:"Error processing the payment.",[a.CREATE_ORDER_ERROR]:"Error creating the order.",[a.BUSINESS_ID_REQUIRED]:"Business ID is required.",[a.CLIENT_ID_REQUIRED]:"Client ID is required.",[a.INVALID_AMOUNT]:"Invalid amount.",[a.INVALID_ITEMS]:"Invalid items.",[a.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[a.INVALID_EMAIL]:"Invalid email.",[a.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[a.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[a.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[a.SECURE_TOKEN_ERROR]:"Error getting secure token.",[a.SECURE_TOKEN_INVALID]:"Invalid secure token.",[a.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[a.REMOVE_CARD]:"Card deleted successfully",[a.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[a.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[a.INVALID_CARD_DATA]:"Invalid card data.",[a.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[a.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[a.CARD_ON_FILE_DECLINED]:"Transaction declined. Please verify your card details.",[a.REQUEST_ABORTED]:"Requests canceled.",[a.REQUEST_FAILED]:"Request failed.",[a.UNKNOWN_ERROR]:"An unexpected error occurred.",[a.CREATE_ERROR]:"Error creating the SDK.",[a.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[a.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[a.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};a.INIT_ERROR,a.STATE_ERROR,a.FETCH_BUSINESS_ERROR,a.INVALID_CONFIG,a.TYPE_SDK_REQUIRED,a.ENVIRONMENT_REQUIRED,a.FETCH_CARDS_ERROR,a.SAVE_CARD_ERROR,a.REMOVE_CARD_ERROR,a.CREATE_PAYMENT_ERROR,a.START_CHECKOUT_ERROR,a.CREATE_ORDER_ERROR,a.BUSINESS_ID_REQUIRED,a.CLIENT_ID_REQUIRED,a.INVALID_AMOUNT,a.INVALID_ITEMS,a.CUSTOMER_OPERATION_ERROR,a.INVALID_EMAIL,a.FETCH_PAYMENT_METHODS_ERROR,a.INVALID_VAULT_TOKEN,a.VAULT_TOKEN_ERROR,a.SECURE_TOKEN_ERROR,a.INVALID_SECRET_API_KEY,a.CUSTOMER_AUTH_TOKEN_NOT_VALID,a.SECURE_TOKEN_INVALID,a.REMOVE_CARD,a.SKYFLOW_NOT_INITIALIZED,a.INVALID_TYPE,a.PAYMENT_PROCESS_ERROR,a.INVALID_PAYMENT_REQUEST,a.INVALID_PAYMENT_REQUEST_CARD_PM,a.SAVE_CARD_PROCESS_ERROR,a.ERROR_LOAD_PAYMENT_FORM,a.INVALID_CARD_DATA,a.ERROR_LOAD_ENROLLMENT_FORM,a.MOUNT_COLLECT_ERROR,a.CARD_ON_FILE_DECLINED,a.CARD_SAVED_SUCCESSFULLY,a.CARD_REMOVED_SUCCESSFULLY,a.REQUEST_ABORTED,a.REQUEST_FAILED,a.UNKNOWN_ERROR,a.CREATE_ERROR,a.FETCH_TRANSACTION_ERROR,a.THREEDS_REDIRECTION_ERROR,a.REMOVE_SDK_ERROR;class l extends Error{constructor(e){var t,r;const n=e.message||d[e.code]||"Unknown error";super(n),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)||n}}}const c=()=>({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}),u=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},h=e=>new s({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack}),p=(e,t=void 0)=>r(void 0,void 0,void 0,(function*(){let r,n,i="Error";e&&"json"in e&&(r=yield null==e?void 0:e.json()),e&&"status"in e&&(n=e.status.toString()),!r&&e&&"text"in e&&(i=yield e.text()),(null==r?void 0:r.detail)&&(i=r.detail);return new s({code:n,body:r,name:n,message:i,stack:t})}));class _{constructor({payload:e=null,apiKey:t,baseUrl:r,redirectOnComplete:n,tdsIframeId:i,tonderPayButtonId:o,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=i,this.tonderPayButtonId=o,this.redirectOnComplete=n,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,n,i,o;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===(o=null===(i=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===i?void 0:i.iframe_resources)||void 0===o?void 0:o.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,n,i;const o=null===(i=null===(n=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===n?void 0:n.iframe_resources)||void 0===i?void 0:i.iframe;if(o){this.saveVerifyTransactionUrl();const r=document.createElement("div");r.innerHTML=o,document.body.appendChild(r);const n=document.createElement("script");n.textContent='document.getElementById("tdsMmethodForm").submit();',r.appendChild(n);const i=document.getElementById("tdsMmethodTgtFrame");i?i.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 n=this,i=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"),n.callBack&&n.callBack(n.payload),t.removeEventListener("load",i)},o=t=>r(this,void 0,void 0,(function*(){const i=yield new Promise(((e,r)=>e(t)));if(i){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(i))return e();{const e=setTimeout((()=>r(this,void 0,void 0,(function*(){clearTimeout(e),yield o(n.requestTransactionStatus())}))),7e3)}}}));yield o(n.requestTransactionStatus())}));t.addEventListener("load",i)}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,n]of t)e[r]=n;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 n=document.createElement("input");n.type="hidden",n.name=e.term_url,n.value=e.TermUrl,t.appendChild(n),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 E=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function m(e,t,n){return r(this,void 0,void 0,(function*(){try{const r=`${e}/api/v1/checkout-router/`,i=n,o=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},i),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(o.status>=200&&o.status<=299)return yield o.json();{const e=yield o.json(),t=new Error("Failed to start checkout router");throw t.details=e,t}}catch(e){throw e}}))}function y(e,t,n=!0,i=null){return r(this,void 0,void 0,(function*(){let r=yield window.OpenPay;return r.setId(e),r.setApiKey(t),r.setSandboxMode(n),yield r.deviceData.setup({signal:i})}))}const R=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"}),v=Object.freeze({TELEMETRY:"/telemetry/event",ACQ_SUBSCRIPTION_TOKEN:"/acq-kushki/subscription/token",ACQ_SUBSCRIPTION_CREATE:"/acq-kushki/subscription/create"});function f(e="stage"){return`${R[e]}${v.TELEMETRY}`}const A="https://cdn.kushkipagos.com/kushki.min.js";let O=!1,T=null;class C{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 R[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 O?Promise.resolve():T||(T=new Promise(((e,t)=>{if(document.querySelector(`script[src="${A}"]`))return O=!0,void e();const r=document.createElement("script");r.src=A,r.async=!0,r.onload=()=>{O=!0,e()},r.onerror=()=>{T=null,t(new Error("Failed to load acquirer script"))},document.head.appendChild(r)})),T)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw new Error("Acquirer script not loaded. Call initialize() first.");return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw new Error("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,n)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void n(new Error(`Error getting JWT: ${e.message}`));const t=e;t.jwt?r(t.jwt):n(new Error("No JWT returned from acquirer"))}))}))}))}generateToken(e){return r(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${v.ACQ_SUBSCRIPTION_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok){const e=yield t.text();throw new Error(`Failed to generate token: ${t.status} - ${e}`)}return t.json()}))}createSubscription(e){return r(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${v.ACQ_SUBSCRIPTION_CREATE}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok){const e=yield t.text();throw new Error(`Failed to create subscription: ${t.status} - ${e}`)}return t.json()}))}validate3DS(e,t){return r(this,void 0,void 0,(function*(){const r=this.getAcquirerInstance();return new Promise(((n,i)=>{r.requestValidate3DS({secureId:e,security:t},(e=>{const t=e;t.code&&"3DS000"!==t.code?i(new Error("3DS validation failed}")):!1!==t.isValid?n(!0):i(new Error("3DS validation failed"))}))}))}))}process(e){var t,n;return r(this,void 0,void 0,(function*(){const r=yield this.getJwt(e.cardBin),i=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:r}),o=i.secureId||(null===(t=i.details)||void 0===t?void 0:t.secureId),s=i.security||(null===(n=i.details)||void 0===n?void 0:n.security);if(!o||!s)throw new Error("Missing secureId or security in token response");return yield this.validate3DS(o,s),this.createSubscription({token:i.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}class g{constructor(e){this.REQUEST_TIMEOUT_MS=1200,this.MAX_MESSAGE_LENGTH=500,this.MAX_STACK_LENGTH=15e3,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?this.truncate(e.stack,this.MAX_STACK_LENGTH):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),n=Object.assign({},t.metadata||{});"undefined"!=typeof window&&(n.url=window.location.href);const i={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:n};return t.tenant_id&&(i.tenant_id=t.tenant_id),t.process_id&&(i.process_id=t.process_id),t.user_id&&(i.user_id=t.user_id),r.stack&&(i.stack=r.stack),t.error_code&&(i.error_code=t.error_code),t.http_status&&(i.http_status=t.http_status),i}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);if("undefined"!=typeof navigator&&navigator.sendBeacon){const e=new Blob([t],{type:"application/json"});if(navigator.sendBeacon(this.config.endpoint,e))return!0}const r=new AbortController,n=setTimeout((()=>r.abort()),this.REQUEST_TIMEOUT_MS);try{const e=yield fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Checkout ${this.config.apiKey}`},body:t,keepalive:!0,signal:r.signal});return clearTimeout(n),e.ok}catch(e){return clearTimeout(n),!1}}catch(e){return!1}}))}}const I=Object.freeze({name:"@tonder.io/ionic-lite-sdk",version:"0.0.68-beta.DEV-2106.1"});class S extends Error{constructor(e){var t;const r=S.parseStatusCode(e.statusCode);super(S.resolveMessage(e.errorCode,e.message)),this.status="error",Object.setPrototypeOf(this,new.target.prototype),this.name="TonderError",this.code=e.errorCode,this.statusCode=r;const n=Object.assign({},e.details||{});delete n.systemCode;const i=S.extractSystemError(e,n);this.details=Object.assign(Object.assign({},n),{code:e.errorCode,statusCode:r}),this.details.systemError=i,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,S)}static parseStatusCode(e){const t=Number(e);return Number.isFinite(t)?t<100||t>599?500:Math.trunc(t):500}static resolveMessage(e,t){return t||(d[e]||d[a.UNKNOWN_ERROR]||"An unexpected error occurred.")}static isHttpStatusCode(e){const t=Number(e);return Number.isFinite(t)&&t>=100&&t<=599}static resolveSystemError(e){return"string"!=typeof e?null:e.trim()}static extractSystemError(e,t){var r,n,i;const o=null==t?void 0:t.cause,s=[null==t?void 0:t.systemError,null===(r=null==e?void 0:e.details)||void 0===r?void 0:r.systemError,null===(n=null==o?void 0:o.body)||void 0===n?void 0:n.code,null===(i=null==o?void 0:o.details)||void 0===i?void 0:i.code];for(const e of s){const t=S.resolveSystemError(e);if(t)return t}return"APP_INTERNAL_001"}}function N(e,t){var r;if(!(null==e?void 0:e.errorCode))throw new Error("buildPublicAppError requires errorCode");const n=!!e.details&&Object.keys(e.details).length>0,i=e.errorCode!==(null==t?void 0:t.code)||!!e.message||void 0!==e.statusCode||n;if(t instanceof S&&!i)return t;const o=null!==(r=e.statusCode)&&void 0!==r?r:S.isHttpStatusCode(null==t?void 0:t.statusCode)?Number(t.statusCode):S.isHttpStatusCode(null==t?void 0:t.code)?Number(t.code):S.isHttpStatusCode(null==t?void 0:t.status)?Number(t.status):500,s=Object.assign(Object.assign({},(null==t?void 0:t.details)||{}),e.details||{});return void 0===s.cause&&void 0!==t&&(s.cause=t),new S({errorCode:e.errorCode,message:e.message,details:s,statusCode:o})}var b,D,M,U,k,L,w,P,j,V,K,F,x;class B{constructor({mode:e="stage",customization:t,apiKey:r,apiKeyTonder:n,returnUrl:i,tdsIframeId:o,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){b.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,D.set(this,void 0),M.set(this,void 0),this.apiKeyTonder=n||r||"",this.returnUrl=i,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||E[this.mode]||E.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new _({apiKey:r,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:o,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=o,this.telemetry=new g({endpoint:f(this.mode),apiKey:this.apiKeyTonder,platform:I.name,platform_version:I.version,mode:this.mode||"stage"})}configureCheckout(e){"secureToken"in e&&n(this,b,"m",L).call(this,e.secureToken),n(this,b,"m",U).call(this,e)}getCustomerId(){var e,t;return null===(t=null===(e=n(this,M,"f"))||void 0===e?void 0:e.id)||void 0===t?void 0:t.toString()}reportSdkError(e,t){var r,n,i;try{const o=this.getCustomerId(),s=Object.assign({tenant_id:null===(i=null===(n=null===(r=this.merchantData)||void 0===r?void 0:r.business)||void 0===n?void 0:n.pk)||void 0===i?void 0:i.toString(),user_id:o},t||{});s.user_id||delete s.user_id,s.feature=(null==t?void 0:t.feature)||"unknown",this.telemetry.captureException(e,s)}catch(e){}}verify3dsTransaction(){return r(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield n(this,b,"m",K).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,i)=>r(this,void 0,void 0,(function*(){var r,o;let s;try{n(this,b,"m",U).call(this,e),s=yield this._checkout(e),this.process3ds.setPayload(s);if(yield this._handle3dsRedirect(s)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(s),t(s)}}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==s?void 0:s.payment_id)||(null===(r=null==s?void 0:s.payment)||void 0===r?void 0:r.id)||(null===(o=null==s?void 0:s.payment)||void 0===o?void 0:o.pk),metadata:{step:"payment",request:e,response:s}}),i(N({errorCode:a.PAYMENT_PROCESS_ERROR},t))}}))))}getSecureToken(e){return r(this,void 0,void 0,(function*(){try{return yield function(e,t,n=null){return r(this,void 0,void 0,(function*(){try{const r=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:n});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw h(e)}}))}(this.baseUrl,e)}catch(e){throw this.reportSdkError(e,{feature:"secure-token",metadata:{step:"getSecureToken"}}),N({errorCode:a.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 n(this,M,"f")||i(this,M,yield function(e,t,n,i=null){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/customer/`,o={email:n.email,first_name:null==n?void 0:n.firstName,last_name:null==n?void 0:n.lastName,phone:null==n?void 0:n.phone},s=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:i,body:JSON.stringify(o)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),n(this,M,"f")}))}_handleCheckout({card:t,payment_method:i,customer:o,isSandbox:s,enable_card_on_file:a,returnUrl:d}){return r(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:u,business:h}=this.merchantData,p=Number(this.cartTotal);let _,E,R;try{let v;!v&&l.merchant_id&&l.public_key&&!i&&(v=yield y(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:f,auth_token:A}=o;_={business:this.apiKeyTonder,client:A,billing_address_id:null,shipping_address_id:null,amount:p,status:"A",reference:u,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata};const O=yield function(e,t,n){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/orders/`,i=n,o=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(i)});if(201===o.status)return yield o.json();throw new Error(`Error: ${o.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,_),T=(new Date).toISOString();E={business_pk:h.pk,client_id:f,amount:p,date:T,order_id:O.id,customer_order_reference:this.order_reference?this.order_reference:u,items:this.cartItems,currency:this.currency,metadata:this.metadata};const C=yield function(e,t,n){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${n.business_pk}/payments/`,i=n,o=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(i)});if(o.status>=200&&o.status<=299)return yield o.json();throw new Error(`Error: ${o.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,E);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:d||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:v||null,token_id:"",order_id:O.id,business_id:h.pk,payment_id:C.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:c(),currency:this.currency},i?{payment_method:i}:{card:t}),{apm_config:n(this,D,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==a?{enable_card_on_file:a}:{});const g=yield m(this.baseUrl,this.apiKeyTonder,R);return g||!1}catch(e){throw this.reportSdkError(e,{feature:"payment",process_id:null==R?void 0:R.payment_id,metadata:{step:"_handleCheckout",orderItems:_,paymentItems:E,routerItems:R}}),e}}))}_fetchMerchantData(){return r(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield o(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,n,i,o=null){return r(this,void 0,void 0,(function*(){try{const r=`${e}/api/v1/business/${i}/cards/`,s=yield fetch(r,{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","User-token":t},signal:o});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield p(s)}catch(e){throw h(e)}}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,n,i=!1){return r(this,void 0,void 0,(function*(){return yield function(e,t,n,i,o,s=!1){return r(this,void 0,void 0,(function*(){try{const r=`${e}/api/v1/business/${i}/cards/`,a=yield fetch(r,{method:"POST",headers:Object.assign({Authorization:`Bearer ${n}`,"Content-Type":"application/json","User-token":t},s?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(o)});if(a.ok)return yield a.json();throw yield p(a)}catch(e){throw h(e)}}))}(this.baseUrl,e,this.secureToken,t,n,i)}))}_removeCustomerCard(e,t,n){return r(this,void 0,void 0,(function*(){return yield function(e,t,n,i="",o){return r(this,void 0,void 0,(function*(){try{const r=`${e}/api/v1/business/${o}/cards/${i}`,s=yield fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","User-token":t}});if(204===s.status)return d[a.CARD_REMOVED_SUCCESSFULLY];if(s.ok&&"json"in s)return yield s.json();throw yield p(s)}catch(e){throw h(e)}}))}(this.baseUrl,e,this.secureToken,n,t)}))}_fetchCustomerPaymentMethods(){return r(this,void 0,void 0,(function*(){return yield function(e,t,n={status:"active",pagesize:"10000"},i=null){return r(this,void 0,void 0,(function*(){try{const r=new URLSearchParams(n).toString(),o=yield fetch(`${e}/api/v1/payment_methods?${r}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:i});if(o.ok)return yield o.json();throw yield p(o)}catch(e){throw h(e)}}))}(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 C({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,n;return r(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(n=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===n?void 0:n.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,n=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:n});if(r.ok){return(yield r.json()).token}throw new Error("Failed to retrieve bearer token")}))}D=new WeakMap,M=new WeakMap,b=new WeakSet,U=function(e){var t,r;!e||e&&0===Object.keys(e).length||(n(this,b,"m",k).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),n(this,b,"m",w).call(this,(null===(r=e.cart)||void 0===r?void 0:r.items)||[]),n(this,b,"m",P).call(this,e),n(this,b,"m",j).call(this,e),n(this,b,"m",V).call(this,e),n(this,b,"m",F).call(this,e))},k=function(e){e&&(this.customer=e)},L=function(e){this.secureToken=e},w=function(e){this.cartItems=e},P=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,n,i,o,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===(n=null==e?void 0:e.checkout)||void 0===n?void 0:n.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===(i=e.checkout)||void 0===i?void 0:i.id)||(null==e?void 0:e.checkout_id)};try{return yield m(this.baseUrl,this.apiKeyTonder,t)}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==e?void 0:e.payment_id)||(null===(o=null==e?void 0:e.payment)||void 0===o?void 0:o.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){i(this,D,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",W="Número de tarjeta",X="CVC/CVV",q="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",ne="AA",ie={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")'}},oe={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:n,vault_id:i,vault_url:o,data:s}){return r(this,void 0,void 0,(function*(){const a=t.init({vaultID:i,vaultURL:o,getBearerToken:()=>r(this,void 0,void 0,(function*(){return yield Y(e,n)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),d=yield function(e,n){return r(this,void 0,void 0,(function*(){const i=yield function(e,n){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 n.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,n);return i?i.map((t=>new Promise((r=>{var n;const i=document.createElement("div");i.hidden=!0,i.id=`id-${t.key}`,null===(n=document.querySelector("body"))||void 0===n||n.appendChild(i),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const n=e[t.key];return t.element.setValue(n),r(t.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(d)).some((e=>!e)))throw h(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield a.collect();if(e)return e.records[0].fields;throw h(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw h(e)}}))}function de(e){const{element:r,fieldMessage:n="",errorStyles:i={},requiredMessage:o="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:i,color:"transparent"})})),r.on(t.EventName.BLUR,(e=>{if(ce({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?o:""!=n?`El campo ${n} no es válido`:s;r.setError(t)}le({element:r,errorStyles:i})})),r.on(t.EventName.FOCUS,(e=>{ce({eventName:"onFocus",data:e,events:a}),le({element:r,errorStyles:i,color:"transparent"}),r.resetError()})))}function le(e){const{element:t,errorStyles:r={},color:n=""}=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)),""!=n&&{color:n})})})}const ce=t=>{const{eventName:r,data:n,events:i}=t;if(i&&r in i){const t=i[r];"function"==typeof t&&t({elementType:e(n,"elementType",""),isEmpty:e(n,"isEmpty",""),isFocused:e(n,"isFocused",""),isValid:e(n,"isValid","")})}};function ue(e){return r(this,void 0,void 0,(function*(){const{element:t,containerId:r,retries:n=2,delay:i=30}=e;for(let e=0;e<=n;e++){if(document.querySelector(r))return void t.mount(r);e<n&&(yield new Promise((e=>setTimeout(e,i))))}console.warn(`[mountCardFields] Container ${r} was not found after ${n+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"}),pe={[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"}},_e=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return pe[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class Ee extends B{constructor({apiKey:e,mode:t,returnUrl:r,callBack:n,apiKeyTonder:i,baseUrlTonder:o,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:r,callBack:n,apiKeyTonder:i,baseUrlTonder:o,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),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"}}),N({errorCode:a.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:n,first_name:i="",last_name:o="",email:s=""}=r,{vault_id:l,vault_url:c,business:u}=this.merchantData,h=this._hasCardOnFileKeys(),p={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 ae({vault_id:l,vault_url:c,data:p,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),E=yield this._saveCustomerCard(n,null==u?void 0:u.pk,_,h);if(t=E.skyflow_id,h){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:i||"",lastName:o||"",email:s||""},customerId:n,currency:this.currency||"MXN"})}catch(e){throw N({errorCode:a.SAVE_CARD_ERROR,message:d[a.CARD_ON_FILE_DECLINED]},e)}const l={skyflow_id:_.skyflow_id,subscription_id:r.subscriptionId};yield this._saveCustomerCard(n,null==u?void 0:u.pk,l)}return E}catch(e){throw t&&(yield this.removeCustomerCard(t)),this.reportSdkError(e,{feature:"save-card",process_id:t||this.getCustomerId(),metadata:{step:"saveCustomerCard"}}),N({errorCode:a.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"}}),N({errorCode:a.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},_e(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw this.reportSdkError(e,{feature:"get-payment-methods",metadata:{step:"getCustomerPaymentMethods"}}),N({errorCode:a.FETCH_PAYMENT_METHODS_ERROR},e)}}))}mountCardFields(e){var n;return r(this,void 0,void 0,(function*(){const i=e.card_id?`update:${e.card_id}`:"create",o=null!==(n=e.unmount_context)&&void 0!==n?n:"all";"none"!==o&&("current"===o?this.unmountCardFields(i):this.unmountCardFields(o)),yield this.createSkyflowInstance();const s=yield function(e){var n,i,o,s,a,d,l,c,u,h,p,_,E,m,y,R,v;return r(this,void 0,void 0,(function*(){const{skyflowInstance:r,data:f,customization:A,events:O}=e,T=r.container(t.ContainerType.COLLECT),C=[],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},I={[x.CVV]:[z],[x.CARD_NUMBER]:[z],[x.EXPIRATION_MONTH]:[z],[x.EXPIRATION_YEAR]:[z],[x.CARDHOLDER_NAME]:[$,z]},S={errorStyles:(null===(i=null===(n=null==A?void 0:A.styles)||void 0===n?void 0:n.cardForm)||void 0===i?void 0:i.errorStyles)||se,inputStyles:(null===(s=null===(o=null==A?void 0:A.styles)||void 0===o?void 0:o.cardForm)||void 0===s?void 0:s.inputStyles)||ie,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)||oe},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)||W,cvv:(null===(u=null==A?void 0:A.labels)||void 0===u?void 0:u.cvv)||X,expiration_date:(null===(h=null==A?void 0:A.labels)||void 0===h?void 0:h.expiry_date)||G,expiration_month:(null===(p=null==A?void 0:A.labels)||void 0===p?void 0:p.expiration_month)||q,expiration_year:(null===(_=null==A?void 0:A.labels)||void 0===_?void 0:_.expiration_year)||J},b={name:(null===(E=null==A?void 0:A.placeholders)||void 0===E?void 0:E.name)||Z,card_number:(null===(m=null==A?void 0:A.placeholders)||void 0===m?void 0:m.card_number)||ee,cvv:(null===(y=null==A?void 0:A.placeholders)||void 0===y?void 0:y.cvv)||te,expiration_month:(null===(R=null==A?void 0:A.placeholders)||void 0===R?void 0:R.expiration_month)||re,expiration_year:(null===(v=null==A?void 0:A.placeholders)||void 0===v?void 0:v.expiration_year)||ne},D={[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=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:g[e],validations:I[e]},S),{label:N[e],placeholder:b[e]}),f.card_id?{skyflowID:f.card_id}:{}));de({element:t,errorStyles:S.errorStyles,fieldMessage:[x.CVV,x.EXPIRATION_MONTH,x.EXPIRATION_YEAR].includes(e)?"":N[e],events:D[e]});const r=`#collect_${String(e)}`+(f.card_id?`_${f.card_id}`:"");yield ue({element:t,containerId:r}),C.push({element:t,containerId:r})}else for(const e of f.fields){const t=e.field,r=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:g[t],validations:I[t]},S),{label:N[t],placeholder:b[t]}),f.card_id?{skyflowID:f.card_id}:{})),n=e.container_id||`#collect_${String(t)}`+(f.card_id?`_${f.card_id}`:"");yield ue({element:r,containerId:n}),C.push({element:r,containerId:n})}return{elements:C.map((e=>e.element)),container:T}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events});this.mountedElementsByContext.set(i,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const r=`update:${e}`,n=this.mountedElementsByContext.get(r);return(null===(t=null==n?void 0:n.container)||void 0===t?void 0:t.container)||null}collectCardTokens(e){var t,n,i;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===(n=null===(t=null==e?void 0:e.records)||void 0===t?void 0:t[0])||void 0===n?void 0:n.fields)||null}catch(t){const r=null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.description;throw this.reportSdkError(t,{feature:"collect-card-tokens",process_id:e,metadata:{step:"collectCardTokens"}}),new l({code:a.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 o(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw this.reportSdkError(e,{feature:"get-business",metadata:{step:"getBusiness"}}),N({errorCode:a.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:n}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:n,vault_id:i,vault_url:o}){return r(this,void 0,void 0,(function*(){return t.init({vaultID:i,vaultURL:o,getBearerToken:()=>r(this,void 0,void 0,(function*(){return yield Y(e,n)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:n,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,n){return r(this,void 0,void 0,(function*(){try{return yield y(e,t,n)}catch(e){throw this.reportSdkError(e,{feature:"get-openpay-device-session",metadata:{step:"getOpenpayDeviceSessionID"}}),h(e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:n}){return r(this,void 0,void 0,(function*(){return yield ae({vault_id:e,vault_url:t,data:n,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:n,returnUrl:i}){var o,s;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:p,first_name:_="",last_name:E="",email:m=""}=l,y=this._hasCardOnFileKeys();let R,v=null,f=null,A=null,O=!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(p,this.merchantData.business.pk))}));if(!t){if("string"==typeof e)if(f=e,R={skyflow_id:e},y){yield T();const t=null===(s=null===(o=this.customerCardsCache)||void 0===o?void 0:o.cards)||void 0===s?void 0:s.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 ae({vault_id:c,vault_url:u,data:t,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),f=R.skyflow_id,y&&(A={name:R.cardholder_name,number:R.card_number,expiryMonth:R.expiration_month,expiryYear:R.expiration_year,cvv:R.cvv},O=!0)}if(O){if(!f||!A)throw new Error("Missing card data for card-on-file processing");let e=null;try{const t=yield this._saveCustomerCard(p,null==h?void 0:h.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 n=yield this._initializeCardOnFile();let i;try{i=yield n.process({cardTokens:A,cardBin:r,contactDetails:{firstName:_||"",lastName:E||"",email:m||""},customerId:p,currency:this.currency||"MXN"})}catch(e){throw N({errorCode:a.PAYMENT_PROCESS_ERROR,message:d[a.CARD_ON_FILE_DECLINED]},e)}v={subscriptionId:i.subscriptionId},yield this._saveCustomerCard(p,null==h?void 0:h.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:l,isSandbox:n,returnUrl:i,enable_card_on_file:!!(null==v?void 0:v.subscriptionId)&&y})}))}customerRegister(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,r={email:e},n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(r)});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw this.reportSdkError(e,{feature:"customer-register",metadata:{step:"customerRegister"}}),h(e)}}))}createOrder(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,r=e,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw this.reportSdkError(e,{feature:"create-order",metadata:{step:"createOrder"}}),h(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,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw this.reportSdkError(e,{feature:"create-payment",metadata:{step:"createPayment"}}),h(e)}}))}startCheckoutRouter(e){return r(this,void 0,void 0,(function*(){const t=yield m(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:n,skyflowTokens:i,return_url:o,isSandbox:a,metadata:d,currency:l,payment_method:u}=e,h=yield this._fetchMerchantData(),p=yield this.customerRegister(n.email);if(!(p&&"auth_token"in p&&h&&"reference"in h))throw new s({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:p.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:h.reference,is_oneclick:!0,items:t.items},_=yield this.createOrder(e),E=(new Date).toISOString();if(!("id"in _&&"id"in p&&"business"in h))throw new s({code:"500",body:_,name:"Keys error",message:"Order response errors"});{const e={business_pk:h.business.pk,amount:r,date:E,order_id:_.id,client_id:p.id},t=yield this.createPayment(e);let s;const{openpay_keys:R,business:v}=h;R.merchant_id&&R.public_key&&(s=yield y(R.merchant_id,R.public_key,a));const f=Object.assign(Object.assign({name:n.name,last_name:n.lastname,email_client:n.email,phone_number:n.phone,return_url:o,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 _&&_.id,business_id:v.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:c(),currency:l},u?{payment_method:u}:{card:i}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),A=yield m(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"}}),h(e)}}))}registerCustomerCard(e,t,n){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const r=yield fetch(`${this.baseUrl}/api/v1/business/${u(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},n))});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw this.reportSdkError(e,{feature:"register-customer-card",metadata:{step:"registerCustomerCard"}}),h(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/${u(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 p(r)}catch(e){throw this.reportSdkError(e,{feature:"delete-customer-card",process_id:t,metadata:{step:"deleteCustomerCard"}}),h(e)}}))}getActiveAPMs(){return r(this,void 0,void 0,(function*(){try{const e=yield function(e,t,n="?status=active&page_size=10000&country=México",i=null){return r(this,void 0,void 0,(function*(){try{const r=yield fetch(`${e}/api/v1/payment_methods${n}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:i});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw h(e)}}))}(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},_e(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 ye(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function Re(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 n=t.reduce(((e,t,r)=>r%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return n+=r,n%10==0};export{S as AppError,B as BaseInlineCheckout,Ee as LiteCheckout,g as SdkTelemetryClient,Re as validateCVV,me as validateCardNumber,ye as validateCardholderName,ve as validateExpirationMonth,fe as validateExpirationYear};
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Tonder API base URLs by environment mode
3
+ */
4
+ export declare const API_BASE_URL_BY_MODE: Readonly<{
5
+ production: "https://api.tonder.io";
6
+ sandbox: "https://api-stage.tonder.io";
7
+ stage: "https://api-stage.tonder.io";
8
+ development: "https://api-stage.tonder.io";
9
+ }>;
10
+ /**
11
+ * API endpoint paths
12
+ */
13
+ export declare const API_ENDPOINTS: Readonly<{
14
+ TELEMETRY: "/telemetry/event";
15
+ ACQ_SUBSCRIPTION_TOKEN: "/acq-kushki/subscription/token";
16
+ ACQ_SUBSCRIPTION_CREATE: "/acq-kushki/subscription/create";
17
+ }>;
18
+ /**
19
+ * Get the full telemetry endpoint URL for a given mode
20
+ */
21
+ export declare function getTelemetryEndpoint(mode?: "production" | "sandbox" | "stage" | "development"): string;
22
+ /**
23
+ * Get the API base URL for a given mode
24
+ */
25
+ export declare function getApiBaseUrl(mode?: "production" | "sandbox" | "stage" | "development"): string;
@@ -48,6 +48,7 @@ export declare const MESSAGES_ES: {
48
48
  INVALID_CARD_DATA: string;
49
49
  ERROR_LOAD_ENROLLMENT_FORM: string;
50
50
  MOUNT_COLLECT_ERROR: string;
51
+ CARD_ON_FILE_DECLINED: string;
51
52
  CARD_SAVED_SUCCESSFULLY: string;
52
53
  CARD_REMOVED_SUCCESSFULLY: string;
53
54
  REQUEST_ABORTED: string;
@@ -40,6 +40,7 @@ export declare enum ErrorKeyEnum {
40
40
  ERROR_LOAD_PAYMENT_FORM = "ERROR_LOAD_PAYMENT_FORM",
41
41
  ERROR_LOAD_ENROLLMENT_FORM = "ERROR_LOAD_ENROLLMENT_FORM",
42
42
  MOUNT_COLLECT_ERROR = "MOUNT_COLLECT_ERROR",
43
+ CARD_ON_FILE_DECLINED = "CARD_ON_FILE_DECLINED",
43
44
  CARD_SAVED_SUCCESSFULLY = "CARD_SAVED_SUCCESSFULLY",
44
45
  CARD_REMOVED_SUCCESSFULLY = "CARD_REMOVED_SUCCESSFULLY",
45
46
  REQUEST_ABORTED = "REQUEST_ABORTED",
@@ -0,0 +1,25 @@
1
+ export interface IAppErrorInput {
2
+ errorCode: string;
3
+ message?: string;
4
+ details?: Record<string, unknown>;
5
+ statusCode?: number;
6
+ }
7
+ export declare class AppError extends Error {
8
+ readonly status: 'error';
9
+ readonly code: string;
10
+ readonly statusCode: number;
11
+ details: Record<string, unknown>;
12
+ constructor(error: IAppErrorInput);
13
+ static parseStatusCode(code: unknown): number;
14
+ static resolveMessage(errorCode: string, message?: string): string;
15
+ static isHttpStatusCode(value: unknown): boolean;
16
+ static resolveSystemError(value: unknown): string | null;
17
+ static extractSystemError(appErrorInput: IAppErrorInput, details: Record<string, unknown>): string | null;
18
+ }
19
+ export interface IBuildPublicAppErrorInput {
20
+ errorCode: string;
21
+ message?: string;
22
+ details?: Record<string, unknown>;
23
+ statusCode?: number;
24
+ }
25
+ export declare function buildPublicAppError(data: IBuildPublicAppErrorInput, error?: any): AppError;
@@ -22,6 +22,8 @@ export interface IStartCheckoutRequestBase {
22
22
  browser_info?: any;
23
23
  metadata: any;
24
24
  currency: string;
25
+ apm_config?: IMPConfigRequest | Record<string, any>;
26
+ items?: IItem[];
25
27
  }
26
28
  export type IStartCheckoutRequestWithCard = IStartCheckoutRequestBase & {
27
29
  card: any;
@@ -155,9 +155,10 @@ export interface IApiError {
155
155
  }
156
156
  export interface IPublicError {
157
157
  status: string;
158
- code: number;
158
+ code: string;
159
159
  message: string;
160
- detail: Record<string, any> | string;
160
+ statusCode: number;
161
+ details: Record<string, any>;
161
162
  }
162
163
  export type CustomizationOptions = {
163
164
  redirectOnComplete?: boolean;