loopzero-gateway-email 0.0.0-stage → 0.1.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,896 @@
1
+ 'use strict';
2
+
3
+ var loopzeroGateway = require('loopzero-gateway');
4
+ var imapflow = require('imapflow');
5
+ var mailparser = require('mailparser');
6
+ var nodemailer = require('nodemailer');
7
+
8
+ // src/adapter.ts
9
+
10
+ // src/errors.ts
11
+ var NETWORK_ERR_RE = /ECONN|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|EAI_AGAIN|fetch failed/i;
12
+ function mapEmailError(err) {
13
+ if (err === null || err === void 0) {
14
+ return { code: "unknown", message: "Unknown error" };
15
+ }
16
+ if (typeof err === "string") {
17
+ return { code: "unknown", message: err };
18
+ }
19
+ const e = err;
20
+ const code = e.code ?? "";
21
+ const respCode = typeof e.responseCode === "number" ? e.responseCode : void 0;
22
+ const message = typeof e.message === "string" && e.message.length > 0 ? e.message : String(err);
23
+ if (code === "EAUTH" || code === "EAUTHENTICATION") {
24
+ return { code: "auth_failed", message };
25
+ }
26
+ if (code === "EENVELOPE" && /550/.test(message)) {
27
+ return { code: "invalid_request", message };
28
+ }
29
+ if (code === "ECONNECTION" || code === "ESOCKET" || code === "ETLS") {
30
+ return { code: "server_error", message };
31
+ }
32
+ if (code === "ETIMEDOUT") {
33
+ return { code: "timeout", message };
34
+ }
35
+ if (respCode !== void 0) {
36
+ if (respCode === 535 || respCode === 530) return { code: "auth_failed", message };
37
+ if (respCode === 421 || respCode === 451 || respCode === 452)
38
+ return { code: "rate_limit", message };
39
+ if (respCode === 550 || respCode === 551 || respCode === 553)
40
+ return { code: "invalid_request", message };
41
+ if (respCode >= 500) return { code: "server_error", message };
42
+ if (respCode >= 400) return { code: "rate_limit", message };
43
+ }
44
+ if (e.name === "IMAP_AUTH_FAILED" || /auth/i.test(message)) {
45
+ return { code: "auth_failed", message };
46
+ }
47
+ if (NETWORK_ERR_RE.test(message)) return { code: "server_error", message };
48
+ return { code: "unknown", message };
49
+ }
50
+
51
+ // src/filters.ts
52
+ var NOREPLY_RE = /^(noreply|no-reply|no_reply|donotreply|do-not-reply|mailer-daemon|postmaster|bounce|notifications)@/i;
53
+ function extractAddr(s) {
54
+ const m = s.match(/<([^>]+)>/);
55
+ return (m?.[1] ?? s).toLowerCase().trim();
56
+ }
57
+ function isAutomatedSender(fromAddress, headers) {
58
+ if (NOREPLY_RE.test(fromAddress)) return true;
59
+ const lowered = /* @__PURE__ */ new Map();
60
+ for (const [k, v] of headers) lowered.set(k.toLowerCase(), v);
61
+ const autoSubmitted = lowered.get("auto-submitted");
62
+ if (typeof autoSubmitted === "string" && /auto-generated|auto-replied/i.test(autoSubmitted)) {
63
+ return true;
64
+ }
65
+ const precedence = lowered.get("precedence");
66
+ if (typeof precedence === "string" && /bulk|list/i.test(precedence)) {
67
+ return true;
68
+ }
69
+ const xAuto = lowered.get("x-auto-response-suppress");
70
+ if (typeof xAuto === "string" && /all/i.test(xAuto)) {
71
+ return true;
72
+ }
73
+ return false;
74
+ }
75
+ function isAllowedSender(fromAddress, allowedSenders) {
76
+ if (allowedSenders === void 0) return true;
77
+ const norm = extractAddr(fromAddress);
78
+ return allowedSenders.some((s) => extractAddr(s) === norm);
79
+ }
80
+ var ImapClient = class {
81
+ constructor(config) {
82
+ this.config = config;
83
+ }
84
+ config;
85
+ client;
86
+ idleAbort;
87
+ lostListener;
88
+ /** Set by `disconnect()`, so the close it causes is not reported as a loss. */
89
+ closing = false;
90
+ onConnectionLost(listener) {
91
+ this.lostListener = listener;
92
+ }
93
+ async connect() {
94
+ const client = new imapflow.ImapFlow({
95
+ host: this.config.host,
96
+ port: this.config.port,
97
+ secure: this.config.secure,
98
+ auth: this.config.auth,
99
+ logger: false
100
+ });
101
+ this.client = client;
102
+ let lastError;
103
+ client.on("error", (err) => {
104
+ lastError = err;
105
+ });
106
+ let opened = false;
107
+ client.on("close", () => {
108
+ if (!opened || this.closing) return;
109
+ this.lostListener?.(lastError);
110
+ });
111
+ await client.connect();
112
+ await client.mailboxOpen("INBOX");
113
+ opened = true;
114
+ }
115
+ // eslint-disable-next-line @typescript-eslint/require-await
116
+ async mailboxStatus() {
117
+ const box = this.client?.mailbox;
118
+ if (box === void 0 || box === false) throw new Error("no mailbox open");
119
+ return { uidValidity: Number(box.uidValidity), uidNext: box.uidNext };
120
+ }
121
+ supportsIdle() {
122
+ if (this.client === void 0) return false;
123
+ const caps = this.client.capabilities;
124
+ return caps?.has?.("IDLE") ?? false;
125
+ }
126
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — imapflow can hand headers as Map OR Buffer depending on protocol path; this is the single normalization site.
127
+ async fetchUnseen(sinceUid) {
128
+ if (this.client === void 0) return [];
129
+ const out = [];
130
+ const query = sinceUid === void 0 ? { seen: false } : { seen: false, uid: `${sinceUid}:*` };
131
+ for await (const raw of this.client.fetch(query, {
132
+ uid: true,
133
+ source: true,
134
+ headers: true
135
+ })) {
136
+ const msg = raw;
137
+ const headers = /* @__PURE__ */ new Map();
138
+ const h = msg.headers;
139
+ if (h instanceof Map) {
140
+ for (const [k, v] of h) {
141
+ headers.set(String(k), Array.isArray(v) ? v[0] ?? "" : v);
142
+ }
143
+ } else if (h instanceof Buffer) {
144
+ for (const line of h.toString("utf8").split(/\r?\n/)) {
145
+ const idx = line.indexOf(":");
146
+ if (idx > 0)
147
+ headers.set(line.slice(0, idx).trim().toLowerCase(), line.slice(idx + 1).trim());
148
+ }
149
+ }
150
+ if (msg.uid !== void 0 && msg.source !== void 0) {
151
+ out.push({
152
+ uid: msg.uid,
153
+ source: msg.source,
154
+ headers
155
+ });
156
+ }
157
+ }
158
+ return out;
159
+ }
160
+ async markSeen(uids) {
161
+ if (this.client === void 0 || uids.length === 0) return;
162
+ await this.client.messageFlagsAdd({ uid: uids.join(",") }, ["\\Seen"], { uid: true });
163
+ }
164
+ async startIdle(onExists) {
165
+ if (this.client === void 0) return;
166
+ this.idleAbort = new AbortController();
167
+ const c = this.client;
168
+ c.on("exists", () => {
169
+ onExists();
170
+ });
171
+ void c.idle().catch(() => {
172
+ });
173
+ }
174
+ async stopIdle() {
175
+ if (this.idleAbort !== void 0) {
176
+ this.idleAbort.abort();
177
+ this.idleAbort = void 0;
178
+ }
179
+ }
180
+ async disconnect() {
181
+ this.closing = true;
182
+ await this.stopIdle();
183
+ if (this.client !== void 0) {
184
+ try {
185
+ await this.client.logout();
186
+ } catch {
187
+ }
188
+ this.client = void 0;
189
+ }
190
+ }
191
+ };
192
+ var DEFAULT_MAX_BODY = 5e4;
193
+ function stripBraces(id) {
194
+ if (id === void 0 || id.length === 0) return void 0;
195
+ return id.replace(/^<|>$/g, "");
196
+ }
197
+ function normalizeRefs(refs) {
198
+ if (refs === void 0) return void 0;
199
+ const arr = Array.isArray(refs) ? refs : refs.split(/\s+/).filter((s) => s.length > 0);
200
+ const cleaned = arr.map((r) => stripBraces(r)).filter((r) => r !== void 0);
201
+ return cleaned.length > 0 ? cleaned : void 0;
202
+ }
203
+ function addressesFrom(obj) {
204
+ if (obj === void 0) return [];
205
+ if (Array.isArray(obj)) {
206
+ const out = [];
207
+ for (const o of obj) out.push(...o.value ?? []);
208
+ return out;
209
+ }
210
+ return Array.from(obj.value ?? []);
211
+ }
212
+ async function normalizeEmail(rawBuffer, opts) {
213
+ const parsed = await mailparser.simpleParser(rawBuffer);
214
+ const messageId = stripBraces(parsed.messageId) ?? "unknown";
215
+ const inReplyTo = stripBraces(parsed.inReplyTo);
216
+ const references = normalizeRefs(parsed.references);
217
+ const fromEntries = addressesFrom(parsed.from);
218
+ const fromAddress = (fromEntries[0]?.address ?? "anonymous").toLowerCase().trim();
219
+ const trimmedName = fromEntries[0]?.name?.trim();
220
+ const fromName = trimmedName !== void 0 && trimmedName.length > 0 ? trimmedName : void 0;
221
+ const botAddrLc = opts.botAddress.toLowerCase().trim();
222
+ const recipients = [];
223
+ for (const entry of [
224
+ ...addressesFrom(parsed.to),
225
+ ...addressesFrom(parsed.cc)
226
+ ]) {
227
+ const addr = entry.address?.toLowerCase().trim();
228
+ if (addr !== void 0 && addr.length > 0 && addr !== botAddrLc) {
229
+ recipients.push(addr);
230
+ }
231
+ }
232
+ const subject = parsed.subject ?? "(no subject)";
233
+ const rawText = parsed.text ?? "";
234
+ const maxChars = opts.maxBodyChars ?? DEFAULT_MAX_BODY;
235
+ const text = rawText.length > maxChars ? `${rawText.slice(0, maxChars)}
236
+
237
+ [truncated \u2014 full body in event.email.raw]` : rawText;
238
+ const receivedAt = parsed.date instanceof Date ? parsed.date.getTime() : Date.now();
239
+ const attachmentCount = Array.isArray(parsed.attachments) ? parsed.attachments.length : 0;
240
+ const emailMeta = {
241
+ messageId,
242
+ ...inReplyTo !== void 0 ? { inReplyTo } : {},
243
+ ...references !== void 0 ? { references } : {},
244
+ subject,
245
+ fromAddress,
246
+ ...fromName !== void 0 ? { fromName } : {},
247
+ recipients,
248
+ attachmentCount,
249
+ raw: parsed
250
+ };
251
+ return {
252
+ id: messageId,
253
+ platform: "email",
254
+ sender: {
255
+ id: fromAddress,
256
+ ...fromName !== void 0 ? { displayName: fromName } : {}
257
+ },
258
+ channel: { id: fromAddress, type: "dm", topicId: messageId },
259
+ text,
260
+ receivedAt,
261
+ email: emailMeta
262
+ };
263
+ }
264
+
265
+ // src/refuse-attachments.ts
266
+ function refuseAttachments(out) {
267
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
268
+ return {
269
+ ok: false,
270
+ error: { code: "attachments_unsupported", message: "email adapter cannot send attachments" }
271
+ };
272
+ }
273
+
274
+ // src/seen-uids.ts
275
+ var SeenUidSet = class _SeenUidSet {
276
+ set = /* @__PURE__ */ new Set();
277
+ static MAX_SIZE = 5e3;
278
+ static TRIM_TO = 4e3;
279
+ has(uid) {
280
+ return this.set.has(uid);
281
+ }
282
+ add(uid) {
283
+ if (this.set.size >= _SeenUidSet.MAX_SIZE) this.trim();
284
+ this.set.add(uid);
285
+ }
286
+ trim() {
287
+ const target = _SeenUidSet.TRIM_TO;
288
+ const toDrop = this.set.size - target;
289
+ if (toDrop <= 0) return;
290
+ let i = 0;
291
+ for (const key of this.set) {
292
+ if (i >= toDrop) break;
293
+ this.set.delete(key);
294
+ i++;
295
+ }
296
+ }
297
+ get size() {
298
+ return this.set.size;
299
+ }
300
+ clear() {
301
+ this.set.clear();
302
+ }
303
+ };
304
+ var SmtpClient = class {
305
+ constructor(config) {
306
+ this.config = config;
307
+ }
308
+ config;
309
+ transporter;
310
+ getTransporter() {
311
+ if (this.transporter === void 0) {
312
+ this.transporter = nodemailer.createTransport({
313
+ host: this.config.host,
314
+ port: this.config.port,
315
+ secure: this.config.secure,
316
+ auth: this.config.auth
317
+ });
318
+ }
319
+ return this.transporter;
320
+ }
321
+ async verify() {
322
+ return this.getTransporter().verify();
323
+ }
324
+ async send(opts) {
325
+ const mail = {
326
+ from: opts.from,
327
+ to: opts.to,
328
+ subject: opts.subject,
329
+ text: opts.text
330
+ };
331
+ if (opts.html !== void 0) {
332
+ mail.html = opts.html;
333
+ }
334
+ if (opts.inReplyTo !== void 0) {
335
+ mail.inReplyTo = `<${opts.inReplyTo}>`;
336
+ }
337
+ if (opts.references !== void 0 && opts.references.length > 0) {
338
+ mail.references = opts.references.map((r) => `<${r}>`);
339
+ }
340
+ const info = await this.getTransporter().sendMail(mail);
341
+ const raw = (info.messageId ?? "").replace(/^<|>$/g, "");
342
+ return raw;
343
+ }
344
+ async close() {
345
+ if (this.transporter !== void 0) {
346
+ this.transporter.close();
347
+ this.transporter = void 0;
348
+ }
349
+ }
350
+ };
351
+
352
+ // src/thread-store.ts
353
+ var ThreadStore = class _ThreadStore {
354
+ map = /* @__PURE__ */ new Map();
355
+ static MAX_SIZE = 1e3;
356
+ recordFromInbound(event) {
357
+ const ctx = {
358
+ subject: event.email.subject,
359
+ references: event.email.references ?? [],
360
+ lastMessageId: event.email.messageId
361
+ };
362
+ if (this.map.size >= _ThreadStore.MAX_SIZE && !this.map.has(event.email.messageId)) {
363
+ const firstKey = this.map.keys().next().value;
364
+ if (firstKey !== void 0) this.map.delete(firstKey);
365
+ }
366
+ this.map.delete(event.email.messageId);
367
+ this.map.set(event.email.messageId, ctx);
368
+ }
369
+ lookup(topicId) {
370
+ return this.map.get(topicId);
371
+ }
372
+ get size() {
373
+ return this.map.size;
374
+ }
375
+ clear() {
376
+ this.map.clear();
377
+ }
378
+ };
379
+
380
+ // src/adapter.ts
381
+ var DEFAULT_POLL_INTERVAL_MS = 15e3;
382
+ var MAX_RECONNECT_DELAY_MS = 6e4;
383
+ function reportDrainFailure(err) {
384
+ console.error("[email] drain failed:", err instanceof Error ? err.message : err);
385
+ }
386
+ function htmlPartFor(text, format) {
387
+ if (format === "html") return text;
388
+ const escaped = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
389
+ return `<pre>${escaped}</pre>`;
390
+ }
391
+ var EmailAdapter = class extends loopzeroGateway.BasePlatformAdapter {
392
+ platform = "email";
393
+ options;
394
+ seenUids = new SeenUidSet();
395
+ /** UIDs finished with in this batch, awaiting one `\Seen` command (#11). */
396
+ pendingSeen = /* @__PURE__ */ new Set();
397
+ threadStore = new ThreadStore();
398
+ imap;
399
+ smtp;
400
+ handler;
401
+ connected = false;
402
+ // EC-4: serialize concurrent _dispatchInbound calls.
403
+ dispatchQueue = Promise.resolve();
404
+ pollTimer;
405
+ /** Set by `disconnect()`: a lost connection is then not reopened. */
406
+ stopping = false;
407
+ reconnectTimer;
408
+ reconnectBackoff = new loopzeroGateway.ReconnectBackoff({
409
+ initialDelayMs: 1e3,
410
+ maxDelayMs: MAX_RECONNECT_DELAY_MS
411
+ });
412
+ /** In-memory cursor (#348); mirrored to `options.cursorStore` when one is given. */
413
+ cursor;
414
+ constructor(opts) {
415
+ super();
416
+ for (const k of ["address", "password", "imapHost", "smtpHost"]) {
417
+ const v = opts[k];
418
+ if (typeof v !== "string" || v.length === 0) {
419
+ throw new TypeError(`EmailAdapter: ${k} is required and must be a non-empty string`);
420
+ }
421
+ }
422
+ this.options = opts;
423
+ }
424
+ async connect() {
425
+ if (this.connected) return true;
426
+ this.stopping = false;
427
+ try {
428
+ const smtpFactory = this.options.__smtpFactory;
429
+ const smtpConfig = {
430
+ host: this.options.smtpHost,
431
+ port: this.options.smtpPort ?? 587,
432
+ secure: (this.options.smtpPort ?? 587) === 465,
433
+ auth: { user: this.options.address, pass: this.options.password }
434
+ };
435
+ this.smtp = smtpFactory !== void 0 ? smtpFactory(smtpConfig) : new SmtpClient(smtpConfig);
436
+ await this.smtp.verify();
437
+ await this._openImap();
438
+ this.connected = true;
439
+ return true;
440
+ } catch (err) {
441
+ console.error("[email] connect failed:", err instanceof Error ? err.message : err);
442
+ await this.disconnect().catch(() => {
443
+ });
444
+ return false;
445
+ }
446
+ }
447
+ /** A fresh IMAP client, watched for loss of its connection. */
448
+ _newImapClient() {
449
+ const imapFactory = this.options.__imapFactory;
450
+ const config = {
451
+ host: this.options.imapHost,
452
+ port: this.options.imapPort ?? 993,
453
+ secure: true,
454
+ auth: { user: this.options.address, pass: this.options.password }
455
+ };
456
+ const client = imapFactory !== void 0 ? imapFactory(config) : new ImapClient(config);
457
+ client.onConnectionLost((cause) => this._imapLost(client, cause));
458
+ return client;
459
+ }
460
+ /**
461
+ * Open IMAP, keep or take the cursor, and start watching: IDLE when the server has it, a poll
462
+ * otherwise. Used by `connect()` and by every reconnect, so a reconnect resumes from the cursor
463
+ * and dispatches what arrived while the connection was down.
464
+ */
465
+ async _openImap() {
466
+ const imap = this._newImapClient();
467
+ this.imap = imap;
468
+ try {
469
+ await imap.connect();
470
+ await this._establishCursor(imap);
471
+ if (imap.supportsIdle()) {
472
+ await imap.startIdle(() => {
473
+ void this._drainUnseen().catch(reportDrainFailure);
474
+ });
475
+ void this._drainUnseen().catch(reportDrainFailure);
476
+ } else {
477
+ const intervalMs = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
478
+ this.pollTimer = setInterval(() => {
479
+ void this._drainUnseen().catch(reportDrainFailure);
480
+ }, intervalMs);
481
+ }
482
+ this.reconnectBackoff.opened();
483
+ } catch (err) {
484
+ if (this.imap === imap) this.imap = void 0;
485
+ await imap.disconnect().catch(() => {
486
+ });
487
+ throw err;
488
+ }
489
+ }
490
+ /**
491
+ * The IMAP connection dropped (a reset, a timeout, the server going away). The adapter stays
492
+ * connected from its caller's view and opens a new IMAP connection with growing delays until
493
+ * one succeeds or `disconnect()` is called. Without this a dropped link ended inbound mail for
494
+ * the life of the process while `connect()` had answered true.
495
+ */
496
+ _imapLost(client, cause) {
497
+ if (this.stopping || this.imap !== client) return;
498
+ console.error(
499
+ `[email] IMAP connection lost (${cause?.message ?? "closed by the server"}); reconnecting`
500
+ );
501
+ this.imap = void 0;
502
+ this._stopPolling();
503
+ void client.disconnect().catch(() => {
504
+ });
505
+ this._scheduleReconnect();
506
+ }
507
+ _scheduleReconnect() {
508
+ if (this.stopping || this.reconnectTimer !== void 0) return;
509
+ const delay = this.reconnectBackoff.nextDelayMs() ?? MAX_RECONNECT_DELAY_MS;
510
+ this.reconnectTimer = setTimeout(() => {
511
+ this.reconnectTimer = void 0;
512
+ this._reconnectImap().catch((err) => {
513
+ console.error(
514
+ "[email] IMAP reconnect crashed (will retry):",
515
+ err instanceof Error ? err.message : err
516
+ );
517
+ this._scheduleReconnect();
518
+ });
519
+ }, delay);
520
+ }
521
+ async _reconnectImap() {
522
+ if (this.stopping) return;
523
+ try {
524
+ await this._openImap();
525
+ if (this.stopping) {
526
+ await this.imap?.disconnect().catch(() => {
527
+ });
528
+ this.imap = void 0;
529
+ }
530
+ } catch (err) {
531
+ console.error(
532
+ "[email] IMAP reconnect failed (will retry):",
533
+ err instanceof Error ? err.message : err
534
+ );
535
+ this._scheduleReconnect();
536
+ }
537
+ }
538
+ _stopPolling() {
539
+ if (this.pollTimer !== void 0) {
540
+ clearInterval(this.pollTimer);
541
+ this.pollTimer = void 0;
542
+ }
543
+ }
544
+ async disconnect() {
545
+ this.stopping = true;
546
+ if (this.reconnectTimer !== void 0) {
547
+ clearTimeout(this.reconnectTimer);
548
+ this.reconnectTimer = void 0;
549
+ }
550
+ this._stopPolling();
551
+ if (this.imap !== void 0) {
552
+ await this.imap.disconnect().catch(() => {
553
+ });
554
+ this.imap = void 0;
555
+ }
556
+ if (this.smtp !== void 0) {
557
+ await this.smtp.close().catch(() => {
558
+ });
559
+ this.smtp = void 0;
560
+ }
561
+ this.connected = false;
562
+ this.handler = void 0;
563
+ this.seenUids.clear();
564
+ this.threadStore.clear();
565
+ }
566
+ async sendMessage(out) {
567
+ return refuseAttachments(out) ?? this.sendText(out);
568
+ }
569
+ async sendText(out) {
570
+ if (out.text.length === 0) {
571
+ return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
572
+ }
573
+ if (!this.connected || this.smtp === void 0) {
574
+ return {
575
+ ok: false,
576
+ error: { code: "not_connected", message: "EmailAdapter not connected." }
577
+ };
578
+ }
579
+ const to = out.channel.id;
580
+ const topicId = out.channel.topicId;
581
+ const context = topicId !== void 0 ? this.threadStore.lookup(topicId) : void 0;
582
+ const { subject, inReplyTo, references } = replyHeaders(context);
583
+ const from = this.options.fromName !== void 0 ? { name: this.options.fromName, address: this.options.address } : this.options.address;
584
+ try {
585
+ const base = {
586
+ from,
587
+ to,
588
+ subject,
589
+ text: out.text,
590
+ ...inReplyTo !== void 0 ? { inReplyTo } : {},
591
+ ...references !== void 0 ? { references } : {}
592
+ };
593
+ const html = out.format === "markdown" || out.format === "html" ? htmlPartFor(out.text, out.format) : void 0;
594
+ const messageId = await sendWithTextFallback(this.smtp, base, html);
595
+ return { ok: true, messageId };
596
+ } catch (err) {
597
+ return { ok: false, error: mapEmailError(err) };
598
+ }
599
+ }
600
+ onInbound(handler) {
601
+ this.handler = handler;
602
+ return () => {
603
+ if (this.handler === handler) this.handler = void 0;
604
+ };
605
+ }
606
+ /**
607
+ * Load the cursor, and baseline it at the mailbox's UIDNEXT when there is none or its
608
+ * UIDVALIDITY no longer matches (the UIDs it counted are gone). Existing mail is not dispatched.
609
+ */
610
+ async _establishCursor(imap) {
611
+ const store = this.options.cursorStore;
612
+ const status = await imap.mailboxStatus();
613
+ const known = this.cursor ?? await store?.load();
614
+ if (known !== void 0 && known.uidValidity === status.uidValidity) {
615
+ this.cursor = known;
616
+ return;
617
+ }
618
+ this.cursor = { uidValidity: status.uidValidity, uid: status.uidNext };
619
+ await store?.save(this.cursor);
620
+ }
621
+ /** @internal — drain UNSEEN past the cursor once and dispatch each. */
622
+ async _drainUnseen() {
623
+ if (this.imap === void 0 || this.cursor === void 0) return;
624
+ const since = this.cursor.uid;
625
+ let messages = [];
626
+ try {
627
+ messages = await this.imap.fetchUnseen(since);
628
+ } catch (err) {
629
+ console.error("[email] fetchUnseen failed:", err instanceof Error ? err.message : err);
630
+ return;
631
+ }
632
+ messages = messages.filter((m) => m.uid >= since);
633
+ for (const msg of messages) {
634
+ this._dispatchInbound(msg.uid, msg.source, msg.headers);
635
+ }
636
+ await this._advanceCursor(messages);
637
+ this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());
638
+ }
639
+ async _advanceCursor(messages) {
640
+ if (this.cursor === void 0 || messages.length === 0) return;
641
+ const next = Math.max(...messages.map((m) => m.uid)) + 1;
642
+ if (next <= this.cursor.uid) return;
643
+ this.cursor = { uidValidity: this.cursor.uidValidity, uid: next };
644
+ try {
645
+ await this.options.cursorStore?.save(this.cursor);
646
+ } catch (err) {
647
+ console.error("[email] could not save cursor:", err instanceof Error ? err.message : err);
648
+ }
649
+ }
650
+ /**
651
+ * EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.
652
+ * Fire-and-forget: never throws; errors logged.
653
+ */
654
+ _dispatchInbound(uid, rawBuffer, headers) {
655
+ this.dispatchQueue = this.dispatchQueue.then(
656
+ () => this._dispatchInboundInner(uid, rawBuffer, headers).catch(
657
+ (err) => console.error("[email] dispatch error:", err instanceof Error ? err.message : err)
658
+ )
659
+ );
660
+ return this.dispatchQueue;
661
+ }
662
+ async _dispatchInboundInner(uid, rawBuffer, headers) {
663
+ if (this.seenUids.has(uid)) return;
664
+ this.seenUids.add(uid);
665
+ try {
666
+ await this._dispatchOrDrop(uid, rawBuffer, headers);
667
+ } finally {
668
+ this.pendingSeen.add(uid);
669
+ }
670
+ }
671
+ /**
672
+ * Flush the batch to the server. Never throws — a mailbox we cannot flag is
673
+ * not worth dropping mail over; those UIDs simply come back on the next drain.
674
+ */
675
+ async _flushSeen() {
676
+ if (this.imap === void 0 || this.pendingSeen.size === 0) return;
677
+ const uids = [...this.pendingSeen];
678
+ this.pendingSeen.clear();
679
+ try {
680
+ await this.imap.markSeen(uids);
681
+ } catch (err) {
682
+ console.error(
683
+ `[email] could not flag ${uids.length} message(s) \\Seen (they will be re-delivered):`,
684
+ err instanceof Error ? err.message : err
685
+ );
686
+ }
687
+ }
688
+ async _dispatchOrDrop(uid, rawBuffer, headers) {
689
+ const event = await normalizeEmail(rawBuffer, {
690
+ botAddress: this.options.address,
691
+ ...this.options.maxBodyChars !== void 0 ? { maxBodyChars: this.options.maxBodyChars } : {}
692
+ });
693
+ if (event.email.fromAddress === this.options.address.toLowerCase()) {
694
+ console.warn(`[email] dropped own-address loopback (uid=${uid})`);
695
+ return;
696
+ }
697
+ if (this.options.allowAutomated !== true && isAutomatedSender(event.email.fromAddress, headers)) {
698
+ console.warn(`[email] dropped automated sender: ${event.email.fromAddress}`);
699
+ return;
700
+ }
701
+ if (!isAllowedSender(event.email.fromAddress, this.options.allowedSenders)) {
702
+ console.warn(`[email] sender not in allowlist: ${event.email.fromAddress}`);
703
+ return;
704
+ }
705
+ this.threadStore.recordFromInbound(event);
706
+ if (this.handler !== void 0) await this.handler(event);
707
+ }
708
+ /** Test seams. @internal */
709
+ get _seenUidsSize() {
710
+ return this.seenUids.size;
711
+ }
712
+ get _threadStoreSize() {
713
+ return this.threadStore.size;
714
+ }
715
+ /** Test seam — wait for queued dispatches to drain. @internal */
716
+ async _drainDispatchQueue() {
717
+ await this.dispatchQueue;
718
+ }
719
+ /** Test seam — drain IMAP UNSEEN now + flush dispatch queue. @internal */
720
+ async _drainNow() {
721
+ await this._drainUnseen();
722
+ await this.dispatchQueue;
723
+ }
724
+ /**
725
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
726
+ *
727
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
728
+ * named as the handler's failure rather than the platform's, and delivery continues.
729
+ */
730
+ async deliver(event) {
731
+ return this.runHandler(this.handler, event);
732
+ }
733
+ };
734
+ function replyHeaders(context) {
735
+ if (context === void 0) return { subject: "Message from agent" };
736
+ return {
737
+ subject: context.subject.startsWith("Re:") ? context.subject : `Re: ${context.subject}`,
738
+ inReplyTo: context.lastMessageId,
739
+ // EC-6: dedup the chain.
740
+ references: Array.from(/* @__PURE__ */ new Set([...context.references, context.lastMessageId]))
741
+ };
742
+ }
743
+ async function sendWithTextFallback(smtp, base, html) {
744
+ try {
745
+ return await smtp.send(html === void 0 ? base : { ...base, html });
746
+ } catch (err) {
747
+ if (html === void 0) throw err;
748
+ process.stderr.write(
749
+ "[gateway-email] the server rejected the html part; retrying with text only\n"
750
+ );
751
+ return smtp.send(base);
752
+ }
753
+ }
754
+
755
+ // ../../shared/channel-config-field.ts
756
+ var field = (key, env, description, { required = true, secret = false } = {}) => ({ key, required, secret, env, description });
757
+
758
+ // ../../shared/env-value-readers.ts
759
+ function readEnvNumber(invalid2, config, key) {
760
+ const value = config[key];
761
+ if (value === void 0) return void 0;
762
+ if (typeof value === "number" && Number.isFinite(value)) return value;
763
+ if (typeof value === "string" && /^[0-9]+$/.test(value.trim())) {
764
+ const parsed = Number(value.trim());
765
+ if (Number.isFinite(parsed)) return parsed;
766
+ }
767
+ throw invalid2(key, "a number or a digit string");
768
+ }
769
+ function readEnvBoolean(invalid2, config, key) {
770
+ const value = config[key];
771
+ if (value === void 0) return void 0;
772
+ if (value === true || value === "true") return true;
773
+ if (value === false || value === "false") return false;
774
+ throw invalid2(key, 'a boolean or the string "true" or "false"');
775
+ }
776
+ function envValueReaders(invalid2) {
777
+ return {
778
+ number: (config, key) => readEnvNumber(invalid2, config, key),
779
+ boolean: (config, key) => readEnvBoolean(invalid2, config, key)
780
+ };
781
+ }
782
+
783
+ // src/channel.ts
784
+ var readers = loopzeroGateway.channelConfigReaders("gateway-email");
785
+ var { invalid } = readers;
786
+ var isAbsent = (value) => value === void 0;
787
+ var read = {
788
+ ...envValueReaders(invalid),
789
+ string: readers.requiredString,
790
+ optionalString: (config, key) => config[key] === void 0 ? void 0 : readers.requiredString(config, key),
791
+ list(config, key) {
792
+ const value = config[key];
793
+ if (value === void 0) return void 0;
794
+ if (typeof value === "string") {
795
+ return value.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
796
+ }
797
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
798
+ throw invalid(key, "an array of strings or a comma-separated string");
799
+ }
800
+ };
801
+ function readCursorStore(config) {
802
+ const value = config.cursorStore;
803
+ if (isAbsent(value)) return void 0;
804
+ const store = value;
805
+ if (typeof value !== "object" || typeof store?.load !== "function" || typeof store.save !== "function") {
806
+ throw invalid("cursorStore", "an object with load and save functions");
807
+ }
808
+ return value;
809
+ }
810
+ var CONFIG = [
811
+ field(
812
+ "address",
813
+ "EMAIL_ADDRESS",
814
+ "Email address the bot listens on; also the From address of outbound mail."
815
+ ),
816
+ field("password", "EMAIL_PASSWORD", "Password or app password for the IMAP and SMTP login.", {
817
+ secret: true
818
+ }),
819
+ field("imapHost", "EMAIL_IMAP_HOST", "IMAP server host name."),
820
+ field("imapPort", "EMAIL_IMAP_PORT", "IMAP server port.", { required: false }),
821
+ field("smtpHost", "EMAIL_SMTP_HOST", "SMTP server host name."),
822
+ field("smtpPort", "EMAIL_SMTP_PORT", "SMTP server port.", { required: false }),
823
+ field("fromName", "EMAIL_FROM_NAME", "Display name for outbound mail.", { required: false }),
824
+ field(
825
+ "allowedSenders",
826
+ "EMAIL_ALLOWED_SENDERS",
827
+ "Sender addresses allowed through, as a list or comma-separated string.",
828
+ { required: false }
829
+ ),
830
+ field(
831
+ "allowAutomated",
832
+ "EMAIL_ALLOW_AUTOMATED",
833
+ "When true, automated senders (no-reply, bulk mail) are not filtered out.",
834
+ { required: false }
835
+ ),
836
+ field("pollIntervalMs", "EMAIL_POLL_INTERVAL_MS", "Milliseconds between mailbox polls.", {
837
+ required: false
838
+ }),
839
+ field("maxBodyChars", "EMAIL_MAX_BODY_CHARS", "Longest inbound body kept, in characters.", {
840
+ required: false
841
+ }),
842
+ {
843
+ key: "cursorStore",
844
+ required: false,
845
+ secret: false,
846
+ description: "Programmatic store that persists the IMAP cursor; no env binding."
847
+ }
848
+ ];
849
+ var emailChannel = {
850
+ platform: "email",
851
+ transport: "socket",
852
+ senderIdentity: {
853
+ unauthenticated: "an email From header is written by the sender and can be forged"
854
+ },
855
+ config: CONFIG,
856
+ create(config) {
857
+ const address = read.string(config, "address");
858
+ const password = read.string(config, "password");
859
+ const imapHost = read.string(config, "imapHost");
860
+ const smtpHost = read.string(config, "smtpHost");
861
+ const imapPort = read.number(config, "imapPort");
862
+ const smtpPort = read.number(config, "smtpPort");
863
+ const fromName = read.optionalString(config, "fromName");
864
+ const allowedSenders = read.list(config, "allowedSenders");
865
+ const allowAutomated = read.boolean(config, "allowAutomated");
866
+ const pollIntervalMs = read.number(config, "pollIntervalMs");
867
+ const maxBodyChars = read.number(config, "maxBodyChars");
868
+ const cursorStore = readCursorStore(config);
869
+ return new EmailAdapter({
870
+ address,
871
+ password,
872
+ imapHost,
873
+ smtpHost,
874
+ ...imapPort === void 0 ? {} : { imapPort },
875
+ ...smtpPort === void 0 ? {} : { smtpPort },
876
+ ...fromName === void 0 ? {} : { fromName },
877
+ ...allowedSenders === void 0 ? {} : { allowedSenders },
878
+ ...allowAutomated === void 0 ? {} : { allowAutomated },
879
+ ...pollIntervalMs === void 0 ? {} : { pollIntervalMs },
880
+ ...maxBodyChars === void 0 ? {} : { maxBodyChars },
881
+ ...cursorStore === void 0 ? {} : { cursorStore }
882
+ });
883
+ }
884
+ };
885
+
886
+ exports.EmailAdapter = EmailAdapter;
887
+ exports.SeenUidSet = SeenUidSet;
888
+ exports.ThreadStore = ThreadStore;
889
+ exports.emailChannel = emailChannel;
890
+ exports.extractAddr = extractAddr;
891
+ exports.isAllowedSender = isAllowedSender;
892
+ exports.isAutomatedSender = isAutomatedSender;
893
+ exports.mapEmailError = mapEmailError;
894
+ exports.normalizeEmail = normalizeEmail;
895
+ //# sourceMappingURL=index.cjs.map
896
+ //# sourceMappingURL=index.cjs.map