@pmate/chat-sdk 0.12.0-next.9 → 0.12.0-next.91

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.
Files changed (125) hide show
  1. package/README.md +216 -83
  2. package/lib/advanced.d.ts +10 -0
  3. package/lib/advanced.js +10 -0
  4. package/lib/chat.d.ts +5 -0
  5. package/lib/chat.js +11 -0
  6. package/lib/chatContract.d.ts +158 -0
  7. package/lib/chatContract.js +1 -0
  8. package/lib/chatError.d.ts +31 -0
  9. package/lib/chatError.js +18 -0
  10. package/lib/chatTypes.d.ts +128 -0
  11. package/lib/chatTypes.js +1 -0
  12. package/lib/commands.d.ts +20 -0
  13. package/lib/commands.js +12 -0
  14. package/lib/components/ChatInputDesktop.js +5 -4
  15. package/lib/components/ChatInputMobile.js +5 -4
  16. package/lib/components/CommandMenu.d.ts +15 -0
  17. package/lib/components/CommandMenu.js +10 -0
  18. package/lib/credentials.d.ts +26 -0
  19. package/lib/credentials.js +110 -0
  20. package/lib/fileMetadata.d.ts +9 -0
  21. package/lib/fileMetadata.js +18 -0
  22. package/lib/framework.d.ts +11 -0
  23. package/lib/framework.js +12 -0
  24. package/lib/history.d.ts +4 -0
  25. package/lib/history.js +8 -0
  26. package/lib/hooks/useChatSnapshot.d.ts +4 -0
  27. package/lib/hooks/useChatSnapshot.js +9 -0
  28. package/lib/hooks/useComposerSuggestions.d.ts +50 -0
  29. package/lib/hooks/useComposerSuggestions.js +70 -0
  30. package/lib/index.d.ts +6 -0
  31. package/lib/index.js +6 -0
  32. package/lib/internal/chatEngine.d.ts +131 -0
  33. package/lib/internal/chatEngine.js +306 -0
  34. package/lib/internal/chatRegistry.d.ts +4 -0
  35. package/lib/internal/chatRegistry.js +4 -0
  36. package/lib/internal/createPublicChat.d.ts +4 -0
  37. package/lib/internal/createPublicChat.js +62 -0
  38. package/lib/messageView.d.ts +6 -0
  39. package/lib/messageView.js +103 -0
  40. package/lib/runtime/batchedReadIndex.d.ts +16 -3
  41. package/lib/runtime/batchedReadIndex.js +50 -4
  42. package/lib/runtime/cachedMessage.d.ts +12 -0
  43. package/lib/runtime/cachedMessage.js +18 -0
  44. package/lib/runtime/chatClient.d.ts +8 -1
  45. package/lib/runtime/chatClient.js +18 -6
  46. package/lib/runtime/chatError.d.ts +5 -0
  47. package/lib/runtime/chatError.js +20 -0
  48. package/lib/runtime/chatSession.d.ts +141 -13
  49. package/lib/runtime/chatSession.js +797 -48
  50. package/lib/runtime/connectivity.d.ts +4 -0
  51. package/lib/runtime/connectivity.js +8 -0
  52. package/lib/runtime/conversationDirectory.d.ts +37 -0
  53. package/lib/runtime/conversationDirectory.js +116 -0
  54. package/lib/runtime/conversationRead.d.ts +14 -0
  55. package/lib/runtime/conversationRead.js +34 -0
  56. package/lib/runtime/conversationReading.d.ts +30 -0
  57. package/lib/runtime/conversationReading.js +47 -0
  58. package/lib/runtime/createChat.d.ts +14 -7
  59. package/lib/runtime/createChat.js +67 -24
  60. package/lib/runtime/durableSender.d.ts +97 -14
  61. package/lib/runtime/durableSender.js +787 -71
  62. package/lib/runtime/groupClient.d.ts +92 -0
  63. package/lib/runtime/groupClient.js +380 -0
  64. package/lib/runtime/groupDenial.d.ts +2 -0
  65. package/lib/runtime/groupDenial.js +4 -0
  66. package/lib/runtime/groupIdentity.d.ts +4 -0
  67. package/lib/runtime/groupIdentity.js +26 -0
  68. package/lib/runtime/inboxClient.d.ts +65 -0
  69. package/lib/runtime/inboxClient.js +268 -0
  70. package/lib/runtime/inboxGroup.d.ts +4 -0
  71. package/lib/runtime/inboxGroup.js +51 -0
  72. package/lib/runtime/inboxStore.d.ts +194 -0
  73. package/lib/runtime/inboxStore.js +329 -0
  74. package/lib/runtime/inboxTransport.d.ts +6 -0
  75. package/lib/runtime/inboxTransport.js +76 -0
  76. package/lib/runtime/index.d.ts +10 -0
  77. package/lib/runtime/index.js +8 -0
  78. package/lib/runtime/indexedDbRecovery.d.ts +6 -0
  79. package/lib/runtime/indexedDbRecovery.js +42 -0
  80. package/lib/runtime/messageClient.d.ts +37 -8
  81. package/lib/runtime/messageClient.js +366 -68
  82. package/lib/runtime/messageControls.d.ts +19 -0
  83. package/lib/runtime/messageControls.js +44 -0
  84. package/lib/runtime/messageDiscussionStore.d.ts +63 -0
  85. package/lib/runtime/messageDiscussionStore.js +147 -0
  86. package/lib/runtime/messageLaunch.d.ts +44 -0
  87. package/lib/runtime/messageLaunch.js +137 -0
  88. package/lib/runtime/messageQuotes.d.ts +3 -0
  89. package/lib/runtime/messageQuotes.js +17 -0
  90. package/lib/runtime/messageReaders.d.ts +5 -1
  91. package/lib/runtime/messageReaders.js +16 -5
  92. package/lib/runtime/messageStore.d.ts +51 -2
  93. package/lib/runtime/messageStore.js +264 -14
  94. package/lib/runtime/messageThread.d.ts +9 -0
  95. package/lib/runtime/messageThread.js +17 -0
  96. package/lib/runtime/messageTimeline.d.ts +51 -0
  97. package/lib/runtime/messageTimeline.js +121 -0
  98. package/lib/runtime/outboxSchema.d.ts +5 -0
  99. package/lib/runtime/outboxSchema.js +59 -0
  100. package/lib/runtime/outgoingContent.d.ts +95 -0
  101. package/lib/runtime/outgoingContent.js +121 -0
  102. package/lib/runtime/readBatchJournal.d.ts +35 -0
  103. package/lib/runtime/readBatchJournal.js +210 -0
  104. package/lib/runtime/readCounts.d.ts +7 -1
  105. package/lib/runtime/readCounts.js +108 -21
  106. package/lib/runtime/readIndex.d.ts +74 -7
  107. package/lib/runtime/readIndex.js +488 -33
  108. package/lib/runtime/readSchema.d.ts +2 -0
  109. package/lib/runtime/readSchema.js +58 -0
  110. package/lib/runtime/readSync.d.ts +8 -0
  111. package/lib/runtime/readSync.js +125 -17
  112. package/lib/runtime/readingClient.d.ts +22 -0
  113. package/lib/runtime/readingClient.js +141 -20
  114. package/lib/runtime/readingContent.d.ts +5 -0
  115. package/lib/runtime/readingContent.js +23 -0
  116. package/lib/runtime/responseCache.d.ts +41 -5
  117. package/lib/runtime/responseCache.js +182 -44
  118. package/lib/runtime/socialReadClient.d.ts +30 -4
  119. package/lib/runtime/socialReadClient.js +34 -8
  120. package/lib/runtime/voiceUpload.d.ts +2 -0
  121. package/lib/runtime/voiceUpload.js +27 -0
  122. package/lib/snapshot.d.ts +36 -0
  123. package/lib/snapshot.js +52 -0
  124. package/lib/types/chatInput.d.ts +3 -0
  125. package/package.json +32 -2
