dymo-api 1.0.37 → 1.0.39

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.
@@ -50,7 +50,7 @@ const isValidData = async (token, data) => {
50
50
  return response.data;
51
51
  }
52
52
  catch (error) {
53
- throw customError(5000, error.message);
53
+ throw customError(5000, error.response?.data?.message || error.message);
54
54
  }
55
55
  };
56
56
  exports.isValidData = isValidData;
@@ -82,7 +82,7 @@ const sendEmail = async (token, data) => {
82
82
  return response.data;
83
83
  }
84
84
  catch (error) {
85
- throw customError(5000, error.message);
85
+ throw customError(5000, error.response?.data?.message || error.message);
86
86
  }
87
87
  };
88
88
  exports.sendEmail = sendEmail;
@@ -102,7 +102,7 @@ const getRandom = async (token, data) => {
102
102
  return response.data;
103
103
  }
104
104
  catch (error) {
105
- throw customError(5000, error.message);
105
+ throw customError(5000, error.response?.data?.message || error.message);
106
106
  }
107
107
  };
108
108
  exports.getRandom = getRandom;
@@ -45,7 +45,7 @@ const getPrayerTimes = async (data) => {
45
45
  return response.data;
46
46
  }
47
47
  catch (error) {
48
- throw customError(5000, error.message);
48
+ throw customError(5000, error.response?.data?.message || error.message);
49
49
  }
50
50
  };
51
51
  exports.getPrayerTimes = getPrayerTimes;
@@ -58,7 +58,7 @@ const satinizer = async (data) => {
58
58
  return response.data;
59
59
  }
60
60
  catch (error) {
61
- throw customError(5000, error.message);
61
+ throw customError(5000, error.response?.data?.message || error.message);
62
62
  }
63
63
  };
64
64
  exports.satinizer = satinizer;
@@ -94,7 +94,7 @@ const isValidPwd = async (data) => {
94
94
  return response.data;
95
95
  }
96
96
  catch (error) {
97
- throw customError(5000, error.message);
97
+ throw customError(5000, error.response?.data?.message || error.message);
98
98
  }
99
99
  };
100
100
  exports.isValidPwd = isValidPwd;
@@ -107,7 +107,7 @@ const newURLEncrypt = async (data) => {
107
107
  return response.data;
108
108
  }
109
109
  catch (error) {
110
- throw customError(5000, error.message);
110
+ throw customError(5000, error.response?.data?.message || error.message);
111
111
  }
112
112
  };
113
113
  exports.newURLEncrypt = newURLEncrypt;
