imapflow 2.0.7 → 2.0.8

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 (78) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/cjs/commands/append.js +12 -12
  3. package/dist/cjs/commands/authenticate.d.ts +3 -8
  4. package/dist/cjs/commands/close.js +2 -1
  5. package/dist/cjs/commands/copy.js +4 -4
  6. package/dist/cjs/commands/create.js +2 -3
  7. package/dist/cjs/commands/delete.js +4 -4
  8. package/dist/cjs/commands/expunge.js +8 -5
  9. package/dist/cjs/commands/fetch.js +12 -10
  10. package/dist/cjs/commands/idle.js +6 -2
  11. package/dist/cjs/commands/list.js +2 -2
  12. package/dist/cjs/commands/move.js +11 -6
  13. package/dist/cjs/commands/namespace.js +1 -1
  14. package/dist/cjs/commands/quota.js +10 -9
  15. package/dist/cjs/commands/rename.js +4 -4
  16. package/dist/cjs/commands/search.js +7 -8
  17. package/dist/cjs/commands/select.js +5 -6
  18. package/dist/cjs/commands/status.js +11 -11
  19. package/dist/cjs/commands/store.js +5 -5
  20. package/dist/cjs/commands/subscribe.js +2 -17
  21. package/dist/cjs/commands/subscription.d.ts +10 -0
  22. package/dist/cjs/commands/subscription.js +29 -0
  23. package/dist/cjs/commands/unsubscribe.js +2 -17
  24. package/dist/cjs/download.d.ts +22 -0
  25. package/dist/cjs/download.js +588 -0
  26. package/dist/cjs/errors.d.ts +2 -0
  27. package/dist/cjs/handler/imap-compiler.js +1 -1
  28. package/dist/cjs/handler/imap-stream.js +4 -4
  29. package/dist/cjs/handler/parser-instance.js +2 -2
  30. package/dist/cjs/handler/token-parser.js +1 -1
  31. package/dist/cjs/imap-flow.d.ts +16 -7
  32. package/dist/cjs/imap-flow.js +247 -730
  33. package/dist/cjs/jp-decoder.js +1 -1
  34. package/dist/cjs/package-info.d.ts +1 -1
  35. package/dist/cjs/package-info.js +3 -3
  36. package/dist/cjs/search-compiler.js +5 -12
  37. package/dist/cjs/tools.d.ts +51 -10
  38. package/dist/cjs/tools.js +77 -15
  39. package/dist/cjs/types.d.ts +30 -16
  40. package/dist/esm/commands/append.js +13 -13
  41. package/dist/esm/commands/authenticate.d.ts +3 -8
  42. package/dist/esm/commands/close.js +2 -1
  43. package/dist/esm/commands/copy.js +5 -5
  44. package/dist/esm/commands/create.js +3 -4
  45. package/dist/esm/commands/delete.js +5 -5
  46. package/dist/esm/commands/expunge.js +9 -6
  47. package/dist/esm/commands/fetch.js +13 -11
  48. package/dist/esm/commands/idle.js +7 -3
  49. package/dist/esm/commands/list.js +2 -2
  50. package/dist/esm/commands/move.js +12 -7
  51. package/dist/esm/commands/namespace.js +2 -2
  52. package/dist/esm/commands/quota.js +11 -10
  53. package/dist/esm/commands/rename.js +5 -5
  54. package/dist/esm/commands/search.js +8 -9
  55. package/dist/esm/commands/select.js +6 -7
  56. package/dist/esm/commands/status.js +12 -12
  57. package/dist/esm/commands/store.js +6 -6
  58. package/dist/esm/commands/subscribe.js +2 -17
  59. package/dist/esm/commands/subscription.d.ts +10 -0
  60. package/dist/esm/commands/subscription.js +26 -0
  61. package/dist/esm/commands/unsubscribe.js +2 -17
  62. package/dist/esm/download.d.ts +22 -0
  63. package/dist/esm/download.js +581 -0
  64. package/dist/esm/errors.d.ts +2 -0
  65. package/dist/esm/handler/imap-compiler.js +1 -1
  66. package/dist/esm/handler/imap-stream.js +4 -4
  67. package/dist/esm/handler/parser-instance.js +2 -2
  68. package/dist/esm/handler/token-parser.js +1 -1
  69. package/dist/esm/imap-flow.d.ts +16 -7
  70. package/dist/esm/imap-flow.js +248 -731
  71. package/dist/esm/jp-decoder.js +1 -1
  72. package/dist/esm/package-info.d.ts +1 -1
  73. package/dist/esm/package-info.js +3 -3
  74. package/dist/esm/search-compiler.js +5 -12
  75. package/dist/esm/tools.d.ts +51 -10
  76. package/dist/esm/tools.js +72 -15
  77. package/dist/esm/types.d.ts +30 -16
  78. package/package.json +4 -4
