@theokit/gateway-discord 0.1.2 → 0.1.3
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 +48 -0
- package/dist/index.cjs +8 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/package.json +13 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,53 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- e682180: **A message whose handler throws no longer kills the bot.** On Teams and on WhatsApp's web backend it did — not degraded delivery, an exit code. `Error: ... / Node.js v22.22.2`, and the next message never arrived.
|
|
8
|
+
|
|
9
|
+
Both dispatched with `void handler(event)`. `void` reads as "I am not waiting for this"; what it tells the runtime is "I am not handling the error", and under Node 22's default an unhandled rejection ends the process. Measured against both adapters through their own injection seams before the fix, and again after: the throw is now contained, named, and delivery continues.
|
|
10
|
+
|
|
11
|
+
**Discord and Telegram contained it but blamed the wrong thing.** The rejection escaped into the platform library's error channel, so a bug in the consumer's own handler surfaced as `[discord] client error` / `[telegram] bot error`. Anyone debugging that went looking in discord.js and grammy for a fault that was in their own code. Both now report `handler threw` and return `"handler_threw"` from the internal dispatch seam.
|
|
12
|
+
|
|
13
|
+
**WhatsApp Cloud dropped the rest of the batch, and made the platform resend it.** Meta packs several messages and their delivery receipts into one webhook, and the dispatch loop awaited each handler with nothing around it. One throw skipped every remaining message in the payload, skipped the status receipts, and rejected `handleWebhookPayload` — so the caller's route answered 500 and Meta redelivered the whole batch, replaying the messages that had already been handled. That is a duplicate-reply bug reached through a different door than the one fixed in #11. The same method also now answers `false` on a signed body that is not JSON, instead of throwing out of a method whose contract is `true`/`false`.
|
|
14
|
+
|
|
15
|
+
**Email gained a net it did not strictly need.** Its drain is written never to reject, and it does not — but both launch sites discard the promise, so that property was the only thing between a future edit and the same fatal rejection, and nothing enforced it. The catch now lives at the site that would pay for it.
|
|
16
|
+
|
|
17
|
+
**The contract is written down, and held to.** `BasePlatformAdapter.onInbound` now states it: a handler may throw, and an adapter must contain that throw, report it as the handler's failure rather than the platform's, and keep delivering. Eight of ten adapters had converged on exactly that with nothing recording it. `tests/lint/adapter-contract.test.ts` gains two invariants — every adapter names a handler throw as the handler's, and no adapter launches a user callback with a bare `void` — and both were checked against a deliberately reverted adapter to confirm they fire rather than pass vacuously.
|
|
18
|
+
|
|
19
|
+
- 8cbf136: **Every published export now carries documentation.** Forty-seven public symbols shipped with no docblock at all, so a consumer hovering `DiscordAdapter`, `SlackAdapter`, `WhatsAppCloudBackend`, `ThreadStore` or any of the error classes got an empty tooltip. Coverage across the eleven packages went from 71.2% to 100% (163/163), measured over the published declarations rather than the source, because a docblock is not documentation until it survives the build.
|
|
20
|
+
|
|
21
|
+
The text says what each symbol is for and what constrains it, not what its name already says. `TelegramAdapter` records that a bot cannot enumerate its chats nor speak into one that has not spoken first. `DiscordAdapter` records that reading message content needs a privileged intent enabled in the developer portal, without which every `event.text` arrives empty and nothing says why. `WhatsAppWebBackend` records that it is unofficial and can get a number banned. `shouldDispatchSyncEvent` records that Matrix replays history on sync, which is why a freshly started bot would otherwise answer every message it can still see.
|
|
22
|
+
|
|
23
|
+
**`gateway-slack`'s README documented a type that does not exist.** Its usage example imported `GatewayMessageEvent` from `@theokit/gateway`. That name is an internal alias inside the Discord and Telegram adapters (`MessageEvent as GatewayMessageEvent`), never an export. A reader who copied the example got code that did not compile. It now imports `MessageEvent`, which is what `onInbound` actually hands the handler.
|
|
24
|
+
|
|
25
|
+
Two docblocks that attached to nothing were reattached: `acquirePidLock` in `gateway-whatsapp` had its documentation stranded thirty lines above, over a different function, and shipped undocumented as a result.
|
|
26
|
+
|
|
27
|
+
- b8ef098: **Every package now ships the licence it declares.** All twelve manifests in this repository declare `Apache-2.0`, and the repository had no `LICENSE` file at all — not at the root, and not in any package directory except `gateway-email`. So each published tarball asserted a licence while carrying none of its terms, and §4(a) of that licence requires a copy to travel with the distribution. Worse than a missing file: with no licence text anywhere, everything outside the manifests fell back to default copyright, which grants a recipient nothing.
|
|
28
|
+
|
|
29
|
+
The text is now at the repository root and inside every publishable package, byte-identical to the canonical Apache License 2.0 with the appendix filled in (`Copyright 2026 usetheo.dev`). The one pre-existing copy, in `gateway-email`, was replaced along with the rest: it carried the same truncated paragraph 4(d) found across the ecosystem, dropping "reasonable and customary use" from the NOTICE clause — a modified body under an unmodified SPDX identifier.
|
|
30
|
+
|
|
31
|
+
**The repository moved to the official `usetheokit` organization.** Existing clones and published URLs keep working through GitHub's permanent redirect; the root manifest now declares `Apache-2.0` explicitly rather than leaving the workspace root silent.
|
|
32
|
+
|
|
33
|
+
- 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
|
|
34
|
+
|
|
35
|
+
**LINE — no outbound message was ever delivered.** The adapter called the v9 SDK client with positional arguments while that client takes a single request object, so LINE received an empty request and rejected every send with a 400. Upgrade if you use this adapter at all: nothing it sent reached anyone.
|
|
36
|
+
|
|
37
|
+
**Telegram — the bot froze on long replies.** Any message over 4096 characters that began with an unclosed code span (a stray backtick) put the splitter into an infinite loop, hanging the process until it ran out of memory. Long agent answers now split correctly whatever markdown they contain.
|
|
38
|
+
|
|
39
|
+
**Mattermost — long messages silently vanished.** The adapter never split anything, so any reply over 16,383 characters was rejected by the server and the user simply saw nothing. Long replies are now split into parts Mattermost accepts.
|
|
40
|
+
|
|
41
|
+
**SMS — long messages were rejected from the hundredth part onward.** The `(i/N)` prefix outgrew the space reserved for it, pushing every later part past the provider's limit.
|
|
42
|
+
|
|
43
|
+
**Matrix and LINE — `connect()` reported success with an invalid token.** Both now verify the credential with the server before returning `true`, so a wrong token fails at startup instead of silently receiving nothing forever.
|
|
44
|
+
|
|
45
|
+
**Email and Teams — the bot could go permanently deaf.** Replacing an inbound handler and then disposing of the previous one removed the new handler as well, and the gateway stopped receiving messages with nothing logged.
|
|
46
|
+
|
|
47
|
+
Also: a `pre_inbound` hook that threw put its raw error text into the user's chat, which could expose internal details such as connection strings or tokens. Users now see only which hook failed; the detail goes to the server log, redacted.
|
|
48
|
+
|
|
49
|
+
WhatsApp additionally stops opening a second session when `connect()` is called twice, and its group mention filter no longer treats unrelated digits scattered through a message as a mention of the bot.
|
|
50
|
+
|
|
3
51
|
## 0.1.2
|
|
4
52
|
|
|
5
53
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -146,7 +146,14 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
146
146
|
*/
|
|
147
147
|
async dispatchEvent(event) {
|
|
148
148
|
if (this.handler === void 0) return "no_handler";
|
|
149
|
-
|
|
149
|
+
try {
|
|
150
|
+
await this.handler(event);
|
|
151
|
+
} catch (err) {
|
|
152
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
153
|
+
process.stderr.write(`[discord] handler threw: ${m}
|
|
154
|
+
`);
|
|
155
|
+
return "handler_threw";
|
|
156
|
+
}
|
|
150
157
|
return "ok";
|
|
151
158
|
}
|
|
152
159
|
};
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/split.ts","../src/adapter.ts"],"names":["chunkText","GatewayIntentBits","BasePlatformAdapter","Client","Events","DiscordAPIError"],"mappings":";;;;;;AAeA,IAAM,mBAAA,GAAsB,GAAA;AAC5B,IAAM,kBAAA,GAAqB,IAAA;AAEpB,SAAS,gBAAgB,IAAA,EAAwB;AACtD,EAAA,OAAOA,kBAAU,IAAA,EAAM;AAAA,IACrB,KAAA,EAAO,mBAAA;AAAA,IACP,SAAA,EAAW,kBAAA;AAAA,IACX,UAAA,EAAY,CAAC,MAAA,EAAQ,IAAI,CAAA;AAAA,IACzB,UAAA,EAAY,QAAA;AAAA,IACZ,YAAA,EAAc;AAAA,GACf,CAAA;AAC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AAA,IAAI,GAAA,CAAI,WAAW,GAAA,EAAK;AACtB,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","file":"index.cjs","sourcesContent":["/**\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\nconst DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\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 lastResort: \"window\",\n stripLeading: /^\\n+/,\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 { Client, DiscordAPIError, Events, GatewayIntentBits, type Message } from \"discord.js\";\n\nimport { splitForDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\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\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\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\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\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 this.client = new Client({ intents });\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 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 = splitForDiscord(out.text);\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 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 await this.dispatchEvent(normalizeEvent(msg));\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\"> {\n if (this.handler === undefined) return \"no_handler\";\n await this.handler(event);\n return \"ok\";\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\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"]}
|
|
1
|
+
{"version":3,"sources":["../src/split.ts","../src/adapter.ts"],"names":["chunkText","GatewayIntentBits","BasePlatformAd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AAW,GAAA,CAAI,SAAA;AAAA,MACf,WAAW,GAAA,CAAI,EAAA;AAAA,MACf,GAAA,EAAK;AAAA;AACP,GACF;AACF;AAEA,SAAS,aAAa,GAAA,EAA0B;AAC9C,EAAA,IAAI,eAAeC,0BAAA,EAAiB;AAClC,IAAA,MAAM,OAAA,GAAU,MAAA,CAAO,GAAA,CAAI,IAAI,CAAA;AAC/B,IAAA,IAAI,YAAY,OAAA,EAAS;AACvB,MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,YAAA,EAAc,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAE;AAAA,IAC1E;AACA,IAAA,IAAI,OAAA,KAAY,OAAA,IAAW,OAAA,KAAY,OAAA,EAAS;AAC9C,MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,eAAA,EAAiB,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAE;AAAA,IAC7E;AACA,IAAA,IAAI,GAAA,CAAI,WAAW,GAAA,EAAK;AACtB,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","file":"index.cjs","sourcesContent":["/**\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\nconst DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\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 lastResort: \"window\",\n stripLeading: /^\\n+/,\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 { Client, DiscordAPIError, Events, GatewayIntentBits, type Message } from \"discord.js\";\n\nimport { splitForDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\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\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\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\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 this.client = new Client({ intents });\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 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 = splitForDiscord(out.text);\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 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 await this.dispatchEvent(normalizeEvent(msg));\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\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\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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -23,6 +23,13 @@ interface DiscordAdapterOptions {
|
|
|
23
23
|
*/
|
|
24
24
|
readonly intents?: GatewayIntentBits[];
|
|
25
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.
|
|
28
|
+
*
|
|
29
|
+
* Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in
|
|
30
|
+
* the Discord developer portal as well as requested here; without it every `event.text` arrives
|
|
31
|
+
* empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.
|
|
32
|
+
*/
|
|
26
33
|
declare class DiscordAdapter extends BasePlatformAdapter {
|
|
27
34
|
readonly platform: "discord";
|
|
28
35
|
private readonly client;
|
package/dist/index.d.ts
CHANGED
|
@@ -23,6 +23,13 @@ interface DiscordAdapterOptions {
|
|
|
23
23
|
*/
|
|
24
24
|
readonly intents?: GatewayIntentBits[];
|
|
25
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.
|
|
28
|
+
*
|
|
29
|
+
* Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in
|
|
30
|
+
* the Discord developer portal as well as requested here; without it every `event.text` arrives
|
|
31
|
+
* empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.
|
|
32
|
+
*/
|
|
26
33
|
declare class DiscordAdapter extends BasePlatformAdapter {
|
|
27
34
|
readonly platform: "discord";
|
|
28
35
|
private readonly client;
|
package/dist/index.js
CHANGED
|
@@ -144,7 +144,14 @@ var DiscordAdapter = class extends BasePlatformAdapter {
|
|
|
144
144
|
*/
|
|
145
145
|
async dispatchEvent(event) {
|
|
146
146
|
if (this.handler === void 0) return "no_handler";
|
|
147
|
-
|
|
147
|
+
try {
|
|
148
|
+
await this.handler(event);
|
|
149
|
+
} catch (err) {
|
|
150
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
151
|
+
process.stderr.write(`[discord] handler threw: ${m}
|
|
152
|
+
`);
|
|
153
|
+
return "handler_threw";
|
|
154
|
+
}
|
|
148
155
|
return "ok";
|
|
149
156
|
}
|
|
150
157
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/split.ts","../src/adapter.ts"],"names":[],"mappings":";;;;AAeA,IAAM,mBAAA,GAAsB,GAAA;AA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,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAE;AAAA,IAC1E;AACA,IAAA,IAAI,OAAA,KAAY,OAAA,IAAW,OAAA,KAAY,OAAA,EAAS;AAC9C,MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,eAAA,EAAiB,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAE;AAAA,IAC7E;AACA,IAAA,IAAI,GAAA,CAAI,WAAW,GAAA,EAAK;AACtB,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","file":"index.js","sourcesContent":["/**\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\nconst DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\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 lastResort: \"window\",\n stripLeading: /^\\n+/,\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 { Client, DiscordAPIError, Events, GatewayIntentBits, type Message } from \"discord.js\";\n\nimport { splitForDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\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\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\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\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\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 this.client = new Client({ intents });\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 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 = splitForDiscord(out.text);\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 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 await this.dispatchEvent(normalizeEvent(msg));\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\"> {\n if (this.handler === undefined) return \"no_handler\";\n await this.handler(event);\n return \"ok\";\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\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"]}
|
|
1
|
+
{"version":3,"sources":["../src/split.ts","../src/adapter.ts"],"names":[],"mappings":";;;;AAeA,IAAM,mBAAA,GAAsB,GAAA;AAC5B,IAAM,kBAAA,GAAqB,IAAA;AAEpB,SAAS,gBAAgB,IAAA,EAAwB;AACtD,EAAA,OAAO,UAAU,IAAA,EAAM;AAAA,IACrB,KAAA,EAAO,mBAAA;AAAA,IACP,SAAA,EAAW,kBAAA;AAAA,IACX,UAAA,EAAY,CAAC,MAAA,EAAQ,IAAI,CAAA;AAAA,IACzB,UAAA,EAAY,QAAA;AAAA,IACZ,YAAA,EAAc;AAAA,GACf,CAAA;AACH;;;ACGO,IAAM,uBAAA,GAA4D;AAAA,EACvE,iBAAA,CAAkB,MAAA;AAAA,EAClB,iBAAA,CAAkB,aAAA;AAAA,EAClB,iBAAA,CAAkB,cAAA;AAAA,EAClB,iBAAA,CAAkB,cAAA;AAAA,EAClB,iBAAA,CAAkB;AACpB,CAAA;AASO,IAAM,cAAA,GAAN,cAA6B,mBAAA,CAAoB;AAAA,EAC7C,QAAA,GAAW,SAAA;AAAA,EACH,MAAA;AAAA,EACA,KAAA;AAAA,EACT,OAAA;AAAA,EACA,SAAA,GAAY,KAAA;AAAA,EAEpB,YAAY,IAAA,EAA6B;AACvC,IAAA,KAAA,EAAM;AACN,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,MAAM,OAAA,GAAW,KAAK,OAAA,IAAW,uBAAA;AACjC,IAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AACxB,MAAA,OAAA,CAAQ,MAAA,CAAO,KAAA;AAAA,QACb;AAAA,OACF;AAAA,IACF;AACA,IAAA,I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KAAA,EAAO,EAAE,MAAM,SAAA,EAAW,OAAA,EAAU,GAAA,CAAc,OAAA,EAAQ,EAAE;AAClF","file":"index.js","sourcesContent":["/**\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\nconst DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\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 lastResort: \"window\",\n stripLeading: /^\\n+/,\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 { Client, DiscordAPIError, Events, GatewayIntentBits, type Message } from \"discord.js\";\n\nimport { splitForDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\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\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\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\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 this.client = new Client({ intents });\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 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 = splitForDiscord(out.text);\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 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 await this.dispatchEvent(normalizeEvent(msg));\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\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\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"]}
|
package/package.json
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway-discord",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Discord (discord.js) platform adapter for @theokit/gateway. ADRs D171, D179.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/usetheokit/theokit-gateways.git",
|
|
9
|
+
"directory": "packages/gateway-discord"
|
|
10
|
+
},
|
|
6
11
|
"type": "module",
|
|
7
12
|
"engines": {
|
|
8
13
|
"node": ">=22.12.0"
|
|
@@ -29,9 +34,9 @@
|
|
|
29
34
|
"CHANGELOG.md"
|
|
30
35
|
],
|
|
31
36
|
"peerDependencies": {
|
|
37
|
+
"@theokit/gateway": ">=0.6.0 <1.0.0",
|
|
32
38
|
"@theokit/sdk": "^2.18.0",
|
|
33
|
-
"discord.js": "^14.16.0"
|
|
34
|
-
"@theokit/gateway": "^0.5.1"
|
|
39
|
+
"discord.js": "^14.16.0"
|
|
35
40
|
},
|
|
36
41
|
"devDependencies": {
|
|
37
42
|
"@theokit/sdk": "^2.18.0",
|
|
@@ -40,7 +45,11 @@
|
|
|
40
45
|
"typescript": "^5.8.0",
|
|
41
46
|
"vitest": "^4.1.8",
|
|
42
47
|
"zod": "^4.0.0",
|
|
43
|
-
"@theokit/gateway": "0.
|
|
48
|
+
"@theokit/gateway": "0.6.0"
|
|
49
|
+
},
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public",
|
|
52
|
+
"provenance": true
|
|
44
53
|
},
|
|
45
54
|
"scripts": {
|
|
46
55
|
"build": "tsup",
|