@postalsys/ee-client 1.6.0 → 1.7.1

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 +17 -1
  2. package/index.d.ts +23 -0
  3. package/index.js +478 -102
  4. package/package.json +2 -2
package/README.md CHANGED
@@ -181,6 +181,16 @@ Send a plain-text email. `to` may be:
181
181
 
182
182
  Resolves to EmailEngine's submit response.
183
183
 
184
+ ### `saveDraft(to?, subject?, text?): Promise<object>`
185
+
186
+ Store a plain-text message as a draft instead of sending it (`POST /v1/account/{account}/message`). The message is uploaded to the account's Drafts special-use folder with the `\Draft` flag set and the account's own name and address as the sender, so it can later be delivered with `submitDraft()`. `to` accepts the same values as `sendMessage()` and may be omitted for a draft without recipients. Resolves to EmailEngine's upload response (`{ id, path, uid, ... }`).
187
+
188
+ ### `submitDraft(messageId: string, options?: SubmitDraftOptions): Promise<object>`
189
+
190
+ Send an existing draft message as-is (`POST /v1/account/{account}/message/{message}/submit`). The message must be a draft: stored in the Drafts folder or flagged as a draft (IMAP), carrying the DRAFT label (Gmail), or a draft message (MS Graph). The provider removes the draft once it has been sent and files the sent copy into the Sent Mail folder. Requires EmailEngine v2.76.0 or later.
191
+
192
+ The optional `options` object mirrors the API's SubmitDraft payload (`envelope`, `copy`, `sentMailPath`, `sendAt`, ...). Resolves to EmailEngine's submit response (`{ response, messageId, queueId, sendAt }`).
193
+
184
194
  ### `downloadAttachment(attachmentId: string, suggestedFilename?: string): Promise<void>`
185
195
 
186
196
  Browser only. Fetch an attachment and trigger a download, using the filename from the `Content-Disposition` header when available.
@@ -204,9 +214,15 @@ When a `container` is provided the client builds a full webmail interface:
204
214
  - Folder tree with special-folder ordering (Inbox, Drafts, Sent, Trash, Junk, Archive) and nested folders
205
215
  - Paginated message list with a selectable page size (persisted to `localStorage`)
206
216
  - Message viewer with mark read/unread, delete, move-to-folder, download original, and attachment downloads
217
+ - Draft messages show a "Send Draft" button that submits the stored draft for delivery after confirmation (requires EmailEngine v2.76.0 or later; editing the draft first is not supported)
207
218
  - Quoted thread history collapsed behind a "Show quoted text" control
208
- - Compose modal (floating button) for sending plain-text mail
219
+ - Compose modal (floating button) for sending plain-text mail, with a Save Draft option that stores the message in the Drafts folder instead of sending it
209
220
  - Dark mode toggle with the preference persisted to `localStorage`
221
+ - Failed requests replace the affected pane's placeholder with an error panel and a Retry button
222
+
223
+ ### Failed requests
224
+
225
+ When a request behind a pane fails, that pane shows why instead of sitting on its "Loading..." placeholder. The reason is the message EmailEngine returned - for example "Requested account is not yet initialized" for an account that has not connected yet, or "Requested mailbox folder was not found" - and a Retry button re-runs the request. If the server could not be reached at all, the panel says so and names the configured `apiUrl`. The underlying promise still rejects, so callers driving the client programmatically can handle the error themselves.
210
226
 
211
227
  ### Quoted thread history
212
228
 
