larkmate 0.0.0-stage → 0.1.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.
package/src/client.js ADDED
@@ -0,0 +1,445 @@
1
+ import { uploadFile } from './upload.js';
2
+ import { FeishuError, requireNumericId, requireText } from './errors.js';
3
+ import { shortId } from './gateway.js';
4
+
5
+ function ids(values, label) {
6
+ if (!Array.isArray(values)) throw new FeishuError('INVALID_ARGUMENT', `${label} must be a list.`);
7
+ return [...new Set(values.map(value => requireNumericId(value, label)))];
8
+ }
9
+
10
+ function decodedPayload(gateway, response, type, operation) {
11
+ if (!response.packet.payload?.length) {
12
+ throw new FeishuError('EFFECT_UNKNOWN', 'No confirmation was returned; inspect the chat before retrying.',
13
+ { operation, requestId: response.requestId });
14
+ }
15
+ try { return gateway.decode(type, response.packet.payload); }
16
+ catch {
17
+ throw new FeishuError('EFFECT_UNKNOWN', 'The confirmation was unreadable; inspect the chat before retrying.',
18
+ { operation, requestId: response.requestId });
19
+ }
20
+ }
21
+
22
+ export class LarkMateClient {
23
+ constructor(gateway) { this.gateway = gateway; }
24
+
25
+ async status() {
26
+ return { status: 'ready', identity: 'user', user: await this.gateway.authenticate() };
27
+ }
28
+
29
+ async search(query) {
30
+ requireText(query, 'query');
31
+ const response = await this.gateway.call(11021, 'UniversalSearchRequest', {
32
+ header: {
33
+ searchSession: shortId(), sessionSeqId: 1, query, locale: 'zh_CN',
34
+ searchContext: {
35
+ tagName: 'SMART_SEARCH',
36
+ entityItems: [{ type: 1 }, { type: 2 }, { type: 3, filter: { groupChatFilter: {} } }],
37
+ commonFilter: { includeOuterTenant: true }, sourceKey: 'messenger',
38
+ },
39
+ },
40
+ }, { operation: 'search' });
41
+ if (!response.packet.payload?.length) return { items: [] };
42
+ let data;
43
+ try { data = this.gateway.decode('UniversalSearchResponse', response.packet.payload); }
44
+ catch { throw new FeishuError('INVALID_RESPONSE', 'The search response was unreadable.'); }
45
+ const names = { 1: 'user', 2: 'bot', 3: 'group' };
46
+ return { items: (data.results || []).map(item => ({
47
+ id: String(item.id || ''), type: names[item.type] || 'unknown',
48
+ name: (item.titleHighlighted || '').replace(/<[^>]+>/g, ''),
49
+ })) };
50
+ }
51
+
52
+ async chats({ limit = 50, cursor, parent, scope = 'inbox' } = {}) {
53
+ if (!['inbox', 'done'].includes(scope)) throw new FeishuError('INVALID_ARGUMENT', 'scope must be inbox or done.');
54
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new FeishuError('INVALID_ARGUMENT', 'limit must be between 1 and 100.');
55
+ for (const [value, label] of [[cursor, 'cursor'], [parent, 'parent']]) {
56
+ if (value != null && !/^[0-9]{1,19}$/.test(String(value))) throw new FeishuError('INVALID_ARGUMENT', label + ' must be a numeric identifier.');
57
+ }
58
+ const response = await this.gateway.call(1000, 'PullFeedCardsRequest', {
59
+ type: scope === 'done' ? 2 : 1, pullType: cursor ? 2 : 1, count: limit,
60
+ ...(cursor ? { cursor: String(cursor) } : {}), ...(parent ? { parentCardId: String(parent) } : {}),
61
+ }, { operation: 'list-chats', version: '5.7.0' });
62
+ if (!response.packet.payload?.length) throw new FeishuError('INVALID_RESPONSE', 'No inbox page was returned.');
63
+ let page;
64
+ try { page = this.gateway.decode('PullFeedCardsResponse', response.packet.payload); }
65
+ catch { throw new FeishuError('INVALID_RESPONSE', 'The inbox page was unreadable.'); }
66
+ const types = { 1: 'p2p', 2: 'group', 3: 'topic_group' };
67
+ const items = [], boxes = [];
68
+ for (const card of page.cards || []) {
69
+ if (card.type === 5) { boxes.push({ id: String(card.id) }); continue; }
70
+ if (card.type !== 1) continue;
71
+ const chat = page.chats?.[card.id];
72
+ const unreadCount = chat && Object.hasOwn(chat, 'newMessageCount') ? chat.newMessageCount : null;
73
+ const manualUnread = card.feedCardField ? (card.feedCardField.markAsUnread?.unread ?? false) : null;
74
+ const unread = unreadCount > 0 || manualUnread === true ? true : unreadCount === 0 && manualUnread === false ? false : null;
75
+ items.push({ id: String(card.id), name: chat?.name || '', type: types[chat?.type] || 'unknown',
76
+ updatedAt: Object.hasOwn(card, 'updateTime') ? String(card.updateTime) : null, unreadCount, manualUnread, unread });
77
+ }
78
+ const nextCursor = Object.hasOwn(page, 'nextCursor') && String(page.nextCursor) !== '0' ? String(page.nextCursor) : null;
79
+ return { items, boxes, nextCursor, scope };
80
+ }
81
+
82
+ async openChat(userId) {
83
+ requireNumericId(userId, 'user ID');
84
+ const response = await this.gateway.call(13, 'PutChatRequest', { type: 1, chatterIds: [userId] },
85
+ { mutating: true, operation: 'open-chat' });
86
+ const result = decodedPayload(this.gateway, response, 'PutChatResponse', 'open-chat');
87
+ if (!result.chat?.id) throw new FeishuError('EFFECT_UNKNOWN', 'No chat ID was returned; inspect before retrying.');
88
+ return { chatId: result.chat.id, status: 'opened' };
89
+ }
90
+
91
+ async chatInfo(chatId) {
92
+ requireNumericId(chatId, 'chat ID');
93
+ const response = await this.gateway.call(64, 'PullChatsByIdsRequest', { chatIds: [chatId] }, { operation: 'chat-info' });
94
+ if (!response.packet.payload?.length) throw new FeishuError('NOT_FOUND', 'The chat was not found.');
95
+ let result;
96
+ try { result = this.gateway.decode('PullChatsByIdsResponse', response.packet.payload); }
97
+ catch { throw new FeishuError('INVALID_RESPONSE', 'The chat response was unreadable.'); }
98
+ const chat = result.chats?.[chatId];
99
+ if (!chat?.id || String(chat.id) !== chatId) throw new FeishuError('NOT_FOUND', 'The requested chat was not found.');
100
+ const types = { 1: 'p2p', 2: 'group', 3: 'topic_group' };
101
+ const memberCount = Object.hasOwn(chat, 'memberCount') ? chat.memberCount
102
+ : Object.hasOwn(chat, 'userCount') ? chat.userCount : null;
103
+ return { id: String(chat.id), name: chat.name || '', type: types[chat.type] || 'unknown',
104
+ description: Object.hasOwn(chat, 'description') ? chat.description : null,
105
+ isDissolved: Object.hasOwn(chat, 'isDissolved') ? chat.isDissolved : null,
106
+ memberCount,
107
+ lastMessagePosition: Object.hasOwn(chat, 'lastMessagePosition') ? chat.lastMessagePosition : null };
108
+ }
109
+
110
+ async updateGroup({ chatId, name, description }) {
111
+ requireNumericId(chatId, 'chat ID');
112
+ if (name == null && description == null) {
113
+ throw new FeishuError('INVALID_ARGUMENT', 'Specify a group name or description.');
114
+ }
115
+ if (name != null) requireText(name, 'group name');
116
+ if (description != null && typeof description !== 'string') {
117
+ throw new FeishuError('INVALID_ARGUMENT', 'description must be a string.');
118
+ }
119
+ const updateFields = [];
120
+ if (name != null) updateFields.push(1);
121
+ if (description != null) updateFields.push(3);
122
+ const response = await this.gateway.call(72, 'PatchGroupChatRequest', {
123
+ chatId, ...(name != null ? { name } : {}), ...(description != null ? { description } : {}), updateFields,
124
+ }, { mutating: true, operation: 'update-group' });
125
+ const result = decodedPayload(this.gateway, response, 'PatchGroupChatResponse', 'update-group');
126
+ if (!result.chat?.id || String(result.chat.id) !== chatId) {
127
+ throw new FeishuError('EFFECT_UNKNOWN', 'The requested group was not confirmed; inspect before retrying.',
128
+ { requestId: response.requestId });
129
+ }
130
+ const confirmed = (name == null || (Object.hasOwn(result.chat, 'name') && result.chat.name === name))
131
+ && (description == null || (Object.hasOwn(result.chat, 'description') && result.chat.description === description));
132
+ return { status: confirmed ? 'updated' : 'submitted_unconfirmed', chatId, requestId: response.requestId };
133
+ }
134
+
135
+ async dissolveGroup(chatId) {
136
+ requireNumericId(chatId, 'chat ID');
137
+ const response = await this.gateway.call(72, 'PatchGroupChatRequest', {
138
+ chatId, isDissolved: true, updateFields: [16],
139
+ }, { mutating: true, operation: 'dissolve-group' });
140
+ const result = decodedPayload(this.gateway, response, 'PatchGroupChatResponse', 'dissolve-group');
141
+ if (!result.chat?.id || String(result.chat.id) !== chatId) {
142
+ throw new FeishuError('EFFECT_UNKNOWN', 'The requested group was not confirmed; inspect before retrying.',
143
+ { requestId: response.requestId });
144
+ }
145
+ return { status: result.chat.isDissolved === true ? 'dissolved' : 'submitted_unconfirmed',
146
+ chatId, requestId: response.requestId };
147
+ }
148
+
149
+ async history({ chatId, limit = 20, start }) {
150
+ requireNumericId(chatId, 'chat ID');
151
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
152
+ throw new FeishuError('INVALID_ARGUMENT', 'limit must be an integer between 1 and 100.');
153
+ }
154
+ if (start != null && (!Number.isInteger(start) || start < 1 || start + limit - 1 > 2147483647)) {
155
+ throw new FeishuError('INVALID_ARGUMENT', 'start and the requested page must fit the positive 32-bit position range.');
156
+ }
157
+ const info = start == null ? await this.chatInfo(chatId) : null;
158
+ if (info && info.lastMessagePosition == null) {
159
+ throw new FeishuError('POSITION_UNAVAILABLE', 'The latest message position was not returned; provide --start.');
160
+ }
161
+ if (info && info.lastMessagePosition === 0) return { items: [] };
162
+ const first = start ?? Math.max(1, info.lastMessagePosition - limit + 1);
163
+ const end = start == null ? info.lastMessagePosition : first + limit - 1;
164
+ const positions = Array.from({ length: end - first + 1 }, (_, index) => first + index);
165
+ const response = await this.gateway.call(43, 'PullMessagesByPositionsRequest', { chatId, positions },
166
+ { operation: 'history' });
167
+ if (!response.packet.payload?.length) throw new FeishuError('INVALID_RESPONSE', 'No history page was returned.');
168
+ let data;
169
+ try { data = this.gateway.decode('PullMessagesByPositionsResponse', response.packet.payload); }
170
+ catch { throw new FeishuError('INVALID_RESPONSE', 'The history page was unreadable.'); }
171
+ const requested = new Set(positions);
172
+ const items = Object.entries(data.messages || {}).filter(([position]) => requested.has(Number(position))).map(([position, message]) => {
173
+ let text = null;
174
+ if (message.content?.length && (message.type === 4 || message.type === 2)) {
175
+ try {
176
+ const content = this.gateway.decode(message.type === 4 ? 'TextContent' : 'PostContent', message.content);
177
+ text = content.richText?.innerText || content.text || null;
178
+ } catch { /* Keep unsupported or undecodable content explicitly unknown. */ }
179
+ }
180
+ let resource = null;
181
+ if (message.content?.length && (message.type === 3 || message.type === 5)) {
182
+ try {
183
+ const content = this.gateway.decode(message.type === 3 ? 'FileContent' : 'ImageContent', message.content);
184
+ resource = message.type === 3
185
+ ? { key: content.key || null, name: content.name || null, size: Object.hasOwn(content, 'size') ? String(content.size) : null, mime: content.mime || null }
186
+ : { key: content.imageV2?.imageKey || content.image?.imageKey || content.image?.key || null };
187
+ } catch { /* Leave unknown resources unparsed. */ }
188
+ }
189
+ return { id: String(message.id || ''), position: Number(position),
190
+ senderId: message.fromId || '', type: message.type, text,
191
+ createTime: Object.hasOwn(message, 'createTime') ? String(message.createTime) : null, resource };
192
+ }).sort((a, b) => a.position - b.position);
193
+ return { items, requestedPositions: positions.length,
194
+ omittedPositions: positions.length - items.length, nextStart: first > 1 ? Math.max(1, first - limit) : null,
195
+ nextLimit: first > 1 ? Math.min(limit, first - 1) : null,
196
+ hasMore: Object.hasOwn(data, 'hasMore') ? data.hasMore : null };
197
+ }
198
+
199
+ async historyPages({ chatId, limit = 20, start, pages = 1, query, sender, after, before }) {
200
+ if (!Number.isInteger(pages) || pages < 1 || pages > 100) throw new FeishuError('INVALID_ARGUMENT', 'pages must be between 1 and 100.');
201
+ if (sender) requireNumericId(sender, 'sender ID');
202
+ for (const [value, label] of [[after, 'after'], [before, 'before']]) {
203
+ if (value != null && (!Number.isSafeInteger(value) || value < 0)) throw new FeishuError('INVALID_ARGUMENT', label + ' must be a Unix timestamp in seconds.');
204
+ }
205
+ if (after != null && before != null && after > before) throw new FeishuError('INVALID_ARGUMENT', 'after must not be later than before.');
206
+ let next = start, pageLimit = limit, nextLimit = null, scanned = 0, omittedPositions = 0, missingTimestamps = 0, items = [];
207
+ for (let i = 0; i < pages; i++) {
208
+ const page = await this.history({ chatId, limit: pageLimit, start: next });
209
+ scanned += page.requestedPositions || 0;
210
+ omittedPositions += page.omittedPositions || 0;
211
+ items.push(...page.items.filter(item => {
212
+ if (sender && item.senderId !== sender) return false;
213
+ if (query && !(item.text || '').includes(query)) return false;
214
+ if (after != null || before != null) {
215
+ if (item.createTime == null) { missingTimestamps++; return false; }
216
+ const time = Number(item.createTime);
217
+ if (!Number.isSafeInteger(time)) { missingTimestamps++; return false; }
218
+ if ((after != null && time < after) || (before != null && time > before)) return false;
219
+ }
220
+ return true;
221
+ }));
222
+ next = page.nextStart;
223
+ nextLimit = page.nextLimit;
224
+ pageLimit = nextLimit;
225
+ if (next == null) break;
226
+ }
227
+ items.sort((a, b) => a.position - b.position);
228
+ return { items, scannedPositions: scanned, omittedPositions, missingTimestamps, nextStart: next ?? null, nextLimit, filterScope: 'scanned_positions_only' };
229
+ }
230
+
231
+ async sendFile({ chatId, path }) {
232
+ requireNumericId(chatId, 'chat ID');
233
+ requireText(path, 'file path');
234
+ const file = await uploadFile(this.gateway, path);
235
+ const cid = shortId();
236
+ const response = await this.gateway.call(5, 'PutMessageRequest', {
237
+ type: 3, chatId, cid, isNotified: true, version: 1,
238
+ content: { fileKey: file.key, fileName: file.name, fileSize: file.size },
239
+ }, { version: '5.7.0', mutating: true, operation: 'send-file' });
240
+ let id = null;
241
+ try {
242
+ if (response.packet.payload?.length) {
243
+ const message = this.gateway.decode('PutMessageResponse', response.packet.payload).message;
244
+ if (message?.id && !String(message.id).startsWith('-') && (!message.chatId || message.chatId === chatId)) id = String(message.id);
245
+ }
246
+ } catch { /* Submission remains unconfirmed. */ }
247
+ return { status: id ? 'accepted' : 'submitted_unconfirmed', chatId, messageId: id, cid, requestId: response.requestId, fileName: file.name };
248
+ }
249
+
250
+ async send({ chatId, text, mentions = [] }) {
251
+ requireNumericId(chatId, 'chat ID');
252
+ requireText(text, 'text');
253
+ if (!Array.isArray(mentions)) throw new FeishuError('INVALID_ARGUMENT', 'mentions must be a list.');
254
+ await this.gateway.authenticate();
255
+ const elementIds = [];
256
+ const atIds = [];
257
+ const dictionary = {};
258
+ let remaining = text;
259
+ const addText = part => {
260
+ if (!part) return;
261
+ const id = shortId();
262
+ elementIds.push(id);
263
+ dictionary[id] = { tag: 1, property: this.gateway.encode('TextProperty', { content: part }) };
264
+ };
265
+ for (const mention of mentions) {
266
+ requireNumericId(mention.id, 'mention ID');
267
+ const marker = `@${requireText(mention.name, 'mention name')}`;
268
+ const index = remaining.indexOf(marker);
269
+ if (index < 0) throw new FeishuError('INVALID_ARGUMENT', 'The mention marker is absent from the text.');
270
+ addText(remaining.slice(0, index));
271
+ const id = shortId();
272
+ elementIds.push(id);
273
+ atIds.push(id);
274
+ dictionary[id] = { tag: 5, property: this.gateway.encode('AtProperty', { userId: mention.id, content: marker }) };
275
+ remaining = remaining.slice(index + marker.length);
276
+ }
277
+ addText(remaining);
278
+ const cid = shortId();
279
+ const response = await this.gateway.call(5, 'PutMessageRequest', {
280
+ type: 4, chatId, cid, isNotified: true, version: 1,
281
+ content: { richText: { elementIds, innerText: text, elements: { dictionary }, atIds } },
282
+ }, { version: '5.7.0', mutating: true, operation: 'send' });
283
+ return { status: 'submitted_unconfirmed', chatId, cid, requestId: response.requestId };
284
+ }
285
+
286
+ async resolveMembers(memberIds) {
287
+ if (!memberIds.length) return [];
288
+ const response = await this.gateway.call(46, 'PullChattersByIdsRequest', {
289
+ chatterIds: memberIds, needBotInfo: true, notSubscribeChatters: true,
290
+ }, { operation: 'resolve-members' });
291
+ if (!response.packet.payload?.length) throw new FeishuError('INVALID_RESPONSE', 'No member information was returned.');
292
+ let data;
293
+ try { data = this.gateway.decode('PullChattersByIdsResponse', response.packet.payload); }
294
+ catch { throw new FeishuError('INVALID_RESPONSE', 'The member information was unreadable.'); }
295
+ return memberIds.map(id => {
296
+ const chatter = data.chatters?.[id];
297
+ if (!chatter || String(chatter.id || '') !== id || !Object.hasOwn(chatter, 'type')
298
+ || (chatter.type !== 1 && chatter.type !== 2)) {
299
+ throw new FeishuError('MEMBER_TYPE_UNKNOWN', 'Cannot establish whether a member is a user or a bot.', { memberId: id });
300
+ }
301
+ return { id, type: chatter.type === 1 ? 'user' : 'bot' };
302
+ });
303
+ }
304
+
305
+ async botProtection({ chatId, botId }) {
306
+ requireNumericId(chatId, 'chat ID');
307
+ requireNumericId(botId, 'bot ID');
308
+ const { data } = await this.gateway.botApi('fetch_bot_conf_resource', {
309
+ chat_id: chatId, bot_id: botId,
310
+ }, { operation: 'read-bot-protection' });
311
+ if (data.ok !== true || !Array.isArray(data.fields)) {
312
+ throw new FeishuError('PROTECTION_UNAVAILABLE', 'Feishu did not return the bot protection setting.');
313
+ }
314
+ const field = data.fields.find(item => item.field_key === 'check_mender');
315
+ const value = field?.field_value || field?.default_value;
316
+ if (value !== 'true' && value !== 'false') {
317
+ throw new FeishuError('PROTECTION_UNAVAILABLE', 'Feishu did not return the bot protection setting.');
318
+ }
319
+ return { chatId, botId, enabled: value === 'true' };
320
+ }
321
+
322
+ async setBotProtection({ chatId, botId, enabled = true }) {
323
+ requireNumericId(chatId, 'chat ID');
324
+ requireNumericId(botId, 'bot ID');
325
+ if (typeof enabled !== 'boolean') throw new FeishuError('INVALID_ARGUMENT', 'enabled must be a boolean.');
326
+ const result = await this.gateway.botApi('UpdateAppBotInfo', {
327
+ chat_id: chatId, bot_id: botId, check_mender: enabled,
328
+ }, { mutating: true, operation: 'set-bot-protection' });
329
+ return this.verifyBotProtection({ chatId, botId, enabled, requestId: result.requestId });
330
+ }
331
+
332
+ async verifyBotProtection({ chatId, botId, enabled, requestId }) {
333
+ try {
334
+ const current = await this.botProtection({ chatId, botId });
335
+ return { chatId, botId, requestId, enabled: current.enabled,
336
+ status: current.enabled === enabled ? 'verified' : 'protection_mismatch' };
337
+ } catch (error) {
338
+ return { chatId, botId, requestId, enabled: null, status: 'submitted_unconfirmed',
339
+ verificationError: error instanceof FeishuError ? error.code : 'INVALID_RESPONSE' };
340
+ }
341
+ }
342
+
343
+ async inviteBot({ chatId, botId, protect = true }) {
344
+ requireNumericId(chatId, 'chat ID');
345
+ requireNumericId(botId, 'bot ID');
346
+ if (typeof protect !== 'boolean') throw new FeishuError('INVALID_ARGUMENT', 'protect must be a boolean.');
347
+ const result = await this.gateway.botApi('SetBotAddConf', {
348
+ chat_id: chatId, bot_id: botId, check_mender: protect,
349
+ }, { mutating: true, operation: 'invite-bot' });
350
+ return this.verifyBotProtection({ chatId, botId, enabled: protect, requestId: result.requestId });
351
+ }
352
+
353
+ async createGroup({ name, description, memberIds = [], protectBots = true }) {
354
+ requireText(name, 'group name');
355
+ if (description != null && typeof description !== 'string') {
356
+ throw new FeishuError('INVALID_ARGUMENT', 'description must be a string.');
357
+ }
358
+ if (typeof protectBots !== 'boolean') throw new FeishuError('INVALID_ARGUMENT', 'protectBots must be a boolean.');
359
+ const members = await this.resolveMembers(ids(memberIds, 'member ID'));
360
+ const users = members.filter(item => item.type === 'user').map(item => item.id);
361
+ const bots = members.filter(item => item.type === 'bot');
362
+ const response = await this.gateway.call(13, 'PutChatRequest', {
363
+ type: 2, groupName: name, ...(description ? { groupDesc: description } : {}),
364
+ chatterIds: users, cid: shortId(),
365
+ }, { mutating: true, operation: 'create-group' });
366
+ const result = decodedPayload(this.gateway, response, 'PutChatResponse', 'create-group');
367
+ if (!result.chat?.id) throw new FeishuError('EFFECT_UNKNOWN', 'No group ID was returned; inspect before retrying.');
368
+ if (Object.hasOwn(result.chat, 'type') && result.chat.type !== 2) {
369
+ throw new FeishuError('EFFECT_UNKNOWN', 'The response did not confirm a group; inspect before retrying.',
370
+ { chatId: String(result.chat.id) });
371
+ }
372
+ const chatId = String(result.chat.id);
373
+ const botsSubmitted = [];
374
+ for (const bot of bots) {
375
+ try { botsSubmitted.push(await this.inviteBot({ chatId, botId: bot.id, protect: protectBots })); }
376
+ catch (error) {
377
+ throw new FeishuError('GROUP_CREATED_PARTIAL', 'The group was created; inspect its members before retrying.', {
378
+ chatId, botsSubmitted, failedBotId: bot.id,
379
+ causeCode: error instanceof FeishuError ? error.code : 'CLI_ERROR',
380
+ causeRequestId: error instanceof FeishuError ? error.details.requestId : undefined,
381
+ });
382
+ }
383
+ }
384
+ return { status: botsSubmitted.every(bot => bot.status === 'verified') ? 'created' : 'created_protection_unconfirmed',
385
+ chatId, requestId: response.requestId,
386
+ membersVerified: false, bots: botsSubmitted };
387
+ }
388
+
389
+ async invite({ chatId, memberIds, protectBots = true }) {
390
+ requireNumericId(chatId, 'chat ID');
391
+ if (typeof protectBots !== 'boolean') throw new FeishuError('INVALID_ARGUMENT', 'protectBots must be a boolean.');
392
+ const memberList = ids(memberIds, 'member ID');
393
+ if (!memberList.length) throw new FeishuError('INVALID_ARGUMENT', 'At least one member ID is required.');
394
+ const members = await this.resolveMembers(memberList);
395
+ const users = members.filter(item => item.type === 'user').map(item => item.id);
396
+ const bots = members.filter(item => item.type === 'bot');
397
+ const submitted = [];
398
+ if (users.length) {
399
+ const response = await this.gateway.call(47, 'PutChatChatterRequest', {
400
+ chatId, chatterIds: users, isInviteAtChatters: false,
401
+ }, { mutating: true, operation: 'invite-members' });
402
+ const result = decodedPayload(this.gateway, response, 'PutChatChatterResponse', 'invite-members');
403
+ if (!result.chat?.id || String(result.chat.id) !== chatId) {
404
+ throw new FeishuError('EFFECT_UNKNOWN', 'The requested group was not confirmed; inspect before retrying.',
405
+ { requestId: response.requestId });
406
+ }
407
+ submitted.push({ type: 'users', memberIds: users, status: 'submitted_unconfirmed', requestId: response.requestId });
408
+ }
409
+ for (const bot of bots) {
410
+ try { submitted.push({ type: 'bot', ...await this.inviteBot({ chatId, botId: bot.id, protect: protectBots }) }); }
411
+ catch (error) {
412
+ if (!submitted.length) throw error;
413
+ throw new FeishuError('INVITE_PARTIAL', 'Some invitations were submitted; inspect the group before retrying.', {
414
+ chatId, submitted, failedBotId: bot.id,
415
+ causeCode: error instanceof FeishuError ? error.code : 'CLI_ERROR',
416
+ causeRequestId: error instanceof FeishuError ? error.details.requestId : undefined,
417
+ });
418
+ }
419
+ }
420
+ return { status: 'submitted_unconfirmed', chatId, requested: members.length, submitted };
421
+ }
422
+
423
+ async members({ chatId, cursor, offset, limit = 100 }) {
424
+ requireNumericId(chatId, 'chat ID');
425
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
426
+ throw new FeishuError('INVALID_ARGUMENT', 'limit must be an integer between 1 and 200.');
427
+ }
428
+ if (cursor != null && !/^\d+$/.test(String(cursor))) {
429
+ throw new FeishuError('INVALID_ARGUMENT', 'cursor must be a non-negative integer.');
430
+ }
431
+ const response = await this.gateway.call(44, 'PullChatChattersRequest', {
432
+ chatId, needChatters: true, limit, ...(cursor != null ? { cursor: String(cursor) } : {}),
433
+ ...(offset ? { offset } : {}),
434
+ }, { operation: 'list-members' });
435
+ if (!response.packet.payload?.length) throw new FeishuError('INVALID_RESPONSE', 'No member page was returned.');
436
+ let data;
437
+ try { data = this.gateway.decode('PullChatChattersResponse', response.packet.payload); }
438
+ catch { throw new FeishuError('INVALID_RESPONSE', 'The member page was unreadable.'); }
439
+ const entries = { ...(data.chatters || {}), ...(data.updateChatters || {}) };
440
+ return { items: Object.entries(entries).map(([key, value]) => ({
441
+ id: String(value.id || key), name: value.name || '', type: Object.hasOwn(value, 'type') ? value.type : null,
442
+ })), nextCursor: Object.hasOwn(data, 'nextCursor') ? data.nextCursor.toString() : null,
443
+ nextOffset: data.nextOffset || null };
444
+ }
445
+ }
@@ -0,0 +1,23 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { FeishuError } from './errors.js';
5
+
6
+ export async function loadCookie({ file, env = process.env, home = homedir() } = {}) {
7
+ let cookie = !file && env.LARKMATE_COOKIE;
8
+ if (!cookie) {
9
+ const path = file || join(env.LARKMATE_HOME || join(home, '.larkmate'), 'credentials.json');
10
+ let contents;
11
+ try { contents = await readFile(path, 'utf8'); }
12
+ catch { throw new FeishuError('CREDENTIALS_UNAVAILABLE', 'Cannot read LarkMate credentials.'); }
13
+ try { cookie = JSON.parse(contents).cookie; }
14
+ catch { throw new FeishuError('CREDENTIALS_INVALID', 'Credentials must be JSON with a cookie field.'); }
15
+ }
16
+ if (typeof cookie !== 'string' || !cookie.trim() || cookie === 'SETUP_NEEDED') {
17
+ throw new FeishuError('CREDENTIALS_UNAVAILABLE', 'No usable user Cookie is configured.');
18
+ }
19
+ if (/[^\x00-\xff]/.test(cookie) || /[\r\n]/.test(cookie)) {
20
+ throw new FeishuError('CREDENTIALS_INVALID', 'The Cookie contains invalid header characters.');
21
+ }
22
+ return cookie.trim();
23
+ }
package/src/errors.js ADDED
@@ -0,0 +1,22 @@
1
+ export class FeishuError extends Error {
2
+ constructor(code, message, details = {}) {
3
+ super(message);
4
+ this.name = 'FeishuError';
5
+ this.code = code;
6
+ this.details = details;
7
+ }
8
+ }
9
+
10
+ export function requireNumericId(value, label) {
11
+ if (typeof value !== 'string' || !/^\d+$/.test(value)) {
12
+ throw new FeishuError('INVALID_ARGUMENT', `${label} must be a numeric ID from search.`);
13
+ }
14
+ return value;
15
+ }
16
+
17
+ export function requireText(value, label) {
18
+ if (typeof value !== 'string' || !value.trim()) {
19
+ throw new FeishuError('INVALID_ARGUMENT', `${label} must not be empty.`);
20
+ }
21
+ return value;
22
+ }