@theokit/gateway-mattermost 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +48 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.js.map +1 -1
- package/package.json +13 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,41 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 8cbf136: **Every published export now carries documentation.** Forty-seven public symbols shipped with no docblock at all, so a consumer hovering `DiscordAdapter`, `SlackAdapter`, `WhatsAppCloudBackend`, `ThreadStore` or any of the error classes got an empty tooltip. Coverage across the eleven packages went from 71.2% to 100% (163/163), measured over the published declarations rather than the source, because a docblock is not documentation until it survives the build.
|
|
8
|
+
|
|
9
|
+
The text says what each symbol is for and what constrains it, not what its name already says. `TelegramAdapter` records that a bot cannot enumerate its chats nor speak into one that has not spoken first. `DiscordAdapter` records that reading message content needs a privileged intent enabled in the developer portal, without which every `event.text` arrives empty and nothing says why. `WhatsAppWebBackend` records that it is unofficial and can get a number banned. `shouldDispatchSyncEvent` records that Matrix replays history on sync, which is why a freshly started bot would otherwise answer every message it can still see.
|
|
10
|
+
|
|
11
|
+
**`gateway-slack`'s README documented a type that does not exist.** Its usage example imported `GatewayMessageEvent` from `@theokit/gateway`. That name is an internal alias inside the Discord and Telegram adapters (`MessageEvent as GatewayMessageEvent`), never an export. A reader who copied the example got code that did not compile. It now imports `MessageEvent`, which is what `onInbound` actually hands the handler.
|
|
12
|
+
|
|
13
|
+
Two docblocks that attached to nothing were reattached: `acquirePidLock` in `gateway-whatsapp` had its documentation stranded thirty lines above, over a different function, and shipped undocumented as a result.
|
|
14
|
+
|
|
15
|
+
- b8ef098: **Every package now ships the licence it declares.** All twelve manifests in this repository declare `Apache-2.0`, and the repository had no `LICENSE` file at all — not at the root, and not in any package directory except `gateway-email`. So each published tarball asserted a licence while carrying none of its terms, and §4(a) of that licence requires a copy to travel with the distribution. Worse than a missing file: with no licence text anywhere, everything outside the manifests fell back to default copyright, which grants a recipient nothing.
|
|
16
|
+
|
|
17
|
+
The text is now at the repository root and inside every publishable package, byte-identical to the canonical Apache License 2.0 with the appendix filled in (`Copyright 2026 usetheo.dev`). The one pre-existing copy, in `gateway-email`, was replaced along with the rest: it carried the same truncated paragraph 4(d) found across the ecosystem, dropping "reasonable and customary use" from the NOTICE clause — a modified body under an unmodified SPDX identifier.
|
|
18
|
+
|
|
19
|
+
**The repository moved to the official `usetheokit` organization.** Existing clones and published URLs keep working through GitHub's permanent redirect; the root manifest now declares `Apache-2.0` explicitly rather than leaving the workspace root silent.
|
|
20
|
+
|
|
21
|
+
- 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
|
|
22
|
+
|
|
23
|
+
**LINE — no outbound message was ever delivered.** The adapter called the v9 SDK client with positional arguments while that client takes a single request object, so LINE received an empty request and rejected every send with a 400. Upgrade if you use this adapter at all: nothing it sent reached anyone.
|
|
24
|
+
|
|
25
|
+
**Telegram — the bot froze on long replies.** Any message over 4096 characters that began with an unclosed code span (a stray backtick) put the splitter into an infinite loop, hanging the process until it ran out of memory. Long agent answers now split correctly whatever markdown they contain.
|
|
26
|
+
|
|
27
|
+
**Mattermost — long messages silently vanished.** The adapter never split anything, so any reply over 16,383 characters was rejected by the server and the user simply saw nothing. Long replies are now split into parts Mattermost accepts.
|
|
28
|
+
|
|
29
|
+
**SMS — long messages were rejected from the hundredth part onward.** The `(i/N)` prefix outgrew the space reserved for it, pushing every later part past the provider's limit.
|
|
30
|
+
|
|
31
|
+
**Matrix and LINE — `connect()` reported success with an invalid token.** Both now verify the credential with the server before returning `true`, so a wrong token fails at startup instead of silently receiving nothing forever.
|
|
32
|
+
|
|
33
|
+
**Email and Teams — the bot could go permanently deaf.** Replacing an inbound handler and then disposing of the previous one removed the new handler as well, and the gateway stopped receiving messages with nothing logged.
|
|
34
|
+
|
|
35
|
+
Also: a `pre_inbound` hook that threw put its raw error text into the user's chat, which could expose internal details such as connection strings or tokens. Users now see only which hook failed; the detail goes to the server log, redacted.
|
|
36
|
+
|
|
37
|
+
WhatsApp additionally stops opening a second session when `connect()` is called twice, and its group mention filter no longer treats unrelated digits scattered through a message as a mention of the bot.
|
|
38
|
+
|
|
3
39
|
## 0.1.2
|
|
4
40
|
|
|
5
41
|
### Patch Changes
|
package/dist/index.cjs.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":["GatewayConfigurationError","chunkText","BasePlatformAdapter"],"mappings":";;;;;AAYO,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;AAEO,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;;;ACcA,eAAe,cAAA,GAA4C;AACzD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,OAAO,oBAAoB,CAAA;AAC7C,IAAA,OAAO,GAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,qBAAqB,oBAAoB,CAAA;AAAA,EACrD;AACF;AAgBA,eAAsB,kBAAkB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AAA,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\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-mattermost\", opts);\n }\n}\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\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\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\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\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\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,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AAI,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","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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -104,6 +104,13 @@ interface ConnectOptions {
|
|
|
104
104
|
readonly baseUrl: string;
|
|
105
105
|
readonly accessToken: string;
|
|
106
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Authenticate against a Mattermost server and open the websocket that carries inbound posts.
|
|
109
|
+
*
|
|
110
|
+
* The SDK is loaded lazily, so a project that installs this package without using it never pays for
|
|
111
|
+
* the dependency. Returns the handle every other function here takes — client, websocket and the
|
|
112
|
+
* channel cache, kept together because they share a lifetime.
|
|
113
|
+
*/
|
|
107
114
|
declare function connectMattermost(opts: ConnectOptions): Promise<MattermostClientHandle>;
|
|
108
115
|
/**
|
|
109
116
|
* Convert REST base URL to WebSocket URL:
|
|
@@ -113,6 +120,13 @@ declare function connectMattermost(opts: ConnectOptions): Promise<MattermostClie
|
|
|
113
120
|
* @public — exported for unit tests + consumer-side reuse.
|
|
114
121
|
*/
|
|
115
122
|
declare function wsUrlFromBase(baseUrl: string): string;
|
|
123
|
+
/**
|
|
124
|
+
* Fetch a channel by id, remembering the answer on the handle.
|
|
125
|
+
*
|
|
126
|
+
* Normalising an inbound post needs the channel's type, and a busy channel would otherwise cost one
|
|
127
|
+
* API call per message. Returns `undefined` rather than throwing when the channel cannot be read —
|
|
128
|
+
* a post from a channel the bot cannot see is a normal event, not a failure.
|
|
129
|
+
*/
|
|
116
130
|
declare function getChannelCached(handle: MattermostClientHandle, channelId: string): Promise<MattermostChannel | undefined>;
|
|
117
131
|
|
|
118
132
|
/**
|
|
@@ -155,10 +169,25 @@ declare function parsePostFromWS(msg: WSMessage): MattermostPost | undefined;
|
|
|
155
169
|
|
|
156
170
|
/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
|
|
157
171
|
type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;
|
|
172
|
+
/**
|
|
173
|
+
* Misconfiguration of this adapter, raised before any network call.
|
|
174
|
+
*
|
|
175
|
+
* Extends the shared core base so every gateway package reports configuration faults in one shape:
|
|
176
|
+
* a structured `code` the caller can branch on, tagged with `"gateway-mattermost"` as the origin. A
|
|
177
|
+
* missing credential or an unsupported option is a programmer error, not a transient failure —
|
|
178
|
+
* these are never retried.
|
|
179
|
+
*/
|
|
158
180
|
declare class ConfigurationError extends GatewayConfigurationError {
|
|
159
181
|
readonly name = "ConfigurationError";
|
|
160
182
|
constructor(opts: ConfigurationErrorOptions);
|
|
161
183
|
}
|
|
184
|
+
/**
|
|
185
|
+
* The platform SDK this adapter needs is declared as a peer dependency and is not installed.
|
|
186
|
+
*
|
|
187
|
+
* Raised at connect time rather than at import, so a project that installs several gateway packages
|
|
188
|
+
* only pays for the SDKs of the ones it actually starts. The message names the exact package and
|
|
189
|
+
* the command that installs it.
|
|
190
|
+
*/
|
|
162
191
|
declare class SDKNotInstalledError extends ConfigurationError {
|
|
163
192
|
constructor(pkgName: string);
|
|
164
193
|
}
|
|
@@ -189,6 +218,13 @@ interface ShouldRespondOptions {
|
|
|
189
218
|
readonly botUsername: string;
|
|
190
219
|
readonly requireMention: boolean;
|
|
191
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* Decide whether the bot should answer a post.
|
|
223
|
+
*
|
|
224
|
+
* Three rules in order: never answer itself (the loop guard), always answer a direct message, and in
|
|
225
|
+
* a channel answer only when mentioned unless `requireMention` is turned off. The mention default
|
|
226
|
+
* is what keeps a bot added to a busy channel from replying to every message in it.
|
|
227
|
+
*/
|
|
192
228
|
declare function shouldRespond(opts: ShouldRespondOptions): boolean;
|
|
193
229
|
/**
|
|
194
230
|
* Word-boundary match for `@${botUsername}`. Word boundaries land at
|
|
@@ -210,7 +246,19 @@ declare function hasMentionWithBoundary(text: string, botUsername: string): bool
|
|
|
210
246
|
*/
|
|
211
247
|
|
|
212
248
|
declare function normalizeMattermostType(channel: MattermostChannel | undefined): "D" | "G" | "O" | "P" | (string & {});
|
|
249
|
+
/**
|
|
250
|
+
* Map Mattermost's channel type to the gateway's conversation kind.
|
|
251
|
+
*
|
|
252
|
+
* A post carrying a root id is a threaded reply whatever channel it sits in, so that wins over the
|
|
253
|
+
* channel's own type; `"D"` is a direct message, and everything else is treated as a group.
|
|
254
|
+
*/
|
|
213
255
|
declare function mapChannelType(rawType: string, hasRootId: boolean): "dm" | "group" | "thread";
|
|
256
|
+
/**
|
|
257
|
+
* Turn a Mattermost post into a `MattermostMessageEvent`.
|
|
258
|
+
*
|
|
259
|
+
* `channel` and `senderUsername` are optional because both are fetched separately and either can be
|
|
260
|
+
* unavailable; the event is still produced, with the conversation kind falling back to a group.
|
|
261
|
+
*/
|
|
214
262
|
declare function postToMessageEvent(post: MattermostPost, channel: MattermostChannel | undefined, senderUsername: string | undefined): MattermostMessageEvent;
|
|
215
263
|
|
|
216
264
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -104,6 +104,13 @@ interface ConnectOptions {
|
|
|
104
104
|
readonly baseUrl: string;
|
|
105
105
|
readonly accessToken: string;
|
|
106
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Authenticate against a Mattermost server and open the websocket that carries inbound posts.
|
|
109
|
+
*
|
|
110
|
+
* The SDK is loaded lazily, so a project that installs this package without using it never pays for
|
|
111
|
+
* the dependency. Returns the handle every other function here takes — client, websocket and the
|
|
112
|
+
* channel cache, kept together because they share a lifetime.
|
|
113
|
+
*/
|
|
107
114
|
declare function connectMattermost(opts: ConnectOptions): Promise<MattermostClientHandle>;
|
|
108
115
|
/**
|
|
109
116
|
* Convert REST base URL to WebSocket URL:
|
|
@@ -113,6 +120,13 @@ declare function connectMattermost(opts: ConnectOptions): Promise<MattermostClie
|
|
|
113
120
|
* @public — exported for unit tests + consumer-side reuse.
|
|
114
121
|
*/
|
|
115
122
|
declare function wsUrlFromBase(baseUrl: string): string;
|
|
123
|
+
/**
|
|
124
|
+
* Fetch a channel by id, remembering the answer on the handle.
|
|
125
|
+
*
|
|
126
|
+
* Normalising an inbound post needs the channel's type, and a busy channel would otherwise cost one
|
|
127
|
+
* API call per message. Returns `undefined` rather than throwing when the channel cannot be read —
|
|
128
|
+
* a post from a channel the bot cannot see is a normal event, not a failure.
|
|
129
|
+
*/
|
|
116
130
|
declare function getChannelCached(handle: MattermostClientHandle, channelId: string): Promise<MattermostChannel | undefined>;
|
|
117
131
|
|
|
118
132
|
/**
|
|
@@ -155,10 +169,25 @@ declare function parsePostFromWS(msg: WSMessage): MattermostPost | undefined;
|
|
|
155
169
|
|
|
156
170
|
/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
|
|
157
171
|
type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;
|
|
172
|
+
/**
|
|
173
|
+
* Misconfiguration of this adapter, raised before any network call.
|
|
174
|
+
*
|
|
175
|
+
* Extends the shared core base so every gateway package reports configuration faults in one shape:
|
|
176
|
+
* a structured `code` the caller can branch on, tagged with `"gateway-mattermost"` as the origin. A
|
|
177
|
+
* missing credential or an unsupported option is a programmer error, not a transient failure —
|
|
178
|
+
* these are never retried.
|
|
179
|
+
*/
|
|
158
180
|
declare class ConfigurationError extends GatewayConfigurationError {
|
|
159
181
|
readonly name = "ConfigurationError";
|
|
160
182
|
constructor(opts: ConfigurationErrorOptions);
|
|
161
183
|
}
|
|
184
|
+
/**
|
|
185
|
+
* The platform SDK this adapter needs is declared as a peer dependency and is not installed.
|
|
186
|
+
*
|
|
187
|
+
* Raised at connect time rather than at import, so a project that installs several gateway packages
|
|
188
|
+
* only pays for the SDKs of the ones it actually starts. The message names the exact package and
|
|
189
|
+
* the command that installs it.
|
|
190
|
+
*/
|
|
162
191
|
declare class SDKNotInstalledError extends ConfigurationError {
|
|
163
192
|
constructor(pkgName: string);
|
|
164
193
|
}
|
|
@@ -189,6 +218,13 @@ interface ShouldRespondOptions {
|
|
|
189
218
|
readonly botUsername: string;
|
|
190
219
|
readonly requireMention: boolean;
|
|
191
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* Decide whether the bot should answer a post.
|
|
223
|
+
*
|
|
224
|
+
* Three rules in order: never answer itself (the loop guard), always answer a direct message, and in
|
|
225
|
+
* a channel answer only when mentioned unless `requireMention` is turned off. The mention default
|
|
226
|
+
* is what keeps a bot added to a busy channel from replying to every message in it.
|
|
227
|
+
*/
|
|
192
228
|
declare function shouldRespond(opts: ShouldRespondOptions): boolean;
|
|
193
229
|
/**
|
|
194
230
|
* Word-boundary match for `@${botUsername}`. Word boundaries land at
|
|
@@ -210,7 +246,19 @@ declare function hasMentionWithBoundary(text: string, botUsername: string): bool
|
|
|
210
246
|
*/
|
|
211
247
|
|
|
212
248
|
declare function normalizeMattermostType(channel: MattermostChannel | undefined): "D" | "G" | "O" | "P" | (string & {});
|
|
249
|
+
/**
|
|
250
|
+
* Map Mattermost's channel type to the gateway's conversation kind.
|
|
251
|
+
*
|
|
252
|
+
* A post carrying a root id is a threaded reply whatever channel it sits in, so that wins over the
|
|
253
|
+
* channel's own type; `"D"` is a direct message, and everything else is treated as a group.
|
|
254
|
+
*/
|
|
213
255
|
declare function mapChannelType(rawType: string, hasRootId: boolean): "dm" | "group" | "thread";
|
|
256
|
+
/**
|
|
257
|
+
* Turn a Mattermost post into a `MattermostMessageEvent`.
|
|
258
|
+
*
|
|
259
|
+
* `channel` and `senderUsername` are optional because both are fetched separately and either can be
|
|
260
|
+
* unavailable; the event is still produced, with the conversation kind falling back to a group.
|
|
261
|
+
*/
|
|
214
262
|
declare function postToMessageEvent(post: MattermostPost, channel: MattermostChannel | undefined, senderUsername: string | undefined): MattermostMessageEvent;
|
|
215
263
|
|
|
216
264
|
/**
|
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":";;;AAYO,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;AAEO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA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AAA,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","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\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-mattermost\", opts);\n }\n}\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\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\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\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\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\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,eAAe,cAAA,GAA4C;AACzD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,OAAO,oBAAoB,CAAA;AAC7C,IAAA,OAAO,GAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,qBAAqB,oBAAoB,CAAA;AAAA,EACrD;AACF;AAuBA,eAAsB,kBAAkB,IAAA,EAAuD;AAC7F,EAAA,MAAM,GAAA,GAAM,MAAM,cAAA,EAAe;AACjC,EAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,OAAA,EAAQ;AAC/B,EAAA,MAAA,CAAO,MAAA,CAAO,KAAK,OAAO,CAAA;AAC1B,EAAA,MAAA,CAAO,QAAA,CAAS,KAAK,WAAW,CAAA;AAChC,EAAA,MAAM,EAAA,GAAK,MAAM,MAAA,CAAO,KAAA,E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ACrE,UAAU,MAAA,CAAO;AAAA,KACnB;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAOA,SAAS,mBAAmB,GAAA,EAA0B;AACpD,EAAA,MAAM,CAAA,GAAI,GAAA;AACV,EAAA,MAAM,MAAA,GAAS,EAAE,WAAA,IAAe,CAAA;AAChC,EAAA,IAAI,WAAW,GAAA,EAAK;AAClB,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,cAAc,OAAA,EAAS,CAAA,CAAE,WAAW,uBAAA;AAAwB,KAC7E;AAAA,EACF;AACA,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,MAAA,KAAW,GAAA,EAAK;AACpC,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,mBAAA;AAAA,QACN,OAAA,EAAS,EAAE,OAAA,IAAW;AAAA;AACxB,KACF;AAAA,EACF;AACA,EAAA,IAAI,WAAW,GAAA,EAAK;AAClB,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,mBAAmB,OAAA,EAAS,CAAA,CAAE,WAAW,6BAAA;AAA8B,KACxF;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO;AAAA,MACL,IAAA,EAAM,aAAA;AAAA,MACN,OAAA,EAAS,EAAE,OAAA,KAAY,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAAA;AACxE,GACF;AACF","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"]}
|
package/package.json
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway-mattermost",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Mattermost platform adapter for @theokit/gateway. WebSocket gateway + REST. ADRs D397-D404.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/usetheokit/theokit-gateways.git",
|
|
9
|
+
"directory": "packages/gateway-mattermost"
|
|
10
|
+
},
|
|
6
11
|
"type": "module",
|
|
7
12
|
"engines": {
|
|
8
13
|
"node": ">=22.12.0"
|
|
@@ -31,9 +36,9 @@
|
|
|
31
36
|
],
|
|
32
37
|
"peerDependencies": {
|
|
33
38
|
"@mattermost/client": "^9.0.0",
|
|
39
|
+
"@theokit/gateway": ">=0.6.0 <1.0.0",
|
|
34
40
|
"@theokit/sdk": "^2.18.0",
|
|
35
|
-
"ws": "^8.0.0"
|
|
36
|
-
"@theokit/gateway": "^0.5.1"
|
|
41
|
+
"ws": "^8.0.0"
|
|
37
42
|
},
|
|
38
43
|
"peerDependenciesMeta": {
|
|
39
44
|
"@mattermost/client": {
|
|
@@ -49,7 +54,11 @@
|
|
|
49
54
|
"typescript": "^5.8.0",
|
|
50
55
|
"vitest": "^4.1.8",
|
|
51
56
|
"zod": "^4.0.0",
|
|
52
|
-
"@theokit/gateway": "0.
|
|
57
|
+
"@theokit/gateway": "0.6.0"
|
|
58
|
+
},
|
|
59
|
+
"publishConfig": {
|
|
60
|
+
"access": "public",
|
|
61
|
+
"provenance": true
|
|
53
62
|
},
|
|
54
63
|
"scripts": {
|
|
55
64
|
"build": "tsup",
|