@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,116 @@
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
+ import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core';
13
+ /** How long a temporary `media_id` stays readable: the platform documents three days. */
14
+ export const MEDIA_LIFETIME_MS = 3 * 24 * 60 * 60 * 1_000;
15
+ /** Message of any caught value, for a log line. */
16
+ function messageOf(error) {
17
+ return error instanceof Error ? error.message : String(error);
18
+ }
19
+ /**
20
+ * The platform upload type of one resource kind.
21
+ *
22
+ * @param kind - the resource kind of the element.
23
+ * @returns `image`, `voice`, `video` or `file`; the platform names audio `voice`.
24
+ */
25
+ export function mediaTypeOf(kind) {
26
+ switch (kind) {
27
+ case 'image':
28
+ return 'image';
29
+ case 'audio':
30
+ return 'voice';
31
+ case 'video':
32
+ return 'video';
33
+ case 'file':
34
+ return 'file';
35
+ }
36
+ }
37
+ /** File name of a source, for the multipart part of an upload. */
38
+ function fileNameOf(ref, fetchedName, mime) {
39
+ if (ref.meta.name !== undefined && ref.meta.name !== '')
40
+ return ref.meta.name;
41
+ if (fetchedName !== undefined && fetchedName !== '')
42
+ return fetchedName;
43
+ const subtype = mime?.split('/')[1]?.split(';')[0];
44
+ return `wecom-${ref.kind}${subtype === undefined ? '' : `.${subtype}`}`;
45
+ }
46
+ /**
47
+ * Upload one outbound attachment and return the `media_id` a send references.
48
+ *
49
+ * @param bot - the adapter whose credentials the upload uses.
50
+ * @param ref - the unresolved resource.
51
+ * @param ctx - fetch context of the send pipeline.
52
+ * @returns the platform media key, with the three-day expiry the core caches against.
53
+ * @throws PlatformError with an unknown outcome when the platform accepted the upload without returning an id.
54
+ */
55
+ export async function uploadMedia(bot, ref, ctx) {
56
+ const fetched = await ctx.fetch(ref.src, ctx.signal);
57
+ const mime = ref.meta.mime ?? fetched.mime;
58
+ const name = fileNameOf(ref, fetched.name, mime);
59
+ const type = mediaTypeOf(ref.kind);
60
+ const form = new FormData();
61
+ form.append('media', new Blob([fetched.data], mime === undefined ? {} : { type: mime }), name);
62
+ const answer = await bot.internal.mediaUpload({ type, media: form }, ctx.signal);
63
+ if (answer.media_id === undefined || answer.media_id === '') {
64
+ // The request reached the platform and it answered success, but no reusable key came back.
65
+ throw new PlatformError('invalid', 'wecom: /cgi-bin/media/upload answered without a media_id', { published: 'unknown' });
66
+ }
67
+ const createdAt = answer.created_at;
68
+ return {
69
+ key: answer.media_id,
70
+ ...(typeof createdAt === 'number' && Number.isFinite(createdAt)
71
+ ? { expiresAt: createdAt * 1_000 + MEDIA_LIFETIME_MS }
72
+ : {}),
73
+ extra: {
74
+ type,
75
+ name,
76
+ ...(mime === undefined ? {} : { mime }),
77
+ size: fetched.data.byteLength,
78
+ },
79
+ };
80
+ }
81
+ /**
82
+ * Serve the bytes of one inbound media object.
83
+ *
84
+ * A `media_id` the platform no longer accepts (it lives three days), a file above the 20 MB the plain download serves and
85
+ * a transport failure all answer `502`: the stored element keeps its label, but its bytes are gone.
86
+ *
87
+ * @param bot - the receiving adapter.
88
+ * @param mediaId - the `MediaId` the callback carried.
89
+ * @returns the bytes with their own headers, or the refusal status.
90
+ */
91
+ export async function serveMedia(bot, mediaId) {
92
+ let response;
93
+ try {
94
+ response = await bot.internal.mediaGet({ media_id: mediaId });
95
+ }
96
+ catch (error) {
97
+ bot.ctx.logger.warn('wecom: media %s could not be downloaded: %s', mediaId, messageOf(error));
98
+ return new Response(null, { status: 502 });
99
+ }
100
+ const contentType = response.headers.get('content-type') ?? '';
101
+ if (!response.ok || contentType.includes('application/json')) {
102
+ // A failure of this endpoint is still HTTP 200 with an `{ errcode }` envelope (40007 once the id expired).
103
+ bot.ctx.logger.warn('wecom: media %s answered %s: %s', mediaId, String(response.status), contentType.includes('application/json')
104
+ ? await response.text()
105
+ : contentType);
106
+ return new Response(null, { status: 502 });
107
+ }
108
+ const headers = new Headers();
109
+ if (contentType !== '')
110
+ headers.set('content-type', contentType);
111
+ const disposition = response.headers.get('content-disposition');
112
+ if (disposition !== null)
113
+ headers.set('content-disposition', disposition);
114
+ return new Response(response.body, { status: response.status, headers });
115
+ }
116
+ //# sourceMappingURL=media.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.js","sourceRoot":"","sources":["../../src/media.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAA;AASlE,yFAAyF;AACzF,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,KAAK,CAAA;AAEzD,mDAAmD;AACnD,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC/D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CACzB,IAAkB;IAElB,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,OAAO;YACV,OAAO,OAAO,CAAA;QAChB,KAAK,OAAO;YACV,OAAO,OAAO,CAAA;QAChB,KAAK,OAAO;YACV,OAAO,OAAO,CAAA;QAChB,KAAK,MAAM;YACT,OAAO,MAAM,CAAA;IACjB,CAAC;AACH,CAAC;AAED,kEAAkE;AAClE,SAAS,UAAU,CACjB,GAAgB,EAChB,WAA+B,EAC/B,IAAwB;IAExB,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,SAAS,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,KAA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C,CAAC;IACD,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAA;IAC9D,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,WAAW,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE,CAAC;QAC7D,2GAA2G;QAC3G,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CACjB,iCAAiC,EACjC,OAAO,EACP,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,EACvB,WAAW,CAAC,QAAQ,CAAC,kBAAkB,CAAC;YACtC,CAAC,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE;YACvB,CAAC,CAAC,WAAW,CAChB,CAAA;QACD,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAA;IAC5C,CAAC;IACD,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE,CAAA;IAC7B,IAAI,WAAW,KAAK,EAAE;QAAE,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,CAAC,CAAA;IAChE,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAA;IAC/D,IAAI,WAAW,KAAK,IAAI;QAAE,OAAO,CAAC,GAAG,CAAC,qBAAqB,EAAE,WAAW,CAAC,CAAA;IACzE,OAAO,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,CAAA;AAC1E,CAAC"}
@@ -0,0 +1,20 @@
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
+ import type { Mode } from '@deepseek-ai/cordis-plugin-im-core';
11
+ import type { Config } from '../config.ts';
12
+ import type { WecomModeTypes } from './shared.ts';
13
+ /**
14
+ * Build the `markdown` mode.
15
+ *
16
+ * @param config - the adapter configuration; it carries the numeric `AgentID` every request body repeats.
17
+ * @returns the single mode this adapter registers.
18
+ */
19
+ export declare function createMarkdownMode(config: Config): Mode<WecomModeTypes>;
20
+ //# sourceMappingURL=markdown.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdown.d.ts","sourceRoot":"","sources":["../../../src/modes/markdown.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,IAAI,EAAiB,MAAM,oCAAoC,CAAA;AAE7E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAQ1C,OAAO,KAAK,EAAkB,cAAc,EAAa,MAAM,aAAa,CAAA;AA8F5E;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,CA6IvE"}
@@ -0,0 +1,205 @@
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
+ import { ElementRegistry } from '@deepseek-ai/cordis-plugin-im-core';
11
+ import { assembleDraft, checkDraft, reportMovedMedia, serializeDraft, WECOM_LIMITS, } from "./shared.js";
12
+ /** How a `span[color]` value maps onto the three colours the platform paints. */
13
+ const FONT_COLOR = {
14
+ default: undefined,
15
+ muted: 'comment',
16
+ info: 'info',
17
+ success: 'info',
18
+ warning: 'warning',
19
+ danger: 'warning',
20
+ };
21
+ /** The text run of rendered children and the nodes that cannot ride inside it. */
22
+ function textRun(nodes) {
23
+ let text = '';
24
+ const rest = [];
25
+ for (const node of nodes) {
26
+ if (node.type === 'text')
27
+ text += node.text;
28
+ else
29
+ rest.push(node);
30
+ }
31
+ return { text, rest };
32
+ }
33
+ /** One inline mark around the rendered children, keeping any media of the subtree outside it. */
34
+ function marked(children, ctx, open, close = open) {
35
+ const run = textRun(ctx.render(children));
36
+ if (run.text === '')
37
+ return run.rest;
38
+ return [{ type: 'text', text: `${open}${run.text}${close}` }, ...run.rest];
39
+ }
40
+ /** One rendered line: the platform has no multiline construct, so embedded newlines become spaces. */
41
+ function oneLine(text) {
42
+ return text.replace(/\s*\n+\s*/g, ' ').trim();
43
+ }
44
+ /** One media message; a media element standing in phrasing content is reported as moved, not as degraded. */
45
+ function mediaNode(media, kind, el, ctx, src, meta) {
46
+ reportMovedMedia(el, ctx);
47
+ const name = meta.name !== undefined && meta.name !== '' ? meta.name : undefined;
48
+ return {
49
+ type: 'media',
50
+ media,
51
+ ref: ctx.resource(kind, src, meta),
52
+ ...(name === undefined ? {} : { name }),
53
+ };
54
+ }
55
+ /** The handler of one heading level: `#` repeated, then the text on a single line. */
56
+ function heading(level) {
57
+ return (el, ctx) => {
58
+ const run = textRun(ctx.render(el.children));
59
+ const text = oneLine(run.text);
60
+ if (text === '')
61
+ return run.rest;
62
+ // A heading has to start a line, and it ends without one so the next line follows directly below it.
63
+ return [
64
+ { type: 'text', text: `\n${'#'.repeat(level)} ${text}` },
65
+ ...run.rest,
66
+ ];
67
+ };
68
+ }
69
+ /** The handler of one list: its items are collected into a list node the assembler expands into lines. */
70
+ function list(ordered, el, ctx) {
71
+ return {
72
+ type: 'list',
73
+ ordered,
74
+ start: el.type === 'ol' ? (el.attrs.start ?? 1) : 1,
75
+ items: ctx.render(el.children),
76
+ };
77
+ }
78
+ /**
79
+ * Build the `markdown` mode.
80
+ *
81
+ * @param config - the adapter configuration; it carries the numeric `AgentID` every request body repeats.
82
+ * @returns the single mode this adapter registers.
83
+ */
84
+ export function createMarkdownMode(config) {
85
+ const elements = new ElementRegistry()
86
+ .register('text', (el) => ({ type: 'text', text: el.attrs.content }))
87
+ .register('br', () => ({ type: 'text', text: '\n' }))
88
+ // Paragraphs get a blank line between them; a paragraph that already ends on a newline is not padded twice.
89
+ .register('p', (el, ctx) => {
90
+ const nodes = ctx.render(el.children);
91
+ const run = textRun(nodes);
92
+ const out = [{ type: 'text', text: '\n' }, ...nodes];
93
+ if (!run.text.endsWith('\n'))
94
+ out.push({ type: 'text', text: '\n' });
95
+ return out;
96
+ })
97
+ .register('h1', heading(1))
98
+ .register('h2', heading(2))
99
+ .register('h3', heading(3))
100
+ .register('h4', heading(4))
101
+ .register('h5', heading(5))
102
+ .register('h6', heading(6))
103
+ .register('b', (el, ctx) => marked(el.children, ctx, '**'))
104
+ .register('code', (el, ctx) => {
105
+ // The platform documents no multiline inline code, so the newlines of the subtree become spaces.
106
+ const text = oneLine(ctx.text(el.children));
107
+ return text === '' ? [] : [{ type: 'text', text: `\`${text}\`` }];
108
+ })
109
+ .register('a', (el, ctx) => {
110
+ const run = textRun(ctx.render(el.children));
111
+ const label = run.text.trim() === '' ? el.attrs.href : run.text;
112
+ return [
113
+ { type: 'text', text: `[${label}](${el.attrs.href})` },
114
+ ...run.rest,
115
+ ];
116
+ })
117
+ .register('span', (el, ctx) => {
118
+ const color = FONT_COLOR[el.attrs.color ?? 'default'];
119
+ const run = textRun(ctx.render(el.children));
120
+ if (run.text === '')
121
+ return run.rest;
122
+ if (color === undefined)
123
+ return [{ type: 'text', text: run.text }, ...run.rest];
124
+ return [
125
+ { type: 'text', text: `<font color="${color}">${run.text}</font>` },
126
+ ...run.rest,
127
+ ];
128
+ }, { variants: ['color'] })
129
+ // Application messages have no mention mechanism: the text is shown and nobody is notified.
130
+ .register('at', (el) => ({
131
+ type: 'text',
132
+ text: `@${el.attrs.name ?? el.attrs.id ?? ''}`,
133
+ }), { variants: ['user'] })
134
+ .register('blockquote', (el, ctx) => {
135
+ const run = textRun(ctx.render(el.children));
136
+ // The paragraphs of the subtree end and start on newlines; a quote does not spell those as empty quoted lines.
137
+ const source = run.text.replace(/^\n+/, '').replace(/\n+$/, '');
138
+ if (source === '')
139
+ return run.rest;
140
+ const quoted = source
141
+ .split('\n')
142
+ .map((line) => `> ${line}`)
143
+ .join('\n');
144
+ return [{ type: 'text', text: quoted }, ...run.rest];
145
+ })
146
+ .register('ul', (el, ctx) => list(false, el, ctx))
147
+ .register('ol', (el, ctx) => list(true, el, ctx))
148
+ .register('li', (el, ctx) => ({
149
+ type: 'item',
150
+ nodes: ctx.render(el.children),
151
+ }))
152
+ .register('img', (el, ctx) => mediaNode('image', 'image', el, ctx, el.attrs.src, {}), { variants: ['inline'] })
153
+ .register('audio', (el, ctx) => mediaNode('voice', 'audio', el, ctx, el.attrs.src, {
154
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
155
+ ...(el.attrs.duration === undefined
156
+ ? {}
157
+ : { duration: el.attrs.duration }),
158
+ }))
159
+ .register('video', (el, ctx) => mediaNode('video', 'video', el, ctx, el.attrs.src, {
160
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
161
+ ...(el.attrs.duration === undefined
162
+ ? {}
163
+ : { duration: el.attrs.duration }),
164
+ }))
165
+ .register('file', (el, ctx) => mediaNode('file', 'file', el, ctx, el.attrs.src, {
166
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
167
+ ...(el.attrs.size === undefined ? {} : { size: el.attrs.size }),
168
+ }))
169
+ .register('button', (el, ctx) => {
170
+ const text = ctx.text(el.children).trim();
171
+ const attrs = el.attrs;
172
+ if (attrs.type === 'link') {
173
+ return {
174
+ type: 'link-button',
175
+ text: text === '' ? attrs.href : text,
176
+ href: attrs.href,
177
+ };
178
+ }
179
+ if (attrs.type === 'action' || attrs.type === 'submit') {
180
+ return {
181
+ type: 'button',
182
+ key: attrs.id,
183
+ text: text === '' ? attrs.id : text,
184
+ };
185
+ }
186
+ // Only `action` and `link` are declared, so the engine lowers an input button before this handler runs; the
187
+ // inline-code form keeps the command readable.
188
+ return { type: 'text', text: `\`${attrs.text}\`` };
189
+ }, { variants: ['action', 'link'] })
190
+ .envelope('title');
191
+ return {
192
+ id: 'markdown',
193
+ elements,
194
+ limits: {
195
+ 'limit.payload.bytes': WECOM_LIMITS.payloadBytes,
196
+ 'limit.delete.window': WECOM_LIMITS.deleteWindow,
197
+ 'limit.buttons.row': WECOM_LIMITS.buttonsRow,
198
+ 'limit.buttons.rows': WECOM_LIMITS.buttonRows,
199
+ },
200
+ assemble: (nodes, envelope, ctx) => assembleDraft(nodes, envelope, ctx),
201
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx, Number(config.agentId)),
202
+ check: (draft) => checkDraft(draft),
203
+ };
204
+ }
205
+ //# sourceMappingURL=markdown.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdown.js","sourceRoot":"","sources":["../../../src/modes/markdown.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAA;AAIpE,OAAO,EACL,aAAa,EACb,UAAU,EACV,gBAAgB,EAChB,cAAc,EACd,YAAY,GACb,MAAM,aAAa,CAAA;AAGpB,iFAAiF;AACjF,MAAM,UAAU,GAAuC;IACrD,OAAO,EAAE,SAAS;IAClB,KAAK,EAAE,SAAS;IAChB,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE,MAAM;IACf,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,SAAS;CAClB,CAAA;AAED,kFAAkF;AAClF,SAAS,OAAO,CAAC,KAA2B;IAI1C,IAAI,IAAI,GAAG,EAAE,CAAA;IACb,MAAM,IAAI,GAAgB,EAAE,CAAA;IAC5B,KAAK,MAAM,IAAI,IAAI,KAAK,E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E,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACvD,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC;KACpC,CAAA;AACH,CAAC"}
@@ -0,0 +1,227 @@
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
+ import type { Envelope, LimitViolation, ModeTypes, Prepared, RenderContext, ResourceRef, SerializeContext } from '@deepseek-ai/cordis-plugin-im-core';
10
+ import type { Element } from '@deepseek-ai/satori-element';
11
+ /** One node a handler produces. */
12
+ export type WecomNode = {
13
+ type: 'text';
14
+ text: string;
15
+ } | {
16
+ type: 'media';
17
+ media: WecomMediaKind;
18
+ ref: ResourceRef;
19
+ name?: string;
20
+ } | {
21
+ type: 'button';
22
+ key: string;
23
+ text: string;
24
+ } | {
25
+ type: 'link-button';
26
+ text: string;
27
+ href: string;
28
+ } | {
29
+ type: 'item';
30
+ nodes: WecomNode[];
31
+ } | {
32
+ type: 'list';
33
+ ordered: boolean;
34
+ start: number;
35
+ items: WecomNode[];
36
+ };
37
+ /** The four media `msgtype`s the platform accepts from an application. */
38
+ export type WecomMediaKind = 'image' | 'voice' | 'video' | 'file';
39
+ /** One button of the template card. */
40
+ export type WecomCardButton = {
41
+ text: string;
42
+ key: string;
43
+ } | {
44
+ text: string;
45
+ href: string;
46
+ };
47
+ /** One platform message, before resource resolution. */
48
+ export type WecomDraft = {
49
+ kind: 'markdown';
50
+ content: string;
51
+ } | {
52
+ kind: 'media';
53
+ media: WecomMediaKind;
54
+ ref: ResourceRef;
55
+ name?: string;
56
+ } | {
57
+ kind: 'card';
58
+ title: string;
59
+ taskId: string;
60
+ buttons: WecomCardButton[];
61
+ };
62
+ /** One entry of a `button_interaction` card's `button_list`. */
63
+ export interface TemplateCardButton {
64
+ text: string;
65
+ /** `1` for a jump button; a callback button omits it (`0`). */
66
+ type?: 1;
67
+ key?: string;
68
+ url?: string;
69
+ }
70
+ /** The `template_card` body of one card message. */
71
+ export interface TemplateCard {
72
+ card_type: 'button_interaction';
73
+ main_title: {
74
+ title: string;
75
+ };
76
+ button_list: TemplateCardButton[];
77
+ task_id: string;
78
+ }
79
+ /** Exact request body of one `message/send` call. */
80
+ export type WecomPayload = {
81
+ touser: string;
82
+ agentid: number;
83
+ msgtype: 'markdown';
84
+ markdown: {
85
+ content: string;
86
+ };
87
+ } | {
88
+ touser: string;
89
+ agentid: number;
90
+ msgtype: 'image';
91
+ image: {
92
+ media_id: string;
93
+ };
94
+ } | {
95
+ touser: string;
96
+ agentid: number;
97
+ msgtype: 'voice';
98
+ voice: {
99
+ media_id: string;
100
+ };
101
+ } | {
102
+ touser: string;
103
+ agentid: number;
104
+ msgtype: 'video';
105
+ video: {
106
+ media_id: string;
107
+ title?: string;
108
+ };
109
+ } | {
110
+ touser: string;
111
+ agentid: number;
112
+ msgtype: 'file';
113
+ file: {
114
+ media_id: string;
115
+ };
116
+ } | {
117
+ touser: string;
118
+ agentid: number;
119
+ msgtype: 'template_card';
120
+ template_card: TemplateCard;
121
+ };
122
+ /** Mode types of the `markdown` mode. */
123
+ export interface WecomModeTypes extends ModeTypes {
124
+ node: WecomNode;
125
+ draft: WecomDraft;
126
+ payload: WecomPayload;
127
+ }
128
+ /** The platform's documented bounds, and nothing else. */
129
+ export declare const WECOM_LIMITS: {
130
+ /** `text.content` and `markdown.content`: at most 2,048 bytes, counted as UTF-8. */
131
+ readonly payloadBytes: 2048;
132
+ /** `message/recall` accepts a message up to 24 hours after it was sent. */
133
+ readonly deleteWindow: number;
134
+ /** `button_list` of a `button_interaction` card holds at most six buttons. */
135
+ readonly buttonsRow: 6;
136
+ /** The card has one button row. */
137
+ readonly buttonRows: 1;
138
+ };
139
+ /** The word joiner a card title falls back to: the platform requires `main_title`, and content is never empty. */
140
+ export declare const CARD_TITLE_FALLBACK = "\u2060";
141
+ /**
142
+ * Pin the process-random segment of every `task_id`.
143
+ *
144
+ * The platform requires the id to be unique inside one application, so it is seeded from process entropy. A test that
145
+ * compares serialized request bodies pins the segment instead, so two runs produce the same payloads; the counter keeps
146
+ * advancing, because two cards of one run still must not share an id.
147
+ *
148
+ * @param salt - the segment to use: `0-9a-zA-Z_-`, at most 128 bytes together with the rest of the id.
149
+ */
150
+ export declare function pinTaskIdSalt(salt: string): void;
151
+ /**
152
+ * The `task_id` of one card.
153
+ *
154
+ * The platform requires the id to be unique within the application, so a counter alone would collide with the ids of the
155
+ * previous process after a restart; the random boot segment makes the pair unique across restarts.
156
+ *
157
+ * @returns an id the platform accepts: `0-9a-zA-Z_-` only, at most 128 bytes.
158
+ */
159
+ export declare function nextTaskId(): string;
160
+ /**
161
+ * Report inline media that moves out of its text run into a message of its own.
162
+ *
163
+ * @param el - the media element.
164
+ * @param ctx - the render context.
165
+ */
166
+ export declare function reportMovedMedia(el: Element, ctx: RenderContext<WecomModeTypes>): void;
167
+ /**
168
+ * Cut one line into pieces of at most `limit` bytes, never inside a surrogate pair.
169
+ *
170
+ * @param text - the line to cut.
171
+ * @param limit - the byte bound.
172
+ * @returns the pieces, in order; concatenating them reproduces the line.
173
+ */
174
+ export declare function hardCutBytes(text: string, limit: number): string[];
175
+ /**
176
+ * Cut a body into chunks the platform accepts.
177
+ *
178
+ * Lines are accumulated while they fit; a line that would overflow closes the current chunk, and a line longer than the
179
+ * bound is cut by bytes. A cut can land inside a formatting mark (`**`, `` ` ``), which the client then shows as literal
180
+ * characters: the platform documents no escape syntax that would avoid it.
181
+ *
182
+ * @param text - the body of one logical message.
183
+ * @param limit - the byte bound of one `markdown` message.
184
+ * @returns one or more chunks, in order; never empty.
185
+ */
186
+ export declare function splitMarkdownBytes(text: string, limit?: number): string[];
187
+ /**
188
+ * Expand list and item nodes into the flat node stream {@link assembleDraft} splits into messages.
189
+ *
190
+ * @param nodes - rendered nodes, in document order.
191
+ * @returns the same content with every list marker applied and media nodes kept in place.
192
+ */
193
+ export declare function flattenNodes(nodes: readonly WecomNode[]): WecomNode[];
194
+ /**
195
+ * Fold a node stream into platform messages.
196
+ *
197
+ * The text buffer is split by bytes and closed before every media element; the collected buttons become one card
198
+ * message after the body, and a seventh button onwards degrades to a `[label]` line in the body. The title of the
199
+ * 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
200
+ * never lost on a message without buttons.
201
+ *
202
+ * @param nodes - rendered nodes, in document order.
203
+ * @param envelope - the root `<title>`, if the content carried one.
204
+ * @param ctx - the render context, for the split and drop reports.
205
+ * @returns one draft per platform message, in send order; never empty.
206
+ */
207
+ export declare function assembleDraft(nodes: WecomNode[], envelope: Envelope, ctx: RenderContext<WecomModeTypes>): WecomDraft[];
208
+ /**
209
+ * Build the exact request body of one prepared draft.
210
+ *
211
+ * @param prepared - the draft with its resource keys resolved.
212
+ * @param ctx - the send context: the target chat names the `touser` recipient.
213
+ * @param agentId - the numeric `AgentID` every send carries.
214
+ * @returns the `message/send` body.
215
+ */
216
+ export declare function serializeDraft(prepared: Prepared<WecomDraft>, ctx: SerializeContext, agentId: number): WecomPayload;
217
+ /**
218
+ * Hard platform limits of one draft, checked before any request.
219
+ *
220
+ * Splitting already keeps the body inside the byte bound and the card inside the button bound; the checks stay as the
221
+ * only place the adapter refuses a draft the platform would answer `45002` for.
222
+ *
223
+ * @param draft - the assembled draft.
224
+ * @returns every violation the platform would refuse.
225
+ */
226
+ export declare function checkDraft(draft: WecomDraft): LimitViolation[];
227
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../../src/modes/shared.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,KAAK,EACV,QAAQ,EAC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