@theokit/gateway-mattermost 0.2.1 → 0.3.1

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 CHANGED
@@ -1,5 +1,80 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
8
+
9
+ `@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
10
+ `filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
11
+ carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
12
+ `supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
13
+ field. The runner and the router refuse an outbound carrying attachments as
14
+ `attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
15
+ `supportsAttachments`.
16
+
17
+ `@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
18
+ `sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
19
+ when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
20
+ than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
21
+
22
+ Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
23
+ with `attachments_unsupported` and makes no platform call, instead of sending the text and
24
+ dropping the image.
25
+
26
+ The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
27
+ throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
28
+ as a handler error is. Dispatch still does not throw.
29
+
30
+ - 17c0713: Keep Markdown table rows whole when Discord, Slack, Teams, Telegram, WhatsApp and Mattermost split a long reply. A cut that fell inside a table row now moves back to the start of that row when the row fits in a part, so each row reaches the platform byte-identical. `chunkText` gains the opt-in `keepTableRows` option; text with no table row splits into the same chunks as before.
31
+
32
+ ## 0.3.0
33
+
34
+ ### Minor Changes
35
+
36
+ - 05e7fdd: Edit a message an adapter sent, so a reply can stream as a preview that the final text replaces.
37
+
38
+ `BasePlatformAdapter` gains `supportsEdit` (`false` by default) and
39
+ `editMessage(messageId, out)`, whose default refuses with `edit_unsupported`, makes no platform
40
+ call and never throws. A third-party subclass that already declares a member with either name and
41
+ a different type no longer compiles against this release, and under `noImplicitOverride` one
42
+ that declares it without `override` does not either.
43
+
44
+ Telegram (`editMessageText`), Discord (one REST `PATCH` of the message, without fetching the
45
+ channel), Slack (`chat.update`), Mattermost (`patchPost`), Matrix (an `m.replace` event) and Teams
46
+ (`updateActivity`, or `activities(conversationId).update` on `@microsoft/teams.api` below 2.0.14)
47
+ set `supportsEdit` to `true` and replace the text of a message they sent, honouring `format` as
48
+ `sendMessage` does (Slack's `chat.update` takes no `mrkdwn` argument, so its edit sends the text
49
+ as it is for every format), and return `{ ok: true, messageId }` with the same id. E-mail, SMS, LINE and
50
+ WhatsApp keep the default.
51
+
52
+ An edit is refused with no request as `edit_too_long` when the text would need more than one
53
+ platform message (Matrix has no length check), as `invalid_message_id` for an empty id (and on
54
+ Telegram one that is not a safe positive integer), and as `empty_text` and `not_connected` where
55
+ `sendMessage` answers those. Telegram answers its "message is not modified" refusal as a success.
56
+ On Discord an unknown channel is answered by the platform, as `discord_10003`. On Matrix a
57
+ `#alias` the adapter never resolved costs one lookup before the edit. Teams and Matrix do not
58
+ retry a refused markup as plain text on an edit, as they do on a send.
59
+
60
+ The six adapters keep `>=0.9.0` as their peer range on `@theokit/gateway` in this release. At run
61
+ time they work against any core in that range, since no adapter calls the base `editMessage`. Their
62
+ sources declare both members with `override`, so building them against a core older than this one
63
+ reports TS4113. The floor rises to this core in the next release, once it is on npm
64
+ (`docs/adr/0008-edit-capable-adapters-raise-their-core-floor-after-the-core-ships.md`). A
65
+ consumer's own typecheck reads the published declarations, which carry no `override`, and passes
66
+ on an older core.
67
+
68
+ ### Patch Changes
69
+
70
+ - 13117af: A `plain` text full of markup characters no longer goes out as a message longer than the
71
+ platform allows. The text was split on its own length and escaped afterwards, and escaping can
72
+ double a part, so 995 copies of `*a` went to Discord as one 2985-character message and came back
73
+ `discord_50035`, and 8000 copies went to Mattermost as one 24000-character post and came back
74
+ `invalid_request`. A part whose escaped body passes the cap is now split again at half the cap.
75
+ `editMessage` sends the same parts, so on both platforms an edit is refused as `edit_too_long`
76
+ for exactly the texts a send delivers as more than one message.
77
+
3
78
  ## 0.2.1
4
79
 
5
80
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -23,7 +23,10 @@ var SDKNotInstalledError = class extends ConfigurationError {
23
23
  async function loadMattermost() {
24
24
  try {
25
25
  const mod = await import('@mattermost/client');
26
- return mod;
26
+ return {
27
+ Client4: mod.Client4 ?? mod.default?.Client4,
28
+ WebSocketClient: mod.WebSocketClient ?? mod.default?.WebSocketClient
29
+ };
27
30
  } catch {
28
31
  throw new SDKNotInstalledError("@mattermost/client");
29
32
  }
@@ -122,15 +125,34 @@ function postToMessageEvent(post, channel, senderUsername) {
122
125
  }
123
126
  };
124
127
  }
128
+
129
+ // src/refuse-attachments.ts
130
+ function refuseAttachments(out) {
131
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
132
+ return {
133
+ ok: false,
134
+ error: {
135
+ code: "attachments_unsupported",
136
+ message: "mattermost adapter cannot send attachments"
137
+ }
138
+ };
139
+ }
125
140
  var MATTERMOST_MAX_POST = 16383;
126
141
  var SAFE_CHUNK = 16e3;
142
+ var BOUNDARIES = {
143
+ boundaries: ["\n\n", "\n", " "],
144
+ lastResort: "last-boundary",
145
+ stripLeading: /^\s+/,
146
+ keepTableRows: true
147
+ };
127
148
  function splitForMattermost(text) {
149
+ return gateway.chunkText(text, { limit: MATTERMOST_MAX_POST, safeLimit: SAFE_CHUNK, ...BOUNDARIES });
150
+ }
151
+ function splitForEscapedMattermost(text) {
128
152
  return gateway.chunkText(text, {
129
- limit: MATTERMOST_MAX_POST,
130
- safeLimit: SAFE_CHUNK,
131
- boundaries: ["\n\n", "\n", " "],
132
- lastResort: "last-boundary",
133
- stripLeading: /^\s+/
153
+ limit: Math.floor(MATTERMOST_MAX_POST / 2),
154
+ safeLimit: SAFE_CHUNK / 2,
155
+ ...BOUNDARIES
134
156
  });
135
157
  }
136
158
 
@@ -187,6 +209,9 @@ var MattermostAdapter = class extends gateway.BasePlatformAdapter {
187
209
  this.inboundHandler = void 0;
188
210
  }
