@openclaw/feishu 2026.5.2 → 2026.5.3-beta.2

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 (224) hide show
  1. package/dist/accounts-Ba3-WP1z.js +423 -0
  2. package/dist/api.js +2280 -0
  3. package/dist/app-registration-B8qc1MCM.js +184 -0
  4. package/dist/audio-preflight.runtime-BPlzkO3l.js +7 -0
  5. package/dist/card-interaction-BfRLgvw_.js +96 -0
  6. package/dist/channel-CSD_Jt8I.js +1668 -0
  7. package/dist/channel-entry.js +22 -0
  8. package/dist/channel-plugin-api.js +2 -0
  9. package/dist/channel.runtime-DYsXcD36.js +700 -0
  10. package/dist/client-DBVoQL5w.js +157 -0
  11. package/dist/contract-api.js +9 -0
  12. package/dist/conversation-id-DWS3Ep2A.js +139 -0
  13. package/dist/directory.static-f3EeoRJd.js +44 -0
  14. package/dist/drive-C5eJLJr7.js +883 -0
  15. package/dist/index.js +68 -0
  16. package/dist/monitor-CT189QfR.js +60 -0
  17. package/dist/monitor.account-dJV2jO8C.js +4990 -0
  18. package/dist/monitor.state-DYM02ipp.js +100 -0
  19. package/dist/policy-D6c-wMPl.js +118 -0
  20. package/dist/probe-BNzzU_uR.js +149 -0
  21. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  22. package/dist/runtime-CG0DuRCy.js +8 -0
  23. package/dist/runtime-api.js +14 -0
  24. package/dist/secret-contract-Dm4Z_zQN.js +119 -0
  25. package/dist/secret-contract-api.js +2 -0
  26. package/dist/security-audit-DqJdocrN.js +11 -0
  27. package/dist/security-audit-shared-ByuMx9cJ.js +38 -0
  28. package/dist/security-contract-api.js +2 -0
  29. package/dist/send-DowxxbpH.js +1218 -0
  30. package/dist/session-conversation-B4nrW-vo.js +27 -0
  31. package/dist/session-key-api.js +2 -0
  32. package/dist/setup-api.js +2 -0
  33. package/dist/setup-entry.js +15 -0
  34. package/dist/subagent-hooks-C3UhPVLV.js +227 -0
  35. package/dist/subagent-hooks-api.js +23 -0
  36. package/dist/targets-JMFJRKSe.js +48 -0
  37. package/dist/thread-bindings-BmS6TLes.js +222 -0
  38. package/package.json +15 -6
  39. package/api.ts +0 -31
  40. package/channel-entry.ts +0 -20
  41. package/channel-plugin-api.ts +0 -1
  42. package/contract-api.ts +0 -16
  43. package/index.ts +0 -82
  44. package/runtime-api.ts +0 -55
  45. package/secret-contract-api.ts +0 -5
  46. package/security-contract-api.ts +0 -1
  47. package/session-key-api.ts +0 -1
  48. package/setup-api.ts +0 -3
  49. package/setup-entry.test.ts +0 -14
  50. package/setup-entry.ts +0 -13
  51. package/src/accounts.test.ts +0 -459
  52. package/src/accounts.ts +0 -326
  53. package/src/app-registration.ts +0 -331
  54. package/src/approval-auth.test.ts +0 -24
  55. package/src/approval-auth.ts +0 -25
  56. package/src/async.test.ts +0 -35
  57. package/src/async.ts +0 -104
  58. package/src/audio-preflight.runtime.ts +0 -9
  59. package/src/bitable.test.ts +0 -131
  60. package/src/bitable.ts +0 -762
  61. package/src/bot-content.ts +0 -474
  62. package/src/bot-group-name.test.ts +0 -108
  63. package/src/bot-runtime-api.ts +0 -12
  64. package/src/bot-sender-name.ts +0 -125
  65. package/src/bot.broadcast.test.ts +0 -463
  66. package/src/bot.card-action.test.ts +0 -577
  67. package/src/bot.checkBotMentioned.test.ts +0 -265
  68. package/src/bot.helpers.test.ts +0 -118
  69. package/src/bot.stripBotMention.test.ts +0 -126
  70. package/src/bot.test.ts +0 -3040
  71. package/src/bot.ts +0 -1559
  72. package/src/card-action.ts +0 -447
  73. package/src/card-interaction.test.ts +0 -129
  74. package/src/card-interaction.ts +0 -159
  75. package/src/card-test-helpers.ts +0 -47
  76. package/src/card-ux-approval.ts +0 -65
  77. package/src/card-ux-launcher.test.ts +0 -99
  78. package/src/card-ux-launcher.ts +0 -121
  79. package/src/card-ux-shared.ts +0 -33
  80. package/src/channel-runtime-api.ts +0 -16
  81. package/src/channel.runtime.ts +0 -47
  82. package/src/channel.test.ts +0 -959
  83. package/src/channel.ts +0 -1313
  84. package/src/chat-schema.ts +0 -25
  85. package/src/chat.test.ts +0 -196
  86. package/src/chat.ts +0 -188
  87. package/src/client.test.ts +0 -433
  88. package/src/client.ts +0 -290
  89. package/src/comment-dispatcher-runtime-api.ts +0 -6
  90. package/src/comment-dispatcher.test.ts +0 -169
  91. package/src/comment-dispatcher.ts +0 -107
  92. package/src/comment-handler-runtime-api.ts +0 -3
  93. package/src/comment-handler.test.ts +0 -486
  94. package/src/comment-handler.ts +0 -309
  95. package/src/comment-reaction.test.ts +0 -166
  96. package/src/comment-reaction.ts +0 -259
  97. package/src/comment-shared.test.ts +0 -182
  98. package/src/comment-shared.ts +0 -406
  99. package/src/comment-target.ts +0 -44
  100. package/src/config-schema.test.ts +0 -309
  101. package/src/config-schema.ts +0 -333
  102. package/src/conversation-id.test.ts +0 -18
  103. package/src/conversation-id.ts +0 -199
  104. package/src/dedup-runtime-api.ts +0 -1
  105. package/src/dedup.ts +0 -141
  106. package/src/directory.static.ts +0 -61
  107. package/src/directory.test.ts +0 -136
  108. package/src/directory.ts +0 -124
  109. package/src/doc-schema.ts +0 -182
  110. package/src/docx-batch-insert.test.ts +0 -91
  111. package/src/docx-batch-insert.ts +0 -223
  112. package/src/docx-color-text.ts +0 -154
  113. package/src/docx-table-ops.test.ts +0 -53
  114. package/src/docx-table-ops.ts +0 -316
  115. package/src/docx-types.ts +0 -38
  116. package/src/docx.account-selection.test.ts +0 -79
  117. package/src/docx.test.ts +0 -685
  118. package/src/docx.ts +0 -1616
  119. package/src/drive-schema.ts +0 -92
  120. package/src/drive.test.ts +0 -1219
  121. package/src/drive.ts +0 -829
  122. package/src/dynamic-agent.ts +0 -137
  123. package/src/event-types.ts +0 -45
  124. package/src/external-keys.test.ts +0 -20
  125. package/src/external-keys.ts +0 -19
  126. package/src/lifecycle.test-support.ts +0 -220
  127. package/src/media.test.ts +0 -900
  128. package/src/media.ts +0 -861
  129. package/src/mention-target.types.ts +0 -5
  130. package/src/mention.ts +0 -114
  131. package/src/message-action-contract.ts +0 -13
  132. package/src/monitor-state-runtime-api.ts +0 -7
  133. package/src/monitor-transport-runtime-api.ts +0 -7
  134. package/src/monitor.account.ts +0 -468
  135. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +0 -219
  136. package/src/monitor.bot-identity.ts +0 -86
  137. package/src/monitor.bot-menu-handler.ts +0 -165
  138. package/src/monitor.bot-menu.lifecycle.test-support.ts +0 -224
  139. package/src/monitor.bot-menu.test.ts +0 -178
  140. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +0 -264
  141. package/src/monitor.card-action.lifecycle.test-support.ts +0 -373
  142. package/src/monitor.cleanup.test.ts +0 -376
  143. package/src/monitor.comment-notice-handler.ts +0 -105
  144. package/src/monitor.comment.test.ts +0 -937
  145. package/src/monitor.comment.ts +0 -1386
  146. package/src/monitor.lifecycle.test.ts +0 -4
  147. package/src/monitor.message-handler.ts +0 -339
  148. package/src/monitor.reaction.lifecycle.test-support.ts +0 -68
  149. package/src/monitor.reaction.test.ts +0 -713
  150. package/src/monitor.startup.test.ts +0 -192
  151. package/src/monitor.startup.ts +0 -74
  152. package/src/monitor.state.defaults.test.ts +0 -46
  153. package/src/monitor.state.ts +0 -170
  154. package/src/monitor.synthetic-error.ts +0 -18
  155. package/src/monitor.test-mocks.ts +0 -45
  156. package/src/monitor.transport.ts +0 -424
  157. package/src/monitor.ts +0 -100
  158. package/src/monitor.webhook-e2e.test.ts +0 -272
  159. package/src/monitor.webhook-security.test.ts +0 -264
  160. package/src/monitor.webhook.test-helpers.ts +0 -116
  161. package/src/outbound-runtime-api.ts +0 -1
  162. package/src/outbound.test.ts +0 -935
  163. package/src/outbound.ts +0 -718
  164. package/src/perm-schema.ts +0 -52
  165. package/src/perm.ts +0 -170
  166. package/src/pins.ts +0 -108
  167. package/src/policy.test.ts +0 -334
  168. package/src/policy.ts +0 -236
  169. package/src/post.test.ts +0 -105
  170. package/src/post.ts +0 -275
  171. package/src/probe.test.ts +0 -275
  172. package/src/probe.ts +0 -166
  173. package/src/processing-claims.ts +0 -59
  174. package/src/qr-terminal.ts +0 -1
  175. package/src/reactions.ts +0 -123
  176. package/src/reasoning-preview.test.ts +0 -59
  177. package/src/reasoning-preview.ts +0 -20
  178. package/src/reply-dispatcher-runtime-api.ts +0 -7
  179. package/src/reply-dispatcher.test.ts +0 -1144
  180. package/src/reply-dispatcher.ts +0 -650
  181. package/src/runtime.ts +0 -9
  182. package/src/secret-contract.ts +0 -145
  183. package/src/secret-input.ts +0 -1
  184. package/src/security-audit-shared.ts +0 -69
  185. package/src/security-audit.test.ts +0 -61
  186. package/src/security-audit.ts +0 -1
  187. package/src/send-result.ts +0 -29
  188. package/src/send-target.test.ts +0 -80
  189. package/src/send-target.ts +0 -35
  190. package/src/send.reply-fallback.test.ts +0 -292
  191. package/src/send.test.ts +0 -550
  192. package/src/send.ts +0 -800
  193. package/src/sequential-key.test.ts +0 -72
  194. package/src/sequential-key.ts +0 -28
  195. package/src/sequential-queue.test.ts +0 -92
  196. package/src/sequential-queue.ts +0 -16
  197. package/src/session-conversation.ts +0 -42
  198. package/src/session-route.ts +0 -48
  199. package/src/setup-core.ts +0 -51
  200. package/src/setup-surface.test.ts +0 -174
  201. package/src/setup-surface.ts +0 -581
  202. package/src/streaming-card.test.ts +0 -190
  203. package/src/streaming-card.ts +0 -490
  204. package/src/subagent-hooks.test.ts +0 -603
  205. package/src/subagent-hooks.ts +0 -397
  206. package/src/targets.ts +0 -97
  207. package/src/test-support/lifecycle-test-support.ts +0 -453
  208. package/src/thread-bindings.test.ts +0 -143
  209. package/src/thread-bindings.ts +0 -330
  210. package/src/tool-account-routing.test.ts +0 -187
  211. package/src/tool-account.test.ts +0 -44
  212. package/src/tool-account.ts +0 -93
  213. package/src/tool-factory-test-harness.ts +0 -79
  214. package/src/tool-result.test.ts +0 -32
  215. package/src/tool-result.ts +0 -16
  216. package/src/tools-config.test.ts +0 -21
  217. package/src/tools-config.ts +0 -22
  218. package/src/types.ts +0 -104
  219. package/src/typing.test.ts +0 -144
  220. package/src/typing.ts +0 -214
  221. package/src/wiki-schema.ts +0 -55
  222. package/src/wiki.ts +0 -227
  223. package/subagent-hooks-api.ts +0 -31
  224. package/tsconfig.json +0 -16
