@zhin.js/adapter-lark 1.0.96 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +641 -0
- package/README.md +70 -83
- package/adapters/lark.js +36 -0
- package/adapters/lark.ts +41 -0
- package/agent/PERMITS.md +22 -0
- package/agent/tools/add_members.ts +20 -0
- package/agent/tools/create_chat.ts +18 -0
- package/agent/tools/dissolve_chat.ts +16 -0
- package/agent/tools/get_user.ts +16 -0
- package/agent/tools/remove_managers.ts +20 -0
- package/agent/tools/set_managers.ts +20 -0
- package/agent/tools/update_chat.ts +21 -0
- package/agent/tools/upload_file.ts +23 -0
- package/commands/endpoint/add/[id].js +3 -0
- package/commands/endpoint/add/[id].ts +3 -0
- package/commands/endpoint/list.js +3 -0
- package/commands/endpoint/list.ts +3 -0
- package/commands/endpoint/remove/[id].js +3 -0
- package/commands/endpoint/remove/[id].ts +3 -0
- package/lib/client.d.ts +12 -0
- package/lib/client.js +2 -0
- package/lib/endpoint.d.ts +100 -0
- package/lib/endpoint.js +497 -0
- package/lib/index.d.ts +6 -15
- package/lib/index.js +6 -209
- package/lib/lark-endpoint-commands.d.ts +1 -0
- package/lib/lark-endpoint-commands.js +19 -0
- package/lib/lark-runtime-state.d.ts +1 -0
- package/lib/lark-runtime-state.js +6 -0
- package/lib/media-upload.d.ts +15 -0
- package/lib/media-upload.js +58 -0
- package/lib/platform-permit.d.ts +14 -0
- package/lib/platform-permit.js +35 -0
- package/lib/protocol.d.ts +123 -0
- package/lib/protocol.js +273 -0
- package/lib/webhook.d.ts +14 -0
- package/lib/webhook.js +73 -0
- package/package.json +63 -20
- package/plugin.js +19 -0
- package/schema.json +97 -0
- package/src/client.ts +16 -0
- package/src/endpoint.ts +590 -0
- package/src/index.ts +51 -227
- package/src/lark-endpoint-commands.ts +20 -0
- package/src/lark-runtime-state.ts +7 -0
- package/src/media-upload.ts +69 -0
- package/src/platform-permit.ts +50 -0
- package/src/protocol.ts +402 -0
- package/src/webhook.ts +110 -0
- package/lib/adapter.d.ts +0 -17
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -45
- package/lib/adapter.js.map +0 -1
- package/lib/bot.d.ts +0 -82
- package/lib/bot.d.ts.map +0 -1
- package/lib/bot.js +0 -638
- package/lib/bot.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/types.d.ts +0 -63
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js +0 -2
- package/lib/types.js.map +0 -1
- package/plugin.yml +0 -3
- package/src/adapter.ts +0 -55
- package/src/bot.ts +0 -712
- package/src/types.ts +0 -58
- /package/{skills/lark/SKILL.md → agent/skills/lark.md} +0 -0
package/src/endpoint.ts
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
import { Endpoint } from 'zhin.js/adapter';
|
|
2
|
+
/**
|
|
3
|
+
* LarkEndpoint — lifecycle, outbound, admit, OpenAPI helpers for agent tools.
|
|
4
|
+
*/
|
|
5
|
+
import { readFile } from 'node:fs/promises';
|
|
6
|
+
import { basename } from 'node:path';
|
|
7
|
+
import {
|
|
8
|
+
createRecallEndpointControl,
|
|
9
|
+
type EndpointControl,
|
|
10
|
+
type EndpointGroup,
|
|
11
|
+
type EndpointManagement,
|
|
12
|
+
type EndpointSendRequest,
|
|
13
|
+
} from 'zhin.js/adapter';
|
|
14
|
+
import type { HttpHost, HttpRouteRegistration } from '@zhin.js/host-http';
|
|
15
|
+
import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
|
|
16
|
+
import type { CapabilityId } from 'zhin.js';
|
|
17
|
+
import {
|
|
18
|
+
buildImageUploadForm,
|
|
19
|
+
readOutboundImageMedia,
|
|
20
|
+
resolveMediaBinary,
|
|
21
|
+
} from './media-upload.js';
|
|
22
|
+
import {
|
|
23
|
+
formatInboundContent,
|
|
24
|
+
formatOutboundBody,
|
|
25
|
+
generateMessageId,
|
|
26
|
+
larkInboundConversation,
|
|
27
|
+
resolveChatType,
|
|
28
|
+
resolveSender,
|
|
29
|
+
type AccessToken,
|
|
30
|
+
type LarkApiResponse,
|
|
31
|
+
type LarkMessage,
|
|
32
|
+
type ResolvedLarkConfig,
|
|
33
|
+
} from './protocol.js';
|
|
34
|
+
import { registerLarkWebhookRoutes } from './webhook.js';
|
|
35
|
+
|
|
36
|
+
/** 出站 HTTP 调用统一 30s 超时。 */
|
|
37
|
+
const OUTBOUND_TIMEOUT_MS = 30_000;
|
|
38
|
+
|
|
39
|
+
export type LarkFetch = (
|
|
40
|
+
url: string,
|
|
41
|
+
init?: {
|
|
42
|
+
readonly method?: string;
|
|
43
|
+
readonly headers?: Record<string, string>;
|
|
44
|
+
readonly body?: string | FormData;
|
|
45
|
+
readonly signal?: AbortSignal;
|
|
46
|
+
},
|
|
47
|
+
) => Promise<{
|
|
48
|
+
readonly ok: boolean;
|
|
49
|
+
readonly status: number;
|
|
50
|
+
text(): Promise<string>;
|
|
51
|
+
json(): Promise<unknown>;
|
|
52
|
+
}>;
|
|
53
|
+
|
|
54
|
+
export interface LarkEndpointOptions {
|
|
55
|
+
readonly id: CapabilityId;
|
|
56
|
+
readonly http: HttpHost;
|
|
57
|
+
readonly config: ResolvedLarkConfig;
|
|
58
|
+
readonly fetch?: LarkFetch;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface LarkClientApi {
|
|
62
|
+
getUserInfo(userId: string, userIdType?: 'open_id' | 'user_id' | 'union_id'): Promise<unknown>;
|
|
63
|
+
getChatInfo(chatId: string): Promise<unknown>;
|
|
64
|
+
uploadFile(filePath: string, fileType?: 'image' | 'file' | 'video' | 'audio'): Promise<string | null>;
|
|
65
|
+
createChat(name: string, userIds: string[], ownerId?: string): Promise<string | null>;
|
|
66
|
+
updateChatInfo(chatId: string, options: { name?: string; description?: string }): Promise<boolean>;
|
|
67
|
+
addChatMembers(chatId: string, userIds: string[]): Promise<boolean>;
|
|
68
|
+
removeChatMembers(chatId: string, userIds: string[]): Promise<boolean>;
|
|
69
|
+
getChatMembers(chatId: string): Promise<unknown[]>;
|
|
70
|
+
dissolveChat(chatId: string): Promise<boolean>;
|
|
71
|
+
setChatManagers(chatId: string, userIds: string[]): Promise<boolean>;
|
|
72
|
+
removeChatManagers(chatId: string, userIds: string[]): Promise<boolean>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Feishu/Lark OpenAPI client surface carried by every Endpoint event. */
|
|
76
|
+
export class LarkClient implements LarkClientApi {
|
|
77
|
+
constructor(readonly api: LarkClientApi) {}
|
|
78
|
+
getUserInfo = (id: string, type?: 'open_id' | 'user_id' | 'union_id') =>
|
|
79
|
+
this.api.getUserInfo(id, type);
|
|
80
|
+
getChatInfo = (id: string) => this.api.getChatInfo(id);
|
|
81
|
+
uploadFile = (path: string, type?: 'image' | 'file' | 'video' | 'audio') =>
|
|
82
|
+
this.api.uploadFile(path, type);
|
|
83
|
+
createChat = (name: string, users: string[], owner?: string) =>
|
|
84
|
+
this.api.createChat(name, users, owner);
|
|
85
|
+
updateChatInfo = (id: string, options: { name?: string; description?: string }) =>
|
|
86
|
+
this.api.updateChatInfo(id, options);
|
|
87
|
+
addChatMembers = (id: string, users: string[]) => this.api.addChatMembers(id, users);
|
|
88
|
+
removeChatMembers = (id: string, users: string[]) => this.api.removeChatMembers(id, users);
|
|
89
|
+
getChatMembers = (id: string) => this.api.getChatMembers(id);
|
|
90
|
+
dissolveChat = (id: string) => this.api.dissolveChat(id);
|
|
91
|
+
setChatManagers = (id: string, users: string[]) => this.api.setChatManagers(id, users);
|
|
92
|
+
removeChatManagers = (id: string, users: string[]) => this.api.removeChatManagers(id, users);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export class LarkEndpoint extends Endpoint<LarkClient> {
|
|
96
|
+
readonly client = new LarkClient({
|
|
97
|
+
getUserInfo: (id, type) => this.getUserInfo(id, type),
|
|
98
|
+
getChatInfo: (id) => this.getChatInfo(id),
|
|
99
|
+
uploadFile: (path, type) => this.uploadFile(path, type),
|
|
100
|
+
createChat: (name, users, owner) => this.createChat(name, users, owner),
|
|
101
|
+
updateChatInfo: (id, options) => this.updateChatInfo(id, options),
|
|
102
|
+
addChatMembers: (id, users) => this.addChatMembers(id, users),
|
|
103
|
+
removeChatMembers: (id, users) => this.removeChatMembers(id, users),
|
|
104
|
+
getChatMembers: (id) => this.getChatMembers(id),
|
|
105
|
+
dissolveChat: (id) => this.dissolveChat(id),
|
|
106
|
+
setChatManagers: (id, users) => this.setChatManagers(id, users),
|
|
107
|
+
removeChatManagers: (id, users) => this.removeChatManagers(id, users),
|
|
108
|
+
});
|
|
109
|
+
readonly #logger!: ReturnType<typeof getAdapterLogger>;
|
|
110
|
+
|
|
111
|
+
readonly #options: LarkEndpointOptions;
|
|
112
|
+
readonly #fetch: LarkFetch;
|
|
113
|
+
/**
|
|
114
|
+
* Console 社交面语义端口。Lark OpenAPI 仅接读取类列表能力:
|
|
115
|
+
* - listGroups:GET /im/v1/chats(bot 所在群列表,分页归一为 {group_id: chat_id, name})
|
|
116
|
+
* - listGroupMembers:GET /im/v1/chats/:chat_id/members(open_id 分页,返回平台原生成员形状)
|
|
117
|
+
* 不接的项:listFriends(Lark 无好友概念,contact API 为组织通讯录而非社交关系)、
|
|
118
|
+
* listChannels(无频道/guild 概念)、写操作(审批/踢人/禁言等本轮不在范围内)。
|
|
119
|
+
*/
|
|
120
|
+
readonly management: EndpointManagement = Object.freeze<EndpointManagement>({
|
|
121
|
+
listGroups: async (): Promise<readonly EndpointGroup[]> => {
|
|
122
|
+
const items = await this.#listAllPages('/im/v1/chats');
|
|
123
|
+
const groups: EndpointGroup[] = [];
|
|
124
|
+
for (const item of items) {
|
|
125
|
+
const chatId = typeof item.chat_id === 'string' ? item.chat_id : '';
|
|
126
|
+
if (!chatId) continue;
|
|
127
|
+
groups.push({
|
|
128
|
+
group_id: chatId,
|
|
129
|
+
name: typeof item.name === 'string' && item.name ? item.name : chatId,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
return groups;
|
|
133
|
+
},
|
|
134
|
+
listGroupMembers: (groupId) => this.#listAllPages(
|
|
135
|
+
`/im/v1/chats/${encodeURIComponent(groupId)}/members`,
|
|
136
|
+
{ member_id_type: 'open_id' },
|
|
137
|
+
),
|
|
138
|
+
});
|
|
139
|
+
readonly control: EndpointControl = createRecallEndpointControl((id) => this.recallMessage(id));
|
|
140
|
+
#routeReleases: HttpRouteRegistration[] = [];
|
|
141
|
+
#accessToken: AccessToken = { token: '', expires_in: 0, timestamp: 0 };
|
|
142
|
+
#refreshPromise: Promise<string> | null = null;
|
|
143
|
+
#open = false;
|
|
144
|
+
#started = false;
|
|
145
|
+
|
|
146
|
+
constructor(options: LarkEndpointOptions) {
|
|
147
|
+
super();
|
|
148
|
+
this.#logger = getAdapterLogger('lark', options.config.id);
|
|
149
|
+
this.#options = options;
|
|
150
|
+
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Used by webhook handler. */
|
|
154
|
+
get isOpen(): boolean {
|
|
155
|
+
return this.#open;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
get config(): ResolvedLarkConfig {
|
|
159
|
+
return this.#options.config;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async start(): Promise<void> {
|
|
163
|
+
if (this.#started) return;
|
|
164
|
+
this.#started = true;
|
|
165
|
+
try {
|
|
166
|
+
if (!this.#options.config.encryptKey && !this.#options.config.verificationToken) {
|
|
167
|
+
// encryptKey / verificationToken 都未配置时 webhook 完全无鉴权,任何人可伪造事件
|
|
168
|
+
this.#logger.warn(formatCompact({
|
|
169
|
+
endpoint: this.#options.config.id,
|
|
170
|
+
op: 'webhook',
|
|
171
|
+
ok: false,
|
|
172
|
+
error: 'neither encryptKey nor verificationToken configured; webhook is unauthenticated',
|
|
173
|
+
}));
|
|
174
|
+
}
|
|
175
|
+
await this.#refreshAccessToken();
|
|
176
|
+
this.#routeReleases.push(...registerLarkWebhookRoutes(this.#options.http, this));
|
|
177
|
+
this.#logger.debug(formatCompact({
|
|
178
|
+
endpoint: this.#options.config.id,
|
|
179
|
+
op: 'webhook',
|
|
180
|
+
path: this.#options.config.webhookPath,
|
|
181
|
+
}));
|
|
182
|
+
} catch (error) {
|
|
183
|
+
await this.stop();
|
|
184
|
+
this.#logger.error('Failed to connect Lark endpoint:', error);
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
open(): void {
|
|
190
|
+
this.#open = true;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
close(): void {
|
|
194
|
+
this.#open = false;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async stop(): Promise<void> {
|
|
198
|
+
this.#open = false;
|
|
199
|
+
for (const release of this.#routeReleases.splice(0)) release();
|
|
200
|
+
this.#started = false;
|
|
201
|
+
this.#logger.debug(formatCompact({ op: 'disconnect' }));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async send({ conversation, payload }: EndpointSendRequest): Promise<string> {
|
|
205
|
+
const materialized = await this.#materializeOutboundMedia(payload);
|
|
206
|
+
const content = formatOutboundBody(materialized);
|
|
207
|
+
const data = await this.#request('/im/v1/messages', {
|
|
208
|
+
method: 'POST',
|
|
209
|
+
params: { receive_id_type: 'chat_id' },
|
|
210
|
+
body: {
|
|
211
|
+
receive_id: conversation.id,
|
|
212
|
+
msg_type: content.msg_type,
|
|
213
|
+
content: content.content,
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
if (data.code !== 0) {
|
|
217
|
+
throw new Error(`Failed to send message: ${data.msg}`);
|
|
218
|
+
}
|
|
219
|
+
const messageId = (data.data?.message_id as string) || `${Date.now()}`;
|
|
220
|
+
this.#logger.debug(formatCompact({ op: 'send', to: conversation.id,
|
|
221
|
+
id: messageId,
|
|
222
|
+
}));
|
|
223
|
+
return messageId;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async recallMessage(messageId: string): Promise<void> {
|
|
227
|
+
if (!messageId || messageId.startsWith('outbound:')) return;
|
|
228
|
+
await this.#request(`/im/v1/messages/${messageId}`, { method: 'DELETE' });
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* im/v1 消息 image 段只接受 image_key:canonical MediaRef(base64/本地路径/URL)
|
|
233
|
+
* 先经 /im/v1/images 物化,产物回写为 MediaRef kind=file(平台不透明引用);
|
|
234
|
+
* 上传失败降级为文本(alt 优先),不阻断发送。
|
|
235
|
+
*/
|
|
236
|
+
async #materializeOutboundMedia(payload: unknown): Promise<unknown> {
|
|
237
|
+
if (!Array.isArray(payload)) return payload;
|
|
238
|
+
return Promise.all(payload.map(async (item) => {
|
|
239
|
+
if (typeof item === 'string' || !item || typeof item !== 'object') return item;
|
|
240
|
+
const seg = item as { type?: unknown; data?: Record<string, unknown> };
|
|
241
|
+
if (seg.type !== 'image') return item;
|
|
242
|
+
const data = seg.data ?? {};
|
|
243
|
+
const media = readOutboundImageMedia(data);
|
|
244
|
+
if (!media) return item;
|
|
245
|
+
const imageKey = await this.uploadImage(media);
|
|
246
|
+
if (!imageKey) {
|
|
247
|
+
const alt = typeof data.alt === 'string' && data.alt ? data.alt : '[image]';
|
|
248
|
+
return { type: 'text', data: { text: alt } };
|
|
249
|
+
}
|
|
250
|
+
return {
|
|
251
|
+
type: 'image',
|
|
252
|
+
data: { media: { kind: 'file', value: imageKey } },
|
|
253
|
+
};
|
|
254
|
+
}));
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** POST /im/v1/images(image_type=message),返回 image_key;失败返回 null。 */
|
|
258
|
+
async uploadImage(media: Parameters<typeof resolveMediaBinary>[0]): Promise<string | null> {
|
|
259
|
+
try {
|
|
260
|
+
await this.#ensureAccessToken();
|
|
261
|
+
const binary = await resolveMediaBinary(media);
|
|
262
|
+
const form = buildImageUploadForm(binary);
|
|
263
|
+
const url = `${this.#options.config.apiBaseUrl}/im/v1/images`;
|
|
264
|
+
const response = await this.#fetch(url, {
|
|
265
|
+
method: 'POST',
|
|
266
|
+
headers: { Authorization: `Bearer ${this.#accessToken.token}` },
|
|
267
|
+
body: form,
|
|
268
|
+
signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS),
|
|
269
|
+
});
|
|
270
|
+
const data = await response.json() as LarkApiResponse;
|
|
271
|
+
if (data.code === 0) {
|
|
272
|
+
return (data.data?.image_key as string) || null;
|
|
273
|
+
}
|
|
274
|
+
throw new Error(`Image upload failed: ${data.msg}`);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
this.#logger.error('Failed to upload image:', error);
|
|
277
|
+
return null;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Test / internal: admit a parsed message when open (non-webhook path). */
|
|
282
|
+
admit(msg: LarkMessage): void {
|
|
283
|
+
if (!this.#open) return;
|
|
284
|
+
const conversation = larkInboundConversation(String(this.#options.id), msg);
|
|
285
|
+
void this.emit('message.receive', {
|
|
286
|
+
conversation,
|
|
287
|
+
message: { conversation, id: generateMessageId(msg) },
|
|
288
|
+
content: formatInboundContent(msg),
|
|
289
|
+
sender: { id: resolveSender(msg) },
|
|
290
|
+
endpointId: this.#options.config.id,
|
|
291
|
+
metadata: Object.freeze({
|
|
292
|
+
messageType: msg.message_type,
|
|
293
|
+
chatType: resolveChatType(msg.chat_id, msg.chat_type),
|
|
294
|
+
}),
|
|
295
|
+
}).catch((err) => {
|
|
296
|
+
this.#logger.warn(formatCompact({
|
|
297
|
+
op: 'lark_gateway_receive_failed',
|
|
298
|
+
conversation: conversation.id,
|
|
299
|
+
error: err instanceof Error ? err.message : String(err),
|
|
300
|
+
}));
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
admitPlatform(name: string, event: unknown): void {
|
|
305
|
+
if (!this.#open) return;
|
|
306
|
+
void this.emitPlatform(name, event).catch((error) => {
|
|
307
|
+
this.#logger.warn(formatCompact({
|
|
308
|
+
op: 'lark_platform_event_failed',
|
|
309
|
+
event: name,
|
|
310
|
+
error: error instanceof Error ? error.message : String(error),
|
|
311
|
+
}));
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async getUserInfo(
|
|
316
|
+
userId: string,
|
|
317
|
+
userIdType: 'open_id' | 'user_id' | 'union_id' = 'open_id',
|
|
318
|
+
): Promise<unknown> {
|
|
319
|
+
try {
|
|
320
|
+
const data = await this.#request(`/contact/v3/users/${userId}`, {
|
|
321
|
+
method: 'GET',
|
|
322
|
+
params: { user_id_type: userIdType },
|
|
323
|
+
});
|
|
324
|
+
return data.data?.user ?? null;
|
|
325
|
+
} catch (error) {
|
|
326
|
+
this.#logger.error('Failed to get user info:', error);
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
async getChatInfo(chatId: string): Promise<unknown> {
|
|
332
|
+
try {
|
|
333
|
+
const data = await this.#request(`/im/v1/chats/${chatId}`, { method: 'GET' });
|
|
334
|
+
return data.data ?? null;
|
|
335
|
+
} catch (error) {
|
|
336
|
+
this.#logger.error('Failed to get chat info:', error);
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async uploadFile(
|
|
342
|
+
filePath: string,
|
|
343
|
+
fileType: 'image' | 'file' | 'video' | 'audio' = 'file',
|
|
344
|
+
): Promise<string | null> {
|
|
345
|
+
try {
|
|
346
|
+
await this.#ensureAccessToken();
|
|
347
|
+
const buf = await readFile(filePath);
|
|
348
|
+
const form = new FormData();
|
|
349
|
+
form.append('file', new Blob([buf]), basename(filePath));
|
|
350
|
+
form.append('file_type', fileType);
|
|
351
|
+
const url = `${this.#options.config.apiBaseUrl}/im/v1/files`;
|
|
352
|
+
const response = await this.#fetch(url, {
|
|
353
|
+
method: 'POST',
|
|
354
|
+
headers: { Authorization: `Bearer ${this.#accessToken.token}` },
|
|
355
|
+
body: form,
|
|
356
|
+
});
|
|
357
|
+
const data = await response.json() as LarkApiResponse;
|
|
358
|
+
if (data.code === 0) {
|
|
359
|
+
return (data.data?.file_key as string) || null;
|
|
360
|
+
}
|
|
361
|
+
throw new Error(`Upload failed: ${data.msg}`);
|
|
362
|
+
} catch (error) {
|
|
363
|
+
this.#logger.error('Failed to upload file:', error);
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async createChat(
|
|
369
|
+
name: string,
|
|
370
|
+
userIds: string[],
|
|
371
|
+
ownerId?: string,
|
|
372
|
+
): Promise<string | null> {
|
|
373
|
+
try {
|
|
374
|
+
const data = await this.#request('/im/v1/chats', {
|
|
375
|
+
method: 'POST',
|
|
376
|
+
body: {
|
|
377
|
+
name,
|
|
378
|
+
user_id_list: userIds,
|
|
379
|
+
...(ownerId ? { owner_id: ownerId } : {}),
|
|
380
|
+
},
|
|
381
|
+
});
|
|
382
|
+
if (data.code === 0) return (data.data?.chat_id as string) || null;
|
|
383
|
+
throw new Error(`Failed to create chat: ${data.msg}`);
|
|
384
|
+
} catch (error) {
|
|
385
|
+
this.#logger.error('Failed to create chat:', error);
|
|
386
|
+
return null;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
async updateChatInfo(
|
|
391
|
+
chatId: string,
|
|
392
|
+
options: { name?: string; description?: string },
|
|
393
|
+
): Promise<boolean> {
|
|
394
|
+
try {
|
|
395
|
+
const data = await this.#request(`/im/v1/chats/${chatId}`, {
|
|
396
|
+
method: 'PUT',
|
|
397
|
+
body: options,
|
|
398
|
+
});
|
|
399
|
+
if (data.code === 0) return true;
|
|
400
|
+
throw new Error(`Failed to update chat: ${data.msg}`);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
this.#logger.error('Failed to update chat:', error);
|
|
403
|
+
return false;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async addChatMembers(chatId: string, userIds: string[]): Promise<boolean> {
|
|
408
|
+
try {
|
|
409
|
+
const data = await this.#request(`/im/v1/chats/${chatId}/members`, {
|
|
410
|
+
method: 'POST',
|
|
411
|
+
body: { id_list: userIds },
|
|
412
|
+
});
|
|
413
|
+
if (data.code === 0) return true;
|
|
414
|
+
throw new Error(`Failed to add members: ${data.msg}`);
|
|
415
|
+
} catch (error) {
|
|
416
|
+
this.#logger.error('Failed to add chat members:', error);
|
|
417
|
+
return false;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
async removeChatMembers(chatId: string, userIds: string[]): Promise<boolean> {
|
|
422
|
+
try {
|
|
423
|
+
const data = await this.#request(`/im/v1/chats/${chatId}/members`, {
|
|
424
|
+
method: 'DELETE',
|
|
425
|
+
body: { id_list: userIds },
|
|
426
|
+
});
|
|
427
|
+
if (data.code === 0) return true;
|
|
428
|
+
throw new Error(`Failed to remove members: ${data.msg}`);
|
|
429
|
+
} catch (error) {
|
|
430
|
+
this.#logger.error('Failed to remove chat members:', error);
|
|
431
|
+
return false;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async getChatMembers(chatId: string): Promise<unknown[]> {
|
|
436
|
+
try {
|
|
437
|
+
const data = await this.#request(`/im/v1/chats/${chatId}/members`, { method: 'GET' });
|
|
438
|
+
if (data.code === 0) return (data.data?.items as unknown[]) || [];
|
|
439
|
+
throw new Error(`Failed to get members: ${data.msg}`);
|
|
440
|
+
} catch (error) {
|
|
441
|
+
this.#logger.error('Failed to get chat members:', error);
|
|
442
|
+
return [];
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
async dissolveChat(chatId: string): Promise<boolean> {
|
|
447
|
+
try {
|
|
448
|
+
const data = await this.#request(`/im/v1/chats/${chatId}`, { method: 'DELETE' });
|
|
449
|
+
if (data.code === 0) return true;
|
|
450
|
+
throw new Error(`Failed to dissolve chat: ${data.msg}`);
|
|
451
|
+
} catch (error) {
|
|
452
|
+
this.#logger.error('Failed to dissolve chat:', error);
|
|
453
|
+
return false;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async setChatManagers(chatId: string, userIds: string[]): Promise<boolean> {
|
|
458
|
+
try {
|
|
459
|
+
const data = await this.#request(`/im/v1/chats/${chatId}/managers/add_managers`, {
|
|
460
|
+
method: 'POST',
|
|
461
|
+
body: { manager_ids: userIds },
|
|
462
|
+
});
|
|
463
|
+
if (data.code === 0) return true;
|
|
464
|
+
throw new Error(`Failed to set managers: ${data.msg}`);
|
|
465
|
+
} catch (error) {
|
|
466
|
+
this.#logger.error('Failed to set chat managers:', error);
|
|
467
|
+
return false;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
async removeChatManagers(chatId: string, userIds: string[]): Promise<boolean> {
|
|
472
|
+
try {
|
|
473
|
+
const data = await this.#request(`/im/v1/chats/${chatId}/managers/delete_managers`, {
|
|
474
|
+
method: 'POST',
|
|
475
|
+
body: { manager_ids: userIds },
|
|
476
|
+
});
|
|
477
|
+
if (data.code === 0) return true;
|
|
478
|
+
throw new Error(`Failed to remove managers: ${data.msg}`);
|
|
479
|
+
} catch (error) {
|
|
480
|
+
this.#logger.error('Failed to remove chat managers:', error);
|
|
481
|
+
return false;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** 拉取分页列表(items + has_more/page_token);code!==0 时抛错交由 RPC 层透出。 */
|
|
486
|
+
async #listAllPages(
|
|
487
|
+
path: string,
|
|
488
|
+
params: Record<string, string | number> = {},
|
|
489
|
+
): Promise<Record<string, unknown>[]> {
|
|
490
|
+
const items: Record<string, unknown>[] = [];
|
|
491
|
+
let pageToken = '';
|
|
492
|
+
do {
|
|
493
|
+
const data = await this.#request(path, {
|
|
494
|
+
method: 'GET',
|
|
495
|
+
params: {
|
|
496
|
+
...params,
|
|
497
|
+
page_size: 100,
|
|
498
|
+
...(pageToken ? { page_token: pageToken } : {}),
|
|
499
|
+
},
|
|
500
|
+
});
|
|
501
|
+
if (data.code !== 0) {
|
|
502
|
+
throw new Error(`Lark API ${path} failed: ${data.msg ?? 'unknown'} (${data.code})`);
|
|
503
|
+
}
|
|
504
|
+
const page = data.data ?? {};
|
|
505
|
+
if (Array.isArray(page.items)) {
|
|
506
|
+
for (const item of page.items) {
|
|
507
|
+
if (item !== null && typeof item === 'object') {
|
|
508
|
+
items.push(item as Record<string, unknown>);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
pageToken = page.has_more === true && typeof page.page_token === 'string'
|
|
513
|
+
? page.page_token
|
|
514
|
+
: '';
|
|
515
|
+
} while (pageToken);
|
|
516
|
+
return items;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
async #request(
|
|
520
|
+
path: string,
|
|
521
|
+
options: {
|
|
522
|
+
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
523
|
+
params?: Record<string, string | number>;
|
|
524
|
+
body?: Record<string, unknown>;
|
|
525
|
+
} = {},
|
|
526
|
+
): Promise<LarkApiResponse> {
|
|
527
|
+
await this.#ensureAccessToken();
|
|
528
|
+
const { method = 'GET', params = {}, body } = options;
|
|
529
|
+
const urlParams = new URLSearchParams(
|
|
530
|
+
Object.fromEntries(
|
|
531
|
+
Object.entries(params).map(([key, value]) => [key, String(value)]),
|
|
532
|
+
),
|
|
533
|
+
);
|
|
534
|
+
const query = urlParams.toString();
|
|
535
|
+
const url = `${this.#options.config.apiBaseUrl}${path}${query ? `?${query}` : ''}`;
|
|
536
|
+
const response = await this.#fetch(url, {
|
|
537
|
+
method,
|
|
538
|
+
headers: {
|
|
539
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
540
|
+
Authorization: `Bearer ${this.#accessToken.token}`,
|
|
541
|
+
},
|
|
542
|
+
body: body && method !== 'GET' ? JSON.stringify(body) : undefined,
|
|
543
|
+
signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS),
|
|
544
|
+
});
|
|
545
|
+
if (!response.ok) {
|
|
546
|
+
const text = await response.text().catch(() => '');
|
|
547
|
+
throw new Error(`Lark API error ${response.status}: ${text}`);
|
|
548
|
+
}
|
|
549
|
+
return await response.json() as LarkApiResponse;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
async #ensureAccessToken(): Promise<void> {
|
|
553
|
+
const now = Date.now();
|
|
554
|
+
if (
|
|
555
|
+
this.#accessToken.token
|
|
556
|
+
&& now < this.#accessToken.timestamp + (this.#accessToken.expires_in - 300) * 1000
|
|
557
|
+
) {
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
if (this.#refreshPromise) {
|
|
561
|
+
await this.#refreshPromise;
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
this.#refreshPromise = this.#refreshAccessToken()
|
|
565
|
+
.then(() => this.#accessToken.token)
|
|
566
|
+
.finally(() => { this.#refreshPromise = null; });
|
|
567
|
+
await this.#refreshPromise;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
async #refreshAccessToken(): Promise<void> {
|
|
571
|
+
const { appId, appSecret, apiBaseUrl } = this.#options.config;
|
|
572
|
+
const url = `${apiBaseUrl}/auth/v3/tenant_access_token/internal`;
|
|
573
|
+
const response = await this.#fetch(url, {
|
|
574
|
+
method: 'POST',
|
|
575
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
|
576
|
+
body: JSON.stringify({ app_id: appId, app_secret: appSecret }),
|
|
577
|
+
});
|
|
578
|
+
const data = await response.json() as LarkApiResponse;
|
|
579
|
+
if (data.code === 0 && data.tenant_access_token) {
|
|
580
|
+
this.#accessToken = {
|
|
581
|
+
token: data.tenant_access_token,
|
|
582
|
+
expires_in: data.expire ?? 7200,
|
|
583
|
+
timestamp: Date.now(),
|
|
584
|
+
};
|
|
585
|
+
this.#logger.debug('Access token refreshed successfully');
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
throw new Error(`Failed to get access token: ${data.msg} (${data.code})`);
|
|
589
|
+
}
|
|
590
|
+
}
|