@im-more/dsh-wecom 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 (91) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +13 -0
  3. package/lib/index.js +2077 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +50 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +126 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +48 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +68 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/crypto.d.ts +69 -0
  14. package/lib/types/crypto.d.ts.map +1 -0
  15. package/lib/types/crypto.js +129 -0
  16. package/lib/types/crypto.js.map +1 -0
  17. package/lib/types/decode.d.ts +58 -0
  18. package/lib/types/decode.d.ts.map +1 -0
  19. package/lib/types/decode.js +182 -0
  20. package/lib/types/decode.js.map +1 -0
  21. package/lib/types/errors.d.ts +67 -0
  22. package/lib/types/errors.d.ts.map +1 -0
  23. package/lib/types/errors.js +170 -0
  24. package/lib/types/errors.js.map +1 -0
  25. package/lib/types/identity.d.ts +20 -0
  26. package/lib/types/identity.d.ts.map +1 -0
  27. package/lib/types/identity.js +34 -0
  28. package/lib/types/identity.js.map +1 -0
  29. package/lib/types/index.d.ts +19 -0
  30. package/lib/types/index.d.ts.map +1 -0
  31. package/lib/types/index.js +18 -0
  32. package/lib/types/index.js.map +1 -0
  33. package/lib/types/internal.d.ts +154 -0
  34. package/lib/types/internal.d.ts.map +1 -0
  35. package/lib/types/internal.js +115 -0
  36. package/lib/types/internal.js.map +1 -0
  37. package/lib/types/media.d.ts +44 -0
  38. package/lib/types/media.d.ts.map +1 -0
  39. package/lib/types/media.js +116 -0
  40. package/lib/types/media.js.map +1 -0
  41. package/lib/types/modes/markdown.d.ts +20 -0
  42. package/lib/types/modes/markdown.d.ts.map +1 -0
  43. package/lib/types/modes/markdown.js +205 -0
  44. package/lib/types/modes/markdown.js.map +1 -0
  45. package/lib/types/modes/shared.d.ts +227 -0
  46. package/lib/types/modes/shared.d.ts.map +1 -0
  47. package/lib/types/modes/shared.js +487 -0
  48. package/lib/types/modes/shared.js.map +1 -0
  49. package/lib/types/request.d.ts +55 -0
  50. package/lib/types/request.d.ts.map +1 -0
  51. package/lib/types/request.js +202 -0
  52. package/lib/types/request.js.map +1 -0
  53. package/lib/types/send.d.ts +54 -0
  54. package/lib/types/send.d.ts.map +1 -0
  55. package/lib/types/send.js +124 -0
  56. package/lib/types/send.js.map +1 -0
  57. package/lib/types/token.d.ts +34 -0
  58. package/lib/types/token.d.ts.map +1 -0
  59. package/lib/types/token.js +61 -0
  60. package/lib/types/token.js.map +1 -0
  61. package/lib/types/transport/webhook.d.ts +41 -0
  62. package/lib/types/transport/webhook.d.ts.map +1 -0
  63. package/lib/types/transport/webhook.js +216 -0
  64. package/lib/types/transport/webhook.js.map +1 -0
  65. package/lib/types/types.d.ts +58 -0
  66. package/lib/types/types.d.ts.map +1 -0
  67. package/lib/types/types.js +2 -0
  68. package/lib/types/types.js.map +1 -0
  69. package/lib/types/xml.d.ts +40 -0
  70. package/lib/types/xml.d.ts.map +1 -0
  71. package/lib/types/xml.js +82 -0
  72. package/lib/types/xml.js.map +1 -0
  73. package/package.json +65 -3
  74. package/src/bot.ts +195 -0
  75. package/src/config.ts +117 -0
  76. package/src/crypto.ts +172 -0
  77. package/src/decode.ts +238 -0
  78. package/src/errors.ts +199 -0
  79. package/src/identity.ts +41 -0
  80. package/src/index.ts +101 -0
  81. package/src/internal.ts +237 -0
  82. package/src/media.ts +157 -0
  83. package/src/modes/markdown.ts +263 -0
  84. package/src/modes/shared.ts +618 -0
  85. package/src/request.ts +291 -0
  86. package/src/send.ts +172 -0
  87. package/src/token.ts +75 -0
  88. package/src/transport/webhook.ts +292 -0
  89. package/src/types.ts +74 -0
  90. package/src/xml.ts +89 -0
  91. package/README.md +0 -3
