@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.
- package/LICENSE +21 -0
- package/cordis.patch.yml +14 -0
- package/lib/index.js +1334 -0
- package/lib/index.js.map +1 -0
- package/lib/types/bot.d.ts +49 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +189 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +51 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +55 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/decode.d.ts +60 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +195 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +33 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +156 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/html.d.ts +30 -0
- package/lib/types/html.d.ts.map +1 -0
- package/lib/types/html.js +121 -0
- package/lib/types/html.js.map +1 -0
- package/lib/types/index.d.ts +11 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +10 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/mail.d.ts +24 -0
- package/lib/types/mail.d.ts.map +1 -0
- package/lib/types/mail.js +26 -0
- package/lib/types/mail.js.map +1 -0
- package/lib/types/media.d.ts +52 -0
- package/lib/types/media.d.ts.map +1 -0
- package/lib/types/media.js +81 -0
- package/lib/types/media.js.map +1 -0
- package/lib/types/modes/html.d.ts +13 -0
- package/lib/types/modes/html.d.ts.map +1 -0
- package/lib/types/modes/html.js +70 -0
- package/lib/types/modes/html.js.map +1 -0
- package/lib/types/modes/shared.d.ts +114 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +185 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/send.d.ts +26 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +58 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/transport/imap.d.ts +95 -0
- package/lib/types/transport/imap.d.ts.map +1 -0
- package/lib/types/transport/imap.js +354 -0
- package/lib/types/transport/imap.js.map +1 -0
- package/package.json +70 -3
- package/src/bot.ts +264 -0
- package/src/config.ts +98 -0
- package/src/decode.ts +275 -0
- package/src/errors.ts +199 -0
- package/src/html.ts +137 -0
- package/src/index.ts +32 -0
- package/src/mail.ts +46 -0
- package/src/media.ts +102 -0
- package/src/modes/html.ts +105 -0
- package/src/modes/shared.ts +285 -0
- package/src/send.ts +87 -0
- package/src/transport/imap.ts +418 -0
- package/README.md +0 -3
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["messageOf"],"sources":["types/config.js","types/html.js","types/decode.js","types/errors.js","types/media.js","types/modes/shared.js","types/modes/html.js","types/send.js","types/transport/imap.js","types/mail.js","types/bot.js"],"sourcesContent":["import z from '@deepseek-ai/schemastery';\n/** Validated Mail adapter configuration. */\nexport const Config = z.object({\n username: z.string().required(),\n password: z.string().role('secret').required(),\n selfId: z.string(),\n name: z.string(),\n subject: z.string().default('Koishi'),\n mailbox: z.string().default('INBOX'),\n imap: z.intersect([\n z.object({\n host: z.string().required(),\n tls: z.boolean().default(true),\n }),\n z.union([\n z.object({ tls: z.const(true), port: z.natural().default(993) }),\n z.object({ tls: z.const(false), port: z.natural().default(143) }),\n ]),\n ]),\n smtp: z.intersect([\n z.object({\n host: z.string().required(),\n tls: z.boolean().default(true),\n }),\n z.union([\n z.object({ tls: z.const(true), port: z.natural().default(465) }),\n z.object({ tls: z.const(false), port: z.natural().default(25) }),\n ]),\n ]),\n retry: z\n .object({\n times: z.natural().default(6),\n interval: z.natural().role('ms').default(5_000),\n lazy: z.natural().role('ms').default(60_000),\n })\n .default({}),\n media: z\n .object({\n stagingTtlMs: z\n .natural()\n .role('ms')\n .default(10 * 60_000),\n maxStagedBytes: z.natural().default(64 * 1024 * 1024),\n })\n .default({}),\n});\n/**\n * The address this bot answers as: `selfId` when given, else the login name.\n * @param config - the validated adapter configuration.\n * @returns the bot's own address.\n */\nexport function addressOf(config) {\n return config.selfId || config.username;\n}\n//# sourceMappingURL=config.js.map","/**\n * HTML body decoding: an HTML string from `mailparser` becomes Satori elements, following the upstream traversal\n * (`html5parser` + `visit`) instead of a text extraction.\n *\n * Two deliberate deviations from upstream, both one-line bug fixes (design §5.2): an unknown named character\n * reference is kept literally instead of replacing the whole text node, and an image's `alt` is read from `alt`\n * rather than from `src`.\n */\nimport { h } from '@deepseek-ai/satori-element';\nimport { parse, SyntaxKind } from 'html5parser';\n/** The named character references the traversal decodes (upstream's table). */\nconst entities = {\n nbsp: ' ',\n cent: '¢',\n pound: '£',\n yen: '¥',\n euro: '€',\n copy: '©',\n reg: '®',\n lt: '<',\n gt: '>',\n quot: '\"',\n amp: '&',\n apos: \"'\",\n};\n/**\n * Decode named, decimal and hexadecimal character references of one text run.\n *\n * A named reference outside {@link entities} is not an error: it stays as written. (Upstream returned the whole text\n * node in that case, which duplicated everything around the unknown reference.)\n *\n * @param text - raw character data of one HTML text node.\n * @returns the text with the known references decoded.\n */\nexport function decodeHE(text) {\n const regex = /&(([a-z0-9]+)|(#[0-9]{1,6})|(#x[0-9a-fA-F]{1,6}));/gi;\n return text.replace(regex, (raw, _whole, name, dec, hex) => {\n if (name)\n return entities[name] ?? raw;\n if (dec)\n return String.fromCharCode(Number(dec.substring(1)));\n if (hex)\n return String.fromCharCode(parseInt(hex.substring(2), 16));\n return raw;\n });\n}\n/** One attribute of a parsed tag, as written in the source. */\nfunction attribute(node, name) {\n return node.attributeMap?.[name]?.value?.value;\n}\n/** Tags whose whole subtree is not part of the message body. */\nconst IGNORED = new Set(['head', 'script', 'style', 'meta']);\n/**\n * Convert an HTML body into elements.\n *\n * @param html - the `text/html` part `mailparser` decoded.\n * @param options - `onSubscript` reports a dropped `<sub>`/`<sup>` (the vocabulary has neither).\n * @returns the elements of the body, in document order.\n */\nexport function htmlToElements(html, options = {}) {\n const visit = (nodes) => {\n const out = [];\n for (const node of nodes) {\n if (node.type === SyntaxKind.Text) {\n out.push(h.text(decodeHE(node.value).trim() || ' '));\n continue;\n }\n const body = node.body ?? [];\n switch (node.name) {\n case 'a':\n out.push(h('a', { href: attribute(node, 'href') || '#' }, ...visit(body)));\n break;\n case 'strong':\n case 'b':\n out.push(h('b', ...visit(body)));\n break;\n case 'br':\n out.push(h('br'));\n break;\n case 'code':\n out.push(h('code', ...visit(body)));\n break;\n case 's':\n case 'del':\n out.push(h('s', ...visit(body)));\n break;\n case 'i':\n case 'em':\n out.push(h('i', ...visit(body)));\n break;\n case 'p':\n out.push(h('p', ...visit(body)));\n break;\n case 'sub':\n case 'sup':\n // The vocabulary has neither: the text stays, the position is lost.\n options.onSubscript?.();\n out.push(...visit(body));\n break;\n case 'u':\n out.push(h('u', ...visit(body)));\n break;\n case 'img': {\n const src = attribute(node, 'src');\n if (src === undefined || !/^(data|https?):/i.test(src))\n break;\n const alt = attribute(node, 'alt');\n out.push(h('img', { src, ...(alt === undefined ? {} : { alt }) }));\n break;\n }\n default:\n if (IGNORED.has(node.name))\n break;\n out.push(...visit(body));\n }\n }\n return out;\n };\n return visit(parse(html, { setAttributeMap: true }));\n}\n//# sourceMappingURL=html.js.map","/**\n * Inbound decoding: one parsed message becomes one {@link InboundMessage}.\n *\n * The message is addressed to the sender's own mailbox (`chat.id = private:<address>`), the `Message-ID` is the\n * message identity (and the intake dedupe key), `In-Reply-To`/`References` become `quote`/`referrer`, and attachments\n * become media elements whose `src` is the bot's `satori:` attachment route. Messages sent by the bot itself are\n * skipped, because a copy arriving back in the mailbox would otherwise answer itself.\n */\nimport { h } from '@deepseek-ai/satori-element';\nimport { htmlToElements } from \"./html.js\";\n/**\n * The element kind of one attachment.\n * @param mime - the attachment's MIME type.\n * @returns the vocabulary tag the attachment is shown as.\n */\nexport function attachmentKind(mime) {\n const type = mime.split(';')[0]?.trim().toLowerCase() ?? '';\n if (type.startsWith('image/'))\n return 'img';\n if (type.startsWith('audio/'))\n return 'audio';\n if (type.startsWith('video/'))\n return 'video';\n return 'file';\n}\n/** Every address of the given headers, groups expanded; entries without an address are dropped. */\nfunction addressesOf(...headers) {\n const out = [];\n for (const header of headers) {\n if (header === undefined)\n continue;\n for (const object of Array.isArray(header) ? header : [header]) {\n for (const item of object.value) {\n const list = item.group ?? [item];\n for (const address of list) {\n if (address.address)\n out.push(address);\n }\n }\n }\n }\n return out;\n}\n/** `References:` as a list of `<…>` values (mailparser gives a string for a single reference). */\nfunction referencesOf(mail) {\n if (mail.references === undefined)\n return [];\n return Array.isArray(mail.references)\n ? [...mail.references]\n : [mail.references];\n}\n/** A stable id for a message that carries no `Message-ID`. */\nfunction synthesizedId(uid, selfId) {\n const at = selfId.lastIndexOf('@');\n return `<${uid}@${at < 0 ? selfId : selfId.slice(at + 1)}>`;\n}\n/** The display name of an address, when it has one. */\nfunction nameOf(address) {\n const name = address.name.trim();\n return name === '' ? undefined : name;\n}\n/** Media elements of the message's attachments, in MIME order, served by the attachment route. */\nfunction attachmentElements(bot, mail, source) {\n return mail.attachments.map((attachment, index) => {\n const kind = attachmentKind(attachment.contentType);\n const filename = attachment.filename ?? `attachment-${index + 1}`;\n const src = bot.getInternalUrl(`/messages/${source.uid}/attachments/${index}`, { box: source.mailbox });\n switch (kind) {\n case 'img':\n return h('img', {\n src,\n ...(attachment.filename === undefined\n ? {}\n : { alt: attachment.filename }),\n });\n case 'audio':\n return h('audio', { src, name: filename });\n case 'video':\n return h('video', { src, name: filename });\n case 'file':\n return h('file', { src, name: filename });\n }\n });\n}\n/** The body elements of one message: the HTML traversal, or the plain text part, plus the attachments. */\nfunction bodyElements(bot, mail, source) {\n const body = [];\n if (!mail.html) {\n const text = mail.text ?? '';\n if (text !== '')\n body.push(h.text(text));\n }\n else {\n const log = bot.log;\n body.push(...htmlToElements(mail.html, log === undefined\n ? {}\n : {\n onSubscript: () => {\n log('mail: dropped <sub>/<sup>, the vocabulary has no subscript');\n },\n }));\n }\n body.push(...attachmentElements(bot, mail, source));\n return body;\n}\n/**\n * Decode one parsed message.\n *\n * @param bot - the adapter the message arrived for (identity, mailbox, `satori:` route base).\n * @param mail - the parsed MIME message.\n * @param source - the IMAP coordinates the message was read at.\n * @returns the inbound message, or `undefined` when the message cannot be routed (no sender address, or the bot's\n * own message).\n */\nexport function decodeMessage(bot, mail, source) {\n const from = mail.from?.value[0];\n if (from?.address === undefined || from.address === '') {\n bot.log?.('mail: dropped a message without a sender address');\n return undefined;\n }\n if (from.address.toLowerCase() === bot.selfId.toLowerCase()) {\n bot.log?.(`mail: dropped a message from the bot's own address (${from.address})`);\n return undefined;\n }\n const address = from.address;\n const name = nameOf(from);\n const messageId = mail.messageId ?? synthesizedId(source.uid, bot.selfId);\n const replyTo = mail.replyTo?.value[0]?.address;\n const references = referencesOf(mail);\n const body = bodyElements(bot, mail, source);\n // Content must never be empty; a structural-only message becomes one `<raw>` child.\n const content = h('message', {}, ...(body.length === 0\n ? [\n h('raw', {\n platform: 'mail',\n type: 'message',\n data: {\n messageId,\n contentType: mail.headers.get('content-type'),\n },\n }, h.text('')),\n ]\n : body));\n const recipients = addressesOf(mail.to, mail.cc);\n const seen = new Set();\n const users = [];\n let mentionsSelf = false;\n for (const recipient of recipients) {\n if (recipient.address === undefined)\n continue;\n const lower = recipient.address.toLowerCase();\n if (lower === bot.selfId.toLowerCase()) {\n mentionsSelf = true;\n continue;\n }\n if (seen.has(lower))\n continue;\n seen.add(lower);\n const recipientName = nameOf(recipient);\n users.push({\n id: recipient.address,\n ...(recipientName === undefined ? {} : { name: recipientName }),\n });\n }\n const chat = {\n id: `private:${address}`,\n type: 'direct',\n ...(name === undefined ? {} : { name }),\n };\n const sender = {\n id: address,\n ...(name === undefined ? {} : { name }),\n };\n const referrer = {\n address,\n messageId,\n ...(mail.subject === undefined ? {} : { subject: mail.subject }),\n ...(replyTo === undefined ? {} : { replyTo }),\n ...(references.length === 0 ? {} : { references }),\n uid: source.uid,\n mailbox: source.mailbox,\n };\n return {\n id: messageId,\n chat,\n sender,\n content,\n ...(mail.inReplyTo === undefined ? {} : { quote: { id: mail.inReplyTo } }),\n mentions: { self: mentionsSelf, all: false, users },\n time: mail.date === undefined ? Date.now() : +mail.date,\n referrer,\n raw: { uid: source.uid, mailbox: source.mailbox, size: source.size },\n };\n}\n//# sourceMappingURL=decode.js.map","/**\n * SMTP failures and their mapping onto the core platform taxonomy.\n *\n * `nodemailer` reports one failed mail transaction as an `Error` carrying `code` (the stage), `command` (the SMTP\n * verb) and `responseCode` (the server's numeric answer). The stage alone cannot say whether the message left this\n * host: a connection loss after `DATA` started says nothing, while a refusal before the body was sent means the\n * server certainly did not accept the message. `published` is decided from that, the error kind from the stage and\n * the refined by the response code.\n */\nimport { PlatformError } from '@deepseek-ai/cordis-plugin-im-core';\n/** Read the classification fields off a caught value (a non-`Error` carries none of them). */\nfunction failureOf(error) {\n if (error instanceof Error) {\n const value = error;\n return {\n name: value.name,\n message: value.message,\n ...(typeof value.code === 'string' ? { code: value.code } : {}),\n ...(typeof value.command === 'string' ? { command: value.command } : {}),\n ...(typeof value.response === 'string'\n ? { response: value.response }\n : {}),\n ...(typeof value.responseCode === 'number'\n ? { responseCode: value.responseCode }\n : {}),\n };\n }\n return { message: String(error) };\n}\n/** Whether a caught value is the abort error of a cancelled operation. */\nfunction isCancellation(error) {\n return ((error instanceof Error || error instanceof DOMException) &&\n error.name === 'AbortError');\n}\n/** Whether a response code is a temporary refusal (RFC 5321 §4.2). */\nfunction isTemporary(code) {\n return code >= 400 && code < 500;\n}\n/** Whether a response code is a permanent refusal (RFC 5321 §4.2). */\nfunction isPermanent(code) {\n return code >= 500 && code < 600;\n}\n/**\n * Refine a stage's default kind with the meaning of the server's response code.\n * @param code - the numeric SMTP response, when the error carried one.\n * @param fallback - the kind the stage implies on its own.\n * @returns the refined kind.\n */\nfunction refineKind(code, fallback) {\n switch (code) {\n case 421:\n case 450:\n case 451:\n return 'retryable';\n case 452:\n return 'rate-limit';\n case 534:\n case 535:\n return 'permission';\n case 550:\n return 'not-found';\n case 552:\n return 'limit';\n case 553:\n case 554:\n return 'invalid';\n }\n if (isTemporary(code))\n return 'retryable';\n if (isPermanent(code))\n return 'invalid';\n return fallback;\n}\n/** The `RCPT TO` kind of one rejection (550 names a missing mailbox, other 5xx codes deny the recipient). */\nfunction recipientKind(code) {\n if (code === 550)\n return 'not-found';\n if (isPermanent(code))\n return 'permission';\n return refineKind(code, 'retryable');\n}\n/** Whether the error says the message grew past the server's size limit before `DATA` began. */\nfunction isOversized(failure) {\n return /larger than allowed|message size|maximum message size/i.test(failure.message ?? failure.response ?? '');\n}\n/**\n * Map any failure of a publication onto the core taxonomy.\n *\n * `published: 'no'` is claimed only when the transaction provably had not handed the body over when it failed: an\n * authentication or envelope refusal, a `DATA` command refusal, or a completed `DATA` the server rejected. A transport\n * failure without a server answer leaves the outcome unknown, because `nodemailer` reports a connection that died\n * while the body was in flight exactly like a refused connection; a `354` answer says the body had started.\n *\n * @param error - the caught failure.\n * @returns the classified platform error.\n */\nexport function classifyMailError(error) {\n if (error instanceof PlatformError)\n return error;\n const failure = failureOf(error);\n const message = failure.message === undefined\n ? 'mail: send failed'\n : `mail: ${failure.message}`;\n const cause = error;\n const code = failure.responseCode;\n const codeInit = code === undefined ? {} : { code };\n const make = (kind, published) => new PlatformError(kind, message, { ...codeInit, published, cause });\n if (isCancellation(error))\n return new PlatformError('fatal', message, { published: 'unknown', cause });\n switch (failure.code) {\n case 'EAUTH':\n return make('permission', 'no');\n case 'EENVELOPE':\n switch (failure.command) {\n case 'MAIL FROM':\n // A 550 here rejects the sender identity, not a missing mailbox; every other code keeps its RFC meaning.\n return make(code === 550 || code === undefined\n ? 'permission'\n : refineKind(code, 'permission'), 'no');\n case 'RCPT TO':\n // The last RCPT answer is the one recorded; all-recipients-rejected keeps it.\n return make(code === undefined ? 'invalid' : recipientKind(code), 'no');\n case 'DATA':\n return make(code === undefined ? 'invalid' : refineKind(code, 'invalid'), 'no');\n default:\n // \"No recipients defined\" and other local envelope checks: nothing was sent.\n return make(code === undefined ? 'invalid' : refineKind(code, 'invalid'), 'no');\n }\n case 'EMESSAGE':\n if (failure.command === 'MAIL FROM' && isOversized(failure))\n return make('limit', 'no');\n if (failure.command === 'DATA')\n return make(code === undefined ? 'invalid' : refineKind(code, 'invalid'), 'no');\n return make(code === undefined ? 'invalid' : refineKind(code, 'invalid'), 'no');\n case 'ECONNECTION':\n case 'ETIMEDOUT': {\n // `nodemailer` reports a socket that died while the body was in flight exactly like a refused connection: no\n // server answer is attached, so whether the message left this host cannot be told. Claiming `no` there would\n // invite a duplicate delivery, so an answerless transport failure stays unknown. A server answer can be told:\n // `354` means the body had started, any other code means the transaction had not reached that point.\n if (code === undefined)\n return make('retryable', 'unknown');\n const published = code === 354 ? 'unknown' : 'no';\n return make(refineKind(code, 'retryable'), published);\n }\n case 'EDNS':\n return make('retryable', 'no');\n case 'EPROTOCOL':\n return make('retryable', 'unknown');\n case 'ESTREAM':\n return make('invalid', 'no');\n default:\n return make('retryable', 'unknown');\n }\n}\n//# sourceMappingURL=errors.js.map","import { randomUUID } from 'node:crypto';\n/**\n * Bounded in-memory staging for outbound attachments.\n *\n * SMTP has no upload step: the bytes must ride the MIME body of the message that references them, and `serialize` is\n * pure, so `upload` fetches and stages the bytes and `sendPayload` reads them back by key. Entries expire and the\n * whole store is bounded. A key is the Content-ID of its attachment (and the `cid:` target of the HTML part), which\n * makes it safe inside a `Message-ID`-style bracket.\n *\n * A key is single-use: the resolved resource carries `expiresAt: 0`, so the pipeline cache never reuses a key whose\n * bytes a successful send released.\n */\nexport class MediaStaging {\n ttlMs;\n maxBytes;\n entries = new Map();\n bytes = 0;\n constructor(ttlMs, maxBytes) {\n this.ttlMs = ttlMs;\n this.maxBytes = maxBytes;\n }\n /**\n * Stage bytes under a fresh Content-ID.\n * @param media - the bytes, their suggested name and MIME type.\n * @returns the resource key `prepare` hands to `serialize`; it is also the `cid`.\n */\n stage(media) {\n const now = Date.now();\n this.prune(now);\n const key = randomUUID().replaceAll('-', '');\n const bytes = media.data.byteLength;\n this.entries.set(key, { media, bytes, expiresAt: now + this.ttlMs });\n this.bytes += bytes;\n this.evict();\n const extra = { name: media.name, mime: media.mime };\n return { key, expiresAt: 0, extra };\n }\n /**\n * Read staged bytes without releasing them.\n * @param key - a key returned by {@link stage}.\n * @returns the staged media, or undefined once expired, evicted or released.\n */\n get(key) {\n this.prune(Date.now());\n return this.entries.get(key)?.media;\n }\n /**\n * Read staged bytes and release them (a published message needs them no more).\n * @param key - a key returned by {@link stage}.\n * @returns the staged media, or undefined once expired, evicted or released.\n */\n take(key) {\n this.prune(Date.now());\n const entry = this.entries.get(key);\n if (entry === undefined)\n return undefined;\n this.entries.delete(key);\n this.bytes -= entry.bytes;\n return entry.media;\n }\n prune(now) {\n for (const [key, entry] of this.entries) {\n if (entry.expiresAt > now)\n continue;\n this.entries.delete(key);\n this.bytes -= entry.bytes;\n }\n }\n evict() {\n while (this.bytes > this.maxBytes) {\n const oldest = this.entries.keys().next();\n if (oldest.done === true)\n return;\n const entry = this.entries.get(oldest.value);\n this.entries.delete(oldest.value);\n if (entry !== undefined)\n this.bytes -= entry.bytes;\n }\n }\n}\n//# sourceMappingURL=media.js.map","/**\n * The single `html` mode's node, draft and payload types, HTML escaping, media promotion and MIME payload assembly.\n *\n * A mail message is one MIME document, so `assemble` always returns exactly one draft: inline nodes accumulate into\n * the HTML and plain-text parts, while media become `multipart/related` (`cid:`) or `multipart/mixed` attachments. A\n * media element standing in phrasing content is lifted out of the text run and reported as `moved` (nothing is lost,\n * only repositioned), which is the `mail-media-split` entry of the render report.\n */\nimport { PlatformError } from '@deepseek-ai/cordis-plugin-im-core';\nimport { isPhrasingContainer } from '@deepseek-ai/satori-element';\n/** Escape character data of the HTML part. */\nexport function escapeHtml(text) {\n return text\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>');\n}\n/** Escape one HTML attribute value (double-quoted). */\nexport function escapeAttribute(text) {\n return escapeHtml(text).replaceAll('\"', '"');\n}\n/** One inline node. */\nexport function inlineNode(html, text) {\n return { type: 'inline', html, text };\n}\n/**\n * Split rendered children into one inline run and the media nodes that follow it.\n * @param nodes - rendered children.\n * @returns the concatenated HTML/text of the run and the media nodes, in source order.\n */\nexport function inlineRun(nodes) {\n let html = '';\n let text = '';\n const rest = [];\n for (const node of nodes) {\n if (node.type === 'media') {\n rest.push(node);\n continue;\n }\n html += node.html;\n text += node.text;\n }\n return { html, text, rest };\n}\n/**\n * Wrap the inline text of rendered children in one HTML tag; media of the subtree follows the wrapper.\n * @param tag - the HTML tag name.\n * @param nodes - rendered children.\n * @param textSuffix - plain-text separator this block adds after its inline text.\n * @returns the wrapper (when it has text) and the media nodes.\n */\nexport function inlineWrapper(tag, nodes, textSuffix = '') {\n const { html, text, rest } = inlineRun(nodes);\n if (html === '')\n return rest;\n return [inlineNode(`<${tag}>${html}</${tag}>`, text + textSuffix), ...rest];\n}\n/** Resource kind of one media tag. */\nexport function resourceKindOf(tag) {\n switch (tag) {\n case 'img':\n return 'image';\n case 'audio':\n return 'audio';\n case 'video':\n return 'video';\n case 'file':\n return 'file';\n }\n}\n/**\n * Turn one media element into its node.\n *\n * An `http(s)` image, audio or video stays a reference to the remote URL: the recipient's client fetches it, so the\n * sent message carries no copy. Everything else (and every file, which has no markup to carry a URL) is fetched and\n * becomes an attachment. Media lifted out of phrasing content is reported as `moved`.\n *\n * @param el - one of `img`/`audio`/`video`/`file`.\n * @param ctx - render context of the mode.\n * @returns the inline node of a remote media reference, or the media node of an attachment.\n */\nexport function mediaNode(el, ctx) {\n const tag = el.type;\n const src = el.attrs.src;\n if (src === '') {\n throw new PlatformError('invalid', `mail: <${tag}> has no src, so nothing could be sent`, { published: 'no' });\n }\n if (tag !== 'file' && /^https?:\\/\\//i.test(src)) {\n const escaped = escapeAttribute(src);\n const html = tag === 'img'\n ? `<img src=\"${escaped}\">`\n : `<${tag} src=\"${escaped}\" controls>`;\n return inlineNode(html, '');\n }\n const parent = ctx.ancestors[ctx.ancestors.length - 1];\n if (parent !== undefined && isPhrasingContainer(parent.type)) {\n ctx.report.moved.push({\n tag,\n reason: 'mail-media-split',\n path: ctx.stableId(el),\n });\n }\n const meta = {};\n if (el.type === 'audio' || el.type === 'video' || el.type === 'file') {\n if (el.attrs.name !== undefined)\n meta.name = el.attrs.name;\n }\n return {\n type: 'media',\n tag,\n ref: ctx.resource(resourceKindOf(tag), src, meta),\n };\n}\n/** The recipient address of a chat id (`private:` is the direct-chat idiom of this platform). */\nfunction addressOfChat(chatId) {\n const prefix = 'private:';\n return chatId.startsWith(prefix) ? chatId.slice(prefix.length) : chatId;\n}\n/** The adapter-private reply context of a publication, when the target carries one. */\nfunction referrerOf(target) {\n const referrer = target.referrer;\n if (typeof referrer !== 'object' || referrer === null)\n return undefined;\n return referrer;\n}\n/** Fold a node stream into the one draft a mail message is. */\nexport function assembleDraft(nodes, quote) {\n return [{ nodes, ...(quote === undefined ? {} : { quote }) }];\n}\n/**\n * Build the `sendMail` options of one draft.\n *\n * The recipient is the chat's address, unless the message being answered named a `Reply-To`. A reply carries\n * `In-Reply-To` (the quoted `Message-ID`) and `References` (the answered message's chain plus that id), and its\n * subject is the answered subject with one `Re: ` prefix.\n */\nexport function serializeDraft(prepared, ctx) {\n const draft = prepared.draft;\n const config = ctx.bot.config;\n const referrer = referrerOf(ctx.target);\n const quote = draft.quote ?? ctx.quote;\n let html = '';\n let text = '';\n const attachments = [];\n for (const node of draft.nodes) {\n if (node.type === 'inline') {\n html += node.html;\n text += node.text;\n continue;\n }\n const resolved = prepared.resolved.get(node.ref);\n if (resolved === undefined)\n throw new Error('mail: an attachment was not prepared before serialize');\n const extra = resolved.extra;\n const cid = node.tag === 'file' ? undefined : resolved.key;\n if (cid !== undefined) {\n const escaped = escapeAttribute(cid);\n html +=\n node.tag === 'img'\n ? `<img src=\"cid:${escaped}\">`\n : `<${node.tag} src=\"cid:${escaped}\" controls>`;\n }\n const suggested = node.ref.meta.name ?? extra?.name;\n attachments.push({\n key: resolved.key,\n ...(cid === undefined ? {} : { cid }),\n filename: suggested !== undefined && suggested !== ''\n ? suggested\n : `attachment-${attachments.length + 1}`,\n contentType: node.ref.meta.mime ?? extra?.mime ?? 'application/octet-stream',\n });\n }\n return {\n to: referrer?.replyTo ?? addressOfChat(ctx.target.chat.id),\n subject: referrer?.subject ? `Re: ${referrer.subject}` : config.subject,\n html: `<pre>${html}</pre>`,\n text: text.trim() === '' ? '' : text,\n ...(quote === undefined ? {} : { inReplyTo: quote }),\n ...(quote === undefined || referrer === undefined\n ? {}\n : { references: [...(referrer.references ?? []), quote] }),\n attachments,\n };\n}\n//# sourceMappingURL=shared.js.map","/**\n * `html` mode: the only mode, a single MIME message per logical message.\n *\n * Native tags are the inline subset a mail body can express (`b`/`i`/`u`/`s`/`code`/`pre`/`a`/`p`/`blockquote`/\n * lists and media). Everything else takes the core fallback and is reported as degraded. `assemble` always returns\n * one draft — mail has no message splitting — and `serialize` writes the `<pre>`-wrapped HTML, the plain-text\n * alternative and the attachments.\n */\nimport { ElementRegistry } from '@deepseek-ai/cordis-plugin-im-core';\nimport { assembleDraft, escapeAttribute, escapeHtml, inlineNode, inlineRun, inlineWrapper, mediaNode, serializeDraft, } from \"./shared.js\";\n/** An address a `mailto:` link can carry. */\nconst MAIL_ADDRESS = /^[^\\s@<>]+@[^\\s@<>]+$/;\n/** Wrap the inline text of `children` in one tag, letting media of the subtree follow it. */\nfunction wrap(tag, ctx, children, textSuffix = '') {\n return inlineWrapper(tag, ctx.render(children), textSuffix);\n}\n/** Build the `html` mode. */\nexport function createHtmlMode() {\n const elements = new ElementRegistry()\n .register('text', (el) => inlineNode(escapeHtml(el.attrs.content), el.attrs.content))\n .register('br', () => inlineNode('<br>', '\\n'))\n .register('p', (el, ctx) => wrap('p', ctx, el.children, '\\n\\n'))\n .register('b', (el, ctx) => wrap('b', ctx, el.children))\n .register('i', (el, ctx) => wrap('i', ctx, el.children))\n .register('u', (el, ctx) => wrap('u', ctx, el.children))\n .register('s', (el, ctx) => wrap('s', ctx, el.children))\n .register('code', (el, ctx) => {\n const content = ctx.text(el.children);\n return inlineNode(`<code>${escapeHtml(content)}</code>`, content);\n })\n .register('pre', (el, ctx) => {\n const content = ctx.text(el.children);\n return inlineNode(`<pre>${escapeHtml(content)}</pre>`, `${content}\\n\\n`);\n })\n .register('blockquote', (el, ctx) => wrap('blockquote', ctx, el.children, '\\n\\n'))\n .register('ul', (el, ctx) => wrap('ul', ctx, el.children))\n .register('ol', (el, ctx) => wrap('ol', ctx, el.children))\n .register('li', (el, ctx) => wrap('li', ctx, el.children, '\\n'))\n .register('a', (el, ctx) => {\n const { html, text, rest } = inlineRun(ctx.render(el.children));\n const href = el.attrs.href;\n const label = html === '' ? escapeHtml(href) : html;\n const plain = text === '' ? href : text;\n const plainText = plain === href ? href : `${plain} (${href})`;\n return [\n inlineNode(`<a href=\"${escapeAttribute(href)}\">${label}</a>`, plainText),\n ...rest,\n ];\n })\n .register('at', (el) => {\n const id = el.attrs.id;\n const label = el.attrs.name ?? id ?? el.attrs.type;\n if (id !== undefined && MAIL_ADDRESS.test(id)) {\n return inlineNode(`<a href=\"mailto:${escapeAttribute(id)}\">@${escapeHtml(id)}</a>`, `@${id}`);\n }\n return inlineNode(escapeHtml(`@${label}`), `@${label}`);\n }, { variants: ['user'] })\n .register('img', (el, ctx) => mediaNode(el, ctx), { variants: ['inline'] })\n .register('audio', (el, ctx) => mediaNode(el, ctx))\n .register('video', (el, ctx) => mediaNode(el, ctx))\n .register('file', (el, ctx) => mediaNode(el, ctx));\n return {\n id: 'html',\n elements,\n limits: {},\n assemble: (nodes, envelope) => assembleDraft(nodes, envelope.quote),\n serialize: (prepared, ctx) => serializeDraft(prepared, ctx),\n };\n}\n//# sourceMappingURL=html.js.map","import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core';\n/**\n * Publish one logical message as one SMTP transaction.\n *\n * The staged bytes are read before sending and released only after the server accepted the message, so a failed or\n * retried send still finds them. `confirmed` means the server answered `2xx` to `DATA` — the message left this host,\n * not that its recipient ever receives it.\n *\n * @param deps - staging and the SMTP transport.\n * @param payload - the serialized message.\n * @param _target - the chat being published to (the payload already names its recipient).\n * @param _ctx - send context (the quote is already part of the payload).\n * @returns the published part; `id` is nodemailer's generated `Message-ID`.\n */\nexport async function sendPayload(deps, payload, _target, _ctx) {\n const attachments = [];\n for (const attachment of payload.attachments) {\n const staged = deps.staging.get(attachment.key);\n if (staged === undefined) {\n throw new PlatformError('invalid', `mail: the attachment \"${attachment.filename}\" is no longer staged, nothing was sent`, { published: 'no' });\n }\n attachments.push({\n filename: attachment.filename,\n content: Buffer.from(staged.data),\n contentType: attachment.contentType,\n ...(attachment.cid === undefined ? {} : { cid: attachment.cid }),\n });\n }\n const options = {\n to: payload.to,\n subject: payload.subject,\n html: payload.html,\n text: payload.text,\n ...(payload.inReplyTo === undefined\n ? {}\n : { inReplyTo: payload.inReplyTo }),\n ...(payload.references === undefined\n ? {}\n : { references: payload.references }),\n ...(attachments.length === 0 ? {} : { attachments }),\n };\n const id = await deps.smtp.send(options);\n // The server already accepted the body, so an answer without a Message-ID is a published outcome, not a refusal.\n if (!id) {\n throw new PlatformError('invalid', 'mail: the server accepted the message without a Message-ID', {\n published: 'unknown',\n });\n }\n for (const attachment of payload.attachments)\n deps.staging.take(attachment.key);\n return {\n id,\n kind: 'message',\n time: Date.now(),\n referrer: { address: payload.to, messageId: id, subject: payload.subject },\n };\n}\n//# sourceMappingURL=send.js.map","/**\n * IMAP inbound transport: connection lifecycle, scanning, acknowledgement and reconnection.\n *\n * `node-imap` owns IDLE/NOOP keepalive internally, so this transport never sends a keepalive itself. It starts one\n * `Connection` and reuses it for every reconnect (the library resets its own state and keeps listeners). Every\n * `\\\\Seen` write happens only after the host accepted the message: a crash or a failed intake therefore leaves the\n * message unread, and the next scan delivers it again (the host dedupes by `Message-ID`). A malformed message is the\n * one exception: it is marked seen, because retrying it would fail forever.\n */\nimport { simpleParser } from 'mailparser';\nimport NodeIMAP from 'node-imap';\n/**\n * The delay before the next connection attempt.\n *\n * The fast budget counts consecutive failures: the first `retry.times` dials wait `retry.interval`, later ones wait\n * `retry.lazy`. A successful connection resets the count, so a flap is retried fast again.\n *\n * @param failures - consecutive failures before this attempt.\n * @param retry - the configured retry budget and delays.\n * @returns the delay in milliseconds.\n */\nexport function reconnectDelay(failures, retry) {\n return failures < retry.times ? retry.interval : retry.lazy;\n}\n/** The error message of a caught value. */\nfunction messageOf(error) {\n return error instanceof Error ? error.message : String(error);\n}\n/**\n * Read and parse one fetched message. The body stream is piped into `simpleParser` as soon as it arrives (an unread\n * stream would block the parser), so the result is a promise of either the parsed message, a parse error or neither\n * when the server sent no body.\n */\nfunction readMessage(message) {\n let uid;\n let size = 0;\n let parsing;\n return new Promise((resolve) => {\n message.on('body', (stream, info) => {\n size = info.size;\n // node-imap hands over a `stream.Readable`, which its declaration file types as `NodeJS.ReadableStream`.\n parsing = simpleParser(stream);\n // Observed right away: the explicit await below may come later, and an unhandled rejection would end the process.\n parsing.catch(() => undefined);\n });\n message.on('attributes', (attributes) => {\n uid = attributes.uid;\n });\n message.on('end', () => {\n const pending = parsing;\n if (pending === undefined) {\n resolve({ uid, size });\n return;\n }\n pending.then((mail) => {\n resolve({ uid, size, mail });\n }, (error) => {\n resolve({ uid, size, error });\n });\n });\n });\n}\n/**\n * The inbound connection of one account.\n *\n * `start()` resolves once the first attempt reached a stable state: the mailbox is open and the first scan runs in\n * the background, or the failure was transient and the reconnect timer took over. A permanent failure (credentials,\n * mailbox) rejects instead, so a misconfiguration is visible at startup.\n */\nexport class ImapTransport {\n options;\n imap;\n first;\n failures = 0;\n connected = false;\n stopping = false;\n permanent;\n reconnectTimer;\n scanning = false;\n rescan = false;\n scanPromise;\n mailListenerAttached = false;\n constructor(options) {\n this.options = options;\n }\n /** Create the connection (once) and wait for the first attempt's stable outcome. */\n async start() {\n const { config } = this.options;\n const imap = new NodeIMAP({\n user: config.username,\n password: config.password,\n host: config.imap.host,\n port: config.imap.port,\n tls: config.imap.tls,\n });\n this.imap = imap;\n imap.on('error', (error) => {\n this.handleError(error);\n });\n imap.on('ready', () => {\n this.handleReady();\n });\n imap.on('close', () => {\n this.handleClose();\n });\n const first = new Promise((resolve, reject) => {\n this.first = { resolve, reject };\n });\n imap.connect();\n return first;\n }\n /** Abort the reconnect timer, log out and wait for an in-flight scan. */\n async stop() {\n this.stopping = true;\n this.clearReconnect();\n const imap = this.imap;\n this.imap = undefined;\n if (imap !== undefined)\n imap.end();\n await this.scanPromise?.catch(() => undefined);\n }\n /**\n * Re-fetch one message by UID for the attachment route (`undefined` when the UID no longer exists).\n * @param uid - the IMAP UID to fetch.\n * @returns the parsed message.\n */\n async fetch(uid) {\n const imap = this.imap;\n if (imap === undefined)\n throw new Error('mail: the IMAP connection is not open');\n const fetched = imap.fetch(uid, { bodies: '' });\n const results = [];\n const tasks = [];\n await new Promise((resolve, reject) => {\n fetched.on('message', (message) => {\n tasks.push(readMessage(message).then((result) => {\n results.push(result);\n }));\n });\n fetched.on('end', () => {\n resolve();\n });\n fetched.on('error', reject);\n });\n await Promise.all(tasks);\n const [result] = results;\n if (result === undefined)\n return undefined;\n if (result.error !== undefined)\n throw result.error;\n return result.mail;\n }\n handleReady() {\n if (this.stopping)\n return;\n const imap = this.imap;\n if (imap === undefined)\n return;\n imap.openBox(this.options.config.mailbox, false, (error) => {\n if (this.stopping)\n return;\n if (error) {\n this.options.logger.error('mail: the mailbox %s could not be opened: %s', this.options.config.mailbox, messageOf(error));\n this.failPermanently(error);\n return;\n }\n this.failures = 0;\n this.connected = true;\n this.options.onOnline();\n this.first?.resolve();\n this.first = undefined;\n this.attachMailListener();\n void this.scan();\n });\n }\n handleError(error) {\n if (this.stopping)\n return;\n if (error.source === 'authentication') {\n this.options.logger.error('mail: IMAP authentication failed: %s', messageOf(error));\n this.failPermanently(error);\n return;\n }\n this.options.logger.warn('mail: IMAP error (%s): %s', error.source ?? 'unknown', messageOf(error));\n // A transient first failure lets startup continue with the reconnect timer instead of failing the whole profile.\n this.first?.resolve();\n this.first = undefined;\n }\n handleClose() {\n if (this.stopping)\n return;\n this.connected = false;\n if (this.permanent !== undefined)\n return;\n // A close during the first attempt is transient too: the reconnect loop takes over.\n this.first?.resolve();\n this.first = undefined;\n this.options.onReconnect();\n this.scheduleReconnect();\n }\n failPermanently(error) {\n this.permanent = error;\n this.connected = false;\n this.clearReconnect();\n this.first?.reject(error);\n this.first = undefined;\n this.options.onOffline(error);\n }\n scheduleReconnect() {\n if (this.stopping ||\n this.permanent !== undefined ||\n this.reconnectTimer !== undefined ||\n this.connected)\n return;\n const delay = reconnectDelay(this.failures, this.options.config.retry);\n this.failures += 1;\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = undefined;\n if (this.stopping || this.permanent !== undefined)\n return;\n this.imap?.connect();\n }, delay);\n }\n clearReconnect() {\n if (this.reconnectTimer === undefined)\n return;\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = undefined;\n }\n /** Register the new-mail listener once: every reconnect reuses the connection and its listeners. */\n attachMailListener() {\n const imap = this.imap;\n if (this.mailListenerAttached || imap === undefined)\n return;\n this.mailListenerAttached = true;\n imap.on('mail', () => {\n void this.scan();\n });\n }\n /** Run one scan; a request during a scan sets one \"run again\" flag instead of starting a second scan. */\n scan() {\n if (this.scanning) {\n this.rescan = true;\n return Promise.resolve();\n }\n this.scanning = true;\n const run = (async () => {\n try {\n do {\n this.rescan = false;\n await this.scanOnce();\n } while (this.rescan && !this.stopping && this.connected);\n }\n catch (error) {\n // A failed scan never ends the connection loop: the next mail event or reconnect scans again.\n this.options.logger.error('mail: the scan failed: %s', messageOf(error));\n }\n finally {\n this.scanning = false;\n }\n })();\n this.scanPromise = run;\n return run;\n }\n async scanOnce() {\n const imap = this.imap;\n if (imap === undefined)\n return;\n const uids = await new Promise((resolve, reject) => {\n imap.search(['UNSEEN'], (error, result) => {\n if (error)\n reject(error);\n else\n resolve(result ?? []);\n });\n });\n if (uids.length === 0)\n return;\n const fetched = imap.fetch(uids, { bodies: '' });\n const tasks = [];\n await new Promise((resolve) => {\n let settled = false;\n const done = () => {\n if (settled)\n return;\n settled = true;\n resolve();\n };\n fetched.on('message', (message) => {\n tasks.push(this.deliverMessage(message));\n });\n fetched.on('end', done);\n fetched.on('error', (error) => {\n this.options.logger.error('mail: fetching the message bodies failed: %s', messageOf(error));\n done();\n });\n });\n await Promise.all(tasks);\n }\n /** Parse one fetched message, hand it to the host and acknowledge it only when the host accepted it. */\n async deliverMessage(message) {\n const result = await readMessage(message);\n if (result.mail === undefined) {\n // A malformed message can never be parsed: marking it seen is the only way out of the retry loop.\n if (result.error !== undefined) {\n this.options.logger.error('mail: the message could not be parsed: %s', messageOf(result.error));\n }\n else {\n this.options.logger.error('mail: a fetched message carried no body');\n }\n if (result.uid !== undefined)\n await this.markSeen(result.uid);\n return;\n }\n if (result.uid === undefined) {\n // Without the UID there is nothing to acknowledge; the host still receives the message.\n this.options.logger.error('mail: a fetched message carried no UID');\n return;\n }\n try {\n await this.options.deliver(result.mail, {\n uid: result.uid,\n mailbox: this.options.config.mailbox,\n size: result.size,\n });\n }\n catch (error) {\n // Not accepted: leave it unseen so the next scan retries it.\n this.options.logger.error('mail: the host did not accept a message, it stays unseen: %s', messageOf(error));\n return;\n }\n await this.markSeen(result.uid);\n }\n /** Write `\\\\Seen`; a failure only warns, because the host deduplicates the redelivery by `Message-ID`. */\n async markSeen(uid) {\n const imap = this.imap;\n if (imap === undefined)\n return;\n try {\n await new Promise((resolve, reject) => {\n imap.setFlags(uid, ['\\\\SEEN'], (error) => {\n if (error)\n reject(error);\n else\n resolve();\n });\n });\n }\n catch (error) {\n this.options.logger.warn('mail: the message %d could not be marked as seen: %s', uid, messageOf(error));\n }\n }\n}\n//# sourceMappingURL=imap.js.map","import { createTransport } from 'nodemailer';\nexport class SMTP {\n transporter;\n from;\n constructor(config) {\n this.transporter = createTransport({\n host: config.smtp.host,\n port: config.smtp.port,\n secure: config.smtp.tls,\n auth: {\n user: config.username,\n pass: config.password,\n },\n });\n const address = config.selfId || config.username;\n this.from = config.name ? `${config.name} <${address}>` : address;\n }\n async send(options) {\n const info = await this.transporter.sendMail({\n ...options,\n from: this.from,\n });\n return info.messageId;\n }\n}\n//# sourceMappingURL=mail.js.map","import { Adapter, PlatformError, Status, } from '@deepseek-ai/cordis-plugin-im-core';\nimport { addressOf, Config } from \"./config.js\";\nimport { decodeMessage } from \"./decode.js\";\nimport { classifyMailError } from \"./errors.js\";\nimport { MediaStaging } from \"./media.js\";\nimport { createHtmlMode } from \"./modes/html.js\";\nimport { sendPayload } from \"./send.js\";\nimport { ImapTransport } from \"./transport/imap.js\";\nimport { SMTP } from \"./mail.js\";\n/** The error message of a caught value. */\nfunction messageOf(error) {\n return error instanceof Error ? error.message : String(error);\n}\n/** Response headers of one attachment served through the `satori:` route. */\nfunction attachmentHeaders(attachment) {\n const headers = new Headers({ 'content-type': attachment.contentType });\n const disposition = attachment.contentDisposition ?? 'attachment';\n headers.set('content-disposition', attachment.filename === undefined\n ? disposition\n : `${disposition}; filename=\"${attachment.filename.replaceAll('\"', '')}\"`);\n return headers;\n}\n/**\n * Mail adapter: IMAP inbound, SMTP outbound, one `html` mode.\n *\n * Identity is fixed at construction because a mail account has no platform user id to look up: `bot.id` is\n * `mail:<address>` and `bot.selfId` is the address itself. Inbound messages are acknowledged by `\\\\Seen` only after\n * `bot.receive` accepted them; outbound attachments are staged in memory between `prepare` and `sendPayload`.\n */\nexport class MailBot extends Adapter {\n /** The Loader applies this schema to a profile row's `config` before the constructor runs. */\n static Config = Config;\n modes = { html: createHtmlMode() };\n modeOrder = ['html'];\n /** Outbound SMTP transport (the adapter's platform API). */\n internal;\n /** Outbound attachment bytes between `prepare` and `sendPayload`. */\n staging;\n transport;\n /** Single-entry memo of the last message fetched for an attachment, so a message with several attachments costs one fetch. */\n memo;\n constructor(ctx, config) {\n const address = addressOf(config);\n super(ctx, config, {\n id: `mail:${address}`,\n platform: 'mail',\n adapter: 'mail',\n });\n this.selfId = address;\n this.user = {\n id: address,\n ...(config.name ? { name: config.name } : {}),\n isBot: true,\n };\n this.internal = new SMTP(config);\n this.staging = new MediaStaging(config.media.stagingTtlMs, config.media.maxStagedBytes);\n this.defineInternalRoute('/messages/:uid/attachments/:index', (request) => this.serveAttachment(request));\n }\n async connect() {\n // A wrong SMTP configuration becomes visible at startup, but inbound must not be blocked by it.\n try {\n await this.internal.transporter.verify();\n this.ctx.logger.debug('mail: SMTP credentials verified');\n }\n catch (error) {\n this.ctx.logger.warn('mail: SMTP verification failed, sending may fail: %s', messageOf(error));\n }\n const transport = new ImapTransport({\n config: this.config,\n logger: this.ctx.logger,\n deliver: (mail, source) => this.deliver(mail, source),\n onOnline: () => {\n this.online();\n },\n onReconnect: () => {\n this.status = Status.RECONNECT;\n },\n onOffline: (error) => {\n this.offline(error);\n },\n });\n this.transport = transport;\n try {\n await transport.start();\n }\n catch (error) {\n // `Bot.start` only stores a connect failure on `bot.error`; a permanent failure belongs in the log as well.\n this.ctx.logger.error('mail: connect failed: %s', messageOf(error));\n await transport.stop();\n this.transport = undefined;\n throw error;\n }\n }\n async disconnect() {\n const transport = this.transport;\n this.transport = undefined;\n await transport?.stop();\n }\n async upload(ref, _scope, ctx) {\n let fetched;\n try {\n fetched = await ctx.fetch(ref.src, ctx.signal);\n }\n catch (error) {\n // No byte left this host, so the publication certainly did not happen.\n throw new PlatformError('invalid', `mail: the resource \"${ref.src}\" could not be read: ${messageOf(error)}`, {\n published: 'no',\n cause: error,\n });\n }\n const mime = ref.meta.mime ?? fetched.mime;\n return this.staging.stage({\n data: fetched.data,\n name: ref.meta.name ?? fetched.name ?? '',\n ...(mime === undefined ? {} : { mime }),\n });\n }\n resourceScope(_target, _kind) {\n return this.id;\n }\n async sendPayload(payload, target, ctx) {\n return sendPayload({ config: this.config, staging: this.staging, smtp: this.internal }, payload, target, ctx);\n }\n classify(error) {\n return classifyMailError(error);\n }\n /** Decode and hand one message to the host; `\\\\Seen` is written by the transport once this resolved. */\n async deliver(mail, source) {\n const decoder = {\n selfId: this.selfId,\n config: this.config,\n getInternalUrl: (path, init) => this.getInternalUrl(path, init),\n log: (text) => {\n this.ctx.logger.debug(text);\n },\n };\n const message = decodeMessage(decoder, mail, source);\n if (message === undefined)\n return;\n await this.receive(this.session({\n type: 'message',\n id: message.id,\n timestamp: message.time,\n message,\n }));\n }\n /** Serve one attachment of a stored message, re-fetching the message by UID. */\n async serveAttachment(request) {\n const uid = Number(request.params.uid);\n const index = Number(request.params.index);\n if (!Number.isSafeInteger(uid) ||\n uid <= 0 ||\n !Number.isSafeInteger(index) ||\n index < 0) {\n return new Response(null, { status: 400 });\n }\n if (request.query.get('box') !== this.config.mailbox)\n return new Response(null, { status: 404 });\n let mail;\n try {\n mail = await this.fetchMail(uid);\n }\n catch (error) {\n this.ctx.logger.warn('mail: the message %d could not be fetched: %s', uid, messageOf(error));\n return new Response(null, { status: 502 });\n }\n const attachment = mail?.attachments[index];\n if (attachment === undefined)\n return new Response(null, { status: 404 });\n return new Response(new Uint8Array(attachment.content), {\n headers: attachmentHeaders(attachment),\n });\n }\n /** Fetch one message for the attachment route, memoizing the last one. */\n async fetchMail(uid) {\n if (this.memo?.uid === uid)\n return this.memo.mail;\n const transport = this.transport;\n if (transport === undefined)\n throw new Error('mail: the IMAP connection is not open');\n const mail = await transport.fetch(uid);\n if (mail !== undefined)\n this.memo = { uid, mail };\n return mail;\n }\n}\nexport { Config };\nexport default MailBot;\n//# sourceMappingURL=bot.js.map"],"mappings":";;;;;;;;;;AAEA,MAAa,SAAS,EAAE,OAAO;CAC3B,UAAU,EAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,UAAU,EAAE,OAAO,CAAC,CAAC,KAAK,QAAQ,CAAC,CAAC,SAAS;CAC7C,QAAQ,EAAE,OAAO;CACjB,MAAM,EAAE,OAAO;CACf,SAAS,EAAE,OAA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AQ,OAAO,QAAQ,OAAO,KAAK;EACzC,IAAI,CAAC,OAAO,cAAc,GAAG,KACzB,OAAO,KACP,CAAC,OAAO,cAAc,KAAK,KAC3B,QAAQ,GACR,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;EAE7C,IAAI,QAAQ,MAAM,IAAI,KAAK,MAAM,KAAK,OAAO,SACzC,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;EAC7C,IAAI;EACJ,IAAI;GACA,OAAO,MAAM,KAAK,UAAU,GAAG;EACnC,SACO,OAAO;GACV,KAAK,IAAI,OAAO,KAAK,iDAAiD,KAAK,UAAU,KAAK,CAAC;GAC3F,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;EAC7C;EACA,MAAM,aAAa,MAAM,YAAY;EACrC,IAAI,eAAe,KAAA,GACf,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;EAC7C,OAAO,IAAI,SAAS,IAAI,WAAW,WAAW,OAAO,GAAG,EACpD,SAAS,kBAAkB,UAAU,EACzC,CAAC;CACL;;CAEA,MAAM,UAAU,KAAK;EACjB,IAAI,KAAK,MAAM,QAAQ,KACnB,OAAO,KAAK,KAAK;EACrB,MAAM,YAAY,KAAK;EACvB,IAAI,cAAc,KAAA,GACd,MAAM,IAAI,MAAM,uCAAuC;EAC3D,MAAM,OAAO,MAAM,UAAU,MAAM,GAAG;EACtC,IAAI,SAAS,KAAA,GACT,KAAK,OAAO;GAAE;GAAK;EAAK;EAC5B,OAAO;CACX;AACJ"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import { Adapter, PlatformError } from '@deepseek-ai/cordis-plugin-im-core';
|
|
3
|
+
import type { Mode, PrepareContext, ResolvedResource, ResourceKind, ResourceRef, SendContext, SentPart, Target } from '@deepseek-ai/cordis-plugin-im-core';
|
|
4
|
+
import { Config } from './config.ts';
|
|
5
|
+
import type { Config as MailConfig } from './config.ts';
|
|
6
|
+
import { MediaStaging } from './media.ts';
|
|
7
|
+
import type { MailModeTypes } from './modes/shared.ts';
|
|
8
|
+
import { SMTP } from './mail.ts';
|
|
9
|
+
/** The one mode this adapter implements. */
|
|
10
|
+
export interface MailModes {
|
|
11
|
+
[mode: string]: Mode<MailModeTypes>;
|
|
12
|
+
html: Mode<MailModeTypes>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Mail adapter: IMAP inbound, SMTP outbound, one `html` mode.
|
|
16
|
+
*
|
|
17
|
+
* Identity is fixed at construction because a mail account has no platform user id to look up: `bot.id` is
|
|
18
|
+
* `mail:<address>` and `bot.selfId` is the address itself. Inbound messages are acknowledged by `\\Seen` only after
|
|
19
|
+
* `bot.receive` accepted them; outbound attachments are staged in memory between `prepare` and `sendPayload`.
|
|
20
|
+
*/
|
|
21
|
+
export declare class MailBot extends Adapter<MailConfig, MailModes> {
|
|
22
|
+
/** The Loader applies this schema to a profile row's `config` before the constructor runs. */
|
|
23
|
+
static readonly Config: import("@deepseek-ai/schemastery").default<Config>;
|
|
24
|
+
readonly modes: MailModes;
|
|
25
|
+
readonly modeOrder: readonly ["html"];
|
|
26
|
+
/** Outbound SMTP transport (the adapter's platform API). */
|
|
27
|
+
readonly internal: SMTP;
|
|
28
|
+
/** Outbound attachment bytes between `prepare` and `sendPayload`. */
|
|
29
|
+
readonly staging: MediaStaging;
|
|
30
|
+
private transport;
|
|
31
|
+
/** Single-entry memo of the last message fetched for an attachment, so a message with several attachments costs one fetch. */
|
|
32
|
+
private memo;
|
|
33
|
+
constructor(ctx: Context, config: MailConfig);
|
|
34
|
+
connect(): Promise<void>;
|
|
35
|
+
disconnect(): Promise<void>;
|
|
36
|
+
upload(ref: ResourceRef, _scope: string, ctx: PrepareContext): Promise<ResolvedResource>;
|
|
37
|
+
resourceScope(_target: Target, _kind: ResourceKind): string;
|
|
38
|
+
sendPayload(payload: unknown, target: Target, ctx: SendContext): Promise<SentPart>;
|
|
39
|
+
classify(error: unknown): PlatformError;
|
|
40
|
+
/** Decode and hand one message to the host; `\\Seen` is written by the transport once this resolved. */
|
|
41
|
+
private deliver;
|
|
42
|
+
/** Serve one attachment of a stored message, re-fetching the message by UID. */
|
|
43
|
+
private serveAttachment;
|
|
44
|
+
/** Fetch one message for the attachment route, memoizing the last one. */
|
|
45
|
+
private fetchMail;
|
|
46
|
+
}
|
|
47
|
+
export { Config };
|
|
48
|
+
export default MailBot;
|
|
49
|
+
//# sourceMappingURL=bot.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bot.d.ts","sourceRoot":"","sources":["../../src/bot.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EACL,OAAO,EACP,aAAa,EAEd,MAAM,oCAAoC,CAAA;AAC3C,OAAO,KAAK,EACV,IAAI,EACJ,cAAc,EACd,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,WAAW,EACX,QAAQ,EACR,MAAM,EACP,MAAM,oCAAoC,CAAA;AAE3C,OAAO,EAAa,MAAM,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,KAAK,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,aAAa,CAAA;AAIvD,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAEzC,OAAO,KAAK,EAAE,aAAa,EAAe,MAAM,mBAAmB,CAAA;AAGnE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAEhC,4CAA4C;AAC5C,MAAM,WAAW,SAAS;IACxB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC,aAAa,CAAC,CAAA;IACnC,IAAI,EAAE,IAAI,CAAC,aAAa,CAAC,CAAA;CAC1B;AAoBD;;;;;;GAMG;AACH,qBAAa,OAAQ,SAAQ,OAAO,CAAC,UAAU,EAAE,SAAS,CAAC;IACzD,8FAA8F;IAC9F,MAAM,CAAC,QAAQ,CAAC,MAAM,qDAAS;IAE/B,QAAQ,CAAC,KAAK,EAAE,SAAS,CAA6B;IACtD,QAAQ,CAAC,SAAS,oBAAoB;IAEtC,4DAA4D;IAC5D,SAAkB,QAAQ,EAAE,IAAI,CAAA;IAChC,qEAAqE;IACrE,QAAQ,CAAC,OAAO,EAAE,YAAY,CAAA;IAE9B,OAAO,CAAC,SAAS,CAA2B;IAC5C,8HAA8H;IAC9H,OAAO,CAAC,IAAI,CAA+C;gBAE/C,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU;IAuB7B,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAqCxB,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAM3B,MAAM,CACnB,GAAG,EAAE,WAAW,EAChB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,cAAc,GAClB,OAAO,CAAC,gBAAgB,CAAC;IAuBnB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,GAAG,MAAM;IAIrD,WAAW,CACxB,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,WAAW,GACf,OAAO,CAAC,QAAQ,CAAC;IASX,QAAQ,CAAC,KAAK,EAAE,OAAO;IAIhC,wGAAwG;YAC1F,OAAO;IAqBrB,gFAAgF;YAClE,eAAe;IAoC7B,0EAA0E;YAC5D,SAAS;CASxB;AAED,OAAO,EAAE,MAAM,EAAE,CAAA;AAEjB,eAAe,OAAO,CAAA"}
|
package/lib/types/bot.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { Adapter, PlatformError, Status, } from '@deepseek-ai/cordis-plugin-im-core';
|
|
2
|
+
import { addressOf, Config } from "./config.js";
|
|
3
|
+
import { decodeMessage } from "./decode.js";
|
|
4
|
+
import { classifyMailError } from "./errors.js";
|
|
5
|
+
import { MediaStaging } from "./media.js";
|
|
6
|
+
import { createHtmlMode } from "./modes/html.js";
|
|
7
|
+
import { sendPayload } from "./send.js";
|
|
8
|
+
import { ImapTransport } from "./transport/imap.js";
|
|
9
|
+
import { SMTP } from "./mail.js";
|
|
10
|
+
/** The error message of a caught value. */
|
|
11
|
+
function messageOf(error) {
|
|
12
|
+
return error instanceof Error ? error.message : String(error);
|
|
13
|
+
}
|
|
14
|
+
/** Response headers of one attachment served through the `satori:` route. */
|
|
15
|
+
function attachmentHeaders(attachment) {
|
|
16
|
+
const headers = new Headers({ 'content-type': attachment.contentType });
|
|
17
|
+
const disposition = attachment.contentDisposition ?? 'attachment';
|
|
18
|
+
headers.set('content-disposition', attachment.filename === undefined
|
|
19
|
+
? disposition
|
|
20
|
+
: `${disposition}; filename="${attachment.filename.replaceAll('"', '')}"`);
|
|
21
|
+
return headers;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Mail adapter: IMAP inbound, SMTP outbound, one `html` mode.
|
|
25
|
+
*
|
|
26
|
+
* Identity is fixed at construction because a mail account has no platform user id to look up: `bot.id` is
|
|
27
|
+
* `mail:<address>` and `bot.selfId` is the address itself. Inbound messages are acknowledged by `\\Seen` only after
|
|
28
|
+
* `bot.receive` accepted them; outbound attachments are staged in memory between `prepare` and `sendPayload`.
|
|
29
|
+
*/
|
|
30
|
+
export class MailBot extends Adapter {
|
|
31
|
+
/** The Loader applies this schema to a profile row's `config` before the constructor runs. */
|
|
32
|
+
static Config = Config;
|
|
33
|
+
modes = { html: createHtmlMode() };
|
|
34
|
+
modeOrder = ['html'];
|
|
35
|
+
/** Outbound SMTP transport (the adapter's platform API). */
|
|
36
|
+
internal;
|
|
37
|
+
/** Outbound attachment bytes between `prepare` and `sendPayload`. */
|
|
38
|
+
staging;
|
|
39
|
+
transport;
|
|
40
|
+
/** Single-entry memo of the last message fetched for an attachment, so a message with several attachments costs one fetch. */
|
|
41
|
+
memo;
|
|
42
|
+
constructor(ctx, config) {
|
|
43
|
+
const address = addressOf(config);
|
|
44
|
+
super(ctx, config, {
|
|
45
|
+
id: `mail:${address}`,
|
|
46
|
+
platform: 'mail',
|
|
47
|
+
adapter: 'mail',
|
|
48
|
+
});
|
|
49
|
+
this.selfId = address;
|
|
50
|
+
this.user = {
|
|
51
|
+
id: address,
|
|
52
|
+
...(config.name ? { name: config.name } : {}),
|
|
53
|
+
isBot: true,
|
|
54
|
+
};
|
|
55
|
+
this.internal = new SMTP(config);
|
|
56
|
+
this.staging = new MediaStaging(config.media.stagingTtlMs, config.media.maxStagedBytes);
|
|
57
|
+
this.defineInternalRoute('/messages/:uid/attachments/:index', (request) => this.serveAttachment(request));
|
|
58
|
+
}
|
|
59
|
+
async connect() {
|
|
60
|
+
// A wrong SMTP configuration becomes visible at startup, but inbound must not be blocked by it.
|
|
61
|
+
try {
|
|
62
|
+
await this.internal.transporter.verify();
|
|
63
|
+
this.ctx.logger.debug('mail: SMTP credentials verified');
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
this.ctx.logger.warn('mail: SMTP verification failed, sending may fail: %s', messageOf(error));
|
|
67
|
+
}
|
|
68
|
+
const transport = new ImapTransport({
|
|
69
|
+
config: this.config,
|
|
70
|
+
logger: this.ctx.logger,
|
|
71
|
+
deliver: (mail, source) => this.deliver(mail, source),
|
|
72
|
+
onOnline: () => {
|
|
73
|
+
this.online();
|
|
74
|
+
},
|
|
75
|
+
onReconnect: () => {
|
|
76
|
+
this.status = Status.RECONNECT;
|
|
77
|
+
},
|
|
78
|
+
onOffline: (error) => {
|
|
79
|
+
this.offline(error);
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
this.transport = transport;
|
|
83
|
+
try {
|
|
84
|
+
await transport.start();
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
// `Bot.start` only stores a connect failure on `bot.error`; a permanent failure belongs in the log as well.
|
|
88
|
+
this.ctx.logger.error('mail: connect failed: %s', messageOf(error));
|
|
89
|
+
await transport.stop();
|
|
90
|
+
this.transport = undefined;
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async disconnect() {
|
|
95
|
+
const transport = this.transport;
|
|
96
|
+
this.transport = undefined;
|
|
97
|
+
await transport?.stop();
|
|
98
|
+
}
|
|
99
|
+
async upload(ref, _scope, ctx) {
|
|
100
|
+
let fetched;
|
|
101
|
+
try {
|
|
102
|
+
fetched = await ctx.fetch(ref.src, ctx.signal);
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
// No byte left this host, so the publication certainly did not happen.
|
|
106
|
+
throw new PlatformError('invalid', `mail: the resource "${ref.src}" could not be read: ${messageOf(error)}`, {
|
|
107
|
+
published: 'no',
|
|
108
|
+
cause: error,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
const mime = ref.meta.mime ?? fetched.mime;
|
|
112
|
+
return this.staging.stage({
|
|
113
|
+
data: fetched.data,
|
|
114
|
+
name: ref.meta.name ?? fetched.name ?? '',
|
|
115
|
+
...(mime === undefined ? {} : { mime }),
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
resourceScope(_target, _kind) {
|
|
119
|
+
return this.id;
|
|
120
|
+
}
|
|
121
|
+
async sendPayload(payload, target, ctx) {
|
|
122
|
+
return sendPayload({ config: this.config, staging: this.staging, smtp: this.internal }, payload, target, ctx);
|
|
123
|
+
}
|
|
124
|
+
classify(error) {
|
|
125
|
+
return classifyMailError(error);
|
|
126
|
+
}
|
|
127
|
+
/** Decode and hand one message to the host; `\\Seen` is written by the transport once this resolved. */
|
|
128
|
+
async deliver(mail, source) {
|
|
129
|
+
const decoder = {
|
|
130
|
+
selfId: this.selfId,
|
|
131
|
+
config: this.config,
|
|
132
|
+
getInternalUrl: (path, init) => this.getInternalUrl(path, init),
|
|
133
|
+
log: (text) => {
|
|
134
|
+
this.ctx.logger.debug(text);
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
const message = decodeMessage(decoder, mail, source);
|
|
138
|
+
if (message === undefined)
|
|
139
|
+
return;
|
|
140
|
+
await this.receive(this.session({
|
|
141
|
+
type: 'message',
|
|
142
|
+
id: message.id,
|
|
143
|
+
timestamp: message.time,
|
|
144
|
+
message,
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
/** Serve one attachment of a stored message, re-fetching the message by UID. */
|
|
148
|
+
async serveAttachment(request) {
|
|
149
|
+
const uid = Number(request.params.uid);
|
|
150
|
+
const index = Number(request.params.index);
|
|
151
|
+
if (!Number.isSafeInteger(uid) ||
|
|
152
|
+
uid <= 0 ||
|
|
153
|
+
!Number.isSafeInteger(index) ||
|
|
154
|
+
index < 0) {
|
|
155
|
+
return new Response(null, { status: 400 });
|
|
156
|
+
}
|
|
157
|
+
if (request.query.get('box') !== this.config.mailbox)
|
|
158
|
+
return new Response(null, { status: 404 });
|
|
159
|
+
let mail;
|
|
160
|
+
try {
|
|
161
|
+
mail = await this.fetchMail(uid);
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
this.ctx.logger.warn('mail: the message %d could not be fetched: %s', uid, messageOf(error));
|
|
165
|
+
return new Response(null, { status: 502 });
|
|
166
|
+
}
|
|
167
|
+
const attachment = mail?.attachments[index];
|
|
168
|
+
if (attachment === undefined)
|
|
169
|
+
return new Response(null, { status: 404 });
|
|
170
|
+
return new Response(new Uint8Array(attachment.content), {
|
|
171
|
+
headers: attachmentHeaders(attachment),
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
/** Fetch one message for the attachment route, memoizing the last one. */
|
|
175
|
+
async fetchMail(uid) {
|
|
176
|
+
if (this.memo?.uid === uid)
|
|
177
|
+
return this.memo.mail;
|
|
178
|
+
const transport = this.transport;
|
|
179
|
+
if (transport === undefined)
|
|
180
|
+
throw new Error('mail: the IMAP connection is not open');
|
|
181
|
+
const mail = await transport.fetch(uid);
|
|
182
|
+
if (mail !== undefined)
|
|
183
|
+
this.memo = { uid, mail };
|
|
184
|
+
return mail;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
export { Config };
|
|
188
|
+
export default MailBot;
|
|
189
|
+
//# sourceMappingURL=bot.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bot.js","sourceRoot":"","sources":["../../src/bot.ts"],"names":[],"mappings":"AACA,OAAO,EACL,OAAO,EACP,aAAa,EACb,MAAM,GACP,MAAM,oCAAoC,CAAA;AAY3C,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAE/C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAE3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAEhD,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAQhC,2CAA2C;AAC3C,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC/D,CAAC;AAED,6EAA6E;AAC7E,SAAS,iBAAiB,CAAC,UAAsB;IAC/C,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,EAAE,cAAc,EAAE,UAAU,CAAC,WAAW,EAAE,CAAC,CAAA;IACvE,MAAM,WAAW,GAAG,UAAU,CAAC,kBAAkB,IAAI,YAAY,CAAA;IACjE,OAAO,CAAC,GAAG,CACT,qBAAqB,EACrB,UAAU,CAAC,QAAQ,KAAK,SAAS;QAC/B,CAAC,CAAC,WAAW;QACb,CAAC,CAAC,GAAG,WAAW,eAAe,UAAU,CAAC,QAAQ,CAAC,UAAU,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAC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SAAS,GAAG,IAAI,CAAC,SAAS,CAAA;QAChC,IAAI,SAAS,KAAK,SAAS;YACzB,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAA;QAC1D,MAAM,IAAI,GAAG,MAAM,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;QACvC,IAAI,IAAI,KAAK,SAAS;YAAE,IAAI,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,CAAA;QACjD,OAAO,IAAI,CAAA;IACb,CAAC;;AAGH,OAAO,EAAE,MAAM,EAAE,CAAA;AAEjB,eAAe,OAAO,CAAA"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import z from '@deepseek-ai/schemastery';
|
|
2
|
+
/** One mail account: IMAP credentials and the two transport endpoints. */
|
|
3
|
+
export interface Config {
|
|
4
|
+
/** Login name of the account (usually the address); used by both IMAP `LOGIN` and SMTP `AUTH`. */
|
|
5
|
+
username: string;
|
|
6
|
+
/** Password or application password. */
|
|
7
|
+
password: string;
|
|
8
|
+
/** The address this bot answers as; defaults to {@link Config.username}. */
|
|
9
|
+
selfId?: string | null;
|
|
10
|
+
/** Display name of the `From:` header. */
|
|
11
|
+
name?: string | null;
|
|
12
|
+
/** Subject of a message that does not answer another one. */
|
|
13
|
+
subject: string;
|
|
14
|
+
/** Mailbox the inbound scan watches. */
|
|
15
|
+
mailbox: string;
|
|
16
|
+
imap: {
|
|
17
|
+
host: string;
|
|
18
|
+
/** Implicit TLS. With `port: 143` this asks `node-imap` to upgrade via STARTTLS. */
|
|
19
|
+
tls: boolean;
|
|
20
|
+
port: number;
|
|
21
|
+
};
|
|
22
|
+
smtp: {
|
|
23
|
+
host: string;
|
|
24
|
+
/** Implicit TLS (`secure`). */
|
|
25
|
+
tls: boolean;
|
|
26
|
+
port: number;
|
|
27
|
+
};
|
|
28
|
+
retry: {
|
|
29
|
+
/** Fast-retry budget of the reconnect timer; it never gives up. */
|
|
30
|
+
times: number;
|
|
31
|
+
/** Delay between dials while the fast-retry budget lasts. */
|
|
32
|
+
interval: number;
|
|
33
|
+
/** Delay between dials once the fast-retry budget is spent. */
|
|
34
|
+
lazy: number;
|
|
35
|
+
};
|
|
36
|
+
media: {
|
|
37
|
+
/** How long outbound attachment bytes stay staged for a retry. */
|
|
38
|
+
stagingTtlMs: number;
|
|
39
|
+
/** Upper bound of all staged bytes; the oldest entries are evicted first. */
|
|
40
|
+
maxStagedBytes: number;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** Validated Mail adapter configuration. */
|
|
44
|
+
export declare const Config: z<Config>;
|
|
45
|
+
/**
|
|
46
|
+
* The address this bot answers as: `selfId` when given, else the login name.
|
|
47
|
+
* @param config - the validated adapter configuration.
|
|
48
|
+
* @returns the bot's own address.
|
|
49
|
+
*/
|
|
50
|
+
export declare function addressOf(config: Config): string;
|
|
51
|
+
//# sourceMappingURL=config.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAExC,0EAA0E;AAC1E,MAAM,WAAW,MAAM;IACrB,kGAAkG;IAClG,QAAQ,EAAE,MAAM,CAAA;IAChB,wCAAwC;IACxC,QAAQ,EAAE,MAAM,CAAA;IAChB,4EAA4E;IAC5E,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,0CAA0C;IAC1C,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,6DAA6D;IAC7D,OAAO,EAAE,MAAM,CAAA;IACf,wCAAwC;IACxC,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE;QACJ,IAAI,EAAE,MAAM,CAAA;QACZ,oFAAoF;QACpF,GAAG,EAAE,OAAO,CAAA;QACZ,IAAI,EAAE,MAAM,CAAA;KACb,CAAA;IACD,IAAI,EAAE;QACJ,IAAI,EAAE,MAAM,CAAA;QACZ,+BAA+B;QAC/B,GAAG,EAAE,OAAO,CAAA;QACZ,IAAI,EAAE,MAAM,CAAA;KACb,CAAA;IACD,KAAK,EAAE;QACL,mEAAmE;QACnE,KAAK,EAAE,MAAM,CAAA;QACb,6DAA6D;QAC7D,QAAQ,EAAE,MAAM,CAAA;QAChB,+DAA+D;QAC/D,IAAI,EAAE,MAAM,CAAA;KACb,CAAA;IACD,KAAK,EAAE;QACL,kEAAkE;QAClE,YAAY,EAAE,MAAM,CAAA;QACpB,6EAA6E;QAC7E,cAAc,EAAE,MAAM,CAAA;KACvB,CAAA;CACF;AAED,4CAA4C;AAC5C,eAAO,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CA2C3B,CAAA;AAEF;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEhD"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import z from '@deepseek-ai/schemastery';
|
|
2
|
+
/** Validated Mail adapter configuration. */
|
|
3
|
+
export const Config = z.object({
|
|
4
|
+
username: z.string().required(),
|
|
5
|
+
password: z.string().role('secret').required(),
|
|
6
|
+
selfId: z.string(),
|
|
7
|
+
name: z.string(),
|
|
8
|
+
subject: z.string().default('Koishi'),
|
|
9
|
+
mailbox: z.string().default('INBOX'),
|
|
10
|
+
imap: z.intersect([
|
|
11
|
+
z.object({
|
|
12
|
+
host: z.string().required(),
|
|
13
|
+
tls: z.boolean().default(true),
|
|
14
|
+
}),
|
|
15
|
+
z.union([
|
|
16
|
+
z.object({ tls: z.const(true), port: z.natural().default(993) }),
|
|
17
|
+
z.object({ tls: z.const(false), port: z.natural().default(143) }),
|
|
18
|
+
]),
|
|
19
|
+
]),
|
|
20
|
+
smtp: z.intersect([
|
|
21
|
+
z.object({
|
|
22
|
+
host: z.string().required(),
|
|
23
|
+
tls: z.boolean().default(true),
|
|
24
|
+
}),
|
|
25
|
+
z.union([
|
|
26
|
+
z.object({ tls: z.const(true), port: z.natural().default(465) }),
|
|
27
|
+
z.object({ tls: z.const(false), port: z.natural().default(25) }),
|
|
28
|
+
]),
|
|
29
|
+
]),
|
|
30
|
+
retry: z
|
|
31
|
+
.object({
|
|
32
|
+
times: z.natural().default(6),
|
|
33
|
+
interval: z.natural().role('ms').default(5_000),
|
|
34
|
+
lazy: z.natural().role('ms').default(60_000),
|
|
35
|
+
})
|
|
36
|
+
.default({}),
|
|
37
|
+
media: z
|
|
38
|
+
.object({
|
|
39
|
+
stagingTtlMs: z
|
|
40
|
+
.natural()
|
|
41
|
+
.role('ms')
|
|
42
|
+
.default(10 * 60_000),
|
|
43
|
+
maxStagedBytes: z.natural().default(64 * 1024 * 1024),
|
|
44
|
+
})
|
|
45
|
+
.default({}),
|
|
46
|
+
});
|
|
47
|
+
/**
|
|
48
|
+
* The address this bot answers as: `selfId` when given, else the login name.
|
|
49
|
+
* @param config - the validated adapter configuration.
|
|
50
|
+
* @returns the bot's own address.
|
|
51
|
+
*/
|
|
52
|
+
export function addressOf(config) {
|
|
53
|
+
return config.selfId || config.username;
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,CAAC,MAAM,0BAA0B,CAAA;AA4CxC,4CAA4C;AAC5C,MAAM,CAAC,MAAM,MAAM,GAAc,CAAC,CAAC,MAAM,CAAC;IACxC,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC/B,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,QAAQ,EAAE;IAC9C,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE;IAClB,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;IAChB,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC;IACrC,OA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