@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/send.ts ADDED
@@ -0,0 +1,275 @@
1
+ /**
2
+ * Outbound hooks: send, delete, reaction, members and message reads.
3
+ *
4
+ * Every write is one `PUT /rooms/{roomId}/send|redact/...` with a transaction id; `txtId` is derived from the caller's
5
+ * idempotency key when there is one (Matrix deduplicates a retransmission with the same id), else from a per-process
6
+ * random base plus a counter. Matrix returns only an `event_id`, so a published part carries no platform timestamp.
7
+ */
8
+
9
+ import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
10
+ import type {
11
+ ChatRef,
12
+ InboundMessage,
13
+ MembersPage,
14
+ MessageHandle,
15
+ MessageRef,
16
+ SendContext,
17
+ SentPart,
18
+ Target,
19
+ UserRef,
20
+ } from '@deepseek-ai/cordis-plugin-im-core'
21
+ import { createHash } from 'node:crypto'
22
+ import { MESSAGE_TYPES } from './decode.ts'
23
+ import type { MatrixReferrer } from './decode.ts'
24
+ import type { RoomCache } from './rooms.ts'
25
+ import type {
26
+ MatrixPayload,
27
+ MatrixRelation,
28
+ MatrixThread,
29
+ } from './modes/shared.ts'
30
+ import type { MatrixClient } from './request.ts'
31
+ import type { ClientEvent, M_ROOM_MEMBER } from './types.ts'
32
+
33
+ /** Everything the outbound hooks need from the adapter. */
34
+ export interface MatrixSendDeps {
35
+ readonly client: MatrixClient
36
+ /** The bot's Matrix user id. */
37
+ readonly selfId: string
38
+ /** A fresh transaction id (random process base plus a counter). */
39
+ nextTxn(): number
40
+ readonly rooms: RoomCache
41
+ /** Whether a user id is a bot of this process. */
42
+ isBot(userId: string): boolean
43
+ /** Decode one event fetched by id for the requested chat. */
44
+ decode(chat: ChatRef, event: ClientEvent): InboundMessage
45
+ }
46
+
47
+ /** The transaction id of one request: idempotency key first, counter otherwise. */
48
+ export function txnIdOf(deps: MatrixSendDeps, ctx: SendContext): string {
49
+ const key = ctx.options.idempotencyKey
50
+ if (key !== undefined) {
51
+ return createHash('sha256')
52
+ .update(`${key}#${ctx.index}`)
53
+ .digest('hex')
54
+ .slice(0, 32)
55
+ }
56
+ return String(deps.nextTxn())
57
+ }
58
+
59
+ /**
60
+ * Whether a retry of one send is deduplicated by Matrix. Only a call with an idempotency key is: the spec returns the
61
+ * first answer for a retransmission of the same `(endpoint, txnId)` pair.
62
+ */
63
+ export function idempotentSend(_target: Target, ctx: SendContext): boolean {
64
+ return ctx.options.idempotencyKey !== undefined
65
+ }
66
+
67
+ /** The event content of one serialized payload. */
68
+ function eventContent(payload: MatrixPayload): Record<string, unknown> {
69
+ const relates: MatrixRelation | undefined = payload.relates
70
+ const common = {
71
+ 'm.mentions': payload.mentions,
72
+ ...(relates === undefined ? {} : { 'm.relates_to': relates }),
73
+ }
74
+ if (payload.kind === 'text') {
75
+ return {
76
+ msgtype: 'm.text',
77
+ body: payload.body,
78
+ ...(payload.html === undefined
79
+ ? {}
80
+ : { format: 'org.matrix.custom.html', formatted_body: payload.html }),
81
+ ...common,
82
+ }
83
+ }
84
+ return {
85
+ msgtype: payload.msgtype,
86
+ body: payload.body,
87
+ filename: payload.body,
88
+ url: payload.url,
89
+ ...(payload.info === undefined ? {} : { info: payload.info }),
90
+ ...common,
91
+ }
92
+ }
93
+
94
+ /** The published part of one accepted event. */
95
+ function partOf(
96
+ deps: MatrixSendDeps,
97
+ payload: MatrixPayload,
98
+ eventId: unknown,
99
+ ): SentPart {
100
+ if (typeof eventId !== 'string' || eventId === '') {
101
+ // The request reached the homeserver, so an answer without an id is a published outcome, not a refusal.
102
+ throw new PlatformError(
103
+ 'invalid',
104
+ 'matrix: the homeserver answered without an event_id',
105
+ { published: 'unknown' },
106
+ )
107
+ }
108
+ const thread: MatrixThread | undefined = payload.thread
109
+ const referrer: MatrixReferrer = {
110
+ roomId: payload.roomId,
111
+ eventId,
112
+ sender: deps.selfId,
113
+ ...(thread === undefined ? {} : { threadRoot: thread.root }),
114
+ }
115
+ return {
116
+ id: eventId,
117
+ kind: 'message',
118
+ time: Date.now(),
119
+ ...(thread === undefined
120
+ ? {}
121
+ : { thread: { id: thread.root, root: thread.root } }),
122
+ referrer,
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Send one serialized payload.
128
+ * @param deps - adapter services.
129
+ * @param payload - the serialized payload.
130
+ * @param _target - the chat being published to (the payload already names it).
131
+ * @param ctx - core send context (signal, part index, idempotency key).
132
+ * @returns the published part.
133
+ */
134
+ export async function sendPayload(
135
+ deps: MatrixSendDeps,
136
+ payload: MatrixPayload,
137
+ _target: Target,
138
+ ctx: SendContext,
139
+ ): Promise<SentPart> {
140
+ const txn = txnIdOf(deps, ctx)
141
+ const path = `/client/v3/rooms/${payload.roomId}/send/m.room.message/${txn}`
142
+ const answer = await deps.client.put<{ event_id?: string }>(
143
+ path,
144
+ eventContent(payload),
145
+ ctx.options.signal === undefined ? {} : { signal: ctx.options.signal },
146
+ )
147
+ return partOf(deps, payload, answer.event_id)
148
+ }
149
+
150
+ /**
151
+ * Redact one published event.
152
+ * @param deps - adapter services.
153
+ * @param part - the part to delete.
154
+ * @param handle - the message the part belongs to (its target names the room).
155
+ */
156
+ export async function deletePart(
157
+ deps: MatrixSendDeps,
158
+ part: SentPart,
159
+ handle: MessageHandle,
160
+ ): Promise<void> {
161
+ if (part.id === '') {
162
+ throw new PlatformError(
163
+ 'invalid',
164
+ 'matrix: an empty event id cannot be redacted',
165
+ { published: 'no' },
166
+ )
167
+ }
168
+ await deps.client.put(
169
+ `/client/v3/rooms/${handle.target.chat.id}/redact/${part.id}/${deps.nextTxn()}`,
170
+ {},
171
+ )
172
+ }
173
+
174
+ /**
175
+ * Add an annotation (`m.reaction`) to one message.
176
+ * @param deps - adapter services.
177
+ * @param message - the message to react to.
178
+ * @param emoji - the annotation key, passed through as written (`:shortcode:` included).
179
+ */
180
+ export async function createReaction(
181
+ deps: MatrixSendDeps,
182
+ message: MessageRef,
183
+ emoji: string,
184
+ ): Promise<void> {
185
+ await deps.client.put(
186
+ `/client/v3/rooms/${message.chat.id}/send/m.reaction/${deps.nextTxn()}`,
187
+ {
188
+ 'm.relates_to': {
189
+ rel_type: 'm.annotation',
190
+ event_id: message.id,
191
+ key: emoji,
192
+ },
193
+ },
194
+ )
195
+ }
196
+
197
+ /**
198
+ * List the joined members of a room.
199
+ *
200
+ * The room state endpoint returns the whole member set at once, so there is no cursor; `limit` truncates the page.
201
+ *
202
+ * @param deps - adapter services.
203
+ * @param chat - the room.
204
+ * @param _cursor - ignored; the state read is one full page.
205
+ * @param limit - page size bound.
206
+ * @returns the joined members, each with the display name its membership event carried.
207
+ */
208
+ export async function members(
209
+ deps: MatrixSendDeps,
210
+ chat: ChatRef,
211
+ _cursor?: string,
212
+ limit?: number,
213
+ ): Promise<MembersPage> {
214
+ const state = await deps.client.get<ClientEvent[]>(
215
+ `/client/v3/rooms/${chat.id}/state`,
216
+ )
217
+ const data: UserRef[] = []
218
+ for (const event of state) {
219
+ if (event.type !== 'm.room.member' || event.state_key === undefined)
220
+ continue
221
+ const content = event.content as M_ROOM_MEMBER
222
+ if (content.membership !== 'join') continue
223
+ if (content.displayname !== undefined) {
224
+ deps.rooms.applyMember(
225
+ chat.id,
226
+ event.state_key,
227
+ 'join',
228
+ content.displayname,
229
+ )
230
+ }
231
+ data.push({
232
+ id: event.state_key,
233
+ ...(content.displayname === undefined
234
+ ? {}
235
+ : { name: content.displayname }),
236
+ isBot: deps.isBot(event.state_key),
237
+ })
238
+ }
239
+ const page = limit === undefined ? data : data.slice(0, Math.max(0, limit))
240
+ return { data: page }
241
+ }
242
+
243
+ /**
244
+ * Read one message by id.
245
+ * @param deps - adapter services.
246
+ * @param chat - the chat the caller asked about; the decoded message reports it unchanged.
247
+ * @param id - the event id.
248
+ * @returns the decoded message.
249
+ */
250
+ export async function getMessage(
251
+ deps: MatrixSendDeps,
252
+ chat: ChatRef,
253
+ id: string,
254
+ ): Promise<InboundMessage> {
255
+ const event = await deps.client.get<ClientEvent>(
256
+ `/client/v3/rooms/${chat.id}/event/${id}`,
257
+ )
258
+ if (event.type !== 'm.room.message') {
259
+ throw new PlatformError(
260
+ 'not-found',
261
+ `matrix: event ${id} in ${chat.id} is not a message`,
262
+ { published: 'no' },
263
+ )
264
+ }
265
+ const content = event.content as { msgtype?: string }
266
+ if (content.msgtype === undefined || !MESSAGE_TYPES.has(content.msgtype)) {
267
+ // A redacted event keeps an empty content object; an unsupported msgtype has no inbound representation.
268
+ throw new PlatformError(
269
+ 'not-found',
270
+ `matrix: event ${id} in ${chat.id} is not a readable message`,
271
+ { published: 'no' },
272
+ )
273
+ }
274
+ return deps.decode(chat, event)
275
+ }