@theokit/gateway-mattermost 0.1.1 → 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 CHANGED
@@ -1,5 +1,69 @@
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
+
39
+ ## 0.1.2
40
+
41
+ ### Patch Changes
42
+
43
+ - 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.
44
+
45
+ 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.
46
+
47
+ **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.
48
+
49
+ - 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
50
+
51
+ **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.
52
+
53
+ **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.
54
+
55
+ **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.
56
+
57
+ **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.
58
+
59
+ **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.
60
+
61
+ **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.
62
+
63
+ 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.
64
+
65
+ 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.
66
+
3
67
  ## 0.1.1
4
68
 
5
69
  ### Patch Changes
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 usetheo.dev
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/index.cjs CHANGED
@@ -3,16 +3,10 @@
3
3
  var gateway = require('@theokit/gateway');
4
4
 
5
5
  // src/adapter.ts
6
-
7
- // src/errors.ts
8
- var ConfigurationError = class extends Error {
6
+ var ConfigurationError = class extends gateway.GatewayConfigurationError {
9
7
  name = "ConfigurationError";
10
- code;
11
- detail;
12
8
  constructor(opts) {
13
- super(opts.message ?? `gateway-mattermost: ${opts.code}`);
14
- this.code = opts.code;
15
- this.detail = opts.detail;
9
+ super("gateway-mattermost", opts);
16
10
  }
17
11
  };
18
12
  var SDKNotInstalledError = class extends ConfigurationError {
@@ -128,6 +122,17 @@ function postToMessageEvent(post, channel, senderUsername) {
128
122
  }
129
123
  };
130
124
  }
125
+ var MATTERMOST_MAX_POST = 16383;
126
+ var SAFE_CHUNK = 16e3;
127
+ function splitForMattermost(text) {
128
+ return gateway.chunkText(text, {
129
+ limit: MATTERMOST_MAX_POST,
130
+ safeLimit: SAFE_CHUNK,
131
+ boundaries: ["\n\n", "\n", " "],
132
+ lastResort: "last-boundary",
133
+ stripLeading: /^\s+/
134
+ });
135
+ }
131
136
 
132
137
  // src/adapter.ts
133
138
  var MattermostAdapter = class extends gateway.BasePlatformAdapter {
@@ -192,12 +197,16 @@ var MattermostAdapter = class extends gateway.BasePlatformAdapter {
192
197
  };
193
198
  }
194
199
  try {
195
- const post = await this.handle.client.createPost({
196
- channel_id: out.channel.id,
197
- message: out.text,
198
- ...out.channel.type === "thread" && out.channel.topicId !== void 0 ? { root_id: out.channel.topicId } : {}
199
- });
200
- return { ok: true, messageId: post.id };
200
+ let lastId;
201
+ for (const chunk of splitForMattermost(out.text)) {
202
+ const post = await this.handle.client.createPost({
203
+ channel_id: out.channel.id,
204
+ message: chunk,
205
+ ...out.channel.type === "thread" && out.channel.topicId !== void 0 ? { root_id: out.channel.topicId } : {}
206
+ });
207
+ lastId = post.id;
208
+ }
209
+ return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
201
210
  } catch (err) {
202
211
  return mapMattermostError(err);
203
212
  }
@@ -318,6 +327,7 @@ exports.normalizeMattermostType = normalizeMattermostType;
318
327
  exports.parsePostFromWS = parsePostFromWS;
319
328
  exports.postToMessageEvent = postToMessageEvent;
320
329
  exports.shouldRespond = shouldRespond;
330
+ exports.splitForMattermost = splitForMattermost;
321
331
  exports.wsUrlFromBase = wsUrlFromBase;
322
332
  //# sourceMappingURL=index.cjs.map
