@postalsys/ee-client 1.3.3 → 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 +1 -1
  2. package/index.d.ts +45 -6
  3. package/index.js +176 -126
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -129,7 +129,7 @@ UI rendering, the compose modal, and dark mode only activate when a `container`
129
129
 
130
130
  ### Factory helper
131
131
 
132
- `createEmailEngineClient()` is a convenience wrapper that also accepts a container element or an element id, and validates that `account` is present:
132
+ `createEmailEngineClient()` is a convenience wrapper that resolves a `containerId` to its DOM element and validates that `account` is present:
133
133
 
134
134
  ```javascript
135
135
  import { createEmailEngineClient } from '@postalsys/ee-client';
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.3",
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",