@theokit/gateway-mattermost 0.1.5 → 0.2.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,64 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 1e215ab: The peer floor on `@theokit/gateway` is `>=0.9.0`, which is what these packages have needed since
8
+ they gained `deliver`.
9
+
10
+ `deliver` and `runHandler` arrived in the core at 0.9.0, and the previous release shipped these
11
+ adapters still declaring `>=0.6.0` — a floor `dep-check` had already proven false by building the
12
+ workspace against it: TS4113 on the override, TS2551 on `runHandler`, in all ten packages.
13
+
14
+ It could not be corrected in that release. `dep-check`'s install check packs an adapter and installs
15
+ it the way a consumer would, and until 0.9.0 was on npm no consumer could resolve a package asking
16
+ for it — the check was right about the world as it stood. The floor is raised here, against a
17
+ registry where the version it names exists.
18
+
19
+ Between the two releases a consumer installing against an older core got a build error rather than a
20
+ resolution error: the same failure, later and less clearly. That window is closed.
21
+
22
+ ## 0.2.0
23
+
24
+ ### Minor Changes
25
+
26
+ - b38172b: **The peer floor on `@theokit/gateway` rises with this release.** Every adapter now implements
27
+ `deliver` over `runHandler`, and neither exists in an older core — an adapter installed against one
28
+ does not build. `dep-check` caught that by building the whole workspace against the floor each
29
+ package claimed, which is the one thing a version range cannot tell you by reading it.
30
+
31
+ The floor is set in the version commit rather than here, because a range cannot name a version that
32
+ does not exist yet: raised in the workspace, the same gate then fails the other way round — every
33
+ adapter declaring a floor above the core installed beside it. That is the shape `fa70153` used when
34
+ these ranges were first written.
35
+
36
+ `deliver(event)` — every adapter can now be handed an event that arrived out of band (#83).
37
+
38
+ `onInbound` was the seam every adapter implemented and it had no public counterpart. Six platforms
39
+ self-deliver once connected — long polling, a gateway socket, Socket Mode, a sync loop, IMAP — so
40
+ the asymmetry stayed invisible: `GatewayRunner` worked for eight platforms and silently did nothing
41
+ for LINE and WhatsApp Cloud, whose payloads arrive on an HTTP route the application owns. Every app
42
+ wired those two by hand, beside the runner rather than through it.
43
+
44
+ ```ts
45
+ const outcome = await adapter.deliver(event); // "ok" | "no_handler" | "handler_threw"
46
+ ```
47
+
48
+ The three outcomes are distinguished because a caller acts on them differently: answering a webhook
49
+ 200 when nobody was subscribed tells the provider to stop retrying a message nothing received.
50
+
51
+ `BasePlatformAdapter.runHandler` holds the containment once, where ten copies of it used to live —
52
+ a handler is user code, its throw is named as the handler's failure rather than the platform's, and
53
+ delivery continues. Each adapter's `deliver` is one line over it.
54
+
55
+ Also: `gateway-sms`'s `createWebhookServer` now signs against the configured `publicUrl` (#90).
56
+ Twilio verifies against the URL it POSTed to, and behind a proxy that rewrites `host` — a tunnel, an
57
+ ingress, a load balancer terminating TLS — the reconstruction from headers yields the internal
58
+ address, so a correct signature fails on every delivery. `publicUrl` is required by all three
59
+ backend option shapes and documented as "used by signature verifier"; until now no source file read
60
+ it. The header reconstruction stays as the fallback for an app served directly.
61
+
3
62
  ## 0.1.5
4
63
 
5
64
  ### Patch Changes
package/README.md CHANGED
@@ -4,6 +4,14 @@ Mattermost platform adapter for [`@theokit/gateway`](../gateway).
4
4
 
5
5
  Works with self-hosted Mattermost (Docker / Kubernetes / bare metal) and Mattermost Cloud. WebSocket gateway for real-time inbound, REST v4 for outbound.
6
6
 
7
+
8
+ ## How inbound arrives
9
+
10
+ **WebSocket.** The adapter subscribes to the server's event socket; messages reach `onInbound` once
11
+ `connect()` resolves. There is no webhook to host and nothing for an application to authenticate.
12
+
13
+ Mattermost's platform does offer outgoing webhooks and slash commands. This adapter does not use
14
+ them, so nothing here validates one.
7
15
  ## Install
8
16
 
9
17
  ```bash
package/dist/index.cjs CHANGED
@@ -198,7 +198,8 @@ var MattermostAdapter = class extends gateway.BasePlatformAdapter {
198
198
  }
199
199
  try {
200
200
  let lastId;
201
- for (const chunk of splitForMattermost(out.text)) {
201
+ for (const raw of splitForMattermost(out.text)) {
202
+ const chunk = out.format === "plain" ? escapeMarkdown(raw) : raw;
202
203
  const post = await this.handle.client.createPost({
203
204
  channel_id: out.channel.id,
204
205
  message: chunk,
@@ -261,6 +262,15 @@ var MattermostAdapter = class extends gateway.BasePlatformAdapter {
261
262
  `);
262
263
  }
263
264
  }
265
+ /**
266
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
267
+ *
268
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
269
+ * named as the handler's failure rather than the platform's, and delivery continues.
270
+ */
271
+ async deliver(event) {
272
+ return this.runHandler(this.inboundHandler, event);
273
+ }
264
274
  };