323
333
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/filters.ts","../src/normalize.ts","../src/adapter.ts"],"names":["BasePlatformAdapter"],"mappings":";;;;;;;AAWO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAC1B,IAAA,GAAO,oBAAA;AAAA,EAChB,IAAA;AAAA,EACA,MAAA;AAAA,EACT,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,IAAA,CAAK,OAAA,IAAW,CAAA,oBAAA,EAAuB,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AACxD,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AAAA,EACrB;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,MAC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AAW,OAAO,SAAA,GAAY,CAAA;AAAA,MACrE,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.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-mattermost`.\n */\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport interface ConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\nexport class ConfigurationError extends Error {\n override readonly name = \"ConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n constructor(opts: ConfigurationErrorOptions) {\n super(opts.message ?? `gateway-mattermost: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\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 * `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 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 const post = await this.handle.client.createPost({\n channel_id: out.channel.id,\n message: out.text,\n ...(out.channel.type === \"thread\" && out.channel.topicId !== undefined\n ? { root_id: out.channel.topicId }\n : {}),\n });\n return { ok: true, messageId: post.id };\n } catch (err) {\n return mapMattermostError(err);\n }\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */\n getClient(): MattermostClientHandle | undefined {\n return this.handle;\n }\n\n private attachWsListener(): void {\n if (this.handle === undefined) return;\n const handle = this.handle;\n this.wsListener = (msg: WSMessage) => {\n if (msg.event !== \"posted\") return;\n void this.processPostedEvent(handle, msg).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] processPostedEvent failed: ${m}\\n`);\n });\n };\n handle.ws.addMessageListener(this.wsListener);\n }\n\n private async processPostedEvent(handle: MattermostClientHandle, msg: WSMessage): Promise<void> {\n const post = parsePostFromWS(msg);\n if (post === undefined) return;\n const channel = await getChannelCached(handle, post.channel_id);\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n const requireMention = this.opts.requireMention ?? true;\n if (\n !shouldRespond({\n post,\n channelType,\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention,\n })\n ) {\n return;\n }\n const senderUsername =\n typeof msg.data.sender_name === \"string\"\n ? (msg.data.sender_name as string).replace(/^@/, \"\")\n : undefined;\n const event = postToMessageEvent(post, channel, senderUsername);\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] handler threw: ${m}\\n`);\n }\n }\n}\n\n/**\n * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.\n *\n * @public — exposed so consumers can drive their own WS listener too.\n */\nexport function parsePostFromWS(msg: WSMessage): MattermostPost | undefined {\n const raw = msg.data?.post;\n if (typeof raw !== \"string\") return undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<MattermostPost>;\n if (\n typeof parsed.id !== \"string\" ||\n typeof parsed.user_id !== \"string\" ||\n typeof parsed.channel_id !== \"string\" ||\n typeof parsed.message !== \"string\"\n ) {\n return undefined;\n }\n return {\n id: parsed.id,\n user_id: parsed.user_id,\n channel_id: parsed.channel_id,\n root_id: typeof parsed.root_id === \"string\" ? parsed.root_id : \"\",\n message: parsed.message,\n create_at: typeof parsed.create_at === \"number\" ? parsed.create_at : 0,\n metadata: parsed.metadata,\n };\n } catch {\n return undefined;\n }\n}\n\ninterface MattermostRestError {\n status_code?: number;\n message?: string;\n}\n\nfunction mapMattermostError(err: unknown): SendResult {\n const e = err as MattermostRestError;\n const status = e.status_code ?? 0;\n if (status === 429) {\n return {\n ok: false,\n error: { code: \"rate_limit\", message: e.message ?? \"Mattermost rate limit\" },\n };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: {\n code: \"permission_denied\",\n message: e.message ?? \"Mattermost auth/permission error\",\n },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Mattermost rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/filters.ts","../src/normalize.ts","../src/split.ts","../src/adapter.ts"],"names":["GatewayConfigurationError","chunkText","BasePlatformAdapter"],"mappings":";;;;;AAoBO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,sBAAsB,IAAI,CAAA;AAAA,EAClC;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,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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
@@ -1,4 +1,4 @@
1
- import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, MattermostMessageEvent } from '@theokit/gateway';
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, MattermostMessageEvent } from '@theokit/gateway';
2
2
 
3
3
  /**
4
4
  * Public options + internal Mattermost shape narrowing.
@@ -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
  /**
@@ -148,19 +162,32 @@ declare function parsePostFromWS(msg: WSMessage): MattermostPost | undefined;
148
162
 
149
163
  /**
150
164
  * Typed errors for `@theokit/gateway-mattermost`.
165
+ *
166
+ * `ConfigurationError` extends the shared core `GatewayConfigurationError`
167
+ * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).
151
168
  */