@@ -0,0 +1,237 @@
1
+ import type { WecomBot } from './bot.ts'
2
+ import type { WecomPayload } from './modes/shared.ts'
3
+ import { download, invoke } from './request.ts'
4
+ import type { WecomTokenAnswer } from './token.ts'
5
+
6
+ /** Answer of `GET /cgi-bin/gettoken`; the token cache reads it. */
7
+ export type { WecomTokenAnswer }
8
+
9
+ /** Answer of `GET /cgi-bin/agent/get`. */
10
+ export interface AgentGetAnswer {
11
+ errcode?: number
12
+ errmsg?: string
13
+ agentid?: number | string
14
+ name?: string
15
+ square_logo_url?: string
16
+ }
17
+
18
+ /** Answer of `GET /cgi-bin/user/get`. */
19
+ export interface UserGetAnswer {
20
+ errcode?: number
21
+ errmsg?: string
22
+ userid?: string
23
+ name?: string
24
+ }
25
+
26
+ /** Answer of `POST /cgi-bin/message/send`. */
27
+ export interface MessageSendAnswer {
28
+ errcode?: number
29
+ errmsg?: string
30
+ /** `|`-separated userids that do not exist or are outside the application's visible range. */
31
+ invaliduser?: string
32
+ invalidparty?: string
33
+ invalidtag?: string
34
+ /** `|`-separated userids inside the range but without a basic API licence. */
35
+ unlicenseduser?: string
36
+ msgid?: string
37
+ /** Only a card that may be updated later carries one. */
38
+ response_code?: string
39
+ }
40
+
41
+ /** Answer of `POST /cgi-bin/media/upload`. */
42
+ export interface MediaUploadAnswer {
43
+ errcode?: number
44
+ errmsg?: string
45
+ type?: string
46
+ media_id?: string
47
+ created_at?: number
48
+ }
49
+
50
+ /** Answer of `POST /cgi-bin/message/recall`, `update_template_card` and `appchat/send`. */
51
+ export interface WecomStatusAnswer {
52
+ errcode?: number
53
+ errmsg?: string
54
+ msgid?: string
55
+ }
56
+
57
+ /** One `update_template_card` request. */
58
+ export interface UpdateTemplateCardInput {
59
+ userids: string[]
60
+ agentid: number
61
+ response_code: string
62
+ template_card?: object
63
+ button?: { replace_name: string }
64
+ }
65
+
66
+ /** One `appchat/send` request: the platform's group-chat surface, which no adapter hook uses. */
67
+ export interface AppchatSendInput {
68
+ chatid: string
69
+ msgtype: string
70
+ [field: string]: unknown
71
+ }
72
+
73
+ /**
74
+ * The mapped WeCom REST surface: one method per platform endpoint of the adapter's scope, and nothing hand-written on
75
+ * top of it.
76
+ *
77
+ * Every method goes through `request.ts`, so `access_token` injection, `errcode` unwrapping and the refresh-and-retry of
78
+ * a refused token are identical for all of them.
79
+ */
80
+ export class Internal {
81
+ constructor(private readonly bot: WecomBot) {}
82
+
83
+ /**
84
+ * Exchange the enterprise credentials for an application `access_token`.
85
+ *
86
+ * @param input - the enterprise id and the application secret.
87
+ * @returns the token envelope, with `expires_in`.
88
+ */
89
+ async getToken(input: {
90
+ corpid: string
91
+ corpsecret: string
92
+ }): Promise<WecomTokenAnswer> {
93
+ return await invoke<WecomTokenAnswer>(
94
+ this.bot,
95
+ 'GET',
96
+ '/cgi-bin/gettoken',
97
+ {
98
+ params: { corpid: input.corpid, corpsecret: input.corpsecret },
99
+ },
100
+ )
101
+ }
102
+
103
+ /**
104
+ * Read one application's own description.
105
+ *
106
+ * @param input - the numeric `AgentID`.
107
+ * @returns the application envelope, with `name` and `square_logo_url`.
108
+ */
109
+ async agentGet(input: { agentid: number }): Promise<AgentGetAnswer> {
110
+ return await invoke<AgentGetAnswer>(this.bot, 'GET', '/cgi-bin/agent/get', {
111
+ params: { agentid: input.agentid },
112
+ })
113
+ }
114
+
115
+ /**
116
+ * Read one member of the enterprise address book.
117
+ *
118
+ * @param input - the member userid.
119
+ * @returns the member envelope, with `name` when the application may see it.
120
+ */
121
+ async userGet(input: { userid: string }): Promise<UserGetAnswer> {
122
+ return await invoke<UserGetAnswer>(this.bot, 'GET', '/cgi-bin/user/get', {
123
+ params: { userid: input.userid },
124
+ })
125
+ }
126
+
127
+ /**
128
+ * Push one application message.
129
+ *
130
+ * @param input - the exact `message/send` body.
131
+ * @returns the send envelope, with `msgid` and the invalid-recipient lists.
132
+ */
133
+ async messageSend(input: WecomPayload): Promise<MessageSendAnswer> {
134
+ return await invoke<MessageSendAnswer>(
135
+ this.bot,
136
+ 'POST',
137
+ '/cgi-bin/message/send',
138
+ {
139
+ data: input,
140
+ },
141
+ )
142
+ }
143
+
144
+ /**
145
+ * Upload one temporary media file.
146
+ *
147
+ * @param input - the platform media type (`image`, `voice`, `video`, `file`) and the multipart form.
148
+ * @returns the upload envelope, with `media_id` and `created_at`.
149
+ */
150
+ async mediaUpload(
151
+ input: { type: string; media: FormData },
152
+ signal?: AbortSignal,
153
+ ): Promise<MediaUploadAnswer> {
154
+ return await invoke<MediaUploadAnswer>(
155
+ this.bot,
156
+ 'POST',
157
+ '/cgi-bin/media/upload',
158
+ {
159
+ params: { type: input.type },
160
+ data: input.media,
161
+ ...(signal === undefined ? {} : { signal }),
162
+ },
163
+ )
164
+ }
165
+
166
+ /**
167
+ * Download the bytes of one temporary media file.
168
+ *
169
+ * @param input - the `media_id` the callback carried.
170
+ * @param signal - cancellation.
171
+ * @returns the answer as it arrived: the bytes, or the platform's JSON refusal.
172
+ */
173
+ async mediaGet(
174
+ input: { media_id: string },
175
+ signal?: AbortSignal,
176
+ ): Promise<Response> {
177
+ return await download(
178
+ this.bot,
179
+ '/cgi-bin/media/get',
180
+ { media_id: input.media_id },
181
+ signal,
182
+ )
183
+ }
184
+
185
+ /**
186
+ * Recall one published application message.
187
+ *
188
+ * @param input - the `msgid` the send answer carried.
189
+ * @returns the status envelope.
190
+ */
191
+ async messageRecall(input: { msgid: string }): Promise<WecomStatusAnswer> {
192
+ return await invoke<WecomStatusAnswer>(
193
+ this.bot,
194
+ 'POST',
195
+ '/cgi-bin/message/recall',
196
+ {
197
+ data: { msgid: input.msgid },
198
+ },
199
+ )
200
+ }
201
+
202
+ /**
203
+ * Update one button-interaction card, within the platform's 72-hour, single-use window.
204
+ *
205
+ * @param input - the recipients, the card identity and the new card or button.
206
+ * @returns the status envelope.
207
+ */
208
+ async updateTemplateCard(
209
+ input: UpdateTemplateCardInput,
210
+ ): Promise<WecomStatusAnswer> {
211
+ return await invoke<WecomStatusAnswer>(
212
+ this.bot,
213
+ 'POST',
214
+ '/cgi-bin/message/update_template_card',
215
+ {
216
+ data: input,
217
+ },
218
+ )
219
+ }
220
+
221
+ /**
222
+ * Send one message into an application group chat.
223
+ *
224
+ * @param input - the group chat id and the message fields.
225
+ * @returns the send envelope.
226
+ */
227
+ async appchatSend(input: AppchatSendInput): Promise<WecomStatusAnswer> {
228
+ return await invoke<WecomStatusAnswer>(
229
+ this.bot,
230
+ 'POST',
231
+ '/cgi-bin/appchat/send',
232
+ {
233
+ data: input,
234
+ },
235
+ )
236
+ }
237
+ }
package/src/media.ts ADDED
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Media in both directions.
3
+ *
4
+ * Outbound, the platform has a real upload endpoint: the bytes are fetched, posted to `media/upload` as a multipart form
5
+ * and the returned `media_id` is what a `message/send` of type `image`/`voice`/`video`/`file` carries. The id lives three
6
+ * days, so the resolved resource carries an `expiresAt` and the core uploads the same content again after that instead of
7
+ * reusing an id the platform has already dropped.
8
+ *
9
+ * Inbound, the callback names only a `MediaId`; the bytes are read on demand from `media/get` through the bot's own
10
+ * `satori:` route.
11
+ */
12
+
13
+ import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
14
+ import type {
15
+ PrepareContext,
16
+ ResolvedResource,
17
+ ResourceKind,
18
+ ResourceRef,
19
+ } from '@deepseek-ai/cordis-plugin-im-core'
20
+ import type { WecomBot } from './bot.ts'
21
+
22
+ /** How long a temporary `media_id` stays readable: the platform documents three days. */
23
+ export const MEDIA_LIFETIME_MS = 3 * 24 * 60 * 60 * 1_000
24
+
25
+ /** Message of any caught value, for a log line. */
26
+ function messageOf(error: unknown): string {
27
+ return error instanceof Error ? error.message : String(error)
28
+ }
29
+
30
+ /**
31
+ * The platform upload type of one resource kind.
32
+ *
33
+ * @param kind - the resource kind of the element.
34
+ * @returns `image`, `voice`, `video` or `file`; the platform names audio `voice`.
35
+ */
36
+ export function mediaTypeOf(
37
+ kind: ResourceKind,
38
+ ): 'image' | 'voice' | 'video' | 'file' {
39
+ switch (kind) {
40
+ case 'image':
41
+ return 'image'
42
+ case 'audio':
43
+ return 'voice'
44
+ case 'video':
45
+ return 'video'
46
+ case 'file':
47
+ return 'file'
48
+ }
49
+ }
50
+
51
+ /** File name of a source, for the multipart part of an upload. */
52
+ function fileNameOf(
53
+ ref: ResourceRef,
54
+ fetchedName: string | undefined,
55
+ mime: string | undefined,
56
+ ): string {
57
+ if (ref.meta.name !== undefined && ref.meta.name !== '') return ref.meta.name
58
+ if (fetchedName !== undefined && fetchedName !== '') return fetchedName
59
+ const subtype = mime?.split('/')[1]?.split(';')[0]
60
+ return `wecom-${ref.kind}${subtype === undefined ? '' : `.${subtype}`}`
61
+ }
62
+
63
+ /**
64
+ * Upload one outbound attachment and return the `media_id` a send references.
65
+ *
66
+ * @param bot - the adapter whose credentials the upload uses.
67
+ * @param ref - the unresolved resource.
68
+ * @param ctx - fetch context of the send pipeline.
69
+ * @returns the platform media key, with the three-day expiry the core caches against.
70
+ * @throws PlatformError with an unknown outcome when the platform accepted the upload without returning an id.
71
+ */
72
+ export async function uploadMedia(
73
+ bot: WecomBot,
74
+ ref: ResourceRef,
75
+ ctx: PrepareContext,
76
+ ): Promise<ResolvedResource> {
77
+ const fetched = await ctx.fetch(ref.src, ctx.signal)
78
+ const mime = ref.meta.mime ?? fetched.mime
79
+ const name = fileNameOf(ref, fetched.name, mime)
80
+ const type = mediaTypeOf(ref.kind)
81
+ const form = new FormData()
82
+ form.append(
83
+ 'media',
84
+ new Blob([fetched.data], mime === undefined ? {} : { type: mime }),
85
+ name,
86
+ )
87
+ const answer = await bot.internal.mediaUpload(
88
+ { type, media: form },
89
+ ctx.signal,
90
+ )
91
+ if (answer.media_id === undefined || answer.media_id === '') {
92
+ // The request reached the platform and it answered success, but no reusable key came back.
93
+ throw new PlatformError(
94
+ 'invalid',
95
+ 'wecom: /cgi-bin/media/upload answered without a media_id',
96
+ { published: 'unknown' },
97
+ )
98
+ }
99
+ const createdAt = answer.created_at
100
+ return {
101
+ key: answer.media_id,
102
+ ...(typeof createdAt === 'number' && Number.isFinite(createdAt)
103
+ ? { expiresAt: createdAt * 1_000 + MEDIA_LIFETIME_MS }
104
+ : {}),
105
+ extra: {
106
+ type,
107
+ name,
108
+ ...(mime === undefined ? {} : { mime }),
109
+ size: fetched.data.byteLength,
110
+ },
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Serve the bytes of one inbound media object.
116
+ *
117
+ * A `media_id` the platform no longer accepts (it lives three days), a file above the 20 MB the plain download serves and
118
+ * a transport failure all answer `502`: the stored element keeps its label, but its bytes are gone.
119
+ *
120
+ * @param bot - the receiving adapter.
121
+ * @param mediaId - the `MediaId` the callback carried.
122
+ * @returns the bytes with their own headers, or the refusal status.
123
+ */
124
+ export async function serveMedia(
125
+ bot: WecomBot,
126
+ mediaId: string,
127
+ ): Promise<Response> {
128
+ let response: Response
129
+ try {
130
+ response = await bot.internal.mediaGet({ media_id: mediaId })
131
+ } catch (error) {
132
+ bot.ctx.logger.warn(
133
+ 'wecom: media %s could not be downloaded: %s',
134
+ mediaId,
135
+ messageOf(error),
136
+ )
137
+ return new Response(null, { status: 502 })
138
+ }
139
+ const contentType = response.headers.get('content-type') ?? ''
140
+ if (!response.ok || contentType.includes('application/json')) {
141
+ // A failure of this endpoint is still HTTP 200 with an `{ errcode }` envelope (40007 once the id expired).
142
+ bot.ctx.logger.warn(
143
+ 'wecom: media %s answered %s: %s',
144
+ mediaId,
145
+ String(response.status),
146
+ contentType.includes('application/json')
147
+ ? await response.text()
148
+ : contentType,
149
+ )
150
+ return new Response(null, { status: 502 })
151
+ }
152
+ const headers = new Headers()
153
+ if (contentType !== '') headers.set('content-type', contentType)
154
+ const disposition = response.headers.get('content-disposition')
155
+ if (disposition !== null) headers.set('content-disposition', disposition)
156
+ return new Response(response.body, { status: response.status, headers })
157
+ }
@@ -0,0 +1,263 @@
1
+ /**
2
+ * `markdown` mode: the single outbound representation of an application message.
3
+ *
4
+ * The body is sent verbatim — the platform documents a markdown subset but no escape syntax, so nothing is escaped and
5
+ * a pair of `*` in the text may render as bold. Headings, bold, links, inline code, block quotes, font colours,
6
+ * mentions, lists and media have a native form; italic, underline, strike-through, spoilers, code blocks, rules,
7
+ * tables, panels and form controls take the core fallback, which keeps their text and records the degradation.
8
+ * Buttons become one `template_card` message after the body.
9
+ */
10
+
11
+ import { ElementRegistry } from '@deepseek-ai/cordis-plugin-im-core'
12
+ import type { Mode, RenderContext } from '@deepseek-ai/cordis-plugin-im-core'
13
+ import type { Element } from '@deepseek-ai/satori-element'
14
+ import type { Config } from '../config.ts'
15
+ import {
16
+ assembleDraft,
17
+ checkDraft,
18
+ reportMovedMedia,
19
+ serializeDraft,
20
+ WECOM_LIMITS,
21
+ } from './shared.ts'
22
+ import type { WecomMediaKind, WecomModeTypes, WecomNode } from './shared.ts'
23
+
24
+ /** How a `span[color]` value maps onto the three colours the platform paints. */
25
+ const FONT_COLOR: Record<string, string | undefined> = {
26
+ default: undefined,
27
+ muted: 'comment',
28
+ info: 'info',
29
+ success: 'info',
30
+ warning: 'warning',
31
+ danger: 'warning',
32
+ }
33
+
34
+ /** The text run of rendered children and the nodes that cannot ride inside it. */
35
+ function textRun(nodes: readonly WecomNode[]): {
36
+ text: string
37
+ rest: WecomNode[]
38
+ } {
39
+ let text = ''
40
+ const rest: WecomNode[] = []
41
+ for (const node of nodes) {
42
+ if (node.type === 'text') text += node.text
43
+ else rest.push(node)
44
+ }
45
+ return { text, rest }
46
+ }
47
+
48
+ /** One inline mark around the rendered children, keeping any media of the subtree outside it. */
49
+ function marked(
50
+ children: readonly Element[],
51
+ ctx: RenderContext<WecomModeTypes>,
52
+ open: string,
53
+ close = open,
54
+ ): WecomNode[] {
55
+ const run = textRun(ctx.render(children))
56
+ if (run.text === '') return run.rest
57
+ return [{ type: 'text', text: `${open}${run.text}${close}` }, ...run.rest]
58
+ }
59
+
60
+ /** One rendered line: the platform has no multiline construct, so embedded newlines become spaces. */
61
+ function oneLine(text: string): string {
62
+ return text.replace(/\s*\n+\s*/g, ' ').trim()
63
+ }
64
+
65
+ /** One media message; a media element standing in phrasing content is reported as moved, not as degraded. */
66
+ function mediaNode(
67
+ media: WecomMediaKind,
68
+ kind: 'image' | 'audio' | 'video' | 'file',
69
+ el: Element,
70
+ ctx: RenderContext<WecomModeTypes>,
71
+ src: string,
72
+ meta: { name?: string; duration?: number; size?: number },
73
+ ): WecomNode {
74
+ reportMovedMedia(el, ctx)
75
+ const name =
76
+ meta.name !== undefined && meta.name !== '' ? meta.name : undefined
77
+ return {
78
+ type: 'media',
79
+ media,
80
+ ref: ctx.resource(kind, src, meta),
81
+ ...(name === undefined ? {} : { name }),
82
+ }
83
+ }
84
+
85
+ /** The handler of one heading level: `#` repeated, then the text on a single line. */
86
+ function heading(level: 1 | 2 | 3 | 4 | 5 | 6) {
87
+ return (
88
+ el: Element<'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'>,
89
+ ctx: RenderContext<WecomModeTypes>,
90
+ ): WecomNode[] => {
91
+ const run = textRun(ctx.render(el.children))
92
+ const text = oneLine(run.text)
93
+ if (text === '') return run.rest
94
+ // A heading has to start a line, and it ends without one so the next line follows directly below it.
95
+ return [
96
+ { type: 'text', text: `\n${'#'.repeat(level)} ${text}` },
97
+ ...run.rest,
98
+ ]
99
+ }
100
+ }
101
+
102
+ /** The handler of one list: its items are collected into a list node the assembler expands into lines. */
103
+ function list(
104
+ ordered: boolean,
105
+ el: Element<'ul' | 'ol'>,
106
+ ctx: RenderContext<WecomModeTypes>,
107
+ ): WecomNode {
108
+ return {
109
+ type: 'list',
110
+ ordered,
111
+ start: el.type === 'ol' ? (el.attrs.start ?? 1) : 1,
112
+ items: ctx.render(el.children),
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Build the `markdown` mode.
118
+ *
119
+ * @param config - the adapter configuration; it carries the numeric `AgentID` every request body repeats.
120
+ * @returns the single mode this adapter registers.
121
+ */
122
+ export function createMarkdownMode(config: Config): Mode<WecomModeTypes> {
123
+ const elements = new ElementRegistry<WecomModeTypes>()
124
+ .register('text', (el) => ({ type: 'text', text: el.attrs.content }))
125
+ .register('br', () => ({ type: 'text', text: '\n' }))
126
+ // Paragraphs get a blank line between them; a paragraph that already ends on a newline is not padded twice.
127
+ .register('p', (el, ctx) => {
128
+ const nodes = ctx.render(el.children)
129
+ const run = textRun(nodes)
130
+ const out: WecomNode[] = [{ type: 'text', text: '\n' }, ...nodes]
131
+ if (!run.text.endsWith('\n')) out.push({ type: 'text', text: '\n' })
132
+ return out
133
+ })
134
+ .register('h1', heading(1))
135
+ .register('h2', heading(2))
136
+ .register('h3', heading(3))
137
+ .register('h4', heading(4))
138
+ .register('h5', heading(5))
139
+ .register('h6', heading(6))
140
+ .register('b', (el, ctx) => marked(el.children, ctx, '**'))
141
+ .register('code', (el, ctx): WecomNode[] => {
142
+ // The platform documents no multiline inline code, so the newlines of the subtree become spaces.
143
+ const text = oneLine(ctx.text(el.children))
144
+ return text === '' ? [] : [{ type: 'text', text: `\`${text}\`` }]
145
+ })
146
+ .register('a', (el, ctx) => {
147
+ const run = textRun(ctx.render(el.children))
148
+ const label = run.text.trim() === '' ? el.attrs.href : run.text
149
+ return [
150
+ { type: 'text', text: `[${label}](${el.attrs.href})` },
151
+ ...run.rest,
152
+ ]
153
+ })
154
+ .register(
155
+ 'span',
156
+ (el, ctx) => {
157
+ const color = FONT_COLOR[el.attrs.color ?? 'default']
158
+ const run = textRun(ctx.render(el.children))
159
+ if (run.text === '') return run.rest
160
+ if (color === undefined)
161
+ return [{ type: 'text', text: run.text }, ...run.rest]
162
+ return [
163
+ { type: 'text', text: `<font color="${color}">${run.text}</font>` },
164
+ ...run.rest,
165
+ ]
166
+ },
167
+ { variants: ['color'] },
168
+ )
169
+ // Application messages have no mention mechanism: the text is shown and nobody is notified.
170
+ .register(
171
+ 'at',
172
+ (el) => ({
173
+ type: 'text',
174
+ text: `@${el.attrs.name ?? el.attrs.id ?? ''}`,
175
+ }),
176
+ { variants: ['user'] },
177
+ )
178
+ .register('blockquote', (el, ctx) => {
179
+ const run = textRun(ctx.render(el.children))
180
+ // The paragraphs of the subtree end and start on newlines; a quote does not spell those as empty quoted lines.
181
+ const source = run.text.replace(/^\n+/, '').replace(/\n+$/, '')
182
+ if (source === '') return run.rest
183
+ const quoted = source
184
+ .split('\n')
185
+ .map((line) => `> ${line}`)
186
+ .join('\n')
187
+ return [{ type: 'text', text: quoted }, ...run.rest]
188
+ })
189
+ .register('ul', (el, ctx) => list(false, el, ctx))
190
+ .register('ol', (el, ctx) => list(true, el, ctx))
191
+ .register('li', (el, ctx) => ({
192
+ type: 'item',
193
+ nodes: ctx.render(el.children),
194
+ }))
195
+ .register(
196
+ 'img',
197
+ (el, ctx) => mediaNode('image', 'image', el, ctx, el.attrs.src, {}),
198
+ { variants: ['inline'] },
199
+ )
200
+ .register('audio', (el, ctx) =>
201
+ mediaNode('voice', 'audio', el, ctx, el.attrs.src, {
202
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
203
+ ...(el.attrs.duration === undefined
204
+ ? {}
205
+ : { duration: el.attrs.duration }),
206
+ }),
207
+ )
208
+ .register('video', (el, ctx) =>
209
+ mediaNode('video', 'video', el, ctx, el.attrs.src, {
210
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
211
+ ...(el.attrs.duration === undefined
212
+ ? {}
213
+ : { duration: el.attrs.duration }),
214
+ }),
215
+ )
216
+ .register('file', (el, ctx) =>
217
+ mediaNode('file', 'file', el, ctx, el.attrs.src, {
218
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
219
+ ...(el.attrs.size === undefined ? {} : { size: el.attrs.size }),
220
+ }),
221
+ )
222
+ .register(
223
+ 'button',
224
+ (el, ctx) => {
225
+ const text = ctx.text(el.children).trim()
226
+ const attrs = el.attrs
227
+ if (attrs.type === 'link') {
228
+ return {
229
+ type: 'link-button',
230
+ text: text === '' ? attrs.href : text,
231
+ href: attrs.href,
232
+ }
233
+ }
234
+ if (attrs.type === 'action' || attrs.type === 'submit') {
235
+ return {
236
+ type: 'button',
237
+ key: attrs.id,
238
+ text: text === '' ? attrs.id : text,
239
+ }
240
+ }
241
+ // Only `action` and `link` are declared, so the engine lowers an input button before this handler runs; the
242
+ // inline-code form keeps the command readable.
243
+ return { type: 'text', text: `\`${attrs.text}\`` }
244
+ },
245
+ { variants: ['action', 'link'] },
246
+ )
247
+ .envelope('title')
248
+
249
+ return {
250
+ id: 'markdown',
251
+ elements,
252
+ limits: {
253
+ 'limit.payload.bytes': WECOM_LIMITS.payloadBytes,
254
+ 'limit.delete.window': WECOM_LIMITS.deleteWindow,
255
+ 'limit.buttons.row': WECOM_LIMITS.buttonsRow,
256
+ 'limit.buttons.rows': WECOM_LIMITS.buttonRows,
257
+ },
258
+ assemble: (nodes, envelope, ctx) => assembleDraft(nodes, envelope, ctx),
259
+ serialize: (prepared, ctx) =>
260
+ serializeDraft(prepared, ctx, Number(config.agentId)),
261
+ check: (draft) => checkDraft(draft),
262
+ }
263
+ }