@theokit/gateway-matrix 0.6.0 → 0.7.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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - bc799e9: Export `matrixChannel`, `mattermostChannel` and `emailChannel`: `ChannelDescriptor`s with `MATRIX_*`, `MATTERMOST_*` and `EMAIL_*` environment bindings for `createChannels` and `configFromEnv`. The peer range on `@theokit/gateway` is now `>=0.21.0`.
8
+
9
+ ### Patch Changes
10
+
11
+ - fc94485: The email, IRC, Matrix, Nextcloud Talk and Signal channel descriptors build their configuration fields with the shared `field` helper, and email and Matrix read their env-string numbers and booleans through one shared reader instead of two copies. The descriptors and the values they accept are unchanged.
12
+
3
13
  ## 0.6.0
4
14
 
5
15
  ### Minor Changes
package/README.md CHANGED
@@ -111,6 +111,29 @@ Aliases are resolved + cached on first use. If the admin renames an alias mid-pr
111
111
 
112
112
  The adapter doesn't handle federation — Matrix protocol does. Your bot in `@theo-bot:matrix.org` can be added to rooms by users on any homeserver and the conversation flows transparently. Outbound performance varies with remote homeserver latency; failure modes (e.g. remote unreachable) surface as `SendResult{send_failed}`.
113
113
 
114
+ ## Channel descriptor
115
+
116
+ `matrixChannel` describes the channel as data for `createChannels` and `configFromEnv` from `@theokit/gateway`. Its transport is `socket`.
117
+
118
+ ```ts
119
+ import { configFromEnv, createChannels } from "@theokit/gateway";
120
+ import { matrixChannel } from "@theokit/gateway-matrix";
121
+
122
+ const { config, missing, secrets } = configFromEnv(matrixChannel, process.env, "APP_");
123
+ const { adapters, rejected } = createChannels([{ descriptor: matrixChannel, config, envPrefix: "APP_" }]);
124
+ ```
125
+
126
+ | Config key | Env name | Required | Secret |
127
+ | --- | --- | --- | --- |
128
+ | `homeserverUrl` | `MATRIX_HOMESERVER_URL` | yes | no |
129
+ | `accessToken` | `MATRIX_ACCESS_TOKEN` | yes | yes |
130
+ | `userId` | `MATRIX_USER_ID` | yes | no |
131
+ | `freshnessWindowMs` | `MATRIX_FRESHNESS_WINDOW_MS` | no | no |
132
+ | `requireMention` | `MATRIX_REQUIRE_MENTION` | no | no |
133
+ | `acceptInvite` | none (callback) | no | no |
134
+
135
+ The `APP_` prefix is the app's choice. A value of the wrong type throws `invalid_config` naming the key; a list may be an array or a comma-separated string, a boolean `true`/`false` or the same strings, a number a number or a digit string.
136
+
114
137
  ## ADRs
115
138
 
116
139
  D413 – D421 in `.claude/knowledge-base/adrs/`.
package/dist/index.cjs CHANGED
@@ -628,12 +628,108 @@ function mapMatrixError(err) {
628
628
  };
629
629
  }
630
630
 
