@im-more/dsh-mail 0.0.0-stage → 0.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 (66) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +14 -0
  3. package/lib/index.js +1334 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +49 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +189 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +51 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +55 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/decode.d.ts +60 -0
  14. package/lib/types/decode.d.ts.map +1 -0
  15. package/lib/types/decode.js +195 -0
  16. package/lib/types/decode.js.map +1 -0
  17. package/lib/types/errors.d.ts +33 -0
  18. package/lib/types/errors.d.ts.map +1 -0
  19. package/lib/types/errors.js +156 -0
  20. package/lib/types/errors.js.map +1 -0
  21. package/lib/types/html.d.ts +30 -0
  22. package/lib/types/html.d.ts.map +1 -0
  23. package/lib/types/html.js +121 -0
  24. package/lib/types/html.js.map +1 -0
  25. package/lib/types/index.d.ts +11 -0
  26. package/lib/types/index.d.ts.map +1 -0
  27. package/lib/types/index.js +10 -0
  28. package/lib/types/index.js.map +1 -0
  29. package/lib/types/mail.d.ts +24 -0
  30. package/lib/types/mail.d.ts.map +1 -0
  31. package/lib/types/mail.js +26 -0
  32. package/lib/types/mail.js.map +1 -0
  33. package/lib/types/media.d.ts +52 -0
  34. package/lib/types/media.d.ts.map +1 -0
  35. package/lib/types/media.js +81 -0
  36. package/lib/types/media.js.map +1 -0
  37. package/lib/types/modes/html.d.ts +13 -0
  38. package/lib/types/modes/html.d.ts.map +1 -0
  39. package/lib/types/modes/html.js +70 -0
  40. package/lib/types/modes/html.js.map +1 -0
  41. package/lib/types/modes/shared.d.ts +114 -0
  42. package/lib/types/modes/shared.d.ts.map +1 -0
  43. package/lib/types/modes/shared.js +185 -0
  44. package/lib/types/modes/shared.js.map +1 -0
  45. package/lib/types/send.d.ts +26 -0
  46. package/lib/types/send.d.ts.map +1 -0
  47. package/lib/types/send.js +58 -0
  48. package/lib/types/send.js.map +1 -0
  49. package/lib/types/transport/imap.d.ts +95 -0
  50. package/lib/types/transport/imap.d.ts.map +1 -0
  51. package/lib/types/transport/imap.js +354 -0
  52. package/lib/types/transport/imap.js.map +1 -0
  53. package/package.json +70 -3
  54. package/src/bot.ts +264 -0
  55. package/src/config.ts +98 -0
  56. package/src/decode.ts +275 -0
  57. package/src/errors.ts +199 -0
  58. package/src/html.ts +137 -0
  59. package/src/index.ts +32 -0
  60. package/src/mail.ts +46 -0
  61. package/src/media.ts +102 -0
  62. package/src/modes/html.ts +105 -0
  63. package/src/modes/shared.ts +285 -0
  64. package/src/send.ts +87 -0
  65. package/src/transport/imap.ts +418 -0
  66. package/README.md +0 -3