@@ -0,0 +1,263 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const axios_1 = __importDefault(require("axios"));
30
+ const PublicAPI = __importStar(require("./branches/public"));
31
+ const PrivateAPI = __importStar(require("./branches/private"));
32
+ const config_1 = __importStar(require("./config"));
33
+ const autoupdate_1 = require("./services/autoupdate");
34
+ const customError = (code, message) => {
35
+ return Object.assign(new Error(), { code, message: `[${config_1.default.lib.name}] ${message}` });
36
+ };
37
+ ;
38
+ ;
39
+ ;
40
+ class DymoAPI {
41
+ /**
42
+ * @param {Object} options - Options to create the DymoAPI instance.
43
+ * @param {string} [options.rootApiKey] - The root API key.
44
+ * @param {string} [options.apiKey] - The API key.
45
+ * @param {boolean} [options.local] - Whether to use a local server instead of the cloud server.
46
+ * @param {Object} [options.serverEmailConfig] - The server email config.
47
+ * @description
48
+ * This is the main class to interact with the Dymo API. It should be
49
+ * instantiated with the root API key and the API key. The root API key is
50
+ * used to fetch the tokens and the API key is used to authenticate the
51
+ * requests.
52
+ * @example
53
+ * const dymoApi = new DymoAPI({
54
+ * rootApiKey: "6bfb7675-6b69-4f8d-9f43-5a6f7f02c6c5",
55
+ * apiKey: "4c8b7675-6b69-4f8d-9f43-5a6f7f02c6c5",
56
+ * local: true
57
+ * });
58
+ */
59
+ constructor({ rootApiKey = null, apiKey = null, local = false, serverEmailConfig = undefined }) {
60
+ this.rootApiKey = rootApiKey;
61
+ this.apiKey = apiKey;
62
+ this.tokensResponse = null;
63
+ this.lastFetchTime = null;
64
+ this.serverEmailConfig = serverEmailConfig;
65
+ this.local = rootApiKey ? local : false; // Only allow setting local if rootApiKey is defined.
66
+ (0, config_1.setBaseUrl)(this.local);
67
+ this.autoupdate();
68
+ this.initializeTokens(); // Calls the function to obtain tokens when creating the object.
69
+ }
70
+ /**
71
+ * Retrieves and caches authentication tokens.
72
+ *
73
+ * This method checks if cached tokens are available and valid. If so, it returns
74
+ * the cached tokens. Otherwise, it generates new tokens using the provided API keys
75
+ * and caches them. The tokens are fetched from the server using a POST request.
76
+ *
77
+ * The method also handles validation of root and API tokens, throwing errors if
78
+ * any of the tokens are invalid. Cached tokens are considered valid for 5 minutes.
79
+ *
80
+ * @returns {Promise<Object|undefined>} A promise that resolves to the tokens response
81
+ * if successful, or undefined if no tokens are available.
82
+ * @throws Will throw an error if token validation fails, or if there is an issue
83
+ * with the token retrieval process.
84
+ */
85
+ async getTokens() {
86
+ const currentTime = new Date();
87
+ if (this.tokensResponse && this.lastFetchTime && (currentTime.getTime() - this.lastFetchTime.getTime()) < 5 * 60 * 1000) {
88
+ console.log(`[${config_1.default.lib.name}] Using cached tokens response.`);
89
+ return this.tokensResponse;
90
+ }
91
+ ;
92
+ const tokens = {};
93
+ if (this.rootApiKey)
94
+ tokens.root = `Bearer ${this.rootApiKey}`;
95
+ if (this.apiKey)
96
+ tokens.api = `Bearer ${this.apiKey}`;
97
+ try {
98
+ if (Object.keys(tokens).length === 0)
99
+ return;
100
+ const response = await axios_1.default.post(`${config_1.BASE_URL}/v1/dvr/tokens`, { tokens });
101
+ if (tokens.root && response.data.root === false)
102
+ throw customError(3000, "Invalid root token.");
103
+ if (tokens.api && response.data.api === false)
104
+ throw customError(3000, "Invalid API token.");
105
+ this.tokensResponse = response.data;
106
+ this.lastFetchTime = currentTime;
107
+ console.log(`[${config_1.default.lib.name}] Tokens initialized successfully.`);
108
+ return this.tokensResponse;
109
+ }
110
+ catch (error) {
111
+ throw customError(5000, error.message);
112
+ }
113
+ }
114
+ /**
115
+ * Initializes the tokens response by calling getTokens().
116
+ *
117
+ * This method is called in the constructor and will throw an error if the
118
+ * initialization process fails.
119
+ *
120
+ * @throws Will throw an error if there is an issue with the token retrieval
121
+ * process.
122
+ */
123
+ async initializeTokens() {
124
+ try {
125
+ await this.getTokens();
126
+ }
127
+ catch (error) {
128
+ throw customError(5000, `Error initializing tokens: ${error.message}`);
129
+ }
130
+ }
131
+ /**
132
+ * Checks for updates and logs a message if a new version is available.
133
+ *
134
+ * This method is called in the constructor and will throw an error if the
135
+ * update check fails.
136
+ *
137
+ * @throws Will throw an error if there is an issue with the update check
138
+ * process.
139
+ */
140
+ async autoupdate() {
141
+ try {
142
+ await (0, autoupdate_1.checkForUpdates)();
143
+ }
144
+ catch (error) {
145
+ throw customError(5000, `Error checking the latest version in npmjs: ${error.message}`);
146
+ }
147
+ }
148
+ // FUNCTIONS / Private.
149
+ /**
150
+ * Validates the given data against the configured validation settings.
151
+ *
152
+ * This method requires either the root API key or the API key to be set.
153
+ * If neither is set, it will throw an error.
154
+ *
155
+ * @param {Object} data - The data to be validated.
156
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
157
+ * @throws Will throw an error if there is an issue with the validation process.
158
+ */
159
+ async isValidData(data) {
160
+ return await PrivateAPI.isValidData(this.rootApiKey || this.apiKey, data);
161
+ }
162
+ /**
163
+ * Sends an email using the configured email client settings.
164
+ *
165
+ * This method requires either the root API key or the server email config to be set.
166
+ * If neither is set, it will throw an error.
167
+ *
168
+ * @param {Object} data - The email data to be sent.
169
+ * @param {string} data.from - The email address from which the email will be sent.
170
+ * @param {string} data.to - The email address to which the email will be sent.
171
+ * @param {string} data.subject - The subject of the email.
172
+ * @param {string} data.html - The HTML content of the email.
173
+ * @param {React.ReactElement} data.react - The React component to be rendered as the email content.
174
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
175
+ * @throws Will throw an error if there is an issue with the email sending process.
176
+ */
177
+ async sendEmail(data) {
178
+ if (!this.serverEmailConfig && !this.rootApiKey)
179
+ throw customError(5000, "You must configure the email client settings.");
180
+ return await PrivateAPI.sendEmail(this.rootApiKey || this.apiKey, { serverEmailConfig: this.serverEmailConfig, ...data });
181
+ }
182
+ /**
183
+ * Generates a random number between the provided min and max values.
184
+ *
185
+ * This method requires either the root API key or the API key to be set.
186
+ * If neither is set, it will throw an error.
187
+ *
188
+ * @param {Object} data - The data to be sent.
189
+ * @param {number} data.min - The minimum value of the range.
190
+ * @param {number} data.max - The maximum value of the range.
191
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
192
+ * @throws Will throw an error if there is an issue with the random number generation process.
193
+ */
194
+ async getRandom(data) {
195
+ return await PrivateAPI.getRandom(this.rootApiKey || this.apiKey, data);
196
+ }
197
+ // FUNCTIONS / Public.
198
+ /**
199
+ * Retrieves the prayer times for the given location.
200
+ *
201
+ * This method requires a latitude and longitude to be provided in the
202
+ * data object. If either of these are not provided, it will throw an error.
203
+ *
204
+ * @param {Object} data - The data to be sent.
205
+ * @param {number} data.lat - The latitude of the location.
206
+ * @param {number} data.lon - The longitude of the location.
207
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
208
+ * @throws Will throw an error if there is an issue with the prayer times retrieval process.
209
+ */
210
+ async getPrayerTimes(data) {
211
+ return await PublicAPI.getPrayerTimes(data);
212
+ }
213
+ /**
214
+ * Satinizes the input, replacing any special characters with their HTML
215
+ * entities.
216
+ *
217
+ * @param {Object} data - The data to be sent.
218
+ * @param {string} data.input - The input to be satinized.
219
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
220
+ * @throws Will throw an error if there is an issue with the satinization process.
221
+ */
222
+ async satinizer(data) {
223
+ return await PublicAPI.satinizer(data);
224
+ }
225
+ /**
226
+ * Validates a password based on the given parameters.
227
+ *
228
+ * This method requires the password to be provided in the data object.
229
+ * If the password is not provided, it will throw an error. The method
230
+ * will validate the password against the following rules:
231
+ * - The password must be at least 8 characters long.
232
+ * - The password must be at most 32 characters long.
233
+ * - The password must contain at least one uppercase letter.
234
+ * - The password must contain at least one lowercase letter.
235
+ * - The password must contain at least one number.
236
+ * - The password must contain at least one special character.
237
+ * - The password must not contain any of the given banned words.
238
+ *
239
+ * @param {Object} data - The data to be sent.
240
+ * @param {string} data.password - The password to be validated.
241
+ * @param {string[]} [data.bannedWords] - The list of banned words that the password must not contain.
242
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
243
+ * @throws Will throw an error if there is an issue with the password validation process.
244
+ */
245
+ async isValidPwd(data) {
246
+ return await PublicAPI.isValidPwd(data);
247
+ }
248
+ /**
249
+ * Encrypts a URL using the configured encryption settings.
250
+ *
251
+ * This method requires the URL to be provided in the data object.
252
+ * If the URL is not provided, it will throw an error.
253
+ *
254
+ * @param {Object} data - The data to be sent.
255
+ * @param {string} data.url - The URL to be encrypted.
256
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
257
+ * @throws Will throw an error if there is an issue with the URL encryption process.
258
+ */
259
+ async newURLEncrypt(data) {
260
+ return await PublicAPI.newURLEncrypt(data);
261
+ }
262
+ }
263
+ exports.default = DymoAPI;
@@ -5,22 +5,23 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.checkForUpdates = checkForUpdates;
7
7
  const axios_1 = __importDefault(require("axios"));