631
+ // ../../shared/channel-config-field.ts
632
+ var field = (key, env, description, { required = true, secret = false } = {}) => ({ key, required, secret, env, description });
633
+
634
+ // ../../shared/env-value-readers.ts
635
+ function readEnvNumber(invalid2, config, key) {
636
+ const value = config[key];
637
+ if (value === void 0) return void 0;
638
+ if (typeof value === "number" && Number.isFinite(value)) return value;
639
+ if (typeof value === "string" && /^[0-9]+$/.test(value.trim())) {
640
+ const parsed = Number(value.trim());
641
+ if (Number.isFinite(parsed)) return parsed;
642
+ }
643
+ throw invalid2(key, "a number or a digit string");
644
+ }
645
+ function readEnvBoolean(invalid2, config, key) {
646
+ const value = config[key];
647
+ if (value === void 0) return void 0;
648
+ if (value === true || value === "true") return true;
649
+ if (value === false || value === "false") return false;
650
+ throw invalid2(key, 'a boolean or the string "true" or "false"');
651
+ }
652
+ function envValueReaders(invalid2) {
653
+ return {
654
+ number: (config, key) => readEnvNumber(invalid2, config, key),
655
+ boolean: (config, key) => readEnvBoolean(invalid2, config, key)
656
+ };
657
+ }
658
+
659
+ // src/channel.ts
660
+ var readers = gateway.channelConfigReaders(
661
+ "gateway-matrix",
662
+ (options) => new ConfigurationError(options)
663
+ );
664
+ var { invalid } = readers;
665
+ var isAbsent = (value) => value === void 0;
666
+ var read = {
667
+ ...envValueReaders(invalid),
668
+ string: readers.requiredString
669
+ };
670
+ function readAcceptInvite(config) {
671
+ const value = config.acceptInvite;
672
+ if (isAbsent(value)) return void 0;
673
+ if (typeof value !== "function") throw invalid("acceptInvite", "a function");
674
+ return value;
675
+ }
676
+ var CONFIG = [
677
+ field(
678
+ "homeserverUrl",
679
+ "MATRIX_HOMESERVER_URL",
680
+ "Base URL of the Matrix homeserver, e.g. https://matrix.example.org."
681
+ ),
682
+ field("accessToken", "MATRIX_ACCESS_TOKEN", "Access token of the bot account.", { secret: true }),
683
+ field("userId", "MATRIX_USER_ID", "Matrix user id of the bot, e.g. @bot:example.org."),
684
+ field(
685
+ "freshnessWindowMs",
686
+ "MATRIX_FRESHNESS_WINDOW_MS",
687
+ "Events older than this many milliseconds are dropped.",
688
+ { required: false }
689
+ ),
690
+ field(
691
+ "requireMention",
692
+ "MATRIX_REQUIRE_MENTION",
693
+ "When true, group messages reach the handler only if they mention the bot.",
694
+ { required: false }
695
+ ),
696
+ {
697
+ key: "acceptInvite",
698
+ required: false,
699
+ secret: false,
700
+ description: "Programmatic callback deciding whether to accept a room invite; no env binding."
701
+ }
702
+ ];
703
+ var matrixChannel = {
704
+ platform: "matrix",
705
+ transport: "socket",
706
+ senderIdentity: "authenticated",
707
+ config: CONFIG,
708
+ create(config) {
709
+ const homeserverUrl = read.string(config, "homeserverUrl");
710
+ const accessToken = read.string(config, "accessToken");
711
+ const userId = read.string(config, "userId");
712
+ const freshnessWindowMs = read.number(config, "freshnessWindowMs");
713
+ const requireMention = read.boolean(config, "requireMention");
714
+ const acceptInvite = readAcceptInvite(config);
715
+ return new MatrixAdapter({
716
+ homeserverUrl,
717
+ accessToken,
718
+ userId,
719
+ ...freshnessWindowMs === void 0 ? {} : { freshnessWindowMs },
720
+ ...requireMention === void 0 ? {} : { requireMention },
721
+ ...acceptInvite === void 0 ? {} : { acceptInvite }
722
+ });
723
+ }
724
+ };
725
+
631
726
  exports.AliasCache = AliasCache;
632
727
  exports.ConfigurationError = ConfigurationError;
633
728
  exports.EncryptedRoomError = EncryptedRoomError;
634
729
  exports.MatrixAdapter = MatrixAdapter;
635
730
  exports.SDKNotInstalledError = SDKNotInstalledError;
636
731
  exports.detectChannelType = detectChannelType;
732
+ exports.matrixChannel = matrixChannel;
637
733
  exports.matrixEventToMessageEvent = matrixEventToMessageEvent;
638
734
  exports.shouldDispatchSyncEvent = shouldDispatchSyncEvent;
