larkmate 0.1.10 → 0.1.12

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.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: larkmate
3
- description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、搜索与操作消息、收发文件及图片、管理群组,以及查询录制妙记、申请访问权限和导出文字记录。当用户要求使用 LarkMate 或需要执行上述个人飞书操作时使用;不负责飞书文档或日历。
3
+ description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、搜索与操作消息、收发文件及图片、管理群组、飞书任务和日历,以及查询录制妙记、申请访问权限和导出文字记录。当用户要求使用 LarkMate 或需要执行上述个人飞书操作时使用;不负责飞书文档。
4
4
  ---
5
5
 
6
6
  # LarkMate
@@ -15,8 +15,10 @@ description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、
15
15
 
16
16
  - 查找会话、搜索与导出消息、获取链接、下载资源,以及管理会话状态和标签: [会话与消息](references/chats.md)。
17
17
  - 发送与管理消息、文件、图片、表情和收藏,管理群组及成员: [发送与群组](references/writes.md)。
18
+ - 查询和管理飞书任务、任务视图及成员: [飞书任务](references/tasks.md)。
19
+ - 查询和管理日历、日程及邀请: [日历与日程](references/calendar.md)。
18
20
  - 查找录制妙记、导出文字记录、查询或申请访问权限: [录制妙记](references/minutes.md)。
19
21
 
20
22
  命令输出 JSON:成功为 `ok: true`,失败为 `ok: false`,检查退出码和错误信息。飞书网页客户端数字 ID 与开放平台 ID 不同;按实际查询结果选定对象,名称相近时先消歧。列表和搜索有分页或扫描范围,无法读取的内容、缺失结果和权限错误应如实说明。
21
23
 
22
- `chat-open` 会打开或创建私聊;发送、修改消息、表情、收藏、群组、会话状态及妙记权限申请等命令也会修改数据,请按用户的实际意图操作。写入返回 `EFFECT_UNKNOWN`、`submitted_unconfirmed` 或部分成功时,先查询实际状态,避免重复提交。不要将消息已发送当作对方已读。
24
+ `chat-open` 会打开或创建私聊;发送、修改消息、表情、收藏、群组、会话状态、任务、日历及妙记权限申请等命令也会修改数据,请按用户的实际意图操作。写入返回 `EFFECT_UNKNOWN`、`submitted_unconfirmed` 或部分成功时,先查询实际状态,避免重复提交。不要将消息已发送当作对方已读。
@@ -0,0 +1,30 @@
1
+ # 日历与日程
2
+
3
+ `calendars` 查询管理和订阅的日历;`calendar-search` 搜索联系人、会议室和共享日历。`calendar-events` 按时间范围查询并展开重复日程,默认查询主日历,可选择具体日历或全部日历。结束时间为开区间,一次最长查询 366 天;检查 `complete` 和 `warnings`。遇到无法展开的规则应说明,不要当作没有安排。
4
+
5
+ ```sh
6
+ larkmate calendars
7
+ larkmate calendar-search --query '名称'
8
+ larkmate calendar-events --start '2026-11-30T00:00:00+08:00' --end '2026-12-01T00:00:00+08:00'
9
+ larkmate calendar-events --start '2026-11-30T00:00:00+08:00' --end '2026-12-07T00:00:00+08:00' --all-calendars
10
+ larkmate event-get --id "$EVENT_ID"
11
+ larkmate calendar-rooms --start '2026-11-30T10:00:00+08:00' --end '2026-11-30T11:00:00+08:00' --query '会议室'
12
+ ```
13
+
14
+ 时间使用带时区的 ISO 时间或 Unix 秒。重复日程结果中的 `startTime`、`endTime` 和 `originalTime` 对应该次发生,`event` 是系列信息。修改或删除重复日程时根据用户意图传 `--span`(1 本次、2 本次及以后、3 整个系列)和 `--instance-start`;普通日程默认 span 0。日历返回的例外或规则若不完整,展开结果可能与网页不同,重要安排应核对详情。
15
+
16
+ ```sh
17
+ larkmate event-create --title '讨论' --start '2026-11-30T10:00:00+08:00' --end '2026-11-30T10:30:00+08:00' --user "$USER_ID" --reminder 15
18
+ larkmate event-update --id "$EVENT_ID" --description '更新说明' --add-user "$USER_ID"
19
+ larkmate event-share --id "$EVENT_ID" --chat "$CHAT_ID"
20
+ larkmate event-reply --id "$EVENT_ID" --response accept
21
+ larkmate event-delete --id "$EVENT_ID"
22
+ larkmate calendar-create --name '团队日历'
23
+ larkmate calendar-update --id "$CALENDAR_ID" --description '说明'
24
+ larkmate calendar-subscribe --id "$CALENDAR_ID"
25
+ larkmate calendar-unsubscribe --id "$CALENDAR_ID"
26
+ ```
27
+
28
+ `event-create` 和 `event-update` 支持参与人、群组和会议室;完整字段可用 `--json` 传入,结构见包内 `proto/calendar-schema.json` 的 `calendar_entities.WebCalendarEvent`。日历创建和更新的 `--json` 使用 `calendar_entities.WebCalendar` 字段,包括公开范围和共享成员。各字段是否可用取决于当前账号权限与飞书接口。命令选项以 `--help` 为准。
29
+
30
+ 分享日程会向指定会话发送信息;创建、修改或删除日程可能通知参与人;`--no-notify` 请求不通知,具体行为由飞书决定。不要推断用户已授权邀请其他人或修改共享权限。写入返回 `submitted_unconfirmed`、`EFFECT_UNKNOWN` 或部分成功时,先查询实际状态,不盲目重试。
@@ -7,6 +7,10 @@ larkmate search-messages --query '消息关键词' --cursor "$NEXT_CURSOR"
7
7
  larkmate chats --limit 50
8
8
  larkmate chats --cursor "$NEXT_CURSOR"
9
9
  larkmate chats --parent "$BOX_ID"
10
+ larkmate group-query --group unread --pages 3
11
+ larkmate group-query --group at_me --query '关键词'
12
+ larkmate sidebar-list
13
+ larkmate sidebar-set --filter muted --visibility show --position 2
10
14
  larkmate chat-info --chat "$CHAT_ID"
11
15
  larkmate history --chat "$CHAT_ID" --limit 50 --pages 3
12
16
  larkmate message-link --chat "$CHAT_ID" --message "$MESSAGE_ID"