8
+ //@ts-ignore
8
9
  const child_process_1 = require("child_process");
9
- const localVersion = (0, child_process_1.execSync)(`npm list dymo-api --depth=0`).toString().match(new RegExp(`dymo-api@(\\d+\\.\\d+\\.\\d+)`))?.[1] || "0.0.0";
10
+ const localVersion = (0, child_process_1.execSync)("npm list dymo-api --depth=0").toString().match(new RegExp("dymo-api@(\\d+\\.\\d+\\.\\d+)"))?.[1] || "0.0.0";
10
11
  async function checkForUpdates() {
11
12
  try {
12
13
  const response = await axios_1.default.get("https://registry.npmjs.org/dymo-api/latest");
13
14
  const latestVersion = response.data.version;
14
15
  if (localVersion !== latestVersion)
15
- console.log(`A new version of dymo-api is available: ${latestVersion}. You are using ${localVersion}. Consider updating.`);
16
+ console.log(`[Dymo API] A new version of dymo-api is available: ${latestVersion}. You are using ${localVersion}. Consider updating.`);
16
17
  }
17
18
  catch (error) {
18
19
  if (error.response)
19
- console.error("Error fetching the latest version:", error.response.data);
20
+ console.error("[Dymo API] Error fetching the latest version:", error.response.data);
20
21
  else if (error.request)
21
- console.error("No response received from the server:", error.request);
22
+ console.error("[Dymo API] No response received from the server:", error.request);
22
23
  else
23
- console.error("An unknown error occurred:", error.message);
24
+ console.error("[Dymo API] An unknown error occurred:", error.message);
24
25
  }
25
26
  }
26
27
  ;