639
735
  exports.subscribeToTimeline = subscribeToTimeline;
@@ -1 +1 @@
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":["GatewayConfigurationError","BasePlatformAdapter"],"mappings":";;;;;AAoBO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,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,MAA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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 /**\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"]}
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","../../../shared/channel-config-field.ts","../../../shared/env-value-readers.ts","../src/channel.ts"],"names":["GatewayConfigurationError","BasePlatformAdapter","invalid","channelConfigReaders"],"mappings":";;;;;AAoBO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,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;AA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AA,MACvB,aAAA;AAAA,MACA,WAAA;AAAA,MACA,MAAA;AAAA,MACA,GAAI,iBAAA,KAAsB,MAAA,GAAY,EAAC,GAAI,EAAE,iBAAA,EAAkB;AAAA,MAC/D,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAC,GAAI,EAAE,cAAA,EAAe;AAAA,MACzD,GAAI,YAAA,KAAiB,MAAA,GAAY,EAAC,GAAI,EAAE,YAAA;AAAa,KACtD,CAAA;AAAA,EACH;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 /**\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","/**\n * One configuration field, shaped like the core's `ChannelConfigField` (typed locally so a published\n * `.d.ts` never names a core type an older peer release lacks), and its constructor.\n */\nexport interface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n readonly env?: string;\n}\n\nexport const field = (\n key: string,\n env: string,\n description: string,\n { required = true, secret = false }: { required?: boolean; secret?: boolean } = {},\n): ConfigField => ({ key, required, secret, env, description });\n","/**\n * Readers for config values that may arrive as environment strings, where only `undefined` is\n * absent: `null` and `\"\"` are wrong shapes and throw. The core readers treat both as absent, so a\n * channel that must refuse them takes these instead. `invalid` is the channel's own error builder.\n */\ntype Config = Readonly<Record<string, unknown>>;\ntype Invalid = (key: string, expected: string) => Error;\n\nfunction readEnvNumber(invalid: Invalid, config: Config, key: string): number | undefined {\n const value = config[key];\n if (value === undefined) return undefined;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && /^[0-9]+$/.test(value.trim())) {\n const parsed = Number(value.trim());\n if (Number.isFinite(parsed)) return parsed;\n }\n throw invalid(key, \"a number or a digit string\");\n}\n\nfunction readEnvBoolean(invalid: Invalid, config: Config, key: string): boolean | undefined {\n const value = config[key];\n if (value === undefined) return undefined;\n if (value === true || value === \"true\") return true;\n if (value === false || value === \"false\") return false;\n throw invalid(key, 'a boolean or the string \"true\" or \"false\"');\n}\n\nexport function envValueReaders(invalid: Invalid) {\n return {\n number: (config: Config, key: string) => readEnvNumber(invalid, config, key),\n boolean: (config: Config, key: string) => readEnvBoolean(invalid, config, key),\n };\n}\n","/**\n * `matrixChannel` — the Matrix channel described as data.\n *\n * Typed locally on purpose: the object is structurally a `ChannelDescriptor`, and the integration\n * package's typecheck is where a drift between the two fails.\n */\n\nimport { channelConfigReaders } from \"@theokit/gateway\";\nimport { type ConfigField, field } from \"../../../shared/channel-config-field.js\";\nimport { envValueReaders } from \"../../../shared/env-value-readers.js\";\nimport { MatrixAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport type { MatrixAdapterOptions } from \"./types.js\";\n\nconst readers = channelConfigReaders(\n \"gateway-matrix\",\n (options) => new ConfigurationError(options),\n);\nconst { invalid } = readers;\n\n/** Only `undefined` is absent: `null` and `\"\"` are wrong shapes and throw `invalid_config`. */\nconst isAbsent = (value: unknown): boolean => value === undefined;\n\n/** Readers for values that may arrive as env strings; only `undefined` is absent. */\nconst read = {\n ...envValueReaders(invalid),\n string: readers.requiredString,\n};\n\nfunction readAcceptInvite(\n config: Readonly<Record<string, unknown>>,\n): MatrixAdapterOptions[\"acceptInvite\"] {\n const value = config.acceptInvite;\n if (isAbsent(value)) return undefined;\n if (typeof value !== \"function\") throw invalid(\"acceptInvite\", \"a function\");\n return value as MatrixAdapterOptions[\"acceptInvite\"];\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n field(\n \"homeserverUrl\",\n \"MATRIX_HOMESERVER_URL\",\n \"Base URL of the Matrix homeserver, e.g. https://matrix.example.org.\",\n ),\n field(\"accessToken\", \"MATRIX_ACCESS_TOKEN\", \"Access token of the bot account.\", { secret: true }),\n field(\"userId\", \"MATRIX_USER_ID\", \"Matrix user id of the bot, e.g. @bot:example.org.\"),\n field(\n \"freshnessWindowMs\",\n \"MATRIX_FRESHNESS_WINDOW_MS\",\n \"Events older than this many milliseconds are dropped.\",\n { required: false },\n ),\n field(\n \"requireMention\",\n \"MATRIX_REQUIRE_MENTION\",\n \"When true, group messages reach the handler only if they mention the bot.\",\n { required: false },\n ),\n {\n key: \"acceptInvite\",\n required: false,\n secret: false,\n description: \"Programmatic callback deciding whether to accept a room invite; no env binding.\",\n },\n];\n\n/**\n * The Matrix channel: a sync loop the adapter opens itself, so it needs no webhook route.\n *\n * `create` validates each value with this package's `ConfigurationError` and makes no network call.\n *\n * @public\n */\nexport const matrixChannel = {\n platform: \"matrix\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): MatrixAdapter {\n const homeserverUrl = read.string(config, \"homeserverUrl\");\n const accessToken = read.string(config, \"accessToken\");\n const userId = read.string(config, \"userId\");\n const freshnessWindowMs = read.number(config, \"freshnessWindowMs\");\n const requireMention = read.boolean(config, \"requireMention\");\n const acceptInvite = readAcceptInvite(config);\n return new MatrixAdapter({\n homeserverUrl,\n accessToken,\n userId,\n ...(freshnessWindowMs === undefined ? {} : { freshnessWindowMs }),\n ...(requireMention === undefined ? {} : { requireMention }),\n ...(acceptInvite === undefined ? {} : { acceptInvite }),\n });\n },\n};\n"]}
package/dist/index.d.cts CHANGED
@@ -300,6 +300,40 @@ declare class AliasCache {
300
300
  size(): number;
301
301
  }
