@nextclaw/channel-plugin-feishu 0.2.12 → 0.2.14

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 (102) hide show
  1. package/README.md +3 -1
  2. package/index.ts +65 -0
  3. package/openclaw.plugin.json +3 -7
  4. package/package.json +33 -9
  5. package/skills/feishu-doc/SKILL.md +211 -0
  6. package/skills/feishu-doc/references/block-types.md +103 -0
  7. package/skills/feishu-drive/SKILL.md +97 -0
  8. package/skills/feishu-perm/SKILL.md +119 -0
  9. package/skills/feishu-wiki/SKILL.md +111 -0
  10. package/src/accounts.test.ts +371 -0
  11. package/src/accounts.ts +244 -0
  12. package/src/async.ts +62 -0
  13. package/src/bitable.ts +725 -0
  14. package/src/bot.card-action.test.ts +63 -0
  15. package/src/bot.checkBotMentioned.test.ts +193 -0
  16. package/src/bot.stripBotMention.test.ts +134 -0
  17. package/src/bot.test.ts +2107 -0
  18. package/src/bot.ts +1556 -0
  19. package/src/card-action.ts +79 -0
  20. package/src/channel.test.ts +48 -0
  21. package/src/channel.ts +369 -0
  22. package/src/chat-schema.ts +24 -0
  23. package/src/chat.test.ts +89 -0
  24. package/src/chat.ts +130 -0
  25. package/src/client.test.ts +324 -0
  26. package/src/client.ts +196 -0
  27. package/src/config-schema.test.ts +247 -0
  28. package/src/config-schema.ts +306 -0
  29. package/src/dedup.ts +203 -0
  30. package/src/directory.test.ts +40 -0
  31. package/src/directory.ts +156 -0
  32. package/src/doc-schema.ts +182 -0
  33. package/src/docx-batch-insert.test.ts +90 -0
  34. package/src/docx-batch-insert.ts +187 -0
  35. package/src/docx-color-text.ts +149 -0
  36. package/src/docx-table-ops.ts +298 -0
  37. package/src/docx.account-selection.test.ts +70 -0
  38. package/src/docx.test.ts +445 -0
  39. package/src/docx.ts +1460 -0
  40. package/src/drive-schema.ts +46 -0
  41. package/src/drive.ts +228 -0
  42. package/src/dynamic-agent.ts +131 -0
  43. package/src/external-keys.test.ts +20 -0
  44. package/src/external-keys.ts +19 -0
  45. package/src/feishu-command-handler.ts +59 -0
  46. package/src/media.test.ts +523 -0
  47. package/src/media.ts +484 -0
  48. package/src/mention.ts +133 -0
  49. package/src/monitor.account.ts +562 -0
  50. package/src/monitor.reaction.test.ts +653 -0
  51. package/src/monitor.startup.test.ts +190 -0
  52. package/src/monitor.startup.ts +64 -0
  53. package/src/monitor.state.defaults.test.ts +46 -0
  54. package/src/monitor.state.ts +155 -0
  55. package/src/monitor.test-mocks.ts +45 -0
  56. package/src/monitor.transport.ts +264 -0
  57. package/src/monitor.ts +95 -0
  58. package/src/monitor.webhook-e2e.test.ts +214 -0
  59. package/src/monitor.webhook-security.test.ts +142 -0
  60. package/src/monitor.webhook.test-helpers.ts +98 -0
  61. package/src/onboarding.status.test.ts +25 -0
  62. package/src/onboarding.test.ts +143 -0
  63. package/src/onboarding.ts +489 -0
  64. package/src/outbound.test.ts +356 -0
  65. package/src/outbound.ts +176 -0
  66. package/src/perm-schema.ts +52 -0
  67. package/src/perm.ts +176 -0
  68. package/src/policy.test.ts +154 -0
  69. package/src/policy.ts +123 -0
  70. package/src/post.test.ts +105 -0
  71. package/src/post.ts +274 -0
  72. package/src/probe.test.ts +270 -0
  73. package/src/probe.ts +156 -0
  74. package/src/reactions.ts +153 -0
  75. package/src/reply-dispatcher.test.ts +513 -0
  76. package/src/reply-dispatcher.ts +397 -0
  77. package/src/runtime.ts +6 -0
  78. package/src/secret-input.ts +13 -0
  79. package/src/send-message.ts +71 -0
  80. package/src/send-result.ts +29 -0
  81. package/src/send-target.test.ts +74 -0
  82. package/src/send-target.ts +29 -0
  83. package/src/send.reply-fallback.test.ts +189 -0
  84. package/src/send.test.ts +168 -0
  85. package/src/send.ts +481 -0
  86. package/src/streaming-card.test.ts +54 -0
  87. package/src/streaming-card.ts +374 -0
  88. package/src/targets.test.ts +70 -0
  89. package/src/targets.ts +107 -0
  90. package/src/tool-account-routing.test.ts +129 -0
  91. package/src/tool-account.ts +70 -0
  92. package/src/tool-factory-test-harness.ts +76 -0
  93. package/src/tool-result.test.ts +32 -0
  94. package/src/tool-result.ts +14 -0
  95. package/src/tools-config.test.ts +21 -0
  96. package/src/tools-config.ts +22 -0
  97. package/src/types.ts +103 -0
  98. package/src/typing.test.ts +144 -0
  99. package/src/typing.ts +210 -0
  100. package/src/wiki-schema.ts +55 -0
  101. package/src/wiki.ts +233 -0
  102. package/index.js +0 -27