package/index.d.ts CHANGED
@@ -46,6 +46,9 @@ export interface Message {
46
46
  cc?: EmailAddress[];
47
47
  date: string;
48
48
  unseen: boolean;
49
+ draft?: boolean;
50
+ /** Special-use flag of the folder the message is stored in, e.g. "\\Drafts" */
51
+ messageSpecialUse?: string;
49
52
  intro?: string;
50
53
  text?: MessageText;
51
54
  attachments?: Attachment[];
@@ -59,6 +62,24 @@ export interface MessageListResponse {
59
62
 
60
63
  export type SendRecipient = string | EmailAddress;
61
64
 
65
+ /**
66
+ * Optional payload for `submitDraft()`. Mirrors the SubmitDraft schema of the
67
+ * EmailEngine API; all fields are optional and most only apply to SMTP deliveries.
68
+ */
69
+ export interface SubmitDraftOptions {
70
+ /** SMTP envelope override; derived from the draft's headers when omitted */
71
+ envelope?: { from?: string; to?: string[] };
72
+ /** Copy the sent message to the Sent Mail folder (SMTP only; account default when unset) */
73
+ copy?: boolean | null;
74
+ /** Upload the sent message to this folder instead of the default Sent Mail folder (SMTP only) */
75
+ sentMailPath?: string;
76
+ /** Schedule the send instead of sending immediately */
77
+ sendAt?: string | Date;
78
+ deliveryAttempts?: number;
79
+ gateway?: string;
80
+ [key: string]: unknown;
81
+ }
82
+
62
83
  /**
63
84
  * Custom dialog handler. Invoked by the client as
64
85
  * `(message, title, cancelText, okText)`; `cancelText` is `null` for alerts.
@@ -113,6 +134,8 @@ export declare class EmailEngineClient {
113
134
  deleteMessage(messageId: string): Promise<boolean>;
114
135
  moveMessage(messageId: string, targetPath: string): Promise<boolean>;
115
136
  sendMessage(to: SendRecipient | SendRecipient[], subject: string, text: string): Promise<any>;
137
+ saveDraft(to?: SendRecipient | SendRecipient[] | null, subject?: string, text?: string): Promise<any>;
138
+ submitDraft(messageId: string, options?: SubmitDraftOptions | null): Promise<any>;
116
139
  downloadAttachment(attachmentId: string, suggestedFilename?: string): Promise<void>;
117
140
  downloadOriginalMessage(messageId: string, subject?: string): Promise<void>;
118
141
  formatDate(dateStr: string): string;
package/index.js CHANGED
@@ -66,23 +66,13 @@ export class EmailEngineClient {
66
66
  this._startKeepAliveTimer();
67
67
  }
68
68
 
69
- async apiRequest(method, endpoint, data = null) {
70
- // Update activity timestamp for keep-alive
69
+ // Resolves the platform fetch (native in browsers and modern Node, node-fetch as
70
+ // an optional fallback on older Node) and normalizes transport failures, so both
71
+ // HTTP entry points - apiRequest and _fetchBlob - fail in the same shape.
72
+ async _fetch(url, options) {
73
+ // Any request counts as activity for the keep-alive timer
71
74
  this._updateActivity();
72
75
 
73
- const url = `${this.apiUrl}${endpoint}`;
74
- const options = {
75
- method: method,
76
- headers: {
77
- 'Content-Type': 'application/json',
78
- ...this._authHeaders()
79
- }
80
- };
81
-
82
- if (data) {
83
- options.body = JSON.stringify(data);
84
- }
85
-
86
76
  let fetchFn = globalThis.fetch;
87
77
  if (!fetchFn) {
88
78
  // Native fetch is missing (older Node.js). Fall back to node-fetch.
@@ -102,26 +92,63 @@ export class EmailEngineClient {
102
92
  );
103
93
  }
104
94
 
105
- const response = await fetchFn(url, options);
106
- if (!response.ok) {
107
- let errorDetails;
108
- try {
109
- errorDetails = await response.json();
110
- } catch (parseError) {
111
- // If JSON parsing fails, fall back to status text
112
- errorDetails = { message: response.statusText };
95
+ try {
96
+ return await fetchFn(url, options);
97
+ } catch (err) {
98
+ // Mark transport level failures - an unreachable server, DNS/TLS
99
+ // problems, a blocked CORS preflight - so callers can tell them apart
100
+ // from an API error that carries a server message.
101
+ const error = new Error(`Could not reach the EmailEngine server at ${this.apiUrl}`);
102
+ error.isNetworkError = true;
103
+ error.cause = err;
104
+ throw error;
105
+ }
106
+ }
107
+
108
+ // Turns a non-ok response into an Error carrying the server's own explanation.
109
+ // EmailEngine answers with Boom payloads - { statusCode, error, message, code,
110
+ // fields } - which _errorMessage() knows how to read.
111
+ async _responseError(response) {
112
+ let details;
113
+ try {
114
+ details = await response.json();
115
+ } catch (parseError) {
116
+ // Not a JSON body - the status line is all there is to go on
117
+ details = { message: response.statusText };
118
+ }
119
+
120
+ const error = new Error(`API request failed: ${response.statusText}`);
121
+ error.statusCode = response.status;
122
+ error.details = details;
123
+ return error;
124
+ }
125
+
126
+ async apiRequest(method, endpoint, data = null) {
127
+ const options = {
128
+ method: method,
129
+ headers: {
130
+ 'Content-Type': 'application/json',
131
+ ...this._authHeaders()
113
132
  }
133
+ };
114
134
 
115
- const error = new Error(`API request failed: ${response.statusText}`);
116
- error.statusCode = response.status;
117
- error.details = errorDetails;
118
- throw error;
135
+ if (data) {
136
+ options.body = JSON.stringify(data);
137
+ }
138
+
139
+ const response = await this._fetch(`${this.apiUrl}${endpoint}`, options);
140
+ if (!response.ok) {
141
+ throw await this._responseError(response);
119
142
  }
120
143
 
121
144
  return await response.json();
122
145
  }
123
146
 
124
147
  async loadFolders() {
148
+ // Reset the pane to its loading state so a retry after a failure does not
149
+ // keep showing the previous error while the new request is in flight.
150
+ this._setPaneHtml('.ee-folder-tree', '<div class="ee-loading">Loading folders...</div>');
151
+
125
152
  try {
126
153
  const data = await this.apiRequest('GET', `/v1/account/${this.account}/mailboxes`);
127
154
  this.folders = data.mailboxes || [];
@@ -132,17 +159,13 @@ export class EmailEngineClient {
132
159
  return this.folders;
133
160
  } catch (error) {
134
161
  console.error('Failed to load folders:', error);
162
+ this._renderPaneError('.ee-folder-tree', 'Folders unavailable', error, () => this._loadInitialView());
135
163
  throw error;
136
164
  }
137
165
  }
138
166
 
139
167
  async loadMessages(path, cursor = null) {
140
- if (this.container) {
141
- const messageList = this.container.querySelector('.ee-message-list');
142
- if (messageList) {
143
- messageList.innerHTML = '<div class="ee-loading">Loading messages...</div>';
144
- }
145
- }
168
+ this._setPaneHtml('.ee-message-list', '<div class="ee-loading">Loading messages...</div>');
146
169
 
147
170
  try {
148
171
  const params = new URLSearchParams({ path: path, pageSize: this.pageSize });
@@ -172,23 +195,15 @@ export class EmailEngineClient {
172
195
  };
173
196
  } catch (error) {
174
197
  console.error('Failed to load messages:', error);
175
- if (this.container) {
176
- const messageList = this.container.querySelector('.ee-message-list');
177
- if (messageList) {
178
- messageList.innerHTML = '<div class="ee-error">Failed to load messages</div>';
179
- }
180
- }
198
+ this._renderPaneError('.ee-message-list', 'Messages unavailable', error, () =>
199
+ this._fireAndForget(this.loadMessages(path, cursor))
200
+ );
181
201
  throw error;
182
202
  }
183
203
  }
184
204
 
185
205
  async loadMessage(messageId) {
186
- if (this.container) {
187
- const viewer = this.container.querySelector('.ee-message-viewer');
188
- if (viewer) {
189
- viewer.innerHTML = '<div class="ee-loading">Loading message...</div>';
190
- }
191
- }
206
+ this._setPaneHtml('.ee-message-viewer', '<div class="ee-loading">Loading message...</div>');
192
207
 
193
208
  try {
194
209
  const params = new URLSearchParams({
@@ -224,12 +239,9 @@ export class EmailEngineClient {
224
239
  return this.currentMessage;
225
240
  } catch (error) {
226
241
  console.error('Failed to load message:', error);
227
- if (this.container) {
228
- const viewer = this.container.querySelector('.ee-message-viewer');
229
- if (viewer) {
230
- viewer.innerHTML = '<div class="ee-error">Failed to load message</div>';
231
- }
232
- }
242
+ this._renderPaneError('.ee-message-viewer', 'Message unavailable', error, () =>
243
+ this._fireAndForget(this.loadMessage(messageId))
244
+ );
233
245
  throw error;
234
246
  }
235
247
  }
@@ -310,14 +322,25 @@ export class EmailEngineClient {
310
322
  }
311
323
  }
312
324
 
325
+ _normalizeRecipients(to) {
326
+ return Array.isArray(to)
327
+ ? to.map(addr => (typeof addr === 'string' ? { address: addr } : addr))
328
+ : [typeof to === 'string' ? { address: to } : to];
329
+ }
330
+
331
+ // Account details (name, email address) fetched once and cached for the lifetime
332
+ // of the instance; used as the From identity of saved drafts.
333
+ async _getAccountInfo() {
334
+ if (!this._accountInfo) {
335
+ this._accountInfo = await this.apiRequest('GET', `/v1/account/${this.account}`);
336
+ }
337
+ return this._accountInfo;
338
+ }
339
+
313
340
  async sendMessage(to, subject, text) {
314
341
  try {
315
- const toAddresses = Array.isArray(to)
316
- ? to.map(addr => (typeof addr === 'string' ? { address: addr } : addr))
317
- : [typeof to === 'string' ? { address: to } : to];
318
-
319
342
  const messageData = {
320
- to: toAddresses,
343
+ to: this._normalizeRecipients(to),
321
344
  subject: subject,
322
345
  text: text
323
346
  };
@@ -326,29 +349,94 @@ export class EmailEngineClient {
326
349
  return response;
327
350
  } catch (error) {
328
351
  console.error('Failed to send message:', error);
329
- // Try to parse detailed error information
330
- this._parseApiError(error);
331
352
  throw error;
332
353
  }
333
354
  }
334
355
 
335
- _parseApiError(error) {
356
+ async saveDraft(to, subject, text) {
336
357
  try {
337
- // If error has response text, try to parse it
338
- if (error.message && error.message.includes('API request failed:')) {
339
- // This is our custom error from apiRequest, the actual response might have more details
340
- error.isDetailedError = false;
358
+ if (!this.folders.length) {
359
+ await this.loadFolders();
341
360
  }
342
- } catch (parseError) {
343
- // If parsing fails, just use the original error
344
- console.error('Failed to parse error details:', parseError);
361
+ const draftsFolder = this.folders.find(f => f.specialUse === '\\Drafts');
362
+ if (!draftsFolder) {
363
+ throw new Error('No Drafts folder found for this account');
364
+ }
365
+
366
+ const messageData = {
367
+ path: draftsFolder.path,
368
+ flags: ['\\Draft'],
369
+ subject: subject,
370
+ text: text
371
+ };
372
+
373
+ const recipients = to ? this._normalizeRecipients(to) : [];
374
+ if (recipients.length) {
375
+ messageData.to = recipients;
376
+ }
377
+
378
+ // The upload endpoint does not add a From header on its own, but the draft
379
+ // needs one to be deliverable later - use the account's own identity.
380
+ try {
381
+ const accountInfo = await this._getAccountInfo();
382
+ if (accountInfo && accountInfo.email) {
383
+ messageData.from = { name: accountInfo.name || '', address: accountInfo.email };
384
+ }
385
+ } catch (err) {
386
+ // Non-fatal: the draft is saved without a From header
387
+ }
388
+
389
+ const response = await this.apiRequest('POST', `/v1/account/${this.account}/message`, messageData);
390
+ return response;
391
+ } catch (error) {
392
+ console.error('Failed to save draft:', error);
393
+ throw error;
345
394
  }
346
395
  }
347
396
 
348
- _formatSendError(error) {
349
- // If we have detailed error information from the API
350
- if (error.details && error.details.fields && Array.isArray(error.details.fields)) {
351
- const fieldErrors = error.details.fields
397
+ async submitDraft(messageId, options = null) {
398
+ try {
399
+ const response = await this.apiRequest(
400
+ 'POST',
401
+ `/v1/account/${this.account}/message/${messageId}/submit`,
402
+ options
403
+ );
404
+ return response;
405
+ } catch (error) {
406
+ console.error('Failed to submit draft:', error);
407
+ throw error;
408
+ }
409
+ }
410
+
411
+ // A message counts as a draft when the server marks it as one (the \Draft flag on IMAP,
412
+ // the DRAFT label on Gmail, a draft message on MS Graph) or when it sits in the Drafts
413
+ // special-use folder.
414
+ _isDraftMessage(msg) {
415
+ if (!msg) {
416
+ return false;
417
+ }
418
+ if (msg.draft || msg.messageSpecialUse === '\\Drafts') {
419
+ return true;
420
+ }
421
+ const folder = this.folders.find(f => f.path === this.currentFolder);
422
+ return !!(folder && folder.specialUse === '\\Drafts');
423
+ }
424
+
425
+ // Best-effort human readable reason for a failed request. EmailEngine returns
426
+ // Boom style payloads - { statusCode, error, message, code, fields } - so the
427
+ // `message` field usually carries the actual cause, e.g. "Requested account is
428
+ // not yet initialized" when the account has not connected yet.
429
+ _errorMessage(error, fallback = 'Unexpected error') {
430
+ if (!error) {
431
+ return fallback;
432
+ }
433
+
434
+ const details = error.details;
435
+ const detailsMessage = details && typeof details.message === 'string' ? details.message : '';
436
+
437
+ // Validation failures list the offending fields
438
+ if (details && Array.isArray(details.fields)) {
439
+ const fieldErrors = details.fields
352
440
  // Keep only entries that carry a usable message string.
353
441
  .filter(field => field && typeof field.message === 'string')
354
442
  // Map technical field names to user-friendly ones. Each replace
@@ -361,15 +449,100 @@ export class EmailEngineClient {
361
449
  .replace(/"text"/g, 'message')
362
450
  );
363
451
 
364
- const mainMessage = error.details.message || 'Failed to send email';
452
+ const mainMessage = detailsMessage || fallback;
365
453
  if (fieldErrors.length > 0) {
366
454
  return `${mainMessage}:\n\n• ${fieldErrors.join('\n• ')}`;
367
455
  }
368
456
  return mainMessage;
369
457
  }
370
458
 
371
- // Fallback to generic error message
372
- return 'Failed to send email. Please check your input and try again.';
459
+ if (detailsMessage) {
460
+ return detailsMessage;
461
+ }
462
+
463
+ if (error.statusCode) {
464
+ return `The server responded with status ${error.statusCode}`;
465
+ }
466
+
467
+ return error.message || fallback;
468
+ }
469
+
470
+ _formatSendError(error) {
471
+ return this._errorMessage(error, 'Failed to send email. Please check your input and try again.');
472
+ }
473
+
474
+ // Writes markup into one of the client's panes when the UI exists and is still
475
+ // alive, and hands the pane back so callers can wire up what they rendered.
476
+ _setPaneHtml(selector, html) {
477
+ if (typeof document === 'undefined' || !this.container || this._destroyed) {
478
+ return null;
479
+ }
480
+
481
+ const pane = this.container.querySelector(selector);
482
+ if (pane) {
483
+ pane.innerHTML = html;
484
+ }
485
+ return pane;
486
+ }
487
+
488
+ // Replaces a pane's contents with an error panel explaining why its data is
489
+ // missing, optionally with a Retry button. Without this a failed request
490
+ // leaves the pane stuck on its "Loading..." placeholder forever, with the
491
+ // only trace of the failure in the developer console.
492
+ _renderPaneError(selector, title, error, retry = null) {
493
+ const detail = this._errorMessage(error, '');
494
+ const pane = this._setPaneHtml(
495
+ selector,
496
+ `
497
+ <div class="ee-error">
498
+ <div class="ee-error-title">${this.escapeHtml(title)}</div>
499
+ ${detail ? `<div class="ee-error-detail">${this.escapeHtml(detail)}</div>` : ''}
500
+ ${retry ? '<button type="button" class="ee-button ee-error-retry">Retry</button>' : ''}
501
+ </div>
502
+ `
503
+ );
504
+
505
+ if (pane && retry) {
506
+ const retryButton = pane.querySelector('.ee-error-retry');
507
+ if (retryButton) {
508
+ retryButton.addEventListener('click', () => {
509
+ if (this._destroyed) {
510
+ return;
511
+ }
512
+ // Disable while the request is in flight so an impatient second
513
+ // click can not fan out a duplicate round trip. A failed retry
514
+ // re-renders the panel with a fresh button.
515
+ retryButton.disabled = true;
516
+ retry();
517
+ });
518
+ }
519
+ }
520
+ }
521
+
522
+ // Loads started from a DOM handler render their own error panel, so the user
523
+ // has already been told. Swallow the rejection rather than letting it surface
524
+ // as an unhandled rejection in hosts with a global error reporter.
525
+ _fireAndForget(promise) {
526
+ promise.catch(() => {});
527
+ }
528
+
529
+ // Message actions (flag, delete, move) have no pane of their own to report into:
530
+ // when one fails the message simply stays put, which is indistinguishable from
531
+ // nothing having happened. Say so instead.
532
+ _alertActionFailed(error, fallback) {
533
+ console.error(`${fallback}:`, error);
534
+ return this.alertMethod(this._errorMessage(error, fallback), 'Error', null, 'OK');
535
+ }
536
+
537
+ // The message list before any folder is opened. Shared with createLayout so the
538
+ // pane header markup lives in one place.
539
+ _messageListPlaceholder() {
540
+ return `
541
+ <div class="ee-pane-header">
542
+ <span class="ee-pane-title">Messages</span>
543
+ </div>
544
+ <div class="ee-empty-state">Select a folder</div>
545
+ `;
373
546
  }
374
547
 
375
548
  formatDate(dateStr) {
@@ -423,15 +596,17 @@ export class EmailEngineClient {
423
596
  }
424
597
 
425
598
  // Authenticated GET for binary payloads (attachments, message source).
426
- // apiRequest is not reused here - it always parses the body as JSON.
599
+ // apiRequest is not reused here - it always parses the body as JSON - but the
600
+ // same _fetch/_responseError pair is, so a failed download reports the same
601
+ // reason as any other request.
427
602
  async _fetchBlob(endpoint) {
428
- const response = await fetch(`${this.apiUrl}${endpoint}`, {
603
+ const response = await this._fetch(`${this.apiUrl}${endpoint}`, {
429
604
  headers: this._authHeaders(),
430
605
  credentials: 'include'
431
606
  });
432
607
 
433
608
  if (!response.ok) {
434
- throw new Error(`HTTP error! status: ${response.status}`);
609
+ throw await this._responseError(response);
435
610
  }
436
611
 
437
612
  return response;
@@ -456,7 +631,12 @@ export class EmailEngineClient {
456
631
  this._saveBlob(blob, filename);
457
632
  } catch (error) {
458
633
  console.error('Failed to download attachment:', error);
459
- this.alertMethod('Failed to download attachment. Please try again.', 'Download Error', null, 'OK');
634
+ this.alertMethod(
635
+ this._errorMessage(error, 'Failed to download attachment. Please try again.'),
636
+ 'Download Error',
637
+ null,
638
+ 'OK'
639
+ );
460
640
  }
461
641
  }
462
642
 
@@ -476,7 +656,12 @@ export class EmailEngineClient {
476
656
  this._saveBlob(blob, filename);
477
657
  } catch (error) {
478
658
  console.error('Failed to download original message:', error);
479
- this.alertMethod('Failed to download original message. Please try again.', 'Download Error', null, 'OK');
659
+ this.alertMethod(
660
+ this._errorMessage(error, 'Failed to download original message. Please try again.'),
661
+ 'Download Error',
662
+ null,
663
+ 'OK'
664
+ );
480
665
  }
481
666
  }
482
667
 
@@ -841,6 +1026,25 @@ export class EmailEngineClient {
841
1026
  border: 1px solid #fcc;
842
1027
  border-radius: 4px;
843
1028
  margin: 16px;
1029
+ /* Panes can be as narrow as the 200px sidebar and server
1030
+ messages are arbitrary text, so break anywhere rather than
1031
+ letting a long word push the layout wider. */
1032
+ overflow-wrap: anywhere;
1033
+ }
1034
+
1035
+ .ee-error-title {
1036
+ font-weight: 500;
1037
+ }
1038
+
1039
+ .ee-error-detail {
1040
+ margin-top: 6px;
1041
+ font-size: 12px;
1042
+ /* Field level API errors arrive as a newline separated list */
1043
+ white-space: pre-line;
1044
+ }
1045
+
1046
+ .ee-error-retry {
1047
+ margin-top: 10px;
844
1048
  }
845
1049
 
846
1050
  .ee-flag {
@@ -1095,11 +1299,34 @@ export class EmailEngineClient {
1095
1299
  font-size: 14px;
1096
1300
  cursor: pointer;
1097
1301
  }
1098
-
1302
+
1099
1303
  .ee-compose-cancel:hover {
1100
1304
  background: #545b62;
1101
1305
  }
1102
1306
 
1307
+ .ee-compose-save-draft {
1308
+ background: transparent;
1309
+ color: #007bff;
1310
+ border: 1px solid #007bff;
1311
+ padding: 10px 20px;
1312
+ border-radius: 4px;
1313
+ font-size: 14px;
1314
+ font-weight: 500;
1315
+ cursor: pointer;
1316
+ }
1317
+
1318
+ .ee-compose-save-draft:hover:not(:disabled) {
1319
+ background: #007bff;
1320
+ color: white;
1321
+ }
1322
+
1323
+ .ee-compose-save-draft:disabled {
1324
+ color: #6c757d;
1325
+ border-color: #6c757d;
1326
+ cursor: not-allowed;
1327
+ opacity: 0.6;
1328
+ }
1329
+
1103
1330
  /* Dark mode toggle button */
1104
1331
  .ee-dark-mode-toggle {
1105
1332
  position: absolute;
@@ -1254,11 +1481,16 @@ export class EmailEngineClient {
1254
1481
  }
1255
1482
 
1256
1483
  .ee-dark-mode .ee-loading,
1257
- .ee-dark-mode .ee-empty-state,
1258
- .ee-dark-mode .ee-error {
1484
+ .ee-dark-mode .ee-empty-state {
1259
1485
  color: #999;
1260
1486
  }
1261
1487
 
1488
+ .ee-dark-mode .ee-error {
1489
+ background: #3a2222;
1490
+ border-color: #5c3030;
1491
+ color: #f0a5a5;
1492
+ }
1493
+
1262
1494
  .ee-dark-mode .ee-pagination {
1263
1495
  background: #252525;
1264
1496
  border-color: #333;
@@ -1314,6 +1546,16 @@ export class EmailEngineClient {
1314
1546
  .ee-dark-mode .ee-compose-cancel:hover {
1315
1547
  background: #555;
1316
1548
  }
1549
+
1550
+ .ee-dark-mode .ee-compose-save-draft {
1551
+ color: #66b2ff;
1552
+ border-color: #66b2ff;
1553
+ }
1554
+
1555
+ .ee-dark-mode .ee-compose-save-draft:hover:not(:disabled) {
1556
+ background: #66b2ff;
1557
+ color: #1a1a1a;
1558
+ }
1317
1559
  `;
1318
1560
  document.head.appendChild(style);
1319
1561
  this._styleElement = style;
@@ -1442,7 +1684,7 @@ export class EmailEngineClient {
1442
1684
  folderTree.querySelectorAll('.ee-folder-item').forEach(item => {
1443
1685
  item.addEventListener('click', () => {
1444
1686
  const path = item.getAttribute('data-path');
1445
- this.loadMessages(path);
1687
+ this._fireAndForget(this.loadMessages(path));
1446
1688
  });
1447
1689
  });
1448
1690
  }
@@ -1518,19 +1760,19 @@ export class EmailEngineClient {
1518
1760
  messageList.querySelectorAll('.ee-message-item').forEach(item => {
1519
1761
  item.addEventListener('click', () => {
1520
1762
  const messageId = item.getAttribute('data-id');
1521
- this.loadMessage(messageId);
1763
+ this._fireAndForget(this.loadMessage(messageId));
1522
1764
  });
1523
1765
  });
1524
1766
 
1525
1767
  messageList.querySelectorAll('[data-action="prev-page"]').forEach(btn => {
1526
1768
  btn.addEventListener('click', () => {
1527
- this.loadMessages(this.currentFolder, this.prevPageCursor);
1769
+ this._fireAndForget(this.loadMessages(this.currentFolder, this.prevPageCursor));
1528
1770
  });
1529
1771
  });
1530
1772
 
1531
1773
  messageList.querySelectorAll('[data-action="next-page"]').forEach(btn => {
1532
1774
  btn.addEventListener('click', () => {
1533
- this.loadMessages(this.currentFolder, this.nextPageCursor);
1775
+ this._fireAndForget(this.loadMessages(this.currentFolder, this.nextPageCursor));
1534
1776
  });
1535
1777
  });
1536
1778
 
@@ -1542,7 +1784,7 @@ export class EmailEngineClient {
1542
1784
  if (typeof window !== 'undefined' && window.localStorage) {
1543
1785
  localStorage.setItem('ee-client-page-size', this.pageSize.toString());
1544
1786
  }
1545
- this.loadMessages(this.currentFolder);
1787
+ this._fireAndForget(this.loadMessages(this.currentFolder));
1546
1788
  });
1547
1789
  }
1548
1790
  }
@@ -1564,8 +1806,10 @@ export class EmailEngineClient {
1564
1806
 
1565
1807
  const msg = this.currentMessage;
1566
1808
  const isUnseen = msg.unseen;
1809
+ const isDraft = this._isDraftMessage(msg);
1567
1810
  const html = `
1568
1811
  <div class="ee-message-actions">
1812
+ ${isDraft ? '<button class="ee-button" data-action="send-draft">Send Draft</button>' : ''}
1569
1813
  <button class="ee-button" data-action="toggle-read">Mark as ${isUnseen ? 'seen' : 'unseen'}</button>
1570
1814
  <button class="ee-button" data-action="delete">Delete</button>
1571
1815
  <button class="ee-button" data-action="download-original">Download Original</button>
@@ -1640,9 +1884,46 @@ export class EmailEngineClient {
1640
1884
 
1641
1885
  this._labelCollapsedThreads(viewer);
1642
1886
 
1887
+ const sendDraftButton = viewer.querySelector('[data-action="send-draft"]');
1888
+ if (sendDraftButton) {
1889
+ sendDraftButton.addEventListener('click', async () => {
1890
+ const result = await this.confirmMethod(
1891
+ 'Send this draft to its recipients now? The draft is removed from the Drafts folder once it has been sent.',
1892
+ 'Send Draft',
1893
+ 'Cancel',
1894
+ 'Send'
1895
+ );
1896
+ if (!result) {
1897
+ return;
1898
+ }
1899
+
1900
+ const originalText = sendDraftButton.textContent;
1901
+ sendDraftButton.disabled = true;
1902
+ sendDraftButton.textContent = 'Sending...';
1903
+
1904
+ try {
1905
+ await this.submitDraft(msg.id);
1906
+ await this.alertMethod('Draft queued for delivery.', 'Success', null, 'OK');
1907
+ // Refresh the folder view - the provider removes the draft once it is sent,
1908
+ // immediately for Gmail and MS Graph, after SMTP delivery for IMAP accounts.
1909
+ if (!this._destroyed && this.currentFolder) {
1910
+ await this.loadMessages(this.currentFolder);
1911
+ }
1912
+ } catch (error) {
1913
+ console.error('Failed to send draft:', error);
1914
+ const errorMessage = this._formatSendError(error);
1915
+ await this.alertMethod(errorMessage, 'Send Error', null, 'OK');
1916
+ sendDraftButton.disabled = false;
1917
+ sendDraftButton.textContent = originalText;
1918
+ }
1919
+ });
1920
+ }
1921
+
1643
1922
  viewer.querySelector('[data-action="toggle-read"]').addEventListener('click', () => {
1644
1923
  const currentlyUnseen = msg.unseen;
1645
- this.markAsRead(msg.id, currentlyUnseen);
1924
+ this.markAsRead(msg.id, currentlyUnseen).catch(error =>
1925
+ this._alertActionFailed(error, 'Failed to update the message flags')
1926
+ );
1646
1927
  });
1647
1928
 
1648
1929
  viewer.querySelector('[data-action="delete"]').addEventListener('click', async () => {
@@ -1653,7 +1934,9 @@ export class EmailEngineClient {
1653
1934
  'Delete'
1654
1935
  );
1655
1936
  if (result) {
1656
- this.deleteMessage(msg.id);
1937
+ this.deleteMessage(msg.id).catch(error =>
1938
+ this._alertActionFailed(error, 'Failed to delete the message')
1939
+ );
1657
1940
  }
1658
1941
  });
1659
1942
 
@@ -1664,7 +1947,12 @@ export class EmailEngineClient {
1664
1947
  viewer.querySelector('[data-action="move"]').addEventListener('change', e => {
1665
1948
  const targetPath = e.target.value;
1666
1949
  if (targetPath) {
1667
- this.moveMessage(msg.id, targetPath);
1950
+ this.moveMessage(msg.id, targetPath).catch(error => {
1951
+ // The message did not move, so the select must not keep showing
1952
+ // the target folder as though it had
1953
+ e.target.value = '';
1954
+ this._alertActionFailed(error, 'Failed to move the message');
1955
+ });
1668
1956
  }
1669
1957
  });
1670
1958
 
@@ -1717,16 +2005,9 @@ export class EmailEngineClient {
1717
2005
  <div class="ee-pane-header">
1718
2006
  <span class="ee-pane-title">Folders</span>
1719
2007
  </div>
1720
- <div class="ee-folder-tree">
1721
- <div class="ee-loading">Loading folders...</div>
1722
- </div>
1723
- </div>
1724
- <div class="ee-message-list">
1725
- <div class="ee-pane-header">
1726
- <span class="ee-pane-title">Messages</span>
1727
- </div>
1728
- <div class="ee-empty-state">Select a folder</div>
2008
+ <div class="ee-folder-tree"></div>
1729
2009
  </div>
2010
+ <div class="ee-message-list">${this._messageListPlaceholder()}</div>
1730
2011
  <div class="ee-message-viewer">
1731
2012
  <div class="ee-empty-state">Select a message to view</div>
1732
2013
  </div>
@@ -1754,6 +2035,7 @@ export class EmailEngineClient {
1754
2035
  </form>
1755
2036
  <div class="ee-compose-actions">
1756
2037
  <button type="button" class="ee-compose-cancel">Cancel</button>
2038
+ <button type="button" class="ee-compose-save-draft">Save Draft</button>
1757
2039
  <button type="button" class="ee-compose-send">Send</button>
1758
2040
  </div>
1759
2041
  </div>
@@ -1776,6 +2058,7 @@ export class EmailEngineClient {
1776
2058
  const modal = this.container.querySelector('.ee-compose-modal');
1777
2059
  const closeButton = this.container.querySelector('.ee-compose-close');
1778
2060
  const cancelButton = this.container.querySelector('.ee-compose-cancel');
2061
+ const saveDraftButton = this.container.querySelector('.ee-compose-save-draft');
1779
2062
  const sendButton = this.container.querySelector('.ee-compose-send');
1780
2063
  const form = this.container.querySelector('.ee-compose-form');
1781
2064
 
@@ -1811,6 +2094,52 @@ export class EmailEngineClient {
1811
2094
  };
1812
2095
  document.addEventListener('keydown', this._composeKeydownHandler);
1813
2096
 
2097
+ // Save the composed message as a draft instead of sending it
2098
+ saveDraftButton.addEventListener('click', async () => {
2099
+ const formData = new FormData(form);
2100
+ const to = formData.get('to').trim();
2101
+ const subject = formData.get('subject').trim();
2102
+ const message = formData.get('message').trim();
2103
+
2104
+ if (!to && !subject && !message) {
2105
+ modal.classList.remove('show');
2106
+ await this.alertMethod(
2107
+ 'Nothing to save - fill in at least one field first.',
2108
+ 'Validation Error',
2109
+ null,
2110
+ 'OK'
2111
+ );
2112
+ modal.classList.add('show');
2113
+ setTimeout(() => form.querySelector('input[name="to"]').focus(), 100);
2114
+ return;
2115
+ }
2116
+
2117
+ const originalText = saveDraftButton.textContent;
2118
+ saveDraftButton.disabled = true;
2119
+ saveDraftButton.textContent = 'Saving...';
2120
+
2121
+ try {
2122
+ const response = await this.saveDraft(to || null, subject, message);
2123
+ closeModal();
2124
+ await this.alertMethod('Draft saved to the Drafts folder.', 'Success', null, 'OK');
2125
+ // Refresh the list when the user is looking at the Drafts folder
2126
+ if (!this._destroyed && response && response.path && this.currentFolder === response.path) {
2127
+ await this.loadMessages(this.currentFolder);
2128
+ }
2129
+ } catch (error) {
2130
+ console.error('Failed to save draft:', error);
2131
+ // Close modal before showing error alert, then reopen with preserved values
2132
+ modal.classList.remove('show');
2133
+ const errorMessage = this._formatSendError(error);
2134
+ await this.alertMethod(errorMessage, 'Save Error', null, 'OK');
2135
+ modal.classList.add('show');
2136
+ setTimeout(() => form.querySelector('input[name="to"]').focus(), 100);
2137
+ } finally {
2138
+ saveDraftButton.disabled = false;
2139
+ saveDraftButton.textContent = originalText;
2140
+ }
2141
+ });
2142
+
1814
2143
  // Send email
1815
2144
  sendButton.addEventListener('click', async () => {
1816
2145
  const formData = new FormData(form);
@@ -1889,6 +2218,17 @@ export class EmailEngineClient {
1889
2218
  const buttonSize = 56; // Button width/height
1890
2219
  const margin = 20; // Desired margin from edges
1891
2220
 
2221
+ // A hidden container (display: none) reports a zero-size rect; positioning
2222
+ // against it would push the fixed-position button off-screen. Hide the button
2223
+ // instead and let the ResizeObserver below restore it once the container is
2224
+ // shown - hosts often create the client inside a container that is only made
2225
+ // visible afterwards.
2226
+ if (!containerRect.width && !containerRect.height) {
2227
+ composeButton.style.display = 'none';
2228
+ return;
2229
+ }
2230
+ composeButton.style.display = '';
2231
+
1892
2232
  // Calculate the ideal position (bottom-right of container with margin)
1893
2233
  const idealBottom = window.innerHeight - containerRect.bottom + margin;
1894
2234
  const idealRight = window.innerWidth - containerRect.right + margin;
@@ -1917,10 +2257,26 @@ export class EmailEngineClient {
1917
2257
  window.addEventListener('scroll', updateWithThrottle);
1918
2258
  window.addEventListener('resize', updateWithThrottle);
1919
2259
 
1920
- // Store cleanup function for potential future use
2260
+ // Reposition when the container itself changes size or becomes visible - window
2261
+ // scroll/resize events never fire for those. Calls the update directly instead of
2262
+ // the throttled wrapper: the throttle drops trailing calls, which would leave the
2263
+ // button hidden when the observer fires twice in quick succession (initial
2264
+ // notification followed by the container being shown). Observer callbacks are
2265
+ // already batched per frame by the browser, so there is nothing to throttle.
2266
+ let resizeObserver = null;
2267
+ if (typeof ResizeObserver !== 'undefined') {
2268
+ resizeObserver = new ResizeObserver(updateButtonPosition);
2269
+ resizeObserver.observe(this.container);
2270
+ }
2271
+
2272
+ // Cleanup runs from destroy()
1921
2273
  this._composeButtonCleanup = () => {
1922
2274
  window.removeEventListener('scroll', updateWithThrottle);
1923
2275
  window.removeEventListener('resize', updateWithThrottle);
2276
+ if (resizeObserver) {
2277
+ resizeObserver.disconnect();
2278
+ resizeObserver = null;
2279
+ }
1924
2280
  };
1925
2281
  }
1926
2282
 
@@ -1952,18 +2308,38 @@ export class EmailEngineClient {
1952
2308
  toggleBtn.addEventListener('click', () => this.toggleDarkMode());
1953
2309
  }
1954
2310
 
1955
- this.loadFolders()
2311
+ this._loadInitialView();
2312
+ }
2313
+
2314
+ // Load the folder list and open the account's inbox. Used on startup and by
2315
+ // the Retry button that loadFolders renders when the request fails; both
2316
+ // failure paths already put an error panel in the UI, so the rejection is
2317
+ // logged and swallowed here rather than surfacing as an unhandled rejection.
2318
+ _loadInitialView() {
2319
+ // Drop whatever a previous attempt left here; loadFolders and loadMessages
2320
+ // paint their own loading states from this point on.
2321
+ this._setPaneHtml('.ee-message-list', this._messageListPlaceholder());
2322
+
2323
+ return this.loadFolders()
2324
+ .catch(error => {
2325
+ // loadFolders reports into the sidebar, but the message list is the
2326
+ // larger pane and would still read "Select a folder" - a folder the
2327
+ // sidebar can no longer offer. Say what happened there too.
2328
+ this._renderPaneError('.ee-message-list', 'Folders unavailable', error, () => this._loadInitialView());
2329
+ throw error;
2330
+ })
1956
2331
  .then(() => {
1957
2332
  const inbox =
1958
2333
  this.folders.find(f => f.specialUse && f.specialUse.includes('\\Inbox')) ||
1959
2334
  this.folders.find(f => f.name.toLowerCase() === 'inbox') ||
1960
2335
  this.folders[0];
1961
2336
  if (inbox) {
1962
- this.loadMessages(inbox.path);
2337
+ return this.loadMessages(inbox.path);
1963
2338
  }
1964
2339
  })
1965
2340
  .catch(error => {
1966
- console.error('Failed to auto-select inbox:', error);
2341
+ // Both loadFolders and loadMessages have already rendered a panel
2342
+ console.error('Failed to load the initial view:', error);
1967
2343
  });
1968
2344
  }
1969
2345
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postalsys/ee-client",
3
- "version": "1.6.0",
3
+ "version": "1.7.1",
4
4
  "description": "EmailEngine client library for browser and Node.js applications",
5
5
  "main": "index.js",
6
6
  "module": "index.js",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "devDependencies": {
45
45
  "eslint": "^8.57.1",
46
- "prettier": "^3.9.5"
46
+ "prettier": "^3.9.6"
47
47
  },
48
48
  "peerDependencies": {
49
49
  "node-fetch": "^3.0.0"