@kodelyth/feishu 2026.5.42 → 2026.6.1

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 (192) hide show
  1. package/klaw.plugin.json +1712 -47
  2. package/package.json +17 -4
  3. package/api.ts +0 -32
  4. package/channel-entry.ts +0 -20
  5. package/channel-plugin-api.ts +0 -1
  6. package/contract-api.ts +0 -16
  7. package/index.ts +0 -82
  8. package/runtime-api.ts +0 -52
  9. package/secret-contract-api.ts +0 -5
  10. package/security-contract-api.ts +0 -1
  11. package/session-key-api.ts +0 -1
  12. package/setup-api.ts +0 -3
  13. package/setup-entry.test.ts +0 -19
  14. package/setup-entry.ts +0 -13
  15. package/src/accounts.test.ts +0 -480
  16. package/src/accounts.ts +0 -333
  17. package/src/agent-config.ts +0 -21
  18. package/src/app-registration.ts +0 -331
  19. package/src/approval-auth.test.ts +0 -24
  20. package/src/approval-auth.ts +0 -25
  21. package/src/async.test.ts +0 -35
  22. package/src/async.ts +0 -104
  23. package/src/audio-preflight.runtime.ts +0 -9
  24. package/src/bitable.test.ts +0 -136
  25. package/src/bitable.ts +0 -762
  26. package/src/bot-content.ts +0 -485
  27. package/src/bot-group-name.test.ts +0 -116
  28. package/src/bot-runtime-api.ts +0 -12
  29. package/src/bot-sender-name.ts +0 -125
  30. package/src/bot.broadcast.test.ts +0 -523
  31. package/src/bot.card-action.test.ts +0 -552
  32. package/src/bot.checkBotMentioned.test.ts +0 -265
  33. package/src/bot.helpers.test.ts +0 -135
  34. package/src/bot.stripBotMention.test.ts +0 -126
  35. package/src/bot.test.ts +0 -3671
  36. package/src/bot.ts +0 -1703
  37. package/src/card-action.ts +0 -447
  38. package/src/card-interaction.test.ts +0 -131
  39. package/src/card-interaction.ts +0 -159
  40. package/src/card-test-helpers.ts +0 -54
  41. package/src/card-ux-approval.ts +0 -65
  42. package/src/card-ux-launcher.test.ts +0 -106
  43. package/src/card-ux-launcher.ts +0 -121
  44. package/src/card-ux-shared.ts +0 -33
  45. package/src/channel-runtime-api.ts +0 -16
  46. package/src/channel.runtime.ts +0 -47
  47. package/src/channel.test.ts +0 -1151
  48. package/src/channel.ts +0 -1423
  49. package/src/chat-schema.ts +0 -25
  50. package/src/chat.test.ts +0 -240
  51. package/src/chat.ts +0 -188
  52. package/src/client-timeout.ts +0 -42
  53. package/src/client.test.ts +0 -447
  54. package/src/client.ts +0 -262
  55. package/src/comment-dispatcher-runtime-api.ts +0 -6
  56. package/src/comment-dispatcher.test.ts +0 -185
  57. package/src/comment-dispatcher.ts +0 -107
  58. package/src/comment-handler-runtime-api.ts +0 -3
  59. package/src/comment-handler.test.ts +0 -592
  60. package/src/comment-handler.ts +0 -303
  61. package/src/comment-reaction.test.ts +0 -138
  62. package/src/comment-reaction.ts +0 -259
  63. package/src/comment-shared.test.ts +0 -183
  64. package/src/comment-shared.ts +0 -406
  65. package/src/comment-target.ts +0 -44
  66. package/src/config-schema.test.ts +0 -326
  67. package/src/config-schema.ts +0 -335
  68. package/src/conversation-id.test.ts +0 -18
  69. package/src/conversation-id.ts +0 -199
  70. package/src/dedup-runtime-api.ts +0 -1
  71. package/src/dedup.ts +0 -141
  72. package/src/dedupe-key.ts +0 -72
  73. package/src/directory.static.ts +0 -61
  74. package/src/directory.test.ts +0 -141
  75. package/src/directory.ts +0 -124
  76. package/src/doc-schema.ts +0 -182
  77. package/src/docx-batch-insert.test.ts +0 -116
  78. package/src/docx-batch-insert.ts +0 -223
  79. package/src/docx-color-text.ts +0 -154
  80. package/src/docx-table-ops.test.ts +0 -53
  81. package/src/docx-table-ops.ts +0 -316
  82. package/src/docx-types.ts +0 -38
  83. package/src/docx.account-selection.test.ts +0 -95
  84. package/src/docx.test.ts +0 -701
  85. package/src/docx.ts +0 -1596
  86. package/src/drive-schema.ts +0 -92
  87. package/src/drive.test.ts +0 -1237
  88. package/src/drive.ts +0 -829
  89. package/src/dynamic-agent.test.ts +0 -155
  90. package/src/dynamic-agent.ts +0 -143
  91. package/src/event-types.ts +0 -45
  92. package/src/external-keys.test.ts +0 -20
  93. package/src/external-keys.ts +0 -19
  94. package/src/lifecycle.test-support.ts +0 -220
  95. package/src/media.test.ts +0 -955
  96. package/src/media.ts +0 -1105
  97. package/src/mention-target.types.ts +0 -5
  98. package/src/mention.ts +0 -114
  99. package/src/message-action-contract.ts +0 -13
  100. package/src/monitor-state-runtime-api.ts +0 -7
  101. package/src/monitor-transport-runtime-api.ts +0 -10
  102. package/src/monitor.account.ts +0 -492
  103. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +0 -219
  104. package/src/monitor.bot-identity.ts +0 -86
  105. package/src/monitor.bot-menu-handler.ts +0 -165
  106. package/src/monitor.bot-menu.lifecycle.test-support.ts +0 -224
  107. package/src/monitor.bot-menu.test.ts +0 -188
  108. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +0 -264
  109. package/src/monitor.card-action.lifecycle.test-support.ts +0 -421
  110. package/src/monitor.cleanup.test.ts +0 -383
  111. package/src/monitor.comment-notice-handler.ts +0 -105
  112. package/src/monitor.comment.test.ts +0 -967
  113. package/src/monitor.comment.ts +0 -1386
  114. package/src/monitor.lifecycle.test.ts +0 -4
  115. package/src/monitor.message-handler.ts +0 -350
  116. package/src/monitor.reaction.lifecycle.test-support.ts +0 -68
  117. package/src/monitor.reaction.test.ts +0 -739
  118. package/src/monitor.startup.test.ts +0 -213
  119. package/src/monitor.startup.ts +0 -74
  120. package/src/monitor.state.defaults.test.ts +0 -46
  121. package/src/monitor.state.ts +0 -170
  122. package/src/monitor.synthetic-error.ts +0 -18
  123. package/src/monitor.test-mocks.ts +0 -46
  124. package/src/monitor.transport.ts +0 -451
  125. package/src/monitor.ts +0 -100
  126. package/src/monitor.webhook-e2e.test.ts +0 -279
  127. package/src/monitor.webhook-security.test.ts +0 -389
  128. package/src/monitor.webhook.test-helpers.ts +0 -116
  129. package/src/outbound-runtime-api.ts +0 -1
  130. package/src/outbound.test.ts +0 -1118
  131. package/src/outbound.ts +0 -785
  132. package/src/perm-schema.ts +0 -52
  133. package/src/perm.ts +0 -170
  134. package/src/pins.ts +0 -108
  135. package/src/policy.test.ts +0 -223
  136. package/src/policy.ts +0 -318
  137. package/src/post.test.ts +0 -105
  138. package/src/post.ts +0 -275
  139. package/src/probe.test.ts +0 -283
  140. package/src/probe.ts +0 -166
  141. package/src/processing-claims.ts +0 -59
  142. package/src/qr-terminal.ts +0 -1
  143. package/src/reactions.ts +0 -123
  144. package/src/reasoning-preview.test.ts +0 -113
  145. package/src/reasoning-preview.ts +0 -28
  146. package/src/reply-dispatcher-runtime-api.ts +0 -7
  147. package/src/reply-dispatcher.test.ts +0 -1513
  148. package/src/reply-dispatcher.ts +0 -748
  149. package/src/runtime.ts +0 -9
  150. package/src/secret-contract.ts +0 -145
  151. package/src/secret-input.ts +0 -1
  152. package/src/security-audit-shared.ts +0 -69
  153. package/src/security-audit.test.ts +0 -59
  154. package/src/security-audit.ts +0 -1
  155. package/src/send-result.ts +0 -80
  156. package/src/send-target.test.ts +0 -86
  157. package/src/send-target.ts +0 -35
  158. package/src/send.reply-fallback.test.ts +0 -417
  159. package/src/send.test.ts +0 -621
  160. package/src/send.ts +0 -861
  161. package/src/sequential-key.test.ts +0 -72
  162. package/src/sequential-key.ts +0 -25
  163. package/src/sequential-queue.test.ts +0 -165
  164. package/src/sequential-queue.ts +0 -86
  165. package/src/session-conversation.ts +0 -42
  166. package/src/session-route.ts +0 -48
  167. package/src/setup-core.ts +0 -51
  168. package/src/setup-surface.test.ts +0 -484
  169. package/src/setup-surface.ts +0 -618
  170. package/src/streaming-card.test.ts +0 -397
  171. package/src/streaming-card.ts +0 -571
  172. package/src/subagent-hooks.test.ts +0 -627
  173. package/src/subagent-hooks.ts +0 -413
  174. package/src/targets.ts +0 -97
  175. package/src/test-support/lifecycle-test-support.ts +0 -454
  176. package/src/thread-bindings.test.ts +0 -180
  177. package/src/thread-bindings.ts +0 -331
  178. package/src/tool-account-routing.test.ts +0 -250
  179. package/src/tool-account.test.ts +0 -44
  180. package/src/tool-account.ts +0 -93
  181. package/src/tool-factory-test-harness.ts +0 -79
  182. package/src/tool-result.test.ts +0 -32
  183. package/src/tool-result.ts +0 -16
  184. package/src/tools-config.test.ts +0 -21
  185. package/src/tools-config.ts +0 -22
  186. package/src/types.ts +0 -106
  187. package/src/typing.test.ts +0 -144
  188. package/src/typing.ts +0 -214
  189. package/src/wiki-schema.ts +0 -69
  190. package/src/wiki.ts +0 -270
  191. package/subagent-hooks-api.ts +0 -31
  192. package/tsconfig.json +0 -16