@@ -43,3 +47,7 @@ larkmate label-remove --label "$LABEL_ID" --chat "$CHAT_ID"
43
47
  ```
44
48
 
45
49
  `mark` 对应聊天右键菜单的旗帜“标记”。`read` 会推进到调用时最新可见位置并清除手动未读标记;`unread` 可能把已完成会话放回收件箱。标签创建、重命名和删除分别使用 `label-create`、`label-rename`、`label-delete`,会话成员调整仅支持手动标签。删除标签会删除整个个人标签。
50
+
51
+ `group-query` 支持消息、未读、免打扰、@我、单聊、群组、话题群、云文档、话题和已完成分组;可按名称筛选,使用 `nextCursor` 继续扫描。收纳盒需以 `--parent` 单独查询,`unknownState` 表示无法确定状态的数量。@我通过未读提及消息匹配会话,可能与飞书界面显示不同。标记和标签分别用 `marked`、`labels` 和 `label-chats` 查询。
52
+
53
+ `sidebar-set` 可以显示、隐藏或排序分组,并设置其在消息分组中的展示规则和 @所有人选项;使用 `larkmate sidebar-set --help` 查看参数。修改前先查询当前设置。
@@ -0,0 +1,22 @@
1
+ # 飞书任务
2
+
3
+ `task-center` 查询任务中心及视图;`tasks-list` 支持 mine、followed、all、created、assigned 和 completed 视图。可按关键词搜索、读取、新建、编辑、完成、重开和删除任务。
4
+
5
+ `tasks-list` 使用返回的 `nextCursor` 继续分页;任务列表发生变化时需从头查询。注意 `missing` 和 `serverReportedAllTasks`,不要把服务端未返回的任务当成不存在。
6
+
7
+ ```sh
8
+ larkmate task-center
9
+ larkmate tasks-list --scope mine --limit 50
10
+ larkmate tasks-list --scope mine --cursor "$NEXT_CURSOR"
11
+ larkmate task-search --query '关键词'
12
+ larkmate task-get --id "$TASK_ID"
13
+ larkmate task-create --title '任务标题' --description '说明' --due '2026-12-01T18:00:00+08:00' --assignee "$USER_ID" --follower "$FOLLOWER_ID"
14
+ larkmate task-update --id "$TASK_ID" --due '2026-12-02T18:00:00+08:00' --add-assignee "$USER_ID"
15
+ larkmate task-complete --id "$TASK_ID"
16
+ larkmate task-reopen --id "$TASK_ID"
17
+ larkmate task-delete --id "$TASK_ID"
18
+ ```
19
+
20
+ 开始和截止时间可用毫秒时间戳或 ISO 日期;更新时用 `0` 清除时间。创建支持全天、重复规则、所属清单和积分等选项,使用 `task-create --help` 查看。`--json` 可从调用方本地文件或标准输入读取完整 `todo_entities.InputTask` JSON,提供提醒、子任务、附件引用和自定义字段等高级配置;字段结构参照包内 `proto/todo-schema.json`。常用参数覆盖 JSON 中对应字段。更新支持标题、描述、时间、重复规则、里程碑、积分、负责人和关注人;`--commits-json` 接受高级字段的原生提交数组(`key`、`dataType`、Base64 编码的 `added`/`deleted`),结构参照同一协议文件。高级字段能否使用由飞书接口和当前用户权限决定。
21
+
22
+ 写入返回 `EFFECT_UNKNOWN`、`submitted_unconfirmed`、部分成功或拒绝时,先重新读取任务并核对状态,不要盲目重试。任务创建、修改、完成和删除会改变飞书数据,只在用户授权范围内操作。
@@ -11,6 +11,17 @@ import { handleFileRequest, brokerUpload, brokerDownload } from './agent-files.j
11
11
  // An explicit mapping prevents callers from reaching arbitrary object methods.
12
12
  const routes = {
13
13
  status: ['client', 'status', 'global'], search: ['client', 'search', 'global'],
14
+ 'calendars': ['calendar','calendars','global'], 'calendar-search': ['calendar','searchCalendars','global'],
15
+ 'calendar-events': ['calendar','events','global'], 'event-get': ['calendar','event','global'], 'calendar-rooms': ['calendar','rooms','global'],
16
+ 'event-create': ['calendar','createEvent','global'], 'event-update': ['calendar','updateEvent','global'], 'event-delete': ['calendar','deleteEvent','global'],
17
+ 'event-share': ['calendar','share','allChats'], 'event-reply': ['calendar','reply','global'], 'calendar-create': ['calendar','createCalendar','global'], 'calendar-update': ['calendar','updateCalendar','global'],
18
+ 'calendar-delete': ['calendar','deleteCalendar','global'], 'calendar-subscribe': ['calendar','subscription','global'], 'calendar-unsubscribe': ['calendar','subscription','global'],
19
+ 'group-query': ['feeds', 'query', 'allChats'],
20
+ 'task-center': ['tasks', 'center', 'global'], 'tasks-list': ['tasks', 'list', 'global'],
21
+ 'task-search': ['tasks', 'search', 'global'], 'task-get': ['tasks', 'get', 'global'],
22
+ 'task-create': ['tasks', 'create', 'global'], 'task-update': ['tasks', 'update', 'global'],
23
+ 'task-complete': ['tasks', 'complete', 'global'], 'task-reopen': ['tasks', 'complete', 'global'], 'task-delete': ['tasks', 'delete', 'global'],
24
+ 'sidebar-list': ['sidebar', 'list', 'global'], 'sidebar-set': ['sidebar', 'set', 'allChats'],
14
25
  'search-messages': ['client', 'searchMessages', 'allChats'], chats: ['client', 'chats', 'allChats'],
15
26
  pinned: ['controls', 'pinned', 'allChats'], marked: ['controls', 'marked', 'allChats'],
16
27
  labels: ['controls', 'labels', 'allChats'], 'label-chats': ['controls', 'labelChats', 'allChats'],
@@ -44,7 +55,7 @@ const routes = {
44
55
  const writes = new Set(['send', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread',
45
56
  'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
46
57
  'group-update', 'group-dissolve', 'group-bot-protection', 'message-edit', 'message-forward', 'message-recall', 'favorite-add',
47
- 'favorite-remove', 'reaction-add', 'reaction-remove', 'minutes-request-access', 'send-file', 'send-image']);
58
+ 'favorite-remove', 'reaction-add', 'reaction-remove', 'minutes-request-access', 'send-file', 'send-image', 'sidebar-set', 'task-create', 'task-update', 'task-complete', 'task-reopen', 'task-delete', 'event-create', 'event-update', 'event-delete', 'event-share', 'event-reply', 'calendar-create', 'calendar-update', 'calendar-delete', 'calendar-subscribe', 'calendar-unsubscribe']);
48
59
 
49
60
  export function brokerCommands() {
50
61
  return Object.entries(routes).map(([command, [, , scope]]) => ({ command,
@@ -116,6 +127,8 @@ export function authorize(policy, request) {
116
127
  const args = request.args;
117
128
  const chatAllowed = id => numeric(id) && (policy.allowAllChats || policy.chatIds.includes(id));
118
129
  if (scope === 'global' && !policy.allowGlobal) denied();
130
+ if (['calendar-subscribe', 'calendar-unsubscribe'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].subscribe !== (request.command === 'calendar-subscribe'))) denied();
131
+ if (['task-complete', 'task-reopen'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].completed !== (request.command === 'task-complete'))) denied();
119
132
  if (['allChats', 'labelTrue', 'labelFalse', 'reactionAdd', 'reactionRemove'].includes(scope) && (!policy.allowGlobal || !policy.allowAllChats)) denied();
120
133
  if (scope === 'allMinutes' && (!policy.allowGlobal || !policy.allowAllMinutes)) denied();
121
134
  if (scope === 'file' && (args.length !== 1 || !only(args[0], method === 'download' ? ['chatId', 'messageId', 'key', 'position'] : ['chatId']) || !chatAllowed(args[0].chatId))) denied();
@@ -0,0 +1,125 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import rrule from 'rrule';
3
+ import { FeishuError } from './errors.js';
4
+ const { RRule } = rrule;
5
+ const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
6
+ const fail = message => { throw new FeishuError('INVALID_ARGUMENT', message); };
7
+ const object = v => v && typeof v === 'object' && !Array.isArray(v);
8
+ const requireId = v => { if (typeof v !== 'string' || !v || v.length > 512) fail('An identifier is required.'); return v; };
9
+ export function epoch(value) {
10
+ if (typeof value !== 'string' && typeof value !== 'number') fail('A date or Unix timestamp is required.');
11
+ const s = String(value); let n;
12
+ if (/^\d+$/.test(s)) n = Number(s); else { if (!/(Z|[+-]\d\d:\d\d)$/i.test(s)) fail('Use an ISO date-time with an explicit timezone, or Unix seconds.'); n = Date.parse(s) / 1000; }
13
+ if (!Number.isSafeInteger(n) || n < 0) fail('Invalid time.'); return n;
14
+ }
15
+ function validate(type, data, path = 'input') {
16
+ if (!object(data)) fail(`${path} must be an object.`); type.resolveAll();
17
+ for (const [key,value] of Object.entries(data)) {
18
+ const f = type.fields[key]; if (!f) fail(`Unknown field ${path}.${key}.`);
19
+ const check = v => { if (f.resolvedType?.fields) validate(f.resolvedType,v,`${path}.${key}`);
20
+ else if (f.resolvedType?.values && !(typeof v === 'string' && Object.hasOwn(f.resolvedType.values,v)) && !(Number.isInteger(v) && Object.values(f.resolvedType.values).includes(v))) fail(`Invalid ${path}.${key}.`); };
21
+ if (f.map) { if (!object(value)) fail(`${path}.${key} must be an object.`); Object.values(value).forEach(check); }
22
+ else if (f.repeated) { if (!Array.isArray(value)) fail(`${path}.${key} must be an array.`); value.forEach(check); }
23
+ else check(value);
24
+ }
25
+ const err = type.verify(type.fromObject(data)); if (err) fail(`${path}: ${err}`);
26
+ }
27
+ function localAsUtc(seconds, zone) {
28
+ const parts = new Intl.DateTimeFormat('en-US', { timeZone: zone, year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit',hourCycle:'h23' }).formatToParts(new Date(seconds*1000));
29
+ const d = Object.fromEntries(parts.map(x => [x.type,x.value])); return new Date(Date.UTC(+d.year,+d.month-1,+d.day,+d.hour,+d.minute,+d.second));
30
+ }
31
+ function wallToEpoch(wall, zone) {
32
+ let guess=wall.getTime(); const target=wall.getTime();
33
+ for(let i=0;i<4;i++){const delta=target-localAsUtc(guess/1000,zone).getTime();if(!delta)return Math.floor(guess/1000);guess+=delta;}
34
+ if(localAsUtc(guess/1000,zone).getTime()!==target)throw Error('Nonexistent local time');return Math.floor(guess/1000);
35
+ }
36
+ export function expandEvents(events, from, to) {
37
+ const out = [], warnings = [], exceptions = new Map();
38
+ for (const e of events) if (Number(e.originalTime) > 0) exceptions.set(`${e.calendarId}\0${e.key}\0${e.originalTime}`,e);
39
+ for (const e of events) {
40
+ if (e.isDeleted || e.status === 3) continue;
41
+ const start = Number(e.startTime), end = Number(e.endTime), duration = Math.max(0,end-start);
42
+ if (!e.rrule) { if (start < to && end > from) out.push({ event:e, startTime:String(start), endTime:String(end), recurring:false }); continue; }
43
+ try {
44
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || !e.startTimezone) throw Error();
45
+ const options = RRule.parseString(e.rrule.replace(/^RRULE:/i,'')); options.dtstart = localAsUtc(start,e.startTimezone);
46
+ const until = options.until ? Math.floor(options.until.getTime()/1000) : null; if (until != null) options.until=localAsUtc(until,e.startTimezone);
47
+ const dates = new RRule(options).between(new Date((from-duration-172800)*1000),new Date((to+172800)*1000),true,(_date,index)=>index<10000);
48
+ if (dates.length >= 10000) throw Error();
49
+ for (const date of dates) { const t = wallToEpoch(date,e.startTimezone); if ((until != null && t>until) || t < start || t >= to || t+duration <= from || exceptions.has(`${e.calendarId}\0${e.key}\0${t}`)) continue;
50
+ out.push({ event:e, startTime:String(t), endTime:String(t+duration), recurring:true, originalTime:String(t) }); }
51
+ } catch { warnings.push({ code:'RECURRENCE_UNEXPANDED', eventId:e.id, calendarId:e.calendarId }); }
52
+ }
53
+ out.sort((a,b)=>Number(a.startTime)-Number(b.startTime)); return { items:out, warnings };
54
+ }
55
+ export class Calendar {
56
+ constructor(gateway) { this.gateway=gateway; }
57
+ async call(command,type,body,response,write=false,operation='calendar') {
58
+ const r=await this.gateway.call(command,type,body,{mutating:write,operation});
59
+ return this.gateway.decode(response,r.packet.payload || new Uint8Array());
60
+ }
61
+ async calendars({ maxPages=20 }={}) {
62
+ if (!Number.isInteger(maxPages)||maxPages<1||maxPages>100) fail('Invalid calendar page count.');
63
+ let token='',items=[],seen=new Set(),more=false;
64
+ for(let i=0;i<maxPages;i++){let r=await this.call(1001001,'calendar_web.ListCalendarsRequest',{pageSize:200,...(token?{syncToken:token}:{})},'calendar_web.ListCalendarsResponse');
65
+ if(!r)throw new FeishuError('INVALID_RESPONSE','Calendars were not returned.'); items.push(...r.calendars.filter(x=>!x.isDeleted)); more=r.hasMore;
66
+ if(!more){token='';break}if(!r.nextSyncToken||seen.has(r.nextSyncToken))throw new FeishuError('PAGINATION_INCOMPLETE','Calendar pagination could not advance.');token=r.nextSyncToken;seen.add(token);}
67
+ return {items,complete:!more,nextCursor:token||null};
68
+ }
69
+ async searchCalendars({query,offset=0,count=20}={}) { if(typeof query!=='string'||!query.trim()||!Number.isInteger(offset)||offset<0||!Number.isInteger(count)||count<1||count>100)fail('Invalid calendar search.');
70
+ let r=await this.call(1000017,'calendars.MultiCalendarSearchRequest',{query,offset,count,needSearchMeetingRoom:true,needSearchSharedCalendar:true,needSearchPrimaryCalendar:true},'calendars.MultiCalendarSearchResponse'); if(!r)throw new FeishuError('INVALID_RESPONSE','Calendar search was not returned.'); return {items:r.contents,calendarBriefMap:r.calendarBriefMap,calendarChatterMap:r.calendarChatterMap,chatterMap:r.chatterMap}; }
71
+ async rooms({start,end,query='',count=50,cursor=0,timezone=defaultTimezone,rrule}={}) {start=epoch(start);end=epoch(end);if(end<=start||typeof query!=='string'||!Number.isInteger(count)||count<1||count>100||!Number.isInteger(cursor)||cursor<0)fail('Invalid room search.');
72
+ let r=await this.call(1000016,'calendar_events.SearchMeetingRoomsRequest',{startTime:String(start),endTime:String(end),keyword:query,count,cursor,startTimezone:timezone,...(rrule?{rrule}:{})},'calendar_events.SearchMeetingRoomsResponse');if(!r)throw new FeishuError('INVALID_RESPONSE','Meeting rooms were not returned.');return {items:r.buildings,hasMore:r.hasMore,nextCursor:r.hasMore?r.cursor:null}; }
73
+ async events({start,end,calendarIds=[],allCalendars=false,maxPages=20}={}) {
74
+ let from=epoch(start),to=epoch(end);if(to<=from||to-from>366*86400||!Array.isArray(calendarIds)||!Number.isInteger(maxPages)||maxPages<1||maxPages>100)fail('Use a valid range of at most 366 days.');
75
+ let cal=await this.calendars();if(!cal.complete)throw new FeishuError('PAGINATION_INCOMPLETE','Calendar list is incomplete.');
76
+ let ids=calendarIds.length?calendarIds.map(requireId):cal.items.filter(x=>allCalendars||x.isPrimary).map(x=>x.id);if(!ids.length)throw new FeishuError('NOT_FOUND','No selected calendar was found.');
77
+ let events=[],pending=ids.map(calendarId=>({calendarId,timeMin:String(from),timeMax:String(to),pageSize:200,filters:{maxAttendeesCountPerEvent:100,needsReminders:true,needsDescription:true,maxResourcesCountPerEvent:100}})),seen=new Set();
78
+ for(let i=0;i<maxPages&&pending.length;i++){let r=await this.call(1002001,'calendar_web.ListCalendarEventsRequest',{params:pending},'calendar_web.ListCalendarEventsResponse');if(!r)throw new FeishuError('INVALID_RESPONSE','Calendar events were not returned.');let next=[];
79
+ for(const p of pending){let result=r.results[p.calendarId];if(!result)throw new FeishuError('INVALID_RESPONSE','A selected calendar was omitted.');events.push(...result.calendarEvents);if(result.nextPageToken){const k=p.calendarId+'\0'+result.nextPageToken;if(seen.has(k))throw new FeishuError('PAGINATION_INCOMPLETE','Event pagination repeated its cursor.');seen.add(k);next.push({...p,pageToken:result.nextPageToken})}}pending=next;}
80
+ let expanded=expandEvents(events,from,to);return {...expanded,series:events.filter(e=>e.rrule),complete:pending.length===0,remainingCalendars:pending.map(x=>x.calendarId),range:{start:String(from),end:String(to)}};
81
+ }
82
+ async event({eventId}) { let r=await this.call(1002006,'calendar_web.MGetEventsWithIdsRequest',{ids:[requireId(eventId)]},'calendar_web.MGetEventsWithIdsResponse');let event=r?.events?.[eventId]||Object.values(r?.events||{}).find(x=>x.id===eventId);if(!event)throw new FeishuError('NOT_FOUND','Event not found or inaccessible.');return {event}; }
83
+ async attendees({users=[],groups=[],calendars=[]}={}) { if(![users,groups,calendars].every(Array.isArray))fail('Invalid attendees.');let items=[];
84
+ for(const [values,cmd,req,res,key,param] of [[users,1002008,'GetUserAttendeesByUserIdsRequest','GetUserAttendeesByUserIdsResponse','userAttendees','userIds'],[groups,1002007,'GetGroupAttendeesByGroupIdsRequest','GetGroupAttendeesByGroupIdsResponse','groupAttendees','groupIds'],[calendars,1002009,'GetAttendeesByCalendarIdsRequest','GetAttendeesByCalendarIdsResponse','attendees','calendarIds']])if(values.length){values.forEach(requireId);let r=await this.call(cmd,`calendar_web.${req}`,{[param]:values},`calendar_web.${res}`);if(!r)throw new FeishuError('INVALID_RESPONSE','Attendees could not be resolved.');for(const id of values){if(!r[key]?.[id])throw new FeishuError('NOT_FOUND','An attendee could not be resolved.');items.push(r[key][id]);}}
85
+ return {items}; }
86
+ async createEvent({input={},title,start,end,calendarId,timezone=defaultTimezone,description,allDay,repeat,users=[],groups=[],rooms=[],notify=true}={}) {
87
+ if(!object(input))fail('Event input must be an object.'); await this.gateway.authenticate();await this.gateway.ensureCalendarProto();
88
+ if(!calendarId){const c=await this.calendars();calendarId=c.items.find(x=>x.isPrimary)?.id}requireId(calendarId);
89
+ let event={...input,id:'0',key:input.key||randomUUID(),calendarId,organizerCalendarId:input.organizerCalendarId||calendarId,creatorCalendarId:input.creatorCalendarId||calendarId,source:1,status:input.status||2,selfAttendeeStatus:2};
90
+ if(title!=null)event.summary=title;if(description!=null)event.description=description;if(start!=null)event.startTime=String(epoch(start));if(end!=null)event.endTime=String(epoch(end));if(allDay!=null)event.isAllDay=allDay;if(repeat!=null)event.rrule=repeat;
91
+ event.startTimezone=event.startTimezone||timezone;event.endTimezone=event.endTimezone||timezone;
92
+ if(!event.summary||Number(event.endTime)<=Number(event.startTime)||!Number.isSafeInteger(Number(event.startTime))||!Number.isSafeInteger(Number(event.endTime)))fail('A title and valid start/end are required.');
93
+ if(users.length||groups.length||rooms.length) event.attendees=[...(event.attendees||[]),...(await this.attendees({users,groups,calendars:rooms})).items];
94
+ validate(this.gateway.calendarProto.lookupType('calendar_entities.WebCalendarEvent'),event);
95
+ await this.call(1002003,'calendar_web.CreateEventRequest',{event,notificationType:notify?1:2},'calendar_web.CreateEventResponse',true,'event-create');
96
+ return {status:'submitted_unconfirmed',calendarId,key:event.key,startTime:String(event.startTime),endTime:String(event.endTime)};
97
+ }
98
+ async updateEvent({eventId,patch={},span=0,instanceStart,notify=true,addUsers=[],removeUsers=[],addGroups=[],removeGroups=[],addRooms=[],removeRooms=[]}={}) {
99
+ if(!object(patch)||!Number.isInteger(span)||span<0||span>3)fail('Invalid event update.');const current=(await this.event({eventId})).event;
100
+ let type=this.gateway.calendarProto.lookupType('calendar_entities.WebCalendarEvent'),data=type.toObject(current,{longs:String,enums:Number,bytes:String});
101
+ for(const k of ['id','key','calendarId','creatorCalendarId','organizerCalendarId','originalTime','source','status','isDeleted','selfAttendeeStatus'])if(Object.hasOwn(patch,k))fail(`Cannot change event identity field ${k}.`);
102
+ const memberLists=[addUsers,removeUsers,addGroups,removeGroups,addRooms,removeRooms];if(!memberLists.every(Array.isArray))fail('Attendee changes must be arrays.');
103
+ if(memberLists.some(x=>x.length)&&Object.hasOwn(patch,'attendees'))fail('Do not combine attendee replacement with add/remove options.');
104
+ if(memberLists.some(x=>x.length)){
105
+ let attendees=[...(data.attendees||[])];
106
+ for(const [ids,match] of [[removeUsers,x=>x.user?.userId],[removeGroups,x=>x.group?.groupId],[removeRooms,x=>x.attendeeCalendarId]])for(const id of ids){requireId(id);let index=attendees.findIndex(x=>match(x)===id);if(index<0)fail('An attendee to remove was not found.');attendees.splice(index,1);}
107
+ if(addUsers.length||addGroups.length||addRooms.length)attendees.push(...(await this.attendees({users:addUsers,groups:addGroups,calendars:addRooms})).items);
108
+ patch={...patch,attendees};
109
+ }
110
+ let event={...data,...patch}; if (patch.startTime != null) event.startTime=String(epoch(patch.startTime)); if (patch.endTime != null) event.endTime=String(epoch(patch.endTime)); validate(type,event);if(Number(event.endTime)<=Number(event.startTime))fail('End must be after start.');
111
+ await this.call(1002004,'calendar_web.UpdateEventRequest',{event,span, ...(instanceStart!=null?{instanceStartTime:String(epoch(instanceStart))}:{}),notificationType:notify?1:2},'calendar_web.UpdateEventResponse',true,'event-update');return {status:'submitted_unconfirmed',eventId};
112
+ }
113
+ async deleteEvent({eventId,span=0,instanceStart,notify=true}={}) {if(!Number.isInteger(span)||span<0||span>3)fail('Invalid event span.');let {event}=await this.event({eventId});
114
+ await this.call(1002005,'calendar_web.DeleteEventRequest',{calendarId:event.calendarId,key:event.key,originalTime:String(event.originalTime||0),span,instanceStartTime:String(instanceStart!=null?epoch(instanceStart):event.startTime),notificationType:notify?1:2},'calendar_web.DeleteEventResponse',true,'event-delete');return {status:'submitted_unconfirmed',eventId}; }
115
+ async share({eventId,chatIds=[]}={}) { if(!Array.isArray(chatIds)||!chatIds.length||chatIds.some(id=>typeof id!=='string'||!/^\d{1,19}$/.test(id)))fail('At least one numeric chat ID is required.');let {event}=await this.event({eventId});
116
+ let r=await this.call(1002012,'calendar_web.ShareCalendarEventRequest',{chatIds,calendarId:event.calendarId,key:event.key,originalTime:String(event.originalTime||0)},'calendar_web.ShareCalendarEventResponse',true,'event-share');return {status:r.sharedFailedChats?.length?'partially_rejected':'submitted_unconfirmed',eventId,failedChats:(r.sharedFailedChats||[]).map(String)}; }
117
+ async reply({eventId,response,comment,quitMeeting=false}={}) {let replyType={accept:1,decline:2,tentative:3}[response];if(!replyType)fail('Invalid invitation response.');let {event}=await this.event({eventId});
118
+ await this.call(1020002,'calendar_events.ReplyCalendarEventInvitationRequest',{calendarEventKey:{uniqueKey:event.key,calendarId:event.calendarId,originalTime:String(event.originalTime||0)},replyType,quitMeeting,...(comment?{rsvpCommentInfo:{comment}}:{})},'calendar_events.ReplyCalendarEventInvitationResponse',true,'event-reply');return {status:'submitted_unconfirmed',eventId,response}; }
119
+ async createCalendar({input={},name,description,timezone=defaultTimezone}={}) {if(!object(input))fail('Calendar input must be an object.');let u=await this.gateway.authenticate();await this.gateway.ensureCalendarProto();let calendar={...input,creatorUserId:u.id,defaultTimezone:input.defaultTimezone||timezone,defaultAccessRole:input.defaultAccessRole??1,visibilityProperty:input.visibilityProperty??32};if(name!=null)calendar.summary=name;if(description!=null)calendar.description=description;if(!calendar.summary)fail('Calendar name is required.');validate(this.gateway.calendarProto.lookupType('calendar_entities.WebCalendar'),calendar);
120
+ await this.call(1001004,'calendar_web.CreateCalendarRequest',{calendar},'calendar_web.CreateCalendarResponse',true,'calendar-create');return {status:'submitted_unconfirmed',name:calendar.summary}; }
121
+ async updateCalendar({calendarId,patch={}}={}) {requireId(calendarId);if(!object(patch)||['id','creatorUserId','isPrimary','type'].some(k=>Object.hasOwn(patch,k)))fail('Invalid calendar patch.');let found=(await this.calendars()).items.find(x=>x.id===calendarId);if(!found)throw new FeishuError('NOT_FOUND','Calendar not found.');let type=this.gateway.calendarProto.lookupType('calendar_entities.WebCalendar'),calendar={...type.toObject(found,{longs:String,enums:Number,bytes:String}),...patch};validate(type,calendar);await this.call(1001006,'calendar_web.UpdateCalendarRequest',{calendar},'calendar_web.UpdateCalendarResponse',true,'calendar-update');return {status:'submitted_unconfirmed',calendarId}; }
122
+ async deleteCalendar({calendarId}={}) {requireId(calendarId);let found=(await this.calendars()).items.find(x=>x.id===calendarId);if(!found||found.isPrimary)fail('Cannot delete the primary or an unknown calendar.');await this.call(1001005,'calendar_web.DeleteCalendarRequest',{calendarId},'calendar_web.DeleteCalendarResponse',true,'calendar-delete');return {status:'submitted_unconfirmed',calendarId}; }
123
+ async subscription({calendarId,subscribe}={}) {requireId(calendarId);if(typeof subscribe!=='boolean')fail('Invalid subscription.');let r=await this.call(subscribe?1001002:1001003,`calendar_web.Batch${subscribe?'Subscribe':'Unsubscribe'}CalendarsRequest`,{calendarIds:[calendarId],...(subscribe?{visibilityMask:[32]}:{}),subscriptionMask:[1]},`calendar_web.Batch${subscribe?'Subscribe':'Unsubscribe'}CalendarsResponse`,true,subscribe?'calendar-subscribe':'calendar-unsubscribe');
124
+ if(!r)return {status:'submitted_unconfirmed',calendarId};let rejected=subscribe?!!r.normalViewFailedCalendarIdErrCodeMap?.[calendarId]:r.failedCalendarIds.includes(calendarId);return {status:rejected?'rejected':'submitted',calendarId}; }
125
+ }
@@ -0,0 +1,82 @@
1
+ import { FeishuError } from './errors.js';
2
+
3
+ const valid = new Set(['messages', 'unread', 'muted', 'at_me', 'p2p', 'group', 'topic_group', 'docs', 'threads', 'done']);
4
+ const numeric = value => typeof value === 'string' && /^\d{1,19}$/.test(value);
5
+ const own = (o, k) => !!o && Object.hasOwn(o, k);
6
+
7
+ export class FeedGroups {
8
+ constructor(gateway) { this.gateway = gateway; }
9
+ async atMessages() {
10
+ const p = await this.gateway.call(96, 'PullUnreadAtMessageIdsRequest', {}, { operation: 'group-query' });
11
+ if (!own(p.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Unread mention data was not returned.');
12
+ const ids = this.gateway.decode('PullUnreadAtMessageIdsResponse', p.packet.payload).messageIds;
13
+ const byChat = new Map(); let missing = 0;
14
+ for (let i = 0; i < ids.length; i += 100) {
15
+ const r = await this.gateway.call(8, 'PullMessagesByIdsRequest', { messageIds: ids.slice(i, i + 100) }, { operation: 'group-query' });
16
+ if (!own(r.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Mention messages were not returned.');
17
+ const messages = this.gateway.decode('PullMessagesByIdsResponse', r.packet.payload).messages;
18
+ for (const id of ids.slice(i, i + 100)) {
19
+ const m = messages[id]; if (!m?.chatId) { missing++; continue; }
20
+ const list = byChat.get(m.chatId) || []; list.push(id); byChat.set(m.chatId, list);
21
+ }
22
+ }
23
+ return { byChat, missing, total: ids.length };
24
+ }
25
+ async page({ group, cursor, parent, limit }) {
26
+ const r = await this.gateway.call(1000, 'PullFeedCardsRequest', { type: group === 'done' ? 2 : 1,
27
+ pullType: cursor ? 2 : 1, count: limit, ...(cursor ? { cursor } : {}), ...(parent ? { parentCardId: parent } : {}) },
28
+ { operation: 'group-query', version: '5.7.0' });
29
+ if (!own(r.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Feed page was not returned.');
30
+ return this.gateway.decode('PullFeedCardsResponse', r.packet.payload);
31
+ }
32
+ async query({ group, query, limit = 100, pages = 20, cursor, parent } = {}) {
33
+ if (!valid.has(group) || !Number.isInteger(limit) || limit < 1 || limit > 100 || !Number.isInteger(pages) || pages < 1 || pages > 100 ||
34
+ (query != null && typeof query !== 'string') || (cursor != null && !numeric(cursor)) || (parent != null && !numeric(parent))) {
35
+ throw new FeishuError('INVALID_ARGUMENT', 'Invalid group query or pagination.');
36
+ }
37
+ const mention = group === 'at_me' ? await this.atMessages() : null;
38
+ let next = cursor, items = [], boxes = [], scanned = 0, unknown = 0; const seen = new Set();
39
+ for (let i = 0; i < pages; i++) {
40
+ const page = await this.page({ group, cursor: next, parent, limit });
41
+ const settings = {};
42
+ if (group === 'muted') {
43
+ const ids = page.cards.filter(c => c.type === 1).map(c => c.id);
44
+ if (ids.length) {
45
+ const r = await this.gateway.call(62, 'PullChatSettingsRequest', { chatIds: ids }, { operation: 'group-query' });
46
+ if (!own(r.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Notification settings were not returned.');
47
+ Object.assign(settings, this.gateway.decode('PullChatSettingsResponse', r.packet.payload).chatSettings);
48
+ }
49
+ }
50
+ for (const card of page.cards) {
51
+ if (card.type === 5) { boxes.push({ id: String(card.id) }); continue; }
52
+ const id = String(card.id), chat = page.chats[id], doc = page.docFeeds[id], thread = page.threads[id];
53
+ let item;
54
+ if (card.type === 1) {
55
+ const count = own(chat, 'newMessageCount') ? chat.newMessageCount : null;
56
+ const manual = card.feedCardField ? (card.feedCardField.markAsUnread?.unread ?? false) : null;
57
+ const unread = count > 0 || manual === true ? true : count === 0 && manual === false ? false : null;
58
+ item = { id, type: ({ 1: 'p2p', 2: 'group', 3: 'topic_group' })[chat?.type] || 'unknown', name: chat?.name || '', unread, unreadCount: count };
59
+ if (group === 'muted') item.muted = own(settings[id], 'isRemind') ? !settings[id].isRemind : null;
60
+ if (mention?.byChat.has(id)) item.atMessageIds = mention.byChat.get(id);
61
+ } else if (card.type === 3) item = { id, type: 'docs', name: doc?.title || '', unreadCount: own(doc, 'newMessageCount') ? doc.newMessageCount : null, url: doc?.url || null };
62
+ else if (card.type === 4) item = { id, type: 'threads', name: thread?.topic || '', chatId: thread?.channelId || null, unreadCount: own(thread, 'newMessageCount') ? thread.newMessageCount : null };
63
+ else continue;
64
+ scanned++;
65
+ if (group === 'unread') {
66
+ const state = item.type === 'docs' || item.type === 'threads' ? (item.unreadCount == null ? null : item.unreadCount > 0) : item.unread;
67
+ if (state == null) { unknown++; continue; } if (!state) continue;
68
+ } else if (group === 'muted') { if (item.muted == null) { unknown++; continue; } if (!item.muted) continue; }
69
+ else if (group === 'at_me') { if (!mention.byChat.has(id)) continue; }
70
+ else if (!['messages', 'done'].includes(group) && item.type !== group) continue;
71
+ if (query && !item.name.toLocaleLowerCase().includes(query.toLocaleLowerCase())) continue;
72
+ items.push(item);
73
+ }
74
+ const cursorValue = own(page, 'nextCursor') && String(page.nextCursor) !== '0' ? String(page.nextCursor) : null;
75
+ if (!cursorValue) { next = null; break; }
76
+ if (seen.has(cursorValue) || cursorValue === next) throw new FeishuError('PAGINATION_INCOMPLETE', 'Feed pagination repeated its cursor.');
77
+ seen.add(cursorValue); next = cursorValue;
78
+ }
79
+ return { group, items, boxes, scanned, unknownState: unknown, nextCursor: next ?? null, complete: next == null,
80
+ ...(mention ? { mentionMessages: mention.total, unmappedMentionMessages: mention.missing } : {}) };
81
+ }
82
+ }
package/src/gateway.js CHANGED
@@ -1,9 +1,14 @@
1
1
  import { randomBytes, randomUUID } from 'node:crypto';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import protobuf from 'protobufjs';
4
+ import { readFile } from 'node:fs/promises';
4
5
  import { FeishuError } from './errors.js';
5
6
 
6
7
  const protoFile = fileURLToPath(new URL('../proto/lark.proto', import.meta.url));
8
+ const calendarProtoFile = fileURLToPath(new URL('../proto/calendar-schema.json', import.meta.url));
9
+ let calendarProtoPromise;
10
+ const todoProtoFile = fileURLToPath(new URL('../proto/todo-schema.json', import.meta.url));
11
+ let todoProtoPromise;
7
12
  const defaults = {
8
13
  csrf: 'https://internal-api-lark-api.feishu.cn/accounts/csrf',
9
14
  user: 'https://internal-api-lark-api.feishu.cn/accounts/web/user',
@@ -104,7 +109,7 @@ export class Gateway {
104
109
  }
105
110
 
106
111
  encode(name, data) {
107
- const type = this.proto.lookupType(name);
112
+ const type = (/^(calendar_web|calendar_events|calendar_entities|calendars)\./.test(name) ? this.calendarProto : name.startsWith('todo.') || name.startsWith('todo_entities.') ? this.todoProto : this.proto).lookupType(name);
108
113
  const message = type.fromObject(data);
109
114
  const error = type.verify(message);
110
115
  if (error) throw new FeishuError('PROTOCOL_INPUT_INVALID', `Invalid ${name} payload.`);
@@ -112,7 +117,7 @@ export class Gateway {
112
117
  }
113
118
 
114
119
  decode(name, bytes) {
115
- return this.proto.lookupType(name).decode(bytes);
120
+ return (/^(calendar_web|calendar_events|calendar_entities|calendars)\./.test(name) ? this.calendarProto : name.startsWith('todo.') || name.startsWith('todo_entities.') ? this.todoProto : this.proto).lookupType(name).decode(bytes);
116
121
  }
117
122
 
118
123
  async uploadRequest(path, body, contentType) {
@@ -151,8 +156,22 @@ export class Gateway {
151
156
  return { data, requestId };
152
157
  }
153
158
 
159
+ async ensureTodoProto() {
160
+ todoProtoPromise ||= readFile(todoProtoFile, 'utf8').then(text => protobuf.Root.fromJSON(JSON.parse(text)));
161
+ this.todoProto = await todoProtoPromise;
162
+ return this.todoProto;
163
+ }
164
+
165
+ async ensureCalendarProto() {
166
+ calendarProtoPromise ||= readFile(calendarProtoFile, 'utf8').then(text => protobuf.Root.fromJSON(JSON.parse(text)));
167
+ this.calendarProto = await calendarProtoPromise;
168
+ return this.calendarProto;
169
+ }
170
+
154
171
  async call(command, requestType, body, { version = '2.7.0', mutating = false, operation } = {}) {
155
172
  await this.authenticate();
173
+ if (requestType.startsWith('todo.')) await this.ensureTodoProto();
174
+ if (/^(calendar_web|calendar_events|calendar_entities|calendars)\./.test(requestType)) await this.ensureCalendarProto();
156
175
  const requestId = randomUUID();
157
176
  const packet = this.encode('Packet', {
158
177
  payloadType: 1, cmd: command, cid: requestId,
@@ -0,0 +1,80 @@
1
+ import { FeishuError } from './errors.js';
2
+
3
+ export const SIDEBAR_FILTERS = Object.freeze({ at_me: 1, unread: 2, delayed: 3, docs: 4, p2p: 5, group: 6, bot: 7,
4
+ help_desk: 8, topic_group: 9, done: 10, crypto_chat: 11, muted: 12, labels: 13, team: 14, marked: 15,
5
+ threads: 16, unread_over_days: 17, calendar_meetings: 18, instant_meetings: 19, messages: 25, expired_fold: 26 });
6
+ const byId = Object.fromEntries(Object.entries(SIDEBAR_FILTERS).map(([name, id]) => [id, name]));
7
+ const rules = { always: 1, new: 2, never: 3 };
8
+ const msgTypes = { all: 1, at_me: 2, at_all: 3, star_contacts: 4 };
9
+ const invalid = () => { throw new FeishuError('INVALID_ARGUMENT', 'Invalid sidebar filter or settings.'); };
10
+ const idFor = input => typeof input === 'string' && Object.hasOwn(SIDEBAR_FILTERS, input) ? SIDEBAR_FILTERS[input] : /^\d+$/.test(String(input)) && Number(input) > 0 && Number(input) <= 2147483647 ? Number(input) : invalid();
11
+
12
+ export class SidebarFilters {
13
+ constructor(gateway) { this.gateway = gateway; }
14
+ async raw() {
15
+ const res = await this.gateway.call(7022, 'PullSidebarFilterSettingRequest', { needAllFilters: true }, { operation: 'sidebar-list' });
16
+ if (!res.packet.payload?.length) throw new FeishuError('INVALID_RESPONSE', 'No sidebar settings were returned.');
17
+ let p; try { p = this.gateway.decode('PullSidebarFilterSettingResponse', res.packet.payload); } catch { throw new FeishuError('INVALID_RESPONSE', 'Sidebar settings were unreadable.'); }
18
+ if (!p.setting || !Array.isArray(p.setting.usedFilters)) throw new FeishuError('INVALID_RESPONSE', 'Sidebar filter settings were absent.');
19
+ return p;
20
+ }
21
+ view(p) {
22
+ const used = p.setting.usedFilters.map(x => x.systemFilter);
23
+ const available = [...new Set([...used, ...p.allFilters.map(x => x.systemFilter)])].filter(x => Number.isInteger(x) && x > 0);
24
+ const display = p.setting.filterDisplayFeedRule || {};
25
+ return { items: available.map(id => ({ id, name: byId[id] || `unknown_${id}`, shown: used.includes(id),
26
+ position: used.includes(id) ? used.indexOf(id) + 1 : null,
27
+ displayRule: display[id] ? { mainRule: display[id].mainRule ?? null, msgTypes: display[id].msgTypes || [] } : null })),
28
+ showFilter: p.setting.showFilter ?? null, showMuteFilter: p.setting.showMuteFilter ?? null,
29
+ showAtAllInAtFilter: p.setting.showAtAllInAtFilter ?? null, flagSortingRule: p.setting.flagSortingRule ?? null, commonlyUsedFilters: p.setting.commonlyUsedFilters?.map(x => x.systemFilter) || [], version: p.setting.version?.toString() ?? null };
30
+ }
31
+ async list() { return this.view(await this.raw()); }
32
+ async set({ filter, visibility, position, display, messageTypes, atAll, showFilter, showMuteFilter, flagSortingRule, commonlyUsedFilters }) {
33
+ const id = idFor(filter);
34
+ if (visibility != null && !['show', 'hide'].includes(visibility)) invalid();
35
+ if (position != null && (!Number.isInteger(position) || position < 1)) invalid();
36
+ if (display != null && !Object.hasOwn(rules, display)) invalid();
37
+ if (messageTypes != null && (!Array.isArray(messageTypes) || messageTypes.some(x => !Object.hasOwn(msgTypes, x)) || new Set(messageTypes).size !== messageTypes.length)) invalid();
38
+ if (messageTypes != null && display == null) invalid();
39
+ if (atAll != null && typeof atAll !== 'boolean') invalid();
40
+ if (atAll != null && id !== SIDEBAR_FILTERS.at_me) invalid();
41
+ if ([showFilter, showMuteFilter].some(x => x != null && typeof x !== 'boolean')) invalid();
42
+ if (flagSortingRule != null && (!Number.isInteger(flagSortingRule) || flagSortingRule < 0 || flagSortingRule > 2147483647)) invalid();
43
+ if (commonlyUsedFilters != null && (!Array.isArray(commonlyUsedFilters) || new Set(commonlyUsedFilters.map(idFor)).size !== commonlyUsedFilters.length)) invalid();
44
+ if (visibility == null && position == null && display == null && atAll == null && showFilter == null && showMuteFilter == null && flagSortingRule == null && commonlyUsedFilters == null) invalid();
45
+ const before = await this.raw(), available = new Set([...before.allFilters, ...before.setting.usedFilters].map(x => x.systemFilter));
46
+ if (!available.has(id)) invalid();
47
+ let ids = before.setting.usedFilters.map(x => x.systemFilter);
48
+ if (new Set(ids).size !== ids.length) throw new FeishuError('INVALID_RESPONSE', 'Sidebar order contains duplicates.');
49
+ const fields = [], request = { clientSupportVersion: before.setting.version?.toString() || '0' };
50
+ if (visibility != null || position != null) {
51
+ if (visibility === 'hide') ids = ids.filter(x => x !== id);
52
+ if (visibility === 'show' && !ids.includes(id)) ids.push(id);
53
+ if (position != null) {
54
+ if (!ids.includes(id) || position > ids.length) invalid();
55
+ ids = ids.filter(x => x !== id); ids.splice(position - 1, 0, id);
56
+ }
57
+ request.usedFilters = ids.map(systemFilter => ({ systemFilter })); fields.push(2);
58
+ }
59
+ let selectedMessageTypes;
60
+ if (display != null) {
61
+ selectedMessageTypes = messageTypes ? messageTypes.map(x => msgTypes[x]) : [...(before.setting.filterDisplayFeedRule?.[id]?.msgTypes || [])];
62
+ request.filterDisplayFeedRule = { ...before.setting.filterDisplayFeedRule,
63
+ [id]: { mainRule: rules[display], msgTypes: selectedMessageTypes } }; fields.push(8);
64
+ }
65
+ if (atAll != null) { request.showAtAllInAtFilter = atAll; fields.push(5); }
66
+ if (showFilter != null) { request.showFilter = showFilter; fields.push(1); }
67
+ if (showMuteFilter != null) { request.showMuteFilter = showMuteFilter; fields.push(3); }
68
+ if (flagSortingRule != null) { request.flagSortingRule = flagSortingRule; fields.push(7); }
69
+ if (commonlyUsedFilters != null) { const common = commonlyUsedFilters.map(idFor); if (common.some(x => !available.has(x))) invalid(); request.commonlyUsedFilters = common.map(systemFilter => ({ systemFilter })); fields.push(6); }
70
+ request.updateFields = fields;
71
+ await this.gateway.call(7023, 'PutSidebarFilterSettingRequest', request, { mutating: true, operation: 'sidebar-set' });
72
+ let after; try { after = await this.raw(); } catch { return { status: 'submitted_unconfirmed', filter: id }; }
73
+ const view = this.view(after), item = view.items.find(x => x.id === id);
74
+ const orderOk = !fields.includes(2) || JSON.stringify(after.setting.usedFilters.map(x => x.systemFilter)) === JSON.stringify(ids);
75
+ const displayOk = display == null || (item?.displayRule?.mainRule === rules[display] && JSON.stringify(item.displayRule.msgTypes) === JSON.stringify(selectedMessageTypes));
76
+ const atAllOk = atAll == null || view.showAtAllInAtFilter === atAll;
77
+ const extraOk = (showFilter == null || view.showFilter === showFilter) && (showMuteFilter == null || view.showMuteFilter === showMuteFilter) && (flagSortingRule == null || view.flagSortingRule === flagSortingRule) && (commonlyUsedFilters == null || JSON.stringify(view.commonlyUsedFilters) === JSON.stringify(commonlyUsedFilters.map(idFor)));
78
+ return { status: orderOk && displayOk && atAllOk && extraOk ? 'updated' : 'submitted_unconfirmed', filter: item };
79
+ }
80
+ }