@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
@@ -0,0 +1,485 @@
1
+ /**
2
+ * The single `html` mode's node, draft and payload types, HTML escaping, media promotion, reply/thread relations and
3
+ * payload assembly.
4
+ *
5
+ * A Matrix message is either one `m.text` event with `body` + `formatted_body`, or one media event per media element.
6
+ * Every handler therefore returns an HTML fragment and its plain-text projection from the same traversal, so the two
7
+ * sides cannot drift; `assemble` flushes a text draft around each media element.
8
+ */
9
+
10
+ import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
11
+ import type {
12
+ ModeTypes,
13
+ Prepared,
14
+ RenderContext,
15
+ ResourceRef,
16
+ SerializeContext,
17
+ } from '@deepseek-ai/cordis-plugin-im-core'
18
+ import { isPhrasingContainer } from '@deepseek-ai/satori-element'
19
+ import type { Element } from '@deepseek-ai/satori-element'
20
+ import type { MatrixReferrer } from '../decode.ts'
21
+ import { addMention, createMentionSet, mentionWire } from '../mentions.ts'
22
+ import type { MentionNode, MatrixMentionWire } from '../mentions.ts'
23
+
24
+ /** Media elements Matrix publishes as their own event. */
25
+ export type MatrixMediaTag = 'img' | 'audio' | 'video' | 'file'
26
+
27
+ /** One inline run: its HTML and plain-text projections, and the mentions it contributes. */
28
+ export interface MatrixHtmlNode {
29
+ type: 'html'
30
+ html: string
31
+ text: string
32
+ mentions?: MentionNode[]
33
+ }
34
+
35
+ /** One media element, to be published after the text run it stood in. */
36
+ export interface MatrixMediaNode {
37
+ type: 'media'
38
+ tag: MatrixMediaTag
39
+ ref: ResourceRef
40
+ name?: string
41
+ width?: number
42
+ height?: number
43
+ duration?: number
44
+ }
45
+
46
+ /** One node a mode handler produces. */
47
+ export type MatrixNode = MatrixHtmlNode | MatrixMediaNode
48
+
49
+ /** One text event before resource resolution. */
50
+ export interface MatrixTextDraft {
51
+ kind: 'text'
52
+ html: string
53
+ text: string
54
+ mentions: MatrixMentionWire
55
+ }
56
+
57
+ /** One media event before resource resolution. */
58
+ export interface MatrixMediaDraft {
59
+ kind: 'media'
60
+ tag: MatrixMediaTag
61
+ ref: ResourceRef
62
+ name?: string
63
+ width?: number
64
+ height?: number
65
+ duration?: number
66
+ mentions: MatrixMentionWire
67
+ }
68
+
69
+ /** One platform event before resource resolution. */
70
+ export type MatrixDraft = MatrixTextDraft | MatrixMediaDraft
71
+
72
+ /** `info` of one media event. */
73
+ export interface MatrixMediaInfo {
74
+ w?: number
75
+ h?: number
76
+ mimetype?: string
77
+ size?: number
78
+ duration?: number
79
+ }
80
+
81
+ /** The thread relation one payload carries. */
82
+ export interface MatrixThread {
83
+ root: string
84
+ }
85
+
86
+ /** The `m.relates_to` object of one payload. */
87
+ export interface MatrixRelation {
88
+ rel_type?: 'm.thread'
89
+ event_id?: string
90
+ 'm.in_reply_to'?: { event_id: string }
91
+ is_falling_back?: boolean
92
+ }
93
+
94
+ /** One `m.text` request body. */
95
+ export interface MatrixTextPayload {
96
+ kind: 'text'
97
+ roomId: string
98
+ body: string
99
+ html?: string
100
+ mentions: MatrixMentionWire
101
+ relates?: MatrixRelation
102
+ thread?: MatrixThread
103
+ }
104
+
105
+ /** One media request body (`m.image` / `m.file` / `m.audio` / `m.video`). */
106
+ export interface MatrixMediaPayload {
107
+ kind: 'media'
108
+ roomId: string
109
+ msgtype: 'm.image' | 'm.file' | 'm.audio' | 'm.video'
110
+ url: string
111
+ body: string
112
+ info?: MatrixMediaInfo
113
+ mentions: MatrixMentionWire
114
+ relates?: MatrixRelation
115
+ thread?: MatrixThread
116
+ }
117
+
118
+ /** Exact request data of one platform event. */
119
+ export type MatrixPayload = MatrixTextPayload | MatrixMediaPayload
120
+
121
+ /** Mode types of the `html` mode. */
122
+ export interface MatrixModeTypes extends ModeTypes {
123
+ node: MatrixNode
124
+ draft: MatrixDraft
125
+ payload: MatrixPayload
126
+ }
127
+
128
+ /** Escape character data of `formatted_body`. */
129
+ export function escapeHtml(text: string): string {
130
+ return text
131
+ .replaceAll('&', '&')
132
+ .replaceAll('<', '&lt;')
133
+ .replaceAll('>', '&gt;')
134
+ }
135
+
136
+ /** Escape one HTML attribute value (double-quoted). */
137
+ export function escapeAttribute(text: string): string {
138
+ return escapeHtml(text).replaceAll('"', '&quot;')
139
+ }
140
+
141
+ /** One inline node. */
142
+ export function htmlNode(
143
+ html: string,
144
+ text: string,
145
+ mentions?: MentionNode[],
146
+ ): MatrixHtmlNode {
147
+ return {
148
+ type: 'html',
149
+ html,
150
+ text,
151
+ ...(mentions === undefined || mentions.length === 0 ? {} : { mentions }),
152
+ }
153
+ }
154
+
155
+ /** The mutable mention collection one inline run accumulates. */
156
+ export type MatrixMentionSet = ReturnType<typeof createMentionSet>
157
+
158
+ /** One mention node per collected user and one for the room mention. */
159
+ export function mentionNodes(set: MatrixMentionSet): MentionNode[] {
160
+ return [
161
+ ...set.users.map((user) => ({ user })),
162
+ ...(set.room ? [{ room: true }] : []),
163
+ ]
164
+ }
165
+
166
+ /** The inline HTML and text of rendered children, plus the media that cannot ride inside the run. */
167
+ export interface InlineRun {
168
+ html: string
169
+ text: string
170
+ mentions: MatrixMentionSet
171
+ rest: MatrixNode[]
172
+ }
173
+
174
+ /**
175
+ * Split rendered children into one inline run and the media nodes that follow it.
176
+ * @param nodes - rendered children.
177
+ * @returns the concatenated HTML/text, the collected mentions and the media nodes, in source order.
178
+ */
179
+ export function inlineRun(nodes: readonly MatrixNode[]): InlineRun {
180
+ let html = ''
181
+ let text = ''
182
+ const mentions = createMentionSet()
183
+ const rest: MatrixNode[] = []
184
+ for (const node of nodes) {
185
+ if (node.type === 'media') {
186
+ rest.push(node)
187
+ continue
188
+ }
189
+ html += node.html
190
+ text += node.text
191
+ for (const mention of node.mentions ?? []) addMention(mentions, mention)
192
+ }
193
+ return { html, text, mentions, rest }
194
+ }
195
+
196
+ /**
197
+ * Wrap the inline text of rendered children in one HTML tag; media of the subtree follows the wrapper.
198
+ * @param tag - the HTML tag name.
199
+ * @param nodes - rendered children.
200
+ * @param textSuffix - plain-text separator this block adds after its inline text.
201
+ * @returns the wrapper (when it has text) and the media nodes.
202
+ */
203
+ export function inlineWrapper(
204
+ tag: string,
205
+ nodes: readonly MatrixNode[],
206
+ textSuffix = '',
207
+ ): MatrixNode[] {
208
+ const { html, text, mentions, rest } = inlineRun(nodes)
209
+ const out: MatrixNode[] = []
210
+ if (html !== '') {
211
+ out.push(
212
+ htmlNode(
213
+ `<${tag}>${html}</${tag}>`,
214
+ text + textSuffix,
215
+ mentionNodes(mentions),
216
+ ),
217
+ )
218
+ }
219
+ out.push(...rest)
220
+ return out
221
+ }
222
+
223
+ /**
224
+ * Turn one media element into its node.
225
+ *
226
+ * Matrix clients render inline `mxc:` images inconsistently and a media message is the standard presentation, so every
227
+ * media element becomes its own event. Media standing in phrasing content is reported as `moved`: nothing is lost,
228
+ * only repositioned.
229
+ *
230
+ * @param el - one of `img`/`audio`/`video`/`file`.
231
+ * @param ctx - render context of the mode.
232
+ * @returns the media node, to be published after the text run it was found in.
233
+ */
234
+ export function mediaNode(
235
+ el: Element<MatrixMediaTag>,
236
+ ctx: RenderContext<MatrixModeTypes>,
237
+ ): MatrixNode {
238
+ const parent = ctx.ancestors[ctx.ancestors.length - 1]
239
+ if (parent !== undefined && isPhrasingContainer(parent.type)) {
240
+ ctx.report.moved.push({
241
+ tag: el.type,
242
+ reason: 'matrix-media-split',
243
+ path: ctx.stableId(el),
244
+ })
245
+ }
246
+ switch (el.type) {
247
+ case 'img':
248
+ return {
249
+ type: 'media',
250
+ tag: 'img',
251
+ ref: ctx.resource('image', el.attrs.src, {
252
+ ...(el.attrs.alt === undefined ? {} : { name: el.attrs.alt }),
253
+ ...(el.attrs.width === undefined ? {} : { width: el.attrs.width }),
254
+ ...(el.attrs.height === undefined ? {} : { height: el.attrs.height }),
255
+ }),
256
+ ...(el.attrs.alt === undefined ? {} : { name: el.attrs.alt }),
257
+ ...(el.attrs.width === undefined ? {} : { width: el.attrs.width }),
258
+ ...(el.attrs.height === undefined ? {} : { height: el.attrs.height }),
259
+ }
260
+ case 'audio':
261
+ return {
262
+ type: 'media',
263
+ tag: 'audio',
264
+ ref: ctx.resource('audio', el.attrs.src, {
265
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
266
+ ...(el.attrs.duration === undefined
267
+ ? {}
268
+ : { duration: el.attrs.duration }),
269
+ }),
270
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
271
+ ...(el.attrs.duration === undefined
272
+ ? {}
273
+ : { duration: el.attrs.duration }),
274
+ }
275
+ case 'video':
276
+ return {
277
+ type: 'media',
278
+ tag: 'video',
279
+ ref: ctx.resource('video', el.attrs.src, {
280
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
281
+ ...(el.attrs.duration === undefined
282
+ ? {}
283
+ : { duration: el.attrs.duration }),
284
+ }),
285
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
286
+ ...(el.attrs.duration === undefined
287
+ ? {}
288
+ : { duration: el.attrs.duration }),
289
+ }
290
+ case 'file':
291
+ return {
292
+ type: 'media',
293
+ tag: 'file',
294
+ ref: ctx.resource(
295
+ 'file',
296
+ el.attrs.src,
297
+ el.attrs.name === undefined ? {} : { name: el.attrs.name },
298
+ ),
299
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
300
+ }
301
+ }
302
+ }
303
+
304
+ /** The Matrix `msgtype` of one media tag. */
305
+ export function msgtypeOf(
306
+ tag: MatrixMediaTag,
307
+ ): 'm.image' | 'm.file' | 'm.audio' | 'm.video' {
308
+ switch (tag) {
309
+ case 'img':
310
+ return 'm.image'
311
+ case 'audio':
312
+ return 'm.audio'
313
+ case 'video':
314
+ return 'm.video'
315
+ case 'file':
316
+ return 'm.file'
317
+ }
318
+ }
319
+
320
+ /**
321
+ * Fold a node stream into platform events: a text run around each media node.
322
+ * @param nodes - rendered nodes, in source order.
323
+ * @returns the drafts to publish, at least one for any content a handler produced.
324
+ */
325
+ export function assembleDrafts(nodes: readonly MatrixNode[]): MatrixDraft[] {
326
+ const drafts: MatrixDraft[] = []
327
+ let html = ''
328
+ let text = ''
329
+ let mentions = createMentionSet()
330
+
331
+ const flush = (): void => {
332
+ if (html.trim() === '' && text.trim() === '') {
333
+ html = ''
334
+ text = ''
335
+ mentions = createMentionSet()
336
+ return
337
+ }
338
+ drafts.push({ kind: 'text', html, text, mentions: mentionWire(mentions) })
339
+ html = ''
340
+ text = ''
341
+ mentions = createMentionSet()
342
+ }
343
+
344
+ for (const node of nodes) {
345
+ if (node.type === 'media') {
346
+ flush()
347
+ drafts.push({
348
+ kind: 'media',
349
+ tag: node.tag,
350
+ ref: node.ref,
351
+ ...(node.name === undefined ? {} : { name: node.name }),
352
+ ...(node.width === undefined ? {} : { width: node.width }),
353
+ ...(node.height === undefined ? {} : { height: node.height }),
354
+ ...(node.duration === undefined ? {} : { duration: node.duration }),
355
+ mentions: {},
356
+ })
357
+ continue
358
+ }
359
+ html += node.html
360
+ text += node.text
361
+ for (const mention of node.mentions ?? []) addMention(mentions, mention)
362
+ }
363
+ flush()
364
+ return drafts
365
+ }
366
+
367
+ /** The adapter-private reply context of a publication, when the target carries one. */
368
+ function referrerOf(
369
+ target: SerializeContext['target'],
370
+ ): MatrixReferrer | undefined {
371
+ const referrer = target.referrer
372
+ if (typeof referrer !== 'object' || referrer === null) return undefined
373
+ return referrer as MatrixReferrer
374
+ }
375
+
376
+ /** The thread root a target names: an explicit id, else the referrer's root for `thread: true`. */
377
+ function threadRootOf(target: SerializeContext['target']): string | undefined {
378
+ if (typeof target.thread === 'string') return target.thread
379
+ if (target.thread !== true) return undefined
380
+ return referrerOf(target)?.threadRoot
381
+ }
382
+
383
+ /**
384
+ * Build the `m.relates_to` object of one event.
385
+ *
386
+ * A reply names only the quoted event id: the fallback body needs the quoted text, which this adapter does not fetch.
387
+ * A thread carries its root, and — because the specification requires an unthreaded-client fallback — an
388
+ * `m.in_reply_to` naming the latest known event (`is_falling_back: true`).
389
+ */
390
+ function relationOf(ctx: SerializeContext): MatrixRelation | undefined {
391
+ const referrer = referrerOf(ctx.target)
392
+ const threadRoot = threadRootOf(ctx.target)
393
+ const quote = ctx.index === 0 ? ctx.quote : undefined
394
+ if (threadRoot === undefined) {
395
+ return quote === undefined
396
+ ? undefined
397
+ : { 'm.in_reply_to': { event_id: quote } }
398
+ }
399
+ const reply = quote ?? referrer?.eventId
400
+ return {
401
+ rel_type: 'm.thread',
402
+ event_id: threadRoot,
403
+ ...(reply === undefined
404
+ ? {}
405
+ : { is_falling_back: true, 'm.in_reply_to': { event_id: reply } }),
406
+ }
407
+ }
408
+
409
+ /** One media key resolved by `prepare`. */
410
+ function resolvedKey(
411
+ prepared: Prepared<MatrixDraft>,
412
+ ref: ResourceRef,
413
+ ): string {
414
+ const resolved = prepared.resolved.get(ref)
415
+ if (resolved === undefined) {
416
+ throw new PlatformError(
417
+ 'invalid',
418
+ 'matrix: media was not prepared before serialize',
419
+ { published: 'no' },
420
+ )
421
+ }
422
+ return resolved.key
423
+ }
424
+
425
+ /** The extra fields `upload` recorded for one prepared media key. */
426
+ function extraOf(
427
+ prepared: Prepared<MatrixDraft>,
428
+ ref: ResourceRef,
429
+ ): { name?: string; mime?: string; size?: number } {
430
+ const resolved = prepared.resolved.get(ref)
431
+ if (resolved === undefined) return {}
432
+ const extra = resolved.extra
433
+ if (typeof extra !== 'object' || extra === null) return {}
434
+ return extra
435
+ }
436
+
437
+ /**
438
+ * Build the request payload of one draft.
439
+ *
440
+ * @param prepared - one assembled draft with its resolved media.
441
+ * @param ctx - serialize context (target, part index, quote).
442
+ * @returns the exact request data `sendPayload` posts.
443
+ */
444
+ export function serializeDraft(
445
+ prepared: Prepared<MatrixDraft>,
446
+ ctx: SerializeContext,
447
+ ): MatrixPayload {
448
+ const draft = prepared.draft
449
+ const relates = relationOf(ctx)
450
+ const thread = threadRootOf(ctx.target)
451
+ const common = {
452
+ roomId: ctx.target.chat.id,
453
+ mentions: draft.mentions,
454
+ ...(relates === undefined ? {} : { relates }),
455
+ ...(thread === undefined ? {} : { thread: { root: thread } }),
456
+ }
457
+ if (draft.kind === 'text') {
458
+ const body = draft.text.trim()
459
+ const html = draft.html.trim()
460
+ return {
461
+ kind: 'text',
462
+ ...common,
463
+ // Matrix requires a plain `body`; the media path is the only draft that may carry no text.
464
+ body: body === '' ? ' ' : body,
465
+ ...(html === '' ? {} : { html }),
466
+ }
467
+ }
468
+ const extra = extraOf(prepared, draft.ref)
469
+ const body = draft.name ?? extra.name ?? 'file'
470
+ const info: MatrixMediaInfo = {
471
+ ...(draft.width === undefined ? {} : { w: draft.width }),
472
+ ...(draft.height === undefined ? {} : { h: draft.height }),
473
+ ...(draft.duration === undefined ? {} : { duration: draft.duration }),
474
+ ...(extra.mime === undefined ? {} : { mimetype: extra.mime }),
475
+ ...(extra.size === undefined ? {} : { size: extra.size }),
476
+ }
477
+ return {
478
+ kind: 'media',
479
+ ...common,
480
+ msgtype: msgtypeOf(draft.tag),
481
+ url: resolvedKey(prepared, draft.ref),
482
+ body,
483
+ ...(Object.keys(info).length === 0 ? {} : { info }),
484
+ }
485
+ }