@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,618 @@
1
+ /**
2
+ * Shared types and the draft machinery of the single `markdown` mode.
3
+ *
4
+ * A WeCom application message is one `message/send` call, and its `msgtype` decides what it can carry: `markdown` holds
5
+ * the formatted body, `image`/`voice`/`video`/`file` hold one `media_id` each, and `template_card` holds the buttons.
6
+ * A draft is therefore exactly one platform message: the body is split at the documented 2,048 bytes, every media
7
+ * element becomes a message of its own, and a message with buttons gets a card message after its body.
8
+ */
9
+
10
+ import { randomBytes } from 'node:crypto'
11
+ import { INTERACTION_DROPPED } from '@deepseek-ai/cordis-plugin-im-core'
12
+ import type {
13
+ Envelope,
14
+ LimitViolation,
15
+ ModeTypes,
16
+ Prepared,
17
+ RenderContext,
18
+ ResourceRef,
19
+ SerializeContext,
20
+ } from '@deepseek-ai/cordis-plugin-im-core'
21
+ import { isPhrasingContainer } from '@deepseek-ai/satori-element'
22
+ import type { Element } from '@deepseek-ai/satori-element'
23
+
24
+ /** One node a handler produces. */
25
+ export type WecomNode =
26
+ | { type: 'text'; text: string }
27
+ | { type: 'media'; media: WecomMediaKind; ref: ResourceRef; name?: string }
28
+ | { type: 'button'; key: string; text: string }
29
+ | { type: 'link-button'; text: string; href: string }
30
+ | { type: 'item'; nodes: WecomNode[] }
31
+ | { type: 'list'; ordered: boolean; start: number; items: WecomNode[] }
32
+
33
+ /** The four media `msgtype`s the platform accepts from an application. */
34
+ export type WecomMediaKind = 'image' | 'voice' | 'video' | 'file'
35
+
36
+ /** One button of the template card. */
37
+ export type WecomCardButton =
38
+ { text: string; key: string } | { text: string; href: string }
39
+
40
+ /** One platform message, before resource resolution. */
41
+ export type WecomDraft =
42
+ | { kind: 'markdown'; content: string }
43
+ | { kind: 'media'; media: WecomMediaKind; ref: ResourceRef; name?: string }
44
+ | { kind: 'card'; title: string; taskId: string; buttons: WecomCardButton[] }
45
+
46
+ /** One entry of a `button_interaction` card's `button_list`. */
47
+ export interface TemplateCardButton {
48
+ text: string
49
+ /** `1` for a jump button; a callback button omits it (`0`). */
50
+ type?: 1
51
+ key?: string
52
+ url?: string
53
+ }
54
+
55
+ /** The `template_card` body of one card message. */
56
+ export interface TemplateCard {
57
+ card_type: 'button_interaction'
58
+ main_title: { title: string }
59
+ button_list: TemplateCardButton[]
60
+ task_id: string
61
+ }
62
+
63
+ /** Exact request body of one `message/send` call. */
64
+ export type WecomPayload =
65
+ | {
66
+ touser: string
67
+ agentid: number
68
+ msgtype: 'markdown'
69
+ markdown: { content: string }
70
+ }
71
+ | {
72
+ touser: string
73
+ agentid: number
74
+ msgtype: 'image'
75
+ image: { media_id: string }
76
+ }
77
+ | {
78
+ touser: string
79
+ agentid: number
80
+ msgtype: 'voice'
81
+ voice: { media_id: string }
82
+ }
83
+ | {
84
+ touser: string
85
+ agentid: number
86
+ msgtype: 'video'
87
+ video: { media_id: string; title?: string }
88
+ }
89
+ | {
90
+ touser: string
91
+ agentid: number
92
+ msgtype: 'file'
93
+ file: { media_id: string }
94
+ }
95
+ | {
96
+ touser: string
97
+ agentid: number
98
+ msgtype: 'template_card'
99
+ template_card: TemplateCard
100
+ }
101
+
102
+ /** Mode types of the `markdown` mode. */
103
+ export interface WecomModeTypes extends ModeTypes {
104
+ node: WecomNode
105
+ draft: WecomDraft
106
+ payload: WecomPayload
107
+ }
108
+
109
+ /** The platform's documented bounds, and nothing else. */
110
+ export const WECOM_LIMITS = {
111
+ /** `text.content` and `markdown.content`: at most 2,048 bytes, counted as UTF-8. */
112
+ payloadBytes: 2_048,
113
+ /** `message/recall` accepts a message up to 24 hours after it was sent. */
114
+ deleteWindow: 24 * 60 * 60 * 1_000,
115
+ /** `button_list` of a `button_interaction` card holds at most six buttons. */
116
+ buttonsRow: 6,
117
+ /** The card has one button row. */
118
+ buttonRows: 1,
119
+ } as const
120
+
121
+ /** The word joiner a card title falls back to: the platform requires `main_title`, and content is never empty. */
122
+ export const CARD_TITLE_FALLBACK = '\u2060'
123
+
124
+ /** The process-wide random segment of every `task_id`, in base 36. */
125
+ let bootSalt = randomBytes(6).readUIntBE(0, 6).toString(36)
126
+
127
+ /** The sequence within this process; `task_id` must not repeat inside one application. */
128
+ let taskSequence = 0
129
+
130
+ /**
131
+ * Pin the process-random segment of every `task_id`.
132
+ *
133
+ * The platform requires the id to be unique inside one application, so it is seeded from process entropy. A test that
134
+ * compares serialized request bodies pins the segment instead, so two runs produce the same payloads; the counter keeps
135
+ * advancing, because two cards of one run still must not share an id.
136
+ *
137
+ * @param salt - the segment to use: `0-9a-zA-Z_-`, at most 128 bytes together with the rest of the id.
138
+ */
139
+ export function pinTaskIdSalt(salt: string): void {
140
+ bootSalt = salt
141
+ }
142
+
143
+ /**
144
+ * The `task_id` of one card.
145
+ *
146
+ * The platform requires the id to be unique within the application, so a counter alone would collide with the ids of the
147
+ * previous process after a restart; the random boot segment makes the pair unique across restarts.
148
+ *
149
+ * @returns an id the platform accepts: `0-9a-zA-Z_-` only, at most 128 bytes.
150
+ */
151
+ export function nextTaskId(): string {
152
+ taskSequence += 1
153
+ return `dsh-${bootSalt}-${taskSequence}`
154
+ }
155
+
156
+ /**
157
+ * Report inline media that moves out of its text run into a message of its own.
158
+ *
159
+ * @param el - the media element.
160
+ * @param ctx - the render context.
161
+ */
162
+ export function reportMovedMedia(
163
+ el: Element,
164
+ ctx: RenderContext<WecomModeTypes>,
165
+ ): void {
166
+ const parent = ctx.ancestors[ctx.ancestors.length - 1]
167
+ if (parent !== undefined && isPhrasingContainer(parent.type)) {
168
+ ctx.report.moved.push({
169
+ tag: el.type,
170
+ reason: 'wecom-media-split',
171
+ path: ctx.stableId(el),
172
+ })
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Cut one line into pieces of at most `limit` bytes, never inside a surrogate pair.
178
+ *
179
+ * @param text - the line to cut.
180
+ * @param limit - the byte bound.
181
+ * @returns the pieces, in order; concatenating them reproduces the line.
182
+ */
183
+ export function hardCutBytes(text: string, limit: number): string[] {
184
+ const pieces: string[] = []
185
+ let piece = ''
186
+ let bytes = 0
187
+ // `for…of` walks code points, so a surrogate pair is never split between two pieces.
188
+ for (const character of text) {
189
+ const size = Buffer.byteLength(character, 'utf8')
190
+ if (bytes + size > limit && piece !== '') {
191
+ pieces.push(piece)
192
+ piece = ''
193
+ bytes = 0
194
+ }
195
+ piece += character
196
+ bytes += size
197
+ }
198
+ if (piece !== '') pieces.push(piece)
199
+ return pieces
200
+ }
201
+
202
+ /**
203
+ * Cut a body into chunks the platform accepts.
204
+ *
205
+ * Lines are accumulated while they fit; a line that would overflow closes the current chunk, and a line longer than the
206
+ * bound is cut by bytes. A cut can land inside a formatting mark (`**`, `` ` ``), which the client then shows as literal
207
+ * characters: the platform documents no escape syntax that would avoid it.
208
+ *
209
+ * @param text - the body of one logical message.
210
+ * @param limit - the byte bound of one `markdown` message.
211
+ * @returns one or more chunks, in order; never empty.
212
+ */
213
+ export function splitMarkdownBytes(
214
+ text: string,
215
+ limit: number = WECOM_LIMITS.payloadBytes,
216
+ ): string[] {
217
+ if (Buffer.byteLength(text, 'utf8') <= limit) return [text]
218
+ const chunks: string[] = []
219
+ let current = ''
220
+ let currentBytes = 0
221
+ const close = (): void => {
222
+ if (current !== '') chunks.push(current)
223
+ current = ''
224
+ currentBytes = 0
225
+ }
226
+ for (const line of text.split(/(?<=\n)/)) {
227
+ const lineBytes = Buffer.byteLength(line, 'utf8')
228
+ if (currentBytes + lineBytes <= limit) {
229
+ current += line
230
+ currentBytes += lineBytes
231
+ continue
232
+ }
233
+ close()
234
+ if (lineBytes <= limit) {
235
+ current = line
236
+ currentBytes = lineBytes
237
+ continue
238
+ }
239
+ const pieces = hardCutBytes(line, limit)
240
+ // Everything but the last piece is one chunk of its own; the tail stays open for the next line.
241
+ for (const piece of pieces.slice(0, -1)) chunks.push(piece)
242
+ current = pieces[pieces.length - 1] ?? ''
243
+ currentBytes = Buffer.byteLength(current, 'utf8')
244
+ }
245
+ close()
246
+ return chunks.length === 0 ? [''] : chunks
247
+ }
248
+
249
+ /** Strip the newlines a paragraph puts around the content of one list item. */
250
+ function trimEdges(nodes: WecomNode[]): WecomNode[] {
251
+ const out = [...nodes]
252
+ while (out.length > 0) {
253
+ const first = out[0]!
254
+ if (first.type !== 'text') break
255
+ const stripped = first.text.replace(/^\n+/, '')
256
+ if (stripped === '') {
257
+ out.shift()
258
+ continue
259
+ }
260
+ out[0] = { type: 'text', text: stripped }
261
+ break
262
+ }
263
+ while (out.length > 0) {
264
+ const last = out[out.length - 1]!
265
+ if (last.type !== 'text') break
266
+ const stripped = last.text.replace(/\n+$/, '')
267
+ if (stripped === '') {
268
+ out.pop()
269
+ continue
270
+ }
271
+ out[out.length - 1] = { type: 'text', text: stripped }
272
+ break
273
+ }
274
+ return out
275
+ }
276
+
277
+ /** Put a list marker at the start of the item's first line, or before its first media node. */
278
+ function applyMarker(nodes: WecomNode[], marker: string): void {
279
+ for (let index = 0; index < nodes.length; index++) {
280
+ const node = nodes[index]!
281
+ if (node.type !== 'text') {
282
+ nodes.splice(index, 0, { type: 'text', text: marker.trimEnd() })
283
+ return
284
+ }
285
+ const leading = /^\n*/.exec(node.text)?.[0].length ?? 0
286
+ if (leading < node.text.length) {
287
+ nodes[index] = {
288
+ type: 'text',
289
+ text: `${node.text.slice(0, leading)}${marker}${node.text.slice(leading)}`,
290
+ }
291
+ return
292
+ }
293
+ }
294
+ }
295
+
296
+ /** One list node, expanded into one line per item. */
297
+ function flattenList(
298
+ node: Extract<WecomNode, { type: 'list' }>,
299
+ depth: number,
300
+ ): WecomNode[] {
301
+ const out: WecomNode[] = []
302
+ const indent = ' '.repeat(depth)
303
+ let number = node.start
304
+ node.items.forEach((item, index) => {
305
+ const marker = node.ordered ? `${indent}${number++}. ` : `${indent}- `
306
+ const inner = trimEdges(
307
+ flattenAt(item.type === 'item' ? item.nodes : [item], depth + 1),
308
+ )
309
+ if (index > 0) out.push({ type: 'text', text: '\n' })
310
+ if (inner.length === 0) {
311
+ out.push({ type: 'text', text: marker.trimEnd() })
312
+ return
313
+ }
314
+ applyMarker(inner, marker)
315
+ out.push(...inner)
316
+ })
317
+ if (out.length > 0) out.push({ type: 'text', text: '\n' })
318
+ return out
319
+ }
320
+
321
+ /** Expand every list and item of one node stream. */
322
+ function flattenAt(nodes: readonly WecomNode[], depth: number): WecomNode[] {
323
+ const out: WecomNode[] = []
324
+ for (const node of nodes) {
325
+ switch (node.type) {
326
+ case 'text':
327
+ case 'media':
328
+ case 'button':
329
+ case 'link-button':
330
+ out.push(node)
331
+ break
332
+ case 'item':
333
+ out.push(...flattenAt(node.nodes, depth))
334
+ break
335
+ case 'list': {
336
+ const last = out[out.length - 1]
337
+ if (
338
+ last !== undefined &&
339
+ !(last.type === 'text' && last.text.endsWith('\n'))
340
+ ) {
341
+ out.push({ type: 'text', text: '\n' })
342
+ }
343
+ out.push(...flattenList(node, depth))
344
+ break
345
+ }
346
+ }
347
+ }
348
+ return out
349
+ }
350
+
351
+ /**
352
+ * Expand list and item nodes into the flat node stream {@link assembleDraft} splits into messages.
353
+ *
354
+ * @param nodes - rendered nodes, in document order.
355
+ * @returns the same content with every list marker applied and media nodes kept in place.
356
+ */
357
+ export function flattenNodes(nodes: readonly WecomNode[]): WecomNode[] {
358
+ return flattenAt(nodes, 0)
359
+ }
360
+
361
+ /** The media draft of one media node. */
362
+ function mediaDraftOf(node: Extract<WecomNode, { type: 'media' }>): WecomDraft {
363
+ return {
364
+ kind: 'media',
365
+ media: node.media,
366
+ ref: node.ref,
367
+ ...(node.name === undefined ? {} : { name: node.name }),
368
+ }
369
+ }
370
+
371
+ /**
372
+ * Fold a node stream into platform messages.
373
+ *
374
+ * The text buffer is split by bytes and closed before every media element; the collected buttons become one card
375
+ * message after the body, and a seventh button onwards degrades to a `[label]` line in the body. The title of the
376
+ * envelope stays in the body as a bold line and becomes the card's `main_title` when there is a card, so a title is
377
+ * never lost on a message without buttons.
378
+ *
379
+ * @param nodes - rendered nodes, in document order.
380
+ * @param envelope - the root `<title>`, if the content carried one.
381
+ * @param ctx - the render context, for the split and drop reports.
382
+ * @returns one draft per platform message, in send order; never empty.
383
+ */
384
+ export function assembleDraft(
385
+ nodes: WecomNode[],
386
+ envelope: Envelope,
387
+ ctx: RenderContext<WecomModeTypes>,
388
+ ): WecomDraft[] {
389
+ const drafts: WecomDraft[] = []
390
+ const buttons: WecomCardButton[] = []
391
+ let buffer = ''
392
+ let firstLine = ''
393
+ let split = 0
394
+
395
+ const noteFirstLine = (text: string): void => {
396
+ if (firstLine !== '') return
397
+ for (const line of text.split('\n')) {
398
+ const trimmed = line.trim()
399
+ if (trimmed !== '') {
400
+ firstLine = trimmed
401
+ return
402
+ }
403
+ }
404
+ }
405
+
406
+ const flushText = (): void => {
407
+ // The blank lines a paragraph puts around its text are separators inside the body, not at its edges.
408
+ const text = buffer.replace(/^\n+/, '').replace(/\n+$/, '')
409
+ buffer = ''
410
+ if (text === '') return
411
+ noteFirstLine(text)
412
+ const chunks = splitMarkdownBytes(text)
413
+ split += chunks.length - 1
414
+ for (const chunk of chunks)
415
+ drafts.push({ kind: 'markdown', content: chunk })
416
+ }
417
+
418
+ const title = envelope.title
419
+ const titleText = title === undefined ? '' : ctx.text(title.children).trim()
420
+ if (titleText !== '') {
421
+ buffer += `**${titleText}**`
422
+ const subtitle = title?.attrs.subtitle
423
+ if (subtitle !== undefined && subtitle !== '') buffer += `\n${subtitle}`
424
+ buffer += '\n'
425
+ }
426
+
427
+ for (const node of flattenNodes(nodes)) {
428
+ switch (node.type) {
429
+ case 'text':
430
+ buffer += node.text
431
+ break
432
+ case 'media':
433
+ flushText()
434
+ drafts.push(mediaDraftOf(node))
435
+ break
436
+ case 'button':
437
+ buttons.push({ text: node.text, key: node.key })
438
+ break
439
+ case 'link-button':
440
+ buttons.push({ text: node.text, href: node.href })
441
+ break
442
+ default:
443
+ break
444
+ }
445
+ }
446
+
447
+ if (buttons.length > WECOM_LIMITS.buttonsRow) {
448
+ // The platform refuses a seventh button, so the overflow becomes text instead of disappearing.
449
+ for (const button of buttons.splice(WECOM_LIMITS.buttonsRow)) {
450
+ const label = 'key' in button ? button.key : button.text
451
+ ctx.report.dropped.push({
452
+ what: `button:${label}`,
453
+ reason: INTERACTION_DROPPED,
454
+ })
455
+ buffer += `[${button.text}]\n`
456
+ }
457
+ }
458
+
459
+ if (buttons.length > 0) {
460
+ flushText()
461
+ drafts.push({
462
+ kind: 'card',
463
+ title:
464
+ titleText !== ''
465
+ ? titleText
466
+ : firstLine !== ''
467
+ ? firstLine
468
+ : CARD_TITLE_FALLBACK,
469
+ taskId: nextTaskId(),
470
+ buttons: [...buttons],
471
+ })
472
+ // The card is an extra platform message after a body that already exists.
473
+ if (drafts.length > 1) split += 1
474
+ } else {
475
+ flushText()
476
+ }
477
+
478
+ ctx.report.split += split
479
+ if (drafts.length === 0)
480
+ drafts.push({ kind: 'markdown', content: CARD_TITLE_FALLBACK })
481
+ return drafts
482
+ }
483
+
484
+ /** One resolved resource key of a prepared draft. */
485
+ function resolvedKey(prepared: Prepared<WecomDraft>, ref: ResourceRef): string {
486
+ const resolved = prepared.resolved.get(ref)
487
+ if (resolved === undefined) {
488
+ throw new Error('wecom: media was not prepared before serialize')
489
+ }
490
+ return resolved.key
491
+ }
492
+
493
+ /**
494
+ * Build the exact request body of one prepared draft.
495
+ *
496
+ * @param prepared - the draft with its resource keys resolved.
497
+ * @param ctx - the send context: the target chat names the `touser` recipient.
498
+ * @param agentId - the numeric `AgentID` every send carries.
499
+ * @returns the `message/send` body.
500
+ */
501
+ export function serializeDraft(
502
+ prepared: Prepared<WecomDraft>,
503
+ ctx: SerializeContext,
504
+ agentId: number,
505
+ ): WecomPayload {
506
+ const touser = ctx.target.chat.id
507
+ const draft = prepared.draft
508
+ switch (draft.kind) {
509
+ case 'markdown':
510
+ return {
511
+ touser,
512
+ agentid: agentId,
513
+ msgtype: 'markdown',
514
+ markdown: { content: draft.content },
515
+ }
516
+ case 'media': {
517
+ const mediaId = resolvedKey(prepared, draft.ref)
518
+ switch (draft.media) {
519
+ case 'image':
520
+ return {
521
+ touser,
522
+ agentid: agentId,
523
+ msgtype: 'image',
524
+ image: { media_id: mediaId },
525
+ }
526
+ case 'voice':
527
+ return {
528
+ touser,
529
+ agentid: agentId,
530
+ msgtype: 'voice',
531
+ voice: { media_id: mediaId },
532
+ }
533
+ case 'file':
534
+ return {
535
+ touser,
536
+ agentid: agentId,
537
+ msgtype: 'file',
538
+ file: { media_id: mediaId },
539
+ }
540
+ case 'video':
541
+ return {
542
+ touser,
543
+ agentid: agentId,
544
+ msgtype: 'video',
545
+ video: {
546
+ media_id: mediaId,
547
+ ...(draft.name === undefined ? {} : { title: draft.name }),
548
+ },
549
+ }
550
+ }
551
+ throw new Error('wecom: unknown media kind')
552
+ }
553
+ case 'card':
554
+ return {
555
+ touser,
556
+ agentid: agentId,
557
+ msgtype: 'template_card',
558
+ template_card: {
559
+ card_type: 'button_interaction',
560
+ main_title: { title: draft.title },
561
+ button_list: draft.buttons.map((button): TemplateCardButton =>
562
+ 'key' in button
563
+ ? { text: button.text, key: button.key }
564
+ : { text: button.text, type: 1, url: button.href },
565
+ ),
566
+ task_id: draft.taskId,
567
+ },
568
+ }
569
+ }
570
+ }
571
+
572
+ /**
573
+ * Hard platform limits of one draft, checked before any request.
574
+ *
575
+ * Splitting already keeps the body inside the byte bound and the card inside the button bound; the checks stay as the
576
+ * only place the adapter refuses a draft the platform would answer `45002` for.
577
+ *
578
+ * @param draft - the assembled draft.
579
+ * @returns every violation the platform would refuse.
580
+ */
581
+ export function checkDraft(draft: WecomDraft): LimitViolation[] {
582
+ switch (draft.kind) {
583
+ case 'markdown': {
584
+ const bytes = Buffer.byteLength(draft.content, 'utf8')
585
+ if (bytes <= WECOM_LIMITS.payloadBytes) return []
586
+ return [
587
+ {
588
+ kind: 'size',
589
+ key: 'limit.payload.bytes',
590
+ limit: WECOM_LIMITS.payloadBytes,
591
+ actual: bytes,
592
+ message: `WeCom markdown accepts ${WECOM_LIMITS.payloadBytes} bytes, got ${bytes}`,
593
+ },
594
+ ]
595
+ }
596
+ case 'card': {
597
+ const violations: LimitViolation[] = []
598
+ if (draft.buttons.length > WECOM_LIMITS.buttonsRow) {
599
+ violations.push({
600
+ kind: 'size',
601
+ key: 'limit.buttons.row',
602
+ limit: WECOM_LIMITS.buttonsRow,
603
+ actual: draft.buttons.length,
604
+ message: `WeCom cards accept ${WECOM_LIMITS.buttonsRow} buttons, got ${draft.buttons.length}`,
605
+ })
606
+ }
607
+ if (draft.taskId === '') {
608
+ violations.push({
609
+ kind: 'shape',
610
+ message: 'WeCom cards need a task_id',
611
+ })
612
+ }
613
+ return violations
614
+ }
615
+ case 'media':
616
+ return []
617
+ }
618
+ }