temp-disposable-email 0.0.0

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 (90) hide show
  1. package/.nvmrc +1 -0
  2. package/LICENSE +21 -0
  3. package/README.md +196 -0
  4. package/cypress.config.ts +12 -0
  5. package/dist/cjs/index.d.ts +4 -0
  6. package/dist/cjs/index.d.ts.map +1 -0
  7. package/dist/cjs/index.js +47 -0
  8. package/dist/cjs/index.js.map +1 -0
  9. package/dist/cjs/services/accountService.d.ts +37 -0
  10. package/dist/cjs/services/accountService.d.ts.map +1 -0
  11. package/dist/cjs/services/accountService.js +100 -0
  12. package/dist/cjs/services/accountService.js.map +1 -0
  13. package/dist/cjs/services/authService.d.ts +3 -0
  14. package/dist/cjs/services/authService.d.ts.map +1 -0
  15. package/dist/cjs/services/authService.js +22 -0
  16. package/dist/cjs/services/authService.js.map +1 -0
  17. package/dist/cjs/services/messageService.d.ts +54 -0
  18. package/dist/cjs/services/messageService.d.ts.map +1 -0
  19. package/dist/cjs/services/messageService.js +122 -0
  20. package/dist/cjs/services/messageService.js.map +1 -0
  21. package/dist/cjs/utils/api.d.ts +7 -0
  22. package/dist/cjs/utils/api.d.ts.map +1 -0
  23. package/dist/cjs/utils/api.js +47 -0
  24. package/dist/cjs/utils/api.js.map +1 -0
  25. package/dist/cjs/utils/constant.d.ts +2 -0
  26. package/dist/cjs/utils/constant.d.ts.map +1 -0
  27. package/dist/cjs/utils/constant.js +5 -0
  28. package/dist/cjs/utils/constant.js.map +1 -0
  29. package/dist/cjs/utils/delay.d.ts +2 -0
  30. package/dist/cjs/utils/delay.d.ts.map +1 -0
  31. package/dist/cjs/utils/delay.js +6 -0
  32. package/dist/cjs/utils/delay.js.map +1 -0
  33. package/dist/cjs/utils/generateRandomName.d.ts +2 -0
  34. package/dist/cjs/utils/generateRandomName.d.ts.map +1 -0
  35. package/dist/cjs/utils/generateRandomName.js +6 -0
  36. package/dist/cjs/utils/generateRandomName.js.map +1 -0
  37. package/dist/cjs/utils/getVerificationCode.d.ts +17 -0
  38. package/dist/cjs/utils/getVerificationCode.d.ts.map +1 -0
  39. package/dist/cjs/utils/getVerificationCode.js +29 -0
  40. package/dist/cjs/utils/getVerificationCode.js.map +1 -0
  41. package/dist/esm/index.d.ts +4 -0
  42. package/dist/esm/index.d.ts.map +1 -0
  43. package/dist/esm/index.js +6 -0
  44. package/dist/esm/index.js.map +1 -0
  45. package/dist/esm/services/accountService.d.ts +37 -0
  46. package/dist/esm/services/accountService.d.ts.map +1 -0
  47. package/dist/esm/services/accountService.js +92 -0
  48. package/dist/esm/services/accountService.js.map +1 -0
  49. package/dist/esm/services/authService.d.ts +3 -0
  50. package/dist/esm/services/authService.d.ts.map +1 -0
  51. package/dist/esm/services/authService.js +14 -0
  52. package/dist/esm/services/authService.js.map +1 -0
  53. package/dist/esm/services/messageService.d.ts +54 -0
  54. package/dist/esm/services/messageService.d.ts.map +1 -0
  55. package/dist/esm/services/messageService.js +114 -0
  56. package/dist/esm/services/messageService.js.map +1 -0
  57. package/dist/esm/utils/api.d.ts +7 -0
  58. package/dist/esm/utils/api.d.ts.map +1 -0
  59. package/dist/esm/utils/api.js +38 -0
  60. package/dist/esm/utils/api.js.map +1 -0
  61. package/dist/esm/utils/constant.d.ts +2 -0
  62. package/dist/esm/utils/constant.d.ts.map +1 -0
  63. package/dist/esm/utils/constant.js +2 -0
  64. package/dist/esm/utils/constant.js.map +1 -0
  65. package/dist/esm/utils/delay.d.ts +2 -0
  66. package/dist/esm/utils/delay.d.ts.map +1 -0
  67. package/dist/esm/utils/delay.js +2 -0
  68. package/dist/esm/utils/delay.js.map +1 -0
  69. package/dist/esm/utils/generateRandomName.d.ts +2 -0
  70. package/dist/esm/utils/generateRandomName.d.ts.map +1 -0
  71. package/dist/esm/utils/generateRandomName.js +2 -0
  72. package/dist/esm/utils/generateRandomName.js.map +1 -0
  73. package/dist/esm/utils/getVerificationCode.d.ts +17 -0
  74. package/dist/esm/utils/getVerificationCode.d.ts.map +1 -0
  75. package/dist/esm/utils/getVerificationCode.js +25 -0
  76. package/dist/esm/utils/getVerificationCode.js.map +1 -0
  77. package/jest.config.js +8 -0
  78. package/package.json +60 -0
  79. package/playwright.config.ts +78 -0
  80. package/src/index.ts +11 -0
  81. package/src/services/accountService.ts +103 -0
  82. package/src/services/authService.ts +23 -0
  83. package/src/services/messageService.ts +155 -0
  84. package/src/utils/api.ts +38 -0
  85. package/src/utils/constant.ts +1 -0
  86. package/src/utils/delay.ts +2 -0
  87. package/src/utils/generateRandomName.ts +2 -0
  88. package/src/utils/getVerificationCode.ts +27 -0
  89. package/tsconfig.cjs.json +16 -0
  90. package/tsconfig.json +17 -0