@@ -1,5 +1,41 @@
1
- import { IndexedDbResponseCache } from "./responseCache.js";
1
+ import { asChatError, ChatError } from "./chatError.js";
2
+ import { isOffline, isOfflineNetworkFailure } from "./connectivity.js";
3
+ import { IndexedDbResponseCache, isResponseCacheAuthorityError, assertResponseCacheAccess } from "./responseCache.js";
2
4
  import { messageScopeKey } from "./messageStore.js";
5
+ const requestId = () => crypto.randomUUID();
6
+ const safeId = (value) => value && /^[a-zA-Z0-9_.:@-]{1,128}$/.test(value) ? value : undefined;
7
+ // Error bodies are untrusted; never retain their text, scope, or arbitrary fields.
8
+ async function failureCode(response) {
9
+ if (response.bodyUsed || response.body?.locked)
10
+ return;
11
+ const reader = response.body?.getReader();
12
+ if (!reader)
13
+ return;
14
+ let timer;
15
+ try {
16
+ const deadline = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("READ_COUNTS_DIAGNOSTIC_TIMEOUT")), 250); });
17
+ let text = "", bytes = 0;
18
+ const decoder = new TextDecoder();
19
+ while (true) {
20
+ const part = await Promise.race([reader.read(), deadline]);
21
+ if (part.done)
22
+ break;
23
+ bytes += part.value.byteLength;
24
+ if (bytes > 4096)
25
+ return;
26
+ text += decoder.decode(part.value, { stream: true });
27
+ }
28
+ const code = JSON.parse(text + decoder.decode())?.message;
29
+ return typeof code === "string" && /^(SOCIAL_READ_(UNAVAILABLE|IDENTITY_UNAVAILABLE|FORBIDDEN)|INVALID_READ_COUNTS|UNAUTHORIZED|INVALID_SOCIAL_READ_IDENTITY|READ_RECEIVER_NOT_READY)$/.test(code) ? code : undefined;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ finally {
35
+ clearTimeout(timer);
36
+ void reader.cancel().catch(() => { });
37
+ }
38
+ }
3
39
  let subscriptionSequence = 0;