package/src/policy.ts DELETED
@@ -1,318 +0,0 @@
1
- import { normalizeAccountId, resolveMergedAccountConfig } from "klaw/plugin-sdk/account-resolution";
2
- import {
3
- createChannelIngressResolver,
4
- defineStableChannelIngressIdentity,
5
- type ChannelIngressIdentitySubjectInput,
6
- type ResolveChannelMessageIngressParams,
7
- } from "klaw/plugin-sdk/channel-ingress-runtime";
8
- import type { KlawConfig } from "klaw/plugin-sdk/core";
9
- import { normalizeOptionalLowercaseString } from "klaw/plugin-sdk/string-coerce-runtime";
10
- import type { ChannelGroupContext } from "../runtime-api.js";
11
- import { detectIdType } from "./targets.js";
12
- import type { FeishuConfig } from "./types.js";
13
-
14
- type FeishuDmPolicy = "open" | "pairing" | "allowlist" | "disabled";
15
- type FeishuGroupPolicy = "open" | "allowlist" | "disabled" | "allowall";
16
- type NormalizedFeishuGroupPolicy = Exclude<FeishuGroupPolicy, "allowall">;
17
-
18
- const FEISHU_PROVIDER_PREFIX_RE = /^(feishu|lark):/i;
19
- const FEISHU_TYPED_PREFIX_RE = /^(chat|group|channel|user|dm|open_id):/i;
20
- const FEISHU_ID_KIND = "plugin:feishu-id" as const;
21
- const feishuIngressIdentity = defineStableChannelIngressIdentity({
22
- key: "feishu-id",
23
- kind: FEISHU_ID_KIND,
24
- normalize: normalizeFeishuAllowEntry,
25
- sensitivity: "pii",
26
- aliases: [
27
- {
28
- key: "feishu-alt-id",
29
- kind: FEISHU_ID_KIND,
30
- normalizeEntry: () => null,
31
- normalizeSubject: normalizeFeishuAllowEntry,
32
- sensitivity: "pii",
33
- },
34
- ],
35
- isWildcardEntry: (entry) => normalizeFeishuAllowEntry(entry) === "*",
36
- resolveEntryId: ({ entryIndex }) => `feishu-entry-${entryIndex + 1}`,
37
- });
38
-
39
- export function normalizeFeishuAllowEntry(raw: string): string {
40
- const trimmed = raw.trim();
41
- if (!trimmed) {
42
- return "";
43
- }
44
- if (trimmed === "*") {
45
- return "*";
46
- }
47
-
48
- let withoutProviderPrefix = trimmed;
49
- while (FEISHU_PROVIDER_PREFIX_RE.test(withoutProviderPrefix)) {
50
- withoutProviderPrefix = withoutProviderPrefix.replace(FEISHU_PROVIDER_PREFIX_RE, "").trim();
51
- }
52
- if (withoutProviderPrefix === "*") {
53
- return "*";
54
- }
55
- const lowered = normalizeOptionalLowercaseString(withoutProviderPrefix) ?? "";
56
- if (!lowered) {
57
- return "";
58
- }
59
- const prefixed = lowered.match(FEISHU_TYPED_PREFIX_RE);
60
- if (prefixed?.[1]) {
61
- const kind = ["chat", "group", "channel"].includes(prefixed[1]) ? "chat" : "user";
62
- const value = withoutProviderPrefix.slice(prefixed[0].length).trim();
63
- return value === "*" ? "*" : value ? `${kind}:${value}` : "";
64
- }
65
-
66
- const detectedType = detectIdType(withoutProviderPrefix);
67
- if (detectedType === "chat_id") {
68
- return `chat:${withoutProviderPrefix}`;
69
- }
70
- if (detectedType === "open_id" || detectedType === "user_id") {
71
- return `user:${withoutProviderPrefix}`;
72
- }
73
-
74
- return "";
75
- }
76
-
77
- function normalizeFeishuDmPolicy(policy: string | null | undefined): FeishuDmPolicy {
78
- return policy === "open" ||
79
- policy === "pairing" ||
80
- policy === "allowlist" ||
81
- policy === "disabled"
82
- ? policy
83
- : "pairing";
84
- }
85
-
86
- function normalizeFeishuGroupPolicy(policy: FeishuGroupPolicy): NormalizedFeishuGroupPolicy {
87
- return policy === "allowall" ? "open" : policy;
88
- }
89
-
90
- function createFeishuIngressSubject(params: {
91
- primaryId?: string | null;
92
- alternateIds?: Array<string | null | undefined>;
93
- }): ChannelIngressIdentitySubjectInput {
94
- const ids = [params.primaryId, ...(params.alternateIds ?? [])]
95
- .map((value) => value?.trim())
96
- .filter((value): value is string => Boolean(value));
97
- return {
98
- stableId: ids[0],
99
- aliases: {
100
- "feishu-alt-id": ids[1],
101
- },
102
- };
103
- }
104
-
105
- function createFeishuIngressResolver(params: {
106
- cfg?: KlawConfig;
107
- accountId?: string | null;
108
- readAllowFromStore?: ResolveChannelMessageIngressParams["readStoreAllowFrom"];
109
- }) {
110
- return createChannelIngressResolver({
111
- channelId: "feishu",
112
- accountId: normalizeAccountId(params.accountId) ?? "default",
113
- identity: feishuIngressIdentity,
114
- cfg: params.cfg,
115
- ...(params.readAllowFromStore ? { readStoreAllowFrom: params.readAllowFromStore } : {}),
116
- });
117
- }
118
-
119
- export async function resolveFeishuDmIngressAccess(params: {
120
- cfg: KlawConfig;
121
- accountId?: string | null;
122
- dmPolicy?: string | null;
123
- allowFrom?: Array<string | number> | null;
124
- readAllowFromStore?: () => Promise<Array<string | number>>;
125
- senderOpenId: string;
126
- senderUserId?: string | null;
127
- conversationId: string;
128
- mayPair: boolean;
129
- command?: { hasControlCommand: boolean };
130
- }) {
131
- return await createFeishuIngressResolver({
132
- cfg: params.cfg,
133
- accountId: params.accountId,
134
- readAllowFromStore: params.readAllowFromStore,
135
- }).message({
136
- subject: createFeishuIngressSubject({
137
- primaryId: params.senderOpenId,
138
- alternateIds: [params.senderUserId],
139
- }),
140
- conversation: {
141
- kind: "direct",
142
- id: params.conversationId,
143
- },
144
- event: {
145
- mayPair: params.mayPair,
146
- },
147
- dmPolicy: normalizeFeishuDmPolicy(params.dmPolicy),
148
- groupPolicy: "disabled",
149
- allowFrom: params.allowFrom ?? [],
150
- ...(params.command ? { command: params.command } : {}),
151
- });
152
- }
153
-
154
- export async function resolveFeishuGroupConversationIngressAccess(params: {
155
- cfg: KlawConfig;
156
- accountId?: string | null;
157
- chatId: string;
158
- groupPolicy: FeishuGroupPolicy;
159
- groupAllowFrom?: Array<string | number> | null;
160
- groupExplicitlyConfigured?: boolean;
161
- }) {
162
- const groupPolicy = normalizeFeishuGroupPolicy(params.groupPolicy);
163
- const groupAllowFrom =
164
- groupPolicy === "allowlist" && params.groupExplicitlyConfigured
165
- ? [...(params.groupAllowFrom ?? []), params.chatId]
166
- : (params.groupAllowFrom ?? []);
167
- return await createFeishuIngressResolver({
168
- cfg: params.cfg,
169
- accountId: params.accountId,
170
- }).message({
171
- subject: createFeishuIngressSubject({
172
- primaryId: params.chatId,
173
- }),
174
- conversation: {
175
- kind: "group",
176
- id: params.chatId,
177
- },
178
- dmPolicy: "disabled",
179
- groupPolicy,
180
- groupAllowFrom,
181
- });
182
- }
183
-
184
- export async function resolveFeishuGroupSenderActivationIngressAccess(params: {
185
- cfg: KlawConfig;
186
- accountId?: string | null;
187
- chatId: string;
188
- allowFrom?: Array<string | number> | null;
189
- senderOpenId: string;
190
- senderUserId?: string | null;
191
- requireMention: boolean;
192
- mentionedBot: boolean;
193
- command?: { hasControlCommand: boolean };
194
- }) {
195
- const groupAllowFrom = params.allowFrom ?? [];
196
- return await createFeishuIngressResolver({
197
- cfg: params.cfg,
198
- accountId: params.accountId,
199
- }).message({
200
- subject: createFeishuIngressSubject({
201
- primaryId: params.senderOpenId,
202
- alternateIds: [params.senderUserId],
203
- }),
204
- conversation: {
205
- kind: "group",
206
- id: params.chatId,
207
- },
208
- dmPolicy: "disabled",
209
- groupPolicy: groupAllowFrom.length > 0 ? "allowlist" : "open",
210
- groupAllowFrom,
211
- mentionFacts: {
212
- canDetectMention: true,
213
- wasMentioned: params.mentionedBot,
214
- },
215
- policy: {
216
- activation: {
217
- requireMention: params.requireMention,
218
- allowTextCommands: false,
219
- },
220
- },
221
- ...(params.command ? { command: params.command } : {}),
222
- });
223
- }
224
-
225
- export function resolveFeishuGroupConfig(params: { cfg?: FeishuConfig; groupId?: string | null }) {
226
- const groups = params.cfg?.groups ?? {};
227
- const wildcard = groups["*"];
228
- const groupId = params.groupId?.trim();
229
- if (!groupId) {
230
- return undefined;
231
- }
232
-
233
- const direct = groups[groupId];
234
- if (direct) {
235
- return direct;
236
- }
237
-
238
- const lowered = normalizeOptionalLowercaseString(groupId) ?? "";
239
- const matchKey = Object.keys(groups).find(
240
- (key) => normalizeOptionalLowercaseString(key) === lowered,
241
- );
242
- if (matchKey) {
243
- return groups[matchKey];
244
- }
245
- return wildcard;
246
- }
247
-
248
- export function hasExplicitFeishuGroupConfig(params: {
249
- cfg?: FeishuConfig;
250
- groupId?: string | null;
251
- }): boolean {
252
- const groups = params.cfg?.groups ?? {};
253
- const groupId = params.groupId?.trim();
254
- if (!groupId) {
255
- return false;
256
- }
257
- if (Object.prototype.hasOwnProperty.call(groups, groupId) && groupId !== "*") {
258
- return true;
259
- }
260
-
261
- const lowered = normalizeOptionalLowercaseString(groupId) ?? "";
262
- return Object.keys(groups).some(
263
- (key) => key !== "*" && normalizeOptionalLowercaseString(key) === lowered,
264
- );
265
- }
266
-
267
- export function resolveFeishuGroupToolPolicy(params: ChannelGroupContext) {
268
- const cfg = params.cfg.channels?.feishu;
269
- if (!cfg) {
270
- return undefined;
271
- }
272
-
273
- const groupConfig = resolveFeishuGroupConfig({
274
- cfg,
275
- groupId: params.groupId,
276
- });
277
-
278
- return groupConfig?.tools;
279
- }
280
-
281
- export function resolveFeishuReplyPolicy(params: {
282
- isDirectMessage: boolean;
283
- cfg: KlawConfig;
284
- accountId?: string | null;
285
- groupId?: string | null;
286
- /**
287
- * Effective group policy resolved for this chat. When "open", requireMention
288
- * defaults to false so that non-text messages (e.g. images) that cannot carry
289
- * @-mentions are still delivered to the agent.
290
- */
291
- groupPolicy?: "open" | "allowlist" | "disabled" | "allowall";
292
- }): { requireMention: boolean } {
293
- if (params.isDirectMessage) {
294
- return { requireMention: false };
295
- }
296
-
297
- const feishuCfg = params.cfg.channels?.feishu;
298
- const resolvedCfg = resolveMergedAccountConfig<FeishuConfig>({
299
- channelConfig: feishuCfg,
300
- accounts: feishuCfg?.accounts as Record<string, Partial<FeishuConfig>> | undefined,
301
- accountId: normalizeAccountId(params.accountId),
302
- normalizeAccountId,
303
- omitKeys: ["defaultAccount"],
304
- });
305
- const groupRequireMention = resolveFeishuGroupConfig({
306
- cfg: resolvedCfg,
307
- groupId: params.groupId,
308
- })?.requireMention;
309
-
310
- return {
311
- requireMention:
312
- typeof groupRequireMention === "boolean"
313
- ? groupRequireMention
314
- : typeof resolvedCfg.requireMention === "boolean"
315
- ? resolvedCfg.requireMention
316
- : params.groupPolicy !== "open",
317
- };
318
- }
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).toStrictEqual([]);
29
- expect(result.mentionedOpenIds).toStrictEqual([]);
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).toStrictEqual([]);
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 "klaw/plugin-sdk/string-coerce-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
- }