package/.nvmrc ADDED
@@ -0,0 +1 @@
1
+ 20.x.x
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Pirasanthan Jesugeevegan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,196 @@
1
+ <h1 align="center">Temp Disposable Email</h1>
2
+ <p align="center">
3
+ <a href="#feature">Features</a> |
4
+ <a href="#install">Install</a> |
5
+ <a href="#usage">Usage </a>|
6
+ <a href="#example">Examples </a>|
7
+ <a href="#doc">API Document</a>
8
+ </p>
9
+
10
+ <div align="center">
11
+ <span style="display: inline-block; margin-right: 10px;">
12
+ <a href="https://www.npmjs.com/package/gmail-tester">
13
+ <img src="https://badge.fury.io/js/temp-disposable-email.svg" alt="npm version" />
14
+ </a>
15
+ </span>
16
+ <span style="display: inline-block; margin-right: 10px;">
17
+ <img src="https://img.shields.io/npm/d18m/temp-disposable-email" alt="NPM Downloads" />
18
+ </span>
19
+ <span style="display: inline-block; margin-right: 10px;">
20
+ <a href="https://opensource.org/licenses/MIT">
21
+ <img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT" />
22
+ </a>
23
+ </span>
24
+ <span style="display: inline-block;">
25
+ <a href="https://github.com/pirasanthan-jesugeevegan/temp-disposable-email">
26
+ <img src="https://img.shields.io/github/stars/pirasanthan-jesugeevegan/temp-disposable-email?style=social" alt="GitHub stars" />
27
+ </a>
28
+ </span>
29
+ </div>
30
+
31
+ This npm package provides a simple interface for temp email. You can use it to create disposable email accounts, retrieve messages, and delete accounts when done. It includes polling functionality to wait for messages in the inbox and fetch their content.
32
+
33
+ <p id="feature"></p>
34
+
35
+ ## Features
36
+
37
+ - **Create Inbox**: Generate a unique, random email address and create an inbox.
38
+ - **Fetch Messages**: Retrieve the latest messages from the inbox.
39
+ - **Read Message Content**: Get the content (HTML and text) of a specific message.
40
+ - **Delete Messages**: Delete a specific message from the inbox.
41
+ - **Delete Account**: Remove the temporary account after usage
42
+
43
+ <p id="install"></p>
44
+
45
+ ## Installation
46
+
47
+ You can install this package via npm:
48
+
49
+ ```bash
50
+ npm install temp-disposable-email
51
+ ```
52
+
53
+ <p id="usage"></p>
54
+
55
+ ## Usage
56
+
57
+ ### 1\. Importing the package
58
+
59
+ To use the package, import the functions in your TypeScript or JavaScript project:
60
+
61
+ #### Using ES Modules (Recommended)
62
+
63
+ ```typescript
64
+ import { createInbox, getMessage, deleteAccount } from 'temp-disposable-email';
65
+ ```
66
+
67
+ #### Using CommonJS
68
+
69
+ ```javascript
70
+ const {
71
+ createInbox,
72
+ getMessage,
73
+ deleteAccount,
74
+ } = require('temp-disposable-email');
75
+ ```
76
+
77
+ ### 2\. Create an Inbox
78
+
79
+ This function creates a new disposable email account using a random username or a specified one. It also authenticates and generates a token for accessing messages.
80
+
81
+ ```typescript
82
+ const email = await createInbox(); // or pass a custom username
83
+ console.log('Created email address:', email);
84
+ ```
85
+
86
+ #### Parameters
87
+
88
+ - `username` (Optional): The username for the new email address. If not provided, a random username will be generated.
89
+
90
+ #### Returns
91
+
92
+ - `Promise<string>`: The generated email address.
93
+
94
+ ### 3\. Fetch Recent Email
95
+
96
+ This function retrieves the latest message from the created inbox. You can specify polling options (timeout, interval, logging) for periodic checks when no message is immediately available.
97
+
98
+ ```typescript
99
+ const message = await getRecentEmail();
100
+ console.log('Message received:', message);
101
+ ```
102
+
103
+ #### Parameters
104
+
105
+ - `options` (Optional): Polling options that can include:
106
+ - `maxWaitTime`: Maximum polling time in milliseconds (default: 30,000ms).
107
+ - `waitInterval`: Interval between polling attempts in milliseconds (default: 2,000ms).
108
+ - `logPolling`: Enable or disable logging of polling attempts (default: false).
109
+ - `deleteAfterRead`: Whether to delete the latest message after reading, helpful for parallel run
110
+
111
+ #### Returns
112
+
113
+ - `Promise<object | null>`: An object containing email details like `from`, `to`, `subject`, `intro`, `text`, and `html`.
114
+
115
+ ### 4\. Delete the Created Account
116
+
117
+ Once you're done with the email inbox, you can delete the account to clean up resources.
118
+
119
+ ```typescript
120
+ await deleteAccount();
121
+ console.log('Account deleted');
122
+ ```
123
+
124
+ #### Returns
125
+
126
+ - `Promise<void>`: Resolves when the account is successfully deleted.
127
+
128
+ <p id="example"></p>
129
+
130
+ ## Example Workflow
131
+
132
+ Here's a complete example of creating an inbox, retrieving a message, and deleting the account:
133
+
134
+ ```typescript
135
+ import { createInbox, getMessage, deleteAccount } from 'temp-disposable-email';
136
+
137
+ async function run() {
138
+ try {
139
+ // Create a new inbox
140
+ const email = await createInbox();
141
+ console.log('Created email:', email);
142
+
143
+ // Get the first available message from the inbox
144
+ const message = await getMessage({
145
+ maxWaitTime: 50000,
146
+ waitInterval: 3000,
147
+ logPolling: true,
148
+ });
149
+ console.log('Received message:', message);
150
+
151
+ // Delete the inbox
152
+ await deleteAccount();
153
+ console.log('Account deleted successfully');
154
+ } catch (error) {
155
+ console.error('Error:', error.message);
156
+ }
157
+ }
158
+
159
+ run();
160
+ ```
161
+
162
+ <p id="doc"></p>
163
+
164
+ ## API Documentation
165
+
166
+ ### `createInbox(username?: string): Promise<string>`
167
+
168
+ - **Description**: Creates a disposable inbox with a randomly generated or provided username.
169
+ - **Parameters**:
170
+ - `username` (Optional): A custom username for the email address.
171
+ - **Returns**: A promise that resolves to the generated email address.
172
+
173
+ ### `getRecentEmail(options?: GetEmailOptions): Promise<any | null>`
174
+
175
+ - **Description**: Retrieves the latest message from the inbox, polling if necessary.
176
+ - **Parameters**:
177
+ - `options` (Optional): Polling configuration for waiting for messages. See GetEmailOptions.
178
+ - **Returns**: A promise that resolves to the message content (or `null` if no messages are found).
179
+
180
+ ### `deleteAccount(): Promise<void>`
181
+
182
+ - **Description**: Deletes the inbox and its associated account.
183
+ - **Returns**: A promise that resolves when the account is successfully deleted.
184
+
185
+ ## Get Email Options
186
+
187
+ You can configure polling behavior by passing an options object to `getMessage`. The available options are:
188
+
189
+ - `maxWaitTime` (Optional): The maximum time to wait for messages (in milliseconds).
190
+ - `waitInterval` (Optional): The interval between polling attempts (in milliseconds).
191
+ - `logPolling` (Optional): Whether to log each polling attempt for debugging purposes.
192
+ - `deleteAfterRead` (Optional): Whether to delete messages after reading
193
+
194
+ ## License
195
+
196
+ This project is licensed under the MIT License.
@@ -0,0 +1,12 @@
1
+ import { defineConfig } from 'cypress';
2
+
3
+ export default defineConfig({
4
+ e2e: {
5
+ specPattern: 'examples/cypress/e2e/**/*.cy.ts',
6
+ supportFile: 'examples/cypress/support/e2e.ts',
7
+ fixturesFolder: 'examples/cypress/fixtures',
8
+ setupNodeEvents(on, config) {
9
+ // implement node event listeners here
10
+ },
11
+ },
12
+ });
@@ -0,0 +1,4 @@
1
+ export { createInbox, deleteAccount } from './services/accountService';
2
+ export { getRecentEmail, deleteMessage, MessageContent, GetEmailOptions, } from './services/messageService';
3
+ export { getVerificationCode } from './utils/getVerificationCode';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,EACL,cAAc,EACd,aAAa,EACb,cAAc,EACd,eAAe,GAChB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC"}
@@ -0,0 +1,47 @@
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 () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.getVerificationCode = exports.deleteMessage = exports.getRecentEmail = exports.deleteAccount = exports.createInbox = void 0;
37
+ const dotenv = __importStar(require("dotenv"));
38
+ dotenv.config();
39
+ var accountService_1 = require("./services/accountService");
40
+ Object.defineProperty(exports, "createInbox", { enumerable: true, get: function () { return accountService_1.createInbox; } });
41
+ Object.defineProperty(exports, "deleteAccount", { enumerable: true, get: function () { return accountService_1.deleteAccount; } });
42
+ var messageService_1 = require("./services/messageService");
43
+ Object.defineProperty(exports, "getRecentEmail", { enumerable: true, get: function () { return messageService_1.getRecentEmail; } });
44
+ Object.defineProperty(exports, "deleteMessage", { enumerable: true, get: function () { return messageService_1.deleteMessage; } });
45
+ var getVerificationCode_1 = require("./utils/getVerificationCode");
46
+ Object.defineProperty(exports, "getVerificationCode", { enumerable: true, get: function () { return getVerificationCode_1.getVerificationCode; } });
47
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAiC;AACjC,MAAM,CAAC,MAAM,EAAE,CAAC;AAEhB,4DAAuE;AAA9D,6GAAA,WAAW,OAAA;AAAE,+GAAA,aAAa,OAAA;AACnC,4DAKmC;AAJjC,gHAAA,cAAc,OAAA;AACd,+GAAA,aAAa,OAAA;AAIf,mEAAkE;AAAzD,0HAAA,mBAAmB,OAAA"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Creates a new email inbox with a unique address.
3
+ *
4
+ * This function selects an available domain, generates an email
5
+ * address, and attempts to create an account on the Mail.tm service.
6
+ * If account creation is rate-limited, the function retries with a
7
+ * delay. Upon successful creation, it authenticates the account and
8
+ * stores the token and account ID for future API calls.
9
+ *
10
+ * @param {string} [username] - Optional username; a random one is generated if not provided.
11
+ * @returns {Promise<string>} The generated email address.
12
+ *
13
+ * @throws {Error} If no domains are available or account creation fails.
14
+ *
15
+ * @example
16
+ * const email = await createInbox("customUser");
17
+ * console.log(email); // Outputs: "customUser@mail.tm"
18
+ */
19
+ export declare const createInbox: (username?: string) => Promise<string>;
20
+ /**
21
+ * Deletes the account created during `createInbox`.
22
+ *
23
+ * This function removes the email account from the Mail.tm service
24
+ * and clears the stored authentication token and account ID.
25
+ * Subsequent API calls requiring authentication will fail until a
26
+ * new account is created.
27
+ *
28
+ * @returns {Promise<void>} Resolves when the account is successfully deleted.
29
+ *
30
+ * @throws {Error} If no account is authenticated or deletion fails.
31
+ *
32
+ * @example
33
+ * await deleteAccount();
34
+ * console.log("Account deleted successfully.");
35
+ */
36
+ export declare const deleteAccount: () => Promise<void>;
37
+ //# sourceMappingURL=accountService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accountService.d.ts","sourceRoot":"","sources":["../../../src/services/accountService.ts"],"names":[],"mappings":"AAOA;;;;;;;;;;;;;;;;;GAiBG;AAEH,eAAO,MAAM,WAAW,cAAqB,MAAM,KAAG,OAAO,CAAC,MAAM,CA2CnE,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,aAAa,QAAa,OAAO,CAAC,IAAI,CAelD,CAAC"}
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.deleteAccount = exports.createInbox = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const authService_1 = require("./authService");
9
+ const generateRandomName_1 = require("../utils/generateRandomName");
10
+ const delay_1 = require("../utils/delay");
11
+ const constant_1 = require("../utils/constant");
12
+ let accountId = null;
13
+ /**
14
+ * Creates a new email inbox with a unique address.
15
+ *
16
+ * This function selects an available domain, generates an email
17
+ * address, and attempts to create an account on the Mail.tm service.
18
+ * If account creation is rate-limited, the function retries with a
19
+ * delay. Upon successful creation, it authenticates the account and
20
+ * stores the token and account ID for future API calls.
21
+ *
22
+ * @param {string} [username] - Optional username; a random one is generated if not provided.
23
+ * @returns {Promise<string>} The generated email address.
24
+ *
25
+ * @throws {Error} If no domains are available or account creation fails.
26
+ *
27
+ * @example
28
+ * const email = await createInbox("customUser");
29
+ * console.log(email); // Outputs: "customUser@mail.tm"
30
+ */
31
+ const createInbox = async (username) => {
32
+ const domainsResponse = await axios_1.default.get(`${constant_1.BASE_URL}/domains`, {
33
+ headers: { accept: 'application/ld+json' },
34
+ });
35
+ const domains = domainsResponse.data['hydra:member'].map((domain) => domain.domain);
36
+ if (domains.length === 0)
37
+ throw new Error('No available domains.');
38
+ const emailAddress = `${username || (0, generateRandomName_1.generateRandomName)()}@${domains[0]}`;
39
+ const password = (0, generateRandomName_1.generateRandomName)();
40
+ let attempts = 0;
41
+ const maxRetries = 5;
42
+ while (attempts < maxRetries) {
43
+ try {
44
+ const accountResponse = await axios_1.default.post(`${constant_1.BASE_URL}/accounts`, { address: emailAddress, password }, {
45
+ headers: {
46
+ accept: 'application/json',
47
+ 'Content-Type': 'application/json',
48
+ },
49
+ });
50
+ accountId = accountResponse.data.id;
51
+ await (0, authService_1.authenticate)(emailAddress, password);
52
+ return emailAddress;
53
+ }
54
+ catch (error) {
55
+ if (error.response?.status === 429) {
56
+ attempts++;
57
+ const retryAfter = error.response.headers['retry-after']
58
+ ? parseInt(error.response.headers['retry-after'])
59
+ : 5;
60
+ await (0, delay_1.delay)(retryAfter * 1000);
61
+ }
62
+ else {
63
+ throw error;
64
+ }
65
+ }
66
+ }
67
+ throw new Error('Failed to create account after multiple retries.');
68
+ };
69
+ exports.createInbox = createInbox;
70
+ /**
71
+ * Deletes the account created during `createInbox`.
72
+ *
73
+ * This function removes the email account from the Mail.tm service
74
+ * and clears the stored authentication token and account ID.
75
+ * Subsequent API calls requiring authentication will fail until a
76
+ * new account is created.
77
+ *
78
+ * @returns {Promise<void>} Resolves when the account is successfully deleted.
79
+ *
80
+ * @throws {Error} If no account is authenticated or deletion fails.
81
+ *
82
+ * @example
83
+ * await deleteAccount();
84
+ * console.log("Account deleted successfully.");
85
+ */
86
+ const deleteAccount = async () => {
87
+ const token = (0, authService_1.getToken)();
88
+ if (!token || !accountId) {
89
+ throw new Error('Account information missing. Create and authenticate an account first.');
90
+ }
91
+ await axios_1.default.delete(`${constant_1.BASE_URL}/accounts/${accountId}`, {
92
+ headers: {
93
+ accept: '*/*',
94
+ Authorization: `Bearer ${token}`,
95
+ },
96
+ });
97
+ accountId = null;
98
+ };
99
+ exports.deleteAccount = deleteAccount;
100
+ //# sourceMappingURL=accountService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accountService.js","sourceRoot":"","sources":["../../../src/services/accountService.ts"],"names":[],"mappings":";;;;;;AAAA,kDAA0B;AAC1B,+CAAuD;AACvD,oEAAiE;AACjE,0CAAuC;AACvC,gDAA6C;AAE7C,IAAI,SAAS,GAAkB,IAAI,CAAC;AACpC;;;;;;;;;;;;;;;;;GAiBG;AAEI,MAAM,WAAW,GAAG,KAAK,EAAE,QAAiB,EAAmB,EAAE;IACtE,MAAM,eAAe,GAAG,MAAM,eAAK,CAAC,GAAG,CAAC,GAAG,mBAAQ,UAAU,EAAE;QAC7D,OAAO,EAAE,EAAE,MAAM,EAAE,qBAAqB,EAAE;KAC3C,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,GAAG,CACtD,CAAC,MAA0B,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAC9C,CAAC;IACF,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;IAEnE,MAAM,YAAY,GAAG,GAAG,QAAQ,IAAI,IAAA,uCAAkB,GAAE,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;IACzE,MAAM,QAAQ,GAAG,IAAA,uCAAkB,GAAE,CAAC;IAEtC,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,MAAM,UAAU,GAAG,CAAC,CAAC;IAErB,OAAO,QAAQ,GAAG,UAAU,EAAE,CAAC;QAC7B,IAAI,CAAC;YACH,MAAM,eAAe,GAAG,MAAM,eAAK,CAAC,IAAI,CACtC,GAAG,mBAAQ,WAAW,EACtB,EAAE,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,EACnC;gBACE,OAAO,EAAE;oBACP,MAAM,EAAE,kBAAkB;oBAC1B,cAAc,EAAE,kBAAkB;iBACnC;aACF,CACF,CAAC;YACF,SAAS,GAAG,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC;YACpC,MAAM,IAAA,0BAAY,EAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;YAC3C,OAAO,YAAY,CAAC;QACtB,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,IAAI,KAAK,CAAC,QAAQ,EAAE,MAAM,KAAK,GAAG,EAAE,CAAC;gBACnC,QAAQ,EAAE,CAAC;gBACX,MAAM,UAAU,GAAG,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC;oBACtD,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;oBACjD,CAAC,CAAC,CAAC,CAAC;gBACN,MAAM,IAAA,aAAK,EAAC,UAAU,GAAG,IAAI,CAAC,CAAC;YACjC,CAAC;iBAAM,CAAC;gBACN,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;IACH,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;AACtE,CAAC,CAAC;AA3CW,QAAA,WAAW,eA2CtB;AAEF;;;;;;;;;;;;;;;GAeG;AACI,MAAM,aAAa,GAAG,KAAK,IAAmB,EAAE;IACrD,MAAM,KAAK,GAAG,IAAA,sBAAQ,GAAE,CAAC;IACzB,IAAI,CAAC,KAAK,IAAI,CAAC,SAAS,EAAE,CAAC;QACzB,MAAM,IAAI,KAAK,CACb,wEAAwE,CACzE,CAAC;IACJ,CAAC;IAED,MAAM,eAAK,CAAC,MAAM,CAAC,GAAG,mBAAQ,aAAa,SAAS,EAAE,EAAE;QACtD,OAAO,EAAE;YACP,MAAM,EAAE,KAAK;YACb,aAAa,EAAE,UAAU,KAAK,EAAE;SACjC;KACF,CAAC,CAAC;IACH,SAAS,GAAG,IAAI,CAAC;AACnB,CAAC,CAAC;AAfW,QAAA,aAAa,iBAexB"}
@@ -0,0 +1,3 @@
1
+ export declare const authenticate: (email: string, password: string) => Promise<void>;
2
+ export declare const getToken: () => string | null;
3
+ //# sourceMappingURL=authService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authService.d.ts","sourceRoot":"","sources":["../../../src/services/authService.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,YAAY,UAChB,MAAM,YACH,MAAM,KACf,OAAO,CAAC,IAAI,CAYd,CAAC;AAEF,eAAO,MAAM,QAAQ,QAAO,MAAM,GAAG,IAAa,CAAC"}
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getToken = exports.authenticate = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const constant_1 = require("../utils/constant");
9
+ let token = null;
10
+ const authenticate = async (email, password) => {
11
+ const response = await axios_1.default.post(`${constant_1.BASE_URL}/token`, { address: email, password }, {
12
+ headers: {
13
+ accept: 'application/json',
14
+ 'Content-Type': 'application/json',
15
+ },
16
+ });
17
+ token = response.data.token;
18
+ };
19
+ exports.authenticate = authenticate;
20
+ const getToken = () => token;
21
+ exports.getToken = getToken;
22
+ //# sourceMappingURL=authService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authService.js","sourceRoot":"","sources":["../../../src/services/authService.ts"],"names":[],"mappings":";;;;;;AAAA,kDAA0B;AAC1B,gDAA6C;AAE7C,IAAI,KAAK,GAAkB,IAAI,CAAC;AAEzB,MAAM,YAAY,GAAG,KAAK,EAC/B,KAAa,EACb,QAAgB,EACD,EAAE;IACjB,MAAM,QAAQ,GAAG,MAAM,eAAK,CAAC,IAAI,CAC/B,GAAG,mBAAQ,QAAQ,EACnB,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,EAC5B;QACE,OAAO,EAAE;YACP,MAAM,EAAE,kBAAkB;YAC1B,cAAc,EAAE,kBAAkB;SACnC;KACF,CACF,CAAC;IACF,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC;AAC9B,CAAC,CAAC;AAfW,QAAA,YAAY,gBAevB;AAEK,MAAM,QAAQ,GAAG,GAAkB,EAAE,CAAC,KAAK,CAAC;AAAtC,QAAA,QAAQ,YAA8B"}
@@ -0,0 +1,54 @@
1
+ export interface MessageContent {
2
+ from: {
3
+ address: string;
4
+ };
5
+ to: {
6
+ address: string;
7
+ }[];
8
+ subject: string;
9
+ intro: string;
10
+ text: string;
11
+ html: string;
12
+ }
13
+ export interface GetEmailOptions {
14
+ maxWaitTime?: number;
15
+ waitInterval?: number;
16
+ logPolling?: boolean;
17
+ deleteAfterRead?: boolean;
18
+ }
19
+ /**
20
+ * Retrieves the latest message from the inbox.
21
+ *
22
+ * If messages are available, this function fetches the first one and
23
+ * returns its details. Polling options can be specified to wait for
24
+ * messages if the inbox is empty. Optionally, the message can be
25
+ * deleted after reading.
26
+ *
27
+ * @param {GetEmailOptions} [options] - Optional settings for polling and deletion.
28
+ * @returns {Promise<MessageContent | null>} The email content (sender, recipient, subject, text, HTML), or `null` if no messages are found.
29
+ *
30
+ * @throws {Error} If no messages are available within the polling timeout or authentication fails.
31
+ *
32
+ * @example
33
+ * const message = await getRecentEmail({ maxWaitTime: 5000, waitInterval: 1000, logPolling: true });
34
+ * console.log(message.subject); // Outputs: "Hello!"
35
+ */
36
+ export declare const getRecentEmail: (options?: GetEmailOptions) => Promise<MessageContent | null>;
37
+ /**
38
+ * Deletes a message by its unique ID from the Mail.tm inbox.
39
+ *
40
+ * This function requires a valid authentication token. If the
41
+ * token is not set, an error is thrown. The message is deleted
42
+ * using the Mail.tm API, and a success or failure message is logged.
43
+ *
44
+ * @param {string} messageId - The unique ID of the message to delete.
45
+ * @returns {Promise<void>} Resolves after the message is deleted.
46
+ *
47
+ * @throws {Error} If authentication is missing or the deletion fails.
48
+ *
49
+ * @example
50
+ * await deleteMessage("12345");
51
+ * console.log("Message deleted successfully.");
52
+ */
53
+ export declare const deleteMessage: (messageId: string) => Promise<void>;
54
+ //# sourceMappingURL=messageService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messageService.d.ts","sourceRoot":"","sources":["../../../src/services/messageService.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1B,EAAE,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AACD,MAAM,WAAW,eAAe;IAC9B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,cAAc,aACf,eAAe,KACxB,OAAO,CAAC,cAAc,GAAG,IAAI,CAkF/B,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,aAAa,cAAqB,MAAM,KAAG,OAAO,CAAC,IAAI,CAenE,CAAC"}
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.deleteMessage = exports.getRecentEmail = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const authService_1 = require("./authService");
9
+ const constant_1 = require("../utils/constant");
10
+ const api_1 = require("../utils/api");
11
+ /**
12
+ * Retrieves the latest message from the inbox.
13
+ *
14
+ * If messages are available, this function fetches the first one and
15
+ * returns its details. Polling options can be specified to wait for
16
+ * messages if the inbox is empty. Optionally, the message can be
17
+ * deleted after reading.
18
+ *
19
+ * @param {GetEmailOptions} [options] - Optional settings for polling and deletion.
20
+ * @returns {Promise<MessageContent | null>} The email content (sender, recipient, subject, text, HTML), or `null` if no messages are found.
21
+ *
22
+ * @throws {Error} If no messages are available within the polling timeout or authentication fails.
23
+ *
24
+ * @example
25
+ * const message = await getRecentEmail({ maxWaitTime: 5000, waitInterval: 1000, logPolling: true });
26
+ * console.log(message.subject); // Outputs: "Hello!"
27
+ */
28
+ const getRecentEmail = async (options) => {
29
+ const token = (0, authService_1.getToken)();
30
+ const { maxWaitTime = 30000, waitInterval = 2000, logPolling = false, deleteAfterRead = false, } = options || {};
31
+ if (!token)
32
+ throw new Error('Authentication required. Call createInbox() first.');
33
+ if (!options) {
34
+ const messages = await (0, api_1.fetchMessages)();
35
+ if (messages.length === 0)
36
+ throw new Error('No messages available');
37
+ const messageId = messages[0].id;
38
+ const { from, to, subject, intro, text, html } = await (0, api_1.fetchMessageContent)(messageId);
39
+ if (deleteAfterRead) {
40
+ await (0, exports.deleteMessage)(messageId);
41
+ }
42
+ return {
43
+ from: from.address,
44
+ to: to[0].address,
45
+ subject,
46
+ intro,
47
+ text,
48
+ html,
49
+ };
50
+ }
51
+ const startTime = Date.now();
52
+ if (logPolling) {
53
+ console.log(`Polling started with a timeout of ${maxWaitTime / 1000}sec and interval of ${waitInterval / 1000}sec.`);
54
+ }
55
+ while (Date.now() - startTime < maxWaitTime) {
56
+ const messages = await (0, api_1.fetchMessages)();
57
+ if (messages.length > 0) {
58
+ if (logPolling) {
59
+ console.log(`Found ${messages.length} message(s), fetching details...`);
60
+ }
61
+ const messageId = messages[0].id;
62
+ if (logPolling) {
63
+ console.log(`Message retrieved`);
64
+ }
65
+ const { from, to, subject, intro, text, html } = await (0, api_1.fetchMessageContent)(messageId);
66
+ if (deleteAfterRead) {
67
+ await (0, exports.deleteMessage)(messageId);
68
+ }
69
+ return {
70
+ from: from.address,
71
+ to: to[0].address,
72
+ subject,
73
+ intro,
74
+ text,
75
+ html,
76
+ };
77
+ }
78
+ await new Promise((resolve) => setTimeout(resolve, waitInterval));
79
+ if (logPolling) {
80
+ console.log(`No messages found, waiting for ${waitInterval / 1000} seconds...`);
81
+ }
82
+ }
83
+ if (logPolling) {
84
+ console.log(`Waiting timeout of ${maxWaitTime / 1000} seconds reached. No messages found.`);
85
+ }
86
+ throw new Error(`No messages available within ${maxWaitTime / 1000} seconds timeout`);
87
+ };
88
+ exports.getRecentEmail = getRecentEmail;
89
+ /**
90
+ * Deletes a message by its unique ID from the Mail.tm inbox.
91
+ *
92
+ * This function requires a valid authentication token. If the
93
+ * token is not set, an error is thrown. The message is deleted
94
+ * using the Mail.tm API, and a success or failure message is logged.
95
+ *
96
+ * @param {string} messageId - The unique ID of the message to delete.
97
+ * @returns {Promise<void>} Resolves after the message is deleted.
98
+ *
99
+ * @throws {Error} If authentication is missing or the deletion fails.
100
+ *
101
+ * @example
102
+ * await deleteMessage("12345");
103
+ * console.log("Message deleted successfully.");
104
+ */
105
+ const deleteMessage = async (messageId) => {
106
+ const token = (0, authService_1.getToken)();
107
+ if (!token)
108
+ throw new Error('Authentication required. Call createInbox() first.');
109
+ try {
110
+ await axios_1.default.delete(`${constant_1.BASE_URL}/messages/${messageId}`, {
111
+ headers: {
112
+ accept: '*/*',
113
+ Authorization: `Bearer ${token}`,
114
+ },
115
+ });
116
+ }
117
+ catch (error) {
118
+ console.error(`Failed to delete message with ID ${messageId}: ${error}`);
119
+ }
120
+ };
121
+ exports.deleteMessage = deleteMessage;
122
+ //# sourceMappingURL=messageService.js.map