265
275
  function parsePostFromWS(msg) {
266
276
  const raw = msg.data?.post;
@@ -315,6 +325,9 @@ function mapMattermostError(err) {
315
325
  }
316
326
  };
317
327
  }
328
+ function escapeMarkdown(text) {
329
+ return text.replace(/([\\*_`~])/g, "\\$1");
330
+ }
318
331
 
319
332
  exports.ConfigurationError = ConfigurationError;
320
333
  exports.MattermostAdapter = MattermostAdapter;
@@ -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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AA,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","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 for (const chunk of splitForMattermost(out.text)) {\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/**\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"]}
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,CA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AA,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.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"]}
package/dist/index.d.cts CHANGED
@@ -159,6 +159,13 @@ declare class MattermostAdapter extends BasePlatformAdapter {
159
159
  getClient(): MattermostClientHandle | undefined;
160
160
  private attachWsListener;
161
161
  private processPostedEvent;
162
+ /**
163
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
164
+ *
165
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
166
+ * named as the handler's failure rather than the platform's, and delivery continues.
167
+ */
168
+ deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
162
169
  }
163
170
  /**
164
171
  * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.
package/dist/index.d.ts CHANGED
@@ -159,6 +159,13 @@ declare class MattermostAdapter extends BasePlatformAdapter {
159
159
  getClient(): MattermostClientHandle | undefined;
160
160
  private attachWsListener;
161
161
  private processPostedEvent;
162
+ /**
163
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
164
+ *
165
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
166
+ * named as the handler's failure rather than the platform's, and delivery continues.
167
+ */
168
+ deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
162
169
  }
163
170
  /**
164
171
  * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.
package/dist/index.js CHANGED
@@ -196,7 +196,8 @@ var MattermostAdapter = class extends BasePlatformAdapter {
196
196
  }
197
197
  try {
198
198
  let lastId;
199
- for (const chunk of splitForMattermost(out.text)) {
199
+ for (const raw of splitForMattermost(out.text)) {
200
+ const chunk = out.format === "plain" ? escapeMarkdown(raw) : raw;
200
201
  const post = await this.handle.client.createPost({
201
202
  channel_id: out.channel.id,
202
203
  message: chunk,
@@ -259,6 +260,15 @@ var MattermostAdapter = class extends BasePlatformAdapter {
259
260
  `);
260
261
  }
261
262
  }
263
+ /**
264
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
265
+ *
266
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
267
+ * named as the handler's failure rather than the platform's, and delivery continues.
268
+ */
269
+ async deliver(event) {
270
+ return this.runHandler(this.inboundHandler, event);
271
+ }
262
272
  };
263
273
  function parsePostFromWS(msg) {
264
274
  const raw = msg.data?.post;
@@ -313,6 +323,9 @@ function mapMattermostError(err) {
313
323
  }
314
324
  };
315
325
  }
326
+ function escapeMarkdown(text) {
327
+ return text.replace(/([\\*_`~])/g, "\\$1");
328
+ }
316
329
 
317
330
  export { ConfigurationError, MattermostAdapter, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, splitForMattermost, wsUrlFromBase };
318
331
  //# sourceMappingURL=index.js.map
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,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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ACL,IAAA,EAAM,aAAA;AAAA,MACN,OAAA,EAAS,EAAE,OAAA,KAAY,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAAA;AACxE,GACF;AACF","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 for (const chunk of splitForMattermost(out.text)) {\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/**\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"]}
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,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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AAA,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-mattermost",
3
- "version": "0.1.5",
3
+ "version": "0.2.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": {
@@ -35,8 +35,8 @@
35
35
  "CHANGELOG.md"
36
36
  ],
37
37
  "peerDependencies": {
38
- "@mattermost/client": "^9.0.0",
39
- "@theokit/gateway": ">=0.6.0 <1.0.0",
38
+ "@mattermost/client": "^9.0.0 || ^11.0.0",
39
+ "@theokit/gateway": ">=0.9.0 <1.0.0",
40
40
  "ws": "^8.0.0"
41
41
  },
42
42
  "peerDependenciesMeta": {
@@ -48,12 +48,15 @@
48
48
  }
49
49
  },
50
50
  "devDependencies": {
51
- "@theokit/sdk": "^4.53.1",
51
+ "@mattermost/client": "11.9.0",
52
+ "@stryker-mutator/core": "10",
53
+ "@stryker-mutator/vitest-runner": "10",
54
+ "@theokit/sdk": "^4.62.0",
52
55
  "tsup": "^8.5.0",
53
- "typescript": "^5.8.0",
54
- "vitest": "^4.1.8",
56
+ "typescript": "5.9.3",
57
+ "vitest": "^4.1.11",
55
58
  "zod": "^4.0.0",
56
- "@theokit/gateway": "0.7.0"
59
+ "@theokit/gateway": "0.9.0"
57
60
  },
58
61
  "publishConfig": {
59
62
  "access": "public",
@@ -62,6 +65,7 @@
62
65
  "scripts": {
63
66
  "build": "tsup",
64
67
  "typecheck": "tsc --noEmit",
65
- "test": "vitest run"
68
+ "test": "vitest run",
69
+ "test:mutation": "stryker run"
66
70
  }
67
71
  }