@theokit/gateway-discord 0.6.0 → 0.7.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/CHANGELOG.md +6 -0
- package/README.md +4 -0
- package/dist/index.cjs +3 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
package/README.md
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -45,6 +45,9 @@ var DEFAULT_DISCORD_INTENTS = [
|
|
|
45
45
|
discord_js.GatewayIntentBits.DirectMessageReactions
|
|
46
46
|
];
|
|
47
47
|
var DiscordAdapter = class extends gateway.BasePlatformAdapter {
|
|
48
|
+
get capabilities() {
|
|
49
|
+
return { ...super.capabilities, maxMessageChars: DISCORD_MAX_MESSAGE, threads: true };
|
|
50
|
+
}
|
|
48
51
|
platform = "discord";
|
|
49
52
|
client;
|
|
50
53
|
token;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts"],"names":["chunkText","GatewayIntentBits","BasePlatformAdapter","Client","Partials","Events","Routes","DiscordAPIError"],"mappings":";;;;;;;;AAmBO,SAAS,kBAAkB,GAAA,EAA8C;AAC9E,EAAA,IAAI,IAAI,WAAA,IAAe,IAAA,IAAQ,IAAI,WAAA,CAAY,MAAA,KAAW,GAAG,OAAO,MAAA;AACpE,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO,EAAE,IAAA,EAAM,yBAAA,EAA2B,SAAS,yCAAA;AAA0C,GAC/F;AACF;ACVO,IAAM,mBAAA,GAAsB,GAAA;AACnC,IAAM,kBAAA,GAAqB,IAAA;AAC3B,IAAM,UAAA,GAAa;AAAA,EACjB,UAAA,EAAY,CAAC,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tB,MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,cAAA,EAAgB,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAE;AAAA,IAC5E;AACA,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,IAAA,EAAM,CAAA,QAAA,EAAW,OAAO,CAAA,CAAA,EAAI,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAE;AAAA,EAClF;AACA,EAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,SAAA,EAAW,OAAA,EAAU,GAAA,CAAc,OAAA,EAAQ,EAAE;AAClF;AAaA,SAAS,eAAe,GAAA,EAAgC;AACtD,EAAA,OAAO,gBAAgB,GAAA,CAAI,IAAI,CAAA,CAAE,OAAA,CAAQ,CAAC,IAAA,KAAS;AACjD,IAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAA;AACrC,IAAA,IAAI,IAAA,CAAK,MAAA,IAAU,mBAAA,EAAqB,OAAO,CAAC,IAAI,CAAA;AACpD,IAAA,OAAO,sBAAA,CAAuB,IAAI,CAAA,CAAE,GAAA,CAAI,CAAC,SAAS,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAC,CAAA;AAAA,EAC7E,CAAC,CAAA;AACH;AASA,SAAS,OAAA,CAAQ,QAAmC,IAAA,EAAsB;AACxE,EAAA,OAAO,MAAA,KAAW,OAAA,GAAU,cAAA,CAAe,IAAI,CAAA,GAAI,IAAA;AACrD;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.cjs","sourcesContent":["/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"discord adapter cannot send attachments\" },\n };\n}\n","/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nexport const DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into chunks Discord accepts as separate messages.\n *\n * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers\n * a blank line, then a newline, inside a 1900-character window, and falls back\n * to the window edge when the text has neither.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order; sending them one after another reproduces `text`\n * minus the leading newlines stripped at each cut.\n */\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n ...BOUNDARIES,\n });\n}\n\n/**\n * Split a text that is escaped after the split, at half the cap.\n *\n * Escaping adds at most one backslash per character, so a part of at most 1000 characters fits\n * one message once escaped. The adapter calls this only for a part whose escaped body passed the\n * cap, so the parts of an ordinary text are the ones `splitForDiscord` returns.\n */\nexport function splitForEscapedDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE / 2,\n safeLimit: SAFE_DISCORD_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport {\n Client,\n DiscordAPIError,\n Events,\n GatewayIntentBits,\n type Message,\n Partials,\n Routes,\n} from \"discord.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { DISCORD_MAX_MESSAGE, splitForDiscord, splitForEscapedDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n /**\n * Deliver a guild or thread message only when it mentions the bot. Default `true`.\n *\n * A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a\n * reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is\n * not a mention). `@everyone`, `@here` and role mentions do not count. An event with no\n * discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or\n * `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is\n * unknown, so every group message is dropped and one stderr line says why. Pass `false` to\n * deliver every message, as the adapter did before this option existed.\n */\n readonly requireMention?: boolean;\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private readonly requireMention: boolean;\n private warnedMissingBotId = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n this.requireMention = opts.requireMention ?? true;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n // DMs arrive on a channel discord.js has not cached; without the Channel\n // partial it drops their messageCreate, so DMs never reach the agent.\n this.client = new Client({ intents, partials: [Partials.Channel] });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n const chunks = renderMessages(out);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Discord edits a sent message's text with one REST call. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.\n *\n * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`\n * without fetching the channel first, so a success is one request whatever the channel cache\n * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split\n * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would\n * deliver as more than one message is refused as `edit_too_long` with no request.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const messages = renderMessages(out);\n if (messages.length !== 1) return editPartsRefusal(messages.length);\n const content = messages[0] as string;\n try {\n await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {\n body: { content },\n });\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override async react(channelId: string, messageId: string, emoji: string): Promise<SendResult> {\n if (channelId.length === 0 || messageId.length === 0 || emoji.length === 0) {\n return {\n ok: false,\n error: { code: \"invalid_reaction\", message: \"channel, message id and emoji are required\" },\n };\n }\n try {\n await this.client.rest.put(\n Routes.channelMessageOwnReaction(channelId, messageId, encodeURIComponent(emoji)),\n );\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n /** Discord shows \"<bot> is typing\" for 10 s per call; the runner renews it. */\n override async startTyping(channelId: string): Promise<void> {\n if (channelId.length === 0 || !this.connected) return;\n try {\n await this.client.rest.post(Routes.channelTyping(channelId));\n } catch {\n /* cosmetic — swallow */\n }\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n const event = normalizeEvent(msg);\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Whether an event may reach the handler: always for a DM or with `requireMention` off,\n * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call\n * it, so the two entries cannot disagree.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (event.channel.type === \"dm\" || !this.requireMention) return true;\n const botId = this.client.user?.id;\n if (botId === undefined) {\n this.warnMissingBotIdOnce();\n return false;\n }\n const raw = event.platform === \"discord\" ? event.discord.raw : undefined;\n const mentionedUsers = (raw as { mentions?: { users?: { has?: unknown } } } | undefined)\n ?.mentions?.users;\n if (typeof mentionedUsers?.has === \"function\") return mentionedUsers.has(botId) === true;\n // A hand-built event carries no discord.js collection; the mention syntax is the evidence left.\n return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);\n }\n\n private warnMissingBotIdOnce(): void {\n if (this.warnedMissingBotId) return;\n this.warnedMissingBotId = true;\n process.stderr.write(\n \"[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\\n\",\n );\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * The mention gate runs first, as on the socket path: an event it drops answers `\"ok\"`, with or\n * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its\n * throw is named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\n/**\n * The refusal for a text that is not exactly one Discord message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForDiscord`\n * returns at least one part for any non-empty text and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Discord messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The message bodies a text goes out as, each within `DISCORD_MAX_MESSAGE`.\n *\n * Split FIRST, escape each part. The other order lets the splitter's hard window cut land between\n * a backslash and the character it guards: message 1 ends in a stray backslash the user never\n * typed, and message 2 opens with a bare `*` that Discord parses as markup. Demonstrated in review\n * against the real splitter. The splitter measures the caller's text, and escaping a `plain` part\n * can double it, so a part whose body passes the cap is split again at half the cap, which every\n * escaped body fits. `sendMessage` and `editMessage` both send what this returns, so an edit is\n * refused for exactly the texts a send delivers as more than one message.\n */\nfunction renderMessages(out: OutboundMessage): string[] {\n return splitForDiscord(out.text).flatMap((part) => {\n const body = bodyFor(out.format, part);\n if (body.length <= DISCORD_MAX_MESSAGE) return [body];\n return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));\n });\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts"],"names":["chunkText","GatewayIntentBits","BasePlatformAdapter","Client","Partials","Events","Routes","DiscordAPIError"],"mappings":";;;;;;;;AAmBO,SAAS,kBAAkB,GAAA,EAA8C;AAC9E,EAAA,IAAI,IAAI,WAAA,IAAe,IAAA,IAAQ,IAAI,WAAA,CAAY,MAAA,KAAW,GAAG,OAAO,MAAA;AACpE,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO,EAAE,IAAA,EAAM,yBAAA,EAA2B,SAAS,yCAAA;AAA0C,GAC/F;AACF;ACVO,IAAM,mBAAA,GAAsB,GAAA;AACnC,IAAM,kBAAA,GAAqB,IAAA;AAC3B,IAAM,UAAA,GAAa;AAAA,EACjB,UAAA,EAAY,CAAC,MAAA,EAAQ,IAAI,CAAA;AAAA,EACzB,UAAA,EAAY,QAAA;AAAA,EACZ,YAAA,EAAc,MAAA;AAAA,EACd,aAAA,EAAe;AACjB,CAAA;AAaO,SAAS,gBAAgB,IAAA,EAAwB;AACtD,EAAA,OAAOA,kBAAU,IAAA,EAAM;AAAA,IACrB,KAAA,EAAO,mBAAA;AAAA,IACP,SAAA,EAAW,kBAAA;AAAA,IACX,GAAG;AAAA,GACJ,CAAA;AACH;AASO,SAAS,uBAAuB,IAAA,EAAwB;AAC7D,EAAA,OAAOA,kBAAU,IAAA,EAAM;AAAA,IACrB,OAAO,mBAAA,GAAsB,CAA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AAS,GAAA,CAAI,OAAA,EAAQ,EAAE;AAAA,EAClF;AACA,EAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,SAAA,EAAW,OAAA,EAAU,GAAA,CAAc,OAAA,EAAQ,EAAE;AAClF;AAaA,SAAS,eAAe,GAAA,EAAgC;AACtD,EAAA,OAAO,gBAAgB,GAAA,CAAI,IAAI,CAAA,CAAE,OAAA,CAAQ,CAAC,IAAA,KAAS;AACjD,IAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAA;AACrC,IAAA,IAAI,IAAA,CAAK,MAAA,IAAU,mBAAA,EAAqB,OAAO,CAAC,IAAI,CAAA;AACpD,IAAA,OAAO,sBAAA,CAAuB,IAAI,CAAA,CAAE,GAAA,CAAI,CAAC,SAAS,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAC,CAAA;AAAA,EAC7E,CAAC,CAAA;AACH;AASA,SAAS,OAAA,CAAQ,QAAmC,IAAA,EAAsB;AACxE,EAAA,OAAO,MAAA,KAAW,OAAA,GAAU,cAAA,CAAe,IAAI,CAAA,GAAI,IAAA;AACrD;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.cjs","sourcesContent":["/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"discord adapter cannot send attachments\" },\n };\n}\n","/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nexport const DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into chunks Discord accepts as separate messages.\n *\n * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers\n * a blank line, then a newline, inside a 1900-character window, and falls back\n * to the window edge when the text has neither.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order; sending them one after another reproduces `text`\n * minus the leading newlines stripped at each cut.\n */\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n ...BOUNDARIES,\n });\n}\n\n/**\n * Split a text that is escaped after the split, at half the cap.\n *\n * Escaping adds at most one backslash per character, so a part of at most 1000 characters fits\n * one message once escaped. The adapter calls this only for a part whose escaped body passed the\n * cap, so the parts of an ordinary text are the ones `splitForDiscord` returns.\n */\nexport function splitForEscapedDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE / 2,\n safeLimit: SAFE_DISCORD_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport {\n type AdapterCapabilities,\n BasePlatformAdapter,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\nimport {\n Client,\n DiscordAPIError,\n Events,\n GatewayIntentBits,\n type Message,\n Partials,\n Routes,\n} from \"discord.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { DISCORD_MAX_MESSAGE, splitForDiscord, splitForEscapedDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n /**\n * Deliver a guild or thread message only when it mentions the bot. Default `true`.\n *\n * A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a\n * reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is\n * not a mention). `@everyone`, `@here` and role mentions do not count. An event with no\n * discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or\n * `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is\n * unknown, so every group message is dropped and one stderr line says why. Pass `false` to\n * deliver every message, as the adapter did before this option existed.\n */\n readonly requireMention?: boolean;\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n override get capabilities(): AdapterCapabilities {\n return { ...super.capabilities, maxMessageChars: DISCORD_MAX_MESSAGE, threads: true };\n }\n\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private readonly requireMention: boolean;\n private warnedMissingBotId = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n this.requireMention = opts.requireMention ?? true;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n // DMs arrive on a channel discord.js has not cached; without the Channel\n // partial it drops their messageCreate, so DMs never reach the agent.\n this.client = new Client({ intents, partials: [Partials.Channel] });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n const chunks = renderMessages(out);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Discord edits a sent message's text with one REST call. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.\n *\n * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`\n * without fetching the channel first, so a success is one request whatever the channel cache\n * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split\n * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would\n * deliver as more than one message is refused as `edit_too_long` with no request.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const messages = renderMessages(out);\n if (messages.length !== 1) return editPartsRefusal(messages.length);\n const content = messages[0] as string;\n try {\n await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {\n body: { content },\n });\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override async react(channelId: string, messageId: string, emoji: string): Promise<SendResult> {\n if (channelId.length === 0 || messageId.length === 0 || emoji.length === 0) {\n return {\n ok: false,\n error: { code: \"invalid_reaction\", message: \"channel, message id and emoji are required\" },\n };\n }\n try {\n await this.client.rest.put(\n Routes.channelMessageOwnReaction(channelId, messageId, encodeURIComponent(emoji)),\n );\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n /** Discord shows \"<bot> is typing\" for 10 s per call; the runner renews it. */\n override async startTyping(channelId: string): Promise<void> {\n if (channelId.length === 0 || !this.connected) return;\n try {\n await this.client.rest.post(Routes.channelTyping(channelId));\n } catch {\n /* cosmetic — swallow */\n }\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n const event = normalizeEvent(msg);\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Whether an event may reach the handler: always for a DM or with `requireMention` off,\n * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call\n * it, so the two entries cannot disagree.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (event.channel.type === \"dm\" || !this.requireMention) return true;\n const botId = this.client.user?.id;\n if (botId === undefined) {\n this.warnMissingBotIdOnce();\n return false;\n }\n const raw = event.platform === \"discord\" ? event.discord.raw : undefined;\n const mentionedUsers = (raw as { mentions?: { users?: { has?: unknown } } } | undefined)\n ?.mentions?.users;\n if (typeof mentionedUsers?.has === \"function\") return mentionedUsers.has(botId) === true;\n // A hand-built event carries no discord.js collection; the mention syntax is the evidence left.\n return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);\n }\n\n private warnMissingBotIdOnce(): void {\n if (this.warnedMissingBotId) return;\n this.warnedMissingBotId = true;\n process.stderr.write(\n \"[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\\n\",\n );\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * The mention gate runs first, as on the socket path: an event it drops answers `\"ok\"`, with or\n * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its\n * throw is named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\n/**\n * The refusal for a text that is not exactly one Discord message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForDiscord`\n * returns at least one part for any non-empty text and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Discord messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The message bodies a text goes out as, each within `DISCORD_MAX_MESSAGE`.\n *\n * Split FIRST, escape each part. The other order lets the splitter's hard window cut land between\n * a backslash and the character it guards: message 1 ends in a stray backslash the user never\n * typed, and message 2 opens with a bare `*` that Discord parses as markup. Demonstrated in review\n * against the real splitter. The splitter measures the caller's text, and escaping a `plain` part\n * can double it, so a part whose body passes the cap is split again at half the cap, which every\n * escaped body fits. `sendMessage` and `editMessage` both send what this returns, so an edit is\n * refused for exactly the texts a send delivers as more than one message.\n */\nfunction renderMessages(out: OutboundMessage): string[] {\n return splitForDiscord(out.text).flatMap((part) => {\n const body = bodyFor(out.format, part);\n if (body.length <= DISCORD_MAX_MESSAGE) return [body];\n return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));\n });\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
|
|
1
|
+
import { BasePlatformAdapter, AdapterCapabilities, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
|
|
2
2
|
import { GatewayIntentBits, Client } from 'discord.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -50,6 +50,7 @@ interface DiscordAdapterOptions {
|
|
|
50
50
|
* empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.
|
|
51
51
|
*/
|
|
52
52
|
declare class DiscordAdapter extends BasePlatformAdapter {
|
|
53
|
+
get capabilities(): AdapterCapabilities;
|
|
53
54
|
readonly platform: "discord";
|
|
54
55
|
private readonly client;
|
|
55
56
|
private readonly token;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
|
|
1
|
+
import { BasePlatformAdapter, AdapterCapabilities, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
|
|
2
2
|
import { GatewayIntentBits, Client } from 'discord.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -50,6 +50,7 @@ interface DiscordAdapterOptions {
|
|
|
50
50
|
* empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.
|
|
51
51
|
*/
|
|
52
52
|
declare class DiscordAdapter extends BasePlatformAdapter {
|
|
53
|
+
get capabilities(): AdapterCapabilities;
|
|
53
54
|
readonly platform: "discord";
|
|
54
55
|
private readonly client;
|
|
55
56
|
private readonly token;
|
package/dist/index.js
CHANGED
|
@@ -43,6 +43,9 @@ var DEFAULT_DISCORD_INTENTS = [
|
|
|
43
43
|
GatewayIntentBits.DirectMessageReactions
|
|
44
44
|
];
|
|
45
45
|
var DiscordAdapter = class extends BasePlatformAdapter {
|
|
46
|
+
get capabilities() {
|
|
47
|
+
return { ...super.capabilities, maxMessageChars: DISCORD_MAX_MESSAGE, threads: true };
|
|
48
|
+
}
|
|
46
49
|
platform = "discord";
|
|
47
50
|
client;
|
|
48
51
|
token;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts"],"names":[],"mappings":";;;;;;AAmBO,SAAS,kBAAkB,GAAA,EAA8C;AAC9E,EAAA,IAAI,IAAI,WAAA,IAAe,IAAA,IAAQ,IAAI,WAAA,CAAY,MAAA,KAAW,GAAG,OAAO,MAAA;AACpE,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO,EAAE,IAAA,EAAM,yBAAA,EAA2B,SAAS,yCAAA;AAA0C,GAC/F;AACF;ACVO,IAAM,mBAAA,GAAsB,GAAA;AACnC,IAAM,kBAAA,GAAqB,IAAA;AAC3B,IAAM,UAAA,GAAa;AAAA,EACjB,UAAA,EAAY,CAAC,MAAA,EAAQ,IAAI,CAAA;AAAA,EACzB,UAAA,EAAY,QAAA;AAAA,EACZ,YAAA,EAAc,MAAA;AAAA,EACd,aAAA,EAAe;AACjB,CAAA;AAaO,SAAS,gBAAgB,IAAA,EAAwB;AACtD,EAAA,OAAO,UAAU,IAAA,EAAM;AAAA,IACrB,KAAA,EAAO,mBAAA;AAAA,IACP,SAAA,EAAW,kBAAA;AAAA,IACX,GAAG;AAAA,GACJ,CAAA;AACH;AASO,SAAS,uBAAuB,IAAA,EAAwB;AAC7D,EAAA,OAAO,UAAU,IAAA,EAAM;AAAA,IACrB,OAAO,mBAAA,GAAsB,CAAA;AAAA,IAC7B,WAAW,kBAAA,GAAqB,CAAA;AAAA,IAChC,GA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AA,OAAO,gBAAgB,GAAA,CAAI,IAAI,CAAA,CAAE,OAAA,CAAQ,CAAC,IAAA,KAAS;AACjD,IAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAA;AACrC,IAAA,IAAI,IAAA,CAAK,MAAA,IAAU,mBAAA,EAAqB,OAAO,CAAC,IAAI,CAAA;AACpD,IAAA,OAAO,sBAAA,CAAuB,IAAI,CAAA,CAAE,GAAA,CAAI,CAAC,SAAS,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAC,CAAA;AAAA,EAC7E,CAAC,CAAA;AACH;AASA,SAAS,OAAA,CAAQ,QAAmC,IAAA,EAAsB;AACxE,EAAA,OAAO,MAAA,KAAW,OAAA,GAAU,cAAA,CAAe,IAAI,CAAA,GAAI,IAAA;AACrD;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.js","sourcesContent":["/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"discord adapter cannot send attachments\" },\n };\n}\n","/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nexport const DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into chunks Discord accepts as separate messages.\n *\n * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers\n * a blank line, then a newline, inside a 1900-character window, and falls back\n * to the window edge when the text has neither.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order; sending them one after another reproduces `text`\n * minus the leading newlines stripped at each cut.\n */\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n ...BOUNDARIES,\n });\n}\n\n/**\n * Split a text that is escaped after the split, at half the cap.\n *\n * Escaping adds at most one backslash per character, so a part of at most 1000 characters fits\n * one message once escaped. The adapter calls this only for a part whose escaped body passed the\n * cap, so the parts of an ordinary text are the ones `splitForDiscord` returns.\n */\nexport function splitForEscapedDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE / 2,\n safeLimit: SAFE_DISCORD_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport {\n Client,\n DiscordAPIError,\n Events,\n GatewayIntentBits,\n type Message,\n Partials,\n Routes,\n} from \"discord.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { DISCORD_MAX_MESSAGE, splitForDiscord, splitForEscapedDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n /**\n * Deliver a guild or thread message only when it mentions the bot. Default `true`.\n *\n * A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a\n * reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is\n * not a mention). `@everyone`, `@here` and role mentions do not count. An event with no\n * discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or\n * `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is\n * unknown, so every group message is dropped and one stderr line says why. Pass `false` to\n * deliver every message, as the adapter did before this option existed.\n */\n readonly requireMention?: boolean;\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private readonly requireMention: boolean;\n private warnedMissingBotId = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n this.requireMention = opts.requireMention ?? true;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n // DMs arrive on a channel discord.js has not cached; without the Channel\n // partial it drops their messageCreate, so DMs never reach the agent.\n this.client = new Client({ intents, partials: [Partials.Channel] });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n const chunks = renderMessages(out);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Discord edits a sent message's text with one REST call. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.\n *\n * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`\n * without fetching the channel first, so a success is one request whatever the channel cache\n * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split\n * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would\n * deliver as more than one message is refused as `edit_too_long` with no request.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const messages = renderMessages(out);\n if (messages.length !== 1) return editPartsRefusal(messages.length);\n const content = messages[0] as string;\n try {\n await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {\n body: { content },\n });\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override async react(channelId: string, messageId: string, emoji: string): Promise<SendResult> {\n if (channelId.length === 0 || messageId.length === 0 || emoji.length === 0) {\n return {\n ok: false,\n error: { code: \"invalid_reaction\", message: \"channel, message id and emoji are required\" },\n };\n }\n try {\n await this.client.rest.put(\n Routes.channelMessageOwnReaction(channelId, messageId, encodeURIComponent(emoji)),\n );\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n /** Discord shows \"<bot> is typing\" for 10 s per call; the runner renews it. */\n override async startTyping(channelId: string): Promise<void> {\n if (channelId.length === 0 || !this.connected) return;\n try {\n await this.client.rest.post(Routes.channelTyping(channelId));\n } catch {\n /* cosmetic — swallow */\n }\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n const event = normalizeEvent(msg);\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Whether an event may reach the handler: always for a DM or with `requireMention` off,\n * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call\n * it, so the two entries cannot disagree.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (event.channel.type === \"dm\" || !this.requireMention) return true;\n const botId = this.client.user?.id;\n if (botId === undefined) {\n this.warnMissingBotIdOnce();\n return false;\n }\n const raw = event.platform === \"discord\" ? event.discord.raw : undefined;\n const mentionedUsers = (raw as { mentions?: { users?: { has?: unknown } } } | undefined)\n ?.mentions?.users;\n if (typeof mentionedUsers?.has === \"function\") return mentionedUsers.has(botId) === true;\n // A hand-built event carries no discord.js collection; the mention syntax is the evidence left.\n return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);\n }\n\n private warnMissingBotIdOnce(): void {\n if (this.warnedMissingBotId) return;\n this.warnedMissingBotId = true;\n process.stderr.write(\n \"[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\\n\",\n );\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * The mention gate runs first, as on the socket path: an event it drops answers `\"ok\"`, with or\n * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its\n * throw is named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\n/**\n * The refusal for a text that is not exactly one Discord message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForDiscord`\n * returns at least one part for any non-empty text and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Discord messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The message bodies a text goes out as, each within `DISCORD_MAX_MESSAGE`.\n *\n * Split FIRST, escape each part. The other order lets the splitter's hard window cut land between\n * a backslash and the character it guards: message 1 ends in a stray backslash the user never\n * typed, and message 2 opens with a bare `*` that Discord parses as markup. Demonstrated in review\n * against the real splitter. The splitter measures the caller's text, and escaping a `plain` part\n * can double it, so a part whose body passes the cap is split again at half the cap, which every\n * escaped body fits. `sendMessage` and `editMessage` both send what this returns, so an edit is\n * refused for exactly the texts a send delivers as more than one message.\n */\nfunction renderMessages(out: OutboundMessage): string[] {\n return splitForDiscord(out.text).flatMap((part) => {\n const body = bodyFor(out.format, part);\n if (body.length <= DISCORD_MAX_MESSAGE) return [body];\n return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));\n });\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts"],"names":[],"mappings":";;;;;;AAmBO,SAAS,kBAAkB,GAAA,EAA8C;AAC9E,EAAA,IAAI,IAAI,WAAA,IAAe,IAAA,IAAQ,IAAI,WAAA,CAAY,MAAA,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AC,CAAA;AAAA,EAC7E,CAAC,CAAA;AACH;AASA,SAAS,OAAA,CAAQ,QAAmC,IAAA,EAAsB;AACxE,EAAA,OAAO,MAAA,KAAW,OAAA,GAAU,cAAA,CAAe,IAAI,CAAA,GAAI,IAAA;AACrD;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.js","sourcesContent":["/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"discord adapter cannot send attachments\" },\n };\n}\n","/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nexport const DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into chunks Discord accepts as separate messages.\n *\n * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers\n * a blank line, then a newline, inside a 1900-character window, and falls back\n * to the window edge when the text has neither.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order; sending them one after another reproduces `text`\n * minus the leading newlines stripped at each cut.\n */\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n ...BOUNDARIES,\n });\n}\n\n/**\n * Split a text that is escaped after the split, at half the cap.\n *\n * Escaping adds at most one backslash per character, so a part of at most 1000 characters fits\n * one message once escaped. The adapter calls this only for a part whose escaped body passed the\n * cap, so the parts of an ordinary text are the ones `splitForDiscord` returns.\n */\nexport function splitForEscapedDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE / 2,\n safeLimit: SAFE_DISCORD_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport {\n type AdapterCapabilities,\n BasePlatformAdapter,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\nimport {\n Client,\n DiscordAPIError,\n Events,\n GatewayIntentBits,\n type Message,\n Partials,\n Routes,\n} from \"discord.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { DISCORD_MAX_MESSAGE, splitForDiscord, splitForEscapedDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n /**\n * Deliver a guild or thread message only when it mentions the bot. Default `true`.\n *\n * A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a\n * reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is\n * not a mention). `@everyone`, `@here` and role mentions do not count. An event with no\n * discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or\n * `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is\n * unknown, so every group message is dropped and one stderr line says why. Pass `false` to\n * deliver every message, as the adapter did before this option existed.\n */\n readonly requireMention?: boolean;\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n override get capabilities(): AdapterCapabilities {\n return { ...super.capabilities, maxMessageChars: DISCORD_MAX_MESSAGE, threads: true };\n }\n\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private readonly requireMention: boolean;\n private warnedMissingBotId = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n this.requireMention = opts.requireMention ?? true;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n // DMs arrive on a channel discord.js has not cached; without the Channel\n // partial it drops their messageCreate, so DMs never reach the agent.\n this.client = new Client({ intents, partials: [Partials.Channel] });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n const chunks = renderMessages(out);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Discord edits a sent message's text with one REST call. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.\n *\n * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`\n * without fetching the channel first, so a success is one request whatever the channel cache\n * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split\n * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would\n * deliver as more than one message is refused as `edit_too_long` with no request.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const messages = renderMessages(out);\n if (messages.length !== 1) return editPartsRefusal(messages.length);\n const content = messages[0] as string;\n try {\n await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {\n body: { content },\n });\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override async react(channelId: string, messageId: string, emoji: string): Promise<SendResult> {\n if (channelId.length === 0 || messageId.length === 0 || emoji.length === 0) {\n return {\n ok: false,\n error: { code: \"invalid_reaction\", message: \"channel, message id and emoji are required\" },\n };\n }\n try {\n await this.client.rest.put(\n Routes.channelMessageOwnReaction(channelId, messageId, encodeURIComponent(emoji)),\n );\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n /** Discord shows \"<bot> is typing\" for 10 s per call; the runner renews it. */\n override async startTyping(channelId: string): Promise<void> {\n if (channelId.length === 0 || !this.connected) return;\n try {\n await this.client.rest.post(Routes.channelTyping(channelId));\n } catch {\n /* cosmetic — swallow */\n }\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n const event = normalizeEvent(msg);\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Whether an event may reach the handler: always for a DM or with `requireMention` off,\n * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call\n * it, so the two entries cannot disagree.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (event.channel.type === \"dm\" || !this.requireMention) return true;\n const botId = this.client.user?.id;\n if (botId === undefined) {\n this.warnMissingBotIdOnce();\n return false;\n }\n const raw = event.platform === \"discord\" ? event.discord.raw : undefined;\n const mentionedUsers = (raw as { mentions?: { users?: { has?: unknown } } } | undefined)\n ?.mentions?.users;\n if (typeof mentionedUsers?.has === \"function\") return mentionedUsers.has(botId) === true;\n // A hand-built event carries no discord.js collection; the mention syntax is the evidence left.\n return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);\n }\n\n private warnMissingBotIdOnce(): void {\n if (this.warnedMissingBotId) return;\n this.warnedMissingBotId = true;\n process.stderr.write(\n \"[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\\n\",\n );\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * The mention gate runs first, as on the socket path: an event it drops answers `\"ok\"`, with or\n * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its\n * throw is named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\n/**\n * The refusal for a text that is not exactly one Discord message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForDiscord`\n * returns at least one part for any non-empty text and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Discord messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The message bodies a text goes out as, each within `DISCORD_MAX_MESSAGE`.\n *\n * Split FIRST, escape each part. The other order lets the splitter's hard window cut land between\n * a backslash and the character it guards: message 1 ends in a stray backslash the user never\n * typed, and message 2 opens with a bare `*` that Discord parses as markup. Demonstrated in review\n * against the real splitter. The splitter measures the caller's text, and escaping a `plain` part\n * can double it, so a part whose body passes the cap is split again at half the cap, which every\n * escaped body fits. `sendMessage` and `editMessage` both send what this returns, so an edit is\n * refused for exactly the texts a send delivers as more than one message.\n */\nfunction renderMessages(out: OutboundMessage): string[] {\n return splitForDiscord(out.text).flatMap((part) => {\n const body = bodyFor(out.format, part);\n if (body.length <= DISCORD_MAX_MESSAGE) return [body];\n return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));\n });\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway-discord",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Discord (discord.js) platform adapter for @theokit/gateway. ADRs D171, D179.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"typescript": "5.9.3",
|
|
49
49
|
"vitest": "^4.1.11",
|
|
50
50
|
"zod": "^4.0.0",
|
|
51
|
-
"@theokit/gateway": "0.
|
|
51
|
+
"@theokit/gateway": "0.19.0"
|
|
52
52
|
},
|
|
53
53
|
"publishConfig": {
|
|
54
54
|
"access": "public",
|