@postalsys/ee-client 1.3.2 → 1.4.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 (4) hide show
  1. package/README.md +162 -113
  2. package/index.d.ts +45 -6
  3. package/index.js +176 -126
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -1,6 +1,20 @@
1
1
  # @postalsys/ee-client
2
2
 
3
- EmailEngine client library for browser and Node.js applications.
3
+ Client library for [EmailEngine](https://emailengine.app/) that works in both the browser and Node.js.
4
+
5
+ It wraps the EmailEngine REST API (`/v1/account/...`) so you can list folders, read and search messages, change flags, move and delete messages, download attachments, and send mail. When you also give it a DOM element, it renders a complete, self-contained webmail interface (folder tree, paginated message list, message viewer, compose modal, dark mode) into that element.
6
+
7
+ This is the same client that powers the built-in message browser in the EmailEngine admin UI.
8
+
9
+ ## About EmailEngine
10
+
11
+ [EmailEngine](https://emailengine.app/) is a headless email client application that exposes IMAP, SMTP, Gmail API, and Microsoft Graph API accounts through a single unified REST API and webhooks. This library talks to that REST API - you need a running EmailEngine instance to use it.
12
+
13
+ - Website: https://emailengine.app/
14
+ - API reference: https://api.emailengine.app/
15
+ - Documentation: https://docs.emailengine.app/
16
+
17
+ Note that EmailEngine (the server) is commercial software and requires a subscription; this client library is MIT-licensed.
4
18
 
5
19
  ## Installation
6
20
 
@@ -8,193 +22,228 @@ EmailEngine client library for browser and Node.js applications.
8
22
  npm install @postalsys/ee-client
9
23
  ```
10
24
 
11
- For Node.js environments, you may also need to install `node-fetch`:
25
+ This package is **ES modules only** (`"type": "module"`). Import it with `import`; `require()` will not work.
12
26
 
13
- ```bash
14
- npm install node-fetch
15
- ```
27
+ It has **no runtime dependencies** and uses the platform `fetch`:
16
28
 
17
- ## Usage
29
+ - In the browser and on Node.js 18+, the global `fetch` is used automatically.
30
+ - On older Node.js (14-17), install [`node-fetch`](https://www.npmjs.com/package/node-fetch) as a fallback:
18
31
 
19
- ### Browser
32
+ ```bash
33
+ npm install node-fetch
34
+ ```
20
35
 
21
- ```javascript
22
- import { EmailEngineClient } from '@postalsys/ee-client';
36
+ ## Quick start
23
37
 
24
- // Create client with UI container
25
- const client = new EmailEngineClient({
26
- apiUrl: 'https://your-emailengine-server.com',
27
- account: 'your-account-id',
28
- accessToken: 'your-access-token',
29
- container: document.getElementById('email-client')
30
- });
38
+ ### Browser (embedded webmail UI)
39
+
40
+ Pass a `container` element and the client renders a full webmail UI into it and loads the inbox automatically:
41
+
42
+ ```html
43
+ <div id="email-client" style="height: 600px;"></div>
44
+ <script type="module">
45
+ import { EmailEngineClient } from '@postalsys/ee-client';
46
+
47
+ const client = new EmailEngineClient({
48
+ apiUrl: 'https://your-emailengine-server.example.com',
49
+ account: 'your-account-id',
50
+ accessToken: 'your-access-token',
51
+ container: document.getElementById('email-client')
52
+ });
53
+ </script>
31
54
  ```
32
55
 
33
- ### Node.js
56
+ Because the browser talks to EmailEngine directly, use a short-lived, account-scoped token here (see [Authentication](#authentication)) - never a root or admin token.
57
+
58
+ ### Node.js (API client, no UI)
59
+
60
+ Omit `container` to use the client purely as an API wrapper:
34
61
 
35
62
  ```javascript
36
63
  import { EmailEngineClient } from '@postalsys/ee-client';
37
64
 
38
- // Create client for API-only usage
39
65
  const client = new EmailEngineClient({
40
- apiUrl: 'https://your-emailengine-server.com',
66
+ apiUrl: 'https://your-emailengine-server.example.com',
41
67
  account: 'your-account-id',
42
68
  accessToken: 'your-access-token'
43
69
  });
44
70
 
45
- // Load folders
71
+ // List folders
46
72
  const folders = await client.loadFolders();
47
73
 
48
74
  // Load messages from INBOX
49
- const { messages } = await client.loadMessages('INBOX');
75
+ const { messages, nextPageCursor } = await client.loadMessages('INBOX');
50
76
 
51
- // Load a specific message
77
+ // Load a single message (its HTML is returned pre-processed for safe display)
52
78
  const message = await client.loadMessage(messages[0].id);
79
+
80
+ // Send a plain-text message
81
+ await client.sendMessage('user@example.com', 'Hello', 'Sent from ee-client');
82
+
83
+ // Release the keep-alive timer when done (see destroy() below)
84
+ client.destroy();
85
+ ```
86
+
87
+ ## Authentication
88
+
89
+ Every request is sent to EmailEngine with an `Authorization: Bearer <accessToken>` header. Tokens are scoped to a single account, so create one token per account you expose. There are two kinds of tokens you can pass as `accessToken`:
90
+
91
+ ### Access tokens
92
+
93
+ Provision a long-lived, account-scoped access token with the `api` scope through the EmailEngine admin UI, or via the API:
94
+
95
+ ```bash
96
+ curl -XPOST "https://your-emailengine-server.example.com/v1/token" \
97
+ -H "Authorization: Bearer <root-token>" \
98
+ -H "Content-Type: application/json" \
99
+ -d '{
100
+ "account": "your-account-id",
101
+ "description": "Webmail client",
102
+ "scopes": ["api"]
103
+ }'
53
104
  ```
54
105
 
55
- ## API
106
+ The response contains a `token` string to use as `accessToken`. Keep root tokens on your server; only hand an account-scoped `api` token to the browser.
107
+
108
+ ### Session tokens (`sess_...`)
109
+
110
+ EmailEngine can also mint short-lived, session-bound tokens whose value starts with `sess_` (this is how its own built-in message browser is embedded). These expire quickly on inactivity. When the client detects a `sess_` token, it automatically pings `GET /v1/account/{account}` after about five minutes of inactivity to keep the token alive. Call [`destroy()`](#destroy-void) to stop that timer when you tear the client down.
111
+
112
+ ## Constructor options
113
+
114
+ ```javascript
115
+ new EmailEngineClient(options);
116
+ ```
56
117
 
57
- ### Constructor Options
118
+ | Option | Type | Default | Description |
119
+ | --------------- | ------------- | ----------------------- | ------------------------------------------------------------------------------------------------------- |
120
+ | `account` | `string` | (required) | EmailEngine account identifier. |
121
+ | `apiUrl` | `string` | `http://127.0.0.1:3000` | Base URL of your EmailEngine instance. |
122
+ | `accessToken` | `string` | - | Bearer token for API authentication. |
123
+ | `container` | `HTMLElement` | - | DOM element to render the webmail UI into. Omit for API-only use. |
124
+ | `pageSize` | `number` | `20` | Messages per page. A saved value in `localStorage` takes precedence. |
125
+ | `confirmMethod` | `function` | browser `confirm()` | Custom confirm dialog, `(message, title, cancelText, okText)`. May be sync or async; returns a boolean. |
126
+ | `alertMethod` | `function` | browser `alert()` | Custom alert dialog, `(message, title, cancelText, okText)` where `cancelText` is `null`. |
58
127
 
59
- - `apiUrl` (string, optional): EmailEngine API URL. Defaults to `http://127.0.0.1:3000`
60
- - `account` (string, required): Account identifier
61
- - `accessToken` (string, optional): Access token for authentication
62
- - `container` (HTMLElement, optional): DOM container for UI components (browser only)
63
- - `confirmMethod` (function, optional): Custom confirm dialog method. Receives `(message, title, cancelText, okText)` parameters. Can be sync or async. Defaults to browser's `confirm()` with standard parameters.
64
- - `alertMethod` (function, optional): Custom alert dialog method. Receives `(message, title, cancelText, okText)` parameters where `cancelText` is `null` for alerts. Can be sync or async. Defaults to browser's `alert()` with standard parameters.
128
+ UI rendering, the compose modal, and dark mode only activate when a `container` is supplied. In a non-browser environment the UI is skipped and the instance behaves as a plain API client.
65
129
 
66
- **Note**: For session tokens (starting with `sess_`), the client automatically implements a keep-alive mechanism that pings the `/v1/account/{account}` endpoint every 5 minutes of inactivity to prevent token expiration.
130
+ ### Factory helper
131
+
132
+ `createEmailEngineClient()` is a convenience wrapper that resolves a `containerId` to its DOM element and validates that `account` is present:
133
+
134
+ ```javascript
135
+ import { createEmailEngineClient } from '@postalsys/ee-client';
136
+
137
+ // From an options object with a containerId
138
+ const client = createEmailEngineClient({
139
+ apiUrl: 'https://your-emailengine-server.example.com',
140
+ account: 'your-account-id',
141
+ accessToken: 'your-access-token',
142
+ containerId: 'email-client'
143
+ });
144
+ ```
67
145
 
68
- ### Methods
146
+ ## Methods
69
147
 
70
- #### `loadFolders(): Promise<Folder[]>`
148
+ ### `loadFolders(): Promise<Folder[]>`
71
149
 
72
- Load all folders/mailboxes for the account.
150
+ Load all folders/mailboxes for the account. Renders the folder tree when a container is set.
73
151
 
74
- #### `loadMessages(path: string, cursor?: string): Promise<MessageListResponse>`
152
+ ### `loadMessages(path: string, cursor?: string): Promise<MessageListResponse>`
75
153
 
76
- Load messages from a specific folder.
154
+ Load a page of messages from a folder. Pass `nextPageCursor` / `prevPageCursor` from a previous response to paginate. Resolves to `{ messages, nextPageCursor, prevPageCursor }`.
77
155
 
78
- #### `loadMessage(messageId: string): Promise<Message>`
156
+ ### `loadMessage(messageId: string): Promise<Message>`
79
157
 
80
- Load a specific message by ID.
158
+ Load a single message. HTML is requested with `webSafeHtml=true`, so EmailEngine returns it pre-processed with inline images embedded for safe display, and the message is marked as seen.
81
159
 
82
- #### `markAsRead(messageId: string, seen?: boolean): Promise<boolean>`
160
+ ### `markAsRead(messageId: string, seen?: boolean): Promise<boolean>`
83
161
 
84
- Mark a message as read or unread.
162
+ Add or remove the `\Seen` flag. Pass `false` to mark as unread.
85
163
 
86
- #### `deleteMessage(messageId: string): Promise<boolean>`
164
+ ### `deleteMessage(messageId: string): Promise<boolean>`
87
165
 
88
- Delete a message.
166
+ Delete a message (EmailEngine moves it to Trash, or removes it if already in Trash).
89
167
 
90
- #### `moveMessage(messageId: string, targetPath: string): Promise<boolean>`
168
+ ### `moveMessage(messageId: string, targetPath: string): Promise<boolean>`
91
169
 
92
170
  Move a message to another folder.
93
171
 
94
- #### `sendMessage(to: string | object | array, subject: string, text: string): Promise<object>`
172
+ ### `sendMessage(to, subject, text): Promise<object>`
95
173
 
96
- Send a new email message. The `to` parameter can be:
174
+ Send a plain-text email. `to` may be:
97
175
 
98
- - A string email address: `'user@example.com'`
99
- - An object with name and address: `{ name: 'John Doe', address: 'john@example.com' }`
100
- - An array of strings or objects for multiple recipients
176
+ - a string address: `'user@example.com'`
177
+ - an object: `{ name: 'John Doe', address: 'john@example.com' }`
178
+ - an array of strings and/or objects for multiple recipients
101
179
 
102
- #### `destroy(): void`
180
+ Resolves to EmailEngine's submit response.
103
181
 
104
- Clean up the client instance, clearing any active timers (like the keep-alive timer for session tokens).
182
+ ### `downloadAttachment(attachmentId: string, suggestedFilename?: string): Promise<void>`
105
183
 
106
- ## Browser UI
184
+ Browser only. Fetch an attachment and trigger a download, using the filename from the `Content-Disposition` header when available.
107
185
 
108
- When used in a browser with a container element, the client automatically creates a full email interface with:
186
+ ### `downloadOriginalMessage(messageId: string, subject?: string): Promise<void>`
109
187
 
110
- - Folder tree navigation
111
- - Message list with pagination
112
- - Message viewer with actions (mark as read/unread, delete, move)
113
- - Responsive design
114
- - Dark mode support with persistent preference
188
+ Browser only. Download the raw message source as an `.eml` file.
115
189
 
116
- ```html
117
- <div id="email-client" style="height: 600px;"></div>
118
- <script type="module">
119
- import { EmailEngineClient } from '@postalsys/ee-client';
190
+ ### `destroy(): void`
120
191
 
121
- new EmailEngineClient({
122
- apiUrl: 'https://your-emailengine-server.com',
123
- account: 'your-account-id',
124
- accessToken: 'your-access-token',
125
- container: document.getElementById('email-client'),
126
- // Optional: Custom confirm dialog
127
- confirmMethod: async message => {
128
- return await myCustomDialog.confirm(message);
129
- }
130
- });
131
- </script>
132
- ```
192
+ Clean up the instance and clear the `sess_` token keep-alive interval. Always call this when you are finished with a client (for example when unmounting the UI) to avoid a leaked timer.
193
+
194
+ ## Browser UI
133
195
 
134
- ### Custom Dialog Methods
196
+ When a `container` is provided the client builds a full webmail interface:
135
197
 
136
- You can provide custom alert and confirm dialog methods that will be used instead of the browser's default dialogs. This is useful for integrating with UI frameworks or custom dialog systems:
198
+ - Folder tree with special-folder ordering (Inbox, Drafts, Sent, Trash, Junk, Archive) and nested folders
199
+ - Paginated message list with a selectable page size (persisted to `localStorage`)
200
+ - Message viewer with mark read/unread, delete, move-to-folder, download original, and attachment downloads
201
+ - Compose modal (floating button) for sending plain-text mail
202
+ - Dark mode toggle with the preference persisted to `localStorage`
203
+
204
+ ### Custom dialogs
205
+
206
+ Provide `confirmMethod` and `alertMethod` to route confirmations and alerts through your own modal system instead of the browser defaults - useful when integrating with a UI framework:
137
207
 
138
208
  ```javascript
139
209
  const client = new EmailEngineClient({
140
- apiUrl: 'https://your-emailengine-server.com',
210
+ apiUrl: 'https://your-emailengine-server.example.com',
141
211
  account: 'your-account-id',
142
212
  accessToken: 'your-access-token',
143
213
  container: document.getElementById('email-client'),
144
214
 
145
- // Custom alert method
146
215
  alertMethod: async (message, title, cancelText, okText) => {
147
- return await MyModal.alert({
148
- title: title, // e.g., "Success", "Error", "Notice"
149
- message: message,
150
- okButton: okText // e.g., "OK"
151
- // cancelText is null for alerts
152
- });
216
+ return await MyModal.alert({ title, message, okButton: okText });
153
217
  },
154
218
 
155
- // Custom confirm method
156
219
  confirmMethod: async (message, title, cancelText, okText) => {
157
- return await MyModal.confirm({
158
- title: title, // e.g., "Delete Message", "Confirm"
159
- message: message,
160
- cancelButton: cancelText, // e.g., "Cancel"
161
- okButton: okText // e.g., "Delete", "OK"
162
- });
220
+ return await MyModal.confirm({ title, message, cancelButton: cancelText, okButton: okText });
163
221
  }
164
222
  });
165
223
  ```
166
224
 
167
- #### Dialog Method Signatures
168
-
169
- Both methods receive the same parameters:
170
-
171
- - `message` (string): The message to display
172
- - `title` (string): Dialog title (defaults: "Confirm" for confirm, "Notice" for alert)
173
- - `cancelText` (string|null): Cancel button text ("Cancel" for confirm, `null` for alert)
174
- - `okText` (string): OK/action button text (defaults: "OK")
225
+ Both methods receive the same arguments:
175
226
 
176
- #### Built-in Dialog Types
227
+ - `message` (string): text to display
228
+ - `title` (string): dialog title (defaults: `Confirm` / `Notice`)
229
+ - `cancelText` (string | null): cancel button text (`Cancel` for confirm, `null` for alert)
230
+ - `okText` (string): confirm/OK button text (default `OK`)
177
231
 
178
- The library uses contextually appropriate titles and button texts:
232
+ The client uses contextual titles such as `Delete Message`, `Validation Error`, `Success`, `Send Error`, and `Download Error`. `confirmMethod` should return a boolean (or a promise for one); `alertMethod` may be sync or async.
179
233
 
180
- - **Validation errors**: `alertMethod(message, "Validation Error", null, "OK")`
181
- - **Success messages**: `alertMethod(message, "Success", null, "OK")`
182
- - **Send errors**: `alertMethod(message, "Send Error", null, "OK")`
183
- - **Download errors**: `alertMethod(message, "Download Error", null, "OK")`
184
- - **Delete confirmation**: `confirmMethod(message, "Delete Message", "Cancel", "Delete")`
234
+ ## Security
185
235
 
186
- Both methods can be synchronous or asynchronous and should return a boolean for confirm dialogs.
236
+ This library renders attacker-controlled email content, so it is careful about HTML injection:
187
237
 
188
- ### Dark Mode
238
+ - All untrusted values (subjects, addresses, names, filenames, folder names) are HTML-escaped before being written to the DOM.
239
+ - The one intentional raw-HTML sink is the message body itself. The client fetches it with EmailEngine's `webSafeHtml` option so the HTML arrives already pre-processed for safe embedding.
189
240
 
190
- The email client includes built-in dark mode support with automatic persistence of user preference:
241
+ Do not disable escaping or add new raw-HTML sinks when extending the UI.
191
242
 
192
- - **Toggle Button**: A moon/sun icon in the top-right corner toggles between light and dark modes
193
- - **Persistent Preference**: Dark mode preference is saved to localStorage and restored on page reload
194
- - **Complete Theme**: All UI components are styled for optimal readability in both light and dark modes
243
+ ## TypeScript
195
244
 
196
- Dark mode is automatically initialized based on the saved preference when the client is created.
245
+ Type declarations ship with the package (`index.d.ts`), so `EmailEngineClient`, `createEmailEngineClient`, and the exported interfaces (`Folder`, `Message`, `MessageListResponse`, `EmailEngineClientOptions`, and others) are typed out of the box - no `@types` package needed.
197
246
 
198
247
  ## License
199
248
 
200
- MIT © Postal Systems OÜ
249
+ MIT (c) Postal Systems OÜ
package/index.d.ts CHANGED
@@ -26,6 +26,18 @@ export interface Folder {
26
26
  status?: MessageStatus;
27
27
  }
28
28
 
29
+ export interface FolderTreeEntry {
30
+ folder: Folder;
31
+ depth: number;
32
+ }
33
+
34
+ export interface Attachment {
35
+ id: string;
36
+ filename?: string;
37
+ contentType?: string;
38
+ size?: number;
39
+ }
40
+
29
41
  export interface Message {
30
42
  id: string;
31
43
  subject?: string;
@@ -36,6 +48,7 @@ export interface Message {
36
48
  unseen: boolean;
37
49
  intro?: string;
38
50
  text?: MessageText;
51
+ attachments?: Attachment[];
39
52
  }
40
53
 
41
54
  export interface MessageListResponse {
@@ -44,20 +57,40 @@ export interface MessageListResponse {
44
57
  prevPageCursor?: string;
45
58
  }
46
59
 
60
+ export type SendRecipient = string | EmailAddress;
61
+
62
+ /**
63
+ * Custom dialog handler. Invoked by the client as
64
+ * `(message, title, cancelText, okText)`; `cancelText` is `null` for alerts.
65
+ * May be synchronous or asynchronous. Confirm handlers should resolve to a boolean.
66
+ */
67
+ export type DialogMethod = (
68
+ message: string,
69
+ title?: string,
70
+ cancelText?: string | null,
71
+ okText?: string
72
+ ) => boolean | void | Promise<boolean | void>;
73
+
47
74
  export interface EmailEngineClientOptions {
48
75
  apiUrl?: string;
49
76
  account: string;
50
77
  accessToken?: string;
51
78
  container?: HTMLElement;
52
79
  containerId?: string;
53
- confirmMethod?: (message: string) => boolean | Promise<boolean>;
80
+ pageSize?: number;
81
+ confirmMethod?: DialogMethod;
82
+ alertMethod?: DialogMethod;
54
83
  }
55
84
 
56
85
  export declare class EmailEngineClient {
57
86
  apiUrl: string;
58
87
  account: string;
59
88
  accessToken?: string;
60
- container?: HTMLElement;
89
+ container?: HTMLElement | null;
90
+ confirmMethod: DialogMethod;
91
+ alertMethod: DialogMethod;
92
+ pageSize: number;
93
+ darkMode: boolean;
61
94
  currentFolder: string | null;
62
95
  currentMessage: Message | null;
63
96
  folders: Folder[];
@@ -74,17 +107,23 @@ export declare class EmailEngineClient {
74
107
  markAsRead(messageId: string, seen?: boolean): Promise<boolean>;
75
108
  deleteMessage(messageId: string): Promise<boolean>;
76
109
  moveMessage(messageId: string, targetPath: string): Promise<boolean>;
110
+ sendMessage(to: SendRecipient | SendRecipient[], subject: string, text: string): Promise<any>;
111
+ downloadAttachment(attachmentId: string, suggestedFilename?: string): Promise<void>;
112
+ downloadOriginalMessage(messageId: string, subject?: string): Promise<void>;
77
113
  formatDate(dateStr: string): string;
114
+ formatFileSize(bytes: number): string;
115
+ escapeHtml(value: unknown): string;
78
116
  createStyles(): void;
79
- calculateFolderDepth(folder: Folder): number;
80
- buildFolderTree(): Folder[];
117
+ buildFolderTree(): FolderTreeEntry[];
81
118
  renderFolderList(): void;
82
119
  renderMessageList(): void;
83
120
  renderMessage(): void;
84
121
  createLayout(): void;
85
122
  init(): void;
123
+ toggleDarkMode(): void;
124
+ destroy(): void;
86
125
  }
87
126
 
88
- export declare function createEmailEngineClient(options: EmailEngineClientOptions | string | HTMLElement): EmailEngineClient;
127
+ export declare function createEmailEngineClient(options: EmailEngineClientOptions): EmailEngineClient;
89
128
 
90
- export default EmailEngineClient;
129
+ export default EmailEngineClient;
package/index.js CHANGED
@@ -3,7 +3,20 @@ export class EmailEngineClient {
3
3
  this.apiUrl = options.apiUrl || 'http://127.0.0.1:3000';
4
4
  this.account = options.account;
5
5
  this.accessToken = options.accessToken;
6
- this.container = options.container;
6
+ this.container = options.container || null;
7
+ // Resolve containerId when no element was passed directly, so
8
+ // `new EmailEngineClient({ containerId })` renders UI too (not only the
9
+ // factory). In a non-DOM env this stays null - an API-only client.
10
+ if (!this.container && options.containerId && typeof document !== 'undefined') {
11
+ this.container = document.getElementById(options.containerId);
12
+ // A containerId that matches nothing is almost always a typo; warn
13
+ // rather than silently degrading to a UI-less, API-only client.
14
+ if (!this.container) {
15
+ console.warn(
16
+ `EmailEngineClient: no element found for containerId "${options.containerId}"; UI rendering disabled`
17
+ );
18
+ }
19
+ }
7
20
  this.confirmMethod =
8
21
  options.confirmMethod ||
9
22
  ((message, _title = 'Confirm', _cancelText = 'Cancel', _okText = 'OK') => confirm(message));
@@ -17,6 +30,11 @@ export class EmailEngineClient {
17
30
  this.nextPageCursor = null;
18
31
  this.prevPageCursor = null;
19
32
 
33
+ // Set once destroy() runs; guards async completions (loadFolders,
34
+ // loadMessages, loadMessage) from re-rendering or scrolling into a
35
+ // torn-down - or recreated - container.
36
+ this._destroyed = false;
37
+
20
38
  // Keep-alive timer for sess_ tokens
21
39
  this.keepAliveTimer = null;
22
40
  this.lastActivity = Date.now();
@@ -30,7 +48,8 @@ export class EmailEngineClient {
30
48
  // Get page size from localStorage or options or default
31
49
  const savedPageSize =
32
50
  typeof window !== 'undefined' && window.localStorage ? localStorage.getItem('ee-client-page-size') : null;
33
- this.pageSize = savedPageSize ? parseInt(savedPageSize) : options.pageSize || 20;
51
+ const requestedPageSize = savedPageSize ? parseInt(savedPageSize, 10) : parseInt(options.pageSize, 10);
52
+ this.pageSize = requestedPageSize > 0 ? requestedPageSize : 20;
34
53
 
35
54
  if (this.container) {
36
55
  this.init();
@@ -48,32 +67,32 @@ export class EmailEngineClient {
48
67
  const options = {
49
68
  method: method,
50
69
  headers: {
51
- 'Content-Type': 'application/json'
70
+ 'Content-Type': 'application/json',
71
+ ...this._authHeaders()
52
72
  }
53
73
  };
54
74
 
55
- if (this.accessToken) {
56
- options.headers['Authorization'] = `Bearer ${this.accessToken}`;
57
- }
58
-
59
75
  if (data) {
60
76
  options.body = JSON.stringify(data);
61
77
  }
62
78
 
63
79
  let fetchFn = globalThis.fetch;
64
- if (!fetchFn && typeof require !== 'undefined') {
80
+ if (!fetchFn) {
81
+ // Native fetch is missing (older Node.js). Fall back to node-fetch.
82
+ // This is a dynamic import so browsers and modern Node never load it.
65
83
  try {
66
84
  const nodeFetch = await import('node-fetch');
67
85
  fetchFn = nodeFetch.default;
68
86
  } catch (err) {
69
- throw new Error(
70
- 'fetch is not available. In Node.js environments, please install node-fetch: npm install node-fetch'
71
- );
87
+ // node-fetch is not installed; the guard below reports it
72
88
  }
73
89
  }
74
90
 
75
91
  if (!fetchFn) {
76
- throw new Error('fetch is not available');
92
+ // Either node-fetch is missing or it exposed no callable default export
93
+ throw new Error(
94
+ 'fetch is not available. In Node.js environments, please install node-fetch: npm install node-fetch'
95
+ );
77
96
  }
78
97
 
79
98
  const response = await fetchFn(url, options);
@@ -99,6 +118,7 @@ export class EmailEngineClient {
99
118
  try {
100
119
  const data = await this.apiRequest('GET', `/v1/account/${this.account}/mailboxes`);
101
120
  this.folders = data.mailboxes || [];
121
+ this._folderTreeCache = null;
102
122
  if (this.container) {
103
123
  this.renderFolderList();
104
124
  }
@@ -181,7 +201,7 @@ export class EmailEngineClient {
181
201
  }
182
202
  }
183
203
 
184
- if (this.container) {
204
+ if (this.container && !this._destroyed) {
185
205
  this.renderMessage();
186
206
 
187
207
  // Scroll to top of the email client container
@@ -321,23 +341,18 @@ export class EmailEngineClient {
321
341
  _formatSendError(error) {
322
342
  // If we have detailed error information from the API
323
343
  if (error.details && error.details.fields && Array.isArray(error.details.fields)) {
324
- const fieldErrors = error.details.fields.map(field => {
325
- // Try to make field errors more user-friendly
326
- let message = field.message;
327
-
328
- // Map technical field names to user-friendly names
329
- if (message.includes('to[0].address') || message.includes('"address"')) {
330
- message = message.replace(/to\[\d+\]\.address|"address"/g, 'email address');
331
- }
332
- if (message.includes('"subject"')) {
333
- message = message.replace('"subject"', 'subject');
334
- }
335
- if (message.includes('"text"')) {
336
- message = message.replace('"text"', 'message');
337
- }
338
-
339
- return message;
340
- });
344
+ const fieldErrors = error.details.fields
345
+ // Keep only entries that carry a usable message string.
346
+ .filter(field => field && typeof field.message === 'string')
347
+ // Map technical field names to user-friendly ones. Each replace
348
+ // is a no-op when its pattern is absent, so no includes-guards
349
+ // are needed - and to[N] for any index is handled, not just to[0].
350
+ .map(field =>
351
+ field.message
352
+ .replace(/to\[\d+\]\.address|"address"/g, 'email address')
353
+ .replace(/"subject"/g, 'subject')
354
+ .replace(/"text"/g, 'message')
355
+ );
341
356
 
342
357
  const mainMessage = error.details.message || 'Failed to send email';
343
358
  if (fieldErrors.length > 0) {
@@ -381,21 +396,43 @@ export class EmailEngineClient {
381
396
  return String(value).replace(/[&<>"']/g, ch => htmlEscapes[ch]);
382
397
  }
383
398
 
384
- async downloadAttachment(attachmentId, suggestedFilename = null) {
385
- try {
386
- const headers = {};
387
- if (this.accessToken) {
388
- headers['Authorization'] = `Bearer ${this.accessToken}`;
389
- }
399
+ _authHeaders() {
400
+ const headers = {};
401
+ if (this.accessToken) {
402
+ headers['Authorization'] = `Bearer ${this.accessToken}`;
403
+ }
404
+ return headers;
405
+ }
390
406
 
391
- const response = await fetch(`${this.apiUrl}/v1/account/${this.account}/attachment/${attachmentId}`, {
392
- headers,
393
- credentials: 'include'
394
- });
407
+ _saveBlob(blob, filename) {
408
+ const url = window.URL.createObjectURL(blob);
409
+ const a = document.createElement('a');
410
+ a.href = url;
411
+ a.download = filename;
412
+ document.body.appendChild(a);
413
+ a.click();
414
+ document.body.removeChild(a);
415
+ window.URL.revokeObjectURL(url);
416
+ }
395
417
 
396
- if (!response.ok) {
397
- throw new Error(`HTTP error! status: ${response.status}`);
398
- }
418
+ // Authenticated GET for binary payloads (attachments, message source).
419
+ // apiRequest is not reused here - it always parses the body as JSON.
420
+ async _fetchBlob(endpoint) {
421
+ const response = await fetch(`${this.apiUrl}${endpoint}`, {
422
+ headers: this._authHeaders(),
423
+ credentials: 'include'
424
+ });
425
+
426
+ if (!response.ok) {
427
+ throw new Error(`HTTP error! status: ${response.status}`);
428
+ }
429
+
430
+ return response;
431
+ }
432
+
433
+ async downloadAttachment(attachmentId, suggestedFilename = null) {
434
+ try {
435
+ const response = await this._fetchBlob(`/v1/account/${this.account}/attachment/${attachmentId}`);
399
436
 
400
437
  // Get filename from Content-Disposition header if available
401
438
  const contentDisposition = response.headers.get('content-disposition');
@@ -407,18 +444,9 @@ export class EmailEngineClient {
407
444
  }
408
445
  }
409
446
 
410
- // Get the attachment data
447
+ // Get the attachment data and trigger the download
411
448
  const blob = await response.blob();
412
-
413
- // Create a download link
414
- const url = window.URL.createObjectURL(blob);
415
- const a = document.createElement('a');
416
- a.href = url;
417
- a.download = filename;
418
- document.body.appendChild(a);
419
- a.click();
420
- document.body.removeChild(a);
421
- window.URL.revokeObjectURL(url);
449
+ this._saveBlob(blob, filename);
422
450
  } catch (error) {
423
451
  console.error('Failed to download attachment:', error);
424
452
  this.alertMethod('Failed to download attachment. Please try again.', 'Download Error', null, 'OK');
@@ -427,19 +455,7 @@ export class EmailEngineClient {
427
455
 
428
456
  async downloadOriginalMessage(messageId, subject = null) {
429
457
  try {
430
- const headers = {};
431
- if (this.accessToken) {
432
- headers['Authorization'] = `Bearer ${this.accessToken}`;
433
- }
434
-
435
- const response = await fetch(`${this.apiUrl}/v1/account/${this.account}/message/${messageId}/source`, {
436
- headers,
437
- credentials: 'include'
438
- });
439
-
440
- if (!response.ok) {
441
- throw new Error(`HTTP error! status: ${response.status}`);
442
- }
458
+ const response = await this._fetchBlob(`/v1/account/${this.account}/message/${messageId}/source`);
443
459
 
444
460
  // Get the email data
445
461
  const blob = await response.blob();
@@ -450,15 +466,7 @@ export class EmailEngineClient {
450
466
  const safeSubject = subject ? subject.replace(/[^a-z0-9]/gi, '_').substring(0, 50) : 'email';
451
467
  const filename = `${dateStr}_${safeSubject}.eml`;
452
468
 
453
- // Create a download link
454
- const url = window.URL.createObjectURL(blob);
455
- const a = document.createElement('a');
456
- a.href = url;
457
- a.download = filename;
458
- document.body.appendChild(a);
459
- a.click();
460
- document.body.removeChild(a);
461
- window.URL.revokeObjectURL(url);
469
+ this._saveBlob(blob, filename);
462
470
  } catch (error) {
463
471
  console.error('Failed to download original message:', error);
464
472
  this.alertMethod('Failed to download original message. Please try again.', 'Download Error', null, 'OK');
@@ -1273,18 +1281,14 @@ export class EmailEngineClient {
1273
1281
  }
1274
1282
  `;
1275
1283
  document.head.appendChild(style);
1284
+ this._styleElement = style;
1276
1285
  }
1277
1286
 
1278
- calculateFolderDepth(folder) {
1279
- if (!folder.parentPath || !folder.delimiter) {
1280
- return 0;
1287
+ buildFolderTree() {
1288
+ if (this._folderTreeCache) {
1289
+ return this._folderTreeCache;
1281
1290
  }
1282
1291
 
1283
- const pathParts = folder.path.split(folder.delimiter);
1284
- return Math.max(0, pathParts.length - 1);
1285
- }
1286
-
1287
- buildFolderTree() {
1288
1292
  const specialFolders = [];
1289
1293
  const regularFolders = [];
1290
1294
 
@@ -1319,34 +1323,52 @@ export class EmailEngineClient {
1319
1323
  return a.name.localeCompare(b.name);
1320
1324
  });
1321
1325
 
1322
- const buildHierarchy = (folders, parentPath = null, depth = 0) => {
1323
- const result = [];
1326
+ // Index children by parent in a single pass so the hierarchy walk is
1327
+ // O(n) instead of re-filtering the whole list at every level. A folder
1328
+ // whose parent is not among the regular folders (special-use parent,
1329
+ // missing parent, or no parent) is a root, keyed under null - those must
1330
+ // still surface at the top level rather than be dropped.
1331
+ const regularPaths = new Set(regularFolders.map(f => f.path));
1332
+ const childrenByParent = new Map();
1333
+ regularFolders.forEach(folder => {
1334
+ const key = regularPaths.has(folder.parentPath) ? folder.parentPath : null;
1335
+ const siblings = childrenByParent.get(key);
1336
+ if (siblings) {
1337
+ siblings.push(folder);
1338
+ } else {
1339
+ childrenByParent.set(key, [folder]);
1340
+ }
1341
+ });
1342
+ childrenByParent.forEach(siblings => siblings.sort((a, b) => a.name.localeCompare(b.name)));
1324
1343
 
1325
- const children = folders.filter(f => {
1326
- if (parentPath === null) {
1327
- return f.parentPath === 'INBOX' || !f.parentPath || f.parentPath === '';
1328
- } else {
1329
- return f.parentPath === parentPath;
1344
+ // Each entry carries its depth in the rendered tree (roots = 0). Depth
1345
+ // comes from tree position, not the path string, so a folder whose
1346
+ // parent is a special-use or missing folder renders flush at the top.
1347
+ const visited = new Set();
1348
+ const walk = (parentKey, depth) => {
1349
+ const result = [];
1350
+ const siblings = childrenByParent.get(parentKey) || [];
1351
+ siblings.forEach(folder => {
1352
+ // Guard against cyclic/self-referential parentPath values.
1353
+ if (visited.has(folder.path)) {
1354
+ return;
1330
1355
  }
1356
+ visited.add(folder.path);
1357
+ result.push({ folder, depth });
1358
+ result.push(...walk(folder.path, depth + 1));
1331
1359
  });
1332
-
1333
- children.sort((a, b) => a.name.localeCompare(b.name));
1334
-
1335
- children.forEach(folder => {
1336
- result.push(folder);
1337
- result.push(...buildHierarchy(folders, folder.path, depth + 1));
1338
- });
1339
-
1340
1360
  return result;
1341
1361
  };
1342
1362
 
1343
- const hierarchicalRegular = buildHierarchy(regularFolders);
1363
+ const hierarchicalRegular = walk(null, 0);
1344
1364
 
1345
- return [...specialFolders, ...hierarchicalRegular];
1365
+ const tree = [...specialFolders.map(folder => ({ folder, depth: 0 })), ...hierarchicalRegular];
1366
+ this._folderTreeCache = tree;
1367
+ return tree;
1346
1368
  }
1347
1369
 
1348
1370
  renderFolderList() {
1349
- if (typeof document === 'undefined' || !this.container) {
1371
+ if (typeof document === 'undefined' || !this.container || this._destroyed) {
1350
1372
  return;
1351
1373
  }
1352
1374
 
@@ -1356,13 +1378,15 @@ export class EmailEngineClient {
1356
1378
  }
1357
1379
 
1358
1380
  const sortedFolders = this.buildFolderTree();
1381
+ // Precompute which paths are some folder's parent so the per-row
1382
+ // has-children check is O(1) instead of scanning this.folders each time.
1383
+ const parentPaths = new Set(this.folders.map(f => f.parentPath));
1359
1384
 
1360
1385
  const html = `
1361
1386
  <ul class="ee-folder-list">
1362
1387
  ${sortedFolders
1363
- .map(folder => {
1364
- const depth = this.calculateFolderDepth(folder);
1365
- const hasChildren = this.folders.some(f => f.parentPath === folder.path);
1388
+ .map(({ folder, depth }) => {
1389
+ const hasChildren = parentPaths.has(folder.path);
1366
1390
  return `
1367
1391
  <li class="ee-folder-item ${folder.path === this.currentFolder ? 'active' : ''}"
1368
1392
  data-path="${this.escapeHtml(folder.path)}"
@@ -1389,7 +1413,7 @@ export class EmailEngineClient {
1389
1413
  }
1390
1414
 
1391
1415
  renderMessageList() {
1392
- if (typeof document === 'undefined' || !this.container) {
1416
+ if (typeof document === 'undefined' || !this.container || this._destroyed) {
1393
1417
  return;
1394
1418
  }
1395
1419
 
@@ -1489,7 +1513,7 @@ export class EmailEngineClient {
1489
1513
  }
1490
1514
 
1491
1515
  renderMessage() {
1492
- if (typeof document === 'undefined' || !this.container) {
1516
+ if (typeof document === 'undefined' || !this.container || this._destroyed) {
1493
1517
  return;
1494
1518
  }
1495
1519
 
@@ -1513,8 +1537,7 @@ export class EmailEngineClient {
1513
1537
  <select class="ee-button" data-action="move">
1514
1538
  <option value="">Move to...</option>
1515
1539
  ${this.buildFolderTree()
1516
- .map(folder => {
1517
- const depth = this.calculateFolderDepth(folder);
1540
+ .map(({ folder, depth }) => {
1518
1541
  const indent = ' '.repeat(depth);
1519
1542
  const prefix = depth > 0 ? '└ ' : '';
1520
1543
  return `<option value="${this.escapeHtml(folder.path)}" ${folder.path === this.currentFolder ? 'disabled' : ''}>${indent}${prefix}${this.escapeHtml(folder.name)}</option>`;
@@ -1721,11 +1744,12 @@ export class EmailEngineClient {
1721
1744
  });
1722
1745
 
1723
1746
  // Close on Escape key
1724
- document.addEventListener('keydown', e => {
1747
+ this._composeKeydownHandler = e => {
1725
1748
  if (e.key === 'Escape' && modal.classList.contains('show')) {
1726
1749
  closeModal();
1727
1750
  }
1728
- });
1751
+ };
1752
+ document.addEventListener('keydown', this._composeKeydownHandler);
1729
1753
 
1730
1754
  // Send email
1731
1755
  sendButton.addEventListener('click', async () => {
@@ -1928,6 +1952,11 @@ export class EmailEngineClient {
1928
1952
  localStorage.setItem('ee-client-dark-mode', this.darkMode.toString());
1929
1953
  }
1930
1954
 
1955
+ // DOM updates only apply to the rendered UI; skip without a container
1956
+ if (!this.container) {
1957
+ return;
1958
+ }
1959
+
1931
1960
  // Update UI
1932
1961
  const client = this.container.querySelector('.ee-client');
1933
1962
  if (client) {
@@ -1946,40 +1975,61 @@ export class EmailEngineClient {
1946
1975
  }
1947
1976
 
1948
1977
  destroy() {
1978
+ // Mark destroyed first so any in-flight async completion skips
1979
+ // re-rendering into a torn-down or recreated container.
1980
+ this._destroyed = true;
1981
+
1949
1982
  // Clean up keep-alive timer
1950
1983
  if (this.keepAliveTimer) {
1951
1984
  clearInterval(this.keepAliveTimer);
1952
1985
  this.keepAliveTimer = null;
1953
1986
  }
1987
+
1988
+ // Remove the compose button's window scroll/resize listeners
1989
+ if (this._composeButtonCleanup) {
1990
+ this._composeButtonCleanup();
1991
+ this._composeButtonCleanup = null;
1992
+ }
1993
+
1994
+ // Remove the document-level Escape keydown listener
1995
+ if (this._composeKeydownHandler && typeof document !== 'undefined') {
1996
+ document.removeEventListener('keydown', this._composeKeydownHandler);
1997
+ this._composeKeydownHandler = null;
1998
+ }
1999
+
2000
+ // Remove the injected stylesheet
2001
+ if (this._styleElement && this._styleElement.parentNode) {
2002
+ this._styleElement.parentNode.removeChild(this._styleElement);
2003
+ this._styleElement = null;
2004
+ }
1954
2005
  }
1955
2006
  }
1956
2007
 
1957
2008
  export function createEmailEngineClient(options) {
1958
- if (typeof options === 'string') {
1959
- options = {
1960
- container: typeof document !== 'undefined' ? document.getElementById(options) : null
1961
- };
1962
- } else if (typeof HTMLElement !== 'undefined' && options instanceof HTMLElement) {
1963
- options = {
1964
- container: options
1965
- };
1966
- } else if (typeof options === 'object' && options.containerId) {
1967
- options.container = typeof document !== 'undefined' ? document.getElementById(options.containerId) : null;
2009
+ if (!options || typeof options !== 'object') {
2010
+ throw new Error('Invalid options: expected an options object');
1968
2011
  }
1969
2012
 
1970
- if (options.container && !options.container) {
1971
- throw new Error('Container element not found');
2013
+ if (!options.account) {
2014
+ throw new Error('Account identifier is required');
1972
2015
  }
1973
2016
 
1974
2017
  if (!options.apiUrl) {
1975
2018
  console.warn('No API URL specified, using default http://127.0.0.1:3000');
1976
2019
  }
1977
2020
 
1978
- if (!options.account) {
1979
- throw new Error('Account identifier is required');
2021
+ const client = new EmailEngineClient(options);
2022
+
2023
+ // The constructor is the single place that resolves containerId to an
2024
+ // element. In a DOM environment a containerId that matches nothing is a
2025
+ // caller error, so fail loudly here - and tear down the half-built client
2026
+ // so its keep-alive timer does not leak.
2027
+ if (options.containerId && !client.container && typeof document !== 'undefined') {
2028
+ client.destroy();
2029
+ throw new Error('Container element not found');
1980
2030
  }
1981
2031
 
1982
- return new EmailEngineClient(options);
2032
+ return client;
1983
2033
  }
1984
2034
 
1985
2035
  export default EmailEngineClient;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postalsys/ee-client",
3
- "version": "1.3.2",
3
+ "version": "1.4.0",
4
4
  "description": "EmailEngine client library for browser and Node.js applications",
5
5
  "main": "index.js",
6
6
  "module": "index.js",