package/lib/index.js ADDED
@@ -0,0 +1,1334 @@
1
+ import { Adapter, ElementRegistry, PlatformError, Status } from "@deepseek-ai/cordis-plugin-im-core";
2
+ import z from "@deepseek-ai/schemastery";
3
+ import { h, isPhrasingContainer } from "@deepseek-ai/satori-element";
4
+ import { SyntaxKind, parse } from "html5parser";
5
+ import { randomUUID } from "node:crypto";
6
+ import { simpleParser } from "mailparser";
7
+ import NodeIMAP from "node-imap";
8
+ import { createTransport } from "nodemailer";
9
+ // lib/types/config.js
10
+ /** Validated Mail adapter configuration. */
11
+ const Config = z.object({
12
+ username: z.string().required(),
13
+ password: z.string().role("secret").required(),
14
+ selfId: z.string(),
15
+ name: z.string(),
16
+ subject: z.string().default("Koishi"),
17
+ mailbox: z.string().default("INBOX"),
18
+ imap: z.intersect([z.object({
19
+ host: z.string().required(),
20
+ tls: z.boolean().default(true)
21
+ }), z.union([z.object({
22
+ tls: z.const(true),
23
+ port: z.natural().default(993)
24
+ }), z.object({
25
+ tls: z.const(false),
26
+ port: z.natural().default(143)
27
+ })])]),
28
+ smtp: z.intersect([z.object({
29
+ host: z.string().required(),
30
+ tls: z.boolean().default(true)
31
+ }), z.union([z.object({
32
+ tls: z.const(true),
33
+ port: z.natural().default(465)
34
+ }), z.object({
35
+ tls: z.const(false),
36
+ port: z.natural().default(25)
37
+ })])]),
38
+ retry: z.object({
39
+ times: z.natural().default(6),
40
+ interval: z.natural().role("ms").default(5e3),
41
+ lazy: z.natural().role("ms").default(6e4)
42
+ }).default({}),
43
+ media: z.object({
44
+ stagingTtlMs: z.natural().role("ms").default(6e5),
45
+ maxStagedBytes: z.natural().default(67108864)
46
+ }).default({})
47
+ });
48
+ /**
49
+ * The address this bot answers as: `selfId` when given, else the login name.
50
+ * @param config - the validated adapter configuration.
51
+ * @returns the bot's own address.
52
+ */
53
+ function addressOf(config) {
54
+ return config.selfId || config.username;
55
+ }
56
+ // lib/types/html.js
57
+ /**
58
+ * HTML body decoding: an HTML string from `mailparser` becomes Satori elements, following the upstream traversal
59
+ * (`html5parser` + `visit`) instead of a text extraction.
60
+ *
61
+ * Two deliberate deviations from upstream, both one-line bug fixes (design §5.2): an unknown named character
62
+ * reference is kept literally instead of replacing the whole text node, and an image's `alt` is read from `alt`
63
+ * rather than from `src`.
64
+ */
65
+ /** The named character references the traversal decodes (upstream's table). */
66
+ const entities = {
67
+ nbsp: " ",
68
+ cent: "¢",
69
+ pound: "£",
70
+ yen: "¥",
71
+ euro: "€",
72
+ copy: "©",
73
+ reg: "®",
74
+ lt: "<",
75
+ gt: ">",
76
+ quot: "\"",
77
+ amp: "&",
78
+ apos: "'"
79
+ };
80
+ /**
81
+ * Decode named, decimal and hexadecimal character references of one text run.
82
+ *
83
+ * A named reference outside {@link entities} is not an error: it stays as written. (Upstream returned the whole text
84
+ * node in that case, which duplicated everything around the unknown reference.)
85
+ *
86
+ * @param text - raw character data of one HTML text node.
87
+ * @returns the text with the known references decoded.
88
+ */
89
+ function decodeHE(text) {
90
+ return text.replace(/&(([a-z0-9]+)|(#[0-9]{1,6})|(#x[0-9a-fA-F]{1,6}));/gi, (raw, _whole, name, dec, hex) => {
91
+ if (name) return entities[name] ?? raw;
92
+ if (dec) return String.fromCharCode(Number(dec.substring(1)));
93
+ if (hex) return String.fromCharCode(parseInt(hex.substring(2), 16));
94
+ return raw;
95
+ });
96
+ }
97
+ /** One attribute of a parsed tag, as written in the source. */
98
+ function attribute(node, name) {
99
+ return node.attributeMap?.[name]?.value?.value;
100
+ }
101
+ /** Tags whose whole subtree is not part of the message body. */
102
+ const IGNORED = /* @__PURE__ */ new Set([
103
+ "head",
104
+ "script",
105
+ "style",
106
+ "meta"
107
+ ]);
108
+ /**
109
+ * Convert an HTML body into elements.
110
+ *
111
+ * @param html - the `text/html` part `mailparser` decoded.
112
+ * @param options - `onSubscript` reports a dropped `<sub>`/`<sup>` (the vocabulary has neither).
113
+ * @returns the elements of the body, in document order.
114
+ */
115
+ function htmlToElements(html, options = {}) {
116
+ const visit = (nodes) => {
117
+ const out = [];
118
+ for (const node of nodes) {
119
+ if (node.type === SyntaxKind.Text) {
120
+ out.push(h.text(decodeHE(node.value).trim() || " "));
121
+ continue;
122
+ }
123
+ const body = node.body ?? [];
124
+ switch (node.name) {
125
+ case "a":
126
+ out.push(h("a", { href: attribute(node, "href") || "#" }, ...visit(body)));
127
+ break;
128
+ case "strong":
129
+ case "b":
130
+ out.push(h("b", ...visit(body)));
131
+ break;
132
+ case "br":
133
+ out.push(h("br"));
134
+ break;
135
+ case "code":
136
+ out.push(h("code", ...visit(body)));
137
+ break;
138
+ case "s":
139
+ case "del":
140
+ out.push(h("s", ...visit(body)));
141
+ break;
142
+ case "i":
143
+ case "em":
144
+ out.push(h("i", ...visit(body)));
145
+ break;
146
+ case "p":
147
+ out.push(h("p", ...visit(body)));
148
+ break;
149
+ case "sub":
150
+ case "sup":
151
+ options.onSubscript?.();
152
+ out.push(...visit(body));
153
+ break;
154
+ case "u":
155
+ out.push(h("u", ...visit(body)));
156
+ break;
157
+ case "img": {
158
+ const src = attribute(node, "src");
159
+ if (src === void 0 || !/^(data|https?):/i.test(src)) break;
160
+ const alt = attribute(node, "alt");
161
+ out.push(h("img", {
162
+ src,
163
+ ...alt === void 0 ? {} : { alt }
164
+ }));
165
+ break;
166
+ }
167
+ default:
168
+ if (IGNORED.has(node.name)) break;
169
+ out.push(...visit(body));
170
+ }
171
+ }
172
+ return out;
173
+ };
174
+ return visit(parse(html, { setAttributeMap: true }));
175
+ }
176
+ // lib/types/decode.js
177
+ /**
178
+ * Inbound decoding: one parsed message becomes one {@link InboundMessage}.
179
+ *
180
+ * The message is addressed to the sender's own mailbox (`chat.id = private:<address>`), the `Message-ID` is the
181
+ * message identity (and the intake dedupe key), `In-Reply-To`/`References` become `quote`/`referrer`, and attachments
182
+ * become media elements whose `src` is the bot's `satori:` attachment route. Messages sent by the bot itself are
183
+ * skipped, because a copy arriving back in the mailbox would otherwise answer itself.
184
+ */
185
+ /**
186
+ * The element kind of one attachment.
187
+ * @param mime - the attachment's MIME type.
188
+ * @returns the vocabulary tag the attachment is shown as.
189
+ */
190
+ function attachmentKind(mime) {
191
+ const type = mime.split(";")[0]?.trim().toLowerCase() ?? "";
192
+ if (type.startsWith("image/")) return "img";
193
+ if (type.startsWith("audio/")) return "audio";
194
+ if (type.startsWith("video/")) return "video";
195
+ return "file";
196
+ }
197
+ /** Every address of the given headers, groups expanded; entries without an address are dropped. */
198
+ function addressesOf(...headers) {
199
+ const out = [];
200
+ for (const header of headers) {
201
+ if (header === void 0) continue;
202
+ for (const object of Array.isArray(header) ? header : [header]) for (const item of object.value) {
203
+ const list = item.group ?? [item];
204
+ for (const address of list) if (address.address) out.push(address);
205
+ }
206
+ }
207
+ return out;
208
+ }
209
+ /** `References:` as a list of `<…>` values (mailparser gives a string for a single reference). */
210
+ function referencesOf(mail) {
211
+ if (mail.references === void 0) return [];
212
+ return Array.isArray(mail.references) ? [...mail.references] : [mail.references];
213
+ }
214
+ /** A stable id for a message that carries no `Message-ID`. */
215
+ function synthesizedId(uid, selfId) {
216
+ const at = selfId.lastIndexOf("@");
217
+ return `<${uid}@${at < 0 ? selfId : selfId.slice(at + 1)}>`;
218
+ }
219
+ /** The display name of an address, when it has one. */
220
+ function nameOf(address) {
221
+ const name = address.name.trim();
222
+ return name === "" ? void 0 : name;
223
+ }
224
+ /** Media elements of the message's attachments, in MIME order, served by the attachment route. */
225
+ function attachmentElements(bot, mail, source) {
226
+ return mail.attachments.map((attachment, index) => {
227
+ const kind = attachmentKind(attachment.contentType);
228
+ const filename = attachment.filename ?? `attachment-${index + 1}`;
229
+ const src = bot.getInternalUrl(`/messages/${source.uid}/attachments/${index}`, { box: source.mailbox });
230
+ switch (kind) {
231
+ case "img": return h("img", {
232
+ src,
233
+ ...attachment.filename === void 0 ? {} : { alt: attachment.filename }
234
+ });
235
+ case "audio": return h("audio", {
236
+ src,
237
+ name: filename
238
+ });
239
+ case "video": return h("video", {
240
+ src,
241
+ name: filename
242
+ });
243
+ case "file": return h("file", {
244
+ src,
245
+ name: filename
246
+ });
247
+ }
248
+ });
249
+ }
250
+ /** The body elements of one message: the HTML traversal, or the plain text part, plus the attachments. */
251
+ function bodyElements(bot, mail, source) {
252
+ const body = [];
253
+ if (!mail.html) {
254
+ const text = mail.text ?? "";
255
+ if (text !== "") body.push(h.text(text));
256
+ } else {
257
+ const log = bot.log;
258
+ body.push(...htmlToElements(mail.html, log === void 0 ? {} : { onSubscript: () => {
259
+ log("mail: dropped <sub>/<sup>, the vocabulary has no subscript");
260
+ } }));
261
+ }
262
+ body.push(...attachmentElements(bot, mail, source));
263
+ return body;
264
+ }
265
+ /**
266
+ * Decode one parsed message.
267
+ *
268
+ * @param bot - the adapter the message arrived for (identity, mailbox, `satori:` route base).
269
+ * @param mail - the parsed MIME message.
270
+ * @param source - the IMAP coordinates the message was read at.
271
+ * @returns the inbound message, or `undefined` when the message cannot be routed (no sender address, or the bot's
272
+ * own message).
273
+ */
274
+ function decodeMessage(bot, mail, source) {
275
+ const from = mail.from?.value[0];
276
+ if (from?.address === void 0 || from.address === "") {
277
+ bot.log?.("mail: dropped a message without a sender address");
278
+ return;
279
+ }
280
+ if (from.address.toLowerCase() === bot.selfId.toLowerCase()) {
281
+ bot.log?.(`mail: dropped a message from the bot's own address (${from.address})`);
282
+ return;
283
+ }
284
+ const address = from.address;
285
+ const name = nameOf(from);
286
+ const messageId = mail.messageId ?? synthesizedId(source.uid, bot.selfId);
287
+ const replyTo = mail.replyTo?.value[0]?.address;
288
+ const references = referencesOf(mail);
289
+ const body = bodyElements(bot, mail, source);
290
+ const content = h("message", {}, ...body.length === 0 ? [h("raw", {
291
+ platform: "mail",
292
+ type: "message",
293
+ data: {
294
+ messageId,
295
+ contentType: mail.headers.get("content-type")
296
+ }
297
+ }, h.text(""))] : body);
298
+ const recipients = addressesOf(mail.to, mail.cc);
299
+ const seen = /* @__PURE__ */ new Set();
300
+ const users = [];
301
+ let mentionsSelf = false;
302
+ for (const recipient of recipients) {
303
+ if (recipient.address === void 0) continue;
304
+ const lower = recipient.address.toLowerCase();
305
+ if (lower === bot.selfId.toLowerCase()) {
306
+ mentionsSelf = true;
307
+ continue;
308
+ }
309
+ if (seen.has(lower)) continue;
310
+ seen.add(lower);
311
+ const recipientName = nameOf(recipient);
312
+ users.push({
313
+ id: recipient.address,
314
+ ...recipientName === void 0 ? {} : { name: recipientName }
315
+ });
316
+ }
317
+ const chat = {
318
+ id: `private:${address}`,
319
+ type: "direct",
320
+ ...name === void 0 ? {} : { name }
321
+ };
322
+ const sender = {
323
+ id: address,
324
+ ...name === void 0 ? {} : { name }
325
+ };
326
+ const referrer = {
327
+ address,
328
+ messageId,
329
+ ...mail.subject === void 0 ? {} : { subject: mail.subject },
330
+ ...replyTo === void 0 ? {} : { replyTo },
331
+ ...references.length === 0 ? {} : { references },
332
+ uid: source.uid,
333
+ mailbox: source.mailbox
334
+ };
335
+ return {
336
+ id: messageId,
337
+ chat,
338
+ sender,
339
+ content,
340
+ ...mail.inReplyTo === void 0 ? {} : { quote: { id: mail.inReplyTo } },
341
+ mentions: {
342
+ self: mentionsSelf,
343
+ all: false,
344
+ users
345
+ },
346
+ time: mail.date === void 0 ? Date.now() : +mail.date,
347
+ referrer,
348
+ raw: {
349
+ uid: source.uid,
350
+ mailbox: source.mailbox,
351
+ size: source.size
352
+ }
353
+ };
354
+ }
355
+ // lib/types/errors.js
356
+ /**
357
+ * SMTP failures and their mapping onto the core platform taxonomy.
358
+ *
359
+ * `nodemailer` reports one failed mail transaction as an `Error` carrying `code` (the stage), `command` (the SMTP
360
+ * verb) and `responseCode` (the server's numeric answer). The stage alone cannot say whether the message left this
361
+ * host: a connection loss after `DATA` started says nothing, while a refusal before the body was sent means the
362
+ * server certainly did not accept the message. `published` is decided from that, the error kind from the stage and
363
+ * the refined by the response code.
364
+ */
365
+ /** Read the classification fields off a caught value (a non-`Error` carries none of them). */
366
+ function failureOf(error) {
367
+ if (error instanceof Error) {
368
+ const value = error;
369
+ return {
370
+ name: value.name,
371
+ message: value.message,
372
+ ...typeof value.code === "string" ? { code: value.code } : {},
373
+ ...typeof value.command === "string" ? { command: value.command } : {},
374
+ ...typeof value.response === "string" ? { response: value.response } : {},
375
+ ...typeof value.responseCode === "number" ? { responseCode: value.responseCode } : {}
376
+ };
377
+ }
378
+ return { message: String(error) };
379
+ }
380
+ /** Whether a caught value is the abort error of a cancelled operation. */
381
+ function isCancellation(error) {
382
+ return (error instanceof Error || error instanceof DOMException) && error.name === "AbortError";
383
+ }
384
+ /** Whether a response code is a temporary refusal (RFC 5321 §4.2). */
385
+ function isTemporary(code) {
386
+ return code >= 400 && code < 500;
387
+ }
388
+ /** Whether a response code is a permanent refusal (RFC 5321 §4.2). */
389
+ function isPermanent(code) {
390
+ return code >= 500 && code < 600;
391
+ }
392
+ /**
393
+ * Refine a stage's default kind with the meaning of the server's response code.
394
+ * @param code - the numeric SMTP response, when the error carried one.
395
+ * @param fallback - the kind the stage implies on its own.
396
+ * @returns the refined kind.
397
+ */
398
+ function refineKind(code, fallback) {
399
+ switch (code) {
400
+ case 421:
401
+ case 450:
402
+ case 451: return "retryable";
403
+ case 452: return "rate-limit";
404
+ case 534:
405
+ case 535: return "permission";
406
+ case 550: return "not-found";
407
+ case 552: return "limit";
408
+ case 553:
409
+ case 554: return "invalid";
410
+ }
411
+ if (isTemporary(code)) return "retryable";
412
+ if (isPermanent(code)) return "invalid";
413
+ return fallback;
414
+ }
415
+ /** The `RCPT TO` kind of one rejection (550 names a missing mailbox, other 5xx codes deny the recipient). */
416
+ function recipientKind(code) {
417
+ if (code === 550) return "not-found";
418
+ if (isPermanent(code)) return "permission";
419
+ return refineKind(code, "retryable");
420
+ }
421
+ /** Whether the error says the message grew past the server's size limit before `DATA` began. */
422
+ function isOversized(failure) {
423
+ return /larger than allowed|message size|maximum message size/i.test(failure.message ?? failure.response ?? "");
424
+ }
425
+ /**
426
+ * Map any failure of a publication onto the core taxonomy.
427
+ *
428
+ * `published: 'no'` is claimed only when the transaction provably had not handed the body over when it failed: an
429
+ * authentication or envelope refusal, a `DATA` command refusal, or a completed `DATA` the server rejected. A transport
430
+ * failure without a server answer leaves the outcome unknown, because `nodemailer` reports a connection that died
431
+ * while the body was in flight exactly like a refused connection; a `354` answer says the body had started.
432
+ *
433
+ * @param error - the caught failure.
434
+ * @returns the classified platform error.
435
+ */
436
+ function classifyMailError(error) {
437
+ if (error instanceof PlatformError) return error;
438
+ const failure = failureOf(error);
439
+ const message = failure.message === void 0 ? "mail: send failed" : `mail: ${failure.message}`;
440
+ const cause = error;
441
+ const code = failure.responseCode;
442
+ const codeInit = code === void 0 ? {} : { code };
443
+ const make = (kind, published) => new PlatformError(kind, message, {
444
+ ...codeInit,
445
+ published,
446
+ cause
447
+ });
448
+ if (isCancellation(error)) return new PlatformError("fatal", message, {
449
+ published: "unknown",
450
+ cause
451
+ });
452
+ switch (failure.code) {
453
+ case "EAUTH": return make("permission", "no");
454
+ case "EENVELOPE": switch (failure.command) {
455
+ case "MAIL FROM": return make(code === 550 || code === void 0 ? "permission" : refineKind(code, "permission"), "no");
456
+ case "RCPT TO": return make(code === void 0 ? "invalid" : recipientKind(code), "no");
457
+ case "DATA": return make(code === void 0 ? "invalid" : refineKind(code, "invalid"), "no");
458
+ default: return make(code === void 0 ? "invalid" : refineKind(code, "invalid"), "no");
459
+ }
460
+ case "EMESSAGE":
461
+ if (failure.command === "MAIL FROM" && isOversized(failure)) return make("limit", "no");
462
+ if (failure.command === "DATA") return make(code === void 0 ? "invalid" : refineKind(code, "invalid"), "no");
463
+ return make(code === void 0 ? "invalid" : refineKind(code, "invalid"), "no");
464
+ case "ECONNECTION":
465
+ case "ETIMEDOUT": {
466
+ if (code === void 0) return make("retryable", "unknown");
467
+ const published = code === 354 ? "unknown" : "no";
468
+ return make(refineKind(code, "retryable"), published);
469
+ }
470
+ case "EDNS": return make("retryable", "no");
471
+ case "EPROTOCOL": return make("retryable", "unknown");
472
+ case "ESTREAM": return make("invalid", "no");
473
+ default: return make("retryable", "unknown");
474
+ }
475
+ }
476
+ // lib/types/media.js
477
+ /**
478
+ * Bounded in-memory staging for outbound attachments.
479
+ *
480
+ * SMTP has no upload step: the bytes must ride the MIME body of the message that references them, and `serialize` is
481
+ * pure, so `upload` fetches and stages the bytes and `sendPayload` reads them back by key. Entries expire and the
482
+ * whole store is bounded. A key is the Content-ID of its attachment (and the `cid:` target of the HTML part), which
483
+ * makes it safe inside a `Message-ID`-style bracket.
484
+ *
485
+ * A key is single-use: the resolved resource carries `expiresAt: 0`, so the pipeline cache never reuses a key whose
486
+ * bytes a successful send released.
487
+ */
488
+ var MediaStaging = class {
489
+ ttlMs;
490
+ maxBytes;
491
+ entries = /* @__PURE__ */ new Map();
492
+ bytes = 0;
493
+ constructor(ttlMs, maxBytes) {
494
+ this.ttlMs = ttlMs;
495
+ this.maxBytes = maxBytes;
496
+ }
497
+ /**
498
+ * Stage bytes under a fresh Content-ID.
499
+ * @param media - the bytes, their suggested name and MIME type.
500
+ * @returns the resource key `prepare` hands to `serialize`; it is also the `cid`.
501
+ */
502
+ stage(media) {
503
+ const now = Date.now();
504
+ this.prune(now);
505
+ const key = randomUUID().replaceAll("-", "");
506
+ const bytes = media.data.byteLength;
507
+ this.entries.set(key, {
508
+ media,
509
+ bytes,
510
+ expiresAt: now + this.ttlMs
511
+ });
512
+ this.bytes += bytes;
513
+ this.evict();
514
+ return {
515
+ key,
516
+ expiresAt: 0,
517
+ extra: {
518
+ name: media.name,
519
+ mime: media.mime
520
+ }
521
+ };
522
+ }
523
+ /**
524
+ * Read staged bytes without releasing them.
525
+ * @param key - a key returned by {@link stage}.
526
+ * @returns the staged media, or undefined once expired, evicted or released.
527
+ */
528
+ get(key) {
529
+ this.prune(Date.now());
530
+ return this.entries.get(key)?.media;
531
+ }
532
+ /**
533
+ * Read staged bytes and release them (a published message needs them no more).
534
+ * @param key - a key returned by {@link stage}.
535
+ * @returns the staged media, or undefined once expired, evicted or released.
536
+ */
537
+ take(key) {
538
+ this.prune(Date.now());
539
+ const entry = this.entries.get(key);
540
+ if (entry === void 0) return void 0;
541
+ this.entries.delete(key);
542
+ this.bytes -= entry.bytes;
543
+ return entry.media;
544
+ }
545
+ prune(now) {
546
+ for (const [key, entry] of this.entries) {
547
+ if (entry.expiresAt > now) continue;
548
+ this.entries.delete(key);
549
+ this.bytes -= entry.bytes;
550
+ }
551
+ }
552
+ evict() {
553
+ while (this.bytes > this.maxBytes) {
554
+ const oldest = this.entries.keys().next();
555
+ if (oldest.done === true) return;
556
+ const entry = this.entries.get(oldest.value);
557
+ this.entries.delete(oldest.value);
558
+ if (entry !== void 0) this.bytes -= entry.bytes;
559
+ }
560
+ }
561
+ };
562
+ // lib/types/modes/shared.js
563
+ /**
564
+ * The single `html` mode's node, draft and payload types, HTML escaping, media promotion and MIME payload assembly.
565
+ *
566
+ * A mail message is one MIME document, so `assemble` always returns exactly one draft: inline nodes accumulate into
567
+ * the HTML and plain-text parts, while media become `multipart/related` (`cid:`) or `multipart/mixed` attachments. A
568
+ * media element standing in phrasing content is lifted out of the text run and reported as `moved` (nothing is lost,
569
+ * only repositioned), which is the `mail-media-split` entry of the render report.
570
+ */
571
+ /** Escape character data of the HTML part. */
572
+ function escapeHtml(text) {
573
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
574
+ }
575
+ /** Escape one HTML attribute value (double-quoted). */
576
+ function escapeAttribute(text) {
577
+ return escapeHtml(text).replaceAll("\"", "&quot;");
578
+ }
579
+ /** One inline node. */
580
+ function inlineNode(html, text) {
581
+ return {
582
+ type: "inline",
583
+ html,
584
+ text
585
+ };
586
+ }
587
+ /**
588
+ * Split rendered children into one inline run and the media nodes that follow it.
589
+ * @param nodes - rendered children.
590
+ * @returns the concatenated HTML/text of the run and the media nodes, in source order.
591
+ */
592
+ function inlineRun(nodes) {
593
+ let html = "";
594
+ let text = "";
595
+ const rest = [];
596
+ for (const node of nodes) {
597
+ if (node.type === "media") {
598
+ rest.push(node);
599
+ continue;
600
+ }
601
+ html += node.html;
602
+ text += node.text;
603
+ }
604
+ return {
605
+ html,
606
+ text,
607
+ rest
608
+ };
609
+ }
610
+ /**
611
+ * Wrap the inline text of rendered children in one HTML tag; media of the subtree follows the wrapper.
612
+ * @param tag - the HTML tag name.
613
+ * @param nodes - rendered children.
614
+ * @param textSuffix - plain-text separator this block adds after its inline text.
615
+ * @returns the wrapper (when it has text) and the media nodes.
616
+ */
617
+ function inlineWrapper(tag, nodes, textSuffix = "") {
618
+ const { html, text, rest } = inlineRun(nodes);
619
+ if (html === "") return rest;
620
+ return [inlineNode(`<${tag}>${html}</${tag}>`, text + textSuffix), ...rest];
621
+ }
622
+ /** Resource kind of one media tag. */
623
+ function resourceKindOf(tag) {
624
+ switch (tag) {
625
+ case "img": return "image";
626
+ case "audio": return "audio";
627
+ case "video": return "video";
628
+ case "file": return "file";
629
+ }
630
+ }
631
+ /**
632
+ * Turn one media element into its node.
633
+ *
634
+ * An `http(s)` image, audio or video stays a reference to the remote URL: the recipient's client fetches it, so the
635
+ * sent message carries no copy. Everything else (and every file, which has no markup to carry a URL) is fetched and
636
+ * becomes an attachment. Media lifted out of phrasing content is reported as `moved`.
637
+ *
638
+ * @param el - one of `img`/`audio`/`video`/`file`.
639
+ * @param ctx - render context of the mode.
640
+ * @returns the inline node of a remote media reference, or the media node of an attachment.
641
+ */
642
+ function mediaNode(el, ctx) {
643
+ const tag = el.type;
644
+ const src = el.attrs.src;
645
+ if (src === "") throw new PlatformError("invalid", `mail: <${tag}> has no src, so nothing could be sent`, { published: "no" });
646
+ if (tag !== "file" && /^https?:\/\//i.test(src)) {
647
+ const escaped = escapeAttribute(src);
648
+ return inlineNode(tag === "img" ? `<img src="${escaped}">` : `<${tag} src="${escaped}" controls>`, "");
649
+ }
650
+ const parent = ctx.ancestors[ctx.ancestors.length - 1];
651
+ if (parent !== void 0 && isPhrasingContainer(parent.type)) ctx.report.moved.push({
652
+ tag,
653
+ reason: "mail-media-split",
654
+ path: ctx.stableId(el)
655
+ });
656
+ const meta = {};
657
+ if (el.type === "audio" || el.type === "video" || el.type === "file") {
658
+ if (el.attrs.name !== void 0) meta.name = el.attrs.name;
659
+ }
660
+ return {
661
+ type: "media",
662
+ tag,
663
+ ref: ctx.resource(resourceKindOf(tag), src, meta)
664
+ };
665
+ }
666
+ /** The recipient address of a chat id (`private:` is the direct-chat idiom of this platform). */
667
+ function addressOfChat(chatId) {
668
+ return chatId.startsWith("private:") ? chatId.slice(8) : chatId;
669
+ }
670
+ /** The adapter-private reply context of a publication, when the target carries one. */
671
+ function referrerOf(target) {
672
+ const referrer = target.referrer;
673
+ if (typeof referrer !== "object" || referrer === null) return void 0;
674
+ return referrer;
675
+ }
676
+ /** Fold a node stream into the one draft a mail message is. */
677
+ function assembleDraft(nodes, quote) {
678
+ return [{
679
+ nodes,
680
+ ...quote === void 0 ? {} : { quote }
681
+ }];
682
+ }
683
+ /**
684
+ * Build the `sendMail` options of one draft.
685
+ *
686
+ * The recipient is the chat's address, unless the message being answered named a `Reply-To`. A reply carries
687
+ * `In-Reply-To` (the quoted `Message-ID`) and `References` (the answered message's chain plus that id), and its
688
+ * subject is the answered subject with one `Re: ` prefix.
689
+ */
690
+ function serializeDraft(prepared, ctx) {
691
+ const draft = prepared.draft;
692
+ const config = ctx.bot.config;
693
+ const referrer = referrerOf(ctx.target);
694
+ const quote = draft.quote ?? ctx.quote;
695
+ let html = "";
696
+ let text = "";
697
+ const attachments = [];
698
+ for (const node of draft.nodes) {
699
+ if (node.type === "inline") {
700
+ html += node.html;
701
+ text += node.text;
702
+ continue;
703
+ }
704
+ const resolved = prepared.resolved.get(node.ref);
705
+ if (resolved === void 0) throw new Error("mail: an attachment was not prepared before serialize");
706
+ const extra = resolved.extra;
707
+ const cid = node.tag === "file" ? void 0 : resolved.key;
708
+ if (cid !== void 0) {
709
+ const escaped = escapeAttribute(cid);
710
+ html += node.tag === "img" ? `<img src="cid:${escaped}">` : `<${node.tag} src="cid:${escaped}" controls>`;
711
+ }
712
+ const suggested = node.ref.meta.name ?? extra?.name;
713
+ attachments.push({
714
+ key: resolved.key,
715
+ ...cid === void 0 ? {} : { cid },
716
+ filename: suggested !== void 0 && suggested !== "" ? suggested : `attachment-${attachments.length + 1}`,
717
+ contentType: node.ref.meta.mime ?? extra?.mime ?? "application/octet-stream"
718
+ });
719
+ }
720
+ return {
721
+ to: referrer?.replyTo ?? addressOfChat(ctx.target.chat.id),
722
+ subject: referrer?.subject ? `Re: ${referrer.subject}` : config.subject,
723
+ html: `<pre>${html}</pre>`,
724
+ text: text.trim() === "" ? "" : text,
725
+ ...quote === void 0 ? {} : { inReplyTo: quote },
726
+ ...quote === void 0 || referrer === void 0 ? {} : { references: [...referrer.references ?? [], quote] },
727
+ attachments
728
+ };
729
+ }
730
+ // lib/types/modes/html.js
731
+ /**
732
+ * `html` mode: the only mode, a single MIME message per logical message.
733
+ *
734
+ * Native tags are the inline subset a mail body can express (`b`/`i`/`u`/`s`/`code`/`pre`/`a`/`p`/`blockquote`/
735
+ * lists and media). Everything else takes the core fallback and is reported as degraded. `assemble` always returns
736
+ * one draft — mail has no message splitting — and `serialize` writes the `<pre>`-wrapped HTML, the plain-text
737
+ * alternative and the attachments.
738
+ */
739
+ /** An address a `mailto:` link can carry. */
740
+ const MAIL_ADDRESS = /^[^\s@<>]+@[^\s@<>]+$/;
741
+ /** Wrap the inline text of `children` in one tag, letting media of the subtree follow it. */
742
+ function wrap(tag, ctx, children, textSuffix = "") {
743
+ return inlineWrapper(tag, ctx.render(children), textSuffix);
744
+ }
745
+ /** Build the `html` mode. */
746
+ function createHtmlMode() {
747
+ return {
748
+ id: "html",
749
+ elements: new ElementRegistry().register("text", (el) => inlineNode(escapeHtml(el.attrs.content), el.attrs.content)).register("br", () => inlineNode("<br>", "\n")).register("p", (el, ctx) => wrap("p", ctx, el.children, "\n\n")).register("b", (el, ctx) => wrap("b", ctx, el.children)).register("i", (el, ctx) => wrap("i", ctx, el.children)).register("u", (el, ctx) => wrap("u", ctx, el.children)).register("s", (el, ctx) => wrap("s", ctx, el.children)).register("code", (el, ctx) => {
750
+ const content = ctx.text(el.children);
751
+ return inlineNode(`<code>${escapeHtml(content)}</code>`, content);
752
+ }).register("pre", (el, ctx) => {
753
+ const content = ctx.text(el.children);
754
+ return inlineNode(`<pre>${escapeHtml(content)}</pre>`, `${content}\n\n`);
755
+ }).register("blockquote", (el, ctx) => wrap("blockquote", ctx, el.children, "\n\n")).register("ul", (el, ctx) => wrap("ul", ctx, el.children)).register("ol", (el, ctx) => wrap("ol", ctx, el.children)).register("li", (el, ctx) => wrap("li", ctx, el.children, "\n")).register("a", (el, ctx) => {
756
+ const { html, text, rest } = inlineRun(ctx.render(el.children));
757
+ const href = el.attrs.href;
758
+ const label = html === "" ? escapeHtml(href) : html;
759
+ const plain = text === "" ? href : text;
760
+ const plainText = plain === href ? href : `${plain} (${href})`;
761
+ return [inlineNode(`<a href="${escapeAttribute(href)}">${label}</a>`, plainText), ...rest];
762
+ }).register("at", (el) => {
763
+ const id = el.attrs.id;
764
+ const label = el.attrs.name ?? id ?? el.attrs.type;
765
+ if (id !== void 0 && MAIL_ADDRESS.test(id)) return inlineNode(`<a href="mailto:${escapeAttribute(id)}">@${escapeHtml(id)}</a>`, `@${id}`);
766
+ return inlineNode(escapeHtml(`@${label}`), `@${label}`);
767
+ }, { variants: ["user"] }).register("img", (el, ctx) => mediaNode(el, ctx), { variants: ["inline"] }).register("audio", (el, ctx) => mediaNode(el, ctx)).register("video", (el, ctx) => mediaNode(el, ctx)).register("file", (el, ctx) => mediaNode(el, ctx)),
768
+ limits: {},
769
+ assemble: (nodes, envelope) => assembleDraft(nodes, envelope.quote),
770
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx)
771
+ };
772
+ }
773
+ // lib/types/send.js
774
+ /**
775
+ * Publish one logical message as one SMTP transaction.
776
+ *
777
+ * The staged bytes are read before sending and released only after the server accepted the message, so a failed or
778
+ * retried send still finds them. `confirmed` means the server answered `2xx` to `DATA` — the message left this host,
779
+ * not that its recipient ever receives it.
780
+ *
781
+ * @param deps - staging and the SMTP transport.
782
+ * @param payload - the serialized message.
783
+ * @param _target - the chat being published to (the payload already names its recipient).
784
+ * @param _ctx - send context (the quote is already part of the payload).
785
+ * @returns the published part; `id` is nodemailer's generated `Message-ID`.
786
+ */
787
+ async function sendPayload(deps, payload, _target, _ctx) {
788
+ const attachments = [];
789
+ for (const attachment of payload.attachments) {
790
+ const staged = deps.staging.get(attachment.key);
791
+ if (staged === void 0) throw new PlatformError("invalid", `mail: the attachment "${attachment.filename}" is no longer staged, nothing was sent`, { published: "no" });
792
+ attachments.push({
793
+ filename: attachment.filename,
794
+ content: Buffer.from(staged.data),
795
+ contentType: attachment.contentType,
796
+ ...attachment.cid === void 0 ? {} : { cid: attachment.cid }
797
+ });
798
+ }
799
+ const options = {
800
+ to: payload.to,
801
+ subject: payload.subject,
802
+ html: payload.html,
803
+ text: payload.text,
804
+ ...payload.inReplyTo === void 0 ? {} : { inReplyTo: payload.inReplyTo },
805
+ ...payload.references === void 0 ? {} : { references: payload.references },
806
+ ...attachments.length === 0 ? {} : { attachments }
807
+ };
808
+ const id = await deps.smtp.send(options);
809
+ if (!id) throw new PlatformError("invalid", "mail: the server accepted the message without a Message-ID", { published: "unknown" });
810
+ for (const attachment of payload.attachments) deps.staging.take(attachment.key);
811
+ return {
812
+ id,
813
+ kind: "message",
814
+ time: Date.now(),
815
+ referrer: {
816
+ address: payload.to,
817
+ messageId: id,
818
+ subject: payload.subject
819
+ }
820
+ };
821
+ }
822
+ // lib/types/transport/imap.js
823
+ /**
824
+ * IMAP inbound transport: connection lifecycle, scanning, acknowledgement and reconnection.
825
+ *
826
+ * `node-imap` owns IDLE/NOOP keepalive internally, so this transport never sends a keepalive itself. It starts one
827
+ * `Connection` and reuses it for every reconnect (the library resets its own state and keeps listeners). Every
828
+ * `\\Seen` write happens only after the host accepted the message: a crash or a failed intake therefore leaves the
829
+ * message unread, and the next scan delivers it again (the host dedupes by `Message-ID`). A malformed message is the
830
+ * one exception: it is marked seen, because retrying it would fail forever.
831
+ */
832
+ /**
833
+ * The delay before the next connection attempt.
834
+ *
835
+ * The fast budget counts consecutive failures: the first `retry.times` dials wait `retry.interval`, later ones wait
836
+ * `retry.lazy`. A successful connection resets the count, so a flap is retried fast again.
837
+ *
838
+ * @param failures - consecutive failures before this attempt.
839
+ * @param retry - the configured retry budget and delays.
840
+ * @returns the delay in milliseconds.
841
+ */
842
+ function reconnectDelay(failures, retry) {
843
+ return failures < retry.times ? retry.interval : retry.lazy;
844
+ }
845
+ /** The error message of a caught value. */
846
+ function messageOf$1(error) {
847
+ return error instanceof Error ? error.message : String(error);
848
+ }
849
+ /**
850
+ * Read and parse one fetched message. The body stream is piped into `simpleParser` as soon as it arrives (an unread
851
+ * stream would block the parser), so the result is a promise of either the parsed message, a parse error or neither
852
+ * when the server sent no body.
853
+ */
854
+ function readMessage(message) {
855
+ let uid;
856
+ let size = 0;
857
+ let parsing;
858
+ return new Promise((resolve) => {
859
+ message.on("body", (stream, info) => {
860
+ size = info.size;
861
+ parsing = simpleParser(stream);
862
+ parsing.catch(() => void 0);
863
+ });
864
+ message.on("attributes", (attributes) => {
865
+ uid = attributes.uid;
866
+ });
867
+ message.on("end", () => {
868
+ const pending = parsing;
869
+ if (pending === void 0) {
870
+ resolve({
871
+ uid,
872
+ size
873
+ });
874
+ return;
875
+ }
876
+ pending.then((mail) => {
877
+ resolve({
878
+ uid,
879
+ size,
880
+ mail
881
+ });
882
+ }, (error) => {
883
+ resolve({
884
+ uid,
885
+ size,
886
+ error
887
+ });
888
+ });
889
+ });
890
+ });
891
+ }
892
+ /**
893
+ * The inbound connection of one account.
894
+ *
895
+ * `start()` resolves once the first attempt reached a stable state: the mailbox is open and the first scan runs in
896
+ * the background, or the failure was transient and the reconnect timer took over. A permanent failure (credentials,
897
+ * mailbox) rejects instead, so a misconfiguration is visible at startup.
898
+ */
899
+ var ImapTransport = class {
900
+ options;
901
+ imap;
902
+ first;
903
+ failures = 0;
904
+ connected = false;
905
+ stopping = false;
906
+ permanent;
907
+ reconnectTimer;
908
+ scanning = false;
909
+ rescan = false;
910
+ scanPromise;
911
+ mailListenerAttached = false;
912
+ constructor(options) {
913
+ this.options = options;
914
+ }
915
+ /** Create the connection (once) and wait for the first attempt's stable outcome. */
916
+ async start() {
917
+ const { config } = this.options;
918
+ const imap = new NodeIMAP({
919
+ user: config.username,
920
+ password: config.password,
921
+ host: config.imap.host,
922
+ port: config.imap.port,
923
+ tls: config.imap.tls
924
+ });
925
+ this.imap = imap;
926
+ imap.on("error", (error) => {
927
+ this.handleError(error);
928
+ });
929
+ imap.on("ready", () => {
930
+ this.handleReady();
931
+ });
932
+ imap.on("close", () => {
933
+ this.handleClose();
934
+ });
935
+ const first = new Promise((resolve, reject) => {
936
+ this.first = {
937
+ resolve,
938
+ reject
939
+ };
940
+ });
941
+ imap.connect();
942
+ return first;
943
+ }
944
+ /** Abort the reconnect timer, log out and wait for an in-flight scan. */
945
+ async stop() {
946
+ this.stopping = true;
947
+ this.clearReconnect();
948
+ const imap = this.imap;
949
+ this.imap = void 0;
950
+ if (imap !== void 0) imap.end();
951
+ await this.scanPromise?.catch(() => void 0);
952
+ }
953
+ /**
954
+ * Re-fetch one message by UID for the attachment route (`undefined` when the UID no longer exists).
955
+ * @param uid - the IMAP UID to fetch.
956
+ * @returns the parsed message.
957
+ */
958
+ async fetch(uid) {
959
+ const imap = this.imap;
960
+ if (imap === void 0) throw new Error("mail: the IMAP connection is not open");
961
+ const fetched = imap.fetch(uid, { bodies: "" });
962
+ const results = [];
963
+ const tasks = [];
964
+ await new Promise((resolve, reject) => {
965
+ fetched.on("message", (message) => {
966
+ tasks.push(readMessage(message).then((result) => {
967
+ results.push(result);
968
+ }));
969
+ });
970
+ fetched.on("end", () => {
971
+ resolve();
972
+ });
973
+ fetched.on("error", reject);
974
+ });
975
+ await Promise.all(tasks);
976
+ const [result] = results;
977
+ if (result === void 0) return void 0;
978
+ if (result.error !== void 0) throw result.error;
979
+ return result.mail;
980
+ }
981
+ handleReady() {
982
+ if (this.stopping) return;
983
+ const imap = this.imap;
984
+ if (imap === void 0) return;
985
+ imap.openBox(this.options.config.mailbox, false, (error) => {
986
+ if (this.stopping) return;
987
+ if (error) {
988
+ this.options.logger.error("mail: the mailbox %s could not be opened: %s", this.options.config.mailbox, messageOf$1(error));
989
+ this.failPermanently(error);
990
+ return;
991
+ }
992
+ this.failures = 0;
993
+ this.connected = true;
994
+ this.options.onOnline();
995
+ this.first?.resolve();
996
+ this.first = void 0;
997
+ this.attachMailListener();
998
+ this.scan();
999
+ });
1000
+ }
1001
+ handleError(error) {
1002
+ if (this.stopping) return;
1003
+ if (error.source === "authentication") {
1004
+ this.options.logger.error("mail: IMAP authentication failed: %s", messageOf$1(error));
1005
+ this.failPermanently(error);
1006
+ return;
1007
+ }
1008
+ this.options.logger.warn("mail: IMAP error (%s): %s", error.source ?? "unknown", messageOf$1(error));
1009
+ this.first?.resolve();
1010
+ this.first = void 0;
1011
+ }
1012
+ handleClose() {
1013
+ if (this.stopping) return;
1014
+ this.connected = false;
1015
+ if (this.permanent !== void 0) return;
1016
+ this.first?.resolve();
1017
+ this.first = void 0;
1018
+ this.options.onReconnect();
1019
+ this.scheduleReconnect();
1020
+ }
1021
+ failPermanently(error) {
1022
+ this.permanent = error;
1023
+ this.connected = false;
1024
+ this.clearReconnect();
1025
+ this.first?.reject(error);
1026
+ this.first = void 0;
1027
+ this.options.onOffline(error);
1028
+ }
1029
+ scheduleReconnect() {
1030
+ if (this.stopping || this.permanent !== void 0 || this.reconnectTimer !== void 0 || this.connected) return;
1031
+ const delay = reconnectDelay(this.failures, this.options.config.retry);
1032
+ this.failures += 1;
1033
+ this.reconnectTimer = setTimeout(() => {
1034
+ this.reconnectTimer = void 0;
1035
+ if (this.stopping || this.permanent !== void 0) return;
1036
+ this.imap?.connect();
1037
+ }, delay);
1038
+ }
1039
+ clearReconnect() {
1040
+ if (this.reconnectTimer === void 0) return;
1041
+ clearTimeout(this.reconnectTimer);
1042
+ this.reconnectTimer = void 0;
1043
+ }
1044
+ /** Register the new-mail listener once: every reconnect reuses the connection and its listeners. */
1045
+ attachMailListener() {
1046
+ const imap = this.imap;
1047
+ if (this.mailListenerAttached || imap === void 0) return;
1048
+ this.mailListenerAttached = true;
1049
+ imap.on("mail", () => {
1050
+ this.scan();
1051
+ });
1052
+ }
1053
+ /** Run one scan; a request during a scan sets one "run again" flag instead of starting a second scan. */
1054
+ scan() {
1055
+ if (this.scanning) {
1056
+ this.rescan = true;
1057
+ return Promise.resolve();
1058
+ }
1059
+ this.scanning = true;
1060
+ const run = (async () => {
1061
+ try {
1062
+ do {
1063
+ this.rescan = false;
1064
+ await this.scanOnce();
1065
+ } while (this.rescan && !this.stopping && this.connected);
1066
+ } catch (error) {
1067
+ this.options.logger.error("mail: the scan failed: %s", messageOf$1(error));
1068
+ } finally {
1069
+ this.scanning = false;
1070
+ }
1071
+ })();
1072
+ this.scanPromise = run;
1073
+ return run;
1074
+ }
1075
+ async scanOnce() {
1076
+ const imap = this.imap;
1077
+ if (imap === void 0) return;
1078
+ const uids = await new Promise((resolve, reject) => {
1079
+ imap.search(["UNSEEN"], (error, result) => {
1080
+ if (error) reject(error);
1081
+ else resolve(result ?? []);
1082
+ });
1083
+ });
1084
+ if (uids.length === 0) return;
1085
+ const fetched = imap.fetch(uids, { bodies: "" });
1086
+ const tasks = [];
1087
+ await new Promise((resolve) => {
1088
+ let settled = false;
1089
+ const done = () => {
1090
+ if (settled) return;
1091
+ settled = true;
1092
+ resolve();
1093
+ };
1094
+ fetched.on("message", (message) => {
1095
+ tasks.push(this.deliverMessage(message));
1096
+ });
1097
+ fetched.on("end", done);
1098
+ fetched.on("error", (error) => {
1099
+ this.options.logger.error("mail: fetching the message bodies failed: %s", messageOf$1(error));
1100
+ done();
1101
+ });
1102
+ });
1103
+ await Promise.all(tasks);
1104
+ }
1105
+ /** Parse one fetched message, hand it to the host and acknowledge it only when the host accepted it. */
1106
+ async deliverMessage(message) {
1107
+ const result = await readMessage(message);
1108
+ if (result.mail === void 0) {
1109
+ if (result.error !== void 0) this.options.logger.error("mail: the message could not be parsed: %s", messageOf$1(result.error));
1110
+ else this.options.logger.error("mail: a fetched message carried no body");
1111
+ if (result.uid !== void 0) await this.markSeen(result.uid);
1112
+ return;
1113
+ }
1114
+ if (result.uid === void 0) {
1115
+ this.options.logger.error("mail: a fetched message carried no UID");
1116
+ return;
1117
+ }
1118
+ try {
1119
+ await this.options.deliver(result.mail, {
1120
+ uid: result.uid,
1121
+ mailbox: this.options.config.mailbox,
1122
+ size: result.size
1123
+ });
1124
+ } catch (error) {
1125
+ this.options.logger.error("mail: the host did not accept a message, it stays unseen: %s", messageOf$1(error));
1126
+ return;
1127
+ }
1128
+ await this.markSeen(result.uid);
1129
+ }
1130
+ /** Write `\\Seen`; a failure only warns, because the host deduplicates the redelivery by `Message-ID`. */
1131
+ async markSeen(uid) {
1132
+ const imap = this.imap;
1133
+ if (imap === void 0) return;
1134
+ try {
1135
+ await new Promise((resolve, reject) => {
1136
+ imap.setFlags(uid, ["\\SEEN"], (error) => {
1137
+ if (error) reject(error);
1138
+ else resolve();
1139
+ });
1140
+ });
1141
+ } catch (error) {
1142
+ this.options.logger.warn("mail: the message %d could not be marked as seen: %s", uid, messageOf$1(error));
1143
+ }
1144
+ }
1145
+ };
1146
+ // lib/types/mail.js
1147
+ var SMTP = class {
1148
+ transporter;
1149
+ from;
1150
+ constructor(config) {
1151
+ this.transporter = createTransport({
1152
+ host: config.smtp.host,
1153
+ port: config.smtp.port,
1154
+ secure: config.smtp.tls,
1155
+ auth: {
1156
+ user: config.username,
1157
+ pass: config.password
1158
+ }
1159
+ });
1160
+ const address = config.selfId || config.username;
1161
+ this.from = config.name ? `${config.name} <${address}>` : address;
1162
+ }
1163
+ async send(options) {
1164
+ return (await this.transporter.sendMail({
1165
+ ...options,
1166
+ from: this.from
1167
+ })).messageId;
1168
+ }
1169
+ };
1170
+ // lib/types/bot.js
1171
+ /** The error message of a caught value. */
1172
+ function messageOf(error) {
1173
+ return error instanceof Error ? error.message : String(error);
1174
+ }
1175
+ /** Response headers of one attachment served through the `satori:` route. */
1176
+ function attachmentHeaders(attachment) {
1177
+ const headers = new Headers({ "content-type": attachment.contentType });
1178
+ const disposition = attachment.contentDisposition ?? "attachment";
1179
+ headers.set("content-disposition", attachment.filename === void 0 ? disposition : `${disposition}; filename="${attachment.filename.replaceAll("\"", "")}"`);
1180
+ return headers;
1181
+ }
1182
+ /**
1183
+ * Mail adapter: IMAP inbound, SMTP outbound, one `html` mode.
1184
+ *
1185
+ * Identity is fixed at construction because a mail account has no platform user id to look up: `bot.id` is
1186
+ * `mail:<address>` and `bot.selfId` is the address itself. Inbound messages are acknowledged by `\\Seen` only after
1187
+ * `bot.receive` accepted them; outbound attachments are staged in memory between `prepare` and `sendPayload`.
1188
+ */
1189
+ var MailBot = class extends Adapter {
1190
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
1191
+ static Config = Config;
1192
+ modes = { html: createHtmlMode() };
1193
+ modeOrder = ["html"];
1194
+ /** Outbound SMTP transport (the adapter's platform API). */
1195
+ internal;
1196
+ /** Outbound attachment bytes between `prepare` and `sendPayload`. */
1197
+ staging;
1198
+ transport;
1199
+ /** Single-entry memo of the last message fetched for an attachment, so a message with several attachments costs one fetch. */
1200
+ memo;
1201
+ constructor(ctx, config) {
1202
+ const address = addressOf(config);
1203
+ super(ctx, config, {
1204
+ id: `mail:${address}`,
1205
+ platform: "mail",
1206
+ adapter: "mail"
1207
+ });
1208
+ this.selfId = address;
1209
+ this.user = {
1210
+ id: address,
1211
+ ...config.name ? { name: config.name } : {},
1212
+ isBot: true
1213
+ };
1214
+ this.internal = new SMTP(config);
1215
+ this.staging = new MediaStaging(config.media.stagingTtlMs, config.media.maxStagedBytes);
1216
+ this.defineInternalRoute("/messages/:uid/attachments/:index", (request) => this.serveAttachment(request));
1217
+ }
1218
+ async connect() {
1219
+ try {
1220
+ await this.internal.transporter.verify();
1221
+ this.ctx.logger.debug("mail: SMTP credentials verified");
1222
+ } catch (error) {
1223
+ this.ctx.logger.warn("mail: SMTP verification failed, sending may fail: %s", messageOf(error));
1224
+ }
1225
+ const transport = new ImapTransport({
1226
+ config: this.config,
1227
+ logger: this.ctx.logger,
1228
+ deliver: (mail, source) => this.deliver(mail, source),
1229
+ onOnline: () => {
1230
+ this.online();
1231
+ },
1232
+ onReconnect: () => {
1233
+ this.status = Status.RECONNECT;
1234
+ },
1235
+ onOffline: (error) => {
1236
+ this.offline(error);
1237
+ }
1238
+ });
1239
+ this.transport = transport;
1240
+ try {
1241
+ await transport.start();
1242
+ } catch (error) {
1243
+ this.ctx.logger.error("mail: connect failed: %s", messageOf(error));
1244
+ await transport.stop();
1245
+ this.transport = void 0;
1246
+ throw error;
1247
+ }
1248
+ }
1249
+ async disconnect() {
1250
+ const transport = this.transport;
1251
+ this.transport = void 0;
1252
+ await transport?.stop();
1253
+ }
1254
+ async upload(ref, _scope, ctx) {
1255
+ let fetched;
1256
+ try {
1257
+ fetched = await ctx.fetch(ref.src, ctx.signal);
1258
+ } catch (error) {
1259
+ throw new PlatformError("invalid", `mail: the resource "${ref.src}" could not be read: ${messageOf(error)}`, {
1260
+ published: "no",
1261
+ cause: error
1262
+ });
1263
+ }
1264
+ const mime = ref.meta.mime ?? fetched.mime;
1265
+ return this.staging.stage({
1266
+ data: fetched.data,
1267
+ name: ref.meta.name ?? fetched.name ?? "",
1268
+ ...mime === void 0 ? {} : { mime }
1269
+ });
1270
+ }
1271
+ resourceScope(_target, _kind) {
1272
+ return this.id;
1273
+ }
1274
+ async sendPayload(payload, target, ctx) {
1275
+ return sendPayload({
1276
+ config: this.config,
1277
+ staging: this.staging,
1278
+ smtp: this.internal
1279
+ }, payload, target, ctx);
1280
+ }
1281
+ classify(error) {
1282
+ return classifyMailError(error);
1283
+ }
1284
+ /** Decode and hand one message to the host; `\\Seen` is written by the transport once this resolved. */
1285
+ async deliver(mail, source) {
1286
+ const message = decodeMessage({
1287
+ selfId: this.selfId,
1288
+ config: this.config,
1289
+ getInternalUrl: (path, init) => this.getInternalUrl(path, init),
1290
+ log: (text) => {
1291
+ this.ctx.logger.debug(text);
1292
+ }
1293
+ }, mail, source);
1294
+ if (message === void 0) return;
1295
+ await this.receive(this.session({
1296
+ type: "message",
1297
+ id: message.id,
1298
+ timestamp: message.time,
1299
+ message
1300
+ }));
1301
+ }
1302
+ /** Serve one attachment of a stored message, re-fetching the message by UID. */
1303
+ async serveAttachment(request) {
1304
+ const uid = Number(request.params.uid);
1305
+ const index = Number(request.params.index);
1306
+ if (!Number.isSafeInteger(uid) || uid <= 0 || !Number.isSafeInteger(index) || index < 0) return new Response(null, { status: 400 });
1307
+ if (request.query.get("box") !== this.config.mailbox) return new Response(null, { status: 404 });
1308
+ let mail;
1309
+ try {
1310
+ mail = await this.fetchMail(uid);
1311
+ } catch (error) {
1312
+ this.ctx.logger.warn("mail: the message %d could not be fetched: %s", uid, messageOf(error));
1313
+ return new Response(null, { status: 502 });
1314
+ }
1315
+ const attachment = mail?.attachments[index];
1316
+ if (attachment === void 0) return new Response(null, { status: 404 });
1317
+ return new Response(new Uint8Array(attachment.content), { headers: attachmentHeaders(attachment) });
1318
+ }
1319
+ /** Fetch one message for the attachment route, memoizing the last one. */
1320
+ async fetchMail(uid) {
1321
+ if (this.memo?.uid === uid) return this.memo.mail;
1322
+ const transport = this.transport;
1323
+ if (transport === void 0) throw new Error("mail: the IMAP connection is not open");
1324
+ const mail = await transport.fetch(uid);
1325
+ if (mail !== void 0) this.memo = {
1326
+ uid,
1327
+ mail
1328
+ };
1329
+ return mail;
1330
+ }
1331
+ };
1332
+ export { Config, ImapTransport, MailBot, MailBot as default, MediaStaging, SMTP, addressOf, attachmentKind, classifyMailError, createHtmlMode, decodeMessage, sendPayload };
1333
+
1334
+ //# sourceMappingURL=index.js.map