package/src/policy.ts DELETED
@@ -1,236 +0,0 @@
1
- import {
2
- normalizeAccountId,
3
- resolveMergedAccountConfig,
4
- } from "openclaw/plugin-sdk/account-resolution";
5
- import type { OpenClawConfig } from "openclaw/plugin-sdk/core";
6
- import { evaluateSenderGroupAccessForPolicy } from "openclaw/plugin-sdk/group-access";
7
- import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/text-runtime";
8
- import type { AllowlistMatch, ChannelGroupContext } from "../runtime-api.js";
9
- import { detectIdType } from "./targets.js";
10
- import type { FeishuConfig } from "./types.js";
11
-
12
- type FeishuAllowlistMatch = AllowlistMatch<"wildcard" | "id">;
13
-
14
- const FEISHU_PROVIDER_PREFIX_RE = /^(feishu|lark):/i;
15
-
16
- function stripRepeatedFeishuProviderPrefixes(raw: string): string {
17
- let normalized = raw.trim();
18
- while (FEISHU_PROVIDER_PREFIX_RE.test(normalized)) {
19
- normalized = normalized.replace(FEISHU_PROVIDER_PREFIX_RE, "").trim();
20
- }
21
- return normalized;
22
- }
23
-
24
- function canonicalizeFeishuAllowlistKey(params: { kind: "chat" | "user"; value: string }): string {
25
- const value = params.value.trim();
26
- if (!value) {
27
- return "";
28
- }
29
- // A typed wildcard (`chat:*`, `user:*`, `open_id:*`, `dm:*`, `group:*`,
30
- // `channel:*`) collapses to the bare wildcard so it keeps matching across
31
- // both kinds, preserving the prior `normalizeFeishuTarget`-based behavior.
32
- if (value === "*") {
33
- return "*";
34
- }
35
- return `${params.kind}:${value}`;
36
- }
37
-
38
- function normalizeFeishuAllowEntry(raw: string): string {
39
- const trimmed = raw.trim();
40
- if (!trimmed) {
41
- return "";
42
- }
43
- if (trimmed === "*") {
44
- return "*";
45
- }
46
-
47
- const withoutProviderPrefix = stripRepeatedFeishuProviderPrefixes(trimmed);
48
- if (withoutProviderPrefix === "*") {
49
- return "*";
50
- }
51
- const lowered = normalizeOptionalLowercaseString(withoutProviderPrefix) ?? "";
52
- if (!lowered) {
53
- return "";
54
- }
55
- // Lowercase for prefix detection only; preserve the original ID casing in the
56
- // canonicalized key. Sender candidates pass through this same path so allowlist
57
- // entries and runtime IDs stay normalized symmetrically.
58
- if (
59
- lowered.startsWith("chat:") ||
60
- lowered.startsWith("group:") ||
61
- lowered.startsWith("channel:")
62
- ) {
63
- return canonicalizeFeishuAllowlistKey({
64
- kind: "chat",
65
- value: withoutProviderPrefix.slice(withoutProviderPrefix.indexOf(":") + 1),
66
- });
67
- }
68
- if (lowered.startsWith("user:") || lowered.startsWith("dm:")) {
69
- return canonicalizeFeishuAllowlistKey({
70
- kind: "user",
71
- value: withoutProviderPrefix.slice(withoutProviderPrefix.indexOf(":") + 1),
72
- });
73
- }
74
- if (lowered.startsWith("open_id:")) {
75
- return canonicalizeFeishuAllowlistKey({
76
- kind: "user",
77
- value: withoutProviderPrefix.slice(withoutProviderPrefix.indexOf(":") + 1),
78
- });
79
- }
80
-
81
- const detectedType = detectIdType(withoutProviderPrefix);
82
- if (detectedType === "chat_id") {
83
- return canonicalizeFeishuAllowlistKey({
84
- kind: "chat",
85
- value: withoutProviderPrefix,
86
- });
87
- }
88
- if (detectedType === "open_id" || detectedType === "user_id") {
89
- return canonicalizeFeishuAllowlistKey({
90
- kind: "user",
91
- value: withoutProviderPrefix,
92
- });
93
- }
94
-
95
- return "";
96
- }
97
-
98
- export function resolveFeishuAllowlistMatch(params: {
99
- allowFrom: Array<string | number>;
100
- senderId: string;
101
- senderIds?: Array<string | null | undefined>;
102
- senderName?: string | null;
103
- }): FeishuAllowlistMatch {
104
- const allowFrom = params.allowFrom
105
- .map((entry) => normalizeFeishuAllowEntry(String(entry)))
106
- .filter(Boolean);
107
- if (allowFrom.length === 0) {
108
- return { allowed: false };
109
- }
110
- if (allowFrom.includes("*")) {
111
- return { allowed: true, matchKey: "*", matchSource: "wildcard" };
112
- }
113
-
114
- // Feishu allowlists are ID-based; mutable display names must never grant access.
115
- const senderCandidates = [params.senderId, ...(params.senderIds ?? [])]
116
- .map((entry) => normalizeFeishuAllowEntry(entry ?? ""))
117
- .filter(Boolean);
118
-
119
- for (const senderId of senderCandidates) {
120
- if (allowFrom.includes(senderId)) {
121
- return { allowed: true, matchKey: senderId, matchSource: "id" };
122
- }
123
- }
124
-
125
- return { allowed: false };
126
- }
127
-
128
- export function resolveFeishuGroupConfig(params: { cfg?: FeishuConfig; groupId?: string | null }) {
129
- const groups = params.cfg?.groups ?? {};
130
- const wildcard = groups["*"];
131
- const groupId = params.groupId?.trim();
132
- if (!groupId) {
133
- return undefined;
134
- }
135
-
136
- const direct = groups[groupId];
137
- if (direct) {
138
- return direct;
139
- }
140
-
141
- const lowered = normalizeOptionalLowercaseString(groupId) ?? "";
142
- const matchKey = Object.keys(groups).find(
143
- (key) => normalizeOptionalLowercaseString(key) === lowered,
144
- );
145
- if (matchKey) {
146
- return groups[matchKey];
147
- }
148
- return wildcard;
149
- }
150
-
151
- export function hasExplicitFeishuGroupConfig(params: {
152
- cfg?: FeishuConfig;
153
- groupId?: string | null;
154
- }): boolean {
155
- const groups = params.cfg?.groups ?? {};
156
- const groupId = params.groupId?.trim();
157
- if (!groupId) {
158
- return false;
159
- }
160
- if (Object.prototype.hasOwnProperty.call(groups, groupId) && groupId !== "*") {
161
- return true;
162
- }
163
-
164
- const lowered = normalizeOptionalLowercaseString(groupId) ?? "";
165
- return Object.keys(groups).some(
166
- (key) => key !== "*" && normalizeOptionalLowercaseString(key) === lowered,
167
- );
168
- }
169
-
170
- export function resolveFeishuGroupToolPolicy(params: ChannelGroupContext) {
171
- const cfg = params.cfg.channels?.feishu;
172
- if (!cfg) {
173
- return undefined;
174
- }
175
-
176
- const groupConfig = resolveFeishuGroupConfig({
177
- cfg,
178
- groupId: params.groupId,
179
- });
180
-
181
- return groupConfig?.tools;
182
- }
183
-
184
- export function isFeishuGroupAllowed(params: {
185
- groupPolicy: "open" | "allowlist" | "disabled" | "allowall";
186
- allowFrom: Array<string | number>;
187
- senderId: string;
188
- senderIds?: Array<string | null | undefined>;
189
- senderName?: string | null;
190
- }): boolean {
191
- return evaluateSenderGroupAccessForPolicy({
192
- groupPolicy: params.groupPolicy === "allowall" ? "open" : params.groupPolicy,
193
- groupAllowFrom: params.allowFrom.map((entry) => String(entry)),
194
- senderId: params.senderId,
195
- isSenderAllowed: () => resolveFeishuAllowlistMatch(params).allowed,
196
- }).allowed;
197
- }
198
-
199
- export function resolveFeishuReplyPolicy(params: {
200
- isDirectMessage: boolean;
201
- cfg: OpenClawConfig;
202
- accountId?: string | null;
203
- groupId?: string | null;
204
- /**
205
- * Effective group policy resolved for this chat. When "open", requireMention
206
- * defaults to false so that non-text messages (e.g. images) that cannot carry
207
- * @-mentions are still delivered to the agent.
208
- */
209
- groupPolicy?: "open" | "allowlist" | "disabled" | "allowall";
210
- }): { requireMention: boolean } {
211
- if (params.isDirectMessage) {
212
- return { requireMention: false };
213
- }
214
-
215
- const feishuCfg = params.cfg.channels?.feishu;
216
- const resolvedCfg = resolveMergedAccountConfig<FeishuConfig>({
217
- channelConfig: feishuCfg,
218
- accounts: feishuCfg?.accounts as Record<string, Partial<FeishuConfig>> | undefined,
219
- accountId: normalizeAccountId(params.accountId),
220
- normalizeAccountId,
221
- omitKeys: ["defaultAccount"],
222
- });
223
- const groupRequireMention = resolveFeishuGroupConfig({
224
- cfg: resolvedCfg,
225
- groupId: params.groupId,
226
- })?.requireMention;
227
-
228
- return {
229
- requireMention:
230
- typeof groupRequireMention === "boolean"
231
- ? groupRequireMention
232
- : typeof resolvedCfg.requireMention === "boolean"
233
- ? resolvedCfg.requireMention
234
- : params.groupPolicy !== "open",
235
- };
236
- }
package/src/post.test.ts DELETED
@@ -1,105 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { parsePostContent } from "./post.js";
3
-
4
- describe("parsePostContent", () => {
5
- it("renders title and styled text as markdown", () => {
6
- const content = JSON.stringify({
7
- title: "Daily *Plan*",
8
- content: [
9
- [
10
- { tag: "text", text: "Bold", style: { bold: true } },
11
- { tag: "text", text: " " },
12
- { tag: "text", text: "Italic", style: { italic: true } },
13
- { tag: "text", text: " " },
14
- { tag: "text", text: "Underline", style: { underline: true } },
15
- { tag: "text", text: " " },
16
- { tag: "text", text: "Strike", style: { strikethrough: true } },
17
- { tag: "text", text: " " },
18
- { tag: "text", text: "Code", style: { code: true, bold: true } },
19
- ],
20
- ],
21
- });
22
-
23
- const result = parsePostContent(content);
24
-
25
- expect(result.textContent).toBe(
26
- "Daily \\*Plan\\*\n\n**Bold** *Italic* <u>Underline</u> ~~Strike~~ `Code`",
27
- );
28
- expect(result.imageKeys).toEqual([]);
29
- expect(result.mentionedOpenIds).toEqual([]);
30
- });
31
-
32
- it("renders links and mentions", () => {
33
- const content = JSON.stringify({
34
- title: "",
35
- content: [
36
- [
37
- { tag: "a", text: "Docs [v2]", href: "https://example.com/guide(a)" },
38
- { tag: "text", text: " " },
39
- { tag: "at", user_name: "alice_bob" },
40
- { tag: "text", text: " " },
41
- { tag: "at", open_id: "ou_123" },
42
- { tag: "text", text: " " },
43
- { tag: "a", href: "https://example.com/no-text" },
44
- ],
45
- ],
46
- });
47
-
48
- const result = parsePostContent(content);
49
-
50
- expect(result.textContent).toBe(
51
- "[Docs \\[v2\\]](https://example.com/guide(a)) @alice\\_bob @ou\\_123 [https://example.com/no\\-text](https://example.com/no-text)",
52
- );
53
- expect(result.mentionedOpenIds).toEqual(["ou_123"]);
54
- });
55
-
56
- it("inserts image placeholders and collects image keys", () => {
57
- const content = JSON.stringify({
58
- title: "",
59
- content: [
60
- [
61
- { tag: "text", text: "Before " },
62
- { tag: "img", image_key: "img_1" },
63
- { tag: "text", text: " after" },
64
- ],
65
- [{ tag: "img", image_key: "img_2" }],
66
- ],
67
- });
68
-
69
- const result = parsePostContent(content);
70
-
71
- expect(result.textContent).toBe("Before ![image] after\n![image]");
72
- expect(result.imageKeys).toEqual(["img_1", "img_2"]);
73
- expect(result.mentionedOpenIds).toEqual([]);
74
- });
75
-
76
- it("supports locale wrappers", () => {
77
- const wrappedByPost = JSON.stringify({
78
- post: {
79
- zh_cn: {
80
- title: "标题",
81
- content: [[{ tag: "text", text: "内容A" }]],
82
- },
83
- },
84
- });
85
- const wrappedByLocale = JSON.stringify({
86
- zh_cn: {
87
- title: "标题",
88
- content: [[{ tag: "text", text: "内容B" }]],
89
- },
90
- });
91
-
92
- expect(parsePostContent(wrappedByPost)).toEqual({
93
- textContent: "标题\n\n内容A",
94
- imageKeys: [],
95
- mediaKeys: [],
96
- mentionedOpenIds: [],
97
- });
98
- expect(parsePostContent(wrappedByLocale)).toEqual({
99
- textContent: "标题\n\n内容B",
100
- imageKeys: [],
101
- mediaKeys: [],
102
- mentionedOpenIds: [],
103
- });
104
- });
105
- });
package/src/post.ts DELETED
@@ -1,275 +0,0 @@
1
- import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/text-runtime";
2
- import { isRecord } from "./comment-shared.js";
3
- import { normalizeFeishuExternalKey } from "./external-keys.js";
4
-
5
- const FALLBACK_POST_TEXT = "[Rich text message]";
6
- const MARKDOWN_SPECIAL_CHARS = /([\\`*_{}[\]()#+\-!|>~])/g;
7
-
8
- type PostParseResult = {
9
- textContent: string;
10
- imageKeys: string[];
11
- mediaKeys: Array<{ fileKey: string; fileName?: string }>;
12
- mentionedOpenIds: string[];
13
- };
14
-
15
- type PostPayload = {
16
- title: string;
17
- content: unknown[];
18
- };
19
-
20
- function toStringOrEmpty(value: unknown): string {
21
- return typeof value === "string" ? value : "";
22
- }
23
-
24
- function escapeMarkdownText(text: string): string {
25
- return text.replace(MARKDOWN_SPECIAL_CHARS, "\\$1");
26
- }
27
-
28
- function toBoolean(value: unknown): boolean {
29
- return value === true || value === 1 || value === "true";
30
- }
31
-
32
- function isStyleEnabled(style: Record<string, unknown> | undefined, key: string): boolean {
33
- if (!style) {
34
- return false;
35
- }
36
- return toBoolean(style[key]);
37
- }
38
-
39
- function wrapInlineCode(text: string): string {
40
- const maxRun = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
41
- const fence = "`".repeat(maxRun + 1);
42
- const needsPadding = text.startsWith("`") || text.endsWith("`");
43
- const body = needsPadding ? ` ${text} ` : text;
44
- return `${fence}${body}${fence}`;
45
- }
46
-
47
- function sanitizeFenceLanguage(language: string): string {
48
- return language.trim().replace(/[^A-Za-z0-9_+#.-]/g, "");
49
- }
50
-
51
- function renderTextElement(element: Record<string, unknown>): string {
52
- const text = toStringOrEmpty(element.text);
53
- const style = isRecord(element.style) ? element.style : undefined;
54
-
55
- if (isStyleEnabled(style, "code")) {
56
- return wrapInlineCode(text);
57
- }
58
-
59
- let rendered = escapeMarkdownText(text);
60
- if (!rendered) {
61
- return "";
62
- }
63
-
64
- if (isStyleEnabled(style, "bold")) {
65
- rendered = `**${rendered}**`;
66
- }
67
- if (isStyleEnabled(style, "italic")) {
68
- rendered = `*${rendered}*`;
69
- }
70
- if (isStyleEnabled(style, "underline")) {
71
- rendered = `<u>${rendered}</u>`;
72
- }
73
- if (
74
- isStyleEnabled(style, "strikethrough") ||
75
- isStyleEnabled(style, "line_through") ||
76
- isStyleEnabled(style, "lineThrough")
77
- ) {
78
- rendered = `~~${rendered}~~`;
79
- }
80
- return rendered;
81
- }
82
-
83
- function renderLinkElement(element: Record<string, unknown>): string {
84
- const href = toStringOrEmpty(element.href).trim();
85
- const rawText = toStringOrEmpty(element.text);
86
- const text = rawText || href;
87
- if (!text) {
88
- return "";
89
- }
90
- if (!href) {
91
- return escapeMarkdownText(text);
92
- }
93
- return `[${escapeMarkdownText(text)}](${href})`;
94
- }
95
-
96
- function renderMentionElement(element: Record<string, unknown>): string {
97
- const mention =
98
- toStringOrEmpty(element.user_name) ||
99
- toStringOrEmpty(element.user_id) ||
100
- toStringOrEmpty(element.open_id);
101
- if (!mention) {
102
- return "";
103
- }
104
- return `@${escapeMarkdownText(mention)}`;
105
- }
106
-
107
- function renderEmotionElement(element: Record<string, unknown>): string {
108
- const text =
109
- toStringOrEmpty(element.emoji) ||
110
- toStringOrEmpty(element.text) ||
111
- toStringOrEmpty(element.emoji_type);
112
- return escapeMarkdownText(text);
113
- }
114
-
115
- function renderCodeBlockElement(element: Record<string, unknown>): string {
116
- const language = sanitizeFenceLanguage(
117
- toStringOrEmpty(element.language) || toStringOrEmpty(element.lang),
118
- );
119
- const code = (toStringOrEmpty(element.text) || toStringOrEmpty(element.content)).replace(
120
- /\r\n/g,
121
- "\n",
122
- );
123
- const trailingNewline = code.endsWith("\n") ? "" : "\n";
124
- return `\`\`\`${language}\n${code}${trailingNewline}\`\`\``;
125
- }
126
-
127
- function renderElement(
128
- element: unknown,
129
- imageKeys: string[],
130
- mediaKeys: Array<{ fileKey: string; fileName?: string }>,
131
- mentionedOpenIds: string[],
132
- ): string {
133
- if (!isRecord(element)) {
134
- return escapeMarkdownText(toStringOrEmpty(element));
135
- }
136
-
137
- const tag = normalizeLowercaseStringOrEmpty(toStringOrEmpty(element.tag));
138
- switch (tag) {
139
- case "text":
140
- return renderTextElement(element);
141
- case "a":
142
- return renderLinkElement(element);
143
- case "at":
144
- {
145
- const mentioned = toStringOrEmpty(element.open_id) || toStringOrEmpty(element.user_id);
146
- const normalizedMention = normalizeFeishuExternalKey(mentioned);
147
- if (normalizedMention) {
148
- mentionedOpenIds.push(normalizedMention);
149
- }
150
- }
151
- return renderMentionElement(element);
152
- case "img": {
153
- const imageKey = normalizeFeishuExternalKey(toStringOrEmpty(element.image_key));
154
- if (imageKey) {
155
- imageKeys.push(imageKey);
156
- }
157
- return "![image]";
158
- }
159
- case "media": {
160
- const fileKey = normalizeFeishuExternalKey(toStringOrEmpty(element.file_key));
161
- if (fileKey) {
162
- const fileName = toStringOrEmpty(element.file_name) || undefined;
163
- mediaKeys.push({ fileKey, fileName });
164
- }
165
- return "[media]";
166
- }
167
- case "emotion":
168
- return renderEmotionElement(element);
169
- case "md":
170
- case "lark_md":
171
- return toStringOrEmpty(element.text) || toStringOrEmpty(element.content);
172
- case "br":
173
- return "\n";
174
- case "hr":
175
- return "\n\n---\n\n";
176
- case "code": {
177
- const code = toStringOrEmpty(element.text) || toStringOrEmpty(element.content);
178
- return code ? wrapInlineCode(code) : "";
179
- }
180
- case "code_block":
181
- case "pre":
182
- return renderCodeBlockElement(element);
183
- default:
184
- return escapeMarkdownText(toStringOrEmpty(element.text));
185
- }
186
- }
187
-
188
- function toPostPayload(candidate: unknown): PostPayload | null {
189
- if (!isRecord(candidate) || !Array.isArray(candidate.content)) {
190
- return null;
191
- }
192
- return {
193
- title: toStringOrEmpty(candidate.title),
194
- content: candidate.content,
195
- };
196
- }
197
-
198
- function resolveLocalePayload(candidate: unknown): PostPayload | null {
199
- const direct = toPostPayload(candidate);
200
- if (direct) {
201
- return direct;
202
- }
203
- if (!isRecord(candidate)) {
204
- return null;
205
- }
206
- for (const value of Object.values(candidate)) {
207
- const localePayload = toPostPayload(value);
208
- if (localePayload) {
209
- return localePayload;
210
- }
211
- }
212
- return null;
213
- }
214
-
215
- function resolvePostPayload(parsed: unknown): PostPayload | null {
216
- const direct = toPostPayload(parsed);
217
- if (direct) {
218
- return direct;
219
- }
220
-
221
- if (!isRecord(parsed)) {
222
- return null;
223
- }
224
-
225
- const wrappedPost = resolveLocalePayload(parsed.post);
226
- if (wrappedPost) {
227
- return wrappedPost;
228
- }
229
-
230
- return resolveLocalePayload(parsed);
231
- }
232
-
233
- export function parsePostContent(content: string): PostParseResult {
234
- try {
235
- const parsed = JSON.parse(content);
236
- const payload = resolvePostPayload(parsed);
237
- if (!payload) {
238
- return {
239
- textContent: FALLBACK_POST_TEXT,
240
- imageKeys: [],
241
- mediaKeys: [],
242
- mentionedOpenIds: [],
243
- };
244
- }
245
-
246
- const imageKeys: string[] = [];
247
- const mediaKeys: Array<{ fileKey: string; fileName?: string }> = [];
248
- const mentionedOpenIds: string[] = [];
249
- const paragraphs: string[] = [];
250
-
251
- for (const paragraph of payload.content) {
252
- if (!Array.isArray(paragraph)) {
253
- continue;
254
- }
255
- let renderedParagraph = "";
256
- for (const element of paragraph) {
257
- renderedParagraph += renderElement(element, imageKeys, mediaKeys, mentionedOpenIds);
258
- }
259
- paragraphs.push(renderedParagraph);
260
- }
261
-
262
- const title = escapeMarkdownText(payload.title.trim());
263
- const body = paragraphs.join("\n").trim();
264
- const textContent = [title, body].filter(Boolean).join("\n\n").trim();
265
-
266
- return {
267
- textContent: textContent || FALLBACK_POST_TEXT,
268
- imageKeys,
269
- mediaKeys,
270
- mentionedOpenIds,
271
- };
272
- } catch {
273
- return { textContent: FALLBACK_POST_TEXT, imageKeys: [], mediaKeys: [], mentionedOpenIds: [] };
274
- }
275
- }