189
211
  async sendMessage(out) {
212
+ return refuseAttachments(out) ?? this.sendText(out);
213
+ }
214
+ async sendText(out) {
190
215
  if (out.text.length === 0) {
191
216
  return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
192
217
  }
@@ -198,11 +223,10 @@ var MattermostAdapter = class extends gateway.BasePlatformAdapter {
198
223
  }
199
224
  try {
200
225
  let lastId;
201
- for (const raw of splitForMattermost(out.text)) {
202
- const chunk = out.format === "plain" ? escapeMarkdown(raw) : raw;
226
+ for (const message of renderPosts(out)) {
203
227
  const post = await this.handle.client.createPost({
204
228
  channel_id: out.channel.id,
205
- message: chunk,
229
+ message,
206
230
  ...out.channel.type === "thread" && out.channel.topicId !== void 0 ? { root_id: out.channel.topicId } : {}
207
231
  });
208
232
  lastId = post.id;
@@ -212,6 +236,41 @@ var MattermostAdapter = class extends gateway.BasePlatformAdapter {
212
236
  return mapMattermostError(err);
213
237
  }
214
238
  }
239
+ /** Mattermost edits a sent post's text through `Client4.patchPost`. */
240
+ supportsEdit = true;
241
+ /**
242
+ * Replace the text of a post this bot sent, through `patchPost({ id, message })`.
243
+ *
244
+ * Applies `sendMessage`'s checks (`empty_text`, then `not_connected`), refuses an empty id, and
245
+ * refuses as `edit_too_long` a text the shared `renderPosts` turns into more than one post, all
246
+ * with no request, so an edit is refused for exactly the texts a send delivers as several posts.
247
+ */
248
+ async editMessage(messageId, out) {
249
+ return refuseAttachments(out) ?? this.editText(messageId, out);
250
+ }
251
+ async editText(messageId, out) {
252
+ if (out.text.length === 0) {
253
+ return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
254
+ }
255
+ if (this.handle === void 0) {
256
+ return {
257
+ ok: false,
258
+ error: { code: "not_connected", message: "MattermostAdapter.connect() not called" }
259
+ };
260
+ }
261
+ if (messageId.length === 0) {
262
+ return { ok: false, error: { code: "invalid_message_id", message: "message id is empty" } };
263
+ }
264
+ const posts = renderPosts(out);
265
+ if (posts.length !== 1) return editPartsRefusal(posts.length);
266
+ const message = posts[0];
267
+ try {
268
+ await this.handle.client.patchPost({ id: messageId, message });
269
+ } catch (err) {
270
+ return mapMattermostError(err);
271
+ }
272
+ return { ok: true, messageId };
273
+ }
215
274
  onInbound(handler) {
216
275
  this.inboundHandler = handler;
217
276
  return () => {
@@ -269,8 +328,27 @@ var MattermostAdapter = class extends gateway.BasePlatformAdapter {
269
328
  * named as the handler's failure rather than the platform's, and delivery continues.
270
329
  */
271
330
  async deliver(event) {
331
+ if (!this.passesMentionGate(event)) return "ok";
272
332
  return this.runHandler(this.inboundHandler, event);
273
333
  }
334
+ /**
335
+ * The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.
336
+ *
337
+ * Needs the bot identity from a live connection and the raw post on the event; when either is
338
+ * missing there is nothing to judge by, so the event passes as it did before.
339
+ */
340
+ passesMentionGate(event) {
341
+ const handle = this.handle;
342
+ const mm = event.mattermost;
343
+ if (handle === void 0 || mm?.raw === void 0) return true;
344
+ return shouldRespond({
345
+ post: mm.raw,
346
+ channelType: event.channel.type === "thread" ? "thread" : event.channel.type === "dm" ? "dm" : "group",
347
+ botUserId: handle.botUserId,
348
+ botUsername: handle.botUsername,
349
+ requireMention: this.opts.requireMention ?? true
350
+ });
351
+ }
274
352
  };
275
353
  function parsePostFromWS(msg) {
276
354
  const raw = msg.data?.post;
@@ -293,6 +371,26 @@ function parsePostFromWS(msg) {
293
371
  return void 0;
294
372
  }
295
373
  }
374
+ function editPartsRefusal(partCount) {
375
+ if (partCount > 1) {
376
+ return {
377
+ ok: false,
378
+ error: {
379
+ code: "edit_too_long",
380
+ message: `text needs ${partCount} Mattermost posts; an edit replaces one`
381
+ }
382
+ };
383
+ }
384
+ return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
385
+ }
386
+ function renderPosts(out) {
387
+ if (out.format !== "plain") return splitForMattermost(out.text);
388
+ return splitForMattermost(out.text).flatMap((part) => {
389
+ const escaped = escapeMarkdown(part);
390
+ if (escaped.length <= MATTERMOST_MAX_POST) return [escaped];
391
+ return splitForEscapedMattermost(part).map(escapeMarkdown);
392
+ });
393
+ }
296
394
  function mapMattermostError(err) {
297
395
  const e = err;
298
396
  const status = e.status_code ?? 0;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/filters.ts","../src/normalize.ts","../src/split.ts","../src/adapter.ts"],"names":["GatewayConfigurationError","chunkText","BasePlatformAdapter"],"mappings":";;;;;AAoBO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,sBAAsB,IAAI,CAAA;AAAA,EAClC;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,CAAA,8BAAA,EAAiC,OAAO,CAAA,+BAAA,EAAkC,OAAO,CAAA,CAAA;AAAA,MAC1F,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;;;ACDA,eAAe,cAAA,GAA4C;AACzD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,OAAO,oBAAoB,CAAA;AAC7C,IAAA,OAAO,GAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,qBAAqB,oBAAoB,CAAA;AAAA,EACrD;AACF;AAuBA,eAAsB,kBAAkB,IAAA,EAAuD;AAC7F,EAAA,MAAM,GAAA,GAAM,MAAM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KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,mBAAmB,OAAA,EAAS,CAAA,CAAE,WAAW,6BAAA;AAA8B,KACxF;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO;AAAA,MACL,IAAA,EAAM,aAAA;AAAA,MACN,OAAA,EAAS,EAAE,OAAA,KAAY,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAAA;AACxE,GACF;AACF;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-mattermost`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-mattermost\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-mattermost\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-mattermost: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Wrapper over `@mattermost/client` — lazy import + lifecycle.\n *\n * Owns:\n * - Client4 (REST) for outbound posts + channel/user lookup.\n * - WebSocketClient for real-time `posted` events.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\ninterface Client4Like {\n setUrl(url: string): void;\n setToken(token: string): void;\n getMe(): Promise<{ id: string; username: string }>;\n getChannel(channelId: string): Promise<MattermostChannel>;\n createPost(post: {\n channel_id: string;\n message: string;\n root_id?: string;\n }): Promise<MattermostPost>;\n}\n\ninterface WebSocketClientLike {\n initialize(url: string, token: string): void;\n addMessageListener(listener: (msg: WSMessage) => void): void;\n removeMessageListener(listener: (msg: WSMessage) => void): void;\n close(): void;\n}\n\nexport interface WSMessage {\n readonly event: string;\n readonly data: Record<string, unknown>;\n readonly broadcast?: { readonly channel_id?: string; readonly team_id?: string };\n}\n\ninterface MattermostModule {\n Client4: new () => Client4Like;\n WebSocketClient: new () => WebSocketClientLike;\n}\n\nasync function loadMattermost(): Promise<MattermostModule> {\n try {\n const mod = await import(\"@mattermost/client\");\n return mod as unknown as MattermostModule;\n } catch {\n throw new SDKNotInstalledError(\"@mattermost/client\");\n }\n}\n\nexport interface MattermostClientHandle {\n readonly client: Client4Like;\n readonly ws: WebSocketClientLike;\n readonly botUserId: string;\n readonly botUsername: string;\n /** Channel-id LRU cache (max 200) to avoid extra getChannel calls. */\n readonly channelCache: Map<string, MattermostChannel>;\n}\n\nexport interface ConnectOptions {\n readonly baseUrl: string;\n readonly accessToken: string;\n}\n\n/**\n * Authenticate against a Mattermost server and open the websocket that carries inbound posts.\n *\n * The SDK is loaded lazily, so a project that installs this package without using it never pays for\n * the dependency. Returns the handle every other function here takes — client, websocket and the\n * channel cache, kept together because they share a lifetime.\n */\nexport async function connectMattermost(opts: ConnectOptions): Promise<MattermostClientHandle> {\n const mod = await loadMattermost();\n const client = new mod.Client4();\n client.setUrl(opts.baseUrl);\n client.setToken(opts.accessToken);\n const me = await client.getMe();\n const ws = new mod.WebSocketClient();\n const wsUrl = wsUrlFromBase(opts.baseUrl);\n ws.initialize(wsUrl, opts.accessToken);\n return {\n client,\n ws,\n botUserId: me.id,\n botUsername: me.username,\n channelCache: new Map(),\n };\n}\n\n/**\n * Convert REST base URL to WebSocket URL:\n * `https://x.com` → `wss://x.com/api/v4/websocket`\n * `http://localhost:8065` → `ws://localhost:8065/api/v4/websocket`\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function wsUrlFromBase(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/$/, \"\");\n const wsScheme = trimmed.startsWith(\"https://\") ? \"wss://\" : \"ws://\";\n const hostPart = trimmed.replace(/^https?:\\/\\//, \"\");\n return `${wsScheme}${hostPart}/api/v4/websocket`;\n}\n\n/**\n * Fetch a channel by id, remembering the answer on the handle.\n *\n * Normalising an inbound post needs the channel's type, and a busy channel would otherwise cost one\n * API call per message. Returns `undefined` rather than throwing when the channel cannot be read —\n * a post from a channel the bot cannot see is a normal event, not a failure.\n */\nexport async function getChannelCached(\n handle: MattermostClientHandle,\n channelId: string,\n): Promise<MattermostChannel | undefined> {\n const cached = handle.channelCache.get(channelId);\n if (cached !== undefined) return cached;\n try {\n const channel = await handle.client.getChannel(channelId);\n // LRU cap: drop oldest when full.\n if (handle.channelCache.size >= 200) {\n const firstKey = handle.channelCache.keys().next().value;\n if (firstKey !== undefined) handle.channelCache.delete(firstKey);\n }\n handle.channelCache.set(channelId, channel);\n return channel;\n } catch {\n return undefined;\n }\n}\n","/**\n * Inbound dispatch pipeline (D403, EC-2).\n *\n * Order matters — these checks compose:\n *\n * 1. Loop guard: drop bot's own posts (D275 mirror).\n * 2. DM channels: always respond.\n * 3. `requireMention === false`: respond.\n * 4. **Metadata.mentions** array contains bot user-id → respond (PRIORITY).\n * 5. **Word-boundary text regex** `\\b@${botUsername}\\b` → respond.\n * 6. Else: ignore.\n *\n * EC-2: substring match (`post.message.includes(\"@theo\")`) catches\n * `@theory_dept` and dispatches false-positive. The fix is two-fold:\n * prefer the unambiguous `metadata.mentions` array (API-provided\n * user-ids), and when text fallback is required, use `\\b` boundaries.\n */\n\nimport type { MattermostPost } from \"./types.js\";\n\n/** @knipignore — input shape for `shouldRespond`; useful for callers wrapping the filter pipeline. */\nexport interface ShouldRespondOptions {\n readonly post: MattermostPost;\n readonly channelType: \"dm\" | \"group\" | \"thread\";\n readonly botUserId: string;\n readonly botUsername: string;\n readonly requireMention: boolean;\n}\n\n/**\n * Decide whether the bot should answer a post.\n *\n * Three rules in order: never answer itself (the loop guard), always answer a direct message, and in\n * a channel answer only when mentioned unless `requireMention` is turned off. The mention default\n * is what keeps a bot added to a busy channel from replying to every message in it.\n */\nexport function shouldRespond(opts: ShouldRespondOptions): boolean {\n const { post, channelType, botUserId, botUsername, requireMention } = opts;\n // 1. Loop guard.\n if (post.user_id === botUserId) return false;\n // 2. DM — always.\n if (channelType === \"dm\") return true;\n // 3. Opt-out of mention enforcement.\n if (!requireMention) return true;\n // 4. metadata.mentions takes priority — never ambiguous.\n const mentioned = post.metadata?.mentions?.includes(botUserId) ?? false;\n if (mentioned) return true;\n // 5. Text fallback with word boundary (EC-2).\n if (botUsername.length > 0 && hasMentionWithBoundary(post.message, botUsername)) {\n return true;\n }\n return false;\n}\n\n/**\n * Word-boundary match for `@${botUsername}`. Word boundaries land at\n * `\\b` (start/end of `\\w` regions), so `@theo` at the head of `@theory`\n * does NOT match because `\\b` is between `o` and `r` only when the\n * NEXT char is a non-word char.\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function hasMentionWithBoundary(text: string, botUsername: string): boolean {\n // Escape regex metacharacters in username (Mattermost allows `.`, `_`, `-`).\n const safe = botUsername.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(`(^|[^\\\\w])@${safe}(?![\\\\w.])`, \"u\");\n return re.test(text);\n}\n","/**\n * Inbound normalization: Mattermost Post → MattermostMessageEvent.\n *\n * Channel-type mapping (D402):\n * - `D` (Direct) → `\"dm\"`\n * - `G`/`O`/`P` (Group/Open/Private) → `\"group\"`\n * - Posts with `root_id !== \"\"` → `\"thread\"` with `topicId = root_id` (D399).\n */\n\nimport type { MattermostMessageEvent } from \"@theokit/gateway\";\n\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\nexport function normalizeMattermostType(\n channel: MattermostChannel | undefined,\n): \"D\" | \"G\" | \"O\" | \"P\" | (string & {}) {\n return channel?.type ?? \"O\";\n}\n\n/**\n * Map Mattermost's channel type to the gateway's conversation kind.\n *\n * A post carrying a root id is a threaded reply whatever channel it sits in, so that wins over the\n * channel's own type; `\"D\"` is a direct message, and everything else is treated as a group.\n */\nexport function mapChannelType(rawType: string, hasRootId: boolean): \"dm\" | \"group\" | \"thread\" {\n if (hasRootId) return \"thread\";\n if (rawType === \"D\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn a Mattermost post into a `MattermostMessageEvent`.\n *\n * `channel` and `senderUsername` are optional because both are fetched separately and either can be\n * unavailable; the event is still produced, with the conversation kind falling back to a group.\n */\nexport function postToMessageEvent(\n post: MattermostPost,\n channel: MattermostChannel | undefined,\n senderUsername: string | undefined,\n): MattermostMessageEvent {\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n return {\n id: post.id,\n platform: \"mattermost\",\n sender: {\n id: post.user_id,\n ...(senderUsername !== undefined ? { username: senderUsername } : {}),\n },\n channel: {\n id: post.channel_id,\n type: channelType,\n ...(channelType === \"thread\" ? { topicId: post.root_id } : {}),\n },\n text: post.message,\n receivedAt: post.create_at > 0 ? post.create_at : Date.now(),\n mattermost: {\n postId: post.id,\n channelId: post.channel_id,\n teamId: channel?.team_id ?? \"\",\n ...(post.root_id.length > 0 ? { rootId: post.root_id } : {}),\n channelType: rawType,\n raw: post,\n },\n };\n}\n","/**\n * `splitForMattermost` — segment outbound text to Mattermost's post cap.\n *\n * This package shipped without any splitting at all, alone among the ten\n * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent\n * reply longer than the cap came back:\n *\n * HTTP 400 — \"Post Message property is longer than the maximum permitted length.\"\n *\n * and the user saw nothing. No unit test could catch it, because there was no\n * cap in the code to assert against; it took a real server to answer 400.\n * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,\n * 16384 is refused.\n *\n * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This\n * splits on code points via the core chunker, which is the closest the JS side\n * gets without walking graphemes; a message of astral-plane characters could\n * still exceed the server's count, which is why the window leaves headroom.\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\n/** Mattermost's default `MaxPostSize`, in runes. */\nconst MATTERMOST_MAX_POST = 16_383;\n\n/**\n * Cut inside a smaller window than the cap.\n *\n * The headroom absorbs the gap between how JavaScript counts a string and how\n * the server counts runes. Landing exactly on the limit is the one place this\n * can still fail, and the failure is a 400 the user never sees.\n */\nconst SAFE_CHUNK = 16_000;\n\nexport function splitForMattermost(text: string): string[] {\n return chunkText(text, {\n limit: MATTERMOST_MAX_POST,\n safeLimit: SAFE_CHUNK,\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n stripLeading: /^\\s+/,\n });\n}\n","/**\n * `MattermostAdapter` — implements BasePlatformAdapter over Client4 + WS.\n * ADRs D397-D404.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport {\n type ConnectOptions,\n connectMattermost,\n getChannelCached,\n type MattermostClientHandle,\n type WSMessage,\n} from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { shouldRespond } from \"./filters.js\";\nimport { mapChannelType, normalizeMattermostType, postToMessageEvent } from \"./normalize.js\";\nimport { splitForMattermost } from \"./split.js\";\nimport type { MattermostAdapterOptions, MattermostPost } from \"./types.js\";\n\nexport class MattermostAdapter extends BasePlatformAdapter {\n readonly platform = \"mattermost\" as const;\n private readonly opts: MattermostAdapterOptions;\n private handle: MattermostClientHandle | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private wsListener: ((msg: WSMessage) => void) | undefined;\n private connected = false;\n\n constructor(opts: MattermostAdapterOptions) {\n super();\n if (opts.baseUrl.length === 0) {\n throw new ConfigurationError({\n code: \"base_url_required\",\n message: 'gateway-mattermost: opts.baseUrl is empty (e.g. \"https://mattermost.acme.com\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-mattermost: opts.accessToken is empty (generate one in System Console → Integrations → Bot Accounts)\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n this.handle = await connectMattermost({\n baseUrl: this.opts.baseUrl,\n accessToken: this.opts.accessToken,\n } satisfies ConnectOptions);\n this.attachWsListener();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n if (this.handle !== undefined && this.wsListener !== undefined) {\n this.handle.ws.removeMessageListener(this.wsListener);\n }\n this.handle?.ws.close();\n this.handle = undefined;\n this.wsListener = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n try {\n // Split before sending. This package used to post `out.text` whole, alone\n // among the ten adapters, so anything past Mattermost's 16383-rune cap came\n // back HTTP 400 and the user saw nothing at all.\n let lastId: string | undefined;\n // Mattermost parses markdown natively, so `markdown` needs no flag; `plain` is the\n // case that needs work, because raw text would be parsed anyway.\n // Split first, escape per chunk — the same ordering Discord needs, for the same reason:\n // a cut between a backslash and its character produces a stray backslash in one message\n // and a bare marker in the next.\n for (const raw of splitForMattermost(out.text)) {\n const chunk = out.format === \"plain\" ? escapeMarkdown(raw) : raw;\n const post = await this.handle.client.createPost({\n channel_id: out.channel.id,\n message: chunk,\n ...(out.channel.type === \"thread\" && out.channel.topicId !== undefined\n ? { root_id: out.channel.topicId }\n : {}),\n });\n lastId = post.id;\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n } catch (err) {\n return mapMattermostError(err);\n }\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */\n getClient(): MattermostClientHandle | undefined {\n return this.handle;\n }\n\n private attachWsListener(): void {\n if (this.handle === undefined) return;\n const handle = this.handle;\n this.wsListener = (msg: WSMessage) => {\n if (msg.event !== \"posted\") return;\n void this.processPostedEvent(handle, msg).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] processPostedEvent failed: ${m}\\n`);\n });\n };\n handle.ws.addMessageListener(this.wsListener);\n }\n\n private async processPostedEvent(handle: MattermostClientHandle, msg: WSMessage): Promise<void> {\n const post = parsePostFromWS(msg);\n if (post === undefined) return;\n const channel = await getChannelCached(handle, post.channel_id);\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n const requireMention = this.opts.requireMention ?? true;\n if (\n !shouldRespond({\n post,\n channelType,\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention,\n })\n ) {\n return;\n }\n const senderUsername =\n typeof msg.data.sender_name === \"string\"\n ? (msg.data.sender_name as string).replace(/^@/, \"\")\n : undefined;\n const event = postToMessageEvent(post, channel, senderUsername);\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] handler threw: ${m}\\n`);\n }\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.inboundHandler, event);\n }\n}\n\n/**\n * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.\n *\n * @public — exposed so consumers can drive their own WS listener too.\n */\nexport function parsePostFromWS(msg: WSMessage): MattermostPost | undefined {\n const raw = msg.data?.post;\n if (typeof raw !== \"string\") return undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<MattermostPost>;\n if (\n typeof parsed.id !== \"string\" ||\n typeof parsed.user_id !== \"string\" ||\n typeof parsed.channel_id !== \"string\" ||\n typeof parsed.message !== \"string\"\n ) {\n return undefined;\n }\n return {\n id: parsed.id,\n user_id: parsed.user_id,\n channel_id: parsed.channel_id,\n root_id: typeof parsed.root_id === \"string\" ? parsed.root_id : \"\",\n message: parsed.message,\n create_at: typeof parsed.create_at === \"number\" ? parsed.create_at : 0,\n metadata: parsed.metadata,\n };\n } catch {\n return undefined;\n }\n}\n\ninterface MattermostRestError {\n status_code?: number;\n message?: string;\n}\n\nfunction mapMattermostError(err: unknown): SendResult {\n const e = err as MattermostRestError;\n const status = e.status_code ?? 0;\n if (status === 429) {\n return {\n ok: false,\n error: { code: \"rate_limit\", message: e.message ?? \"Mattermost rate limit\" },\n };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: {\n code: \"permission_denied\",\n message: e.message ?? \"Mattermost auth/permission error\",\n },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Mattermost rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\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/errors.ts","../src/client.ts","../src/filters.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts"],"names":["GatewayConfigurationError","chunkText","BasePlatformAdapter"],"mappings":";;;;;AAoBO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,sBAAsB,IAAI,CAAA;AAAA,EAClC;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,CAAA,8BAAA,EAAiC,OAAO,CAAA,+BAAA,EAAkC,OAAO,CAAA,CAAA;AAAA,M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,MACJ,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,mBAAA;AAAA,QACN,OAAA,EAAS,EAAE,OAAA,IAAW;AAAA;AACxB,KACF;AAAA,EACF;AACA,EAAA,IAAI,WAAW,GAAA,EAAK;AAClB,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,mBAAmB,OAAA,EAAS,CAAA,CAAE,WAAW,6BAAA;AAA8B,KACxF;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO;AAAA,MACL,IAAA,EAAM,aAAA;AAAA,MACN,OAAA,EAAS,EAAE,OAAA,KAAY,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAAA;AACxE,GACF;AACF;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-mattermost`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-mattermost\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-mattermost\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-mattermost: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Wrapper over `@mattermost/client` — lazy import + lifecycle.\n *\n * Owns:\n * - Client4 (REST) for outbound posts + channel/user lookup.\n * - WebSocketClient for real-time `posted` events.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\ninterface Client4Like {\n setUrl(url: string): void;\n setToken(token: string): void;\n getMe(): Promise<{ id: string; username: string }>;\n getChannel(channelId: string): Promise<MattermostChannel>;\n createPost(post: {\n channel_id: string;\n message: string;\n root_id?: string;\n }): Promise<MattermostPost>;\n /** Replace the fields a patch names on an existing post; the adapter's edit sends `message`. */\n patchPost(patch: { id: string; message: string }): Promise<MattermostPost>;\n}\n\ninterface WebSocketClientLike {\n initialize(url: string, token: string): void;\n addMessageListener(listener: (msg: WSMessage) => void): void;\n removeMessageListener(listener: (msg: WSMessage) => void): void;\n close(): void;\n}\n\nexport interface WSMessage {\n readonly event: string;\n readonly data: Record<string, unknown>;\n readonly broadcast?: { readonly channel_id?: string; readonly team_id?: string };\n}\n\ninterface MattermostModule {\n Client4: new () => Client4Like;\n WebSocketClient: new () => WebSocketClientLike;\n}\n\nasync function loadMattermost(): Promise<MattermostModule> {\n try {\n const mod = (await import(\"@mattermost/client\")) as unknown as Partial<MattermostModule> & {\n default?: MattermostModule;\n };\n // Node's CommonJS namespace does not expose the SDK's getter-defined exports.\n return {\n Client4: mod.Client4 ?? mod.default?.Client4,\n WebSocketClient: mod.WebSocketClient ?? mod.default?.WebSocketClient,\n } as MattermostModule;\n } catch {\n throw new SDKNotInstalledError(\"@mattermost/client\");\n }\n}\n\nexport interface MattermostClientHandle {\n readonly client: Client4Like;\n readonly ws: WebSocketClientLike;\n readonly botUserId: string;\n readonly botUsername: string;\n /** Channel-id LRU cache (max 200) to avoid extra getChannel calls. */\n readonly channelCache: Map<string, MattermostChannel>;\n}\n\nexport interface ConnectOptions {\n readonly baseUrl: string;\n readonly accessToken: string;\n}\n\n/**\n * Authenticate against a Mattermost server and open the websocket that carries inbound posts.\n *\n * The SDK is loaded lazily, so a project that installs this package without using it never pays for\n * the dependency. Returns the handle every other function here takes — client, websocket and the\n * channel cache, kept together because they share a lifetime.\n */\nexport async function connectMattermost(opts: ConnectOptions): Promise<MattermostClientHandle> {\n const mod = await loadMattermost();\n const client = new mod.Client4();\n client.setUrl(opts.baseUrl);\n client.setToken(opts.accessToken);\n const me = await client.getMe();\n const ws = new mod.WebSocketClient();\n const wsUrl = wsUrlFromBase(opts.baseUrl);\n ws.initialize(wsUrl, opts.accessToken);\n return {\n client,\n ws,\n botUserId: me.id,\n botUsername: me.username,\n channelCache: new Map(),\n };\n}\n\n/**\n * Convert REST base URL to WebSocket URL:\n * `https://x.com` → `wss://x.com/api/v4/websocket`\n * `http://localhost:8065` → `ws://localhost:8065/api/v4/websocket`\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function wsUrlFromBase(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/$/, \"\");\n const wsScheme = trimmed.startsWith(\"https://\") ? \"wss://\" : \"ws://\";\n const hostPart = trimmed.replace(/^https?:\\/\\//, \"\");\n return `${wsScheme}${hostPart}/api/v4/websocket`;\n}\n\n/**\n * Fetch a channel by id, remembering the answer on the handle.\n *\n * Normalising an inbound post needs the channel's type, and a busy channel would otherwise cost one\n * API call per message. Returns `undefined` rather than throwing when the channel cannot be read —\n * a post from a channel the bot cannot see is a normal event, not a failure.\n */\nexport async function getChannelCached(\n handle: MattermostClientHandle,\n channelId: string,\n): Promise<MattermostChannel | undefined> {\n const cached = handle.channelCache.get(channelId);\n if (cached !== undefined) return cached;\n try {\n const channel = await handle.client.getChannel(channelId);\n // LRU cap: drop oldest when full.\n if (handle.channelCache.size >= 200) {\n const firstKey = handle.channelCache.keys().next().value;\n if (firstKey !== undefined) handle.channelCache.delete(firstKey);\n }\n handle.channelCache.set(channelId, channel);\n return channel;\n } catch {\n return undefined;\n }\n}\n","/**\n * Inbound dispatch pipeline (D403, EC-2).\n *\n * Order matters — these checks compose:\n *\n * 1. Loop guard: drop bot's own posts (D275 mirror).\n * 2. DM channels: always respond.\n * 3. `requireMention === false`: respond.\n * 4. **Metadata.mentions** array contains bot user-id → respond (PRIORITY).\n * 5. **Word-boundary text regex** `\\b@${botUsername}\\b` → respond.\n * 6. Else: ignore.\n *\n * EC-2: substring match (`post.message.includes(\"@theo\")`) catches\n * `@theory_dept` and dispatches false-positive. The fix is two-fold:\n * prefer the unambiguous `metadata.mentions` array (API-provided\n * user-ids), and when text fallback is required, use `\\b` boundaries.\n */\n\nimport type { MattermostPost } from \"./types.js\";\n\n/** @knipignore — input shape for `shouldRespond`; useful for callers wrapping the filter pipeline. */\nexport interface ShouldRespondOptions {\n readonly post: MattermostPost;\n readonly channelType: \"dm\" | \"group\" | \"thread\";\n readonly botUserId: string;\n readonly botUsername: string;\n readonly requireMention: boolean;\n}\n\n/**\n * Decide whether the bot should answer a post.\n *\n * Three rules in order: never answer itself (the loop guard), always answer a direct message, and in\n * a channel answer only when mentioned unless `requireMention` is turned off. The mention default\n * is what keeps a bot added to a busy channel from replying to every message in it.\n */\nexport function shouldRespond(opts: ShouldRespondOptions): boolean {\n const { post, channelType, botUserId, botUsername, requireMention } = opts;\n // 1. Loop guard.\n if (post.user_id === botUserId) return false;\n // 2. DM — always.\n if (channelType === \"dm\") return true;\n // 3. Opt-out of mention enforcement.\n if (!requireMention) return true;\n // 4. metadata.mentions takes priority — never ambiguous.\n const mentioned = post.metadata?.mentions?.includes(botUserId) ?? false;\n if (mentioned) return true;\n // 5. Text fallback with word boundary (EC-2).\n if (botUsername.length > 0 && hasMentionWithBoundary(post.message, botUsername)) {\n return true;\n }\n return false;\n}\n\n/**\n * Word-boundary match for `@${botUsername}`. Word boundaries land at\n * `\\b` (start/end of `\\w` regions), so `@theo` at the head of `@theory`\n * does NOT match because `\\b` is between `o` and `r` only when the\n * NEXT char is a non-word char.\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function hasMentionWithBoundary(text: string, botUsername: string): boolean {\n // Escape regex metacharacters in username (Mattermost allows `.`, `_`, `-`).\n const safe = botUsername.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(`(^|[^\\\\w])@${safe}(?![\\\\w.])`, \"u\");\n return re.test(text);\n}\n","/**\n * Inbound normalization: Mattermost Post → MattermostMessageEvent.\n *\n * Channel-type mapping (D402):\n * - `D` (Direct) → `\"dm\"`\n * - `G`/`O`/`P` (Group/Open/Private) → `\"group\"`\n * - Posts with `root_id !== \"\"` → `\"thread\"` with `topicId = root_id` (D399).\n */\n\nimport type { MattermostMessageEvent } from \"@theokit/gateway\";\n\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\nexport function normalizeMattermostType(\n channel: MattermostChannel | undefined,\n): \"D\" | \"G\" | \"O\" | \"P\" | (string & {}) {\n return channel?.type ?? \"O\";\n}\n\n/**\n * Map Mattermost's channel type to the gateway's conversation kind.\n *\n * A post carrying a root id is a threaded reply whatever channel it sits in, so that wins over the\n * channel's own type; `\"D\"` is a direct message, and everything else is treated as a group.\n */\nexport function mapChannelType(rawType: string, hasRootId: boolean): \"dm\" | \"group\" | \"thread\" {\n if (hasRootId) return \"thread\";\n if (rawType === \"D\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn a Mattermost post into a `MattermostMessageEvent`.\n *\n * `channel` and `senderUsername` are optional because both are fetched separately and either can be\n * unavailable; the event is still produced, with the conversation kind falling back to a group.\n */\nexport function postToMessageEvent(\n post: MattermostPost,\n channel: MattermostChannel | undefined,\n senderUsername: string | undefined,\n): MattermostMessageEvent {\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n return {\n id: post.id,\n platform: \"mattermost\",\n sender: {\n id: post.user_id,\n ...(senderUsername !== undefined ? { username: senderUsername } : {}),\n },\n channel: {\n id: post.channel_id,\n type: channelType,\n ...(channelType === \"thread\" ? { topicId: post.root_id } : {}),\n },\n text: post.message,\n receivedAt: post.create_at > 0 ? post.create_at : Date.now(),\n mattermost: {\n postId: post.id,\n channelId: post.channel_id,\n teamId: channel?.team_id ?? \"\",\n ...(post.root_id.length > 0 ? { rootId: post.root_id } : {}),\n channelType: rawType,\n raw: post,\n },\n };\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: \"mattermost adapter cannot send attachments\",\n },\n };\n}\n","/**\n * `splitForMattermost` — segment outbound text to Mattermost's post cap.\n *\n * This package shipped without any splitting at all, alone among the ten\n * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent\n * reply longer than the cap came back:\n *\n * HTTP 400 — \"Post Message property is longer than the maximum permitted length.\"\n *\n * and the user saw nothing. No unit test could catch it, because there was no\n * cap in the code to assert against; it took a real server to answer 400.\n * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,\n * 16384 is refused.\n *\n * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This\n * splits on code points via the core chunker, which is the closest the JS side\n * gets without walking graphemes; a message of astral-plane characters could\n * still exceed the server's count, which is why the window leaves headroom.\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\n/** Mattermost's default `MaxPostSize`, in runes. */\nexport const MATTERMOST_MAX_POST = 16_383;\n\n/**\n * Cut inside a smaller window than the cap.\n *\n * The headroom absorbs the gap between how JavaScript counts a string and how\n * the server counts runes. Landing exactly on the limit is the one place this\n * can still fail, and the failure is a 400 the user never sees.\n */\nconst SAFE_CHUNK = 16_000;\n\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n stripLeading: /^\\s+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into posts that fit Mattermost's post cap.\n *\n * Each chunk is at most {@link MATTERMOST_MAX_POST} code points, cut inside a\n * 16000-character window at a blank line, a newline or a space, in that order of\n * preference.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order, each with leading whitespace stripped at the cut.\n */\nexport function splitForMattermost(text: string): string[] {\n return chunkText(text, { limit: MATTERMOST_MAX_POST, safeLimit: SAFE_CHUNK, ...BOUNDARIES });\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 8191 characters fits\n * one post once escaped. The adapter calls this only for a part whose escaped body passed the cap,\n * so the parts of an ordinary text are the ones `splitForMattermost` returns.\n */\nexport function splitForEscapedMattermost(text: string): string[] {\n return chunkText(text, {\n limit: Math.floor(MATTERMOST_MAX_POST / 2),\n safeLimit: SAFE_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `MattermostAdapter` — implements BasePlatformAdapter over Client4 + WS.\n * ADRs D397-D404.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport {\n type ConnectOptions,\n connectMattermost,\n getChannelCached,\n type MattermostClientHandle,\n type WSMessage,\n} from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { shouldRespond } from \"./filters.js\";\nimport { mapChannelType, normalizeMattermostType, postToMessageEvent } from \"./normalize.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { MATTERMOST_MAX_POST, splitForEscapedMattermost, splitForMattermost } from \"./split.js\";\nimport type { MattermostAdapterOptions, MattermostPost } from \"./types.js\";\n\nexport class MattermostAdapter extends BasePlatformAdapter {\n readonly platform = \"mattermost\" as const;\n private readonly opts: MattermostAdapterOptions;\n private handle: MattermostClientHandle | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private wsListener: ((msg: WSMessage) => void) | undefined;\n private connected = false;\n\n constructor(opts: MattermostAdapterOptions) {\n super();\n if (opts.baseUrl.length === 0) {\n throw new ConfigurationError({\n code: \"base_url_required\",\n message: 'gateway-mattermost: opts.baseUrl is empty (e.g. \"https://mattermost.acme.com\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-mattermost: opts.accessToken is empty (generate one in System Console → Integrations → Bot Accounts)\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n this.handle = await connectMattermost({\n baseUrl: this.opts.baseUrl,\n accessToken: this.opts.accessToken,\n } satisfies ConnectOptions);\n this.attachWsListener();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n if (this.handle !== undefined && this.wsListener !== undefined) {\n this.handle.ws.removeMessageListener(this.wsListener);\n }\n this.handle?.ws.close();\n this.handle = undefined;\n this.wsListener = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n try {\n // Split before sending. This package used to post `out.text` whole, alone\n // among the ten adapters, so anything past Mattermost's 16383-rune cap came\n // back HTTP 400 and the user saw nothing at all.\n let lastId: string | undefined;\n for (const message of renderPosts(out)) {\n const post = await this.handle.client.createPost({\n channel_id: out.channel.id,\n message,\n ...(out.channel.type === \"thread\" && out.channel.topicId !== undefined\n ? { root_id: out.channel.topicId }\n : {}),\n });\n lastId = post.id;\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n } catch (err) {\n return mapMattermostError(err);\n }\n }\n\n /** Mattermost edits a sent post's text through `Client4.patchPost`. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a post this bot sent, through `patchPost({ id, message })`.\n *\n * Applies `sendMessage`'s checks (`empty_text`, then `not_connected`), refuses an empty id, and\n * refuses as `edit_too_long` a text the shared `renderPosts` turns into more than one post, all\n * with no request, so an edit is refused for exactly the texts a send delivers as several posts.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const posts = renderPosts(out);\n if (posts.length !== 1) return editPartsRefusal(posts.length);\n const message = posts[0] as string;\n try {\n await this.handle.client.patchPost({ id: messageId, message });\n } catch (err) {\n return mapMattermostError(err);\n }\n return { ok: true, messageId };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */\n getClient(): MattermostClientHandle | undefined {\n return this.handle;\n }\n\n private attachWsListener(): void {\n if (this.handle === undefined) return;\n const handle = this.handle;\n this.wsListener = (msg: WSMessage) => {\n if (msg.event !== \"posted\") return;\n void this.processPostedEvent(handle, msg).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] processPostedEvent failed: ${m}\\n`);\n });\n };\n handle.ws.addMessageListener(this.wsListener);\n }\n\n private async processPostedEvent(handle: MattermostClientHandle, msg: WSMessage): Promise<void> {\n const post = parsePostFromWS(msg);\n if (post === undefined) return;\n const channel = await getChannelCached(handle, post.channel_id);\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n const requireMention = this.opts.requireMention ?? true;\n if (\n !shouldRespond({\n post,\n channelType,\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention,\n })\n ) {\n return;\n }\n const senderUsername =\n typeof msg.data.sender_name === \"string\"\n ? (msg.data.sender_name as string).replace(/^@/, \"\")\n : undefined;\n const event = postToMessageEvent(post, channel, senderUsername);\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] handler threw: ${m}\\n`);\n }\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 if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.inboundHandler, event);\n }\n\n /**\n * The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.\n *\n * Needs the bot identity from a live connection and the raw post on the event; when either is\n * missing there is nothing to judge by, so the event passes as it did before.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n const handle = this.handle;\n const mm = (event as { mattermost?: { raw?: MattermostPost } }).mattermost;\n if (handle === undefined || mm?.raw === undefined) return true;\n return shouldRespond({\n post: mm.raw,\n channelType:\n event.channel.type === \"thread\" ? \"thread\" : event.channel.type === \"dm\" ? \"dm\" : \"group\",\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention: this.opts.requireMention ?? true,\n });\n }\n}\n\n/**\n * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.\n *\n * @public — exposed so consumers can drive their own WS listener too.\n */\nexport function parsePostFromWS(msg: WSMessage): MattermostPost | undefined {\n const raw = msg.data?.post;\n if (typeof raw !== \"string\") return undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<MattermostPost>;\n if (\n typeof parsed.id !== \"string\" ||\n typeof parsed.user_id !== \"string\" ||\n typeof parsed.channel_id !== \"string\" ||\n typeof parsed.message !== \"string\"\n ) {\n return undefined;\n }\n return {\n id: parsed.id,\n user_id: parsed.user_id,\n channel_id: parsed.channel_id,\n root_id: typeof parsed.root_id === \"string\" ? parsed.root_id : \"\",\n message: parsed.message,\n create_at: typeof parsed.create_at === \"number\" ? parsed.create_at : 0,\n metadata: parsed.metadata,\n };\n } catch {\n return undefined;\n }\n}\n\ninterface MattermostRestError {\n status_code?: number;\n message?: string;\n}\n\n/**\n * The refusal for a text that is not exactly one Mattermost post.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since\n * `splitForMattermost` returns at least one part for any non-empty text and empty text is refused\n * earlier; the arm 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} Mattermost posts; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\n/**\n * The post bodies a text goes out as, each within `MATTERMOST_MAX_POST`.\n *\n * Mattermost parses markdown natively, so `markdown` needs no flag; `plain` is the case that needs\n * work, because raw text would be parsed anyway. Split first, escape per part, the ordering Discord\n * needs for the same reason: a cut between a backslash and its character produces a stray\n * backslash in one post and a bare marker in the next. The splitter measures the caller's text,\n * and escaping can double a part, so a part whose escaped body passes the cap is split again at\n * half the cap, which every escaped body fits. `sendMessage` and `editMessage` both send what this\n * returns.\n */\nfunction renderPosts(out: OutboundMessage): string[] {\n if (out.format !== \"plain\") return splitForMattermost(out.text);\n return splitForMattermost(out.text).flatMap((part) => {\n const escaped = escapeMarkdown(part);\n if (escaped.length <= MATTERMOST_MAX_POST) return [escaped];\n return splitForEscapedMattermost(part).map(escapeMarkdown);\n });\n}\n\nfunction mapMattermostError(err: unknown): SendResult {\n const e = err as MattermostRestError;\n const status = e.status_code ?? 0;\n if (status === 429) {\n return {\n ok: false,\n error: { code: \"rate_limit\", message: e.message ?? \"Mattermost rate limit\" },\n };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: {\n code: \"permission_denied\",\n message: e.message ?? \"Mattermost auth/permission error\",\n },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Mattermost rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\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
@@ -84,6 +84,11 @@ interface Client4Like {
84
84
  message: string;
85
85
  root_id?: string;
86
86
  }): Promise<MattermostPost>;
87
+ /** Replace the fields a patch names on an existing post; the adapter's edit sends `message`. */
88
+ patchPost(patch: {
89
+ id: string;
90
+ message: string;
91
+ }): Promise<MattermostPost>;
87
92
  }
88
93
  interface WebSocketClientLike {
89
94
  initialize(url: string, token: string): void;
@@ -154,6 +159,18 @@ declare class MattermostAdapter extends BasePlatformAdapter {
154
159
  connect(): Promise<boolean>;
155
160
  disconnect(): Promise<void>;
156
161
  sendMessage(out: OutboundMessage): Promise<SendResult>;
162
+ private sendText;
163
+ /** Mattermost edits a sent post's text through `Client4.patchPost`. */
164
+ readonly supportsEdit = true;
165
+ /**
166
+ * Replace the text of a post this bot sent, through `patchPost({ id, message })`.
167
+ *
168
+ * Applies `sendMessage`'s checks (`empty_text`, then `not_connected`), refuses an empty id, and
169
+ * refuses as `edit_too_long` a text the shared `renderPosts` turns into more than one post, all
170
+ * with no request, so an edit is refused for exactly the texts a send delivers as several posts.
171
+ */
172
+ editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
173
+ private editText;
157
174
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
158
175
  /** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */
159
176
  getClient(): MattermostClientHandle | undefined;
@@ -166,6 +183,13 @@ declare class MattermostAdapter extends BasePlatformAdapter {
166
183
  * named as the handler's failure rather than the platform's, and delivery continues.
167
184
  */
168
185
  deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
186
+ /**
187
+ * The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.
188
+ *
189
+ * Needs the bot identity from a live connection and the raw post on the event; when either is
190
+ * missing there is nothing to judge by, so the event passes as it did before.
191
+ */
192
+ private passesMentionGate;
169
193
  }
170
194
  /**
171
195
  * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.
@@ -276,25 +300,14 @@ declare function mapChannelType(rawType: string, hasRootId: boolean): "dm" | "gr
276
300
  declare function postToMessageEvent(post: MattermostPost, channel: MattermostChannel | undefined, senderUsername: string | undefined): MattermostMessageEvent;
277
301
 
278
302
  /**
279
- * `splitForMattermost` — segment outbound text to Mattermost's post cap.
280
- *
281
- * This package shipped without any splitting at all, alone among the ten
282
- * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent
283
- * reply longer than the cap came back:
284
- *
285
- * HTTP 400 — "Post Message property is longer than the maximum permitted length."
286
- *
287
- * and the user saw nothing. No unit test could catch it, because there was no
288
- * cap in the code to assert against; it took a real server to answer 400.
289
- * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,
290
- * 16384 is refused.
303
+ * Split `text` into posts that fit Mattermost's post cap.
291
304
  *
292
- * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This
293
- * splits on code points via the core chunker, which is the closest the JS side
294
- * gets without walking graphemes; a message of astral-plane characters could
295
- * still exceed the server's count, which is why the window leaves headroom.
305
+ * Each chunk is at most {@link MATTERMOST_MAX_POST} code points, cut inside a
306
+ * 16000-character window at a blank line, a newline or a space, in that order of
307
+ * preference.
296
308
  *
297
- * @internal
309
+ * @param text - The full outbound reply.
310
+ * @returns The chunks in order, each with leading whitespace stripped at the cut.
298
311
  */
299
312
  declare function splitForMattermost(text: string): string[];
300
313
 
package/dist/index.d.ts CHANGED
@@ -84,6 +84,11 @@ interface Client4Like {
84
84
  message: string;
85
85
  root_id?: string;
86
86
  }): Promise<MattermostPost>;
87
+ /** Replace the fields a patch names on an existing post; the adapter's edit sends `message`. */
88
+ patchPost(patch: {
89
+ id: string;
90
+ message: string;
91
+ }): Promise<MattermostPost>;
87
92
  }
88
93
  interface WebSocketClientLike {
89
94
  initialize(url: string, token: string): void;
@@ -154,6 +159,18 @@ declare class MattermostAdapter extends BasePlatformAdapter {
154
159
  connect(): Promise<boolean>;
155
160
  disconnect(): Promise<void>;
156
161
  sendMessage(out: OutboundMessage): Promise<SendResult>;
162
+ private sendText;
163
+ /** Mattermost edits a sent post's text through `Client4.patchPost`. */
164
+ readonly supportsEdit = true;
165
+ /**
166
+ * Replace the text of a post this bot sent, through `patchPost({ id, message })`.
167
+ *
168
+ * Applies `sendMessage`'s checks (`empty_text`, then `not_connected`), refuses an empty id, and
169
+ * refuses as `edit_too_long` a text the shared `renderPosts` turns into more than one post, all
170
+ * with no request, so an edit is refused for exactly the texts a send delivers as several posts.
171
+ */
172
+ editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
173
+ private editText;
157
174
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
158
175
  /** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */
159
176
  getClient(): MattermostClientHandle | undefined;
@@ -166,6 +183,13 @@ declare class MattermostAdapter extends BasePlatformAdapter {
166
183
  * named as the handler's failure rather than the platform's, and delivery continues.
167
184
  */
168
185
  deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
186
+ /**
187
+ * The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.
188
+ *
189
+ * Needs the bot identity from a live connection and the raw post on the event; when either is
190
+ * missing there is nothing to judge by, so the event passes as it did before.
191
+ */
192
+ private passesMentionGate;
169
193
  }
170
194
  /**
171
195
  * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.
@@ -276,25 +300,14 @@ declare function mapChannelType(rawType: string, hasRootId: boolean): "dm" | "gr
276
300
  declare function postToMessageEvent(post: MattermostPost, channel: MattermostChannel | undefined, senderUsername: string | undefined): MattermostMessageEvent;
277
301
 
278
302
  /**
279
- * `splitForMattermost` — segment outbound text to Mattermost's post cap.
280
- *
281
- * This package shipped without any splitting at all, alone among the ten
282
- * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent
283
- * reply longer than the cap came back:
284
- *
285
- * HTTP 400 — "Post Message property is longer than the maximum permitted length."
286
- *
287
- * and the user saw nothing. No unit test could catch it, because there was no
288
- * cap in the code to assert against; it took a real server to answer 400.
289
- * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,
290
- * 16384 is refused.
303
+ * Split `text` into posts that fit Mattermost's post cap.
291
304
  *
292
- * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This
293
- * splits on code points via the core chunker, which is the closest the JS side
294
- * gets without walking graphemes; a message of astral-plane characters could
295
- * still exceed the server's count, which is why the window leaves headroom.
305
+ * Each chunk is at most {@link MATTERMOST_MAX_POST} code points, cut inside a
306
+ * 16000-character window at a blank line, a newline or a space, in that order of
307
+ * preference.
296
308
  *
297
- * @internal
309
+ * @param text - The full outbound reply.
310
+ * @returns The chunks in order, each with leading whitespace stripped at the cut.
298
311
  */
299
312
  declare function splitForMattermost(text: string): string[];
300
313
 
package/dist/index.js CHANGED
@@ -21,7 +21,10 @@ var SDKNotInstalledError = class extends ConfigurationError {
21
21
  async function loadMattermost() {
22
22
  try {
23
23
  const mod = await import('@mattermost/client');
24
- return mod;
24
+ return {
25
+ Client4: mod.Client4 ?? mod.default?.Client4,
26
+ WebSocketClient: mod.WebSocketClient ?? mod.default?.WebSocketClient
27
+ };
25
28
  } catch {
26
29
  throw new SDKNotInstalledError("@mattermost/client");
27
30
  }
@@ -120,15 +123,34 @@ function postToMessageEvent(post, channel, senderUsername) {
120
123
  }
121
124
  };
122
125
  }
126
+
127
+ // src/refuse-attachments.ts
128
+ function refuseAttachments(out) {
129
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
130
+ return {
131
+ ok: false,
132
+ error: {
133
+ code: "attachments_unsupported",
134
+ message: "mattermost adapter cannot send attachments"
135
+ }
136
+ };
137
+ }
123
138
  var MATTERMOST_MAX_POST = 16383;
124
139
  var SAFE_CHUNK = 16e3;
140
+ var BOUNDARIES = {
141
+ boundaries: ["\n\n", "\n", " "],
142
+ lastResort: "last-boundary",
143
+ stripLeading: /^\s+/,
144
+ keepTableRows: true
145
+ };
125
146
  function splitForMattermost(text) {
147
+ return chunkText(text, { limit: MATTERMOST_MAX_POST, safeLimit: SAFE_CHUNK, ...BOUNDARIES });
148
+ }
149
+ function splitForEscapedMattermost(text) {
126
150
  return chunkText(text, {
127
- limit: MATTERMOST_MAX_POST,
128
- safeLimit: SAFE_CHUNK,
129
- boundaries: ["\n\n", "\n", " "],
130
- lastResort: "last-boundary",
131
- stripLeading: /^\s+/
151
+ limit: Math.floor(MATTERMOST_MAX_POST / 2),
152
+ safeLimit: SAFE_CHUNK / 2,
153
+ ...BOUNDARIES
132
154
  });
133
155
  }
134
156
 
@@ -185,6 +207,9 @@ var MattermostAdapter = class extends BasePlatformAdapter {
185
207
  this.inboundHandler = void 0;
186
208
  }
187
209
  async sendMessage(out) {
210
+ return refuseAttachments(out) ?? this.sendText(out);
211
+ }
212
+ async sendText(out) {
188
213
  if (out.text.length === 0) {
189
214
  return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
190
215
  }
@@ -196,11 +221,10 @@ var MattermostAdapter = class extends BasePlatformAdapter {
196
221
  }
197
222
  try {
198
223
  let lastId;
199
- for (const raw of splitForMattermost(out.text)) {
200
- const chunk = out.format === "plain" ? escapeMarkdown(raw) : raw;
224
+ for (const message of renderPosts(out)) {
201
225
  const post = await this.handle.client.createPost({
202
226
  channel_id: out.channel.id,
203
- message: chunk,
227
+ message,
204
228
  ...out.channel.type === "thread" && out.channel.topicId !== void 0 ? { root_id: out.channel.topicId } : {}
205
229
  });
206
230
  lastId = post.id;
@@ -210,6 +234,41 @@ var MattermostAdapter = class extends BasePlatformAdapter {
210
234
  return mapMattermostError(err);
211
235
  }
212
236
  }
237
+ /** Mattermost edits a sent post's text through `Client4.patchPost`. */
238
+ supportsEdit = true;
239
+ /**
240
+ * Replace the text of a post this bot sent, through `patchPost({ id, message })`.
241
+ *
242
+ * Applies `sendMessage`'s checks (`empty_text`, then `not_connected`), refuses an empty id, and
243
+ * refuses as `edit_too_long` a text the shared `renderPosts` turns into more than one post, all
244
+ * with no request, so an edit is refused for exactly the texts a send delivers as several posts.
245
+ */
246
+ async editMessage(messageId, out) {
247
+ return refuseAttachments(out) ?? this.editText(messageId, out);
248
+ }
249
+ async editText(messageId, out) {
250
+ if (out.text.length === 0) {
251
+ return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
252
+ }
253
+ if (this.handle === void 0) {
254
+ return {
255
+ ok: false,
256
+ error: { code: "not_connected", message: "MattermostAdapter.connect() not called" }
257
+ };
258
+ }
259
+ if (messageId.length === 0) {
260
+ return { ok: false, error: { code: "invalid_message_id", message: "message id is empty" } };
261
+ }
262
+ const posts = renderPosts(out);
263
+ if (posts.length !== 1) return editPartsRefusal(posts.length);
264
+ const message = posts[0];
265
+ try {
266
+ await this.handle.client.patchPost({ id: messageId, message });
267
+ } catch (err) {
268
+ return mapMattermostError(err);
269
+ }
270
+ return { ok: true, messageId };
271
+ }
213
272
  onInbound(handler) {
214
273
  this.inboundHandler = handler;
215
274
  return () => {
@@ -267,8 +326,27 @@ var MattermostAdapter = class extends BasePlatformAdapter {
267
326
  * named as the handler's failure rather than the platform's, and delivery continues.
268
327
  */
269
328
  async deliver(event) {
329
+ if (!this.passesMentionGate(event)) return "ok";
270
330
  return this.runHandler(this.inboundHandler, event);
271
331
  }
332
+ /**
333
+ * The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.
334
+ *
335
+ * Needs the bot identity from a live connection and the raw post on the event; when either is
336
+ * missing there is nothing to judge by, so the event passes as it did before.
337
+ */
338
+ passesMentionGate(event) {
339
+ const handle = this.handle;
340
+ const mm = event.mattermost;
341
+ if (handle === void 0 || mm?.raw === void 0) return true;
342
+ return shouldRespond({
343
+ post: mm.raw,
344
+ channelType: event.channel.type === "thread" ? "thread" : event.channel.type === "dm" ? "dm" : "group",
345
+ botUserId: handle.botUserId,
346
+ botUsername: handle.botUsername,
347
+ requireMention: this.opts.requireMention ?? true
348
+ });
349
+ }
272
350
  };
273
351
  function parsePostFromWS(msg) {
274
352
  const raw = msg.data?.post;
@@ -291,6 +369,26 @@ function parsePostFromWS(msg) {
291
369
  return void 0;
292
370
  }
293
371
  }
372
+ function editPartsRefusal(partCount) {
373
+ if (partCount > 1) {
374
+ return {
375
+ ok: false,
376
+ error: {
377
+ code: "edit_too_long",
378
+ message: `text needs ${partCount} Mattermost posts; an edit replaces one`
379
+ }
380
+ };
381
+ }
382
+ return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
383
+ }
384
+ function renderPosts(out) {
385
+ if (out.format !== "plain") return splitForMattermost(out.text);
386
+ return splitForMattermost(out.text).flatMap((part) => {
387
+ const escaped = escapeMarkdown(part);
388
+ if (escaped.length <= MATTERMOST_MAX_POST) return [escaped];
389
+ return splitForEscapedMattermost(part).map(escapeMarkdown);
390
+ });
391
+ }
294
392
  function mapMattermostError(err) {
295
393
  const e = err;
296
394
  const status = e.status_code ?? 0;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/filters.ts","../src/normalize.ts","../src/split.ts","../src/adapter.ts"],"names":[],"mappings":";;;AAoBO,IAAM,kBAAA,GAAN,cAAiC,yBAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,sBAAsB,IAAI,CAAA;AAAA,EAClC;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,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AI,WAAW,GAAA,EAAK;AAClB,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,cAAc,OAAA,EAAS,CAAA,CAAE,WAAW,uBAAA;AAAwB,KAC7E;AAAA,EACF;AACA,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,MAAA,KAAW,GAAA,EAAK;AACpC,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,mBAAA;AAAA,QACN,OAAA,EAAS,EAAE,OAAA,IAAW;AAAA;AACxB,KACF;AAAA,EACF;AACA,EAAA,IAAI,WAAW,GAAA,EAAK;AAClB,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,mBAAmB,OAAA,EAAS,CAAA,CAAE,WAAW,6BAAA;AAA8B,KACxF;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO;AAAA,MACL,IAAA,EAAM,aAAA;AAAA,MACN,OAAA,EAAS,EAAE,OAAA,KAAY,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAAA;AACxE,GACF;AACF;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-mattermost`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-mattermost\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-mattermost\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-mattermost: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Wrapper over `@mattermost/client` — lazy import + lifecycle.\n *\n * Owns:\n * - Client4 (REST) for outbound posts + channel/user lookup.\n * - WebSocketClient for real-time `posted` events.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\ninterface Client4Like {\n setUrl(url: string): void;\n setToken(token: string): void;\n getMe(): Promise<{ id: string; username: string }>;\n getChannel(channelId: string): Promise<MattermostChannel>;\n createPost(post: {\n channel_id: string;\n message: string;\n root_id?: string;\n }): Promise<MattermostPost>;\n}\n\ninterface WebSocketClientLike {\n initialize(url: string, token: string): void;\n addMessageListener(listener: (msg: WSMessage) => void): void;\n removeMessageListener(listener: (msg: WSMessage) => void): void;\n close(): void;\n}\n\nexport interface WSMessage {\n readonly event: string;\n readonly data: Record<string, unknown>;\n readonly broadcast?: { readonly channel_id?: string; readonly team_id?: string };\n}\n\ninterface MattermostModule {\n Client4: new () => Client4Like;\n WebSocketClient: new () => WebSocketClientLike;\n}\n\nasync function loadMattermost(): Promise<MattermostModule> {\n try {\n const mod = await import(\"@mattermost/client\");\n return mod as unknown as MattermostModule;\n } catch {\n throw new SDKNotInstalledError(\"@mattermost/client\");\n }\n}\n\nexport interface MattermostClientHandle {\n readonly client: Client4Like;\n readonly ws: WebSocketClientLike;\n readonly botUserId: string;\n readonly botUsername: string;\n /** Channel-id LRU cache (max 200) to avoid extra getChannel calls. */\n readonly channelCache: Map<string, MattermostChannel>;\n}\n\nexport interface ConnectOptions {\n readonly baseUrl: string;\n readonly accessToken: string;\n}\n\n/**\n * Authenticate against a Mattermost server and open the websocket that carries inbound posts.\n *\n * The SDK is loaded lazily, so a project that installs this package without using it never pays for\n * the dependency. Returns the handle every other function here takes — client, websocket and the\n * channel cache, kept together because they share a lifetime.\n */\nexport async function connectMattermost(opts: ConnectOptions): Promise<MattermostClientHandle> {\n const mod = await loadMattermost();\n const client = new mod.Client4();\n client.setUrl(opts.baseUrl);\n client.setToken(opts.accessToken);\n const me = await client.getMe();\n const ws = new mod.WebSocketClient();\n const wsUrl = wsUrlFromBase(opts.baseUrl);\n ws.initialize(wsUrl, opts.accessToken);\n return {\n client,\n ws,\n botUserId: me.id,\n botUsername: me.username,\n channelCache: new Map(),\n };\n}\n\n/**\n * Convert REST base URL to WebSocket URL:\n * `https://x.com` → `wss://x.com/api/v4/websocket`\n * `http://localhost:8065` → `ws://localhost:8065/api/v4/websocket`\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function wsUrlFromBase(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/$/, \"\");\n const wsScheme = trimmed.startsWith(\"https://\") ? \"wss://\" : \"ws://\";\n const hostPart = trimmed.replace(/^https?:\\/\\//, \"\");\n return `${wsScheme}${hostPart}/api/v4/websocket`;\n}\n\n/**\n * Fetch a channel by id, remembering the answer on the handle.\n *\n * Normalising an inbound post needs the channel's type, and a busy channel would otherwise cost one\n * API call per message. Returns `undefined` rather than throwing when the channel cannot be read —\n * a post from a channel the bot cannot see is a normal event, not a failure.\n */\nexport async function getChannelCached(\n handle: MattermostClientHandle,\n channelId: string,\n): Promise<MattermostChannel | undefined> {\n const cached = handle.channelCache.get(channelId);\n if (cached !== undefined) return cached;\n try {\n const channel = await handle.client.getChannel(channelId);\n // LRU cap: drop oldest when full.\n if (handle.channelCache.size >= 200) {\n const firstKey = handle.channelCache.keys().next().value;\n if (firstKey !== undefined) handle.channelCache.delete(firstKey);\n }\n handle.channelCache.set(channelId, channel);\n return channel;\n } catch {\n return undefined;\n }\n}\n","/**\n * Inbound dispatch pipeline (D403, EC-2).\n *\n * Order matters — these checks compose:\n *\n * 1. Loop guard: drop bot's own posts (D275 mirror).\n * 2. DM channels: always respond.\n * 3. `requireMention === false`: respond.\n * 4. **Metadata.mentions** array contains bot user-id → respond (PRIORITY).\n * 5. **Word-boundary text regex** `\\b@${botUsername}\\b` → respond.\n * 6. Else: ignore.\n *\n * EC-2: substring match (`post.message.includes(\"@theo\")`) catches\n * `@theory_dept` and dispatches false-positive. The fix is two-fold:\n * prefer the unambiguous `metadata.mentions` array (API-provided\n * user-ids), and when text fallback is required, use `\\b` boundaries.\n */\n\nimport type { MattermostPost } from \"./types.js\";\n\n/** @knipignore — input shape for `shouldRespond`; useful for callers wrapping the filter pipeline. */\nexport interface ShouldRespondOptions {\n readonly post: MattermostPost;\n readonly channelType: \"dm\" | \"group\" | \"thread\";\n readonly botUserId: string;\n readonly botUsername: string;\n readonly requireMention: boolean;\n}\n\n/**\n * Decide whether the bot should answer a post.\n *\n * Three rules in order: never answer itself (the loop guard), always answer a direct message, and in\n * a channel answer only when mentioned unless `requireMention` is turned off. The mention default\n * is what keeps a bot added to a busy channel from replying to every message in it.\n */\nexport function shouldRespond(opts: ShouldRespondOptions): boolean {\n const { post, channelType, botUserId, botUsername, requireMention } = opts;\n // 1. Loop guard.\n if (post.user_id === botUserId) return false;\n // 2. DM — always.\n if (channelType === \"dm\") return true;\n // 3. Opt-out of mention enforcement.\n if (!requireMention) return true;\n // 4. metadata.mentions takes priority — never ambiguous.\n const mentioned = post.metadata?.mentions?.includes(botUserId) ?? false;\n if (mentioned) return true;\n // 5. Text fallback with word boundary (EC-2).\n if (botUsername.length > 0 && hasMentionWithBoundary(post.message, botUsername)) {\n return true;\n }\n return false;\n}\n\n/**\n * Word-boundary match for `@${botUsername}`. Word boundaries land at\n * `\\b` (start/end of `\\w` regions), so `@theo` at the head of `@theory`\n * does NOT match because `\\b` is between `o` and `r` only when the\n * NEXT char is a non-word char.\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function hasMentionWithBoundary(text: string, botUsername: string): boolean {\n // Escape regex metacharacters in username (Mattermost allows `.`, `_`, `-`).\n const safe = botUsername.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(`(^|[^\\\\w])@${safe}(?![\\\\w.])`, \"u\");\n return re.test(text);\n}\n","/**\n * Inbound normalization: Mattermost Post → MattermostMessageEvent.\n *\n * Channel-type mapping (D402):\n * - `D` (Direct) → `\"dm\"`\n * - `G`/`O`/`P` (Group/Open/Private) → `\"group\"`\n * - Posts with `root_id !== \"\"` → `\"thread\"` with `topicId = root_id` (D399).\n */\n\nimport type { MattermostMessageEvent } from \"@theokit/gateway\";\n\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\nexport function normalizeMattermostType(\n channel: MattermostChannel | undefined,\n): \"D\" | \"G\" | \"O\" | \"P\" | (string & {}) {\n return channel?.type ?? \"O\";\n}\n\n/**\n * Map Mattermost's channel type to the gateway's conversation kind.\n *\n * A post carrying a root id is a threaded reply whatever channel it sits in, so that wins over the\n * channel's own type; `\"D\"` is a direct message, and everything else is treated as a group.\n */\nexport function mapChannelType(rawType: string, hasRootId: boolean): \"dm\" | \"group\" | \"thread\" {\n if (hasRootId) return \"thread\";\n if (rawType === \"D\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn a Mattermost post into a `MattermostMessageEvent`.\n *\n * `channel` and `senderUsername` are optional because both are fetched separately and either can be\n * unavailable; the event is still produced, with the conversation kind falling back to a group.\n */\nexport function postToMessageEvent(\n post: MattermostPost,\n channel: MattermostChannel | undefined,\n senderUsername: string | undefined,\n): MattermostMessageEvent {\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n return {\n id: post.id,\n platform: \"mattermost\",\n sender: {\n id: post.user_id,\n ...(senderUsername !== undefined ? { username: senderUsername } : {}),\n },\n channel: {\n id: post.channel_id,\n type: channelType,\n ...(channelType === \"thread\" ? { topicId: post.root_id } : {}),\n },\n text: post.message,\n receivedAt: post.create_at > 0 ? post.create_at : Date.now(),\n mattermost: {\n postId: post.id,\n channelId: post.channel_id,\n teamId: channel?.team_id ?? \"\",\n ...(post.root_id.length > 0 ? { rootId: post.root_id } : {}),\n channelType: rawType,\n raw: post,\n },\n };\n}\n","/**\n * `splitForMattermost` — segment outbound text to Mattermost's post cap.\n *\n * This package shipped without any splitting at all, alone among the ten\n * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent\n * reply longer than the cap came back:\n *\n * HTTP 400 — \"Post Message property is longer than the maximum permitted length.\"\n *\n * and the user saw nothing. No unit test could catch it, because there was no\n * cap in the code to assert against; it took a real server to answer 400.\n * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,\n * 16384 is refused.\n *\n * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This\n * splits on code points via the core chunker, which is the closest the JS side\n * gets without walking graphemes; a message of astral-plane characters could\n * still exceed the server's count, which is why the window leaves headroom.\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\n/** Mattermost's default `MaxPostSize`, in runes. */\nconst MATTERMOST_MAX_POST = 16_383;\n\n/**\n * Cut inside a smaller window than the cap.\n *\n * The headroom absorbs the gap between how JavaScript counts a string and how\n * the server counts runes. Landing exactly on the limit is the one place this\n * can still fail, and the failure is a 400 the user never sees.\n */\nconst SAFE_CHUNK = 16_000;\n\nexport function splitForMattermost(text: string): string[] {\n return chunkText(text, {\n limit: MATTERMOST_MAX_POST,\n safeLimit: SAFE_CHUNK,\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n stripLeading: /^\\s+/,\n });\n}\n","/**\n * `MattermostAdapter` — implements BasePlatformAdapter over Client4 + WS.\n * ADRs D397-D404.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport {\n type ConnectOptions,\n connectMattermost,\n getChannelCached,\n type MattermostClientHandle,\n type WSMessage,\n} from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { shouldRespond } from \"./filters.js\";\nimport { mapChannelType, normalizeMattermostType, postToMessageEvent } from \"./normalize.js\";\nimport { splitForMattermost } from \"./split.js\";\nimport type { MattermostAdapterOptions, MattermostPost } from \"./types.js\";\n\nexport class MattermostAdapter extends BasePlatformAdapter {\n readonly platform = \"mattermost\" as const;\n private readonly opts: MattermostAdapterOptions;\n private handle: MattermostClientHandle | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private wsListener: ((msg: WSMessage) => void) | undefined;\n private connected = false;\n\n constructor(opts: MattermostAdapterOptions) {\n super();\n if (opts.baseUrl.length === 0) {\n throw new ConfigurationError({\n code: \"base_url_required\",\n message: 'gateway-mattermost: opts.baseUrl is empty (e.g. \"https://mattermost.acme.com\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-mattermost: opts.accessToken is empty (generate one in System Console → Integrations → Bot Accounts)\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n this.handle = await connectMattermost({\n baseUrl: this.opts.baseUrl,\n accessToken: this.opts.accessToken,\n } satisfies ConnectOptions);\n this.attachWsListener();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n if (this.handle !== undefined && this.wsListener !== undefined) {\n this.handle.ws.removeMessageListener(this.wsListener);\n }\n this.handle?.ws.close();\n this.handle = undefined;\n this.wsListener = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n try {\n // Split before sending. This package used to post `out.text` whole, alone\n // among the ten adapters, so anything past Mattermost's 16383-rune cap came\n // back HTTP 400 and the user saw nothing at all.\n let lastId: string | undefined;\n // Mattermost parses markdown natively, so `markdown` needs no flag; `plain` is the\n // case that needs work, because raw text would be parsed anyway.\n // Split first, escape per chunk — the same ordering Discord needs, for the same reason:\n // a cut between a backslash and its character produces a stray backslash in one message\n // and a bare marker in the next.\n for (const raw of splitForMattermost(out.text)) {\n const chunk = out.format === \"plain\" ? escapeMarkdown(raw) : raw;\n const post = await this.handle.client.createPost({\n channel_id: out.channel.id,\n message: chunk,\n ...(out.channel.type === \"thread\" && out.channel.topicId !== undefined\n ? { root_id: out.channel.topicId }\n : {}),\n });\n lastId = post.id;\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n } catch (err) {\n return mapMattermostError(err);\n }\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */\n getClient(): MattermostClientHandle | undefined {\n return this.handle;\n }\n\n private attachWsListener(): void {\n if (this.handle === undefined) return;\n const handle = this.handle;\n this.wsListener = (msg: WSMessage) => {\n if (msg.event !== \"posted\") return;\n void this.processPostedEvent(handle, msg).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] processPostedEvent failed: ${m}\\n`);\n });\n };\n handle.ws.addMessageListener(this.wsListener);\n }\n\n private async processPostedEvent(handle: MattermostClientHandle, msg: WSMessage): Promise<void> {\n const post = parsePostFromWS(msg);\n if (post === undefined) return;\n const channel = await getChannelCached(handle, post.channel_id);\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n const requireMention = this.opts.requireMention ?? true;\n if (\n !shouldRespond({\n post,\n channelType,\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention,\n })\n ) {\n return;\n }\n const senderUsername =\n typeof msg.data.sender_name === \"string\"\n ? (msg.data.sender_name as string).replace(/^@/, \"\")\n : undefined;\n const event = postToMessageEvent(post, channel, senderUsername);\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] handler threw: ${m}\\n`);\n }\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.inboundHandler, event);\n }\n}\n\n/**\n * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.\n *\n * @public — exposed so consumers can drive their own WS listener too.\n */\nexport function parsePostFromWS(msg: WSMessage): MattermostPost | undefined {\n const raw = msg.data?.post;\n if (typeof raw !== \"string\") return undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<MattermostPost>;\n if (\n typeof parsed.id !== \"string\" ||\n typeof parsed.user_id !== \"string\" ||\n typeof parsed.channel_id !== \"string\" ||\n typeof parsed.message !== \"string\"\n ) {\n return undefined;\n }\n return {\n id: parsed.id,\n user_id: parsed.user_id,\n channel_id: parsed.channel_id,\n root_id: typeof parsed.root_id === \"string\" ? parsed.root_id : \"\",\n message: parsed.message,\n create_at: typeof parsed.create_at === \"number\" ? parsed.create_at : 0,\n metadata: parsed.metadata,\n };\n } catch {\n return undefined;\n }\n}\n\ninterface MattermostRestError {\n status_code?: number;\n message?: string;\n}\n\nfunction mapMattermostError(err: unknown): SendResult {\n const e = err as MattermostRestError;\n const status = e.status_code ?? 0;\n if (status === 429) {\n return {\n ok: false,\n error: { code: \"rate_limit\", message: e.message ?? \"Mattermost rate limit\" },\n };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: {\n code: \"permission_denied\",\n message: e.message ?? \"Mattermost auth/permission error\",\n },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Mattermost rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\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/errors.ts","../src/client.ts","../src/filters.ts","../src/normalize.ts","../src/refuse-attachments.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,CAAA;AACH;AAEA,SAAS,mBAAmB,GAAA,EAA0B;AACpD,EAAA,MAAM,CAAA,GAAI,GAAA;AACV,EAAA,MAAM,MAAA,GAAS,EAAE,WAAA,IAAe,CAAA;AAChC,EAAA,IAAI,WAAW,GAAA,EAAK;AAClB,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,cAAc,OAAA,EAAS,CAAA,CAAE,WAAW,uBAAA;AAAwB,KAC7E;AAAA,EACF;AACA,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,MAAA,KAAW,GAAA,EAAK;AACpC,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,mBAAA;AAAA,QACN,OAAA,EAAS,EAAE,OAAA,IAAW;AAAA;AACxB,KACF;AAAA,EACF;AACA,EAAA,IAAI,WAAW,GAAA,EAAK;AAClB,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,mBAAmB,OAAA,EAAS,CAAA,CAAE,WAAW,6BAAA;AAA8B,KACxF;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO;AAAA,MACL,IAAA,EAAM,aAAA;AAAA,MACN,OAAA,EAAS,EAAE,OAAA,KAAY,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAAA;AACxE,GACF;AACF;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-mattermost`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-mattermost\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-mattermost\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-mattermost: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Wrapper over `@mattermost/client` — lazy import + lifecycle.\n *\n * Owns:\n * - Client4 (REST) for outbound posts + channel/user lookup.\n * - WebSocketClient for real-time `posted` events.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\ninterface Client4Like {\n setUrl(url: string): void;\n setToken(token: string): void;\n getMe(): Promise<{ id: string; username: string }>;\n getChannel(channelId: string): Promise<MattermostChannel>;\n createPost(post: {\n channel_id: string;\n message: string;\n root_id?: string;\n }): Promise<MattermostPost>;\n /** Replace the fields a patch names on an existing post; the adapter's edit sends `message`. */\n patchPost(patch: { id: string; message: string }): Promise<MattermostPost>;\n}\n\ninterface WebSocketClientLike {\n initialize(url: string, token: string): void;\n addMessageListener(listener: (msg: WSMessage) => void): void;\n removeMessageListener(listener: (msg: WSMessage) => void): void;\n close(): void;\n}\n\nexport interface WSMessage {\n readonly event: string;\n readonly data: Record<string, unknown>;\n readonly broadcast?: { readonly channel_id?: string; readonly team_id?: string };\n}\n\ninterface MattermostModule {\n Client4: new () => Client4Like;\n WebSocketClient: new () => WebSocketClientLike;\n}\n\nasync function loadMattermost(): Promise<MattermostModule> {\n try {\n const mod = (await import(\"@mattermost/client\")) as unknown as Partial<MattermostModule> & {\n default?: MattermostModule;\n };\n // Node's CommonJS namespace does not expose the SDK's getter-defined exports.\n return {\n Client4: mod.Client4 ?? mod.default?.Client4,\n WebSocketClient: mod.WebSocketClient ?? mod.default?.WebSocketClient,\n } as MattermostModule;\n } catch {\n throw new SDKNotInstalledError(\"@mattermost/client\");\n }\n}\n\nexport interface MattermostClientHandle {\n readonly client: Client4Like;\n readonly ws: WebSocketClientLike;\n readonly botUserId: string;\n readonly botUsername: string;\n /** Channel-id LRU cache (max 200) to avoid extra getChannel calls. */\n readonly channelCache: Map<string, MattermostChannel>;\n}\n\nexport interface ConnectOptions {\n readonly baseUrl: string;\n readonly accessToken: string;\n}\n\n/**\n * Authenticate against a Mattermost server and open the websocket that carries inbound posts.\n *\n * The SDK is loaded lazily, so a project that installs this package without using it never pays for\n * the dependency. Returns the handle every other function here takes — client, websocket and the\n * channel cache, kept together because they share a lifetime.\n */\nexport async function connectMattermost(opts: ConnectOptions): Promise<MattermostClientHandle> {\n const mod = await loadMattermost();\n const client = new mod.Client4();\n client.setUrl(opts.baseUrl);\n client.setToken(opts.accessToken);\n const me = await client.getMe();\n const ws = new mod.WebSocketClient();\n const wsUrl = wsUrlFromBase(opts.baseUrl);\n ws.initialize(wsUrl, opts.accessToken);\n return {\n client,\n ws,\n botUserId: me.id,\n botUsername: me.username,\n channelCache: new Map(),\n };\n}\n\n/**\n * Convert REST base URL to WebSocket URL:\n * `https://x.com` → `wss://x.com/api/v4/websocket`\n * `http://localhost:8065` → `ws://localhost:8065/api/v4/websocket`\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function wsUrlFromBase(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/$/, \"\");\n const wsScheme = trimmed.startsWith(\"https://\") ? \"wss://\" : \"ws://\";\n const hostPart = trimmed.replace(/^https?:\\/\\//, \"\");\n return `${wsScheme}${hostPart}/api/v4/websocket`;\n}\n\n/**\n * Fetch a channel by id, remembering the answer on the handle.\n *\n * Normalising an inbound post needs the channel's type, and a busy channel would otherwise cost one\n * API call per message. Returns `undefined` rather than throwing when the channel cannot be read —\n * a post from a channel the bot cannot see is a normal event, not a failure.\n */\nexport async function getChannelCached(\n handle: MattermostClientHandle,\n channelId: string,\n): Promise<MattermostChannel | undefined> {\n const cached = handle.channelCache.get(channelId);\n if (cached !== undefined) return cached;\n try {\n const channel = await handle.client.getChannel(channelId);\n // LRU cap: drop oldest when full.\n if (handle.channelCache.size >= 200) {\n const firstKey = handle.channelCache.keys().next().value;\n if (firstKey !== undefined) handle.channelCache.delete(firstKey);\n }\n handle.channelCache.set(channelId, channel);\n return channel;\n } catch {\n return undefined;\n }\n}\n","/**\n * Inbound dispatch pipeline (D403, EC-2).\n *\n * Order matters — these checks compose:\n *\n * 1. Loop guard: drop bot's own posts (D275 mirror).\n * 2. DM channels: always respond.\n * 3. `requireMention === false`: respond.\n * 4. **Metadata.mentions** array contains bot user-id → respond (PRIORITY).\n * 5. **Word-boundary text regex** `\\b@${botUsername}\\b` → respond.\n * 6. Else: ignore.\n *\n * EC-2: substring match (`post.message.includes(\"@theo\")`) catches\n * `@theory_dept` and dispatches false-positive. The fix is two-fold:\n * prefer the unambiguous `metadata.mentions` array (API-provided\n * user-ids), and when text fallback is required, use `\\b` boundaries.\n */\n\nimport type { MattermostPost } from \"./types.js\";\n\n/** @knipignore — input shape for `shouldRespond`; useful for callers wrapping the filter pipeline. */\nexport interface ShouldRespondOptions {\n readonly post: MattermostPost;\n readonly channelType: \"dm\" | \"group\" | \"thread\";\n readonly botUserId: string;\n readonly botUsername: string;\n readonly requireMention: boolean;\n}\n\n/**\n * Decide whether the bot should answer a post.\n *\n * Three rules in order: never answer itself (the loop guard), always answer a direct message, and in\n * a channel answer only when mentioned unless `requireMention` is turned off. The mention default\n * is what keeps a bot added to a busy channel from replying to every message in it.\n */\nexport function shouldRespond(opts: ShouldRespondOptions): boolean {\n const { post, channelType, botUserId, botUsername, requireMention } = opts;\n // 1. Loop guard.\n if (post.user_id === botUserId) return false;\n // 2. DM — always.\n if (channelType === \"dm\") return true;\n // 3. Opt-out of mention enforcement.\n if (!requireMention) return true;\n // 4. metadata.mentions takes priority — never ambiguous.\n const mentioned = post.metadata?.mentions?.includes(botUserId) ?? false;\n if (mentioned) return true;\n // 5. Text fallback with word boundary (EC-2).\n if (botUsername.length > 0 && hasMentionWithBoundary(post.message, botUsername)) {\n return true;\n }\n return false;\n}\n\n/**\n * Word-boundary match for `@${botUsername}`. Word boundaries land at\n * `\\b` (start/end of `\\w` regions), so `@theo` at the head of `@theory`\n * does NOT match because `\\b` is between `o` and `r` only when the\n * NEXT char is a non-word char.\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function hasMentionWithBoundary(text: string, botUsername: string): boolean {\n // Escape regex metacharacters in username (Mattermost allows `.`, `_`, `-`).\n const safe = botUsername.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(`(^|[^\\\\w])@${safe}(?![\\\\w.])`, \"u\");\n return re.test(text);\n}\n","/**\n * Inbound normalization: Mattermost Post → MattermostMessageEvent.\n *\n * Channel-type mapping (D402):\n * - `D` (Direct) → `\"dm\"`\n * - `G`/`O`/`P` (Group/Open/Private) → `\"group\"`\n * - Posts with `root_id !== \"\"` → `\"thread\"` with `topicId = root_id` (D399).\n */\n\nimport type { MattermostMessageEvent } from \"@theokit/gateway\";\n\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\nexport function normalizeMattermostType(\n channel: MattermostChannel | undefined,\n): \"D\" | \"G\" | \"O\" | \"P\" | (string & {}) {\n return channel?.type ?? \"O\";\n}\n\n/**\n * Map Mattermost's channel type to the gateway's conversation kind.\n *\n * A post carrying a root id is a threaded reply whatever channel it sits in, so that wins over the\n * channel's own type; `\"D\"` is a direct message, and everything else is treated as a group.\n */\nexport function mapChannelType(rawType: string, hasRootId: boolean): \"dm\" | \"group\" | \"thread\" {\n if (hasRootId) return \"thread\";\n if (rawType === \"D\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn a Mattermost post into a `MattermostMessageEvent`.\n *\n * `channel` and `senderUsername` are optional because both are fetched separately and either can be\n * unavailable; the event is still produced, with the conversation kind falling back to a group.\n */\nexport function postToMessageEvent(\n post: MattermostPost,\n channel: MattermostChannel | undefined,\n senderUsername: string | undefined,\n): MattermostMessageEvent {\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n return {\n id: post.id,\n platform: \"mattermost\",\n sender: {\n id: post.user_id,\n ...(senderUsername !== undefined ? { username: senderUsername } : {}),\n },\n channel: {\n id: post.channel_id,\n type: channelType,\n ...(channelType === \"thread\" ? { topicId: post.root_id } : {}),\n },\n text: post.message,\n receivedAt: post.create_at > 0 ? post.create_at : Date.now(),\n mattermost: {\n postId: post.id,\n channelId: post.channel_id,\n teamId: channel?.team_id ?? \"\",\n ...(post.root_id.length > 0 ? { rootId: post.root_id } : {}),\n channelType: rawType,\n raw: post,\n },\n };\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: \"mattermost adapter cannot send attachments\",\n },\n };\n}\n","/**\n * `splitForMattermost` — segment outbound text to Mattermost's post cap.\n *\n * This package shipped without any splitting at all, alone among the ten\n * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent\n * reply longer than the cap came back:\n *\n * HTTP 400 — \"Post Message property is longer than the maximum permitted length.\"\n *\n * and the user saw nothing. No unit test could catch it, because there was no\n * cap in the code to assert against; it took a real server to answer 400.\n * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,\n * 16384 is refused.\n *\n * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This\n * splits on code points via the core chunker, which is the closest the JS side\n * gets without walking graphemes; a message of astral-plane characters could\n * still exceed the server's count, which is why the window leaves headroom.\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\n/** Mattermost's default `MaxPostSize`, in runes. */\nexport const MATTERMOST_MAX_POST = 16_383;\n\n/**\n * Cut inside a smaller window than the cap.\n *\n * The headroom absorbs the gap between how JavaScript counts a string and how\n * the server counts runes. Landing exactly on the limit is the one place this\n * can still fail, and the failure is a 400 the user never sees.\n */\nconst SAFE_CHUNK = 16_000;\n\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n stripLeading: /^\\s+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into posts that fit Mattermost's post cap.\n *\n * Each chunk is at most {@link MATTERMOST_MAX_POST} code points, cut inside a\n * 16000-character window at a blank line, a newline or a space, in that order of\n * preference.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order, each with leading whitespace stripped at the cut.\n */\nexport function splitForMattermost(text: string): string[] {\n return chunkText(text, { limit: MATTERMOST_MAX_POST, safeLimit: SAFE_CHUNK, ...BOUNDARIES });\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 8191 characters fits\n * one post once escaped. The adapter calls this only for a part whose escaped body passed the cap,\n * so the parts of an ordinary text are the ones `splitForMattermost` returns.\n */\nexport function splitForEscapedMattermost(text: string): string[] {\n return chunkText(text, {\n limit: Math.floor(MATTERMOST_MAX_POST / 2),\n safeLimit: SAFE_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `MattermostAdapter` — implements BasePlatformAdapter over Client4 + WS.\n * ADRs D397-D404.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport {\n type ConnectOptions,\n connectMattermost,\n getChannelCached,\n type MattermostClientHandle,\n type WSMessage,\n} from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { shouldRespond } from \"./filters.js\";\nimport { mapChannelType, normalizeMattermostType, postToMessageEvent } from \"./normalize.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { MATTERMOST_MAX_POST, splitForEscapedMattermost, splitForMattermost } from \"./split.js\";\nimport type { MattermostAdapterOptions, MattermostPost } from \"./types.js\";\n\nexport class MattermostAdapter extends BasePlatformAdapter {\n readonly platform = \"mattermost\" as const;\n private readonly opts: MattermostAdapterOptions;\n private handle: MattermostClientHandle | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private wsListener: ((msg: WSMessage) => void) | undefined;\n private connected = false;\n\n constructor(opts: MattermostAdapterOptions) {\n super();\n if (opts.baseUrl.length === 0) {\n throw new ConfigurationError({\n code: \"base_url_required\",\n message: 'gateway-mattermost: opts.baseUrl is empty (e.g. \"https://mattermost.acme.com\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-mattermost: opts.accessToken is empty (generate one in System Console → Integrations → Bot Accounts)\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n this.handle = await connectMattermost({\n baseUrl: this.opts.baseUrl,\n accessToken: this.opts.accessToken,\n } satisfies ConnectOptions);\n this.attachWsListener();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n if (this.handle !== undefined && this.wsListener !== undefined) {\n this.handle.ws.removeMessageListener(this.wsListener);\n }\n this.handle?.ws.close();\n this.handle = undefined;\n this.wsListener = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n try {\n // Split before sending. This package used to post `out.text` whole, alone\n // among the ten adapters, so anything past Mattermost's 16383-rune cap came\n // back HTTP 400 and the user saw nothing at all.\n let lastId: string | undefined;\n for (const message of renderPosts(out)) {\n const post = await this.handle.client.createPost({\n channel_id: out.channel.id,\n message,\n ...(out.channel.type === \"thread\" && out.channel.topicId !== undefined\n ? { root_id: out.channel.topicId }\n : {}),\n });\n lastId = post.id;\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n } catch (err) {\n return mapMattermostError(err);\n }\n }\n\n /** Mattermost edits a sent post's text through `Client4.patchPost`. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a post this bot sent, through `patchPost({ id, message })`.\n *\n * Applies `sendMessage`'s checks (`empty_text`, then `not_connected`), refuses an empty id, and\n * refuses as `edit_too_long` a text the shared `renderPosts` turns into more than one post, all\n * with no request, so an edit is refused for exactly the texts a send delivers as several posts.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const posts = renderPosts(out);\n if (posts.length !== 1) return editPartsRefusal(posts.length);\n const message = posts[0] as string;\n try {\n await this.handle.client.patchPost({ id: messageId, message });\n } catch (err) {\n return mapMattermostError(err);\n }\n return { ok: true, messageId };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */\n getClient(): MattermostClientHandle | undefined {\n return this.handle;\n }\n\n private attachWsListener(): void {\n if (this.handle === undefined) return;\n const handle = this.handle;\n this.wsListener = (msg: WSMessage) => {\n if (msg.event !== \"posted\") return;\n void this.processPostedEvent(handle, msg).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] processPostedEvent failed: ${m}\\n`);\n });\n };\n handle.ws.addMessageListener(this.wsListener);\n }\n\n private async processPostedEvent(handle: MattermostClientHandle, msg: WSMessage): Promise<void> {\n const post = parsePostFromWS(msg);\n if (post === undefined) return;\n const channel = await getChannelCached(handle, post.channel_id);\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n const requireMention = this.opts.requireMention ?? true;\n if (\n !shouldRespond({\n post,\n channelType,\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention,\n })\n ) {\n return;\n }\n const senderUsername =\n typeof msg.data.sender_name === \"string\"\n ? (msg.data.sender_name as string).replace(/^@/, \"\")\n : undefined;\n const event = postToMessageEvent(post, channel, senderUsername);\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] handler threw: ${m}\\n`);\n }\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 if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.inboundHandler, event);\n }\n\n /**\n * The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.\n *\n * Needs the bot identity from a live connection and the raw post on the event; when either is\n * missing there is nothing to judge by, so the event passes as it did before.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n const handle = this.handle;\n const mm = (event as { mattermost?: { raw?: MattermostPost } }).mattermost;\n if (handle === undefined || mm?.raw === undefined) return true;\n return shouldRespond({\n post: mm.raw,\n channelType:\n event.channel.type === \"thread\" ? \"thread\" : event.channel.type === \"dm\" ? \"dm\" : \"group\",\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention: this.opts.requireMention ?? true,\n });\n }\n}\n\n/**\n * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.\n *\n * @public — exposed so consumers can drive their own WS listener too.\n */\nexport function parsePostFromWS(msg: WSMessage): MattermostPost | undefined {\n const raw = msg.data?.post;\n if (typeof raw !== \"string\") return undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<MattermostPost>;\n if (\n typeof parsed.id !== \"string\" ||\n typeof parsed.user_id !== \"string\" ||\n typeof parsed.channel_id !== \"string\" ||\n typeof parsed.message !== \"string\"\n ) {\n return undefined;\n }\n return {\n id: parsed.id,\n user_id: parsed.user_id,\n channel_id: parsed.channel_id,\n root_id: typeof parsed.root_id === \"string\" ? parsed.root_id : \"\",\n message: parsed.message,\n create_at: typeof parsed.create_at === \"number\" ? parsed.create_at : 0,\n metadata: parsed.metadata,\n };\n } catch {\n return undefined;\n }\n}\n\ninterface MattermostRestError {\n status_code?: number;\n message?: string;\n}\n\n/**\n * The refusal for a text that is not exactly one Mattermost post.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since\n * `splitForMattermost` returns at least one part for any non-empty text and empty text is refused\n * earlier; the arm 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} Mattermost posts; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\n/**\n * The post bodies a text goes out as, each within `MATTERMOST_MAX_POST`.\n *\n * Mattermost parses markdown natively, so `markdown` needs no flag; `plain` is the case that needs\n * work, because raw text would be parsed anyway. Split first, escape per part, the ordering Discord\n * needs for the same reason: a cut between a backslash and its character produces a stray\n * backslash in one post and a bare marker in the next. The splitter measures the caller's text,\n * and escaping can double a part, so a part whose escaped body passes the cap is split again at\n * half the cap, which every escaped body fits. `sendMessage` and `editMessage` both send what this\n * returns.\n */\nfunction renderPosts(out: OutboundMessage): string[] {\n if (out.format !== \"plain\") return splitForMattermost(out.text);\n return splitForMattermost(out.text).flatMap((part) => {\n const escaped = escapeMarkdown(part);\n if (escaped.length <= MATTERMOST_MAX_POST) return [escaped];\n return splitForEscapedMattermost(part).map(escapeMarkdown);\n });\n}\n\nfunction mapMattermostError(err: unknown): SendResult {\n const e = err as MattermostRestError;\n const status = e.status_code ?? 0;\n if (status === 429) {\n return {\n ok: false,\n error: { code: \"rate_limit\", message: e.message ?? \"Mattermost rate limit\" },\n };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: {\n code: \"permission_denied\",\n message: e.message ?? \"Mattermost auth/permission error\",\n },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Mattermost rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\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-mattermost",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "Mattermost platform adapter for @theokit/gateway. WebSocket gateway + REST. ADRs D397-D404.",
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
  "sideEffects": false,
31
32
  "files": [
@@ -56,12 +57,26 @@
56
57
  "typescript": "5.9.3",
57
58
  "vitest": "^4.1.11",
58
59
  "zod": "^4.0.0",
59
- "@theokit/gateway": "0.9.0"
60
+ "@theokit/gateway": "0.14.0"
60
61
  },
61
62
  "publishConfig": {
62
63
  "access": "public",
63
64
  "provenance": true
64
65
  },
66
+ "bugs": {
67
+ "url": "https://github.com/usetheokit/theokit-gateways/issues"
68
+ },
69
+ "homepage": "https://github.com/usetheokit/theokit-gateways/tree/main/packages/gateway-mattermost#readme",
70
+ "keywords": [
71
+ "theokit",
72
+ "gateway",
73
+ "mattermost",
74
+ "platform",
75
+ "adapter",
76
+ "websocket",
77
+ "rest",
78
+ "adrs"
79
+ ],
65
80
  "scripts": {
66
81
  "build": "tsup",
67
82
  "typecheck": "tsc --noEmit",