larkmate 0.1.24 → 0.1.26
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/README.md +4 -2
- package/bin/larkmate.js +20 -2
- package/package.json +1 -1
- package/proto/lark.proto +29 -0
- package/skills/larkmate/references/chats.md +2 -0
- package/skills/larkmate/references/listen.md +2 -0
- package/skills/larkmate/references/writes.md +16 -0
- package/src/agent-broker.js +6 -5
- package/src/client.js +61 -17
- package/src/export-messages.js +20 -3
- package/src/listen-filter.js +4 -4
- package/src/listen.js +5 -14
- package/src/rich-text.js +88 -0
package/README.md
CHANGED
|
@@ -59,8 +59,10 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
|
|
|
59
59
|
- [x] 分页读取指定会话的历史消息
|
|
60
60
|
- [x] 在已扫描的历史消息中按关键词、发送者和时间筛选
|
|
61
61
|
- [x] 按会话、发送者和时间范围分页导出消息到本地文件
|
|
62
|
-
- [x]
|
|
63
|
-
- [
|
|
62
|
+
- [x] 读取文本、链接、提及及部分图片和文件元数据
|
|
63
|
+
- [ ] 完整解析富文本中的图片、表情包和互动卡片
|
|
64
|
+
- [x] 发送文本、链接、飞书表情和带标题的消息,引用回复、@ 用户或所有人
|
|
65
|
+
- [x] 发送文件
|
|
64
66
|
- [x] 全局搜索消息(分页)
|
|
65
67
|
- [x] 编辑文本消息或撤回消息
|
|
66
68
|
- [x] 转发或收藏消息
|
package/bin/larkmate.js
CHANGED
|
@@ -455,7 +455,8 @@ program.command('messages-export').description('Export a conversation to a local
|
|
|
455
455
|
program.command('send').description('Send text once as the user; delivery remains unconfirmed.')
|
|
456
456
|
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
457
457
|
.requiredOption('--text <text>', 'message text')
|
|
458
|
-
.option('--mention <id:name>', 'mention a numeric user or bot ID; repeatable', collect, [])
|
|
458
|
+
.option('--mention <id:name>', 'mention a numeric user or bot ID, or all for everyone; repeatable', collect, [])
|
|
459
|
+
.option('--emoji <key>', 'turn each :key: marker into a Feishu emoji; repeatable', collect, [])
|
|
459
460
|
.option('--reply-to <id>', 'reply to a numeric message ID')
|
|
460
461
|
.option('--reply-root <id>', 'root ID when replying to an existing reply')
|
|
461
462
|
.action(async options => {
|
|
@@ -464,7 +465,24 @@ program.command('send').description('Send text once as the user; delivery remain
|
|
|
464
465
|
if (colon < 1) throw new FeishuError('INVALID_ARGUMENT', 'A mention must use id:name.');
|
|
465
466
|
return { id: value.slice(0, colon), name: value.slice(colon + 1) };
|
|
466
467
|
});
|
|
467
|
-
output(await (await client()).send({ chatId: options.chat, text: options.text, mentions, replyTo: options.replyTo, replyRoot: options.replyRoot }));
|
|
468
|
+
output(await (await client()).send({ chatId: options.chat, text: options.text, mentions, emojis: options.emoji, replyTo: options.replyTo, replyRoot: options.replyRoot }));
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
program.command('emoji-list').description('List available Feishu emoji names and keys.')
|
|
472
|
+
.option('--query <text>', 'filter by emoji name or key')
|
|
473
|
+
.action(async options => output(await (await client()).emojiList({ query: options.query })));
|
|
474
|
+
|
|
475
|
+
program.command('send-rich').description('Send structured text, links, mentions and emoji from JSON.')
|
|
476
|
+
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
477
|
+
.requiredOption('--json <path>', 'JSON file or - for standard input')
|
|
478
|
+
.option('--reply-to <id>', 'reply to a numeric message ID')
|
|
479
|
+
.option('--reply-root <id>', 'root ID when replying to an existing reply')
|
|
480
|
+
.action(async options => {
|
|
481
|
+
const input = await readJson(options.json);
|
|
482
|
+
if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(k => !['segments', 'title'].includes(k))) {
|
|
483
|
+
throw new FeishuError('INVALID_ARGUMENT', 'JSON must contain segments and an optional title.');
|
|
484
|
+
}
|
|
485
|
+
output(await (await client()).sendRich({ chatId: options.chat, segments: input.segments, title: input.title, replyTo: options.replyTo, replyRoot: options.replyRoot }));
|
|
468
486
|
});
|
|
469
487
|
|
|
470
488
|
program.command('send-file').description('Upload and send a local file as the user.')
|
package/package.json
CHANGED
package/proto/lark.proto
CHANGED
|
@@ -199,6 +199,7 @@ message RichTextElement {
|
|
|
199
199
|
FIGURE = 4;
|
|
200
200
|
AT = 5;
|
|
201
201
|
A = 6;
|
|
202
|
+
EMOTION = 10;
|
|
202
203
|
}
|
|
203
204
|
}
|
|
204
205
|
|
|
@@ -213,6 +214,34 @@ message AtProperty {
|
|
|
213
214
|
optional string content = 2;
|
|
214
215
|
}
|
|
215
216
|
|
|
217
|
+
message EmotionProperty {
|
|
218
|
+
optional string key = 1;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
message PullEmojiResourcesV2Request {
|
|
222
|
+
map<string, int32> emojiSetId2version = 1;
|
|
223
|
+
optional bool needUserTenantResources = 2;
|
|
224
|
+
optional int32 accessType = 3;
|
|
225
|
+
}
|
|
226
|
+
message EmojiI18nText {
|
|
227
|
+
optional string defaultText = 1;
|
|
228
|
+
map<string, string> i18nTexts = 2;
|
|
229
|
+
}
|
|
230
|
+
message EmojiResource {
|
|
231
|
+
optional string key = 1;
|
|
232
|
+
optional EmojiI18nText i18nText = 2;
|
|
233
|
+
optional bool isDeleted = 4;
|
|
234
|
+
repeated string skinKeys = 5;
|
|
235
|
+
optional string emojiSetId = 7;
|
|
236
|
+
}
|
|
237
|
+
message EmojiResourceSet {
|
|
238
|
+
optional string setId = 1;
|
|
239
|
+
optional int32 setSource = 2;
|
|
240
|
+
repeated EmojiResource emojiResources = 3;
|
|
241
|
+
optional int32 version = 4;
|
|
242
|
+
}
|
|
243
|
+
message PullEmojiResourcesV2Response { repeated EmojiResourceSet emojiResourceSet = 1; }
|
|
244
|
+
|
|
216
245
|
// For A (hyperlink) elements.
|
|
217
246
|
message AnchorProperty {
|
|
218
247
|
optional string href = 1;
|
|
@@ -22,6 +22,8 @@ larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000
|
|
|
22
22
|
|
|
23
23
|
`chats` 默认读取收件箱的一页,不是全部历史会话。`--type`、`--state` 只过滤当前页,`--scope done` 查询已完成分组;`boxes` 用 `--parent` 单独读取,`nextCursor` 用于翻页。`history` 每页最多 100 个位置,`--pages` 最多 100 页;`--query`、`--sender`、`--after`、`--before` 只过滤已扫描的位置,不是全量搜索。`omittedPositions` 是没有返回的位置数,不是消息数;部分消息类型可能没有可解析正文。
|
|
24
24
|
|
|
25
|
+
历史消息的 `segments` 保留文本、提及、链接和飞书表情代码,`title` 是带标题消息的标题;`textIncomplete` 表示正文未能完整解析,汇总中的 `incompleteText` 是此类消息数。飞书原生表情在纯文本中以 `:代码:` 表示。
|
|
26
|
+
|
|
25
27
|
`search-messages` 用于在当前用户可访问的会话范围内进行跨会话搜索,可使用 `nextCursor` 配合相同的查询条件继续翻页;具体搜索范围和结果由飞书服务决定。`message-link` 返回飞书生成的原生消息链接。`download-file` 根据 `history` 返回的资源键将文件或图片下载至新文件,不会覆盖已有文件;若下载中断,输出文件将不完整。`favorites` 用于读取收藏列表首页,其中 `hasMore` 表示可能仍有未返回的收藏。
|
|
26
28
|
|
|
27
29
|
使用受限代理或系统用户委托下载时,还须传入目标消息的 `--position`,取值为 `history` 返回的 `position`;执行器会核验消息和资源是否属于授权会话。文件大小受策略的 `maxFileBytes` 限制。
|
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
服务订阅支持会话及发送人的 ID、名称和正则,以及消息类型、正文包含/排除、正文正则和排除本人。相同维度的 ID、名称和正则是“或”,不同维度是“且”。大量条件或 `anyOf`、`allOf`、`not` 组合通过 `POST /events` JSON 传入;规则模式支持同样的条件。正则使用 RE2 语法,不支持部分 JavaScript 正则特性。名称解析失败且结果无法确定时会发出 `name_unavailable` 缺口,不猜测匹配;同名对象都会匹配,需要精确区分时使用 ID。
|
|
6
6
|
|
|
7
|
+
消息事件的 `segments` 包含解析出的文本、提及、链接和飞书表情代码;文本过滤也检查带标题消息的标题。`textIncomplete` 表示未能完整解析,无法安全判断的文本规则会产生缺口事件。
|
|
8
|
+
|
|
7
9
|
通过 `listen-service --policy <绝对路径>` 为每个 API key 限定会话、发送人和类型;订阅过滤条件只能缩小授权范围。未配置策略时依靠 socket 文件权限控制访问。授权配置及订阅示例见 [API 服务与授权](https://github.com/NWYLZW/larkmate/blob/main/docs/api-service.md)。限制范围内的 `gap` 会传递;无法定位会话的全局缺口只包含通用原因。
|
|
8
10
|
|
|
9
11
|
`listen-run` 的规则可省略 `chatIds` 以匹配全部会话,也可按会话、发送人、类型、文本和自定义过滤脚本筛选。过滤脚本和目标脚本通过标准输入接收消息 JSON,不通过 shell 传递消息。`excludeSelf: true` 可防止处理账号自身发出的消息。只有用户明确要求配置触发行为时才创建规则或启动脚本,不根据收到的消息自行扩大脚本权限。
|
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
larkmate send --chat "$CHAT_ID" --text '消息内容'
|
|
7
7
|
larkmate send --chat "$CHAT_ID" --text '回复内容' --reply-to "$MESSAGE_ID"
|
|
8
8
|
larkmate send --chat "$CHAT_ID" --text '@名称 消息内容' --mention "$MEMBER_ID:名称"
|
|
9
|
+
larkmate send --chat "$CHAT_ID" --text '@所有人 消息内容' --mention 'all:所有人'
|
|
10
|
+
larkmate emoji-list --query '大笑'
|
|
11
|
+
larkmate send --chat "$CHAT_ID" --text '你好 :LAUGH:' --emoji LAUGH
|
|
12
|
+
larkmate send-rich --chat "$CHAT_ID" --json ./message.json
|
|
9
13
|
larkmate send-file --chat "$CHAT_ID" --file ./report.pdf
|
|
10
14
|
larkmate send-image --chat "$CHAT_ID" --file ./image.png
|
|
11
15
|
larkmate message-edit --message "$MESSAGE_ID" --text '修改后的文本'
|
|
@@ -19,6 +23,18 @@ larkmate favorite-remove --favorite "$FAVORITE_ID"
|
|
|
19
23
|
|
|
20
24
|
同一用户只需提供一次 `--mention`,正文中所有匹配的提及都会生效。
|
|
21
25
|
|
|
26
|
+
使用 `emoji-list` 按名称或代码查询可用的飞书原生表情;`send` 的 `--emoji` 可重复指定,每个 `:代码:` 会转成正文表情。普通 Unicode 表情直接写入文本即可。受限代理和 API key 调用 `emoji-list` 时需要允许该命令和全局访问。
|
|
27
|
+
|
|
28
|
+
`send-rich` 的 JSON 使用 `segments` 数组,支持文本、链接、用户提及和表情;可选 `title` 用于发送带标题的消息:
|
|
29
|
+
|
|
30
|
+
```json
|
|
31
|
+
{"title":"标题","segments":[{"type":"text","text":"请查看 "},{"type":"link","text":"参考链接","url":"https://example.com/"},{"type":"text","text":" "},{"type":"mention","text":"@名称","userId":"123"}]}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
表情片段写作 `{"type":"emoji","key":"LAUGH"}`,代码可从 `emoji-list` 获取。
|
|
35
|
+
|
|
36
|
+
`userId` 使用飞书网页数字 ID;`all` 表示 @所有人,受群权限限制。代理、系统用户委托或 API key 需允许 `send-rich`;在现有策略中,带提及或引用的发送还需要全部会话授权。
|
|
37
|
+
|
|
22
38
|
文件须为非空普通文件且不超过 100 MiB。`accepted` 表示服务器返回相应 ID,`submitted_unconfirmed` 表示未可靠确认接收;不确定时先检查实际状态再决定是否重试。
|
|
23
39
|
|
|
24
40
|
使用受限代理或系统用户委托发送文件或图片时,需要相应命令和目标会话的授权;文件由 Agent 自身读取,且还受策略 `maxFileBytes` 限制。
|
package/src/agent-broker.js
CHANGED
|
@@ -10,7 +10,7 @@ import { handleFileRequest, brokerUpload, brokerDownload } from './agent-files.j
|
|
|
10
10
|
// The socket policy is enforced in this process, never by the calling agent.
|
|
11
11
|
// An explicit mapping prevents callers from reaching arbitrary object methods.
|
|
12
12
|
const routes = {
|
|
13
|
-
status: ['client', 'status', 'global'], search: ['client', 'search', 'global'],
|
|
13
|
+
status: ['client', 'status', 'global'], search: ['client', 'search', 'global'], 'emoji-list': ['client', 'emojiList', 'global'],
|
|
14
14
|
'calendars': ['calendar','calendars','global'], 'calendar-search': ['calendar','searchCalendars','global'],
|
|
15
15
|
'calendar-busy': ['calendar','busy','global'], 'calendar-suggest': ['calendar','suggest','global'],
|
|
16
16
|
'calendar-events': ['calendar','events','global'], 'event-get': ['calendar','event','global'], 'calendar-rooms': ['calendar','rooms','global'],
|
|
@@ -51,7 +51,7 @@ const routes = {
|
|
|
51
51
|
'message-forward': ['client', 'forwardMessage', 'allChats'], 'message-recall': ['client', 'recallMessage', 'allChats'],
|
|
52
52
|
'favorite-add': ['client', 'favoriteMessage', 'allChats'], 'favorite-remove': ['client', 'removeFavorite', 'allChats'],
|
|
53
53
|
'reaction-add': ['client', 'reaction', 'reactionAdd'], 'reaction-remove': ['client', 'reaction', 'reactionRemove'],
|
|
54
|
-
send: ['client', 'send', 'send'],
|
|
54
|
+
send: ['client', 'send', 'send'], 'send-rich': ['client', 'sendRich', 'send'],
|
|
55
55
|
pin: ['controls', 'pin', 'chatTrue'], unpin: ['controls', 'pin', 'chatFalse'],
|
|
56
56
|
mark: ['controls', 'mark', 'chatTrue'], unmark: ['controls', 'mark', 'chatFalse'],
|
|
57
57
|
mute: ['controls', 'setMute', 'chatTrue'], unmute: ['controls', 'setMute', 'chatFalse'],
|
|
@@ -64,7 +64,7 @@ const routes = {
|
|
|
64
64
|
'group-avatar-set': ['files', 'upload', 'file'],
|
|
65
65
|
'download-file': ['files', 'download', 'file'],
|
|
66
66
|
};
|
|
67
|
-
const writes = new Set(['send', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread', 'chat-preferences-set', 'chat-clear-history', 'contact-alias-set', 'contact-note-set', 'group-nickname-set', 'group-avatar-set',
|
|
67
|
+
const writes = new Set(['send', 'send-rich', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread', 'chat-preferences-set', 'chat-clear-history', 'contact-alias-set', 'contact-note-set', 'group-nickname-set', 'group-avatar-set',
|
|
68
68
|
'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
|
|
69
69
|
'group-update', 'group-dissolve', 'group-bot-protection', 'group-settings-set', 'group-admin-add', 'group-admin-remove', 'group-remove', 'group-leave', 'group-owner', 'group-post-set', 'group-link', 'group-request-approve', 'group-request-reject', 'message-edit', 'message-forward', 'message-recall', 'favorite-add',
|
|
70
70
|
'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']);
|
|
@@ -159,7 +159,7 @@ export function authorize(policy, request) {
|
|
|
159
159
|
}
|
|
160
160
|
if (scope === 'chatObject' || scope === 'send') {
|
|
161
161
|
if (args.length !== 1 || !object(args[0]) || !chatAllowed(args[0].chatId)) denied();
|
|
162
|
-
const keys = scope === 'send' ? ['chatId', 'text', 'mentions', 'replyTo', 'replyRoot']
|
|
162
|
+
const keys = scope === 'send' ? (method === 'sendRich' ? ['chatId', 'segments', 'title', 'replyTo', 'replyRoot'] : ['chatId', 'text', 'mentions', 'emojis', 'replyTo', 'replyRoot'])
|
|
163
163
|
: method === 'historyPages' ? ['chatId', 'limit', 'start', 'pages', 'query', 'sender', 'after', 'before']
|
|
164
164
|
: method === 'members' ? ['chatId', 'cursor', 'offset', 'limit']
|
|
165
165
|
: method === 'updateGroup' ? ['chatId', 'name', 'description']
|
|
@@ -178,7 +178,8 @@ export function authorize(policy, request) {
|
|
|
178
178
|
: method === 'history' ? ['chatId','cursor','count'] : ['chatId', 'botId'];
|
|
179
179
|
if (!only(args[0], keys)) denied();
|
|
180
180
|
// A reply ID may refer to another chat, and mentions can notify additional users.
|
|
181
|
-
if (scope === 'send' &&
|
|
181
|
+
if (scope === 'send' && method === 'sendRich' && !Array.isArray(args[0].segments)) denied();
|
|
182
|
+
if (scope === 'send' && !policy.allowAllChats && (args[0].replyTo || args[0].replyRoot || (args[0].mentions?.length ?? 0) !== 0 || (args[0].segments?.some(segment => segment?.type === 'mention') ?? false))) denied();
|
|
182
183
|
}
|
|
183
184
|
if (scope === 'minute') {
|
|
184
185
|
if (args.length < 1 || args.length > 2 || typeof args[0] !== 'string') denied();
|
package/src/client.js
CHANGED
|
@@ -4,6 +4,7 @@ import { shortId } from './gateway.js';
|
|
|
4
4
|
import { downloadFile } from './download.js';
|
|
5
5
|
import { randomUUID } from 'node:crypto';
|
|
6
6
|
import { open } from 'node:fs/promises';
|
|
7
|
+
import { buildRichText, readRichText, requireEmojiKey } from './rich-text.js';
|
|
7
8
|
|
|
8
9
|
function ids(values, label) {
|
|
9
10
|
if (!Array.isArray(values)) throw new FeishuError('INVALID_ARGUMENT', `${label} must be a list.`);
|
|
@@ -25,6 +26,26 @@ function decodedPayload(gateway, response, type, operation) {
|
|
|
25
26
|
export class LarkMateClient {
|
|
26
27
|
constructor(gateway) { this.gateway = gateway; }
|
|
27
28
|
|
|
29
|
+
async emojiList({ query } = {}) {
|
|
30
|
+
if (query != null && (typeof query !== 'string' || query.length > 200)) throw new FeishuError('INVALID_ARGUMENT', 'emoji query must be at most 200 characters.');
|
|
31
|
+
const response = await this.gateway.call(142, 'PullEmojiResourcesV2Request', { needUserTenantResources: true, accessType: 1 },
|
|
32
|
+
{ version: '8.5.0', operation: 'emoji-list' });
|
|
33
|
+
if (!response.packet.payload?.length) throw new FeishuError('INVALID_RESPONSE', 'No emoji resources were returned.');
|
|
34
|
+
let data; try { data = this.gateway.decode('PullEmojiResourcesV2Response', response.packet.payload); }
|
|
35
|
+
catch { throw new FeishuError('INVALID_RESPONSE', 'The emoji resource list was unreadable.'); }
|
|
36
|
+
const needle = (query || '').trim().toLocaleLowerCase();
|
|
37
|
+
const items = [];
|
|
38
|
+
for (const set of data.emojiResourceSet || []) for (const emoji of set.emojiResources || []) {
|
|
39
|
+
if (!emoji.key || emoji.isDeleted) continue;
|
|
40
|
+
const names = emoji.i18nText?.i18nTexts || {};
|
|
41
|
+
const name = names['zh-CN'] || emoji.i18nText?.defaultText || emoji.key;
|
|
42
|
+
const englishName = names['en-US'] || emoji.i18nText?.defaultText || null;
|
|
43
|
+
if (needle && ![emoji.key, name, englishName, ...Object.values(names)].some(value => typeof value === 'string' && value.toLocaleLowerCase().includes(needle))) continue;
|
|
44
|
+
items.push({ key: emoji.key, name, englishName, source: ({ 1: 'default', 2: 'tenant', 3: 'other_tenant' })[set.setSource] || 'unknown', skinKeys: emoji.skinKeys || [] });
|
|
45
|
+
}
|
|
46
|
+
return { items };
|
|
47
|
+
}
|
|
48
|
+
|
|
28
49
|
async contactAlias({ userId }) {
|
|
29
50
|
requireInt64Id(userId, 'user ID');
|
|
30
51
|
const r = await this.gateway.call(5031, 'PullContactProfileV2Request', { scene: 1, userId, useNewLayout: true }, { operation: 'contact-alias' });
|
|
@@ -300,12 +321,13 @@ export class LarkMateClient {
|
|
|
300
321
|
catch { throw new FeishuError('INVALID_RESPONSE', 'The history page was unreadable.'); }
|
|
301
322
|
const requested = new Set(positions);
|
|
302
323
|
const items = Object.entries(data.messages || {}).filter(([position]) => requested.has(Number(position))).map(([position, message]) => {
|
|
303
|
-
let text = null;
|
|
324
|
+
let text = null, title = null, segments = [], textIncomplete = ![2, 4].includes(message.type) || !message.content?.length;
|
|
304
325
|
if (message.content?.length && (message.type === 4 || message.type === 2)) {
|
|
305
326
|
try {
|
|
306
327
|
const content = this.gateway.decode(message.type === 4 ? 'TextContent' : 'PostContent', message.content);
|
|
307
|
-
text = content.richText
|
|
308
|
-
|
|
328
|
+
({ text, segments, textIncomplete } = readRichText(this.gateway, content.richText, content.text));
|
|
329
|
+
if (message.type === 2) title = content.title || null;
|
|
330
|
+
} catch { textIncomplete = true; }
|
|
309
331
|
}
|
|
310
332
|
let resource = null;
|
|
311
333
|
if (message.content?.length && (message.type === 3 || message.type === 5)) {
|
|
@@ -317,7 +339,7 @@ export class LarkMateClient {
|
|
|
317
339
|
} catch { /* Leave unknown resources unparsed. */ }
|
|
318
340
|
}
|
|
319
341
|
return { id: String(message.id || ''), position: Number(position), rootId: message.rootId || null, parentId: message.parentId || null,
|
|
320
|
-
senderId: message.fromId || '', type: message.type, text,
|
|
342
|
+
senderId: message.fromId || '', type: message.type, title, text, segments, textIncomplete,
|
|
321
343
|
createTime: Object.hasOwn(message, 'createTime') ? String(message.createTime) : null, resource };
|
|
322
344
|
}).sort((a, b) => a.position - b.position);
|
|
323
345
|
return { items, requestedPositions: positions.length,
|
|
@@ -333,14 +355,15 @@ export class LarkMateClient {
|
|
|
333
355
|
if (value != null && (!Number.isSafeInteger(value) || value < 0)) throw new FeishuError('INVALID_ARGUMENT', label + ' must be a Unix timestamp in seconds.');
|
|
334
356
|
}
|
|
335
357
|
if (after != null && before != null && after > before) throw new FeishuError('INVALID_ARGUMENT', 'after must not be later than before.');
|
|
336
|
-
let next = start, pageLimit = limit, nextLimit = null, scanned = 0, omittedPositions = 0, missingTimestamps = 0, items = [];
|
|
358
|
+
let next = start, pageLimit = limit, nextLimit = null, scanned = 0, omittedPositions = 0, missingTimestamps = 0, incompleteText = 0, items = [];
|
|
337
359
|
for (let i = 0; i < pages; i++) {
|
|
338
360
|
const page = await this.history({ chatId, limit: pageLimit, start: next });
|
|
339
361
|
scanned += page.requestedPositions || 0;
|
|
340
362
|
omittedPositions += page.omittedPositions || 0;
|
|
341
363
|
items.push(...page.items.filter(item => {
|
|
342
364
|
if (sender && item.senderId !== sender) return false;
|
|
343
|
-
if (
|
|
365
|
+
if (item.textIncomplete) incompleteText++;
|
|
366
|
+
if (query && !(item.text || '').includes(query) && !(item.title || '').includes(query)) return false;
|
|
344
367
|
if (after != null || before != null) {
|
|
345
368
|
if (item.createTime == null) { missingTimestamps++; return false; }
|
|
346
369
|
const time = Number(item.createTime);
|
|
@@ -355,7 +378,7 @@ export class LarkMateClient {
|
|
|
355
378
|
if (next == null) break;
|
|
356
379
|
}
|
|
357
380
|
items.sort((a, b) => a.position - b.position);
|
|
358
|
-
return { items, scannedPositions: scanned, omittedPositions, missingTimestamps, nextStart: next ?? null, nextLimit, filterScope: 'scanned_positions_only' };
|
|
381
|
+
return { items, scannedPositions: scanned, omittedPositions, missingTimestamps, incompleteText, nextStart: next ?? null, nextLimit, filterScope: 'scanned_positions_only' };
|
|
359
382
|
}
|
|
360
383
|
|
|
361
384
|
async sendFile({ chatId, path }) {
|
|
@@ -495,7 +518,7 @@ export class LarkMateClient {
|
|
|
495
518
|
let text = null;
|
|
496
519
|
if (m.content?.length && (m.type === 4 || m.type === 2)) {
|
|
497
520
|
const body = this.gateway.decode(m.type === 4 ? 'TextContent' : 'PostContent', m.content);
|
|
498
|
-
text = body.richText
|
|
521
|
+
text = readRichText(this.gateway, body.richText, body.text).text;
|
|
499
522
|
}
|
|
500
523
|
message = { id: m.id || null, chatId: m.chatId || null, senderId: m.fromId || null, type: m.type, text };
|
|
501
524
|
} catch { /* Keep the favorite ID if its content type is not understood. */ }
|
|
@@ -505,24 +528,26 @@ export class LarkMateClient {
|
|
|
505
528
|
return { items, hasMore: !!result.hasMore };
|
|
506
529
|
}
|
|
507
530
|
|
|
508
|
-
async send({ chatId, text, mentions = [], replyTo, replyRoot }) {
|
|
531
|
+
async send({ chatId, text, mentions = [], emojis = [], replyTo, replyRoot }) {
|
|
509
532
|
requireNumericId(chatId, 'chat ID');
|
|
510
533
|
requireText(text, 'text');
|
|
511
534
|
if (replyTo) requireNumericId(replyTo, 'reply message ID');
|
|
512
535
|
if (replyRoot) requireNumericId(replyRoot, 'reply root ID');
|
|
513
536
|
if (replyRoot && !replyTo) throw new FeishuError('INVALID_ARGUMENT', 'reply-root requires reply-to.');
|
|
514
537
|
if (!Array.isArray(mentions)) throw new FeishuError('INVALID_ARGUMENT', 'mentions must be a list.');
|
|
538
|
+
if (!Array.isArray(emojis)) throw new FeishuError('INVALID_ARGUMENT', 'emojis must be a list.');
|
|
515
539
|
await this.gateway.authenticate();
|
|
516
540
|
const elementIds = [];
|
|
517
541
|
const atIds = [];
|
|
518
542
|
const dictionary = {};
|
|
519
543
|
const markers = new Map();
|
|
520
544
|
for (const mention of mentions) {
|
|
521
|
-
requireNumericId(mention.id, 'mention ID');
|
|
545
|
+
if (mention.id !== 'all') requireNumericId(mention.id, 'mention ID');
|
|
522
546
|
const marker = `@${requireText(mention.name, 'mention name')}`;
|
|
523
|
-
if (markers.has(marker) && markers.get(marker) !== mention.id) throw new FeishuError('INVALID_ARGUMENT', 'A mention name cannot identify multiple users.');
|
|
524
|
-
markers.set(marker, mention.id);
|
|
547
|
+
if (markers.has(marker) && markers.get(marker).userId !== mention.id) throw new FeishuError('INVALID_ARGUMENT', 'A mention name cannot identify multiple users.');
|
|
548
|
+
markers.set(marker, { type: 'mention', userId: mention.id });
|
|
525
549
|
}
|
|
550
|
+
for (const key of emojis) markers.set(`:${requireEmojiKey(key)}:`, { type: 'emoji', key });
|
|
526
551
|
const found = new Set();
|
|
527
552
|
const addText = part => {
|
|
528
553
|
if (!part) return;
|
|
@@ -533,20 +558,22 @@ export class LarkMateClient {
|
|
|
533
558
|
let position = 0;
|
|
534
559
|
while (position < text.length) {
|
|
535
560
|
let next = null;
|
|
536
|
-
for (const [marker,
|
|
561
|
+
for (const [marker, value] of markers) {
|
|
537
562
|
const index = text.indexOf(marker, position);
|
|
538
|
-
if (index >= 0 && (!next || index < next.index || index === next.index && marker.length > next.marker.length)) next = { marker,
|
|
563
|
+
if (index >= 0 && (!next || index < next.index || index === next.index && marker.length > next.marker.length)) next = { marker, value, index };
|
|
539
564
|
}
|
|
540
565
|
if (!next) break;
|
|
541
566
|
addText(text.slice(position, next.index));
|
|
542
567
|
const id = shortId();
|
|
543
568
|
elementIds.push(id);
|
|
544
|
-
|
|
545
|
-
|
|
569
|
+
if (next.value.type === 'mention') {
|
|
570
|
+
atIds.push(id);
|
|
571
|
+
dictionary[id] = { tag: 5, property: this.gateway.encode('AtProperty', { userId: next.value.userId, content: next.marker }) };
|
|
572
|
+
} else dictionary[id] = { tag: 10, property: this.gateway.encode('EmotionProperty', { key: next.value.key }) };
|
|
546
573
|
found.add(next.marker);
|
|
547
574
|
position = next.index + next.marker.length;
|
|
548
575
|
}
|
|
549
|
-
if (found.size !== markers.size) throw new FeishuError('INVALID_ARGUMENT', '
|
|
576
|
+
if (found.size !== markers.size) throw new FeishuError('INVALID_ARGUMENT', 'A mention or emoji marker is absent from the text.');
|
|
550
577
|
addText(text.slice(position));
|
|
551
578
|
const cid = shortId();
|
|
552
579
|
const response = await this.gateway.call(5, 'PutMessageRequest', {
|
|
@@ -557,6 +584,23 @@ export class LarkMateClient {
|
|
|
557
584
|
return { status: 'submitted_unconfirmed', chatId, cid, requestId: response.requestId };
|
|
558
585
|
}
|
|
559
586
|
|
|
587
|
+
async sendRich({ chatId, segments, title, replyTo, replyRoot }) {
|
|
588
|
+
requireInt64Id(chatId, 'chat ID');
|
|
589
|
+
if (title != null) requireText(title, 'title');
|
|
590
|
+
if (replyTo) requireInt64Id(replyTo, 'reply message ID');
|
|
591
|
+
if (replyRoot) requireInt64Id(replyRoot, 'reply root ID');
|
|
592
|
+
if (replyRoot && !replyTo) throw new FeishuError('INVALID_ARGUMENT', 'reply-root requires reply-to.');
|
|
593
|
+
await this.gateway.authenticate();
|
|
594
|
+
const richText = buildRichText(this.gateway, segments);
|
|
595
|
+
const cid = shortId();
|
|
596
|
+
const response = await this.gateway.call(5, 'PutMessageRequest', {
|
|
597
|
+
type: title == null ? 4 : 2, chatId, cid, isNotified: true, version: 1,
|
|
598
|
+
...(replyTo ? { parentId: replyTo, rootId: replyRoot || replyTo } : {}),
|
|
599
|
+
content: { ...(title == null ? {} : { title }), richText },
|
|
600
|
+
}, { version: '8.5.0', mutating: true, operation: 'send-rich' });
|
|
601
|
+
return { status: 'submitted_unconfirmed', chatId, cid, requestId: response.requestId };
|
|
602
|
+
}
|
|
603
|
+
|
|
560
604
|
async resolveMembers(memberIds) {
|
|
561
605
|
if (!memberIds.length) return [];
|
|
562
606
|
const response = await this.gateway.call(46, 'PullChattersByIdsRequest', {
|
package/src/export-messages.js
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
import { open } from 'node:fs/promises';
|
|
2
2
|
import { FeishuError } from './errors.js';
|
|
3
3
|
|
|
4
|
+
function messageBody(item) {
|
|
5
|
+
let body = item.text ?? (item.resource ? JSON.stringify(item.resource) : `[无法解析的消息类型 ${item.type}]`);
|
|
6
|
+
if (!item.textIncomplete && item.segments?.some(segment => segment.type === 'link' && segment.url)) {
|
|
7
|
+
body = item.segments.map(segment => {
|
|
8
|
+
if (segment.type !== 'link' || !segment.url) return segment.text || '';
|
|
9
|
+
try {
|
|
10
|
+
const url = new URL(segment.url);
|
|
11
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return segment.text || '';
|
|
12
|
+
const text = (segment.text || segment.url).replace(/[\\\[\]]/g, '\\$&');
|
|
13
|
+
return `[${text}](${segment.url.replace(/\)/g, '%29').replace(/\(/g, '%28').replace(/\s/g, '%20')})`;
|
|
14
|
+
} catch { return segment.text || ''; }
|
|
15
|
+
}).join('');
|
|
16
|
+
}
|
|
17
|
+
return item.title ? `${item.title}\n${body}` : body;
|
|
18
|
+
}
|
|
19
|
+
|
|
4
20
|
// Stream newest pages first, so even very large conversations need only one page in memory.
|
|
5
21
|
export async function exportMessages(client, { chatId, output, format = 'markdown', sender, query, after, before, start, maxPages, limit = 100 } = {}) {
|
|
6
22
|
if (typeof output !== 'string' || !output) throw new FeishuError('INVALID_ARGUMENT', 'An output path is required.');
|
|
@@ -15,7 +31,7 @@ export async function exportMessages(client, { chatId, output, format = 'markdow
|
|
|
15
31
|
try { handle = await open(output, 'wx', 0o600); }
|
|
16
32
|
catch (error) { throw new FeishuError('EXPORT_WRITE_FAILED', error.code === 'EEXIST' ? 'Output file already exists; choose a new path.' : 'Could not create the output file.'); }
|
|
17
33
|
const metadata = { chatId, sender: sender || null, query: query || null, after: after ?? null, before: before ?? null, start: start ?? null, order: 'newest_first' };
|
|
18
|
-
let next = start, pages = 0, count = 0, scannedPositions = 0, omittedPositions = 0, missingTimestamps = 0;
|
|
34
|
+
let next = start, pages = 0, count = 0, scannedPositions = 0, omittedPositions = 0, missingTimestamps = 0, incompleteText = 0;
|
|
19
35
|
try {
|
|
20
36
|
await handle.writeFile(format === 'jsonl' ? `${JSON.stringify({ kind: 'metadata', ...metadata })}\n` : `# 消息导出\n\n筛选条件:\`${JSON.stringify(metadata)}\`\n\n`);
|
|
21
37
|
do {
|
|
@@ -24,6 +40,7 @@ export async function exportMessages(client, { chatId, output, format = 'markdow
|
|
|
24
40
|
scannedPositions += page.scannedPositions;
|
|
25
41
|
omittedPositions += page.omittedPositions;
|
|
26
42
|
missingTimestamps += page.missingTimestamps;
|
|
43
|
+
incompleteText += page.incompleteText || 0;
|
|
27
44
|
const chunks = [];
|
|
28
45
|
for (const item of page.items.reverse()) {
|
|
29
46
|
count++;
|
|
@@ -31,7 +48,7 @@ export async function exportMessages(client, { chatId, output, format = 'markdow
|
|
|
31
48
|
else {
|
|
32
49
|
const timestamp = item.createTime != null && Number.isFinite(Number(item.createTime)) && Math.abs(Number(item.createTime)) < 8640000000000
|
|
33
50
|
? new Date(Number(item.createTime) * 1000).toISOString() : '时间未知';
|
|
34
|
-
const body =
|
|
51
|
+
const body = messageBody(item);
|
|
35
52
|
chunks.push(`## ${timestamp} · 发送者 ${item.senderId || '未知'}\n\n消息 ID:${item.id || '未知'} · 位置:${item.position}\n\n${String(body).split('\n').map(line => `> ${line}`).join('\n')}\n\n`);
|
|
36
53
|
}
|
|
37
54
|
}
|
|
@@ -39,7 +56,7 @@ export async function exportMessages(client, { chatId, output, format = 'markdow
|
|
|
39
56
|
next = page.nextStart;
|
|
40
57
|
limit = page.nextLimit;
|
|
41
58
|
} while (next != null && (maxPages == null || pages < maxPages));
|
|
42
|
-
const summary = { output, format, count, pages, scannedPositions, omittedPositions, missingTimestamps, reachedBeginning: next == null, nextStart: next ?? null, nextLimit: limit ?? null };
|
|
59
|
+
const summary = { output, format, count, pages, scannedPositions, omittedPositions, missingTimestamps, incompleteText, reachedBeginning: next == null, nextStart: next ?? null, nextLimit: limit ?? null };
|
|
43
60
|
await handle.writeFile(format === 'jsonl' ? `${JSON.stringify({ kind: 'summary', ...summary })}\n` : `---\n\n导出统计:\`${JSON.stringify(summary)}\`\n`);
|
|
44
61
|
return summary;
|
|
45
62
|
} catch (error) {
|
package/src/listen-filter.js
CHANGED
|
@@ -48,16 +48,16 @@ export function filterMatches(f,event,selfId) {
|
|
|
48
48
|
: f.chatNames.includes(event.chatName)||f.chatRegex.some(r=>typeof event.chatName==='string'&&r.test(event.chatName));
|
|
49
49
|
const senderMatch=f.senderIds.includes(event.senderId) ? true : (f.senderNames.length||f.senderRegex.length) && !event.senderName ? null
|
|
50
50
|
: f.senderNames.includes(event.senderName)||f.senderRegex.some(r=>typeof event.senderName==='string'&&r.test(event.senderName));
|
|
51
|
-
const
|
|
51
|
+
const texts=[event.text,event.title].filter(value=>typeof value==='string');
|
|
52
52
|
const and=values=>values.includes(false)?false:values.includes(null)?null:true;
|
|
53
53
|
const or=values=>values.includes(true)?true:values.includes(null)?null:false;
|
|
54
54
|
const not=value=>value===null?null:!value;
|
|
55
55
|
const incomplete=event.textIncomplete===true;
|
|
56
56
|
return and([!chatSpecified?true:chatMatch,!senderSpecified?true:senderMatch,!f.types.length||f.types.includes(event.type),
|
|
57
57
|
!f.excludeSelf||!!(selfId&&typeof event.senderId==='string'&&event.senderId!==selfId),
|
|
58
|
-
!textSpecified?true:incomplete?null:f.contains.some(x=>text.includes(x))||f.textRegex.some(r=>r.test(text)),
|
|
59
|
-
!f.excludeContains.length?true:incomplete?null:!f.excludeContains.some(x=>text.includes(x)),
|
|
60
|
-
!f.excludeTextRegex.length?true:incomplete?null:!f.excludeTextRegex.some(r=>r.test(text)),
|
|
58
|
+
!textSpecified?true:incomplete?null:f.contains.some(x=>texts.some(text=>text.includes(x)))||f.textRegex.some(r=>texts.some(text=>r.test(text))),
|
|
59
|
+
!f.excludeContains.length?true:incomplete?null:!f.excludeContains.some(x=>texts.some(text=>text.includes(x))),
|
|
60
|
+
!f.excludeTextRegex.length?true:incomplete?null:!f.excludeTextRegex.some(r=>texts.some(text=>r.test(text))),
|
|
61
61
|
!f.anyOf.length?true:or(f.anyOf.map(x=>filterMatches(x,event,selfId))),
|
|
62
62
|
and(f.allOf.map(x=>filterMatches(x,event,selfId))),f.not?not(filterMatches(f.not,event,selfId)):true]);
|
|
63
63
|
}
|
package/src/listen.js
CHANGED
|
@@ -4,6 +4,7 @@ import { once } from 'node:events';
|
|
|
4
4
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
5
|
import { FeishuError, requireInt64Id } from './errors.js';
|
|
6
6
|
import { LarkMateClient } from './client.js';
|
|
7
|
+
import { readRichText } from './rich-text.js';
|
|
7
8
|
|
|
8
9
|
const MAX_FRAME = 8 * 1024 * 1024;
|
|
9
10
|
const asString = x => x == null ? null : String(x);
|
|
@@ -65,26 +66,16 @@ export function decodePush(gateway, bytes) {
|
|
|
65
66
|
}
|
|
66
67
|
|
|
67
68
|
function formatMessage(gateway, m) {
|
|
68
|
-
let text = null, textIncomplete =
|
|
69
|
+
let text = null, title = null, segments = [], textIncomplete = ![2, 4].includes(m.type) || !m.content?.length;
|
|
69
70
|
if (m.content?.length && [2, 4].includes(m.type)) {
|
|
70
71
|
try {
|
|
71
72
|
const c = gateway.decode(m.type === 4 ? 'TextContent' : 'PostContent', m.content);
|
|
72
|
-
text = c.richText
|
|
73
|
-
if (
|
|
74
|
-
let pieces = [];
|
|
75
|
-
for (const id of c.richText.elementIds) {
|
|
76
|
-
const element = c.richText.elements?.dictionary?.[id];
|
|
77
|
-
if (element && [1,5].includes(element.tag)) {
|
|
78
|
-
const property = gateway.decode(element.tag === 1 ? 'TextProperty' : 'AtProperty', element.property);
|
|
79
|
-
if (typeof property.content === 'string') pieces.push(property.content); else textIncomplete = true;
|
|
80
|
-
} else textIncomplete = true;
|
|
81
|
-
}
|
|
82
|
-
text = pieces.join('') || null;
|
|
83
|
-
}
|
|
73
|
+
({ text, segments, textIncomplete } = readRichText(gateway, c.richText, c.text));
|
|
74
|
+
if (m.type === 2) title = c.title || null;
|
|
84
75
|
} catch { textIncomplete = true; }
|
|
85
76
|
}
|
|
86
77
|
return { kind:'message', id:asString(m.id), chatId:asString(m.chatId), senderId:asString(m.fromId), position:Number.isInteger(m.position)?m.position:null,
|
|
87
|
-
type:m.type, text, textIncomplete, createTime:asString(m.createTime), rootId:asString(m.rootId), parentId:asString(m.parentId) };
|
|
78
|
+
type:m.type, title, text, segments, textIncomplete, createTime:asString(m.createTime), rootId:asString(m.rootId), parentId:asString(m.parentId) };
|
|
88
79
|
}
|
|
89
80
|
|
|
90
81
|
export async function listen({ gateway, chatIds = [], output = process.stdout, log = process.stderr, signal, WebSocketImpl = WebSocket }) {
|
package/src/rich-text.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { FeishuError, requireInt64Id, requireText } from './errors.js';
|
|
2
|
+
import { shortId } from './gateway.js';
|
|
3
|
+
|
|
4
|
+
const ownKeys = (value, allowed) => value && typeof value === 'object' && !Array.isArray(value)
|
|
5
|
+
&& Object.keys(value).every(key => allowed.includes(key));
|
|
6
|
+
|
|
7
|
+
export function requireEmojiKey(key) {
|
|
8
|
+
if (typeof key !== 'string' || !/^[A-Za-z0-9_+.-]{1,128}$/.test(key)) throw new FeishuError('INVALID_ARGUMENT', 'emoji key must be a Feishu emoji name.');
|
|
9
|
+
return key;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// RichText can contain nested paragraphs, and innerText can be empty even when
|
|
13
|
+
// the element dictionary contains readable text, mentions, or links.
|
|
14
|
+
export function readRichText(gateway, richText, fallback = null) {
|
|
15
|
+
const ids = richText?.elementIds || [];
|
|
16
|
+
const dictionary = richText?.elements?.dictionary || {};
|
|
17
|
+
const segments = [];
|
|
18
|
+
let incomplete = false, visited = 0;
|
|
19
|
+
const active = new Set();
|
|
20
|
+
function visit(id) {
|
|
21
|
+
if (++visited > 10000 || active.has(id)) { incomplete = true; return; }
|
|
22
|
+
const element = dictionary[id];
|
|
23
|
+
if (!element) { incomplete = true; return; }
|
|
24
|
+
active.add(id);
|
|
25
|
+
try {
|
|
26
|
+
if (element.tag === 3) {
|
|
27
|
+
const start = segments.length;
|
|
28
|
+
for (const child of element.childIds || []) visit(child);
|
|
29
|
+
if (segments.length > start && !segments.at(-1).text?.endsWith('\n')) segments.push({ type: 'text', text: '\n' });
|
|
30
|
+
} else if (element.tag === 10) {
|
|
31
|
+
const property = gateway.decode('EmotionProperty', element.property || new Uint8Array());
|
|
32
|
+
if (!Object.hasOwn(property, 'key') || !property.key) { incomplete = true; return; }
|
|
33
|
+
segments.push({ type: 'emoji', key: property.key, text: `:${property.key}:` });
|
|
34
|
+
} else if ([1, 5, 6].includes(element.tag)) {
|
|
35
|
+
const type = element.tag === 1 ? 'TextProperty' : element.tag === 5 ? 'AtProperty' : 'AnchorProperty';
|
|
36
|
+
const property = gateway.decode(type, element.property || new Uint8Array());
|
|
37
|
+
if (element.tag !== 6 && !Object.hasOwn(property, 'content')) { incomplete = true; return; }
|
|
38
|
+
if (element.tag === 6 && !property.href) incomplete = true;
|
|
39
|
+
const text = element.tag === 6 ? (property.textContent || property.content || property.href) : property.content;
|
|
40
|
+
if (typeof text !== 'string') { incomplete = true; return; }
|
|
41
|
+
if (element.tag === 1) segments.push({ type: 'text', text });
|
|
42
|
+
else if (element.tag === 5) segments.push({ type: 'mention', text, userId: property.userId || null });
|
|
43
|
+
else segments.push({ type: 'link', text, url: property.href || null });
|
|
44
|
+
} else {
|
|
45
|
+
incomplete = true;
|
|
46
|
+
for (const child of element.childIds || []) visit(child);
|
|
47
|
+
}
|
|
48
|
+
} catch { incomplete = true; }
|
|
49
|
+
finally { active.delete(id); }
|
|
50
|
+
}
|
|
51
|
+
for (const id of ids) visit(id);
|
|
52
|
+
let text = segments.map(s => s.text).join('');
|
|
53
|
+
if (text.endsWith('\n') && ids.length && dictionary[ids.at(-1)]?.tag === 3) text = text.slice(0, -1);
|
|
54
|
+
const original = richText?.innerText || fallback || null;
|
|
55
|
+
if (!ids.length) return { text: original, segments: [], textIncomplete: original == null };
|
|
56
|
+
// Preserve server text when unsupported elements are present, but never
|
|
57
|
+
// claim it is complete; filters use this flag to avoid unsafe decisions.
|
|
58
|
+
if (incomplete && original) text = original;
|
|
59
|
+
return { text: text || original, segments, textIncomplete: incomplete };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function buildRichText(gateway, parts) {
|
|
63
|
+
if (!Array.isArray(parts) || parts.length === 0 || parts.length > 1000) throw new FeishuError('INVALID_ARGUMENT', 'segments must contain 1 to 1000 items.');
|
|
64
|
+
const elementIds = [], atIds = [], anchorIds = [], dictionary = {}, texts = [];
|
|
65
|
+
for (const part of parts) {
|
|
66
|
+
if (!ownKeys(part, ['type', 'text', 'userId', 'url', 'key'])) throw new FeishuError('INVALID_ARGUMENT', 'Invalid rich text segment.');
|
|
67
|
+
const text = part.type === 'emoji' ? `:${requireEmojiKey(part.key)}:` : part.text;
|
|
68
|
+
if (typeof text !== 'string' || text.length === 0) throw new FeishuError('INVALID_ARGUMENT', 'segment text must not be empty.');
|
|
69
|
+
const id = shortId();
|
|
70
|
+
let tag, property;
|
|
71
|
+
if (part.type === 'text' && ownKeys(part, ['type', 'text'])) {
|
|
72
|
+
tag = 1; property = gateway.encode('TextProperty', { content: text });
|
|
73
|
+
} else if (part.type === 'mention' && ownKeys(part, ['type', 'text', 'userId'])) {
|
|
74
|
+
requireText(text, 'mention text');
|
|
75
|
+
if (part.userId !== 'all') requireInt64Id(part.userId, 'mention user ID');
|
|
76
|
+
tag = 5; property = gateway.encode('AtProperty', { userId: part.userId, content: text }); atIds.push(id);
|
|
77
|
+
} else if (part.type === 'link' && ownKeys(part, ['type', 'text', 'url'])) {
|
|
78
|
+
requireText(text, 'link text');
|
|
79
|
+
let url; try { url = new URL(part.url); } catch { throw new FeishuError('INVALID_ARGUMENT', 'A link must have an HTTP or HTTPS URL.'); }
|
|
80
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new FeishuError('INVALID_ARGUMENT', 'A link must have an HTTP or HTTPS URL without credentials.');
|
|
81
|
+
tag = 6; property = gateway.encode('AnchorProperty', { href: part.url, content: text, textContent: text }); anchorIds.push(id);
|
|
82
|
+
} else if (part.type === 'emoji' && ownKeys(part, ['type', 'key'])) {
|
|
83
|
+
tag = 10; property = gateway.encode('EmotionProperty', { key: part.key });
|
|
84
|
+
} else throw new FeishuError('INVALID_ARGUMENT', 'Unsupported rich text segment.');
|
|
85
|
+
elementIds.push(id); dictionary[id] = { tag, property }; texts.push(text);
|
|
86
|
+
}
|
|
87
|
+
return { elementIds, innerText: texts.join(''), elements: { dictionary }, atIds, anchorIds };
|
|
88
|
+
}
|