@@ -0,0 +1,76 @@
1
+ import axios from "axios";
2
+ import config, { BASE_URL } from "../config";
3
+ import { render } from "@react-email/render";
4
+ const customError = (code, message) => {
5
+ return Object.assign(new Error(), { code, message: `[${config.lib.name}] ${message}` });
6
+ };
7
+ export const isValidData = async (token, data) => {
8
+ if (token === null)
9
+ throw customError(3000, "Invalid private token.");
10
+ let i = false;
11
+ for (const key in data) {
12
+ if (data.hasOwnProperty(key) && (key === "email" || key === "phone" || key === "domain" || key === "creditCard" || key === "ip" || key === "wallet")) {
13
+ i = true;
14
+ break;
15
+ }
16
+ }
17
+ if (!i)
18
+ throw customError(1500, "You must provide at least one parameter.");
19
+ try {
20
+ const response = await axios.post(`${BASE_URL}/v1/private/secure/verify`, data, { headers: { "Authorization": token } });
21
+ return response.data;
22
+ }
23
+ catch (error) {
24
+ throw customError(5000, error.response?.data?.message || error.message);
25
+ }
26
+ };
27
+ export const sendEmail = async (token, data) => {
28
+ if (token === null)
29
+ throw customError(3000, "Invalid private token.");
30
+ if (!data.from)
31
+ throw customError(1500, "You must provide an email address from which the following will be sent.");
32
+ if (!data.to)
33
+ throw customError(1500, "You must provide an email to be sent to.");
34
+ if (!data.subject)
35
+ throw customError(1500, "You must provide a subject for the email to be sent.");
36
+ if (!data.html && !data.react)
37
+ throw customError(1500, "You must provide HTML or a React component.");
38
+ if (data.html && data.react)
39
+ throw customError(1500, "You must provide only HTML or a React component, not both.");
40
+ try {
41
+ if (data.react) {
42
+ //@ts-ignore
43
+ data.html = await render(data.react);
44
+ delete data.react;
45
+ }
46
+ }
47
+ catch (error) {
48
+ throw customError(1500, `An error occurred while rendering your React component. Details: ${error}`);
49
+ }
50
+ try {
51
+ const response = await axios.post(`${BASE_URL}/v1/private/sender/sendEmail`, data, { headers: { "Authorization": token } });
52
+ return response.data;
53
+ }
54
+ catch (error) {
55
+ throw customError(5000, error.response?.data?.message || error.message);
56
+ }
57
+ };
58
+ export const getRandom = async (token, data) => {
59
+ if (token === null)
60
+ throw customError(3000, "Invalid private token.");
61
+ if (!data.min || !data.max)
62
+ throw customError(1500, "Both 'min' and 'max' parameters must be defined.");
63
+ if (data.min >= data.max)
64
+ throw customError(1500, "'min' must be less than 'max'.");
65
+ if (data.min < -1000000000 || data.min > 1000000000)
66
+ throw customError(1500, "'min' must be an integer in the interval [-1000000000}, 1000000000].");
67
+ if (data.max < -1000000000 || data.max > 1000000000)
68
+ throw customError(1500, "'max' must be an integer in the interval [-1000000000}, 1000000000].");
69
+ try {
70
+ const response = await axios.post(`${BASE_URL}/v1/private/srng`, data, { headers: { "Authorization": token } });
71
+ return response.data;
72
+ }
73
+ catch (error) {
74
+ throw customError(5000, error.response?.data?.message || error.message);
75
+ }
76
+ };
@@ -0,0 +1,80 @@
1
+ import axios from "axios";
2
+ import config, { BASE_URL } from "../config";
3
+ const customError = (code, message) => {
4
+ return Object.assign(new Error(), { code, message: `[${config.lib.name}] ${message}` });
5
+ };
6
+ ;
7
+ ;
8
+ ;
9
+ ;
10
+ export const getPrayerTimes = async (data) => {
11
+ const { lat, lon } = data;
12
+ if (lat === undefined || lon === undefined)
13
+ throw customError(1000, "You must provide a latitude and longitude.");
14
+ try {
15
+ const response = await axios.get(`${BASE_URL}/v1/public/islam/prayertimes`, { params: data });
16
+ return response.data;
17
+ }
18
+ catch (error) {
19
+ throw customError(5000, error.response?.data?.message || error.message);
20
+ }
21
+ };
22
+ export const satinizer = async (data) => {
23
+ const { input } = data;
24
+ if (input === undefined)
25
+ throw customError(1000, "You must specify at least the input.");
26
+ try {
27
+ const response = await axios.get(`${BASE_URL}/v1/public/inputSatinizer`, { params: { input: encodeURIComponent(input) } });
28
+ return response.data;
29
+ }
30
+ catch (error) {
31
+ throw customError(5000, error.response?.data?.message || error.message);
32
+ }
33
+ };
34
+ export const isValidPwd = async (data) => {
35
+ let { email, password, bannedWords, min, max } = data;
36
+ if (password === undefined)
37
+ throw customError(1000, "You must specify at least the password.");
38
+ const params = { password: encodeURIComponent(password) };
39
+ if (email) {
40
+ if (!/^[a-zA-Z0-9._\-+]+@?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(email))
41
+ throw customError(1500, "If you provide an email address it must be valid.");
42
+ params.email = encodeURIComponent(email);
43
+ }
44
+ if (bannedWords) {
45
+ if (typeof bannedWords === "string")
46
+ bannedWords = bannedWords.slice(1, -1).trim().split(",").map(item => item.trim());
47
+ if (!Array.isArray(bannedWords) || bannedWords.length > 10)
48
+ throw customError(1500, "If you provide a list of banned words; the list may not exceed 10 words and must be of array type.");
49
+ if (!bannedWords.every(word => typeof word === "string") || new Set(bannedWords).size !== bannedWords.length)
50
+ throw customError(1500, "If you provide a list of banned words; all elements must be non-repeated strings.");
51
+ params.bannedWords = bannedWords;
52
+ }
53
+ if (min !== undefined && (!Number.isInteger(min) || min < 8 || min > 32))
54
+ throw customError(1500, "If you provide a minimum it must be valid.");
55
+ if (max !== undefined && (!Number.isInteger(max) || max < 32 || max > 100))
56
+ throw customError(1500, "If you provide a maximum it must be valid.");
57
+ if (min !== undefined)
58
+ params.min = min;
59
+ if (max !== undefined)
60
+ params.max = max;
61
+ try {
62
+ const response = await axios.get(`${BASE_URL}/v1/public/validPwd`, { params });
63
+ return response.data;
64
+ }
65
+ catch (error) {
66
+ throw customError(5000, error.response?.data?.message || error.message);
67
+ }
68
+ };
69
+ export const newURLEncrypt = async (data) => {
70
+ const { url } = data;
71
+ if (url === undefined || (!url.startsWith("https://") && !url.startsWith("http://")))
72
+ throw customError(1500, "You must provide a valid url.");
73
+ try {
74
+ const response = await axios.get(`${BASE_URL}/v1/public/url-encrypt`, { params: data });
75
+ return response.data;
76
+ }
77
+ catch (error) {
78
+ throw customError(5000, error.response?.data?.message || error.message);
79
+ }
80
+ };
@@ -0,0 +1,15 @@
1
+ const config = {
2
+ lib: {
3
+ name: "Dymo API",
4
+ dir: "dymo-api"
5
+ },
6
+ env: {
7
+ baseUrl: "https://api.tpeoficial.com"
8
+ }
9
+ };
10
+ export default config;
11
+ let BASE_URL = config.env.baseUrl;
12
+ export const setBaseUrl = (isLocal) => {
13
+ BASE_URL = isLocal ? "http://localhost:3050" : config.env.baseUrl;
14
+ };
15
+ export { BASE_URL };
@@ -0,0 +1,235 @@
1
+ import axios from "axios";
2
+ import * as PublicAPI from "./branches/public";
3
+ import * as PrivateAPI from "./branches/private";
4
+ import config, { BASE_URL, setBaseUrl } from "./config";
5
+ import { checkForUpdates } from "./services/autoupdate";
6
+ const customError = (code, message) => {
7
+ return Object.assign(new Error(), { code, message: `[${config.lib.name}] ${message}` });
8
+ };
9
+ ;
10
+ ;
11
+ ;
12
+ class DymoAPI {
13
+ /**
14
+ * @param {Object} options - Options to create the DymoAPI instance.
15
+ * @param {string} [options.rootApiKey] - The root API key.
16
+ * @param {string} [options.apiKey] - The API key.
17
+ * @param {boolean} [options.local] - Whether to use a local server instead of the cloud server.
18
+ * @param {Object} [options.serverEmailConfig] - The server email config.
19
+ * @description
20
+ * This is the main class to interact with the Dymo API. It should be
21
+ * instantiated with the root API key and the API key. The root API key is
22
+ * used to fetch the tokens and the API key is used to authenticate the
23
+ * requests.
24
+ * @example
25
+ * const dymoApi = new DymoAPI({
26
+ * rootApiKey: "6bfb7675-6b69-4f8d-9f43-5a6f7f02c6c5",
27
+ * apiKey: "4c8b7675-6b69-4f8d-9f43-5a6f7f02c6c5",
28
+ * local: true
29
+ * });
30
+ */
31
+ constructor({ rootApiKey = null, apiKey = null, local = false, serverEmailConfig = undefined }) {
32
+ this.rootApiKey = rootApiKey;
33
+ this.apiKey = apiKey;
34
+ this.tokensResponse = null;
35
+ this.lastFetchTime = null;
36
+ this.serverEmailConfig = serverEmailConfig;
37
+ this.local = rootApiKey ? local : false; // Only allow setting local if rootApiKey is defined.
38
+ setBaseUrl(this.local);
39
+ this.autoupdate();
40
+ this.initializeTokens(); // Calls the function to obtain tokens when creating the object.
41
+ }
42
+ /**
43
+ * Retrieves and caches authentication tokens.
44
+ *
45
+ * This method checks if cached tokens are available and valid. If so, it returns
46
+ * the cached tokens. Otherwise, it generates new tokens using the provided API keys
47
+ * and caches them. The tokens are fetched from the server using a POST request.
48
+ *
49
+ * The method also handles validation of root and API tokens, throwing errors if
50
+ * any of the tokens are invalid. Cached tokens are considered valid for 5 minutes.
51
+ *
52
+ * @returns {Promise<Object|undefined>} A promise that resolves to the tokens response
53
+ * if successful, or undefined if no tokens are available.
54
+ * @throws Will throw an error if token validation fails, or if there is an issue
55
+ * with the token retrieval process.
56
+ */
57
+ async getTokens() {
58
+ const currentTime = new Date();
59
+ if (this.tokensResponse && this.lastFetchTime && (currentTime.getTime() - this.lastFetchTime.getTime()) < 5 * 60 * 1000) {
60
+ console.log(`[${config.lib.name}] Using cached tokens response.`);
61
+ return this.tokensResponse;
62
+ }
63
+ ;
64
+ const tokens = {};
65
+ if (this.rootApiKey)
66
+ tokens.root = `Bearer ${this.rootApiKey}`;
67
+ if (this.apiKey)
68
+ tokens.api = `Bearer ${this.apiKey}`;
69
+ try {
70
+ if (Object.keys(tokens).length === 0)
71
+ return;
72
+ const response = await axios.post(`${BASE_URL}/v1/dvr/tokens`, { tokens });
73
+ if (tokens.root && response.data.root === false)
74
+ throw customError(3000, "Invalid root token.");
75
+ if (tokens.api && response.data.api === false)
76
+ throw customError(3000, "Invalid API token.");
77
+ this.tokensResponse = response.data;
78
+ this.lastFetchTime = currentTime;
79
+ console.log(`[${config.lib.name}] Tokens initialized successfully.`);
80
+ return this.tokensResponse;
81
+ }
82
+ catch (error) {
83
+ throw customError(5000, error.message);
84
+ }
85
+ }
86
+ /**
87
+ * Initializes the tokens response by calling getTokens().
88
+ *
89
+ * This method is called in the constructor and will throw an error if the
90
+ * initialization process fails.
91
+ *
92
+ * @throws Will throw an error if there is an issue with the token retrieval
93
+ * process.
94
+ */
95
+ async initializeTokens() {
96
+ try {
97
+ await this.getTokens();
98
+ }
99
+ catch (error) {
100
+ throw customError(5000, `Error initializing tokens: ${error.message}`);
101
+ }
102
+ }
103
+ /**
104
+ * Checks for updates and logs a message if a new version is available.
105
+ *
106
+ * This method is called in the constructor and will throw an error if the
107
+ * update check fails.
108
+ *
109
+ * @throws Will throw an error if there is an issue with the update check
110
+ * process.
111
+ */
112
+ async autoupdate() {
113
+ try {
114
+ await checkForUpdates();
115
+ }
116
+ catch (error) {
117
+ throw customError(5000, `Error checking the latest version in npmjs: ${error.message}`);
118
+ }
119
+ }
120
+ // FUNCTIONS / Private.
121
+ /**
122
+ * Validates the given data against the configured validation settings.
123
+ *
124
+ * This method requires either the root API key or the API key to be set.
125
+ * If neither is set, it will throw an error.
126
+ *
127
+ * @param {Object} data - The data to be validated.
128
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
129
+ * @throws Will throw an error if there is an issue with the validation process.
130
+ */
131
+ async isValidData(data) {
132
+ return await PrivateAPI.isValidData(this.rootApiKey || this.apiKey, data);
133
+ }
134
+ /**
135
+ * Sends an email using the configured email client settings.
136
+ *
137
+ * This method requires either the root API key or the server email config to be set.
138
+ * If neither is set, it will throw an error.
139
+ *
140
+ * @param {Object} data - The email data to be sent.
141
+ * @param {string} data.from - The email address from which the email will be sent.
142
+ * @param {string} data.to - The email address to which the email will be sent.
143
+ * @param {string} data.subject - The subject of the email.
144
+ * @param {string} data.html - The HTML content of the email.
145
+ * @param {React.ReactElement} data.react - The React component to be rendered as the email content.
146
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
147
+ * @throws Will throw an error if there is an issue with the email sending process.
148
+ */
149
+ async sendEmail(data) {
150
+ if (!this.serverEmailConfig && !this.rootApiKey)
151
+ throw customError(5000, "You must configure the email client settings.");
152
+ return await PrivateAPI.sendEmail(this.rootApiKey || this.apiKey, { serverEmailConfig: this.serverEmailConfig, ...data });
153
+ }
154
+ /**
155
+ * Generates a random number between the provided min and max values.
156
+ *
157
+ * This method requires either the root API key or the API key to be set.
158
+ * If neither is set, it will throw an error.
159
+ *
160
+ * @param {Object} data - The data to be sent.
161
+ * @param {number} data.min - The minimum value of the range.
162
+ * @param {number} data.max - The maximum value of the range.
163
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
164
+ * @throws Will throw an error if there is an issue with the random number generation process.
165
+ */
166
+ async getRandom(data) {
167
+ return await PrivateAPI.getRandom(this.rootApiKey || this.apiKey, data);
168
+ }
169
+ // FUNCTIONS / Public.
170
+ /**
171
+ * Retrieves the prayer times for the given location.
172
+ *
173
+ * This method requires a latitude and longitude to be provided in the
174
+ * data object. If either of these are not provided, it will throw an error.
175
+ *
176
+ * @param {Object} data - The data to be sent.
177
+ * @param {number} data.lat - The latitude of the location.
178
+ * @param {number} data.lon - The longitude of the location.
179
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
180
+ * @throws Will throw an error if there is an issue with the prayer times retrieval process.
181
+ */
182
+ async getPrayerTimes(data) {
183
+ return await PublicAPI.getPrayerTimes(data);
184
+ }
185
+ /**
186
+ * Satinizes the input, replacing any special characters with their HTML
187
+ * entities.
188
+ *
189
+ * @param {Object} data - The data to be sent.
190
+ * @param {string} data.input - The input to be satinized.
191
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
192
+ * @throws Will throw an error if there is an issue with the satinization process.
193
+ */
194
+ async satinizer(data) {
195
+ return await PublicAPI.satinizer(data);
196
+ }
197
+ /**
198
+ * Validates a password based on the given parameters.
199
+ *
200
+ * This method requires the password to be provided in the data object.
201
+ * If the password is not provided, it will throw an error. The method
202
+ * will validate the password against the following rules:
203
+ * - The password must be at least 8 characters long.
204
+ * - The password must be at most 32 characters long.
205
+ * - The password must contain at least one uppercase letter.
206
+ * - The password must contain at least one lowercase letter.
207
+ * - The password must contain at least one number.
208
+ * - The password must contain at least one special character.
209
+ * - The password must not contain any of the given banned words.
210
+ *
211
+ * @param {Object} data - The data to be sent.
212
+ * @param {string} data.password - The password to be validated.
213
+ * @param {string[]} [data.bannedWords] - The list of banned words that the password must not contain.
214
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
215
+ * @throws Will throw an error if there is an issue with the password validation process.
216
+ */
217
+ async isValidPwd(data) {
218
+ return await PublicAPI.isValidPwd(data);
219
+ }
220
+ /**
221
+ * Encrypts a URL using the configured encryption settings.
222
+ *
223
+ * This method requires the URL to be provided in the data object.
224
+ * If the URL is not provided, it will throw an error.
225
+ *
226
+ * @param {Object} data - The data to be sent.
227
+ * @param {string} data.url - The URL to be encrypted.
228
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
229
+ * @throws Will throw an error if there is an issue with the URL encryption process.
230
+ */
231
+ async newURLEncrypt(data) {
232
+ return await PublicAPI.newURLEncrypt(data);
233
+ }
234
+ }
235
+ export default DymoAPI;
@@ -0,0 +1,4 @@
1
+ ;
2
+ ;
3
+ ;
4
+ export {};
@@ -0,0 +1,21 @@
1
+ import axios from "axios";
2
+ //@ts-ignore
3
+ import { execSync } from "child_process";
4
+ const localVersion = execSync("npm list dymo-api --depth=0").toString().match(new RegExp("dymo-api@(\\d+\\.\\d+\\.\\d+)"))?.[1] || "0.0.0";
5
+ export async function checkForUpdates() {
6
+ try {
7
+ const response = await axios.get("https://registry.npmjs.org/dymo-api/latest");
8
+ const latestVersion = response.data.version;
9
+ if (localVersion !== latestVersion)
10
+ console.log(`[Dymo API] A new version of dymo-api is available: ${latestVersion}. You are using ${localVersion}. Consider updating.`);
11
+ }
12
+ catch (error) {
13
+ if (error.response)
14
+ console.error("[Dymo API] Error fetching the latest version:", error.response.data);
15
+ else if (error.request)
16
+ console.error("[Dymo API] No response received from the server:", error.request);
17
+ else
18
+ console.error("[Dymo API] An unknown error occurred:", error.message);
19
+ }
20
+ }
21
+ ;
@@ -19,21 +19,161 @@ declare class DymoAPI {
19
19
  private lastFetchTime;
20
20
  private serverEmailConfig?;
21
21
  private local;
22
+ /**
23
+ * @param {Object} options - Options to create the DymoAPI instance.
24
+ * @param {string} [options.rootApiKey] - The root API key.
25
+ * @param {string} [options.apiKey] - The API key.
26
+ * @param {boolean} [options.local] - Whether to use a local server instead of the cloud server.
27
+ * @param {Object} [options.serverEmailConfig] - The server email config.
28
+ * @description
29
+ * This is the main class to interact with the Dymo API. It should be
30
+ * instantiated with the root API key and the API key. The root API key is
31
+ * used to fetch the tokens and the API key is used to authenticate the
32
+ * requests.
33
+ * @example
34
+ * const dymoApi = new DymoAPI({
35
+ * rootApiKey: "6bfb7675-6b69-4f8d-9f43-5a6f7f02c6c5",
36
+ * apiKey: "4c8b7675-6b69-4f8d-9f43-5a6f7f02c6c5",
37
+ * local: true
38
+ * });
39
+ */
22
40
  constructor({ rootApiKey, apiKey, local, serverEmailConfig }: {
23
41
  rootApiKey?: string | null;
24
42
  apiKey?: string | null;
25
43
  local?: boolean;
26
44
  serverEmailConfig?: ServerEmailConfig;
27
45
  });
46
+ /**
47
+ * Retrieves and caches authentication tokens.
48
+ *
49
+ * This method checks if cached tokens are available and valid. If so, it returns
50
+ * the cached tokens. Otherwise, it generates new tokens using the provided API keys
51
+ * and caches them. The tokens are fetched from the server using a POST request.
52
+ *
53
+ * The method also handles validation of root and API tokens, throwing errors if
54
+ * any of the tokens are invalid. Cached tokens are considered valid for 5 minutes.
55
+ *
56
+ * @returns {Promise<Object|undefined>} A promise that resolves to the tokens response
57
+ * if successful, or undefined if no tokens are available.
58
+ * @throws Will throw an error if token validation fails, or if there is an issue
59
+ * with the token retrieval process.
60
+ */
28
61
  private getTokens;
62
+ /**
63
+ * Initializes the tokens response by calling getTokens().
64
+ *
65
+ * This method is called in the constructor and will throw an error if the
66
+ * initialization process fails.
67
+ *
68
+ * @throws Will throw an error if there is an issue with the token retrieval
69
+ * process.
70
+ */
29
71
  private initializeTokens;
72
+ /**
73
+ * Checks for updates and logs a message if a new version is available.
74
+ *
75
+ * This method is called in the constructor and will throw an error if the
76
+ * update check fails.
77
+ *
78
+ * @throws Will throw an error if there is an issue with the update check
79
+ * process.
80
+ */
30
81
  private autoupdate;
82
+ /**
83
+ * Validates the given data against the configured validation settings.
84
+ *
85
+ * This method requires either the root API key or the API key to be set.
86
+ * If neither is set, it will throw an error.
87
+ *
88
+ * @param {Object} data - The data to be validated.
89
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
90
+ * @throws Will throw an error if there is an issue with the validation process.
91
+ */
31
92
  isValidData(data: any): Promise<any>;
93
+ /**
94
+ * Sends an email using the configured email client settings.
95
+ *
96
+ * This method requires either the root API key or the server email config to be set.
97
+ * If neither is set, it will throw an error.
98
+ *
99
+ * @param {Object} data - The email data to be sent.
100
+ * @param {string} data.from - The email address from which the email will be sent.
101
+ * @param {string} data.to - The email address to which the email will be sent.
102
+ * @param {string} data.subject - The subject of the email.
103
+ * @param {string} data.html - The HTML content of the email.
104
+ * @param {React.ReactElement} data.react - The React component to be rendered as the email content.
105
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
106
+ * @throws Will throw an error if there is an issue with the email sending process.
107
+ */
32
108
  sendEmail(data: any): Promise<any>;
109
+ /**
110
+ * Generates a random number between the provided min and max values.
111
+ *
112
+ * This method requires either the root API key or the API key to be set.
113
+ * If neither is set, it will throw an error.
114
+ *
115
+ * @param {Object} data - The data to be sent.
116
+ * @param {number} data.min - The minimum value of the range.
117
+ * @param {number} data.max - The maximum value of the range.
118
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
119
+ * @throws Will throw an error if there is an issue with the random number generation process.
120
+ */
33
121
  getRandom(data: any): Promise<any>;
122
+ /**
123
+ * Retrieves the prayer times for the given location.
124
+ *
125
+ * This method requires a latitude and longitude to be provided in the
126
+ * data object. If either of these are not provided, it will throw an error.
127
+ *
128
+ * @param {Object} data - The data to be sent.
129
+ * @param {number} data.lat - The latitude of the location.
130
+ * @param {number} data.lon - The longitude of the location.
131
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
132
+ * @throws Will throw an error if there is an issue with the prayer times retrieval process.
133
+ */
34
134
  getPrayerTimes(data: any): Promise<any>;
135
+ /**
136
+ * Satinizes the input, replacing any special characters with their HTML
137
+ * entities.
138
+ *
139
+ * @param {Object} data - The data to be sent.
140
+ * @param {string} data.input - The input to be satinized.
141
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
142
+ * @throws Will throw an error if there is an issue with the satinization process.
143
+ */
35
144
  satinizer(data: any): Promise<any>;
145
+ /**
146
+ * Validates a password based on the given parameters.
147
+ *
148
+ * This method requires the password to be provided in the data object.
149
+ * If the password is not provided, it will throw an error. The method
150
+ * will validate the password against the following rules:
151
+ * - The password must be at least 8 characters long.
152
+ * - The password must be at most 32 characters long.
153
+ * - The password must contain at least one uppercase letter.
154
+ * - The password must contain at least one lowercase letter.
155
+ * - The password must contain at least one number.
156
+ * - The password must contain at least one special character.
157
+ * - The password must not contain any of the given banned words.
158
+ *
159
+ * @param {Object} data - The data to be sent.
160
+ * @param {string} data.password - The password to be validated.
161
+ * @param {string[]} [data.bannedWords] - The list of banned words that the password must not contain.
162
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
163
+ * @throws Will throw an error if there is an issue with the password validation process.
164
+ */
36
165
  isValidPwd(data: any): Promise<any>;
166
+ /**
167
+ * Encrypts a URL using the configured encryption settings.
168
+ *
169
+ * This method requires the URL to be provided in the data object.
170
+ * If the URL is not provided, it will throw an error.
171
+ *
172
+ * @param {Object} data - The data to be sent.
173
+ * @param {string} data.url - The URL to be encrypted.
174
+ * @returns {Promise<Object>} A promise that resolves to the response from the server.
175
+ * @throws Will throw an error if there is an issue with the URL encryption process.
176
+ */
37
177
  newURLEncrypt(data: any): Promise<any>;
38
178
  }
