@im-more/dsh-matrix 0.0.0-stage → 0.1.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.
Files changed (86) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +14 -0
  3. package/lib/index.js +2401 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/as.d.ts +33 -0
  6. package/lib/types/as.d.ts.map +1 -0
  7. package/lib/types/as.js +237 -0
  8. package/lib/types/as.js.map +1 -0
  9. package/lib/types/bot.d.ts +109 -0
  10. package/lib/types/bot.d.ts.map +1 -0
  11. package/lib/types/bot.js +234 -0
  12. package/lib/types/bot.js.map +1 -0
  13. package/lib/types/config.d.ts +59 -0
  14. package/lib/types/config.d.ts.map +1 -0
  15. package/lib/types/config.js +67 -0
  16. package/lib/types/config.js.map +1 -0
  17. package/lib/types/decode.d.ts +56 -0
  18. package/lib/types/decode.d.ts.map +1 -0
  19. package/lib/types/decode.js +298 -0
  20. package/lib/types/decode.js.map +1 -0
  21. package/lib/types/errors.d.ts +45 -0
  22. package/lib/types/errors.d.ts.map +1 -0
  23. package/lib/types/errors.js +120 -0
  24. package/lib/types/errors.js.map +1 -0
  25. package/lib/types/html.d.ts +44 -0
  26. package/lib/types/html.d.ts.map +1 -0
  27. package/lib/types/html.js +286 -0
  28. package/lib/types/html.js.map +1 -0
  29. package/lib/types/identity.d.ts +20 -0
  30. package/lib/types/identity.d.ts.map +1 -0
  31. package/lib/types/identity.js +136 -0
  32. package/lib/types/identity.js.map +1 -0
  33. package/lib/types/index.d.ts +5 -0
  34. package/lib/types/index.d.ts.map +1 -0
  35. package/lib/types/index.js +5 -0
  36. package/lib/types/index.js.map +1 -0
  37. package/lib/types/media.d.ts +54 -0
  38. package/lib/types/media.d.ts.map +1 -0
  39. package/lib/types/media.js +94 -0
  40. package/lib/types/media.js.map +1 -0
  41. package/lib/types/mentions.d.ts +58 -0
  42. package/lib/types/mentions.d.ts.map +1 -0
  43. package/lib/types/mentions.js +94 -0
  44. package/lib/types/mentions.js.map +1 -0
  45. package/lib/types/modes/html.d.ts +13 -0
  46. package/lib/types/modes/html.d.ts.map +1 -0
  47. package/lib/types/modes/html.js +242 -0
  48. package/lib/types/modes/html.js.map +1 -0
  49. package/lib/types/modes/shared.d.ts +164 -0
  50. package/lib/types/modes/shared.d.ts.map +1 -0
  51. package/lib/types/modes/shared.js +312 -0
  52. package/lib/types/modes/shared.js.map +1 -0
  53. package/lib/types/request.d.ts +82 -0
  54. package/lib/types/request.d.ts.map +1 -0
  55. package/lib/types/request.js +206 -0
  56. package/lib/types/request.js.map +1 -0
  57. package/lib/types/rooms.d.ts +83 -0
  58. package/lib/types/rooms.d.ts.map +1 -0
  59. package/lib/types/rooms.js +177 -0
  60. package/lib/types/rooms.js.map +1 -0
  61. package/lib/types/send.d.ts +76 -0
  62. package/lib/types/send.d.ts.map +1 -0
  63. package/lib/types/send.js +172 -0
  64. package/lib/types/send.js.map +1 -0
  65. package/lib/types/types.d.ts +418 -0
  66. package/lib/types/types.d.ts.map +1 -0
  67. package/lib/types/types.js +134 -0
  68. package/lib/types/types.js.map +1 -0
  69. package/package.json +65 -3
  70. package/src/as.ts +293 -0
  71. package/src/bot.ts +338 -0
  72. package/src/config.ts +100 -0
  73. package/src/decode.ts +392 -0
  74. package/src/errors.ts +149 -0
  75. package/src/html.ts +325 -0
  76. package/src/identity.ts +165 -0
  77. package/src/index.ts +14 -0
  78. package/src/media.ts +132 -0
  79. package/src/mentions.ts +134 -0
  80. package/src/modes/html.ts +346 -0
  81. package/src/modes/shared.ts +485 -0
  82. package/src/request.ts +295 -0
  83. package/src/rooms.ts +232 -0
  84. package/src/send.ts +275 -0
  85. package/src/types.ts +633 -0
  86. package/README.md +0 -3