4
40
  function nextSubscriptionSequence() { subscriptionSequence = Math.max(Date.now() * 1000, subscriptionSequence + 1); return subscriptionSequence; }
5
41
  /** One active conversation; fixed event window, bounded batches, no count polling. */
@@ -11,8 +47,10 @@ export class ReadCountsClient {
11
47
  heartbeat;
12
48
  controller;
13
49
  generation = 0;
50
+ operationId = requestId();
14
51
  retries = 0;
15
52
  closed = false;
53
+ closing;
16
54
  revision = -1;
17
55
  running = false;
18
56
  dirty = false;
@@ -36,25 +74,48 @@ export class ReadCountsClient {
36
74
  if (options.scope) {
37
75
  if (options.scope.appId !== options.appId || options.scope.profileId !== options.profileId)
38
76
  throw new Error("READ_COUNTS_SCOPE_MISMATCH");
39
- this.cache = new IndexedDbResponseCache(messageScopeKey(options.scope));
77
+ this.cache = new IndexedDbResponseCache(messageScopeKey(options.scope), { access: options.access, retryAbort: true });
40
78
  }
41
79
  }
80
+ report(error, stage) {
81
+ const failure = asChatError(error);
82
+ this.options.onError?.(new ChatError(failure.code, failure.message, { cause: error, status: failure.status, threadId: failure.threadId, diagnostic: { ...failure.diagnostic, source: "read-counts", stage } }));
83
+ }
42
84
  denyCache() {
43
85
  this.revoked = true;
44
86
  this.accessVersion++;
45
87
  this.lastResult = undefined;
46
- void this.cache?.invalidate().catch(error => this.options.onError?.(error));
88
+ void this.cache?.invalidate().catch(error => this.report(error, "cache.invalidate"));
47
89
  }
48
90
  async post(path, body, signal) {
49
- const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}${path}`, { method: "POST", headers: { authorization: `Bearer ${this.options.token}`, "content-type": "application/json" }, body: JSON.stringify(body), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(8000)]) : AbortSignal.timeout(8000), redirect: "error" });
50
- if (!response.ok)
51
- throw new Error(`READ_COUNTS_HTTP_${response.status}`);
52
- const envelope = await response.json();
53
- if (envelope.success !== true)
54
- throw new Error("INVALID_READ_COUNTS_RESPONSE");
55
- return envelope.data;
91
+ const scopeVersion = this.options.access ? await assertResponseCacheAccess(this.options.access) : undefined;
92
+ const clientRequestId = requestId(), started = performance.now();
93
+ const diagnostic = { source: "read-counts", route: path, method: "POST", operationId: this.operationId, clientRequestId, attempt: path.endsWith("/counts") ? this.retries + 1 : 1 };
94
+ try {
95
+ const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}${path}`, { method: "POST", headers: { authorization: `Bearer ${this.options.token}`, "content-type": "application/json", "x-request-id": clientRequestId }, body: JSON.stringify(body), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(8000)]) : AbortSignal.timeout(8000), redirect: "error" });
96
+ diagnostic.status = response.status;
97
+ diagnostic.serverRequestId = safeId(response.headers.get("x-request-id"));
98
+ if (!response.ok) {
99
+ diagnostic.serverCode = await failureCode(response);
100
+ throw Object.assign(new Error(`READ_COUNTS_HTTP_${response.status}`), { status: response.status });
101
+ }
102
+ const envelope = await response.json();
103
+ if (envelope.success !== true)
104
+ throw new Error("INVALID_READ_COUNTS_RESPONSE");
105
+ diagnostic.durationMs = Math.round(performance.now() - started);
106
+ // Keep validation and retry behavior unchanged; add only transport diagnostics.
107
+ if (this.options.access)
108
+ await assertResponseCacheAccess(this.options.access, scopeVersion);
109
+ return envelope.data;
110
+ }
111
+ catch (error) {
112
+ diagnostic.durationMs = Math.round(performance.now() - started);
113
+ throw Object.assign(error instanceof Error ? error : new Error("READ_COUNTS_REQUEST_FAILED"), { diagnostic });
114
+ }
56
115
  }
