@theokit/gateway-discord 0.2.1 → 0.4.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 +60 -0
- package/dist/index.cjs +64 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -1
- package/dist/index.d.ts +26 -1
- package/dist/index.js +66 -7
- package/dist/index.js.map +1 -1
- package/package.json +19 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,65 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 05e7fdd: Edit a message an adapter sent, so a reply can stream as a preview that the final text replaces.
|
|
8
|
+
|
|
9
|
+
`BasePlatformAdapter` gains `supportsEdit` (`false` by default) and
|
|
10
|
+
`editMessage(messageId, out)`, whose default refuses with `edit_unsupported`, makes no platform
|
|
11
|
+
call and never throws. A third-party subclass that already declares a member with either name and
|
|
12
|
+
a different type no longer compiles against this release, and under `noImplicitOverride` one
|
|
13
|
+
that declares it without `override` does not either.
|
|
14
|
+
|
|
15
|
+
Telegram (`editMessageText`), Discord (one REST `PATCH` of the message, without fetching the
|
|
16
|
+
channel), Slack (`chat.update`), Mattermost (`patchPost`), Matrix (an `m.replace` event) and Teams
|
|
17
|
+
(`updateActivity`, or `activities(conversationId).update` on `@microsoft/teams.api` below 2.0.14)
|
|
18
|
+
set `supportsEdit` to `true` and replace the text of a message they sent, honouring `format` as
|
|
19
|
+
`sendMessage` does (Slack's `chat.update` takes no `mrkdwn` argument, so its edit sends the text
|
|
20
|
+
as it is for every format), and return `{ ok: true, messageId }` with the same id. E-mail, SMS, LINE and
|
|
21
|
+
WhatsApp keep the default.
|
|
22
|
+
|
|
23
|
+
An edit is refused with no request as `edit_too_long` when the text would need more than one
|
|
24
|
+
platform message (Matrix has no length check), as `invalid_message_id` for an empty id (and on
|
|
25
|
+
Telegram one that is not a safe positive integer), and as `empty_text` and `not_connected` where
|
|
26
|
+
`sendMessage` answers those. Telegram answers its "message is not modified" refusal as a success.
|
|
27
|
+
On Discord an unknown channel is answered by the platform, as `discord_10003`. On Matrix a
|
|
28
|
+
`#alias` the adapter never resolved costs one lookup before the edit. Teams and Matrix do not
|
|
29
|
+
retry a refused markup as plain text on an edit, as they do on a send.
|
|
30
|
+
|
|
31
|
+
The six adapters keep `>=0.9.0` as their peer range on `@theokit/gateway` in this release. At run
|
|
32
|
+
time they work against any core in that range, since no adapter calls the base `editMessage`. Their
|
|
33
|
+
sources declare both members with `override`, so building them against a core older than this one
|
|
34
|
+
reports TS4113. The floor rises to this core in the next release, once it is on npm
|
|
35
|
+
(`docs/adr/0008-edit-capable-adapters-raise-their-core-floor-after-the-core-ships.md`). A
|
|
36
|
+
consumer's own typecheck reads the published declarations, which carry no `override`, and passes
|
|
37
|
+
on an older core.
|
|
38
|
+
|
|
39
|
+
### Patch Changes
|
|
40
|
+
|
|
41
|
+
- 13117af: A `plain` text full of markup characters no longer goes out as a message longer than the
|
|
42
|
+
platform allows. The text was split on its own length and escaped afterwards, and escaping can
|
|
43
|
+
double a part, so 995 copies of `*a` went to Discord as one 2985-character message and came back
|
|
44
|
+
`discord_50035`, and 8000 copies went to Mattermost as one 24000-character post and came back
|
|
45
|
+
`invalid_request`. A part whose escaped body passes the cap is now split again at half the cap.
|
|
46
|
+
`editMessage` sends the same parts, so on both platforms an edit is refused as `edit_too_long`
|
|
47
|
+
for exactly the texts a send delivers as more than one message.
|
|
48
|
+
|
|
49
|
+
## 0.3.0
|
|
50
|
+
|
|
51
|
+
### Minor Changes
|
|
52
|
+
|
|
53
|
+
- 70ce856: Export `splitForDiscord` from the package entry.
|
|
54
|
+
|
|
55
|
+
Seven of the eight packages that ship a splitter already re-exported it; `gateway-discord` was
|
|
56
|
+
the one that did not, which made Discord the only platform whose splitter an outside caller
|
|
57
|
+
could not reach. That matters now rather than as tidiness: B-019 puts the channel presenter
|
|
58
|
+
OUTSIDE these packages and forbids it from splitting, so a caller that must not re-split has to
|
|
59
|
+
be able to call the one the adapter already uses.
|
|
60
|
+
|
|
61
|
+
Additive — no existing export changes.
|
|
62
|
+
|
|
3
63
|
## 0.2.1
|
|
4
64
|
|
|
5
65
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -6,13 +6,23 @@ var discord_js = require('discord.js');
|
|
|
6
6
|
// src/adapter.ts
|
|
7
7
|
var DISCORD_MAX_MESSAGE = 2e3;
|
|
8
8
|
var SAFE_DISCORD_CHUNK = 1900;
|
|
9
|
+
var BOUNDARIES = {
|
|
10
|
+
boundaries: ["\n\n", "\n"],
|
|
11
|
+
lastResort: "window",
|
|
12
|
+
stripLeading: /^\n+/
|
|
13
|
+
};
|
|
9
14
|
function splitForDiscord(text) {
|
|
10
15
|
return gateway.chunkText(text, {
|
|
11
16
|
limit: DISCORD_MAX_MESSAGE,
|
|
12
17
|
safeLimit: SAFE_DISCORD_CHUNK,
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
18
|
+
...BOUNDARIES
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
function splitForEscapedDiscord(text) {
|
|
22
|
+
return gateway.chunkText(text, {
|
|
23
|
+
limit: DISCORD_MAX_MESSAGE / 2,
|
|
24
|
+
safeLimit: SAFE_DISCORD_CHUNK / 2,
|
|
25
|
+
...BOUNDARIES
|
|
16
26
|
});
|
|
17
27
|
}
|
|
18
28
|
|
|
@@ -104,7 +114,7 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
104
114
|
}
|
|
105
115
|
};
|
|
106
116
|
}
|
|
107
|
-
const chunks =
|
|
117
|
+
const chunks = renderMessages(out);
|
|
108
118
|
let lastId;
|
|
109
119
|
for (const chunk of chunks) {
|
|
110
120
|
try {
|
|
@@ -119,6 +129,36 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
119
129
|
}
|
|
120
130
|
return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
|
|
121
131
|
}
|
|
132
|
+
/** Discord edits a sent message's text with one REST call. */
|
|
133
|
+
supportsEdit = true;
|
|
134
|
+
/**
|
|
135
|
+
* Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.
|
|
136
|
+
*
|
|
137
|
+
* That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`
|
|
138
|
+
* without fetching the channel first, so a success is one request whatever the channel cache
|
|
139
|
+
* holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split
|
|
140
|
+
* and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would
|
|
141
|
+
* deliver as more than one message is refused as `edit_too_long` with no request.
|
|
142
|
+
*/
|
|
143
|
+
async editMessage(messageId, out) {
|
|
144
|
+
if (out.text.length === 0) {
|
|
145
|
+
return { ok: false, error: { code: "empty_text", message: "text is empty" } };
|
|
146
|
+
}
|
|
147
|
+
if (messageId.length === 0) {
|
|
148
|
+
return { ok: false, error: { code: "invalid_message_id", message: "message id is empty" } };
|
|
149
|
+
}
|
|
150
|
+
const messages = renderMessages(out);
|
|
151
|
+
if (messages.length !== 1) return editPartsRefusal(messages.length);
|
|
152
|
+
const content = messages[0];
|
|
153
|
+
try {
|
|
154
|
+
await this.client.rest.patch(discord_js.Routes.channelMessage(out.channel.id, messageId), {
|
|
155
|
+
body: { content }
|
|
156
|
+
});
|
|
157
|
+
} catch (err) {
|
|
158
|
+
return mapSendError(err);
|
|
159
|
+
}
|
|
160
|
+
return { ok: true, messageId };
|
|
161
|
+
}
|
|
122
162
|
onInbound(handler) {
|
|
123
163
|
this.handler = handler;
|
|
124
164
|
return () => {
|
|
@@ -200,6 +240,18 @@ function normalizeEvent(msg) {
|
|
|
200
240
|
}
|
|
201
241
|
};
|
|
202
242
|
}
|
|
243
|
+
function editPartsRefusal(partCount) {
|
|
244
|
+
if (partCount > 1) {
|
|
245
|
+
return {
|
|
246
|
+
ok: false,
|
|
247
|
+
error: {
|
|
248
|
+
code: "edit_too_long",
|
|
249
|
+
message: `text needs ${partCount} Discord messages; an edit replaces one`
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
|
|
254
|
+
}
|
|
203
255
|
function mapSendError(err) {
|
|
204
256
|
if (err instanceof discord_js.DiscordAPIError) {
|
|
205
257
|
const codeStr = String(err.code);
|
|
@@ -216,6 +268,13 @@ function mapSendError(err) {
|
|
|
216
268
|
}
|
|
217
269
|
return { ok: false, error: { code: "unknown", message: err.message } };
|
|
218
270
|
}
|
|
271
|
+
function renderMessages(out) {
|
|
272
|
+
return splitForDiscord(out.text).flatMap((part) => {
|
|
273
|
+
const body = bodyFor(out.format, part);
|
|
274
|
+
if (body.length <= DISCORD_MAX_MESSAGE) return [body];
|
|
275
|
+
return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));
|
|
276
|
+
});
|
|
277
|
+
}
|
|
219
278
|
function bodyFor(format, text) {
|
|
220
279
|
return format === "plain" ? escapeMarkdown(text) : text;
|
|
221
280
|
}
|
|
@@ -224,5 +283,6 @@ function escapeMarkdown(text) {
|
|
|
224
283
|
}
|
|
225
284
|
|
|
226
285
|
exports.DiscordAdapter = DiscordAdapter;
|
|
286
|
+
exports.splitForDiscord = splitForDiscord;
|
|
227
287
|
//# sourceMappingURL=index.cjs.map
|
|
228
288
|
//# sourceMappingURL=index.cjs.map
|
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,mBA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AAO,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 * 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 /**\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\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 // Split FIRST, escape each chunk. The other order lets `splitForDiscord`'s hard window cut\n // land between a backslash and the character it guards: message 1 ends in a stray backslash\n // the user never typed, and message 2 opens with a bare `*` that Discord parses as markup.\n // Demonstrated in review against the real splitter.\n const chunks = splitForDiscord(out.text).map((chunk) => bodyFor(out.format, chunk));\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 /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * 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 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\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 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/split.ts","../src/adapter.ts"],"names":["chunkText","GatewayIntentBits","BasePlatformAdapter","Client","Events","Routes","DiscordAPIError"],"mappings":";;;;;;AAeO,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;AAChB,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,CAAA;AAAA,IAC7B,WAAW,kBAAA,GAAqB,CAAA;AAAA,IAChC,GAAG;AAAA,GACJ,CAAA;AACH;;;ACZO,IAAM,uBAAA,GAA4D;AAAA,EACvEC,4BAAA,CAAkB,MAAA;AAAA,EAClBA,4BAAA,CAAkB,aAAA;AAAA,EAClBA,4BAAA,CAAkB,cAAA;AAAA,EAClBA,4BAAA,CAAkB,cAAA;AAAA,EAClBA,4BAAA,CAAkB;AACpB,CAAA;AASO,IAAM,cAAA,GAAN,cAA6BC,2BAAA,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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CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","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\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} 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 Routes,\n} from \"discord.js\";\n\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\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 = 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 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 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 /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * 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 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
|
@@ -57,6 +57,18 @@ declare class DiscordAdapter extends BasePlatformAdapter {
|
|
|
57
57
|
*/
|
|
58
58
|
getBot(): Client;
|
|
59
59
|
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
60
|
+
/** Discord edits a sent message's text with one REST call. */
|
|
61
|
+
readonly supportsEdit = true;
|
|
62
|
+
/**
|
|
63
|
+
* Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.
|
|
64
|
+
*
|
|
65
|
+
* That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`
|
|
66
|
+
* without fetching the channel first, so a success is one request whatever the channel cache
|
|
67
|
+
* holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split
|
|
68
|
+
* and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would
|
|
69
|
+
* deliver as more than one message is refused as `edit_too_long` with no request.
|
|
70
|
+
*/
|
|
71
|
+
editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
|
|
60
72
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
61
73
|
private handleInbound;
|
|
62
74
|
/**
|
|
@@ -68,4 +80,17 @@ declare class DiscordAdapter extends BasePlatformAdapter {
|
|
|
68
80
|
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
69
81
|
}
|
|
70
82
|
|
|
71
|
-
|
|
83
|
+
/**
|
|
84
|
+
* Split `text` into chunks Discord accepts as separate messages.
|
|
85
|
+
*
|
|
86
|
+
* Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers
|
|
87
|
+
* a blank line, then a newline, inside a 1900-character window, and falls back
|
|
88
|
+
* to the window edge when the text has neither.
|
|
89
|
+
*
|
|
90
|
+
* @param text - The full outbound reply.
|
|
91
|
+
* @returns The chunks in order; sending them one after another reproduces `text`
|
|
92
|
+
* minus the leading newlines stripped at each cut.
|
|
93
|
+
*/
|
|
94
|
+
declare function splitForDiscord(text: string): string[];
|
|
95
|
+
|
|
96
|
+
export { DiscordAdapter, type DiscordAdapterOptions, splitForDiscord };
|
package/dist/index.d.ts
CHANGED
|
@@ -57,6 +57,18 @@ declare class DiscordAdapter extends BasePlatformAdapter {
|
|
|
57
57
|
*/
|
|
58
58
|
getBot(): Client;
|
|
59
59
|
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
60
|
+
/** Discord edits a sent message's text with one REST call. */
|
|
61
|
+
readonly supportsEdit = true;
|
|
62
|
+
/**
|
|
63
|
+
* Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.
|
|
64
|
+
*
|
|
65
|
+
* That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`
|
|
66
|
+
* without fetching the channel first, so a success is one request whatever the channel cache
|
|
67
|
+
* holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split
|
|
68
|
+
* and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would
|
|
69
|
+
* deliver as more than one message is refused as `edit_too_long` with no request.
|
|
70
|
+
*/
|
|
71
|
+
editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
|
|
60
72
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
61
73
|
private handleInbound;
|
|
62
74
|
/**
|
|
@@ -68,4 +80,17 @@ declare class DiscordAdapter extends BasePlatformAdapter {
|
|
|
68
80
|
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
69
81
|
}
|
|
70
82
|
|
|
71
|
-
|
|
83
|
+
/**
|
|
84
|
+
* Split `text` into chunks Discord accepts as separate messages.
|
|
85
|
+
*
|
|
86
|
+
* Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers
|
|
87
|
+
* a blank line, then a newline, inside a 1900-character window, and falls back
|
|
88
|
+
* to the window edge when the text has neither.
|
|
89
|
+
*
|
|
90
|
+
* @param text - The full outbound reply.
|
|
91
|
+
* @returns The chunks in order; sending them one after another reproduces `text`
|
|
92
|
+
* minus the leading newlines stripped at each cut.
|
|
93
|
+
*/
|
|
94
|
+
declare function splitForDiscord(text: string): string[];
|
|
95
|
+
|
|
96
|
+
export { DiscordAdapter, type DiscordAdapterOptions, splitForDiscord };
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,26 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { GatewayIntentBits, Client, Events, DiscordAPIError } from 'discord.js';
|
|
1
|
+
import { chunkText, BasePlatformAdapter } from '@theokit/gateway';
|
|
2
|
+
import { GatewayIntentBits, Client, Events, Routes, DiscordAPIError } from 'discord.js';
|
|
3
3
|
|
|
4
4
|
// src/adapter.ts
|
|
5
5
|
var DISCORD_MAX_MESSAGE = 2e3;
|
|
6
6
|
var SAFE_DISCORD_CHUNK = 1900;
|
|
7
|
+
var BOUNDARIES = {
|
|
8
|
+
boundaries: ["\n\n", "\n"],
|
|
9
|
+
lastResort: "window",
|
|
10
|
+
stripLeading: /^\n+/
|
|
11
|
+
};
|
|
7
12
|
function splitForDiscord(text) {
|
|
8
13
|
return chunkText(text, {
|
|
9
14
|
limit: DISCORD_MAX_MESSAGE,
|
|
10
15
|
safeLimit: SAFE_DISCORD_CHUNK,
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
16
|
+
...BOUNDARIES
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
function splitForEscapedDiscord(text) {
|
|
20
|
+
return chunkText(text, {
|
|
21
|
+
limit: DISCORD_MAX_MESSAGE / 2,
|
|
22
|
+
safeLimit: SAFE_DISCORD_CHUNK / 2,
|
|
23
|
+
...BOUNDARIES
|
|
14
24
|
});
|
|
15
25
|
}
|
|
16
26
|
|
|
@@ -102,7 +112,7 @@ var DiscordAdapter = class extends BasePlatformAdapter {
|
|
|
102
112
|
}
|
|
103
113
|
};
|
|
104
114
|
}
|
|
105
|
-
const chunks =
|
|
115
|
+
const chunks = renderMessages(out);
|
|
106
116
|
let lastId;
|
|
107
117
|
for (const chunk of chunks) {
|
|
108
118
|
try {
|
|
@@ -117,6 +127,36 @@ var DiscordAdapter = class extends BasePlatformAdapter {
|
|
|
117
127
|
}
|
|
118
128
|
return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
|
|
119
129
|
}
|
|
130
|
+
/** Discord edits a sent message's text with one REST call. */
|
|
131
|
+
supportsEdit = true;
|
|
132
|
+
/**
|
|
133
|
+
* Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.
|
|
134
|
+
*
|
|
135
|
+
* That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`
|
|
136
|
+
* without fetching the channel first, so a success is one request whatever the channel cache
|
|
137
|
+
* holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split
|
|
138
|
+
* and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would
|
|
139
|
+
* deliver as more than one message is refused as `edit_too_long` with no request.
|
|
140
|
+
*/
|
|
141
|
+
async editMessage(messageId, out) {
|
|
142
|
+
if (out.text.length === 0) {
|
|
143
|
+
return { ok: false, error: { code: "empty_text", message: "text is empty" } };
|
|
144
|
+
}
|
|
145
|
+
if (messageId.length === 0) {
|
|
146
|
+
return { ok: false, error: { code: "invalid_message_id", message: "message id is empty" } };
|
|
147
|
+
}
|
|
148
|
+
const messages = renderMessages(out);
|
|
149
|
+
if (messages.length !== 1) return editPartsRefusal(messages.length);
|
|
150
|
+
const content = messages[0];
|
|
151
|
+
try {
|
|
152
|
+
await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {
|
|
153
|
+
body: { content }
|
|
154
|
+
});
|
|
155
|
+
} catch (err) {
|
|
156
|
+
return mapSendError(err);
|
|
157
|
+
}
|
|
158
|
+
return { ok: true, messageId };
|
|
159
|
+
}
|
|
120
160
|
onInbound(handler) {
|
|
121
161
|
this.handler = handler;
|
|
122
162
|
return () => {
|
|
@@ -198,6 +238,18 @@ function normalizeEvent(msg) {
|
|
|
198
238
|
}
|
|
199
239
|
};
|
|
200
240
|
}
|
|
241
|
+
function editPartsRefusal(partCount) {
|
|
242
|
+
if (partCount > 1) {
|
|
243
|
+
return {
|
|
244
|
+
ok: false,
|
|
245
|
+
error: {
|
|
246
|
+
code: "edit_too_long",
|
|
247
|
+
message: `text needs ${partCount} Discord messages; an edit replaces one`
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
|
|
252
|
+
}
|
|
201
253
|
function mapSendError(err) {
|
|
202
254
|
if (err instanceof DiscordAPIError) {
|
|
203
255
|
const codeStr = String(err.code);
|
|
@@ -214,6 +266,13 @@ function mapSendError(err) {
|
|
|
214
266
|
}
|
|
215
267
|
return { ok: false, error: { code: "unknown", message: err.message } };
|
|
216
268
|
}
|
|
269
|
+
function renderMessages(out) {
|
|
270
|
+
return splitForDiscord(out.text).flatMap((part) => {
|
|
271
|
+
const body = bodyFor(out.format, part);
|
|
272
|
+
if (body.length <= DISCORD_MAX_MESSAGE) return [body];
|
|
273
|
+
return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));
|
|
274
|
+
});
|
|
275
|
+
}
|
|
217
276
|
function bodyFor(format, text) {
|
|
218
277
|
return format === "plain" ? escapeMarkdown(text) : text;
|
|
219
278
|
}
|
|
@@ -221,6 +280,6 @@ function escapeMarkdown(text) {
|
|
|
221
280
|
return text.replace(/([\\*_`~])/g, "\\$1");
|
|
222
281
|
}
|
|
223
282
|
|
|
224
|
-
export { DiscordAdapter };
|
|
283
|
+
export { DiscordAdapter, splitForDiscord };
|
|
225
284
|
//# sourceMappingURL=index.js.map
|
|
226
285
|
//# sourceMappingURL=index.js.map
|
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;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;;;ACUO,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;AACl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I,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;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 * 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 /**\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\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 // Split FIRST, escape each chunk. The other order lets `splitForDiscord`'s hard window cut\n // land between a backslash and the character it guards: message 1 ends in a stray backslash\n // the user never typed, and message 2 opens with a bare `*` that Discord parses as markup.\n // Demonstrated in review against the real splitter.\n const chunks = splitForDiscord(out.text).map((chunk) => bodyFor(out.format, chunk));\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 /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * 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 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\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 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/split.ts","../src/adapter.ts"],"names":[],"mappings":";;;;AAeO,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;AAChB,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,GAA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,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 * 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} 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 Routes,\n} from \"discord.js\";\n\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\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 = 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 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 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 /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * 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 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.4.0",
|
|
4
4
|
"description": "Discord (discord.js) platform adapter for @theokit/gateway. ADRs D171, D179.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"types": "./dist/index.d.cts",
|
|
26
26
|
"default": "./dist/index.cjs"
|
|
27
27
|
}
|
|
28
|
-
}
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
29
30
|
},
|
|
30
31
|
"files": [
|
|
31
32
|
"dist",
|
|
@@ -47,12 +48,27 @@
|
|
|
47
48
|
"typescript": "5.9.3",
|
|
48
49
|
"vitest": "^4.1.11",
|
|
49
50
|
"zod": "^4.0.0",
|
|
50
|
-
"@theokit/gateway": "0.
|
|
51
|
+
"@theokit/gateway": "0.12.0"
|
|
51
52
|
},
|
|
52
53
|
"publishConfig": {
|
|
53
54
|
"access": "public",
|
|
54
55
|
"provenance": true
|
|
55
56
|
},
|
|
57
|
+
"sideEffects": false,
|
|
58
|
+
"bugs": {
|
|
59
|
+
"url": "https://github.com/usetheokit/theokit-gateways/issues"
|
|
60
|
+
},
|
|
61
|
+
"homepage": "https://github.com/usetheokit/theokit-gateways/tree/main/packages/gateway-discord#readme",
|
|
62
|
+
"keywords": [
|
|
63
|
+
"theokit",
|
|
64
|
+
"gateway",
|
|
65
|
+
"discord",
|
|
66
|
+
"discord.js",
|
|
67
|
+
"platform",
|
|
68
|
+
"adapter",
|
|
69
|
+
"adrs",
|
|
70
|
+
"d171"
|
|
71
|
+
],
|
|
56
72
|
"scripts": {
|
|
57
73
|
"build": "tsup",
|
|
58
74
|
"typecheck": "tsc --noEmit",
|