@ghostpaw/email 0.3.0 → 0.4.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.
@@ -0,0 +1,20 @@
1
+ interface EmailRunResult {
2
+ lastInsertRowid: number | bigint;
3
+ changes?: number | bigint | undefined;
4
+ }
5
+ interface EmailStatement {
6
+ run(...params: unknown[]): EmailRunResult;
7
+ get<TRecord>(...params: unknown[]): TRecord | undefined;
8
+ all<TRecord>(...params: unknown[]): TRecord[];
9
+ }
10
+ /**
11
+ * SQLite dependency injected into every email operation.
12
+ * Node.js `DatabaseSync` satisfies this interface directly.
13
+ */
14
+ type EmailDb = {
15
+ exec(sql: string): void;
16
+ prepare(sql: string): EmailStatement;
17
+ close(): void;
18
+ };
19
+
20
+ export type { EmailDb as E };
@@ -0,0 +1,20 @@
1
+ interface EmailRunResult {
2
+ lastInsertRowid: number | bigint;
3
+ changes?: number | bigint | undefined;
4
+ }
5
+ interface EmailStatement {
6
+ run(...params: unknown[]): EmailRunResult;
7
+ get<TRecord>(...params: unknown[]): TRecord | undefined;
8
+ all<TRecord>(...params: unknown[]): TRecord[];
9
+ }
10
+ /**
11
+ * SQLite dependency injected into every email operation.
12
+ * Node.js `DatabaseSync` satisfies this interface directly.
13
+ */
14
+ type EmailDb = {
15
+ exec(sql: string): void;
16
+ prepare(sql: string): EmailStatement;
17
+ close(): void;
18
+ };
19
+
20
+ export type { EmailDb as E };
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var events = require('events');
4
- var net = require('net');
5
- var tls = require('tls');
6
- var zlib = require('zlib');
7
- var crypto = require('crypto');
3
+ var node_events = require('node:events');
4
+ var net = require('node:net');
5
+ var tls = require('node:tls');
6
+ var zlib = require('node:zlib');
7
+ var node_crypto = require('node:crypto');
8
8
 
9
9
  function _interopNamespace(e) {
10
10
  if (e && e.__esModule) return e;
@@ -376,6 +376,11 @@ async function enableCompression(dispatcher) {
376
376
  }
377
377
  }
378
378
 
379
+ // src/lib/connection_error.ts
380
+ function connectionError(error, host, port) {
381
+ return error.code === "ECONNREFUSED" ? new EmailConnectionError(`Connection refused to ${host}:${port}`) : error;
382
+ }
383
+
379
384
  // src/types/defaults.ts
380
385
  var DEFAULT_CONNECTION_TIMEOUT = 3e4;
381
386
  var DEFAULT_SOCKET_TIMEOUT = 3e5;
@@ -398,7 +403,7 @@ var DEFAULT_MAX_MESSAGE_SIZE = 26214400;
398
403
  var DEFAULT_CHARSET = "utf-8";
399
404
 
400
405
  // src/imap/connection.ts
