@theokit/gateway-matrix 0.1.0 → 0.1.2

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,45 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 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.
8
+
9
+ 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.
10
+
11
+ **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.
12
+
13
+ - 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
14
+
15
+ **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.
16
+
17
+ **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.
18
+
19
+ **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.
20
+
21
+ **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.
22
+
23
+ **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.
24
+
25
+ **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.
26
+
27
+ 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.
28
+
29
+ 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.
30
+
31
+ - 7ccb21b: Two defects that only a real server could show, both found by the live suites.
32
+
33
+ **Email — the bot re-answered its whole unread inbox after every restart.** Nothing ever flagged a message as read on the server, and the only record of what had already been handled lived in memory and was thrown away on disconnect. So each reconnect fetched the entire unread backlog again and delivered all of it a second time: on the test mailbox, 166 messages meant 166 duplicate replies to the people who had written in. It got worse over time, because the backlog only ever grew. Messages are now flagged on the server once handled, in a single command per batch, so a restart picks up where it left off.
34
+
35
+ **Matrix — `disconnect()` could kill your process.** Shutting the client down cancels the requests it has open, and one of those cancellations surfaced as an unhandled rejection, which Node treats as fatal. An application that reconnects — the well-behaved kind, with retry on connection loss — could be terminated by its own clean shutdown. Measured against a real homeserver before the fix: 7 occurrences in 8 connect/disconnect cycles. Cancellations during shutdown are now contained, while any cancellation you request yourself through `getClient()` still reaches you unchanged.
36
+
37
+ ## 0.1.1
38
+
39
+ ### Patch Changes
40
+
41
+ - e926cd9: Align the gateway cluster to the hardened `@theokit/sdk` 2.18.0 Harness (ecosystem M6). Bumped the `@theokit/sdk` peer + dev dependency from `^1.9.0` to `^2.18.0` across all 11 packages. The only consumed SDK surface is `Security.redact` (in the gateway core runner) — a stable public API (ADR D68) unchanged across 1.x→2.x — so the alignment is a pin bump, not a migration. Validated: all 11 packages typecheck + build + test green against 2.18.0 (543 tests passed). No dead/unwired surfaces (`no-stubs-no-mocks-no-wired` checklist clean).
42
+
3
43
  ## 2.0.0
4
44
 
5
45
  ### 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-matrix: ${opts.code}`);
14
- this.code = opts.code;
15
- this.detail = opts.detail;
9
+ super("gateway-matrix", opts);
16
10
  }
17
11
  };
