@cuenca-mx/cuenca-js 0.0.1-dev.15 → 0.0.1-dev.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,159 @@
2
2
 
3
3
  `cuenca-js` is a Javascript library client to use Cuenca's services.
4
4
 
5
- ## Installation
6
5
 
7
- ## Documentation
6
+ ## 💻 Installation
7
+
8
+ Using `npm`:
9
+ ```bash
10
+ npm install --save @cuenca-mx/cuenca-js
11
+ ```
12
+
13
+ Using `yarn`:
14
+ ```bash
15
+ yarn add @cuenca-mx/cuenca-js
16
+ ```
17
+
18
+
19
+ ## 🚀 Getting Started
20
+
21
+ ### Configure the client
22
+
23
+ To start using the library, the client must be configured with your credentials. Some configurations can be changed to further improve the use of the library:
24
+
25
+ - Configuring the client on constructor
26
+ The credentials and environment can be set when instantiating the client:
27
+ ```js
28
+ import { Cuenca } from '@cuenca-mx/cuenca-js';
29
+ import { Phase } from '@cuenca-mx/cuenca-js/types';
30
+
31
+ const cuenca = new Cuenca(
32
+ 'SOME_API_KEY',
33
+ 'SOME_API_SECRET',
34
+ Phase.Stage,
35
+ );
36
+ ```
37
+
38
+ - Client's configuration
39
+ The configuration can be changed after creating it using the `configure` method:
40
+ ```js
41
+ import { Cuenca } from '@cuenca-mx/cuenca-js';
42
+ import { Phase } from '@cuenca-mx/cuenca-js/types';
43
+
44
+ const cuenca = new Client();
45
+ // The method will require await if `useJwt` is setted to `true`
46
+ // because a request is made to Cuenca to create the JWT.
47
+ await cuenca.client.configure({
48
+ apiKey: 'SOME_API_KEY',
49
+ apiSecret: 'SOME_API_SECRET',
50
+ loginToken: 'LOGIN_TOKEN',
51
+ phase: Phase.Api, // Production environment
52
+ useJwt: true,
53
+ });
54
+ ```
55
+
56
+ #### Client's configuration values
57
+
58
+ | Configuration Name | Description | Default Value |
59
+ | :---------- | :------------------ | :------: |
60
+ | apiKey | API Key credential | `undefined` |
61
+ | apiSecret | Secret for the API Key | `undefined` |
62
+ | phase | Used to change the environment for the client (production, stage or sandbox) | `Phase.Sandbox` |
63
+ | loginToken | Login Token, sets `X-Cuenca-LoginToken` on each request | `undefined` |
64
+ | useJwt | If `true`, it will create a JWT for authentification | `false` |
65
+
66
+ ### Login
67
+
68
+ After configuring the client, you should login to your user before performing requests on resources:
69
+
70
+ ```js
71
+ const login = await cuenca.userLogins.create('111111'); // Use 6 digit password to login
72
+ console.log(login); // UserLogin model { id: string, lastLoginAt: Date, success: bool }
73
+ ```
74
+
75
+ ### Use Resources
76
+
77
+ Different actions may be performed on each resource depending on which of the following classes they implement:
78
+
79
+ #### Action Classes
80
+ | Name | methods | Description
81
+ | :--- | -----: | ---------: |
82
+ | `Retrievable` | `.retrieve(id)` | Retrieves the resource's model given an ID |
83
+ | `Creatable` | Implementation varies* | Creates the resource from a given data |
84
+ | `Updateable` | Implementation varies* | Updates a resource given its ID and data |
85
+ | `Deactivable` | Implementation varies* | Deactivates the resource given its ID |
86
+ | `Downloadable` | `.pdf()`, `.xml()` | Returns the byte string of a document given its ID |
87
+ | `Queryable` | `.one()`, `.first()`, `.count()`, `.all()` | Perform different types of queries on resources |
88
+
89
+ * *Some resources may have a different implementation of some actions, for more detail check the source code (better documentation is a WIP).
90
+
91
+ #### Resources
92
+ | Name | Actions |
93
+ | :---- | ---------: |
94
+ | accounts | `Queryable`, `Retrievable` |
95
+ | apiKeys | `Creatable`, `Deactivable`, `Queryable`, `Retrievable`, `Updateable` |
96
+ | arpc | `Creatable` |
97
+ | accounts | `Queryable`, `Retrievable` |
98
+ | balanceEntries | `Queryable`, `Retrievable` |
99
+ | billPayments | `Queryable`, `Retrievable` |
100
+ | cardActivations | `Creatable` |
101
+ | cards | `Creatable`, `Deactivable`, `Queryable`, `Retrievable`, `Updateable` |
102
+ | cardTransactions | `Queryable`, `Retrievable` |
103
+ | cardValidations | `Creatable` |
104
+ | commissions | `Queryable`, `Retrievable` |
105
+ | deposits | `Queryable`, `Retrievable` |
106
+ | loginTokens | `Creatable` |
107
+ | savings | `Creatable`, `Deactivable`, `Queryable`, `Retrievable`, `Updateable` |
108
+ | serviceProviders | `Queryable`, `Retrievable` |
109
+ | statements | `Downloadable`, `Queryable` |
110
+ | transfers | `Creatable`, `Queryable`, `Retrievable` |
111
+ | userCredentials | `Creatable`, `Updateable` |
112
+ | userLogins | `Creatable`, `Deactivable` |
113
+ | walletTransactions | `Creatable`, `Queryable`, `Retrievable` |
114
+ | whatsAppTransfers | `Queryable`, `Retrievable` |
115
+
116
+ ### Example:
117
+ ```js
118
+ import { AccountQuery } from '@cuenca-mx/cuenca-js/types';
119
+
120
+ let account;
121
+ account = await cuenca.accounts.first(); // Returns the first value found on the query
122
+
123
+ try {
124
+ // Throws an error if no result was found or if more than one result were found.
125
+ account = await cuenca.accounts.one(
126
+ new AccountQuery({
127
+ accountNumber: 'SOME_ACCOUNT_NUMBER',
128
+ }),
129
+ );
130
+ } catch (error) {
131
+ console.log(error);
132
+ }
133
+ ```
134
+
135
+ ## 💡 Contribute
136
+
137
+ ### Found a bug?
138
+
139
+ Please submit an issue and how to replicate it.
140
+
141
+ ### Want to contribute?
142
+
143
+ Fork the repo and send your PR so we can review it! Any and all help is welcomed, just keep in mind:
144
+
145
+ #### Testing
146
+
147
+ Be sure to keep coverage at least 99%
148
+
149
+
150
+ ## Contact
151
+
152
+ dev@cuenca.com
153
+
154
+ ---
155
+ Developed and maintained with 💙 by [Cuenca](https://github.com/cuenca-mx)
156
+ <p align="center">
157
+ <a href="https://cuenca.com/">
158
+ <img alt="Cuenca Logo" src="https://user-images.githubusercontent.com/23020655/150851002-0de97274-117b-4da4-93b7-e89d7c699793.svg" width="200" />
159
+ </a>
160
+ </p>
@@ -6,9 +6,8 @@ const dateToUTC = (date) => {
6
6
  return new Date(dateObj.getTime());
7
7
  };
8
8
 
9
- const enumValueFromString = (enumValue, value) => {
10
- return Object.values(enumValue).find((enumV) => enumV.value === value);
11
- };
9
+ const enumValueFromString = (enumValue, value) =>
10
+ Object.values(enumValue).find((enumV) => enumV.value === value);
12
11
 
13
12
  exports.dateToUTC = dateToUTC;
14
13
  exports.enumValueFromString = enumValueFromString;
@@ -4,8 +4,7 @@ const dateToUTC = (date) => {
4
4
  return new Date(dateObj.getTime());
5
5
  };
6
6
 
7
- const enumValueFromString = (enumValue, value) => {
8
- return Object.values(enumValue).find((enumV) => enumV.value === value);
9
- };
7
+ const enumValueFromString = (enumValue, value) =>
8
+ Object.values(enumValue).find((enumV) => enumV.value === value);
10
9
 
11
10
  export { dateToUTC as d, enumValueFromString as e };
package/build/index.cjs CHANGED
@@ -3,15 +3,30 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var axios = require('axios');
6
+ var Buffer = require('buffer');
6
7
  var errors_index = require('./errors/index.cjs');
7
- var jwt_index = require('./jwt-74080def.cjs');
8
- var queries = require('./queries-35cba2f2.cjs');
9
- var data = require('./data-c83462d7.cjs');
10
- var walletTransactionRequest = require('./walletTransactionRequest-4542a70e.cjs');
8
+ var jwt_index = require('./jwt/index.cjs');
9
+ var queries = require('./queries-0c03273e.cjs');
10
+ var data = require('./data-9edbb2a0.cjs');
11
+ var walletTransactionRequest = require('./walletTransactionRequest-f549e991.cjs');
11
12
 
12
13
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
13
14
 
14
15
  var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
16
+ var Buffer__default = /*#__PURE__*/_interopDefaultLegacy(Buffer);
17
+
18
+ /* global window */
19
+
20
+ const isBrowser =
21
+ typeof window !== 'undefined' && typeof window.document !== 'undefined';
22
+
23
+ const isNode =
24
+ typeof process !== 'undefined' &&
25
+ Object.prototype.toString.call(process) === '[object process]';
26
+
27
+ const runtimeEnv = { isBrowser, isNode };
28
+
29
+ const name="@cuenca-mx/cuenca-js";const version="0.0.1-dev.19";const description="Cuenca client for JS";const main="./build/index.cjs";const module$1="./build/index.mjs";const browser="./build/umd/cuenca.umd.js";const files=["build/**/*"];const exports$1={".":{"import":"./build/index.mjs",require:"./build/index.cjs"},"./errors":{"import":"./build/errors/index.mjs",require:"./build/errors/index.cjs"},"./jwt":{"import":"./build/jwt/index.mjs",require:"./build/jwt/index.cjs"},"./requests":{"import":"./build/requests/index.mjs",require:"./build/requests/index.cjs"},"./types":{"import":"./build/types/index.mjs",require:"./build/types/index.cjs"}};const packageManager="yarn@3.0.2";const type="module";const repository={type:"git",url:"https://github.com/cuenca-mx/cuenca-js.git",directory:"packages/cuenca-js"};const keywords=["cuenca"];const license="MIT";const bugs={url:"https://github.com/cuenca-mx/cuenca-js/issues"};const homepage="https://cuenca.com";const scripts={build:"rm -rf build/ && yarn rollup --config",test:"yarn node --experimental-vm-modules $(yarn bin jest)",publish:"yarn build && yarn npm publish"};const devDependencies={"@rollup/plugin-json":"^4.1.0","@rollup/plugin-node-resolve":"^13.1.1",jest:"^27.4.5",rollup:"^2.61.1","rollup-plugin-terser":"^7.0.2"};const dependencies={axios:"^0.24.0",buffer:"^6.0.3"};var pkg = {name:name,version:version,description:description,main:main,module:module$1,browser:browser,files:files,exports:exports$1,packageManager:packageManager,type:type,repository:repository,keywords:keywords,license:license,bugs:bugs,homepage:homepage,scripts:scripts,devDependencies:devDependencies,dependencies:dependencies};
15
30
 
16
31
  class Client {
17
32
  constructor({ apiKey, apiSecret, phase = queries.Phase.Sandbox } = {}) {
@@ -32,20 +47,10 @@ class Client {
32
47
  get authHeader() {
33
48
  const { apiKey, apiSecret } = this.basicAuth;
34
49
  if (!apiKey || !apiSecret) return '';
35
-
36
- let authHeader;
37
- if (jwt_index.isNode) {
38
- authHeader = `Basic ${Buffer.from(
39
- `${apiKey}:${apiSecret}`,
40
- 'utf-8',
41
- ).toString('base64')}`;
42
- } else if (jwt_index.isBrowser) {
43
- authHeader = `Basic ${btoa(
44
- `${apiKey}:${unescape(encodeURIComponent(apiSecret))}`,
45
- )}`;
46
- }
47
-
48
- return authHeader;
50
+ return `Basic ${Buffer__default["default"].Buffer.from(
51
+ `${apiKey}:${apiSecret}`,
52
+ 'utf-8',
53
+ ).toString('base64')}`;
49
54
  }
50
55
 
51
56
  addHeadersToRequest(obj) {
@@ -130,11 +135,18 @@ class Client {
130
135
  }) {
131
136
  const headers = {
132
137
  Authorization: this.authHeader,
133
- 'X-User-Agent': `cuenca-js/0.0.1`, // TODO: Change for client version
134
138
  'Content-Type': 'application/json',
135
139
  Accept: `application/${format.value}`,
136
140
  };
137
141
 
142
+ if (runtimeEnv.isNode) {
143
+ headers['User-Agent'] = `cuenca-js/${pkg.version}`;
144
+ } else if (runtimeEnv.isBrowser) {
145
+ // Cannot set User-Agent header on browsers
146
+ // https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
147
+ headers['X-User-Agent'] = `cuenca-js/${pkg.version}`;
148
+ }
149
+
138
150
  if (this.jwtToken) {
139
151
  if (this.jwtToken.isExpired) {
140
152
  this.jwtToken = await jwt_index.Jwt.create(this);
@@ -309,7 +321,13 @@ class BillPayment extends Transaction {
309
321
  status,
310
322
  userId,
311
323
  }) {
312
- super({ amount, createdAt, descriptor, status, userId });
324
+ super({
325
+ amount,
326
+ createdAt,
327
+ descriptor,
328
+ status,
329
+ userId,
330
+ });
313
331
  this.accountNumber = accountNumber;
314
332
  this.id = id;
315
333
  this.providerUri = providerUri;
@@ -423,7 +441,13 @@ class CardTransaction extends Transaction {
423
441
  type,
424
442
  userId,
425
443
  }) {
426
- super({ amount, createdAt, descriptor, status, userId });
444
+ super({
445
+ amount,
446
+ createdAt,
447
+ descriptor,
448
+ status,
449
+ userId,
450
+ });
427
451
  this.cardErrorType = data.enumValueFromString(queries.CardErrorType, cardErrorType);
428
452
  this.cardLastFour = cardLastFour;
429
453
  this.cardType = data.enumValueFromString(queries.CardType, cardType);
@@ -520,7 +544,13 @@ class Commission extends Transaction {
520
544
  type,
521
545
  userId,
522
546
  }) {
523
- super({ amount, createdAt, descriptor, status, userId });
547
+ super({
548
+ amount,
549
+ createdAt,
550
+ descriptor,
551
+ status,
552
+ userId,
553
+ });
524
554
  this.relatedTransactionUri = relatedTransactionUri;
525
555
  this.type = data.enumValueFromString(queries.CommissionType, type);
526
556
  }
@@ -549,7 +579,13 @@ class Deposit extends Transaction {
549
579
  trackingKey,
550
580
  userId,
551
581
  }) {
552
- super({ amount, createdAt, descriptor, status, userId });
582
+ super({
583
+ amount,
584
+ createdAt,
585
+ descriptor,
586
+ status,
587
+ userId,
588
+ });
553
589
  this.id = id;
554
590
  this.network = data.enumValueFromString(queries.DepositNetwork, network);
555
591
  this.sourceUri = sourceUri;
@@ -602,7 +638,14 @@ class Saving extends Wallet {
602
638
  userId,
603
639
  updatedAt,
604
640
  }) {
605
- super({ balance, createdAt, deactivatedAt, id, userId, updatedAt });
641
+ super({
642
+ balance,
643
+ createdAt,
644
+ deactivatedAt,
645
+ id,
646
+ userId,
647
+ updatedAt,
648
+ });
606
649
  this.category = data.enumValueFromString(queries.SavingCategory, category);
607
650
  this.goalAmount = goalAmount;
608
651
  this.goalDate = data.dateToUTC(goalDate);
@@ -681,7 +724,13 @@ class Transfer extends Transaction {
681
724
  updatedAt,
682
725
  userId,
683
726
  }) {
684
- super({ amount, createdAt, descriptor, status, userId });
727
+ super({
728
+ amount,
729
+ createdAt,
730
+ descriptor,
731
+ status,
732
+ userId,
733
+ });
685
734
  this.accountNumber = accountNumber;
686
735
  this.destinationUri = destinationUri;
687
736
  this.id = id;
@@ -753,7 +802,13 @@ class WalletTransaction extends Transaction {
753
802
  userId,
754
803
  walletUri,
755
804
  }) {
756
- super({ amount, createdAt, descriptor, status, userId });
805
+ super({
806
+ amount,
807
+ createdAt,
808
+ descriptor,
809
+ status,
810
+ userId,
811
+ });
757
812
  this.id = id;
758
813
  this.transactionType = data.enumValueFromString(
759
814
  queries.WalletTransactionType,
@@ -792,7 +847,13 @@ class WhatsAppTransfer extends Transaction {
792
847
  updatedAt,
793
848
  userId,
794
849
  }) {
795
- super({ amount, createdAt, descriptor, status, userId });
850
+ super({
851
+ amount,
852
+ createdAt,
853
+ descriptor,
854
+ status,
855
+ userId,
856
+ });
796
857
  this.claimUrl = claimUrl;
797
858
  this.destinationUri = destinationUri;
798
859
  this.id = id;
@@ -1488,42 +1549,4 @@ class Cuenca {
1488
1549
  }
1489
1550
  }
1490
1551
 
1491
- exports.CuencaException = errors_index.CuencaException;
1492
- exports.CuencaResponseException = errors_index.CuencaResponseException;
1493
- exports.InvalidPassword = errors_index.InvalidPassword;
1494
- exports.MalformedJwtToken = errors_index.MalformedJwtToken;
1495
- exports.MultipleResultsFound = errors_index.MultipleResultsFound;
1496
- exports.NoResultFound = errors_index.NoResultFound;
1497
- exports.ValidationError = errors_index.ValidationError;
1498
- exports.Jwt = jwt_index.Jwt;
1499
- exports.AccountQuery = queries.AccountQuery;
1500
- exports.ApiKeyQuery = queries.ApiKeyQuery;
1501
- exports.BalanceEntryQuery = queries.BalanceEntryQuery;
1502
- exports.BillPaymentQuery = queries.BillPaymentQuery;
1503
- exports.CardErrorType = queries.CardErrorType;
1504
- exports.CardFundingType = queries.CardFundingType;
1505
- exports.CardIssuer = queries.CardIssuer;
1506
- exports.CardStatus = queries.CardStatus;
1507
- exports.CardTransactionQuery = queries.CardTransactionQuery;
1508
- exports.CardTransactionType = queries.CardTransactionType;
1509
- exports.CardType = queries.CardType;
1510
- exports.CardsQuery = queries.CardsQuery;
1511
- exports.CommissionType = queries.CommissionType;
1512
- exports.DepositNetwork = queries.DepositNetwork;
1513
- exports.DepositQuery = queries.DepositQuery;
1514
- exports.EntryType = queries.EntryType;
1515
- exports.FileFormat = queries.FileFormat;
1516
- exports.PageSize = queries.PageSize;
1517
- exports.Phase = queries.Phase;
1518
- exports.QueryParams = queries.QueryParams;
1519
- exports.SavingCategory = queries.SavingCategory;
1520
- exports.ServiceProviderCategory = queries.ServiceProviderCategory;
1521
- exports.StatementQuery = queries.StatementQuery;
1522
- exports.TrackDataMethod = queries.TrackDataMethod;
1523
- exports.TransactionStatus = queries.TransactionStatus;
1524
- exports.TransferNetwork = queries.TransferNetwork;
1525
- exports.TransferQuery = queries.TransferQuery;
1526
- exports.WalletQuery = queries.WalletQuery;
1527
- exports.WalletTransactionQuery = queries.WalletTransactionQuery;
1528
- exports.WalletTransactionType = queries.WalletTransactionType;
1529
1552
  exports.Cuenca = Cuenca;
package/build/index.mjs CHANGED
@@ -1,12 +1,23 @@
1
1
  import axios from 'axios';
2
+ import Buffer from 'buffer';
2
3
  import { CuencaResponseException, CuencaException, NoResultFound, MultipleResultsFound, InvalidPassword } from './errors/index.mjs';
3
- export { CuencaException, CuencaResponseException, InvalidPassword, MalformedJwtToken, MultipleResultsFound, NoResultFound, ValidationError } from './errors/index.mjs';
4
- import { i as isNode, a as isBrowser, J as Jwt } from './jwt-8d032723.mjs';
5
- export { J as Jwt } from './jwt-8d032723.mjs';
6
- import { P as Phase, F as FileFormat, E as EntryType, T as TransactionStatus, C as CardIssuer, a as CardStatus, b as CardType, c as CardFundingType, d as CardErrorType, e as CardTransactionType, f as CommissionType, D as DepositNetwork, S as SavingCategory, g as ServiceProviderCategory, h as TransferNetwork, W as WalletTransactionType, A as AccountQuery, i as ApiKeyQuery, B as BalanceEntryQuery, j as BillPaymentQuery, k as CardsQuery, l as CardTransactionQuery, Q as QueryParams, m as DepositQuery, n as WalletQuery, o as StatementQuery, p as TransferQuery, q as WalletTransactionQuery } from './queries-b9cd3fd7.mjs';
7
- export { A as AccountQuery, i as ApiKeyQuery, B as BalanceEntryQuery, j as BillPaymentQuery, d as CardErrorType, c as CardFundingType, C as CardIssuer, a as CardStatus, l as CardTransactionQuery, e as CardTransactionType, b as CardType, k as CardsQuery, f as CommissionType, D as DepositNetwork, m as DepositQuery, E as EntryType, F as FileFormat, s as PageSize, P as Phase, Q as QueryParams, S as SavingCategory, g as ServiceProviderCategory, o as StatementQuery, r as TrackDataMethod, T as TransactionStatus, h as TransferNetwork, p as TransferQuery, n as WalletQuery, q as WalletTransactionQuery, W as WalletTransactionType } from './queries-b9cd3fd7.mjs';
8
- import { d as dateToUTC, e as enumValueFromString } from './data-c1851484.mjs';
9
- import { A as ApiKeyUpdateRequest, a as ArpcRequest, C as CardActivationRequest, b as CardRequest, c as CardUpdateRequest, d as CardValidationRequest, S as SavingRequest, T as TransferRequest, U as UserCredentialRequest, e as UserCredentialUpdateRequest, f as UserLoginRequest, W as WalletTransactionRequest } from './walletTransactionRequest-281c0a96.mjs';
4
+ import { Jwt } from './jwt/index.mjs';
5
+ import { P as Phase, F as FileFormat, E as EntryType, T as TransactionStatus, C as CardIssuer, a as CardStatus, b as CardType, c as CardFundingType, d as CardErrorType, e as CardTransactionType, f as CommissionType, D as DepositNetwork, S as SavingCategory, g as ServiceProviderCategory, h as TransferNetwork, W as WalletTransactionType, A as AccountQuery, i as ApiKeyQuery, B as BalanceEntryQuery, j as BillPaymentQuery, k as CardsQuery, l as CardTransactionQuery, Q as QueryParams, m as DepositQuery, n as WalletQuery, o as StatementQuery, p as TransferQuery, q as WalletTransactionQuery } from './queries-c73144c4.mjs';
6
+ import { d as dateToUTC, e as enumValueFromString } from './data-d5bcb7c8.mjs';
7
+ import { A as ApiKeyUpdateRequest, a as ArpcRequest, C as CardActivationRequest, b as CardRequest, c as CardUpdateRequest, d as CardValidationRequest, S as SavingRequest, T as TransferRequest, U as UserCredentialRequest, e as UserCredentialUpdateRequest, f as UserLoginRequest, W as WalletTransactionRequest } from './walletTransactionRequest-60d3cf69.mjs';
8
+
9
+ /* global window */
10
+
11
+ const isBrowser =
12
+ typeof window !== 'undefined' && typeof window.document !== 'undefined';
13
+
14
+ const isNode =
15
+ typeof process !== 'undefined' &&
16
+ Object.prototype.toString.call(process) === '[object process]';
17
+
18
+ const runtimeEnv = { isBrowser, isNode };
19
+
20
+ const name="@cuenca-mx/cuenca-js";const version="0.0.1-dev.19";const description="Cuenca client for JS";const main="./build/index.cjs";const module="./build/index.mjs";const browser="./build/umd/cuenca.umd.js";const files=["build/**/*"];const exports={".":{"import":"./build/index.mjs",require:"./build/index.cjs"},"./errors":{"import":"./build/errors/index.mjs",require:"./build/errors/index.cjs"},"./jwt":{"import":"./build/jwt/index.mjs",require:"./build/jwt/index.cjs"},"./requests":{"import":"./build/requests/index.mjs",require:"./build/requests/index.cjs"},"./types":{"import":"./build/types/index.mjs",require:"./build/types/index.cjs"}};const packageManager="yarn@3.0.2";const type="module";const repository={type:"git",url:"https://github.com/cuenca-mx/cuenca-js.git",directory:"packages/cuenca-js"};const keywords=["cuenca"];const license="MIT";const bugs={url:"https://github.com/cuenca-mx/cuenca-js/issues"};const homepage="https://cuenca.com";const scripts={build:"rm -rf build/ && yarn rollup --config",test:"yarn node --experimental-vm-modules $(yarn bin jest)",publish:"yarn build && yarn npm publish"};const devDependencies={"@rollup/plugin-json":"^4.1.0","@rollup/plugin-node-resolve":"^13.1.1",jest:"^27.4.5",rollup:"^2.61.1","rollup-plugin-terser":"^7.0.2"};const dependencies={axios:"^0.24.0",buffer:"^6.0.3"};var pkg = {name:name,version:version,description:description,main:main,module:module,browser:browser,files:files,exports:exports,packageManager:packageManager,type:type,repository:repository,keywords:keywords,license:license,bugs:bugs,homepage:homepage,scripts:scripts,devDependencies:devDependencies,dependencies:dependencies};
10
21
 
11
22
  class Client {
12
23
  constructor({ apiKey, apiSecret, phase = Phase.Sandbox } = {}) {
@@ -27,20 +38,10 @@ class Client {
27
38
  get authHeader() {
28
39
  const { apiKey, apiSecret } = this.basicAuth;
29
40
  if (!apiKey || !apiSecret) return '';
30
-
31
- let authHeader;
32
- if (isNode) {
33
- authHeader = `Basic ${Buffer.from(
34
- `${apiKey}:${apiSecret}`,
35
- 'utf-8',
36
- ).toString('base64')}`;
37
- } else if (isBrowser) {
38
- authHeader = `Basic ${btoa(
39
- `${apiKey}:${unescape(encodeURIComponent(apiSecret))}`,
40
- )}`;
41
- }
42
-
43
- return authHeader;
41
+ return `Basic ${Buffer.Buffer.from(
42
+ `${apiKey}:${apiSecret}`,
43
+ 'utf-8',
44
+ ).toString('base64')}`;
44
45
  }
45
46
 
46
47
  addHeadersToRequest(obj) {
@@ -125,11 +126,18 @@ class Client {
125
126
  }) {
126
127
  const headers = {
127
128
  Authorization: this.authHeader,
128
- 'X-User-Agent': `cuenca-js/0.0.1`, // TODO: Change for client version
129
129
  'Content-Type': 'application/json',
130
130
  Accept: `application/${format.value}`,
131
131
  };
132
132
 
133
+ if (runtimeEnv.isNode) {
134
+ headers['User-Agent'] = `cuenca-js/${pkg.version}`;
135
+ } else if (runtimeEnv.isBrowser) {
136
+ // Cannot set User-Agent header on browsers
137
+ // https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
138
+ headers['X-User-Agent'] = `cuenca-js/${pkg.version}`;
139
+ }
140
+
133
141
  if (this.jwtToken) {
134
142
  if (this.jwtToken.isExpired) {
135
143
  this.jwtToken = await Jwt.create(this);
@@ -304,7 +312,13 @@ class BillPayment extends Transaction {
304
312
  status,
305
313
  userId,
306
314
  }) {
307
- super({ amount, createdAt, descriptor, status, userId });
315
+ super({
316
+ amount,
317
+ createdAt,
318
+ descriptor,
319
+ status,
320
+ userId,
321
+ });
308
322
  this.accountNumber = accountNumber;
309
323
  this.id = id;
310
324
  this.providerUri = providerUri;
@@ -418,7 +432,13 @@ class CardTransaction extends Transaction {
418
432
  type,
419
433
  userId,
420
434
  }) {
421
- super({ amount, createdAt, descriptor, status, userId });
435
+ super({
436
+ amount,
437
+ createdAt,
438
+ descriptor,
439
+ status,
440
+ userId,
441
+ });
422
442
  this.cardErrorType = enumValueFromString(CardErrorType, cardErrorType);
423
443
  this.cardLastFour = cardLastFour;
424
444
  this.cardType = enumValueFromString(CardType, cardType);
@@ -515,7 +535,13 @@ class Commission extends Transaction {
515
535
  type,
516
536
  userId,
517
537
  }) {
518
- super({ amount, createdAt, descriptor, status, userId });
538
+ super({
539
+ amount,
540
+ createdAt,
541
+ descriptor,
542
+ status,
543
+ userId,
544
+ });
519
545
  this.relatedTransactionUri = relatedTransactionUri;
520
546
  this.type = enumValueFromString(CommissionType, type);
521
547
  }
@@ -544,7 +570,13 @@ class Deposit extends Transaction {
544
570
  trackingKey,
545
571
  userId,
546
572
  }) {
547
- super({ amount, createdAt, descriptor, status, userId });
573
+ super({
574
+ amount,
575
+ createdAt,
576
+ descriptor,
577
+ status,
578
+ userId,
579
+ });
548
580
  this.id = id;
549
581
  this.network = enumValueFromString(DepositNetwork, network);
550
582
  this.sourceUri = sourceUri;
@@ -597,7 +629,14 @@ class Saving extends Wallet {
597
629
  userId,
598
630
  updatedAt,
599
631
  }) {
600
- super({ balance, createdAt, deactivatedAt, id, userId, updatedAt });
632
+ super({
633
+ balance,
634
+ createdAt,
635
+ deactivatedAt,
636
+ id,
637
+ userId,
638
+ updatedAt,
639
+ });
601
640
  this.category = enumValueFromString(SavingCategory, category);
602
641
  this.goalAmount = goalAmount;
603
642
  this.goalDate = dateToUTC(goalDate);
@@ -676,7 +715,13 @@ class Transfer extends Transaction {
676
715
  updatedAt,
677
716
  userId,
678
717
  }) {
679
- super({ amount, createdAt, descriptor, status, userId });
718
+ super({
719
+ amount,
720
+ createdAt,
721
+ descriptor,
722
+ status,
723
+ userId,
724
+ });
680
725
  this.accountNumber = accountNumber;
681
726
  this.destinationUri = destinationUri;
682
727
  this.id = id;
@@ -748,7 +793,13 @@ class WalletTransaction extends Transaction {
748
793
  userId,
749
794
  walletUri,
750
795
  }) {
751
- super({ amount, createdAt, descriptor, status, userId });
796
+ super({
797
+ amount,
798
+ createdAt,
799
+ descriptor,
800
+ status,
801
+ userId,
802
+ });
752
803
  this.id = id;
753
804
  this.transactionType = enumValueFromString(
754
805
  WalletTransactionType,
@@ -787,7 +838,13 @@ class WhatsAppTransfer extends Transaction {
787
838
  updatedAt,
788
839
  userId,
789
840
  }) {
790
- super({ amount, createdAt, descriptor, status, userId });
841
+ super({
842
+ amount,
843
+ createdAt,
844
+ descriptor,
845
+ status,
846
+ userId,
847
+ });
791
848
  this.claimUrl = claimUrl;
792
849
  this.destinationUri = destinationUri;
793
850
  this.id = id;
@@ -2,9 +2,54 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- require('../errors/index.cjs');
6
- var jwt_index = require('../jwt-74080def.cjs');
5
+ var Buffer = require('buffer');
6
+ var errors_index = require('../errors/index.cjs');
7
7
 
8
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
9
 
10
+ var Buffer__default = /*#__PURE__*/_interopDefaultLegacy(Buffer);
9
11
 
10
- exports.Jwt = jwt_index.Jwt;
12
+ class Jwt {
13
+ constructor(expiresAt, token) {
14
+ this.expiresAt = expiresAt;
15
+ this.token = token;
16
+ }
17
+
18
+ get isExpired() {
19
+ const today = new Date();
20
+ return (this.expiresAt.valueOf() - today.valueOf()) / 60000 <= 5;
21
+ }
22
+
23
+ static getExpirationDate = (token) => {
24
+ let payload;
25
+ try {
26
+ const [, payloadEncoded] = token.split('.');
27
+ payload = JSON.parse(
28
+ Buffer__default["default"].Buffer.from(`${payloadEncoded}==`, 'base64').toString(),
29
+ );
30
+ } catch (error) {
31
+ throw new errors_index.MalformedJwtToken();
32
+ }
33
+
34
+ const { exp } = payload;
35
+ return new Date(new Date(exp * 1000).toUTCString());
36
+ };
37
+
38
+ static create = async (client) => {
39
+ const currentClient = client;
40
+ currentClient.jwtToken = null;
41
+ // Intercepts requests and removes the header if it includes it
42
+ const tokenInterceptor =
43
+ currentClient.deleteRequestHeader('X-Cuenca-Token');
44
+
45
+ const { token } = await client.post('token', {});
46
+
47
+ // Remove the interceptor to avoid removing the header on all requests
48
+ tokenInterceptor.eject();
49
+
50
+ const expiresAt = Jwt.getExpirationDate(token);
51
+ return new Jwt(expiresAt, token);
52
+ };
53
+ }
54
+
55
+ exports.Jwt = Jwt;
@@ -1,2 +1,47 @@
1
- import '../errors/index.mjs';
2
- export { J as Jwt } from '../jwt-8d032723.mjs';
1
+ import Buffer from 'buffer';
2
+ import { MalformedJwtToken } from '../errors/index.mjs';
3
+
4
+ class Jwt {
5
+ constructor(expiresAt, token) {
6
+ this.expiresAt = expiresAt;
7
+ this.token = token;
8
+ }
9
+
10
+ get isExpired() {
11
+ const today = new Date();
12
+ return (this.expiresAt.valueOf() - today.valueOf()) / 60000 <= 5;
13
+ }
14
+
15
+ static getExpirationDate = (token) => {
16
+ let payload;
17
+ try {
18
+ const [, payloadEncoded] = token.split('.');
19
+ payload = JSON.parse(
20
+ Buffer.Buffer.from(`${payloadEncoded}==`, 'base64').toString(),
21
+ );
22
+ } catch (error) {
23
+ throw new MalformedJwtToken();
24
+ }
25
+
26
+ const { exp } = payload;
27
+ return new Date(new Date(exp * 1000).toUTCString());
28
+ };
29
+
30
+ static create = async (client) => {
31
+ const currentClient = client;
32
+ currentClient.jwtToken = null;
33
+ // Intercepts requests and removes the header if it includes it
34
+ const tokenInterceptor =
35
+ currentClient.deleteRequestHeader('X-Cuenca-Token');
36
+
37
+ const { token } = await client.post('token', {});
38
+
39
+ // Remove the interceptor to avoid removing the header on all requests
40
+ tokenInterceptor.eject();
41
+
42
+ const expiresAt = Jwt.getExpirationDate(token);
43
+ return new Jwt(expiresAt, token);
44
+ };
45
+ }
46
+
47
+ export { Jwt };
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var errors_index = require('./errors/index.cjs');
4
- var data = require('./data-c83462d7.cjs');
4
+ var data = require('./data-9edbb2a0.cjs');
5
5
 
6
6
  class CardErrorType {
7
7
  static Blocked = new CardErrorType('blocked');
@@ -1,5 +1,5 @@
1
1
  import { ValidationError } from './errors/index.mjs';
2
- import { d as dateToUTC } from './data-c1851484.mjs';
2
+ import { d as dateToUTC } from './data-d5bcb7c8.mjs';
3
3
 
4
4
  class CardErrorType {
5
5
  static Blocked = new CardErrorType('blocked');
@@ -2,9 +2,9 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var walletTransactionRequest = require('../walletTransactionRequest-4542a70e.cjs');
5
+ var walletTransactionRequest = require('../walletTransactionRequest-f549e991.cjs');
6
6
  require('../errors/index.cjs');
7
- require('../data-c83462d7.cjs');
7
+ require('../data-9edbb2a0.cjs');
8
8
 
9
9
 
10
10
 
@@ -1,3 +1,3 @@
1
- export { A as ApiKeyUpdateRequest, a as ArpcRequest, C as CardActivationRequest, b as CardRequest, c as CardUpdateRequest, d as CardValidationRequest, S as SavingRequest, T as TransferRequest, U as UserCredentialRequest, e as UserCredentialUpdateRequest, f as UserLoginRequest, W as WalletTransactionRequest } from '../walletTransactionRequest-281c0a96.mjs';
1
+ export { A as ApiKeyUpdateRequest, a as ArpcRequest, C as CardActivationRequest, b as CardRequest, c as CardUpdateRequest, d as CardValidationRequest, S as SavingRequest, T as TransferRequest, U as UserCredentialRequest, e as UserCredentialUpdateRequest, f as UserLoginRequest, W as WalletTransactionRequest } from '../walletTransactionRequest-60d3cf69.mjs';
2
2
  import '../errors/index.mjs';
3
- import '../data-c1851484.mjs';
3
+ import '../data-d5bcb7c8.mjs';
@@ -2,9 +2,9 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var queries = require('../queries-35cba2f2.cjs');
5
+ var queries = require('../queries-0c03273e.cjs');
6
6
  require('../errors/index.cjs');
7
- require('../data-c83462d7.cjs');
7
+ require('../data-9edbb2a0.cjs');
8
8
 
9
9
 
10
10
 
@@ -1,3 +1,3 @@
1
- export { A as AccountQuery, i as ApiKeyQuery, B as BalanceEntryQuery, j as BillPaymentQuery, d as CardErrorType, c as CardFundingType, C as CardIssuer, a as CardStatus, l as CardTransactionQuery, e as CardTransactionType, b as CardType, k as CardsQuery, f as CommissionType, D as DepositNetwork, m as DepositQuery, E as EntryType, F as FileFormat, s as PageSize, P as Phase, Q as QueryParams, S as SavingCategory, g as ServiceProviderCategory, o as StatementQuery, r as TrackDataMethod, T as TransactionStatus, h as TransferNetwork, p as TransferQuery, n as WalletQuery, q as WalletTransactionQuery, W as WalletTransactionType } from '../queries-b9cd3fd7.mjs';
1
+ export { A as AccountQuery, i as ApiKeyQuery, B as BalanceEntryQuery, j as BillPaymentQuery, d as CardErrorType, c as CardFundingType, C as CardIssuer, a as CardStatus, l as CardTransactionQuery, e as CardTransactionType, b as CardType, k as CardsQuery, f as CommissionType, D as DepositNetwork, m as DepositQuery, E as EntryType, F as FileFormat, s as PageSize, P as Phase, Q as QueryParams, S as SavingCategory, g as ServiceProviderCategory, o as StatementQuery, r as TrackDataMethod, T as TransactionStatus, h as TransferNetwork, p as TransferQuery, n as WalletQuery, q as WalletTransactionQuery, W as WalletTransactionType } from '../queries-c73144c4.mjs';
2
2
  import '../errors/index.mjs';
3
- import '../data-c1851484.mjs';
3
+ import '../data-d5bcb7c8.mjs';
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("axios")):"function"==typeof define&&define.amd?define(["exports","axios"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).cuenca={},t.axios)}(this,(function(t,e){"use strict";function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var r=s(e);class i extends Error{constructor(t){super(t),Object.setPrototypeOf(this,i.prototype)}}class a extends i{constructor(t,e){super(`Cuenca Response Error: ${e}`),this.name="CuencaResponseError",this.data=t,this.status=e,Object.setPrototypeOf(this,a.prototype)}}class n extends i{constructor(){super("No results were found"),this.name="NoResultFound",Object.setPrototypeOf(this,n.prototype)}}class c extends i{constructor(){super("One result was expected but multiple were found"),this.name="MultipleResultsFound",Object.setPrototypeOf(this,c.prototype)}}class o extends i{constructor(){super("An invalid JWT token was obtained during authentication"),this.name="MalformedJwtToken",Object.setPrototypeOf(this,o.prototype)}}class d extends i{constructor(){super("Invalid password"),this.name="InvalidPassword",Object.setPrototypeOf(this,d.prototype)}}class u extends Error{constructor(t){super(t),Object.setPrototypeOf(this,u.prototype)}}const h="undefined"!=typeof window&&void 0!==window.document,p="undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process);class l{constructor(t,e){this.expiresAt=t,this.token=e}get isExpired(){const t=new Date;return(this.expiresAt.valueOf()-t.valueOf())/6e4<=5}static getExpirationDate=t=>{let e;try{const[,s]=t.split(".");let r;if(p)r=Buffer.from(`${s}==`,"base64").toString();else{if(!h)throw new o;{const t=btoa(unescape(encodeURIComponent(`${s}==`)));r=decodeURIComponent(escape(atob(t)))}}e=JSON.parse(r)}catch(t){throw new o}const{exp:s}=e;return new Date(new Date(1e3*s).toUTCString())};static create=async t=>{const e=t;e.jwtToken=null;const s=e.deleteRequestHeader("X-Cuenca-Token"),{token:r}=await t.post("token",{});s.eject();const i=l.getExpirationDate(r);return new l(i,r)}}class m{static Blocked=new m("blocked");static Comunication=new m("comunication");static ContactlesAmountLimit=new m("contactles_amount_limit");static FraudDetection=new m("fraud_detection");static FraudDetectionUncertain=new m("fraud_detection_uncertain");static InsufficientFounds=new m("insufficient_founds");static InvalidPin=new m("invalid_pin");static Notification=new m("notification");static NotificationDeactivatedCard=new m("notification_deactivated_card");constructor(t){this.value=t}}class w{static Credit=new w("credit");static Debit=new w("debit");constructor(t){this.value=t}}class _{static Accendo=new _("accendo");static Cuenca=new _("cuenca");constructor(t){this.value=t}}class y{static Active=new y("active");static Blocked=new y("blocked");static Created=new y("created");static Deactivated=new y("deactivated");static Printing=new y("printing");constructor(t){this.value=t}}class v{static Auth=new v("auth");static Capture=new v("capture");static Chargeback=new v("chargeback");static Expiration=new v("expiration");static Refund=new v("refund");static Void=new v("void");constructor(t){this.value=t}}class b{static Physical=new b("physical");static Virtual=new b("virtual");constructor(t){this.value=t}}class g{static CardRequest=new g("card_request");static CashDeposit=new g("cash_deposit");static OutgoingSpei=new g("outgoing_spei");constructor(t){this.value=t}}class f{static Cash=new f("cash");static Internal=new f("internal");static Spei=new f("spei");constructor(t){this.value=t}}class x{static Credit=new x("credit");static Debit=new x("debit");constructor(t){this.value=t}}class j{static Pdf=new j("pdf");static Xml=new j("xml");static Json=new j("json");constructor(t){this.value=t}}class A{static Sandbox=new A("sandbox");static Stage=new A("stage");static Api=new A("api");constructor(t){this.value=t}}class O{static Cable=new O("cable");static CreditCard=new O("credit_card");static Electricity=new O("electricity");static Gas=new O("gas");static Internet=new O("internet");static LandlineTelephone=new O("landline_telephone");static MobileTelephonePostpaid=new O("mobile_telephone_postpaid");static MobileTelephonePrepaid=new O("mobile_telephone_prepaid");static SateliteTelevision=new O("satelite_television");static Water=new O("water");constructor(t){this.value=t}}class I{static General=new I("general");static Home=new I("home");static Vehicle=new I("vehicle");static Travel=new I("travel");static Clothing=new I("clothing");static Other=new I("other");static Medical=new I("medical");static Accident=new I("accident");static Education=new I("education");constructor(t){this.value=t}}class k{static NotSet=new k("not_set");static Terminal=new k("terminal");static Manual=new k("manual");static Unknown=new k("unknown");static Contactless=new k("contactless");static FallBack=new k("fall_back");static MagneticStripe=new k("magnetic_stripe");static RecurringCharge=new k("recurring_charge");constructor(t){this.value=t}}class T{static Created=new T("created");static Failed=new T("failed");static InReview=new T("in_review");static Submitted=new T("submitted");static Succeeded=new T("succeeded");constructor(t){this.value=t}}class C{static Internal=new C("internal");static Spei=new C("spei");constructor(t){this.value=t}}class U{static Deposit=new U("deposit");static Withdrawal=new U("withdrawal");constructor(t){this.value=t}}const S=t=>{if(!t)return null;const e=new Date(t);return new Date(e.getTime())},N=(t,e)=>Object.values(t).find((t=>t.value===e));class E{constructor({createdAfter:t,createdBefore:e,limit:s,pageSize:r,relatedTransaction:i,userId:a,count:n=!1}){this.createdAfter=t,this.createdBefore=e,this._lmt=s,this.relatedTransaction=i,this.userId=a,this.count=n,this.pageSize=r}get limit(){return this._limit}set _lmt(t){let e=null;t&&t>=0&&(e=t),this._limit=e}toObject(){return{created_after:this.createdAfter,created_before:this.createdBefore,limit:this.limit,related_transaction:this.relatedTransaction,user_id:this.userId,page_size:this.pageSize&&this.pageSize.size}}toParams(){const t={...this.toObject()};return this.count&&(t.count=1),Object.keys(t).forEach((e=>{null==t[e]&&delete t[e]})),t}toQueryString(){return new URLSearchParams(this.toParams()).toString()}}class P extends E{constructor({accountNumber:t,...e}){super(e),this.accountNumber=t}toObject(){return Object.assign(super.toObject(),{account_number:this.accountNumber})}}class $ extends E{constructor({active:t,...e}){super(e),this.active=t}toObject(){return Object.assign(super.toObject(),{active:this.active})}}class K extends E{constructor({status:t,...e}){super(e),this.status=t}toObject(){return Object.assign(super.toObject(),{status:this.status})}}class D extends K{constructor({trackingKey:t,network:e,...s}){super(s),this.trackingKey=t,this.network=e}toObject(){return Object.assign(super.toObject(),{tracking_key:this.trackingKey,network:this.network})}}class q extends K{constructor({accountNumber:t,idempotencyKey:e,trackingKey:s,network:r,...i}){super(i),this.accountNumber=t,this.idempotencyKey=e,this.trackingKey=s,this.network=r}toObject(){return Object.assign(super.toObject(),{account_number:this.accountNumber,idempotency_key:this.idempotencyKey,tracking_key:this.trackingKey,network:this.network})}}class M extends E{constructor({fundingInstrumentUri:t,count:e=!1,walletId:s="default",...r}){super(r),this.fundingInstrumentUri=t,this.count=e,this.walletId=s}toObject(){return Object.assign(super.toObject(),{wallet_id:this.walletId,funding_instrument_uri:this.fundingInstrumentUri,count:this.count})}}class B extends E{constructor({accountNumber:t,...e}){super(e),this.accountNumber=t}toObject(){return Object.assign(super.toObject(),{account_number:this.accountNumber})}}class R extends E{constructor({cardUri:t,...e}){super(e),this.cardUri=t}toObject(){return Object.assign(super.toObject(),{card_uri:this.cardUri})}}class V extends E{constructor({cardUri:t,count:e=!1,...s}){super(s),this.cardUri=t,this.count=e}toObject(){return Object.assign(super.toObject(),{card_uri:this.cardUri,count:this.count})}}class Q extends E{constructor({walletUri:t,...e}){super(e),this.walletUri=t}toObject(){return Object.assign(super.toObject(),{wallet_uri:this.walletUri})}}class Y extends E{constructor({active:t,...e}){super(e),this.active=t}toObject(){return Object.assign(super.toObject(),{active:this.active})}}class F extends E{constructor({month:t,year:e,...s}){super(s),this.d={month:t,year:e}}get month(){return this._date.month}get year(){return this._date.year}set d({month:t,year:e}){const s=S(Date.now());s.setUTCDate(1);if(S(`${e}-${t}-01`).getTime()>=s.getTime())throw new u(`${e}-${t} is not a valid year-month pair`);this._date={month:t,year:e}}toObject(){return Object.assign(super.toObject(),{month:this.month,year:this.year})}}class z{constructor({apiKey:t,apiSecret:e,phase:s=A.Sandbox}={}){this.phase=s,this.basicAuth={apiKey:t,apiSecret:e},this.jwtToken=null,this._session=r.default.create()}get session(){return this._session}get origin(){return`https://${this.phase.value}.cuenca.com`}get authHeader(){const{apiKey:t,apiSecret:e}=this.basicAuth;if(!t||!e)return"";let s;return p?s=`Basic ${Buffer.from(`${t}:${e}`,"utf-8").toString("base64")}`:h&&(s=`Basic ${btoa(`${t}:${unescape(encodeURIComponent(e))}`)}`),s}addHeadersToRequest(t){const e=this._session.interceptors.request.use((e=>{const s=e,{headers:{common:r}}=s;return Object.keys(t).forEach((e=>r[e]=t[e])),s}));return{interceptorId:e,eject:()=>this._session.interceptors.request.eject(e)}}deleteRequestHeader(t){const e=this._session.interceptors.request.use((e=>{const s=e,{headers:{common:r}}=s;return delete r[t],s}));return{interceptorId:e,eject:()=>this._session.interceptors.request.eject(e)}}addConfigToRequest(t){const e=this._session.interceptors.request.use((e=>{const s=e;return Object.keys(t).forEach((e=>s[e]=t[e])),s}));return{interceptorId:e,eject:()=>this._session.interceptors.request.eject(e)}}async configure({apiKey:t,apiSecret:e,loginToken:s,phase:r,useJwt:i=!1}){this.basicAuth={apiKey:t||this.basicAuth.apiKey,apiSecret:e||this.basicAuth.apiSecret},r&&(this.phase=r),i&&(this.jwtToken=await l.create(this)),s&&this.addHeadersToRequest({"X-Cuenca-LoginToken":s})}async get({endpoint:t,format:e,params:s}){return this.request({endpoint:t,format:e,params:s})}async post({endpoint:t,data:e}){return this.request({method:"POST",endpoint:t,data:e})}async patch({endpoint:t,data:e}){return this.request({method:"PATCH",endpoint:t,data:e})}async delete({endpoint:t,data:e}){return this.request({method:"DELETE",endpoint:t,data:e})}async request({endpoint:t,data:e=null,format:s=j.Json,method:r="GET",params:n=null}){const c={Authorization:this.authHeader,"X-User-Agent":"cuenca-js/0.0.1","Content-Type":"application/json",Accept:`application/${s.value}`};this.jwtToken&&(this.jwtToken.isExpired&&(this.jwtToken=await l.create(this)),c["X-Cuenca-Token"]=this.jwtToken.token);const o=this.addHeadersToRequest(c),d=e;d&&Object.keys(d).forEach((t=>{d[t]instanceof Date&&(d[t]=d[t].toISOString())}));const u=this.addConfigToRequest({method:r,params:n,data:d,url:t});let h;try{h=await this._session.request({baseURL:this.origin})}catch(t){throw t.response?new a(t.response.data,t.response.status):t.request?new i(`No response received: ${t.errno}: ${t.code}`):new i(t.message)}finally{o.eject(),u.eject()}return h.data}}class H{constructor({accountNumber:t,createdAt:e,id:s,institutionName:r,name:i,userId:a}){this.accountNumber=t,this.createdAt=S(e),this.id=s,this.institutionName=r,this.name=i,this.userId=a}static fromObject=({id:t,name:e,...s})=>new H({id:t,name:e,accountNumber:s.account_number,createdAt:s.created_at,institutionName:s.institution_name,userId:s.user_id})}class L{constructor({createdAt:t,deactivatedAt:e,id:s,secret:r,userId:i,updatedAt:a}){this.createdAt=S(t),this.deactivatedAt=S(e),this.id=s,this.secret=r,this.userId=i,this.updatedAt=S(a)}static fromObject=({id:t,secret:e,...s})=>new L({id:t,secret:e,createdAt:s.created_at,deactivatedAt:s.deactivated_at,userId:s.user_id,updatedAt:s.updated_at});get isActive(){const t=S(Date.now());return!this.deactivatedAt||this.deactivatedAt.getTime()>t.getTime()}}class J{constructor({arpc:t,createdAt:e,cardUri:s,isValidArqc:r}){this.arpc=t,this.createdAt=S(e),this.cardUri=s,this.isValidArqc=r}static fromObject=({arpc:t,...e})=>new J({arpc:t,createdAt:e.created_at,cardUri:e.card_uri,isValidArqc:e.is_valid_arqc})}class W{constructor({amount:t,createdAt:e,descriptor:s,entryType:r,fundingInstrumentUri:i,id:a,name:n,relatedTransactionUri:c,rollingBalance:o}){this.amount=t,this.createdAt=S(e),this.descriptor=s,this.entryType=N(x,r),this.fundingInstrumentUri=i,this.id=a,this.name=n,this.relatedTransactionUri=c,this.rollingBalance=o}static fromObject=({amount:t,descriptor:e,id:s,name:r,type:i,...a})=>new W({amount:t,descriptor:e,name:r,id:s,createdAt:a.created_at,entryType:i,fundingInstrumentUri:a.funding_instrument_uri,relatedTransactionUri:a.related_transaction_uri,rollingBalance:a.rolling_balance})}class X{constructor({amount:t,createdAt:e,descriptor:s,status:r,userId:i}){this.amount=t,this.createdAt=S(e),this.descriptor=s,this.status=N(T,r),this.userId=i}}class G extends X{constructor({amount:t,accountNumber:e,createdAt:s,descriptor:r,id:i,providerUri:a,status:n,userId:c}){super({amount:t,createdAt:s,descriptor:r,status:n,userId:c}),this.accountNumber=e,this.id=i,this.providerUri=a}static fromObject=({amount:t,descriptor:e,id:s,status:r,...i})=>new G({amount:t,descriptor:e,id:s,status:r,accountNumber:i.account_number,createdAt:i.created_at,providerUri:i.provider_uri,userId:i.user_id})}class Z{constructor({createdAt:t,cvv2:e,expMonth:s,expYear:r,fundingType:i,id:a,issuer:n,number:c,pin:o,status:d,type:u,updatedAt:h,userId:p}){this.createdAt=S(t),this.cvv2=e,this.expMonth=s,this.expYear=r,this.fundingType=N(w,i),this.id=a,this.issuer=N(_,n),this.number=c,this.pin=o,this.status=N(y,d),this.type=N(b,u),this.updatedAt=S(h),this.userId=p}static fromObject=({cvv2:t,id:e,issuer:s,number:r,pin:i,status:a,type:n,...c})=>new Z({cvv2:t,id:e,issuer:s,number:r,pin:i,status:a,type:n,createdAt:c.created_at,expMonth:c.exp_month,expYear:c.exp_year,fundingType:c.funding_type,updatedAt:c.updated_at,userId:c.user_id})}class tt{constructor({cardUri:t,createdAt:e,id:s,ipAddress:r,success:i,userId:a}){this.cardUri=t,this.createdAt=S(e),this.id=s,this.ipAddress=r,this.success=i,this.userId=a}static fromObject=({id:t,success:e,...s})=>new tt({id:t,success:e,cardUri:s.card_uri,createdAt:s.created_at,ipAddress:s.ip_address,userId:s.user_id})}class et extends X{constructor({amount:t,cardErrorType:e,cardLastFour:s,cardType:r,cardUri:i,createdAt:a,descriptor:n,metadata:c,network:o,relatedCardTransactionsUris:d,status:u,type:h,userId:p}){super({amount:t,createdAt:a,descriptor:n,status:u,userId:p}),this.cardErrorType=N(m,e),this.cardLastFour=s,this.cardType=N(b,r),this.cardUri=i,this.metadata=c,this.network=o,this.relatedCardTransactionsUris=d,this.type=N(v,h)}static fromObject=({amount:t,descriptor:e,metadata:s,network:r,status:i,type:a,...n})=>new et({amount:t,descriptor:e,metadata:s,network:r,status:i,type:a,cardErrorType:n.error_type,cardLastFour:n.card_last4,cardType:n.card_type,cardUri:n.card_uri,createdAt:n.created_at,relatedCardTransactionsUris:n.related_card_transaction,userId:n.user_id})}class st{constructor({cardStatus:t,cardType:e,cardUri:s,createdAt:r,isExpired:i,isPinAttemptsExceeded:a,isValidCvv:n,isValidCvv2:c,isValidExpDate:o,isValidIcvv:d,isValidPinBlock:u,userId:h}){this.cardStatus=N(y,t),this.cardType=N(b,e),this.cardUri=s,this.createdAt=S(r),this.isExpired=i,this.isPinAttemptsExceeded=a,this.isValidCvv=n,this.isValidCvv2=c,this.isValidExpDate=o,this.isValidIcvv=d,this.isValidPinBlock=u,this.userId=h}static fromObject=({...t})=>new st({cardStatus:t.card_status,cardType:t.card_type,cardUri:t.card_uri,createdAt:t.created_at,isExpired:t.is_expired,isPinAttemptsExceeded:t.is_pin_attempts_exceeded,isValidCvv:t.is_valid_cvv,isValidCvv2:t.is_valid_cvv2,isValidExpDate:t.is_valid_exp_date,isValidIcvv:t.is_valid_icvv,isValidPinBlock:t.is_valid_pin_block,userId:t.user_id});get isActive(){return this.cardStatus===y.Active}}class rt extends X{constructor({amount:t,createdAt:e,descriptor:s,relatedTransactionUri:r,status:i,type:a,userId:n}){super({amount:t,createdAt:e,descriptor:s,status:i,userId:n}),this.relatedTransactionUri=r,this.type=N(g,a)}static fromObject=({amount:t,descriptor:e,status:s,type:r,...i})=>new rt({amount:t,descriptor:e,status:s,type:r,createdAt:i.created_at,relatedTransactionUri:i.related_transaction_uri,userId:i.user_id})}class it extends X{constructor({amount:t,createdAt:e,descriptor:s,id:r,network:i,status:a,sourceUri:n,trackingKey:c,userId:o}){super({amount:t,createdAt:e,descriptor:s,status:a,userId:o}),this.id=r,this.network=N(f,i),this.sourceUri=n,this.trackingKey=c}static fromObject=({amount:t,descriptor:e,id:s,network:r,status:i,...a})=>new it({amount:t,descriptor:e,id:s,network:r,status:i,createdAt:a.created_at,sourceUri:a.source_uri,trackingKey:a.tracking_key,userId:a.user_id})}class at{constructor({id:t}){this.id=t}static fromObject=({id:t})=>new at({id:t})}class nt extends class{constructor({balance:t,createdAt:e,deactivatedAt:s,id:r,userId:i,updatedAt:a}){this.balance=t,this.createdAt=S(e),this.deactivatedAt=S(s),this.id=r,this.userId=i,this.updatedAt=S(a)}}{constructor({balance:t,category:e,createdAt:s,deactivatedAt:r,goalAmount:i,goalDate:a,id:n,name:c,userId:o,updatedAt:d}){super({balance:t,createdAt:s,deactivatedAt:r,id:n,userId:o,updatedAt:d}),this.category=N(I,e),this.goalAmount=i,this.goalDate=S(a),this.name=c}static fromObject=({balance:t,category:e,id:s,name:r,...i})=>new nt({balance:t,category:e,id:s,name:r,createdAt:i.created_at,deactivatedAt:i.deactivated_at,goalAmount:i.goal_amount,goalDate:i.goal_date,userId:i.user_id,updatedAt:i.updated_at})}class ct{constructor({categories:t,id:e,name:s,providerKey:r}){var i;this.categories=null==(i=t)?[]:i.map((t=>N(O,t))),this.id=e,this.name=s,this.providerKey=r}static fromObject=({categories:t,id:e,name:s,...r})=>new ct({categories:t,id:e,name:s,providerKey:r.provider_key})}class ot{constructor({createdAt:t,id:e,month:s,year:r}){this.createdAt=S(t),this.id=e,this.month=s,this.year=r}static fromObject=({id:t,month:e,year:s,...r})=>new ot({id:t,month:e,year:s,createdAt:r.created_at})}class dt extends X{constructor({accountNumber:t,amount:e,createdAt:s,descriptor:r,destinationUri:i,id:a,idempotencyKey:n,network:c,recipientName:o,status:d,trackingKey:u,updatedAt:h,userId:p}){super({amount:e,createdAt:s,descriptor:r,status:d,userId:p}),this.accountNumber=t,this.destinationUri=i,this.id=a,this.idempotencyKey=n,this.network=N(C,c),this.recipientName=o,this.trackingKey=u,this.updatedAt=S(h)}static fromObject=({amount:t,descriptor:e,id:s,network:r,status:i,...a})=>new dt({amount:t,descriptor:e,id:s,network:r,status:i,accountNumber:a.account_number,createdAt:a.created_at,destinationUri:a.destination_uri,idempotencyKey:a.idempotency_key,recipientName:a.recipient_name,trackingKey:a.tracking_key,updatedAt:a.updated_at,userId:a.user_id})}class ut{constructor({createdAt:t,id:e,isActive:s,updatedAt:r}){this.createdAt=S(t),this.id=e,this.isActive=s,this.updatedAt=S(r)}static fromObject=({id:t,...e})=>new ut({id:t,createdAt:e.created_at,isActive:e.is_active,updatedAt:e.updated_at})}class ht{constructor({id:t,lastLoginAt:e,success:s}){this.id=t,this.lastLoginAt=S(e),this.success=s}static fromObject=({id:t,success:e,...s})=>new ht({id:t,success:e,lastLoginAt:s.last_login_at})}class pt extends X{constructor({amount:t,createdAt:e,descriptor:s,id:r,status:i,transactionType:a,userId:n,walletUri:c}){super({amount:t,createdAt:e,descriptor:s,status:i,userId:n}),this.id=r,this.transactionType=N(U,a),this.walletUri=c}static fromObject=({amount:t,descriptor:e,id:s,status:r,...i})=>new pt({amount:t,descriptor:e,id:s,status:r,createdAt:i.created_at,transactionType:i.transaction_type,userId:i.user_id,walletUri:i.wallet_uri})}class lt extends X{constructor({amount:t,claimUrl:e,createdAt:s,descriptor:r,destinationUri:i,expiresAt:a,id:n,network:c,phoneNumber:o,recipientName:d,status:u,trackingKey:h,updatedAt:p,userId:l}){super({amount:t,createdAt:s,descriptor:r,status:u,userId:l}),this.claimUrl=e,this.destinationUri=i,this.id=n,this.expiresAt=S(a),this.network=N(C,c),this.phoneNumber=o,this.recipientName=d,this.trackingKey=h,this.updatedAt=S(p)}static fromObject=({amount:t,descriptor:e,id:s,network:r,status:i,...a})=>new lt({amount:t,descriptor:e,id:s,network:r,status:i,createdAt:a.created_at,claimUrl:a.claim_url,destinationUri:a.destination_uri,expiresAt:a.expires_at,phoneNumber:a.phone_number,recipientName:a.recipient_name,trackingKey:a.tracking_key,updatedAt:a.updated_at,userId:a.user_id})}class mt{constructor(t){this.superclass=t}with(...t){return t.reduce(((t,e)=>e(t)),this.superclass)}}const wt=t=>new mt(t),_t=(t,e)=>({accounts:()=>H.fromObject(e),api_keys:()=>L.fromObject(e),arpc:()=>J.fromObject(e),balance_entries:()=>W.fromObject(e),bill_payments:()=>G.fromObject(e),cards:()=>Z.fromObject(e),card_activations:()=>tt.fromObject(e),card_transactions:()=>et.fromObject(e),card_validations:()=>st.fromObject(e),commissions:()=>rt.fromObject(e),deposits:()=>it.fromObject(e),login_tokens:()=>at.fromObject(e),savings:()=>nt.fromObject(e),service_providers:()=>ct.fromObject(e),statements:()=>ot.fromObject(e),transfers:()=>dt.fromObject(e),user_credentials:()=>ut.fromObject(e),user_logins:()=>ht.fromObject(e),wallet_transactions:()=>pt.fromObject(e),whatsapp_transfers:()=>lt.fromObject(e)}[t]()),yt=t=>{if(null===t||""===t)return null;const e=t.match("/(.*?)/");return null===e?null:e[0].replaceAll("/","")};class vt{constructor(t,e,s){this.path=t,this.QueryParams=e,this.client=s}}const bt=t=>class extends t{async retrieve(t){const e=await this.client.get({endpoint:`/${this.path}/${t}`});return _t(this.path,e)}},gt=t=>class extends t{async _create(t){const e=await this.client.post({endpoint:`/${this.path}`,data:t});return _t(this.path,e)}},ft=t=>class extends t{async _update(t,e){const s=await this.client.patch({endpoint:`/${this.path}/${t}`,data:e});return _t(this.path,s)}},xt=t=>class extends t{async _deactivate(t,e){const s=await this.client.delete({endpoint:`/${this.path}/${t}`,data:e});return _t(this.path,s)}},jt=t=>class extends t{async _download(t,e){return await this.client.get({endpoint:`/${this.path}/${t}`,format:e})}},At=t=>class extends t{async one(t=new this.QueryParams({})){const{items:e}=await this.client.get({endpoint:`/${this.path}`,params:t.toParams()});if(!e||!e.length)throw new n;if(e.length>1)throw new c;const[s]=e;return _t(this.path,s)}async first(t=new this.QueryParams({})){const{items:e}=await this.client.get({endpoint:`/${this.path}`,params:t.toParams()});if(!e||!e[0])return null;const[s]=e;return _t(this.path,s)}async count(t=new this.QueryParams({})){t.count=!0;const{count:e}=await this.client.get({endpoint:`/${this.path}`,params:t.toParams()});return e||0}async*all(t=new this.QueryParams({})){let e=`/${this.path}?${t.toQueryString()}`;for(;e;){const t=await this.client.get({endpoint:e});if(t.items)for(const e of t.items){const t=_t(this.path,e);yield t}e=t.next_page_uri}}};class Ot extends(wt(vt).with(At,bt)){constructor(t){super("accounts",P,t)}}class It{toObject(){return{}}toCleanObject(){const t=this.toObject();return Object.keys(t).forEach((e=>{null==t[e]&&delete t[e]})),t}}class kt extends It{constructor(t,e){super(),this.userId=t,this.metadata=e}toObject(){return{user_id:this.userId,metadata:this.metadata}}}class Tt extends It{constructor(t,e,s){super(),this.userId=t,this.issuer=e,this.fundingType=s}toObject(){return{user_id:this.userId,issuer:this.issuer,funding_type:this.fundingType}}}class Ct extends It{constructor(t,e){super(),this.status=t,this.pinBlock=e}toObject(){return{status:this.status,pin_block:this.pinBlock}}}class Ut extends It{constructor(t,e,s,r){super(),this.n=t,this.eM=e,this.eY=s,this.c2=r}get number(){return this._number}set n(t){if([!!t,16===t.length,/^\d{16}/.test(t)].some((t=>!t)))throw new u("Invalid number");this._number=t.trim()}get expMonth(){return this._expMonth}set eM(t){if([!!t,t>=1,t<=12].some((t=>!t)))throw new u("Invalid expiration month");this._expMonth=t}get expYear(){return this._expYear}set eY(t){if([!!t,t>=18,t<=99].some((t=>!t)))throw new u("Invalid expiration year");this._expYear=t}get cvv2(){return this._cvv2}set c2(t){if([!!t,3===t.length,/^\d{3}/.test(t)].some((t=>!t)))throw new u("Invalid cvv2");this._cvv2=t}toObject(){return{number:this.number,exp_month:this.expMonth,exp_year:this.expYear,cvv2:this.cvv2}}}class St extends It{constructor({cvv:t,cvv2:e,expMonth:s,expYear:r,icvv:i,number:a,pinBlock:n,pinAttemptsExceeded:c}){super(),this.c=t,this.c2=e,this.em=s,this.ey=r,this.ic=i,this.n=a,this.pinBloc=n,this.pinAttemptsExceeded=c}get cvv(){return this._cvv}set c(t){if(!t)return;if([3===t.length].some((t=>!t)))throw new u("Invalid cvv");this._cvv=t}get cvv2(){return this._cvv2}set c2(t){if(!t)return;if([3===t.length].some((t=>!t)))throw new u("Invalid cvv2");this._cvv2=t}get expMonth(){return this._expMonth}set em(t){if(!t)return;if([t>=1,t<=12].some((t=>!t)))throw new u("Invalid expiration month");this._expMonth=t}get expYear(){return this._expYear}set ey(t){if(!t)return;if([t>=18,t<=99].some((t=>!t)))throw new u("Invalid expiration year");this._expYear=t}get icvv(){return this._icvv}set ic(t){if(!t)return;if([3===t.length].some((t=>!t)))throw new u("Invalid icvv");this._icvv=t}get number(){return this._number}set n(t){if([!!t,16===t.length,/^\d{16}/.test(t)].some((t=>!t)))throw new u("Invalid number");this._number=t}toObject(){return{cvv:this.cvv,cvv2:this.cvv2,exp_month:this.expMonth,exp_year:this.expYear,icvv:this.icvv,number:this.number,pin_block:this.pinBloc,pin_attempts_exceeded:this.pinAttemptsExceeded}}}class Nt extends It{constructor(t,e,s,r){super(),this.category=t,this.name=r,this.goalAmount=e,this.validDate=s}get goalDate(){return this._goalDate}set validDate(t){if(t){if(S(t).getTime()<=S(Date.now()).getTime())throw new u("The goal_date always need to be higher than now");this._goalDate=t}}toObject(){return{category:this.category,goal_amount:this.goalAmount,goal_date:this.goalDate,name:this.name}}}class Et extends It{constructor(t,e,s,r,i){super(),this.accountNumber=t,this.amount=e,this.descriptor=s,this.idempotencyKey=r,this.recipientName=i}toObject(){return{account_number:this.accountNumber,amount:this.amount,descriptor:this.descriptor,idempotency_key:this.idempotencyKey,recipient_name:this.recipientName}}}class Pt extends It{constructor(t){super(),this.pwd=t}get password(){return this._password}set pwd(t){if([!!t,6===t.length,/^\d{6}$/.test(t)].some((t=>!t)))throw new u("Invalid password");this._password=t}toObject(){return{password:this.password}}}class $t extends It{constructor(t,e){super(),this.pwd=t,this.isActive=e,this.req={password:this.password,isActive:this.isActive}}get password(){return this._password}get request(){return this._request}set pwd(t){if(!t)return void(this._password=t);if([6===t.length,/^\d{6}$/.test(t)].some((t=>!t)))throw new u("Invalid password");this._password=t}set req(t){if(t.password&&null!=t.isActive)throw new u("Only one property can be updated at a time");this._request=t}toObject(){return{password:this.request.password,is_active:this.request.isActive}}}class Kt extends It{constructor(t,e="me"){super(),this.pwd=t,this.userId=e}get password(){return this._password}set pwd(t){if([!!t,6===t.length,/^\d{6}$/.test(t)].some((t=>!t)))throw new u("Invalid password");this._password=t}toObject(){return{password:this.password,user_id:this.userId}}}class Dt extends It{constructor(t,e,s){super(),this.amount=t,this.transactionType=e,this.walletUri=s}toObject(){return{amount:this.amount,transaction_type:this.transactionType,wallet_uri:this.walletUri}}}class qt extends(wt(vt).with(gt,xt,At,bt,ft)){constructor(t){super("api_keys",$,t)}async create(){return await this._create()}async deactivate(t,e=0){return await this._deactivate(t,{minutes:e})}async update(t,e,s){const r=new kt(s,e);return await this._update(t,r.toCleanObject())}}wt(vt).with(gt);class Mt extends(wt(vt).with(At,bt)){constructor(t){super("balance_entries",M,t)}async relatedTransaction(t){const e=yt(t);if(null==e)return null;const s=await this.client.get({endpoint:t});return _t(`${e}`,s)}async fundingInstrument(t){const e=yt(t);if(null==e)return null;const s=await this.client.get({endpoint:t});return _t(`${e}`,s)}}class Bt extends(wt(vt).with(At,bt)){constructor(t){super("bill_payments",B,t)}async serviceProvider(t){const e=yt(t);if(null==e)return null;const s=await this.client.get({endpoint:t});return _t(`${e}`,s)}}class Rt extends(wt(vt).with(gt)){constructor(t){super("card_activations",Object,t)}async create({number:t,expMonth:e,expYear:s,cvv2:r}){const i=new Ut(t,e,s,r);return await this._create(i.toCleanObject())}async card(t){if(!t)return null;const e=await this.client.get({endpoint:t});return Z.fromObject(e)}}class Vt extends(wt(vt).with(gt,xt,At,bt,ft)){constructor(t){super("cards",V,t)}async create(t,e,s){const r=new Tt(t,e,s);return await this._create(r.toCleanObject())}async deactivate(t){return await this._deactivate(t)}async update(t,e,s){const r=new Ct(e,s);return await this._update(t,r.toCleanObject())}}class Qt extends(wt(vt).with(At,bt)){constructor(t){super("card_transactions",R,t)}async relatedCard(t){const e=yt(t);if(null==e)return null;const s=await this.client.get({endpoint:t});return _t(`${e}`,s)}}class Yt extends(wt(vt).with(gt)){constructor(t){super("card_validations",Object,t)}async create({cvv:t,cvv2:e,expMonth:s,expYear:r,icvv:i,number:a,pinBlock:n,pinAttemptsExceeded:c}){const o=new St({cvv:t,cvv2:e,expMonth:s,expYear:r,icvv:i,number:a,pinBlock:n,pinAttemptsExceeded:c});return await this._create(o.toCleanObject())}async card(t){if(!t)return null;const e=await this.client.get({endpoint:t});return Z.fromObject(e)}}class Ft extends(wt(vt).with(At,bt)){constructor(t){super("commissions",E,t)}async relatedTransaction(t){const e=yt(t);if(null==e)return null;const s=await this.client.get(t);return _t(`${e}`,s)}}class zt extends(wt(vt).with(At,bt)){constructor(t){super("deposits",D,t)}async source(t){const e=await this.client.get({endpoint:t});return H.fromObject(e)}}class Ht extends(wt(vt).with(gt)){constructor(t){super("login_tokens",Object,t)}async create(){return await this._create()}}class Lt extends(wt(vt).with(gt,xt,At,bt,ft)){constructor(t){super("savings",Y,t)}async create(t,e,s,r){const i=new Nt(t,e,s,r);return await this._create(i.toObject())}async deactivate(t){return await this._deactivate(t)}async update(t,e,s,r,i){const a=new Nt(e,s,r,i);return await this._update(t,a.toObject())}}class Jt extends(wt(vt).with(At,bt)){constructor(t){super("service_providers",E,t)}}class Wt extends(wt(vt).with(jt,At)){constructor(t){super("statements",F,t)}async pdf(t){return await this._download(t,j.Pdf)}async xml(t){return await this._download(t,j.Xml)}}class Xt extends(wt(vt).with(gt,At,bt)){constructor(t){super("transfers",q,t)}async destination(t){const e=await this.client.get({endpoint:t});return H.fromObject(e)}async create({accountNumber:t,amount:e,descriptor:s,recipientName:r,idempotencyKey:i}){const a=i||this.constructor._genIdempotencyKey(t,e),n=new Et(t,e,s,a,r);return await this._create(n.toCleanObject())}async createMany(t){if(!t||!Array.isArray(t)||!t.length)return{};const e={submitted:[],errors:[]};return await Promise.all(t.map((async({accountNumber:t,amount:s,descriptor:r,idempotencyKey:i,recipientName:a})=>{const n=new Et(t,s,r,i||this.constructor._genIdempotencyKey(t,s),a);let c;try{c=await this._create(n.toCleanObject())}catch(t){return void e.errors.push({actualRequest:n,error:t})}e.submitted.push(c)}))),e}static _genIdempotencyKey(t,e){const[s]=S(Date.now()).toISOString().split("T");return`${s}:${t}:${e}`}}class Gt extends(wt(vt).with(gt,ft)){constructor(t){super("user_credentials",Object,t)}async create(t){const e=new Pt(t);return await this._create(e.toObject())}async update({isActive:t,password:e,userId:s="me"}){const r=new $t(e,t);return await this._update(s,r.toCleanObject())}}class Zt extends(wt(vt).with(gt,xt)){constructor(t){super("user_logins",Object,t),this.loginIdInHeaders=null}async create(t,e){const s=new Kt(t,e),r=await this._create(s.toObject());if(!r.success)throw new d;return this.loginIdInHeaders=this.client.addHeadersToRequest({"X-Cuenca-LoginId":r.id}),r}async logOut(t="me"){return await this._deactivate(t,{}),this.loginIdInHeaders&&this.loginIdInHeaders.eject(),!0}}class te extends(wt(vt).with(gt,At,bt)){constructor(t){super("wallet_transactions",Q,t)}async create(t,e,s){const r=new Dt(t,e,s);return await this._create(r.toObject())}async realtedWallet(t){const e=yt(t);if(null==e)return null;const s=await this.client.get(t);return _t(`${e}`,s)}}class ee extends(wt(vt).with(At,bt)){constructor(t){super("whatsapp_transfers",E,t)}async accountDestination(t){const e=yt(t);if(null==e)return null;const s=await this.client.get(t);return _t(`${e}`,s)}}t.AccountQuery=P,t.ApiKeyQuery=$,t.BalanceEntryQuery=M,t.BillPaymentQuery=B,t.CardErrorType=m,t.CardFundingType=w,t.CardIssuer=_,t.CardStatus=y,t.CardTransactionQuery=R,t.CardTransactionType=v,t.CardType=b,t.CardsQuery=V,t.CommissionType=g,t.Cuenca=class{constructor(t,e,s=A.Sandbox){this.client=new z({apiKey:t,apiSecret:e,phase:s}),this.withClient(this.client)}withClient(t){this.accounts=new Ot(t),this.apiKeys=new qt(t),this.balanceEntries=new Mt(t),this.billPayments=new Bt(t),this.cardActivations=new Rt(t),this.cards=new Vt(t),this.cardTransactions=new Qt(t),this.cardValidations=new Yt(t),this.commissions=new Ft(t),this.deposits=new zt(t),this.loginTokens=new Ht(t),this.savings=new Lt(t),this.serviceProviders=new Jt(t),this.statements=new Wt(t),this.transfers=new Xt(t),this.userCredentials=new Gt(t),this.userLogins=new Zt(t),this.walletTransactions=new te(t),this.whatsAppTransfers=new ee(t)}},t.CuencaException=i,t.CuencaResponseException=a,t.DepositNetwork=f,t.DepositQuery=D,t.EntryType=x,t.FileFormat=j,t.InvalidPassword=d,t.Jwt=l,t.MalformedJwtToken=o,t.MultipleResultsFound=c,t.NoResultFound=n,t.PageSize=class{constructor(t){this.maxSize=100,this._ps=t}get size(){return this._pageSize}set _ps(t){let e=this.maxSize;t&&t>0&&t<=this.maxSize&&(e=t),this._pageSize=e}},t.Phase=A,t.QueryParams=E,t.SavingCategory=I,t.ServiceProviderCategory=O,t.StatementQuery=F,t.TrackDataMethod=k,t.TransactionStatus=T,t.TransferNetwork=C,t.TransferQuery=q,t.ValidationError=u,t.WalletQuery=Y,t.WalletTransactionQuery=Q,t.WalletTransactionType=U}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("axios"),require("buffer")):"function"==typeof define&&define.amd?define(["exports","axios","buffer"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).cuenca={},t.axios,t.Buffer)}(this,(function(t,e,s){"use strict";function i(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var r=i(e),a=i(s);class n extends Error{constructor(t){super(t),Object.setPrototypeOf(this,n.prototype)}}class c extends n{constructor(t,e){super(`Cuenca Response Error: ${e}`),this.name="CuencaResponseError",this.data=t,this.status=e,Object.setPrototypeOf(this,c.prototype)}}class o extends n{constructor(){super("No results were found"),this.name="NoResultFound",Object.setPrototypeOf(this,o.prototype)}}class d extends n{constructor(){super("One result was expected but multiple were found"),this.name="MultipleResultsFound",Object.setPrototypeOf(this,d.prototype)}}class u extends n{constructor(){super("An invalid JWT token was obtained during authentication"),this.name="MalformedJwtToken",Object.setPrototypeOf(this,u.prototype)}}class h extends n{constructor(){super("Invalid password"),this.name="InvalidPassword",Object.setPrototypeOf(this,h.prototype)}}class p extends Error{constructor(t){super(t),Object.setPrototypeOf(this,p.prototype)}}const l="undefined"!=typeof window&&void 0!==window.document,m="undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process),w=l,_=m;class b{constructor(t,e){this.expiresAt=t,this.token=e}get isExpired(){const t=new Date;return(this.expiresAt.valueOf()-t.valueOf())/6e4<=5}static getExpirationDate=t=>{let e;try{const[,s]=t.split(".");e=JSON.parse(a.default.Buffer.from(`${s}==`,"base64").toString())}catch(t){throw new u}const{exp:s}=e;return new Date(new Date(1e3*s).toUTCString())};static create=async t=>{const e=t;e.jwtToken=null;const s=e.deleteRequestHeader("X-Cuenca-Token"),{token:i}=await t.post("token",{});s.eject();const r=b.getExpirationDate(i);return new b(r,i)}}class v{static Blocked=new v("blocked");static Comunication=new v("comunication");static ContactlesAmountLimit=new v("contactles_amount_limit");static FraudDetection=new v("fraud_detection");static FraudDetectionUncertain=new v("fraud_detection_uncertain");static InsufficientFounds=new v("insufficient_founds");static InvalidPin=new v("invalid_pin");static Notification=new v("notification");static NotificationDeactivatedCard=new v("notification_deactivated_card");constructor(t){this.value=t}}class y{static Credit=new y("credit");static Debit=new y("debit");constructor(t){this.value=t}}class g{static Accendo=new g("accendo");static Cuenca=new g("cuenca");constructor(t){this.value=t}}class f{static Active=new f("active");static Blocked=new f("blocked");static Created=new f("created");static Deactivated=new f("deactivated");static Printing=new f("printing");constructor(t){this.value=t}}class j{static Auth=new j("auth");static Capture=new j("capture");static Chargeback=new j("chargeback");static Expiration=new j("expiration");static Refund=new j("refund");static Void=new j("void");constructor(t){this.value=t}}class A{static Physical=new A("physical");static Virtual=new A("virtual");constructor(t){this.value=t}}class x{static CardRequest=new x("card_request");static CashDeposit=new x("cash_deposit");static OutgoingSpei=new x("outgoing_spei");constructor(t){this.value=t}}class O{static Cash=new O("cash");static Internal=new O("internal");static Spei=new O("spei");constructor(t){this.value=t}}class I{static Credit=new I("credit");static Debit=new I("debit");constructor(t){this.value=t}}class k{static Pdf=new k("pdf");static Xml=new k("xml");static Json=new k("json");constructor(t){this.value=t}}class T{static Sandbox=new T("sandbox");static Stage=new T("stage");static Api=new T("api");constructor(t){this.value=t}}class U{static Cable=new U("cable");static CreditCard=new U("credit_card");static Electricity=new U("electricity");static Gas=new U("gas");static Internet=new U("internet");static LandlineTelephone=new U("landline_telephone");static MobileTelephonePostpaid=new U("mobile_telephone_postpaid");static MobileTelephonePrepaid=new U("mobile_telephone_prepaid");static SateliteTelevision=new U("satelite_television");static Water=new U("water");constructor(t){this.value=t}}class C{static General=new C("general");static Home=new C("home");static Vehicle=new C("vehicle");static Travel=new C("travel");static Clothing=new C("clothing");static Other=new C("other");static Medical=new C("medical");static Accident=new C("accident");static Education=new C("education");constructor(t){this.value=t}}class N{static NotSet=new N("not_set");static Terminal=new N("terminal");static Manual=new N("manual");static Unknown=new N("unknown");static Contactless=new N("contactless");static FallBack=new N("fall_back");static MagneticStripe=new N("magnetic_stripe");static RecurringCharge=new N("recurring_charge");constructor(t){this.value=t}}class ${static Created=new $("created");static Failed=new $("failed");static InReview=new $("in_review");static Submitted=new $("submitted");static Succeeded=new $("succeeded");constructor(t){this.value=t}}class S{static Internal=new S("internal");static Spei=new S("spei");constructor(t){this.value=t}}class K{static Deposit=new K("deposit");static Withdrawal=new K("withdrawal");constructor(t){this.value=t}}const E=t=>{if(!t)return null;const e=new Date(t);return new Date(e.getTime())},P=(t,e)=>Object.values(t).find((t=>t.value===e));class q{constructor({createdAfter:t,createdBefore:e,limit:s,pageSize:i,relatedTransaction:r,userId:a,count:n=!1}){this.createdAfter=t,this.createdBefore=e,this._lmt=s,this.relatedTransaction=r,this.userId=a,this.count=n,this.pageSize=i}get limit(){return this._limit}set _lmt(t){let e=null;t&&t>=0&&(e=t),this._limit=e}toObject(){return{created_after:this.createdAfter,created_before:this.createdBefore,limit:this.limit,related_transaction:this.relatedTransaction,user_id:this.userId,page_size:this.pageSize&&this.pageSize.size}}toParams(){const t={...this.toObject()};return this.count&&(t.count=1),Object.keys(t).forEach((e=>{null==t[e]&&delete t[e]})),t}toQueryString(){return new URLSearchParams(this.toParams()).toString()}}class D extends q{constructor({accountNumber:t,...e}){super(e),this.accountNumber=t}toObject(){return Object.assign(super.toObject(),{account_number:this.accountNumber})}}class M extends q{constructor({active:t,...e}){super(e),this.active=t}toObject(){return Object.assign(super.toObject(),{active:this.active})}}class B extends q{constructor({status:t,...e}){super(e),this.status=t}toObject(){return Object.assign(super.toObject(),{status:this.status})}}class V extends B{constructor({trackingKey:t,network:e,...s}){super(s),this.trackingKey=t,this.network=e}toObject(){return Object.assign(super.toObject(),{tracking_key:this.trackingKey,network:this.network})}}class R extends B{constructor({accountNumber:t,idempotencyKey:e,trackingKey:s,network:i,...r}){super(r),this.accountNumber=t,this.idempotencyKey=e,this.trackingKey=s,this.network=i}toObject(){return Object.assign(super.toObject(),{account_number:this.accountNumber,idempotency_key:this.idempotencyKey,tracking_key:this.trackingKey,network:this.network})}}class Y extends q{constructor({fundingInstrumentUri:t,count:e=!1,walletId:s="default",...i}){super(i),this.fundingInstrumentUri=t,this.count=e,this.walletId=s}toObject(){return Object.assign(super.toObject(),{wallet_id:this.walletId,funding_instrument_uri:this.fundingInstrumentUri,count:this.count})}}class H extends q{constructor({accountNumber:t,...e}){super(e),this.accountNumber=t}toObject(){return Object.assign(super.toObject(),{account_number:this.accountNumber})}}class L extends q{constructor({cardUri:t,...e}){super(e),this.cardUri=t}toObject(){return Object.assign(super.toObject(),{card_uri:this.cardUri})}}class F extends q{constructor({cardUri:t,count:e=!1,...s}){super(s),this.cardUri=t,this.count=e}toObject(){return Object.assign(super.toObject(),{card_uri:this.cardUri,count:this.count})}}class z extends q{constructor({walletUri:t,...e}){super(e),this.walletUri=t}toObject(){return Object.assign(super.toObject(),{wallet_uri:this.walletUri})}}class Q extends q{constructor({active:t,...e}){super(e),this.active=t}toObject(){return Object.assign(super.toObject(),{active:this.active})}}class X extends q{constructor({month:t,year:e,...s}){super(s),this.d={month:t,year:e}}get month(){return this._date.month}get year(){return this._date.year}set d({month:t,year:e}){const s=E(Date.now());s.setUTCDate(1);if(E(`${e}-${t}-01`).getTime()>=s.getTime())throw new p(`${e}-${t} is not a valid year-month pair`);this._date={month:t,year:e}}toObject(){return Object.assign(super.toObject(),{month:this.month,year:this.year})}}var J="0.0.1-dev.19";class W{constructor({apiKey:t,apiSecret:e,phase:s=T.Sandbox}={}){this.phase=s,this.basicAuth={apiKey:t,apiSecret:e},this.jwtToken=null,this._session=r.default.create()}get session(){return this._session}get origin(){return`https://${this.phase.value}.cuenca.com`}get authHeader(){const{apiKey:t,apiSecret:e}=this.basicAuth;return t&&e?`Basic ${a.default.Buffer.from(`${t}:${e}`,"utf-8").toString("base64")}`:""}addHeadersToRequest(t){const e=this._session.interceptors.request.use((e=>{const s=e,{headers:{common:i}}=s;return Object.keys(t).forEach((e=>i[e]=t[e])),s}));return{interceptorId:e,eject:()=>this._session.interceptors.request.eject(e)}}deleteRequestHeader(t){const e=this._session.interceptors.request.use((e=>{const s=e,{headers:{common:i}}=s;return delete i[t],s}));return{interceptorId:e,eject:()=>this._session.interceptors.request.eject(e)}}addConfigToRequest(t){const e=this._session.interceptors.request.use((e=>{const s=e;return Object.keys(t).forEach((e=>s[e]=t[e])),s}));return{interceptorId:e,eject:()=>this._session.interceptors.request.eject(e)}}async configure({apiKey:t,apiSecret:e,loginToken:s,phase:i,useJwt:r=!1}){this.basicAuth={apiKey:t||this.basicAuth.apiKey,apiSecret:e||this.basicAuth.apiSecret},i&&(this.phase=i),r&&(this.jwtToken=await b.create(this)),s&&this.addHeadersToRequest({"X-Cuenca-LoginToken":s})}async get({endpoint:t,format:e,params:s}){return this.request({endpoint:t,format:e,params:s})}async post({endpoint:t,data:e}){return this.request({method:"POST",endpoint:t,data:e})}async patch({endpoint:t,data:e}){return this.request({method:"PATCH",endpoint:t,data:e})}async delete({endpoint:t,data:e}){return this.request({method:"DELETE",endpoint:t,data:e})}async request({endpoint:t,data:e=null,format:s=k.Json,method:i="GET",params:r=null}){const a={Authorization:this.authHeader,"Content-Type":"application/json",Accept:`application/${s.value}`};_?a["User-Agent"]=`cuenca-js/${J}`:w&&(a["X-User-Agent"]=`cuenca-js/${J}`),this.jwtToken&&(this.jwtToken.isExpired&&(this.jwtToken=await b.create(this)),a["X-Cuenca-Token"]=this.jwtToken.token);const o=this.addHeadersToRequest(a),d=e;d&&Object.keys(d).forEach((t=>{d[t]instanceof Date&&(d[t]=d[t].toISOString())}));const u=this.addConfigToRequest({method:i,params:r,data:d,url:t});let h;try{h=await this._session.request({baseURL:this.origin})}catch(t){throw t.response?new c(t.response.data,t.response.status):t.request?new n(`No response received: ${t.errno}: ${t.code}`):new n(t.message)}finally{o.eject(),u.eject()}return h.data}}class G{constructor({accountNumber:t,createdAt:e,id:s,institutionName:i,name:r,userId:a}){this.accountNumber=t,this.createdAt=E(e),this.id=s,this.institutionName=i,this.name=r,this.userId=a}static fromObject=({id:t,name:e,...s})=>new G({id:t,name:e,accountNumber:s.account_number,createdAt:s.created_at,institutionName:s.institution_name,userId:s.user_id})}class Z{constructor({createdAt:t,deactivatedAt:e,id:s,secret:i,userId:r,updatedAt:a}){this.createdAt=E(t),this.deactivatedAt=E(e),this.id=s,this.secret=i,this.userId=r,this.updatedAt=E(a)}static fromObject=({id:t,secret:e,...s})=>new Z({id:t,secret:e,createdAt:s.created_at,deactivatedAt:s.deactivated_at,userId:s.user_id,updatedAt:s.updated_at});get isActive(){const t=E(Date.now());return!this.deactivatedAt||this.deactivatedAt.getTime()>t.getTime()}}class tt{constructor({arpc:t,createdAt:e,cardUri:s,isValidArqc:i}){this.arpc=t,this.createdAt=E(e),this.cardUri=s,this.isValidArqc=i}static fromObject=({arpc:t,...e})=>new tt({arpc:t,createdAt:e.created_at,cardUri:e.card_uri,isValidArqc:e.is_valid_arqc})}class et{constructor({amount:t,createdAt:e,descriptor:s,entryType:i,fundingInstrumentUri:r,id:a,name:n,relatedTransactionUri:c,rollingBalance:o}){this.amount=t,this.createdAt=E(e),this.descriptor=s,this.entryType=P(I,i),this.fundingInstrumentUri=r,this.id=a,this.name=n,this.relatedTransactionUri=c,this.rollingBalance=o}static fromObject=({amount:t,descriptor:e,id:s,name:i,type:r,...a})=>new et({amount:t,descriptor:e,name:i,id:s,createdAt:a.created_at,entryType:r,fundingInstrumentUri:a.funding_instrument_uri,relatedTransactionUri:a.related_transaction_uri,rollingBalance:a.rolling_balance})}class st{constructor({amount:t,createdAt:e,descriptor:s,status:i,userId:r}){this.amount=t,this.createdAt=E(e),this.descriptor=s,this.status=P($,i),this.userId=r}}class it extends st{constructor({amount:t,accountNumber:e,createdAt:s,descriptor:i,id:r,providerUri:a,status:n,userId:c}){super({amount:t,createdAt:s,descriptor:i,status:n,userId:c}),this.accountNumber=e,this.id=r,this.providerUri=a}static fromObject=({amount:t,descriptor:e,id:s,status:i,...r})=>new it({amount:t,descriptor:e,id:s,status:i,accountNumber:r.account_number,createdAt:r.created_at,providerUri:r.provider_uri,userId:r.user_id})}class rt{constructor({createdAt:t,cvv2:e,expMonth:s,expYear:i,fundingType:r,id:a,issuer:n,number:c,pin:o,status:d,type:u,updatedAt:h,userId:p}){this.createdAt=E(t),this.cvv2=e,this.expMonth=s,this.expYear=i,this.fundingType=P(y,r),this.id=a,this.issuer=P(g,n),this.number=c,this.pin=o,this.status=P(f,d),this.type=P(A,u),this.updatedAt=E(h),this.userId=p}static fromObject=({cvv2:t,id:e,issuer:s,number:i,pin:r,status:a,type:n,...c})=>new rt({cvv2:t,id:e,issuer:s,number:i,pin:r,status:a,type:n,createdAt:c.created_at,expMonth:c.exp_month,expYear:c.exp_year,fundingType:c.funding_type,updatedAt:c.updated_at,userId:c.user_id})}class at{constructor({cardUri:t,createdAt:e,id:s,ipAddress:i,success:r,userId:a}){this.cardUri=t,this.createdAt=E(e),this.id=s,this.ipAddress=i,this.success=r,this.userId=a}static fromObject=({id:t,success:e,...s})=>new at({id:t,success:e,cardUri:s.card_uri,createdAt:s.created_at,ipAddress:s.ip_address,userId:s.user_id})}class nt extends st{constructor({amount:t,cardErrorType:e,cardLastFour:s,cardType:i,cardUri:r,createdAt:a,descriptor:n,metadata:c,network:o,relatedCardTransactionsUris:d,status:u,type:h,userId:p}){super({amount:t,createdAt:a,descriptor:n,status:u,userId:p}),this.cardErrorType=P(v,e),this.cardLastFour=s,this.cardType=P(A,i),this.cardUri=r,this.metadata=c,this.network=o,this.relatedCardTransactionsUris=d,this.type=P(j,h)}static fromObject=({amount:t,descriptor:e,metadata:s,network:i,status:r,type:a,...n})=>new nt({amount:t,descriptor:e,metadata:s,network:i,status:r,type:a,cardErrorType:n.error_type,cardLastFour:n.card_last4,cardType:n.card_type,cardUri:n.card_uri,createdAt:n.created_at,relatedCardTransactionsUris:n.related_card_transaction,userId:n.user_id})}class ct{constructor({cardStatus:t,cardType:e,cardUri:s,createdAt:i,isExpired:r,isPinAttemptsExceeded:a,isValidCvv:n,isValidCvv2:c,isValidExpDate:o,isValidIcvv:d,isValidPinBlock:u,userId:h}){this.cardStatus=P(f,t),this.cardType=P(A,e),this.cardUri=s,this.createdAt=E(i),this.isExpired=r,this.isPinAttemptsExceeded=a,this.isValidCvv=n,this.isValidCvv2=c,this.isValidExpDate=o,this.isValidIcvv=d,this.isValidPinBlock=u,this.userId=h}static fromObject=({...t})=>new ct({cardStatus:t.card_status,cardType:t.card_type,cardUri:t.card_uri,createdAt:t.created_at,isExpired:t.is_expired,isPinAttemptsExceeded:t.is_pin_attempts_exceeded,isValidCvv:t.is_valid_cvv,isValidCvv2:t.is_valid_cvv2,isValidExpDate:t.is_valid_exp_date,isValidIcvv:t.is_valid_icvv,isValidPinBlock:t.is_valid_pin_block,userId:t.user_id});get isActive(){return this.cardStatus===f.Active}}class ot extends st{constructor({amount:t,createdAt:e,descriptor:s,relatedTransactionUri:i,status:r,type:a,userId:n}){super({amount:t,createdAt:e,descriptor:s,status:r,userId:n}),this.relatedTransactionUri=i,this.type=P(x,a)}static fromObject=({amount:t,descriptor:e,status:s,type:i,...r})=>new ot({amount:t,descriptor:e,status:s,type:i,createdAt:r.created_at,relatedTransactionUri:r.related_transaction_uri,userId:r.user_id})}class dt extends st{constructor({amount:t,createdAt:e,descriptor:s,id:i,network:r,status:a,sourceUri:n,trackingKey:c,userId:o}){super({amount:t,createdAt:e,descriptor:s,status:a,userId:o}),this.id=i,this.network=P(O,r),this.sourceUri=n,this.trackingKey=c}static fromObject=({amount:t,descriptor:e,id:s,network:i,status:r,...a})=>new dt({amount:t,descriptor:e,id:s,network:i,status:r,createdAt:a.created_at,sourceUri:a.source_uri,trackingKey:a.tracking_key,userId:a.user_id})}class ut{constructor({id:t}){this.id=t}static fromObject=({id:t})=>new ut({id:t})}class ht extends class{constructor({balance:t,createdAt:e,deactivatedAt:s,id:i,userId:r,updatedAt:a}){this.balance=t,this.createdAt=E(e),this.deactivatedAt=E(s),this.id=i,this.userId=r,this.updatedAt=E(a)}}{constructor({balance:t,category:e,createdAt:s,deactivatedAt:i,goalAmount:r,goalDate:a,id:n,name:c,userId:o,updatedAt:d}){super({balance:t,createdAt:s,deactivatedAt:i,id:n,userId:o,updatedAt:d}),this.category=P(C,e),this.goalAmount=r,this.goalDate=E(a),this.name=c}static fromObject=({balance:t,category:e,id:s,name:i,...r})=>new ht({balance:t,category:e,id:s,name:i,createdAt:r.created_at,deactivatedAt:r.deactivated_at,goalAmount:r.goal_amount,goalDate:r.goal_date,userId:r.user_id,updatedAt:r.updated_at})}class pt{constructor({categories:t,id:e,name:s,providerKey:i}){var r;this.categories=null==(r=t)?[]:r.map((t=>P(U,t))),this.id=e,this.name=s,this.providerKey=i}static fromObject=({categories:t,id:e,name:s,...i})=>new pt({categories:t,id:e,name:s,providerKey:i.provider_key})}class lt{constructor({createdAt:t,id:e,month:s,year:i}){this.createdAt=E(t),this.id=e,this.month=s,this.year=i}static fromObject=({id:t,month:e,year:s,...i})=>new lt({id:t,month:e,year:s,createdAt:i.created_at})}class mt extends st{constructor({accountNumber:t,amount:e,createdAt:s,descriptor:i,destinationUri:r,id:a,idempotencyKey:n,network:c,recipientName:o,status:d,trackingKey:u,updatedAt:h,userId:p}){super({amount:e,createdAt:s,descriptor:i,status:d,userId:p}),this.accountNumber=t,this.destinationUri=r,this.id=a,this.idempotencyKey=n,this.network=P(S,c),this.recipientName=o,this.trackingKey=u,this.updatedAt=E(h)}static fromObject=({amount:t,descriptor:e,id:s,network:i,status:r,...a})=>new mt({amount:t,descriptor:e,id:s,network:i,status:r,accountNumber:a.account_number,createdAt:a.created_at,destinationUri:a.destination_uri,idempotencyKey:a.idempotency_key,recipientName:a.recipient_name,trackingKey:a.tracking_key,updatedAt:a.updated_at,userId:a.user_id})}class wt{constructor({createdAt:t,id:e,isActive:s,updatedAt:i}){this.createdAt=E(t),this.id=e,this.isActive=s,this.updatedAt=E(i)}static fromObject=({id:t,...e})=>new wt({id:t,createdAt:e.created_at,isActive:e.is_active,updatedAt:e.updated_at})}class _t{constructor({id:t,lastLoginAt:e,success:s}){this.id=t,this.lastLoginAt=E(e),this.success=s}static fromObject=({id:t,success:e,...s})=>new _t({id:t,success:e,lastLoginAt:s.last_login_at})}class bt extends st{constructor({amount:t,createdAt:e,descriptor:s,id:i,status:r,transactionType:a,userId:n,walletUri:c}){super({amount:t,createdAt:e,descriptor:s,status:r,userId:n}),this.id=i,this.transactionType=P(K,a),this.walletUri=c}static fromObject=({amount:t,descriptor:e,id:s,status:i,...r})=>new bt({amount:t,descriptor:e,id:s,status:i,createdAt:r.created_at,transactionType:r.transaction_type,userId:r.user_id,walletUri:r.wallet_uri})}class vt extends st{constructor({amount:t,claimUrl:e,createdAt:s,descriptor:i,destinationUri:r,expiresAt:a,id:n,network:c,phoneNumber:o,recipientName:d,status:u,trackingKey:h,updatedAt:p,userId:l}){super({amount:t,createdAt:s,descriptor:i,status:u,userId:l}),this.claimUrl=e,this.destinationUri=r,this.id=n,this.expiresAt=E(a),this.network=P(S,c),this.phoneNumber=o,this.recipientName=d,this.trackingKey=h,this.updatedAt=E(p)}static fromObject=({amount:t,descriptor:e,id:s,network:i,status:r,...a})=>new vt({amount:t,descriptor:e,id:s,network:i,status:r,createdAt:a.created_at,claimUrl:a.claim_url,destinationUri:a.destination_uri,expiresAt:a.expires_at,phoneNumber:a.phone_number,recipientName:a.recipient_name,trackingKey:a.tracking_key,updatedAt:a.updated_at,userId:a.user_id})}class yt{constructor(t){this.superclass=t}with(...t){return t.reduce(((t,e)=>e(t)),this.superclass)}}const gt=t=>new yt(t),ft=(t,e)=>({accounts:()=>G.fromObject(e),api_keys:()=>Z.fromObject(e),arpc:()=>tt.fromObject(e),balance_entries:()=>et.fromObject(e),bill_payments:()=>it.fromObject(e),cards:()=>rt.fromObject(e),card_activations:()=>at.fromObject(e),card_transactions:()=>nt.fromObject(e),card_validations:()=>ct.fromObject(e),commissions:()=>ot.fromObject(e),deposits:()=>dt.fromObject(e),login_tokens:()=>ut.fromObject(e),savings:()=>ht.fromObject(e),service_providers:()=>pt.fromObject(e),statements:()=>lt.fromObject(e),transfers:()=>mt.fromObject(e),user_credentials:()=>wt.fromObject(e),user_logins:()=>_t.fromObject(e),wallet_transactions:()=>bt.fromObject(e),whatsapp_transfers:()=>vt.fromObject(e)}[t]()),jt=t=>{if(null===t||""===t)return null;const e=t.match("/(.*?)/");return null===e?null:e[0].replaceAll("/","")};class At{constructor(t,e,s){this.path=t,this.QueryParams=e,this.client=s}}const xt=t=>class extends t{async retrieve(t){const e=await this.client.get({endpoint:`/${this.path}/${t}`});return ft(this.path,e)}},Ot=t=>class extends t{async _create(t){const e=await this.client.post({endpoint:`/${this.path}`,data:t});return ft(this.path,e)}},It=t=>class extends t{async _update(t,e){const s=await this.client.patch({endpoint:`/${this.path}/${t}`,data:e});return ft(this.path,s)}},kt=t=>class extends t{async _deactivate(t,e){const s=await this.client.delete({endpoint:`/${this.path}/${t}`,data:e});return ft(this.path,s)}},Tt=t=>class extends t{async _download(t,e){return await this.client.get({endpoint:`/${this.path}/${t}`,format:e})}},Ut=t=>class extends t{async one(t=new this.QueryParams({})){const{items:e}=await this.client.get({endpoint:`/${this.path}`,params:t.toParams()});if(!e||!e.length)throw new o;if(e.length>1)throw new d;const[s]=e;return ft(this.path,s)}async first(t=new this.QueryParams({})){const{items:e}=await this.client.get({endpoint:`/${this.path}`,params:t.toParams()});if(!e||!e[0])return null;const[s]=e;return ft(this.path,s)}async count(t=new this.QueryParams({})){t.count=!0;const{count:e}=await this.client.get({endpoint:`/${this.path}`,params:t.toParams()});return e||0}async*all(t=new this.QueryParams({})){let e=`/${this.path}?${t.toQueryString()}`;for(;e;){const t=await this.client.get({endpoint:e});if(t.items)for(const e of t.items){const t=ft(this.path,e);yield t}e=t.next_page_uri}}};class Ct extends(gt(At).with(Ut,xt)){constructor(t){super("accounts",D,t)}}class Nt{toObject(){return{}}toCleanObject(){const t=this.toObject();return Object.keys(t).forEach((e=>{null==t[e]&&delete t[e]})),t}}class $t extends Nt{constructor(t,e){super(),this.userId=t,this.metadata=e}toObject(){return{user_id:this.userId,metadata:this.metadata}}}class St extends Nt{constructor(t,e,s){super(),this.userId=t,this.issuer=e,this.fundingType=s}toObject(){return{user_id:this.userId,issuer:this.issuer,funding_type:this.fundingType}}}class Kt extends Nt{constructor(t,e){super(),this.status=t,this.pinBlock=e}toObject(){return{status:this.status,pin_block:this.pinBlock}}}class Et extends Nt{constructor(t,e,s,i){super(),this.n=t,this.eM=e,this.eY=s,this.c2=i}get number(){return this._number}set n(t){if([!!t,16===t.length,/^\d{16}/.test(t)].some((t=>!t)))throw new p("Invalid number");this._number=t.trim()}get expMonth(){return this._expMonth}set eM(t){if([!!t,t>=1,t<=12].some((t=>!t)))throw new p("Invalid expiration month");this._expMonth=t}get expYear(){return this._expYear}set eY(t){if([!!t,t>=18,t<=99].some((t=>!t)))throw new p("Invalid expiration year");this._expYear=t}get cvv2(){return this._cvv2}set c2(t){if([!!t,3===t.length,/^\d{3}/.test(t)].some((t=>!t)))throw new p("Invalid cvv2");this._cvv2=t}toObject(){return{number:this.number,exp_month:this.expMonth,exp_year:this.expYear,cvv2:this.cvv2}}}class Pt extends Nt{constructor({cvv:t,cvv2:e,expMonth:s,expYear:i,icvv:r,number:a,pinBlock:n,pinAttemptsExceeded:c}){super(),this.c=t,this.c2=e,this.em=s,this.ey=i,this.ic=r,this.n=a,this.pinBloc=n,this.pinAttemptsExceeded=c}get cvv(){return this._cvv}set c(t){if(!t)return;if([3===t.length].some((t=>!t)))throw new p("Invalid cvv");this._cvv=t}get cvv2(){return this._cvv2}set c2(t){if(!t)return;if([3===t.length].some((t=>!t)))throw new p("Invalid cvv2");this._cvv2=t}get expMonth(){return this._expMonth}set em(t){if(!t)return;if([t>=1,t<=12].some((t=>!t)))throw new p("Invalid expiration month");this._expMonth=t}get expYear(){return this._expYear}set ey(t){if(!t)return;if([t>=18,t<=99].some((t=>!t)))throw new p("Invalid expiration year");this._expYear=t}get icvv(){return this._icvv}set ic(t){if(!t)return;if([3===t.length].some((t=>!t)))throw new p("Invalid icvv");this._icvv=t}get number(){return this._number}set n(t){if([!!t,16===t.length,/^\d{16}/.test(t)].some((t=>!t)))throw new p("Invalid number");this._number=t}toObject(){return{cvv:this.cvv,cvv2:this.cvv2,exp_month:this.expMonth,exp_year:this.expYear,icvv:this.icvv,number:this.number,pin_block:this.pinBloc,pin_attempts_exceeded:this.pinAttemptsExceeded}}}class qt extends Nt{constructor(t,e,s,i){super(),this.category=t,this.name=i,this.goalAmount=e,this.validDate=s}get goalDate(){return this._goalDate}set validDate(t){if(t){if(E(t).getTime()<=E(Date.now()).getTime())throw new p("The goal_date always need to be higher than now");this._goalDate=t}}toObject(){return{category:this.category,goal_amount:this.goalAmount,goal_date:this.goalDate,name:this.name}}}class Dt extends Nt{constructor(t,e,s,i,r){super(),this.accountNumber=t,this.amount=e,this.descriptor=s,this.idempotencyKey=i,this.recipientName=r}toObject(){return{account_number:this.accountNumber,amount:this.amount,descriptor:this.descriptor,idempotency_key:this.idempotencyKey,recipient_name:this.recipientName}}}class Mt extends Nt{constructor(t){super(),this.pwd=t}get password(){return this._password}set pwd(t){if([!!t,6===t.length,/^\d{6}$/.test(t)].some((t=>!t)))throw new p("Invalid password");this._password=t}toObject(){return{password:this.password}}}class Bt extends Nt{constructor(t,e){super(),this.pwd=t,this.isActive=e,this.req={password:this.password,isActive:this.isActive}}get password(){return this._password}get request(){return this._request}set pwd(t){if(!t)return void(this._password=t);if([6===t.length,/^\d{6}$/.test(t)].some((t=>!t)))throw new p("Invalid password");this._password=t}set req(t){if(t.password&&null!=t.isActive)throw new p("Only one property can be updated at a time");this._request=t}toObject(){return{password:this.request.password,is_active:this.request.isActive}}}class Vt extends Nt{constructor(t,e="me"){super(),this.pwd=t,this.userId=e}get password(){return this._password}set pwd(t){if([!!t,6===t.length,/^\d{6}$/.test(t)].some((t=>!t)))throw new p("Invalid password");this._password=t}toObject(){return{password:this.password,user_id:this.userId}}}class Rt extends Nt{constructor(t,e,s){super(),this.amount=t,this.transactionType=e,this.walletUri=s}toObject(){return{amount:this.amount,transaction_type:this.transactionType,wallet_uri:this.walletUri}}}class Yt extends(gt(At).with(Ot,kt,Ut,xt,It)){constructor(t){super("api_keys",M,t)}async create(){return await this._create()}async deactivate(t,e=0){return await this._deactivate(t,{minutes:e})}async update(t,e,s){const i=new $t(s,e);return await this._update(t,i.toCleanObject())}}gt(At).with(Ot);class Ht extends(gt(At).with(Ut,xt)){constructor(t){super("balance_entries",Y,t)}async relatedTransaction(t){const e=jt(t);if(null==e)return null;const s=await this.client.get({endpoint:t});return ft(`${e}`,s)}async fundingInstrument(t){const e=jt(t);if(null==e)return null;const s=await this.client.get({endpoint:t});return ft(`${e}`,s)}}class Lt extends(gt(At).with(Ut,xt)){constructor(t){super("bill_payments",H,t)}async serviceProvider(t){const e=jt(t);if(null==e)return null;const s=await this.client.get({endpoint:t});return ft(`${e}`,s)}}class Ft extends(gt(At).with(Ot)){constructor(t){super("card_activations",Object,t)}async create({number:t,expMonth:e,expYear:s,cvv2:i}){const r=new Et(t,e,s,i);return await this._create(r.toCleanObject())}async card(t){if(!t)return null;const e=await this.client.get({endpoint:t});return rt.fromObject(e)}}class zt extends(gt(At).with(Ot,kt,Ut,xt,It)){constructor(t){super("cards",F,t)}async create(t,e,s){const i=new St(t,e,s);return await this._create(i.toCleanObject())}async deactivate(t){return await this._deactivate(t)}async update(t,e,s){const i=new Kt(e,s);return await this._update(t,i.toCleanObject())}}class Qt extends(gt(At).with(Ut,xt)){constructor(t){super("card_transactions",L,t)}async relatedCard(t){const e=jt(t);if(null==e)return null;const s=await this.client.get({endpoint:t});return ft(`${e}`,s)}}class Xt extends(gt(At).with(Ot)){constructor(t){super("card_validations",Object,t)}async create({cvv:t,cvv2:e,expMonth:s,expYear:i,icvv:r,number:a,pinBlock:n,pinAttemptsExceeded:c}){const o=new Pt({cvv:t,cvv2:e,expMonth:s,expYear:i,icvv:r,number:a,pinBlock:n,pinAttemptsExceeded:c});return await this._create(o.toCleanObject())}async card(t){if(!t)return null;const e=await this.client.get({endpoint:t});return rt.fromObject(e)}}class Jt extends(gt(At).with(Ut,xt)){constructor(t){super("commissions",q,t)}async relatedTransaction(t){const e=jt(t);if(null==e)return null;const s=await this.client.get(t);return ft(`${e}`,s)}}class Wt extends(gt(At).with(Ut,xt)){constructor(t){super("deposits",V,t)}async source(t){const e=await this.client.get({endpoint:t});return G.fromObject(e)}}class Gt extends(gt(At).with(Ot)){constructor(t){super("login_tokens",Object,t)}async create(){return await this._create()}}class Zt extends(gt(At).with(Ot,kt,Ut,xt,It)){constructor(t){super("savings",Q,t)}async create(t,e,s,i){const r=new qt(t,e,s,i);return await this._create(r.toObject())}async deactivate(t){return await this._deactivate(t)}async update(t,e,s,i,r){const a=new qt(e,s,i,r);return await this._update(t,a.toObject())}}class te extends(gt(At).with(Ut,xt)){constructor(t){super("service_providers",q,t)}}class ee extends(gt(At).with(Tt,Ut)){constructor(t){super("statements",X,t)}async pdf(t){return await this._download(t,k.Pdf)}async xml(t){return await this._download(t,k.Xml)}}class se extends(gt(At).with(Ot,Ut,xt)){constructor(t){super("transfers",R,t)}async destination(t){const e=await this.client.get({endpoint:t});return G.fromObject(e)}async create({accountNumber:t,amount:e,descriptor:s,recipientName:i,idempotencyKey:r}){const a=r||this.constructor._genIdempotencyKey(t,e),n=new Dt(t,e,s,a,i);return await this._create(n.toCleanObject())}async createMany(t){if(!t||!Array.isArray(t)||!t.length)return{};const e={submitted:[],errors:[]};return await Promise.all(t.map((async({accountNumber:t,amount:s,descriptor:i,idempotencyKey:r,recipientName:a})=>{const n=new Dt(t,s,i,r||this.constructor._genIdempotencyKey(t,s),a);let c;try{c=await this._create(n.toCleanObject())}catch(t){return void e.errors.push({actualRequest:n,error:t})}e.submitted.push(c)}))),e}static _genIdempotencyKey(t,e){const[s]=E(Date.now()).toISOString().split("T");return`${s}:${t}:${e}`}}class ie extends(gt(At).with(Ot,It)){constructor(t){super("user_credentials",Object,t)}async create(t){const e=new Mt(t);return await this._create(e.toObject())}async update({isActive:t,password:e,userId:s="me"}){const i=new Bt(e,t);return await this._update(s,i.toCleanObject())}}class re extends(gt(At).with(Ot,kt)){constructor(t){super("user_logins",Object,t),this.loginIdInHeaders=null}async create(t,e){const s=new Vt(t,e),i=await this._create(s.toObject());if(!i.success)throw new h;return this.loginIdInHeaders=this.client.addHeadersToRequest({"X-Cuenca-LoginId":i.id}),i}async logOut(t="me"){return await this._deactivate(t,{}),this.loginIdInHeaders&&this.loginIdInHeaders.eject(),!0}}class ae extends(gt(At).with(Ot,Ut,xt)){constructor(t){super("wallet_transactions",z,t)}async create(t,e,s){const i=new Rt(t,e,s);return await this._create(i.toObject())}async realtedWallet(t){const e=jt(t);if(null==e)return null;const s=await this.client.get(t);return ft(`${e}`,s)}}class ne extends(gt(At).with(Ut,xt)){constructor(t){super("whatsapp_transfers",q,t)}async accountDestination(t){const e=jt(t);if(null==e)return null;const s=await this.client.get(t);return ft(`${e}`,s)}}t.Cuenca=class{constructor(t,e,s=T.Sandbox){this.client=new W({apiKey:t,apiSecret:e,phase:s}),this.withClient(this.client)}withClient(t){this.accounts=new Ct(t),this.apiKeys=new Yt(t),this.balanceEntries=new Ht(t),this.billPayments=new Lt(t),this.cardActivations=new Ft(t),this.cards=new zt(t),this.cardTransactions=new Qt(t),this.cardValidations=new Xt(t),this.commissions=new Jt(t),this.deposits=new Wt(t),this.loginTokens=new Gt(t),this.savings=new Zt(t),this.serviceProviders=new te(t),this.statements=new ee(t),this.transfers=new se(t),this.userCredentials=new ie(t),this.userLogins=new re(t),this.walletTransactions=new ae(t),this.whatsAppTransfers=new ne(t)}}}));
@@ -1,5 +1,5 @@
1
1
  import { ValidationError } from './errors/index.mjs';
2
- import { d as dateToUTC } from './data-c1851484.mjs';
2
+ import { d as dateToUTC } from './data-d5bcb7c8.mjs';
3
3
 
4
4
  class BaseRequest {
5
5
  toObject() {
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var errors_index = require('./errors/index.cjs');
4
- var data = require('./data-c83462d7.cjs');
4
+ var data = require('./data-9edbb2a0.cjs');
5
5
 
6
6
  class BaseRequest {
7
7
  toObject() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cuenca-mx/cuenca-js",
3
- "version": "0.0.1-dev.15",
3
+ "version": "0.0.1-dev.19",
4
4
  "description": "Cuenca client for JS",
5
5
  "main": "./build/index.cjs",
6
6
  "module": "./build/index.mjs",
@@ -51,13 +51,14 @@
51
51
  "publish": "yarn build && yarn npm publish"
52
52
  },
53
53
  "devDependencies": {
54
- "@rollup/plugin-commonjs": "^21.0.1",
54
+ "@rollup/plugin-json": "^4.1.0",
55
55
  "@rollup/plugin-node-resolve": "^13.1.1",
56
56
  "jest": "^27.4.5",
57
57
  "rollup": "^2.61.1",
58
58
  "rollup-plugin-terser": "^7.0.2"
59
59
  },
60
60
  "dependencies": {
61
- "axios": "^0.24.0"
61
+ "axios": "^0.24.0",
62
+ "buffer": "^6.0.3"
62
63
  }
63
64
  }
@@ -1,69 +0,0 @@
1
- 'use strict';
2
-
3
- var errors_index = require('./errors/index.cjs');
4
-
5
- /* global window */
6
-
7
- const isBrowser =
8
- typeof window !== 'undefined' && typeof window.document !== 'undefined';
9
-
10
- const isNode =
11
- typeof process !== 'undefined' &&
12
- Object.prototype.toString.call(process) === '[object process]';
13
-
14
- class Jwt {
15
- constructor(expiresAt, token) {
16
- this.expiresAt = expiresAt;
17
- this.token = token;
18
- }
19
-
20
- get isExpired() {
21
- const today = new Date();
22
- return (this.expiresAt.valueOf() - today.valueOf()) / 60000 <= 5;
23
- }
24
-
25
- static getExpirationDate = (token) => {
26
- let payload;
27
- try {
28
- const [, payloadEncoded] = token.split('.');
29
- let unparsed;
30
- if (isNode) {
31
- unparsed = Buffer.from(`${payloadEncoded}==`, 'base64').toString();
32
- } else if (isBrowser) {
33
- const encoded = btoa(
34
- unescape(encodeURIComponent(`${payloadEncoded}==`)),
35
- );
36
- unparsed = decodeURIComponent(escape(atob(encoded)));
37
- } else {
38
- throw new errors_index.MalformedJwtToken();
39
- }
40
-
41
- payload = JSON.parse(unparsed);
42
- } catch (error) {
43
- throw new errors_index.MalformedJwtToken();
44
- }
45
-
46
- const { exp } = payload;
47
- return new Date(new Date(exp * 1000).toUTCString());
48
- };
49
-
50
- static create = async (client) => {
51
- const currentClient = client;
52
- currentClient.jwtToken = null;
53
- // Intercepts requests and removes the header if it includes it
54
- const tokenInterceptor =
55
- currentClient.deleteRequestHeader('X-Cuenca-Token');
56
-
57
- const { token } = await client.post('token', {});
58
-
59
- // Remove the interceptor to avoid removing the header on all requests
60
- tokenInterceptor.eject();
61
-
62
- const expiresAt = Jwt.getExpirationDate(token);
63
- return new Jwt(expiresAt, token);
64
- };
65
- }
66
-
67
- exports.Jwt = Jwt;
68
- exports.isBrowser = isBrowser;
69
- exports.isNode = isNode;
@@ -1,65 +0,0 @@
1
- import { MalformedJwtToken } from './errors/index.mjs';
2
-
3
- /* global window */
4
-
5
- const isBrowser =
6
- typeof window !== 'undefined' && typeof window.document !== 'undefined';
7
-
8
- const isNode =
9
- typeof process !== 'undefined' &&
10
- Object.prototype.toString.call(process) === '[object process]';
11
-
12
- class Jwt {
13
- constructor(expiresAt, token) {
14
- this.expiresAt = expiresAt;
15
- this.token = token;
16
- }
17
-
18
- get isExpired() {
19
- const today = new Date();
20
- return (this.expiresAt.valueOf() - today.valueOf()) / 60000 <= 5;
21
- }
22
-
23
- static getExpirationDate = (token) => {
24
- let payload;
25
- try {
26
- const [, payloadEncoded] = token.split('.');
27
- let unparsed;
28
- if (isNode) {
29
- unparsed = Buffer.from(`${payloadEncoded}==`, 'base64').toString();
30
- } else if (isBrowser) {
31
- const encoded = btoa(
32
- unescape(encodeURIComponent(`${payloadEncoded}==`)),
33
- );
34
- unparsed = decodeURIComponent(escape(atob(encoded)));
35
- } else {
36
- throw new MalformedJwtToken();
37
- }
38
-
39
- payload = JSON.parse(unparsed);
40
- } catch (error) {
41
- throw new MalformedJwtToken();
42
- }
43
-
44
- const { exp } = payload;
45
- return new Date(new Date(exp * 1000).toUTCString());
46
- };
47
-
48
- static create = async (client) => {
49
- const currentClient = client;
50
- currentClient.jwtToken = null;
51
- // Intercepts requests and removes the header if it includes it
52
- const tokenInterceptor =
53
- currentClient.deleteRequestHeader('X-Cuenca-Token');
54
-
55
- const { token } = await client.post('token', {});
56
-
57
- // Remove the interceptor to avoid removing the header on all requests
58
- tokenInterceptor.eject();
59
-
60
- const expiresAt = Jwt.getExpirationDate(token);
61
- return new Jwt(expiresAt, token);
62
- };
63
- }
64
-
65
- export { Jwt as J, isBrowser as a, isNode as i };