@pmate/chat-sdk 0.12.0-next.9 → 0.12.0-next.90
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 +216 -83
- package/lib/advanced.d.ts +10 -0
- package/lib/advanced.js +10 -0
- package/lib/chat.d.ts +5 -0
- package/lib/chat.js +11 -0
- package/lib/chatContract.d.ts +158 -0
- package/lib/chatContract.js +1 -0
- package/lib/chatError.d.ts +31 -0
- package/lib/chatError.js +18 -0
- package/lib/chatTypes.d.ts +128 -0
- package/lib/chatTypes.js +1 -0
- package/lib/commands.d.ts +20 -0
- package/lib/commands.js +12 -0
- package/lib/components/ChatInputDesktop.js +5 -4
- package/lib/components/ChatInputMobile.js +5 -4
- package/lib/components/CommandMenu.d.ts +15 -0
- package/lib/components/CommandMenu.js +10 -0
- package/lib/credentials.d.ts +26 -0
- package/lib/credentials.js +110 -0
- package/lib/fileMetadata.d.ts +9 -0
- package/lib/fileMetadata.js +18 -0
- package/lib/framework.d.ts +11 -0
- package/lib/framework.js +12 -0
- package/lib/history.d.ts +4 -0
- package/lib/history.js +8 -0
- package/lib/hooks/useChatSnapshot.d.ts +4 -0
- package/lib/hooks/useChatSnapshot.js +9 -0
- package/lib/hooks/useComposerSuggestions.d.ts +50 -0
- package/lib/hooks/useComposerSuggestions.js +70 -0
- package/lib/index.d.ts +6 -0
- package/lib/index.js +6 -0
- package/lib/internal/chatEngine.d.ts +131 -0
- package/lib/internal/chatEngine.js +306 -0
- package/lib/internal/chatRegistry.d.ts +4 -0
- package/lib/internal/chatRegistry.js +4 -0
- package/lib/internal/createPublicChat.d.ts +4 -0
- package/lib/internal/createPublicChat.js +62 -0
- package/lib/messageView.d.ts +6 -0
- package/lib/messageView.js +103 -0
- package/lib/runtime/batchedReadIndex.d.ts +16 -3
- package/lib/runtime/batchedReadIndex.js +50 -4
- package/lib/runtime/cachedMessage.d.ts +12 -0
- package/lib/runtime/cachedMessage.js +18 -0
- package/lib/runtime/chatClient.d.ts +8 -1
- package/lib/runtime/chatClient.js +18 -6
- package/lib/runtime/chatError.d.ts +5 -0
- package/lib/runtime/chatError.js +20 -0
- package/lib/runtime/chatSession.d.ts +141 -13
- package/lib/runtime/chatSession.js +797 -48
- package/lib/runtime/connectivity.d.ts +4 -0
- package/lib/runtime/connectivity.js +8 -0
- package/lib/runtime/conversationDirectory.d.ts +37 -0
- package/lib/runtime/conversationDirectory.js +116 -0
- package/lib/runtime/conversationRead.d.ts +14 -0
- package/lib/runtime/conversationRead.js +34 -0
- package/lib/runtime/conversationReading.d.ts +30 -0
- package/lib/runtime/conversationReading.js +47 -0
- package/lib/runtime/createChat.d.ts +14 -7
- package/lib/runtime/createChat.js +67 -24
- package/lib/runtime/durableSender.d.ts +97 -14
- package/lib/runtime/durableSender.js +787 -71
- package/lib/runtime/groupClient.d.ts +92 -0
- package/lib/runtime/groupClient.js +380 -0
- package/lib/runtime/groupDenial.d.ts +2 -0
- package/lib/runtime/groupDenial.js +4 -0
- package/lib/runtime/groupIdentity.d.ts +4 -0
- package/lib/runtime/groupIdentity.js +26 -0
- package/lib/runtime/inboxClient.d.ts +65 -0
- package/lib/runtime/inboxClient.js +268 -0
- package/lib/runtime/inboxGroup.d.ts +4 -0
- package/lib/runtime/inboxGroup.js +51 -0
- package/lib/runtime/inboxStore.d.ts +194 -0
- package/lib/runtime/inboxStore.js +321 -0
- package/lib/runtime/inboxTransport.d.ts +6 -0
- package/lib/runtime/inboxTransport.js +76 -0
- package/lib/runtime/index.d.ts +10 -0
- package/lib/runtime/index.js +8 -0
- package/lib/runtime/indexedDbRecovery.d.ts +6 -0
- package/lib/runtime/indexedDbRecovery.js +42 -0
- package/lib/runtime/messageClient.d.ts +37 -8
- package/lib/runtime/messageClient.js +366 -68
- package/lib/runtime/messageControls.d.ts +19 -0
- package/lib/runtime/messageControls.js +44 -0
- package/lib/runtime/messageDiscussionStore.d.ts +63 -0
- package/lib/runtime/messageDiscussionStore.js +147 -0
- package/lib/runtime/messageLaunch.d.ts +44 -0
- package/lib/runtime/messageLaunch.js +137 -0
- package/lib/runtime/messageQuotes.d.ts +3 -0
- package/lib/runtime/messageQuotes.js +17 -0
- package/lib/runtime/messageReaders.d.ts +5 -1
- package/lib/runtime/messageReaders.js +16 -5
- package/lib/runtime/messageStore.d.ts +51 -2
- package/lib/runtime/messageStore.js +264 -14
- package/lib/runtime/messageThread.d.ts +9 -0
- package/lib/runtime/messageThread.js +17 -0
- package/lib/runtime/messageTimeline.d.ts +51 -0
- package/lib/runtime/messageTimeline.js +121 -0
- package/lib/runtime/outboxSchema.d.ts +5 -0
- package/lib/runtime/outboxSchema.js +59 -0
- package/lib/runtime/outgoingContent.d.ts +95 -0
- package/lib/runtime/outgoingContent.js +121 -0
- package/lib/runtime/readBatchJournal.d.ts +35 -0
- package/lib/runtime/readBatchJournal.js +210 -0
- package/lib/runtime/readCounts.d.ts +7 -1
- package/lib/runtime/readCounts.js +108 -21
- package/lib/runtime/readIndex.d.ts +74 -7
- package/lib/runtime/readIndex.js +488 -33
- package/lib/runtime/readSchema.d.ts +2 -0
- package/lib/runtime/readSchema.js +58 -0
- package/lib/runtime/readSync.d.ts +8 -0
- package/lib/runtime/readSync.js +125 -17
- package/lib/runtime/readingClient.d.ts +22 -0
- package/lib/runtime/readingClient.js +141 -20
- package/lib/runtime/readingContent.d.ts +5 -0
- package/lib/runtime/readingContent.js +23 -0
- package/lib/runtime/responseCache.d.ts +41 -5
- package/lib/runtime/responseCache.js +182 -44
- package/lib/runtime/socialReadClient.d.ts +30 -4
- package/lib/runtime/socialReadClient.js +34 -8
- package/lib/runtime/voiceUpload.d.ts +2 -0
- package/lib/runtime/voiceUpload.js +27 -0
- package/lib/snapshot.d.ts +36 -0
- package/lib/snapshot.js +52 -0
- package/lib/types/chatInput.d.ts +3 -0
- package/package.json +32 -2
package/lib/runtime/readIndex.js
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
|
+
import { validMessageThreadRoot } from "./messageThread.js";
|
|
2
|
+
import { prepareReadSchema } from "./readSchema.js";
|
|
3
|
+
import { ReadBatchJournal, lockReadOwner } from "./readBatchJournal.js";
|
|
1
4
|
import { Dexie } from "dexie";
|
|
5
|
+
import { isReadingControl } from "./readingContent.js";
|
|
2
6
|
import { isValidChatTeamId } from "./thread.js";
|
|
7
|
+
/** Retain read semantics without a second durable copy of message bodies. */
|
|
8
|
+
export function readingMetadata(state) {
|
|
9
|
+
let changed = false;
|
|
10
|
+
const threads = state.threads.map(thread => {
|
|
11
|
+
let different = false;
|
|
12
|
+
const messages = thread.messages.map(message => {
|
|
13
|
+
if (message.payload === null && typeof message.readingControl === "boolean")
|
|
14
|
+
return message;
|
|
15
|
+
different = true;
|
|
16
|
+
return { ...message, payload: null, readingControl: Boolean(message.readingControl) || isReadingControl(message.payload, state.appId) };
|
|
17
|
+
});
|
|
18
|
+
if (!different)
|
|
19
|
+
return thread;
|
|
20
|
+
changed = true;
|
|
21
|
+
return { ...thread, messages };
|
|
22
|
+
});
|
|
23
|
+
return changed ? { ...state, threads } : state;
|
|
24
|
+
}
|
|
3
25
|
export class ReadSyncGap extends Error {
|
|
4
26
|
cursor;
|
|
5
27
|
constructor(cursor) {
|
|
@@ -10,6 +32,17 @@ export class ReadSyncGap extends Error {
|
|
|
10
32
|
export function createReadIndex(appId, profileId) {
|
|
11
33
|
return { schemaVersion: 1, appId, profileId, syncCursor: "0", threads: [], pending: [] };
|
|
12
34
|
}
|
|
35
|
+
export function readingCursor(thread, root) {
|
|
36
|
+
return root == null ? thread.readThroughSeq : Object.hasOwn(thread.messageThreadReadThrough ?? {}, root) ? thread.messageThreadReadThrough[root] : 0;
|
|
37
|
+
}
|
|
38
|
+
function mergeDiscussionCursors(a, b) {
|
|
39
|
+
if (!a.messageThreadReadThrough && !b.messageThreadReadThrough)
|
|
40
|
+
return {};
|
|
41
|
+
const entries = new Map(Object.entries(a.messageThreadReadThrough ?? {}));
|
|
42
|
+
for (const [root, seq] of Object.entries(b.messageThreadReadThrough ?? {}))
|
|
43
|
+
entries.set(root, Math.max(entries.get(root) ?? 0, seq));
|
|
44
|
+
return { messageThreadReadThrough: Object.fromEntries(entries) };
|
|
45
|
+
}
|
|
13
46
|
function validateThread(thread) {
|
|
14
47
|
if (!thread.id || !["dm", "group"].includes(thread.kind) || !Number.isSafeInteger(thread.readThroughSeq) || thread.readThroughSeq < 0)
|
|
15
48
|
throw new Error("INVALID_READ_THREAD");
|
|
@@ -17,9 +50,13 @@ function validateThread(thread) {
|
|
|
17
50
|
throw new Error("INVALID_READ_TEAM");
|
|
18
51
|
if (thread.conversationId !== undefined && (!thread.conversationId || !thread.teamId))
|
|
19
52
|
throw new Error("INVALID_READ_CONVERSATION");
|
|
53
|
+
if (thread.preservedReadMessageIds !== undefined && (!Array.isArray(thread.preservedReadMessageIds) || thread.preservedReadMessageIds.some(id => typeof id !== "string" || !id)))
|
|
54
|
+
throw new Error("INVALID_PRESERVED_READ_MESSAGES");
|
|
55
|
+
if (Object.entries(thread.messageThreadReadThrough ?? {}).some(([root, seq]) => !validMessageThreadRoot(root) || !Number.isSafeInteger(seq) || seq < 0))
|
|
56
|
+
throw new Error("INVALID_MESSAGE_THREAD_READING");
|
|
20
57
|
const ids = new Set(), positions = new Set();
|
|
21
58
|
for (const message of thread.messages) {
|
|
22
|
-
if (!message.id || !Number.isSafeInteger(message.seq) || message.seq < 1 || ids.has(message.id) || positions.has(message.seq)
|
|
59
|
+
if (message.threadRootId != null && !validMessageThreadRoot(message.threadRootId) || !message.id || !Number.isSafeInteger(message.seq) || message.seq < 1 || ids.has(message.id) || positions.has(message.seq)
|
|
23
60
|
|| !["visible", "explicit"].includes(message.readPolicy))
|
|
24
61
|
throw new Error("INVALID_READ_MESSAGE");
|
|
25
62
|
ids.add(message.id);
|
|
@@ -31,11 +68,11 @@ function cloneThread(thread) {
|
|
|
31
68
|
return structuredClone({ ...thread, messages: [...thread.messages].sort((a, b) => a.seq - b.seq), explicitReadMessageIds: [...new Set(thread.explicitReadMessageIds)] });
|
|
32
69
|
}
|
|
33
70
|
function applyOperation(thread, operation) {
|
|
34
|
-
return { ...thread, readThroughSeq: Math.max(thread.readThroughSeq, operation.readThroughSeq),
|
|
71
|
+
return { ...thread, ...(operation.threadRootId === undefined ? { readThroughSeq: Math.max(thread.readThroughSeq, operation.readThroughSeq) } : { messageThreadReadThrough: { ...thread.messageThreadReadThrough, [operation.threadRootId]: Math.max(readingCursor(thread, operation.threadRootId), operation.readThroughSeq) } }),
|
|
35
72
|
explicitReadMessageIds: [...new Set([...thread.explicitReadMessageIds, ...operation.explicitReadMessageIds])] };
|
|
36
73
|
}
|
|
37
74
|
function covered(thread, operation) {
|
|
38
|
-
return thread.
|
|
75
|
+
return readingCursor(thread, operation.threadRootId) >= operation.readThroughSeq
|
|
39
76
|
&& operation.explicitReadMessageIds.every(id => thread.explicitReadMessageIds.includes(id));
|
|
40
77
|
}
|
|
41
78
|
/** A snapshot is authoritative for server state, never for unsent local operations. */
|
|
@@ -59,7 +96,7 @@ export function installReadSnapshot(current, snapshot) {
|
|
|
59
96
|
for (const previous of current.threads) {
|
|
60
97
|
const thread = byId.get(previous.id);
|
|
61
98
|
if (thread)
|
|
62
|
-
byId.set(thread.id, { ...thread, readThroughSeq: Math.max(thread.readThroughSeq, previous.readThroughSeq),
|
|
99
|
+
byId.set(thread.id, { ...thread, ...mergeDiscussionCursors(thread, previous), preservedReadMessageIds: [...new Set([...(thread.preservedReadMessageIds ?? []), ...(previous.preservedReadMessageIds ?? [])])], readThroughSeq: Math.max(thread.readThroughSeq, previous.readThroughSeq),
|
|
63
100
|
explicitReadMessageIds: [...new Set([...thread.explicitReadMessageIds, ...previous.explicitReadMessageIds])] });
|
|
64
101
|
}
|
|
65
102
|
return resolveObservedReads({ ...snapshot, threads: [...byId.values()], pending, observedReadIntents: current.observedReadIntents ?? [] });
|
|
@@ -75,7 +112,7 @@ export function applyReadChange(current, change) {
|
|
|
75
112
|
const incoming = cloneThread(change.thread);
|
|
76
113
|
const pending = current.pending.filter(operation => operation.threadId !== incoming.id || !covered(incoming, operation));
|
|
77
114
|
const previous = current.threads.find(thread => thread.id === incoming.id);
|
|
78
|
-
const merged = previous ? { ...incoming, readThroughSeq: Math.max(incoming.readThroughSeq, previous.readThroughSeq),
|
|
115
|
+
const merged = previous ? { ...incoming, ...mergeDiscussionCursors(incoming, previous), preservedReadMessageIds: [...new Set([...(incoming.preservedReadMessageIds ?? []), ...(previous.preservedReadMessageIds ?? [])])], readThroughSeq: Math.max(incoming.readThroughSeq, previous.readThroughSeq),
|
|
79
116
|
explicitReadMessageIds: [...new Set([...incoming.explicitReadMessageIds, ...previous.explicitReadMessageIds])] } : incoming;
|
|
80
117
|
const projected = pending.filter(operation => operation.threadId === incoming.id).reduce(applyOperation, merged);
|
|
81
118
|
return resolveObservedReads({ ...current, syncCursor: change.syncCursor, pending, threads: [...current.threads.filter(t => t.id !== incoming.id), projected] });
|
|
@@ -86,12 +123,12 @@ export function recordReadIntent(current, intent) {
|
|
|
86
123
|
throw new Error("INVALID_READ_INTENT");
|
|
87
124
|
const observed = current.observedReadIntents ?? [];
|
|
88
125
|
if (observed.some(item => item.threadId === intent.threadId && item.messageId === intent.messageId && item.readPolicy === intent.readPolicy))
|
|
89
|
-
return current;
|
|
126
|
+
return resolveObservedReads(current);
|
|
90
127
|
if (observed.some(item => item.operationId === intent.operationId) || current.pending.some(item => item.operationId === intent.operationId))
|
|
91
128
|
throw new Error("INVALID_READ_OPERATION_ID");
|
|
92
129
|
return resolveObservedReads({ ...current, observedReadIntents: [...observed, structuredClone(intent)] });
|
|
93
130
|
}
|
|
94
|
-
function resolveObservedReads(current) {
|
|
131
|
+
export function resolveObservedReads(current) {
|
|
95
132
|
let next = current;
|
|
96
133
|
const remaining = [];
|
|
97
134
|
for (const intent of current.observedReadIntents ?? []) {
|
|
@@ -108,6 +145,9 @@ function resolveObservedReads(current) {
|
|
|
108
145
|
next = intent.readPolicy === "explicit" ? recordExplicitRead(next, intent.threadId, intent.messageId, intent.operationId)
|
|
109
146
|
: recordVisibleRead(next, intent.threadId, intent.messageId, intent.operationId);
|
|
110
147
|
}
|
|
148
|
+
const previous = current.observedReadIntents;
|
|
149
|
+
if (next === current && previous && previous.length === remaining.length && previous.every((intent, i) => intent === remaining[i]))
|
|
150
|
+
return current;
|
|
111
151
|
return { ...next, observedReadIntents: remaining };
|
|
112
152
|
}
|
|
113
153
|
/** Called only for a message the visible viewport actually reached. */
|
|
@@ -116,9 +156,9 @@ export function recordVisibleRead(current, threadId, messageId, operationId) {
|
|
|
116
156
|
const message = thread?.messages.find(m => m.id === messageId);
|
|
117
157
|
if (!thread || !message || message.readPolicy !== "visible")
|
|
118
158
|
throw new Error("INVALID_VISIBLE_READ");
|
|
119
|
-
if (message.seq <= thread.
|
|
159
|
+
if (thread.preservedReadMessageIds?.includes(message.id) || message.seq <= readingCursor(thread, message.threadRootId))
|
|
120
160
|
return current;
|
|
121
|
-
return enqueue(current, { operationId, threadId: thread.id, readThroughSeq: message.seq, readThroughMessageId: message.id, explicitReadMessageIds: [] });
|
|
161
|
+
return enqueue(current, { operationId, threadId: thread.id, ...(message.threadRootId == null ? {} : { threadRootId: message.threadRootId }), readThroughSeq: message.seq, readThroughMessageId: message.id, explicitReadMessageIds: [] });
|
|
122
162
|
}
|
|
123
163
|
export function recordExplicitRead(current, threadId, messageId, operationId) {
|
|
124
164
|
const thread = readSource(current, threadId, messageId);
|
|
@@ -127,7 +167,7 @@ export function recordExplicitRead(current, threadId, messageId, operationId) {
|
|
|
127
167
|
throw new Error("INVALID_EXPLICIT_READ");
|
|
128
168
|
if (thread.explicitReadMessageIds.includes(messageId))
|
|
129
169
|
return current;
|
|
130
|
-
return enqueue(current, { operationId, threadId: thread.id, readThroughSeq: 0, explicitReadMessageIds: [messageId] });
|
|
170
|
+
return enqueue(current, { operationId, threadId: thread.id, ...(message.threadRootId == null ? {} : { threadRootId: message.threadRootId }), readThroughSeq: 0, explicitReadMessageIds: [messageId] });
|
|
131
171
|
}
|
|
132
172
|
function enqueue(current, operation) {
|
|
133
173
|
if (!operation.operationId || current.pending.some(p => p.operationId === operation.operationId))
|
|
@@ -138,9 +178,10 @@ function enqueue(current, operation) {
|
|
|
138
178
|
export function coalesceReadOperations(current) {
|
|
139
179
|
const batches = new Map();
|
|
140
180
|
for (const operation of current.pending) {
|
|
141
|
-
const
|
|
181
|
+
const key = JSON.stringify([operation.threadId, operation.threadRootId ?? null]);
|
|
182
|
+
const batch = batches.get(key);
|
|
142
183
|
if (!batch) {
|
|
143
|
-
batches.set(
|
|
184
|
+
batches.set(key, { ...structuredClone(operation), operationIds: [operation.operationId] });
|
|
144
185
|
continue;
|
|
145
186
|
}
|
|
146
187
|
batch.operationIds.push(operation.operationId);
|
|
@@ -153,32 +194,108 @@ export function coalesceReadOperations(current) {
|
|
|
153
194
|
return [...batches.values()];
|
|
154
195
|
}
|
|
155
196
|
/** Counts are over the indexed message coverage, not an estimate of missing history. */
|
|
156
|
-
export function unreadInThread(state, threadId) {
|
|
197
|
+
export function unreadInThread(state, threadId, hidden, threadRootId) {
|
|
157
198
|
const thread = state.threads.find(t => t.id === threadId);
|
|
158
199
|
if (!thread)
|
|
159
200
|
throw new Error("UNKNOWN_READ_THREAD");
|
|
160
201
|
const explicit = new Set(thread.explicitReadMessageIds);
|
|
161
|
-
const messages = thread.messages.filter(message => !message.recalled && message.from !== state.profileId && message.recipients.includes(state.profileId)
|
|
162
|
-
&& (message.readPolicy === "explicit" ? !explicit.has(message.id) : message.seq > thread.
|
|
202
|
+
const messages = thread.messages.filter(message => (threadRootId === undefined || message.threadRootId === threadRootId) && !message.recalled && !hidden?.get(message.id)?.has(message.from) && !(message.readingControl || isReadingControl(message.payload, state.appId)) && message.from !== state.profileId && message.recipients.includes(state.profileId)
|
|
203
|
+
&& !thread.preservedReadMessageIds?.includes(message.id) && (message.readPolicy === "explicit" ? !explicit.has(message.id) : message.seq > readingCursor(thread, message.threadRootId)));
|
|
163
204
|
const unreadMessageCount = messages.length;
|
|
164
205
|
const unreadMentionCount = messages.filter(message => message.mentions.includes(state.profileId)).length;
|
|
165
206
|
return { unreadMessageCount, unreadMentionCount, badgeCount: thread.kind === "group" ? unreadMentionCount : unreadMessageCount };
|
|
166
207
|
}
|
|
167
|
-
|
|
208
|
+
function readTeamVersion(versions, team) { return Object.hasOwn(versions, team) ? versions[team] : 0; }
|
|
209
|
+
export function assertReadIndexVersions(expected, current = {}, teamId) {
|
|
210
|
+
const teams = new Set(teamId === undefined ? [...Object.keys(expected), ...Object.keys(current)] : [teamId]);
|
|
211
|
+
if ([...teams].some(team => readTeamVersion(expected, team) !== readTeamVersion(current, team)))
|
|
212
|
+
throw new Error("READ_SCOPE_CHANGED");
|
|
213
|
+
}
|
|
214
|
+
/** Remove only the withdrawn team's original sources, logical conversations and
|
|
215
|
+
* queued observations. Other teams' pending operations must survive. */
|
|
216
|
+
export function removeReadTeam(state, teamId, knownThreadIds = []) {
|
|
217
|
+
const removed = new Set(knownThreadIds);
|
|
218
|
+
for (const thread of state.threads)
|
|
219
|
+
if (thread.teamId === teamId) {
|
|
220
|
+
removed.add(thread.id);
|
|
221
|
+
if (thread.conversationId)
|
|
222
|
+
removed.add(thread.conversationId);
|
|
223
|
+
}
|
|
224
|
+
return { ...state, syncCursor: "0", threads: state.threads.filter(thread => thread.teamId !== teamId && !removed.has(thread.id)),
|
|
225
|
+
pending: state.pending.filter(operation => !removed.has(operation.threadId)),
|
|
226
|
+
observedReadIntents: state.observedReadIntents?.filter(intent => !removed.has(intent.threadId)) };
|
|
227
|
+
}
|
|
228
|
+
/** Preserves the database and logical keys; store renaming fences old format writers. */
|
|
168
229
|
export class IndexedDbReadIndex {
|
|
169
230
|
storageScope;
|
|
231
|
+
migrateLegacy;
|
|
232
|
+
metadataOnly;
|
|
170
233
|
database;
|
|
171
234
|
profiles;
|
|
235
|
+
threadRows;
|
|
236
|
+
messageRows;
|
|
237
|
+
positionRows;
|
|
238
|
+
normalizedStates = new WeakSet();
|
|
239
|
+
orderedStates = new WeakSet();
|
|
240
|
+
legacyClean = new Set();
|
|
241
|
+
observationMessages = new WeakMap();
|
|
242
|
+
versions;
|
|
172
243
|
closed = false;
|
|
173
|
-
|
|
244
|
+
journal;
|
|
245
|
+
factory;
|
|
246
|
+
schemaReady;
|
|
247
|
+
ownerTail = Promise.resolve();
|
|
248
|
+
constructor(factory = globalThis.indexedDB, name = "pmate-social-read-index", storageScope, migrateLegacy = false, metadataOnly = false) {
|
|
174
249
|
this.storageScope = storageScope;
|
|
250
|
+
this.migrateLegacy = migrateLegacy;
|
|
251
|
+
this.metadataOnly = metadataOnly;
|
|
175
252
|
if (!factory)
|
|
176
253
|
throw new Error("READ_STORAGE_UNAVAILABLE");
|
|
254
|
+
this.factory = factory;
|
|
177
255
|
this.database = new Dexie(name, { indexedDB: factory, IDBKeyRange: globalThis.IDBKeyRange });
|
|
178
256
|
// The empty schema retains the legacy out-of-line primary key and records.
|
|
179
257
|
this.database.version(1).stores({ profiles: "" });
|
|
180
|
-
this.
|
|
258
|
+
this.database.version(2).stores({ profiles: "", versions: "" });
|
|
259
|
+
this.database.version(3).stores({ readThreads: "[owner+id],owner", readMessages: "[owner+thread+id],[owner+thread],owner", readPositions: "[owner+id],owner" });
|
|
260
|
+
// Native indexes track scalar source identity even when an older writer
|
|
261
|
+
// changes rows. Reading these keys does not deserialize messageIds arrays.
|
|
262
|
+
this.database.version(4).stores({ readThreads: "[owner+id],owner,[owner+id+value.kind+value.teamId],[owner+value.conversationId+value.kind+value.teamId+id],[owner+id+value.conversationId]" });
|
|
263
|
+
// Keep v4 indexes for already-open older SDKs, and make source discovery
|
|
264
|
+
// dense for legitimate legacy rows whose optional team field is absent.
|
|
265
|
+
this.database.version(5).stores({ readThreads: "[owner+id],owner,[owner+id+value.kind+value.teamId],[owner+value.conversationId+value.kind+value.teamId+id],[owner+id+value.conversationId],[owner+id+value.kind],[owner+value.conversationId+value.kind+id]" });
|
|
266
|
+
this.database.version(6).stores({ profiles: "unsupportedReadingFormat", versions: "unsupportedReadingFormat", readingProfiles: "", readingVersions: "", readThreads: null, readMessages: null, readPositions: null, readingThreads: "[owner+id],owner,[owner+id+value.kind+value.teamId],[owner+value.conversationId+value.kind+value.teamId+id],[owner+id+value.conversationId],[owner+id+value.kind],[owner+value.conversationId+value.kind+id]", readingMessages: "[owner+thread+id],[owner+thread],owner", readingPositions: "[owner+id],owner", readBatches: "[owner+key],owner" });
|
|
267
|
+
this.journal = new ReadBatchJournal(this.database, () => this.closed);
|
|
268
|
+
this.positionRows = this.database.table("readingPositions");
|
|
269
|
+
this.threadRows = this.database.table("readingThreads");
|
|
270
|
+
this.messageRows = this.database.table("readingMessages");
|
|
271
|
+
this.profiles = this.database.table("readingProfiles");
|
|
272
|
+
this.versions = this.database.table("readingVersions");
|
|
181
273
|
this.database.on("versionchange", () => { this.database.close({ disableAutoOpen: false }); return false; });
|
|
274
|
+
this.schemaReady = prepareReadSchema(factory, name);
|
|
275
|
+
void this.schemaReady.catch(() => { });
|
|
276
|
+
}
|
|
277
|
+
async owned(appId, profileId, run) {
|
|
278
|
+
const previous = this.ownerTail;
|
|
279
|
+
let release;
|
|
280
|
+
this.ownerTail = new Promise(resolve => { release = resolve; });
|
|
281
|
+
await previous;
|
|
282
|
+
try {
|
|
283
|
+
if (this.closed)
|
|
284
|
+
throw new Error("READ_STORAGE_CLOSED");
|
|
285
|
+
await this.schemaReady;
|
|
286
|
+
if (this.closed)
|
|
287
|
+
throw new Error("READ_STORAGE_CLOSED");
|
|
288
|
+
const owner = JSON.stringify(this.key(appId, profileId));
|
|
289
|
+
return await lockReadOwner(this.factory, this.database.name, owner, async () => { await this.journal.recover(owner); return run(); }, work => this.journal.lease(owner, work));
|
|
290
|
+
}
|
|
291
|
+
catch (error) {
|
|
292
|
+
if (this.closed)
|
|
293
|
+
throw new Error("READ_STORAGE_CLOSED");
|
|
294
|
+
throw error;
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
release();
|
|
298
|
+
}
|
|
182
299
|
}
|
|
183
300
|
async transaction(mode, execute) {
|
|
184
301
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
@@ -186,11 +303,15 @@ export class IndexedDbReadIndex {
|
|
|
186
303
|
throw new Error("READ_STORAGE_CLOSED");
|
|
187
304
|
let started = false;
|
|
188
305
|
try {
|
|
189
|
-
return await this.database.transaction(mode, this.profiles, async () => {
|
|
306
|
+
return await this.database.transaction(mode, [this.profiles, this.versions, this.threadRows, this.messageRows, this.positionRows, this.database.table("readBatches")], async () => {
|
|
190
307
|
if (this.closed)
|
|
191
308
|
throw new Error("READ_STORAGE_CLOSED");
|
|
192
309
|
started = true;
|
|
193
|
-
|
|
310
|
+
await this.journal.checkLeases();
|
|
311
|
+
const result = await execute();
|
|
312
|
+
if (mode === "rw")
|
|
313
|
+
await this.journal.checkLeases(true);
|
|
314
|
+
return result;
|
|
194
315
|
});
|
|
195
316
|
}
|
|
196
317
|
catch (error) {
|
|
@@ -205,21 +326,355 @@ export class IndexedDbReadIndex {
|
|
|
205
326
|
throw new Error("READ_STORAGE_UNAVAILABLE");
|
|
206
327
|
}
|
|
207
328
|
key(appId, profileId) { return this.storageScope === undefined ? [appId, profileId] : [appId, profileId, this.storageScope]; }
|
|
208
|
-
|
|
209
|
-
|
|
329
|
+
/** Keyset pages avoid materializing a second, unbounded array of durable rows.
|
|
330
|
+
* Keep the caller's transaction so every page belongs to one consistent view. */
|
|
331
|
+
async readPages(table, owner, key, visit) {
|
|
332
|
+
let after;
|
|
333
|
+
for (;;) {
|
|
334
|
+
const rows = await table.where(":id").between(after ?? [owner, Dexie.minKey], [owner, Dexie.maxKey], !after, true).limit(128).toArray();
|
|
335
|
+
for (const row of rows)
|
|
336
|
+
visit(row);
|
|
337
|
+
if (rows.length < 128)
|
|
338
|
+
return;
|
|
339
|
+
after = key(rows[rows.length - 1]);
|
|
340
|
+
}
|
|
210
341
|
}
|
|
211
|
-
async
|
|
212
|
-
|
|
213
|
-
const
|
|
214
|
-
const
|
|
215
|
-
|
|
342
|
+
async hydrate(current, key) {
|
|
343
|
+
if (current.normalized) {
|
|
344
|
+
const owner = JSON.stringify(key);
|
|
345
|
+
const byThread = new Map();
|
|
346
|
+
const byPosition = new Map(), byId = new Map();
|
|
347
|
+
await Promise.all([
|
|
348
|
+
this.readPages(this.threadRows, owner, row => [row.owner, row.id], row => byId.set(row.id, row)),
|
|
349
|
+
this.readPages(this.messageRows, owner, row => [row.owner, row.thread, row.id], row => {
|
|
350
|
+
if (!byThread.has(row.thread))
|
|
351
|
+
byThread.set(row.thread, new Map());
|
|
352
|
+
byThread.get(row.thread).set(row.id, row);
|
|
353
|
+
}),
|
|
354
|
+
this.readPages(this.positionRows, owner, row => [row.owner, row.id], row => byPosition.set(row.id, row)),
|
|
355
|
+
]);
|
|
356
|
+
const { normalized: _normalized, threadOrder, ...state } = current;
|
|
357
|
+
const result = { ...state, threads: (threadOrder ?? []).map(id => {
|
|
358
|
+
const row = byId.get(id);
|
|
359
|
+
const position = byPosition.get(id);
|
|
360
|
+
if (!row || !position)
|
|
361
|
+
throw new Error("READ_STORAGE_INCOMPLETE");
|
|
362
|
+
const stored = byThread.get(id) ?? new Map();
|
|
363
|
+
let messages;
|
|
364
|
+
if (row.messageCount !== undefined && !row.messageIds.length) {
|
|
365
|
+
const ordered = [...stored.values()], ranked = ordered.every(row => Number.isSafeInteger(row.ordinal));
|
|
366
|
+
ordered.sort((a, b) => ranked ? a.ordinal - b.ordinal : a.value.seq - b.value.seq);
|
|
367
|
+
if (ordered.length !== row.messageCount)
|
|
368
|
+
throw new Error("READ_STORAGE_INCOMPLETE");
|
|
369
|
+
messages = ordered.map(row => row.value);
|
|
370
|
+
}
|
|
371
|
+
else
|
|
372
|
+
messages = row.messageIds.map(messageId => {
|
|
373
|
+
const message = stored.get(messageId);
|
|
374
|
+
if (!message)
|
|
375
|
+
throw new Error("READ_STORAGE_INCOMPLETE");
|
|
376
|
+
return message.value;
|
|
377
|
+
});
|
|
378
|
+
return { ...row.value, readThroughSeq: position.readThroughSeq, messageThreadReadThrough: position.messageThreadReadThrough, explicitReadMessageIds: position.explicitReadMessageIds, messages };
|
|
379
|
+
}) };
|
|
380
|
+
this.normalizedStates.add(result);
|
|
381
|
+
if ((threadOrder ?? []).every(id => byId.get(id)?.messageCount !== undefined && !byId.get(id).messageIds.length && [...(byThread.get(id)?.values() ?? [])].every(row => Number.isSafeInteger(row.ordinal))))
|
|
382
|
+
this.orderedStates.add(result);
|
|
383
|
+
return result;
|
|
384
|
+
}
|
|
385
|
+
return current;
|
|
386
|
+
}
|
|
387
|
+
async loadCurrent(appId, profileId) {
|
|
388
|
+
const current = await this.loadStored(appId, profileId);
|
|
389
|
+
if (!current || !this.metadataOnly)
|
|
390
|
+
return current;
|
|
391
|
+
const metadata = readingMetadata(current);
|
|
392
|
+
if (metadata !== current)
|
|
393
|
+
await this.writeState(appId, profileId, current, metadata);
|
|
394
|
+
return metadata;
|
|
395
|
+
}
|
|
396
|
+
async loadStored(appId, profileId) {
|
|
397
|
+
const current = await this.transaction("r", async () => {
|
|
398
|
+
if (this.storageScope === undefined && (await this.profiles.get([appId, profileId, "legacy-owner-v1"]))?.legacyOwner)
|
|
399
|
+
return undefined;
|
|
400
|
+
const row = await this.profiles.get(this.key(appId, profileId));
|
|
401
|
+
if (row && (row.appId !== appId || row.profileId !== profileId || row.schemaVersion !== 1))
|
|
216
402
|
throw new Error("READ_IDENTITY_MISMATCH");
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
403
|
+
return row?.normalized ? this.hydrate(row, this.key(appId, profileId)) : row;
|
|
404
|
+
});
|
|
405
|
+
if (current) {
|
|
406
|
+
await this.cleanupClaimedLegacy(appId, profileId);
|
|
407
|
+
if (!this.normalizedStates.has(current) && (this.migrateLegacy || this.metadataOnly)) {
|
|
408
|
+
const next = this.metadataOnly ? readingMetadata(current) : current;
|
|
409
|
+
await this.writeState(appId, profileId, undefined, next);
|
|
410
|
+
return next;
|
|
411
|
+
}
|
|
412
|
+
return current;
|
|
413
|
+
}
|
|
414
|
+
if (!this.migrateLegacy || this.storageScope === undefined)
|
|
415
|
+
return undefined;
|
|
416
|
+
const legacyOwner = JSON.stringify([appId, profileId]);
|
|
417
|
+
const legacy = await lockReadOwner(this.factory, this.database.name, legacyOwner, async () => {
|
|
418
|
+
await this.journal.recover(legacyOwner);
|
|
419
|
+
const allowed = await this.transaction("rw", async () => {
|
|
420
|
+
const key = [appId, profileId, "legacy-owner-v1"], marker = await this.profiles.get(key);
|
|
421
|
+
if (marker && marker.legacyOwner !== this.storageScope)
|
|
422
|
+
return false;
|
|
423
|
+
const raw = await this.profiles.get([appId, profileId]);
|
|
424
|
+
if (!raw)
|
|
425
|
+
return false;
|
|
426
|
+
if (raw.appId !== appId || raw.profileId !== profileId || raw.schemaVersion !== 1)
|
|
427
|
+
throw new Error("READ_IDENTITY_MISMATCH");
|
|
428
|
+
if (!marker)
|
|
429
|
+
await this.profiles.put({ ...createReadIndex(appId, profileId), legacyOwner: this.storageScope }, key);
|
|
430
|
+
return true;
|
|
431
|
+
});
|
|
432
|
+
if (!allowed)
|
|
433
|
+
return undefined;
|
|
434
|
+
return this.transaction("r", async () => { const row = await this.profiles.get([appId, profileId]); return row?.normalized ? this.hydrate(row, [appId, profileId]) : row; });
|
|
435
|
+
}, work => this.journal.lease(legacyOwner, work));
|
|
436
|
+
if (!legacy)
|
|
437
|
+
return undefined;
|
|
438
|
+
if (legacy.appId !== appId || legacy.profileId !== profileId || legacy.schemaVersion !== 1)
|
|
439
|
+
throw new Error("READ_IDENTITY_MISMATCH");
|
|
440
|
+
const next = this.metadataOnly ? readingMetadata(legacy) : legacy;
|
|
441
|
+
await this.writeState(appId, profileId, undefined, next);
|
|
442
|
+
await this.cleanupClaimedLegacy(appId, profileId);
|
|
443
|
+
return next;
|
|
444
|
+
}
|
|
445
|
+
async cleanupClaimedLegacy(appId, profileId) {
|
|
446
|
+
if (this.storageScope === undefined || !this.migrateLegacy)
|
|
447
|
+
return;
|
|
448
|
+
const key = JSON.stringify(this.key(appId, profileId));
|
|
449
|
+
if (this.legacyClean.has(key))
|
|
450
|
+
return;
|
|
451
|
+
const marker = await this.transaction("r", () => this.profiles.get([appId, profileId, "legacy-owner-v1"]));
|
|
452
|
+
if (marker?.legacyOwner === this.storageScope) {
|
|
453
|
+
await this.transaction("rw", () => this.profiles.delete([appId, profileId]));
|
|
454
|
+
await this.cleanUnreachable(JSON.stringify([appId, profileId]), undefined);
|
|
455
|
+
}
|
|
456
|
+
this.legacyClean.add(key);
|
|
457
|
+
}
|
|
458
|
+
async load(appId, profileId) {
|
|
459
|
+
return this.owned(appId, profileId, () => this.loadCurrent(appId, profileId));
|
|
460
|
+
}
|
|
461
|
+
async loadVersioned(appId, profileId) {
|
|
462
|
+
return this.owned(appId, profileId, async () => ({ state: await this.loadCurrent(appId, profileId), versions: await this.transaction("r", async () => (await this.versions.get(this.key(appId, profileId)))?.teams ?? {}) }));
|
|
463
|
+
}
|
|
464
|
+
async loadVersions(appId, profileId) {
|
|
465
|
+
return this.owned(appId, profileId, () => this.transaction("r", async () => (await this.versions.get(this.key(appId, profileId)))?.teams ?? {}));
|
|
466
|
+
}
|
|
467
|
+
async invalidateTeam(appId, profileId, teamId, version, knownThreadIds = []) {
|
|
468
|
+
if (!isValidChatTeamId(teamId) || !Number.isSafeInteger(version) || version < 1)
|
|
469
|
+
throw new Error("INVALID_READ_SCOPE_VERSION");
|
|
470
|
+
return this.owned(appId, profileId, async () => {
|
|
471
|
+
const teams = await this.transaction("r", async () => (await this.versions.get(this.key(appId, profileId)))?.teams ?? {});
|
|
472
|
+
if (readTeamVersion(teams, teamId) >= version)
|
|
473
|
+
return await this.loadCurrent(appId, profileId) ?? createReadIndex(appId, profileId);
|
|
474
|
+
return this.updateOwned(appId, profileId, state => removeReadTeam(state, teamId, knownThreadIds), undefined, { teams: { ...teams, [teamId]: version } });
|
|
220
475
|
});
|
|
221
476
|
}
|
|
222
|
-
async
|
|
477
|
+
async observe(appId, profileId, transform, scope) {
|
|
478
|
+
if (!this.metadataOnly || scope.targets.length > 128)
|
|
479
|
+
return undefined;
|
|
480
|
+
const key = this.key(appId, profileId), owner = JSON.stringify(key), base = scope.base;
|
|
481
|
+
const header = await this.profiles.get(key);
|
|
482
|
+
if (header && (header.appId !== appId || header.profileId !== profileId || header.schemaVersion !== 1))
|
|
483
|
+
throw new Error("READ_IDENTITY_MISMATCH");
|
|
484
|
+
if (!header?.normalized || base.schemaVersion !== 1 || base.appId !== appId || base.profileId !== profileId || base.syncCursor !== header.syncCursor ||
|
|
485
|
+
header.threadOrder?.length !== base.threads.length || header.threadOrder.some((id, i) => id !== base.threads[i].id))
|
|
486
|
+
return undefined;
|
|
487
|
+
const sources = new Map();
|
|
488
|
+
for (const threadId of new Set(scope.targets.map(target => target.threadId))) {
|
|
489
|
+
const direct = await this.threadRows.where("[owner+id+value.kind]").between([owner, threadId, Dexie.minKey], [owner, threadId, Dexie.maxKey], true, true).limit(129).keys();
|
|
490
|
+
const assigned = await this.threadRows.where("[owner+value.conversationId+value.kind+id]").between([owner, threadId, Dexie.minKey], [owner, threadId, Dexie.maxKey], true, true).limit(129).keys();
|
|
491
|
+
if (direct.length + assigned.length > 128)
|
|
492
|
+
return undefined;
|
|
493
|
+
const identities = [...new Map([...direct.map(value => ({ id: value[1], kind: value[2] })), ...assigned.map(value => ({ id: value[3], kind: value[2] }))].map(value => [value.id, value])).values()];
|
|
494
|
+
const indexedIds = new Set(identities.map(identity => identity.id));
|
|
495
|
+
const expected = base.threads.filter(thread => thread.id === threadId || thread.conversationId === threadId);
|
|
496
|
+
// Sparse indexes omit legacy sources without team metadata. A partial
|
|
497
|
+
// family cannot safely resolve an observation for the logical thread.
|
|
498
|
+
if (indexedIds.size !== expected.length || expected.some(thread => !indexedIds.has(thread.id)))
|
|
499
|
+
return undefined;
|
|
500
|
+
for (const identity of identities) {
|
|
501
|
+
const cached = base.threads.find(thread => thread.id === identity.id);
|
|
502
|
+
if (!cached || cached.kind !== identity.kind)
|
|
503
|
+
return undefined;
|
|
504
|
+
const team = await this.threadRows.where("[owner+id+value.kind+value.teamId]").between([owner, identity.id, Dexie.minKey], [owner, identity.id, Dexie.maxKey], true, true).limit(2).keys();
|
|
505
|
+
if (team.length > 1 || cached.teamId !== team[0]?.[3])
|
|
506
|
+
return undefined;
|
|
507
|
+
const mapping = await this.threadRows.where("[owner+id+value.conversationId]").between([owner, identity.id, Dexie.minKey], [owner, identity.id, Dexie.maxKey], true, true).limit(2).keys();
|
|
508
|
+
if (mapping.length > 1 || cached.conversationId !== mapping[0]?.[2])
|
|
509
|
+
return undefined;
|
|
510
|
+
let source = sources.get(identity.id);
|
|
511
|
+
if (!source) {
|
|
512
|
+
source = { cached, ids: new Set() };
|
|
513
|
+
sources.set(identity.id, source);
|
|
514
|
+
}
|
|
515
|
+
for (const target of scope.targets)
|
|
516
|
+
if (target.threadId === threadId)
|
|
517
|
+
source.ids.add(target.messageId);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
if ([...sources.values()].reduce((sum, source) => sum + source.ids.size, 0) > 128)
|
|
521
|
+
return undefined;
|
|
522
|
+
const sourceIds = [...sources.keys()];
|
|
523
|
+
// Cursors are the mutable cross-document view. Refresh their small rows,
|
|
524
|
+
// while message metadata remains targeted; otherwise a later batch based
|
|
525
|
+
// on an older snapshot could regress a different conversation's progress.
|
|
526
|
+
const positionById = new Map();
|
|
527
|
+
await this.readPages(this.positionRows, owner, row => [row.owner, row.id], row => positionById.set(row.id, row));
|
|
528
|
+
if (base.threads.some(thread => !positionById.has(thread.id)))
|
|
529
|
+
return undefined;
|
|
530
|
+
const positions = sourceIds.map(id => positionById.get(id));
|
|
531
|
+
const partialThreads = [];
|
|
532
|
+
for (let i = 0; i < sourceIds.length; i++) {
|
|
533
|
+
const id = sourceIds[i], source = sources.get(id), position = positions[i];
|
|
534
|
+
if (!position)
|
|
535
|
+
return undefined;
|
|
536
|
+
let cached = this.observationMessages.get(source.cached.messages);
|
|
537
|
+
if (!cached) {
|
|
538
|
+
cached = new Map(source.cached.messages.map(message => [message.id, message]));
|
|
539
|
+
this.observationMessages.set(source.cached.messages, cached);
|
|
540
|
+
}
|
|
541
|
+
const ids = [...source.ids], rows = await this.messageRows.bulkGet(ids.map(messageId => [owner, id, messageId]));
|
|
542
|
+
const messages = [];
|
|
543
|
+
for (let j = 0; j < ids.length; j++) {
|
|
544
|
+
const previous = cached.get(ids[j]), message = rows[j]?.value;
|
|
545
|
+
if (message && (message.payload !== null || typeof message.readingControl !== "boolean"))
|
|
546
|
+
return undefined;
|
|
547
|
+
if (JSON.stringify(previous) !== JSON.stringify(message))
|
|
548
|
+
return undefined;
|
|
549
|
+
if (message)
|
|
550
|
+
messages.push(previous);
|
|
551
|
+
}
|
|
552
|
+
partialThreads.push({ ...source.cached, messages, readThroughSeq: position.readThroughSeq, messageThreadReadThrough: position.messageThreadReadThrough, explicitReadMessageIds: position.explicitReadMessageIds });
|
|
553
|
+
}
|
|
554
|
+
const partial = { schemaVersion: 1, appId, profileId, syncCursor: header.syncCursor, pending: header.pending, observedReadIntents: header.observedReadIntents, threads: partialThreads };
|
|
555
|
+
const result = transform(partial, (await this.versions.get(key))?.teams ?? {});
|
|
556
|
+
if (result.appId !== appId || result.profileId !== profileId || result.schemaVersion !== 1)
|
|
557
|
+
throw new Error("READ_IDENTITY_MISMATCH");
|
|
558
|
+
if (result.syncCursor !== partial.syncCursor || result.threads.length !== partialThreads.length || result.threads.some((thread, i) => thread.id !== partialThreads[i].id || thread.kind !== partialThreads[i].kind || thread.teamId !== partialThreads[i].teamId || thread.conversationId !== partialThreads[i].conversationId || thread.messages !== partialThreads[i].messages))
|
|
559
|
+
return undefined;
|
|
560
|
+
const writes = [];
|
|
561
|
+
for (let i = 0; i < result.threads.length; i++) {
|
|
562
|
+
const thread = result.threads[i], before = positions[i];
|
|
563
|
+
if (thread.readThroughSeq !== before.readThroughSeq || JSON.stringify(thread.messageThreadReadThrough) !== JSON.stringify(before.messageThreadReadThrough) || JSON.stringify(thread.explicitReadMessageIds) !== JSON.stringify(before.explicitReadMessageIds))
|
|
564
|
+
writes.push({ owner, id: thread.id, readThroughSeq: thread.readThroughSeq, messageThreadReadThrough: thread.messageThreadReadThrough, explicitReadMessageIds: thread.explicitReadMessageIds });
|
|
565
|
+
}
|
|
566
|
+
if (writes.length > 126)
|
|
567
|
+
return undefined;
|
|
568
|
+
if (writes.length)
|
|
569
|
+
await this.positionRows.bulkPut(writes);
|
|
570
|
+
if (JSON.stringify(header.pending) !== JSON.stringify(result.pending) || JSON.stringify(header.observedReadIntents) !== JSON.stringify(result.observedReadIntents))
|
|
571
|
+
await this.profiles.put({ ...header, pending: result.pending, observedReadIntents: result.observedReadIntents }, key);
|
|
572
|
+
const byId = new Map(positionById);
|
|
573
|
+
result.threads.forEach(thread => byId.set(thread.id, thread));
|
|
574
|
+
let changed = false;
|
|
575
|
+
const threads = base.threads.map(thread => {
|
|
576
|
+
const position = byId.get(thread.id);
|
|
577
|
+
if (!position || thread.readThroughSeq === position.readThroughSeq && JSON.stringify(thread.messageThreadReadThrough) === JSON.stringify(position.messageThreadReadThrough) && JSON.stringify(thread.explicitReadMessageIds) === JSON.stringify(position.explicitReadMessageIds))
|
|
578
|
+
return thread;
|
|
579
|
+
changed = true;
|
|
580
|
+
return { ...thread, readThroughSeq: position.readThroughSeq, messageThreadReadThrough: position.messageThreadReadThrough, explicitReadMessageIds: position.explicitReadMessageIds };
|
|
581
|
+
});
|
|
582
|
+
if (!changed && JSON.stringify(base.pending) === JSON.stringify(result.pending) && JSON.stringify(base.observedReadIntents) === JSON.stringify(result.observedReadIntents))
|
|
583
|
+
return base;
|
|
584
|
+
return { ...base, threads, pending: result.pending, observedReadIntents: result.observedReadIntents };
|
|
585
|
+
}
|
|
586
|
+
async update(appId, profileId, transform, observation) {
|
|
587
|
+
return this.owned(appId, profileId, () => this.updateOwned(appId, profileId, transform, observation));
|
|
588
|
+
}
|
|
589
|
+
async updateOwned(appId, profileId, transform, observation, versions) {
|
|
590
|
+
if (observation) {
|
|
591
|
+
const observed = await this.transaction("rw", () => this.observe(appId, profileId, transform, observation));
|
|
592
|
+
if (observed)
|
|
593
|
+
return observed;
|
|
594
|
+
}
|
|
595
|
+
if (this.storageScope === undefined && (await this.profiles.get([appId, profileId, "legacy-owner-v1"]))?.legacyOwner)
|
|
596
|
+
throw new Error("READ_LEGACY_OWNERSHIP_CHANGED");
|
|
597
|
+
const loaded = { previous: await this.loadCurrent(appId, profileId), versions: await this.transaction("r", async () => (await this.versions.get(this.key(appId, profileId)))?.teams ?? {}) };
|
|
598
|
+
const previous = loaded.previous, transformed = transform(previous ?? createReadIndex(appId, profileId), loaded.versions);
|
|
599
|
+
const next = this.metadataOnly ? readingMetadata(transformed) : transformed;
|
|
600
|
+
if (next.appId !== appId || next.profileId !== profileId || next.schemaVersion !== 1)
|
|
601
|
+
throw new Error("READ_IDENTITY_MISMATCH");
|
|
602
|
+
if (next === previous && !versions)
|
|
603
|
+
return next;
|
|
604
|
+
await this.writeState(appId, profileId, previous, next, versions);
|
|
605
|
+
return next;
|
|
606
|
+
}
|
|
607
|
+
async writeState(appId, profileId, previous, next, versions) {
|
|
608
|
+
const owner = JSON.stringify(this.key(appId, profileId)), header = { ...next, threads: [], normalized: true, threadOrder: next.threads.map(thread => thread.id) };
|
|
609
|
+
if (!previous || !this.orderedStates.has(previous))
|
|
610
|
+
await this.cleanUnreachable(owner, previous);
|
|
611
|
+
await this.journal.commit(owner, this.changes(owner, previous, next), { profileKey: this.key(appId, profileId), header, versions });
|
|
612
|
+
this.normalizedStates.add(next);
|
|
613
|
+
this.orderedStates.add(next);
|
|
614
|
+
}
|
|
615
|
+
async cleanUnreachable(owner, previous) {
|
|
616
|
+
const threads = new Map(previous?.threads.map(thread => [thread.id, new Set(thread.messages.map(message => message.id))]) ?? []);
|
|
617
|
+
for (const name of ["readingThreads", "readingPositions", "readingMessages"]) {
|
|
618
|
+
const table = this.database.table(name);
|
|
619
|
+
let after;
|
|
620
|
+
for (;;) {
|
|
621
|
+
const keys = await table.where(":id").between(after ?? [owner, Dexie.minKey], [owner, Dexie.maxKey], !after, true).limit(126).primaryKeys();
|
|
622
|
+
if (!keys.length)
|
|
623
|
+
break;
|
|
624
|
+
const dead = keys.filter(key => !threads.has(key[1]) || name === "readingMessages" && !threads.get(key[1]).has(key[2]));
|
|
625
|
+
if (dead.length)
|
|
626
|
+
await this.transaction("rw", () => table.bulkDelete(dead));
|
|
627
|
+
after = keys[keys.length - 1];
|
|
628
|
+
if (keys.length < 126)
|
|
629
|
+
break;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
*changes(owner, previous, next) {
|
|
634
|
+
const oldThreads = new Map(previous?.threads.map(thread => [thread.id, thread]) ?? []), ids = new Set(), modern = previous !== undefined && this.orderedStates.has(previous);
|
|
635
|
+
for (const thread of next.threads) {
|
|
636
|
+
if (ids.has(thread.id))
|
|
637
|
+
throw new Error("DUPLICATE_READ_THREAD");
|
|
638
|
+
ids.add(thread.id);
|
|
639
|
+
const old = oldThreads.get(thread.id);
|
|
640
|
+
if (old === thread && modern)
|
|
641
|
+
continue;
|
|
642
|
+
const { messages, readThroughSeq, messageThreadReadThrough, explicitReadMessageIds, ...value } = thread;
|
|
643
|
+
if (!modern || !old || old.readThroughSeq !== readThroughSeq || JSON.stringify(old.messageThreadReadThrough) !== JSON.stringify(messageThreadReadThrough) || JSON.stringify(old.explicitReadMessageIds) !== JSON.stringify(explicitReadMessageIds))
|
|
644
|
+
yield { table: "readingPositions", key: [owner, thread.id], value: { owner, id: thread.id, readThroughSeq, messageThreadReadThrough, explicitReadMessageIds } };
|
|
645
|
+
const metadata = { owner, id: thread.id, value, messageIds: [], messageCount: messages.length };
|
|
646
|
+
const oldMetadata = old ? { owner, id: old.id, value: (({ messages: _m, readThroughSeq: _r, messageThreadReadThrough: _mt, explicitReadMessageIds: _e, ...rest }) => rest)(old), messageIds: modern ? [] : old.messages.map(message => message.id), ...(modern ? { messageCount: old.messages.length } : {}) } : undefined;
|
|
647
|
+
if (JSON.stringify(metadata) !== JSON.stringify(oldMetadata))
|
|
648
|
+
yield { table: "readingThreads", key: [owner, thread.id], value: metadata };
|
|
649
|
+
if (old?.messages === messages && modern)
|
|
650
|
+
continue;
|
|
651
|
+
const byId = new Map(old?.messages.map(message => [message.id, message]) ?? []), ranks = new Map(old?.messages.map((message, index) => [message.id, index]) ?? []), seen = new Set();
|
|
652
|
+
for (const [ordinal, message] of messages.entries()) {
|
|
653
|
+
if (seen.has(message.id))
|
|
654
|
+
throw new Error("INVALID_READ_MESSAGE");
|
|
655
|
+
seen.add(message.id);
|
|
656
|
+
const prior = byId.get(message.id);
|
|
657
|
+
if (!modern || ranks.get(message.id) !== ordinal || prior !== message && JSON.stringify(prior) !== JSON.stringify(message))
|
|
658
|
+
yield { table: "readingMessages", key: [owner, thread.id, message.id], value: { owner, thread: thread.id, id: message.id, value: message, ordinal } };
|
|
659
|
+
}
|
|
660
|
+
for (const id of byId.keys())
|
|
661
|
+
if (!seen.has(id))
|
|
662
|
+
yield { table: "readingMessages", key: [owner, thread.id, id] };
|
|
663
|
+
}
|
|
664
|
+
for (const old of oldThreads.values())
|
|
665
|
+
if (!ids.has(old.id)) {
|
|
666
|
+
yield { table: "readingThreads", key: [owner, old.id] };
|
|
667
|
+
yield { table: "readingPositions", key: [owner, old.id] };
|
|
668
|
+
for (const message of old.messages)
|
|
669
|
+
yield { table: "readingMessages", key: [owner, old.id, message.id] };
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
async close() { this.closed = true; try {
|
|
673
|
+
await this.journal.releaseLeases();
|
|
674
|
+
}
|
|
675
|
+
finally {
|
|
676
|
+
this.database.close();
|
|
677
|
+
} }
|
|
223
678
|
}
|
|
224
679
|
export function sourcesInConversation(state, conversationId) {
|
|
225
680
|
return state.threads.filter(thread => (thread.conversationId ?? thread.id) === conversationId);
|
|
@@ -231,14 +686,14 @@ function readSource(state, conversationId, messageId) {
|
|
|
231
686
|
return sources[0];
|
|
232
687
|
}
|
|
233
688
|
/** Aggregate logical history while each original source retains its own read cursor. */
|
|
234
|
-
export function unreadInConversation(state, conversationId) {
|
|
689
|
+
export function unreadInConversation(state, conversationId, hidden, threadRootId) {
|
|
235
690
|
const sources = sourcesInConversation(state, conversationId);
|
|
236
691
|
if (!sources.length)
|
|
237
692
|
throw new Error("UNKNOWN_READ_CONVERSATION");
|
|
238
693
|
if (new Set(sources.map(source => source.teamId)).size > 1)
|
|
239
694
|
throw new Error("READ_CONVERSATION_TEAM_MISMATCH");
|
|
240
695
|
return sources.reduce((total, source) => {
|
|
241
|
-
const unread = unreadInThread(state, source.id);
|
|
696
|
+
const unread = unreadInThread(state, source.id, hidden, threadRootId);
|
|
242
697
|
return { unreadMessageCount: total.unreadMessageCount + unread.unreadMessageCount, unreadMentionCount: total.unreadMentionCount + unread.unreadMentionCount, badgeCount: total.badgeCount + unread.badgeCount };
|
|
243
698
|
}, { unreadMessageCount: 0, unreadMentionCount: 0, badgeCount: 0 });
|
|
244
699
|
}
|