39
179
  export default DymoAPI;
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "dymo-api",
3
- "version": "1.0.37",
3
+ "version": "1.0.39",
4
4
  "description": "Flow system for Dymo API.",
5
- "main": "dist/dymo-api.js",
6
- "module": "dist/dymo-api.mjs",
5
+ "main": "dist/cjs/dymo-api.js",
6
+ "module": "dist/esm/dymo-api.mjs",
7
+ "types": "dist/types/dymo-api.d.ts",
7
8
  "files": [
8
9
  "dist/**/*",
9
10
  "README.md",
10
11
  "LICENSE"
11
12
  ],
12
- "types": "dist/types/dymo-api.d.ts",
13
13
  "scripts": {
14
- "build": "tsc && shx cp dist/dymo-api.js dist/dymo-api.mjs",
14
+ "build": "tsc -p tsconfig.cjs.json && tsc -p tsconfig.esm.json",
15
15
  "start": "ts-node src/dymo-api.ts",
16
16
  "prepublishOnly": "npm run build",
17
17
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -43,7 +43,8 @@
43
43
  "devDependencies": {
44
44
  "@types/axios": "^0.9.36",
45
45
  "@types/node": "^22.0.2",
46
+ "rimraf": "^6.0.1",
46
47
  "ts-node": "^10.9.2",
47
48
  "typescript": "^5.5.4"
48
49
  }
49
- }
50
+ }
package/dist/dymo-api.js DELETED
@@ -1,124 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- const axios_1 = __importDefault(require("axios"));
30
- const PublicAPI = __importStar(require("./branches/public"));
31
- const PrivateAPI = __importStar(require("./branches/private"));
32
- const config_1 = __importStar(require("./config"));
33
- const autoupdate_1 = require("./services/autoupdate");
34
- const customError = (code, message) => {
35
- return Object.assign(new Error(), { code, message: `[${config_1.default.lib.name}] ${message}` });
36
- };
37
- ;
38
- ;
39
- ;
40
- class DymoAPI {
41
- constructor({ rootApiKey = null, apiKey = null, local = false, serverEmailConfig = undefined }) {
42
- this.rootApiKey = rootApiKey;
43
- this.apiKey = apiKey;
44
- this.tokensResponse = null;
45
- this.lastFetchTime = null;
46
- this.serverEmailConfig = serverEmailConfig;
47
- this.local = rootApiKey ? local : false; // Only allow setting local if rootApiKey is defined.
48
- (0, config_1.setBaseUrl)(this.local);
49
- this.autoupdate();
50
- this.initializeTokens(); // Calls the function to obtain tokens when creating the object.
51
- }
52
- async getTokens() {
53
- const currentTime = new Date();
54
- if (this.tokensResponse && this.lastFetchTime && (currentTime.getTime() - this.lastFetchTime.getTime()) < 5 * 60 * 1000) {
55
- console.log(`[${config_1.default.lib.name}] Using cached tokens response.`);
56
- return this.tokensResponse;
57
- }
58
- ;
59
- const tokens = {};
60
- if (this.rootApiKey)
61
- tokens.root = `Bearer ${this.rootApiKey}`;
62
- if (this.apiKey)
63
- tokens.api = `Bearer ${this.apiKey}`;
64
- try {
65
- if (Object.keys(tokens).length === 0)
66
- return;
67
- const response = await axios_1.default.post(`${config_1.BASE_URL}/v1/dvr/tokens`, { tokens });
68
- if (tokens.root && response.data.root === false)
69
- throw customError(3000, "Invalid root token.");
70
- if (tokens.api && response.data.api === false)
71
- throw customError(3000, "Invalid API token.");
72
- this.tokensResponse = response.data;
73
- this.lastFetchTime = currentTime;
74
- console.log(`[${config_1.default.lib.name}] Tokens initialized successfully.`);
75
- return this.tokensResponse;
76
- }
77
- catch (error) {
78
- throw customError(5000, error.message);
79
- }
80
- }
81
- async initializeTokens() {
82
- try {
83
- await this.getTokens();
84
- }
85
- catch (error) {
86
- throw customError(5000, `Error initializing tokens: ${error.message}`);
87
- }
88
- }
89
- async autoupdate() {
90
- try {
91
- await (0, autoupdate_1.checkForUpdates)();
92
- }
93
- catch (error) {
94
- throw customError(5000, `Error checking the latest version in npmjs: ${error.message}`);
95
- }
96
- }
97
- // FUNCTIONS / Private.
98
- async isValidData(data) {
99
- return await PrivateAPI.isValidData(this.rootApiKey || this.apiKey, data);
100
- }
101
- async sendEmail(data) {
102
- console.log(this.serverEmailConfig, this.rootApiKey);
103
- if (!this.serverEmailConfig && !this.rootApiKey)
104
- throw customError(5000, "You must configure the email client settings.");
105
- return await PrivateAPI.sendEmail(this.rootApiKey || this.apiKey, { serverEmailConfig: this.serverEmailConfig, ...data });
106
- }
107
- async getRandom(data) {
108
- return await PrivateAPI.getRandom(this.rootApiKey || this.apiKey, data);
109
- }
110
- // FUNCTIONS / Public.
111
- async getPrayerTimes(data) {
112
- return await PublicAPI.getPrayerTimes(data);
113
- }
114
- async satinizer(data) {
115
- return await PublicAPI.satinizer(data);
116
- }
117
- async isValidPwd(data) {
118
- return await PublicAPI.isValidPwd(data);
119
- }
120
- async newURLEncrypt(data) {
121
- return await PublicAPI.newURLEncrypt(data);
122
- }
123
- }
124
- exports.default = DymoAPI;
package/dist/dymo-api.mjs DELETED
@@ -1,124 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- const axios_1 = __importDefault(require("axios"));
30
- const PublicAPI = __importStar(require("./branches/public"));
31
- const PrivateAPI = __importStar(require("./branches/private"));
32
- const config_1 = __importStar(require("./config"));
33
- const autoupdate_1 = require("./services/autoupdate");
34
- const customError = (code, message) => {
35
- return Object.assign(new Error(), { code, message: `[${config_1.default.lib.name}] ${message}` });
36
- };
37
- ;
38
- ;
39
- ;
40
- class DymoAPI {
41
- constructor({ rootApiKey = null, apiKey = null, local = false, serverEmailConfig = undefined }) {
42
- this.rootApiKey = rootApiKey;
43
- this.apiKey = apiKey;
44
- this.tokensResponse = null;
45
- this.lastFetchTime = null;
46
- this.serverEmailConfig = serverEmailConfig;
47
- this.local = rootApiKey ? local : false; // Only allow setting local if rootApiKey is defined.
48
- (0, config_1.setBaseUrl)(this.local);
49
- this.autoupdate();
50
- this.initializeTokens(); // Calls the function to obtain tokens when creating the object.
51
- }
52
- async getTokens() {
53
- const currentTime = new Date();
54
- if (this.tokensResponse && this.lastFetchTime && (currentTime.getTime() - this.lastFetchTime.getTime()) < 5 * 60 * 1000) {
55
- console.log(`[${config_1.default.lib.name}] Using cached tokens response.`);
56
- return this.tokensResponse;
57
- }
58
- ;
59
- const tokens = {};
60
- if (this.rootApiKey)
61
- tokens.root = `Bearer ${this.rootApiKey}`;
62
- if (this.apiKey)
63
- tokens.api = `Bearer ${this.apiKey}`;
64
- try {
65
- if (Object.keys(tokens).length === 0)
66
- return;
67
- const response = await axios_1.default.post(`${config_1.BASE_URL}/v1/dvr/tokens`, { tokens });
68
- if (tokens.root && response.data.root === false)
69
- throw customError(3000, "Invalid root token.");
70
- if (tokens.api && response.data.api === false)
71
- throw customError(3000, "Invalid API token.");
72
- this.tokensResponse = response.data;
73
- this.lastFetchTime = currentTime;
74
- console.log(`[${config_1.default.lib.name}] Tokens initialized successfully.`);
75
- return this.tokensResponse;
76
- }
77
- catch (error) {
78
- throw customError(5000, error.message);
79
- }
80
- }
81
- async initializeTokens() {
82
- try {
83
- await this.getTokens();
84
- }
85
- catch (error) {
86
- throw customError(5000, `Error initializing tokens: ${error.message}`);
87
- }
88
- }
89
- async autoupdate() {
90
- try {
91
- await (0, autoupdate_1.checkForUpdates)();
92
- }
93
- catch (error) {
94
- throw customError(5000, `Error checking the latest version in npmjs: ${error.message}`);
95
- }
96
- }
97
- // FUNCTIONS / Private.
98
- async isValidData(data) {
99
- return await PrivateAPI.isValidData(this.rootApiKey || this.apiKey, data);
100
- }
101
- async sendEmail(data) {
102
- console.log(this.serverEmailConfig, this.rootApiKey);
103
- if (!this.serverEmailConfig && !this.rootApiKey)
104
- throw customError(5000, "You must configure the email client settings.");
105
- return await PrivateAPI.sendEmail(this.rootApiKey || this.apiKey, { serverEmailConfig: this.serverEmailConfig, ...data });
106
- }
107
- async getRandom(data) {
108
- return await PrivateAPI.getRandom(this.rootApiKey || this.apiKey, data);
109
- }
110
- // FUNCTIONS / Public.
111
- async getPrayerTimes(data) {
112
- return await PublicAPI.getPrayerTimes(data);
113
- }
114
- async satinizer(data) {
115
- return await PublicAPI.satinizer(data);
116
- }
117
- async isValidPwd(data) {
118
- return await PublicAPI.isValidPwd(data);
119
- }
120
- async newURLEncrypt(data) {
121
- return await PublicAPI.newURLEncrypt(data);
122
- }
123
- }
124
- exports.default = DymoAPI;
File without changes
File without changes