302
302
 
303
+ /**
304
+ * One configuration field, shaped like the core's `ChannelConfigField` (typed locally so a published
305
+ * `.d.ts` never names a core type an older peer release lacks), and its constructor.
306
+ */
307
+ interface ConfigField {
308
+ readonly key: string;
309
+ readonly required: boolean;
310
+ readonly secret: boolean;
311
+ readonly description: string;
312
+ readonly env?: string;
313
+ }
314
+
315
+ /**
316
+ * `matrixChannel` — the Matrix channel described as data.
317
+ *
318
+ * Typed locally on purpose: the object is structurally a `ChannelDescriptor`, and the integration
319
+ * package's typecheck is where a drift between the two fails.
320
+ */
321
+
322
+ /**
323
+ * The Matrix channel: a sync loop the adapter opens itself, so it needs no webhook route.
324
+ *
325
+ * `create` validates each value with this package's `ConfigurationError` and makes no network call.
326
+ *
327
+ * @public
328
+ */
329
+ declare const matrixChannel: {
330
+ platform: "matrix";
331
+ transport: "socket";
332
+ senderIdentity: "authenticated";
333
+ config: readonly ConfigField[];
334
+ create(config: Readonly<Record<string, unknown>>): MatrixAdapter;
335
+ };
336
+
303
337
  /**
304
338
  * Typed errors for `@theokit/gateway-matrix`.
305
339
  *
@@ -358,4 +392,4 @@ declare function matrixEventToMessageEvent(event: MatrixEventLike, room: MatrixR
358
392
 
359
393
  declare function detectChannelType(room: MatrixRoomLike | undefined): "dm" | "group";
360
394
 
361
- export { AliasCache, ConfigurationError, EncryptedRoomError, MatrixAdapter, type MatrixAdapterOptions, type MatrixClientLike, type MatrixEventLike, type MatrixRoomLike, SDKNotInstalledError, type SyncFilterOpts, type TimelineSubscription, detectChannelType, matrixEventToMessageEvent, shouldDispatchSyncEvent, subscribeToTimeline };
395
+ export { AliasCache, ConfigurationError, EncryptedRoomError, MatrixAdapter, type MatrixAdapterOptions, type MatrixClientLike, type MatrixEventLike, type MatrixRoomLike, SDKNotInstalledError, type SyncFilterOpts, type TimelineSubscription, detectChannelType, matrixChannel, matrixEventToMessageEvent, shouldDispatchSyncEvent, subscribeToTimeline };
package/dist/index.d.ts CHANGED
@@ -300,6 +300,40 @@ declare class AliasCache {
300
300
  size(): number;
301
301
  }
302
302
 
303
+ /**
304
+ * One configuration field, shaped like the core's `ChannelConfigField` (typed locally so a published
305
+ * `.d.ts` never names a core type an older peer release lacks), and its constructor.
306
+ */
307
+ interface ConfigField {
308
+ readonly key: string;
309
+ readonly required: boolean;
310
+ readonly secret: boolean;
311
+ readonly description: string;
312
+ readonly env?: string;
313
+ }
314
+
315
+ /**
316
+ * `matrixChannel` — the Matrix channel described as data.
317
+ *
318
+ * Typed locally on purpose: the object is structurally a `ChannelDescriptor`, and the integration
319
+ * package's typecheck is where a drift between the two fails.
320
+ */
321
+
322
+ /**
323
+ * The Matrix channel: a sync loop the adapter opens itself, so it needs no webhook route.
324
+ *
325
+ * `create` validates each value with this package's `ConfigurationError` and makes no network call.
326
+ *
327
+ * @public
328
+ */
329
+ declare const matrixChannel: {
330
+ platform: "matrix";
331
+ transport: "socket";
332
+ senderIdentity: "authenticated";
333
+ config: readonly ConfigField[];
334
+ create(config: Readonly<Record<string, unknown>>): MatrixAdapter;
335
+ };
336
+
303
337
  /**
304
338
  * Typed errors for `@theokit/gateway-matrix`.
305
339
  *
@@ -358,4 +392,4 @@ declare function matrixEventToMessageEvent(event: MatrixEventLike, room: MatrixR
358
392
 
359
393
  declare function detectChannelType(room: MatrixRoomLike | undefined): "dm" | "group";
360
394
 
361
- export { AliasCache, ConfigurationError, EncryptedRoomError, MatrixAdapter, type MatrixAdapterOptions, type MatrixClientLike, type MatrixEventLike, type MatrixRoomLike, SDKNotInstalledError, type SyncFilterOpts, type TimelineSubscription, detectChannelType, matrixEventToMessageEvent, shouldDispatchSyncEvent, subscribeToTimeline };
395
+ export { AliasCache, ConfigurationError, EncryptedRoomError, MatrixAdapter, type MatrixAdapterOptions, type MatrixClientLike, type MatrixEventLike, type MatrixRoomLike, SDKNotInstalledError, type SyncFilterOpts, type TimelineSubscription, detectChannelType, matrixChannel, matrixEventToMessageEvent, shouldDispatchSyncEvent, subscribeToTimeline };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { GatewayConfigurationError, BasePlatformAdapter } from '@theokit/gateway';
1
+ import { channelConfigReaders, GatewayConfigurationError, BasePlatformAdapter } from '@theokit/gateway';
2
2
 
3
3
  // src/adapter.ts
4
4
  var ConfigurationError = class extends GatewayConfigurationError {
@@ -626,6 +626,101 @@ function mapMatrixError(err) {
626
626
  };
627
627
  }
628
628
 
629
- export { AliasCache, ConfigurationError, EncryptedRoomError, MatrixAdapter, SDKNotInstalledError, detectChannelType, matrixEventToMessageEvent, shouldDispatchSyncEvent, subscribeToTimeline };
629
+ // ../../shared/channel-config-field.ts
630
+ var field = (key, env, description, { required = true, secret = false } = {}) => ({ key, required, secret, env, description });
631
+
632
+ // ../../shared/env-value-readers.ts
633
+ function readEnvNumber(invalid2, config, key) {
634
+ const value = config[key];
635
+ if (value === void 0) return void 0;
636
+ if (typeof value === "number" && Number.isFinite(value)) return value;
637
+ if (typeof value === "string" && /^[0-9]+$/.test(value.trim())) {
638
+ const parsed = Number(value.trim());
639
+ if (Number.isFinite(parsed)) return parsed;
640
+ }
641
+ throw invalid2(key, "a number or a digit string");
642
+ }
643
+ function readEnvBoolean(invalid2, config, key) {
644
+ const value = config[key];
645
+ if (value === void 0) return void 0;
646
+ if (value === true || value === "true") return true;
647
+ if (value === false || value === "false") return false;
648
+ throw invalid2(key, 'a boolean or the string "true" or "false"');
649
+ }
650
+ function envValueReaders(invalid2) {
651
+ return {
652
+ number: (config, key) => readEnvNumber(invalid2, config, key),
653
+ boolean: (config, key) => readEnvBoolean(invalid2, config, key)
654
+ };
655
+ }
656
+
657
+ // src/channel.ts
658
+ var readers = channelConfigReaders(
659
+ "gateway-matrix",
660
+ (options) => new ConfigurationError(options)
661
+ );
662
+ var { invalid } = readers;
663
+ var isAbsent = (value) => value === void 0;
664
+ var read = {
665
+ ...envValueReaders(invalid),
666
+ string: readers.requiredString
667
+ };
668
+ function readAcceptInvite(config) {
669
+ const value = config.acceptInvite;
670
+ if (isAbsent(value)) return void 0;
671
+ if (typeof value !== "function") throw invalid("acceptInvite", "a function");
672
+ return value;
673
+ }
674
+ var CONFIG = [
675
+ field(
676
+ "homeserverUrl",
677
+ "MATRIX_HOMESERVER_URL",
678
+ "Base URL of the Matrix homeserver, e.g. https://matrix.example.org."
679
+ ),
680
+ field("accessToken", "MATRIX_ACCESS_TOKEN", "Access token of the bot account.", { secret: true }),
681
+ field("userId", "MATRIX_USER_ID", "Matrix user id of the bot, e.g. @bot:example.org."),
682
+ field(
683
+ "freshnessWindowMs",
684
+ "MATRIX_FRESHNESS_WINDOW_MS",
685
+ "Events older than this many milliseconds are dropped.",
686
+ { required: false }
687
+ ),
688
+ field(
689
+ "requireMention",
690
+ "MATRIX_REQUIRE_MENTION",
691
+ "When true, group messages reach the handler only if they mention the bot.",
692
+ { required: false }
693
+ ),
694
+ {
695
+ key: "acceptInvite",
696
+ required: false,
697
+ secret: false,
698
+ description: "Programmatic callback deciding whether to accept a room invite; no env binding."
699
+ }
700
+ ];
701
+ var matrixChannel = {
702
+ platform: "matrix",
703
+ transport: "socket",
704
+ senderIdentity: "authenticated",
705
+ config: CONFIG,
706
+ create(config) {
707
+ const homeserverUrl = read.string(config, "homeserverUrl");
708
+ const accessToken = read.string(config, "accessToken");
709
+ const userId = read.string(config, "userId");
710
+ const freshnessWindowMs = read.number(config, "freshnessWindowMs");
711
+ const requireMention = read.boolean(config, "requireMention");
712
+ const acceptInvite = readAcceptInvite(config);
713
+ return new MatrixAdapter({
714
+ homeserverUrl,
715
+ accessToken,
716
+ userId,
717
+ ...freshnessWindowMs === void 0 ? {} : { freshnessWindowMs },
718
+ ...requireMention === void 0 ? {} : { requireMention },
719
+ ...acceptInvite === void 0 ? {} : { acceptInvite }
720
+ });
721
+ }
722
+ };
723
+
724
+ export { AliasCache, ConfigurationError, EncryptedRoomError, MatrixAdapter, SDKNotInstalledError, detectChannelType, matrixChannel, matrixEventToMessageEvent, shouldDispatchSyncEvent, subscribeToTimeline };
630
725
  //# sourceMappingURL=index.js.map
631
726
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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,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,QAC3B,IAAA,EAAM,kBAAA;A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D;AAGA,SAAS,eAAe,GAAA,EAA0B;AAChD,EAAA,MAAM,CAAA,GAAI,GAAA;AACV,EAAA,MAAM,MAAA,GAAS,EAAE,UAAA,IAAc,CAAA;AAC/B,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,CAAA,CAAE,OAAA,KAAY,kBAAA,EAAoB;AACtD,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,IAAA,EAAM,YAAA,EAAc,OAAA,EAAS,CAAA,CAAE,OAAA,IAAW,mBAAA,EAAoB,EAAE;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.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"]}
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","../../../shared/channel-config-field.ts","../../../shared/env-value-readers.ts","../src/channel.ts"],"names":["invalid"],"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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AAAA,EACH;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","/**\n * One configuration field, shaped like the core's `ChannelConfigField` (typed locally so a published\n * `.d.ts` never names a core type an older peer release lacks), and its constructor.\n */\nexport interface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n readonly env?: string;\n}\n\nexport const field = (\n key: string,\n env: string,\n description: string,\n { required = true, secret = false }: { required?: boolean; secret?: boolean } = {},\n): ConfigField => ({ key, required, secret, env, description });\n","/**\n * Readers for config values that may arrive as environment strings, where only `undefined` is\n * absent: `null` and `\"\"` are wrong shapes and throw. The core readers treat both as absent, so a\n * channel that must refuse them takes these instead. `invalid` is the channel's own error builder.\n */\ntype Config = Readonly<Record<string, unknown>>;\ntype Invalid = (key: string, expected: string) => Error;\n\nfunction readEnvNumber(invalid: Invalid, config: Config, key: string): number | undefined {\n const value = config[key];\n if (value === undefined) return undefined;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && /^[0-9]+$/.test(value.trim())) {\n const parsed = Number(value.trim());\n if (Number.isFinite(parsed)) return parsed;\n }\n throw invalid(key, \"a number or a digit string\");\n}\n\nfunction readEnvBoolean(invalid: Invalid, config: Config, key: string): boolean | undefined {\n const value = config[key];\n if (value === undefined) return undefined;\n if (value === true || value === \"true\") return true;\n if (value === false || value === \"false\") return false;\n throw invalid(key, 'a boolean or the string \"true\" or \"false\"');\n}\n\nexport function envValueReaders(invalid: Invalid) {\n return {\n number: (config: Config, key: string) => readEnvNumber(invalid, config, key),\n boolean: (config: Config, key: string) => readEnvBoolean(invalid, config, key),\n };\n}\n","/**\n * `matrixChannel` — the Matrix channel described as data.\n *\n * Typed locally on purpose: the object is structurally a `ChannelDescriptor`, and the integration\n * package's typecheck is where a drift between the two fails.\n */\n\nimport { channelConfigReaders } from \"@theokit/gateway\";\nimport { type ConfigField, field } from \"../../../shared/channel-config-field.js\";\nimport { envValueReaders } from \"../../../shared/env-value-readers.js\";\nimport { MatrixAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport type { MatrixAdapterOptions } from \"./types.js\";\n\nconst readers = channelConfigReaders(\n \"gateway-matrix\",\n (options) => new ConfigurationError(options),\n);\nconst { invalid } = readers;\n\n/** Only `undefined` is absent: `null` and `\"\"` are wrong shapes and throw `invalid_config`. */\nconst isAbsent = (value: unknown): boolean => value === undefined;\n\n/** Readers for values that may arrive as env strings; only `undefined` is absent. */\nconst read = {\n ...envValueReaders(invalid),\n string: readers.requiredString,\n};\n\nfunction readAcceptInvite(\n config: Readonly<Record<string, unknown>>,\n): MatrixAdapterOptions[\"acceptInvite\"] {\n const value = config.acceptInvite;\n if (isAbsent(value)) return undefined;\n if (typeof value !== \"function\") throw invalid(\"acceptInvite\", \"a function\");\n return value as MatrixAdapterOptions[\"acceptInvite\"];\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n field(\n \"homeserverUrl\",\n \"MATRIX_HOMESERVER_URL\",\n \"Base URL of the Matrix homeserver, e.g. https://matrix.example.org.\",\n ),\n field(\"accessToken\", \"MATRIX_ACCESS_TOKEN\", \"Access token of the bot account.\", { secret: true }),\n field(\"userId\", \"MATRIX_USER_ID\", \"Matrix user id of the bot, e.g. @bot:example.org.\"),\n field(\n \"freshnessWindowMs\",\n \"MATRIX_FRESHNESS_WINDOW_MS\",\n \"Events older than this many milliseconds are dropped.\",\n { required: false },\n ),\n field(\n \"requireMention\",\n \"MATRIX_REQUIRE_MENTION\",\n \"When true, group messages reach the handler only if they mention the bot.\",\n { required: false },\n ),\n {\n key: \"acceptInvite\",\n required: false,\n secret: false,\n description: \"Programmatic callback deciding whether to accept a room invite; no env binding.\",\n },\n];\n\n/**\n * The Matrix channel: a sync loop the adapter opens itself, so it needs no webhook route.\n *\n * `create` validates each value with this package's `ConfigurationError` and makes no network call.\n *\n * @public\n */\nexport const matrixChannel = {\n platform: \"matrix\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): MatrixAdapter {\n const homeserverUrl = read.string(config, \"homeserverUrl\");\n const accessToken = read.string(config, \"accessToken\");\n const userId = read.string(config, \"userId\");\n const freshnessWindowMs = read.number(config, \"freshnessWindowMs\");\n const requireMention = read.boolean(config, \"requireMention\");\n const acceptInvite = readAcceptInvite(config);\n return new MatrixAdapter({\n homeserverUrl,\n accessToken,\n userId,\n ...(freshnessWindowMs === undefined ? {} : { freshnessWindowMs }),\n ...(requireMention === undefined ? {} : { requireMention }),\n ...(acceptInvite === undefined ? {} : { acceptInvite }),\n });\n },\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-matrix",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Matrix protocol platform adapter for @theokit/gateway. ADRs D413-D421.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -36,7 +36,7 @@
36
36
  "CHANGELOG.md"
37
37
  ],
38
38
  "peerDependencies": {
39
- "@theokit/gateway": ">=0.9.0 <1.0.0",
39
+ "@theokit/gateway": ">=0.21.0 <1.0.0",
40
40
  "matrix-js-sdk": "^32.0.0 || ^42.0.0"
41
41
  },
42
42
  "peerDependenciesMeta": {
@@ -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.15.0"
56
+ "@theokit/gateway": "0.24.0"
57
57
  },
58
58
  "publishConfig": {
59
59
  "access": "public",