imapflow 2.0.7 → 2.1.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 (82) hide show
  1. package/CHANGELOG.md +29 -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 +22 -18
  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 +12 -9
  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 +50 -1
  27. package/dist/cjs/errors.js +53 -1
  28. package/dist/cjs/handler/imap-compiler.js +1 -1
  29. package/dist/cjs/handler/imap-stream.d.ts +13 -2
  30. package/dist/cjs/handler/imap-stream.js +51 -30
  31. package/dist/cjs/handler/parser-instance.js +2 -2
  32. package/dist/cjs/handler/token-parser.js +15 -9
  33. package/dist/cjs/imap-flow.d.ts +30 -84
  34. package/dist/cjs/imap-flow.js +282 -734
  35. package/dist/cjs/jp-decoder.js +1 -1
  36. package/dist/cjs/package-info.d.ts +1 -1
  37. package/dist/cjs/package-info.js +3 -3
  38. package/dist/cjs/search-compiler.js +5 -12
  39. package/dist/cjs/tools.d.ts +52 -11
  40. package/dist/cjs/tools.js +86 -23
  41. package/dist/cjs/types.d.ts +30 -16
  42. package/dist/esm/commands/append.js +13 -13
  43. package/dist/esm/commands/authenticate.d.ts +3 -8
  44. package/dist/esm/commands/close.js +2 -1
  45. package/dist/esm/commands/copy.js +5 -5
  46. package/dist/esm/commands/create.js +3 -4
  47. package/dist/esm/commands/delete.js +5 -5
  48. package/dist/esm/commands/expunge.js +9 -6
  49. package/dist/esm/commands/fetch.js +13 -11
  50. package/dist/esm/commands/idle.js +7 -3
  51. package/dist/esm/commands/list.js +22 -18
  52. package/dist/esm/commands/move.js +12 -7
  53. package/dist/esm/commands/namespace.js +2 -2
  54. package/dist/esm/commands/quota.js +11 -10
  55. package/dist/esm/commands/rename.js +5 -5
  56. package/dist/esm/commands/search.js +8 -9
  57. package/dist/esm/commands/select.js +13 -10
  58. package/dist/esm/commands/status.js +12 -12
  59. package/dist/esm/commands/store.js +6 -6
  60. package/dist/esm/commands/subscribe.js +2 -17
  61. package/dist/esm/commands/subscription.d.ts +10 -0
  62. package/dist/esm/commands/subscription.js +26 -0
  63. package/dist/esm/commands/unsubscribe.js +2 -17
  64. package/dist/esm/download.d.ts +22 -0
  65. package/dist/esm/download.js +581 -0
  66. package/dist/esm/errors.d.ts +50 -1
  67. package/dist/esm/errors.js +52 -0
  68. package/dist/esm/handler/imap-compiler.js +1 -1
  69. package/dist/esm/handler/imap-stream.d.ts +13 -2
  70. package/dist/esm/handler/imap-stream.js +51 -30
  71. package/dist/esm/handler/parser-instance.js +2 -2
  72. package/dist/esm/handler/token-parser.js +15 -9
  73. package/dist/esm/imap-flow.d.ts +30 -84
  74. package/dist/esm/imap-flow.js +282 -735
  75. package/dist/esm/jp-decoder.js +1 -1
  76. package/dist/esm/package-info.d.ts +1 -1
  77. package/dist/esm/package-info.js +3 -3
  78. package/dist/esm/search-compiler.js +5 -12
  79. package/dist/esm/tools.d.ts +52 -11
  80. package/dist/esm/tools.js +79 -21
  81. package/dist/esm/types.d.ts +30 -16
  82. package/package.json +4 -4
@@ -1,11 +1,58 @@
1
1
  import type { ImapResponse } from './handler/types.js';