57
116
  subscription(threadId, release) {
117
+ if (release && isOffline())
118
+ return Promise.resolve();
58
119
  return this.post("/api/social/reading/subscription", { appId: this.options.appId, profileId: this.options.profileId, threadId, clientInstanceId: this.options.clientInstanceId, sequence: nextSubscriptionSequence(), release });
59
120
  }
60
121
  renew() {
@@ -73,8 +134,11 @@ export class ReadCountsClient {
73
134
  this.heartbeat = setInterval(() => { if (!this.closed && this.thread === threadId)
74
135
  this.renew(); }, 20_000);
75
136
  // Recover changes that occurred before a receiver/subscription became ready.
76
- if (recovered && this.revision >= 0)
137
+ if (recovered) {
138
+ // A fresh cache predates the new lease and cannot cover its delivery gap.
139
+ this.force = true;
77
140
  this.schedule(0);
141
+ }
78
142
  }).catch(error => {
79
143
  if (this.closed || generation !== this.generation)
80
144
  return;
@@ -85,7 +149,14 @@ export class ReadCountsClient {
85
149
  clearInterval(this.heartbeat);
86
150
  this.heartbeat = undefined;
87
151
  }
88
- this.options.onError?.(error);
152
+ if (isResponseCacheAuthorityError(error)) {
153
+ this.lastResult = undefined;
154
+ this.subscriptionDenied = true;
155
+ clearInterval(this.heartbeat);
156
+ this.heartbeat = undefined;
157
+ }
158
+ if (!isOfflineNetworkFailure(error))
159
+ this.report(error, "subscription.renew");
89
160
  }).finally(() => { if (this.subscriptionPending === pending)
90
161
  this.subscriptionPending = undefined; });
91
162
  this.subscriptionPending = pending;
@@ -104,6 +175,7 @@ export class ReadCountsClient {
104
175
  return;
105
176
  }
106
177
  const old = this.thread;
178
+ this.operationId = requestId();
107
179
  this.generation++;
108
180
  this.controller?.abort();
109
181
  clearTimeout(this.timer);