package/src/dedup.ts ADDED
@@ -0,0 +1,203 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import {
4
+ createDedupeCache,
5
+ createPersistentDedupe,
6
+ readJsonFileWithFallback,
7
+ } from "openclaw/plugin-sdk/feishu";
8
+
9
+ // Persistent TTL: 24 hours — survives restarts & WebSocket reconnects.
10
+ const DEDUP_TTL_MS = 24 * 60 * 60 * 1000;
11
+ const MEMORY_MAX_SIZE = 1_000;
12
+ const FILE_MAX_ENTRIES = 10_000;
13
+ const EVENT_DEDUP_TTL_MS = 5 * 60 * 1000;
14
+ const EVENT_MEMORY_MAX_SIZE = 2_000;
15
+ type PersistentDedupeData = Record<string, number>;
16
+
17
+ const memoryDedupe = createDedupeCache({ ttlMs: DEDUP_TTL_MS, maxSize: MEMORY_MAX_SIZE });
18
+ const processingClaims = createDedupeCache({
19
+ ttlMs: EVENT_DEDUP_TTL_MS,
20
+ maxSize: EVENT_MEMORY_MAX_SIZE,
21
+ });
22
+
23
+ function resolveStateDirFromEnv(env: NodeJS.ProcessEnv = process.env): string {
24
+ const stateOverride = env.OPENCLAW_STATE_DIR?.trim() || env.CLAWDBOT_STATE_DIR?.trim();
25
+ if (stateOverride) {
26
+ return stateOverride;
27
+ }
28
+ if (env.VITEST || env.NODE_ENV === "test") {
29
+ return path.join(os.tmpdir(), ["openclaw-vitest", String(process.pid)].join("-"));
30
+ }
31
+ return path.join(os.homedir(), ".openclaw");
32
+ }
33
+
34
+ function resolveNamespaceFilePath(namespace: string): string {
35
+ const safe = namespace.replace(/[^a-zA-Z0-9_-]/g, "_");
36
+ return path.join(resolveStateDirFromEnv(), "feishu", "dedup", `${safe}.json`);
37
+ }
38
+
39
+ const persistentDedupe = createPersistentDedupe({
40
+ ttlMs: DEDUP_TTL_MS,
41
+ memoryMaxSize: MEMORY_MAX_SIZE,
42
+ fileMaxEntries: FILE_MAX_ENTRIES,
43
+ resolveFilePath: resolveNamespaceFilePath,
44
+ });
45
+
46
+ function resolveEventDedupeKey(
47
+ namespace: string,
48
+ messageId: string | undefined | null,
49
+ ): string | null {
50
+ const trimmed = messageId?.trim();
51
+ if (!trimmed) {
52
+ return null;
53
+ }
54
+ return `${namespace}:${trimmed}`;
55
+ }
56
+
57
+ function normalizeMessageId(messageId: string | undefined | null): string | null {
58
+ const trimmed = messageId?.trim();
59
+ return trimmed ? trimmed : null;
60
+ }
61
+
62
+ function resolveMemoryDedupeKey(
63
+ namespace: string,
64
+ messageId: string | undefined | null,
65
+ ): string | null {
66
+ const trimmed = normalizeMessageId(messageId);
67
+ if (!trimmed) {
68
+ return null;
69
+ }
70
+ return `${namespace}:${trimmed}`;
71
+ }
72
+
73
+ export function tryBeginFeishuMessageProcessing(
74
+ messageId: string | undefined | null,
75
+ namespace = "global",
76
+ ): boolean {
77
+ return !processingClaims.check(resolveEventDedupeKey(namespace, messageId));
78
+ }
79
+
80
+ export function releaseFeishuMessageProcessing(
81
+ messageId: string | undefined | null,
82
+ namespace = "global",
83
+ ): void {
84
+ processingClaims.delete(resolveEventDedupeKey(namespace, messageId));
85
+ }
86
+
87
+ export async function finalizeFeishuMessageProcessing(params: {
88
+ messageId: string | undefined | null;
89
+ namespace?: string;
90
+ log?: (...args: unknown[]) => void;
91
+ claimHeld?: boolean;
92
+ }): Promise<boolean> {
93
+ const { messageId, namespace = "global", log, claimHeld = false } = params;
94
+ const normalizedMessageId = normalizeMessageId(messageId);
95
+ const memoryKey = resolveMemoryDedupeKey(namespace, messageId);
96
+ if (!memoryKey || !normalizedMessageId) {
97
+ return false;
98
+ }
99
+ if (!claimHeld && !tryBeginFeishuMessageProcessing(normalizedMessageId, namespace)) {
100
+ return false;
101
+ }
102
+ if (!tryRecordMessage(memoryKey)) {
103
+ releaseFeishuMessageProcessing(normalizedMessageId, namespace);
104
+ return false;
105
+ }
106
+ if (!(await tryRecordMessagePersistent(normalizedMessageId, namespace, log))) {
107
+ releaseFeishuMessageProcessing(normalizedMessageId, namespace);
108
+ return false;
109
+ }
110
+ return true;
111
+ }
112
+
113
+ export async function recordProcessedFeishuMessage(
114
+ messageId: string | undefined | null,
115
+ namespace = "global",
116
+ log?: (...args: unknown[]) => void,
117
+ ): Promise<boolean> {
118
+ const normalizedMessageId = normalizeMessageId(messageId);
119
+ const memoryKey = resolveMemoryDedupeKey(namespace, messageId);
120
+ if (!memoryKey || !normalizedMessageId) {
121
+ return false;
122
+ }
123
+ tryRecordMessage(memoryKey);
124
+ return await tryRecordMessagePersistent(normalizedMessageId, namespace, log);
125
+ }
126
+
127
+ export async function hasProcessedFeishuMessage(
128
+ messageId: string | undefined | null,
129
+ namespace = "global",
130
+ log?: (...args: unknown[]) => void,
131
+ ): Promise<boolean> {
132
+ const normalizedMessageId = normalizeMessageId(messageId);
133
+ const memoryKey = resolveMemoryDedupeKey(namespace, messageId);
134
+ if (!memoryKey || !normalizedMessageId) {
135
+ return false;
136
+ }
137
+ if (hasRecordedMessage(memoryKey)) {
138
+ return true;
139
+ }
140
+ return hasRecordedMessagePersistent(normalizedMessageId, namespace, log);
141
+ }
142
+
143
+ /**
144
+ * Synchronous dedup — memory only.
145
+ * Kept for backward compatibility; prefer {@link tryRecordMessagePersistent}.
146
+ */
147
+ export function tryRecordMessage(messageId: string): boolean {
148
+ return !memoryDedupe.check(messageId);
149
+ }
150
+
151
+ export function hasRecordedMessage(messageId: string): boolean {
152
+ const trimmed = messageId.trim();
153
+ if (!trimmed) {
154
+ return false;
155
+ }
156
+ return memoryDedupe.peek(trimmed);
157
+ }
158
+
159
+ export async function tryRecordMessagePersistent(
160
+ messageId: string,
161
+ namespace = "global",
162
+ log?: (...args: unknown[]) => void,
163
+ ): Promise<boolean> {
164
+ return persistentDedupe.checkAndRecord(messageId, {
165
+ namespace,
166
+ onDiskError: (error) => {
167
+ log?.(`feishu-dedup: disk error, falling back to memory: ${String(error)}`);
168
+ },
169
+ });
170
+ }
171
+
172
+ export async function hasRecordedMessagePersistent(
173
+ messageId: string,
174
+ namespace = "global",
175
+ log?: (...args: unknown[]) => void,
176
+ ): Promise<boolean> {
177
+ const trimmed = messageId.trim();
178
+ if (!trimmed) {
179
+ return false;
180
+ }
181
+ const now = Date.now();
182
+ const filePath = resolveNamespaceFilePath(namespace);
183
+ try {
184
+ const { value } = await readJsonFileWithFallback<PersistentDedupeData>(filePath, {});
185
+ const seenAt = value[trimmed];
186
+ if (typeof seenAt !== "number" || !Number.isFinite(seenAt)) {
187
+ return false;
188
+ }
189
+ return DEDUP_TTL_MS <= 0 || now - seenAt < DEDUP_TTL_MS;
190
+ } catch (error) {
191
+ log?.(`feishu-dedup: persistent peek failed: ${String(error)}`);
192
+ return false;
193
+ }
194
+ }
195
+
196
+ export async function warmupDedupFromDisk(
197
+ namespace: string,
198
+ log?: (...args: unknown[]) => void,
199
+ ): Promise<number> {
200
+ return persistentDedupe.warmup(namespace, (error) => {
201
+ log?.(`feishu-dedup: warmup disk error: ${String(error)}`);
202
+ });
203
+ }
@@ -0,0 +1,40 @@
1
+ import type { ClawdbotConfig } from "openclaw/plugin-sdk/feishu";
2
+ import { describe, expect, it, vi } from "vitest";
3
+
4
+ vi.mock("./accounts.js", () => ({
5
+ resolveFeishuAccount: vi.fn(() => ({
6
+ configured: false,
7
+ config: {
8
+ allowFrom: ["user:alice", "user:bob"],
9
+ dms: {
10
+ "user:carla": {},
11
+ },
12
+ groups: {
13
+ "chat-1": {},
14
+ },
15
+ groupAllowFrom: ["chat-2"],
16
+ },
17
+ })),
18
+ }));
19
+
20
+ import { listFeishuDirectoryGroups, listFeishuDirectoryPeers } from "./directory.js";
21
+
22
+ describe("feishu directory (config-backed)", () => {
23
+ const cfg = {} as ClawdbotConfig;
24
+
25
+ it("merges allowFrom + dms into peer entries", async () => {
26
+ const peers = await listFeishuDirectoryPeers({ cfg, query: "a" });
27
+ expect(peers).toEqual([
28
+ { kind: "user", id: "alice" },
29
+ { kind: "user", id: "carla" },
30
+ ]);
31
+ });
32
+
33
+ it("merges groups map + groupAllowFrom into group entries", async () => {
34
+ const groups = await listFeishuDirectoryGroups({ cfg });
35
+ expect(groups).toEqual([
36
+ { kind: "group", id: "chat-1" },
37
+ { kind: "group", id: "chat-2" },
38
+ ]);
39
+ });
40
+ });
@@ -0,0 +1,156 @@
1
+ import {
2
+ listDirectoryGroupEntriesFromMapKeysAndAllowFrom,
3
+ listDirectoryUserEntriesFromAllowFromAndMapKeys,
4
+ } from "openclaw/plugin-sdk/compat";
5
+ import type { ClawdbotConfig } from "openclaw/plugin-sdk/feishu";
6
+ import { resolveFeishuAccount } from "./accounts.js";
7
+ import { createFeishuClient } from "./client.js";
8
+ import { normalizeFeishuTarget } from "./targets.js";
9
+
10
+ export type FeishuDirectoryPeer = {
11
+ kind: "user";
12
+ id: string;
13
+ name?: string;
14
+ };
15
+
16
+ export type FeishuDirectoryGroup = {
17
+ kind: "group";
18
+ id: string;
19
+ name?: string;
20
+ };
21
+
22
+ function toFeishuDirectoryPeers(ids: string[]): FeishuDirectoryPeer[] {
23
+ return ids.map((id) => ({ kind: "user", id }));
24
+ }
25
+
26
+ function toFeishuDirectoryGroups(ids: string[]): FeishuDirectoryGroup[] {
27
+ return ids.map((id) => ({ kind: "group", id }));
28
+ }
29
+
30
+ export async function listFeishuDirectoryPeers(params: {
31
+ cfg: ClawdbotConfig;
32
+ query?: string;
33
+ limit?: number;
34
+ accountId?: string;
35
+ }): Promise<FeishuDirectoryPeer[]> {
36
+ const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
37
+ const entries = listDirectoryUserEntriesFromAllowFromAndMapKeys({
38
+ allowFrom: account.config.allowFrom,
39
+ map: account.config.dms,
40
+ query: params.query,
41
+ limit: params.limit,
42
+ normalizeAllowFromId: (entry) => normalizeFeishuTarget(entry) ?? entry,
43
+ normalizeMapKeyId: (entry) => normalizeFeishuTarget(entry) ?? entry,
44
+ });
45
+ return toFeishuDirectoryPeers(entries.map((entry) => entry.id));
46
+ }
47
+
48
+ export async function listFeishuDirectoryGroups(params: {
49
+ cfg: ClawdbotConfig;
50
+ query?: string;
51
+ limit?: number;
52
+ accountId?: string;
53
+ }): Promise<FeishuDirectoryGroup[]> {
54
+ const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
55
+ const entries = listDirectoryGroupEntriesFromMapKeysAndAllowFrom({
56
+ groups: account.config.groups,
57
+ allowFrom: account.config.groupAllowFrom,
58
+ query: params.query,
59
+ limit: params.limit,
60
+ });
61
+ return toFeishuDirectoryGroups(entries.map((entry) => entry.id));
62
+ }
63
+
64
+ export async function listFeishuDirectoryPeersLive(params: {
65
+ cfg: ClawdbotConfig;
66
+ query?: string;
67
+ limit?: number;
68
+ accountId?: string;
69
+ }): Promise<FeishuDirectoryPeer[]> {
70
+ const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
71
+ if (!account.configured) {
72
+ return listFeishuDirectoryPeers(params);
73
+ }
74
+
75
+ try {
76
+ const client = createFeishuClient(account);
77
+ const peers: FeishuDirectoryPeer[] = [];
78
+ const limit = params.limit ?? 50;
79
+
80
+ const response = await client.contact.user.list({
81
+ params: {
82
+ page_size: Math.min(limit, 50),
83
+ },
84
+ });
85
+
86
+ if (response.code === 0 && response.data?.items) {
87
+ for (const user of response.data.items) {
88
+ if (user.open_id) {
89
+ const q = params.query?.trim().toLowerCase() || "";
90
+ const name = user.name || "";
91
+ if (!q || user.open_id.toLowerCase().includes(q) || name.toLowerCase().includes(q)) {
92
+ peers.push({
93
+ kind: "user",
94
+ id: user.open_id,
95
+ name: name || undefined,
96
+ });
97
+ }
98
+ }
99
+ if (peers.length >= limit) {
100
+ break;
101
+ }
102
+ }
103
+ }
104
+
105
+ return peers;
106
+ } catch {
107
+ return listFeishuDirectoryPeers(params);
108
+ }
109
+ }
110
+
111
+ export async function listFeishuDirectoryGroupsLive(params: {
112
+ cfg: ClawdbotConfig;
113
+ query?: string;
114
+ limit?: number;
115
+ accountId?: string;
116
+ }): Promise<FeishuDirectoryGroup[]> {
117
+ const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
118
+ if (!account.configured) {
119
+ return listFeishuDirectoryGroups(params);
120
+ }
121
+
122
+ try {
123
+ const client = createFeishuClient(account);
124
+ const groups: FeishuDirectoryGroup[] = [];
125
+ const limit = params.limit ?? 50;
126
+
127
+ const response = await client.im.chat.list({
128
+ params: {
129
+ page_size: Math.min(limit, 100),
130
+ },
131
+ });
132
+
133
+ if (response.code === 0 && response.data?.items) {
134
+ for (const chat of response.data.items) {
135
+ if (chat.chat_id) {
136
+ const q = params.query?.trim().toLowerCase() || "";
137
+ const name = chat.name || "";
138
+ if (!q || chat.chat_id.toLowerCase().includes(q) || name.toLowerCase().includes(q)) {
139
+ groups.push({
140
+ kind: "group",
141
+ id: chat.chat_id,
142
+ name: name || undefined,
143
+ });
144
+ }
145
+ }
146
+ if (groups.length >= limit) {
147
+ break;
148
+ }
149
+ }
150
+ }
151
+
152
+ return groups;
153
+ } catch {
154
+ return listFeishuDirectoryGroups(params);
155
+ }
156
+ }
@@ -0,0 +1,182 @@
1
+ import { Type, type Static } from "@sinclair/typebox";
2
+
3
+ const tableCreationProperties = {
4
+ doc_token: Type.String({ description: "Document token" }),
5
+ parent_block_id: Type.Optional(
6
+ Type.String({ description: "Parent block ID (default: document root)" }),
7
+ ),
8
+ row_size: Type.Integer({ description: "Table row count", minimum: 1 }),
9
+ column_size: Type.Integer({ description: "Table column count", minimum: 1 }),
10
+ column_width: Type.Optional(
11
+ Type.Array(Type.Number({ minimum: 1 }), {
12
+ description: "Column widths in px (length should match column_size)",
13
+ }),
14
+ ),
15
+ };
16
+
17
+ export const FeishuDocSchema = Type.Union([
18
+ Type.Object({
19
+ action: Type.Literal("read"),
20
+ doc_token: Type.String({ description: "Document token (extract from URL /docx/XXX)" }),
21
+ }),
22
+ Type.Object({
23
+ action: Type.Literal("write"),
24
+ doc_token: Type.String({ description: "Document token" }),
25
+ content: Type.String({
26
+ description: "Markdown content to write (replaces entire document content)",
27
+ }),
28
+ }),
29
+ Type.Object({
30
+ action: Type.Literal("append"),
31
+ doc_token: Type.String({ description: "Document token" }),
32
+ content: Type.String({ description: "Markdown content to append to end of document" }),
33
+ }),
34
+ Type.Object({
35
+ action: Type.Literal("insert"),
36
+ doc_token: Type.String({ description: "Document token" }),
37
+ content: Type.String({ description: "Markdown content to insert" }),
38
+ after_block_id: Type.String({
39
+ description: "Insert content after this block ID. Use list_blocks to find block IDs.",
40
+ }),
41
+ }),
42
+ Type.Object({
43
+ action: Type.Literal("create"),
44
+ title: Type.String({ description: "Document title" }),
45
+ folder_token: Type.Optional(Type.String({ description: "Target folder token (optional)" })),
46
+ grant_to_requester: Type.Optional(
47
+ Type.Boolean({
48
+ description:
49
+ "Grant edit permission to the trusted requesting Feishu user from runtime context (default: true).",
50
+ }),
51
+ ),
52
+ }),
53
+ Type.Object({
54
+ action: Type.Literal("list_blocks"),
55
+ doc_token: Type.String({ description: "Document token" }),
56
+ }),
57
+ Type.Object({
58
+ action: Type.Literal("get_block"),
59
+ doc_token: Type.String({ description: "Document token" }),
60
+ block_id: Type.String({ description: "Block ID (from list_blocks)" }),
61
+ }),
62
+ Type.Object({
63
+ action: Type.Literal("update_block"),
64
+ doc_token: Type.String({ description: "Document token" }),
65
+ block_id: Type.String({ description: "Block ID (from list_blocks)" }),
66
+ content: Type.String({ description: "New text content" }),
67
+ }),
68
+ Type.Object({
69
+ action: Type.Literal("delete_block"),
70
+ doc_token: Type.String({ description: "Document token" }),
71
+ block_id: Type.String({ description: "Block ID" }),
72
+ }),
73
+ // Table creation (explicit structure)
74
+ Type.Object({
75
+ action: Type.Literal("create_table"),
76
+ ...tableCreationProperties,
77
+ }),
78
+ Type.Object({
79
+ action: Type.Literal("write_table_cells"),
80
+ doc_token: Type.String({ description: "Document token" }),
81
+ table_block_id: Type.String({ description: "Table block ID" }),
82
+ values: Type.Array(Type.Array(Type.String()), {
83
+ description: "2D matrix values[row][col] to write into table cells",
84
+ minItems: 1,
85
+ }),
86
+ }),
87
+ Type.Object({
88
+ action: Type.Literal("create_table_with_values"),
89
+ ...tableCreationProperties,
90
+ values: Type.Array(Type.Array(Type.String()), {
91
+ description: "2D matrix values[row][col] to write into table cells",
92
+ minItems: 1,
93
+ }),
94
+ }),
95
+ // Table row/column manipulation
96
+ Type.Object({
97
+ action: Type.Literal("insert_table_row"),
98
+ doc_token: Type.String({ description: "Document token" }),
99
+ block_id: Type.String({ description: "Table block ID" }),
100
+ row_index: Type.Optional(
101
+ Type.Number({ description: "Row index to insert at (-1 for end, default: -1)" }),
102
+ ),
103
+ }),
104
+ Type.Object({
105
+ action: Type.Literal("insert_table_column"),
106
+ doc_token: Type.String({ description: "Document token" }),
107
+ block_id: Type.String({ description: "Table block ID" }),
108
+ column_index: Type.Optional(
109
+ Type.Number({ description: "Column index to insert at (-1 for end, default: -1)" }),
110
+ ),
111
+ }),
112
+ Type.Object({
113
+ action: Type.Literal("delete_table_rows"),
114
+ doc_token: Type.String({ description: "Document token" }),
115
+ block_id: Type.String({ description: "Table block ID" }),
116
+ row_start: Type.Number({ description: "Start row index (0-based)" }),
117
+ row_count: Type.Optional(Type.Number({ description: "Number of rows to delete (default: 1)" })),
118
+ }),
119
+ Type.Object({
120
+ action: Type.Literal("delete_table_columns"),
121
+ doc_token: Type.String({ description: "Document token" }),
122
+ block_id: Type.String({ description: "Table block ID" }),
123
+ column_start: Type.Number({ description: "Start column index (0-based)" }),
124
+ column_count: Type.Optional(
125
+ Type.Number({ description: "Number of columns to delete (default: 1)" }),
126
+ ),
127
+ }),
128
+ Type.Object({
129
+ action: Type.Literal("merge_table_cells"),
130
+ doc_token: Type.String({ description: "Document token" }),
131
+ block_id: Type.String({ description: "Table block ID" }),
132
+ row_start: Type.Number({ description: "Start row index" }),
133
+ row_end: Type.Number({ description: "End row index (exclusive)" }),
134
+ column_start: Type.Number({ description: "Start column index" }),
135
+ column_end: Type.Number({ description: "End column index (exclusive)" }),
136
+ }),
137
+ // Image / file upload
138
+ Type.Object({
139
+ action: Type.Literal("upload_image"),
140
+ doc_token: Type.String({ description: "Document token" }),
141
+ url: Type.Optional(Type.String({ description: "Remote image URL (http/https)" })),
142
+ file_path: Type.Optional(Type.String({ description: "Local image file path" })),
143
+ image: Type.Optional(
144
+ Type.String({
145
+ description:
146
+ "Image as data URI (data:image/png;base64,...) or plain base64 string. Use instead of url/file_path for DALL-E outputs, canvas screenshots, etc.",
147
+ }),
148
+ ),
149
+ parent_block_id: Type.Optional(
150
+ Type.String({ description: "Parent block ID (default: document root)" }),
151
+ ),
152
+ filename: Type.Optional(Type.String({ description: "Optional filename override" })),
153
+ index: Type.Optional(
154
+ Type.Integer({
155
+ minimum: 0,
156
+ description: "Insert position (0-based index among siblings). Omit to append.",
157
+ }),
158
+ ),
159
+ }),
160
+ Type.Object({
161
+ action: Type.Literal("upload_file"),
162
+ doc_token: Type.String({ description: "Document token" }),
163
+ url: Type.Optional(Type.String({ description: "Remote file URL (http/https)" })),
164
+ file_path: Type.Optional(Type.String({ description: "Local file path" })),
165
+ parent_block_id: Type.Optional(
166
+ Type.String({ description: "Parent block ID (default: document root)" }),
167
+ ),
168
+ filename: Type.Optional(Type.String({ description: "Optional filename override" })),
169
+ }),
170
+ // Text color / style
171
+ Type.Object({
172
+ action: Type.Literal("color_text"),
173
+ doc_token: Type.String({ description: "Document token" }),
174
+ block_id: Type.String({ description: "Text block ID to update" }),
175
+ content: Type.String({
176
+ description:
177
+ 'Text with color markup. Tags: [red], [green], [blue], [orange], [yellow], [purple], [grey], [bold], [bg:yellow]. Example: "Revenue [green]+15%[/green] YoY"',
178
+ }),
179
+ }),
180
+ ]);
181
+
182
+ export type FeishuDocParams = Static<typeof FeishuDocSchema>;
@@ -0,0 +1,90 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { BATCH_SIZE, insertBlocksInBatches } from "./docx-batch-insert.js";
3
+
4
+ function createCountingIterable<T>(values: T[]) {
5
+ let iterations = 0;
6
+ return {
7
+ values: {
8
+ [Symbol.iterator]: function* () {
9
+ iterations += 1;
10
+ yield* values;
11
+ },
12
+ },
13
+ getIterations: () => iterations,
14
+ };
15
+ }
16
+
17
+ describe("insertBlocksInBatches", () => {
18
+ it("builds the source block map once for large flat trees", async () => {
19
+ const blockCount = BATCH_SIZE + 200;
20
+ const blocks = Array.from({ length: blockCount }, (_, index) => ({
21
+ block_id: `block_${index}`,
22
+ block_type: 2,
23
+ }));
24
+ const counting = createCountingIterable(blocks);
25
+ const createMock = vi.fn(async ({ data }: { data: { children_id: string[] } }) => ({
26
+ code: 0,
27
+ data: {
28
+ children: data.children_id.map((id) => ({ block_id: id })),
29
+ },
30
+ }));
31
+ const client = {
32
+ docx: {
33
+ documentBlockDescendant: {
34
+ create: createMock,
35
+ },
36
+ },
37
+ } as any;
38
+
39
+ const result = await insertBlocksInBatches(
40
+ client,
41
+ "doc_1",
42
+ counting.values as any[],
43
+ blocks.map((block) => block.block_id),
44
+ );
45
+
46
+ expect(counting.getIterations()).toBe(1);
47
+ expect(createMock).toHaveBeenCalledTimes(2);
48
+ expect(createMock.mock.calls[0]?.[0]?.data.children_id).toHaveLength(BATCH_SIZE);
49
+ expect(createMock.mock.calls[1]?.[0]?.data.children_id).toHaveLength(200);
50
+ expect(result.children).toHaveLength(blockCount);
51
+ });
52
+
53
+ it("keeps nested descendants grouped with their root blocks", async () => {
54
+ const createMock = vi.fn(
55
+ async ({
56
+ data,
57
+ }: {
58
+ data: { children_id: string[]; descendants: Array<{ block_id: string }> };
59
+ }) => ({
60
+ code: 0,
61
+ data: {
62
+ children: data.children_id.map((id) => ({ block_id: id })),
63
+ },
64
+ }),
65
+ );
66
+ const client = {
67
+ docx: {
68
+ documentBlockDescendant: {
69
+ create: createMock,
70
+ },
71
+ },
72
+ } as any;
73
+ const blocks = [
74
+ { block_id: "root_a", block_type: 1, children: ["child_a"] },
75
+ { block_id: "child_a", block_type: 2 },
76
+ { block_id: "root_b", block_type: 1, children: ["child_b"] },
77
+ { block_id: "child_b", block_type: 2 },
78
+ ];
79
+
80
+ await insertBlocksInBatches(client, "doc_1", blocks as any[], ["root_a", "root_b"]);
81
+
82
+ expect(createMock).toHaveBeenCalledTimes(1);
83
+ expect(createMock.mock.calls[0]?.[0]?.data.children_id).toEqual(["root_a", "root_b"]);
84
+ expect(
85
+ createMock.mock.calls[0]?.[0]?.data.descendants.map(
86
+ (block: { block_id: string }) => block.block_id,
87
+ ),
88
+ ).toEqual(["root_a", "child_a", "root_b", "child_b"]);
89
+ });
90
+ });