@pmate/chat-sdk 0.14.0-seq.0 → 0.14.0-seq.10
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 +1 -3
- package/lib/chatContract.d.ts +2 -0
- package/lib/chatTypes.d.ts +3 -0
- package/lib/internal/chatEngine.d.ts +3 -7
- package/lib/messageView.js +1 -1
- package/lib/runtime/activity.d.ts +2 -1
- package/lib/runtime/activity.js +4 -1
- package/lib/runtime/botAuth.d.ts +1 -0
- package/lib/runtime/botAuth.js +1 -0
- package/lib/runtime/chatClient.d.ts +2 -0
- package/lib/runtime/chatClient.js +38 -7
- package/lib/runtime/chatSession.d.ts +2 -0
- package/lib/runtime/groupClient.d.ts +2 -0
- package/lib/runtime/groupClient.js +5 -1
- package/lib/runtime/inboxDeletion.d.ts +7 -0
- package/lib/runtime/inboxDeletion.js +21 -0
- package/lib/runtime/inboxGroup.js +6 -2
- package/lib/runtime/inboxStore.js +33 -3
- package/lib/runtime/messageControls.js +6 -3
- package/lib/runtime/messageStore.d.ts +1 -0
- package/lib/runtime/messageTimeline.d.ts +1 -0
- package/lib/runtime/messageTimeline.js +8 -5
- package/lib/runtime/outgoingContent.d.ts +2 -0
- package/lib/runtime/outgoingContent.js +6 -2
- package/lib/runtime/profileChat.d.ts +5 -1
- package/lib/runtime/profileChat.js +43 -16
- package/lib/runtime/profileCoordinator.d.ts +5 -0
- package/lib/runtime/profileCoordinator.js +51 -6
- package/lib/runtime/profileDatabase.d.ts +1 -0
- package/lib/runtime/profileDatabase.js +2 -0
- package/lib/runtime/profileLegacyInbox.js +1 -1
- package/lib/runtime/profileMemoryStore.d.ts +1 -0
- package/lib/runtime/profileMemoryStore.js +1 -1
- package/lib/runtime/profileOutboxDispatcher.js +1 -1
- package/lib/runtime/profileOwner.js +2 -2
- package/lib/runtime/profileProjection.d.ts +2 -0
- package/lib/runtime/profileProjection.js +76 -9
- package/lib/runtime/profileStoreTypes.d.ts +2 -0
- package/lib/runtime/readSync.js +1 -1
- package/lib/runtime/socialReadClient.d.ts +53 -0
- package/lib/runtime/socialReadClient.js +114 -11
- package/package.json +6 -7
package/README.md
CHANGED
|
@@ -29,9 +29,7 @@ If overriding `onKeyDown`, call `picker.inputProps.onKeyDown(event)` first and r
|
|
|
29
29
|
when `event.defaultPrevented`. Hosts supply only valid current group candidates and
|
|
30
30
|
must preserve the text offsets if transforming the message before transport.
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
production components, include duplicate names and scrolling, and support empty
|
|
34
|
-
results by typing an unmatched query.
|
|
32
|
+
For a local component preview, run `pnpm preview:component --component src/components/icons.tsx --export MicOutlineIcon --headed` in this package. For mention interactions, supply candidates through the host component, then test duplicate names, scrolling and an unmatched query.
|
|
35
33
|
|
|
36
34
|
## Connection recovery
|
|
37
35
|
|
package/lib/chatContract.d.ts
CHANGED
package/lib/chatTypes.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ export type ChatMessage = Readonly<{
|
|
|
12
12
|
mine: boolean;
|
|
13
13
|
status: "sending" | "sent" | "failed" | "read";
|
|
14
14
|
recalled: boolean;
|
|
15
|
+
recalledAt?: number;
|
|
15
16
|
unread?: boolean;
|
|
16
17
|
attentionEligible?: boolean;
|
|
17
18
|
reading?: Readonly<{
|
|
@@ -66,6 +67,8 @@ export type ChatGroup = Readonly<{
|
|
|
66
67
|
status: "active";
|
|
67
68
|
title: string;
|
|
68
69
|
avatar?: string;
|
|
70
|
+
background?: string;
|
|
71
|
+
description?: string;
|
|
69
72
|
memberIds: readonly string[];
|
|
70
73
|
} | {
|
|
71
74
|
status: "dissolved";
|
|
@@ -25,13 +25,7 @@ export type ReadersQuery = {
|
|
|
25
25
|
afterProfileId?: string;
|
|
26
26
|
revision?: number;
|
|
27
27
|
};
|
|
28
|
-
export type GroupChanges =
|
|
29
|
-
expectedRevision?: string;
|
|
30
|
-
addMembers?: readonly string[];
|
|
31
|
-
removeMembers?: readonly string[];
|
|
32
|
-
title?: string;
|
|
33
|
-
avatar?: string;
|
|
34
|
-
};
|
|
28
|
+
export type GroupChanges = import("../chatContract.js").GroupChanges;
|
|
35
29
|
export type SendOptions = {
|
|
36
30
|
waitFor?: "accepted" | "delivered";
|
|
37
31
|
};
|
|
@@ -111,6 +105,8 @@ export declare class ChatEngine {
|
|
|
111
105
|
status: "active";
|
|
112
106
|
title: string;
|
|
113
107
|
avatar?: string;
|
|
108
|
+
background?: string;
|
|
109
|
+
description?: string;
|
|
114
110
|
memberIds: readonly string[];
|
|
115
111
|
} | {
|
|
116
112
|
threadId: string;
|
package/lib/messageView.js
CHANGED
|
@@ -96,7 +96,7 @@ export function createMessagePresenter() {
|
|
|
96
96
|
value = bodies.get(item.message) ?? projectMessageContent(item.message);
|
|
97
97
|
bodies.set(item.message, value);
|
|
98
98
|
}
|
|
99
|
-
const result = { id: item.id, threadId: item.threadId, ...(item.threadRootId === undefined ? {} : { threadRootId: item.threadRootId }), timestamp: item.timestamp, from: item.from, mine: item.mine, status: item.status, recalled: item.recalled, unread: item.unread, attentionEligible: item.attentionEligible, reading: item.reading, reactions: item.reactions, ...value };
|
|
99
|
+
const result = { id: item.id, threadId: item.threadId, ...(item.threadRootId === undefined ? {} : { threadRootId: item.threadRootId }), timestamp: item.timestamp, from: item.from, mine: item.mine, status: item.status, recalled: item.recalled, ...(item.recalledAt === undefined ? {} : { recalledAt: item.recalledAt }), unread: item.unread, attentionEligible: item.attentionEligible, reading: item.reading, reactions: item.reactions, ...value };
|
|
100
100
|
items.set(item, result);
|
|
101
101
|
return result;
|
|
102
102
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type ChatRuntimeMessage } from "./protocol.js";
|
|
2
2
|
export type ChatActivityState = "working" | "typing" | "idle";
|
|
3
3
|
export type ChatActivityBody = {
|
|
4
|
-
kind: "activity";
|
|
4
|
+
kind: "activity" | "signal";
|
|
5
5
|
appId: string;
|
|
6
6
|
teamId?: string;
|
|
7
7
|
threadKind: "dm" | "group";
|
|
@@ -39,6 +39,7 @@ export declare function createActivityMessage(input: ActivityTarget & {
|
|
|
39
39
|
phase?: string;
|
|
40
40
|
detail?: string;
|
|
41
41
|
}): ChatRuntimeMessage;
|
|
42
|
+
export declare function isChatSignalKind(kind: unknown): kind is ChatActivityBody["kind"];
|
|
42
43
|
export declare function parseChatActivity(message: ChatRuntimeMessage, appId: string, profileId: string, now?: number): ChatActivity | null;
|
|
43
44
|
/** Keeps ordering tombstones after completion so a late heartbeat cannot revive an activity. */
|
|
44
45
|
export declare class ChatActivityStore {
|
package/lib/runtime/activity.js
CHANGED
|
@@ -14,9 +14,12 @@ export function createActivityMessage(input) {
|
|
|
14
14
|
message.recipients = input.recipients ?? [];
|
|
15
15
|
return message;
|
|
16
16
|
}
|
|
17
|
+
export function isChatSignalKind(kind) {
|
|
18
|
+
return kind === "signal" || kind === "activity";
|
|
19
|
+
}
|
|
17
20
|
export function parseChatActivity(message, appId, profileId, now = Date.now()) {
|
|
18
21
|
const body = message.body;
|
|
19
|
-
if (message.opcode !== ChatMsgOp.CHAT || body?.kind
|
|
22
|
+
if (message.opcode !== ChatMsgOp.CHAT || !isChatSignalKind(body?.kind) || body.appId !== appId || !message.from || message.from === profileId || !message.to
|
|
20
23
|
|| (body.threadKind !== "dm" && body.threadKind !== "group")
|
|
21
24
|
|| (body.threadKind === "dm" ? message.to !== profileId : !message.recipients?.includes(profileId))
|
|
22
25
|
|| (body.teamId !== undefined && !isValidChatTeamId(body.teamId))
|
package/lib/runtime/botAuth.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ export type BotLoginSession = {
|
|
|
26
26
|
};
|
|
27
27
|
};
|
|
28
28
|
};
|
|
29
|
+
/** Authenticate the Bot Account. Always exchange this token for the target App before business requests. */
|
|
29
30
|
export declare function loginPmateBot(input: {
|
|
30
31
|
botKey: PmateBotKeyFile;
|
|
31
32
|
authBaseUrl?: string;
|
package/lib/runtime/botAuth.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const DEFAULT_AUTH_API_BASE_URL = "https://auth-api-v2.pmate.chat";
|
|
2
|
+
/** Authenticate the Bot Account. Always exchange this token for the target App before business requests. */
|
|
2
3
|
export async function loginPmateBot(input) {
|
|
3
4
|
const fetcher = input.fetchImpl ?? fetch;
|
|
4
5
|
const baseUrl = (input.authBaseUrl ?? DEFAULT_AUTH_API_BASE_URL).replace(/\/+$/, "");
|
|
@@ -4,7 +4,7 @@ import { OnlineReachReceiver } from "./reach.js";
|
|
|
4
4
|
import { OnlineNotificationReceiver } from "./notification.js";
|
|
5
5
|
import { ChatPresenceClient } from "./presence.js";
|
|
6
6
|
import { parseChatUpdate } from "./updates.js";
|
|
7
|
-
import { ChatActivityStore, ChatActivityPublisher, createActivityMessage, parseChatActivity } from "./activity.js";
|
|
7
|
+
import { ChatActivityStore, ChatActivityPublisher, createActivityMessage, isChatSignalKind, parseChatActivity } from "./activity.js";
|
|
8
8
|
import { loginPmateBot } from "./botAuth.js";
|
|
9
9
|
import { parsePmateBotKeyJson } from "./botKey.js";
|
|
10
10
|
import { ChatMsgKind, ChatMsgOp, ChatRealtimeEvents, RuntimeWebsocketClient, createRuntimeMsg, } from "./protocol.js";
|
|
@@ -68,11 +68,22 @@ export class ChatClient {
|
|
|
68
68
|
if (!this.botKey) {
|
|
69
69
|
throw new Error("ChatClient requires either session or PMate bot key JSON");
|
|
70
70
|
}
|
|
71
|
-
|
|
71
|
+
const account = await loginPmateBot({
|
|
72
72
|
botKey: this.botKey,
|
|
73
73
|
authBaseUrl: this.options.authBaseUrl,
|
|
74
74
|
fetchImpl: this.options.fetchImpl,
|
|
75
75
|
});
|
|
76
|
+
const identity = account.session?.identity ?? account.identity;
|
|
77
|
+
if (identity?.kind !== "bot" || identity.app || !identity.accountId)
|
|
78
|
+
throw new Error("Bot Account session required");
|
|
79
|
+
const response = await (this.options.fetchImpl ?? fetch)(`${(this.options.authBaseUrl ?? DEFAULT_AUTH_API_BASE_URL).replace(/\/+$/, "")}/session/exchange`, {
|
|
80
|
+
method: "POST", redirect: "error", headers: { authorization: `Bearer ${account.token}`, "content-type": "application/json" },
|
|
81
|
+
body: JSON.stringify({ app: this.options.appId }),
|
|
82
|
+
});
|
|
83
|
+
const payload = await response.json();
|
|
84
|
+
if (!response.ok || !payload.success || !payload.data?.token || payload.data.identity?.app !== this.options.appId || payload.data.identity?.accountId !== identity.accountId)
|
|
85
|
+
throw new Error("Bot App session exchange failed");
|
|
86
|
+
this.session = payload.data;
|
|
76
87
|
}
|
|
77
88
|
const profileId = await this.resolveProfileId();
|
|
78
89
|
if (generation !== this.generation)
|
|
@@ -250,7 +261,7 @@ export class ChatClient {
|
|
|
250
261
|
return this.sendChat(input.groupId, {
|
|
251
262
|
kind: "group", threadKind: "group", action: "groupUpdate",
|
|
252
263
|
payload: { appId: this.options.appId, groupId: input.groupId, ...(input.teamId !== undefined ? { teamId: input.teamId } : {}), expectedRevision: input.expectedRevision,
|
|
253
|
-
addMembers: input.addMembers ?? [], removeMembers: input.removeMembers ?? [], ...(input.title !== undefined ? { title: input.title } : {}), ...(input.avatar !== undefined ? { avatar: input.avatar } : {}) },
|
|
264
|
+
addMembers: input.addMembers ?? [], removeMembers: input.removeMembers ?? [], ...(input.title !== undefined ? { title: input.title } : {}), ...(input.background !== undefined ? { background: input.background } : {}), ...(input.description !== undefined ? { description: input.description } : {}), ...(input.avatar !== undefined ? { avatar: input.avatar } : {}) },
|
|
254
265
|
});
|
|
255
266
|
}
|
|
256
267
|
async dissolveGroup(input) {
|
|
@@ -322,7 +333,7 @@ export class ChatClient {
|
|
|
322
333
|
}, ChatMsgKind.DM);
|
|
323
334
|
await this.sendAndWaitForAck(auth);
|
|
324
335
|
}
|
|
325
|
-
async sendAndWaitForAck(msg) {
|
|
336
|
+
async sendAndWaitForAck(msg, recoverAuth = true) {
|
|
326
337
|
const client = this.requireClient();
|
|
327
338
|
if (msg.opcode !== ChatMsgOp.AUTH && this.connection !== "connected") {
|
|
328
339
|
throw new Error(this.connection === "authentication_required" ? "登录已失效,请重新登录" : "聊天连接正在恢复,请稍后重试");
|
|
@@ -345,7 +356,22 @@ export class ChatClient {
|
|
|
345
356
|
pending.reject(error instanceof Error ? error : new Error("Send failed"));
|
|
346
357
|
}
|
|
347
358
|
}
|
|
348
|
-
|
|
359
|
+
try {
|
|
360
|
+
return await ack;
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
// This ACK explicitly guarantees that Hub rejected the write before
|
|
364
|
+
// processing it. Re-authenticate, then retry the exact envelope once.
|
|
365
|
+
// Disconnects/timeouts have uncertain delivery and must not be replayed here.
|
|
366
|
+
if (!recoverAuth || msg.opcode === ChatMsgOp.AUTH || !(error instanceof ChatAckError)
|
|
367
|
+
|| error.code !== "CHAT_CONNECTION_AUTH_REQUIRED" || this.client !== client
|
|
368
|
+
|| this.connection === "closed" || this.connection === "authentication_required")
|
|
369
|
+
throw error;
|
|
370
|
+
if (this.connection === "connected")
|
|
371
|
+
client.close(false);
|
|
372
|
+
await this.waitUntilReady();
|
|
373
|
+
return this.sendAndWaitForAck(msg, false);
|
|
374
|
+
}
|
|
349
375
|
}
|
|
350
376
|
handleIncoming(message) {
|
|
351
377
|
if (message.opcode === ChatMsgOp.NOTIFICATION) {
|
|
@@ -369,13 +395,13 @@ export class ChatClient {
|
|
|
369
395
|
pending.resolve(ack);
|
|
370
396
|
}
|
|
371
397
|
else {
|
|
372
|
-
pending.reject(new ChatAckError(ack.message || ack.code || "Ack failed"));
|
|
398
|
+
pending.reject(new ChatAckError(ack.message || ack.code || "Ack failed", ack.code));
|
|
373
399
|
}
|
|
374
400
|
}
|
|
375
401
|
return;
|
|
376
402
|
}
|
|
377
403
|
if (message.opcode === ChatMsgOp.CHAT) {
|
|
378
|
-
if (message.body?.kind
|
|
404
|
+
if (isChatSignalKind(message.body?.kind)) {
|
|
379
405
|
const activity = parseChatActivity(message, this.options.appId, this.profileId());
|
|
380
406
|
if (activity)
|
|
381
407
|
this.activities.accept(activity);
|
|
@@ -469,6 +495,11 @@ export class ChatClient {
|
|
|
469
495
|
}
|
|
470
496
|
}
|
|
471
497
|
class ChatAckError extends Error {
|
|
498
|
+
code;
|
|
499
|
+
constructor(message, code) {
|
|
500
|
+
super(message);
|
|
501
|
+
this.code = code;
|
|
502
|
+
}
|
|
472
503
|
}
|
|
473
504
|
export function createChatClient(options) {
|
|
474
505
|
return new ChatClient(options);
|
|
@@ -156,6 +156,8 @@ export declare class ChatSession<T extends StoredMessage> {
|
|
|
156
156
|
removeMembers?: readonly string[];
|
|
157
157
|
title?: string;
|
|
158
158
|
avatar?: string;
|
|
159
|
+
background?: string;
|
|
160
|
+
description?: string;
|
|
159
161
|
}): Promise<ChatGroup>;
|
|
160
162
|
dissolveGroup(target: ChatConversation | string, options?: {
|
|
161
163
|
expectedRevision?: string;
|
|
@@ -115,9 +115,13 @@ export class GroupClient {
|
|
|
115
115
|
throw new Error("INVALID_GROUP_METADATA");
|
|
116
116
|
return Object.freeze({ groupId: value.groupId, teamId: scope.teamId, ownerId: value.ownerId, revision: value.revision, versionNumber: value.versionNumber, status: "dissolved", ...(value.dissolvedBy ? { dissolvedBy: value.dissolvedBy } : {}), ...(value.dissolvedAt === undefined ? {} : { dissolvedAt: value.dissolvedAt }) });
|
|
117
117
|
}
|
|
118
|
+
if (value.background != null && typeof value.background !== "string")
|
|
119
|
+
throw new Error("INVALID_GROUP_METADATA");
|
|
120
|
+
if (value.description != null && (typeof value.description !== "string" || [...value.description].length > 500))
|
|
121
|
+
throw new Error("INVALID_GROUP_METADATA");
|
|
118
122
|
if (value.status !== undefined && value.status !== "active" || !Array.isArray(value.members) || !value.members.length || value.members.length > 256 || !value.members.every(validMessageIdentifier) || !value.members.includes(value.ownerId) || !value.members.includes(scope.profileId) || typeof value.title !== "string" || value.avatar !== undefined && value.avatar !== null && typeof value.avatar !== "string")
|
|
119
123
|
throw new Error("INVALID_GROUP_METADATA");
|
|
120
|
-
return Object.freeze({ groupId: value.groupId, teamId: scope.teamId, ownerId: value.ownerId, title: value.title, ...(value.avatar ? { avatar: value.avatar } : {}), memberIds: Object.freeze([...new Set(value.members)].sort()), revision: value.revision, versionNumber: value.versionNumber, status: "active" });
|
|
124
|
+
return Object.freeze({ groupId: value.groupId, teamId: scope.teamId, ownerId: value.ownerId, title: value.title, ...(value.background == null ? {} : { background: value.background }), ...(value.description == null ? {} : { description: value.description }), ...(value.avatar ? { avatar: value.avatar } : {}), memberIds: Object.freeze([...new Set(value.members)].sort()), revision: value.revision, versionNumber: value.versionNumber, status: "active" });
|
|
121
125
|
}
|
|
122
126
|
cached(value, entry) {
|
|
123
127
|
return this.normalize(value.status === "dissolved" ? { appId: this.options.scope.appId, ...value } : { appId: this.options.scope.appId, ...value, members: value.memberIds }, entry);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function inboxDeletion(fact: Record<string, unknown>): {
|
|
2
|
+
threadId: string;
|
|
3
|
+
teamId: string;
|
|
4
|
+
messageIds: Set<string>;
|
|
5
|
+
};
|
|
6
|
+
export declare function hideDeletedQuote<T>(body: T, deleted: ReadonlySet<string>): T;
|
|
7
|
+
export declare function recallTarget(body: unknown): string | undefined;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
function identifier(value) {
|
|
2
|
+
return typeof value === "string" && value.length > 0 && value.length <= 256 && !/[\p{Cc}]/u.test(value);
|
|
3
|
+
}
|
|
4
|
+
export function inboxDeletion(fact) {
|
|
5
|
+
if (!identifier(fact.threadId) || !identifier(fact.teamId) || !Array.isArray(fact.messageIds)
|
|
6
|
+
|| fact.messageIds.length < 1 || fact.messageIds.length > 1000 || !fact.messageIds.every(identifier)) {
|
|
7
|
+
throw Error("INVALID_INBOX_MESSAGE_DELETION");
|
|
8
|
+
}
|
|
9
|
+
return { threadId: fact.threadId, teamId: fact.teamId, messageIds: new Set(fact.messageIds) };
|
|
10
|
+
}
|
|
11
|
+
export function hideDeletedQuote(body, deleted) {
|
|
12
|
+
const message = body;
|
|
13
|
+
const quote = message?.content?.quote;
|
|
14
|
+
if (!message || !quote?.messageId || !deleted.has(quote.messageId))
|
|
15
|
+
return body;
|
|
16
|
+
return { ...message, content: { ...message.content, quote: { ...quote, content: "[消息已删除]" } } };
|
|
17
|
+
}
|
|
18
|
+
export function recallTarget(body) {
|
|
19
|
+
const wire = body;
|
|
20
|
+
return wire?.kind === "recall" ? wire.targetMessageId : wire?.content?.recall?.messageId;
|
|
21
|
+
}
|
|
@@ -42,10 +42,14 @@ export function projectInboxGroup(appId, groupId, teamId, events) {
|
|
|
42
42
|
const ids = members(payload.members);
|
|
43
43
|
if (!ids || !ids.includes(owner) || !group.members?.includes(actor))
|
|
44
44
|
return;
|
|
45
|
-
if (actor !== owner && (group.members.some(id => !ids.includes(id)) || typeof payload.avatar === "string" && payload.avatar !== group.avatar || typeof payload.title === "string" && payload.title !== group.title))
|
|
45
|
+
if (actor !== owner && (group.members.some(id => !ids.includes(id)) || typeof payload.avatar === "string" && payload.avatar !== group.avatar || typeof payload.background === "string" && payload.background !== group.background || typeof payload.description === "string" && payload.description !== group.description || typeof payload.title === "string" && payload.title !== group.title))
|
|
46
|
+
return;
|
|
47
|
+
if (payload.background != null && typeof payload.background !== "string")
|
|
48
|
+
return;
|
|
49
|
+
if (payload.description != null && (typeof payload.description !== "string" || [...payload.description].length > 500))
|
|
46
50
|
return;
|
|
47
51
|
group = { ...group, members: ids, revision: event.messageId, versionNumber: group.versionNumber + 1,
|
|
48
|
-
...(typeof payload.title === "string" ? { title: payload.title } : {}), ...(typeof payload.avatar === "string" ? { avatar: payload.avatar } : {}) };
|
|
52
|
+
...(typeof payload.background === "string" ? { background: payload.background } : {}), ...(typeof payload.description === "string" ? { description: payload.description } : {}), ...(typeof payload.title === "string" ? { title: payload.title } : {}), ...(typeof payload.avatar === "string" ? { avatar: payload.avatar } : {}) };
|
|
49
53
|
}
|
|
50
54
|
}
|
|
51
55
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { hideDeletedQuote, inboxDeletion, recallTarget } from "./inboxDeletion.js";
|
|
1
2
|
import { INBOX_PROJECTION_VERSIONS, validateInboxReceipt } from "./inboxProjections.js";
|
|
2
3
|
import { Dexie } from "dexie";
|
|
3
4
|
import { messageRequiresPlayback, isReadingControl } from "./readingContent.js";
|
|
@@ -237,11 +238,19 @@ export class IndexedDbInbox {
|
|
|
237
238
|
throw new Error("INBOX_FACT_IDENTITY_MISMATCH");
|
|
238
239
|
switch (event.kind) {
|
|
239
240
|
case "messageAdded": {
|
|
240
|
-
|
|
241
|
-
|
|
241
|
+
let message = data;
|
|
242
|
+
const thread = message.threadId, sequence = message.seq;
|
|
243
|
+
if (!thread || !message.messageId || !message.from || typeof sequence !== "number" || !Number.isSafeInteger(sequence) || sequence < 1 || !["dm", "group"].includes(message.threadKind))
|
|
242
244
|
throw new Error("INVALID_INBOX_MESSAGE");
|
|
243
245
|
if (message.from !== this.scope.profileId && !message.recipients?.includes(this.scope.profileId) && !(message.threadKind === "dm" && message.to === this.scope.profileId))
|
|
244
246
|
throw new Error("INBOX_MESSAGE_INACCESSIBLE");
|
|
247
|
+
const scope = JSON.stringify([thread, message.teamId]);
|
|
248
|
+
const deleted = new Set((await this.facts.get([owner, "messageDeleted", scope]))?.value.messageIds ?? []);
|
|
249
|
+
const targetOfRecall = recallTarget(message.body);
|
|
250
|
+
if (deleted.has(message.messageId) || (targetOfRecall && deleted.has(targetOfRecall)))
|
|
251
|
+
return;
|
|
252
|
+
if (deleted.size)
|
|
253
|
+
message = { ...message, body: hideDeletedQuote(message.body, deleted) };
|
|
245
254
|
await this.threads.put({ owner, id: thread, kind: message.threadKind, teamId: message.teamId, targetId: message.to });
|
|
246
255
|
const body = message.body;
|
|
247
256
|
if (body?.kind === "group") {
|
|
@@ -255,7 +264,7 @@ export class IndexedDbInbox {
|
|
|
255
264
|
return thread;
|
|
256
265
|
const root = messageThreadRoot(message.body) ?? "";
|
|
257
266
|
const recalls = await this.facts.get([owner, "recall", JSON.stringify([thread, message.messageId])]);
|
|
258
|
-
await this.messages.put({ owner, thread, id: message.messageId, acceptedAt: sourceAcceptedAt, time: message.serverCreatedAt, seq:
|
|
267
|
+
await this.messages.put({ owner, thread, id: message.messageId, acceptedAt: sourceAcceptedAt, time: message.serverCreatedAt, seq: sequence, changeSeq: event.inboxSeq.padStart(19, "0"), root, recalled: recalls?.value.from === message.from, value: message });
|
|
259
268
|
const target = body?.kind === "recall" ? body.targetMessageId : body?.kind === "message" && body.content?.appId === this.scope.appId ? body.content?.recall?.messageId : undefined;
|
|
260
269
|
if (typeof target === "string") {
|
|
261
270
|
const key = JSON.stringify([thread, target]);
|
|
@@ -266,6 +275,27 @@ export class IndexedDbInbox {
|
|
|
266
275
|
}
|
|
267
276
|
return thread;
|
|
268
277
|
}
|
|
278
|
+
case "messageDeleted": {
|
|
279
|
+
const { threadId: thread, teamId, messageIds } = inboxDeletion(data), scope = JSON.stringify([thread, teamId]);
|
|
280
|
+
const old = await this.facts.get([owner, event.kind, scope]);
|
|
281
|
+
const deleted = new Set([...(old?.value.messageIds ?? []), ...messageIds]);
|
|
282
|
+
await this.facts.put({ owner, kind: event.kind, id: scope, thread, value: { threadId: thread, teamId, messageIds: [...deleted] } });
|
|
283
|
+
await this.facts.put({ owner, kind: "structure", id: thread, thread, value: { seq: event.inboxSeq } });
|
|
284
|
+
const rows = await this.messages.where("[owner+thread]").equals([owner, thread]).toArray();
|
|
285
|
+
for (const row of rows) {
|
|
286
|
+
if (row.value.teamId !== teamId)
|
|
287
|
+
continue;
|
|
288
|
+
const target = recallTarget(row.value.body);
|
|
289
|
+
if (deleted.has(row.id) || (target && deleted.has(target)))
|
|
290
|
+
await this.messages.delete([owner, thread, row.id]);
|
|
291
|
+
else {
|
|
292
|
+
const body = hideDeletedQuote(row.value.body, deleted);
|
|
293
|
+
if (body !== row.value.body)
|
|
294
|
+
await this.messages.update([owner, thread, row.id], { value: { ...row.value, body }, changeSeq: event.inboxSeq.padStart(19, "0") });
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return thread;
|
|
298
|
+
}
|
|
269
299
|
case "readingUpdated": {
|
|
270
300
|
if (data.receiptOnly === true) {
|
|
271
301
|
await this.writeReceipts([event]);
|
|
@@ -13,7 +13,7 @@ export function messageControls(message, scope, key) {
|
|
|
13
13
|
if (app !== undefined && app !== scope.appId)
|
|
14
14
|
return [];
|
|
15
15
|
if (row.recalled || row.legacyDisplay?.recalled)
|
|
16
|
-
return [{ scope: key, thread: message.threadId, target: message.id, kind: "recall", actor: row.from, emoji: "", id: message.id, timestamp: message.
|
|
16
|
+
return [{ scope: key, thread: message.threadId, target: message.id, kind: "recall", actor: row.from, emoji: "", id: message.id, timestamp: message.recalledAt ?? 0, revision: 0, active: true }];
|
|
17
17
|
const body = row.body;
|
|
18
18
|
const content = body?.kind === "message" && body.content?.appId === scope.appId ? body.content : undefined;
|
|
19
19
|
const target = body?.kind === "recall" && row.appId === scope.appId ? body.targetMessageId : content?.recall?.messageId;
|
|
@@ -37,8 +37,11 @@ export function applyMessageControls(messages, controls) {
|
|
|
37
37
|
if (!facts?.length)
|
|
38
38
|
return message;
|
|
39
39
|
const row = message;
|
|
40
|
-
const
|
|
40
|
+
const recalls = facts.filter(event => event.kind === "recall" && event.actor === row.from);
|
|
41
|
+
const recalled = message.recalled || recalls.length > 0;
|
|
42
|
+
const timestamps = recalls.map(event => event.timestamp).filter(time => Number.isSafeInteger(time) && time > 0);
|
|
43
|
+
const recalledAt = timestamps.length ? Math.min(message.recalledAt ?? Infinity, ...timestamps) : message.recalledAt;
|
|
41
44
|
const reactionEvents = facts.filter(event => event.kind === "reaction").map(event => ({ id: event.id, messageId: event.target, threadId: event.thread, from: event.actor, emojiId: event.emoji, active: event.active, revision: event.revision, timestamp: event.timestamp }));
|
|
42
|
-
return { ...message, ...(recalled ? { recalled: true } : {}), ...(reactionEvents.length ? { reactionEvents: [...(row.reactionEvents ?? []), ...reactionEvents] } : {}) };
|
|
45
|
+
return { ...message, ...(recalled ? { recalled: true, ...(recalledAt === undefined ? {} : { recalledAt }) } : {}), ...(reactionEvents.length ? { reactionEvents: [...(row.reactionEvents ?? []), ...reactionEvents] } : {}) };
|
|
43
46
|
});
|
|
44
47
|
}
|
|
@@ -52,9 +52,10 @@ export function projectMessageTimeline(input) {
|
|
|
52
52
|
continue;
|
|
53
53
|
const envelope = message, body = content(envelope, input.appId), target = nativeRecall(envelope, input.appId) ?? body?.content?.recall?.messageId;
|
|
54
54
|
if (typeof target === "string" && target.length > 0 && target.length <= 256 && envelope.from) {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
const senders = recalled.get(target) ?? new Map();
|
|
56
|
+
const time = status !== "sending" && Number.isSafeInteger(message.timestamp) && message.timestamp > 0 ? message.timestamp : Infinity;
|
|
57
|
+
senders.set(envelope.from, Math.min(senders.get(envelope.from) ?? Infinity, time));
|
|
58
|
+
recalled.set(target, senders);
|
|
58
59
|
}
|
|
59
60
|
const reaction = body?.content?.reaction;
|
|
60
61
|
if (body?.contentKind === "text" && reaction?.version === 1 && typeof reaction.messageId === "string" && typeof reaction.emojiId === "string" && typeof reaction.active === "boolean" && typeof reaction.revision === "number" && reaction.revision >= 1 && envelope.from) {
|
|
@@ -107,14 +108,16 @@ export function projectMessageTimeline(input) {
|
|
|
107
108
|
continue;
|
|
108
109
|
const mine = envelope.from === input.profileId, reading = input.reading[message.id];
|
|
109
110
|
const withdrawn = Boolean(tombstones.has(message.id) || message.recalled || envelope.legacyDisplay?.recalled || envelope.from && recalled.get(message.id)?.has(envelope.from));
|
|
111
|
+
const recallTime = envelope.from ? recalled.get(message.id)?.get(envelope.from) : undefined;
|
|
112
|
+
const recalledAt = Math.min(message.recalledAt ?? Infinity, recallTime ?? Infinity);
|
|
110
113
|
const candidate = input.candidates?.get(message.id);
|
|
111
|
-
const item = { id: message.id, threadId: message.threadId, ...(messageThreadRoot(envelope.body) === undefined ? {} : { threadRootId: messageThreadRoot(envelope.body) }), timestamp: message.timestamp, from: envelope.from, mine, status: !mine && reading ? (reading.read ? "read" : status === "read" ? "sent" : status) : status, recalled: withdrawn, ...(candidate ? { unread: !mine && !withdrawn && (reading ? !reading.read : candidate.unread), attentionEligible: candidate.attentionEligible } : {}),
|
|
114
|
+
const item = { id: message.id, threadId: message.threadId, ...(messageThreadRoot(envelope.body) === undefined ? {} : { threadRootId: messageThreadRoot(envelope.body) }), timestamp: message.timestamp, from: envelope.from, mine, status: !mine && reading ? (reading.read ? "read" : status === "read" ? "sent" : status) : status, recalled: withdrawn, ...(Number.isFinite(recalledAt) ? { recalledAt } : {}), ...(candidate ? { unread: !mine && !withdrawn && (reading ? !reading.read : candidate.unread), attentionEligible: candidate.attentionEligible } : {}),
|
|
112
115
|
message: withdrawn ? undefined : message, reading, reactionEvents: withdrawn ? [] : groupedEvents.get(message.id) ?? [], reactions: withdrawn ? [] : [...(grouped.get(message.id) ?? [])].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([emojiId, users]) => { const userIds = [...users].sort(); return { emojiId, userIds, mine: userIds.includes(input.profileId) }; }) };
|
|
113
116
|
const old = previous.get(item.id);
|
|
114
117
|
const sameReading = old?.reading === item.reading || old?.reading?.seq === item.reading?.seq && old?.reading?.read === item.reading?.read && old?.reading?.readPolicy === item.reading?.readPolicy;
|
|
115
118
|
const sameReactions = old?.reactions.length === item.reactions.length && old.reactions.every((reaction, index) => { const next = item.reactions[index]; return reaction.emojiId === next.emojiId && reaction.mine === next.mine && reaction.userIds.length === next.userIds.length && reaction.userIds.every((user, i) => user === next.userIds[i]); });
|
|
116
119
|
const sameEvents = old?.reactionEvents.length === item.reactionEvents.length && old.reactionEvents.every((event, index) => { const next = item.reactionEvents[index]; return event.id === next.id && event.from === next.from && event.emojiId === next.emojiId && event.active === next.active && event.revision === next.revision && event.timestamp === next.timestamp && event.threadId === next.threadId && event.messageId === next.messageId; });
|
|
117
|
-
result.push(old && sameEvents && old.message === item.message && old.timestamp === item.timestamp && old.from === item.from && old.mine === item.mine && old.status === item.status && old.recalled === item.recalled && old.unread === item.unread && old.attentionEligible === item.attentionEligible && sameReading && sameReactions ? old : item);
|
|
120
|
+
result.push(old && sameEvents && old.message === item.message && old.timestamp === item.timestamp && old.from === item.from && old.mine === item.mine && old.status === item.status && old.recalled === item.recalled && old.recalledAt === item.recalledAt && old.unread === item.unread && old.attentionEligible === item.attentionEligible && sameReading && sameReactions ? old : item);
|
|
118
121
|
}
|
|
119
122
|
result.sort((a, b) => a.timestamp - b.timestamp || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
120
123
|
return input.previous?.length === result.length && result.every((item, index) => item === input.previous[index]) ? input.previous : result;
|
|
@@ -58,13 +58,17 @@ export function outgoingContent(scope, thread, input) {
|
|
|
58
58
|
}
|
|
59
59
|
if (input.groupUpdate) {
|
|
60
60
|
const update = input.groupUpdate, add = members(update.addMembers ?? []), remove = members(update.removeMembers ?? []);
|
|
61
|
-
if (thread.kind !== "group" || !validMessageIdentifier(update.expectedRevision) || Number(add.length > 0) + Number(remove.length > 0) + Number(update.title !== undefined) + Number(update.avatar !== undefined) !== 1)
|
|
61
|
+
if (thread.kind !== "group" || !validMessageIdentifier(update.expectedRevision) || Number(add.length > 0) + Number(remove.length > 0) + Number(update.title !== undefined) + Number(update.avatar !== undefined) + Number(update.description !== undefined) + Number(update.background !== undefined) !== 1)
|
|
62
62
|
throw new Error("INVALID_GROUP_UPDATE");
|
|
63
63
|
if (update.title !== undefined && (typeof update.title !== "string" || !update.title.trim() || [...update.title.trim()].length > 120))
|
|
64
64
|
throw new Error("INVALID_GROUP_TITLE");
|
|
65
|
+
if (update.background !== undefined && !["default", "mist", "cream", "apricot", "sage", "aqua", "blue", "lavender", "rose"].includes(update.background))
|
|
66
|
+
throw new Error("INVALID_GROUP_BACKGROUND");
|
|
67
|
+
if (update.description !== undefined && (typeof update.description !== "string" || [...update.description.trim()].length > 500))
|
|
68
|
+
throw new Error("INVALID_GROUP_DESCRIPTION");
|
|
65
69
|
if (update.avatar !== undefined && (typeof update.avatar !== "string" || !update.avatar.startsWith("https://") || update.avatar.length > 2048 || /\s/u.test(update.avatar)))
|
|
66
70
|
throw new Error("INVALID_GROUP_AVATAR");
|
|
67
|
-
return { to: thread.targetId, body: { kind: "group", threadKind: "group", action: "groupUpdate", payload: { ...identity, groupId: thread.targetId, expectedRevision: update.expectedRevision, addMembers: add, removeMembers: remove, ...(update.title === undefined ? {} : { title: update.title.trim() }), ...(update.avatar === undefined ? {} : { avatar: update.avatar }) } } };
|
|
71
|
+
return { to: thread.targetId, body: { kind: "group", threadKind: "group", action: "groupUpdate", payload: { ...identity, groupId: thread.targetId, expectedRevision: update.expectedRevision, addMembers: add, removeMembers: remove, ...(update.title === undefined ? {} : { title: update.title.trim() }), ...(update.background === undefined ? {} : { background: update.background }), ...(update.description === undefined ? {} : { description: update.description.trim() }), ...(update.avatar === undefined ? {} : { avatar: update.avatar }) } } };
|
|
68
72
|
}
|
|
69
73
|
if (input.groupDissolve) {
|
|
70
74
|
if (thread.kind !== "group" || !validMessageIdentifier(input.groupDissolve.expectedRevision))
|
|
@@ -109,7 +109,7 @@ export declare class ProfileChat implements Chat {
|
|
|
109
109
|
private loadGroup;
|
|
110
110
|
private refreshChangedGroups;
|
|
111
111
|
refreshGroup(id: string, options?: ReadOptions): Promise<ChatGroup>;
|
|
112
|
-
private
|
|
112
|
+
private confirmGroup;
|
|
113
113
|
createGroup(input: {
|
|
114
114
|
groupId?: string;
|
|
115
115
|
title: string;
|
|
@@ -123,6 +123,8 @@ export declare class ProfileChat implements Chat {
|
|
|
123
123
|
status: "active";
|
|
124
124
|
title: string;
|
|
125
125
|
avatar?: string;
|
|
126
|
+
background?: string;
|
|
127
|
+
description?: string;
|
|
126
128
|
memberIds: readonly string[];
|
|
127
129
|
} | {
|
|
128
130
|
threadId: string;
|
|
@@ -153,6 +155,7 @@ export declare class ProfileChat implements Chat {
|
|
|
153
155
|
mine: boolean;
|
|
154
156
|
status: "sending" | "sent" | "failed" | "read";
|
|
155
157
|
recalled: boolean;
|
|
158
|
+
recalledAt?: number;
|
|
156
159
|
unread?: boolean;
|
|
157
160
|
attentionEligible?: boolean;
|
|
158
161
|
reading?: Readonly<{
|
|
@@ -209,6 +212,7 @@ export declare class ProfileChat implements Chat {
|
|
|
209
212
|
mine: boolean;
|
|
210
213
|
status: "sending" | "sent" | "failed" | "read";
|
|
211
214
|
recalled: boolean;
|
|
215
|
+
recalledAt?: number;
|
|
212
216
|
unread?: boolean;
|
|
213
217
|
attentionEligible?: boolean;
|
|
214
218
|
reading?: Readonly<{
|