@@ -120,7 +192,7 @@ export class ReadCountsClient {
120
192
  this.subscribed = false;
121
193
  this.subscriptionDenied = false;
122
194
  if (old)
123
- void this.subscription(old, true).catch(error => this.options.onError?.(error));
195
+ void this.subscription(old, true).catch(error => this.report(error, "subscription.release"));
124
196
  if (!threadId)
125
197
  return;
126
198
  this.renew();
@@ -172,7 +244,8 @@ export class ReadCountsClient {
172
244
  this.force = false;
173
245
  const key = JSON.stringify(["counts", threadId, [...ids].sort()]);
174
246
  try {
175
- const stored = this.cache ? await this.cache.read(key).catch(error => { this.options.onError?.(error); return undefined; }) : undefined;
247
+ const stored = this.cache ? await this.cache.read(key).catch(error => { if (isResponseCacheAuthorityError(error))
248
+ throw error; this.report(error, "cache.read"); return undefined; }) : undefined;
176
249
  if (generation !== this.generation || this.closed || accessVersion !== this.accessVersion)
177
250
  return;
178
251
  const cached = this.revoked || (stored?.cached && stored.cached.value.revision < this.revision) ? undefined : stored?.cached;
@@ -183,6 +256,8 @@ export class ReadCountsClient {
183
256
  if (offline || (!force && this.requestedRevision <= this.revision && Date.now() - cached.time < 5000))
184
257
  return;
185
258
  }
259
+ if (isOffline())
260
+ return;
186
261
  const value = await this.post("/api/social/reading/counts", { appId: this.options.appId, profileId: this.options.profileId, threadId, messageIds: ids }, controller.signal);
187
262
  if (generation !== this.generation || this.closed || accessVersion !== this.accessVersion)
188
263
  return;
@@ -193,8 +268,8 @@ export class ReadCountsClient {
193
268
  this.retries = 0;
194
269
  this.revoked = false;
195
270
  if (stored)
196
- await this.cache?.write(key, value, stored.epoch).catch(error => { if (String(error).includes("RESPONSE_CACHE_INVALIDATED"))
197
- throw error; this.options.onError?.(error); });
271
+ await this.cache?.write(key, value, stored.epoch).catch(error => { if (isResponseCacheAuthorityError(error))
272
+ throw error; this.report(error, "cache.write"); });
198
273
  if (generation !== this.generation || this.closed || accessVersion !== this.accessVersion)
199
274
  return;
200
275
  this.revision = value.revision;
@@ -203,11 +278,22 @@ export class ReadCountsClient {
203
278
  this.renew();
204
279
  }
205
280
  catch (error) {
281
+ if (isOfflineNetworkFailure(error)) {
282
+ this.dirty = false;
283
+ return;
284
+ }
206
285
  if (!controller.signal.aborted && generation === this.generation && !this.closed) {
207
286
  if (/READ_COUNTS_HTTP_(401|403)/.test(String(error)))
208
287
  this.denyCache();
209
- this.options.onError?.(error);
210
- if (!/READ_COUNTS_HTTP_4\d\d|INVALID_READ_COUNTS/.test(String(error)) && this.retries < 3) {
288
+ if (isResponseCacheAuthorityError(error)) {
289
+ this.lastResult = undefined;
290
+ this.subscriptionDenied = true;
291
+ this.dirty = false;
292
+ clearInterval(this.heartbeat);
293
+ this.heartbeat = undefined;
294
+ }
295
+ this.report(error, "counts.request");
296
+ if (!isResponseCacheAuthorityError(error) && (!/READ_COUNTS_HTTP_4\d\d|INVALID_READ_COUNTS/.test(String(error)) || /READ_COUNTS_HTTP_(409|429)/.test(String(error))) && this.retries < 3) {
211
297
  retryDelay = 1000 * 2 ** this.retries++;
212
298
  this.dirty = true;
213
299
  }
@@ -221,9 +307,10 @@ export class ReadCountsClient {
221
307
  }
222
308
  }
223
309
  }
310
+ retireScope(version) { return this.cache?.retire(version) ?? Promise.resolve(); }
224
311
  close() {
225
- if (this.closed)
226
- return;
312
+ if (this.closing)
313
+ return this.closing;
227
314
  const old = this.thread;
228
315
  this.closed = true;
229
316
  this.generation++;
@@ -233,6 +320,6 @@ export class ReadCountsClient {
233
320
  if (old)
234
321
  void this.subscription(old, true).catch(() => { });
235
322
  this.thread = undefined;
236
- void this.cache?.close().catch(error => this.options.onError?.(error));
323
+ return this.closing = this.cache?.close().catch(error => this.report(error, "cache.close")) ?? Promise.resolve();
237
324
  }
238
325
  }
@@ -2,15 +2,24 @@
2
2
  export type IndexedReadMessage = {
3
3
  id: string;
4
4
  seq: number;
5
+ threadRootId?: string | null;
5
6
  from: string;
6
7
  recipients: string[];
7
8
  mentions: string[];
8
9
  readPolicy: "visible" | "explicit";
9
10
  recalled: boolean;
10
- /** Cached payload is retained so an offline reload can render the message. */
11
+ /** Legacy standalone readers may retain payloads; unified sessions use the message store. */
11
12
  payload: unknown;
13
+ /** Body-free control classification retained by metadata-only reading indexes. */
14
+ readingControl?: boolean;
12
15
  };
16
+ /** Retain read semantics without a second durable copy of message bodies. */
17
+ export declare function readingMetadata<T extends {
18
+ appId: string;
19
+ threads: IndexedReadThread[];
20
+ }>(state: T): T;
13
21
  export type ReadingOperation = {
22
+ threadRootId?: string;
14
23
  operationId: string;
15
24
  threadId: string;
16
25
  readThroughSeq: number;
@@ -18,6 +27,8 @@ export type ReadingOperation = {
18
27
  explicitReadMessageIds: string[];
19
28
  };
20
29
  export type IndexedReadThread = {
30
+ /** Read facts retained when server-side thread organization moves a message. */
31
+ preservedReadMessageIds?: string[];
21
32
  /** Durable source ID: reading positions must remain attached to this ID. */
22
33
  id: string;
23
34
  teamId?: string;
@@ -26,6 +37,7 @@ export type IndexedReadThread = {
26
37
  kind: "dm" | "group";
27
38
  messages: IndexedReadMessage[];
28
39
  readThroughSeq: number;
40
+ messageThreadReadThrough?: Record<string, number> | null;
29
41
  explicitReadMessageIds: string[];
30
42
  };
31
43
  export type ObservedReadIntent = {
@@ -58,12 +70,14 @@ export declare class ReadSyncGap extends Error {
58
70
  constructor(cursor: string);
59
71
  }
60
72
  export declare function createReadIndex(appId: string, profileId: string): ReadIndexState;
73
+ export declare function readingCursor(thread: Pick<IndexedReadThread, "readThroughSeq" | "messageThreadReadThrough">, root?: string | null): number;
61
74
  /** A snapshot is authoritative for server state, never for unsent local operations. */
62
75
  export declare function installReadSnapshot(current: ReadIndexState, snapshot: ReadSnapshot): ReadIndexState;
63
76
  /** Cursor positions are opaque; only exact predecessor matching proves continuity. */
64
77
  export declare function applyReadChange(current: ReadIndexState, change: ReadChange): ReadIndexState;
65
78
  /** Persist observations even if the message arrived before its Sequence metadata. */
66
79
  export declare function recordReadIntent(current: ReadIndexState, intent: ObservedReadIntent): ReadIndexState;
80
+ export declare function resolveObservedReads(current: ReadIndexState): ReadIndexState;
67
81
  /** Called only for a message the visible viewport actually reached. */
68
82
  export declare function recordVisibleRead(current: ReadIndexState, threadId: string, messageId: string, operationId: string): ReadIndexState;
69
83
  export declare function recordExplicitRead(current: ReadIndexState, threadId: string, messageId: string, operationId: string): ReadIndexState;
@@ -72,32 +86,85 @@ export declare function coalesceReadOperations(current: ReadIndexState): (Readin
72
86
  operationIds: string[];
73
87
  })[];
74
88
  /** Counts are over the indexed message coverage, not an estimate of missing history. */
75
- export declare function unreadInThread(state: ReadIndexState, threadId: string): {
89
+ export declare function unreadInThread(state: ReadIndexState, threadId: string, hidden?: ReadonlyMap<string, ReadonlySet<string>>, threadRootId?: string): {
76
90
  unreadMessageCount: number;
77
91
  unreadMentionCount: number;
78
92
  badgeCount: number;
79
93
  };
94
+ export type ReadIndexVersions = Readonly<Record<string, number>>;
95
+ export type ReadIndexTransform = (current: ReadIndexState, versions?: ReadIndexVersions) => ReadIndexState;
96
+ export declare function assertReadIndexVersions(expected: ReadIndexVersions, current?: ReadIndexVersions, teamId?: string): void;
97
+ /** Remove only the withdrawn team's original sources, logical conversations and
98
+ * queued observations. Other teams' pending operations must survive. */
99
+ export declare function removeReadTeam(state: ReadIndexState, teamId: string, knownThreadIds?: readonly string[]): ReadIndexState;
100
+ /** Internal hint for typed reading observations; arbitrary transforms omit it. */
101
+ export type ReadObservationScope = {
102
+ base: ReadIndexState;
103
+ targets: readonly {
104
+ threadId: string;
105
+ messageId: string;
106
+ }[];
107
+ };
80
108
  export interface ReadIndexPersistence {
81
109
  load(appId: string, profileId: string): Promise<ReadIndexState | undefined>;
110
+ loadVersioned?(appId: string, profileId: string): Promise<{
111
+ state: ReadIndexState | undefined;
112
+ versions: ReadIndexVersions;
113
+ }>;
114
+ loadVersions?(appId: string, profileId: string): Promise<ReadIndexVersions>;
115
+ invalidateTeam?(appId: string, profileId: string, teamId: string, version: number, knownThreadIds?: readonly string[]): Promise<ReadIndexState>;
82
116
  /** Transform and persist atomically; UI publishes only the committed result. */
83
- update(appId: string, profileId: string, transform: (current: ReadIndexState) => ReadIndexState): Promise<ReadIndexState>;
117
+ update(appId: string, profileId: string, transform: ReadIndexTransform, observation?: ReadObservationScope): Promise<ReadIndexState>;
84
118
  }
85
- /** Dexie preserves the legacy database/store and outbound [appId, profileId] keys. */
119
+ /** Preserves the database and logical keys; store renaming fences old format writers. */
86
120
  export declare class IndexedDbReadIndex implements ReadIndexPersistence {
87
121
  private storageScope?;
122
+ private migrateLegacy;
123
+ private metadataOnly;
88
124
  private database;
89
125
  private profiles;
126
+ private threadRows;
127
+ private messageRows;
128
+ private positionRows;
129
+ private normalizedStates;
130
+ private orderedStates;
131
+ private legacyClean;
132
+ private observationMessages;
133
+ private versions;
90
134
  private closed;
91
- constructor(factory?: IDBFactory, name?: string, storageScope?: string | undefined);
135
+ private journal;
136
+ private factory;
137
+ private schemaReady;
138
+ private ownerTail;
139
+ constructor(factory?: IDBFactory, name?: string, storageScope?: string | undefined, migrateLegacy?: boolean, metadataOnly?: boolean);
140
+ private owned;
92
141
  private transaction;
93
142
  private key;
143
+ /** Keyset pages avoid materializing a second, unbounded array of durable rows.
144
+ * Keep the caller's transaction so every page belongs to one consistent view. */
145
+ private readPages;
146
+ private hydrate;
147
+ private loadCurrent;
148
+ private loadStored;
149
+ private cleanupClaimedLegacy;
94
150
  load(appId: string, profileId: string): Promise<ReadIndexState | undefined>;
95
- update(appId: string, profileId: string, transform: (current: ReadIndexState) => ReadIndexState): Promise<ReadIndexState>;
151
+ loadVersioned(appId: string, profileId: string): Promise<{
152
+ state: ReadIndexState | undefined;
153
+ versions: Record<string, number>;
154
+ }>;
155
+ loadVersions(appId: string, profileId: string): Promise<ReadIndexVersions>;
156
+ invalidateTeam(appId: string, profileId: string, teamId: string, version: number, knownThreadIds?: readonly string[]): Promise<ReadIndexState>;
157
+ private observe;
158
+ update(appId: string, profileId: string, transform: ReadIndexTransform, observation?: ReadObservationScope): Promise<ReadIndexState>;
159
+ private updateOwned;
160
+ private writeState;
161
+ private cleanUnreachable;
162
+ private changes;
96
163
  close(): Promise<void>;
97
164
  }
98
165
  export declare function sourcesInConversation(state: ReadIndexState, conversationId: string): IndexedReadThread[];
99
166
  /** Aggregate logical history while each original source retains its own read cursor. */
100
- export declare function unreadInConversation(state: ReadIndexState, conversationId: string): {
167
+ export declare function unreadInConversation(state: ReadIndexState, conversationId: string, hidden?: ReadonlyMap<string, ReadonlySet<string>>, threadRootId?: string): {
101
168
  unreadMessageCount: number;
102
169
  unreadMentionCount: number;
103
170
  badgeCount: number;