@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
@@ -1,447 +0,0 @@
1
- import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
2
- import { FeishuConfigSchema } from "./config-schema.js";
3
- import type { ResolvedFeishuAccount } from "./types.js";
4
-
5
- type CreateFeishuClient = typeof import("./client.js").createFeishuClient;
6
- type CreateFeishuWSClient = typeof import("./client.js").createFeishuWSClient;
7
- type ClearClientCache = typeof import("./client.js").clearClientCache;
8
- type SetFeishuClientRuntimeForTest = typeof import("./client.js").setFeishuClientRuntimeForTest;
9
-
10
- const clientCtorMock = vi.hoisted(() =>
11
- vi.fn(function clientCtor() {
12
- return { connected: true };
13
- }),
14
- );
15
- const wsClientCtorMock = vi.hoisted(() =>
16
- vi.fn(function wsClientCtor() {
17
- return { connected: true };
18
- }),
19
- );
20
- const proxyAgentCtorMock = vi.hoisted(() =>
21
- vi.fn(function createAmbientNodeProxyAgent() {
22
- return { proxied: true };
23
- }),
24
- );
25
- const mockBaseHttpInstance = vi.hoisted(() => ({
26
- request: vi.fn().mockResolvedValue({}),
27
- get: vi.fn().mockResolvedValue({}),
28
- post: vi.fn().mockResolvedValue({}),
29
- put: vi.fn().mockResolvedValue({}),
30
- patch: vi.fn().mockResolvedValue({}),
31
- delete: vi.fn().mockResolvedValue({}),
32
- head: vi.fn().mockResolvedValue({}),
33
- options: vi.fn().mockResolvedValue({}),
34
- }));
35
- const proxyEnvKeys = ["https_proxy", "HTTPS_PROXY", "http_proxy", "HTTP_PROXY"] as const;
36
- type ProxyEnvKey = (typeof proxyEnvKeys)[number];
37
- const registerFeishuDocToolsMock = vi.hoisted(() => vi.fn());
38
- const registerFeishuChatToolsMock = vi.hoisted(() => vi.fn());
39
- const registerFeishuWikiToolsMock = vi.hoisted(() => vi.fn());
40
- const registerFeishuDriveToolsMock = vi.hoisted(() => vi.fn());
41
- const registerFeishuPermToolsMock = vi.hoisted(() => vi.fn());
42
- const registerFeishuBitableToolsMock = vi.hoisted(() => vi.fn());
43
- const feishuPluginMock = vi.hoisted(() => ({ id: "feishu-test-plugin" }));
44
- const setFeishuRuntimeMock = vi.hoisted(() => vi.fn());
45
- const registerFeishuSubagentHooksMock = vi.hoisted(() => vi.fn());
46
-
47
- let createFeishuClient: CreateFeishuClient;
48
- let createFeishuWSClient: CreateFeishuWSClient;
49
- let clearClientCache: ClearClientCache;
50
- let setFeishuClientRuntimeForTest: SetFeishuClientRuntimeForTest;
51
- let FEISHU_HTTP_TIMEOUT_MS: number;
52
- let FEISHU_HTTP_TIMEOUT_MAX_MS: number;
53
- let FEISHU_HTTP_TIMEOUT_ENV_VAR: string;
54
-
55
- let priorProxyEnv: Partial<Record<ProxyEnvKey, string | undefined>> = {};
56
- let priorFeishuTimeoutEnv: string | undefined;
57
-
58
- vi.mock("./channel.js", () => ({
59
- feishuPlugin: feishuPluginMock,
60
- }));
61
-
62
- vi.mock("./docx.js", () => ({
63
- registerFeishuDocTools: registerFeishuDocToolsMock,
64
- }));
65
-
66
- vi.mock("./chat.js", () => ({
67
- registerFeishuChatTools: registerFeishuChatToolsMock,
68
- }));
69
-
70
- vi.mock("./wiki.js", () => ({
71
- registerFeishuWikiTools: registerFeishuWikiToolsMock,
72
- }));
73
-
74
- vi.mock("./drive.js", () => ({
75
- registerFeishuDriveTools: registerFeishuDriveToolsMock,
76
- }));
77
-
78
- vi.mock("./perm.js", () => ({
79
- registerFeishuPermTools: registerFeishuPermToolsMock,
80
- }));
81
-
82
- vi.mock("./bitable.js", () => ({
83
- registerFeishuBitableTools: registerFeishuBitableToolsMock,
84
- }));
85
-
86
- vi.mock("./runtime.js", () => ({
87
- setFeishuRuntime: setFeishuRuntimeMock,
88
- }));
89
-
90
- vi.mock("./subagent-hooks.js", () => ({
91
- registerFeishuSubagentHooks: registerFeishuSubagentHooksMock,
92
- }));
93
-
94
- const baseAccount: ResolvedFeishuAccount = {
95
- accountId: "main",
96
- selectionSource: "explicit",
97
- enabled: true,
98
- configured: true,
99
- appId: "app_123",
100
- appSecret: "secret_123", // pragma: allowlist secret
101
- domain: "feishu",
102
- config: FeishuConfigSchema.parse({}),
103
- };
104
-
105
- function isRecord(value: unknown): value is Record<string, unknown> {
106
- return typeof value === "object" && value !== null;
107
- }
108
-
109
- type HttpInstanceLike = {
110
- get: (url: string, options?: Record<string, unknown>) => Promise<unknown>;
111
- post: (url: string, body?: unknown, options?: Record<string, unknown>) => Promise<unknown>;
112
- };
113
-
114
- function requireHttpInstance(value: unknown): HttpInstanceLike {
115
- if (isRecord(value) && typeof value.get === "function" && typeof value.post === "function") {
116
- return {
117
- get: value.get as HttpInstanceLike["get"],
118
- post: value.post as HttpInstanceLike["post"],
119
- };
120
- }
121
- throw new Error("expected Feishu HTTP instance");
122
- }
123
-
124
- function readCallOptions(
125
- mock: { mock: { calls: unknown[][] } },
126
- index = -1,
127
- ): Record<string, unknown> {
128
- const call = index < 0 ? mock.mock.calls.at(index)?.[0] : mock.mock.calls[index]?.[0];
129
- return isRecord(call) ? call : {};
130
- }
131
-
132
- function firstWsClientOptions(): {
133
- agent?: unknown;
134
- wsConfig?: unknown;
135
- onError?: unknown;
136
- onReady?: unknown;
137
- onReconnected?: unknown;
138
- onReconnecting?: unknown;
139
- } {
140
- const options = readCallOptions(wsClientCtorMock, 0);
141
- return {
142
- agent: options.agent,
143
- wsConfig: options.wsConfig,
144
- onError: options.onError,
145
- onReady: options.onReady,
146
- onReconnected: options.onReconnected,
147
- onReconnecting: options.onReconnecting,
148
- };
149
- }
150
-
151
- beforeAll(async () => {
152
- vi.doMock("@larksuiteoapi/node-sdk", () => ({
153
- AppType: { SelfBuild: "self" },
154
- Domain: { Feishu: "https://open.feishu.cn", Lark: "https://open.larksuite.com" },
155
- LoggerLevel: { info: "info" },
156
- Client: clientCtorMock,
157
- WSClient: wsClientCtorMock,
158
- EventDispatcher: vi.fn(),
159
- defaultHttpInstance: mockBaseHttpInstance,
160
- }));
161
- vi.doMock("@kodelyth/proxyline", () => ({
162
- createAmbientNodeProxyAgent: proxyAgentCtorMock,
163
- hasAmbientNodeProxyConfigured: vi.fn(() =>
164
- Boolean(
165
- process.env.HTTPS_PROXY ??
166
- process.env.https_proxy ??
167
- process.env.HTTP_PROXY ??
168
- process.env.http_proxy,
169
- ),
170
- ),
171
- }));
172
-
173
- ({
174
- createFeishuClient,
175
- createFeishuWSClient,
176
- clearClientCache,
177
- setFeishuClientRuntimeForTest,
178
- FEISHU_HTTP_TIMEOUT_MS,
179
- FEISHU_HTTP_TIMEOUT_MAX_MS,
180
- FEISHU_HTTP_TIMEOUT_ENV_VAR,
181
- } = await import("./client.js"));
182
- });
183
-
184
- beforeEach(() => {
185
- priorProxyEnv = {};
186
- priorFeishuTimeoutEnv = process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR];
187
- delete process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR];
188
- for (const key of proxyEnvKeys) {
189
- priorProxyEnv[key] = process.env[key];
190
- delete process.env[key];
191
- }
192
- vi.clearAllMocks();
193
- clearClientCache();
194
- setFeishuClientRuntimeForTest({
195
- sdk: {
196
- AppType: { SelfBuild: "self" } as never,
197
- Domain: {
198
- Feishu: "https://open.feishu.cn",
199
- Lark: "https://open.larksuite.com",
200
- } as never,
201
- LoggerLevel: { info: "info" } as never,
202
- Client: clientCtorMock as never,
203
- WSClient: wsClientCtorMock as never,
204
- EventDispatcher: vi.fn() as never,
205
- defaultHttpInstance: mockBaseHttpInstance as never,
206
- },
207
- });
208
- });
209
-
210
- afterEach(() => {
211
- for (const key of proxyEnvKeys) {
212
- const value = priorProxyEnv[key];
213
- if (value === undefined) {
214
- delete process.env[key];
215
- } else {
216
- process.env[key] = value;
217
- }
218
- }
219
- if (priorFeishuTimeoutEnv === undefined) {
220
- delete process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR];
221
- } else {
222
- process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR] = priorFeishuTimeoutEnv;
223
- }
224
- setFeishuClientRuntimeForTest();
225
- });
226
-
227
- afterAll(() => {
228
- vi.doUnmock("./channel.js");
229
- vi.doUnmock("./docx.js");
230
- vi.doUnmock("./chat.js");
231
- vi.doUnmock("./wiki.js");
232
- vi.doUnmock("./drive.js");
233
- vi.doUnmock("./perm.js");
234
- vi.doUnmock("./bitable.js");
235
- vi.doUnmock("./runtime.js");
236
- vi.doUnmock("./subagent-hooks.js");
237
- vi.doUnmock("@larksuiteoapi/node-sdk");
238
- vi.doUnmock("@kodelyth/proxyline");
239
- vi.resetModules();
240
- });
241
-
242
- describe("createFeishuClient HTTP timeout", () => {
243
- const readLastClientHttpInstance = (): HttpInstanceLike =>
244
- requireHttpInstance(readCallOptions(clientCtorMock).httpInstance);
245
-
246
- const expectGetCallTimeout = async (timeout: number) => {
247
- const httpInstance = readLastClientHttpInstance();
248
- await httpInstance.get("https://example.com/api");
249
- expect(mockBaseHttpInstance.get).toHaveBeenCalledWith("https://example.com/api", { timeout });
250
- };
251
-
252
- it("passes a custom httpInstance with default timeout to Lark.Client", () => {
253
- createFeishuClient({ appId: "app_1", appSecret: "secret_1", accountId: "timeout-test" }); // pragma: allowlist secret
254
-
255
- const httpInstance = readLastClientHttpInstance();
256
- expect(typeof httpInstance.get).toBe("function");
257
- expect(typeof httpInstance.post).toBe("function");
258
- });
259
-
260
- it("injects default timeout into HTTP request options", async () => {
261
- createFeishuClient({ appId: "app_2", appSecret: "secret_2", accountId: "timeout-inject" }); // pragma: allowlist secret
262
-
263
- const httpInstance = readLastClientHttpInstance();
264
-
265
- await httpInstance.post(
266
- "https://example.com/api",
267
- { data: 1 },
268
- { headers: { "X-Custom": "yes" } },
269
- );
270
-
271
- expect(mockBaseHttpInstance.post).toHaveBeenCalledWith(
272
- "https://example.com/api",
273
- { data: 1 },
274
- { timeout: FEISHU_HTTP_TIMEOUT_MS, headers: { "X-Custom": "yes" } },
275
- );
276
- });
277
-
278
- it("allows explicit timeout override per-request", async () => {
279
- createFeishuClient({ appId: "app_3", appSecret: "secret_3", accountId: "timeout-override" }); // pragma: allowlist secret
280
-
281
- const httpInstance = readLastClientHttpInstance();
282
-
283
- await httpInstance.get("https://example.com/api", { timeout: 5_000 });
284
-
285
- expect(mockBaseHttpInstance.get).toHaveBeenCalledWith("https://example.com/api", {
286
- timeout: 5_000,
287
- });
288
- });
289
-
290
- it("uses config-configured default timeout when provided", async () => {
291
- createFeishuClient({
292
- appId: "app_4",
293
- appSecret: "secret_4", // pragma: allowlist secret
294
- accountId: "timeout-config",
295
- config: { httpTimeoutMs: 45_000 },
296
- });
297
-
298
- await expectGetCallTimeout(45_000);
299
- });
300
-
301
- it("falls back to default timeout when configured timeout is invalid", async () => {
302
- createFeishuClient({
303
- appId: "app_5",
304
- appSecret: "secret_5", // pragma: allowlist secret
305
- accountId: "timeout-config-invalid",
306
- config: { httpTimeoutMs: -1 },
307
- });
308
-
309
- await expectGetCallTimeout(FEISHU_HTTP_TIMEOUT_MS);
310
- });
311
-
312
- it("uses env timeout override when provided and no direct timeout is set", async () => {
313
- process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR] = "60000";
314
-
315
- createFeishuClient({
316
- appId: "app_8",
317
- appSecret: "secret_8", // pragma: allowlist secret
318
- accountId: "timeout-env-override",
319
- config: { httpTimeoutMs: 45_000 },
320
- });
321
-
322
- await expectGetCallTimeout(60_000);
323
- });
324
-
325
- it("prefers direct timeout over env override", async () => {
326
- process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR] = "60000";
327
-
328
- createFeishuClient({
329
- appId: "app_10",
330
- appSecret: "secret_10", // pragma: allowlist secret
331
- accountId: "timeout-direct-override",
332
- httpTimeoutMs: 120_000,
333
- config: { httpTimeoutMs: 45_000 },
334
- });
335
-
336
- await expectGetCallTimeout(120_000);
337
- });
338
-
339
- it("clamps env timeout override to max bound", async () => {
340
- process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR] = String(FEISHU_HTTP_TIMEOUT_MAX_MS + 123_456);
341
-
342
- createFeishuClient({
343
- appId: "app_9",
344
- appSecret: "secret_9", // pragma: allowlist secret
345
- accountId: "timeout-env-clamp",
346
- });
347
-
348
- await expectGetCallTimeout(FEISHU_HTTP_TIMEOUT_MAX_MS);
349
- });
350
-
351
- it("recreates cached client when configured timeout changes", async () => {
352
- createFeishuClient({
353
- appId: "app_6",
354
- appSecret: "secret_6", // pragma: allowlist secret
355
- accountId: "timeout-cache-change",
356
- config: { httpTimeoutMs: 30_000 },
357
- });
358
- createFeishuClient({
359
- appId: "app_6",
360
- appSecret: "secret_6", // pragma: allowlist secret
361
- accountId: "timeout-cache-change",
362
- config: { httpTimeoutMs: 45_000 },
363
- });
364
-
365
- expect(clientCtorMock.mock.calls.length).toBe(2);
366
- const httpInstance = readLastClientHttpInstance();
367
- await httpInstance.get("https://example.com/api");
368
-
369
- expect(mockBaseHttpInstance.get).toHaveBeenCalledWith("https://example.com/api", {
370
- timeout: 45_000,
371
- });
372
- });
373
- });
374
-
375
- describe("createFeishuWSClient proxy handling", () => {
376
- it("passes heartbeat wsConfig defaults to Lark.WSClient", async () => {
377
- await createFeishuWSClient(baseAccount);
378
-
379
- const options = firstWsClientOptions();
380
- expect(options.wsConfig).toEqual({
381
- PingInterval: 30,
382
- PingTimeout: 3,
383
- });
384
- });
385
-
386
- it("passes lifecycle callbacks while preserving heartbeat wsConfig defaults", async () => {
387
- const onError = vi.fn();
388
- const onReady = vi.fn();
389
- const onReconnected = vi.fn();
390
- const onReconnecting = vi.fn();
391
-
392
- await createFeishuWSClient(baseAccount, {
393
- onError,
394
- onReady,
395
- onReconnected,
396
- onReconnecting,
397
- });
398
-
399
- const options = firstWsClientOptions();
400
- expect(options.onError).toBe(onError);
401
- expect(options.onReady).toBe(onReady);
402
- expect(options.onReconnected).toBe(onReconnected);
403
- expect(options.onReconnecting).toBe(onReconnecting);
404
- expect(options.wsConfig).toEqual({
405
- PingInterval: 30,
406
- PingTimeout: 3,
407
- });
408
- });
409
-
410
- it("does not set a ws proxy agent when proxy env is absent", async () => {
411
- await createFeishuWSClient(baseAccount);
412
-
413
- expect(proxyAgentCtorMock).not.toHaveBeenCalled();
414
- const options = firstWsClientOptions();
415
- expect(options.agent).toBeUndefined();
416
- });
417
-
418
- it("creates a ws proxy agent when lowercase https_proxy is set", async () => {
419
- process.env.https_proxy = "http://lower-https:8001";
420
-
421
- await createFeishuWSClient(baseAccount);
422
-
423
- expect(proxyAgentCtorMock).toHaveBeenCalledTimes(1);
424
- const options = firstWsClientOptions();
425
- expect(options.agent).toEqual({ proxied: true });
426
- });
427
-
428
- it("creates a ws proxy agent when uppercase HTTPS_PROXY is set", async () => {
429
- process.env.HTTPS_PROXY = "http://upper-https:8002";
430
-
431
- await createFeishuWSClient(baseAccount);
432
-
433
- expect(proxyAgentCtorMock).toHaveBeenCalledTimes(1);
434
- const options = firstWsClientOptions();
435
- expect(options.agent).toEqual({ proxied: true });
436
- });
437
-
438
- it("falls back to HTTP_PROXY for ws proxy agent creation", async () => {
439
- process.env.HTTP_PROXY = "http://upper-http:8999";
440
-
441
- await createFeishuWSClient(baseAccount);
442
-
443
- expect(proxyAgentCtorMock).toHaveBeenCalledTimes(1);
444
- const options = firstWsClientOptions();
445
- expect(options.agent).toEqual({ proxied: true });
446
- });
447
- });
package/src/client.ts DELETED
@@ -1,262 +0,0 @@
1
- import type { Agent } from "node:https";
2
- import { createRequire } from "node:module";
3
- import * as Lark from "@larksuiteoapi/node-sdk";
4
- import {
5
- readPluginPackageVersion,
6
- resolveAmbientNodeProxyAgent,
7
- } from "klaw/plugin-sdk/extension-shared";
8
- import {
9
- FEISHU_HTTP_TIMEOUT_ENV_VAR,
10
- FEISHU_HTTP_TIMEOUT_MAX_MS,
11
- FEISHU_HTTP_TIMEOUT_MS,
12
- resolveConfiguredHttpTimeoutMs,
13
- } from "./client-timeout.js";
14
- import type { FeishuConfig, FeishuDomain, ResolvedFeishuAccount } from "./types.js";
15
-
16
- const require = createRequire(import.meta.url);
17
- const pluginVersion = readPluginPackageVersion({ require });
18
-
19
- export { pluginVersion };
20
-
21
- const FEISHU_USER_AGENT = `klaw-feishu-builtin/${pluginVersion}/${process.platform}`;
22
- export { FEISHU_USER_AGENT };
23
-
24
- const FEISHU_WS_CONFIG = {
25
- PingInterval: 30,
26
- PingTimeout: 3,
27
- } as const;
28
-
29
- /** User-Agent header value for all Feishu API requests. */
30
- export function getFeishuUserAgent(): string {
31
- return FEISHU_USER_AGENT;
32
- }
33
-
34
- type FeishuClientSdk = Pick<
35
- typeof Lark,
36
- | "AppType"
37
- | "Client"
38
- | "defaultHttpInstance"
39
- | "Domain"
40
- | "EventDispatcher"
41
- | "LoggerLevel"
42
- | "WSClient"
43
- >;
44
-
45
- const defaultFeishuClientSdk: FeishuClientSdk = {
46
- AppType: Lark.AppType,
47
- Client: Lark.Client,
48
- defaultHttpInstance: Lark.defaultHttpInstance,
49
- Domain: Lark.Domain,
50
- EventDispatcher: Lark.EventDispatcher,
51
- LoggerLevel: Lark.LoggerLevel,
52
- WSClient: Lark.WSClient,
53
- };
54
-
55
- let feishuClientSdk: FeishuClientSdk = defaultFeishuClientSdk;
56
-
57
- // Override the SDK's default User-Agent interceptor.
58
- // The Lark SDK registers an axios request interceptor that sets
59
- // 'oapi-node-sdk/1.0.0'. Axios request interceptors execute in LIFO order
60
- // (last-registered runs first), so simply appending ours doesn't work — the
61
- // SDK's interceptor would run last and overwrite our UA. We must clear
62
- // handlers[] first, then register our own as the sole interceptor.
63
- //
64
- // Risk is low: the SDK only registers one interceptor (UA) at init time, and
65
- // we clear it at module load before any other code can register handlers.
66
- // If a future SDK version adds more interceptors, the upgrade will need
67
- // compatibility verification regardless.
68
- {
69
- const inst = Lark.defaultHttpInstance as {
70
- interceptors?: {
71
- request: { handlers: unknown[]; use: (fn: (req: unknown) => unknown) => void };
72
- };
73
- };
74
- if (inst.interceptors?.request) {
75
- inst.interceptors.request.handlers = [];
76
- inst.interceptors.request.use((req: unknown) => {
77
- const r = req as { headers?: Record<string, string> };
78
- if (r.headers) {
79
- r.headers["User-Agent"] = getFeishuUserAgent();
80
- }
81
- return req;
82
- });
83
- }
84
- }
85
-
86
- export { FEISHU_HTTP_TIMEOUT_ENV_VAR, FEISHU_HTTP_TIMEOUT_MAX_MS, FEISHU_HTTP_TIMEOUT_MS };
87
-
88
- type FeishuHttpInstanceLike = Pick<
89
- typeof feishuClientSdk.defaultHttpInstance,
90
- "request" | "get" | "post" | "put" | "patch" | "delete" | "head" | "options"
91
- >;
92
-
93
- async function getWsProxyAgent() {
94
- return resolveAmbientNodeProxyAgent<Agent>();
95
- }
96
-
97
- // Multi-account client cache
98
- const clientCache = new Map<
99
- string,
100
- {
101
- client: Lark.Client;
102
- config: { appId: string; appSecret: string; domain?: FeishuDomain; httpTimeoutMs: number };
103
- }
104
- >();
105
-
106
- function resolveDomain(domain: FeishuDomain | undefined): Lark.Domain | string {
107
- if (domain === "lark") {
108
- return feishuClientSdk.Domain.Lark;
109
- }
110
- if (domain === "feishu" || !domain) {
111
- return feishuClientSdk.Domain.Feishu;
112
- }
113
- return domain.replace(/\/+$/, ""); // Custom URL for private deployment
114
- }
115
-
116
- /**
117
- * Create an HTTP instance that delegates to the Lark SDK's default instance
118
- * but injects a default request timeout and User-Agent header to prevent
119
- * indefinite hangs and set a standardized User-Agent per OAPI best practices.
120
- */
121
- function createTimeoutHttpInstance(defaultTimeoutMs: number): Lark.HttpInstance {
122
- const base: FeishuHttpInstanceLike = feishuClientSdk.defaultHttpInstance;
123
-
124
- function injectTimeout<D>(opts?: Lark.HttpRequestOptions<D>): Lark.HttpRequestOptions<D> {
125
- return { timeout: defaultTimeoutMs, ...opts } as Lark.HttpRequestOptions<D>;
126
- }
127
-
128
- return {
129
- request: (opts) => base.request(injectTimeout(opts)),
130
- get: (url, opts) => base.get(url, injectTimeout(opts)),
131
- post: (url, data, opts) => base.post(url, data, injectTimeout(opts)),
132
- put: (url, data, opts) => base.put(url, data, injectTimeout(opts)),
133
- patch: (url, data, opts) => base.patch(url, data, injectTimeout(opts)),
134
- delete: (url, opts) => base.delete(url, injectTimeout(opts)),
135
- head: (url, opts) => base.head(url, injectTimeout(opts)),
136
- options: (url, opts) => base.options(url, injectTimeout(opts)),
137
- };
138
- }
139
-
140
- /**
141
- * Credentials needed to create a Feishu client.
142
- * Both FeishuConfig and ResolvedFeishuAccount satisfy this interface.
143
- */
144
- export type FeishuClientCredentials = {
145
- accountId?: string;
146
- appId?: string;
147
- appSecret?: string;
148
- domain?: FeishuDomain;
149
- httpTimeoutMs?: number;
150
- config?: Pick<FeishuConfig, "httpTimeoutMs">;
151
- };
152
-
153
- /**
154
- * Create or get a cached Feishu client for an account.
155
- * Accepts any object with appId, appSecret, and optional domain/accountId.
156
- */
157
- export function createFeishuClient(creds: FeishuClientCredentials): Lark.Client {
158
- const { accountId = "default", appId, appSecret, domain } = creds;
159
- const defaultHttpTimeoutMs = resolveConfiguredHttpTimeoutMs(creds);
160
-
161
- if (!appId || !appSecret) {
162
- throw new Error(`Feishu credentials not configured for account "${accountId}"`);
163
- }
164
-
165
- // Check cache
166
- const cached = clientCache.get(accountId);
167
- if (
168
- cached &&
169
- cached.config.appId === appId &&
170
- cached.config.appSecret === appSecret &&
171
- cached.config.domain === domain &&
172
- cached.config.httpTimeoutMs === defaultHttpTimeoutMs
173
- ) {
174
- return cached.client;
175
- }
176
-
177
- // Create new client with timeout-aware HTTP instance
178
- const client = new feishuClientSdk.Client({
179
- appId,
180
- appSecret,
181
- appType: feishuClientSdk.AppType.SelfBuild,
182
- domain: resolveDomain(domain),
183
- httpInstance: createTimeoutHttpInstance(defaultHttpTimeoutMs),
184
- });
185
-
186
- // Cache it
187
- clientCache.set(accountId, {
188
- client,
189
- config: { appId, appSecret, domain, httpTimeoutMs: defaultHttpTimeoutMs },
190
- });
191
-
192
- return client;
193
- }
194
-
195
- export type FeishuWsClientCallbacks = Pick<
196
- ConstructorParameters<typeof feishuClientSdk.WSClient>[0],
197
- "onError" | "onReady" | "onReconnected" | "onReconnecting"
198
- >;
199
-
200
- /**
201
- * Create a Feishu WebSocket client for an account.
202
- * Note: WSClient is not cached since each call creates a new connection.
203
- */
204
- export async function createFeishuWSClient(
205
- account: ResolvedFeishuAccount,
206
- callbacks: FeishuWsClientCallbacks = {},
207
- ): Promise<Lark.WSClient> {
208
- const { accountId, appId, appSecret, domain } = account;
209
-
210
- if (!appId || !appSecret) {
211
- throw new Error(`Feishu credentials not configured for account "${accountId}"`);
212
- }
213
-
214
- const agent = await getWsProxyAgent();
215
- return new feishuClientSdk.WSClient({
216
- appId,
217
- appSecret,
218
- domain: resolveDomain(domain),
219
- ...callbacks,
220
- loggerLevel: feishuClientSdk.LoggerLevel.info,
221
- wsConfig: FEISHU_WS_CONFIG,
222
- ...(agent ? { agent } : {}),
223
- } as ConstructorParameters<typeof feishuClientSdk.WSClient>[0] & {
224
- wsConfig: typeof FEISHU_WS_CONFIG;
225
- });
226
- }
227
-
228
- /**
229
- * Create an event dispatcher for an account.
230
- */
231
- export function createEventDispatcher(account: ResolvedFeishuAccount): Lark.EventDispatcher {
232
- return new feishuClientSdk.EventDispatcher({
233
- encryptKey: account.encryptKey,
234
- verificationToken: account.verificationToken,
235
- });
236
- }
237
-
238
- /**
239
- * Get a cached client for an account (if exists).
240
- */
241
- export function getFeishuClient(accountId: string): Lark.Client | null {
242
- return clientCache.get(accountId)?.client ?? null;
243
- }
244
-
245
- /**
246
- * Clear client cache for a specific account or all accounts.
247
- */
248
- export function clearClientCache(accountId?: string): void {
249
- if (accountId) {
250
- clientCache.delete(accountId);
251
- } else {
252
- clientCache.clear();
253
- }
254
- }
255
-
256
- export function setFeishuClientRuntimeForTest(overrides?: {
257
- sdk?: Partial<FeishuClientSdk>;
258
- }): void {
259
- feishuClientSdk = overrides?.sdk
260
- ? { ...defaultFeishuClientSdk, ...overrides.sdk }
261
- : defaultFeishuClientSdk;
262
- }