2
+ /**
3
+ * The `code` values ImapFlow sets on the errors it raises, so they can be matched without
4
+ * string literals: `if (err.code === ImapFlowErrorCode.NoConnection)`.
5
+ *
6
+ * Parser failures use `ParserError` followed by a number (`ParserError11`) and are not listed
7
+ * one by one, test them with `err.code?.startsWith('ParserError')`. Errors from the socket, TLS
8
+ * or DNS layer pass through with Node's own code (`ECONNREFUSED`, `ENOTFOUND`, ...).
9
+ */
10
+ export declare const ImapFlowErrorCode: {
11
+ readonly NoConnection: "NoConnection";
12
+ readonly EConnectionClosed: "EConnectionClosed";
13
+ readonly StateLogout: "StateLogout";
14
+ readonly ClosedAfterConnectText: "ClosedAfterConnectText";
15
+ readonly ClosedAfterConnectTLS: "ClosedAfterConnectTLS";
16
+ readonly CONNECT_TIMEOUT: "CONNECT_TIMEOUT";
17
+ readonly GREETING_TIMEOUT: "GREETING_TIMEOUT";
18
+ readonly UPGRADE_TIMEOUT: "UPGRADE_TIMEOUT";
19
+ readonly ETIMEOUT: "ETIMEOUT";
20
+ readonly LockTimeout: "LockTimeout";
21
+ readonly ETHROTTLE: "ETHROTTLE";
22
+ readonly UnexpectedTag: "UnexpectedTag";
23
+ readonly InvalidResponse: "InvalidResponse";
24
+ readonly ResponseProcessingFailed: "ResponseProcessingFailed";
25
+ readonly STARTTLS_INJECTION: "STARTTLS_INJECTION";
26
+ readonly COMPRESS_TRAILING_DATA: "COMPRESS_TRAILING_DATA";
27
+ readonly PollFailed: "PollFailed";
28
+ readonly NotFound: "NotFound";
29
+ readonly MissingServerExtension: "MissingServerExtension";
30
+ readonly ParserError: "ParserError";
31
+ readonly ParserErrorExchange: "ParserErrorExchange";
32
+ readonly MAX_IMAP_NESTING_REACHED: "MAX_IMAP_NESTING_REACHED";
33
+ readonly LineTooLarge: "LineTooLarge";
34
+ readonly LiteralTooLarge: "LiteralTooLarge";
35
+ readonly ResponseTooLarge: "ResponseTooLarge";
36
+ readonly InvalidStringValue: "InvalidStringValue";
37
+ readonly InvalidTokenValue: "InvalidTokenValue";
38
+ readonly InvalidTextValue: "InvalidTextValue";
39
+ readonly InvalidSequenceSet: "InvalidSequenceSet";
40
+ readonly DownloadOverflow: "DownloadOverflow";
41
+ readonly DownloadIncomplete: "DownloadIncomplete";
42
+ readonly ProxyError: "ProxyError";
43
+ readonly EPROXY: "EPROXY";
44
+ readonly UnsupportedProxyAddress: "UnsupportedProxyAddress";
45
+ readonly ERR_INVALID_URL: "ERR_INVALID_URL";
46
+ };
47
+ /** One of the {@link ImapFlowErrorCode} values */
48
+ export type ImapFlowErrorCode = (typeof ImapFlowErrorCode)[keyof typeof ImapFlowErrorCode];
2
49
  /**
3
50
  * An Error raised by ImapFlow, with the extra properties the library attaches to describe
4
51
  * the failure. Every property is optional: which ones are present depends on where the
5
52
  * error came from.
6
53
  */