401
- var ImapConnection = class extends events.EventEmitter {
406
+ var ImapConnection = class extends node_events.EventEmitter {
402
407
  #config;
403
408
  #socket = null;
404
409
  #connected = false;
@@ -420,8 +425,9 @@ var ImapConnection = class extends events.EventEmitter {
420
425
  const useTls = this.#config.tls !== false;
421
426
  const onError = (err) => {
422
427
  this.#connected = false;
423
- this.emit("error", err);
424
- reject(err);
428
+ const error = connectionError(err, this.#config.host, this.#config.port);
429
+ if (this.listenerCount("error") > 0) this.emit("error", error);
430
+ reject(error);
425
431
  };
426
432
  if (useTls) {
427
433
  const sock = tls__namespace.connect({
@@ -3748,10 +3754,11 @@ function createFts(db) {
3748
3754
  DELETE FROM messages_fts WHERE rowid = old.id;
3749
3755
  END;
3750
3756
 
3751
- CREATE TRIGGER IF NOT EXISTS messages_au AFTER UPDATE ON messages BEGIN
3752
- DELETE FROM messages_fts WHERE rowid = old.id;
3753
- INSERT INTO messages_fts(rowid, subject, body_text, sender, recipients)
3754
- VALUES (new.id, new.subject, '', new."from", new."to");
3757
+ DROP TRIGGER IF EXISTS messages_au;
3758
+
3759
+ CREATE TRIGGER messages_au AFTER UPDATE ON messages BEGIN
3760
+ UPDATE messages_fts SET subject = new.subject, sender = new."from", recipients = new."to"
3761
+ WHERE rowid = old.id;
3755
3762
  END;
3756
3763
  `);
3757
3764
  }
@@ -3880,11 +3887,11 @@ __export(write_exports, {
3880
3887
  createWriteSurface: () => createWriteSurface
3881
3888
  });
3882
3889
  function generateMessageId(domain) {
3883
- const id = crypto.randomUUID().replace(/-/g, "");
3890
+ const id = node_crypto.randomUUID().replace(/-/g, "");
3884
3891
  return `<${Date.now()}.${id}@${domain}>`;
3885
3892
  }
3886
3893
  function generateBoundary() {
3887
- return `----=_Part_${crypto.randomUUID()}`;
3894
+ return `----=_Part_${node_crypto.randomUUID()}`;
3888
3895
  }
3889
3896
 
3890
3897
  // src/lib/normalize_subject.ts
@@ -4020,6 +4027,10 @@ function encodeDate(date) {
4020
4027
  }
4021
4028
 
4022
4029
  // src/mime/compose_message.ts
4030
+ function bracketId(id) {
4031
+ const value = id.trim();
4032
+ return value.startsWith("<") && value.endsWith(">") ? value : `<${value}>`;
4033
+ }
4023
4034
  function composeMessage(input) {
4024
4035
  const lines = [];
4025
4036
  const from = input.from ?? { address: "unknown@local" };
@@ -4037,10 +4048,10 @@ function composeMessage(input) {
4037
4048
  }
4038
4049
  lines.push(encodeHeader("Subject", input.subject).trim());
4039
4050
  if (input.inReplyTo) {
4040
- lines.push(encodeHeader("In-Reply-To", input.inReplyTo).trim());
4051
+ lines.push(encodeHeader("In-Reply-To", bracketId(input.inReplyTo)).trim());
4041
4052
  }
4042
4053
  if (input.references?.length) {
4043
- lines.push(encodeHeader("References", input.references.join(" ")).trim());
4054
+ lines.push(encodeHeader("References", input.references.map(bracketId).join(" ")).trim());
4044
4055
  }
4045
4056
  if (input.headers) {
4046
4057
  for (const [k, v] of Object.entries(input.headers)) {
@@ -4102,7 +4113,6 @@ ${attBlocks}\r
4102
4113
  --${b}--`;
4103
4114
  }
4104
4115
  const raw2 = `${lines.join("\r\n")}\r
4105
- \r
4106
4116
  ${body}`;
4107
4117
  return Buffer.from(raw2, "utf8");
4108
4118
  }
@@ -4251,7 +4261,9 @@ var SmtpConnection = class {
4251
4261
  reject(new Error("Plaintext port 25 requires allowInsecure: true"));
4252
4262
  return;
4253
4263
  }
4254
- this.#socket.once("error", reject);
4264
+ this.#socket.once("error", (error) => {
4265
+ reject(connectionError(error, this.#host, this.#port));
4266
+ });
4255
4267
  this.#socket.once(
4256
4268
  "secureConnect" in this.#socket ? "secureConnect" : "connect",
4257
4269
  async () => {
@@ -4668,7 +4680,13 @@ var Mailbox = class {
4668
4680
  username: authUser
4669
4681
  });
4670
4682
  const session = new ImapSession(this.#config);
4671
- await session.connect();
4683
+ try {
4684
+ await session.connect();
4685
+ } catch (error) {
4686
+ db.close();
4687
+ this.#db = null;
4688
+ throw error;
4689
+ }
4672
4690
  this.#session = session;
4673
4691
  this.#read = createReadSurface(db, account.id);
4674
4692
  this.#write = createWriteSurface(db, {
package/dist/index.d.cts CHANGED
@@ -1,26 +1,8 @@
1
+ import { E as EmailDb } from './database-Rfe-wn1C.cjs';
1
2
  import { Writable, Duplex } from 'node:stream';
2
3
  import { EventEmitter } from 'node:events';
3
4
  import { DatabaseSync } from 'node:sqlite';
4
5
 
5
- interface EmailRunResult {
6
- lastInsertRowid: number | bigint;
7
- changes?: number | bigint | undefined;
8
- }
9
- interface EmailStatement {
10
- run(...params: unknown[]): EmailRunResult;
11
- get<TRecord>(...params: unknown[]): TRecord | undefined;
12
- all<TRecord>(...params: unknown[]): TRecord[];
13
- }
14
- /**
15
- * SQLite dependency injected into every email operation.
16
- * Node.js `DatabaseSync` satisfies this interface directly.
17
- */
18
- type EmailDb = {
19
- exec(sql: string): void;
20
- prepare(sql: string): EmailStatement;
21
- close(): void;
22
- };
23
-
24
6
  type EmailErrorCode = 'invariant' | 'not_found' | 'state' | 'validation' | 'auth' | 'connection' | 'protocol' | 'timeout' | 'unsupported' | 'envelope_rejected' | 'quota';
25
7
  declare class EmailError extends Error {
26
8
  readonly code: EmailErrorCode;
@@ -1994,4 +1976,4 @@ declare namespace write {
1994
1976
  export { type write_CreateWriteSurfaceOptions as CreateWriteSurfaceOptions, write_createWriteSurface as createWriteSurface };
1995
1977
  }
1996
1978
 
1997
- export { type Account, type AccountStats, type Address, type Attachment, type AttachmentMeta, type AuthConfig, type BodyPart, type ComposeAttachment, type ComposeInput, type ContinuationResponse, DEFAULT_AUTO_EXPUNGE, DEFAULT_BATCH_SIZE, DEFAULT_CHARSET, DEFAULT_COMPRESS, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_IDLE_TIMEOUT, DEFAULT_KEEPALIVE_INTERVAL, DEFAULT_MAX_ATTACHMENT_CACHE, DEFAULT_MAX_BODY_CACHE, DEFAULT_MAX_CONNECTIONS, DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_MAX_NESTING_DEPTH, DEFAULT_MAX_RECONNECT_ATTEMPTS, DEFAULT_MAX_RECONNECT_DELAY, DEFAULT_PIPELINING, DEFAULT_SOCKET_TIMEOUT, DEFAULT_SYNC_DELETED_FOLDERS, DEFAULT_TAG_PREFIX, DEFAULT_WATCH_FOLDERS, EmailAuthError, type EmailConfig, EmailConnectionError, type EmailDb, EmailEnvelopeRejectedError, EmailError, type EmailErrorCode, EmailInvariantError, type EmailNetworkSurface, EmailNotFoundError, EmailProtocolError, EmailQuotaError, type EmailReadSurface, type EmailRuntimeSurface, type EmailSkill, type EmailSkillRegistry, type EmailSoul, type EmailSoulTrait, EmailStateError, EmailTimeoutError, type EmailToolContext, type EmailToolDefinition, type EmailToolResult, EmailUnsupportedError, EmailValidationError, type EmailWriteSurface, type FetchResult, type Folder, type FolderRole, type FolderStatus, type ForwardInput, type ImapResponse, type ImapToken, type InsertMessageInput, type JsonSchema, type JsonSchemaType, type LocalSearchOptions, Mailbox, type Message, type MessageBody, type MessageDetail, type MessageListOptions, type NegotiatedExtensions, type ParsedEnvelope, type ReplyInput, type ResponseCode, type SearchQuery, type SelectedFolder, type SmtpErrorCategory, type SmtpResponse, type SyncFolderResult, type SyncOptions, type SyncResult, type TaggedResponse, type Thread, type ThreadListOptions, type ThreadMessage, type TokenType, type ToolEntityKind, type ToolEntityRef, type ToolOutcomeKind, type ToolSideEffects, type UntaggedResponse, type WatchEvent, type WatchOptions, aligned, attachmentWorkflowSkill, composeAndSendSkill, connectAndSyncSkill, defineEmailSkill, emailSkills, emailSoul, emailSoulEssence, emailSoulTraits, emailTools, errors, getEmailSkillByName, getEmailToolByName, index$8 as imap, initSchema, isEmailError, isRetriable, index$7 as mime, network, organizeBulkSkill, read, readAndReplySkill, recoverFromDisruptionSkill, renderEmailSoulPromptFoundation, runtime, index$6 as schema, searchAndActSkill, index$5 as skills, index$4 as smtp, soul, index$3 as store, index$2 as sync, index$1 as tools, triageInboxSkill, index as types, write };
1979
+ export { type Account, type AccountStats, type Address, type Attachment, type AttachmentMeta, type AuthConfig, type BodyPart, type ComposeAttachment, type ComposeInput, type ContinuationResponse, DEFAULT_AUTO_EXPUNGE, DEFAULT_BATCH_SIZE, DEFAULT_CHARSET, DEFAULT_COMPRESS, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_IDLE_TIMEOUT, DEFAULT_KEEPALIVE_INTERVAL, DEFAULT_MAX_ATTACHMENT_CACHE, DEFAULT_MAX_BODY_CACHE, DEFAULT_MAX_CONNECTIONS, DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_MAX_NESTING_DEPTH, DEFAULT_MAX_RECONNECT_ATTEMPTS, DEFAULT_MAX_RECONNECT_DELAY, DEFAULT_PIPELINING, DEFAULT_SOCKET_TIMEOUT, DEFAULT_SYNC_DELETED_FOLDERS, DEFAULT_TAG_PREFIX, DEFAULT_WATCH_FOLDERS, EmailAuthError, type EmailConfig, EmailConnectionError, EmailDb, EmailEnvelopeRejectedError, EmailError, type EmailErrorCode, EmailInvariantError, type EmailNetworkSurface, EmailNotFoundError, EmailProtocolError, EmailQuotaError, type EmailReadSurface, type EmailRuntimeSurface, type EmailSkill, type EmailSkillRegistry, type EmailSoul, type EmailSoulTrait, EmailStateError, EmailTimeoutError, type EmailToolContext, type EmailToolDefinition, type EmailToolResult, EmailUnsupportedError, EmailValidationError, type EmailWriteSurface, type FetchResult, type Folder, type FolderRole, type FolderStatus, type ForwardInput, type ImapResponse, type ImapToken, type InsertMessageInput, type JsonSchema, type JsonSchemaType, type LocalSearchOptions, Mailbox, type Message, type MessageBody, type MessageDetail, type MessageListOptions, type NegotiatedExtensions, type ParsedEnvelope, type ReplyInput, type ResponseCode, type SearchQuery, type SelectedFolder, type SmtpErrorCategory, type SmtpResponse, type SyncFolderResult, type SyncOptions, type SyncResult, type TaggedResponse, type Thread, type ThreadListOptions, type ThreadMessage, type TokenType, type ToolEntityKind, type ToolEntityRef, type ToolOutcomeKind, type ToolSideEffects, type UntaggedResponse, type WatchEvent, type WatchOptions, aligned, attachmentWorkflowSkill, composeAndSendSkill, connectAndSyncSkill, defineEmailSkill, emailSkills, emailSoul, emailSoulEssence, emailSoulTraits, emailTools, errors, getEmailSkillByName, getEmailToolByName, index$8 as imap, initSchema, isEmailError, isRetriable, index$7 as mime, network, organizeBulkSkill, read, readAndReplySkill, recoverFromDisruptionSkill, renderEmailSoulPromptFoundation, runtime, index$6 as schema, searchAndActSkill, index$5 as skills, index$4 as smtp, soul, index$3 as store, index$2 as sync, index$1 as tools, triageInboxSkill, index as types, write };
package/dist/index.d.ts CHANGED
@@ -1,26 +1,8 @@
1
+ import { E as EmailDb } from './database-Rfe-wn1C.js';
1
2
  import { Writable, Duplex } from 'node:stream';
2
3
  import { EventEmitter } from 'node:events';
3
4
  import { DatabaseSync } from 'node:sqlite';
4
5
 
5
- interface EmailRunResult {
6
- lastInsertRowid: number | bigint;
7
- changes?: number | bigint | undefined;
8
- }
9
- interface EmailStatement {
10
- run(...params: unknown[]): EmailRunResult;
11
- get<TRecord>(...params: unknown[]): TRecord | undefined;
12
- all<TRecord>(...params: unknown[]): TRecord[];
13
- }
14
- /**
15
- * SQLite dependency injected into every email operation.
16
- * Node.js `DatabaseSync` satisfies this interface directly.
17
- */
18
- type EmailDb = {
19
- exec(sql: string): void;
20
- prepare(sql: string): EmailStatement;
21
- close(): void;
22
- };
23
-
24
6
  type EmailErrorCode = 'invariant' | 'not_found' | 'state' | 'validation' | 'auth' | 'connection' | 'protocol' | 'timeout' | 'unsupported' | 'envelope_rejected' | 'quota';
25
7
  declare class EmailError extends Error {
26
8
  readonly code: EmailErrorCode;
@@ -1994,4 +1976,4 @@ declare namespace write {
1994
1976
  export { type write_CreateWriteSurfaceOptions as CreateWriteSurfaceOptions, write_createWriteSurface as createWriteSurface };
1995
1977
  }
1996
1978
 
1997
- export { type Account, type AccountStats, type Address, type Attachment, type AttachmentMeta, type AuthConfig, type BodyPart, type ComposeAttachment, type ComposeInput, type ContinuationResponse, DEFAULT_AUTO_EXPUNGE, DEFAULT_BATCH_SIZE, DEFAULT_CHARSET, DEFAULT_COMPRESS, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_IDLE_TIMEOUT, DEFAULT_KEEPALIVE_INTERVAL, DEFAULT_MAX_ATTACHMENT_CACHE, DEFAULT_MAX_BODY_CACHE, DEFAULT_MAX_CONNECTIONS, DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_MAX_NESTING_DEPTH, DEFAULT_MAX_RECONNECT_ATTEMPTS, DEFAULT_MAX_RECONNECT_DELAY, DEFAULT_PIPELINING, DEFAULT_SOCKET_TIMEOUT, DEFAULT_SYNC_DELETED_FOLDERS, DEFAULT_TAG_PREFIX, DEFAULT_WATCH_FOLDERS, EmailAuthError, type EmailConfig, EmailConnectionError, type EmailDb, EmailEnvelopeRejectedError, EmailError, type EmailErrorCode, EmailInvariantError, type EmailNetworkSurface, EmailNotFoundError, EmailProtocolError, EmailQuotaError, type EmailReadSurface, type EmailRuntimeSurface, type EmailSkill, type EmailSkillRegistry, type EmailSoul, type EmailSoulTrait, EmailStateError, EmailTimeoutError, type EmailToolContext, type EmailToolDefinition, type EmailToolResult, EmailUnsupportedError, EmailValidationError, type EmailWriteSurface, type FetchResult, type Folder, type FolderRole, type FolderStatus, type ForwardInput, type ImapResponse, type ImapToken, type InsertMessageInput, type JsonSchema, type JsonSchemaType, type LocalSearchOptions, Mailbox, type Message, type MessageBody, type MessageDetail, type MessageListOptions, type NegotiatedExtensions, type ParsedEnvelope, type ReplyInput, type ResponseCode, type SearchQuery, type SelectedFolder, type SmtpErrorCategory, type SmtpResponse, type SyncFolderResult, type SyncOptions, type SyncResult, type TaggedResponse, type Thread, type ThreadListOptions, type ThreadMessage, type TokenType, type ToolEntityKind, type ToolEntityRef, type ToolOutcomeKind, type ToolSideEffects, type UntaggedResponse, type WatchEvent, type WatchOptions, aligned, attachmentWorkflowSkill, composeAndSendSkill, connectAndSyncSkill, defineEmailSkill, emailSkills, emailSoul, emailSoulEssence, emailSoulTraits, emailTools, errors, getEmailSkillByName, getEmailToolByName, index$8 as imap, initSchema, isEmailError, isRetriable, index$7 as mime, network, organizeBulkSkill, read, readAndReplySkill, recoverFromDisruptionSkill, renderEmailSoulPromptFoundation, runtime, index$6 as schema, searchAndActSkill, index$5 as skills, index$4 as smtp, soul, index$3 as store, index$2 as sync, index$1 as tools, triageInboxSkill, index as types, write };
1979
+ export { type Account, type AccountStats, type Address, type Attachment, type AttachmentMeta, type AuthConfig, type BodyPart, type ComposeAttachment, type ComposeInput, type ContinuationResponse, DEFAULT_AUTO_EXPUNGE, DEFAULT_BATCH_SIZE, DEFAULT_CHARSET, DEFAULT_COMPRESS, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_IDLE_TIMEOUT, DEFAULT_KEEPALIVE_INTERVAL, DEFAULT_MAX_ATTACHMENT_CACHE, DEFAULT_MAX_BODY_CACHE, DEFAULT_MAX_CONNECTIONS, DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_MAX_NESTING_DEPTH, DEFAULT_MAX_RECONNECT_ATTEMPTS, DEFAULT_MAX_RECONNECT_DELAY, DEFAULT_PIPELINING, DEFAULT_SOCKET_TIMEOUT, DEFAULT_SYNC_DELETED_FOLDERS, DEFAULT_TAG_PREFIX, DEFAULT_WATCH_FOLDERS, EmailAuthError, type EmailConfig, EmailConnectionError, EmailDb, EmailEnvelopeRejectedError, EmailError, type EmailErrorCode, EmailInvariantError, type EmailNetworkSurface, EmailNotFoundError, EmailProtocolError, EmailQuotaError, type EmailReadSurface, type EmailRuntimeSurface, type EmailSkill, type EmailSkillRegistry, type EmailSoul, type EmailSoulTrait, EmailStateError, EmailTimeoutError, type EmailToolContext, type EmailToolDefinition, type EmailToolResult, EmailUnsupportedError, EmailValidationError, type EmailWriteSurface, type FetchResult, type Folder, type FolderRole, type FolderStatus, type ForwardInput, type ImapResponse, type ImapToken, type InsertMessageInput, type JsonSchema, type JsonSchemaType, type LocalSearchOptions, Mailbox, type Message, type MessageBody, type MessageDetail, type MessageListOptions, type NegotiatedExtensions, type ParsedEnvelope, type ReplyInput, type ResponseCode, type SearchQuery, type SelectedFolder, type SmtpErrorCategory, type SmtpResponse, type SyncFolderResult, type SyncOptions, type SyncResult, type TaggedResponse, type Thread, type ThreadListOptions, type ThreadMessage, type TokenType, type ToolEntityKind, type ToolEntityRef, type ToolOutcomeKind, type ToolSideEffects, type UntaggedResponse, type WatchEvent, type WatchOptions, aligned, attachmentWorkflowSkill, composeAndSendSkill, connectAndSyncSkill, defineEmailSkill, emailSkills, emailSoul, emailSoulEssence, emailSoulTraits, emailTools, errors, getEmailSkillByName, getEmailToolByName, index$8 as imap, initSchema, isEmailError, isRetriable, index$7 as mime, network, organizeBulkSkill, read, readAndReplySkill, recoverFromDisruptionSkill, renderEmailSoulPromptFoundation, runtime, index$6 as schema, searchAndActSkill, index$5 as skills, index$4 as smtp, soul, index$3 as store, index$2 as sync, index$1 as tools, triageInboxSkill, index as types, write };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { EventEmitter } from 'events';
2
- import * as net from 'net';
3
- import * as tls from 'tls';
4
- import * as zlib from 'zlib';
5
- import { randomUUID } from 'crypto';
1
+ import { EventEmitter } from 'node:events';
2
+ import * as net from 'node:net';
3
+ import * as tls from 'node:tls';
4
+ import * as zlib from 'node:zlib';
5
+ import { randomUUID } from 'node:crypto';
6
6
 
7
7
  var __defProp = Object.defineProperty;
8
8
  var __export = (target, all) => {
@@ -352,6 +352,11 @@ async function enableCompression(dispatcher) {
352
352
  }
353
353
  }
354
354
 
355
+ // src/lib/connection_error.ts
356
+ function connectionError(error, host, port) {
357
+ return error.code === "ECONNREFUSED" ? new EmailConnectionError(`Connection refused to ${host}:${port}`) : error;
358
+ }
359
+
355
360
  // src/types/defaults.ts
356
361
  var DEFAULT_CONNECTION_TIMEOUT = 3e4;
357
362
  var DEFAULT_SOCKET_TIMEOUT = 3e5;
@@ -396,8 +401,9 @@ var ImapConnection = class extends EventEmitter {
396
401
  const useTls = this.#config.tls !== false;
397
402
  const onError = (err) => {
398
403
  this.#connected = false;
399
- this.emit("error", err);
400
- reject(err);
404
+ const error = connectionError(err, this.#config.host, this.#config.port);
405
+ if (this.listenerCount("error") > 0) this.emit("error", error);
406
+ reject(error);
401
407
  };
402
408
  if (useTls) {
403
409
  const sock = tls.connect({
@@ -3724,10 +3730,11 @@ function createFts(db) {
3724
3730
  DELETE FROM messages_fts WHERE rowid = old.id;
3725
3731
  END;
3726
3732
 
3727
- CREATE TRIGGER IF NOT EXISTS messages_au AFTER UPDATE ON messages BEGIN
3728
- DELETE FROM messages_fts WHERE rowid = old.id;
3729
- INSERT INTO messages_fts(rowid, subject, body_text, sender, recipients)
3730
- VALUES (new.id, new.subject, '', new."from", new."to");
3733
+ DROP TRIGGER IF EXISTS messages_au;
3734
+
3735
+ CREATE TRIGGER messages_au AFTER UPDATE ON messages BEGIN
3736
+ UPDATE messages_fts SET subject = new.subject, sender = new."from", recipients = new."to"
3737
+ WHERE rowid = old.id;
3731
3738
  END;
3732
3739
  `);
3733
3740
  }
@@ -3996,6 +4003,10 @@ function encodeDate(date) {
3996
4003
  }
3997
4004
 
3998
4005
  // src/mime/compose_message.ts
4006
+ function bracketId(id) {
4007
+ const value = id.trim();
4008
+ return value.startsWith("<") && value.endsWith(">") ? value : `<${value}>`;
4009
+ }
3999
4010
  function composeMessage(input) {
4000
4011
  const lines = [];
4001
4012
  const from = input.from ?? { address: "unknown@local" };
@@ -4013,10 +4024,10 @@ function composeMessage(input) {
4013
4024
  }
4014
4025
  lines.push(encodeHeader("Subject", input.subject).trim());
4015
4026
  if (input.inReplyTo) {
4016
- lines.push(encodeHeader("In-Reply-To", input.inReplyTo).trim());
4027
+ lines.push(encodeHeader("In-Reply-To", bracketId(input.inReplyTo)).trim());
4017
4028
  }
4018
4029
  if (input.references?.length) {
4019
- lines.push(encodeHeader("References", input.references.join(" ")).trim());
4030
+ lines.push(encodeHeader("References", input.references.map(bracketId).join(" ")).trim());
4020
4031
  }
4021
4032
  if (input.headers) {
4022
4033
  for (const [k, v] of Object.entries(input.headers)) {
@@ -4078,7 +4089,6 @@ ${attBlocks}\r
4078
4089
  --${b}--`;
4079
4090
  }
4080
4091
  const raw2 = `${lines.join("\r\n")}\r
4081
- \r
4082
4092
  ${body}`;
4083
4093
  return Buffer.from(raw2, "utf8");
4084
4094
  }
@@ -4227,7 +4237,9 @@ var SmtpConnection = class {
4227
4237
  reject(new Error("Plaintext port 25 requires allowInsecure: true"));
4228
4238
  return;
4229
4239
  }
4230
- this.#socket.once("error", reject);
4240
+ this.#socket.once("error", (error) => {
4241
+ reject(connectionError(error, this.#host, this.#port));
4242
+ });
4231
4243
  this.#socket.once(
4232
4244
  "secureConnect" in this.#socket ? "secureConnect" : "connect",
4233
4245
  async () => {
@@ -4644,7 +4656,13 @@ var Mailbox = class {
4644
4656
  username: authUser
4645
4657
  });
4646
4658
  const session = new ImapSession(this.#config);
4647
- await session.connect();
4659
+ try {
4660
+ await session.connect();
4661
+ } catch (error) {
4662
+ db.close();
4663
+ this.#db = null;
4664
+ throw error;
4665
+ }
4648
4666
  this.#session = session;
4649
4667
  this.#read = createReadSurface(db, account.id);
4650
4668
  this.#write = createWriteSurface(db, {