@tonder.io/ionic-lite-sdk 1.0.2-beta.TEC-1207.acd2837 → 1.0.2-beta.develop.05dedd2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -2
- package/dist/classes/BaseInlineCheckout.d.ts +2 -0
- package/dist/data/api.d.ts +1 -1
- package/dist/data/cardApi.d.ts +4 -3
- package/dist/data/customerApi.d.ts +2 -1
- package/dist/data/paymentMethodApi.d.ts +1 -1
- package/dist/data/skyflowApi.d.ts +1 -1
- package/dist/helpers/card_on_file.d.ts +3 -0
- package/dist/helpers/coreSupport.d.ts +17 -0
- package/dist/helpers/skyflow.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/shared/constants/apiEndpoints.d.ts +4 -0
- package/dist/types/core.d.ts +5 -0
- package/dist/types/requests.d.ts +1 -1
- package/package.json +1 -1
- package/src/classes/BaseInlineCheckout.ts +35 -6
- package/src/classes/liteCheckout.ts +30 -40
- package/src/data/api.ts +6 -7
- package/src/data/cardApi.ts +27 -20
- package/src/data/customerApi.ts +11 -7
- package/src/data/paymentMethodApi.ts +6 -7
- package/src/data/skyflowApi.ts +5 -6
- package/src/helpers/card_on_file.ts +5 -1
- package/src/helpers/coreSupport.ts +81 -0
- package/src/helpers/skyflow.ts +4 -4
- package/src/shared/constants/apiEndpoints.ts +4 -0
- package/src/types/core.ts +6 -0
- package/src/types/requests.ts +1 -1
- package/tests/cardOnFileCustomerId.test.ts +69 -0
- package/tests/corePaymentCheckout.test.ts +13 -0
- package/tests/coreSupportApis.test.ts +378 -0
package/README.md
CHANGED
|
@@ -22,6 +22,7 @@ Card data is collected through **Skyflow secure iframes** — raw card values ne
|
|
|
22
22
|
- [6.3 Alternative Payment Method (APM)](#63-alternative-payment-method-apm)
|
|
23
23
|
- [6.4 Payment response reference](#64-payment-response-reference)
|
|
24
24
|
- [6.5 Payments API](#65-payments-api)
|
|
25
|
+
- [6.6 Support APIs: customers, saved cards, payment methods and vault token](#66-support-apis-customers-saved-cards-payment-methods-and-vault-token)
|
|
25
26
|
7. [3DS Handling](#7-3ds-handling)
|
|
26
27
|
8. [Managing Saved Cards](#8-managing-saved-cards)
|
|
27
28
|
- [8.1 List saved cards](#81-list-saved-cards)
|
|
@@ -329,6 +330,8 @@ const { access } = await fetch(`${baseUrl}/api/secure-token/`, {
|
|
|
329
330
|
}).then(r => r.json());
|
|
330
331
|
```
|
|
331
332
|
|
|
333
|
+
With `core_payments_enabled: true` for your business, your backend gets this token from Tonder's payments API (see [6.6](#66-support-apis-customers-saved-cards-payment-methods-and-vault-token)). The SDK takes the token you pass to `configureCheckout` as it is and never requests it.
|
|
334
|
+
|
|
332
335
|
> **Security note:** `YOUR_SECRET_API_KEY` is a server-side credential. In production, make this request from your own backend and return only the `access` token to the frontend. Never expose your secret key in client-side code.
|
|
333
336
|
|
|
334
337
|
---
|
|
@@ -770,6 +773,23 @@ When the business configuration the SDK reads at start-up says `core_payments_en
|
|
|
770
773
|
- The `id` the payments API answers is the **transaction id**: one per attempt with a method (a new card in the hosted checkout is a new transaction), while `payment_id` groups the payment. `verify3dsTransaction()` reads that transaction by `GET /transactions/v1/{id}`, and a refund takes it as `original_transaction_id` (the payments API also accepts the `payment_id` there).
|
|
771
774
|
- **Declared difference:** the `refund_transaction` entry of `actions` points at the payments API refund (`POST <payments API base URL>/transactions/v1/process`, authorized with the same API key) instead of the legacy refund route, and `verify_transaction_status` points at the payments API's `GET <payments API base URL>/transactions/v1/{id}` instead of the legacy per-provider verify route (the verify of such a payment no longer answers the legacy per-provider verify body). The object `verify3dsTransaction()` resolves with keeps the legacy names, types and values for what the payments API holds: `id`, `status`, `transaction_status`, `provider`, `amount`, `currency` (only `code`), `currency_code`, `created`, `modified`, `metadata`, `is_apm`, `transaction_type`, and, when the payments API answers them, `card_brand`, `transaction_reference`, `number_of_payment_attempts`, `number_of_installments`, `three_d_secure`, `reason`, `operation_date` and `decline`, `payment` (only `id`), `checkout` (only `id` and `is_route_finished`), `checkout_id` and `response`. Fields the payments API does not hold, such as fees, rates, taxes, net amount, `guardian_*`, card data, `payment_method`, `wallet` and `incoming_request`, are absent, and `verify3dsTransaction()` no longer carries `next_action`, `actions` or the other checkout-router fields for such a payment. The action also carries a `body` hint, `{ operation_type: 'refund', original_transaction_id }`; send it with your `amount` and optional `reason`.
|
|
772
775
|
|
|
776
|
+
### 6.6 Support APIs: customers, saved cards, payment methods and vault token
|
|
777
|
+
|
|
778
|
+
The calls around a payment follow the same business configuration as 6.5. Nothing changes in your integration: same methods, same arguments, same resolved objects and same error codes.
|
|
779
|
+
|
|
780
|
+
| Call (SDK method) | `core_payments_enabled: true` | `false` or absent |
|
|
781
|
+
|---|---|---|
|
|
782
|
+
| Customer (`getCustomerCards()`, `saveCustomerCard()`, `removeCustomerCard()`, `payment()`) | `POST <payments API base URL>/transactions/v1/customer`, with `Authorization: Token <apiKey>` | `POST <base URL>/api/v1/customer/`, as before |
|
|
783
|
+
| Saved cards (`getCustomerCards()`, `saveCustomerCard()`, `removeCustomerCard()`) | `GET` / `POST` `<payments API base URL>/transactions/v1/cards` and `DELETE` `.../cards/<skyflow_id>`, with `Authorization: Bearer <secureToken>` and the `User-Token` header | `<base URL>/api/v1/business/<id>/cards/`, as before |
|
|
784
|
+
| Payment methods (`getCustomerPaymentMethods()`) | `GET <payments API base URL>/transactions/v1/payment_methods` (same query parameters and answer), with `Authorization: Token <apiKey>` | same |
|
|
785
|
+
| Vault token the card fields use | `GET <payments API base URL>/transactions/v1/vault-token`, with `Authorization: Token <apiKey>` | same |
|
|
786
|
+
|
|
787
|
+
- The customer and the saved cards always go to the same place: the customer's token and the secure token are only valid where they were issued. A payment that ends on the legacy flow while the flag is `true` (an alternative payment method, or the retry after `operations_disabled`) registers its customer on the legacy API first.
|
|
788
|
+
- The payments API reads your business from the credential, so its card routes carry no business id.
|
|
789
|
+
- The payments API answers these calls in its own format; the SDK maps each answer onto the object it always returned (`user_id`, `cards[].fields`, `skyflow_id`, the payment methods list), so your code does not change. A refused call rejects with the same error code as before (`FETCH_CARDS_ERROR`, `SAVE_CARD_ERROR`, `REMOVE_CARD_ERROR`, `CUSTOMER_OPERATION_ERROR`, `FETCH_PAYMENT_METHODS_ERROR`, `VAULT_TOKEN_ERROR`), the HTTP status in `statusCode` and the payments API's error code (for example `card_limit_reached`) in `details.systemError`. **Declared difference:** with the flag on, `cards[].fields.cardholder_name` is absent, because the payments API does not return it.
|
|
790
|
+
- The payment methods and the vault token come from the payments API whatever the flag says, as the start-up configuration does.
|
|
791
|
+
- **Secure token with the flag on:** your backend gets it from the payments API (`POST /transactions/v1/secure-token`, with your secret key and the customer) or, if it still calls the legacy `/api/secure-token/`, from that route, which hands over to the payments API for your business. Pass it to `configureCheckout()` as before. Do not turn `core_payments_enabled` on for a business whose app versions still run an older SDK with saved cards: the older SDK would send that token to the legacy card routes.
|
|
792
|
+
|
|
773
793
|
---
|
|
774
794
|
|
|
775
795
|
## 7. 3DS Handling
|
|
@@ -1300,7 +1320,7 @@ customization: {
|
|
|
1300
1320
|
| Property | Replacement | Notes |
|
|
1301
1321
|
|----------|-------------|-------|
|
|
1302
1322
|
| `apiKeyTonder` | `apiKey` | Renamed for clarity |
|
|
1303
|
-
| `baseUrlTonder` | `mode` | Replaced by environment enum (`'stage'` \| `'production'` \| ...). It still overrides the legacy API host, but the payments API host (start-up configuration and
|
|
1323
|
+
| `baseUrlTonder` | `mode` | Replaced by environment enum (`'stage'` \| `'production'` \| ...). It still overrides the legacy API host, but the payments API host (start-up configuration, payments API, payment methods, vault token and, with the flag on, customers and saved cards) is always derived from `mode` and ignores it |
|
|
1304
1324
|
| `signal` | (removed) | AbortController signal is no longer needed |
|
|
1305
1325
|
|
|
1306
1326
|
### Deprecated methods
|
|
@@ -1308,7 +1328,7 @@ customization: {
|
|
|
1308
1328
|
| Deprecated Method | Use Instead | Notes |
|
|
1309
1329
|
|------------------|-------------|-------|
|
|
1310
1330
|
| `getBusiness()` | (auto-handled) | No longer needed |
|
|
1311
|
-
| `customerRegister(email)` | (auto-handled) | No longer needed |
|
|
1331
|
+
| `customerRegister(email)` | (auto-handled) | No longer needed. Follows `core_payments_enabled` like the customer of `payment()` |
|
|
1312
1332
|
| `createOrder(items)` | `payment()` | Replaced by unified `payment()` |
|
|
1313
1333
|
| `createPayment(items)` | `payment()` | Replaced by unified `payment()` |
|
|
1314
1334
|
| `startCheckoutRouter(data)` | `payment()` | Replaced by unified `payment()` |
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ThreeDSHandler } from "./3dsHandler";
|
|
2
|
+
import { ISupportTarget } from "../types/core";
|
|
2
3
|
import { Business, IConfigureCheckout, IInlineCheckoutBaseOptions, CustomizationOptions } from "../types/commons";
|
|
3
4
|
import { ICustomer } from "../types/customer";
|
|
4
5
|
import { IItem, IProcessPaymentRequest, IStartCheckoutResponse } from "../types/checkout";
|
|
@@ -61,6 +62,7 @@ export declare class BaseInlineCheckout<T extends CustomizationOptions = Customi
|
|
|
61
62
|
_initializeCheckout(): Promise<void>;
|
|
62
63
|
_checkout(data: any): Promise<any>;
|
|
63
64
|
_setCartTotal(total: string | number): void;
|
|
65
|
+
protected _supportTarget(): ISupportTarget;
|
|
64
66
|
_getCustomer(signal?: AbortSignal | null): Promise<Record<string, any>>;
|
|
65
67
|
_handleCheckout(request: CheckoutRequest): Promise<any>;
|
|
66
68
|
_fetchMerchantData(): Promise<Business>;
|
package/dist/data/api.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare function getCustomerAPMs(
|
|
1
|
+
export declare function getCustomerAPMs(coreBaseUrl: string, publicApiKeyTonder: string, query?: string, signal?: AbortSignal | null | undefined): Promise<import("../types/paymentMethod").IPaymentMethodResponse>;
|
package/dist/data/cardApi.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
+
import { ISupportTarget } from "../types/core";
|
|
1
2
|
import { ICustomerCardsResponse, ISaveCardInternalResponse, ISaveCardSkyflowRequest } from "../types/card";
|
|
2
|
-
export declare function fetchCustomerCards(
|
|
3
|
-
export declare function saveCustomerCard(
|
|
4
|
-
export declare function removeCustomerCard(
|
|
3
|
+
export declare function fetchCustomerCards(target: ISupportTarget, customerToken: string, secureToken: string, businessId: string | number, signal?: null): Promise<ICustomerCardsResponse>;
|
|
4
|
+
export declare function saveCustomerCard(target: ISupportTarget, customerToken: string, secureToken: string, businessId: string | number, data: ISaveCardSkyflowRequest, appOrigin?: boolean): Promise<ISaveCardInternalResponse>;
|
|
5
|
+
export declare function removeCustomerCard(target: ISupportTarget, customerToken: string, secureToken: string, skyflowId: string | undefined, businessId: string | number): Promise<string>;
|
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
import { CustomerRegisterResponse } from "../types/responses";
|
|
2
|
-
|
|
2
|
+
import { ISupportTarget } from "../types/core";
|
|
3
|
+
export declare function registerOrFetchCustomer(target: ISupportTarget, apiKey: string, customer: Record<string, any>, signal?: AbortSignal | null): Promise<CustomerRegisterResponse>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { IPaymentMethodResponse } from "../types/paymentMethod";
|
|
2
|
-
export declare function fetchCustomerPaymentMethods(
|
|
2
|
+
export declare function fetchCustomerPaymentMethods(coreBaseUrl: string, apiKey: string, params?: {
|
|
3
3
|
status: string;
|
|
4
4
|
pagesize: string;
|
|
5
5
|
}, signal?: null): Promise<IPaymentMethodResponse>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare function getVaultToken(
|
|
1
|
+
export declare function getVaultToken(coreBaseUrl: string, apiKey: string, signal?: null): Promise<any>;
|
|
@@ -12,11 +12,14 @@ export declare class CardOnFile {
|
|
|
12
12
|
private readonly merchantId;
|
|
13
13
|
private readonly apiKey;
|
|
14
14
|
private readonly isTestEnvironment;
|
|
15
|
+
private readonly subscriptionOwner?;
|
|
15
16
|
private acquirerInstance;
|
|
16
17
|
constructor(config: {
|
|
17
18
|
merchantId: string;
|
|
18
19
|
apiKey: string;
|
|
19
20
|
isTestEnvironment?: boolean;
|
|
21
|
+
/** Replaces the `customerId` of `process()` in the subscription metadata when it answers one. */
|
|
22
|
+
subscriptionOwner?: () => string | undefined;
|
|
20
23
|
});
|
|
21
24
|
initialize(): Promise<void>;
|
|
22
25
|
private getAcquirerInstance;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { PaymentEngine } from "../types/core";
|
|
2
|
+
import { AppError } from "../shared/utils/appError";
|
|
3
|
+
import { CustomerRegisterResponse } from "../types/responses";
|
|
4
|
+
import { ICustomerCardsResponse, ISaveCardInternalResponse } from "../types/card";
|
|
5
|
+
import { IPaymentMethodResponse } from "../types/paymentMethod";
|
|
6
|
+
export declare function fromCoreCustomer(body: any): CustomerRegisterResponse;
|
|
7
|
+
export declare function fromCoreCards(body: any): ICustomerCardsResponse;
|
|
8
|
+
export declare function fromCoreSavedCard(body: any): ISaveCardInternalResponse;
|
|
9
|
+
/** The core's list is never paged: the monolith's paged envelope is rebuilt around it. */
|
|
10
|
+
export declare function fromCorePaymentMethods(body: any): IPaymentMethodResponse;
|
|
11
|
+
/**
|
|
12
|
+
* The core's error is `{ error: { code, ... }, request_id }`: its `code` becomes the body's own
|
|
13
|
+
* `code`, where an error's system error is read from, as it was with the monolith's body.
|
|
14
|
+
*/
|
|
15
|
+
export declare function fromCoreErrorBody(body: any): unknown;
|
|
16
|
+
/** The error of a refused support call, from the monolith's body or the core's. */
|
|
17
|
+
export declare function buildSupportError(response: Response, errorCode: string, engine: PaymentEngine): Promise<AppError>;
|
|
@@ -8,8 +8,8 @@ import { IEvents, ILiteCustomizationOptions } from "../types/commons";
|
|
|
8
8
|
* @deprecated This function is deprecated and will be removed in a future release.
|
|
9
9
|
* Use `mountCardFields()` to render Skyflow Elements and collect card data securely.
|
|
10
10
|
*/
|
|
11
|
-
export declare function getSkyflowTokens({
|
|
12
|
-
export declare function initSkyflowInstance({
|
|
11
|
+
export declare function getSkyflowTokens({ coreBaseUrl, apiKey, vault_id, vault_url, data, }: TokensSkyflowRequest): Promise<any>;
|
|
12
|
+
export declare function initSkyflowInstance({ coreBaseUrl, apiKey, vault_id, vault_url, mode, }: TokensSkyflowRequest): Promise<Skyflow>;
|
|
13
13
|
export declare function mountSkyflowFields(event: {
|
|
14
14
|
skyflowInstance: Skyflow;
|
|
15
15
|
data: IMountCardFieldsRequest;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"skyflow-js";function t(e,t,r,o){return new(r||(r=Promise))((function(i,n){function s(e){try{d(o.next(e))}catch(e){n(e)}}function a(e){try{d(o.throw(e))}catch(e){n(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((o=o.apply(e,t||[])).next())}))}function r(e,t,r,o){if("a"===r&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?o:"a"===r?o.call(e):o?o.value:t.get(e)}function o(e,t,r,o,i){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!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"===o?i.call(e,r):i?i.value=r:t.set(e,r),r}"function"==typeof SuppressedError&&SuppressedError;const i=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"}),n=Object.freeze({TELEMETRY:"/telemetry/v1/events",ACQ_SUBSCRIPTION_TOKEN:"/acq-kushki/subscription/token",ACQ_SUBSCRIPTION_CREATE:"/acq-kushki/subscription/create",CORE_BUSINESS_CONFIG:"/transactions/v1/business/config",CORE_PROCESS:"/transactions/v1/process"});function s(e="stage"){return`${i[e]}${n.TELEMETRY}`}function a(e="stage"){return i[e]}var d;!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"}(d||(d={}));const l={[d.INIT_ERROR]:"Error initializing the SDK.",[d.INVALID_TYPE]:"SDK Type invalid.",[d.STATE_ERROR]:"Error updating SDK state.",[d.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[d.INVALID_CONFIG]:"Required configuration options.",[d.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[d.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[d.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[d.TYPE_SDK_REQUIRED]:"SDK type required.",[d.ENVIRONMENT_REQUIRED]:"Environment required.",[d.FETCH_CARDS_ERROR]:"Error retrieving cards.",[d.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.",[d.SAVE_CARD_ERROR]:"Error saving the card.",[d.REMOVE_CARD_ERROR]:"Error deleting the card.",[d.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[d.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[d.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[d.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[d.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[d.START_CHECKOUT_ERROR]:"Error processing the payment.",[d.CREATE_ORDER_ERROR]:"Error creating the order.",[d.BUSINESS_ID_REQUIRED]:"Business ID is required.",[d.CLIENT_ID_REQUIRED]:"Client ID is required.",[d.INVALID_AMOUNT]:"Invalid amount.",[d.INVALID_ITEMS]:"Invalid items.",[d.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[d.INVALID_EMAIL]:"Invalid email.",[d.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[d.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[d.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[d.SECURE_TOKEN_ERROR]:"Error getting secure token.",[d.SECURE_TOKEN_INVALID]:"Invalid secure token.",[d.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[d.REMOVE_CARD]:"Card deleted successfully",[d.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[d.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[d.INVALID_CARD_DATA]:"Invalid card data.",[d.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[d.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[d.CARD_ON_FILE_DECLINED]:"Transaction declined. Please verify your card details.",[d.REQUEST_ABORTED]:"Requests canceled.",[d.REQUEST_FAILED]:"Request failed.",[d.UNKNOWN_ERROR]:"An unexpected error occurred.",[d.CREATE_ERROR]:"Error creating the SDK.",[d.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[d.THREEDS_REDIRECTION_ERROR]:"An error occurred during the 3DS redirection.",[d.REMOVE_SDK_ERROR]:"An error occurred while removing the SDK instance."};d.INIT_ERROR,d.STATE_ERROR,d.FETCH_BUSINESS_ERROR,d.INVALID_CONFIG,d.TYPE_SDK_REQUIRED,d.ENVIRONMENT_REQUIRED,d.FETCH_CARDS_ERROR,d.SAVE_CARD_ERROR,d.REMOVE_CARD_ERROR,d.CREATE_PAYMENT_ERROR,d.START_CHECKOUT_ERROR,d.CREATE_ORDER_ERROR,d.BUSINESS_ID_REQUIRED,d.CLIENT_ID_REQUIRED,d.INVALID_AMOUNT,d.INVALID_ITEMS,d.CUSTOMER_OPERATION_ERROR,d.INVALID_EMAIL,d.FETCH_PAYMENT_METHODS_ERROR,d.INVALID_VAULT_TOKEN,d.VAULT_TOKEN_ERROR,d.SECURE_TOKEN_ERROR,d.INVALID_SECRET_API_KEY,d.CUSTOMER_AUTH_TOKEN_NOT_VALID,d.SECURE_TOKEN_INVALID,d.REMOVE_CARD,d.SKYFLOW_NOT_INITIALIZED,d.INVALID_TYPE,d.PAYMENT_PROCESS_ERROR,d.INVALID_PAYMENT_REQUEST,d.INVALID_PAYMENT_REQUEST_CARD_PM,d.SAVE_CARD_PROCESS_ERROR,d.ERROR_LOAD_PAYMENT_FORM,d.INVALID_CARD_DATA,d.ERROR_LOAD_ENROLLMENT_FORM,d.MOUNT_COLLECT_ERROR,d.CARD_ON_FILE_DECLINED,d.CARD_SAVED_SUCCESSFULLY,d.CARD_REMOVED_SUCCESSFULLY,d.REQUEST_ABORTED,d.REQUEST_FAILED,d.UNKNOWN_ERROR,d.CREATE_ERROR,d.FETCH_TRANSACTION_ERROR,d.THREEDS_REDIRECTION_ERROR,d.REMOVE_SDK_ERROR;const c="__tonderLockErrorCode__";function u(e){return"object"==typeof e&&null!==e}class h extends Error{constructor(e){var t,r;const o=h.resolveStatusCode(e.statusCode,e.originalError),i=h.resolveMessage(e.errorCode,e.message),n=h.resolveSystemError(null===(t=e.details)||void 0===t?void 0:t.systemError,e.originalError);super(i),this.status="error",Object.setPrototypeOf(this,new.target.prototype),this.name="TonderError",this.code=e.errorCode,this.statusCode=o,this.originalError=e.originalError,this.details={code:e.errorCode,statusCode:o,systemError:n},e.lockErrorCode&&Object.defineProperty(this,c,{value:!0,enumerable:!1,configurable:!0}),null===(r=Error.captureStackTrace)||void 0===r||r.call(Error,this,h)}static isRecord(e){return"object"==typeof e&&null!==e}static parseStatusCode(e){const t=Number(e);return Number.isFinite(t)?t<100||t>599?500:Math.trunc(t):500}static resolveStatusCode(e,t){const r=[e];if(h.isRecord(t)){r.push(t.statusCode,t.status);const e=h.isRecord(t.body)?t.body:null;e&&r.push(e.statusCode,e.status)}for(const e of r)if(h.isHttpStatusCode(e))return Math.trunc(Number(e));return 500}static resolveMessage(e,t){return t||(l[e]||l[d.UNKNOWN_ERROR]||"An unexpected error occurred.")}static isHttpStatusCode(e){const t=Number(e);return Number.isFinite(t)&&t>=100&&t<=599}static normalizeSystemError(e){if("string"!=typeof e)return null;return e.trim()||null}static resolveSystemError(e,t){const r=[e];if(h.isRecord(t)){const e=h.isRecord(t.details)?t.details:null,o=h.isRecord(t.body)?t.body:null,i=o&&h.isRecord(o.details)?o.details:null;r.push(t.systemError,t.code,null==e?void 0:e.systemError,null==e?void 0:e.code,null==o?void 0:o.systemError,null==o?void 0:o.code,null==i?void 0:i.systemError,null==i?void 0:i.code)}for(const e of r){const t=h.normalizeSystemError(e);if(t)return t}return"APP_INTERNAL_001"}}function _(e){return u(e)&&!0===e[c]}function E(e){return e instanceof h&&void 0!==e.originalError?e.originalError:e}function m(e){return t(this,void 0,void 0,(function*(){try{return yield e.clone().json()}catch(e){}try{return(yield e.text())||void 0}catch(e){return}}))}function p(e,t){var r;if(!(null==e?void 0:e.errorCode))throw new Error("buildPublicAppError requires errorCode");const o=null===(r=e.details)||void 0===r?void 0:r.systemError,i=!!e.message||void 0!==e.statusCode||void 0!==o;return!function(e){return u(e)&&"TonderError"===e.name&&"string"==typeof e.code}(t)||(e.lockErrorCode&&function(e){Object.defineProperty(e,c,{value:!0,enumerable:!1,configurable:!0})}(t),i||e.errorCode!==t.code&&!_(t))?new h({errorCode:e.errorCode,message:e.message,statusCode:e.statusCode,details:void 0!==o?{systemError:o}:void 0,originalError:E(t),lockErrorCode:e.lockErrorCode||_(t)}):t}function R(e){var t,r;const o={status:e.status};return e.statusText&&(o.statusText=e.statusText),void 0!==e.body&&(o.body=e.body),new h({errorCode:e.errorCode,message:e.message,statusCode:null!==(t=e.statusCode)&&void 0!==t?t:e.status,details:void 0!==(null===(r=e.details)||void 0===r?void 0:r.systemError)?{systemError:e.details.systemError}:void 0,originalError:o,lockErrorCode:e.lockErrorCode})}function y(e,r){return(null==e?void 0:e.response)?function(e){return t(this,void 0,void 0,(function*(){return R(Object.assign(Object.assign({},e),{status:e.response.status,statusText:e.response.statusText,body:yield m(e.response)}))}))}(e):p(e,r)}function v(e,r,o){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}${n.CORE_BUSINESS_CONFIG}`,{headers:{Authorization:`Token ${r}`},signal:o});if(t.ok)return yield t.json();throw yield y({response:t,errorCode:d.FETCH_BUSINESS_ERROR})}))}class f extends Error{constructor(e){var t,r;const o=e.message||l[e.code]||"Unknown error";super(o),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(r=e.details)||void 0===r?void 0:r.message)||o}}}const C=Object.freeze({production:"https://d35a75syrgujp0.cloudfront.net",sandbox:"https://static.staging.tonder.io",stage:"https://static.staging.tonder.io",development:"https://static.staging.tonder.io"});function A(e="stage"){return C[e]||C.stage}const O=()=>({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}),T=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},S=e=>!e||"card"===e.toLowerCase(),g=(e,t="stage")=>{const r=A(t);return"Visa"===e?`${r}/cards/visa.png`:"Mastercard"===e?`${r}/cards/mastercard.png`:"American Express"===e?`${r}/cards/american_express.png`:`${r}/cards/default_card.png`};const I=new Set(["https:"]);function N(e){if("string"!=typeof e)return!1;try{return I.has(new URL(e,document.baseURI).protocol)}catch(e){return!1}}const b=new Set(["script","object","embed","applet","link","meta","base","style","template"]),D=new Set(["srcdoc","style","ping","srcset"]),k=new Set(["src","href","action","formaction","data","poster","background"]);function M(e){const t=e.trim();return""===t||("about:blank"===t.toLowerCase()||N(t))}function P(e){for(const t of Array.from(e.attributes)){const r=t.localName.toLowerCase();r.startsWith("on")||D.has(r)?e.removeAttributeNode(t):k.has(r)&&!M(t.value)&&e.removeAttributeNode(t)}}const U=["Pending","Processing"];class L{constructor({payload:e=null,apiKey:t,baseUrl:r,coreBaseUrl:o,buildCoreResult:i=(e=>e),redirectOnComplete:n,tdsIframeId:s,tonderPayButtonId:a,callBack:d}){this.engine="legacy",this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.buildCoreResult=i,this.baseUrl=r,this.coreBaseUrl=o,this.apiKey=t,this.payload=e,this.tdsIframeId=s,this.tonderPayButtonId=a,this.redirectOnComplete=n,this.callBack=d}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,r,o,i,n;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===(n=null===(i=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===i?void 0:i.iframe_resources)||void 0===n?void 0:n.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}setEngine(e){this.engine=e}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5,engine:this.engine};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getStoredVerification(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t}return null}getUrlWithExpiration(){var e;const t=this.getStoredVerification();return void 0===t?void 0:null!==(e=null==t?void 0:t.url)&&void 0!==e?e:null}getStoredEngine(){var e;return"core"===(null===(e=this.getStoredVerification())||void 0===e?void 0:e.engine)?"core":"legacy"}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,r;if(null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.iframe)return new Promise(((e,t)=>{var r,o,i;const n=null===(i=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===i?void 0:i.iframe;if(n){this.saveVerifyTransactionUrl();const r=document.createElement("div");r.style.display="none",r.appendChild(function(e){const t=(new DOMParser).parseFromString(e,"text/html");for(const e of Array.from(t.body.querySelectorAll("*")))"http://www.w3.org/1999/xhtml"!==e.namespaceURI||b.has(e.localName)?e.remove():P(e);const r=document.createDocumentFragment();for(const e of Array.from(t.body.childNodes))r.appendChild(document.importNode(e,!0));return r}(n)),document.body.appendChild(r);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',r.appendChild(o);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(!N(e))throw y({errorCode:d.THREEDS_REDIRECTION_ERROR,statusCode:400,lockErrorCode:!0});if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const r=document.querySelector(`#${this.tdsIframeId}`);if(r){r.setAttribute("src",e),r.setAttribute("style","display: block");const o=this,i=e=>t(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}r&&r.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),r.removeEventListener("load",i)},n=r=>t(this,void 0,void 0,(function*(){const i=yield new Promise(((e,t)=>e(r)));if(i){if((e=>o.isVerificationFinal(e))(i))return e();{const e=setTimeout((()=>t(this,void 0,void 0,(function*(){clearTimeout(e),yield n(o.requestTransactionStatus())}))),7e3)}}}));yield n(o.requestTransactionStatus())}));r.addEventListener("load",i)}else console.log("No iframe found")}}else this.callBack&&this.callBack(this.payload)}fetchVerification(e){return t(this,void 0,void 0,(function*(){const t="core"===e.engine?this.coreBaseUrl:this.baseUrl,r=e.url.startsWith("https://")?e.url:`${t}${e.url}`;return yield fetch(r,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}})}))}requestTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getStoredVerification();if(!e)return null;let t;try{if(t=yield this.fetchVerification(e),200===t.status)return yield t.json()}catch(t){if(this.isTransientCoreFailure(e))return this.keepPolling();throw t}return console.error("La verificación de la transacción falló."),this.isTransientCoreFailure(e,t.status)?this.keepPolling():null}))}keepPolling(){return{status:"Pending",transaction_status:"Pending"}}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[r,o]of t)e[r]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return t(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const r=document.createElement("input");r.type="hidden",r.name=e.creq,r.value=e.creq,t.appendChild(r);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return t(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)}))}isCoreOpen(e){return U.includes(null==e?void 0:e.status)}handleCoreTransaction(e){return t(this,void 0,void 0,(function*(){const t=yield e.json();return this.isCoreOpen(t)||this.removeVerifyTransactionUrl(),this.buildCoreResult(t)}))}isVerificationFinal(e){return"core"===this.engine?!this.isCoreOpen(e):"Pending"!==(null==e?void 0:e.transaction_status)}isTransientCoreFailure(e,t){return"core"===e.engine&&(void 0===t||t>=500||429===t||408===t)}verifyTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getStoredVerification();if(null==e?void 0:e.url)try{const t=yield this.fetchVerification(e);if(200!==t.status){if(console.error("La verificación de la transacción falló."),this.isTransientCoreFailure(e,t.status)||this.removeVerifyTransactionUrl(),"core"===e.engine)throw yield y({response:t,errorCode:d.FETCH_TRANSACTION_ERROR});return t}return"core"===e.engine?yield this.handleCoreTransaction(t):yield this.handleTransactionResponse(t)}catch(t){if(console.error("Error al verificar la transacción:",t),"core"===e.engine)throw y({errorCode:d.FETCH_TRANSACTION_ERROR},t);this.removeVerifyTransactionUrl()}else console.log("No verify_transaction_status_url found")}))}}const w=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function V(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/checkout-router/`,i=o,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(Object.assign(Object.assign({},i),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(n.ok)return yield n.json();throw yield y({response:n,errorCode:d.START_CHECKOUT_ERROR})}))}function F(e,r,o=!0,i=null){return t(this,void 0,void 0,(function*(){let t=yield window.OpenPay;return t.setId(e),t.setApiKey(r),t.setSandboxMode(o),yield t.deviceData.setup({signal:i})}))}function j(e){return/^\d{12,19}$/.test(e)&&$(e)}function K(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function x(e){return/^\d{3,4}$/.test(e)}function B(e){return/^(0[1-9]|1[0-2])$/.test(e)}function Y(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const $=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),r=t.shift();let o=t.reduce(((e,t,r)=>r%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=r,o%10==0};function H(e,t,r){const o=t.replace(/\[(\w+)\]/g,".$1").split(".").filter((e=>""!==e));let i=e;for(const e of o){if(null==i)return r;i=i[e]}return void 0===i?r:i}const q="https://cdn.kushkipagos.com/kushki.min.js",z=d.CARD_ON_FILE_DECLINED;let X=!1,Q=null;class W{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=a(r),this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return t(this,void 0,void 0,(function*(){yield function(){return t(this,void 0,void 0,(function*(){return X?Promise.resolve():Q||(Q=new Promise(((e,t)=>{if(document.querySelector(`script[src="${q}"]`))return X=!0,void e();const r=document.createElement("script");r.src=q,r.async=!0,r.onload=()=>{X=!0,e()},r.onerror=()=>{Q=null,t(y({errorCode:z,lockErrorCode:!0,details:{step:"load_acquirer_script",message:"Failed to load acquirer script"}}))},document.head.appendChild(r)})),Q)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw y({errorCode:z,lockErrorCode:!0,details:{step:"create_acquirer_instance",message:"Acquirer script not loaded. Call initialize() first."}});return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw y({errorCode:z,lockErrorCode:!0,details:{step:"get_acquirer_instance",message:"CardOnFile not initialized. Call initialize() first."}});return this.acquirerInstance}getJwt(e){return t(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((r,o)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void o(y({errorCode:z,lockErrorCode:!0,details:{step:"get_jwt",acquirerResponse:e}}));const t=e;t.jwt?r(t.jwt):o(y({errorCode:z,lockErrorCode:!0,details:{step:"get_jwt",message:"No JWT returned from acquirer",acquirerResponse:t}}))}))}))}))}generateToken(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${n.ACQ_SUBSCRIPTION_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield y({response:t,errorCode:z,lockErrorCode:!0,details:{step:"generate_token"}});return t.json()}))}createSubscription(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${n.ACQ_SUBSCRIPTION_CREATE}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield y({response:t,errorCode:z,lockErrorCode:!0,details:{step:"create_subscription"}});return t.json()}))}validate3DS(e,r){return t(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((o,i)=>{t.requestValidate3DS({secureId:e,security:r},(e=>{const t=e;t.code&&"3DS000"!==t.code?i(y({errorCode:z,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}})):!1!==t.isValid?o(!0):i(y({errorCode:z,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}}))}))}))}))}process(e){var r,o;return t(this,void 0,void 0,(function*(){const t=yield this.getJwt(e.cardBin),i=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:t}),n=i.secureId||(null===(r=i.details)||void 0===r?void 0:r.secureId),s=i.security||(null===(o=i.details)||void 0===o?void 0:o.security);if(!n||!s)throw y({errorCode:z,lockErrorCode:!0,details:{step:"process",message:"Missing secureId or security in token response",tokenResponse:i}});return yield this.validate3DS(n,s),this.createSubscription({token:i.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}class J{constructor(e){this.REQUEST_TIMEOUT_MS=5e3,this.MAX_MESSAGE_LENGTH=500,this.config=e}captureException(e,t){try{const r=this.buildEvent(e,t||{});this.sendEvent(r)}catch(e){}}extractErrorInfo(e){try{if(e instanceof Error)return{name:e.name||"Error",message:this.truncate(e.message||"Unknown error",this.MAX_MESSAGE_LENGTH),stack:e.stack||void 0};const t=this.safeStringify(e);return{name:"NonErrorException",message:this.truncate(t,this.MAX_MESSAGE_LENGTH),stack:void 0}}catch(e){return{name:"SerializationError",message:"Failed to serialize error",stack:void 0}}}safeStringify(e){try{const t=new WeakSet;return JSON.stringify(e,((e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return"[Circular]";t.add(r)}return r}))}catch(t){return String(e)}}buildEvent(e,t){const r=this.extractErrorInfo(e),o=Object.assign({},t.metadata||{});void 0===o.error&&(o.error=e),"undefined"!=typeof window&&(o.url=window.location.href);const 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:o};return t.tenant_id&&(i.tenant_id=t.tenant_id),t.request_id&&(i.request_id=t.request_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 t(this,void 0,void 0,(function*(){try{const t=JSON.stringify(e),r=new AbortController,o=setTimeout((()=>r.abort()),this.REQUEST_TIMEOUT_MS);try{const e=yield fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.config.apiKey}`},body:t,keepalive:!0,signal:r.signal});return clearTimeout(o),e.ok}catch(e){return clearTimeout(o),!1}}catch(e){return!1}}))}}const G=Object.freeze({name:"@tonder.io/ionic-lite-sdk",version:"1.0.2"});function Z(e){var t;return e instanceof h&&ee({status:e.statusCode,body:null===(t=e.originalError)||void 0===t?void 0:t.body})}function ee(e){var t,r;return 503===e.status&&"operations_disabled"===(null===(r=null===(t=e.body)||void 0===t?void 0:t.error)||void 0===r?void 0:r.code)}const te=["Success","Authorized","Pending","Processing"],re=["card_number","cvv","expiration_month","expiration_year","cardholder_name"];function oe(e){return void 0!==e&&/^\d+$/.test(e)?Number(e):e}function ie(e,t){return[{name:"verify_transaction_status",url:`${t.coreBaseUrl}/transactions/v1/${e.id}`,method:"GET"},{name:"refund_transaction",url:`${t.coreBaseUrl}/transactions/v1/process`,method:"POST",body:{operation_type:"refund",original_transaction_id:e.id}}]}function ne(e,t){var r,o;const i=e.routing,n=null!==(r=null==i?void 0:i.rejected_psp_responses)&&void 0!==r?r:[],s="Hard"===(null==i?void 0:i.decline_type);return{status:"404",message:s?"Hard decline":null!==(o=e.decline_reason)&&void 0!==o?o:"Transaction declined",checkout_id:null==i?void 0:i.checkout_id,is_route_finished:null==i?void 0:i.is_route_finished,transaction_status:e.status,transaction_id:oe(e.transaction_id),payment_id:e.payment_id,provider:e.provider,decline_code:e.decline_code,psp_response:s?n[n.length-1]:n,actions:ie(e,t)}}function se(e){var t,r;return{status:"200",message:null!==(t=e.decline_reason)&&void 0!==t?t:"High risk transaction blocked",checkout_id:null===(r=e.routing)||void 0===r?void 0:r.checkout_id,transaction_status:"Declined",transaction_id:e.transaction_id,payment_id:e.payment_id,provider:e.provider,amount:Number(e.amount)||0,currency:e.currency,psp_response:e.psp_response,decline_code:e.decline_code}}function ae(e,t){var r,o,i;return{status:"200",message:"Success",checkout_id:null===(r=e.routing)||void 0===r?void 0:r.checkout_id,is_route_finished:null===(o=e.routing)||void 0===o?void 0:o.is_route_finished,transaction_status:e.status,transaction_id:oe(e.transaction_id),payment_id:e.payment_id,provider:e.provider,next_action:null!==(i=e.next_action)&&void 0!==i?i:{},psp_response:e.psp_response,actions:ie(e,t)}}const de=["card_brand","transaction_reference","number_of_payment_attempts","number_of_installments","three_d_secure","reason","operation_date","decline"],le=(e,t)=>null==e?e:t(e),ce={payment:"PAYMENT",refund:"REFUND"};function ue(e){var t;const r=e.routing,o=null==r?void 0:r.checkout_id,i={id:le(e.transaction_id,oe),metadata:e.metadata,response:e.psp_response,payment:le(e.payment_id,(e=>({id:e}))),checkout:le(o,(e=>({id:e,is_route_finished:null==r?void 0:r.is_route_finished}))),checkout_id:o,transaction_type:ce[null!==(t=e.operation_type)&&void 0!==t?t:""],amount:e.amount,currency:le(e.currency,(e=>({code:e}))),currency_code:e.currency,created:e.created_at,modified:e.updated_at};return Object.assign(Object.assign({status:e.status,transaction_status:e.status,provider:e.provider||"tonder",is_apm:!1},Object.fromEntries(Object.entries(i).filter((([,e])=>void 0!==e)))),Object.fromEntries(de.filter((t=>t in e)).map((t=>[t,e[t]]))))}function he(e,t){var r,o;return{status:String(e),message:null!==(o=null===(r=null==t?void 0:t.error)||void 0===r?void 0:r.message)&&void 0!==o?o:"Error",psp_response:[],is_route_finished:!1}}var _e,Ee,me,pe,Re,ye,ve,fe,Ce,Ae,Oe,Te,Se,ge,Ie,Ne;class be{constructor({mode:e="stage",customization:t,apiKey:r,apiKeyTonder:o,returnUrl:i,tdsIframeId:n,callBack:d=(()=>{}),baseUrlTonder:l,tonderPayButtonId:c,sdkInfo:u}){_e.add(this),this.baseUrl="",this.coreBaseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,Ee.set(this,void 0),me.set(this,void 0),this.apiKeyTonder=o||r||"",this.returnUrl=i,this.callBack=d,this.mode=e,this.customer={},this.baseUrl=l||w[this.mode]||w.stage,this.coreBaseUrl=a(this.mode),this.abortController=new AbortController,this.requestId=this.generateRequestId(),this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new L({apiKey:this.apiKeyTonder,baseUrl:this.baseUrl,coreBaseUrl:this.coreBaseUrl,buildCoreResult:ue,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:n,tonderPayButtonId:c,callBack:d}),this.tdsIframeId=n;const h=u||G;this.telemetry=new J({endpoint:s(this.mode),apiKey:this.apiKeyTonder,platform:h.name,platform_version:h.version,mode:this.mode||"stage"})}configureCheckout(e){"secureToken"in e&&r(this,_e,"m",Ce).call(this,e.secureToken),r(this,_e,"m",ve).call(this,e)}getCustomerId(){var e,t;return null===(t=null===(e=r(this,me,"f"))||void 0===e?void 0:e.id)||void 0===t?void 0:t.toString()}reportSdkError(e,t){var r,o,i,n;try{const s=this.getCustomerId(),a=e instanceof h&&void 0!==e.originalError?e.originalError:e,d=Object.assign(Object.assign({},(null==t?void 0:t.metadata)||{}),void 0===(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.error)?{error:a}:{}),l=Object.assign(Object.assign({tenant_id:null===(n=null===(i=null===(o=this.merchantData)||void 0===o?void 0:o.business)||void 0===i?void 0:i.pk)||void 0===n?void 0:n.toString(),user_id:s},t||{}),{metadata:d,request_id:this.requestId});l.user_id||delete l.user_id,l.feature=(null==t?void 0:t.feature)||"unknown",this.telemetry.captureException(e,l)}catch(e){}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}verify3dsTransaction(){return t(this,void 0,void 0,(function*(){const e=this.process3ds.getStoredEngine(),t=yield this.process3ds.verifyTransactionStatus();if("core"===e)return this.process3ds.setPayload(t),t;this.process3ds.setEngine("legacy");const o=yield r(this,_e,"m",ge).call(this,t);return this.process3ds.setPayload(o),this._handle3dsRedirect(o)}))}payment(e){return new Promise(((o,i)=>t(this,void 0,void 0,(function*(){var t,n;let s;try{r(this,_e,"m",ve).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),o(s)}}catch(r){this.reportSdkError(r,{feature:"payment",process_id:(null==s?void 0:s.payment_id)||(null===(t=null==s?void 0:s.payment)||void 0===t?void 0:t.id)||(null===(n=null==s?void 0:s.payment)||void 0===n?void 0:n.pk),metadata:{step:"payment",request:e,response:s}}),i(y({errorCode:d.PAYMENT_PROCESS_ERROR},r))}}))))}getSecureToken(e){return t(this,void 0,void 0,(function*(){try{return yield function(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:o});if(t.ok)return yield t.json();throw yield y({response:t,errorCode:d.SECURE_TOKEN_ERROR})}))}(this.baseUrl,e)}catch(e){throw this.reportSdkError(e,{feature:"secure-token",metadata:{step:"getSecureToken"}}),y({errorCode:d.SECURE_TOKEN_ERROR},e)}}))}_initializeCheckout(){return t(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 t(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 t(this,void 0,void 0,(function*(){return r(this,me,"f")||o(this,me,yield function(e,r,o,i=null){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/customer/`,n={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},s=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},signal:i,body:JSON.stringify(n)});if(s.ok)return yield s.json();throw yield y({response:s,errorCode:d.CUSTOMER_OPERATION_ERROR})}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),r(this,me,"f")}))}_handleCheckout(e){var o;return t(this,void 0,void 0,(function*(){if(!0===(null===(o=this.merchantData)||void 0===o?void 0:o.core_payments_enabled)&&r(this,_e,"m",pe).call(this,e)){this.process3ds.setEngine("core");try{return yield r(this,_e,"m",Re).call(this,e)}catch(e){if(!Z(e))throw e}}return this.process3ds.setEngine("legacy"),r(this,_e,"m",ye).call(this,e)}))}_fetchMerchantData(){return t(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield v(this.coreBaseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){throw this.reportSdkError(e,{feature:"fetch-merchant-data",metadata:{step:"_fetchMerchantData"}}),y({errorCode:d.FETCH_BUSINESS_ERROR},e)}}))}_getCustomerCards(e,r){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i,n=null){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${i}/cards/`,s=yield fetch(t,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},signal:n});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield y({response:s,errorCode:d.FETCH_CARDS_ERROR})}))}(this.baseUrl,e,this.secureToken,r)}))}_saveCustomerCard(e,r,o,i=!1){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i,n,s=!1){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${i}/cards/`,a=yield fetch(t,{method:"POST",headers:Object.assign({Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},s?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(n)});if(a.ok)return yield a.json();throw yield y({response:a,errorCode:d.SAVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,r,o,i)}))}_removeCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i="",n){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${n}/cards/${i}`,s=yield fetch(t,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r}});if(204===s.status)return l[d.CARD_REMOVED_SUCCESSFULLY];if(s.ok&&"json"in s)return yield s.json();throw yield y({response:s,errorCode:d.REMOVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,o,r)}))}_fetchCustomerPaymentMethods(){return t(this,void 0,void 0,(function*(){return yield function(e,r,o={status:"active",pagesize:"10000"},i=null){return t(this,void 0,void 0,(function*(){const t=new URLSearchParams(o).toString(),n=yield fetch(`${e}/api/v1/payment_methods?${t}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(n.ok)return yield n.json();throw yield y({response:n,errorCode:d.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder)}))}_hasCardOnFileKeys(){var e,t;return!!(null===(t=null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys)||void 0===t?void 0:t.public_key)}_initializeCardOnFile(){var e;return t(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new W({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 r,o;return t(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(r=null==e?void 0:e.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>this.process3ds.verifyTransactionStatus())).catch((t=>{console.log("Error loading iframe:",t),this.reportSdkError(t,{feature:"3ds-verification",metadata:{step:"_handle3dsRedirect",response:e}})}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function De(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${r}`},signal:o});if(t.ok){return(yield t.json()).token}throw yield y({response:t,errorCode:d.VAULT_TOKEN_ERROR})}))}Ee=new WeakMap,me=new WeakMap,_e=new WeakSet,pe=function({card:e,payment_method:t}){return!!e&&S(t)},Re=function({card:e,returnUrl:r}){return t(this,void 0,void 0,(function*(){const{reference:o}=this.merchantData;let i,s;try{i=function(e){const{card:t,customer:r}=e,o=[H(r,"firstName",H(r,"name","")),H(r,"lastName",H(r,"lastname",""))].filter(Boolean).join(" "),i=t.card_number?Object.assign(Object.assign({type:"CARD"},Object.fromEntries(re.map((e=>[e,t[e]])))),t.skyflow_id?{skyflow_id:t.skyflow_id}:{}):{type:"CARD",token:t.skyflow_id};return{operation_type:"payment",amount:e.amount,currency:e.currency,client_reference:String(e.reference),customer:{name:o,email:H(r,"email",""),phone:H(r,"phone",void 0),identification:H(r,"identification",void 0)},payment_method:i,metadata:e.metadata,return_url:e.returnUrl,items:e.items,browser_info:e.browserInfo}}({amount:Number(this.cartTotal),currency:this.currency,reference:this.order_reference?this.order_reference:o,customer:this.customer,card:e,metadata:this.metadata,returnUrl:r||this.returnUrl,items:this.cartItems,browserInfo:O()});const h=yield function(e,r,o,i){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}${n.CORE_PROCESS}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`,"X-App-Origin":"sdk/ionic","X-Request-Id":i},body:JSON.stringify(o)}),s=t.ok?yield t.json():yield t.json().catch((()=>{}));return{status:t.status,statusText:t.statusText,body:s}}))}(this.coreBaseUrl,this.apiKeyTonder,i,function(){const e=globalThis.crypto;return"function"==typeof(null==e?void 0:e.randomUUID)?e.randomUUID():`req_${Date.now()}_${Math.random().toString(36).slice(2,12)}`}());if(h.status>=400&&(a=h.status,l=h.body,s={status:a,code:null===(c=null==l?void 0:l.error)||void 0===c?void 0:c.code,type:null===(u=null==l?void 0:l.error)||void 0===u?void 0:u.type,request_id:null==l?void 0:l.request_id}),ee(h))throw R({errorCode:d.START_CHECKOUT_ERROR,status:h.status,body:h.body});const _=function(e,t,r,o){var i;if(402===e&&"payment_declined"===(null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.code))return{outcome:"reject",status:404,body:{status:"404",message:"Error",psp_response:[],is_route_finished:!0}};if(e>=400)return{outcome:"reject",status:e,statusText:o,body:he(e,t)};const n=t;return te.includes(n.status)?{outcome:"resolve",status:200,body:ae(n,r)}:"Declined"===n.status&&"FH01"===n.decline_code?{outcome:"resolve",status:200,body:se(n)}:{outcome:"reject",status:404,body:ne(n,r)}}(h.status,h.body,{coreBaseUrl:this.coreBaseUrl},h.statusText);if("resolve"===_.outcome)return _.body;throw R({errorCode:d.START_CHECKOUT_ERROR,status:_.status,statusText:_.statusText,body:_.body})}catch(e){throw Z(e)||this.reportSdkError(e,{feature:"payment",metadata:{step:"_handleCheckout",payment:i,core_error:s}}),e}var a,l,c,u}))},ye=function({card:e,payment_method:o,customer:i,isSandbox:n,enable_card_on_file:s,returnUrl:a}){return t(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:u}=this.merchantData,h=Number(this.cartTotal);let _,E,m;try{let p;!p&&l.merchant_id&&l.public_key&&!o&&(p=yield F(l.merchant_id,l.public_key,n,this.abortController.signal));const{id:R,auth_token:v}=i;_={business:this.apiKeyTonder,client:v,billing_address_id:null,shipping_address_id:null,amount:h,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata};const f=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/orders/`,i=o,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(n.ok)return yield n.json();throw yield y({response:n,errorCode:d.CREATE_ORDER_ERROR})}))}(this.baseUrl,this.apiKeyTonder,_),C=(new Date).toISOString();E={business_pk:u.pk,client_id:R,amount:h,date:C,order_id:f.id,customer_order_reference:this.order_reference?this.order_reference:c,items:this.cartItems,currency:this.currency,metadata:this.metadata};const A=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${o.business_pk}/payments/`,i=o,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(n.ok)return yield n.json();throw yield y({response:n,errorCode:d.CREATE_PAYMENT_ERROR})}))}(this.baseUrl,this.apiKeyTonder,E);m=Object.assign(Object.assign(Object.assign(Object.assign({name:H(this.customer,"firstName",H(this.customer,"name","")),last_name:H(this.customer,"lastName",H(this.customer,"lastname","")),email_client:H(this.customer,"email",""),phone_number:H(this.customer,"phone",""),return_url:a||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:h,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:f.id,business_id:u.pk,payment_id:A.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:O(),currency:this.currency},o?{payment_method:o}:{card:e}),{apm_config:r(this,Ee,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==s?{enable_card_on_file:s}:{});const T=yield V(this.baseUrl,this.apiKeyTonder,m);return T||!1}catch(e){throw this.reportSdkError(e,{feature:"payment",process_id:null==m?void 0:m.payment_id,metadata:{step:"_handleCheckout",orderItems:_,paymentItems:E,routerItems:m}}),e}}))},ve=function(e){var t,o;!e||e&&0===Object.keys(e).length||(r(this,_e,"m",fe).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),r(this,_e,"m",Ae).call(this,(null===(o=e.cart)||void 0===o?void 0:o.items)||[]),r(this,_e,"m",Oe).call(this,e),r(this,_e,"m",Te).call(this,e),r(this,_e,"m",Se).call(this,e),r(this,_e,"m",Ie).call(this,e))},fe=function(e){e&&(this.customer=e)},Ce=function(e){if("string"!=typeof(t=e)||!/^[\x21-\x7E]+$/.test(t))throw y({errorCode:d.SECURE_TOKEN_INVALID,statusCode:400});var t;this.secureToken=e},Ae=function(e){this.cartItems=e},Oe=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},Te=function(e){this.currency=null==e?void 0:e.currency},Se=function(e){this.card=null==e?void 0:e.card},ge=function(e){var r,o,i,n,s;return t(this,void 0,void 0,(function*(){if("Hard"===(null===(r=null==e?void 0:e.decline)||void 0===r?void 0:r.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(i=e.checkout)||void 0===i?void 0:i.id)||(null==e?void 0:e.checkout_id)};try{return yield V(this.baseUrl,this.apiKeyTonder,t)}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==e?void 0:e.payment_id)||(null===(n=null==e?void 0:e.payment)||void 0===n?void 0:n.id)||(null===(s=null==e?void 0:e.payment)||void 0===s?void 0:s.pk),metadata:{step:"#resumeCheckout",response:e}})}return e}}))},Ie=function(e){o(this,Ee,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"}(Ne||(Ne={}));const ke={type:e.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},Me=RegExp("^(?!s*$).+"),Pe={type:e.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:Me,error:"El campo es requerido"}},Ue="Titular de la tarjeta",Le="Número de tarjeta",we="CVC/CVV",Ve="Mes",Fe="Año",je="Fecha de expiración",Ke="Nombre como aparece en la tarjeta",xe="1234 1234 1234 1234",Be="3-4 dígitos",Ye="MM",$e="AA",He={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")'}},qe={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},ze={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function Xe({baseUrl:r,apiKey:o,vault_id:i,vault_url:n,data:s}){return t(this,void 0,void 0,(function*(){const a=e.init({vaultID:i,vaultURL:n,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield De(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),l=yield function(r,o){return t(this,void 0,void 0,(function*(){const i=yield function(r,o){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(r).map((r=>t(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:r,type:e.ElementType.INPUT_FIELD}),key:r}})))))}))}(r,o);return i?i.map((e=>new Promise((t=>{var o;const i=document.createElement("div");i.hidden=!0,i.id=`id-${e.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(i),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const o=r[e.key];return e.element.setValue(o),t(e.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(l)).some((e=>!e)))throw y({errorCode:d.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}});try{const e=yield a.collect();if(e)return e.records[0].fields;throw y({errorCode:d.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}})}catch(e){throw y({errorCode:d.SAVE_CARD_PROCESS_ERROR},e)}}))}function Qe(t){const{element:r,fieldMessage:o="",errorStyles:i={},requiredMessage:n="Campo requerido",invalidMessage:s="Campo no válido",events:a}=t;"on"in r&&(r.on(e.EventName.CHANGE,(e=>{Je({eventName:"onChange",data:e,events:a}),We({element:r,errorStyles:i,color:"transparent"})})),r.on(e.EventName.BLUR,(e=>{if(Je({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?n:""!=o?`El campo ${o} no es válido`:s;r.setError(t)}We({element:r,errorStyles:i})})),r.on(e.EventName.FOCUS,(e=>{Je({eventName:"onFocus",data:e,events:a}),We({element:r,errorStyles:i,color:"transparent"}),r.resetError()})))}function We(e){const{element:t,errorStyles:r={},color:o=""}=e;Object.keys(r).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base&&Object.assign({},r.base)),""!=o&&{color:o})})})}const Je=e=>{const{eventName:t,data:r,events:o}=e;if(o&&t in o){const e=o[t];"function"==typeof e&&e({elementType:H(r,"elementType",""),isEmpty:H(r,"isEmpty",!1),isFocused:H(r,"isFocused",!1),isValid:H(r,"isValid",!1),value:H(r,"value","")})}};function Ge(e){return t(this,void 0,void 0,(function*(){const{element:t,containerId:r,retries:o=2,delay:i=30}=e;for(let e=0;e<=o;e++){if(document.querySelector(r))return void t.mount(r);e<o&&(yield new Promise((e=>setTimeout(e,i))))}console.warn(`[mountCardFields] Container ${r} was not found after ${o+1} attempts`)}))}const Ze=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"}),et={[Ze.SORIANA]:{label:"Soriana",iconPath:"/payment_methods/soriana.png"},[Ze.OXXO]:{label:"Oxxo",iconPath:"/payment_methods/oxxo.png"},[Ze.CODI]:{label:"CoDi",iconPath:"/payment_methods/codi.png"},[Ze.MERCADOPAGO]:{label:"Mercado Pago",iconPath:"/payment_methods/mercadopago.png"},[Ze.OXXOPAY]:{label:"Oxxo Pay",iconPath:"/payment_methods/oxxopay.png"},[Ze.SPEI]:{label:"SPEI",iconPath:"/payment_methods/spei.png"},[Ze.PAYPAL]:{label:"Paypal",iconPath:"/payment_methods/paypal.png"},[Ze.COMERCIALMEXICANA]:{label:"Comercial Mexicana",iconPath:"/payment_methods/comercial_exicana.png"},[Ze.BANCOMER]:{label:"Bancomer",iconPath:"/payment_methods/bancomer.png"},[Ze.WALMART]:{label:"Walmart",iconPath:"/payment_methods/walmart.png"},[Ze.BODEGA]:{label:"Bodega Aurrera",iconPath:"/payment_methods/bodega_aurrera.png"},[Ze.SAMSCLUB]:{label:"Sam´s Club",iconPath:"/payment_methods/sams_club.png"},[Ze.SUPERAMA]:{label:"Superama",iconPath:"/payment_methods/superama.png"},[Ze.CALIMAX]:{label:"Calimax",iconPath:"/payment_methods/calimax.png"},[Ze.EXTRA]:{label:"Tiendas Extra",iconPath:"/payment_methods/tiendas_extra.png"},[Ze.CIRCULOK]:{label:"Círculo K",iconPath:"/payment_methods/circulo_k.png"},[Ze.SEVEN11]:{label:"7 Eleven",iconPath:"/payment_methods/7_eleven.png"},[Ze.TELECOMM]:{label:"Telecomm",iconPath:"/payment_methods/telecomm.png"},[Ze.BANORTE]:{label:"Banorte",iconPath:"/payment_methods/banorte.png"},[Ze.BENAVIDES]:{label:"Farmacias Benavides",iconPath:"/payment_methods/farmacias_benavides.png"},[Ze.DELAHORRO]:{label:"Farmacias del Ahorro",iconPath:"/payment_methods/farmacias_ahorro.png"},[Ze.ELASTURIANO]:{label:"El Asturiano",iconPath:"/payment_methods/asturiano.png"},[Ze.WALDOS]:{label:"Waldos",iconPath:"/payment_methods/waldos.png"},[Ze.ALSUPER]:{label:"Alsuper",iconPath:"/payment_methods/al_super.png"},[Ze.KIOSKO]:{label:"Kiosko",iconPath:"/payment_methods/kiosko.png"},[Ze.STAMARIA]:{label:"Farmacias Santa María",iconPath:"/payment_methods/farmacias_santa_maria.png"},[Ze.LAMASBARATA]:{label:"Farmacias la más barata",iconPath:"/payment_methods/farmacias_barata.png"},[Ze.FARMROMA]:{label:"Farmacias Roma",iconPath:"/payment_methods/farmacias_roma.png"},[Ze.FARMUNION]:{label:"Pago en Farmacias Unión",iconPath:"/payment_methods/farmacias_union.png"},[Ze.FARMATODO]:{label:"Pago en Farmacias Farmatodo",iconPath:"/payment_methods/farmacias_farmatodo.png\t"},[Ze.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",iconPath:"/payment_methods/farmacias_san_francisco.png"},[Ze.FARM911]:{label:"Farmacias 911",iconPath:"/payment_methods/store.png"},[Ze.FARMECONOMICAS]:{label:"Farmacias Economicas",iconPath:"/payment_methods/store.png"},[Ze.FARMMEDICITY]:{label:"Farmacias Medicity",iconPath:"/payment_methods/store.png"},[Ze.RIANXEIRA]:{label:"Rianxeira",iconPath:"/payment_methods/store.png"},[Ze.WESTERNUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[Ze.ZONAPAGO]:{label:"Zona Pago",iconPath:"/payment_methods/store.png"},[Ze.CAJALOSANDES]:{label:"Caja Los Andes",iconPath:"/payment_methods/store.png"},[Ze.CAJAPAITA]:{label:"Caja Paita",iconPath:"/payment_methods/store.png"},[Ze.CAJASANTA]:{label:"Caja Santa",iconPath:"/payment_methods/store.png"},[Ze.CAJASULLANA]:{label:"Caja Sullana",iconPath:"/payment_methods/store.png"},[Ze.CAJATRUJILLO]:{label:"Caja Trujillo",iconPath:"/payment_methods/store.png"},[Ze.EDPYME]:{label:"Edpyme",iconPath:"/payment_methods/store.png"},[Ze.KASNET]:{label:"KasNet",iconPath:"/payment_methods/store.png"},[Ze.NORANDINO]:{label:"Norandino",iconPath:"/payment_methods/store.png"},[Ze.QAPAQ]:{label:"Qapaq",iconPath:"/payment_methods/store.png"},[Ze.RAIZ]:{label:"Raiz",iconPath:"/payment_methods/store.png"},[Ze.PAYSER]:{label:"Paysera",iconPath:"/payment_methods/store.png"},[Ze.WUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[Ze.BANCOCONTINENTAL]:{label:"Banco Continental",iconPath:"/payment_methods/store.png"},[Ze.GMONEY]:{label:"Go money",iconPath:"/payment_methods/store.png"},[Ze.GOPAY]:{label:"Go pay",iconPath:"/payment_methods/store.png"},[Ze.WU]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[Ze.PUNTOSHEY]:{label:"Puntoshey",iconPath:"/payment_methods/store.png"},[Ze.AMPM]:{label:"Ampm",iconPath:"/payment_methods/store.png"},[Ze.JUMBOMARKET]:{label:"Jumbomarket",iconPath:"/payment_methods/store.png"},[Ze.SMELPUEBLO]:{label:"Smelpueblo",iconPath:"/payment_methods/store.png"},[Ze.BAM]:{label:"Bam",iconPath:"/payment_methods/store.png"},[Ze.REFACIL]:{label:"Refacil",iconPath:"/payment_methods/store.png"},[Ze.ACYVALORES]:{label:"Acyvalores",iconPath:"/payment_methods/store.png"}},tt=(e,t="stage")=>{const r=e.toUpperCase().trim().replace(/\s+/g,"");const o=et[r]||{iconPath:"/payment_methods/store.png",label:""};return{label:o.label,icon:`${A(t)}${o.iconPath}`}};class rt extends be{constructor({apiKey:e,mode:t,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe",sdkInfo:G}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.lastCollectedTokens=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return t(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return t(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=>Object.assign(Object.assign({},e),{fields:Object.assign(Object.assign({},e.fields),{subscription_id:this._hasCardOnFileKeys()?e.fields.subscription_id:void 0}),icon:g(e.fields.card_scheme,this.mode)})))})}catch(e){throw this.reportSdkError(e,{feature:"get-cards",process_id:this.getCustomerId(),metadata:{step:"getCustomerCards"}}),y({errorCode:d.FETCH_CARDS_ERROR},e)}}))}saveCustomerCard(){return t(this,void 0,void 0,(function*(){let e=null;try{yield this._fetchMerchantData();const t=yield this._getCustomer(),{auth_token:r,first_name:o="",last_name:i="",email:n=""}=t,{business:s}=this.merchantData,a=this._hasCardOnFileKeys(),l=yield this.collectCreateCardTokens(),c=yield this._saveCustomerCard(r,null==s?void 0:s.pk,l,a);if(e=c.skyflow_id,a){const e=c.card_bin;if(!e)throw new Error("Card BIN not returned from save card");const t=yield this._initializeCardOnFile();let a;try{a=yield t.process({cardTokens:{name:l.cardholder_name,number:l.card_number,expiryMonth:l.expiration_month,expiryYear:l.expiration_year,cvv:l.cvv},cardBin:e,contactDetails:{firstName:o||"",lastName:i||"",email:n||""},customerId:r,currency:this.currency||"MXN"})}catch(e){throw y({errorCode:d.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}const u={skyflow_id:l.skyflow_id,subscription_id:a.subscriptionId};yield this._saveCustomerCard(r,null==s?void 0:s.pk,u)}return c}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"save-card",process_id:e||this.getCustomerId(),metadata:{step:"saveCustomerCard"}}),y({errorCode:d.SAVE_CARD_ERROR},t)}}))}removeCustomerCard(e){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:r}=this.merchantData;return yield this._removeCustomerCard(t,null==r?void 0:r.pk,e)}catch(t){throw this.reportSdkError(t,{feature:"remove-card",process_id:e,metadata:{step:"removeCustomerCard"}}),y({errorCode:d.REMOVE_CARD_ERROR},t)}}))}getCustomerPaymentMethods(){return t(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},tt(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw this.reportSdkError(e,{feature:"get-payment-methods",metadata:{step:"getCustomerPaymentMethods"}}),y({errorCode:d.FETCH_PAYMENT_METHODS_ERROR},e)}}))}mountCardFields(r){var o;return t(this,void 0,void 0,(function*(){const i=r.card_id?`update:${r.card_id}`:"create",n=null!==(o=r.unmount_context)&&void 0!==o?o:"all";"none"!==n&&("current"===n?this.unmountCardFields(i):this.unmountCardFields(n)),yield this.createSkyflowInstance();const s=yield function(r){var o,i,n,s,a,d,l,c,u,h,_,E,m;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,data:p,customization:R,events:y}=r,v=t.container(e.ContainerType.COLLECT),f=[],C={[Ne.CVV]:e.ElementType.CVV,[Ne.CARD_NUMBER]:e.ElementType.CARD_NUMBER,[Ne.EXPIRATION_MONTH]:e.ElementType.EXPIRATION_MONTH,[Ne.EXPIRATION_YEAR]:e.ElementType.EXPIRATION_YEAR,[Ne.CARDHOLDER_NAME]:e.ElementType.CARDHOLDER_NAME},A={[Ne.CVV]:[Pe],[Ne.CARD_NUMBER]:[Pe],[Ne.EXPIRATION_MONTH]:[Pe],[Ne.EXPIRATION_YEAR]:[Pe],[Ne.CARDHOLDER_NAME]:[ke,Pe]},O={[Ne.CARDHOLDER_NAME]:"cardholderName",[Ne.CARD_NUMBER]:"cardNumber",[Ne.CVV]:"cvv",[Ne.EXPIRATION_MONTH]:"expirationMonth",[Ne.EXPIRATION_YEAR]:"expirationYear"},T=e=>{var t,r,o,i,n,s,a,d,l;const c=null===(t=null==R?void 0:R.styles)||void 0===t?void 0:t[O[e]],u=null===(r=null==R?void 0:R.styles)||void 0===r?void 0:r.cardForm,h=null!==(i=null!==(o=null==c?void 0:c.inputStyles)&&void 0!==o?o:null==u?void 0:u.inputStyles)&&void 0!==i?i:He;return{inputStyles:e===Ne.CARD_NUMBER&&!1!==(null===(n=null==R?void 0:R.styles)||void 0===n?void 0:n.enableCardIcon)?Object.assign(Object.assign({},h),{base:Object.assign({paddingLeft:"15px"},null==h?void 0:h.base)}):h,labelStyles:null!==(a=null!==(s=null==c?void 0:c.labelStyles)&&void 0!==s?s:null==u?void 0:u.labelStyles)&&void 0!==a?a:qe,errorStyles:null!==(l=null!==(d=null==c?void 0:c.errorStyles)&&void 0!==d?d:null==u?void 0:u.errorStyles)&&void 0!==l?l:ze}},S={cardholder_name:(null===(o=null==R?void 0:R.labels)||void 0===o?void 0:o.name)||Ue,card_number:(null===(i=null==R?void 0:R.labels)||void 0===i?void 0:i.card_number)||Le,cvv:(null===(n=null==R?void 0:R.labels)||void 0===n?void 0:n.cvv)||we,expiration_date:(null===(s=null==R?void 0:R.labels)||void 0===s?void 0:s.expiry_date)||je,expiration_month:(null===(a=null==R?void 0:R.labels)||void 0===a?void 0:a.expiration_month)||Ve,expiration_year:(null===(d=null==R?void 0:R.labels)||void 0===d?void 0:d.expiration_year)||Fe},g={cardholder_name:(null===(l=null==R?void 0:R.placeholders)||void 0===l?void 0:l.name)||Ke,card_number:(null===(c=null==R?void 0:R.placeholders)||void 0===c?void 0:c.card_number)||xe,cvv:(null===(u=null==R?void 0:R.placeholders)||void 0===u?void 0:u.cvv)||Be,expiration_month:(null===(h=null==R?void 0:R.placeholders)||void 0===h?void 0:h.expiration_month)||Ye,expiration_year:(null===(_=null==R?void 0:R.placeholders)||void 0===_?void 0:_.expiration_year)||$e},I={[Ne.CVV]:null==y?void 0:y.cvvEvents,[Ne.CARD_NUMBER]:null==y?void 0:y.cardNumberEvents,[Ne.EXPIRATION_MONTH]:null==y?void 0:y.monthEvents,[Ne.EXPIRATION_YEAR]:null==y?void 0:y.yearEvents,[Ne.CARDHOLDER_NAME]:null==y?void 0:y.cardHolderEvents};if("fields"in p&&Array.isArray(p.fields)){const e={enableCardIcon:null===(m=null===(E=null==R?void 0:R.styles)||void 0===E?void 0:E.enableCardIcon)||void 0===m||m};if(p.fields.length>0&&"string"==typeof p.fields[0])for(const t of p.fields){const r=v.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:C[t],validations:A[t]},T(t)),{label:S[t],placeholder:g[t]}),p.card_id?{skyflowID:p.card_id}:{}),t===Ne.CARD_NUMBER?e:void 0);Qe({element:r,errorStyles:T(t).errorStyles,fieldMessage:[Ne.CVV,Ne.EXPIRATION_MONTH,Ne.EXPIRATION_YEAR].includes(t)?"":S[t],events:I[t]});const o=`#collect_${String(t)}`+(p.card_id?`_${p.card_id}`:"");yield Ge({element:r,containerId:o}),f.push({element:r,containerId:o})}else for(const t of p.fields){const r=t.field,o=v.create(Object.assign(Object.assign(Object.assign({table:"cards",column:r,type:C[r],validations:A[r]},T(r)),{label:S[r],placeholder:g[r]}),p.card_id?{skyflowID:p.card_id}:{}),r===Ne.CARD_NUMBER?e:void 0);Qe({element:o,errorStyles:T(r).errorStyles,fieldMessage:[Ne.CVV,Ne.EXPIRATION_MONTH,Ne.EXPIRATION_YEAR].includes(r)?"":S[r],events:I[r]});const i=t.container_id||`#collect_${String(r)}`+(p.card_id?`_${p.card_id}`:"");yield Ge({element:o,containerId:i}),f.push({element:o,containerId:i})}}return{elements:f.map((e=>e.element)),container:v}}))}({skyflowInstance:this.skyflowInstance,data:r,customization:this.customization,events:this.events});this.mountedElementsByContext.set(i,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const r=`update:${e}`,o=this.mountedElementsByContext.get(r);return(null===(t=null==o?void 0:o.container)||void 0===t?void 0:t.container)||null}collectCardTokens(e){var r,o,i;return t(this,void 0,void 0,(function*(){const t=this.getContainerByCardId(e);if(!t)return null;try{const e=yield t.collect();return(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.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 f({code:d.MOUNT_COLLECT_ERROR,details:{message:r}})}}))}collectCreateCardTokens(){var e,r,o,i;return t(this,void 0,void 0,(function*(){const t=this.mountedElementsByContext.get("create"),n=null===(e=null==t?void 0:t.container)||void 0===e?void 0:e.container;if(!n)throw new f({code:d.MOUNT_COLLECT_ERROR,details:{message:"No card fields are mounted. Call mountCardFields() with the required fields before proceeding."}});try{const e=yield n.collect(),t=(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.fields)||{};return this.lastCollectedTokens=t,t}catch(e){const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.description;throw this.reportSdkError(e,{feature:"collect-create-card-tokens",metadata:{step:"collectCreateCardTokens"}}),new f({code:d.MOUNT_COLLECT_ERROR,details:{message:t}})}}))}revealCardFields(r){return t(this,void 0,void 0,(function*(){if(!this.lastCollectedTokens)throw y({errorCode:d.MOUNT_COLLECT_ERROR,details:{message:"No card tokens available. Call saveCustomerCard() or payment() with a new card before calling revealCardFields()."}});if(!this.skyflowInstance)throw y({errorCode:d.MOUNT_COLLECT_ERROR,details:{message:"Skyflow instance not initialized. Ensure mountCardFields() was called before saveCustomerCard() or payment()."}});yield function(r){var o,i,n,s,a,d;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,tokens:l,request:c}=r,u=t.container(e.ContainerType.REVEAL),h={[Ne.CARD_NUMBER]:"MASKED",[Ne.CARDHOLDER_NAME]:"PLAIN_TEXT",[Ne.EXPIRATION_MONTH]:"PLAIN_TEXT",[Ne.EXPIRATION_YEAR]:"PLAIN_TEXT"};for(const t of c.fields){const r="string"==typeof t,_=r?t:t.field;if(_===Ne.CVV){console.warn("[revealCardFields] CVV cannot be revealed (PCI DSS req. 3.2.1). Skipping.");continue}const E=l[_];if(!E){console.warn(`[revealCardFields] No token found for field "${_}", skipping.`);continue}const m=r?{}:t,p=null!==(o=m.container_id)&&void 0!==o?o:`#reveal_${_}`,R=h[_],y=null!==(i=m.styles)&&void 0!==i?i:{},v=null!==(n=c.styles)&&void 0!==n?n:{},f=u.create(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({token:E,redaction:e.RedactionType[R]},void 0!==m.altText&&{altText:m.altText}),void 0!==m.label&&{label:m.label}),y.inputStyles||v.inputStyles?{inputStyles:null!==(s=y.inputStyles)&&void 0!==s?s:v.inputStyles}:{}),y.labelStyles||v.labelStyles?{labelStyles:null!==(a=y.labelStyles)&&void 0!==a?a:v.labelStyles}:{}),y.errorTextStyles||v.errorTextStyles?{errorTextStyles:null!==(d=y.errorTextStyles)&&void 0!==d?d:v.errorTextStyles}:{}));yield Ge({element:f,containerId:p})}try{yield u.reveal()}catch(e){console.warn("[revealCardFields] reveal completed with errors:",e)}}))}({skyflowInstance:this.skyflowInstance,tokens:this.lastCollectedTokens,request: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 t(this,void 0,void 0,(function*(){try{return yield v(this.coreBaseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw this.reportSdkError(e,{feature:"get-business",metadata:{step:"getBusiness"}}),y({errorCode:d.FETCH_BUSINESS_ERROR},e)}}))}createSkyflowInstance(){return t(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:r,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:r,apiKey:o,vault_id:i,vault_url:n,mode:s}){return t(this,void 0,void 0,(function*(){const a="production"===s?e.Env.PROD:e.Env.DEV;return e.init({vaultID:i,vaultURL:n,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield De(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:a}})}))}({vault_id:r,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder,mode:this.mode})}))}getOpenpayDeviceSessionID(e,r,o){return t(this,void 0,void 0,(function*(){try{return yield F(e,r,o)}catch(e){throw this.reportSdkError(e,{feature:"get-openpay-device-session",metadata:{step:"getOpenpayDeviceSessionID"}}),y({errorCode:d.START_CHECKOUT_ERROR},e)}}))}getSkyflowTokens({vault_id:e,vault_url:r,data:o}){return t(this,void 0,void 0,(function*(){return yield Xe({vault_id:e,vault_url:r,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:r,isSandbox:o,returnUrl:i}){var n,s,a;return t(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const l=!0===(null===(n=this.merchantData)||void 0===n?void 0:n.core_payments_enabled)&&S(r)?void 0:r,c=yield this._getCustomer(this.abortController.signal),{business:u}=this.merchantData,{auth_token:h,first_name:_="",last_name:E="",email:m=""}=c,p=this._hasCardOnFileKeys();let R,v=null,f=null,C=null,A=!1;const O=()=>t(this,void 0,void 0,(function*(){var e,t;(null===(t=null===(e=this.customerCardsCache)||void 0===e?void 0:e.cards)||void 0===t?void 0:t.length)||(this.customerCardsCache=yield this._getCustomerCards(h,this.merchantData.business.pk))}));if(!l){if("string"==typeof e)if(f=e,R={skyflow_id:e},p){yield O();const t=null===(a=null===(s=this.customerCardsCache)||void 0===s?void 0:s.cards)||void 0===a?void 0:a.find((t=>t.fields.skyflow_id===e));if(!t)throw new Error("Card not found for card-on-file processing");const r=!!t.fields.subscription_id;r||(yield this.collectCardTokens(e)),r&&(v={subscriptionId:t.fields.subscription_id})}else yield this.collectCardTokens(e);else R=yield this.collectCreateCardTokens(),f=R.skyflow_id,p&&(C={name:R.cardholder_name,number:R.card_number,expiryMonth:R.expiration_month,expiryYear:R.expiration_year,cvv:R.cvv},A=!0);if(A){if(!f||!C)throw new Error("Missing card data for card-on-file processing");let e=null;try{const t=yield this._saveCustomerCard(h,null==u?void 0:u.pk,{skyflow_id:f},!0);e=t.skyflow_id;const r=t.card_bin;if(!r)throw new Error("Card BIN not returned from save card");const o=yield this._initializeCardOnFile();let i;try{i=yield o.process({cardTokens:C,cardBin:r,contactDetails:{firstName:_||"",lastName:E||"",email:m||""},customerId:h,currency:this.currency||"MXN"})}catch(e){throw y({errorCode:d.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}v={subscriptionId:i.subscriptionId},yield this._saveCustomerCard(h,null==u?void 0:u.pk,{skyflow_id:f,subscription_id:v.subscriptionId})}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"payment",process_id:e||this.getCustomerId(),metadata:{step:"card_on_file"}}),t}}}return yield this._handleCheckout({card:R,payment_method:l,customer:c,isSandbox:o,returnUrl:i,enable_card_on_file:!!(null==v?void 0:v.subscriptionId)&&p})}))}customerRegister(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,r={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:d.CUSTOMER_OPERATION_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"customer-register",metadata:{step:"customerRegister"}}),y({errorCode:d.CUSTOMER_OPERATION_ERROR},e)}}))}createOrder(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:d.CREATE_ORDER_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-order",metadata:{step:"createOrder"}}),y({errorCode:d.CREATE_ORDER_ERROR},e)}}))}createPayment(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:d.CREATE_PAYMENT_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-payment",metadata:{step:"createPayment"}}),y({errorCode:d.CREATE_PAYMENT_ERROR},e)}}))}startCheckoutRouter(e){return t(this,void 0,void 0,(function*(){const t=yield V(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return t(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return t(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:i,return_url:n,isSandbox:s,metadata:a,currency:l,payment_method:c}=e,u=yield this._fetchMerchantData(),h=yield this.customerRegister(o.email);if(!(h&&"auth_token"in h&&u&&"reference"in u))throw y({errorCode:d.START_CHECKOUT_ERROR,details:{message:"Merchant or customer reposne errors",merchantResult:u,customerResult:h}});{const e={business:this.apiKeyTonder,client:h.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:u.reference,is_oneclick:!0,items:t.items},_=yield this.createOrder(e),E=(new Date).toISOString();if(!("id"in _&&"id"in h&&"business"in u))throw y({errorCode:d.START_CHECKOUT_ERROR,details:{message:"Order response errors",orderResult:_}});{const e={business_pk:u.business.pk,amount:r,date:E,order_id:_.id,client_id:h.id},t=yield this.createPayment(e);let d;const{openpay_keys:m,business:p}=u;m.merchant_id&&m.public_key&&(d=yield F(m.merchant_id,m.public_key,s));const R=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:n,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:d||null,token_id:"",order_id:"id"in _&&_.id,business_id:p.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:a,browser_info:O(),currency:l},c?{payment_method:c}:{card:i}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),y=yield V(this.baseUrl,this.apiKeyTonder,R);if(yield this.init3DSRedirect(y))return y}}}catch(e){throw this.reportSdkError(e,{feature:"start-checkout-router-full",metadata:{step:"startCheckoutRouterFull"}}),y({errorCode:d.START_CHECKOUT_ERROR},e)}}))}registerCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const t=yield fetch(`${this.baseUrl}/api/v1/business/${T(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":r,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(t.ok)return yield t.json();throw yield y({response:t,errorCode:d.SAVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"register-customer-card",metadata:{step:"registerCustomerCard"}}),y({errorCode:d.SAVE_CARD_ERROR},e)}}))}deleteCustomerCard(e,r=""){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const t=yield fetch(`${this.baseUrl}/api/v1/business/${T(this.merchantData)}/cards/${r}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(t.ok)return!0;throw yield y({response:t,errorCode:d.REMOVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"delete-customer-card",process_id:r,metadata:{step:"deleteCustomerCard"}}),y({errorCode:d.REMOVE_CARD_ERROR},e)}}))}getActiveAPMs(){return t(this,void 0,void 0,(function*(){try{const e=yield function(e,r,o="?status=active&page_size=10000&country=México",i=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(t.ok)return yield t.json();throw yield y({response:t,errorCode:d.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder),r=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=r.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},tt(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}export{h as AppError,be as BaseInlineCheckout,rt as LiteCheckout,J as SdkTelemetryClient,x as validateCVV,j as validateCardNumber,K as validateCardholderName,B as validateExpirationMonth,Y as validateExpirationYear};
|
|
1
|
+
import e from"skyflow-js";function t(e,t,r,o){return new(r||(r=Promise))((function(i,n){function s(e){try{d(o.next(e))}catch(e){n(e)}}function a(e){try{d(o.throw(e))}catch(e){n(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((o=o.apply(e,t||[])).next())}))}function r(e,t,r,o){if("a"===r&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?o:"a"===r?o.call(e):o?o.value:t.get(e)}function o(e,t,r,o,i){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!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"===o?i.call(e,r):i?i.value=r:t.set(e,r),r}"function"==typeof SuppressedError&&SuppressedError;const i=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"}),n=Object.freeze({TELEMETRY:"/telemetry/v1/events",ACQ_SUBSCRIPTION_TOKEN:"/acq-kushki/subscription/token",ACQ_SUBSCRIPTION_CREATE:"/acq-kushki/subscription/create",CORE_BUSINESS_CONFIG:"/transactions/v1/business/config",CORE_PROCESS:"/transactions/v1/process",CORE_CUSTOMER:"/transactions/v1/customer",CORE_CARDS:"/transactions/v1/cards",CORE_PAYMENT_METHODS:"/transactions/v1/payment_methods",CORE_VAULT_TOKEN:"/transactions/v1/vault-token"});function s(e="stage"){return`${i[e]}${n.TELEMETRY}`}function a(e="stage"){return i[e]}var d;!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"}(d||(d={}));const l={[d.INIT_ERROR]:"Error initializing the SDK.",[d.INVALID_TYPE]:"SDK Type invalid.",[d.STATE_ERROR]:"Error updating SDK state.",[d.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[d.INVALID_CONFIG]:"Required configuration options.",[d.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[d.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[d.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[d.TYPE_SDK_REQUIRED]:"SDK type required.",[d.ENVIRONMENT_REQUIRED]:"Environment required.",[d.FETCH_CARDS_ERROR]:"Error retrieving cards.",[d.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.",[d.SAVE_CARD_ERROR]:"Error saving the card.",[d.REMOVE_CARD_ERROR]:"Error deleting the card.",[d.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[d.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[d.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[d.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[d.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[d.START_CHECKOUT_ERROR]:"Error processing the payment.",[d.CREATE_ORDER_ERROR]:"Error creating the order.",[d.BUSINESS_ID_REQUIRED]:"Business ID is required.",[d.CLIENT_ID_REQUIRED]:"Client ID is required.",[d.INVALID_AMOUNT]:"Invalid amount.",[d.INVALID_ITEMS]:"Invalid items.",[d.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[d.INVALID_EMAIL]:"Invalid email.",[d.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[d.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[d.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[d.SECURE_TOKEN_ERROR]:"Error getting secure token.",[d.SECURE_TOKEN_INVALID]:"Invalid secure token.",[d.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[d.REMOVE_CARD]:"Card deleted successfully",[d.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[d.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[d.INVALID_CARD_DATA]:"Invalid card data.",[d.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[d.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[d.CARD_ON_FILE_DECLINED]:"Transaction declined. Please verify your card details.",[d.REQUEST_ABORTED]:"Requests canceled.",[d.REQUEST_FAILED]:"Request failed.",[d.UNKNOWN_ERROR]:"An unexpected error occurred.",[d.CREATE_ERROR]:"Error creating the SDK.",[d.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[d.THREEDS_REDIRECTION_ERROR]:"An error occurred during the 3DS redirection.",[d.REMOVE_SDK_ERROR]:"An error occurred while removing the SDK instance."};d.INIT_ERROR,d.STATE_ERROR,d.FETCH_BUSINESS_ERROR,d.INVALID_CONFIG,d.TYPE_SDK_REQUIRED,d.ENVIRONMENT_REQUIRED,d.FETCH_CARDS_ERROR,d.SAVE_CARD_ERROR,d.REMOVE_CARD_ERROR,d.CREATE_PAYMENT_ERROR,d.START_CHECKOUT_ERROR,d.CREATE_ORDER_ERROR,d.BUSINESS_ID_REQUIRED,d.CLIENT_ID_REQUIRED,d.INVALID_AMOUNT,d.INVALID_ITEMS,d.CUSTOMER_OPERATION_ERROR,d.INVALID_EMAIL,d.FETCH_PAYMENT_METHODS_ERROR,d.INVALID_VAULT_TOKEN,d.VAULT_TOKEN_ERROR,d.SECURE_TOKEN_ERROR,d.INVALID_SECRET_API_KEY,d.CUSTOMER_AUTH_TOKEN_NOT_VALID,d.SECURE_TOKEN_INVALID,d.REMOVE_CARD,d.SKYFLOW_NOT_INITIALIZED,d.INVALID_TYPE,d.PAYMENT_PROCESS_ERROR,d.INVALID_PAYMENT_REQUEST,d.INVALID_PAYMENT_REQUEST_CARD_PM,d.SAVE_CARD_PROCESS_ERROR,d.ERROR_LOAD_PAYMENT_FORM,d.INVALID_CARD_DATA,d.ERROR_LOAD_ENROLLMENT_FORM,d.MOUNT_COLLECT_ERROR,d.CARD_ON_FILE_DECLINED,d.CARD_SAVED_SUCCESSFULLY,d.CARD_REMOVED_SUCCESSFULLY,d.REQUEST_ABORTED,d.REQUEST_FAILED,d.UNKNOWN_ERROR,d.CREATE_ERROR,d.FETCH_TRANSACTION_ERROR,d.THREEDS_REDIRECTION_ERROR,d.REMOVE_SDK_ERROR;const c="__tonderLockErrorCode__";function u(e){return"object"==typeof e&&null!==e}class h extends Error{constructor(e){var t,r;const o=h.resolveStatusCode(e.statusCode,e.originalError),i=h.resolveMessage(e.errorCode,e.message),n=h.resolveSystemError(null===(t=e.details)||void 0===t?void 0:t.systemError,e.originalError);super(i),this.status="error",Object.setPrototypeOf(this,new.target.prototype),this.name="TonderError",this.code=e.errorCode,this.statusCode=o,this.originalError=e.originalError,this.details={code:e.errorCode,statusCode:o,systemError:n},e.lockErrorCode&&Object.defineProperty(this,c,{value:!0,enumerable:!1,configurable:!0}),null===(r=Error.captureStackTrace)||void 0===r||r.call(Error,this,h)}static isRecord(e){return"object"==typeof e&&null!==e}static parseStatusCode(e){const t=Number(e);return Number.isFinite(t)?t<100||t>599?500:Math.trunc(t):500}static resolveStatusCode(e,t){const r=[e];if(h.isRecord(t)){r.push(t.statusCode,t.status);const e=h.isRecord(t.body)?t.body:null;e&&r.push(e.statusCode,e.status)}for(const e of r)if(h.isHttpStatusCode(e))return Math.trunc(Number(e));return 500}static resolveMessage(e,t){return t||(l[e]||l[d.UNKNOWN_ERROR]||"An unexpected error occurred.")}static isHttpStatusCode(e){const t=Number(e);return Number.isFinite(t)&&t>=100&&t<=599}static normalizeSystemError(e){if("string"!=typeof e)return null;return e.trim()||null}static resolveSystemError(e,t){const r=[e];if(h.isRecord(t)){const e=h.isRecord(t.details)?t.details:null,o=h.isRecord(t.body)?t.body:null,i=o&&h.isRecord(o.details)?o.details:null;r.push(t.systemError,t.code,null==e?void 0:e.systemError,null==e?void 0:e.code,null==o?void 0:o.systemError,null==o?void 0:o.code,null==i?void 0:i.systemError,null==i?void 0:i.code)}for(const e of r){const t=h.normalizeSystemError(e);if(t)return t}return"APP_INTERNAL_001"}}function _(e){return u(e)&&!0===e[c]}function E(e){return e instanceof h&&void 0!==e.originalError?e.originalError:e}function m(e){return t(this,void 0,void 0,(function*(){try{return yield e.clone().json()}catch(e){}try{return(yield e.text())||void 0}catch(e){return}}))}function p(e,t){var r;if(!(null==e?void 0:e.errorCode))throw new Error("buildPublicAppError requires errorCode");const o=null===(r=e.details)||void 0===r?void 0:r.systemError,i=!!e.message||void 0!==e.statusCode||void 0!==o;return!function(e){return u(e)&&"TonderError"===e.name&&"string"==typeof e.code}(t)||(e.lockErrorCode&&function(e){Object.defineProperty(e,c,{value:!0,enumerable:!1,configurable:!0})}(t),i||e.errorCode!==t.code&&!_(t))?new h({errorCode:e.errorCode,message:e.message,statusCode:e.statusCode,details:void 0!==o?{systemError:o}:void 0,originalError:E(t),lockErrorCode:e.lockErrorCode||_(t)}):t}function R(e){var t,r;const o={status:e.status};return e.statusText&&(o.statusText=e.statusText),void 0!==e.body&&(o.body=e.body),new h({errorCode:e.errorCode,message:e.message,statusCode:null!==(t=e.statusCode)&&void 0!==t?t:e.status,details:void 0!==(null===(r=e.details)||void 0===r?void 0:r.systemError)?{systemError:e.details.systemError}:void 0,originalError:o,lockErrorCode:e.lockErrorCode})}function v(e,r){return(null==e?void 0:e.response)?function(e){return t(this,void 0,void 0,(function*(){return R(Object.assign(Object.assign({},e),{status:e.response.status,statusText:e.response.statusText,body:yield m(e.response)}))}))}(e):p(e,r)}function y(e,r,o){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}${n.CORE_BUSINESS_CONFIG}`,{headers:{Authorization:`Token ${r}`},signal:o});if(t.ok)return yield t.json();throw yield v({response:t,errorCode:d.FETCH_BUSINESS_ERROR})}))}class f extends Error{constructor(e){var t,r;const o=e.message||l[e.code]||"Unknown error";super(o),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(r=e.details)||void 0===r?void 0:r.message)||o}}}const C=Object.freeze({production:"https://d35a75syrgujp0.cloudfront.net",sandbox:"https://static.staging.tonder.io",stage:"https://static.staging.tonder.io",development:"https://static.staging.tonder.io"});function O(e="stage"){return C[e]||C.stage}const T=()=>({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}),A=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},g=e=>!e||"card"===e.toLowerCase(),S=(e,t="stage")=>{const r=O(t);return"Visa"===e?`${r}/cards/visa.png`:"Mastercard"===e?`${r}/cards/mastercard.png`:"American Express"===e?`${r}/cards/american_express.png`:`${r}/cards/default_card.png`};function I(e){var t;const r=(null!==(t=e.data)&&void 0!==t?t:[]).map((e=>Object.assign(Object.assign({},e),{pk:e.id})));return{count:r.length,next:null,previous:null,results:r}}function N(e){var t;return(null===(t=null==e?void 0:e.error)||void 0===t?void 0:t.code)?{code:e.error.code,message:e.error.message,details:e.error.details,request_id:e.request_id}:e}function b(e,r,o){return t(this,void 0,void 0,(function*(){if("core"!==o)return v({response:e,errorCode:r});const t=yield e.clone().json().catch((()=>{}));return R({errorCode:r,status:e.status,statusText:e.statusText,body:N(t)})}))}const D=new Set(["https:"]);function k(e){if("string"!=typeof e)return!1;try{return D.has(new URL(e,document.baseURI).protocol)}catch(e){return!1}}const M=new Set(["script","object","embed","applet","link","meta","base","style","template"]),U=new Set(["srcdoc","style","ping","srcset"]),P=new Set(["src","href","action","formaction","data","poster","background"]);function L(e){const t=e.trim();return""===t||("about:blank"===t.toLowerCase()||k(t))}function w(e){for(const t of Array.from(e.attributes)){const r=t.localName.toLowerCase();r.startsWith("on")||U.has(r)?e.removeAttributeNode(t):P.has(r)&&!L(t.value)&&e.removeAttributeNode(t)}}const V=["Pending","Processing"];class F{constructor({payload:e=null,apiKey:t,baseUrl:r,coreBaseUrl:o,buildCoreResult:i=(e=>e),redirectOnComplete:n,tdsIframeId:s,tonderPayButtonId:a,callBack:d}){this.engine="legacy",this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.buildCoreResult=i,this.baseUrl=r,this.coreBaseUrl=o,this.apiKey=t,this.payload=e,this.tdsIframeId=s,this.tonderPayButtonId=a,this.redirectOnComplete=n,this.callBack=d}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,r,o,i,n;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===(n=null===(i=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===i?void 0:i.iframe_resources)||void 0===n?void 0:n.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}setEngine(e){this.engine=e}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5,engine:this.engine};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getStoredVerification(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t}return null}getUrlWithExpiration(){var e;const t=this.getStoredVerification();return void 0===t?void 0:null!==(e=null==t?void 0:t.url)&&void 0!==e?e:null}getStoredEngine(){var e;return"core"===(null===(e=this.getStoredVerification())||void 0===e?void 0:e.engine)?"core":"legacy"}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,r;if(null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.iframe)return new Promise(((e,t)=>{var r,o,i;const n=null===(i=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===i?void 0:i.iframe;if(n){this.saveVerifyTransactionUrl();const r=document.createElement("div");r.style.display="none",r.appendChild(function(e){const t=(new DOMParser).parseFromString(e,"text/html");for(const e of Array.from(t.body.querySelectorAll("*")))"http://www.w3.org/1999/xhtml"!==e.namespaceURI||M.has(e.localName)?e.remove():w(e);const r=document.createDocumentFragment();for(const e of Array.from(t.body.childNodes))r.appendChild(document.importNode(e,!0));return r}(n)),document.body.appendChild(r);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',r.appendChild(o);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(!k(e))throw v({errorCode:d.THREEDS_REDIRECTION_ERROR,statusCode:400,lockErrorCode:!0});if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const r=document.querySelector(`#${this.tdsIframeId}`);if(r){r.setAttribute("src",e),r.setAttribute("style","display: block");const o=this,i=e=>t(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}r&&r.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),r.removeEventListener("load",i)},n=r=>t(this,void 0,void 0,(function*(){const i=yield new Promise(((e,t)=>e(r)));if(i){if((e=>o.isVerificationFinal(e))(i))return e();{const e=setTimeout((()=>t(this,void 0,void 0,(function*(){clearTimeout(e),yield n(o.requestTransactionStatus())}))),7e3)}}}));yield n(o.requestTransactionStatus())}));r.addEventListener("load",i)}else console.log("No iframe found")}}else this.callBack&&this.callBack(this.payload)}fetchVerification(e){return t(this,void 0,void 0,(function*(){const t="core"===e.engine?this.coreBaseUrl:this.baseUrl,r=e.url.startsWith("https://")?e.url:`${t}${e.url}`;return yield fetch(r,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}})}))}requestTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getStoredVerification();if(!e)return null;let t;try{if(t=yield this.fetchVerification(e),200===t.status)return yield t.json()}catch(t){if(this.isTransientCoreFailure(e))return this.keepPolling();throw t}return console.error("La verificación de la transacción falló."),this.isTransientCoreFailure(e,t.status)?this.keepPolling():null}))}keepPolling(){return{status:"Pending",transaction_status:"Pending"}}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[r,o]of t)e[r]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return t(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const r=document.createElement("input");r.type="hidden",r.name=e.creq,r.value=e.creq,t.appendChild(r);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return t(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)}))}isCoreOpen(e){return V.includes(null==e?void 0:e.status)}handleCoreTransaction(e){return t(this,void 0,void 0,(function*(){const t=yield e.json();return this.isCoreOpen(t)||this.removeVerifyTransactionUrl(),this.buildCoreResult(t)}))}isVerificationFinal(e){return"core"===this.engine?!this.isCoreOpen(e):"Pending"!==(null==e?void 0:e.transaction_status)}isTransientCoreFailure(e,t){return"core"===e.engine&&(void 0===t||t>=500||429===t||408===t)}verifyTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getStoredVerification();if(null==e?void 0:e.url)try{const t=yield this.fetchVerification(e);if(200!==t.status){if(console.error("La verificación de la transacción falló."),this.isTransientCoreFailure(e,t.status)||this.removeVerifyTransactionUrl(),"core"===e.engine)throw yield v({response:t,errorCode:d.FETCH_TRANSACTION_ERROR});return t}return"core"===e.engine?yield this.handleCoreTransaction(t):yield this.handleTransactionResponse(t)}catch(t){if(console.error("Error al verificar la transacción:",t),"core"===e.engine)throw v({errorCode:d.FETCH_TRANSACTION_ERROR},t);this.removeVerifyTransactionUrl()}else console.log("No verify_transaction_status_url found")}))}}const j=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function K(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/checkout-router/`,i=o,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(Object.assign(Object.assign({},i),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(n.ok)return yield n.json();throw yield v({response:n,errorCode:d.START_CHECKOUT_ERROR})}))}function x(e,r,o=!0,i=null){return t(this,void 0,void 0,(function*(){let t=yield window.OpenPay;return t.setId(e),t.setApiKey(r),t.setSandboxMode(o),yield t.deviceData.setup({signal:i})}))}function B(e){return/^\d{12,19}$/.test(e)&&z(e)}function Y(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function $(e){return/^\d{3,4}$/.test(e)}function H(e){return/^(0[1-9]|1[0-2])$/.test(e)}function q(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const z=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),r=t.shift();let o=t.reduce(((e,t,r)=>r%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=r,o%10==0};function X(e,r,o,i=null){return t(this,void 0,void 0,(function*(){const t="core"===e.engine?`${e.baseUrl}${n.CORE_CUSTOMER}`:`${e.baseUrl}/api/v1/customer/`,s={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},a=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},signal:i,body:JSON.stringify(s)});if(a.ok){const t=yield a.json();return"core"===e.engine?function(e){return{id:e.customer_id,email:e.email,auth_token:e.auth_token,first_name:e.first_name,last_name:e.last_name}}(t):t}throw yield b(a,d.CUSTOMER_OPERATION_ERROR,e.engine)}))}function Q(e,t,r){const o=t.replace(/\[(\w+)\]/g,".$1").split(".").filter((e=>""!==e));let i=e;for(const e of o){if(null==i)return r;i=i[e]}return void 0===i?r:i}function W(e,t,r=""){return"core"===e.engine?`${e.baseUrl}${n.CORE_CARDS}${r&&`/${r}`}`:`${e.baseUrl}/api/v1/business/${t}/cards/${r}`}function J(e,r,o,i,n,s=!1){return t(this,void 0,void 0,(function*(){const t=W(e,i),a=yield fetch(t,{method:"POST",headers:Object.assign({Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},s?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(n)});if(a.ok){const t=yield a.json();return"core"===e.engine?function(e){return Object.assign({skyflow_id:e.id,user_id:e.customer_id},e.card_bin?{card_bin:e.card_bin}:{})}(t):t}throw yield b(a,d.SAVE_CARD_ERROR,e.engine)}))}function G(e,r,o,i="",n){return t(this,void 0,void 0,(function*(){const t=W(e,n,i),s=yield fetch(t,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r}});if(204===s.status)return l[d.CARD_REMOVED_SUCCESSFULLY];if(s.ok&&"json"in s)return yield s.json();throw yield b(s,d.REMOVE_CARD_ERROR,e.engine)}))}const Z="https://cdn.kushkipagos.com/kushki.min.js",ee=d.CARD_ON_FILE_DECLINED;let te=!1,re=null;class oe{constructor(e){var t;this.acquirerInstance=null,this.subscriptionOwner=e.subscriptionOwner,this.isTestEnvironment=null===(t=e.isTestEnvironment)||void 0===t||t;const r=this.isTestEnvironment?"stage":"production";this.apiUrl=a(r),this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return t(this,void 0,void 0,(function*(){yield function(){return t(this,void 0,void 0,(function*(){return te?Promise.resolve():re||(re=new Promise(((e,t)=>{if(document.querySelector(`script[src="${Z}"]`))return te=!0,void e();const r=document.createElement("script");r.src=Z,r.async=!0,r.onload=()=>{te=!0,e()},r.onerror=()=>{re=null,t(v({errorCode:ee,lockErrorCode:!0,details:{step:"load_acquirer_script",message:"Failed to load acquirer script"}}))},document.head.appendChild(r)})),re)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw v({errorCode:ee,lockErrorCode:!0,details:{step:"create_acquirer_instance",message:"Acquirer script not loaded. Call initialize() first."}});return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw v({errorCode:ee,lockErrorCode:!0,details:{step:"get_acquirer_instance",message:"CardOnFile not initialized. Call initialize() first."}});return this.acquirerInstance}getJwt(e){return t(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((r,o)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void o(v({errorCode:ee,lockErrorCode:!0,details:{step:"get_jwt",acquirerResponse:e}}));const t=e;t.jwt?r(t.jwt):o(v({errorCode:ee,lockErrorCode:!0,details:{step:"get_jwt",message:"No JWT returned from acquirer",acquirerResponse:t}}))}))}))}))}generateToken(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${n.ACQ_SUBSCRIPTION_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield v({response:t,errorCode:ee,lockErrorCode:!0,details:{step:"generate_token"}});return t.json()}))}createSubscription(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${n.ACQ_SUBSCRIPTION_CREATE}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield v({response:t,errorCode:ee,lockErrorCode:!0,details:{step:"create_subscription"}});return t.json()}))}validate3DS(e,r){return t(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((o,i)=>{t.requestValidate3DS({secureId:e,security:r},(e=>{const t=e;t.code&&"3DS000"!==t.code?i(v({errorCode:ee,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}})):!1!==t.isValid?o(!0):i(v({errorCode:ee,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}}))}))}))}))}process(e){var r,o,i,n;return t(this,void 0,void 0,(function*(){const t=yield this.getJwt(e.cardBin),s=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:t}),a=s.secureId||(null===(r=s.details)||void 0===r?void 0:r.secureId),d=s.security||(null===(o=s.details)||void 0===o?void 0:o.security);if(!a||!d)throw v({errorCode:ee,lockErrorCode:!0,details:{step:"process",message:"Missing secureId or security in token response",tokenResponse:s}});return yield this.validate3DS(a,d),this.createSubscription({token:s.token,contactDetails:e.contactDetails,metadata:{customerId:null!==(n=null===(i=this.subscriptionOwner)||void 0===i?void 0:i.call(this))&&void 0!==n?n:e.customerId},currency:e.currency})}))}}class ie{constructor(e){this.REQUEST_TIMEOUT_MS=5e3,this.MAX_MESSAGE_LENGTH=500,this.config=e}captureException(e,t){try{const r=this.buildEvent(e,t||{});this.sendEvent(r)}catch(e){}}extractErrorInfo(e){try{if(e instanceof Error)return{name:e.name||"Error",message:this.truncate(e.message||"Unknown error",this.MAX_MESSAGE_LENGTH),stack:e.stack||void 0};const t=this.safeStringify(e);return{name:"NonErrorException",message:this.truncate(t,this.MAX_MESSAGE_LENGTH),stack:void 0}}catch(e){return{name:"SerializationError",message:"Failed to serialize error",stack:void 0}}}safeStringify(e){try{const t=new WeakSet;return JSON.stringify(e,((e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return"[Circular]";t.add(r)}return r}))}catch(t){return String(e)}}buildEvent(e,t){const r=this.extractErrorInfo(e),o=Object.assign({},t.metadata||{});void 0===o.error&&(o.error=e),"undefined"!=typeof window&&(o.url=window.location.href);const 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:o};return t.tenant_id&&(i.tenant_id=t.tenant_id),t.request_id&&(i.request_id=t.request_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 t(this,void 0,void 0,(function*(){try{const t=JSON.stringify(e),r=new AbortController,o=setTimeout((()=>r.abort()),this.REQUEST_TIMEOUT_MS);try{const e=yield fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.config.apiKey}`},body:t,keepalive:!0,signal:r.signal});return clearTimeout(o),e.ok}catch(e){return clearTimeout(o),!1}}catch(e){return!1}}))}}const ne=Object.freeze({name:"@tonder.io/ionic-lite-sdk",version:"1.0.2"});function se(e){var t;return e instanceof h&&ae({status:e.statusCode,body:null===(t=e.originalError)||void 0===t?void 0:t.body})}function ae(e){var t,r;return 503===e.status&&"operations_disabled"===(null===(r=null===(t=e.body)||void 0===t?void 0:t.error)||void 0===r?void 0:r.code)}const de=["Success","Authorized","Pending","Processing"],le=["card_number","cvv","expiration_month","expiration_year","cardholder_name"];function ce(e){return void 0!==e&&/^\d+$/.test(e)?Number(e):e}function ue(e,t){return[{name:"verify_transaction_status",url:`${t.coreBaseUrl}/transactions/v1/${e.id}`,method:"GET"},{name:"refund_transaction",url:`${t.coreBaseUrl}/transactions/v1/process`,method:"POST",body:{operation_type:"refund",original_transaction_id:e.id}}]}function he(e,t){var r,o;const i=e.routing,n=null!==(r=null==i?void 0:i.rejected_psp_responses)&&void 0!==r?r:[],s="Hard"===(null==i?void 0:i.decline_type);return{status:"404",message:s?"Hard decline":null!==(o=e.decline_reason)&&void 0!==o?o:"Transaction declined",checkout_id:null==i?void 0:i.checkout_id,is_route_finished:null==i?void 0:i.is_route_finished,transaction_status:e.status,transaction_id:ce(e.transaction_id),payment_id:e.payment_id,provider:e.provider,decline_code:e.decline_code,psp_response:s?n[n.length-1]:n,actions:ue(e,t)}}function _e(e){var t,r;return{status:"200",message:null!==(t=e.decline_reason)&&void 0!==t?t:"High risk transaction blocked",checkout_id:null===(r=e.routing)||void 0===r?void 0:r.checkout_id,transaction_status:"Declined",transaction_id:e.transaction_id,payment_id:e.payment_id,provider:e.provider,amount:Number(e.amount)||0,currency:e.currency,psp_response:e.psp_response,decline_code:e.decline_code}}function Ee(e,t){var r,o,i;return{status:"200",message:"Success",checkout_id:null===(r=e.routing)||void 0===r?void 0:r.checkout_id,is_route_finished:null===(o=e.routing)||void 0===o?void 0:o.is_route_finished,transaction_status:e.status,transaction_id:ce(e.transaction_id),payment_id:e.payment_id,provider:e.provider,next_action:null!==(i=e.next_action)&&void 0!==i?i:{},psp_response:e.psp_response,actions:ue(e,t)}}const me=["card_brand","transaction_reference","number_of_payment_attempts","number_of_installments","three_d_secure","reason","operation_date","decline"],pe=(e,t)=>null==e?e:t(e),Re={payment:"PAYMENT",refund:"REFUND"};function ve(e){var t;const r=e.routing,o=null==r?void 0:r.checkout_id,i={id:pe(e.transaction_id,ce),metadata:e.metadata,response:e.psp_response,payment:pe(e.payment_id,(e=>({id:e}))),checkout:pe(o,(e=>({id:e,is_route_finished:null==r?void 0:r.is_route_finished}))),checkout_id:o,transaction_type:Re[null!==(t=e.operation_type)&&void 0!==t?t:""],amount:e.amount,currency:pe(e.currency,(e=>({code:e}))),currency_code:e.currency,created:e.created_at,modified:e.updated_at};return Object.assign(Object.assign({status:e.status,transaction_status:e.status,provider:e.provider||"tonder",is_apm:!1},Object.fromEntries(Object.entries(i).filter((([,e])=>void 0!==e)))),Object.fromEntries(me.filter((t=>t in e)).map((t=>[t,e[t]]))))}function ye(e,t){var r,o;return{status:String(e),message:null!==(o=null===(r=null==t?void 0:t.error)||void 0===r?void 0:r.message)&&void 0!==o?o:"Error",psp_response:[],is_route_finished:!1}}var fe,Ce,Oe,Te,Ae,ge,Se,Ie,Ne,be,De,ke,Me,Ue,Pe,Le,we;class Ve{constructor({mode:e="stage",customization:t,apiKey:r,apiKeyTonder:o,returnUrl:i,tdsIframeId:n,callBack:d=(()=>{}),baseUrlTonder:l,tonderPayButtonId:c,sdkInfo:u}){fe.add(this),this.baseUrl="",this.coreBaseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,Ce.set(this,void 0),Oe.set(this,void 0),this.apiKeyTonder=o||r||"",this.returnUrl=i,this.callBack=d,this.mode=e,this.customer={},this.baseUrl=l||j[this.mode]||j.stage,this.coreBaseUrl=a(this.mode),this.abortController=new AbortController,this.requestId=this.generateRequestId(),this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new F({apiKey:this.apiKeyTonder,baseUrl:this.baseUrl,coreBaseUrl:this.coreBaseUrl,buildCoreResult:ve,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:n,tonderPayButtonId:c,callBack:d}),this.tdsIframeId=n;const h=u||ne;this.telemetry=new ie({endpoint:s(this.mode),apiKey:this.apiKeyTonder,platform:h.name,platform_version:h.version,mode:this.mode||"stage"})}configureCheckout(e){"secureToken"in e&&r(this,fe,"m",be).call(this,e.secureToken),r(this,fe,"m",Ie).call(this,e)}getCustomerId(){var e,t;return null===(t=null===(e=r(this,Oe,"f"))||void 0===e?void 0:e.id)||void 0===t?void 0:t.toString()}reportSdkError(e,t){var r,o,i,n;try{const s=this.getCustomerId(),a=e instanceof h&&void 0!==e.originalError?e.originalError:e,d=Object.assign(Object.assign({},(null==t?void 0:t.metadata)||{}),void 0===(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.error)?{error:a}:{}),l=Object.assign(Object.assign({tenant_id:null===(n=null===(i=null===(o=this.merchantData)||void 0===o?void 0:o.business)||void 0===i?void 0:i.pk)||void 0===n?void 0:n.toString(),user_id:s},t||{}),{metadata:d,request_id:this.requestId});l.user_id||delete l.user_id,l.feature=(null==t?void 0:t.feature)||"unknown",this.telemetry.captureException(e,l)}catch(e){}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}verify3dsTransaction(){return t(this,void 0,void 0,(function*(){const e=this.process3ds.getStoredEngine(),t=yield this.process3ds.verifyTransactionStatus();if("core"===e)return this.process3ds.setPayload(t),t;this.process3ds.setEngine("legacy");const o=yield r(this,fe,"m",Pe).call(this,t);return this.process3ds.setPayload(o),this._handle3dsRedirect(o)}))}payment(e){return new Promise(((o,i)=>t(this,void 0,void 0,(function*(){var t,n;let s;try{r(this,fe,"m",Ie).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),o(s)}}catch(r){this.reportSdkError(r,{feature:"payment",process_id:(null==s?void 0:s.payment_id)||(null===(t=null==s?void 0:s.payment)||void 0===t?void 0:t.id)||(null===(n=null==s?void 0:s.payment)||void 0===n?void 0:n.pk),metadata:{step:"payment",request:e,response:s}}),i(v({errorCode:d.PAYMENT_PROCESS_ERROR},r))}}))))}getSecureToken(e){return t(this,void 0,void 0,(function*(){try{return yield function(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:o});if(t.ok)return yield t.json();throw yield v({response:t,errorCode:d.SECURE_TOKEN_ERROR})}))}(this.baseUrl,e)}catch(e){throw this.reportSdkError(e,{feature:"secure-token",metadata:{step:"getSecureToken"}}),v({errorCode:d.SECURE_TOKEN_ERROR},e)}}))}_initializeCheckout(){return t(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 t(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.")}_supportTarget(){var e;return!0===(null===(e=this.merchantData)||void 0===e?void 0:e.core_payments_enabled)?{engine:"core",baseUrl:this.coreBaseUrl}:{engine:"legacy",baseUrl:this.baseUrl}}_getCustomer(e=null){return t(this,void 0,void 0,(function*(){return r(this,Oe,"f")||(yield this._fetchMerchantData(),o(this,Oe,yield X(this._supportTarget(),this.apiKeyTonder,this.customer,e),"f")),r(this,Oe,"f")}))}_handleCheckout(e){var o;return t(this,void 0,void 0,(function*(){if(!0===(null===(o=this.merchantData)||void 0===o?void 0:o.core_payments_enabled)&&r(this,fe,"m",Ae).call(this,e)){this.process3ds.setEngine("core");try{return yield r(this,fe,"m",ge).call(this,e)}catch(e){if(!se(e))throw e}}return this.process3ds.setEngine("legacy"),r(this,fe,"m",Se).call(this,yield r(this,fe,"m",Te).call(this,e))}))}_fetchMerchantData(){return t(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield y(this.coreBaseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){throw this.reportSdkError(e,{feature:"fetch-merchant-data",metadata:{step:"_fetchMerchantData"}}),v({errorCode:d.FETCH_BUSINESS_ERROR},e)}}))}_getCustomerCards(e,r){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i,n=null){return t(this,void 0,void 0,(function*(){const t=W(e,i),s=yield fetch(t,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},signal:n});if(s.ok){const t=yield s.json();return"core"===e.engine?function(e){var t;return{user_id:e.customer_id,cards:(null!==(t=e.data)&&void 0!==t?t:[]).map((e=>{var t;return{fields:{card_number:e.card_number,expiration_month:e.expiration_month,expiration_year:e.expiration_year,skyflow_id:e.id,card_scheme:e.card_scheme,subscription_id:null!==(t=e.subscription_id)&&void 0!==t?t:void 0}}}))}}(t):t}if(401===s.status)return{user_id:0,cards:[]};throw yield b(s,d.FETCH_CARDS_ERROR,e.engine)}))}(this._supportTarget(),e,this.secureToken,r)}))}_saveCustomerCard(e,r,o,i=!1){return t(this,void 0,void 0,(function*(){return yield J(this._supportTarget(),e,this.secureToken,r,o,i)}))}_removeCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){return yield G(this._supportTarget(),e,this.secureToken,o,r)}))}_fetchCustomerPaymentMethods(){return t(this,void 0,void 0,(function*(){return yield function(e,r,o={status:"active",pagesize:"10000"},i=null){return t(this,void 0,void 0,(function*(){const t=new URLSearchParams(o).toString(),s=yield fetch(`${e}${n.CORE_PAYMENT_METHODS}?${t}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(s.ok)return I(yield s.json());throw yield b(s,d.FETCH_PAYMENT_METHODS_ERROR,"core")}))}(this.coreBaseUrl,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 t(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new oe({merchantId:null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys.public_key,apiKey:this.apiKeyTonder,isTestEnvironment:"production"!==this.mode,subscriptionOwner:()=>{var e;return"core"===this._supportTarget().engine&&void 0!==(null===(e=r(this,Oe,"f"))||void 0===e?void 0:e.id)?String(r(this,Oe,"f").id):void 0}}),yield this.cardOnFileInstance.initialize()),this.cardOnFileInstance}))}_handle3dsRedirect(e){var r,o;return t(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(r=null==e?void 0:e.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>this.process3ds.verifyTransactionStatus())).catch((t=>{console.log("Error loading iframe:",t),this.reportSdkError(t,{feature:"3ds-verification",metadata:{step:"_handle3dsRedirect",response:e}})}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function Fe(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}${n.CORE_VAULT_TOKEN}`,{method:"GET",headers:{Authorization:`Token ${r}`},signal:o});if(t.ok){return(yield t.json()).token}throw yield b(t,d.VAULT_TOKEN_ERROR,"core")}))}Ce=new WeakMap,Oe=new WeakMap,fe=new WeakSet,Te=function(e){return t(this,void 0,void 0,(function*(){if("core"!==this._supportTarget().engine)return e;const t=yield X({engine:"legacy",baseUrl:this.baseUrl},this.apiKeyTonder,this.customer,this.abortController.signal);return Object.assign(Object.assign({},e),{customer:t})}))},Ae=function({card:e,payment_method:t}){return!!e&&g(t)},ge=function({card:e,returnUrl:r}){return t(this,void 0,void 0,(function*(){const{reference:o}=this.merchantData;let i,s;try{i=function(e){const{card:t,customer:r}=e,o=[Q(r,"firstName",Q(r,"name","")),Q(r,"lastName",Q(r,"lastname",""))].filter(Boolean).join(" "),i=t.card_number?Object.assign(Object.assign({type:"CARD"},Object.fromEntries(le.map((e=>[e,t[e]])))),t.skyflow_id?{skyflow_id:t.skyflow_id}:{}):{type:"CARD",token:t.skyflow_id};return{operation_type:"payment",amount:e.amount,currency:e.currency,client_reference:String(e.reference),customer:{name:o,email:Q(r,"email",""),phone:Q(r,"phone",void 0),identification:Q(r,"identification",void 0)},payment_method:i,metadata:e.metadata,return_url:e.returnUrl,items:e.items,browser_info:e.browserInfo}}({amount:Number(this.cartTotal),currency:this.currency,reference:this.order_reference?this.order_reference:o,customer:this.customer,card:e,metadata:this.metadata,returnUrl:r||this.returnUrl,items:this.cartItems,browserInfo:T()});const h=yield function(e,r,o,i){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}${n.CORE_PROCESS}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`,"X-App-Origin":"sdk/ionic","X-Request-Id":i},body:JSON.stringify(o)}),s=t.ok?yield t.json():yield t.json().catch((()=>{}));return{status:t.status,statusText:t.statusText,body:s}}))}(this.coreBaseUrl,this.apiKeyTonder,i,function(){const e=globalThis.crypto;return"function"==typeof(null==e?void 0:e.randomUUID)?e.randomUUID():`req_${Date.now()}_${Math.random().toString(36).slice(2,12)}`}());if(h.status>=400&&(a=h.status,l=h.body,s={status:a,code:null===(c=null==l?void 0:l.error)||void 0===c?void 0:c.code,type:null===(u=null==l?void 0:l.error)||void 0===u?void 0:u.type,request_id:null==l?void 0:l.request_id}),ae(h))throw R({errorCode:d.START_CHECKOUT_ERROR,status:h.status,body:h.body});const _=function(e,t,r,o){var i;if(402===e&&"payment_declined"===(null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.code))return{outcome:"reject",status:404,body:{status:"404",message:"Error",psp_response:[],is_route_finished:!0}};if(e>=400)return{outcome:"reject",status:e,statusText:o,body:ye(e,t)};const n=t;return de.includes(n.status)?{outcome:"resolve",status:200,body:Ee(n,r)}:"Declined"===n.status&&"FH01"===n.decline_code?{outcome:"resolve",status:200,body:_e(n)}:{outcome:"reject",status:404,body:he(n,r)}}(h.status,h.body,{coreBaseUrl:this.coreBaseUrl},h.statusText);if("resolve"===_.outcome)return _.body;throw R({errorCode:d.START_CHECKOUT_ERROR,status:_.status,statusText:_.statusText,body:_.body})}catch(e){throw se(e)||this.reportSdkError(e,{feature:"payment",metadata:{step:"_handleCheckout",payment:i,core_error:s}}),e}var a,l,c,u}))},Se=function({card:e,payment_method:o,customer:i,isSandbox:n,enable_card_on_file:s,returnUrl:a}){return t(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:u}=this.merchantData,h=Number(this.cartTotal);let _,E,m;try{let p;!p&&l.merchant_id&&l.public_key&&!o&&(p=yield x(l.merchant_id,l.public_key,n,this.abortController.signal));const{id:R,auth_token:y}=i;_={business:this.apiKeyTonder,client:y,billing_address_id:null,shipping_address_id:null,amount:h,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata};const f=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/orders/`,i=o,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(n.ok)return yield n.json();throw yield v({response:n,errorCode:d.CREATE_ORDER_ERROR})}))}(this.baseUrl,this.apiKeyTonder,_),C=(new Date).toISOString();E={business_pk:u.pk,client_id:R,amount:h,date:C,order_id:f.id,customer_order_reference:this.order_reference?this.order_reference:c,items:this.cartItems,currency:this.currency,metadata:this.metadata};const O=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${o.business_pk}/payments/`,i=o,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(n.ok)return yield n.json();throw yield v({response:n,errorCode:d.CREATE_PAYMENT_ERROR})}))}(this.baseUrl,this.apiKeyTonder,E);m=Object.assign(Object.assign(Object.assign(Object.assign({name:Q(this.customer,"firstName",Q(this.customer,"name","")),last_name:Q(this.customer,"lastName",Q(this.customer,"lastname","")),email_client:Q(this.customer,"email",""),phone_number:Q(this.customer,"phone",""),return_url:a||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:h,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:f.id,business_id:u.pk,payment_id:O.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:T(),currency:this.currency},o?{payment_method:o}:{card:e}),{apm_config:r(this,Ce,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==s?{enable_card_on_file:s}:{});const A=yield K(this.baseUrl,this.apiKeyTonder,m);return A||!1}catch(e){throw this.reportSdkError(e,{feature:"payment",process_id:null==m?void 0:m.payment_id,metadata:{step:"_handleCheckout",orderItems:_,paymentItems:E,routerItems:m}}),e}}))},Ie=function(e){var t,o;!e||e&&0===Object.keys(e).length||(r(this,fe,"m",Ne).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),r(this,fe,"m",De).call(this,(null===(o=e.cart)||void 0===o?void 0:o.items)||[]),r(this,fe,"m",ke).call(this,e),r(this,fe,"m",Me).call(this,e),r(this,fe,"m",Ue).call(this,e),r(this,fe,"m",Le).call(this,e))},Ne=function(e){e&&(this.customer=e)},be=function(e){if("string"!=typeof(t=e)||!/^[\x21-\x7E]+$/.test(t))throw v({errorCode:d.SECURE_TOKEN_INVALID,statusCode:400});var t;this.secureToken=e},De=function(e){this.cartItems=e},ke=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},Me=function(e){this.currency=null==e?void 0:e.currency},Ue=function(e){this.card=null==e?void 0:e.card},Pe=function(e){var r,o,i,n,s;return t(this,void 0,void 0,(function*(){if("Hard"===(null===(r=null==e?void 0:e.decline)||void 0===r?void 0:r.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(i=e.checkout)||void 0===i?void 0:i.id)||(null==e?void 0:e.checkout_id)};try{return yield K(this.baseUrl,this.apiKeyTonder,t)}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==e?void 0:e.payment_id)||(null===(n=null==e?void 0:e.payment)||void 0===n?void 0:n.id)||(null===(s=null==e?void 0:e.payment)||void 0===s?void 0:s.pk),metadata:{step:"#resumeCheckout",response:e}})}return e}}))},Le=function(e){o(this,Ce,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"}(we||(we={}));const je={type:e.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},Ke=RegExp("^(?!s*$).+"),xe={type:e.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:Ke,error:"El campo es requerido"}},Be="Titular de la tarjeta",Ye="Número de tarjeta",$e="CVC/CVV",He="Mes",qe="Año",ze="Fecha de expiración",Xe="Nombre como aparece en la tarjeta",Qe="1234 1234 1234 1234",We="3-4 dígitos",Je="MM",Ge="AA",Ze={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")'}},et={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},tt={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function rt({coreBaseUrl:r,apiKey:o,vault_id:i,vault_url:n,data:s}){return t(this,void 0,void 0,(function*(){const a=e.init({vaultID:i,vaultURL:n,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield Fe(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),l=yield function(r,o){return t(this,void 0,void 0,(function*(){const i=yield function(r,o){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(r).map((r=>t(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:r,type:e.ElementType.INPUT_FIELD}),key:r}})))))}))}(r,o);return i?i.map((e=>new Promise((t=>{var o;const i=document.createElement("div");i.hidden=!0,i.id=`id-${e.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(i),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const o=r[e.key];return e.element.setValue(o),t(e.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(l)).some((e=>!e)))throw v({errorCode:d.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}});try{const e=yield a.collect();if(e)return e.records[0].fields;throw v({errorCode:d.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}})}catch(e){throw v({errorCode:d.SAVE_CARD_PROCESS_ERROR},e)}}))}function ot(t){const{element:r,fieldMessage:o="",errorStyles:i={},requiredMessage:n="Campo requerido",invalidMessage:s="Campo no válido",events:a}=t;"on"in r&&(r.on(e.EventName.CHANGE,(e=>{nt({eventName:"onChange",data:e,events:a}),it({element:r,errorStyles:i,color:"transparent"})})),r.on(e.EventName.BLUR,(e=>{if(nt({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?n:""!=o?`El campo ${o} no es válido`:s;r.setError(t)}it({element:r,errorStyles:i})})),r.on(e.EventName.FOCUS,(e=>{nt({eventName:"onFocus",data:e,events:a}),it({element:r,errorStyles:i,color:"transparent"}),r.resetError()})))}function it(e){const{element:t,errorStyles:r={},color:o=""}=e;Object.keys(r).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base&&Object.assign({},r.base)),""!=o&&{color:o})})})}const nt=e=>{const{eventName:t,data:r,events:o}=e;if(o&&t in o){const e=o[t];"function"==typeof e&&e({elementType:Q(r,"elementType",""),isEmpty:Q(r,"isEmpty",!1),isFocused:Q(r,"isFocused",!1),isValid:Q(r,"isValid",!1),value:Q(r,"value","")})}};function st(e){return t(this,void 0,void 0,(function*(){const{element:t,containerId:r,retries:o=2,delay:i=30}=e;for(let e=0;e<=o;e++){if(document.querySelector(r))return void t.mount(r);e<o&&(yield new Promise((e=>setTimeout(e,i))))}console.warn(`[mountCardFields] Container ${r} was not found after ${o+1} attempts`)}))}const at=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"}),dt={[at.SORIANA]:{label:"Soriana",iconPath:"/payment_methods/soriana.png"},[at.OXXO]:{label:"Oxxo",iconPath:"/payment_methods/oxxo.png"},[at.CODI]:{label:"CoDi",iconPath:"/payment_methods/codi.png"},[at.MERCADOPAGO]:{label:"Mercado Pago",iconPath:"/payment_methods/mercadopago.png"},[at.OXXOPAY]:{label:"Oxxo Pay",iconPath:"/payment_methods/oxxopay.png"},[at.SPEI]:{label:"SPEI",iconPath:"/payment_methods/spei.png"},[at.PAYPAL]:{label:"Paypal",iconPath:"/payment_methods/paypal.png"},[at.COMERCIALMEXICANA]:{label:"Comercial Mexicana",iconPath:"/payment_methods/comercial_exicana.png"},[at.BANCOMER]:{label:"Bancomer",iconPath:"/payment_methods/bancomer.png"},[at.WALMART]:{label:"Walmart",iconPath:"/payment_methods/walmart.png"},[at.BODEGA]:{label:"Bodega Aurrera",iconPath:"/payment_methods/bodega_aurrera.png"},[at.SAMSCLUB]:{label:"Sam´s Club",iconPath:"/payment_methods/sams_club.png"},[at.SUPERAMA]:{label:"Superama",iconPath:"/payment_methods/superama.png"},[at.CALIMAX]:{label:"Calimax",iconPath:"/payment_methods/calimax.png"},[at.EXTRA]:{label:"Tiendas Extra",iconPath:"/payment_methods/tiendas_extra.png"},[at.CIRCULOK]:{label:"Círculo K",iconPath:"/payment_methods/circulo_k.png"},[at.SEVEN11]:{label:"7 Eleven",iconPath:"/payment_methods/7_eleven.png"},[at.TELECOMM]:{label:"Telecomm",iconPath:"/payment_methods/telecomm.png"},[at.BANORTE]:{label:"Banorte",iconPath:"/payment_methods/banorte.png"},[at.BENAVIDES]:{label:"Farmacias Benavides",iconPath:"/payment_methods/farmacias_benavides.png"},[at.DELAHORRO]:{label:"Farmacias del Ahorro",iconPath:"/payment_methods/farmacias_ahorro.png"},[at.ELASTURIANO]:{label:"El Asturiano",iconPath:"/payment_methods/asturiano.png"},[at.WALDOS]:{label:"Waldos",iconPath:"/payment_methods/waldos.png"},[at.ALSUPER]:{label:"Alsuper",iconPath:"/payment_methods/al_super.png"},[at.KIOSKO]:{label:"Kiosko",iconPath:"/payment_methods/kiosko.png"},[at.STAMARIA]:{label:"Farmacias Santa María",iconPath:"/payment_methods/farmacias_santa_maria.png"},[at.LAMASBARATA]:{label:"Farmacias la más barata",iconPath:"/payment_methods/farmacias_barata.png"},[at.FARMROMA]:{label:"Farmacias Roma",iconPath:"/payment_methods/farmacias_roma.png"},[at.FARMUNION]:{label:"Pago en Farmacias Unión",iconPath:"/payment_methods/farmacias_union.png"},[at.FARMATODO]:{label:"Pago en Farmacias Farmatodo",iconPath:"/payment_methods/farmacias_farmatodo.png\t"},[at.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",iconPath:"/payment_methods/farmacias_san_francisco.png"},[at.FARM911]:{label:"Farmacias 911",iconPath:"/payment_methods/store.png"},[at.FARMECONOMICAS]:{label:"Farmacias Economicas",iconPath:"/payment_methods/store.png"},[at.FARMMEDICITY]:{label:"Farmacias Medicity",iconPath:"/payment_methods/store.png"},[at.RIANXEIRA]:{label:"Rianxeira",iconPath:"/payment_methods/store.png"},[at.WESTERNUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[at.ZONAPAGO]:{label:"Zona Pago",iconPath:"/payment_methods/store.png"},[at.CAJALOSANDES]:{label:"Caja Los Andes",iconPath:"/payment_methods/store.png"},[at.CAJAPAITA]:{label:"Caja Paita",iconPath:"/payment_methods/store.png"},[at.CAJASANTA]:{label:"Caja Santa",iconPath:"/payment_methods/store.png"},[at.CAJASULLANA]:{label:"Caja Sullana",iconPath:"/payment_methods/store.png"},[at.CAJATRUJILLO]:{label:"Caja Trujillo",iconPath:"/payment_methods/store.png"},[at.EDPYME]:{label:"Edpyme",iconPath:"/payment_methods/store.png"},[at.KASNET]:{label:"KasNet",iconPath:"/payment_methods/store.png"},[at.NORANDINO]:{label:"Norandino",iconPath:"/payment_methods/store.png"},[at.QAPAQ]:{label:"Qapaq",iconPath:"/payment_methods/store.png"},[at.RAIZ]:{label:"Raiz",iconPath:"/payment_methods/store.png"},[at.PAYSER]:{label:"Paysera",iconPath:"/payment_methods/store.png"},[at.WUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[at.BANCOCONTINENTAL]:{label:"Banco Continental",iconPath:"/payment_methods/store.png"},[at.GMONEY]:{label:"Go money",iconPath:"/payment_methods/store.png"},[at.GOPAY]:{label:"Go pay",iconPath:"/payment_methods/store.png"},[at.WU]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[at.PUNTOSHEY]:{label:"Puntoshey",iconPath:"/payment_methods/store.png"},[at.AMPM]:{label:"Ampm",iconPath:"/payment_methods/store.png"},[at.JUMBOMARKET]:{label:"Jumbomarket",iconPath:"/payment_methods/store.png"},[at.SMELPUEBLO]:{label:"Smelpueblo",iconPath:"/payment_methods/store.png"},[at.BAM]:{label:"Bam",iconPath:"/payment_methods/store.png"},[at.REFACIL]:{label:"Refacil",iconPath:"/payment_methods/store.png"},[at.ACYVALORES]:{label:"Acyvalores",iconPath:"/payment_methods/store.png"}},lt=(e,t="stage")=>{const r=e.toUpperCase().trim().replace(/\s+/g,"");const o=dt[r]||{iconPath:"/payment_methods/store.png",label:""};return{label:o.label,icon:`${O(t)}${o.iconPath}`}};class ct extends Ve{constructor({apiKey:e,mode:t,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe",sdkInfo:ne}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.lastCollectedTokens=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return t(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return t(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=>Object.assign(Object.assign({},e),{fields:Object.assign(Object.assign({},e.fields),{subscription_id:this._hasCardOnFileKeys()?e.fields.subscription_id:void 0}),icon:S(e.fields.card_scheme,this.mode)})))})}catch(e){throw this.reportSdkError(e,{feature:"get-cards",process_id:this.getCustomerId(),metadata:{step:"getCustomerCards"}}),v({errorCode:d.FETCH_CARDS_ERROR},e)}}))}saveCustomerCard(){return t(this,void 0,void 0,(function*(){let e=null;try{yield this._fetchMerchantData();const t=yield this._getCustomer(),{auth_token:r,first_name:o="",last_name:i="",email:n=""}=t,{business:s}=this.merchantData,a=this._hasCardOnFileKeys(),l=yield this.collectCreateCardTokens(),c=yield this._saveCustomerCard(r,null==s?void 0:s.pk,l,a);if(e=c.skyflow_id,a){const e=c.card_bin;if(!e)throw new Error("Card BIN not returned from save card");const t=yield this._initializeCardOnFile();let a;try{a=yield t.process({cardTokens:{name:l.cardholder_name,number:l.card_number,expiryMonth:l.expiration_month,expiryYear:l.expiration_year,cvv:l.cvv},cardBin:e,contactDetails:{firstName:o||"",lastName:i||"",email:n||""},customerId:r,currency:this.currency||"MXN"})}catch(e){throw v({errorCode:d.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}const u={skyflow_id:l.skyflow_id,subscription_id:a.subscriptionId};yield this._saveCustomerCard(r,null==s?void 0:s.pk,u)}return c}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"save-card",process_id:e||this.getCustomerId(),metadata:{step:"saveCustomerCard"}}),v({errorCode:d.SAVE_CARD_ERROR},t)}}))}removeCustomerCard(e){return t(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"}}),v({errorCode:d.REMOVE_CARD_ERROR},t)}}))}getCustomerPaymentMethods(){return t(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},lt(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw this.reportSdkError(e,{feature:"get-payment-methods",metadata:{step:"getCustomerPaymentMethods"}}),v({errorCode:d.FETCH_PAYMENT_METHODS_ERROR},e)}}))}mountCardFields(r){var o;return t(this,void 0,void 0,(function*(){const i=r.card_id?`update:${r.card_id}`:"create",n=null!==(o=r.unmount_context)&&void 0!==o?o:"all";"none"!==n&&("current"===n?this.unmountCardFields(i):this.unmountCardFields(n)),yield this.createSkyflowInstance();const s=yield function(r){var o,i,n,s,a,d,l,c,u,h,_,E,m;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,data:p,customization:R,events:v}=r,y=t.container(e.ContainerType.COLLECT),f=[],C={[we.CVV]:e.ElementType.CVV,[we.CARD_NUMBER]:e.ElementType.CARD_NUMBER,[we.EXPIRATION_MONTH]:e.ElementType.EXPIRATION_MONTH,[we.EXPIRATION_YEAR]:e.ElementType.EXPIRATION_YEAR,[we.CARDHOLDER_NAME]:e.ElementType.CARDHOLDER_NAME},O={[we.CVV]:[xe],[we.CARD_NUMBER]:[xe],[we.EXPIRATION_MONTH]:[xe],[we.EXPIRATION_YEAR]:[xe],[we.CARDHOLDER_NAME]:[je,xe]},T={[we.CARDHOLDER_NAME]:"cardholderName",[we.CARD_NUMBER]:"cardNumber",[we.CVV]:"cvv",[we.EXPIRATION_MONTH]:"expirationMonth",[we.EXPIRATION_YEAR]:"expirationYear"},A=e=>{var t,r,o,i,n,s,a,d,l;const c=null===(t=null==R?void 0:R.styles)||void 0===t?void 0:t[T[e]],u=null===(r=null==R?void 0:R.styles)||void 0===r?void 0:r.cardForm,h=null!==(i=null!==(o=null==c?void 0:c.inputStyles)&&void 0!==o?o:null==u?void 0:u.inputStyles)&&void 0!==i?i:Ze;return{inputStyles:e===we.CARD_NUMBER&&!1!==(null===(n=null==R?void 0:R.styles)||void 0===n?void 0:n.enableCardIcon)?Object.assign(Object.assign({},h),{base:Object.assign({paddingLeft:"15px"},null==h?void 0:h.base)}):h,labelStyles:null!==(a=null!==(s=null==c?void 0:c.labelStyles)&&void 0!==s?s:null==u?void 0:u.labelStyles)&&void 0!==a?a:et,errorStyles:null!==(l=null!==(d=null==c?void 0:c.errorStyles)&&void 0!==d?d:null==u?void 0:u.errorStyles)&&void 0!==l?l:tt}},g={cardholder_name:(null===(o=null==R?void 0:R.labels)||void 0===o?void 0:o.name)||Be,card_number:(null===(i=null==R?void 0:R.labels)||void 0===i?void 0:i.card_number)||Ye,cvv:(null===(n=null==R?void 0:R.labels)||void 0===n?void 0:n.cvv)||$e,expiration_date:(null===(s=null==R?void 0:R.labels)||void 0===s?void 0:s.expiry_date)||ze,expiration_month:(null===(a=null==R?void 0:R.labels)||void 0===a?void 0:a.expiration_month)||He,expiration_year:(null===(d=null==R?void 0:R.labels)||void 0===d?void 0:d.expiration_year)||qe},S={cardholder_name:(null===(l=null==R?void 0:R.placeholders)||void 0===l?void 0:l.name)||Xe,card_number:(null===(c=null==R?void 0:R.placeholders)||void 0===c?void 0:c.card_number)||Qe,cvv:(null===(u=null==R?void 0:R.placeholders)||void 0===u?void 0:u.cvv)||We,expiration_month:(null===(h=null==R?void 0:R.placeholders)||void 0===h?void 0:h.expiration_month)||Je,expiration_year:(null===(_=null==R?void 0:R.placeholders)||void 0===_?void 0:_.expiration_year)||Ge},I={[we.CVV]:null==v?void 0:v.cvvEvents,[we.CARD_NUMBER]:null==v?void 0:v.cardNumberEvents,[we.EXPIRATION_MONTH]:null==v?void 0:v.monthEvents,[we.EXPIRATION_YEAR]:null==v?void 0:v.yearEvents,[we.CARDHOLDER_NAME]:null==v?void 0:v.cardHolderEvents};if("fields"in p&&Array.isArray(p.fields)){const e={enableCardIcon:null===(m=null===(E=null==R?void 0:R.styles)||void 0===E?void 0:E.enableCardIcon)||void 0===m||m};if(p.fields.length>0&&"string"==typeof p.fields[0])for(const t of p.fields){const r=y.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:C[t],validations:O[t]},A(t)),{label:g[t],placeholder:S[t]}),p.card_id?{skyflowID:p.card_id}:{}),t===we.CARD_NUMBER?e:void 0);ot({element:r,errorStyles:A(t).errorStyles,fieldMessage:[we.CVV,we.EXPIRATION_MONTH,we.EXPIRATION_YEAR].includes(t)?"":g[t],events:I[t]});const o=`#collect_${String(t)}`+(p.card_id?`_${p.card_id}`:"");yield st({element:r,containerId:o}),f.push({element:r,containerId:o})}else for(const t of p.fields){const r=t.field,o=y.create(Object.assign(Object.assign(Object.assign({table:"cards",column:r,type:C[r],validations:O[r]},A(r)),{label:g[r],placeholder:S[r]}),p.card_id?{skyflowID:p.card_id}:{}),r===we.CARD_NUMBER?e:void 0);ot({element:o,errorStyles:A(r).errorStyles,fieldMessage:[we.CVV,we.EXPIRATION_MONTH,we.EXPIRATION_YEAR].includes(r)?"":g[r],events:I[r]});const i=t.container_id||`#collect_${String(r)}`+(p.card_id?`_${p.card_id}`:"");yield st({element:o,containerId:i}),f.push({element:o,containerId:i})}}return{elements:f.map((e=>e.element)),container:y}}))}({skyflowInstance:this.skyflowInstance,data:r,customization:this.customization,events:this.events});this.mountedElementsByContext.set(i,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const r=`update:${e}`,o=this.mountedElementsByContext.get(r);return(null===(t=null==o?void 0:o.container)||void 0===t?void 0:t.container)||null}collectCardTokens(e){var r,o,i;return t(this,void 0,void 0,(function*(){const t=this.getContainerByCardId(e);if(!t)return null;try{const e=yield t.collect();return(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.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 f({code:d.MOUNT_COLLECT_ERROR,details:{message:r}})}}))}collectCreateCardTokens(){var e,r,o,i;return t(this,void 0,void 0,(function*(){const t=this.mountedElementsByContext.get("create"),n=null===(e=null==t?void 0:t.container)||void 0===e?void 0:e.container;if(!n)throw new f({code:d.MOUNT_COLLECT_ERROR,details:{message:"No card fields are mounted. Call mountCardFields() with the required fields before proceeding."}});try{const e=yield n.collect(),t=(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.fields)||{};return this.lastCollectedTokens=t,t}catch(e){const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.description;throw this.reportSdkError(e,{feature:"collect-create-card-tokens",metadata:{step:"collectCreateCardTokens"}}),new f({code:d.MOUNT_COLLECT_ERROR,details:{message:t}})}}))}revealCardFields(r){return t(this,void 0,void 0,(function*(){if(!this.lastCollectedTokens)throw v({errorCode:d.MOUNT_COLLECT_ERROR,details:{message:"No card tokens available. Call saveCustomerCard() or payment() with a new card before calling revealCardFields()."}});if(!this.skyflowInstance)throw v({errorCode:d.MOUNT_COLLECT_ERROR,details:{message:"Skyflow instance not initialized. Ensure mountCardFields() was called before saveCustomerCard() or payment()."}});yield function(r){var o,i,n,s,a,d;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,tokens:l,request:c}=r,u=t.container(e.ContainerType.REVEAL),h={[we.CARD_NUMBER]:"MASKED",[we.CARDHOLDER_NAME]:"PLAIN_TEXT",[we.EXPIRATION_MONTH]:"PLAIN_TEXT",[we.EXPIRATION_YEAR]:"PLAIN_TEXT"};for(const t of c.fields){const r="string"==typeof t,_=r?t:t.field;if(_===we.CVV){console.warn("[revealCardFields] CVV cannot be revealed (PCI DSS req. 3.2.1). Skipping.");continue}const E=l[_];if(!E){console.warn(`[revealCardFields] No token found for field "${_}", skipping.`);continue}const m=r?{}:t,p=null!==(o=m.container_id)&&void 0!==o?o:`#reveal_${_}`,R=h[_],v=null!==(i=m.styles)&&void 0!==i?i:{},y=null!==(n=c.styles)&&void 0!==n?n:{},f=u.create(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({token:E,redaction:e.RedactionType[R]},void 0!==m.altText&&{altText:m.altText}),void 0!==m.label&&{label:m.label}),v.inputStyles||y.inputStyles?{inputStyles:null!==(s=v.inputStyles)&&void 0!==s?s:y.inputStyles}:{}),v.labelStyles||y.labelStyles?{labelStyles:null!==(a=v.labelStyles)&&void 0!==a?a:y.labelStyles}:{}),v.errorTextStyles||y.errorTextStyles?{errorTextStyles:null!==(d=v.errorTextStyles)&&void 0!==d?d:y.errorTextStyles}:{}));yield st({element:f,containerId:p})}try{yield u.reveal()}catch(e){console.warn("[revealCardFields] reveal completed with errors:",e)}}))}({skyflowInstance:this.skyflowInstance,tokens:this.lastCollectedTokens,request: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 t(this,void 0,void 0,(function*(){try{return yield y(this.coreBaseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw this.reportSdkError(e,{feature:"get-business",metadata:{step:"getBusiness"}}),v({errorCode:d.FETCH_BUSINESS_ERROR},e)}}))}createSkyflowInstance(){return t(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:r,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({coreBaseUrl:r,apiKey:o,vault_id:i,vault_url:n,mode:s}){return t(this,void 0,void 0,(function*(){const a="production"===s?e.Env.PROD:e.Env.DEV;return e.init({vaultID:i,vaultURL:n,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield Fe(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:a}})}))}({vault_id:r,vault_url:o,coreBaseUrl:this.coreBaseUrl,apiKey:this.apiKeyTonder,mode:this.mode})}))}getOpenpayDeviceSessionID(e,r,o){return t(this,void 0,void 0,(function*(){try{return yield x(e,r,o)}catch(e){throw this.reportSdkError(e,{feature:"get-openpay-device-session",metadata:{step:"getOpenpayDeviceSessionID"}}),v({errorCode:d.START_CHECKOUT_ERROR},e)}}))}getSkyflowTokens({vault_id:e,vault_url:r,data:o}){return t(this,void 0,void 0,(function*(){return yield rt({vault_id:e,vault_url:r,data:o,coreBaseUrl:this.coreBaseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:r,isSandbox:o,returnUrl:i}){var n,s,a;return t(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const l=!0===(null===(n=this.merchantData)||void 0===n?void 0:n.core_payments_enabled)&&g(r)?void 0:r,c=yield this._getCustomer(this.abortController.signal),{business:u}=this.merchantData,{auth_token:h,first_name:_="",last_name:E="",email:m=""}=c,p=this._hasCardOnFileKeys();let R,y=null,f=null,C=null,O=!1;const T=()=>t(this,void 0,void 0,(function*(){var e,t;(null===(t=null===(e=this.customerCardsCache)||void 0===e?void 0:e.cards)||void 0===t?void 0:t.length)||(this.customerCardsCache=yield this._getCustomerCards(h,this.merchantData.business.pk))}));if(!l){if("string"==typeof e)if(f=e,R={skyflow_id:e},p){yield T();const t=null===(a=null===(s=this.customerCardsCache)||void 0===s?void 0:s.cards)||void 0===a?void 0:a.find((t=>t.fields.skyflow_id===e));if(!t)throw new Error("Card not found for card-on-file processing");const r=!!t.fields.subscription_id;r||(yield this.collectCardTokens(e)),r&&(y={subscriptionId:t.fields.subscription_id})}else yield this.collectCardTokens(e);else R=yield this.collectCreateCardTokens(),f=R.skyflow_id,p&&(C={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||!C)throw new Error("Missing card data for card-on-file processing");let e=null;try{const t=yield this._saveCustomerCard(h,null==u?void 0:u.pk,{skyflow_id:f},!0);e=t.skyflow_id;const r=t.card_bin;if(!r)throw new Error("Card BIN not returned from save card");const o=yield this._initializeCardOnFile();let i;try{i=yield o.process({cardTokens:C,cardBin:r,contactDetails:{firstName:_||"",lastName:E||"",email:m||""},customerId:h,currency:this.currency||"MXN"})}catch(e){throw v({errorCode:d.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}y={subscriptionId:i.subscriptionId},yield this._saveCustomerCard(h,null==u?void 0:u.pk,{skyflow_id:f,subscription_id:y.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:l,customer:c,isSandbox:o,returnUrl:i,enable_card_on_file:!!(null==y?void 0:y.subscriptionId)&&p})}))}customerRegister(e){return t(this,void 0,void 0,(function*(){try{return yield this._fetchMerchantData(),yield X(this._supportTarget(),this.apiKeyTonder,{email:e},this.abortController.signal)}catch(e){throw this.reportSdkError(e,{feature:"customer-register",metadata:{step:"customerRegister"}}),v({errorCode:d.CUSTOMER_OPERATION_ERROR},e)}}))}createOrder(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield v({response:o,errorCode:d.CREATE_ORDER_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-order",metadata:{step:"createOrder"}}),v({errorCode:d.CREATE_ORDER_ERROR},e)}}))}createPayment(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield v({response:o,errorCode:d.CREATE_PAYMENT_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-payment",metadata:{step:"createPayment"}}),v({errorCode:d.CREATE_PAYMENT_ERROR},e)}}))}startCheckoutRouter(e){return t(this,void 0,void 0,(function*(){const t=yield K(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return t(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return t(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:i,return_url:n,isSandbox:s,metadata:a,currency:l,payment_method:c}=e,u=yield this._fetchMerchantData(),h=yield this.customerRegister(o.email);if(!(h&&"auth_token"in h&&u&&"reference"in u))throw v({errorCode:d.START_CHECKOUT_ERROR,details:{message:"Merchant or customer reposne errors",merchantResult:u,customerResult:h}});{const e={business:this.apiKeyTonder,client:h.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:u.reference,is_oneclick:!0,items:t.items},_=yield this.createOrder(e),E=(new Date).toISOString();if(!("id"in _&&"id"in h&&"business"in u))throw v({errorCode:d.START_CHECKOUT_ERROR,details:{message:"Order response errors",orderResult:_}});{const e={business_pk:u.business.pk,amount:r,date:E,order_id:_.id,client_id:h.id},t=yield this.createPayment(e);let d;const{openpay_keys:m,business:p}=u;m.merchant_id&&m.public_key&&(d=yield x(m.merchant_id,m.public_key,s));const R=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:n,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:d||null,token_id:"",order_id:"id"in _&&_.id,business_id:p.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:a,browser_info:T(),currency:l},c?{payment_method:c}:{card:i}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),v=yield K(this.baseUrl,this.apiKeyTonder,R);if(yield this.init3DSRedirect(v))return v}}}catch(e){throw this.reportSdkError(e,{feature:"start-checkout-router-full",metadata:{step:"startCheckoutRouterFull"}}),v({errorCode:d.START_CHECKOUT_ERROR},e)}}))}registerCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){try{return yield this._fetchMerchantData(),yield J(this._supportTarget(),r,e,A(this.merchantData),Object.assign({},o))}catch(e){throw this.reportSdkError(e,{feature:"register-customer-card",metadata:{step:"registerCustomerCard"}}),v({errorCode:d.SAVE_CARD_ERROR},e)}}))}deleteCustomerCard(e,r=""){return t(this,void 0,void 0,(function*(){try{if(yield this._fetchMerchantData(),"core"===this._supportTarget().engine)return yield G(this._supportTarget(),e,this.secureToken,r,A(this.merchantData)),!0;const t=yield fetch(`${this.baseUrl}/api/v1/business/${A(this.merchantData)}/cards/${r}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(t.ok)return!0;throw yield v({response:t,errorCode:d.REMOVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"delete-customer-card",process_id:r,metadata:{step:"deleteCustomerCard"}}),v({errorCode:d.REMOVE_CARD_ERROR},e)}}))}getActiveAPMs(){return t(this,void 0,void 0,(function*(){try{const e=yield function(e,r,o="?status=active&page_size=10000&country=México",i=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}${n.CORE_PAYMENT_METHODS}${o}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(t.ok)return I(yield t.json());throw yield b(t,d.FETCH_PAYMENT_METHODS_ERROR,"core")}))}(this.coreBaseUrl,this.apiKeyTonder),r=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=r.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},lt(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}export{h as AppError,Ve as BaseInlineCheckout,ct as LiteCheckout,ie as SdkTelemetryClient,$ as validateCVV,B as validateCardNumber,Y as validateCardholderName,H as validateExpirationMonth,q as validateExpirationYear};
|
|
@@ -16,6 +16,10 @@ export declare const API_ENDPOINTS: Readonly<{
|
|
|
16
16
|
ACQ_SUBSCRIPTION_CREATE: "/acq-kushki/subscription/create";
|
|
17
17
|
CORE_BUSINESS_CONFIG: "/transactions/v1/business/config";
|
|
18
18
|
CORE_PROCESS: "/transactions/v1/process";
|
|
19
|
+
CORE_CUSTOMER: "/transactions/v1/customer";
|
|
20
|
+
CORE_CARDS: "/transactions/v1/cards";
|
|
21
|
+
CORE_PAYMENT_METHODS: "/transactions/v1/payment_methods";
|
|
22
|
+
CORE_VAULT_TOKEN: "/transactions/v1/vault-token";
|
|
19
23
|
}>;
|
|
20
24
|
/**
|
|
21
25
|
* Get the full telemetry endpoint URL for a given mode
|