dymo-api 1.2.31 → 1.2.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/cjs/dymo-api.cjs +1123 -393
  2. package/dist/esm/dymo-api.js +1125 -356
  3. package/dist/types/branches/private/functions/extractWithTextly/index.d.ts +3 -2
  4. package/dist/types/branches/private/functions/extractWithTextly/index.d.ts.map +1 -0
  5. package/dist/types/branches/private/functions/getRandom/index.d.ts +3 -2
  6. package/dist/types/branches/private/functions/getRandom/index.d.ts.map +1 -0
  7. package/dist/types/branches/private/functions/isValidDataRaw/index.d.ts +3 -2
  8. package/dist/types/branches/private/functions/isValidDataRaw/index.d.ts.map +1 -0
  9. package/dist/types/branches/private/functions/isValidEmail/index.d.ts +3 -2
  10. package/dist/types/branches/private/functions/isValidEmail/index.d.ts.map +1 -0
  11. package/dist/types/branches/private/functions/isValidIP/index.d.ts +3 -2
  12. package/dist/types/branches/private/functions/isValidIP/index.d.ts.map +1 -0
  13. package/dist/types/branches/private/functions/isValidPhone/index.d.ts +3 -2
  14. package/dist/types/branches/private/functions/isValidPhone/index.d.ts.map +1 -0
  15. package/dist/types/branches/private/functions/protectReq/index.d.ts +3 -2
  16. package/dist/types/branches/private/functions/protectReq/index.d.ts.map +1 -0
  17. package/dist/types/branches/private/functions/protectReq/requestHandler.d.ts +1 -0
  18. package/dist/types/branches/private/functions/protectReq/requestHandler.d.ts.map +1 -0
  19. package/dist/types/branches/private/functions/sendEmail/index.d.ts +3 -2
  20. package/dist/types/branches/private/functions/sendEmail/index.d.ts.map +1 -0
  21. package/dist/types/branches/private/index.d.ts +9 -8
  22. package/dist/types/branches/private/index.d.ts.map +1 -0
  23. package/dist/types/branches/public/functions/getPrayerTimes/index.d.ts +3 -2
  24. package/dist/types/branches/public/functions/getPrayerTimes/index.d.ts.map +1 -0
  25. package/dist/types/branches/public/functions/isValidPwd/index.d.ts +3 -2
  26. package/dist/types/branches/public/functions/isValidPwd/index.d.ts.map +1 -0
  27. package/dist/types/branches/public/functions/satinize/index.d.ts +2 -1
  28. package/dist/types/branches/public/functions/satinize/index.d.ts.map +1 -0
  29. package/dist/types/branches/public/index.d.ts +4 -3
  30. package/dist/types/branches/public/index.d.ts.map +1 -0
  31. package/dist/types/config/index.d.ts +1 -0
  32. package/dist/types/config/index.d.ts.map +1 -0
  33. package/dist/types/dymo-api.d.ts +2 -1
  34. package/dist/types/dymo-api.d.ts.map +1 -0
  35. package/dist/types/lib/resilience/fallback.d.ts +1 -0
  36. package/dist/types/lib/resilience/fallback.d.ts.map +1 -0
  37. package/dist/types/lib/resilience/index.d.ts +3 -2
  38. package/dist/types/lib/resilience/index.d.ts.map +1 -0
  39. package/dist/types/lib/types/data-verifier.d.ts +3 -2
  40. package/dist/types/lib/types/data-verifier.d.ts.map +1 -0
  41. package/dist/types/lib/types/interfaces.d.ts +5 -4
  42. package/dist/types/lib/types/interfaces.d.ts.map +1 -0
  43. package/dist/types/lib/types/primitives.d.ts +1 -0
  44. package/dist/types/lib/types/primitives.d.ts.map +1 -0
  45. package/dist/types/lib/types/rules.d.ts +2 -1
  46. package/dist/types/lib/types/rules.d.ts.map +1 -0
  47. package/dist/types/lib/types/well-known-bots.d.ts +1 -0
  48. package/dist/types/lib/types/well-known-bots.d.ts.map +1 -0
  49. package/dist/types/utils/basics.d.ts +1 -0
  50. package/dist/types/utils/basics.d.ts.map +1 -0
  51. package/package.json +9 -10
  52. package/dist/cjs/branches/private/functions/extractWithTextly/index.cjs +0 -33
  53. package/dist/cjs/branches/private/functions/getRandom/index.cjs +0 -37
  54. package/dist/cjs/branches/private/functions/isValidDataRaw/index.cjs +0 -33
  55. package/dist/cjs/branches/private/functions/isValidEmail/index.cjs +0 -91
  56. package/dist/cjs/branches/private/functions/isValidIP/index.cjs +0 -80
  57. package/dist/cjs/branches/private/functions/isValidPhone/index.cjs +0 -77
  58. package/dist/cjs/branches/private/functions/protectReq/index.cjs +0 -74
  59. package/dist/cjs/branches/private/functions/protectReq/requestHandler.cjs +0 -22
  60. package/dist/cjs/branches/private/functions/sendEmail/index.cjs +0 -88
  61. package/dist/cjs/branches/private/index.cjs +0 -24
  62. package/dist/cjs/branches/public/functions/getPrayerTimes/index.cjs +0 -31
  63. package/dist/cjs/branches/public/functions/isValidPwd/index.cjs +0 -65
  64. package/dist/cjs/branches/public/functions/satinize/index.cjs +0 -26
  65. package/dist/cjs/branches/public/index.cjs +0 -19
  66. package/dist/cjs/config/index.cjs +0 -12
  67. package/dist/cjs/lib/resilience/fallback.cjs +0 -427
  68. package/dist/cjs/lib/resilience/index.cjs +0 -135
  69. package/dist/cjs/lib/types/data-verifier.cjs +0 -2
  70. package/dist/cjs/lib/types/interfaces.cjs +0 -24
  71. package/dist/cjs/lib/types/primitives.cjs +0 -2
  72. package/dist/cjs/lib/types/rules.cjs +0 -2
  73. package/dist/cjs/lib/types/well-known-bots.cjs +0 -739
  74. package/dist/cjs/utils/basics.cjs +0 -18
  75. package/dist/esm/branches/private/functions/extractWithTextly/index.js +0 -29
  76. package/dist/esm/branches/private/functions/getRandom/index.js +0 -33
  77. package/dist/esm/branches/private/functions/isValidDataRaw/index.js +0 -29
  78. package/dist/esm/branches/private/functions/isValidEmail/index.js +0 -87
  79. package/dist/esm/branches/private/functions/isValidIP/index.js +0 -76
  80. package/dist/esm/branches/private/functions/isValidPhone/index.js +0 -73
  81. package/dist/esm/branches/private/functions/protectReq/index.js +0 -37
  82. package/dist/esm/branches/private/functions/protectReq/requestHandler.js +0 -18
  83. package/dist/esm/branches/private/functions/sendEmail/index.js +0 -81
  84. package/dist/esm/branches/private/index.js +0 -8
  85. package/dist/esm/branches/public/functions/getPrayerTimes/index.js +0 -27
  86. package/dist/esm/branches/public/functions/isValidPwd/index.js +0 -61
  87. package/dist/esm/branches/public/functions/satinize/index.js +0 -22
  88. package/dist/esm/branches/public/index.js +0 -3
  89. package/dist/esm/config/index.js +0 -10
  90. package/dist/esm/lib/resilience/fallback.js +0 -423
  91. package/dist/esm/lib/resilience/index.js +0 -131
  92. package/dist/esm/lib/types/data-verifier.js +0 -1
  93. package/dist/esm/lib/types/interfaces.js +0 -8
  94. package/dist/esm/lib/types/primitives.js +0 -1
  95. package/dist/esm/lib/types/rules.js +0 -1
  96. package/dist/esm/lib/types/well-known-bots.js +0 -736
  97. package/dist/esm/utils/basics.js +0 -10
@@ -1,370 +1,1139 @@
1
- import config from "./config/index.js";
2
1
  import axios from "axios";