7
54
  export interface ImapFlowError extends Error {
8
- /** Error code, e.g. 'NoConnection', 'ETIMEOUT', 'LockTimeout' or a parser error code */
55
+ /** Error code, one of {@link ImapFlowErrorCode}, a parser error code or a code from Node */
9
56
  code?: string | undefined;
10
57
  /** Connection id the error belongs to */
11
58
  cid?: string | undefined;
@@ -33,6 +80,8 @@ export interface ImapFlowError extends Error {
33
80
  tlsFailed?: boolean | undefined;
34
81
  /** Server suggested back-off in milliseconds for an ETHROTTLE error */
35
82
  throttleReset?: number | undefined;
83
+ /** Milliseconds of the ETHROTTLE back-off the connection already waited before rejecting */
84
+ throttleWaited?: number | undefined;
36
85
  /** Additional details, e.g. the timeouts that applied */
37
86
  details?: {
38
87
  [key: string]: any;
@@ -1,3 +1,55 @@
1
+ /**
2
+ * The `code` values ImapFlow sets on the errors it raises, so they can be matched without
3
+ * string literals: `if (err.code === ImapFlowErrorCode.NoConnection)`.
4
+ *
5
+ * Parser failures use `ParserError` followed by a number (`ParserError11`) and are not listed
6
+ * one by one, test them with `err.code?.startsWith('ParserError')`. Errors from the socket, TLS
7
+ * or DNS layer pass through with Node's own code (`ECONNREFUSED`, `ENOTFOUND`, ...).
8
+ */
9
+ export const ImapFlowErrorCode = {
10
+ // the connection is gone, the command was not (or can no longer be) completed
11
+ NoConnection: 'NoConnection',
12
+ EConnectionClosed: 'EConnectionClosed',
13
+ StateLogout: 'StateLogout',
14
+ ClosedAfterConnectText: 'ClosedAfterConnectText',
15
+ ClosedAfterConnectTLS: 'ClosedAfterConnectTLS',
16
+ // timeouts
17
+ CONNECT_TIMEOUT: 'CONNECT_TIMEOUT',
18
+ GREETING_TIMEOUT: 'GREETING_TIMEOUT',
19
+ UPGRADE_TIMEOUT: 'UPGRADE_TIMEOUT',
20
+ ETIMEOUT: 'ETIMEOUT',
21
+ LockTimeout: 'LockTimeout',
22
+ // the server
23
+ ETHROTTLE: 'ETHROTTLE',
24
+ UnexpectedTag: 'UnexpectedTag',
25
+ InvalidResponse: 'InvalidResponse',
26
+ ResponseProcessingFailed: 'ResponseProcessingFailed',
27
+ STARTTLS_INJECTION: 'STARTTLS_INJECTION',
28
+ COMPRESS_TRAILING_DATA: 'COMPRESS_TRAILING_DATA',
29
+ PollFailed: 'PollFailed',
30
+ NotFound: 'NotFound',
31
+ MissingServerExtension: 'MissingServerExtension',
32
+ // response parsing and size limits
33
+ ParserError: 'ParserError',
34
+ ParserErrorExchange: 'ParserErrorExchange',
35
+ MAX_IMAP_NESTING_REACHED: 'MAX_IMAP_NESTING_REACHED',
36
+ LineTooLarge: 'LineTooLarge',
37
+ LiteralTooLarge: 'LiteralTooLarge',
38
+ ResponseTooLarge: 'ResponseTooLarge',
39
+ // invalid values in a command
40
+ InvalidStringValue: 'InvalidStringValue',
41
+ InvalidTokenValue: 'InvalidTokenValue',
42
+ InvalidTextValue: 'InvalidTextValue',
43
+ InvalidSequenceSet: 'InvalidSequenceSet',
44
+ // download()
45
+ DownloadOverflow: 'DownloadOverflow',
46
+ DownloadIncomplete: 'DownloadIncomplete',
47
+ // proxy connections
48
+ ProxyError: 'ProxyError',
49
+ EPROXY: 'EPROXY',
50
+ UnsupportedProxyAddress: 'UnsupportedProxyAddress',
51
+ ERR_INVALID_URL: 'ERR_INVALID_URL'
52
+ };
1
53
  /**
2
54
  * Error subclass thrown when IMAP authentication fails.
3
55
  */
@@ -238,7 +238,7 @@ async function compiler(response, options) {
238
238
  // Strip a leading backslash before checking (system flags like \Seen start with '\').
239
239
  // If any character fails verification, fall back to an IMAP quoted string
240
240
  // (JSON.stringify is used only for log output, where values are display-escaped).
241
- if (node.value === '' || imapFormalSyntax.verify(val.charAt(0) === '\\' ? val.substr(1) : val, imapFormalSyntax['ATOM-CHAR']()) >= 0) {
241
+ if (node.value === '' || imapFormalSyntax.verify(val.charAt(0) === '\\' ? val.slice(1) : val, imapFormalSyntax['ATOM-CHAR']()) >= 0) {
242
242
  val = isLogging ? JSON.stringify(val) : quoteString(val);
243
243
  }
244
244
  resp.push(emitEntry(val));
@@ -145,13 +145,24 @@ export declare class ImapStream extends Transform {
145
145
  * pushed downstream as a readable object.
146
146
  *
147
147
  * @param chunk - The raw data chunk to process.
148
- * @param startPos - The byte offset within the chunk to start processing from.
149
148
  */
150
- processInputChunk(chunk: Buffer, startPos?: number | undefined): Promise<void>;
149
+ processInputChunk(chunk: Buffer): Promise<void>;
150
+ /**
151
+ * Processes the chunk from `startPos` until the parser state changes or the chunk ends.
152
+ *
153
+ * @returns The offset to continue from after a state switch, or `null` when done with the chunk.
154
+ */
155
+ processChunkSegment(chunk: Buffer, startPos: number): Promise<number | null>;
151
156
  /**
152
157
  * Drains the input queue by processing each queued chunk sequentially.
153
158
  * Yields to the event loop every 10 chunks to prevent CPU blocking on
154
159
  * large bursts of incoming data.
160
+ *
161
+ * The `processingInput` guard is cleared in the same synchronous step that finds the queue
162
+ * empty. Clearing it later (in a promise handler) leaves a gap of a few microtasks where a
163
+ * chunk delivered by the writable side is queued but no loop is started for it, so its
164
+ * transform callback is never called and the socket is never read again. Workers deliver
165
+ * the next chunk inside that gap.
155
166
  */
156
167
  processInput(): Promise<void>;
157
168
  /**
@@ -217,12 +217,23 @@ export class ImapStream extends Transform {
217
217
  * pushed downstream as a readable object.
218
218
  *
219
219
  * @param chunk - The raw data chunk to process.
220
- * @param startPos - The byte offset within the chunk to start processing from.
221
220
  */
222
- async processInputChunk(chunk, startPos) {
223
- startPos = startPos || 0;
221
+ async processInputChunk(chunk) {
222
+ // Every state switch hands back the offset to resume from instead of recursing, so a
223
+ // chunk packed with thousands of small literals can not exhaust the call stack
224
+ let nextPos = 0;
225
+ while (nextPos !== null) {
226
+ nextPos = await this.processChunkSegment(chunk, nextPos);
227
+ }
228
+ }
229
+ /**
230
+ * Processes the chunk from `startPos` until the parser state changes or the chunk ends.
231
+ *
232
+ * @returns The offset to continue from after a state switch, or `null` when done with the chunk.
233
+ */
234
+ async processChunkSegment(chunk, startPos) {
224
235
  if (this.destroyed || startPos >= chunk.length) {
225
- return;
236
+ return null;
226
237
  }
227
238
  switch (this.state) {
228
239
  case LINE: {
@@ -232,9 +243,9 @@ export class ImapStream extends Transform {
232
243
  // line end found. Measure the completed line (terminator included) before
233
244
  // concatenating or emitting anything, so the cap does not depend on where
234
245
  // TCP chunk boundaries happen to fall.
235
- let segment = chunk.slice(lineStart, i + 1);
246
+ let segment = chunk.subarray(lineStart, i + 1);
236
247
  if (!this.checkLineLength(this.lineBytes + segment.length)) {
237
- return;
248
+ return null;
238
249
  }
239
250
  this.lineBuffer.push(segment);
240
251
  lineStart = i + 1;
@@ -246,18 +257,18 @@ export class ImapStream extends Transform {
246
257
  // would otherwise be emitted as part of the rejected command.
247
258
  let isLiteralMarker = this.checkLiteralMarker(line);
248
259
  if (this.destroyed) {
249
- return;
260
+ return null;
250
261
  }
251
262
  // Count the line itself and, for a literal marker, the declared
252
263
  // literal bytes against the cumulative per-response budget, so a
253
264
  // response assembled from many tokens stays bounded as a whole
254
265
  if (!this.checkResponseSize(line.length + (isLiteralMarker ? this.literalWaiting : 0))) {
255
- return;
266
+ return null;
256
267
  }
257
268
  this.inputBuffer.push(line);
258
269
  if (isLiteralMarker) {
259
270
  // switch into literal mode and start over
260
- return await this.processInputChunk(chunk, lineStart);
271
+ return lineStart;
261
272
  }
262
273
  // reached end of command input, emit it
263
274
  let payload = this.inputBuffer.length === 1 ? this.inputBuffer[0] : Buffer.concat(this.inputBuffer);
@@ -272,7 +283,7 @@ export class ImapStream extends Transform {
272
283
  if (end > 0 && payload[end - 1] === CR) {
273
284
  end--;
274
285
  }
275
- payload = payload.slice(0, end);
286
+ payload = payload.subarray(0, end);
276
287
  }
277
288
  if (payload.length) {
278
289
  // Whether more buffered input already followed this command on the
@@ -291,7 +302,7 @@ export class ImapStream extends Transform {
291
302
  });
292
303
  this.pendingPush = null;
293
304
  if (this.destroyed) {
294
- return;
305
+ return null;
295
306
  }
296
307
  }
297
308
  }
@@ -300,14 +311,14 @@ export class ImapStream extends Transform {
300
311
  if (lineStart < chunk.length) {
301
312
  // No line terminator was found in the remaining bytes; carry the tail over to
302
313
  // the next chunk after measuring the line it belongs to.
303
- let tail = chunk.slice(lineStart);
314
+ let tail = chunk.subarray(lineStart);
304
315
  // The response counter is only committed when a line completes, so an
305
316
  // in-progress line is measured against the remaining budget separately.
306
317
  // Without this a response cap lowered to bound parser memory buys nothing
307
318
  // while a server streams a line that never terminates - only the much
308
319
  // larger line cap would hold it back.
309
320
  if (!this.checkLineLength(this.lineBytes + tail.length) || !this.checkResponseSize(this.lineBytes + tail.length, true)) {
310
- return;
321
+ return null;
311
322
  }
312
323
  this.lineBytes += tail.length;
313
324
  this.lineBuffer.push(tail);
@@ -317,7 +328,7 @@ export class ImapStream extends Transform {
317
328
  case LITERAL: {
318
329
  const remainingInChunk = chunk.length - startPos;
319
330
  const bytesToRead = Math.min(remainingInChunk, this.literalWaiting);
320
- const partial = startPos === 0 && bytesToRead === chunk.length ? chunk : chunk.slice(startPos, startPos + bytesToRead);
331
+ const partial = startPos === 0 && bytesToRead === chunk.length ? chunk : chunk.subarray(startPos, startPos + bytesToRead);
321
332
  this.literalBuffer.push(partial);
322
333
  this.literalWaiting -= bytesToRead;
323
334
  if (this.literalWaiting === 0) {
@@ -325,33 +336,45 @@ export class ImapStream extends Transform {
325
336
  this.literalBuffer = [];
326
337
  this.state = LINE;
327
338
  if (remainingInChunk > bytesToRead) {
328
- return await this.processInputChunk(chunk, startPos + bytesToRead);
339
+ return startPos + bytesToRead;
329
340
  }
330
341
  }
331
342
  break;
332
343
  }
333
344
  }
345
+ return null;
334
346
  }
335
347
  /**
336
348
  * Drains the input queue by processing each queued chunk sequentially.
337
349
  * Yields to the event loop every 10 chunks to prevent CPU blocking on
338
350
  * large bursts of incoming data.
351
+ *
352
+ * The `processingInput` guard is cleared in the same synchronous step that finds the queue
353
+ * empty. Clearing it later (in a promise handler) leaves a gap of a few microtasks where a
354
+ * chunk delivered by the writable side is queued but no loop is started for it, so its
355
+ * transform callback is never called and the socket is never read again. Workers deliver
356
+ * the next chunk inside that gap.
339
357
  */
340
358
  async processInput() {
341
- let data;
342
- let processedCount = 0;
343
- while (!this.destroyed && (data = this.inputQueue.shift())) {
344
- this.activeInput = data;
345
- await this.processInputChunk(data.chunk);
346
- this.activeInput = null;
347
- // mark chunk as processed
348
- this.releaseInput(data);
349
- // Yield to event loop every 10 chunks to prevent CPU blocking
350
- processedCount++;
351
- if (processedCount % 10 === 0) {
352
- await new Promise(resolve => setImmediate(resolve));
359
+ try {
360
+ let data;
361
+ let processedCount = 0;
362
+ while (!this.destroyed && (data = this.inputQueue.shift())) {
363
+ this.activeInput = data;
364
+ await this.processInputChunk(data.chunk);
365
+ this.activeInput = null;
366
+ // mark chunk as processed
367
+ this.releaseInput(data);
368
+ // Yield to event loop every 10 chunks to prevent CPU blocking
369
+ processedCount++;
370
+ if (processedCount % 10 === 0) {
371
+ await new Promise(resolve => setImmediate(resolve));
372
+ }
353
373
  }
354
374
  }
375
+ finally {
376
+ this.processingInput = false;
377
+ }
355
378
  }
356
379
  /**
357
380
  * Transform stream implementation. Receives raw data chunks from the writable side,
@@ -391,9 +414,7 @@ export class ImapStream extends Transform {
391
414
  this.inputQueue.push({ chunk, next });
392
415
  if (!this.processingInput) {
393
416
  this.processingInput = true;
394
- this.processInput()
395
- .catch(err => this.failStream(err))
396
- .finally(() => (this.processingInput = false));
417
+ this.processInput().catch(err => this.failStream(err));
397
418
  }
398
419
  }
399
420
  /**
@@ -160,7 +160,7 @@ export class ParserInstance {
160
160
  throw error;
161
161
  }
162
162
  this.pos += match[0].length;
163
- this.remainder = this.remainder.substr(match[0].length);
163
+ this.remainder = this.remainder.slice(match[0].length);
164
164
  return element;
165
165
  }
166
166
  /**
@@ -187,7 +187,7 @@ export class ParserInstance {
187
187
  throw error;
188
188
  }
189
189
  this.pos++;
190
- this.remainder = this.remainder.substr(1);
190
+ this.remainder = this.remainder.slice(1);
191
191
  }
192
192
  /**
193
193
  * Parses the remaining input as IMAP attributes using the TokenParser.
@@ -310,7 +310,7 @@ export class TokenParser {
310
310
  // IMAP URL (e.g., imap://user@host/mailbox) which contains characters
311
311
  // that would break normal ATOM parsing (colons, slashes, etc.).
312
312
  // We handle this by consuming everything up to ']' as a single ATOM value.
313
- if (this.str.substr(i + 1, 9).toUpperCase() === 'REFERRAL ') {
313
+ if (this.str.substring(i + 1, i + 10).toUpperCase() === 'REFERRAL ') {
314
314
  // create the REFERRAL atom
315
315
  this.currentNode = this.createNode(this.currentNode, this.pos + i + 1);
316
316
  this.currentNode.type = 'ATOM';
@@ -321,15 +321,21 @@ export class TokenParser {
321
321
  this.currentNode = this.createNode(this.currentNode, this.pos + i + 10);
322
322
  // just call this an ATOM, even though IMAPURL might be more correct
323
323
  this.currentNode.type = 'ATOM';
324
- // jump i to the ']'
325
- i = this.str.indexOf(']', i + 10);
326
- if (i < 0) {
327
- // Malformed REFERRAL with no closing ']'. Consume the rest
328
- // of the string (there is no ']' to exclude) instead of
329
- // computing a negative-index substring, which would yield
330
- // garbage.
331
- i = this.str.length;
324
+ // jump i to the ']' that closes the section. The URL itself can
325
+ // hold a bracketed IPv6 host (imap://[::1]/INBOX), so brackets
326
+ // opened inside the URL are matched before the closing one.
327
+ let depth = 0;
328
+ for (i = i + 10; i < this.str.length; i++) {
329
+ let urlChr = this.str.charAt(i);
330
+ if (urlChr === '[') {
331
+ depth++;
332
+ }
333
+ else if (urlChr === ']' && depth-- === 0) {
334
+ break;
335
+ }
332
336
  }
337
+ // A malformed REFERRAL with no closing ']' leaves i at the end of
338
+ // the string, so the URL takes the rest of it.
333
339
  this.currentNode.endPos = this.pos + i - 1;
334
340
  this.currentNode.value = this.str.substring(this.currentNode.startPos - this.pos, this.currentNode.endPos - this.pos + 1);
335
341
  this.currentNode = this.currentNode.parentNode;
@@ -6,10 +6,10 @@ import net from 'node:net';
6
6
  import { EventEmitter } from 'node:events';
7
7
  import { PassThrough, type Readable } from 'node:stream';
8
8
  import { AuthenticationFailure } from './errors.js';
9
- import type { AppendResponseObject, CopyResponseObject, DownloadManyOptions, DownloadManyResult, DownloadObject, DownloadOptions, ESearchResult, FetchMessageObject, FetchOptions, FetchQueryObject, IdInfoObject, ImapFlowEvents, ImapFlowOptions, InternalLogger, ListOptions, ListResponse, ListTreeResponse, MailboxCreateResponse, MailboxDeleteResponse, MailboxLockObject, MailboxLockOptions, MailboxObject, MailboxOpenOptions, MailboxRenameResponse, MessageRange, MessageRangeOptions, NamespaceObject, NamespacesObject, QuotaResponse, SearchObject, SearchOptions, SearchReturnOption, SequenceString, StatusObject, StatusQuery, StoreOptions, TlsInfo } from './types.js';
9
+ import type { AppendResponseObject, CopyResponseObject, DownloadManyOptions, DownloadManyResult, DownloadObject, DownloadNotFound, DownloadOptions, ESearchResult, FetchMessageObject, FetchOptions, FetchQueryObject, IdInfoObject, ImapFlowEvents, ImapFlowOptions, InternalLogger, ListOptions, ListResponse, ListTreeResponse, MailboxCreateResponse, MailboxDeleteResponse, MailboxLockObject, MailboxLockOptions, MailboxObject, MailboxOpenOptions, MailboxRenameResponse, MessageRange, MessageRangeOptions, NamespaceObject, NamespacesObject, QuotaResponse, SearchObject, SearchOptions, SearchReturnOption, SequenceString, StatusObject, StatusQuery, StoreOptions, TlsInfo } from './types.js';
10
10
  export type * from './types.js';
11
11
  export type { ImapFlowError } from './errors.js';
12
- export { AuthenticationFailure } from './errors.js';
12
+ export { AuthenticationFailure, ImapFlowErrorCode } from './errors.js';
13
13
  export type { ImapAttribute, ImapAttributeList, ImapAttributeNode, ImapResponse } from './handler/types.js';
14
14
  declare const stateValues: {
15
15
  readonly NOT_AUTHENTICATED: 1;
@@ -61,6 +61,17 @@ export interface ImapFlow {
61
61
  prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
62
62
  emit<K extends keyof ImapFlowEvents>(event: K, ...args: ImapFlowEvents[K]): boolean;
63
63
  emit(event: string | symbol, ...args: any[]): boolean;
64
+ /**
65
+ * Logs out and closes the connection when the scope of an `await using` declaration ends.
66
+ * Never throws, the connection is closed whether LOGOUT succeeds or not. Only present on
67
+ * runtimes that define `Symbol.asyncDispose` (Node.js 20.4 and newer).
68
+ *
69
+ * @example
70
+ * await using client = new ImapFlow({...});
71
+ * await client.connect();
72
+ * // client.logout() runs automatically when the scope exits, even on a throw
73
+ */
74
+ [Symbol.asyncDispose](): Promise<void>;
64
75
  }
65
76
  /**
66
77
  * IMAP client class for accessing IMAP mailboxes
@@ -135,6 +146,9 @@ export declare class ImapFlow extends EventEmitter {
135
146
  byeReason: string | undefined;
136
147
  /** Negotiated TLS session details, `false` for a cleartext connection */
137
148
  tls: TlsInfo | false | undefined;
149
+ /**
150
+ * Creates a client for one IMAP connection. Nothing is sent before `connect()` is called
151
+ */
138
152
  constructor(options?: ImapFlowOptions | undefined);
139
153
  /**
140
154
  * Returns byte counters for the current connection.
@@ -315,20 +329,20 @@ export declare class ImapFlow extends EventEmitter {
315
329
  *
316
330
  * @param path mailbox path to check for (unicode string). If value is an array then it is joined using current delimiter symbols. Namespace prefix is added automatically if required.
317
331
  * @param query defines requested status items
318
- * @returns status of the indicated mailbox
332
+ * @returns status of the indicated mailbox, or `false` if the server rejected the request
319
333
  *
320
334
  * @example
321
335
  * let status = await client.status('INBOX', {unseen: true});
322
336
  * console.log(status.unseen);
323
337
  * // 123
324
338
  */
325
- status(path: string | string[], query: StatusQuery): Promise<StatusObject>;
339
+ status(path: string | string[], query: StatusQuery): Promise<StatusObject | false>;
326
340
  /**
327
341
  * Starts listening for new or deleted messages from the currently opened mailbox. Only required if `disableAutoIdle` is set to `true`
328
342
  * otherwise IDLE is started by default on connection inactivity. NB! If `idle()` is called manually then it does not
329
343
  * return until IDLE is finished which means you would have to call some other command out of scope.
330
344
  *
331
- * @returns Did the operation succeed or not
345
+ * @returns `false` if IDLE failed, `undefined` otherwise
332
346
  *
333
347
  * @example
334
348
  * let mailbox = await client.mailboxOpen('INBOX');
@@ -470,6 +484,10 @@ export declare class ImapFlow extends EventEmitter {
470
484
  * ]});
471
485
  */
472
486
  search(query: SearchObject, options?: MessageRangeOptions | undefined): Promise<number[] | false | undefined>;
487
+ /**
488
+ * Search with `returnOptions` set: an ESEARCH result object from a server that supports
489
+ * ESEARCH, the plain list of numbers otherwise
490
+ */
473
491
  search(query: SearchObject, options: SearchOptions & {
474
492
  returnOptions: SearchReturnOption[];
475
493
  }): Promise<ESearchResult | number[] | false | undefined>;
@@ -540,10 +558,12 @@ export declare class ImapFlow extends EventEmitter {
540
558
  * @example
541
559
  * let mailbox = await client.mailboxOpen('INBOX');
542
560
  * // download body part nr '1.2' from latest message
543
- * let {meta, content} = await client.download('*', '1.2');
544
- * content.pipe(fs.createWriteStream(meta.filename));
561
+ * let download = await client.download('*', '1.2');
562
+ * if (download.content) {
563
+ * download.content.pipe(fs.createWriteStream(download.meta.filename));
564
+ * }
545
565
  */
546
- download(range: SequenceString, part?: string | undefined, options?: DownloadOptions | undefined): Promise<DownloadObject>;
566
+ download(range: SequenceString, part?: string | undefined, options?: DownloadOptions | undefined): Promise<DownloadObject | DownloadNotFound>;
547
567
  /**
548
568
  * Fetch multiple attachments as Buffer values
549
569
  *
@@ -583,7 +603,8 @@ export declare class ImapFlow extends EventEmitter {
583
603
  getMailboxLock(path: string | string[], options?: MailboxLockOptions | undefined): Promise<MailboxLockObject>;
584
604
  /**
585
605
  * Detaches sockets from the IMAP pipeline. Useful for upgrading the connection
586
- * (e.g., STARTTLS) or transferring socket ownership.
606
+ * (e.g., STARTTLS) or transferring socket ownership. Call it while the connection is not
607
+ * idling: an IDLE in progress is not broken first, so the server still expects `DONE`.
587
608
  *
588
609
  * @returns Socket objects: `readSocket` is the read socket (inflated socket if compression is enabled, raw socket otherwise),
589
610
  * `writeSocket` the write socket and `socket` the raw underlying socket (same as readSocket/writeSocket when compression is disabled)
@@ -594,81 +615,6 @@ export declare class ImapFlow extends EventEmitter {
594
615
  socket: ImapSocket;
595
616
  };
596
617
  }
597
- /**
598
- * Connection close event. **NB!** ImapFlow does not handle reconnects automatically.
599
- * So whenever a 'close' event occurs you must create a new connection yourself.
600
- *
601
- * @event ImapFlow#close
602
- */
603
- /**
604
- * Error event. In most cases getting an error event also means that connection is closed
605
- * and pending operations should return with a failure.
606
- *
607
- * @event ImapFlow#error
608
- * @example
609
- * client.on('error', err=>{
610
- * console.log(`Error occurred: ${err.message}`);
611
- * });
612
- */
613
- /**
614
- * Message count in currently opened mailbox changed
615
- *
616
- * @event ImapFlow#exists
617
- * @example
618
- * client.on('exists', data=>{
619
- * console.log(`Message count in "${data.path}" is ${data.count}`);
620
- * });
621
- */
622
- /**
623
- * Deleted message sequence number in currently opened mailbox. One event is fired for every deleted email.
624
- *
625
- * @event ImapFlow#expunge
626
- * @example
627
- * client.on('expunge', data=>{
628
- * console.log(`Message #${data.seq} was deleted from "${data.path}"`);
629
- * });
630
- */
631
- /**
632
- * Flags were updated for a message. Not all servers fire this event.
633
- *
634
- * @event ImapFlow#flags
635
- * @example
636
- * client.on('flags', data=>{
637
- * console.log(`Flag set for #${data.seq} is now "${Array.from(data.flags).join(', ')}"`);
638
- * });
639
- */
640
- /**
641
- * Mailbox was opened
642
- *
643
- * @event ImapFlow#mailboxOpen
644
- * @example
645
- * client.on('mailboxOpen', mailbox => {
646
- * console.log(`Mailbox ${mailbox.path} was opened`);
647
- * });
648
- */
649
- /**
650
- * Mailbox was closed
651
- *
652
- * Emitted both when a selected mailbox is closed explicitly, by `mailboxClose()` or by
653
- * selecting a different mailbox, and when the connection itself goes away while a mailbox
654
- * was still selected, whether through a clean logout or a lost transport. The transition is
655
- * reported once per selected mailbox, before the `close` event.
656
- *
657
- * @event ImapFlow#mailboxClose
658
- * @example
659
- * client.on('mailboxClose', mailbox => {
660
- * console.log(`Mailbox ${mailbox.path} was closed`);
661
- * });
662
- */
663
- /**
664
- * Log event if `emitLogs=true`
665
- *
666
- * @event ImapFlow#log
667
- * @example
668
- * client.on('log', entry => {
669
- * console.log(`${entry.cid} ${entry.msg}`);
670
- * });
671
- */
672
618
  declare const imapflow: {
673
619
  ImapFlow: typeof ImapFlow;
674
620
  AuthenticationFailure: typeof AuthenticationFailure;