18
12
  var SDKNotInstalledError = class extends ConfigurationError {
@@ -137,6 +131,30 @@ var MatrixAdapter = class extends gateway.BasePlatformAdapter {
137
131
  aliasCache = new AliasCache();
138
132
  connected = false;
139
133
  warnedEncrypted = /* @__PURE__ */ new Set();
134
+ /** True only between disconnect() and the next connect() — see #12. */
135
+ tearingDown = false;
136
+ /**
137
+ * `fetch` for the SDK that leaves teardown aborts unsettled instead of
138
+ * rejecting (#12).
139
+ *
140
+ * A request aborted while we are tearing the client down has no consumer left
141
+ * that could act on the outcome, so an unsettled promise costs a continuation
142
+ * and nothing else; the alternative is a rejection with no handler anywhere,
143
+ * which ends the host process. It is scoped to the teardown window on purpose:
144
+ * a consumer using the `getClient()` escape hatch (D421) may pass its own
145
+ * abort signal to `search()` or `slidingSync()` and MUST still see those
146
+ * rejections, so outside teardown every error propagates untouched.
147
+ */
148
+ teardownSafeFetch() {
149
+ const base = globalThis.fetch.bind(globalThis);
150
+ return (input, init) => base(input, init).catch((err) => {
151
+ if (this.tearingDown && isAbortError(err)) {
152
+ return new Promise(() => {
153
+ });
154
+ }
155
+ throw err;
156
+ });
157
+ }
140
158
  constructor(opts) {
141
159
  super();
142
160
  if (opts.homeserverUrl.length === 0) {
@@ -161,13 +179,17 @@ var MatrixAdapter = class extends gateway.BasePlatformAdapter {
161
179
  }
162
180
  async connect() {
163
181
  if (this.connected) return true;
182
+ this.tearingDown = false;
164
183
  try {
165
- const mod = await loadMatrixSdk();
166
- this.client = mod.createClient({
184
+ const cfg = {
167
185
  baseUrl: this.opts.homeserverUrl,
168
186
  accessToken: this.opts.accessToken,
169
- userId: this.opts.userId
170
- });
187
+ userId: this.opts.userId,
188
+ fetchFn: this.teardownSafeFetch()
189
+ };
190
+ const factory = this.opts.__clientFactory;
191
+ this.client = factory === void 0 ? (await loadMatrixSdk()).createClient(cfg) : factory(cfg);
192
+ await this.client.whoami();
171
193
  await this.client.startClient({ initialSyncLimit: INITIAL_SYNC_LIMIT });
172
194
  this.attachSync();
173
195
  this.connected = true;
@@ -181,6 +203,7 @@ var MatrixAdapter = class extends gateway.BasePlatformAdapter {
181
203
  }
182
204
  async disconnect() {
183
205
  if (!this.connected) return;
206
+ this.tearingDown = true;
184
207
  this.subscription?.unsubscribe();
185
208
  this.subscription = void 0;
186
209
  this.client?.stopClient();
@@ -286,6 +309,13 @@ var MatrixAdapter = class extends gateway.BasePlatformAdapter {
286
309
  );
287
310
  }
288
311
  };
312
+ function isAbortError(err) {
313
+ if (typeof err !== "object" || err === null) return false;
314
+ const e = err;
315
+ if (e.name === "AbortError") return true;
316
+ if (e.code === 20) return true;
317
+ return typeof e.message === "string" && /aborted/i.test(e.message);
318
+ }
289
319
  function mapMatrixError(err) {
290
320
  const e = err;
291
321
  const status = e.httpStatus ?? 0;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/alias.ts","../src/client.ts","../src/room-state.ts","../src/normalize.ts","../src/sync.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,EA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AC/F;AACA,EAAA,IAAI,WAAW,GAAA,IAAO,MAAA,KAAW,GAAA,IAAO,CAAA,CAAE,YAAY,aAAA,EAAe;AACnE,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,qBAAqB,OAAA,EAAS,CAAA,CAAE,WAAW,yBAAA;AAA0B,KACtF;AAAA,EACF;AACA,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,CAAA,CAAE,OAAA,KAAY,aAAA,EAAe;AACjD,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,aAAa,OAAA,EAAS,CAAA,CAAE,WAAW,2BAAA;AAA4B,KAChF;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-matrix`.\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-matrix: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor() {\n super({\n code: \"sdk_not_installed\",\n message:\n 'gateway-matrix: peer-dep \"matrix-js-sdk\" not installed. Run: pnpm add matrix-js-sdk',\n detail: \"matrix-js-sdk\",\n });\n }\n}\n\nexport class EncryptedRoomError extends ConfigurationError {\n constructor(roomId: string) {\n super({\n code: \"encrypted_room_unsupported\",\n message: `gateway-matrix: room ${roomId} is end-to-end encrypted (E2EE deferred to v0.2)`,\n detail: roomId,\n });\n }\n}\n","/**\n * Matrix alias resolution + caching (D419).\n *\n * Accepts:\n * - Room id (`!abc123:server`) — pass-through.\n * - Alias (`#general:server`) — resolved via `client.getRoomIdForAlias`.\n *\n * Other shapes throw `ConfigurationError({ code: \"invalid_room_ref\" })`.\n */\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/** @knipignore — minimal Client interface `AliasCache.resolve` accepts; useful for callers building their own resolver. */\nexport interface AliasResolverClient {\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n}\n\nexport class AliasCache {\n private readonly cache = new Map<string, string>();\n\n /** Returns the room id; resolves aliases via the client + caches. */\n async resolve(client: AliasResolverClient, refOrId: string): Promise<string> {\n if (refOrId.startsWith(\"!\")) return refOrId;\n if (!refOrId.startsWith(\"#\")) {\n throw new ConfigurationError({\n code: \"invalid_room_ref\",\n message: `gateway-matrix: invalid room reference ${JSON.stringify(refOrId)} — expected '!' (room id) or '#' (alias)`,\n });\n }\n const cached = this.cache.get(refOrId);\n if (cached !== undefined) return cached;\n const { room_id } = await client.getRoomIdForAlias(refOrId);\n this.cache.set(refOrId, room_id);\n return room_id;\n }\n\n /** Drop all cached resolutions. Useful for tests + admin-rename recovery. */\n clear(): void {\n this.cache.clear();\n }\n\n size(): number {\n return this.cache.size;\n }\n}\n","/**\n * Lazy `matrix-js-sdk` loader.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MatrixClientLike } from \"./sync.js\";\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport interface MatrixSdkClient extends MatrixClientLike {\n startClient(opts: { initialSyncLimit: number }): Promise<void>;\n stopClient(): void;\n sendTextMessage(roomId: string, text: string): Promise<{ event_id: string }>;\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n getRoom(roomId: string): MatrixRoomLike | null;\n isRoomEncrypted?(roomId: string): boolean;\n /** Best-effort current user id; matrix-js-sdk returns `string | null`. */\n getUserId(): string | null;\n}\n\ninterface MatrixSdkModule {\n createClient(opts: { baseUrl: string; accessToken: string; userId: string }): MatrixSdkClient;\n}\n\nexport async function loadMatrixSdk(): Promise<MatrixSdkModule> {\n try {\n const mod = await import(\"matrix-js-sdk\");\n return mod as unknown as MatrixSdkModule;\n } catch {\n throw new SDKNotInstalledError();\n }\n}\n","/**\n * Room state helpers (D416).\n *\n * Matrix has no native \"DM\" concept — DMs are rooms with 2 members.\n * The canonical heuristic: `member_count === 2 → \"dm\"`, else `\"group\"`.\n */\n\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport function detectChannelType(room: MatrixRoomLike | undefined): \"dm\" | \"group\" {\n if (room === undefined) return \"group\";\n return room.getJoinedMemberCount() === 2 ? \"dm\" : \"group\";\n}\n","/**\n * Inbound normalization: MatrixEvent + Room → MatrixMessageEvent.\n *\n * @public\n */\n\nimport type { MatrixMessageEvent } from \"@theokit/gateway\";\n\nimport { detectChannelType } from \"./room-state.js\";\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport function matrixEventToMessageEvent(\n event: MatrixEventLike,\n room: MatrixRoomLike,\n): MatrixMessageEvent | undefined {\n const eventId = event.getId();\n const sender = event.getSender();\n if (eventId === undefined || sender === undefined) return undefined;\n const channelType = detectChannelType(room);\n const content = event.getContent();\n const body = content.body ?? \"\";\n return {\n id: eventId,\n platform: \"matrix\",\n sender: { id: sender },\n channel: {\n id: room.roomId,\n type: channelType,\n },\n text: body,\n receivedAt: event.getTs(),\n matrix: {\n roomId: room.roomId,\n eventId,\n memberCount: room.getJoinedMemberCount(),\n raw: event,\n },\n };\n}\n","/**\n * Sync timeline filter (D415, EC-3 absorbed).\n *\n * Wraps `client.on(\"Room.timeline\", listener)` with 3 filters:\n *\n * 1. Drop non-`m.room.message` events (D413).\n * 2. Drop bot's own messages (loop guard, D275 mirror).\n * 3. **EC-3**: drop events older than `freshnessWindowMs` (default 60s)\n * — initial sync from `matrix-js-sdk` delivers ~10 historical events\n * per joined room, which would otherwise trigger an LLM-call storm.\n */\n\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport interface SyncFilterOpts {\n readonly botUserId: string;\n readonly freshnessWindowMs: number;\n}\n\nexport function shouldDispatchSyncEvent(\n event: MatrixEventLike,\n opts: SyncFilterOpts,\n now = Date.now(),\n): boolean {\n if (event.getType() !== \"m.room.message\") return false;\n const sender = event.getSender();\n if (sender === opts.botUserId) return false;\n if (event.getTs() < now - opts.freshnessWindowMs) return false;\n return true;\n}\n\nexport interface TimelineSubscription {\n unsubscribe(): void;\n}\n\nexport interface MatrixClientLike {\n on(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n off(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n}\n\nexport function subscribeToTimeline(\n client: MatrixClientLike,\n handler: (event: MatrixEventLike, room: MatrixRoomLike) => void,\n opts: SyncFilterOpts,\n): TimelineSubscription {\n const wrapped = (event: MatrixEventLike, room: MatrixRoomLike): void => {\n if (!shouldDispatchSyncEvent(event, opts)) return;\n handler(event, room);\n };\n client.on(\"Room.timeline\", wrapped);\n return {\n unsubscribe(): void {\n client.off(\"Room.timeline\", wrapped);\n },\n };\n}\n","/**\n * `MatrixAdapter` — implements BasePlatformAdapter over matrix-js-sdk.\n * ADRs D413-D421.\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 { AliasCache } from \"./alias.js\";\nimport { loadMatrixSdk, type MatrixSdkClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { matrixEventToMessageEvent } from \"./normalize.js\";\nimport { subscribeToTimeline, type TimelineSubscription } from \"./sync.js\";\nimport type { MatrixAdapterOptions, MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nconst DEFAULT_FRESHNESS_MS = 60_000;\nconst INITIAL_SYNC_LIMIT = 10;\n\nexport class MatrixAdapter extends BasePlatformAdapter {\n readonly platform = \"matrix\" as const;\n private readonly opts: MatrixAdapterOptions;\n private client: MatrixSdkClient | undefined;\n private subscription: TimelineSubscription | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private readonly aliasCache = new AliasCache();\n private connected = false;\n private readonly warnedEncrypted = new Set<string>();\n\n constructor(opts: MatrixAdapterOptions) {\n super();\n if (opts.homeserverUrl.length === 0) {\n throw new ConfigurationError({\n code: \"homeserver_url_required\",\n message: 'gateway-matrix: opts.homeserverUrl is empty (e.g. \"https://matrix.org\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-matrix: opts.accessToken is empty (Element → Settings → Help & About → Advanced → Access Token)\",\n });\n }\n if (opts.userId.length === 0 || !opts.userId.startsWith(\"@\")) {\n throw new ConfigurationError({\n code: \"user_id_required\",\n message: 'gateway-matrix: opts.userId must be a Matrix user id (e.g. \"@bot:matrix.org\")',\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const mod = await loadMatrixSdk();\n this.client = mod.createClient({\n baseUrl: this.opts.homeserverUrl,\n accessToken: this.opts.accessToken,\n userId: this.opts.userId,\n });\n await this.client.startClient({ initialSyncLimit: INITIAL_SYNC_LIMIT });\n this.attachSync();\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-matrix] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.subscription?.unsubscribe();\n this.subscription = undefined;\n this.client?.stopClient();\n this.client = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n this.aliasCache.clear();\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.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MatrixAdapter.connect() not called\" },\n };\n }\n try {\n const roomId = await this.aliasCache.resolve(this.client, out.channel.id);\n if (this.isEncrypted(roomId)) {\n this.warnEncryptedOnce(roomId);\n return {\n ok: false,\n error: {\n code: \"encrypted_room_unsupported\",\n message: `Matrix room ${roomId} is encrypted; E2EE deferred to v0.2`,\n },\n };\n }\n const res = await this.client.sendTextMessage(roomId, out.text);\n return { ok: true, messageId: res.event_id };\n } catch (err) {\n return mapMatrixError(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 (D421) — caller can drive matrix-js-sdk directly for advanced features. */\n getClient(): MatrixSdkClient | undefined {\n return this.client;\n }\n\n /** Used by tests to install a mock SDK client + flip connected flag. */\n _installClient(client: MatrixSdkClient): void {\n this.client = client;\n this.connected = true;\n this.attachSync();\n }\n\n private attachSync(): void {\n if (this.client === undefined) return;\n const client = this.client;\n const opts = {\n botUserId: this.opts.userId,\n freshnessWindowMs: this.opts.freshnessWindowMs ?? DEFAULT_FRESHNESS_MS,\n };\n this.subscription = subscribeToTimeline(\n client,\n (ev: MatrixEventLike, room: MatrixRoomLike) => {\n void this.dispatchTimelineEvent(ev, room).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] dispatchTimelineEvent failed: ${m}\\n`);\n });\n },\n opts,\n );\n }\n\n private async dispatchTimelineEvent(event: MatrixEventLike, room: MatrixRoomLike): Promise<void> {\n if (this.isEncrypted(room.roomId)) {\n this.warnEncryptedOnce(room.roomId);\n return;\n }\n const normalized = matrixEventToMessageEvent(event, room);\n if (normalized === undefined) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] handler threw: ${m}\\n`);\n }\n }\n\n private isEncrypted(roomId: string): boolean {\n if (this.client === undefined) return false;\n if (this.client.isRoomEncrypted === undefined) return false;\n try {\n return this.client.isRoomEncrypted(roomId);\n } catch {\n return false;\n }\n }\n\n private warnEncryptedOnce(roomId: string): void {\n if (this.warnedEncrypted.has(roomId)) return;\n this.warnedEncrypted.add(roomId);\n process.stderr.write(\n `[gateway-matrix] room ${roomId} is end-to-end encrypted; skipping (E2EE deferred to v0.2)\\n`,\n );\n }\n}\n\ninterface MatrixRestError {\n httpStatus?: number;\n errcode?: string;\n message?: string;\n name?: string;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error mapping ladder is exhaustive — each branch maps one Matrix errcode/HTTP status to one canonical code; splitting hurts traceability.\nfunction mapMatrixError(err: unknown): SendResult {\n const e = err as MatrixRestError;\n const status = e.httpStatus ?? 0;\n if (status === 429 || e.errcode === \"M_LIMIT_EXCEEDED\") {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Matrix rate limit\" } };\n }\n if (status === 401 || status === 403 || e.errcode === \"M_FORBIDDEN\") {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Matrix permission error\" },\n };\n }\n if (status === 404 || e.errcode === \"M_NOT_FOUND\") {\n return {\n ok: false,\n error: { code: \"not_found\", message: e.message ?? \"Matrix resource not found\" },\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/alias.ts","../src/client.ts","../src/room-state.ts","../src/normalize.ts","../src/sync.ts","../src/adapter.ts"],"names":["GatewayConfigurationError","BasePlatformAdapter"],"mappings":";;;;;AAYO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9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I,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,qBAAqB,OAAA,EAAS,CAAA,CAAE,WAAW,yBAAA;AAA0B,KACtF;AAAA,EACF;AACA,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,CAAA,CAAE,OAAA,KAAY,aAAA,EAAe;AACjD,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,aAAa,OAAA,EAAS,CAAA,CAAE,WAAW,2BAAA;AAA4B,KAChF;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-matrix`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-matrix\", opts);\n }\n}\n\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor() {\n super({\n code: \"sdk_not_installed\",\n message:\n 'gateway-matrix: peer-dep \"matrix-js-sdk\" not installed. Run: pnpm add matrix-js-sdk',\n detail: \"matrix-js-sdk\",\n });\n }\n}\n\nexport class EncryptedRoomError extends ConfigurationError {\n constructor(roomId: string) {\n super({\n code: \"encrypted_room_unsupported\",\n message: `gateway-matrix: room ${roomId} is end-to-end encrypted (E2EE deferred to v0.2)`,\n detail: roomId,\n });\n }\n}\n","/**\n * Matrix alias resolution + caching (D419).\n *\n * Accepts:\n * - Room id (`!abc123:server`) — pass-through.\n * - Alias (`#general:server`) — resolved via `client.getRoomIdForAlias`.\n *\n * Other shapes throw `ConfigurationError({ code: \"invalid_room_ref\" })`.\n */\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/** @knipignore — minimal Client interface `AliasCache.resolve` accepts; useful for callers building their own resolver. */\nexport interface AliasResolverClient {\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n}\n\nexport class AliasCache {\n private readonly cache = new Map<string, string>();\n\n /** Returns the room id; resolves aliases via the client + caches. */\n async resolve(client: AliasResolverClient, refOrId: string): Promise<string> {\n if (refOrId.startsWith(\"!\")) return refOrId;\n if (!refOrId.startsWith(\"#\")) {\n throw new ConfigurationError({\n code: \"invalid_room_ref\",\n message: `gateway-matrix: invalid room reference ${JSON.stringify(refOrId)} — expected '!' (room id) or '#' (alias)`,\n });\n }\n const cached = this.cache.get(refOrId);\n if (cached !== undefined) return cached;\n const { room_id } = await client.getRoomIdForAlias(refOrId);\n this.cache.set(refOrId, room_id);\n return room_id;\n }\n\n /** Drop all cached resolutions. Useful for tests + admin-rename recovery. */\n clear(): void {\n this.cache.clear();\n }\n\n size(): number {\n return this.cache.size;\n }\n}\n","/**\n * Lazy `matrix-js-sdk` loader.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MatrixClientLike } from \"./sync.js\";\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport interface MatrixSdkClient extends MatrixClientLike {\n startClient(opts: { initialSyncLimit: number }): Promise<void>;\n stopClient(): void;\n sendTextMessage(roomId: string, text: string): Promise<{ event_id: string }>;\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n getRoom(roomId: string): MatrixRoomLike | null;\n isRoomEncrypted?(roomId: string): boolean;\n /** Best-effort current user id; matrix-js-sdk returns `string | null`. */\n getUserId(): string | null;\n /**\n * `/_matrix/client/v3/account/whoami` — the cheapest call that makes the\n * server judge the access token. `startClient` does not: it begins syncing\n * asynchronously and resolves regardless, so without this an invalid token\n * produces a connected-looking adapter that never receives anything.\n */\n whoami(): Promise<{ user_id: string }>;\n}\n\ninterface MatrixSdkModule {\n createClient(opts: { baseUrl: string; accessToken: string; userId: string }): MatrixSdkClient;\n}\n\nexport async function loadMatrixSdk(): Promise<MatrixSdkModule> {\n try {\n const mod = await import(\"matrix-js-sdk\");\n return mod as unknown as MatrixSdkModule;\n } catch {\n throw new SDKNotInstalledError();\n }\n}\n","/**\n * Room state helpers (D416).\n *\n * Matrix has no native \"DM\" concept — DMs are rooms with 2 members.\n * The canonical heuristic: `member_count === 2 → \"dm\"`, else `\"group\"`.\n */\n\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport function detectChannelType(room: MatrixRoomLike | undefined): \"dm\" | \"group\" {\n if (room === undefined) return \"group\";\n return room.getJoinedMemberCount() === 2 ? \"dm\" : \"group\";\n}\n","/**\n * Inbound normalization: MatrixEvent + Room → MatrixMessageEvent.\n *\n * @public\n */\n\nimport type { MatrixMessageEvent } from \"@theokit/gateway\";\n\nimport { detectChannelType } from \"./room-state.js\";\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport function matrixEventToMessageEvent(\n event: MatrixEventLike,\n room: MatrixRoomLike,\n): MatrixMessageEvent | undefined {\n const eventId = event.getId();\n const sender = event.getSender();\n if (eventId === undefined || sender === undefined) return undefined;\n const channelType = detectChannelType(room);\n const content = event.getContent();\n const body = content.body ?? \"\";\n return {\n id: eventId,\n platform: \"matrix\",\n sender: { id: sender },\n channel: {\n id: room.roomId,\n type: channelType,\n },\n text: body,\n receivedAt: event.getTs(),\n matrix: {\n roomId: room.roomId,\n eventId,\n memberCount: room.getJoinedMemberCount(),\n raw: event,\n },\n };\n}\n","/**\n * Sync timeline filter (D415, EC-3 absorbed).\n *\n * Wraps `client.on(\"Room.timeline\", listener)` with 3 filters:\n *\n * 1. Drop non-`m.room.message` events (D413).\n * 2. Drop bot's own messages (loop guard, D275 mirror).\n * 3. **EC-3**: drop events older than `freshnessWindowMs` (default 60s)\n * — initial sync from `matrix-js-sdk` delivers ~10 historical events\n * per joined room, which would otherwise trigger an LLM-call storm.\n */\n\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport interface SyncFilterOpts {\n readonly botUserId: string;\n readonly freshnessWindowMs: number;\n}\n\nexport function shouldDispatchSyncEvent(\n event: MatrixEventLike,\n opts: SyncFilterOpts,\n now = Date.now(),\n): boolean {\n if (event.getType() !== \"m.room.message\") return false;\n const sender = event.getSender();\n if (sender === opts.botUserId) return false;\n if (event.getTs() < now - opts.freshnessWindowMs) return false;\n return true;\n}\n\nexport interface TimelineSubscription {\n unsubscribe(): void;\n}\n\nexport interface MatrixClientLike {\n on(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n off(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n}\n\nexport function subscribeToTimeline(\n client: MatrixClientLike,\n handler: (event: MatrixEventLike, room: MatrixRoomLike) => void,\n opts: SyncFilterOpts,\n): TimelineSubscription {\n const wrapped = (event: MatrixEventLike, room: MatrixRoomLike): void => {\n if (!shouldDispatchSyncEvent(event, opts)) return;\n handler(event, room);\n };\n client.on(\"Room.timeline\", wrapped);\n return {\n unsubscribe(): void {\n client.off(\"Room.timeline\", wrapped);\n },\n };\n}\n","/**\n * `MatrixAdapter` — implements BasePlatformAdapter over matrix-js-sdk.\n * ADRs D413-D421.\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 { AliasCache } from \"./alias.js\";\nimport { loadMatrixSdk, type MatrixSdkClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { matrixEventToMessageEvent } from \"./normalize.js\";\nimport { subscribeToTimeline, type TimelineSubscription } from \"./sync.js\";\nimport type { MatrixAdapterOptions, MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nconst DEFAULT_FRESHNESS_MS = 60_000;\nconst INITIAL_SYNC_LIMIT = 10;\n\nexport class MatrixAdapter extends BasePlatformAdapter {\n readonly platform = \"matrix\" as const;\n private readonly opts: MatrixAdapterOptions;\n private client: MatrixSdkClient | undefined;\n private subscription: TimelineSubscription | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private readonly aliasCache = new AliasCache();\n private connected = false;\n private readonly warnedEncrypted = new Set<string>();\n /** True only between disconnect() and the next connect() — see #12. */\n private tearingDown = false;\n\n /**\n * `fetch` for the SDK that leaves teardown aborts unsettled instead of\n * rejecting (#12).\n *\n * A request aborted while we are tearing the client down has no consumer left\n * that could act on the outcome, so an unsettled promise costs a continuation\n * and nothing else; the alternative is a rejection with no handler anywhere,\n * which ends the host process. It is scoped to the teardown window on purpose:\n * a consumer using the `getClient()` escape hatch (D421) may pass its own\n * abort signal to `search()` or `slidingSync()` and MUST still see those\n * rejections, so outside teardown every error propagates untouched.\n */\n private teardownSafeFetch(): typeof globalThis.fetch {\n const base = globalThis.fetch.bind(globalThis);\n return (input, init) =>\n base(input, init).catch((err: unknown) => {\n if (this.tearingDown && isAbortError(err)) {\n return new Promise<Response>(() => {\n /* deliberately never settles — see the doc comment */\n });\n }\n throw err;\n });\n }\n\n constructor(opts: MatrixAdapterOptions) {\n super();\n if (opts.homeserverUrl.length === 0) {\n throw new ConfigurationError({\n code: \"homeserver_url_required\",\n message: 'gateway-matrix: opts.homeserverUrl is empty (e.g. \"https://matrix.org\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-matrix: opts.accessToken is empty (Element → Settings → Help & About → Advanced → Access Token)\",\n });\n }\n if (opts.userId.length === 0 || !opts.userId.startsWith(\"@\")) {\n throw new ConfigurationError({\n code: \"user_id_required\",\n message: 'gateway-matrix: opts.userId must be a Matrix user id (e.g. \"@bot:matrix.org\")',\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n this.tearingDown = false;\n try {\n const cfg = {\n baseUrl: this.opts.homeserverUrl,\n accessToken: this.opts.accessToken,\n userId: this.opts.userId,\n fetchFn: this.teardownSafeFetch(),\n };\n const factory = this.opts.__clientFactory;\n this.client =\n factory === undefined\n ? (await loadMatrixSdk()).createClient(cfg)\n : (factory(cfg) as MatrixSdkClient);\n // Validate the credential BEFORE reporting success. `startClient` kicks\n // off the sync loop asynchronously and resolves whether or not the token\n // is any good — so connect() used to answer `true` for a token the server\n // rejects, leaving an operator with a healthy-looking adapter and total\n // silence. Every sibling adapter returns false here; this one did not,\n // and only a real homeserver could show it.\n await this.client.whoami();\n await this.client.startClient({ initialSyncLimit: INITIAL_SYNC_LIMIT });\n this.attachSync();\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-matrix] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n // Issue #12. `stopClient()` aborts the requests still in flight, and the\n // AbortError escapes as an UNHANDLED rejection — the rejecting promise is\n // the SDK's own `authedRequest` wrapper, which no caller catches and which\n // we cannot reach. Node has terminated on unhandled rejections by default\n // since v15, so an application calling disconnect() inside a reconnect loop\n // could be killed by its own clean shutdown. Measured against a real\n // homeserver: 7 occurrences in 8 connect/disconnect cycles.\n //\n // `teardownSafeFetch` closes it at the only seam the SDK offers. The flag is\n // set here, before the abort, and cleared by the next connect().\n this.tearingDown = true;\n this.subscription?.unsubscribe();\n this.subscription = undefined;\n this.client?.stopClient();\n this.client = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n this.aliasCache.clear();\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.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MatrixAdapter.connect() not called\" },\n };\n }\n try {\n const roomId = await this.aliasCache.resolve(this.client, out.channel.id);\n if (this.isEncrypted(roomId)) {\n this.warnEncryptedOnce(roomId);\n return {\n ok: false,\n error: {\n code: \"encrypted_room_unsupported\",\n message: `Matrix room ${roomId} is encrypted; E2EE deferred to v0.2`,\n },\n };\n }\n const res = await this.client.sendTextMessage(roomId, out.text);\n return { ok: true, messageId: res.event_id };\n } catch (err) {\n return mapMatrixError(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 (D421) — caller can drive matrix-js-sdk directly for advanced features. */\n getClient(): MatrixSdkClient | undefined {\n return this.client;\n }\n\n /** Used by tests to install a mock SDK client + flip connected flag. */\n _installClient(client: MatrixSdkClient): void {\n this.client = client;\n this.connected = true;\n this.attachSync();\n }\n\n private attachSync(): void {\n if (this.client === undefined) return;\n const client = this.client;\n const opts = {\n botUserId: this.opts.userId,\n freshnessWindowMs: this.opts.freshnessWindowMs ?? DEFAULT_FRESHNESS_MS,\n };\n this.subscription = subscribeToTimeline(\n client,\n (ev: MatrixEventLike, room: MatrixRoomLike) => {\n void this.dispatchTimelineEvent(ev, room).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] dispatchTimelineEvent failed: ${m}\\n`);\n });\n },\n opts,\n );\n }\n\n private async dispatchTimelineEvent(event: MatrixEventLike, room: MatrixRoomLike): Promise<void> {\n if (this.isEncrypted(room.roomId)) {\n this.warnEncryptedOnce(room.roomId);\n return;\n }\n const normalized = matrixEventToMessageEvent(event, room);\n if (normalized === undefined) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] handler threw: ${m}\\n`);\n }\n }\n\n private isEncrypted(roomId: string): boolean {\n if (this.client === undefined) return false;\n if (this.client.isRoomEncrypted === undefined) return false;\n try {\n return this.client.isRoomEncrypted(roomId);\n } catch {\n return false;\n }\n }\n\n private warnEncryptedOnce(roomId: string): void {\n if (this.warnedEncrypted.has(roomId)) return;\n this.warnedEncrypted.add(roomId);\n process.stderr.write(\n `[gateway-matrix] room ${roomId} is end-to-end encrypted; skipping (E2EE deferred to v0.2)\\n`,\n );\n }\n}\n\n/**\n * Narrow abort detection. `DOMException.ABORT_ERR` is 20; the message check\n * covers runtimes that report the abort without the standard name or code.\n */\nfunction isAbortError(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) return false;\n const e = err as { name?: unknown; code?: unknown; message?: unknown };\n if (e.name === \"AbortError\") return true;\n if (e.code === 20) return true;\n return typeof e.message === \"string\" && /aborted/i.test(e.message);\n}\n\ninterface MatrixRestError {\n httpStatus?: number;\n errcode?: string;\n message?: string;\n name?: string;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error mapping ladder is exhaustive — each branch maps one Matrix errcode/HTTP status to one canonical code; splitting hurts traceability.\nfunction mapMatrixError(err: unknown): SendResult {\n const e = err as MatrixRestError;\n const status = e.httpStatus ?? 0;\n if (status === 429 || e.errcode === \"M_LIMIT_EXCEEDED\") {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Matrix rate limit\" } };\n }\n if (status === 401 || status === 403 || e.errcode === \"M_FORBIDDEN\") {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Matrix permission error\" },\n };\n }\n if (status === 404 || e.errcode === \"M_NOT_FOUND\") {\n return {\n ok: false,\n error: { code: \"not_found\", message: e.message ?? \"Matrix resource not found\" },\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, MatrixMessageEvent } from '@theokit/gateway';
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, MatrixMessageEvent } from '@theokit/gateway';
2
2
 
3
3
  /**
4
4
  * Public option types + minimal Matrix shape narrowing (kept local so
@@ -93,6 +93,15 @@ interface MatrixSdkClient extends MatrixClientLike {
93
93
  isRoomEncrypted?(roomId: string): boolean;
94
94
  /** Best-effort current user id; matrix-js-sdk returns `string | null`. */
95
95
  getUserId(): string | null;
96
+ /**
97
+ * `/_matrix/client/v3/account/whoami` — the cheapest call that makes the
98
+ * server judge the access token. `startClient` does not: it begins syncing
99
+ * asynchronously and resolves regardless, so without this an invalid token
100
+ * produces a connected-looking adapter that never receives anything.
101
+ */
102
+ whoami(): Promise<{
103
+ user_id: string;
104
+ }>;
96
105
  }
97
106
 
98
107
  /**
@@ -111,6 +120,21 @@ declare class MatrixAdapter extends BasePlatformAdapter {
111
120
  private readonly aliasCache;
112
121
  private connected;
113
122
  private readonly warnedEncrypted;
123
+ /** True only between disconnect() and the next connect() — see #12. */
124
+ private tearingDown;
125
+ /**
126
+ * `fetch` for the SDK that leaves teardown aborts unsettled instead of
127
+ * rejecting (#12).
128
+ *
129
+ * A request aborted while we are tearing the client down has no consumer left
130
+ * that could act on the outcome, so an unsettled promise costs a continuation
131
+ * and nothing else; the alternative is a rejection with no handler anywhere,
132
+ * which ends the host process. It is scoped to the teardown window on purpose:
133
+ * a consumer using the `getClient()` escape hatch (D421) may pass its own
134
+ * abort signal to `search()` or `slidingSync()` and MUST still see those
135
+ * rejections, so outside teardown every error propagates untouched.
136
+ */
137
+ private teardownSafeFetch;
114
138
  constructor(opts: MatrixAdapterOptions);
115
139
  connect(): Promise<boolean>;
116
140
  disconnect(): Promise<void>;
@@ -152,17 +176,15 @@ declare class AliasCache {
152
176
 
153
177
  /**
154
178
  * Typed errors for `@theokit/gateway-matrix`.
179
+ *
180
+ * `ConfigurationError` extends the shared core `GatewayConfigurationError`
181
+ * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).
155
182
  */
183
+
156
184
  /** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
157
- interface ConfigurationErrorOptions {
158
- readonly code: string;
159
- readonly message?: string;
160
- readonly detail?: string;
161
- }
162
- declare class ConfigurationError extends Error {
185
+ type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;
186
+ declare class ConfigurationError extends GatewayConfigurationError {
163
187
  readonly name = "ConfigurationError";
164
- readonly code: string;
165
- readonly detail: string | undefined;
166
188
  constructor(opts: ConfigurationErrorOptions);
167
189
  }
168
190
  declare class SDKNotInstalledError extends ConfigurationError {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, MatrixMessageEvent } from '@theokit/gateway';
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, MatrixMessageEvent } from '@theokit/gateway';
2
2
 
3
3
  /**
4
4
  * Public option types + minimal Matrix shape narrowing (kept local so
@@ -93,6 +93,15 @@ interface MatrixSdkClient extends MatrixClientLike {
93
93
  isRoomEncrypted?(roomId: string): boolean;
94
94
  /** Best-effort current user id; matrix-js-sdk returns `string | null`. */
95
95
  getUserId(): string | null;
96
+ /**
97
+ * `/_matrix/client/v3/account/whoami` — the cheapest call that makes the
98
+ * server judge the access token. `startClient` does not: it begins syncing
99
+ * asynchronously and resolves regardless, so without this an invalid token
100
+ * produces a connected-looking adapter that never receives anything.
101
+ */
102
+ whoami(): Promise<{
103
+ user_id: string;
104
+ }>;
96
105
  }
97
106
 
98
107
  /**
@@ -111,6 +120,21 @@ declare class MatrixAdapter extends BasePlatformAdapter {
111
120
  private readonly aliasCache;
112
121
  private connected;
113
122
  private readonly warnedEncrypted;
123
+ /** True only between disconnect() and the next connect() — see #12. */
124
+ private tearingDown;
125
+ /**
126
+ * `fetch` for the SDK that leaves teardown aborts unsettled instead of
127
+ * rejecting (#12).
128
+ *
129
+ * A request aborted while we are tearing the client down has no consumer left
130
+ * that could act on the outcome, so an unsettled promise costs a continuation
131
+ * and nothing else; the alternative is a rejection with no handler anywhere,
132
+ * which ends the host process. It is scoped to the teardown window on purpose:
133
+ * a consumer using the `getClient()` escape hatch (D421) may pass its own
134
+ * abort signal to `search()` or `slidingSync()` and MUST still see those
135
+ * rejections, so outside teardown every error propagates untouched.
136
+ */
137
+ private teardownSafeFetch;
114
138
  constructor(opts: MatrixAdapterOptions);
115
139
  connect(): Promise<boolean>;
116
140
  disconnect(): Promise<void>;
@@ -152,17 +176,15 @@ declare class AliasCache {
152
176
 
153
177
  /**
154
178
  * Typed errors for `@theokit/gateway-matrix`.
179
+ *
180
+ * `ConfigurationError` extends the shared core `GatewayConfigurationError`
181
+ * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).
155
182
  */
183
+
156
184
  /** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
157
- interface ConfigurationErrorOptions {
158
- readonly code: string;
159
- readonly message?: string;
160
- readonly detail?: string;
161
- }
162
- declare class ConfigurationError extends Error {
185
+ type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;
186
+ declare class ConfigurationError extends GatewayConfigurationError {
163
187
  readonly name = "ConfigurationError";
164
- readonly code: string;
165
- readonly detail: string | undefined;
166
188
  constructor(opts: ConfigurationErrorOptions);
167
189
  }
168
190
  declare class SDKNotInstalledError extends ConfigurationError {
package/dist/index.js CHANGED
@@ -1,16 +1,10 @@
1
- import { BasePlatformAdapter } from '@theokit/gateway';
1
+ import { GatewayConfigurationError, 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-matrix: ${opts.code}`);
12
- this.code = opts.code;
13
- this.detail = opts.detail;
7
+ super("gateway-matrix", opts);
14
8
  }
15
9
  };
16
10
  var SDKNotInstalledError = class extends ConfigurationError {
@@ -135,6 +129,30 @@ var MatrixAdapter = class extends BasePlatformAdapter {
135
129
  aliasCache = new AliasCache();
136
130
  connected = false;
137
131
  warnedEncrypted = /* @__PURE__ */ new Set();
132
+ /** True only between disconnect() and the next connect() — see #12. */
133
+ tearingDown = false;
134
+ /**
135
+ * `fetch` for the SDK that leaves teardown aborts unsettled instead of
136
+ * rejecting (#12).
137
+ *
138
+ * A request aborted while we are tearing the client down has no consumer left
139
+ * that could act on the outcome, so an unsettled promise costs a continuation
140
+ * and nothing else; the alternative is a rejection with no handler anywhere,
141
+ * which ends the host process. It is scoped to the teardown window on purpose:
142
+ * a consumer using the `getClient()` escape hatch (D421) may pass its own
143
+ * abort signal to `search()` or `slidingSync()` and MUST still see those
144
+ * rejections, so outside teardown every error propagates untouched.
145
+ */
146
+ teardownSafeFetch() {
147
+ const base = globalThis.fetch.bind(globalThis);
148
+ return (input, init) => base(input, init).catch((err) => {
149
+ if (this.tearingDown && isAbortError(err)) {
150
+ return new Promise(() => {
151
+ });
152
+ }
153
+ throw err;
154
+ });
155
+ }
138
156
  constructor(opts) {
139
157
  super();
140
158
  if (opts.homeserverUrl.length === 0) {
@@ -159,13 +177,17 @@ var MatrixAdapter = class extends BasePlatformAdapter {
159
177
  }
160
178
  async connect() {
161
179
  if (this.connected) return true;
180
+ this.tearingDown = false;
162
181
  try {
163
- const mod = await loadMatrixSdk();
164
- this.client = mod.createClient({
182
+ const cfg = {
165
183
  baseUrl: this.opts.homeserverUrl,
166
184
  accessToken: this.opts.accessToken,
167
- userId: this.opts.userId
168
- });
185
+ userId: this.opts.userId,
186
+ fetchFn: this.teardownSafeFetch()
187
+ };
188
+ const factory = this.opts.__clientFactory;
189
+ this.client = factory === void 0 ? (await loadMatrixSdk()).createClient(cfg) : factory(cfg);
190
+ await this.client.whoami();
169
191
  await this.client.startClient({ initialSyncLimit: INITIAL_SYNC_LIMIT });
170
192
  this.attachSync();
171
193
  this.connected = true;
@@ -179,6 +201,7 @@ var MatrixAdapter = class extends BasePlatformAdapter {
179
201
  }
180
202
  async disconnect() {
181
203
  if (!this.connected) return;
204
+ this.tearingDown = true;
182
205
  this.subscription?.unsubscribe();
183
206
  this.subscription = void 0;
184
207
  this.client?.stopClient();
@@ -284,6 +307,13 @@ var MatrixAdapter = class extends BasePlatformAdapter {
284
307
  );
285
308
  }
286
309
  };
310
+ function isAbortError(err) {
311
+ if (typeof err !== "object" || err === null) return false;
312
+ const e = err;
313
+ if (e.name === "AbortError") return true;
314
+ if (e.code === 20) return true;
315
+ return typeof e.message === "string" && /aborted/i.test(e.message);
316
+ }
287
317
  function mapMatrixError(err) {
288
318
  const e = err;
289
319
  const status = e.httpStatus ?? 0;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/alias.ts","../src/client.ts","../src/room-state.ts","../src/normalize.ts","../src/sync.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,gBAAA,EAAmB,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AACpD,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,WAAA,GAAc;AACZ,IAAA,KAAA,CAAM;AA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;AACjD,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,aAAa,OAAA,EAAS,CAAA,CAAE,WAAW,2BAAA;AAA4B,KAChF;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-matrix`.\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-matrix: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor() {\n super({\n code: \"sdk_not_installed\",\n message:\n 'gateway-matrix: peer-dep \"matrix-js-sdk\" not installed. Run: pnpm add matrix-js-sdk',\n detail: \"matrix-js-sdk\",\n });\n }\n}\n\nexport class EncryptedRoomError extends ConfigurationError {\n constructor(roomId: string) {\n super({\n code: \"encrypted_room_unsupported\",\n message: `gateway-matrix: room ${roomId} is end-to-end encrypted (E2EE deferred to v0.2)`,\n detail: roomId,\n });\n }\n}\n","/**\n * Matrix alias resolution + caching (D419).\n *\n * Accepts:\n * - Room id (`!abc123:server`) — pass-through.\n * - Alias (`#general:server`) — resolved via `client.getRoomIdForAlias`.\n *\n * Other shapes throw `ConfigurationError({ code: \"invalid_room_ref\" })`.\n */\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/** @knipignore — minimal Client interface `AliasCache.resolve` accepts; useful for callers building their own resolver. */\nexport interface AliasResolverClient {\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n}\n\nexport class AliasCache {\n private readonly cache = new Map<string, string>();\n\n /** Returns the room id; resolves aliases via the client + caches. */\n async resolve(client: AliasResolverClient, refOrId: string): Promise<string> {\n if (refOrId.startsWith(\"!\")) return refOrId;\n if (!refOrId.startsWith(\"#\")) {\n throw new ConfigurationError({\n code: \"invalid_room_ref\",\n message: `gateway-matrix: invalid room reference ${JSON.stringify(refOrId)} — expected '!' (room id) or '#' (alias)`,\n });\n }\n const cached = this.cache.get(refOrId);\n if (cached !== undefined) return cached;\n const { room_id } = await client.getRoomIdForAlias(refOrId);\n this.cache.set(refOrId, room_id);\n return room_id;\n }\n\n /** Drop all cached resolutions. Useful for tests + admin-rename recovery. */\n clear(): void {\n this.cache.clear();\n }\n\n size(): number {\n return this.cache.size;\n }\n}\n","/**\n * Lazy `matrix-js-sdk` loader.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MatrixClientLike } from \"./sync.js\";\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport interface MatrixSdkClient extends MatrixClientLike {\n startClient(opts: { initialSyncLimit: number }): Promise<void>;\n stopClient(): void;\n sendTextMessage(roomId: string, text: string): Promise<{ event_id: string }>;\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n getRoom(roomId: string): MatrixRoomLike | null;\n isRoomEncrypted?(roomId: string): boolean;\n /** Best-effort current user id; matrix-js-sdk returns `string | null`. */\n getUserId(): string | null;\n}\n\ninterface MatrixSdkModule {\n createClient(opts: { baseUrl: string; accessToken: string; userId: string }): MatrixSdkClient;\n}\n\nexport async function loadMatrixSdk(): Promise<MatrixSdkModule> {\n try {\n const mod = await import(\"matrix-js-sdk\");\n return mod as unknown as MatrixSdkModule;\n } catch {\n throw new SDKNotInstalledError();\n }\n}\n","/**\n * Room state helpers (D416).\n *\n * Matrix has no native \"DM\" concept — DMs are rooms with 2 members.\n * The canonical heuristic: `member_count === 2 → \"dm\"`, else `\"group\"`.\n */\n\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport function detectChannelType(room: MatrixRoomLike | undefined): \"dm\" | \"group\" {\n if (room === undefined) return \"group\";\n return room.getJoinedMemberCount() === 2 ? \"dm\" : \"group\";\n}\n","/**\n * Inbound normalization: MatrixEvent + Room → MatrixMessageEvent.\n *\n * @public\n */\n\nimport type { MatrixMessageEvent } from \"@theokit/gateway\";\n\nimport { detectChannelType } from \"./room-state.js\";\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport function matrixEventToMessageEvent(\n event: MatrixEventLike,\n room: MatrixRoomLike,\n): MatrixMessageEvent | undefined {\n const eventId = event.getId();\n const sender = event.getSender();\n if (eventId === undefined || sender === undefined) return undefined;\n const channelType = detectChannelType(room);\n const content = event.getContent();\n const body = content.body ?? \"\";\n return {\n id: eventId,\n platform: \"matrix\",\n sender: { id: sender },\n channel: {\n id: room.roomId,\n type: channelType,\n },\n text: body,\n receivedAt: event.getTs(),\n matrix: {\n roomId: room.roomId,\n eventId,\n memberCount: room.getJoinedMemberCount(),\n raw: event,\n },\n };\n}\n","/**\n * Sync timeline filter (D415, EC-3 absorbed).\n *\n * Wraps `client.on(\"Room.timeline\", listener)` with 3 filters:\n *\n * 1. Drop non-`m.room.message` events (D413).\n * 2. Drop bot's own messages (loop guard, D275 mirror).\n * 3. **EC-3**: drop events older than `freshnessWindowMs` (default 60s)\n * — initial sync from `matrix-js-sdk` delivers ~10 historical events\n * per joined room, which would otherwise trigger an LLM-call storm.\n */\n\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport interface SyncFilterOpts {\n readonly botUserId: string;\n readonly freshnessWindowMs: number;\n}\n\nexport function shouldDispatchSyncEvent(\n event: MatrixEventLike,\n opts: SyncFilterOpts,\n now = Date.now(),\n): boolean {\n if (event.getType() !== \"m.room.message\") return false;\n const sender = event.getSender();\n if (sender === opts.botUserId) return false;\n if (event.getTs() < now - opts.freshnessWindowMs) return false;\n return true;\n}\n\nexport interface TimelineSubscription {\n unsubscribe(): void;\n}\n\nexport interface MatrixClientLike {\n on(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n off(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n}\n\nexport function subscribeToTimeline(\n client: MatrixClientLike,\n handler: (event: MatrixEventLike, room: MatrixRoomLike) => void,\n opts: SyncFilterOpts,\n): TimelineSubscription {\n const wrapped = (event: MatrixEventLike, room: MatrixRoomLike): void => {\n if (!shouldDispatchSyncEvent(event, opts)) return;\n handler(event, room);\n };\n client.on(\"Room.timeline\", wrapped);\n return {\n unsubscribe(): void {\n client.off(\"Room.timeline\", wrapped);\n },\n };\n}\n","/**\n * `MatrixAdapter` — implements BasePlatformAdapter over matrix-js-sdk.\n * ADRs D413-D421.\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 { AliasCache } from \"./alias.js\";\nimport { loadMatrixSdk, type MatrixSdkClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { matrixEventToMessageEvent } from \"./normalize.js\";\nimport { subscribeToTimeline, type TimelineSubscription } from \"./sync.js\";\nimport type { MatrixAdapterOptions, MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nconst DEFAULT_FRESHNESS_MS = 60_000;\nconst INITIAL_SYNC_LIMIT = 10;\n\nexport class MatrixAdapter extends BasePlatformAdapter {\n readonly platform = \"matrix\" as const;\n private readonly opts: MatrixAdapterOptions;\n private client: MatrixSdkClient | undefined;\n private subscription: TimelineSubscription | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private readonly aliasCache = new AliasCache();\n private connected = false;\n private readonly warnedEncrypted = new Set<string>();\n\n constructor(opts: MatrixAdapterOptions) {\n super();\n if (opts.homeserverUrl.length === 0) {\n throw new ConfigurationError({\n code: \"homeserver_url_required\",\n message: 'gateway-matrix: opts.homeserverUrl is empty (e.g. \"https://matrix.org\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-matrix: opts.accessToken is empty (Element → Settings → Help & About → Advanced → Access Token)\",\n });\n }\n if (opts.userId.length === 0 || !opts.userId.startsWith(\"@\")) {\n throw new ConfigurationError({\n code: \"user_id_required\",\n message: 'gateway-matrix: opts.userId must be a Matrix user id (e.g. \"@bot:matrix.org\")',\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const mod = await loadMatrixSdk();\n this.client = mod.createClient({\n baseUrl: this.opts.homeserverUrl,\n accessToken: this.opts.accessToken,\n userId: this.opts.userId,\n });\n await this.client.startClient({ initialSyncLimit: INITIAL_SYNC_LIMIT });\n this.attachSync();\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-matrix] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.subscription?.unsubscribe();\n this.subscription = undefined;\n this.client?.stopClient();\n this.client = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n this.aliasCache.clear();\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.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MatrixAdapter.connect() not called\" },\n };\n }\n try {\n const roomId = await this.aliasCache.resolve(this.client, out.channel.id);\n if (this.isEncrypted(roomId)) {\n this.warnEncryptedOnce(roomId);\n return {\n ok: false,\n error: {\n code: \"encrypted_room_unsupported\",\n message: `Matrix room ${roomId} is encrypted; E2EE deferred to v0.2`,\n },\n };\n }\n const res = await this.client.sendTextMessage(roomId, out.text);\n return { ok: true, messageId: res.event_id };\n } catch (err) {\n return mapMatrixError(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 (D421) — caller can drive matrix-js-sdk directly for advanced features. */\n getClient(): MatrixSdkClient | undefined {\n return this.client;\n }\n\n /** Used by tests to install a mock SDK client + flip connected flag. */\n _installClient(client: MatrixSdkClient): void {\n this.client = client;\n this.connected = true;\n this.attachSync();\n }\n\n private attachSync(): void {\n if (this.client === undefined) return;\n const client = this.client;\n const opts = {\n botUserId: this.opts.userId,\n freshnessWindowMs: this.opts.freshnessWindowMs ?? DEFAULT_FRESHNESS_MS,\n };\n this.subscription = subscribeToTimeline(\n client,\n (ev: MatrixEventLike, room: MatrixRoomLike) => {\n void this.dispatchTimelineEvent(ev, room).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] dispatchTimelineEvent failed: ${m}\\n`);\n });\n },\n opts,\n );\n }\n\n private async dispatchTimelineEvent(event: MatrixEventLike, room: MatrixRoomLike): Promise<void> {\n if (this.isEncrypted(room.roomId)) {\n this.warnEncryptedOnce(room.roomId);\n return;\n }\n const normalized = matrixEventToMessageEvent(event, room);\n if (normalized === undefined) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] handler threw: ${m}\\n`);\n }\n }\n\n private isEncrypted(roomId: string): boolean {\n if (this.client === undefined) return false;\n if (this.client.isRoomEncrypted === undefined) return false;\n try {\n return this.client.isRoomEncrypted(roomId);\n } catch {\n return false;\n }\n }\n\n private warnEncryptedOnce(roomId: string): void {\n if (this.warnedEncrypted.has(roomId)) return;\n this.warnedEncrypted.add(roomId);\n process.stderr.write(\n `[gateway-matrix] room ${roomId} is end-to-end encrypted; skipping (E2EE deferred to v0.2)\\n`,\n );\n }\n}\n\ninterface MatrixRestError {\n httpStatus?: number;\n errcode?: string;\n message?: string;\n name?: string;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error mapping ladder is exhaustive — each branch maps one Matrix errcode/HTTP status to one canonical code; splitting hurts traceability.\nfunction mapMatrixError(err: unknown): SendResult {\n const e = err as MatrixRestError;\n const status = e.httpStatus ?? 0;\n if (status === 429 || e.errcode === \"M_LIMIT_EXCEEDED\") {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Matrix rate limit\" } };\n }\n if (status === 401 || status === 403 || e.errcode === \"M_FORBIDDEN\") {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Matrix permission error\" },\n };\n }\n if (status === 404 || e.errcode === \"M_NOT_FOUND\") {\n return {\n ok: false,\n error: { code: \"not_found\", message: e.message ?? \"Matrix resource not found\" },\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/alias.ts","../src/client.ts","../src/room-state.ts","../src/normalize.ts","../src/sync.ts","../src/adapter.ts"],"names":[],"mappings":";;;AAYO,IAAM,kBAAA,GAAN,cAAiC,yBAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,kBAAkB,IAAI,CAAA;AAAA,EAC9B;AACF;AAEO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,WAAA,GAAc;AACZ,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EACE,qFAAA;AAAA,MACF,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;AAEO,IAAM,kBAAA,GAAN,c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;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-matrix`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-matrix\", opts);\n }\n}\n\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor() {\n super({\n code: \"sdk_not_installed\",\n message:\n 'gateway-matrix: peer-dep \"matrix-js-sdk\" not installed. Run: pnpm add matrix-js-sdk',\n detail: \"matrix-js-sdk\",\n });\n }\n}\n\nexport class EncryptedRoomError extends ConfigurationError {\n constructor(roomId: string) {\n super({\n code: \"encrypted_room_unsupported\",\n message: `gateway-matrix: room ${roomId} is end-to-end encrypted (E2EE deferred to v0.2)`,\n detail: roomId,\n });\n }\n}\n","/**\n * Matrix alias resolution + caching (D419).\n *\n * Accepts:\n * - Room id (`!abc123:server`) — pass-through.\n * - Alias (`#general:server`) — resolved via `client.getRoomIdForAlias`.\n *\n * Other shapes throw `ConfigurationError({ code: \"invalid_room_ref\" })`.\n */\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/** @knipignore — minimal Client interface `AliasCache.resolve` accepts; useful for callers building their own resolver. */\nexport interface AliasResolverClient {\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n}\n\nexport class AliasCache {\n private readonly cache = new Map<string, string>();\n\n /** Returns the room id; resolves aliases via the client + caches. */\n async resolve(client: AliasResolverClient, refOrId: string): Promise<string> {\n if (refOrId.startsWith(\"!\")) return refOrId;\n if (!refOrId.startsWith(\"#\")) {\n throw new ConfigurationError({\n code: \"invalid_room_ref\",\n message: `gateway-matrix: invalid room reference ${JSON.stringify(refOrId)} — expected '!' (room id) or '#' (alias)`,\n });\n }\n const cached = this.cache.get(refOrId);\n if (cached !== undefined) return cached;\n const { room_id } = await client.getRoomIdForAlias(refOrId);\n this.cache.set(refOrId, room_id);\n return room_id;\n }\n\n /** Drop all cached resolutions. Useful for tests + admin-rename recovery. */\n clear(): void {\n this.cache.clear();\n }\n\n size(): number {\n return this.cache.size;\n }\n}\n","/**\n * Lazy `matrix-js-sdk` loader.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MatrixClientLike } from \"./sync.js\";\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport interface MatrixSdkClient extends MatrixClientLike {\n startClient(opts: { initialSyncLimit: number }): Promise<void>;\n stopClient(): void;\n sendTextMessage(roomId: string, text: string): Promise<{ event_id: string }>;\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n getRoom(roomId: string): MatrixRoomLike | null;\n isRoomEncrypted?(roomId: string): boolean;\n /** Best-effort current user id; matrix-js-sdk returns `string | null`. */\n getUserId(): string | null;\n /**\n * `/_matrix/client/v3/account/whoami` — the cheapest call that makes the\n * server judge the access token. `startClient` does not: it begins syncing\n * asynchronously and resolves regardless, so without this an invalid token\n * produces a connected-looking adapter that never receives anything.\n */\n whoami(): Promise<{ user_id: string }>;\n}\n\ninterface MatrixSdkModule {\n createClient(opts: { baseUrl: string; accessToken: string; userId: string }): MatrixSdkClient;\n}\n\nexport async function loadMatrixSdk(): Promise<MatrixSdkModule> {\n try {\n const mod = await import(\"matrix-js-sdk\");\n return mod as unknown as MatrixSdkModule;\n } catch {\n throw new SDKNotInstalledError();\n }\n}\n","/**\n * Room state helpers (D416).\n *\n * Matrix has no native \"DM\" concept — DMs are rooms with 2 members.\n * The canonical heuristic: `member_count === 2 → \"dm\"`, else `\"group\"`.\n */\n\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport function detectChannelType(room: MatrixRoomLike | undefined): \"dm\" | \"group\" {\n if (room === undefined) return \"group\";\n return room.getJoinedMemberCount() === 2 ? \"dm\" : \"group\";\n}\n","/**\n * Inbound normalization: MatrixEvent + Room → MatrixMessageEvent.\n *\n * @public\n */\n\nimport type { MatrixMessageEvent } from \"@theokit/gateway\";\n\nimport { detectChannelType } from \"./room-state.js\";\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport function matrixEventToMessageEvent(\n event: MatrixEventLike,\n room: MatrixRoomLike,\n): MatrixMessageEvent | undefined {\n const eventId = event.getId();\n const sender = event.getSender();\n if (eventId === undefined || sender === undefined) return undefined;\n const channelType = detectChannelType(room);\n const content = event.getContent();\n const body = content.body ?? \"\";\n return {\n id: eventId,\n platform: \"matrix\",\n sender: { id: sender },\n channel: {\n id: room.roomId,\n type: channelType,\n },\n text: body,\n receivedAt: event.getTs(),\n matrix: {\n roomId: room.roomId,\n eventId,\n memberCount: room.getJoinedMemberCount(),\n raw: event,\n },\n };\n}\n","/**\n * Sync timeline filter (D415, EC-3 absorbed).\n *\n * Wraps `client.on(\"Room.timeline\", listener)` with 3 filters:\n *\n * 1. Drop non-`m.room.message` events (D413).\n * 2. Drop bot's own messages (loop guard, D275 mirror).\n * 3. **EC-3**: drop events older than `freshnessWindowMs` (default 60s)\n * — initial sync from `matrix-js-sdk` delivers ~10 historical events\n * per joined room, which would otherwise trigger an LLM-call storm.\n */\n\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport interface SyncFilterOpts {\n readonly botUserId: string;\n readonly freshnessWindowMs: number;\n}\n\nexport function shouldDispatchSyncEvent(\n event: MatrixEventLike,\n opts: SyncFilterOpts,\n now = Date.now(),\n): boolean {\n if (event.getType() !== \"m.room.message\") return false;\n const sender = event.getSender();\n if (sender === opts.botUserId) return false;\n if (event.getTs() < now - opts.freshnessWindowMs) return false;\n return true;\n}\n\nexport interface TimelineSubscription {\n unsubscribe(): void;\n}\n\nexport interface MatrixClientLike {\n on(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n off(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n}\n\nexport function subscribeToTimeline(\n client: MatrixClientLike,\n handler: (event: MatrixEventLike, room: MatrixRoomLike) => void,\n opts: SyncFilterOpts,\n): TimelineSubscription {\n const wrapped = (event: MatrixEventLike, room: MatrixRoomLike): void => {\n if (!shouldDispatchSyncEvent(event, opts)) return;\n handler(event, room);\n };\n client.on(\"Room.timeline\", wrapped);\n return {\n unsubscribe(): void {\n client.off(\"Room.timeline\", wrapped);\n },\n };\n}\n","/**\n * `MatrixAdapter` — implements BasePlatformAdapter over matrix-js-sdk.\n * ADRs D413-D421.\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 { AliasCache } from \"./alias.js\";\nimport { loadMatrixSdk, type MatrixSdkClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { matrixEventToMessageEvent } from \"./normalize.js\";\nimport { subscribeToTimeline, type TimelineSubscription } from \"./sync.js\";\nimport type { MatrixAdapterOptions, MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nconst DEFAULT_FRESHNESS_MS = 60_000;\nconst INITIAL_SYNC_LIMIT = 10;\n\nexport class MatrixAdapter extends BasePlatformAdapter {\n readonly platform = \"matrix\" as const;\n private readonly opts: MatrixAdapterOptions;\n private client: MatrixSdkClient | undefined;\n private subscription: TimelineSubscription | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private readonly aliasCache = new AliasCache();\n private connected = false;\n private readonly warnedEncrypted = new Set<string>();\n /** True only between disconnect() and the next connect() — see #12. */\n private tearingDown = false;\n\n /**\n * `fetch` for the SDK that leaves teardown aborts unsettled instead of\n * rejecting (#12).\n *\n * A request aborted while we are tearing the client down has no consumer left\n * that could act on the outcome, so an unsettled promise costs a continuation\n * and nothing else; the alternative is a rejection with no handler anywhere,\n * which ends the host process. It is scoped to the teardown window on purpose:\n * a consumer using the `getClient()` escape hatch (D421) may pass its own\n * abort signal to `search()` or `slidingSync()` and MUST still see those\n * rejections, so outside teardown every error propagates untouched.\n */\n private teardownSafeFetch(): typeof globalThis.fetch {\n const base = globalThis.fetch.bind(globalThis);\n return (input, init) =>\n base(input, init).catch((err: unknown) => {\n if (this.tearingDown && isAbortError(err)) {\n return new Promise<Response>(() => {\n /* deliberately never settles — see the doc comment */\n });\n }\n throw err;\n });\n }\n\n constructor(opts: MatrixAdapterOptions) {\n super();\n if (opts.homeserverUrl.length === 0) {\n throw new ConfigurationError({\n code: \"homeserver_url_required\",\n message: 'gateway-matrix: opts.homeserverUrl is empty (e.g. \"https://matrix.org\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-matrix: opts.accessToken is empty (Element → Settings → Help & About → Advanced → Access Token)\",\n });\n }\n if (opts.userId.length === 0 || !opts.userId.startsWith(\"@\")) {\n throw new ConfigurationError({\n code: \"user_id_required\",\n message: 'gateway-matrix: opts.userId must be a Matrix user id (e.g. \"@bot:matrix.org\")',\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n this.tearingDown = false;\n try {\n const cfg = {\n baseUrl: this.opts.homeserverUrl,\n accessToken: this.opts.accessToken,\n userId: this.opts.userId,\n fetchFn: this.teardownSafeFetch(),\n };\n const factory = this.opts.__clientFactory;\n this.client =\n factory === undefined\n ? (await loadMatrixSdk()).createClient(cfg)\n : (factory(cfg) as MatrixSdkClient);\n // Validate the credential BEFORE reporting success. `startClient` kicks\n // off the sync loop asynchronously and resolves whether or not the token\n // is any good — so connect() used to answer `true` for a token the server\n // rejects, leaving an operator with a healthy-looking adapter and total\n // silence. Every sibling adapter returns false here; this one did not,\n // and only a real homeserver could show it.\n await this.client.whoami();\n await this.client.startClient({ initialSyncLimit: INITIAL_SYNC_LIMIT });\n this.attachSync();\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-matrix] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n // Issue #12. `stopClient()` aborts the requests still in flight, and the\n // AbortError escapes as an UNHANDLED rejection — the rejecting promise is\n // the SDK's own `authedRequest` wrapper, which no caller catches and which\n // we cannot reach. Node has terminated on unhandled rejections by default\n // since v15, so an application calling disconnect() inside a reconnect loop\n // could be killed by its own clean shutdown. Measured against a real\n // homeserver: 7 occurrences in 8 connect/disconnect cycles.\n //\n // `teardownSafeFetch` closes it at the only seam the SDK offers. The flag is\n // set here, before the abort, and cleared by the next connect().\n this.tearingDown = true;\n this.subscription?.unsubscribe();\n this.subscription = undefined;\n this.client?.stopClient();\n this.client = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n this.aliasCache.clear();\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.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MatrixAdapter.connect() not called\" },\n };\n }\n try {\n const roomId = await this.aliasCache.resolve(this.client, out.channel.id);\n if (this.isEncrypted(roomId)) {\n this.warnEncryptedOnce(roomId);\n return {\n ok: false,\n error: {\n code: \"encrypted_room_unsupported\",\n message: `Matrix room ${roomId} is encrypted; E2EE deferred to v0.2`,\n },\n };\n }\n const res = await this.client.sendTextMessage(roomId, out.text);\n return { ok: true, messageId: res.event_id };\n } catch (err) {\n return mapMatrixError(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 (D421) — caller can drive matrix-js-sdk directly for advanced features. */\n getClient(): MatrixSdkClient | undefined {\n return this.client;\n }\n\n /** Used by tests to install a mock SDK client + flip connected flag. */\n _installClient(client: MatrixSdkClient): void {\n this.client = client;\n this.connected = true;\n this.attachSync();\n }\n\n private attachSync(): void {\n if (this.client === undefined) return;\n const client = this.client;\n const opts = {\n botUserId: this.opts.userId,\n freshnessWindowMs: this.opts.freshnessWindowMs ?? DEFAULT_FRESHNESS_MS,\n };\n this.subscription = subscribeToTimeline(\n client,\n (ev: MatrixEventLike, room: MatrixRoomLike) => {\n void this.dispatchTimelineEvent(ev, room).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] dispatchTimelineEvent failed: ${m}\\n`);\n });\n },\n opts,\n );\n }\n\n private async dispatchTimelineEvent(event: MatrixEventLike, room: MatrixRoomLike): Promise<void> {\n if (this.isEncrypted(room.roomId)) {\n this.warnEncryptedOnce(room.roomId);\n return;\n }\n const normalized = matrixEventToMessageEvent(event, room);\n if (normalized === undefined) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] handler threw: ${m}\\n`);\n }\n }\n\n private isEncrypted(roomId: string): boolean {\n if (this.client === undefined) return false;\n if (this.client.isRoomEncrypted === undefined) return false;\n try {\n return this.client.isRoomEncrypted(roomId);\n } catch {\n return false;\n }\n }\n\n private warnEncryptedOnce(roomId: string): void {\n if (this.warnedEncrypted.has(roomId)) return;\n this.warnedEncrypted.add(roomId);\n process.stderr.write(\n `[gateway-matrix] room ${roomId} is end-to-end encrypted; skipping (E2EE deferred to v0.2)\\n`,\n );\n }\n}\n\n/**\n * Narrow abort detection. `DOMException.ABORT_ERR` is 20; the message check\n * covers runtimes that report the abort without the standard name or code.\n */\nfunction isAbortError(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) return false;\n const e = err as { name?: unknown; code?: unknown; message?: unknown };\n if (e.name === \"AbortError\") return true;\n if (e.code === 20) return true;\n return typeof e.message === \"string\" && /aborted/i.test(e.message);\n}\n\ninterface MatrixRestError {\n httpStatus?: number;\n errcode?: string;\n message?: string;\n name?: string;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error mapping ladder is exhaustive — each branch maps one Matrix errcode/HTTP status to one canonical code; splitting hurts traceability.\nfunction mapMatrixError(err: unknown): SendResult {\n const e = err as MatrixRestError;\n const status = e.httpStatus ?? 0;\n if (status === 429 || e.errcode === \"M_LIMIT_EXCEEDED\") {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Matrix rate limit\" } };\n }\n if (status === 401 || status === 403 || e.errcode === \"M_FORBIDDEN\") {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Matrix permission error\" },\n };\n }\n if (status === 404 || e.errcode === \"M_NOT_FOUND\") {\n return {\n ok: false,\n error: { code: \"not_found\", message: e.message ?? \"Matrix resource not found\" },\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,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-matrix",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Matrix protocol platform adapter for @theokit/gateway. ADRs D413-D421.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -29,15 +29,10 @@
29
29
  "LICENSE",
30
30
  "CHANGELOG.md"
31
31
  ],
32
- "scripts": {
33
- "build": "tsup",
34
- "typecheck": "tsc --noEmit",
35
- "test": "vitest run"
36
- },
37
32
  "peerDependencies": {
38
- "@theokit/gateway": "workspace:^",
39
- "@theokit/sdk": "workspace:^",
40
- "matrix-js-sdk": "^32.0.0"
33
+ "@theokit/sdk": "^2.18.0",
34
+ "matrix-js-sdk": "^32.0.0",
35
+ "@theokit/gateway": "^0.5.1"
41
36
  },
42
37
  "peerDependenciesMeta": {
43
38
  "matrix-js-sdk": {
@@ -45,10 +40,16 @@
45
40
  }
46
41
  },
47
42
  "devDependencies": {
48
- "@theokit/gateway": "workspace:*",
49
- "@theokit/sdk": "workspace:*",
43
+ "@theokit/sdk": "^2.18.0",
50
44
  "tsup": "^8.5.0",
51
45
  "typescript": "^5.8.0",
52
- "vitest": "^4.1.8"
46
+ "vitest": "^4.1.8",
47
+ "zod": "^4.0.0",
48
+ "@theokit/gateway": "0.5.1"
49
+ },
50
+ "scripts": {
51
+ "build": "tsup",
52
+ "typecheck": "tsc --noEmit",
53
+ "test": "vitest run"
53
54
  }
54
- }
55
+ }