@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
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { IndexedDbInbox, inboxSequence } from "./inboxStore.js";
|
|
2
|
+
import { isOffline } from "./connectivity.js";
|
|
3
|
+
/** Push full facts normally; range catch-up repairs gaps and silent push loss.
|
|
4
|
+
* One persisted lease owns live/check traffic across tabs and team sessions. */
|
|
5
|
+
export class InboxClient {
|
|
6
|
+
options;
|
|
7
|
+
store;
|
|
8
|
+
closed = false;
|
|
9
|
+
controller = new AbortController();
|
|
10
|
+
streamController;
|
|
11
|
+
timer;
|
|
12
|
+
running;
|
|
13
|
+
liveTask;
|
|
14
|
+
reconnectTimer;
|
|
15
|
+
token = crypto.randomUUID();
|
|
16
|
+
channel;
|
|
17
|
+
listeners = new Set();
|
|
18
|
+
progressListeners = new Set();
|
|
19
|
+
progress = { stage: "loading", percent: 0, processed: "0", total: "0" };
|
|
20
|
+
wake;
|
|
21
|
+
starting;
|
|
22
|
+
offlineAllowed = false;
|
|
23
|
+
enterOffline = () => { };
|
|
24
|
+
offlineEntry = new Promise(resolve => { this.enterOffline = resolve; });
|
|
25
|
+
initializedOnce = false;
|
|
26
|
+
eventListeners = new Set();
|
|
27
|
+
constructor(options) {
|
|
28
|
+
this.options = options;
|
|
29
|
+
this.store = options.store ?? new IndexedDbInbox(options);
|
|
30
|
+
if (typeof BroadcastChannel !== "undefined" && typeof window !== "undefined") {
|
|
31
|
+
this.channel = new BroadcastChannel(`pmate-inbox:${this.store.owner}`);
|
|
32
|
+
this.channel.onmessage = event => { if (Array.isArray(event.data?.threads))
|
|
33
|
+
this.notify(event.data.threads, false); if (this.initializedOnce && Array.isArray(event.data?.events))
|
|
34
|
+
this.eventListeners.forEach(listener => listener(event.data.events)); };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
snapshot = () => this.progress;
|
|
38
|
+
subscribeProgress = (listener) => { this.progressListeners.add(listener); return () => { this.progressListeners.delete(listener); }; };
|
|
39
|
+
subscribeEvents(listener) { this.eventListeners.add(listener); return () => { this.eventListeners.delete(listener); }; }
|
|
40
|
+
facts(events, after) { if (this.initializedOnce) {
|
|
41
|
+
const fresh = events.filter(event => inboxSequence(event.inboxSeq) > inboxSequence(after));
|
|
42
|
+
if (fresh.length) {
|
|
43
|
+
this.eventListeners.forEach(listener => listener(fresh));
|
|
44
|
+
this.channel?.postMessage({ events: fresh });
|
|
45
|
+
}
|
|
46
|
+
} }
|
|
47
|
+
subscribe(listener) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
|
|
48
|
+
publish(progress) { if (this.closed)
|
|
49
|
+
return; if (progress.stage === "syncing" && this.progress.stage === "syncing")
|
|
50
|
+
progress = { ...progress, percent: Math.max(progress.percent, this.progress.percent) }; this.progress = progress; this.options.onProgress?.(progress); this.progressListeners.forEach(listener => listener()); }
|
|
51
|
+
notify(threads, broadcast = true) { if (this.closed)
|
|
52
|
+
return; this.options.onChange?.(threads); this.listeners.forEach(listener => listener(threads)); if (broadcast)
|
|
53
|
+
this.channel?.postMessage({ threads }); }
|
|
54
|
+
async credentials() { const token = await this.options.getToken?.() ?? this.options.sessionToken; if (!token)
|
|
55
|
+
throw new Error("INBOX_CREDENTIALS_UNAVAILABLE"); return token; }
|
|
56
|
+
async request(action, params = {}, signal) {
|
|
57
|
+
const query = new URLSearchParams({ appId: this.options.appId, profileId: this.options.profileId, ...params });
|
|
58
|
+
const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}/api/social/inbox/${action}?${query}`, { headers: { authorization: `Bearer ${await this.credentials()}` }, cache: "no-store", redirect: "error", signal: AbortSignal.any([this.controller.signal, ...(signal ? [signal] : []), AbortSignal.timeout(20000)]) });
|
|
59
|
+
const result = await response.json();
|
|
60
|
+
if (!response.ok || result.success !== true || result.data === undefined)
|
|
61
|
+
throw Object.assign(new Error(`INBOX_HTTP_${response.status}`), { status: response.status });
|
|
62
|
+
return result.data;
|
|
63
|
+
}
|
|
64
|
+
start() { return this.starting ??= Promise.race([this.initialize(), this.offlineEntry]).catch(error => { this.starting = undefined; throw error; }); }
|
|
65
|
+
readyForDisplay() { return this.initializedOnce || this.offlineAllowed; }
|
|
66
|
+
offlineMode() { return this.offlineAllowed && this.progress.stage !== "ready"; }
|
|
67
|
+
async allowOffline() {
|
|
68
|
+
const cursor = await this.store.cursor();
|
|
69
|
+
if (!cursor?.initialized)
|
|
70
|
+
throw new Error("INBOX_OFFLINE_CACHE_UNAVAILABLE");
|
|
71
|
+
this.offlineAllowed = true;
|
|
72
|
+
this.enterOffline();
|
|
73
|
+
this.publish({ ...this.progress, stage: "offline", percent: 100 });
|
|
74
|
+
}
|
|
75
|
+
async initialize() {
|
|
76
|
+
if (this.options.live === false) {
|
|
77
|
+
if (!this.offlineAllowed)
|
|
78
|
+
await this.synchronize();
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (this.closed)
|
|
82
|
+
throw new Error("INBOX_CLIENT_CLOSED");
|
|
83
|
+
if (!this.timer)
|
|
84
|
+
this.timer = setInterval(() => { void this.tick().catch(error => this.failed(error)); }, 10000);
|
|
85
|
+
if (typeof window !== "undefined" && !this.wake) {
|
|
86
|
+
this.wake = () => {
|
|
87
|
+
if (typeof document !== "undefined" && document.hidden) {
|
|
88
|
+
this.streamController?.abort();
|
|
89
|
+
void this.store.releaseLease(this.token);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
void this.tick().catch(error => this.failed(error));
|
|
93
|
+
};
|
|
94
|
+
for (const event of ["online", "focus", "pageshow"])
|
|
95
|
+
window.addEventListener(event, this.wake);
|
|
96
|
+
if (typeof document !== "undefined")
|
|
97
|
+
document.addEventListener("visibilitychange", this.wake);
|
|
98
|
+
}
|
|
99
|
+
if (this.offlineAllowed && (await this.store.cursor())?.initialized)
|
|
100
|
+
return;
|
|
101
|
+
await this.synchronize();
|
|
102
|
+
await this.tick(false);
|
|
103
|
+
}
|
|
104
|
+
synchronize() {
|
|
105
|
+
if (this.closed)
|
|
106
|
+
return Promise.reject(new Error("INBOX_CLIENT_CLOSED"));
|
|
107
|
+
return this.running ??= this.catchUp().catch(error => { this.failed(error); throw error; }).finally(() => { this.running = undefined; });
|
|
108
|
+
}
|
|
109
|
+
async catchUp() {
|
|
110
|
+
if (isOffline())
|
|
111
|
+
throw new Error("INBOX_OFFLINE");
|
|
112
|
+
const wasReady = this.progress.stage === "ready";
|
|
113
|
+
let cursor = await this.store.cursor(), initial;
|
|
114
|
+
if (cursor)
|
|
115
|
+
initial = await this.request("check", { afterSeq: cursor.seq, epoch: cursor.epoch });
|
|
116
|
+
if (!cursor || initial?.resetRequired) {
|
|
117
|
+
const bootstrap = await this.request("bootstrap");
|
|
118
|
+
cursor = await this.store.bootstrap(bootstrap);
|
|
119
|
+
this.notify([]);
|
|
120
|
+
initial = undefined;
|
|
121
|
+
const target = inboxSequence(bootstrap.headSeq), start = inboxSequence(cursor.seq);
|
|
122
|
+
this.publish({ stage: "syncing", percent: 0, processed: "0", total: (target - start).toString() });
|
|
123
|
+
do {
|
|
124
|
+
const page = await this.request("events", { afterSeq: cursor.seq, throughSeq: target.toString(), epoch: cursor.epoch });
|
|
125
|
+
const previous = cursor.seq, applied = await this.store.apply(page);
|
|
126
|
+
cursor = applied.cursor;
|
|
127
|
+
if (cursor.seq !== previous)
|
|
128
|
+
this.notify(applied.threads);
|
|
129
|
+
this.facts(page.events, previous);
|
|
130
|
+
const processed = inboxSequence(cursor.seq) - start, total = target - start;
|
|
131
|
+
this.publish({ stage: "syncing", percent: total === 0n ? 99 : Number(processed * 9900n / total) / 100, processed: processed.toString(), total: total.toString() });
|
|
132
|
+
} while (inboxSequence(cursor.seq) < target);
|
|
133
|
+
// Capture one more committed head after the fixed initial target, then
|
|
134
|
+
// connect the live stream from the durable cursor so startup has no gap.
|
|
135
|
+
initial = await this.request("check", { afterSeq: cursor.seq, epoch: cursor.epoch });
|
|
136
|
+
}
|
|
137
|
+
const start = inboxSequence(cursor.seq), target = inboxSequence(initial.headSeq);
|
|
138
|
+
let page = initial;
|
|
139
|
+
do {
|
|
140
|
+
const previous = cursor.seq, applied = await this.store.apply(page);
|
|
141
|
+
cursor = applied.cursor;
|
|
142
|
+
if (cursor.seq !== previous)
|
|
143
|
+
this.notify(applied.threads);
|
|
144
|
+
this.facts(page.events, previous);
|
|
145
|
+
const processed = inboxSequence(cursor.seq) - start, total = target - start;
|
|
146
|
+
if (total > 0n || !wasReady)
|
|
147
|
+
this.publish({ stage: "syncing", percent: total === 0n ? 99 : Number(processed * 9900n / total) / 100, processed: processed.toString(), total: total.toString() });
|
|
148
|
+
if (inboxSequence(cursor.seq) >= target)
|
|
149
|
+
break;
|
|
150
|
+
page = await this.request("events", { afterSeq: cursor.seq, throughSeq: target.toString(), epoch: cursor.epoch });
|
|
151
|
+
} while (!this.closed);
|
|
152
|
+
if (!this.closed && (!wasReady || target > start)) {
|
|
153
|
+
this.initializedOnce = true;
|
|
154
|
+
this.publish({ stage: "ready", percent: 100, processed: (target - start).toString(), total: (target - start).toString() });
|
|
155
|
+
this.notify([]);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async tick(check = true) {
|
|
159
|
+
if (this.closed || isOffline() || typeof document !== "undefined" && document.hidden)
|
|
160
|
+
return;
|
|
161
|
+
if (!await this.store.claimLease(this.token)) {
|
|
162
|
+
this.streamController?.abort();
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (check)
|
|
166
|
+
await this.synchronize();
|
|
167
|
+
if (!this.liveTask) {
|
|
168
|
+
let failed = false;
|
|
169
|
+
const task = this.listen().catch(error => { failed = true; if (!this.closed && error?.name !== "AbortError")
|
|
170
|
+
this.failed(error); }).finally(() => {
|
|
171
|
+
if (this.liveTask === task)
|
|
172
|
+
this.liveTask = undefined;
|
|
173
|
+
if (!this.closed)
|
|
174
|
+
this.reconnectTimer = setTimeout(() => { void this.tick(false).catch(error => this.failed(error)); }, failed ? 1000 : 0);
|
|
175
|
+
});
|
|
176
|
+
this.liveTask = task;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async listen() {
|
|
180
|
+
const cursor = await this.store.cursor();
|
|
181
|
+
if (!cursor || this.closed)
|
|
182
|
+
return;
|
|
183
|
+
const query = new URLSearchParams({ appId: this.options.appId, profileId: this.options.profileId, afterSeq: cursor.seq, epoch: cursor.epoch });
|
|
184
|
+
const controller = this.streamController = new AbortController();
|
|
185
|
+
const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}/api/social/inbox/live?${query}`, { headers: { authorization: `Bearer ${await this.credentials()}` }, cache: "no-store", redirect: "error", signal: AbortSignal.any([this.controller.signal, controller.signal]) });
|
|
186
|
+
if (!response.ok || !response.body)
|
|
187
|
+
throw Object.assign(new Error(`INBOX_LIVE_HTTP_${response.status}`), { status: response.status });
|
|
188
|
+
const reader = response.body.getReader(), decoder = new TextDecoder();
|
|
189
|
+
let buffer = "";
|
|
190
|
+
try {
|
|
191
|
+
for (;;) {
|
|
192
|
+
const part = await reader.read();
|
|
193
|
+
if (part.done)
|
|
194
|
+
break;
|
|
195
|
+
buffer += decoder.decode(part.value, { stream: true });
|
|
196
|
+
buffer = buffer.replace(/\r\n/g, "\n");
|
|
197
|
+
if (buffer.length > 16 * 1024 * 1024)
|
|
198
|
+
throw new Error("INBOX_LIVE_TOO_LARGE");
|
|
199
|
+
let boundary;
|
|
200
|
+
while ((boundary = buffer.indexOf("\n\n")) >= 0) {
|
|
201
|
+
const frame = buffer.slice(0, boundary);
|
|
202
|
+
buffer = buffer.slice(boundary + 2);
|
|
203
|
+
const type = frame.split("\n").find(line => line.startsWith("event:"))?.slice(6).trim();
|
|
204
|
+
const data = frame.split("\n").filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
|
|
205
|
+
if (type === "error")
|
|
206
|
+
throw new Error("INBOX_LIVE_UNAVAILABLE");
|
|
207
|
+
if (type !== "inbox" || !data)
|
|
208
|
+
continue;
|
|
209
|
+
const page = JSON.parse(data);
|
|
210
|
+
if (page.resetRequired) {
|
|
211
|
+
await this.synchronize();
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
const previous = (await this.store.cursor())?.seq ?? "0", applied = await this.store.apply(page);
|
|
216
|
+
if (applied.threads.length)
|
|
217
|
+
if (cursor.seq !== previous)
|
|
218
|
+
this.notify(applied.threads);
|
|
219
|
+
this.facts(page.events, previous);
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
if (String(error).includes("INBOX_SEQUENCE_GAP")) {
|
|
223
|
+
await this.synchronize();
|
|
224
|
+
}
|
|
225
|
+
else
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
finally {
|
|
232
|
+
await reader.cancel().catch(() => { });
|
|
233
|
+
reader.releaseLock();
|
|
234
|
+
if (this.streamController === controller)
|
|
235
|
+
this.streamController = undefined;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
failed(error) {
|
|
239
|
+
if (this.closed)
|
|
240
|
+
return;
|
|
241
|
+
this.publish({ ...this.progress, stage: isOffline() ? "offline" : "error", error });
|
|
242
|
+
if (!isOffline())
|
|
243
|
+
this.options.onError?.(error);
|
|
244
|
+
}
|
|
245
|
+
async close() {
|
|
246
|
+
if (this.closed)
|
|
247
|
+
return;
|
|
248
|
+
this.closed = true;
|
|
249
|
+
this.controller.abort();
|
|
250
|
+
this.streamController?.abort();
|
|
251
|
+
clearInterval(this.timer);
|
|
252
|
+
clearTimeout(this.reconnectTimer);
|
|
253
|
+
if (this.wake && typeof window !== "undefined") {
|
|
254
|
+
for (const event of ["online", "focus", "pageshow"])
|
|
255
|
+
window.removeEventListener(event, this.wake);
|
|
256
|
+
if (typeof document !== "undefined")
|
|
257
|
+
document.removeEventListener("visibilitychange", this.wake);
|
|
258
|
+
}
|
|
259
|
+
await Promise.allSettled([this.running, this.liveTask]);
|
|
260
|
+
await this.store.releaseLease(this.token);
|
|
261
|
+
this.channel?.close();
|
|
262
|
+
this.eventListeners.clear();
|
|
263
|
+
this.listeners.clear();
|
|
264
|
+
this.progressListeners.clear();
|
|
265
|
+
if (!this.options.store)
|
|
266
|
+
this.store.close();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { SocialGroup } from "./socialReadClient.js";
|
|
2
|
+
/** Replay structural source facts using the same causal revisions as the Hub.
|
|
3
|
+
* Message order or a late control cannot independently dissolve a group. */
|
|
4
|
+
export declare function projectInboxGroup(appId: string, groupId: string, teamId: string | undefined, events: readonly Record<string, any>[]): SocialGroup | undefined;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** Replay structural source facts using the same causal revisions as the Hub.
|
|
2
|
+
* Message order or a late control cannot independently dissolve a group. */
|
|
3
|
+
export function projectInboxGroup(appId, groupId, teamId, events) {
|
|
4
|
+
const controls = events.filter(event => event.appId === appId && event.to === groupId && event.teamId === teamId && event.threadKind === "group" && event.body?.kind === "group");
|
|
5
|
+
const creates = controls.filter(event => event.body.action === "groupCreate");
|
|
6
|
+
if (creates.length !== 1)
|
|
7
|
+
return;
|
|
8
|
+
const creation = creates[0], owner = creation.from;
|
|
9
|
+
const members = (value) => Array.isArray(value) && value.length <= 256 && value.every(id => typeof id === "string" && id.length > 0 && id.length <= 256) ? [...new Set(value)] : undefined;
|
|
10
|
+
const initial = members(creation.body.payload?.members);
|
|
11
|
+
if (!owner || !creation.messageId || !initial)
|
|
12
|
+
return;
|
|
13
|
+
const initialMembers = [...new Set([...initial, owner])];
|
|
14
|
+
if (initialMembers.length > 256)
|
|
15
|
+
return;
|
|
16
|
+
let group = { appId, groupId, teamId, ownerId: owner, members: initialMembers, title: typeof creation.body.payload.title === "string" ? creation.body.payload.title : "", avatar: typeof creation.body.payload.avatar === "string" ? creation.body.payload.avatar : null, revision: creation.messageId, versionNumber: 1, status: "active" };
|
|
17
|
+
const updates = new Map();
|
|
18
|
+
for (const event of controls)
|
|
19
|
+
if (["groupUpdate", "groupDissolve"].includes(event.body.action) && typeof event.body.payload?.previousRevision === "string") {
|
|
20
|
+
const key = event.body.payload.previousRevision;
|
|
21
|
+
updates.set(key, [...(updates.get(key) ?? []), event]);
|
|
22
|
+
}
|
|
23
|
+
const seen = new Set();
|
|
24
|
+
for (;;) {
|
|
25
|
+
if (seen.has(group.revision))
|
|
26
|
+
return;
|
|
27
|
+
seen.add(group.revision);
|
|
28
|
+
const next = updates.get(group.revision);
|
|
29
|
+
if (!next)
|
|
30
|
+
return group;
|
|
31
|
+
if (next.length !== 1 || group.status === "dissolved")
|
|
32
|
+
return;
|
|
33
|
+
const event = next[0], payload = event.body.payload, actor = event.from;
|
|
34
|
+
if (!actor || !event.messageId)
|
|
35
|
+
return;
|
|
36
|
+
if (event.body.action === "groupDissolve") {
|
|
37
|
+
if (actor !== owner)
|
|
38
|
+
return;
|
|
39
|
+
group = { ...group, revision: event.messageId, versionNumber: group.versionNumber + 1, status: "dissolved", dissolvedBy: actor, dissolvedAt: event.serverCreatedAt };
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
const ids = members(payload.members);
|
|
43
|
+
if (!ids || !ids.includes(owner) || !group.members?.includes(actor))
|
|
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))
|
|
46
|
+
return;
|
|
47
|
+
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 } : {}) };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { Dexie, type Table } from "dexie";
|
|
2
|
+
import { type ReadSnapshot } from "./readIndex.js";
|
|
3
|
+
import type { MessageThreadSummary } from "./socialReadClient.js";
|
|
4
|
+
import type { ChatReaderSocialMessage } from "./readerClient.js";
|
|
5
|
+
export type InboxScope = {
|
|
6
|
+
appId: string;
|
|
7
|
+
accountId: string;
|
|
8
|
+
profileId: string;
|
|
9
|
+
};
|
|
10
|
+
export type InboxEvent = {
|
|
11
|
+
inboxSeq: string;
|
|
12
|
+
sourceId: string;
|
|
13
|
+
acceptedAt: number;
|
|
14
|
+
kind: string;
|
|
15
|
+
fact: Record<string, any>;
|
|
16
|
+
};
|
|
17
|
+
export type InboxPage = {
|
|
18
|
+
epoch: string;
|
|
19
|
+
appId: string;
|
|
20
|
+
profileId: string;
|
|
21
|
+
startSeq: string;
|
|
22
|
+
nextSeq: string;
|
|
23
|
+
headSeq: string;
|
|
24
|
+
hasMore: boolean;
|
|
25
|
+
resetRequired: boolean;
|
|
26
|
+
events: InboxEvent[];
|
|
27
|
+
};
|
|
28
|
+
export type InboxBootstrap = {
|
|
29
|
+
epoch: string;
|
|
30
|
+
appId: string;
|
|
31
|
+
profileId: string;
|
|
32
|
+
startSeq: string;
|
|
33
|
+
headSeq: string;
|
|
34
|
+
windowStart: number;
|
|
35
|
+
basis: {
|
|
36
|
+
id: string;
|
|
37
|
+
kind: string;
|
|
38
|
+
fact: Record<string, any>;
|
|
39
|
+
inboxSeq: string;
|
|
40
|
+
}[];
|
|
41
|
+
};
|
|
42
|
+
export type InboxCursor = {
|
|
43
|
+
owner: string;
|
|
44
|
+
epoch: string;
|
|
45
|
+
seq: string;
|
|
46
|
+
windowStart: number;
|
|
47
|
+
initialized: boolean;
|
|
48
|
+
};
|
|
49
|
+
type InboxLease = {
|
|
50
|
+
owner: string;
|
|
51
|
+
token: string;
|
|
52
|
+
expiresAt: number;
|
|
53
|
+
};
|
|
54
|
+
export type InboxMessage = ChatReaderSocialMessage & {
|
|
55
|
+
seq: number;
|
|
56
|
+
recalled?: boolean;
|
|
57
|
+
};
|
|
58
|
+
type MessageRow = {
|
|
59
|
+
owner: string;
|
|
60
|
+
thread: string;
|
|
61
|
+
id: string;
|
|
62
|
+
acceptedAt: number;
|
|
63
|
+
time: number;
|
|
64
|
+
seq: number;
|
|
65
|
+
changeSeq: string;
|
|
66
|
+
root: string;
|
|
67
|
+
recalled: boolean;
|
|
68
|
+
value: InboxMessage;
|
|
69
|
+
};
|
|
70
|
+
type FactRow = {
|
|
71
|
+
owner: string;
|
|
72
|
+
kind: string;
|
|
73
|
+
id: string;
|
|
74
|
+
thread: string;
|
|
75
|
+
value: Record<string, any>;
|
|
76
|
+
};
|
|
77
|
+
type PositionRow = {
|
|
78
|
+
owner: string;
|
|
79
|
+
thread: string;
|
|
80
|
+
root: string;
|
|
81
|
+
seq: number;
|
|
82
|
+
messageId?: string;
|
|
83
|
+
};
|
|
84
|
+
type ExplicitRow = {
|
|
85
|
+
owner: string;
|
|
86
|
+
thread: string;
|
|
87
|
+
id: string;
|
|
88
|
+
preserved?: boolean;
|
|
89
|
+
};
|
|
90
|
+
type ThreadRow = {
|
|
91
|
+
owner: string;
|
|
92
|
+
id: string;
|
|
93
|
+
kind: "dm" | "group";
|
|
94
|
+
teamId?: string;
|
|
95
|
+
targetId: string;
|
|
96
|
+
};
|
|
97
|
+
export declare function inboxSequence(value: string): bigint;
|
|
98
|
+
/** Normalized facts and derived positions commit with their Inbox cursor. No
|
|
99
|
+
* serialized full-history snapshot is persisted after each message. */
|
|
100
|
+
export declare class IndexedDbInbox {
|
|
101
|
+
readonly scope: InboxScope;
|
|
102
|
+
readonly db: Dexie;
|
|
103
|
+
readonly owner: string;
|
|
104
|
+
readonly cursors: Table<InboxCursor, string>;
|
|
105
|
+
readonly messages: Table<MessageRow, [string, string, string]>;
|
|
106
|
+
readonly facts: Table<FactRow, [string, string, string]>;
|
|
107
|
+
readonly positions: Table<PositionRow, [string, string, string]>;
|
|
108
|
+
readonly explicit: Table<ExplicitRow, [string, string, string]>;
|
|
109
|
+
readonly threads: Table<ThreadRow, [string, string]>;
|
|
110
|
+
readonly leases: Table<InboxLease, string>;
|
|
111
|
+
constructor(scope: InboxScope, options?: {
|
|
112
|
+
indexedDB?: IDBFactory;
|
|
113
|
+
name?: string;
|
|
114
|
+
});
|
|
115
|
+
private tables;
|
|
116
|
+
cursor(): import("dexie").PromiseExtended<InboxCursor | undefined>;
|
|
117
|
+
claimLease(token: string, now?: number): import("dexie").PromiseExtended<boolean>;
|
|
118
|
+
releaseLease(token: string): import("dexie").PromiseExtended<void>;
|
|
119
|
+
private identity;
|
|
120
|
+
bootstrap(input: InboxBootstrap): Promise<InboxCursor>;
|
|
121
|
+
apply(page: InboxPage): Promise<{
|
|
122
|
+
cursor: {
|
|
123
|
+
seq: string;
|
|
124
|
+
initialized: boolean;
|
|
125
|
+
owner: string;
|
|
126
|
+
epoch: string;
|
|
127
|
+
windowStart: number;
|
|
128
|
+
};
|
|
129
|
+
threads: string[];
|
|
130
|
+
}>;
|
|
131
|
+
private applyFact;
|
|
132
|
+
readingSnapshot(): Promise<ReadSnapshot>;
|
|
133
|
+
threadMessages(thread: string): Promise<{
|
|
134
|
+
recalled: boolean;
|
|
135
|
+
body: any;
|
|
136
|
+
teamId?: string;
|
|
137
|
+
sourceThreadId?: string;
|
|
138
|
+
appId: string;
|
|
139
|
+
threadId: string;
|
|
140
|
+
threadKind: "dm" | "group";
|
|
141
|
+
messageId: string;
|
|
142
|
+
from: string;
|
|
143
|
+
to: string;
|
|
144
|
+
recipients?: string[];
|
|
145
|
+
clientCreatedAt?: number;
|
|
146
|
+
serverCreatedAt: number;
|
|
147
|
+
seq: number;
|
|
148
|
+
}[]>;
|
|
149
|
+
conversationMessages(thread: string, teamId: string): Promise<{
|
|
150
|
+
recalled: boolean;
|
|
151
|
+
body: any;
|
|
152
|
+
teamId?: string;
|
|
153
|
+
sourceThreadId?: string;
|
|
154
|
+
appId: string;
|
|
155
|
+
threadId: string;
|
|
156
|
+
threadKind: "dm" | "group";
|
|
157
|
+
messageId: string;
|
|
158
|
+
from: string;
|
|
159
|
+
to: string;
|
|
160
|
+
recipients?: string[];
|
|
161
|
+
clientCreatedAt?: number;
|
|
162
|
+
serverCreatedAt: number;
|
|
163
|
+
seq: number;
|
|
164
|
+
}[]>;
|
|
165
|
+
conversationMessage(thread: string, teamId: string, id: string): Promise<{
|
|
166
|
+
sourceThreadId?: string;
|
|
167
|
+
threadId: string;
|
|
168
|
+
teamId?: string;
|
|
169
|
+
recalled: boolean;
|
|
170
|
+
body: any;
|
|
171
|
+
appId: string;
|
|
172
|
+
threadKind: "dm" | "group";
|
|
173
|
+
messageId: string;
|
|
174
|
+
from: string;
|
|
175
|
+
to: string;
|
|
176
|
+
recipients?: string[];
|
|
177
|
+
clientCreatedAt?: number;
|
|
178
|
+
serverCreatedAt: number;
|
|
179
|
+
seq: number;
|
|
180
|
+
} | undefined>;
|
|
181
|
+
conversationChanges(thread: string, teamId: string, afterSeq: string, afterId?: string): Promise<{
|
|
182
|
+
changeSeq: string;
|
|
183
|
+
id: string;
|
|
184
|
+
}[]>;
|
|
185
|
+
structureSequence(thread: string): Promise<bigint>;
|
|
186
|
+
discussionSummaries(thread: string, team: string, roots: readonly string[]): Promise<{
|
|
187
|
+
items: MessageThreadSummary[];
|
|
188
|
+
revision: number;
|
|
189
|
+
}>;
|
|
190
|
+
group(groupId: string, teamId: string): Promise<import("./socialReadClient.js").SocialGroup | undefined>;
|
|
191
|
+
private annotatedBody;
|
|
192
|
+
close(): void;
|
|
193
|
+
}
|
|
194
|
+
export {};
|