package/src/decode.ts ADDED
@@ -0,0 +1,392 @@
1
+ /**
2
+ * Inbound decoding: one Application Service event becomes one `Session`.
3
+ *
4
+ * `m.room.message` becomes a message (text/emote/notice through `formatted_body` or the plain body, media through the
5
+ * authenticated `satori:` route); `m.reaction` becomes `reaction-added`; `m.room.redaction` becomes
6
+ * `message-deleted` (room v11 moved the target into `content.redacts`). Membership and room-name events only update
7
+ * the room cache, and an invitation of the bot itself is joined when `autoJoin` is on. Everything else is dropped;
8
+ * `m.room.encrypted` is the visible consequence of the no-E2EE decision.
9
+ */
10
+
11
+ import { h } from '@deepseek-ai/cordis-plugin-im-core'
12
+ import type {
13
+ ChatRef,
14
+ Element,
15
+ InboundMessage,
16
+ Session,
17
+ SessionEvent,
18
+ UserRef,
19
+ } from '@deepseek-ai/cordis-plugin-im-core'
20
+ import { htmlToElements, stripPlainFallback } from './html.ts'
21
+ import { internalMediaSource } from './media.ts'
22
+ import { decodeMentions } from './mentions.ts'
23
+ import type { RoomCache } from './rooms.ts'
24
+ import type {
25
+ ClientEvent,
26
+ M_AUDIO,
27
+ M_FILE,
28
+ M_IMAGE,
29
+ M_ROOM_MEMBER,
30
+ M_ROOM_MESSAGE,
31
+ M_ROOM_NAME,
32
+ M_VIDEO,
33
+ } from './types.ts'
34
+
35
+ /** Adapter-private context carried through `Target.referrer`. */
36
+ export interface MatrixReferrer {
37
+ roomId: string
38
+ eventId: string
39
+ /** The sender of the event this referrer belongs to. */
40
+ sender: string
41
+ /** The thread root this event was posted in, when it was threaded. */
42
+ threadRoot?: string
43
+ }
44
+
45
+ /** The part of the adapter inbound decoding uses. */
46
+ export interface MatrixDecoderHost {
47
+ readonly selfId: string
48
+ readonly rooms: RoomCache
49
+ readonly autoJoin: boolean
50
+ getInternalUrl(path: string, init?: Record<string, string>): string
51
+ session(event: Partial<SessionEvent>): Session
52
+ /** Debug line for an event the adapter drops. */
53
+ log(message: string): void
54
+ /** Warning line for an unreadable room. */
55
+ warn(message: string): void
56
+ /** Join a room the bot was invited to (no room-state refresh; the self-join event triggers one). */
57
+ joinRoom(roomId: string): Promise<void>
58
+ /** Re-run the one-shot full-state sync and apply it. */
59
+ refreshRooms(): Promise<void>
60
+ }
61
+
62
+ /** Rooms whose first `m.room.encrypted` event has already been logged. */
63
+ const encryptedLogged = new WeakMap<RoomCache, Set<string>>()
64
+
65
+ /** The message types this adapter decodes; every other `msgtype` is dropped whole. */
66
+ export const MESSAGE_TYPES: ReadonlySet<string> = new Set([
67
+ 'm.text',
68
+ 'm.emote',
69
+ 'm.notice',
70
+ 'm.image',
71
+ 'm.file',
72
+ 'm.audio',
73
+ 'm.video',
74
+ ])
75
+
76
+ /** The chat of one room, from the cache. */
77
+ function chatOf(host: MatrixDecoderHost, roomId: string): ChatRef {
78
+ const name = host.rooms.nameOf(roomId)
79
+ return {
80
+ id: roomId,
81
+ type: host.rooms.isDirect(roomId, host.selfId) ? 'direct' : 'group',
82
+ ...(name === undefined ? {} : { name }),
83
+ }
84
+ }
85
+
86
+ /** The `satori:` source of one `mxc://` URI, or the raw address when it is not one. */
87
+ function mediaSource(
88
+ host: MatrixDecoderHost,
89
+ uri: string | undefined,
90
+ ): string | undefined {
91
+ if (uri === undefined || uri === '') return undefined
92
+ return internalMediaSource(host, uri) ?? uri
93
+ }
94
+
95
+ /** The sender of one event, with the display name the room cache knows. */
96
+ function senderOf(host: MatrixDecoderHost, event: ClientEvent): UserRef {
97
+ const name = host.rooms.displayNameOf(event.room_id, event.sender)
98
+ return {
99
+ id: event.sender,
100
+ ...(name === undefined ? {} : { name }),
101
+ isBot: false,
102
+ }
103
+ }
104
+
105
+ /** The elements of one `m.room.message` content, or undefined for a msgtype this adapter drops. */
106
+ function messageElements(
107
+ host: MatrixDecoderHost,
108
+ event: ClientEvent,
109
+ ): Element[] | undefined {
110
+ const content = event.content as M_ROOM_MESSAGE
111
+ switch (content.msgtype) {
112
+ case 'm.text':
113
+ case 'm.emote':
114
+ case 'm.notice': {
115
+ const formatted = content as { format?: string; formatted_body?: string }
116
+ if (
117
+ formatted.format === 'org.matrix.custom.html' &&
118
+ typeof formatted.formatted_body === 'string' &&
119
+ formatted.formatted_body !== ''
120
+ ) {
121
+ return htmlToElements(formatted.formatted_body, {
122
+ mediaSource: (mxc) => mediaSource(host, mxc) ?? mxc,
123
+ })
124
+ }
125
+ return [h.text(stripPlainFallback(content.body ?? ''))]
126
+ }
127
+ case 'm.image': {
128
+ const image = content as M_IMAGE
129
+ const src = mediaSource(host, image.url)
130
+ if (src === undefined) return undefined
131
+ return [
132
+ h('img', {
133
+ src,
134
+ ...(image.body === '' ? {} : { alt: image.body }),
135
+ ...(image.info?.w === undefined ? {} : { width: image.info.w }),
136
+ ...(image.info?.h === undefined ? {} : { height: image.info.h }),
137
+ }),
138
+ ]
139
+ }
140
+ case 'm.file': {
141
+ const file = content as M_FILE
142
+ const src = mediaSource(host, file.url)
143
+ if (src === undefined) return undefined
144
+ const name = file.filename ?? file.body
145
+ return [h('file', { src, ...(name === '' ? {} : { name }) })]
146
+ }
147
+ case 'm.audio': {
148
+ const audio = content as M_AUDIO
149
+ const src = mediaSource(host, audio.url)
150
+ if (src === undefined) return undefined
151
+ const name = audio.filename ?? audio.body
152
+ return [
153
+ h('audio', {
154
+ src,
155
+ ...(name === '' ? {} : { name }),
156
+ ...(audio.info?.duration === undefined
157
+ ? {}
158
+ : { duration: audio.info.duration }),
159
+ }),
160
+ ]
161
+ }
162
+ case 'm.video': {
163
+ const video = content as M_VIDEO
164
+ const src = mediaSource(host, video.url)
165
+ if (src === undefined) return undefined
166
+ const name = video.body
167
+ return [
168
+ h('video', {
169
+ src,
170
+ ...(name === '' ? {} : { name }),
171
+ ...(video.info?.duration === undefined
172
+ ? {}
173
+ : { duration: video.info.duration }),
174
+ }),
175
+ ]
176
+ }
177
+ default:
178
+ return undefined
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Decode one `m.room.message` event.
184
+ *
185
+ * @param host - the receiving adapter.
186
+ * @param event - one message event.
187
+ * @param chat - the chat to report, when the caller already knows it (`getMessage` uses the requested one).
188
+ * @returns the decoded message, whose content is never empty.
189
+ */
190
+ export function decodeMessage(
191
+ host: MatrixDecoderHost,
192
+ event: ClientEvent,
193
+ chat?: ChatRef,
194
+ ): InboundMessage {
195
+ const content = event.content as M_ROOM_MESSAGE
196
+ const elements = messageElements(host, event)
197
+ if (elements === undefined) {
198
+ host.log(`matrix: ignored msgtype "${content.msgtype ?? 'unknown'}"`)
199
+ }
200
+ // A body of "" or a formatted body that only contained a fallback decodes to nothing usable.
201
+ const usable = (elements ?? []).filter(
202
+ (element) => element.type !== 'text' || element.attrs.content !== '',
203
+ )
204
+ const children =
205
+ usable.length > 0
206
+ ? usable
207
+ : [
208
+ h(
209
+ 'raw',
210
+ { platform: 'matrix', type: 'm.room.message', data: event.content },
211
+ h.text(''),
212
+ ),
213
+ ]
214
+ const message = h('message', {}, ...children)
215
+ const relates = content['m.relates_to']
216
+ const threadRoot =
217
+ relates?.rel_type === 'm.thread' ? relates.event_id : undefined
218
+ const quoteId = relates?.['m.in_reply_to']?.event_id
219
+ const referrer: MatrixReferrer = {
220
+ roomId: event.room_id,
221
+ eventId: event.event_id,
222
+ sender: event.sender,
223
+ ...(threadRoot === undefined ? {} : { threadRoot }),
224
+ }
225
+ return {
226
+ id: event.event_id,
227
+ chat: chat ?? chatOf(host, event.room_id),
228
+ ...(threadRoot === undefined
229
+ ? {}
230
+ : { thread: { id: threadRoot, root: threadRoot } }),
231
+ sender: senderOf(host, event),
232
+ content: message,
233
+ ...(quoteId === undefined ? {} : { quote: { id: quoteId } }),
234
+ mentions: decodeMentions(
235
+ content as { 'm.mentions'?: { user_ids?: string[]; room?: boolean } },
236
+ content.body,
237
+ message.children,
238
+ host.selfId,
239
+ ),
240
+ time: event.origin_server_ts,
241
+ referrer,
242
+ raw: event,
243
+ }
244
+ }
245
+
246
+ /** Decode one received event.
247
+ *
248
+ * @param host - the receiving adapter.
249
+ * @param event - one event of an Application Service transaction.
250
+ * @returns the session to publish, or undefined for an event this adapter does not carry.
251
+ */
252
+ export async function decodeEvent(
253
+ host: MatrixDecoderHost,
254
+ event: ClientEvent,
255
+ ): Promise<Session | undefined> {
256
+ // The homeserver echoes the bot's own events; the host also skips them, but not worth a `receive` round-trip.
257
+ if (event.sender === host.selfId) return undefined
258
+ const timestamp = event.origin_server_ts
259
+ switch (event.type) {
260
+ case 'm.room.message': {
261
+ const content = event.content as M_ROOM_MESSAGE
262
+ if (content['m.new_content'] !== undefined) {
263
+ host.log('matrix: ignored an edited message (m.new_content)')
264
+ return undefined
265
+ }
266
+ if (!MESSAGE_TYPES.has(content.msgtype)) {
267
+ host.log(`matrix: ignored msgtype "${content.msgtype ?? 'unknown'}"`)
268
+ return undefined
269
+ }
270
+ const message = decodeMessage(host, event)
271
+ return host.session({
272
+ type: 'message',
273
+ id: event.event_id,
274
+ timestamp,
275
+ message,
276
+ raw: event,
277
+ })
278
+ }
279
+ case 'm.reaction': {
280
+ const relation = (
281
+ event.content as {
282
+ 'm.relates_to'?: {
283
+ rel_type?: string
284
+ event_id?: string
285
+ key?: string
286
+ }
287
+ }
288
+ )['m.relates_to']
289
+ if (relation?.rel_type !== 'm.annotation') {
290
+ host.log('matrix: ignored a reaction without an m.annotation relation')
291
+ return undefined
292
+ }
293
+ if (relation.event_id === undefined || relation.key === undefined) {
294
+ host.log('matrix: ignored a reaction without an event id or key')
295
+ return undefined
296
+ }
297
+ return host.session({
298
+ type: 'reaction-added',
299
+ id: event.event_id,
300
+ timestamp,
301
+ reaction: {
302
+ message: { id: relation.event_id, chat: chatOf(host, event.room_id) },
303
+ emoji: relation.key,
304
+ user: { id: event.sender },
305
+ },
306
+ raw: event,
307
+ })
308
+ }
309
+ case 'm.room.redaction': {
310
+ // Room version 11 moved the target into `content.redacts`; older rooms keep it on the event.
311
+ const content = event.content as { redacts?: string }
312
+ const target = event.redacts ?? content.redacts
313
+ if (target === undefined) return undefined
314
+ return host.session({
315
+ type: 'message-deleted',
316
+ id: event.event_id,
317
+ timestamp,
318
+ deleted: { id: target, chat: chatOf(host, event.room_id) },
319
+ raw: event,
320
+ })
321
+ }
322
+ case 'm.room.member': {
323
+ const member = event.content as M_ROOM_MEMBER
324
+ const stateKey = event.state_key
325
+ if (stateKey === undefined) return undefined
326
+ host.rooms.applyMember(
327
+ event.room_id,
328
+ stateKey,
329
+ member.membership,
330
+ member.displayname,
331
+ )
332
+ if (stateKey !== host.selfId) return undefined
333
+ if (member.membership === 'invite') {
334
+ if (!host.autoJoin) {
335
+ host.log(
336
+ `matrix: invited to ${event.room_id}; autoJoin is off, so it is not joined`,
337
+ )
338
+ return undefined
339
+ }
340
+ try {
341
+ await host.joinRoom(event.room_id)
342
+ } catch (error) {
343
+ host.warn(
344
+ `matrix: could not join ${event.room_id}: ${error instanceof Error ? error.message : String(error)}`,
345
+ )
346
+ }
347
+ return undefined
348
+ }
349
+ if (member.membership === 'join') {
350
+ // A new room's name/members/summary are not in the push; refresh the cache once.
351
+ try {
352
+ await host.refreshRooms()
353
+ } catch (error) {
354
+ host.warn(
355
+ `matrix: could not refresh rooms after joining ${event.room_id}: ${error instanceof Error ? error.message : String(error)}`,
356
+ )
357
+ }
358
+ }
359
+ return undefined
360
+ }
361
+ case 'm.room.name': {
362
+ const content = event.content as M_ROOM_NAME
363
+ if (typeof content.name === 'string')
364
+ host.rooms.setName(event.room_id, content.name)
365
+ return undefined
366
+ }
367
+ case 'm.room.encryption':
368
+ if (host.rooms.markEncrypted(event.room_id)) {
369
+ host.warn(
370
+ `matrix: room ${event.room_id} enabled end-to-end encryption; this adapter cannot decrypt its messages`,
371
+ )
372
+ }
373
+ return undefined
374
+ case 'm.room.encrypted': {
375
+ let logged = encryptedLogged.get(host.rooms)
376
+ if (logged === undefined) {
377
+ logged = new Set()
378
+ encryptedLogged.set(host.rooms, logged)
379
+ }
380
+ if (!logged.has(event.room_id)) {
381
+ logged.add(event.room_id)
382
+ host.log(
383
+ `matrix: dropped an encrypted message in ${event.room_id} (E2EE is not supported)`,
384
+ )
385
+ }
386
+ return undefined
387
+ }
388
+ default:
389
+ host.log(`matrix: ignored ${event.type} event`)
390
+ return undefined
391
+ }
392
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Matrix failures and their mapping onto the core platform taxonomy.
3
+ *
4
+ * Matrix answers with one JSON envelope (`errcode`, `error`) and asks clients to decide from `errcode`, falling back
5
+ * to the HTTP status only for `M_UNKNOWN`. A refused write is atomic, so every 4xx means nothing was published;
6
+ * transport failures and 5xx answers leave the outcome unknown. The token-failure codes also mark the bot offline at
7
+ * the transport layer, because the AS-issued user token has no refresh path.
8
+ */
9
+
10
+ import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
11
+ import type { PlatformErrorKind } from '@deepseek-ai/cordis-plugin-im-core'
12
+
13
+ /** Fields one failed Matrix call carries for classification. */
14
+ export interface MatrixApiErrorInit {
15
+ /** HTTP method of the failed call, when the failure came from one. */
16
+ method?: string
17
+ /** Endpoint path of the failed call. */
18
+ path?: string
19
+ /** HTTP status; absent for a transport failure. */
20
+ status?: number
21
+ /** The envelope's `errcode`. */
22
+ errcode?: string
23
+ /** The envelope's human-readable `error`. */
24
+ error?: string
25
+ /** Delay asked for by the answer (`retry_after_ms` or `Retry-After`). */
26
+ retryAfterMs?: number
27
+ cause?: unknown
28
+ }
29
+
30
+ /** One failed Matrix API call, with the fields `classify` reads. */
31
+ export class MatrixApiError extends Error {
32
+ readonly method: string | undefined
33
+ readonly path: string | undefined
34
+ readonly status: number | undefined
35
+ readonly errcode: string | undefined
36
+ readonly error: string | undefined
37
+ readonly retryAfterMs: number | undefined
38
+
39
+ constructor(message: string, init: MatrixApiErrorInit = {}) {
40
+ super(message, init.cause === undefined ? undefined : { cause: init.cause })
41
+ this.name = 'MatrixApiError'
42
+ this.method = init.method
43
+ this.path = init.path
44
+ this.status = init.status
45
+ this.errcode = init.errcode
46
+ this.error = init.error
47
+ this.retryAfterMs = init.retryAfterMs
48
+ }
49
+ }
50
+
51
+ /** Whether a failure means the user token is gone; the bot has to be re-logged in from scratch. */
52
+ export function isTokenFailure(error: unknown): boolean {
53
+ if (error instanceof MatrixApiError) {
54
+ if (
55
+ error.errcode === 'M_UNKNOWN_TOKEN' ||
56
+ error.errcode === 'M_MISSING_TOKEN'
57
+ )
58
+ return true
59
+ return error.errcode === undefined && error.status === 401
60
+ }
61
+ return false
62
+ }
63
+
64
+ /** The kind and publish state implied by one `errcode`. */
65
+ function byErrcode(
66
+ errcode: string,
67
+ ): { kind: PlatformErrorKind; published: 'no' | 'unknown' } | undefined {
68
+ switch (errcode) {
69
+ case 'M_LIMIT_EXCEEDED':
70
+ return { kind: 'rate-limit', published: 'no' }
71
+ case 'M_UNKNOWN_TOKEN':
72
+ case 'M_MISSING_TOKEN':
73
+ case 'M_FORBIDDEN':
74
+ case 'M_EXCLUSIVE':
75
+ case 'M_USER_DEACTIVATED':
76
+ case 'M_CONSENT_NOT_GIVEN':
77
+ return { kind: 'permission', published: 'no' }
78
+ case 'M_RESOURCE_LIMIT_EXCEEDED':
79
+ return { kind: 'retryable', published: 'no' }
80
+ case 'M_NOT_FOUND':
81
+ return { kind: 'not-found', published: 'no' }
82
+ case 'M_BAD_JSON':
83
+ case 'M_NOT_JSON':
84
+ case 'M_MISSING_PARAM':
85
+ case 'M_INVALID_PARAM':
86
+ return { kind: 'invalid', published: 'no' }
87
+ case 'M_TOO_LARGE':
88
+ return { kind: 'limit', published: 'no' }
89
+ default:
90
+ return undefined
91
+ }
92
+ }
93
+
94
+ /** The kind and publish state implied by a status when no `errcode` decides it. */
95
+ function byStatus(status: number | undefined): {
96
+ kind: PlatformErrorKind
97
+ published: 'no' | 'unknown'
98
+ } {
99
+ if (status === 429) return { kind: 'rate-limit', published: 'no' }
100
+ if (status !== undefined && status >= 500)
101
+ return { kind: 'retryable', published: 'unknown' }
102
+ // A 2xx answer this client could not read may still have published the event; only a refusal is certainly unpublished.
103
+ if (status !== undefined && status >= 200 && status < 300)
104
+ return { kind: 'retryable', published: 'unknown' }
105
+ if (status !== undefined) return { kind: 'invalid', published: 'no' }
106
+ return { kind: 'retryable', published: 'unknown' }
107
+ }
108
+
109
+ /**
110
+ * Map any failure onto the core platform taxonomy.
111
+ *
112
+ * @param error - the caught failure.
113
+ * @returns the classified platform error, with `retryAfterMs` when the platform named a delay.
114
+ */
115
+ export function classifyMatrixError(error: unknown): PlatformError {
116
+ if (error instanceof PlatformError) return error
117
+ if (error instanceof MatrixApiError) {
118
+ const { kind, published } =
119
+ (error.errcode === undefined || error.errcode === 'M_UNKNOWN'
120
+ ? undefined
121
+ : byErrcode(error.errcode)) ?? byStatus(error.status)
122
+ const code = error.errcode ?? error.status
123
+ return new PlatformError(kind, error.message, {
124
+ ...(code === undefined ? {} : { code }),
125
+ ...(error.retryAfterMs === undefined
126
+ ? {}
127
+ : { retryAfterMs: error.retryAfterMs }),
128
+ published,
129
+ cause: error,
130
+ })
131
+ }
132
+ if (error instanceof Error && error.name === 'AbortError') {
133
+ return new PlatformError('fatal', error.message, {
134
+ published: 'unknown',
135
+ cause: error,
136
+ })
137
+ }
138
+ if (error instanceof DOMException && error.name === 'AbortError') {
139
+ return new PlatformError('fatal', error.message, {
140
+ published: 'unknown',
141
+ cause: error,
142
+ })
143
+ }
144
+ const message = error instanceof Error ? error.message : String(error)
145
+ return new PlatformError('retryable', `matrix request failed: ${message}`, {
146
+ published: 'unknown',
147
+ cause: error,
148
+ })
149
+ }