169
+
152
170
  /** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
153
- interface ConfigurationErrorOptions {
154
- readonly code: string;
155
- readonly message?: string;
156
- readonly detail?: string;
157
- }
158
- declare class ConfigurationError extends Error {
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
+ */
180
+ declare class ConfigurationError extends GatewayConfigurationError {
159
181
  readonly name = "ConfigurationError";
160
- readonly code: string;
161
- readonly detail: string | undefined;
162
182
  constructor(opts: ConfigurationErrorOptions);
163
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
+ */
164
191
  declare class SDKNotInstalledError extends ConfigurationError {
165
192
  constructor(pkgName: string);
166
193
  }
@@ -191,6 +218,13 @@ interface ShouldRespondOptions {
191
218
  readonly botUsername: string;
192
219
  readonly requireMention: boolean;
193
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
+ */
194
228
  declare function shouldRespond(opts: ShouldRespondOptions): boolean;
195
229
  /**
196
230
  * Word-boundary match for `@${botUsername}`. Word boundaries land at
@@ -212,7 +246,42 @@ declare function hasMentionWithBoundary(text: string, botUsername: string): bool
212
246
  */
213
247
 
214
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
+ */
215
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
+ */
216
262
  declare function postToMessageEvent(post: MattermostPost, channel: MattermostChannel | undefined, senderUsername: string | undefined): MattermostMessageEvent;
217
263
 
218
- export { ConfigurationError, MattermostAdapter, type MattermostAdapterOptions, type MattermostChannel, type MattermostPost, type MattermostUser, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, wsUrlFromBase };
264
+ /**
265
+ * `splitForMattermost` — segment outbound text to Mattermost's post cap.
266
+ *
267
+ * This package shipped without any splitting at all, alone among the ten
268
+ * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent
269
+ * reply longer than the cap came back:
270
+ *
271
+ * HTTP 400 — "Post Message property is longer than the maximum permitted length."
272
+ *
273
+ * and the user saw nothing. No unit test could catch it, because there was no
274
+ * cap in the code to assert against; it took a real server to answer 400.
275
+ * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,
276
+ * 16384 is refused.
277
+ *
278
+ * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This
279
+ * splits on code points via the core chunker, which is the closest the JS side
280
+ * gets without walking graphemes; a message of astral-plane characters could
281
+ * still exceed the server's count, which is why the window leaves headroom.
282
+ *
283
+ * @internal
284
+ */
285
+ declare function splitForMattermost(text: string): string[];
286
+
287
+ export { ConfigurationError, MattermostAdapter, type MattermostAdapterOptions, type MattermostChannel, type MattermostPost, type MattermostUser, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, splitForMattermost, wsUrlFromBase };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, MattermostMessageEvent } from '@theokit/gateway';
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, MattermostMessageEvent } from '@theokit/gateway';
2
2
 
3
3
  /**
4
4
  * Public options + internal Mattermost shape narrowing.
@@ -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
  /**
@@ -148,19 +162,32 @@ declare function parsePostFromWS(msg: WSMessage): MattermostPost | undefined;
148
162
 
149
163
  /**
150
164
  * Typed errors for `@theokit/gateway-mattermost`.
165
+ *
166
+ * `ConfigurationError` extends the shared core `GatewayConfigurationError`
167
+ * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).
151
168
  */
