@theokit/gateway-matrix 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +50 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js.map +1 -1
- package/package.json +13 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,47 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 8cbf136: **Every published export now carries documentation.** Forty-seven public symbols shipped with no docblock at all, so a consumer hovering `DiscordAdapter`, `SlackAdapter`, `WhatsAppCloudBackend`, `ThreadStore` or any of the error classes got an empty tooltip. Coverage across the eleven packages went from 71.2% to 100% (163/163), measured over the published declarations rather than the source, because a docblock is not documentation until it survives the build.
|
|
8
|
+
|
|
9
|
+
The text says what each symbol is for and what constrains it, not what its name already says. `TelegramAdapter` records that a bot cannot enumerate its chats nor speak into one that has not spoken first. `DiscordAdapter` records that reading message content needs a privileged intent enabled in the developer portal, without which every `event.text` arrives empty and nothing says why. `WhatsAppWebBackend` records that it is unofficial and can get a number banned. `shouldDispatchSyncEvent` records that Matrix replays history on sync, which is why a freshly started bot would otherwise answer every message it can still see.
|
|
10
|
+
|
|
11
|
+
**`gateway-slack`'s README documented a type that does not exist.** Its usage example imported `GatewayMessageEvent` from `@theokit/gateway`. That name is an internal alias inside the Discord and Telegram adapters (`MessageEvent as GatewayMessageEvent`), never an export. A reader who copied the example got code that did not compile. It now imports `MessageEvent`, which is what `onInbound` actually hands the handler.
|
|
12
|
+
|
|
13
|
+
Two docblocks that attached to nothing were reattached: `acquirePidLock` in `gateway-whatsapp` had its documentation stranded thirty lines above, over a different function, and shipped undocumented as a result.
|
|
14
|
+
|
|
15
|
+
- b8ef098: **Every package now ships the licence it declares.** All twelve manifests in this repository declare `Apache-2.0`, and the repository had no `LICENSE` file at all — not at the root, and not in any package directory except `gateway-email`. So each published tarball asserted a licence while carrying none of its terms, and §4(a) of that licence requires a copy to travel with the distribution. Worse than a missing file: with no licence text anywhere, everything outside the manifests fell back to default copyright, which grants a recipient nothing.
|
|
16
|
+
|
|
17
|
+
The text is now at the repository root and inside every publishable package, byte-identical to the canonical Apache License 2.0 with the appendix filled in (`Copyright 2026 usetheo.dev`). The one pre-existing copy, in `gateway-email`, was replaced along with the rest: it carried the same truncated paragraph 4(d) found across the ecosystem, dropping "reasonable and customary use" from the NOTICE clause — a modified body under an unmodified SPDX identifier.
|
|
18
|
+
|
|
19
|
+
**The repository moved to the official `usetheokit` organization.** Existing clones and published URLs keep working through GitHub's permanent redirect; the root manifest now declares `Apache-2.0` explicitly rather than leaving the workspace root silent.
|
|
20
|
+
|
|
21
|
+
- 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
|
|
22
|
+
|
|
23
|
+
**LINE — no outbound message was ever delivered.** The adapter called the v9 SDK client with positional arguments while that client takes a single request object, so LINE received an empty request and rejected every send with a 400. Upgrade if you use this adapter at all: nothing it sent reached anyone.
|
|
24
|
+
|
|
25
|
+
**Telegram — the bot froze on long replies.** Any message over 4096 characters that began with an unclosed code span (a stray backtick) put the splitter into an infinite loop, hanging the process until it ran out of memory. Long agent answers now split correctly whatever markdown they contain.
|
|
26
|
+
|
|
27
|
+
**Mattermost — long messages silently vanished.** The adapter never split anything, so any reply over 16,383 characters was rejected by the server and the user simply saw nothing. Long replies are now split into parts Mattermost accepts.
|
|
28
|
+
|
|
29
|
+
**SMS — long messages were rejected from the hundredth part onward.** The `(i/N)` prefix outgrew the space reserved for it, pushing every later part past the provider's limit.
|
|
30
|
+
|
|
31
|
+
**Matrix and LINE — `connect()` reported success with an invalid token.** Both now verify the credential with the server before returning `true`, so a wrong token fails at startup instead of silently receiving nothing forever.
|
|
32
|
+
|
|
33
|
+
**Email and Teams — the bot could go permanently deaf.** Replacing an inbound handler and then disposing of the previous one removed the new handler as well, and the gateway stopped receiving messages with nothing logged.
|
|
34
|
+
|
|
35
|
+
Also: a `pre_inbound` hook that threw put its raw error text into the user's chat, which could expose internal details such as connection strings or tokens. Users now see only which hook failed; the detail goes to the server log, redacted.
|
|
36
|
+
|
|
37
|
+
WhatsApp additionally stops opening a second session when `connect()` is called twice, and its group mention filter no longer treats unrelated digits scattered through a message as a mention of the bot.
|
|
38
|
+
|
|
39
|
+
- 7ccb21b: Two defects that only a real server could show, both found by the live suites.
|
|
40
|
+
|
|
41
|
+
**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.
|
|
42
|
+
|
|
43
|
+
**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.
|
|
44
|
+
|
|
3
45
|
## 0.1.2
|
|
4
46
|
|
|
5
47
|
### Patch Changes
|
package/dist/index.cjs.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":["GatewayConfigurationError","BasePlatformAdapter"],"mappings":";;;;;AAYO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,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AAE,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"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/alias.ts","../src/client.ts","../src/room-state.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AE;AAAA,EAC/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 * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-matrix\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-matrix\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor() {\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\n/**\n * The room is end-to-end encrypted, which this adapter cannot read.\n *\n * E2EE is deferred to v0.2. Raised rather than silently ignoring the room, because a bot that\n * appears connected and never sees a message is far harder to diagnose than one that says why.\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\n/**\n * Resolves a Matrix room alias (`#room:server`) to its room id, remembering the answer.\n *\n * An alias resolves through a server round-trip, and the mapping effectively never changes, so\n * repeating it once per outbound message is pure latency. A value that is already a room id is\n * returned untouched, which lets callers pass either form.\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\n/**\n * Decide whether a timeline event should reach the handler.\n *\n * Matrix replays room history on sync, so a freshly started bot would otherwise answer every message\n * it can still see — which is a reply storm in a busy room and an infinite loop in a quiet one. This\n * drops the bot's own events and anything older than the freshness window. `now` is injectable so\n * the decision is testable without waiting.\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\n/** A live timeline listener, with the handle that detaches it again. */\nexport interface TimelineSubscription {\n unsubscribe(): void;\n}\n\n/**\n * The slice of `matrix-js-sdk`'s client this adapter actually uses.\n *\n * Narrow on purpose: it is what lets the sync logic be tested against a few lines of fake rather\n * than a running homeserver, and it states the real coupling to the SDK — two event methods.\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\n/**\n * Attach `handler` to the client's room timeline, filtered by {@link shouldDispatchSyncEvent}.\n *\n * Returns the subscription rather than leaving the listener attached forever: an adapter that\n * reconnects without detaching accumulates listeners, and every inbound message is then handled\n * once per reconnect.\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
|
@@ -64,14 +64,36 @@ interface SyncFilterOpts {
|
|
|
64
64
|
readonly botUserId: string;
|
|
65
65
|
readonly freshnessWindowMs: number;
|
|
66
66
|
}
|
|
67
|
+
/**
|
|
68
|
+
* Decide whether a timeline event should reach the handler.
|
|
69
|
+
*
|
|
70
|
+
* Matrix replays room history on sync, so a freshly started bot would otherwise answer every message
|
|
71
|
+
* it can still see — which is a reply storm in a busy room and an infinite loop in a quiet one. This
|
|
72
|
+
* drops the bot's own events and anything older than the freshness window. `now` is injectable so
|
|
73
|
+
* the decision is testable without waiting.
|
|
74
|
+
*/
|
|
67
75
|
declare function shouldDispatchSyncEvent(event: MatrixEventLike, opts: SyncFilterOpts, now?: number): boolean;
|
|
76
|
+
/** A live timeline listener, with the handle that detaches it again. */
|
|
68
77
|
interface TimelineSubscription {
|
|
69
78
|
unsubscribe(): void;
|
|
70
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* The slice of `matrix-js-sdk`'s client this adapter actually uses.
|
|
82
|
+
*
|
|
83
|
+
* Narrow on purpose: it is what lets the sync logic be tested against a few lines of fake rather
|
|
84
|
+
* than a running homeserver, and it states the real coupling to the SDK — two event methods.
|
|
85
|
+
*/
|
|
71
86
|
interface MatrixClientLike {
|
|
72
87
|
on(event: "Room.timeline", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;
|
|
73
88
|
off(event: "Room.timeline", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;
|
|
74
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Attach `handler` to the client's room timeline, filtered by {@link shouldDispatchSyncEvent}.
|
|
92
|
+
*
|
|
93
|
+
* Returns the subscription rather than leaving the listener attached forever: an adapter that
|
|
94
|
+
* reconnects without detaching accumulates listeners, and every inbound message is then handled
|
|
95
|
+
* once per reconnect.
|
|
96
|
+
*/
|
|
75
97
|
declare function subscribeToTimeline(client: MatrixClientLike, handler: (event: MatrixEventLike, room: MatrixRoomLike) => void, opts: SyncFilterOpts): TimelineSubscription;
|
|
76
98
|
|
|
77
99
|
/**
|
|
@@ -165,6 +187,13 @@ interface AliasResolverClient {
|
|
|
165
187
|
room_id: string;
|
|
166
188
|
}>;
|
|
167
189
|
}
|
|
190
|
+
/**
|
|
191
|
+
* Resolves a Matrix room alias (`#room:server`) to its room id, remembering the answer.
|
|
192
|
+
*
|
|
193
|
+
* An alias resolves through a server round-trip, and the mapping effectively never changes, so
|
|
194
|
+
* repeating it once per outbound message is pure latency. A value that is already a room id is
|
|
195
|
+
* returned untouched, which lets callers pass either form.
|
|
196
|
+
*/
|
|
168
197
|
declare class AliasCache {
|
|
169
198
|
private readonly cache;
|
|
170
199
|
/** Returns the room id; resolves aliases via the client + caches. */
|
|
@@ -183,13 +212,34 @@ declare class AliasCache {
|
|
|
183
212
|
|
|
184
213
|
/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
|
|
185
214
|
type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;
|
|
215
|
+
/**
|
|
216
|
+
* Misconfiguration of this adapter, raised before any network call.
|
|
217
|
+
*
|
|
218
|
+
* Extends the shared core base so every gateway package reports configuration faults in one shape:
|
|
219
|
+
* a structured `code` the caller can branch on, tagged with `"gateway-matrix"` as the origin. A
|
|
220
|
+
* missing credential or an unsupported option is a programmer error, not a transient failure —
|
|
221
|
+
* these are never retried.
|
|
222
|
+
*/
|
|
186
223
|
declare class ConfigurationError extends GatewayConfigurationError {
|
|
187
224
|
readonly name = "ConfigurationError";
|
|
188
225
|
constructor(opts: ConfigurationErrorOptions);
|
|
189
226
|
}
|
|
227
|
+
/**
|
|
228
|
+
* The platform SDK this adapter needs is declared as a peer dependency and is not installed.
|
|
229
|
+
*
|
|
230
|
+
* Raised at connect time rather than at import, so a project that installs several gateway packages
|
|
231
|
+
* only pays for the SDKs of the ones it actually starts. The message names the exact package and
|
|
232
|
+
* the command that installs it.
|
|
233
|
+
*/
|
|
190
234
|
declare class SDKNotInstalledError extends ConfigurationError {
|
|
191
235
|
constructor();
|
|
192
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* The room is end-to-end encrypted, which this adapter cannot read.
|
|
239
|
+
*
|
|
240
|
+
* E2EE is deferred to v0.2. Raised rather than silently ignoring the room, because a bot that
|
|
241
|
+
* appears connected and never sees a message is far harder to diagnose than one that says why.
|
|
242
|
+
*/
|
|
193
243
|
declare class EncryptedRoomError extends ConfigurationError {
|
|
194
244
|
constructor(roomId: string);
|
|
195
245
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -64,14 +64,36 @@ interface SyncFilterOpts {
|
|
|
64
64
|
readonly botUserId: string;
|
|
65
65
|
readonly freshnessWindowMs: number;
|
|
66
66
|
}
|
|
67
|
+
/**
|
|
68
|
+
* Decide whether a timeline event should reach the handler.
|
|
69
|
+
*
|
|
70
|
+
* Matrix replays room history on sync, so a freshly started bot would otherwise answer every message
|
|
71
|
+
* it can still see — which is a reply storm in a busy room and an infinite loop in a quiet one. This
|
|
72
|
+
* drops the bot's own events and anything older than the freshness window. `now` is injectable so
|
|
73
|
+
* the decision is testable without waiting.
|
|
74
|
+
*/
|
|
67
75
|
declare function shouldDispatchSyncEvent(event: MatrixEventLike, opts: SyncFilterOpts, now?: number): boolean;
|
|
76
|
+
/** A live timeline listener, with the handle that detaches it again. */
|
|
68
77
|
interface TimelineSubscription {
|
|
69
78
|
unsubscribe(): void;
|
|
70
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* The slice of `matrix-js-sdk`'s client this adapter actually uses.
|
|
82
|
+
*
|
|
83
|
+
* Narrow on purpose: it is what lets the sync logic be tested against a few lines of fake rather
|
|
84
|
+
* than a running homeserver, and it states the real coupling to the SDK — two event methods.
|
|
85
|
+
*/
|
|
71
86
|
interface MatrixClientLike {
|
|
72
87
|
on(event: "Room.timeline", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;
|
|
73
88
|
off(event: "Room.timeline", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;
|
|
74
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Attach `handler` to the client's room timeline, filtered by {@link shouldDispatchSyncEvent}.
|
|
92
|
+
*
|
|
93
|
+
* Returns the subscription rather than leaving the listener attached forever: an adapter that
|
|
94
|
+
* reconnects without detaching accumulates listeners, and every inbound message is then handled
|
|
95
|
+
* once per reconnect.
|
|
96
|
+
*/
|
|
75
97
|
declare function subscribeToTimeline(client: MatrixClientLike, handler: (event: MatrixEventLike, room: MatrixRoomLike) => void, opts: SyncFilterOpts): TimelineSubscription;
|
|
76
98
|
|
|
77
99
|
/**
|
|
@@ -165,6 +187,13 @@ interface AliasResolverClient {
|
|
|
165
187
|
room_id: string;
|
|
166
188
|
}>;
|
|
167
189
|
}
|
|
190
|
+
/**
|
|
191
|
+
* Resolves a Matrix room alias (`#room:server`) to its room id, remembering the answer.
|
|
192
|
+
*
|
|
193
|
+
* An alias resolves through a server round-trip, and the mapping effectively never changes, so
|
|
194
|
+
* repeating it once per outbound message is pure latency. A value that is already a room id is
|
|
195
|
+
* returned untouched, which lets callers pass either form.
|
|
196
|
+
*/
|
|
168
197
|
declare class AliasCache {
|
|
169
198
|
private readonly cache;
|
|
170
199
|
/** Returns the room id; resolves aliases via the client + caches. */
|
|
@@ -183,13 +212,34 @@ declare class AliasCache {
|
|
|
183
212
|
|
|
184
213
|
/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
|
|
185
214
|
type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;
|
|
215
|
+
/**
|
|
216
|
+
* Misconfiguration of this adapter, raised before any network call.
|
|
217
|
+
*
|
|
218
|
+
* Extends the shared core base so every gateway package reports configuration faults in one shape:
|
|
219
|
+
* a structured `code` the caller can branch on, tagged with `"gateway-matrix"` as the origin. A
|
|
220
|
+
* missing credential or an unsupported option is a programmer error, not a transient failure —
|
|
221
|
+
* these are never retried.
|
|
222
|
+
*/
|
|
186
223
|
declare class ConfigurationError extends GatewayConfigurationError {
|
|
187
224
|
readonly name = "ConfigurationError";
|
|
188
225
|
constructor(opts: ConfigurationErrorOptions);
|
|
189
226
|
}
|
|
227
|
+
/**
|
|
228
|
+
* The platform SDK this adapter needs is declared as a peer dependency and is not installed.
|
|
229
|
+
*
|
|
230
|
+
* Raised at connect time rather than at import, so a project that installs several gateway packages
|
|
231
|
+
* only pays for the SDKs of the ones it actually starts. The message names the exact package and
|
|
232
|
+
* the command that installs it.
|
|
233
|
+
*/
|
|
190
234
|
declare class SDKNotInstalledError extends ConfigurationError {
|
|
191
235
|
constructor();
|
|
192
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* The room is end-to-end encrypted, which this adapter cannot read.
|
|
239
|
+
*
|
|
240
|
+
* E2EE is deferred to v0.2. Raised rather than silently ignoring the room, because a bot that
|
|
241
|
+
* appears connected and never sees a message is far harder to diagnose than one that says why.
|
|
242
|
+
*/
|
|
193
243
|
declare class EncryptedRoomError extends ConfigurationError {
|
|
194
244
|
constructor(roomId: string);
|
|
195
245
|
}
|
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":";;;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,cAAiC,kBAAA,CAAmB;AAAA,EACzD,YAAY,MAAA,EAAgB;AAC1B,IAAA,KAAA,CAAM;AAAA,MACJ,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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"]}
|
|
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":";;;AAoBO,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;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,WAAA,GAAc;AACZ,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EACE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AAA,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 * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-matrix\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-matrix\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor() {\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\n/**\n * The room is end-to-end encrypted, which this adapter cannot read.\n *\n * E2EE is deferred to v0.2. Raised rather than silently ignoring the room, because a bot that\n * appears connected and never sees a message is far harder to diagnose than one that says why.\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\n/**\n * Resolves a Matrix room alias (`#room:server`) to its room id, remembering the answer.\n *\n * An alias resolves through a server round-trip, and the mapping effectively never changes, so\n * repeating it once per outbound message is pure latency. A value that is already a room id is\n * returned untouched, which lets callers pass either form.\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\n/**\n * Decide whether a timeline event should reach the handler.\n *\n * Matrix replays room history on sync, so a freshly started bot would otherwise answer every message\n * it can still see — which is a reply storm in a busy room and an infinite loop in a quiet one. This\n * drops the bot's own events and anything older than the freshness window. `now` is injectable so\n * the decision is testable without waiting.\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\n/** A live timeline listener, with the handle that detaches it again. */\nexport interface TimelineSubscription {\n unsubscribe(): void;\n}\n\n/**\n * The slice of `matrix-js-sdk`'s client this adapter actually uses.\n *\n * Narrow on purpose: it is what lets the sync logic be tested against a few lines of fake rather\n * than a running homeserver, and it states the real coupling to the SDK — two event methods.\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\n/**\n * Attach `handler` to the client's room timeline, filtered by {@link shouldDispatchSyncEvent}.\n *\n * Returns the subscription rather than leaving the listener attached forever: an adapter that\n * reconnects without detaching accumulates listeners, and every inbound message is then handled\n * once per reconnect.\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,8 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway-matrix",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Matrix protocol platform adapter for @theokit/gateway. ADRs D413-D421.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/usetheokit/theokit-gateways.git",
|
|
9
|
+
"directory": "packages/gateway-matrix"
|
|
10
|
+
},
|
|
6
11
|
"type": "module",
|
|
7
12
|
"engines": {
|
|
8
13
|
"node": ">=22.12.0"
|
|
@@ -30,9 +35,9 @@
|
|
|
30
35
|
"CHANGELOG.md"
|
|
31
36
|
],
|
|
32
37
|
"peerDependencies": {
|
|
38
|
+
"@theokit/gateway": ">=0.6.0 <1.0.0",
|
|
33
39
|
"@theokit/sdk": "^2.18.0",
|
|
34
|
-
"matrix-js-sdk": "^32.0.0"
|
|
35
|
-
"@theokit/gateway": "^0.5.1"
|
|
40
|
+
"matrix-js-sdk": "^32.0.0"
|
|
36
41
|
},
|
|
37
42
|
"peerDependenciesMeta": {
|
|
38
43
|
"matrix-js-sdk": {
|
|
@@ -45,7 +50,11 @@
|
|
|
45
50
|
"typescript": "^5.8.0",
|
|
46
51
|
"vitest": "^4.1.8",
|
|
47
52
|
"zod": "^4.0.0",
|
|
48
|
-
"@theokit/gateway": "0.
|
|
53
|
+
"@theokit/gateway": "0.6.0"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public",
|
|
57
|
+
"provenance": true
|
|
49
58
|
},
|
|
50
59
|
"scripts": {
|
|
51
60
|
"build": "tsup",
|