3
- import { validBaseURL } from "./utils/basics.js";
4
- import * as PublicAPI from "./branches/public/index.js";
5
- import * as PrivateAPI from "./branches/private/index.js";
6
- import { ResilienceManager } from "./lib/resilience/index.js";
7
- import { FallbackDataGenerator } from "./lib/resilience/fallback.js";
8
- class DymoAPI {
9
- /**
10
- * @param {Object} options - Options to create the DymoAPI instance.
11
- * @param {string} [options.rootApiKey] - The root API key.
12
- * @param {string} [options.apiKey] - The API key.
13
- * @param {string} [options.baseUrl] - Whether to use a local server instead of the cloud server.
14
- * @param {Object} [options.serverEmailConfig] - The server email config.
15
- * @param {Object} [options.rules] - The rules.
16
- * @param {Object} [options.resilience] - The resilience config.
17
- * @description
18
- * This is the main class to interact with the Dymo API. It should be
19
- * instantiated with the root API key and the API key. The root API key is
20
- * used to fetch the tokens and the API key is used to authenticate the
21
- * requests. Requests are retried once by default with exponential backoff.
22
- * @example
23
- * const dymoApi = new DymoAPI({
24
- * rootApiKey: "6bfb7675-6b69-4f8d-9f43-5a6f7f02c6c5",
25
- * apiKey: "dm_4c8b7675-6b69-4f8d-9f43-5a6f7f02c6c5"
26
- * });
27
- */
28
- constructor({ rootApiKey = null, apiKey = null, baseUrl = "https://api.tpeoficial.com", serverEmailConfig = undefined, rules = {}, resilience = {} } = {}) {
29
- this.rules = {
30
- email: { mode: "LIVE", deny: ["FRAUD", "INVALID", "NO_MX_RECORDS", "NO_REPLY_EMAIL"] },
31
- ip: { mode: "LIVE", deny: ["FRAUD", "INVALID", "TOR_NETWORK"] },
32
- phone: { mode: "LIVE", deny: ["FRAUD", "INVALID"] },
33
- sensitiveInfo: { mode: "LIVE", deny: ["EMAIL", "PHONE", "CREDIT_CARD"] },
34
- waf: { mode: "LIVE", allowBots: ["CURL", "CATEGORY:SEARCH_ENGINE", "CATEGORY:PREVIEW"], deny: ["FRAUD", "TOR_NETWORK"] },
35
- ...rules
36
- };
37
- this.rootApiKey = rootApiKey;
38
- this.apiKey = apiKey;
39
- this.serverEmailConfig = serverEmailConfig;
40
- this.baseUrl = baseUrl;
41
- // Initialize resilience system with client ID
42
- const clientId = this.apiKey || this.rootApiKey || "anonymous";
43
- this.resilienceManager = new ResilienceManager(resilience, clientId);
44
- // We created the Axios client with the appropriate settings.
45
- this.axiosClient = axios.create({
46
- baseURL: `${validBaseURL(this.baseUrl)}/v1`,
47
- headers: {
48
- "User-Agent": "DymoAPISDK/1.0.0",
49
- "X-Dymo-SDK-Env": "Node",
50
- "X-Dymo-SDK-Version": "1.2.31"
51
- }
52
- });
53
- // We set the authorization in the Axios client to make requests.
54
- if (this.rootApiKey || this.apiKey)
55
- this.axiosClient.defaults.headers.Authorization = `Bearer ${this.rootApiKey || this.apiKey}`;
56
- }
57
- ;
58
- getEmailPlugins(rules) {
59
- return [
60
- rules.deny.includes("NO_MX_RECORDS") ? "mxRecords" : undefined,
61
- rules.deny.includes("NO_REACHABLE") ? "reachable" : undefined,
62
- rules.deny.includes("HIGH_RISK_SCORE") ? "riskScore" : undefined,
63
- rules.deny.includes("NO_GRAVATAR") ? "gravatar" : undefined
64
- ].filter(Boolean);
65
- }
66
- // FUNCTIONS / Private.
67
- /**
68
- * Validates the given data against the configured validation settings.
69
- *
70
- * This method requires either the root API key or the API key to be set.
71
- * If neither is set, it will throw an error.
72
- *
73
- * @deprecated Use `isValidDataRaw` instead. This feature will be modified soon.
74
- * @param {Object} data - The data to be validated.
75
- * @param {string} [data.url] - Optional URL to be validated.
76
- * @param {string} [data.email] - Optional email address to be validated.
77
- * @param {Interfaces.PhoneData} [data.phone] - Optional phone number data to be validated.
78
- * @param {string} [data.domain] - Optional domain name to be validated.
79
- * @param {string|Interfaces.CreditCardData} [data.creditCard] - Optional credit card number or data to be validated.
80
- * @param {string} [data.ip] - Optional IP address to be validated.
81
- * @param {string} [data.wallet] - Optional wallet address to be validated.
82
- * @param {string} [data.userAgent] - Optional user agent string to be validated.
83
- * @param {string} [data.iban] - Optional IBAN to be validated.
84
- * @param {Interfaces.VerifyPlugins[]} [data.plugins] - Optional array of verification plugins to be used.
85
- * @returns {Promise<Interfaces.DataValidationAnalysis>} A promise that resolves to the response from the server.
86
- * @throws Will throw an error if there is an issue with the validation process.
87
- *
88
- * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier)
89
- */
90
- async isValidData(data) {
91
- const fallbackData = FallbackDataGenerator.generateFallbackData("isValidData", data);
92
- return await this.resilienceManager.executeWithResilience(this.axiosClient, {
93
- method: "POST",
94
- url: "/private/secure/verify",
95
- data
96
- }, this.resilienceManager.getConfig().fallbackEnabled ? fallbackData : undefined);
97
- }
98
- ;
99
- /**
100
- * Validates the given data against the configured validation settings.
101
- *
102
- * This method requires either the root API key or the API key to be set.
103
- * If neither is set, it will throw an error.
104
- *
105
- * @param {Object} data - The data to be validated.
106
- * @param {string} [data.url] - Optional URL to be validated.
107
- * @param {string} [data.email] - Optional email address to be validated.
108
- * @param {Interfaces.PhoneData} [data.phone] - Optional phone number data to be validated.
109
- * @param {string} [data.domain] - Optional domain name to be validated.
110
- * @param {string|Interfaces.CreditCardData} [data.creditCard] - Optional credit card number or data to be validated.
111
- * @param {string} [data.ip] - Optional IP address to be validated.
112
- * @param {string} [data.wallet] - Optional wallet address to be validated.
113
- * @param {string} [data.userAgent] - Optional user agent string to be validated.
114
- * @param {string} [data.iban] - Optional IBAN to be validated.
115
- * @param {Interfaces.VerifyPlugins[]} [data.plugins] - Optional array of verification plugins to be used.
116
- * @returns {Promise<Interfaces.DataValidationAnalysis>} A promise that resolves to the response from the server.
117
- * @throws Will throw an error if there is an issue with the validation process.
118
- *
119
- * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier)
120
- */
121
- async isValidDataRaw(data) {
122
- const fallbackData = FallbackDataGenerator.generateFallbackData("isValidDataRaw", data);
123
- return await this.resilienceManager.executeWithResilience(this.axiosClient, {
124
- method: "POST",
125
- url: "/private/secure/verify",
126
- data
127
- }, this.resilienceManager.getConfig().fallbackEnabled ? fallbackData : undefined);
2
+ import path from "path";
3
+ import React from "react";
4
+ import { twi } from "tw-to-css";
5
+ import { render } from "@react-email/render";
6
+ const config = {
7
+ lib: {
8
+ name: "Dymo API"
9
+ }
10
+ };
11
+ const customError = (code, message) => {
12
+ return Object.assign(new Error(), { code, message: `[${config.lib.name}] ${message}` });
13
+ };
14
+ const validBaseURL = (baseUrl) => {
15
+ if (/^(https:\/\/api\.tpeoficial\.com$|http:\/\/(localhost:\d+|dymoapi:\d+))$/.test(baseUrl)) return baseUrl;
16
+ else throw new Error("[Dymo API] Invalid URL. It must be https://api.tpeoficial.com or start with http://localhost or http://dymoapi followed by a port.");
17
+ };
18
+ const getPrayerTimes = async (axiosClient, data) => {
19
+ const { lat, lon } = data;
20
+ if (lat === void 0 || lon === void 0) throw customError(1e3, "You must provide a latitude and longitude.");
21
+ try {
22
+ const response = await axiosClient.get("/public/islam/prayertimes", { params: data });
23
+ return response.data;
24
+ } catch (error) {
25
+ throw customError(5e3, error.response?.data?.message || error.message);
26
+ }
27
+ };
28
+ const isValidPwd = async (axiosClient, data) => {
29
+ let { email, password, bannedWords, min, max } = data;
30
+ if (password === void 0) throw customError(1e3, "You must specify at least the password.");
31
+ const params = { password: encodeURIComponent(password) };
32
+ if (email) {
33
+ if (!/^[a-zA-Z0-9._\-+]+@?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(email)) throw customError(1500, "If you provide an email address it must be valid.");
34
+ params.email = encodeURIComponent(email);
35
+ }
36
+ if (bannedWords) {
37
+ if (typeof bannedWords === "string") bannedWords = bannedWords.slice(1, -1).trim().split(",").map((item) => item.trim());
38
+ if (!Array.isArray(bannedWords) || bannedWords.length > 10) throw customError(1500, "If you provide a list of banned words; the list may not exceed 10 words and must be of array type.");
39
+ if (!bannedWords.every((word) => typeof word === "string") || new Set(bannedWords).size !== bannedWords.length) throw customError(1500, "If you provide a list of banned words; all elements must be non-repeated strings.");
40
+ params.bannedWords = bannedWords;
41
+ }
42
+ if (min !== void 0 && (!Number.isInteger(min) || min < 8 || min > 32)) throw customError(1500, "If you provide a minimum it must be valid.");
43
+ if (max !== void 0 && (!Number.isInteger(max) || max < 32 || max > 100)) throw customError(1500, "If you provide a maximum it must be valid.");
44
+ if (min !== void 0) params.min = min;
45
+ if (max !== void 0) params.max = max;
46
+ try {
47
+ const response = await axiosClient.get("/public/validPwd", { params });
48
+ return response.data;
49
+ } catch (error) {
50
+ throw customError(5e3, error.response?.data?.message || error.message);
51
+ }
52
+ };
53
+ const satinize = async (axiosClient, input) => {
54
+ if (input === void 0) throw customError(1e3, "You must specify at least the input.");
55
+ try {
56
+ const response = await axiosClient.get("/public/inputSatinizer", { params: { input: encodeURIComponent(input) } });
57
+ return response.data;
58
+ } catch (error) {
59
+ throw customError(5e3, error.response?.data?.message || error.message);
60
+ }
61
+ };
62
+ const extractWithTextly = async (axiosClient, data) => {
63
+ if (!axiosClient.defaults.headers?.Authorization) throw customError(3e3, "Invalid private token.");
64
+ if (!data.data) throw customError(1500, "No data provided.");
65
+ if (!data.format) throw customError(1500, "No format provided.");
66
+ try {
67
+ const response = await axiosClient.post("/private/textly/extract", data, { headers: { "Content-Type": "application/json" } });
68
+ return response.data;
69
+ } catch (error) {
70
+ throw customError(5e3, error.response?.data?.message || error.message);
71
+ }
72
+ };
73
+ const getRandom = async (axiosClient, data) => {
74
+ if (!axiosClient.defaults.headers?.Authorization) throw customError(3e3, "Invalid private token.");
75
+ if (!data.min || !data.max) throw customError(1500, "Both 'min' and 'max' parameters must be defined.");
76
+ if (data.min >= data.max) throw customError(1500, "'min' must be less than 'max'.");
77
+ if (data.min < -1e9 || data.min > 1e9) throw customError(1500, "'min' must be an integer in the interval [-1000000000}, 1000000000].");
78
+ if (data.max < -1e9 || data.max > 1e9) throw customError(1500, "'max' must be an integer in the interval [-1000000000}, 1000000000].");
79
+ try {
80
+ const response = await axiosClient.post("/private/srng", data, { headers: { "Content-Type": "application/json" } });
81
+ return response.data;
82
+ } catch (error) {
83
+ throw customError(5e3, error.response?.data?.message || error.message);
84
+ }
85
+ };
86
+ const isValidIP = async (axiosClient, ip, rules) => {
87
+ if (!axiosClient.defaults.headers?.Authorization) throw customError(3e3, "Invalid private token.");
88
+ if (rules.deny.length === 0) throw customError(1500, "You must provide at least one deny rule.");
89
+ if (rules.mode === "DRY_RUN") {
90
+ console.warn("[Dymo API] DRY_RUN mode is enabled. No requests with real data will be processed until you switch to LIVE mode.");
91
+ return {
92
+ ip,
93
+ allow: true,
94
+ reasons: [],
95
+ response: "CHANGE TO LIVE MODE"
96
+ };
97
+ }
98
+ try {
99
+ const responseIP = (await axiosClient.post("/private/secure/verify", {
100
+ ip,
101
+ plugins: [
102
+ rules.deny.includes("TOR_NETWORK") ? "torNetwork" : void 0,
103
+ rules.deny.includes("HIGH_RISK_SCORE") ? "riskScore" : void 0
104
+ ].filter(Boolean)
105
+ }, { headers: { "Content-Type": "application/json" } })).data.ip;
106
+ let reasons = [];
107
+ if (rules.deny.includes("INVALID") && !responseIP.valid) {
108
+ return {
109
+ ip: responseIP.ip,
110
+ allow: false,
111
+ reasons: ["INVALID"],
112
+ response: responseIP
113
+ };
128
114
  }
129
- ;
130
- /**
131
- * Validates the given email against the configured rules.
132
- *
133
- * This method requires either the root API key or the API key to be set.
134
- * If neither is set, it will throw an error.
135
- *
136
- * @param {string} [email] - Email address to validate.
137
- * @param {NegativeEmailRules[]} [rules] - Optional rules for validation. Some rules are premium features.
138
- * @important
139
- * **⚠️ NO_MX_RECORDS, HIGH_RISK_SCORE and NO_REACHABLE are [PREMIUM](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier) features.**
140
- * @returns {Promise<Interfaces.EmailValidatorResponse>} Resolves with the validation response.
141
- * @throws Will throw an error if validation cannot be performed.
142
- *
143
- * @example
144
- * const valid = await dymoClient.isValidEmail("user@example.com", { deny: ["FRAUD", "NO_MX_RECORDS"] });
145
- *
146
- * @see [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/email-validation)
147
- */
148
- async isValidEmail(email, rules = this.rules.email) {
149
- const fallbackData = FallbackDataGenerator.generateFallbackData("isValidEmail", email);
150
- return await this.resilienceManager.executeWithResilience(this.axiosClient, {
151
- method: "POST",
152
- url: "/private/secure/verify",
153
- data: { email, plugins: this.getEmailPlugins(rules) }
154
- }, this.resilienceManager.getConfig().fallbackEnabled ? fallbackData : undefined);
115
+ if (rules.deny.includes("FRAUD") && responseIP.fraud) reasons.push("FRAUD");
116
+ if (rules.deny.includes("TOR_NETWORK") && responseIP.plugins.torNetwork) reasons.push("TOR_NETWORK");
117
+ if (rules.deny.includes("HIGH_RISK_SCORE") && responseIP.plugins.riskScore >= 80) reasons.push("HIGH_RISK_SCORE");
118
+ for (const rule of rules.deny) {
119
+ if (rule.startsWith("COUNTRY:")) {
120
+ const block = rule.split(":")[1];
121
+ if (responseIP.countryCode === block) reasons.push(`COUNTRY:${block}`);
122
+ }
155
123
  }
156
- ;
157
- /**
158
- * Validates the given IP against the configured rules.
159
- *
160
- * This method requires either the root API key or the API key to be set.
161
- * If neither is set, it will throw an error.
162
- *
163
- * @param {string} [ip] - IP address to validate.
164
- * @param {NegativeEmailRules[]} [rules] - Optional rules for validation. Some rules are premium features.
165
- * @important
166
- * **⚠️ TOR_NETWORK and HIGH_RISK_SCORE are [PREMIUM](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier) features.**
167
- * @returns {Promise<Interfaces.IPValidatorResponse>} Resolves with the validation response.
168
- * @throws Will throw an error if validation cannot be performed.
169
- *
170
- * @example
171
- * const valid = await isValidIP("52.94.236.248", { deny: ["FRAUD", "TOR_NETWORK", "COUNTRY:RU"] });
172
- *
173
- * @see [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/ip-validation)
174
- */
175
- async isValidIP(ip, rules = this.rules.ip) {
176
- return await PrivateAPI.isValidIP(this.axiosClient, ip, rules);
124
+ return {
125
+ ip: responseIP.ip,
126
+ allow: reasons.length === 0,
127
+ reasons,
128
+ response: responseIP
129
+ };
130
+ } catch (error) {
131
+ const statusCode = error.response?.status || 500;
132
+ const errorMessage = error.response?.data?.message || error.message;
133
+ const errorDetails = JSON.stringify(error.response?.data || {});
134
+ throw customError(5e3, `Error ${statusCode}: ${errorMessage}. Details: ${errorDetails}`);
135
+ }
136
+ };
137
+ const isValidPhone = async (axiosClient, phone, rules) => {
138
+ if (!axiosClient.defaults.headers?.Authorization) throw customError(3e3, "Invalid private token.");
139
+ if (rules.deny.length === 0) throw customError(1500, "You must provide at least one deny rule.");
140
+ if (rules.mode === "DRY_RUN") {
141
+ console.warn("[Dymo API] DRY_RUN mode is enabled. No requests with real data will be processed until you switch to LIVE mode.");
142
+ return {
143
+ phone,
144
+ allow: true,
145
+ reasons: [],
146
+ response: "CHANGE TO LIVE MODE"
147
+ };
148
+ }
149
+ try {
150
+ const responsePhone = (await axiosClient.post("/private/secure/verify", {
151
+ phone,
152
+ plugins: [
153
+ rules.deny.includes("HIGH_RISK_SCORE") ? "riskScore" : void 0
154
+ ].filter(Boolean)
155
+ }, { headers: { "Content-Type": "application/json" } })).data.phone;
156
+ let reasons = [];
157
+ if (rules.deny.includes("INVALID") && !responsePhone.valid) {
158
+ return {
159
+ phone: responsePhone.phone,
160
+ allow: false,
161
+ reasons: ["INVALID"],
162
+ response: responsePhone
163
+ };
177
164
  }
178
- ;
179
- /**
180
- * Validates the given email against the configured rules.
181
- *
182
- * This method requires either the root API key or the API key to be set.
183
- * If neither is set, it will throw an error.
184
- *
185
- * @param {string} [phone] - Phone number to validate.
186
- * @param {NegativePhoneRules[]} [rules] - Optional rules for validation. Some rules are premium features.
187
- * @important
188
- * **⚠️ HIGH_RISK_SCORE is a [PREMIUM](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier) feature.**
189
- * @returns {Promise<Interfaces.EmailValidatorResponse>} Resolves with the validation response.
190
- * @throws Will throw an error if validation cannot be performed.
191
- *
192
- * @example
193
- * const valid = await dymoClient.isValidPhone("+34617509462", { deny: ["FRAUD", "INVALID"] });
194
- *
195
- * @see [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/phone-validation)
196
- */
197
- async isValidPhone(phone, rules = this.rules.phone) {
198
- return await PrivateAPI.isValidPhone(this.axiosClient, phone, rules);
165
+ if (rules.deny.includes("FRAUD") && responsePhone.fraud) reasons.push("FRAUD");
166
+ if (rules.deny.includes("HIGH_RISK_SCORE") && responsePhone.plugins.riskScore >= 80) reasons.push("HIGH_RISK_SCORE");
167
+ for (const rule of rules.deny) {
168
+ if (rule.startsWith("COUNTRY:")) {
169
+ const block = rule.split(":")[1];
170
+ if (responsePhone.countryCode === block) reasons.push(`COUNTRY:${block}`);
171
+ }
199
172
  }
200
- ;
201
- /**
202
- * Protects the given request against the configured rules.
203
- *
204
- * This method requires either the root API key or the API key to be set.
205
- * If neither is set, it will throw an error.
206
- *
207
- * @param {Object} req - The request object to be protected.
208
- * @param {Interfaces.WafRules} [rules] - Optional rules for protection. Some rules are premium features.
209
- * @returns {Promise<Interfaces.HTTPRequest>} Resolves with the protected request.
210
- * @important
211
- * **⚠️ This is a [PREMIUM](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier) and BETA feature.**
212
- * @throws Will throw an error if protection cannot be performed.
213
- *
214
- * @example
215
- * const protectedReq = await dymoClient.protectReq(req);
216
- *
217
- * @see [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier)
218
- */
219
- async protectReq(req, rules = this.rules.waf) {
220
- return await PrivateAPI.protectReq(this.axiosClient, req, rules);
173
+ return {
174
+ phone: responsePhone.phone,
175
+ allow: reasons.length === 0,
176
+ reasons,
177
+ response: responsePhone
178
+ };
179
+ } catch (error) {
180
+ const statusCode = error.response?.status || 500;
181
+ const errorMessage = error.response?.data?.message || error.message;
182
+ const errorDetails = JSON.stringify(error.response?.data || {});
183
+ throw customError(5e3, `Error ${statusCode}: ${errorMessage}. Details: ${errorDetails}`);
184
+ }
185
+ };
186
+ const getUserAgent = (req) => {
187
+ return req.headers?.["user-agent"] || req.headers?.["User-Agent"];
188
+ };
189
+ const getIp = (req) => {
190
+ return req.ip || req.headers?.["x-forwarded-for"] || req.connection?.remoteAddress || req.socket?.remoteAddress || req.req?.socket?.remoteAddress;
191
+ };
192
+ const handleRequest = (req) => {
193
+ return {
194
+ body: req.body,
195
+ userAgent: getUserAgent(req),
196
+ ip: getIp(req)
197
+ };
198
+ };
199
+ const protectReq = async (axiosClient, req, rules) => {
200
+ if (!axiosClient.defaults.headers?.Authorization) throw customError(3e3, "Invalid private token.");
201
+ const reqData = handleRequest(req);
202
+ if (!reqData.userAgent || !reqData.ip) throw customError(1500, "You must provide user agent and ip.");
203
+ if (rules.mode === "DRY_RUN") {
204
+ console.warn("[Dymo API] DRY_RUN mode is enabled. No requests with real data will be processed until you switch to LIVE mode.");
205
+ return {
206
+ ip: reqData.ip,
207
+ userAgent: reqData.userAgent,
208
+ allow: true,
209
+ reasons: []
210
+ };
211
+ }
212
+ try {
213
+ const response = await axiosClient.post("/private/waf/verifyRequest", {
214
+ ip: reqData.ip,
215
+ userAgent: reqData.userAgent,
216
+ allowBots: rules.allowBots,
217
+ deny: rules.deny
218
+ }, { headers: { "Content-Type": "application/json" } });
219
+ return response.data;
220
+ } catch (error) {
221
+ const statusCode = error.response?.status || 500;
222
+ const errorMessage = error.response?.data?.message || error.message;
223
+ const errorDetails = JSON.stringify(error.response?.data || {});
224
+ throw customError(5e3, `Error ${statusCode}: ${errorMessage}. Details: ${errorDetails}`);
225
+ }
226
+ };
227
+ const fs = {};
228
+ const convertTailwindToInlineCss = (htmlContent) => {
229
+ return htmlContent.replace(/class="([^"]+)"( style="([^"]+)")?/g, (match, classList, _, existingStyle) => {
230
+ const compiledStyles = twi(classList, { minify: true, merge: true });
231
+ return match.replace(/class="[^"]+"/, "").replace(/ style="[^"]+"/, "").concat(` style="${existingStyle ? `${existingStyle.trim().slice(0, -1)}; ${compiledStyles}` : compiledStyles}"`);
232
+ });
233
+ };
234
+ const sendEmail = async (axiosClient, data) => {
235
+ if (!axiosClient.defaults.headers?.Authorization) throw customError(3e3, "Invalid private token.");
236
+ if (!data.from) throw customError(1500, "You must provide an email address from which the following will be sent.");
237
+ if (!data.to) throw customError(1500, "You must provide an email to be sent to.");
238
+ if (!data.subject) throw customError(1500, "You must provide a subject for the email to be sent.");
239
+ if (!data.html && !data.react && !React.isValidElement(data.react)) throw customError(1500, "You must provide HTML or a React component.");
240
+ if (data.html && data.react) throw customError(1500, "You must provide only HTML or a React component, not both.");
241
+ try {
242
+ if (data.react) {
243
+ data.html = await render(data.react);
244
+ delete data.react;
221
245
  }
222
- /**
223
- * Sends an email using the configured email client settings.
224
- *
225
- * This method requires either the root API key or the server email config to be set.
226
- * If neither is set, it will throw an error.
227
- *
228
- * @param {Object} data - The email data to be sent.
229
- * @param {string} data.from - The email address from which the email will be sent.
230
- * @param {string} data.to - The email address to which the email will be sent.
231
- * @param {string} data.subject - The subject of the email.
232
- * @param {string} [data.html] - The HTML content of the email.
233
- * @param {React.ReactElement} [data.react] - The React component to be rendered as the email content.
234
- * @param {Object} [data.options] - Content configuration options.
235
- * @param {"high" | "normal" | "low" | undefined} [data.options.priority="normal"] - Email priority (default: normal).
236
- * @param {boolean} [data.options.waitToResponse=true] - Wait until the email is sent (default: true).
237
- * @param {boolean} [data.options.composeTailwindClasses] - Whether to compose tailwind classes.
238
- * @param {Attachment[]} [data.attachments] - An array of attachments to be included in the email.
239
- * @param {string} data.attachments[].filename - The name of the attached file.
240
- * @param {string} [data.attachments[].path] - The path or URL of the attached file. Either this or `content` must be provided.
241
- * @param {Buffer} [data.attachments[].content] - The content of the attached file as a Buffer. Either this or `path` must be provided.
242
- * @param {string} [data.attachments[].cid] - The CID (Content-ID) of the attached file, used for inline images.
243
- * @returns {Promise<Interfaces.EmailStatus>} A promise that resolves to the response from the server.
244
- * @throws Will throw an error if there is an issue with the email sending process.
245
- *
246
- * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/sender-send-email/getting-started)
247
- */
248
- async sendEmail(data) {
249
- if (!this.serverEmailConfig && !this.rootApiKey)
250
- console.error(`[${config.lib.name}] You must configure the email client settings.`);
251
- return await PrivateAPI.sendEmail(this.axiosClient, { serverEmailConfig: this.serverEmailConfig, ...data });
246
+ if (data.options && data.options.composeTailwindClasses) {
247
+ data.html = convertTailwindToInlineCss(data.html);
248
+ delete data.options.composeTailwindClasses;
252
249
  }
253
- ;
254
- /**
255
- * Generates a random number between the provided min and max values.
256
- *
257
- * This method requires either the root API key or the API key to be set.
258
- * If neither is set, it will throw an error.
259
- *
260
- * @param {Interfaces.SRNG} data - The data to be sent.
261
- * @param {number} data.min - The minimum value of the range.
262
- * @param {number} data.max - The maximum value of the range.
263
- * @param {number} [data.quantity] - The number of random values to generate. Defaults to 1 if not provided.
264
- * @returns {Promise<Interfaces.SRNSummary>} A promise that resolves to the response from the server.
265
- * @throws Will throw an error if there is an issue with the random number generation process.
266
- *
267
- * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/secure-random-number-generator)
268
- */
269
- async getRandom(data) {
270
- return await PrivateAPI.getRandom(this.axiosClient, data);
250
+ } catch (error) {
251
+ throw customError(1500, `An error occurred while rendering your React component. Details: ${error}`);
252
+ }
253
+ try {
254
+ let totalSize = 0;
255
+ if (data.attachments && Array.isArray(data.attachments)) {
256
+ const processedAttachments = await Promise.all(
257
+ data.attachments.map(async (attachment) => {
258
+ if (attachment.path && attachment.content || !attachment.path && !attachment.content) throw customError(1500, "You must provide either 'path' or 'content', not both.");
259
+ let contentBuffer;
260
+ if (attachment.path) contentBuffer = await fs.readFile(path.resolve(attachment.path));
261
+ else if (attachment.content) contentBuffer = attachment.content instanceof Buffer ? attachment.content : Buffer.from(attachment.content);
262
+ totalSize += Buffer.byteLength(contentBuffer);
263
+ if (totalSize > 40 * 1024 * 1024) throw customError(1500, "Attachments exceed the maximum allowed size of 40 MB.");
264
+ return {
265
+ filename: attachment.filename || path.basename(attachment.path || ""),
266
+ content: contentBuffer,
267
+ cid: attachment.cid || attachment.filename
268
+ };
269
+ })
270
+ );
271
+ data.attachments = processedAttachments;
271
272
  }
272
- ;
273
- /**
274
- * Extracts structured data from a given string using Textly.
275
- *
276
- * This method requires either the root API key or the API key to be set.
277
- * If neither is set, it will throw an error.
278
- *
279
- * @param {Interfaces.ExtractWithTextly} data - The data to be sent, containing the string to be processed and the format schema.
280
- * @returns {Promise<any>} A promise that resolves to the extracted structured data.
281
- * @throws Will throw an error if there is an issue with the extraction process.
282
- *
283
- * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/textly/text-extraction)
284
- */
285
- async extractWithTextly(data) {
286
- return await PrivateAPI.extractWithTextly(this.axiosClient, data);
273
+ const response = await axiosClient.post("/private/sender/sendEmail", data);
274
+ return response.data;
275
+ } catch (error) {
276
+ throw customError(5e3, error.response?.data?.message || error.message);
277
+ }
278
+ };
279
+ class RateLimitManager {
280
+ constructor() {
281
+ this.tracker = {};
282
+ }
283
+ static getInstance() {
284
+ if (!RateLimitManager.instance) RateLimitManager.instance = new RateLimitManager();
285
+ return RateLimitManager.instance;
286
+ }
287
+ updateRateLimit(clientId, headers) {
288
+ if (!this.tracker[clientId]) this.tracker[clientId] = {};
289
+ const limitInfo = this.tracker[clientId];
290
+ if (headers["x-ratelimit-limit-requests"]) limitInfo.limit = parseInt(headers["x-ratelimit-limit-requests"]);
291
+ if (headers["x-ratelimit-remaining-requests"]) limitInfo.remaining = parseInt(headers["x-ratelimit-remaining-requests"]);
292
+ if (headers["x-ratelimit-reset-requests"]) limitInfo.resetTime = headers["x-ratelimit-reset-requests"];
293
+ if (headers["retry-after"]) limitInfo.retryAfter = parseInt(headers["retry-after"]);
294
+ limitInfo.lastUpdated = Date.now();
295
+ }
296
+ isRateLimited(clientId) {
297
+ const limitInfo = this.tracker[clientId];
298
+ return limitInfo?.remaining !== void 0 && limitInfo.remaining <= 0;
299
+ }
300
+ getRetryAfter(clientId) {
301
+ return this.tracker[clientId]?.retryAfter;
302
+ }
303
+ clearExpiredLimits() {
304
+ const now = Date.now();
305
+ Object.keys(this.tracker).forEach((clientId) => {
306
+ const limitInfo = this.tracker[clientId];
307
+ if (limitInfo.lastUpdated && now - limitInfo.lastUpdated > 3e5) delete this.tracker[clientId];
308
+ });
309
+ }
310
+ }
311
+ class ResilienceManager {
312
+ constructor(config2 = {}, clientId = "default") {
313
+ this.config = {
314
+ fallbackEnabled: config2.fallbackEnabled ?? false,
315
+ retryAttempts: Math.max(0, config2.retryAttempts ?? 2),
316
+ // Number of additional retries
317
+ retryDelay: Math.max(0, config2.retryDelay ?? 1e3)
318
+ };
319
+ this.clientId = clientId;
320
+ this.rateLimitManager = RateLimitManager.getInstance();
321
+ }
322
+ async executeWithResilience(axiosClient, requestConfig, fallbackData) {
323
+ let lastError;
324
+ const totalAttempts = 1 + this.config.retryAttempts;
325
+ this.rateLimitManager.clearExpiredLimits();
326
+ if (this.rateLimitManager.isRateLimited(this.clientId)) {
327
+ const retryAfter = this.rateLimitManager.getRetryAfter(this.clientId);
328
+ if (retryAfter) {
329
+ console.warn(`[Dymo API] Client ${this.clientId} is rate limited. Waiting ${retryAfter} seconds...`);
330
+ await this.sleep(retryAfter * 1e3);
331
+ }
287
332
  }
288
- ;
289
- // FUNCTIONS / Public.
290
- /**
291
- * Retrieves the prayer times for the given location.
292
- *
293
- * This method requires a latitude and longitude to be provided in the
294
- * data object. If either of these are not provided, it will throw an error.
295
- *
296
- * @param {Object} data - The data to be sent.
297
- * @param {number} data.lat - The latitude of the location.
298
- * @param {number} data.lon - The longitude of the location.
299
- * @returns {Promise<Interfaces.CountryPrayerTimes | { error: string }>} A promise that resolves to the response from the server.
300
- * @throws Will throw an error if there is an issue with the prayer times retrieval process.
301
- *
302
- * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/public/prayertimes)
303
- */
304
- async getPrayerTimes(data) {
305
- return await PublicAPI.getPrayerTimes(this.axiosClient, data);
333
+ for (let attempt = 1; attempt <= totalAttempts; attempt++) {
334
+ try {
335
+ const response = await axiosClient.request(requestConfig);
336
+ this.rateLimitManager.updateRateLimit(this.clientId, response.headers);
337
+ if (response.status === 429) {
338
+ const retryAfter = this.rateLimitManager.getRetryAfter(this.clientId);
339
+ if (retryAfter) {
340
+ console.warn(`[Dymo API] Rate limited. Waiting ${retryAfter} seconds (no retries)`);
341
+ await this.sleep(retryAfter * 1e3);
342
+ }
343
+ throw new Error(`Rate limited (429) - not retrying`);
344
+ }
345
+ return response.data;
346
+ } catch (error) {
347
+ lastError = error;
348
+ let shouldRetry = this.shouldRetry(error);
349
+ const isLastAttempt = attempt === totalAttempts;
350
+ if (error.response?.status === 429) shouldRetry = false;
351
+ if (!shouldRetry || isLastAttempt) {
352
+ if (this.config.fallbackEnabled && fallbackData) {
353
+ console.warn(`[Dymo API] Request failed after ${attempt} attempts. Using fallback data.`);
354
+ return fallbackData;
355
+ }
356
+ throw error;
357
+ }
358
+ const delay = this.config.retryDelay * Math.pow(2, attempt - 1);
359
+ console.warn(`[Dymo API] Attempt ${attempt} failed. Retrying in ${delay}ms...`);
360
+ await this.sleep(delay);
361
+ }
306
362
  }
307
- ;
308
- /**
309
- * Satinizes the input, replacing any special characters with their HTML
310
- * entities.
311
- *
312
- * @deprecated Use `satinize` instead. This feature will be removed soon.
313
- * @param {Object} data - The data to be sent.
314
- * @param {string} data.input - The input to be satinized.
315
- * @returns {Promise<Interfaces.SatinizedInputAnalysis>} A promise that resolves to the response from the server.
316
- * @throws Will throw an error if there is an issue with the satinization process.
317
- *
318
- * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/public/input-satinizer)
319
- */
320
- async satinizer(data) {
321
- return await PublicAPI.satinize(this.axiosClient, data.input);
363
+ throw lastError;
364
+ }
365
+ shouldRetry(error) {
366
+ const statusCode = error.response?.status;
367
+ const isNetworkError = !error.response && error.code !== "ECONNABORTED";
368
+ const isServerError = statusCode && statusCode >= 500;
369
+ return isNetworkError || isServerError;
370
+ }
371
+ sleep(ms) {
372
+ return new Promise((resolve) => setTimeout(resolve, ms));
373
+ }
374
+ getConfig() {
375
+ return { ...this.config };
376
+ }
377
+ getClientId() {
378
+ return this.clientId;
379
+ }
380
+ }
381
+ class FallbackDataGenerator {
382
+ static generateFallbackData(method, inputData) {
383
+ switch (method) {
384
+ case "isValidData":
385
+ return this.generateDataValidationAnalysis(inputData);
386
+ case "isValidEmail":
387
+ return this.generateEmailValidatorResponse(inputData);
388
+ case "isValidIP":
389
+ return this.generateIPValidatorResponse(inputData);
390
+ case "isValidPhone":
391
+ return this.generatePhoneValidatorResponse(inputData);
392
+ case "protectReq":
393
+ return this.generateHTTPRequest(inputData);
394
+ case "sendEmail":
395
+ return this.generateEmailStatus();
396
+ case "getRandom":
397
+ return this.generateSRNSummary(inputData);
398
+ case "extractWithTextly":
399
+ return this.generateExtractWithTextly(inputData);
400
+ case "getPrayerTimes":
401
+ return this.generatePrayerTimes(inputData);
402
+ case "satinize":
403
+ return this.generateSatinizedInputAnalysis(inputData);
404
+ case "isValidPwd":
405
+ return this.generatePasswordValidationResult(inputData);
406
+ default:
407
+ throw new Error(`Unknown method for fallback: ${method}`);
322
408
  }
323
- ;
324
- /**
325
- * Satinizes the input, replacing any special characters with their HTML
326
- * entities.
327
- *
328
- * @param {Object} data - The data to be sent.
329
- * @param {string} data.input - The input to be satinized.
330
- * @returns {Promise<Interfaces.SatinizedInputAnalysis>} A promise that resolves to the response from the server.
331
- * @throws Will throw an error if there is an issue with the satinization process.
332
- *
333
- * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/public/input-satinizer)
334
- */
335
- async satinize(input) {
336
- return await PublicAPI.satinize(this.axiosClient, input);
409
+ }
410
+ static validateURL(url) {
411
+ if (!url) return false;
412
+ const urlRegex = /^https?:\/\/(?:[-\w.])+(?:\:[0-9]+)?(?:\/(?:[\w\/_.])*(?:\?(?:[\w&=%.])*)?(?:\#(?:[\w.])*)?)?$/;
413
+ return urlRegex.test(url);
414
+ }
415
+ static validateEmail(email) {
416
+ if (!email) return false;
417
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
418
+ return emailRegex.test(email);
419
+ }
420
+ static validateDomain(domain) {
421
+ if (!domain) return false;
422
+ const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9](?:\.[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])*$/;
423
+ if (!domainRegex.test(domain)) return false;
424
+ const parts = domain.split(".");
425
+ return parts.length >= 2 && parts[parts.length - 1].length > 0;
426
+ }
427
+ static validateCreditCard(creditCard) {
428
+ if (!creditCard) return false;
429
+ const cardNumber = typeof creditCard === "string" ? creditCard : creditCard?.pan || "";
430
+ if (!cardNumber) return false;
431
+ const cardRegex = /^\d{13,19}$/;
432
+ if (!cardRegex.test(cardNumber.replace(/\s/g, ""))) return false;
433
+ const digits = cardNumber.replace(/\s/g, "").split("").map(Number);
434
+ let sum = 0;
435
+ let isEven = false;
436
+ for (let i = digits.length - 1; i >= 0; i--) {
437
+ let digit = digits[i];
438
+ if (isEven) {
439
+ digit *= 2;
440
+ if (digit > 9) digit -= 9;
441
+ }
442
+ sum += digit;
443
+ isEven = !isEven;
337
444
  }
338
- ;
339
- /**
340
- * Validates a password based on the given parameters.
341
- *
342
- * This method requires the password to be provided in the data object.
343
- * If the password is not provided, it will throw an error. The method
344
- * will validate the password against the following rules:
345
- * - The password must be at least 8 characters long.
346
- * - The password must be at most 32 characters long.
347
- * - The password must contain at least one uppercase letter.
348
- * - The password must contain at least one lowercase letter.
349
- * - The password must contain at least one number.
350
- * - The password must contain at least one special character.
351
- * - The password must not contain any of the given banned words.
352
- *
353
- * @param {Object} data - The data to be sent.
354
- * @param {number} [data.min] - Minimum length of the password. Defaults to 8 if not provided.
355
- * @param {number} [data.max] - Maximum length of the password. Defaults to 32 if not provided.
356
- * @param {string} [data.email] - Optional email associated with the password.
357
- * @param {string} data.password - The password to be validated.
358
- * @param {string | string[]} [data.bannedWords] - The list of banned words that the password must not contain.
359
- * @returns {Promise<Interfaces.PasswordValidationResult>} A promise that resolves to the response from the server.
360
- * @throws Will throw an error if there is an issue with the password validation process.
361
- *
362
- * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/public/password-validator)
363
- */
364
- async isValidPwd(data) {
365
- return await PublicAPI.isValidPwd(this.axiosClient, data);
445
+ return sum % 10 === 0;
446
+ }
447
+ static validateIP(ip) {
448
+ if (!ip) return false;
449
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
450
+ const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
451
+ return ipv4Regex.test(ip) || ipv6Regex.test(ip);
452
+ }
453
+ static validatePhone(phone) {
454
+ if (!phone) return false;
455
+ const phoneRegex = /^\+?[1-9]\d{1,14}$/;
456
+ return phoneRegex.test(phone.replace(/[^\d+]/g, ""));
457
+ }
458
+ static validateWallet(wallet) {
459
+ if (!wallet) return false;
460
+ const bitcoinRegex = /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/;
461
+ const ethereumRegex = /^0x[a-fA-F0-9]{40}$/;
462
+ return bitcoinRegex.test(wallet) || ethereumRegex.test(wallet);
463
+ }
464
+ static validateIBAN(iban) {
465
+ if (!iban) return false;
466
+ const ibanRegex = /^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/;
467
+ return ibanRegex.test(iban.replace(/\s/g, "").toUpperCase());
468
+ }
469
+ static extractDomain(url) {
470
+ if (!url) return "";
471
+ try {
472
+ return new URL(url).hostname;
473
+ } catch {
474
+ return "";
366
475
  }
367
- ;
476
+ }
477
+ static generateDataValidationAnalysis(inputData) {
478
+ return {
479
+ url: {
480
+ valid: this.validateURL(inputData?.url),
481
+ fraud: false,
482
+ freeSubdomain: false,
483
+ customTLD: false,
484
+ url: inputData?.url || "",
485
+ domain: this.extractDomain(inputData?.url),
486
+ plugins: {
487
+ blocklist: false,
488
+ compromiseDetector: false,
489
+ mxRecords: [],
490
+ nsfw: false,
491
+ reputation: "unknown",
492
+ riskScore: 0,
493
+ torNetwork: false,
494
+ typosquatting: 0,
495
+ urlShortener: false
496
+ }
497
+ },
498
+ email: this.generateEmailDataAnalysis(inputData?.email),
499
+ phone: this.generatePhoneDataAnalysis(inputData?.phone),
500
+ domain: {
501
+ valid: this.validateDomain(inputData?.domain),
502
+ fraud: false,
503
+ freeSubdomain: false,
504
+ customTLD: false,
505
+ domain: inputData?.domain || "",
506
+ plugins: {
507
+ blocklist: false,
508
+ compromiseDetector: false,
509
+ mxRecords: [],
510
+ nsfw: false,
511
+ reputation: "unknown",
512
+ riskScore: 0,
513
+ torNetwork: false,
514
+ typosquatting: 0,
515
+ urlShortener: false
516
+ }
517
+ },
518
+ creditCard: {
519
+ valid: this.validateCreditCard(inputData?.creditCard),
520
+ fraud: false,
521
+ test: false,
522
+ type: "unknown",
523
+ creditCard: typeof inputData?.creditCard === "string" ? inputData.creditCard : inputData?.creditCard?.pan || "",
524
+ plugins: {
525
+ blocklist: false,
526
+ riskScore: 0
527
+ }
528
+ },
529
+ ip: this.generateIPDataAnalysis(inputData?.ip),
530
+ wallet: {
531
+ valid: this.validateWallet(inputData?.wallet),
532
+ fraud: false,
533
+ wallet: inputData?.wallet || "",
534
+ type: "unknown",
535
+ plugins: {
536
+ blocklist: false,
537
+ riskScore: 0,
538
+ torNetwork: false
539
+ }
540
+ },
541
+ userAgent: {
542
+ valid: false,
543
+ fraud: false,
544
+ userAgent: inputData?.userAgent || "",
545
+ bot: true,
546
+ device: { type: "unknown", brand: "unknown" },
547
+ plugins: {
548
+ blocklist: false,
549
+ riskScore: 0
550
+ }
551
+ },
552
+ iban: {
553
+ valid: this.validateIBAN(inputData?.iban),
554
+ fraud: false,
555
+ iban: inputData?.iban || "",
556
+ plugins: {
557
+ blocklist: false,
558
+ riskScore: 0
559
+ }
560
+ }
561
+ };
562
+ }
563
+ static generateEmailValidatorResponse(inputData) {
564
+ return {
565
+ email: inputData?.email || "",
566
+ allow: this.validateEmail(inputData?.email),
567
+ reasons: this.validateEmail(inputData?.email) ? [] : ["INVALID"],
568
+ response: this.generateEmailDataAnalysis(inputData?.email)
569
+ };
570
+ }
571
+ static generateEmailDataAnalysis(email) {
572
+ return {
573
+ valid: this.validateEmail(email),
574
+ fraud: false,
575
+ proxiedEmail: false,
576
+ freeSubdomain: false,
577
+ corporate: false,
578
+ email: email || "",
579
+ realUser: "",
580
+ didYouMean: null,
581
+ noReply: false,
582
+ customTLD: false,
583
+ domain: "",
584
+ roleAccount: false,
585
+ plugins: {
586
+ mxRecords: [],
587
+ blocklist: false,
588
+ compromiseDetector: false,
589
+ nsfw: false,
590
+ reputation: "unknown",
591
+ riskScore: 0,
592
+ torNetwork: false,
593
+ typosquatting: 0,
594
+ urlShortener: false
595
+ }
596
+ };
597
+ }
598
+ static generateIPValidatorResponse(inputData) {
599
+ return {
600
+ ip: inputData?.ip || "",
601
+ allow: this.validateIP(inputData?.ip),
602
+ reasons: this.validateIP(inputData?.ip) ? [] : ["INVALID"],
603
+ response: this.generateIPDataAnalysis(inputData?.ip)
604
+ };
605
+ }
606
+ static generateIPDataAnalysis(ip) {
607
+ const isValid = this.validateIP(ip);
608
+ return {
609
+ valid: isValid,
610
+ type: isValid ? "IPv4" : "Invalid",
611
+ class: isValid ? "A" : "Unknown",
612
+ fraud: false,
613
+ ip: ip || "",
614
+ continent: "",
615
+ continentCode: "",
616
+ country: "",
617
+ countryCode: "",
618
+ region: "",
619
+ regionName: "",
620
+ city: "",
621
+ district: "",
622
+ zipCode: "",
623
+ lat: 0,
624
+ lon: 0,
625
+ timezone: "",
626
+ offset: 0,
627
+ currency: "",
628
+ isp: "",
629
+ org: "",
630
+ as: "",
631
+ asname: "",
632
+ mobile: false,
633
+ proxy: true,
634
+ hosting: false,
635
+ plugins: {
636
+ blocklist: false,
637
+ riskScore: 0
638
+ }
639
+ };
640
+ }
641
+ static generatePhoneValidatorResponse(inputData) {
642
+ return {
643
+ phone: inputData?.phone || "",
644
+ allow: this.validatePhone(inputData?.phone),
645
+ reasons: this.validatePhone(inputData?.phone) ? [] : ["INVALID"],
646
+ response: this.generatePhoneDataAnalysis(inputData?.phone)
647
+ };
648
+ }
649
+ static generatePhoneDataAnalysis(phone) {
650
+ const phoneNumber = phone?.phone || phone;
651
+ const isValid = this.validatePhone(phoneNumber);
652
+ return {
653
+ valid: isValid,
654
+ fraud: false,
655
+ phone: phone?.phone || "",
656
+ prefix: "",
657
+ number: "",
658
+ lineType: "Unknown",
659
+ carrierInfo: {
660
+ carrierName: "",
661
+ accuracy: 0,
662
+ carrierCountry: "",
663
+ carrierCountryCode: ""
664
+ },
665
+ country: "",
666
+ countryCode: "",
667
+ plugins: {
668
+ blocklist: false,
669
+ riskScore: 0
670
+ }
671
+ };
672
+ }
673
+ static generateHTTPRequest(inputData) {
674
+ return {
675
+ method: inputData?.method || "GET",
676
+ url: inputData?.url || "",
677
+ headers: inputData?.headers || {},
678
+ body: inputData?.body || null,
679
+ allow: false,
680
+ reasons: ["FRAUD"],
681
+ protected: true
682
+ };
683
+ }
684
+ static generateEmailStatus() {
685
+ return {
686
+ status: false,
687
+ error: "API unavailable - using fallback response"
688
+ };
689
+ }
690
+ static generateSRNSummary(inputData) {
691
+ const quantity = inputData?.quantity || 1;
692
+ const values = Array.from({ length: quantity }, () => ({
693
+ integer: 0,
694
+ float: 0
695
+ }));
696
+ return {
697
+ values,
698
+ executionTime: 0
699
+ };
700
+ }
701
+ static generateExtractWithTextly(inputData) {
702
+ return {
703
+ data: inputData?.data || "",
704
+ extracted: {},
705
+ error: "API unavailable - using fallback response"
706
+ };
707
+ }
708
+ static generatePrayerTimes(inputData) {
709
+ return {
710
+ error: "API unavailable - using fallback response"
711
+ };
712
+ }
713
+ static generateSatinizedInputAnalysis(inputData) {
714
+ return {
715
+ input: inputData?.input || "",
716
+ formats: {
717
+ ascii: false,
718
+ bitcoinAddress: false,
719
+ cLikeIdentifier: false,
720
+ coordinates: false,
721
+ crediCard: false,
722
+ date: false,
723
+ discordUsername: false,
724
+ doi: false,
725
+ domain: false,
726
+ e164Phone: false,
727
+ email: false,
728
+ emoji: false,
729
+ hanUnification: false,
730
+ hashtag: false,
731
+ hyphenWordBreak: false,
732
+ ipv6: false,
733
+ ip: false,
734
+ jiraTicket: false,
735
+ macAddress: false,
736
+ name: false,
737
+ number: false,
738
+ panFromGstin: false,
739
+ password: false,
740
+ port: false,
741
+ tel: false,
742
+ text: false,
743
+ semver: false,
744
+ ssn: false,
745
+ uuid: false,
746
+ url: false,
747
+ urlSlug: false,
748
+ username: false
749
+ },
750
+ includes: {
751
+ spaces: false,
752
+ hasSql: false,
753
+ hasNoSql: false,
754
+ letters: false,
755
+ uppercase: false,
756
+ lowercase: false,
757
+ symbols: false,
758
+ digits: false
759
+ }
760
+ };
761
+ }
762
+ static generatePasswordValidationResult(inputData) {
763
+ return {
764
+ valid: false,
765
+ password: inputData?.password || "",
766
+ details: [
767
+ {
768
+ validation: "length",
769
+ message: "API unavailable - using fallback response"
770
+ }
771
+ ]
772
+ };
773
+ }
774
+ }
775
+ class DymoAPI {
776
+ /**
777
+ * @param {Object} options - Options to create the DymoAPI instance.
778
+ * @param {string} [options.rootApiKey] - The root API key.
779
+ * @param {string} [options.apiKey] - The API key.
780
+ * @param {string} [options.baseUrl] - Whether to use a local server instead of the cloud server.
781
+ * @param {Object} [options.serverEmailConfig] - The server email config.
782
+ * @param {Object} [options.rules] - The rules.
783
+ * @param {Object} [options.resilience] - The resilience config.
784
+ * @description
785
+ * This is the main class to interact with the Dymo API. It should be
786
+ * instantiated with the root API key and the API key. The root API key is
787
+ * used to fetch the tokens and the API key is used to authenticate the
788
+ * requests. Requests are retried once by default with exponential backoff.
789
+ * @example
790
+ * const dymoApi = new DymoAPI({
791
+ * rootApiKey: "6bfb7675-6b69-4f8d-9f43-5a6f7f02c6c5",
792
+ * apiKey: "dm_4c8b7675-6b69-4f8d-9f43-5a6f7f02c6c5"
793
+ * });
794
+ */
795
+ constructor({
796
+ rootApiKey = null,
797
+ apiKey = null,
798
+ baseUrl = "https://api.tpeoficial.com",
799
+ serverEmailConfig = void 0,
800
+ rules = {},
801
+ resilience = {}
802
+ } = {}) {
803
+ this.rules = {
804
+ email: { mode: "LIVE", deny: ["FRAUD", "INVALID", "NO_MX_RECORDS", "NO_REPLY_EMAIL"] },
805
+ ip: { mode: "LIVE", deny: ["FRAUD", "INVALID", "TOR_NETWORK"] },
806
+ phone: { mode: "LIVE", deny: ["FRAUD", "INVALID"] },
807
+ sensitiveInfo: { mode: "LIVE", deny: ["EMAIL", "PHONE", "CREDIT_CARD"] },
808
+ waf: { mode: "LIVE", allowBots: ["CURL", "CATEGORY:SEARCH_ENGINE", "CATEGORY:PREVIEW"], deny: ["FRAUD", "TOR_NETWORK"] },
809
+ ...rules
810
+ };
811
+ this.rootApiKey = rootApiKey;
812
+ this.apiKey = apiKey;
813
+ this.serverEmailConfig = serverEmailConfig;
814
+ this.baseUrl = baseUrl;
815
+ const clientId = this.apiKey || this.rootApiKey || "anonymous";
816
+ this.resilienceManager = new ResilienceManager(resilience, clientId);
817
+ this.axiosClient = axios.create({
818
+ baseURL: `${validBaseURL(this.baseUrl)}/v1`,
819
+ headers: {
820
+ "User-Agent": "DymoAPISDK/1.0.0",
821
+ "X-Dymo-SDK-Env": "Node",
822
+ "X-Dymo-SDK-Version": "1.2.33"
823
+ }
824
+ });
825
+ if (this.rootApiKey || this.apiKey) this.axiosClient.defaults.headers.Authorization = `Bearer ${this.rootApiKey || this.apiKey}`;
826
+ }
827
+ getEmailPlugins(rules) {
828
+ return [
829
+ rules.deny.includes("NO_MX_RECORDS") ? "mxRecords" : void 0,
830
+ rules.deny.includes("NO_REACHABLE") ? "reachable" : void 0,
831
+ rules.deny.includes("HIGH_RISK_SCORE") ? "riskScore" : void 0,
832
+ rules.deny.includes("NO_GRAVATAR") ? "gravatar" : void 0
833
+ ].filter(Boolean);
834
+ }
835
+ // FUNCTIONS / Private.
836
+ /**
837
+ * Validates the given data against the configured validation settings.
838
+ *
839
+ * This method requires either the root API key or the API key to be set.
840
+ * If neither is set, it will throw an error.
841
+ *
842
+ * @deprecated Use `isValidDataRaw` instead. This feature will be modified soon.
843
+ * @param {Object} data - The data to be validated.
844
+ * @param {string} [data.url] - Optional URL to be validated.
845
+ * @param {string} [data.email] - Optional email address to be validated.
846
+ * @param {Interfaces.PhoneData} [data.phone] - Optional phone number data to be validated.
847
+ * @param {string} [data.domain] - Optional domain name to be validated.
848
+ * @param {string|Interfaces.CreditCardData} [data.creditCard] - Optional credit card number or data to be validated.
849
+ * @param {string} [data.ip] - Optional IP address to be validated.
850
+ * @param {string} [data.wallet] - Optional wallet address to be validated.
851
+ * @param {string} [data.userAgent] - Optional user agent string to be validated.
852
+ * @param {string} [data.iban] - Optional IBAN to be validated.
853
+ * @param {Interfaces.VerifyPlugins[]} [data.plugins] - Optional array of verification plugins to be used.
854
+ * @returns {Promise<Interfaces.DataValidationAnalysis>} A promise that resolves to the response from the server.
855
+ * @throws Will throw an error if there is an issue with the validation process.
856
+ *
857
+ * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier)
858
+ */
859
+ async isValidData(data) {
860
+ const fallbackData = FallbackDataGenerator.generateFallbackData("isValidData", data);
861
+ return await this.resilienceManager.executeWithResilience(
862
+ this.axiosClient,
863
+ {
864
+ method: "POST",
865
+ url: "/private/secure/verify",
866
+ data
867
+ },
868
+ this.resilienceManager.getConfig().fallbackEnabled ? fallbackData : void 0
869
+ );
870
+ }
871
+ /**
872
+ * Validates the given data against the configured validation settings.
873
+ *
874
+ * This method requires either the root API key or the API key to be set.
875
+ * If neither is set, it will throw an error.
876
+ *
877
+ * @param {Object} data - The data to be validated.
878
+ * @param {string} [data.url] - Optional URL to be validated.
879
+ * @param {string} [data.email] - Optional email address to be validated.
880
+ * @param {Interfaces.PhoneData} [data.phone] - Optional phone number data to be validated.
881
+ * @param {string} [data.domain] - Optional domain name to be validated.
882
+ * @param {string|Interfaces.CreditCardData} [data.creditCard] - Optional credit card number or data to be validated.
883
+ * @param {string} [data.ip] - Optional IP address to be validated.
884
+ * @param {string} [data.wallet] - Optional wallet address to be validated.
885
+ * @param {string} [data.userAgent] - Optional user agent string to be validated.
886
+ * @param {string} [data.iban] - Optional IBAN to be validated.
887
+ * @param {Interfaces.VerifyPlugins[]} [data.plugins] - Optional array of verification plugins to be used.
888
+ * @returns {Promise<Interfaces.DataValidationAnalysis>} A promise that resolves to the response from the server.
889
+ * @throws Will throw an error if there is an issue with the validation process.
890
+ *
891
+ * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier)
892
+ */
893
+ async isValidDataRaw(data) {
894
+ const fallbackData = FallbackDataGenerator.generateFallbackData("isValidDataRaw", data);
895
+ return await this.resilienceManager.executeWithResilience(
896
+ this.axiosClient,
897
+ {
898
+ method: "POST",
899
+ url: "/private/secure/verify",
900
+ data
901
+ },
902
+ this.resilienceManager.getConfig().fallbackEnabled ? fallbackData : void 0
903
+ );
904
+ }
905
+ /**
906
+ * Validates the given email against the configured rules.
907
+ *
908
+ * This method requires either the root API key or the API key to be set.
909
+ * If neither is set, it will throw an error.
910
+ *
911
+ * @param {string} [email] - Email address to validate.
912
+ * @param {NegativeEmailRules[]} [rules] - Optional rules for validation. Some rules are premium features.
913
+ * @important
914
+ * **⚠️ NO_MX_RECORDS, HIGH_RISK_SCORE and NO_REACHABLE are [PREMIUM](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier) features.**
915
+ * @returns {Promise<Interfaces.EmailValidatorResponse>} Resolves with the validation response.
916
+ * @throws Will throw an error if validation cannot be performed.
917
+ *
918
+ * @example
919
+ * const valid = await dymoClient.isValidEmail("user@example.com", { deny: ["FRAUD", "NO_MX_RECORDS"] });
920
+ *
921
+ * @see [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/email-validation)
922
+ */
923
+ async isValidEmail(email, rules = this.rules.email) {
924
+ const fallbackData = FallbackDataGenerator.generateFallbackData("isValidEmail", email);
925
+ return await this.resilienceManager.executeWithResilience(
926
+ this.axiosClient,
927
+ {
928
+ method: "POST",
929
+ url: "/private/secure/verify",
930
+ data: { email, plugins: this.getEmailPlugins(rules) }
931
+ },
932
+ this.resilienceManager.getConfig().fallbackEnabled ? fallbackData : void 0
933
+ );
934
+ }
935
+ /**
936
+ * Validates the given IP against the configured rules.
937
+ *
938
+ * This method requires either the root API key or the API key to be set.
939
+ * If neither is set, it will throw an error.
940
+ *
941
+ * @param {string} [ip] - IP address to validate.
942
+ * @param {NegativeEmailRules[]} [rules] - Optional rules for validation. Some rules are premium features.
943
+ * @important
944
+ * **⚠️ TOR_NETWORK and HIGH_RISK_SCORE are [PREMIUM](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier) features.**
945
+ * @returns {Promise<Interfaces.IPValidatorResponse>} Resolves with the validation response.
946
+ * @throws Will throw an error if validation cannot be performed.
947
+ *
948
+ * @example
949
+ * const valid = await isValidIP("52.94.236.248", { deny: ["FRAUD", "TOR_NETWORK", "COUNTRY:RU"] });
950
+ *
951
+ * @see [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/ip-validation)
952
+ */
953
+ async isValidIP(ip, rules = this.rules.ip) {
954
+ return await isValidIP(this.axiosClient, ip, rules);
955
+ }
956
+ /**
957
+ * Validates the given email against the configured rules.
958
+ *
959
+ * This method requires either the root API key or the API key to be set.
960
+ * If neither is set, it will throw an error.
961
+ *
962
+ * @param {string} [phone] - Phone number to validate.
963
+ * @param {NegativePhoneRules[]} [rules] - Optional rules for validation. Some rules are premium features.
964
+ * @important
965
+ * **⚠️ HIGH_RISK_SCORE is a [PREMIUM](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier) feature.**
966
+ * @returns {Promise<Interfaces.EmailValidatorResponse>} Resolves with the validation response.
967
+ * @throws Will throw an error if validation cannot be performed.
968
+ *
969
+ * @example
970
+ * const valid = await dymoClient.isValidPhone("+34617509462", { deny: ["FRAUD", "INVALID"] });
971
+ *
972
+ * @see [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/phone-validation)
973
+ */
974
+ async isValidPhone(phone, rules = this.rules.phone) {
975
+ return await isValidPhone(this.axiosClient, phone, rules);
976
+ }
977
+ /**
978
+ * Protects the given request against the configured rules.
979
+ *
980
+ * This method requires either the root API key or the API key to be set.
981
+ * If neither is set, it will throw an error.
982
+ *
983
+ * @param {Object} req - The request object to be protected.
984
+ * @param {Interfaces.WafRules} [rules] - Optional rules for protection. Some rules are premium features.
985
+ * @returns {Promise<Interfaces.HTTPRequest>} Resolves with the protected request.
986
+ * @important
987
+ * **⚠️ This is a [PREMIUM](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier) and BETA feature.**
988
+ * @throws Will throw an error if protection cannot be performed.
989
+ *
990
+ * @example
991
+ * const protectedReq = await dymoClient.protectReq(req);
992
+ *
993
+ * @see [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/data-verifier)
994
+ */
995
+ async protectReq(req, rules = this.rules.waf) {
996
+ return await protectReq(this.axiosClient, req, rules);
997
+ }
998
+ /**
999
+ * Sends an email using the configured email client settings.
1000
+ *
1001
+ * This method requires either the root API key or the server email config to be set.
1002
+ * If neither is set, it will throw an error.
1003
+ *
1004
+ * @param {Object} data - The email data to be sent.
1005
+ * @param {string} data.from - The email address from which the email will be sent.
1006
+ * @param {string} data.to - The email address to which the email will be sent.
1007
+ * @param {string} data.subject - The subject of the email.
1008
+ * @param {string} [data.html] - The HTML content of the email.
1009
+ * @param {React.ReactElement} [data.react] - The React component to be rendered as the email content.
1010
+ * @param {Object} [data.options] - Content configuration options.
1011
+ * @param {"high" | "normal" | "low" | undefined} [data.options.priority="normal"] - Email priority (default: normal).
1012
+ * @param {boolean} [data.options.waitToResponse=true] - Wait until the email is sent (default: true).
1013
+ * @param {boolean} [data.options.composeTailwindClasses] - Whether to compose tailwind classes.
1014
+ * @param {Attachment[]} [data.attachments] - An array of attachments to be included in the email.
1015
+ * @param {string} data.attachments[].filename - The name of the attached file.
1016
+ * @param {string} [data.attachments[].path] - The path or URL of the attached file. Either this or `content` must be provided.
1017
+ * @param {Buffer} [data.attachments[].content] - The content of the attached file as a Buffer. Either this or `path` must be provided.
1018
+ * @param {string} [data.attachments[].cid] - The CID (Content-ID) of the attached file, used for inline images.
1019
+ * @returns {Promise<Interfaces.EmailStatus>} A promise that resolves to the response from the server.
1020
+ * @throws Will throw an error if there is an issue with the email sending process.
1021
+ *
1022
+ * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/sender-send-email/getting-started)
1023
+ */
1024
+ async sendEmail(data) {
1025
+ if (!this.serverEmailConfig && !this.rootApiKey) console.error(`[${config.lib.name}] You must configure the email client settings.`);
1026
+ return await sendEmail(this.axiosClient, { serverEmailConfig: this.serverEmailConfig, ...data });
1027
+ }
1028
+ /**
1029
+ * Generates a random number between the provided min and max values.
1030
+ *
1031
+ * This method requires either the root API key or the API key to be set.
1032
+ * If neither is set, it will throw an error.
1033
+ *
1034
+ * @param {Interfaces.SRNG} data - The data to be sent.
1035
+ * @param {number} data.min - The minimum value of the range.
1036
+ * @param {number} data.max - The maximum value of the range.
1037
+ * @param {number} [data.quantity] - The number of random values to generate. Defaults to 1 if not provided.
1038
+ * @returns {Promise<Interfaces.SRNSummary>} A promise that resolves to the response from the server.
1039
+ * @throws Will throw an error if there is an issue with the random number generation process.
1040
+ *
1041
+ * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/secure-random-number-generator)
1042
+ */
1043
+ async getRandom(data) {
1044
+ return await getRandom(this.axiosClient, data);
1045
+ }
1046
+ /**
1047
+ * Extracts structured data from a given string using Textly.
1048
+ *
1049
+ * This method requires either the root API key or the API key to be set.
1050
+ * If neither is set, it will throw an error.
1051
+ *
1052
+ * @param {Interfaces.ExtractWithTextly} data - The data to be sent, containing the string to be processed and the format schema.
1053
+ * @returns {Promise<any>} A promise that resolves to the extracted structured data.
1054
+ * @throws Will throw an error if there is an issue with the extraction process.
1055
+ *
1056
+ * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/private/textly/text-extraction)
1057
+ */
1058
+ async extractWithTextly(data) {
1059
+ return await extractWithTextly(this.axiosClient, data);
1060
+ }
1061
+ // FUNCTIONS / Public.
1062
+ /**
1063
+ * Retrieves the prayer times for the given location.
1064
+ *
1065
+ * This method requires a latitude and longitude to be provided in the
1066
+ * data object. If either of these are not provided, it will throw an error.
1067
+ *
1068
+ * @param {Object} data - The data to be sent.
1069
+ * @param {number} data.lat - The latitude of the location.
1070
+ * @param {number} data.lon - The longitude of the location.
1071
+ * @returns {Promise<Interfaces.CountryPrayerTimes | { error: string }>} A promise that resolves to the response from the server.
1072
+ * @throws Will throw an error if there is an issue with the prayer times retrieval process.
1073
+ *
1074
+ * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/public/prayertimes)
1075
+ */
1076
+ async getPrayerTimes(data) {
1077
+ return await getPrayerTimes(this.axiosClient, data);
1078
+ }
1079
+ /**
1080
+ * Satinizes the input, replacing any special characters with their HTML
1081
+ * entities.
1082
+ *
1083
+ * @deprecated Use `satinize` instead. This feature will be removed soon.
1084
+ * @param {Object} data - The data to be sent.
1085
+ * @param {string} data.input - The input to be satinized.
1086
+ * @returns {Promise<Interfaces.SatinizedInputAnalysis>} A promise that resolves to the response from the server.
1087
+ * @throws Will throw an error if there is an issue with the satinization process.
1088
+ *
1089
+ * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/public/input-satinizer)
1090
+ */
1091
+ async satinizer(data) {
1092
+ return await satinize(this.axiosClient, data.input);
1093
+ }
1094
+ /**
1095
+ * Satinizes the input, replacing any special characters with their HTML
1096
+ * entities.
1097
+ *
1098
+ * @param {Object} data - The data to be sent.
1099
+ * @param {string} data.input - The input to be satinized.
1100
+ * @returns {Promise<Interfaces.SatinizedInputAnalysis>} A promise that resolves to the response from the server.
1101
+ * @throws Will throw an error if there is an issue with the satinization process.
1102
+ *
1103
+ * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/public/input-satinizer)
1104
+ */
1105
+ async satinize(input) {
1106
+ return await satinize(this.axiosClient, input);
1107
+ }
1108
+ /**
1109
+ * Validates a password based on the given parameters.
1110
+ *
1111
+ * This method requires the password to be provided in the data object.
1112
+ * If the password is not provided, it will throw an error. The method
1113
+ * will validate the password against the following rules:
1114
+ * - The password must be at least 8 characters long.
1115
+ * - The password must be at most 32 characters long.
1116
+ * - The password must contain at least one uppercase letter.
1117
+ * - The password must contain at least one lowercase letter.
1118
+ * - The password must contain at least one number.
1119
+ * - The password must contain at least one special character.
1120
+ * - The password must not contain any of the given banned words.
1121
+ *
1122
+ * @param {Object} data - The data to be sent.
1123
+ * @param {number} [data.min] - Minimum length of the password. Defaults to 8 if not provided.
1124
+ * @param {number} [data.max] - Maximum length of the password. Defaults to 32 if not provided.
1125
+ * @param {string} [data.email] - Optional email associated with the password.
1126
+ * @param {string} data.password - The password to be validated.
1127
+ * @param {string | string[]} [data.bannedWords] - The list of banned words that the password must not contain.
1128
+ * @returns {Promise<Interfaces.PasswordValidationResult>} A promise that resolves to the response from the server.
1129
+ * @throws Will throw an error if there is an issue with the password validation process.
1130
+ *
1131
+ * [Documentation](https://docs.tpeoficial.com/docs/dymo-api/public/password-validator)
1132
+ */
1133
+ async isValidPwd(data) {
1134
+ return await isValidPwd(this.axiosClient, data);
1135
+ }
368
1136
  }
369
- ;
370
- export default DymoAPI;
1137
+ export {
1138
+ DymoAPI as default
1139
+ };