169
+
152
170
  /** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
153
- interface ConfigurationErrorOptions {
154
- readonly code: string;
155
- readonly message?: string;
156
- readonly detail?: string;
157
- }
158
- declare class ConfigurationError extends Error {
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
+ */
180
+ declare class ConfigurationError extends GatewayConfigurationError {
159
181
  readonly name = "ConfigurationError";
160
- readonly code: string;
161
- readonly detail: string | undefined;
162
182
  constructor(opts: ConfigurationErrorOptions);
163
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
+ */
164
191
  declare class SDKNotInstalledError extends ConfigurationError {
165
192
  constructor(pkgName: string);
166
193
  }
@@ -191,6 +218,13 @@ interface ShouldRespondOptions {
191
218
  readonly botUsername: string;
192
219
  readonly requireMention: boolean;
193
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
+ */
194
228
  declare function shouldRespond(opts: ShouldRespondOptions): boolean;
195
229
  /**
196
230
  * Word-boundary match for `@${botUsername}`. Word boundaries land at
@@ -212,7 +246,42 @@ declare function hasMentionWithBoundary(text: string, botUsername: string): bool
212
246
  */
213
247
 
214
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
+ */
215
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
+ */
216
262
  declare function postToMessageEvent(post: MattermostPost, channel: MattermostChannel | undefined, senderUsername: string | undefined): MattermostMessageEvent;
217
263
 
218
- export { ConfigurationError, MattermostAdapter, type MattermostAdapterOptions, type MattermostChannel, type MattermostPost, type MattermostUser, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, wsUrlFromBase };
264
+ /**
265
+ * `splitForMattermost` — segment outbound text to Mattermost's post cap.
266
+ *
267
+ * This package shipped without any splitting at all, alone among the ten
268
+ * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent
269
+ * reply longer than the cap came back:
270
+ *
271
+ * HTTP 400 — "Post Message property is longer than the maximum permitted length."
272
+ *
273
+ * and the user saw nothing. No unit test could catch it, because there was no
274
+ * cap in the code to assert against; it took a real server to answer 400.
275
+ * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,
276
+ * 16384 is refused.
277
+ *
278
+ * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This
279
+ * splits on code points via the core chunker, which is the closest the JS side
280
+ * gets without walking graphemes; a message of astral-plane characters could
281
+ * still exceed the server's count, which is why the window leaves headroom.
282
+ *
283
+ * @internal
284
+ */
285
+ declare function splitForMattermost(text: string): string[];
286
+
287
+ export { ConfigurationError, MattermostAdapter, type MattermostAdapterOptions, type MattermostChannel, type MattermostPost, type MattermostUser, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, splitForMattermost, wsUrlFromBase };
package/dist/index.js CHANGED
@@ -1,16 +1,10 @@
1
- import { BasePlatformAdapter } from '@theokit/gateway';
1
+ import { GatewayConfigurationError, chunkText, BasePlatformAdapter } from '@theokit/gateway';
2
2
 
3
3
  // src/adapter.ts
4
-
5
- // src/errors.ts
6
- var ConfigurationError = class extends Error {
4
+ var ConfigurationError = class extends GatewayConfigurationError {
7
5
  name = "ConfigurationError";
8
- code;
9
- detail;
10
6
  constructor(opts) {
11
- super(opts.message ?? `gateway-mattermost: ${opts.code}`);
12
- this.code = opts.code;
13
- this.detail = opts.detail;
7
+ super("gateway-mattermost", opts);
14
8
  }
15
9
  };
16
10
  var SDKNotInstalledError = class extends ConfigurationError {
@@ -126,6 +120,17 @@ function postToMessageEvent(post, channel, senderUsername) {
126
120
  }
127
121
  };
128
122
  }
123
+ var MATTERMOST_MAX_POST = 16383;
124
+ var SAFE_CHUNK = 16e3;
125
+ function splitForMattermost(text) {
126
+ return chunkText(text, {
127
+ limit: MATTERMOST_MAX_POST,
128
+ safeLimit: SAFE_CHUNK,
129
+ boundaries: ["\n\n", "\n", " "],
130
+ lastResort: "last-boundary",
131
+ stripLeading: /^\s+/
132
+ });
133
+ }
129
134
 
130
135
  // src/adapter.ts
131
136
  var MattermostAdapter = class extends BasePlatformAdapter {
@@ -190,12 +195,16 @@ var MattermostAdapter = class extends BasePlatformAdapter {
190
195
  };
191
196
  }
192
197
  try {
193
- const post = await this.handle.client.createPost({
194
- channel_id: out.channel.id,
195
- message: out.text,
196
- ...out.channel.type === "thread" && out.channel.topicId !== void 0 ? { root_id: out.channel.topicId } : {}
197
- });
198
- return { ok: true, messageId: post.id };
198
+ let lastId;
199
+ for (const chunk of splitForMattermost(out.text)) {
200
+ const post = await this.handle.client.createPost({
201
+ channel_id: out.channel.id,
202
+ message: chunk,
203
+ ...out.channel.type === "thread" && out.channel.topicId !== void 0 ? { root_id: out.channel.topicId } : {}
204
+ });
205
+ lastId = post.id;
206
+ }
207
+ return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
199
208
  } catch (err) {
200
209
  return mapMattermostError(err);
201
210
  }
@@ -305,6 +314,6 @@ function mapMattermostError(err) {
305
314
  };
306
315
  }
307
316
 
308
- export { ConfigurationError, MattermostAdapter, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, wsUrlFromBase };
317
+ export { ConfigurationError, MattermostAdapter, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, splitForMattermost, wsUrlFromBase };
309
318
  //# sourceMappingURL=index.js.map
310
319
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/filters.ts","../src/normalize.ts","../src/adapter.ts"],"names":[],"mappings":";;;;;AAWO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAC1B,IAAA,GAAO,oBAAA;AAAA,EAChB,IAAA;AAAA,EACA,MAAA;AAAA,EACT,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,IAAA,CAAK,OAAA,IAAW,CAAA,oBAAA,EAAuB,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AACxD,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AAAA,EACrB;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;;;ACWA,eAAe,cAAA,GAA4C;AACzD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,OAAO,oBAAoB,CAAA;AAC7C,IAAA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A,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\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport interface ConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\nexport class ConfigurationError extends Error {\n override readonly name = \"ConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n constructor(opts: ConfigurationErrorOptions) {\n super(opts.message ?? `gateway-mattermost: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\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 * `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 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 const post = await this.handle.client.createPost({\n channel_id: out.channel.id,\n message: out.text,\n ...(out.channel.type === \"thread\" && out.channel.topicId !== undefined\n ? { root_id: out.channel.topicId }\n : {}),\n });\n return { ok: true, messageId: post.id };\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,MAA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A,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.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.4.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.4.1"
57
+ "@theokit/gateway": "0.6.0"
58
+ },
59
+ "publishConfig": {
60
+ "access": "public",
61
+ "provenance": true
53
62
  },
54
63
  "scripts": {
55
64
  "build": "tsup",