@@ -31,7 +31,7 @@ export class JPDecoder extends Transform {
31
31
  chunk = Buffer.from(chunk, encoding);
32
32
  }
33
33
  if (this.chunklen + chunk.length > this.maxBytes) {
34
- chunk = chunk.slice(0, Math.max(0, this.maxBytes - this.chunklen));
34
+ chunk = chunk.subarray(0, Math.max(0, this.maxBytes - this.chunklen));
35
35
  }
36
36
  if (chunk.length) {
37
37
  this.chunks.push(chunk);
@@ -1,3 +1,3 @@
1
1
  export declare const name = "imapflow";
2
- export declare const version = "2.0.7";
2
+ export declare const version = "2.0.8";
3
3
  export declare const homepage = "https://imapflow.com/";
@@ -1,4 +1,4 @@
1
1
  // Generated by scripts/build.js from package.json. Do not edit by hand.
2
- export const name = 'imapflow';
3
- export const version = '2.0.7';
4
- export const homepage = 'https://imapflow.com/';
2
+ export const name = "imapflow";
3
+ export const version = "2.0.8";
4
+ export const homepage = "https://imapflow.com/";
@@ -403,21 +403,14 @@ export const searchCompiler = (connection, query) => {
403
403
  * @returns Binary tree structure
404
404
  */
405
405
  let genOrTree = (list) => {
406
- let group = false;
407
406
  let groups = [];
408
407
  // Group items in pairs
409
- list.forEach((entry, i) => {
410
- if (i % 2 === 0) {
411
- group = [entry];
412
- }
413
- else {
414
- group.push(entry);
415
- groups.push(group);
416
- group = false;
417
- }
418
- });
408
+ for (let i = 0; i + 1 < list.length; i += 2) {
409
+ groups.push([list[i], list[i + 1]]);
410
+ }
419
411
  // Handle odd number of items
420
- if (group && group.length) {
412
+ if (list.length % 2) {
413
+ let group = [list[list.length - 1]];
421
414
  while (group.length === 1 && Array.isArray(group[0])) {
422
415
  group = group[0];
423
416
  }
@@ -2,7 +2,7 @@ import type { Transform } from 'node:stream';
2
2
  import type { ImapFlow } from './imap-flow.js';
3
3
  import type { ConnectionErrorSite, ImapFlowError } from './errors.js';
4
4
  import type { ImapAttributeList, ImapAttributeNode, ImapResponse } from './handler/types.js';
5
- import type { FetchMessageObject, ListResponse, ListTreeResponse, MailboxObject, MessageEnvelopeObject, MessageStructureObject, StatusQuery } from './types.js';
5
+ import type { FetchMessageObject, ListResponse, ListTreeResponse, MailboxObject, MessageEnvelopeObject, MessageStructureObject, ImapFlowEvents, StatusQuery } from './types.js';
6
6
  export { AuthenticationFailure } from './errors.js';
7
7
  export declare const EXPANDED_RANGE_LIMIT = 16777216;
8
8
  export declare const MAX_UINT32_DIGITS = 10;
@@ -80,6 +80,13 @@ export declare function guardedPromise<T>(executor: (resolve: (value: T | Promis
80
80
  * @returns Rejected promise, with its rejection already observed
81
81
  */
82
82
  export declare function guardedReject(error: Error): Promise<never>;
83
+ /**
84
+ * Clears a timer that may already have been dropped. `clearTimeout()` accepts undefined but not
85
+ * null, and the connection nulls its timer fields once cleared, so every site clears through here.
86
+ *
87
+ * @param timer - Timer handle returned by setTimeout, or null/undefined when none is armed
88
+ */
89
+ export declare function clearTimer(timer: NodeJS.Timeout | null | undefined): void;
83
90
  /**
84
91
  * Detaches a background timer from the event loop, so it cannot keep the process alive on its
85
92
  * own. Applied to every background timer (auto-IDLE, IDLE restart, fallback polling, throttle
@@ -89,13 +96,6 @@ export declare function guardedReject(error: Error): Promise<never>;
89
96
  * @param timer - Timer handle returned by setTimeout
90
97
  * @returns The same timer handle
91
98
  */
92
- /**
93
- * Clears a timer that may already have been dropped. `clearTimeout()` accepts undefined but not
94
- * null, and the connection nulls its timer fields once cleared, so every site clears through here.
95
- *
96
- * @param timer - Timer handle returned by setTimeout, or null/undefined when none is armed
97
- */
98
- export declare function clearTimer(timer: NodeJS.Timeout | null | undefined): void;
99
99
  export declare function unrefTimer<T extends NodeJS.Timeout | null | undefined>(timer: T): T;
100
100
  /**
101
101
  * Logs a failure from background connection work at the level its cause deserves.
@@ -200,6 +200,25 @@ export declare function updateCapabilities(list: ImapAttributeList | null | unde
200
200
  * @returns Uppercase status code string, or false if not found
201
201
  */
202
202
  export declare function getStatusCode(response: ImapResponse | string | false | undefined): string | false;
203
+ /**
204
+ * Emits a state-change event from inside the command pipeline. A listener that throws must not
205
+ * abort the code that emitted it: select() emits before it releases the response, so the throw
206
+ * would leave the reader loop waiting forever, and close() would never get to emit 'close'. The
207
+ * error is logged instead, the same contract untagged handlers and the 'response' event get.
208
+ *
209
+ * @param connection - IMAP connection instance
210
+ * @param event - Event name
211
+ * @param args - Event arguments
212
+ */
213
+ export declare function emitSafe<K extends keyof ImapFlowEvents>(connection: ImapFlow, event: K, ...args: ImapFlowEvents[K]): void;
214
+ /**
215
+ * Collects the values of the TEXT tokens of a parsed response (the human-readable
216
+ * part of a status response, a greeting or a BYE).
217
+ *
218
+ * @param attributes - Attributes of a parsed IMAP response
219
+ * @returns Values of the TEXT tokens, in order
220
+ */
221
+ export declare function getTextValues(attributes: ImapAttributeList | undefined): string[];
203
222
  /**
204
223
  * Compiles an IMAP response object back into a human-readable string.
205
224
  *
@@ -214,6 +233,28 @@ export declare function getErrorText(response: ImapResponse | string | false | u
214
233
  * @returns The enhanced error with `serverResponseCode` and string `response`
215
234
  */
216
235
  export declare function enhanceCommandError(err: ImapFlowError): Promise<ImapFlowError>;
236
+ /**
237
+ * Enhances a failed command's error (see enhanceCommandError()) and logs it, the shared first
238
+ * step of every command's failure path. The caller decides whether to throw or return.
239
+ *
240
+ * @param connection - IMAP connection instance
241
+ * @param err - The command error
242
+ */
243
+ export declare function reportCommandError(connection: ImapFlow, err: ImapFlowError): Promise<void>;
244
+ /**
245
+ * Whether the session is authenticated, that is in the AUTHENTICATED or SELECTED state, which
246
+ * every mailbox-level command requires.
247
+ *
248
+ * @param connection - IMAP connection instance
249
+ */
250
+ export declare function isAuthenticatedState(connection: ImapFlow): boolean;
251
+ /**
252
+ * Returns the selected mailbox, or false when the connection is not in the SELECTED state.
253
+ * Message-level commands use it as their precondition, which also narrows the mailbox type.
254
+ *
255
+ * @param connection - IMAP connection instance
256
+ */
257
+ export declare function getSelectedMailbox(connection: ImapFlow): MailboxObject | false;
217
258
  /**
218
259
  * Converts a flat list of mailbox folders into a tree structure.
219
260
  *
@@ -305,14 +346,14 @@ export declare function toValidDate(value: unknown): Date | null;
305
346
  * @param value - Date to format
306
347
  * @returns Formatted date string, or undefined if invalid
307
348
  */
308
- export declare function formatDate(value: Date | string | null | undefined): string | undefined;
349
+ export declare function formatDate(value: unknown): string | undefined;
309
350
  /**
310
351
  * Formats a date value into IMAP date-time format (DD-Mon-YYYY HH:MM:SS +0000).
311
352
  *
312
353
  * @param value - Date to format
313
354
  * @returns Formatted date-time string, or undefined if invalid
314
355
  */
315
- export declare function formatDateTime(value: Date | string | null | undefined): string | undefined;
356
+ export declare function formatDateTime(value: unknown): string | undefined;
316
357
  /**
317
358
  * Normalizes a flag string. Returns false for non-settable flags (e.g. \Recent),
318
359
  * and capitalizes system flags properly.
package/dist/esm/tools.js CHANGED
@@ -158,15 +158,6 @@ export function guardedReject(error) {
158
158
  promise.catch(noop);
159
159
  return promise;
160
160
  }
161
- /**
162
- * Detaches a background timer from the event loop, so it cannot keep the process alive on its
163
- * own. Applied to every background timer (auto-IDLE, IDLE restart, fallback polling, throttle
164
- * back-off, held-lock diagnostics); connection and greeting deadlines are deliberately left
165
- * attached, because a caller is waiting for connect() to settle.
166
- *
167
- * @param timer - Timer handle returned by setTimeout
168
- * @returns The same timer handle
169
- */
170
161
  /**
171
162
  * Clears a timer that may already have been dropped. `clearTimeout()` accepts undefined but not
172
163
  * null, and the connection nulls its timer fields once cleared, so every site clears through here.
@@ -178,6 +169,15 @@ export function clearTimer(timer) {
178
169
  clearTimeout(timer);
179
170
  }
180
171
  }
172
+ /**
173
+ * Detaches a background timer from the event loop, so it cannot keep the process alive on its
174
+ * own. Applied to every background timer (auto-IDLE, IDLE restart, fallback polling, throttle
175
+ * back-off, held-lock diagnostics); connection and greeting deadlines are deliberately left
176
+ * attached, because a caller is waiting for connect() to settle.
177
+ *
178
+ * @param timer - Timer handle returned by setTimeout
179
+ * @returns The same timer handle
180
+ */
181
181
  export function unrefTimer(timer) {
182
182
  /* c8 ignore next 3 */ // node timers always expose unref(); the guard covers replaced globals in tests
183
183
  if (timer && typeof timer.unref === 'function') {
@@ -393,7 +393,7 @@ export function updateCapabilities(list) {
393
393
  }
394
394
  if (capability.startsWith('APPENDLIMIT=')) {
395
395
  let splitPos = capability.indexOf('=');
396
- map.set('APPENDLIMIT', parseUintValue(capability.substr(splitPos + 1)) || 0);
396
+ map.set('APPENDLIMIT', parseUintValue(capability.slice(splitPos + 1)) || 0);
397
397
  return;
398
398
  }
399
399
  map.set(capability, true);
@@ -419,6 +419,34 @@ export function getStatusCode(response) {
419
419
  ? response.attributes[0].section[0].value.toUpperCase().trim()
420
420
  : false;
421
421
  }
422
+ /**
423
+ * Emits a state-change event from inside the command pipeline. A listener that throws must not
424
+ * abort the code that emitted it: select() emits before it releases the response, so the throw
425
+ * would leave the reader loop waiting forever, and close() would never get to emit 'close'. The
426
+ * error is logged instead, the same contract untagged handlers and the 'response' event get.
427
+ *
428
+ * @param connection - IMAP connection instance
429
+ * @param event - Event name
430
+ * @param args - Event arguments
431
+ */
432
+ export function emitSafe(connection, event, ...args) {
433
+ try {
434
+ connection.emit(event, ...args);
435
+ }
436
+ catch (err) {
437
+ connection.log.warn({ msg: 'Event listener failed', event, err, cid: connection.id });
438
+ }
439
+ }
440
+ /**
441
+ * Collects the values of the TEXT tokens of a parsed response (the human-readable
442
+ * part of a status response, a greeting or a BYE).
443
+ *
444
+ * @param attributes - Attributes of a parsed IMAP response
445
+ * @returns Values of the TEXT tokens, in order
446
+ */
447
+ export function getTextValues(attributes) {
448
+ return (attributes || []).filter(attr => attr?.type === 'TEXT').map(attr => String(attr?.value ?? ''));
449
+ }
422
450
  /**
423
451
  * Compiles an IMAP response object back into a human-readable string.
424
452
  *
@@ -456,6 +484,35 @@ export async function enhanceCommandError(err) {
456
484
  err.response = await getErrorText(err.response);
457
485
  return err;
458
486
  }
487
+ /**
488
+ * Enhances a failed command's error (see enhanceCommandError()) and logs it, the shared first
489
+ * step of every command's failure path. The caller decides whether to throw or return.
490
+ *
491
+ * @param connection - IMAP connection instance
492
+ * @param err - The command error
493
+ */
494
+ export async function reportCommandError(connection, err) {
495
+ await enhanceCommandError(err);
496
+ connection.log.warn({ err, cid: connection.id });
497
+ }
498
+ /**
499
+ * Whether the session is authenticated, that is in the AUTHENTICATED or SELECTED state, which
500
+ * every mailbox-level command requires.
501
+ *
502
+ * @param connection - IMAP connection instance
503
+ */
504
+ export function isAuthenticatedState(connection) {
505
+ return connection.state === connection.states.AUTHENTICATED || connection.state === connection.states.SELECTED;
506
+ }
507
+ /**
508
+ * Returns the selected mailbox, or false when the connection is not in the SELECTED state.
509
+ * Message-level commands use it as their precondition, which also narrows the mailbox type.
510
+ *
511
+ * @param connection - IMAP connection instance
512
+ */
513
+ export function getSelectedMailbox(connection) {
514
+ return connection.state === connection.states.SELECTED && connection.mailbox ? connection.mailbox : false;
515
+ }
459
516
  /**
460
517
  * Converts a flat list of mailbox folders into a tree structure.
461
518
  *
@@ -943,7 +1000,7 @@ export function getStructuredParams(arr) {
943
1000
  // nothing to do here, does not seem like a continuation param
944
1001
  return;
945
1002
  }
946
- actualKey = key.substr(0, match.index).toLowerCase();
1003
+ actualKey = key.substring(0, match.index).toLowerCase();
947
1004
  nr = Number(match[2]) || 0;
948
1005
  if (isUnsafeKey(actualKey)) {
949
1006
  // A continuation key like "__proto__*0*" would group under "__proto__":
@@ -1195,7 +1252,7 @@ export function formatDate(value) {
1195
1252
  if (!date) {
1196
1253
  return;
1197
1254
  }
1198
- let dateParts = date.toISOString().substr(0, 10).split('-');
1255
+ let dateParts = date.toISOString().substring(0, 10).split('-');
1199
1256
  dateParts.reverse();
1200
1257
  let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
1201
1258
  dateParts[1] = months[Number(dateParts[1]) - 1];
@@ -1213,7 +1270,7 @@ export function formatDateTime(value) {
1213
1270
  return;
1214
1271
  }
1215
1272
  let dateStr = formatDate(date).replace(/^0/, ' '); //starts with date-day-fixed with leading 0 replaced by SP
1216
- let timeStr = date.toISOString().substr(11, 8);
1273
+ let timeStr = date.toISOString().substring(11, 19);
1217
1274
  return `${dateStr} ${timeStr} +0000`;
1218
1275
  }
1219
1276
  /**
@@ -1367,8 +1424,8 @@ export function expandRange(range) {
1367
1424
  }
1368
1425
  continue;
1369
1426
  }
1370
- let first = Number(entry.substr(0, colon));
1371
- let second = Number(entry.substr(colon + 1));
1427
+ let first = Number(entry.substring(0, colon));
1428
+ let second = Number(entry.slice(colon + 1));
1372
1429
  if (!isValidSequenceValue(first) || !isValidSequenceValue(second)) {
1373
1430
  continue;
1374
1431
  }
@@ -207,26 +207,32 @@ export interface IdInfoObject {
207
207
  'support-url'?: string | false | undefined;
208
208
  /** Date program was released */
209
209
  date?: Date | string | false | undefined;
210
- [key: string]: any;
210
+ /** Any other field, sent as its string form */
211
+ [key: string]: unknown;
212
+ }
213
+ /**
214
+ * Usage and limit of one quota resource. The `storage` values are bytes (the wire format is
215
+ * kilobytes), the other resources are counts
216
+ */
217
+ export interface QuotaResource {
218
+ /** Current usage, missing when the server did not send a usable number */
219
+ usage?: number | undefined;
220
+ /** The limit, missing when the server did not send a usable number */
221
+ limit?: number | undefined;
222
+ /** Usage as a percentage of the limit, e.g. "50%", set once a limit above zero is known */
223
+ status?: string | undefined;
211
224
  }
212
225
  export interface QuotaResponse {
213
226
  /** Mailbox path this quota applies to */
214
227
  path: string;
215
- /** Storage quota if provided by server */
216
- storage?: {
217
- /** Used storage in bytes */
218
- used: number;
219
- /** Total storage available */
220
- limit: number;
221
- } | undefined;
222
- /** Message count quota if provided by server */
223
- messages?: {
224
- /** Stored messages */
225
- used: number;
226
- /** Maximum messages allowed */
227
- limit: number;
228
- } | undefined;
229
- [resource: string]: any;
228
+ /** The quota root the server reported for the mailbox, if any */
229
+ quotaRoot?: string | undefined;
230
+ /** The STORAGE resource, if the server reports one */
231
+ storage?: QuotaResource | undefined;
232
+ /** The MESSAGE resource, if the server reports one */
233
+ message?: QuotaResource | undefined;
234
+ /** Any other resource the server reports, under its lowercased name (e.g. "mailbox") */
235
+ [resource: string]: QuotaResource | string | undefined;
230
236
  }
231
237
  /**
232
238
  * Status data items to request with `status()` or the `statusQuery` listing option
@@ -616,6 +622,14 @@ export interface DownloadObject {
616
622
  /** Streamed content */
617
623
  content: Readable;
618
624
  }
625
+ /**
626
+ * What `download()` resolves with when there is nothing to download: no mailbox is selected, or
627
+ * the message or part was not found. Check `content` before using the result.
628
+ */
629
+ export interface DownloadNotFound {
630
+ meta?: undefined;
631
+ content?: undefined;
632
+ }
619
633
  export interface DownloadOptions {
620
634
  /** If true then uses UID number instead of sequence number for `range` */
621
635
  uid?: boolean | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imapflow",
3
- "version": "2.0.7",
3
+ "version": "2.0.8",
4
4
  "description": "IMAP Client for Node",
5
5
  "type": "module",
6
6
  "main": "./dist/cjs/imap-flow.js",
@@ -47,7 +47,7 @@
47
47
  "test:rev2": "bash test/integration/run-rev2-tests.sh",
48
48
  "format": "prettier --write \"**/*.{js,cjs,ts,json,md,yml,yaml}\"",
49
49
  "format:check": "prettier --check \"**/*.{js,cjs,ts,json,md,yml,yaml}\"",
50
- "lint": "eslint . && npm run typecheck",
50
+ "lint": "npm run typecheck && eslint .",
51
51
  "lint:fix": "eslint . --fix",
52
52
  "prepare": "npm run build",
53
53
  "update": "rm -rf node_modules package-lock.json && ncu -u && npm install"
@@ -73,12 +73,12 @@
73
73
  "eslint": "10.11.0",
74
74
  "eslint-config-prettier": "10.1.8",
75
75
  "globals": "17.12.0",
76
- "prettier": "3.9.8",
76
+ "prettier": "3.9.9",
77
77
  "tsx": "4.23.15",
78
78
  "types-node-legacy": "npm:@types/node@20.0.0",
79
79
  "typescript": "6.0.3",
80
80
  "typescript-eslint": "8.70.1",
81
- "wrangler": "4.136.3"
81
+ "wrangler": "4.141.0"
82
82
  },
83
83
  "dependencies": {
84
84
  "@zone-eu/mailsplit": "5.4.17",