@theokit/gateway-matrix 0.4.0 → 0.6.0

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/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/replace-content.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,qFAAA;AAAA,MACF,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;AAQO,IAAM,kBAAA,GAAN,cAAiC,kBAAA,CAAmB;AAAA,EACzD,YAAY,MAAA,EAAgB;AAC1B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,4BAAA;AAAA,MACN,OAAA,EAAS,wBAAwB,MAAM,CAAA,gDAAA,CAAA;AAAA,MACvC,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;;;ACnCO,IAAM,aAAN,MAAiB;AAAA,EACL,KAAA,uBAAY,GAAA,EAAoB;AAAA;AAAA,EAGjD,MAAM,OAAA,CAAQ,MAAA,EAA6B,OAAA,EAAkC;AAC3E,IAAA,IAAI,OAAA,CAAQ,UAAA,CAAW,GAAG,CAAA,EAAG,OAAO,OAAA;AACpC,IAAA,IAAI,CAAC,OAAA,CAAQ,UAAA,CAAW,GAAG,CAAA,EAAG;AAC5B,MAAA,MAAM,IAAI,kBAAA,CAAmB;AAAA,QA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F","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 /**\n * Send a message whose content object the caller composes.\n *\n * `sendTextMessage` is a convenience that hard-codes `msgtype: m.text` and a bare `body`, so\n * it has nowhere to put `formatted_body` — the field Matrix documents for markup. Honouring\n * `OutboundMessage.format` therefore needs the general call, not a new argument on the\n * convenience one.\n */\n sendMessage?(roomId: string, content: Record<string, unknown>): 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 * The content of a Matrix `m.replace` event — how an edit is expressed on Matrix.\n *\n * Matrix has no call that changes an event. An edit is a NEW event whose `m.relates_to` names the\n * original with `rel_type: \"m.replace\"` and whose `m.new_content` holds the replacement; clients\n * that understand replacements render `m.new_content` over the original, and the rest show the\n * outer `body`, which carries the conventional `* ` prefix (Matrix Client-Server API v1.12,\n * § Event replacements).\n *\n * `formatted_body` follows the rule `sendMessage` follows: only `format: \"html\"` may declare\n * `org.matrix.custom.html`, because the declaration promises every client the field IS HTML.\n *\n * @internal\n */\n\nimport type { OutboundMessage } from \"@theokit/gateway\";\n\nconst HTML_FORMAT = \"org.matrix.custom.html\";\n\n/** The `m.text` content for `text`, with `formatted_body` only when the caller declared html. */\nfunction textContent(text: string, html: boolean): Record<string, unknown> {\n return html\n ? { msgtype: \"m.text\", body: text, format: HTML_FORMAT, formatted_body: text }\n : { msgtype: \"m.text\", body: text };\n}\n\n/** Build the content of an event that replaces `originalEventId` with `out.text`. */\nexport function replaceContent(\n originalEventId: string,\n out: OutboundMessage,\n): Record<string, unknown> {\n const html = out.format === \"html\";\n return {\n ...textContent(`* ${out.text}`, html),\n \"m.new_content\": textContent(out.text, html),\n \"m.relates_to\": { rel_type: \"m.replace\", event_id: originalEventId },\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 { replaceContent } from \"./replace-content.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.sendHonouringFormat(roomId, out);\n return { ok: true, messageId: res.event_id };\n } catch (err) {\n return mapMatrixError(err);\n }\n }\n\n /**\n * Matrix edits through an `m.replace` event, so the capability holds from construction: it does\n * not depend on a connection or on which client is injected later.\n */\n override readonly supportsEdit = true;\n\n /**\n * Replace a message this bot sent with an `m.replace` event, and return the ORIGINAL event id.\n *\n * Returning the original id lets a second edit target the same message: clients apply the\n * newest replacement of the original, not a replacement of a replacement. There is no length\n * check, since Matrix has no splitter. An injected client without `sendMessage` cannot carry\n * the relation and answers `edit_unsupported`. The room resolves through the same alias cache\n * as `sendMessage`, so a `#alias` this adapter never resolved costs one lookup before the event.\n * Unlike `sendMessage`, a refused markup is not retried as plain text: one request, one answer.\n */\n override async editMessage(messageId: string, 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 const client = this.client;\n if (client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MatrixAdapter.connect() not called\" },\n };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n if (client.sendMessage === undefined) {\n return {\n ok: false,\n error: {\n code: \"edit_unsupported\",\n message: \"matrix client has no sendMessage, so it cannot send an m.replace event\",\n },\n };\n }\n try {\n const roomId = await this.aliasCache.resolve(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 this.warnFormatUnsupported(out.format);\n await client.sendMessage(roomId, replaceContent(messageId, out));\n } catch (err) {\n return mapMatrixError(err);\n }\n return { ok: true, messageId };\n }\n\n /**\n * Send `out`, letting the caller's declared `format` decide the shape.\n *\n * Matrix carries markup in `formatted_body` and declares its type in `format`, whose only\n * value is `org.matrix.custom.html`. That declaration is a promise to every client that the\n * field IS HTML — so only `format: \"html\"` may use it.\n *\n * **`markdown` deliberately does not.** The first version of this method put the caller's\n * markdown into `formatted_body` and declared it HTML, which was worse than the bug it meant\n * to fix: `**bold**` still rendered as literal asterisks because markdown is not HTML, AND a\n * `<div>` anywhere in the text was parsed as a tag and dropped, so the reader received words\n * the sender never wrote and lost the ones they did. Caught in review; the test that\n * \"proved\" it was asserting the defect.\n *\n * So Matrix joins LINE, SMS and WhatsApp: it has no markdown mode, and the honest handling is\n * to say once that the declaration is being dropped rather than to fake it.\n *\n * Falls back to `sendTextMessage` when the client does not expose `sendMessage`: it is\n * optional on {@link MatrixSdkClient} because a consumer may inject a narrower double, and\n * losing the formatting is better than losing the message.\n *\n * @internal\n */\n private async sendHonouringFormat(\n roomId: string,\n out: OutboundMessage,\n ): Promise<{ event_id: string }> {\n const client = this.client as MatrixSdkClient;\n if (out.format !== \"html\" || client.sendMessage === undefined) {\n this.warnFormatUnsupported(out.format);\n return await client.sendTextMessage(roomId, out.text);\n }\n try {\n return await client.sendMessage(roomId, {\n msgtype: \"m.text\",\n body: out.text,\n format: \"org.matrix.custom.html\",\n formatted_body: out.text,\n });\n } catch (err) {\n // ADR-2: an undelivered message is worse than an unformatted one — the caller loses the\n // content and the user sees nothing, which is strictly worse than losing the markup.\n //\n // The discrimination is the whole guard. A bare `catch` would swallow an expired token as\n // a formatting problem and retry into the same 401, turning an actionable error into a\n // silent double failure. Only a request the server judged malformed is retried.\n if (!isMalformedRequest(err)) throw err;\n process.stderr.write(\n \"[gateway-matrix] homeserver rejected the formatted body; retrying as plain text\\n\",\n );\n return await client.sendTextMessage(roomId, out.text);\n }\n }\n\n /** Whether the \"no markdown mode here\" warning has already been emitted. */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared `markdown` has nowhere to go on this platform.\n *\n * Matrix's only markup type is HTML. A caller declaring `markdown` is asking for something\n * the protocol does not have, and putting the markdown in the HTML field would corrupt it.\n *\n * @internal\n */\n private warnFormatUnsupported(format: OutboundMessage[\"format\"]): void {\n if (format === undefined || format === \"plain\" || format === \"html\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-matrix] format=\"${format}\" was declared, and Matrix has no markdown mode — ` +\n \"its only markup type is HTML. Sending as plain text; this is logged once.\\n\",\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 * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.inboundHandler, event);\n }\n}\n\n/**\n * 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/**\n * Did the homeserver judge the REQUEST malformed, as opposed to refusing the sender?\n *\n * Narrow by construction: a 400 with `M_BAD_JSON` or `M_INVALID_PARAM` is the server saying it\n * could not parse what it was given. A 401, 403 or 429 is about who is asking or how often,\n * and retrying those without markup would fail identically while reporting the wrong cause.\n */\nfunction isMalformedRequest(err: unknown): boolean {\n const e = err as MatrixRestError;\n if (e.httpStatus !== 400) return false;\n return e.errcode === \"M_BAD_JSON\" || e.errcode === \"M_INVALID_PARAM\";\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/invite.ts","../src/room-state.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/replace-content.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,C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AA,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.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 /**\n * Send a message whose content object the caller composes.\n *\n * `sendTextMessage` is a convenience that hard-codes `msgtype: m.text` and a bare `body`, so\n * it has nowhere to put `formatted_body` — the field Matrix documents for markup. Honouring\n * `OutboundMessage.format` therefore needs the general call, not a new argument on the\n * convenience one.\n */\n sendMessage?(roomId: string, content: Record<string, unknown>): Promise<{ event_id: string }>;\n /** Send a room event of `eventType` (used for `m.reaction`). */\n sendEvent?(\n roomId: string,\n eventType: string,\n content: Record<string, unknown>,\n ): Promise<{ event_id: string }>;\n /** `PUT /rooms/{roomId}/typing/{userId}`; present on matrix-js-sdk's client. */\n sendTyping?(roomId: string, isTyping: boolean, timeoutMs: number): Promise<unknown>;\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n /** Join a room (used to accept an invite). */\n joinRoom?(roomId: string): Promise<unknown>;\n getRooms?(): import(\"./invite.js\").InviteRoomLike[];\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 * Auto-join for room invites.\n *\n * Matrix delivers an invite as the bot's own `m.room.member` event with `membership: invite`.\n * `matrix-js-sdk` surfaces it as `RoomMember.membership` (live) and leaves invited rooms in\n * `getRooms()` with `getMyMembership() === \"invite\"` (the ones pending at start). Both paths end\n * in {@link handleInvite}, which asks the host's `acceptInvite` and joins only on `true`.\n */\n\nexport interface InviteMemberLike {\n readonly userId: string;\n readonly roomId: string;\n readonly membership?: string;\n}\n\nexport interface InviteEventLike {\n getSender(): string | undefined;\n}\n\nexport interface InviteRoomLike {\n readonly roomId: string;\n getMyMembership?(): string;\n /** The inviter is the sender of the bot's own member event. */\n getMember?(userId: string): { events?: { member?: InviteEventLike } } | null;\n}\n\n/** The slice of the SDK client the invite path uses. */\nexport interface InviteClientLike {\n on(event: string, listener: (...args: never[]) => void): void;\n off(event: string, listener: (...args: never[]) => void): void;\n joinRoom(roomId: string): Promise<unknown>;\n getRooms?(): InviteRoomLike[];\n}\n\nexport interface InviteOpts {\n readonly botUserId: string;\n readonly acceptInvite: (inviter: string, roomId: string) => boolean | Promise<boolean>;\n}\n\nfunction warn(msg: string): void {\n process.stderr.write(`[gateway-matrix] ${msg}\\n`);\n}\n\n/** Join `roomId` when the host accepts `inviter`; a refusal or a failure leaves the invite pending. */\nexport async function handleInvite(\n client: InviteClientLike,\n opts: InviteOpts,\n inviter: string,\n roomId: string,\n seen: Set<string>,\n): Promise<void> {\n if (seen.has(roomId)) return;\n seen.add(roomId);\n try {\n if (!(await opts.acceptInvite(inviter, roomId))) return;\n await client.joinRoom(roomId);\n } catch (err) {\n // Forget it so a later sync can retry.\n seen.delete(roomId);\n warn(`join of ${roomId} failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\n/**\n * Watch for invites to the bot: live ones and those already pending. Returns the detach function.\n */\nexport function subscribeToInvites(client: InviteClientLike, opts: InviteOpts): () => void {\n const seen = new Set<string>();\n const run = (inviter: string, roomId: string): void => {\n void handleInvite(client, opts, inviter, roomId, seen).catch((err: unknown) => {\n warn(`invite handling failed: ${err instanceof Error ? err.message : String(err)}`);\n });\n };\n const onMember = (event: InviteEventLike, member: InviteMemberLike): void => {\n if (member.userId !== opts.botUserId || member.membership !== \"invite\") return;\n run(event.getSender() ?? \"\", member.roomId);\n };\n const scanPending = (): void => {\n for (const room of client.getRooms?.() ?? []) {\n if (room.getMyMembership?.() !== \"invite\") continue;\n const inviter = room.getMember?.(opts.botUserId)?.events?.member?.getSender() ?? \"\";\n run(inviter, room.roomId);\n }\n };\n // `sync` fires on every sync state change, so invites pending at start are caught once the\n // first sync has produced the room list.\n client.on(\"RoomMember.membership\", onMember as never);\n client.on(\"sync\", scanPending as never);\n scanPending();\n return () => {\n client.off(\"RoomMember.membership\", onMember as never);\n client.off(\"sync\", scanPending as never);\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 * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"matrix adapter cannot send attachments\" },\n };\n}\n","/**\n * The content of a Matrix `m.replace` event — how an edit is expressed on Matrix.\n *\n * Matrix has no call that changes an event. An edit is a NEW event whose `m.relates_to` names the\n * original with `rel_type: \"m.replace\"` and whose `m.new_content` holds the replacement; clients\n * that understand replacements render `m.new_content` over the original, and the rest show the\n * outer `body`, which carries the conventional `* ` prefix (Matrix Client-Server API v1.12,\n * § Event replacements).\n *\n * `formatted_body` follows the rule `sendMessage` follows: only `format: \"html\"` may declare\n * `org.matrix.custom.html`, because the declaration promises every client the field IS HTML.\n *\n * @internal\n */\n\nimport type { OutboundMessage } from \"@theokit/gateway\";\n\nconst HTML_FORMAT = \"org.matrix.custom.html\";\n\n/** The `m.text` content for `text`, with `formatted_body` only when the caller declared html. */\nfunction textContent(text: string, html: boolean): Record<string, unknown> {\n return html\n ? { msgtype: \"m.text\", body: text, format: HTML_FORMAT, formatted_body: text }\n : { msgtype: \"m.text\", body: text };\n}\n\n/** Build the content of an event that replaces `originalEventId` with `out.text`. */\nexport function replaceContent(\n originalEventId: string,\n out: OutboundMessage,\n): Record<string, unknown> {\n const html = out.format === \"html\";\n return {\n ...textContent(`* ${out.text}`, html),\n \"m.new_content\": textContent(out.text, html),\n \"m.relates_to\": { rel_type: \"m.replace\", event_id: originalEventId },\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 { subscribeToInvites } from \"./invite.js\";\nimport { matrixEventToMessageEvent } from \"./normalize.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { replaceContent } from \"./replace-content.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 unsubscribeInvites: (() => void) | 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 // A credential refusal is final: `false` tells the runner not to retry. Anything else (the\n // homeserver is down, DNS, 5xx) is thrown so a runner with a reconnect policy retries it.\n const rest = err as MatrixRestError | null;\n if (\n rest?.httpStatus === 401 ||\n rest?.httpStatus === 403 ||\n rest?.errcode === \"M_UNKNOWN_TOKEN\"\n ) {\n return false;\n }\n throw err;\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.unsubscribeInvites?.();\n this.unsubscribeInvites = 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 return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(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.sendHonouringFormat(roomId, out);\n return { ok: true, messageId: res.event_id };\n } catch (err) {\n return mapMatrixError(err);\n }\n }\n\n /**\n * Matrix edits through an `m.replace` event, so the capability holds from construction: it does\n * not depend on a connection or on which client is injected later.\n */\n override readonly supportsEdit = true;\n\n /**\n * Replace a message this bot sent with an `m.replace` event, and return the ORIGINAL event id.\n *\n * Returning the original id lets a second edit target the same message: clients apply the\n * newest replacement of the original, not a replacement of a replacement. There is no length\n * check, since Matrix has no splitter. An injected client without `sendMessage` cannot carry\n * the relation and answers `edit_unsupported`. The room resolves through the same alias cache\n * as `sendMessage`, so a `#alias` this adapter never resolved costs one lookup before the event.\n * Unlike `sendMessage`, a refused markup is not retried as plain text: one request, one answer.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, 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 const client = this.client;\n if (client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MatrixAdapter.connect() not called\" },\n };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n if (client.sendMessage === undefined) {\n return {\n ok: false,\n error: {\n code: \"edit_unsupported\",\n message: \"matrix client has no sendMessage, so it cannot send an m.replace event\",\n },\n };\n }\n try {\n const roomId = await this.aliasCache.resolve(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 this.warnFormatUnsupported(out.format);\n await client.sendMessage(roomId, replaceContent(messageId, out));\n } catch (err) {\n return mapMatrixError(err);\n }\n return { ok: true, messageId };\n }\n\n /** Matrix expires a typing notice after its timeout; the runner renews it while the turn runs. */\n override async startTyping(channelId: string): Promise<void> {\n await this.setTyping(channelId, true);\n }\n\n override async stopTyping(channelId: string): Promise<void> {\n await this.setTyping(channelId, false);\n }\n\n private async setTyping(channelId: string, typing: boolean): Promise<void> {\n const client = this.client;\n if (channelId.length === 0 || client?.sendTyping === undefined) return;\n try {\n const roomId = await this.aliasCache.resolve(client, channelId);\n await client.sendTyping(roomId, typing, 10_000);\n } catch {\n /* cosmetic — swallow */\n }\n }\n\n override async react(channelId: string, messageId: string, emoji: string): Promise<SendResult> {\n if (channelId.length === 0 || messageId.length === 0 || emoji.length === 0) {\n return {\n ok: false,\n error: { code: \"invalid_reaction\", message: \"room, event id and emoji are required\" },\n };\n }\n const client = this.client;\n if (client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MatrixAdapter.connect() not called\" },\n };\n }\n if (client.sendEvent === undefined) {\n return {\n ok: false,\n error: { code: \"react_unsupported\", message: \"matrix client has no sendEvent\" },\n };\n }\n try {\n const roomId = await this.aliasCache.resolve(client, channelId);\n await client.sendEvent(roomId, \"m.reaction\", {\n \"m.relates_to\": { rel_type: \"m.annotation\", event_id: messageId, key: emoji },\n });\n } catch (err) {\n return mapMatrixError(err);\n }\n return { ok: true, messageId };\n }\n\n /**\n * Send `out`, letting the caller's declared `format` decide the shape.\n *\n * Matrix carries markup in `formatted_body` and declares its type in `format`, whose only\n * value is `org.matrix.custom.html`. That declaration is a promise to every client that the\n * field IS HTML — so only `format: \"html\"` may use it.\n *\n * **`markdown` deliberately does not.** The first version of this method put the caller's\n * markdown into `formatted_body` and declared it HTML, which was worse than the bug it meant\n * to fix: `**bold**` still rendered as literal asterisks because markdown is not HTML, AND a\n * `<div>` anywhere in the text was parsed as a tag and dropped, so the reader received words\n * the sender never wrote and lost the ones they did. Caught in review; the test that\n * \"proved\" it was asserting the defect.\n *\n * So Matrix joins LINE, SMS and WhatsApp: it has no markdown mode, and the honest handling is\n * to say once that the declaration is being dropped rather than to fake it.\n *\n * Falls back to `sendTextMessage` when the client does not expose `sendMessage`: it is\n * optional on {@link MatrixSdkClient} because a consumer may inject a narrower double, and\n * losing the formatting is better than losing the message.\n *\n * @internal\n */\n private async sendHonouringFormat(\n roomId: string,\n out: OutboundMessage,\n ): Promise<{ event_id: string }> {\n const client = this.client as MatrixSdkClient;\n if (out.format !== \"html\" || client.sendMessage === undefined) {\n this.warnFormatUnsupported(out.format);\n return await client.sendTextMessage(roomId, out.text);\n }\n try {\n return await client.sendMessage(roomId, {\n msgtype: \"m.text\",\n body: out.text,\n format: \"org.matrix.custom.html\",\n formatted_body: out.text,\n });\n } catch (err) {\n // ADR-2: an undelivered message is worse than an unformatted one — the caller loses the\n // content and the user sees nothing, which is strictly worse than losing the markup.\n //\n // The discrimination is the whole guard. A bare `catch` would swallow an expired token as\n // a formatting problem and retry into the same 401, turning an actionable error into a\n // silent double failure. Only a request the server judged malformed is retried.\n if (!isMalformedRequest(err)) throw err;\n process.stderr.write(\n \"[gateway-matrix] homeserver rejected the formatted body; retrying as plain text\\n\",\n );\n return await client.sendTextMessage(roomId, out.text);\n }\n }\n\n /** Whether the \"no markdown mode here\" warning has already been emitted. */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared `markdown` has nowhere to go on this platform.\n *\n * Matrix's only markup type is HTML. A caller declaring `markdown` is asking for something\n * the protocol does not have, and putting the markdown in the HTML field would corrupt it.\n *\n * @internal\n */\n private warnFormatUnsupported(format: OutboundMessage[\"format\"]): void {\n if (format === undefined || format === \"plain\" || format === \"html\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-matrix] format=\"${format}\" was declared, and Matrix has no markdown mode — ` +\n \"its only markup type is HTML. Sending as plain text; this is logged once.\\n\",\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 const acceptInvite = this.opts.acceptInvite;\n if (acceptInvite !== undefined && client.joinRoom !== undefined) {\n this.unsubscribeInvites?.();\n this.unsubscribeInvites = subscribeToInvites(\n client as unknown as Parameters<typeof subscribeToInvites>[0],\n { botUserId: this.opts.userId, acceptInvite },\n );\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.passesMentionGate(normalized)) 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 /**\n * Whether an event may reach the handler: always for a DM or with `requireMention` off,\n * otherwise only when the content mentions the bot. Both `deliver()` and the sync path call it,\n * so the two entries cannot disagree.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (event.channel.type === \"dm\" || !(this.opts.requireMention ?? true)) return true;\n const botId = this.opts.userId;\n const raw = event.platform === \"matrix\" ? event.matrix.raw : undefined;\n const content = (raw as Partial<MatrixEventLike> | undefined)?.getContent?.();\n if (content === undefined) return event.text.includes(botId);\n const mentions = content[\"m.mentions\"];\n if (mentions !== undefined) return mentions.user_ids?.includes(botId) ?? false;\n return (content.body ?? \"\").includes(botId) || (content.formatted_body ?? \"\").includes(botId);\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 * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * The mention gate runs first, as on the sync path: an event it drops answers `\"ok\"`, with or\n * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its\n * throw is named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.inboundHandler, event);\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/**\n * Did the homeserver judge the REQUEST malformed, as opposed to refusing the sender?\n *\n * Narrow by construction: a 400 with `M_BAD_JSON` or `M_INVALID_PARAM` is the server saying it\n * could not parse what it was given. A 401, 403 or 429 is about who is asking or how often,\n * and retrying those without markup would fail identically while reporting the wrong cause.\n */\nfunction isMalformedRequest(err: unknown): boolean {\n const e = err as MatrixRestError;\n if (e.httpStatus !== 400) return false;\n return e.errcode === \"M_BAD_JSON\" || e.errcode === \"M_INVALID_PARAM\";\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error mapping ladder is exhaustive — each branch maps one Matrix errcode/HTTP status to one canonical code; splitting hurts traceability.\nfunction mapMatrixError(err: unknown): SendResult {\n const e = err as MatrixRestError;\n const status = e.httpStatus ?? 0;\n if (status === 429 || e.errcode === \"M_LIMIT_EXCEEDED\") {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Matrix rate limit\" } };\n }\n if (status === 401 || status === 403 || e.errcode === \"M_FORBIDDEN\") {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Matrix permission error\" },\n };\n }\n if (status === 404 || e.errcode === \"M_NOT_FOUND\") {\n return {\n ok: false,\n error: { code: \"not_found\", message: e.message ?? \"Matrix resource not found\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-matrix",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Matrix protocol platform adapter for @theokit/gateway. ADRs D413-D421.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -53,7 +53,7 @@
53
53
  "typescript": "5.9.3",
54
54
  "vitest": "^4.1.11",
55
55
  "zod": "^4.0.0",
56
- "@theokit/gateway": "0.12.0"
56
+ "@theokit/gateway": "0.15.0"
57
57
  },
58
58
  "publishConfig": {
59
59
  "access": "public",