@pmate/chat-sdk 0.12.0-next.7 → 0.12.0-next.70

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 (96) hide show
  1. package/README.md +152 -81
  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 +148 -0
  7. package/lib/chatContract.js +1 -0
  8. package/lib/chatError.d.ts +11 -0
  9. package/lib/chatError.js +13 -0
  10. package/lib/chatTypes.d.ts +121 -0
  11. package/lib/chatTypes.js +1 -0
  12. package/lib/credentials.d.ts +26 -0
  13. package/lib/credentials.js +110 -0
  14. package/lib/fileMetadata.d.ts +9 -0
  15. package/lib/fileMetadata.js +18 -0
  16. package/lib/framework.d.ts +11 -0
  17. package/lib/framework.js +12 -0
  18. package/lib/history.d.ts +4 -0
  19. package/lib/history.js +8 -0
  20. package/lib/hooks/useChatSnapshot.d.ts +4 -0
  21. package/lib/hooks/useChatSnapshot.js +9 -0
  22. package/lib/index.d.ts +2 -0
  23. package/lib/index.js +2 -0
  24. package/lib/internal/chatEngine.d.ts +131 -0
  25. package/lib/internal/chatEngine.js +280 -0
  26. package/lib/internal/chatRegistry.d.ts +4 -0
  27. package/lib/internal/chatRegistry.js +4 -0
  28. package/lib/internal/createPublicChat.d.ts +4 -0
  29. package/lib/internal/createPublicChat.js +52 -0
  30. package/lib/messageView.d.ts +6 -0
  31. package/lib/messageView.js +103 -0
  32. package/lib/runtime/batchedReadIndex.d.ts +16 -3
  33. package/lib/runtime/batchedReadIndex.js +50 -4
  34. package/lib/runtime/cachedMessage.d.ts +12 -0
  35. package/lib/runtime/cachedMessage.js +18 -0
  36. package/lib/runtime/chatClient.d.ts +2 -0
  37. package/lib/runtime/chatClient.js +8 -3
  38. package/lib/runtime/chatError.d.ts +3 -0
  39. package/lib/runtime/chatError.js +15 -0
  40. package/lib/runtime/chatSession.d.ts +127 -13
  41. package/lib/runtime/chatSession.js +727 -40
  42. package/lib/runtime/connectivity.d.ts +4 -0
  43. package/lib/runtime/connectivity.js +8 -0
  44. package/lib/runtime/conversationDirectory.d.ts +37 -0
  45. package/lib/runtime/conversationDirectory.js +116 -0
  46. package/lib/runtime/conversationRead.d.ts +13 -0
  47. package/lib/runtime/conversationRead.js +34 -0
  48. package/lib/runtime/conversationReading.d.ts +28 -0
  49. package/lib/runtime/conversationReading.js +47 -0
  50. package/lib/runtime/createChat.d.ts +11 -7
  51. package/lib/runtime/createChat.js +46 -23
  52. package/lib/runtime/durableSender.d.ts +97 -14
  53. package/lib/runtime/durableSender.js +786 -71
  54. package/lib/runtime/groupClient.d.ts +76 -0
  55. package/lib/runtime/groupClient.js +325 -0
  56. package/lib/runtime/index.d.ts +7 -0
  57. package/lib/runtime/index.js +5 -0
  58. package/lib/runtime/messageClient.d.ts +35 -8
  59. package/lib/runtime/messageClient.js +364 -66
  60. package/lib/runtime/messageControls.d.ts +19 -0
  61. package/lib/runtime/messageControls.js +44 -0
  62. package/lib/runtime/messageLaunch.d.ts +44 -0
  63. package/lib/runtime/messageLaunch.js +137 -0
  64. package/lib/runtime/messageQuotes.d.ts +3 -0
  65. package/lib/runtime/messageQuotes.js +17 -0
  66. package/lib/runtime/messageReaders.d.ts +12 -1
  67. package/lib/runtime/messageReaders.js +67 -3
  68. package/lib/runtime/messageStore.d.ts +40 -2
  69. package/lib/runtime/messageStore.js +227 -11
  70. package/lib/runtime/messageTimeline.d.ts +50 -0
  71. package/lib/runtime/messageTimeline.js +120 -0
  72. package/lib/runtime/outboxSchema.d.ts +5 -0
  73. package/lib/runtime/outboxSchema.js +59 -0
  74. package/lib/runtime/outgoingContent.d.ts +89 -0
  75. package/lib/runtime/outgoingContent.js +113 -0
  76. package/lib/runtime/readBatchJournal.d.ts +35 -0
  77. package/lib/runtime/readBatchJournal.js +210 -0
  78. package/lib/runtime/readCounts.d.ts +15 -1
  79. package/lib/runtime/readCounts.js +97 -9
  80. package/lib/runtime/readIndex.d.ts +68 -7
  81. package/lib/runtime/readIndex.js +460 -22
  82. package/lib/runtime/readSchema.d.ts +2 -0
  83. package/lib/runtime/readSchema.js +58 -0
  84. package/lib/runtime/readSync.d.ts +1 -0
  85. package/lib/runtime/readSync.js +26 -9
  86. package/lib/runtime/readingClient.d.ts +19 -0
  87. package/lib/runtime/readingClient.js +131 -19
  88. package/lib/runtime/readingContent.d.ts +5 -0
  89. package/lib/runtime/readingContent.js +23 -0
  90. package/lib/runtime/responseCache.d.ts +59 -0
  91. package/lib/runtime/responseCache.js +232 -0
  92. package/lib/runtime/socialReadClient.d.ts +4 -2
  93. package/lib/runtime/socialReadClient.js +12 -8
  94. package/lib/runtime/voiceUpload.d.ts +2 -0
  95. package/lib/runtime/voiceUpload.js +27 -0
  96. package/package.json +27 -2
@@ -1,4 +1,4 @@
1
- import { applyReadChange, ReadSyncGap, createReadIndex, installReadSnapshot } from "./readIndex.js";
1
+ import { readingMetadata, resolveObservedReads, assertReadIndexVersions, applyReadChange, ReadSyncGap, createReadIndex, installReadSnapshot } from "./readIndex.js";
2
2
  /** Keeps local operations until an authoritative projection covers them. */
3
3
  export class ReadSyncClient {
4
4
  options;
@@ -9,8 +9,15 @@ export class ReadSyncClient {
9
9
  this.options = options;
10
10
  }
11
11
  async loadLocal() {
12
- return await this.options.persistence.load(this.options.appId, this.options.profileId)
13
- ?? createReadIndex(this.options.appId, this.options.profileId);
12
+ const { appId, profileId, persistence, metadataOnly } = this.options;
13
+ const state = await persistence.load(appId, profileId) ?? createReadIndex(appId, profileId);
14
+ const normalize = (current) => {
15
+ const next = metadataOnly ? readingMetadata(current) : current;
16
+ return next.observedReadIntents?.length ? resolveObservedReads(next) : next;
17
+ };
18
+ if (normalize(state) === state)
19
+ return state;
20
+ return persistence.update(appId, profileId, normalize);
14
21
  }
15
22
  stop() { this.controller.abort(); }
16
23
  synchronize() {
@@ -33,7 +40,7 @@ export class ReadSyncClient {
33
40
  ...init, signal: timeout.signal, headers: { ...init.headers, authorization: `Bearer ${this.options.sessionToken}` },
34
41
  });
35
42
  if (!response.ok)
36
- throw new Error(`READ_SYNC_HTTP_${response.status}`);
43
+ throw Object.assign(new Error(`READ_SYNC_HTTP_${response.status}`), { status: response.status });
37
44
  const envelope = await response.json();
38
45
  if (envelope.success !== true || envelope.data === undefined)
39
46
  throw new Error("INVALID_READ_SYNC_RESPONSE");
@@ -46,7 +53,9 @@ export class ReadSyncClient {
46
53
  }
47
54
  async run() {
48
55
  const { appId, profileId, persistence } = this.options;
49
- const current = await this.loadLocal();
56
+ const loaded = persistence.loadVersioned ? await persistence.loadVersioned(appId, profileId) : { state: await persistence.load(appId, profileId), versions: {} };
57
+ const current = loaded.state ?? createReadIndex(appId, profileId);
58
+ const versions = loaded.versions;
50
59
  // Ordinary reads are monotonic: only the furthest position per thread needs
51
60
  // sending. Keep every original operation in storage until the projection
52
61
  // confirms it, and never rewrite an operation ID's payload during retries.
@@ -60,6 +69,8 @@ export class ReadSyncClient {
60
69
  }
61
70
  const outgoing = current.pending.filter(operation => operation.explicitReadMessageIds.length || operation.readThroughSeq <= 0 || latest.get(operation.threadId) === operation);
62
71
  for (const operation of outgoing) {
72
+ if (persistence.loadVersions)
73
+ assertReadIndexVersions(versions, await persistence.loadVersions(appId, profileId));
63
74
  const receipt = await this.request("/api/social/reading", {
64
75
  method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...operation, appId, profileId }),
65
76
  });
@@ -69,8 +80,10 @@ export class ReadSyncClient {
69
80
  this.readAfter = Math.max(this.readAfter, receipt.acceptedAt);
70
81
  }
71
82
  const query = new URLSearchParams({ appId, profileId });
83
+ if (this.options.metadataOnly)
84
+ query.set("metadataOnly", "true");
72
85
  if (!this.readAfter && current.syncCursor !== "0") {
73
- const delta = await this.request(`/api/social/reading/changes?${new URLSearchParams({ appId, profileId, after: current.syncCursor })}`);
86
+ const delta = await this.request(`/api/social/reading/changes?${new URLSearchParams({ appId, profileId, after: current.syncCursor, ...(this.options.metadataOnly ? { metadataOnly: "true" } : {}) })}`);
74
87
  if (delta.appId !== appId || delta.profileId !== profileId || typeof delta.syncCursor !== "string"
75
88
  || typeof delta.snapshotRequired !== "boolean" || !Array.isArray(delta.changes))
76
89
  throw new Error("INVALID_READ_DELTA");
@@ -78,8 +91,9 @@ export class ReadSyncClient {
78
91
  try {
79
92
  if (this.controller.signal.aborted)
80
93
  throw new Error("READ_SYNC_STOPPED");
81
- const next = await persistence.update(appId, profileId, state => {
82
- const applied = delta.changes.reduce(applyReadChange, state);
94
+ const next = await persistence.update(appId, profileId, (state, currentVersions) => {
95
+ assertReadIndexVersions(versions, currentVersions);
96
+ const applied = delta.changes.reduce((current, change) => applyReadChange(current, this.options.metadataOnly ? { ...change, thread: readingMetadata({ appId, threads: [change.thread] }).threads[0] } : change), this.options.metadataOnly ? readingMetadata(state) : state);
83
97
  if (applied.syncCursor !== delta.syncCursor)
84
98
  throw new ReadSyncGap(applied.syncCursor);
85
99
  return applied;
@@ -100,7 +114,10 @@ export class ReadSyncClient {
100
114
  if (this.controller.signal.aborted)
101
115
  throw new Error("READ_SYNC_STOPPED");
102
116
  // Merge into the latest transaction, including reads made while HTTP was pending.
103
- const next = await persistence.update(appId, profileId, state => installReadSnapshot(state, snapshot));
117
+ const next = await persistence.update(appId, profileId, (state, currentVersions) => {
118
+ assertReadIndexVersions(versions, currentVersions);
119
+ return installReadSnapshot(state, this.options.metadataOnly ? readingMetadata(snapshot) : snapshot);
120
+ });
104
121
  if (!next.pending.length)
105
122
  this.readAfter = 0;
106
123
  if (!this.controller.signal.aborted)
@@ -1,11 +1,15 @@
1
+ import { type ConversationReadMessage } from "./conversationRead.js";
1
2
  import { type ReadIndexPersistence, type ReadIndexState } from "./readIndex.js";
2
3
  export type ReadingClientOptions = {
3
4
  appId: string;
4
5
  profileId: string;
5
6
  sessionToken: string;
6
7
  hubHttpUrl: string;
8
+ teamId?: string;
9
+ metadataOnly?: boolean;
7
10
  persistence?: ReadIndexPersistence;
8
11
  storageScope?: string;
12
+ migrateLegacy?: boolean;
9
13
  fetch?: typeof fetch;
10
14
  onError?: (error: unknown) => void;
11
15
  onRecovered?: () => void;
@@ -15,6 +19,12 @@ export type ReadingClientOptions = {
15
19
  export declare class ReadingClient {
16
20
  private options;
17
21
  private storage;
22
+ private backing;
23
+ private closing?;
24
+ private revoking?;
25
+ private versions?;
26
+ private prepared;
27
+ private accepted;
18
28
  private persistence;
19
29
  private sync;
20
30
  private tasks;
@@ -34,8 +44,17 @@ export declare class ReadingClient {
34
44
  refresh: () => void;
35
45
  synchronize(targetCursor?: string, profileId?: string): Promise<ReadIndexState>;
36
46
  update(transform: (state: ReadIndexState) => ReadIndexState): Promise<ReadIndexState>;
47
+ private updateScoped;
48
+ prepareTeam(teamId: string, version: number): Promise<void>;
49
+ private assertThreadTeam;
50
+ markRead(threadId: string, messages?: readonly ConversationReadMessage[]): Promise<ReadIndexState>;
37
51
  recordVisible(threadId: string, messageIds: string[]): Promise<ReadIndexState>;
38
52
  recordExplicit(threadId: string, messageIds: string[]): Promise<ReadIndexState>;
39
53
  private record;
54
+ withdraw(): void;
55
+ private stop;
56
+ /** This client is retired permanently. Drain accepted local observations
57
+ * before deleting one team's profile-wide projection; sibling teams survive. */
58
+ revokeTeam(teamId: string, version: number, knownThreadIds?: readonly string[]): Promise<void>;
40
59
  close(): Promise<void>;
41
60
  }
@@ -1,12 +1,21 @@
1
+ import { isValidChatTeamId } from "./thread.js";
2
+ import { isOffline, isOfflineNetworkFailure } from "./connectivity.js";
3
+ import { recordConversationRead } from "./conversationRead.js";
1
4
  import { BatchedReadIndex } from "./batchedReadIndex.js";
2
5
  import { WindowedTasks } from "./coalescer.js";
3
- import { IndexedDbReadIndex, recordReadIntent } from "./readIndex.js";
6
+ import { IndexedDbReadIndex, readingMetadata, recordReadIntent, assertReadIndexVersions } from "./readIndex.js";
4
7
  import { ReadSyncClient } from "./readSync.js";
5
8
  /** Owns durable local reads, network coalescing, retries and state notifications.
6
9
  * Hosts report actual visibility; loading or subscribing never marks messages read. */
7
10
  export class ReadingClient {
8
11
  options;
9
12
  storage;
13
+ backing;
14
+ closing;
15
+ revoking;
16
+ versions;
17
+ prepared = new Map();
18
+ accepted = new Set();
10
19
  persistence;
11
20
  sync;
12
21
  tasks;
@@ -19,7 +28,10 @@ export class ReadingClient {
19
28
  generation = 0;
20
29
  constructor(options) {
21
30
  this.options = options;
22
- const storage = options.persistence ?? (this.storage = new IndexedDbReadIndex(globalThis.indexedDB, "pmate-social-read-index", options.storageScope));
31
+ if (options.teamId !== undefined && !isValidChatTeamId(options.teamId))
32
+ throw new Error("INVALID_READ_TEAM");
33
+ const storage = options.persistence ?? (this.storage = new IndexedDbReadIndex(globalThis.indexedDB, "pmate-social-read-index", options.storageScope, options.migrateLegacy, options.metadataOnly));
34
+ this.backing = storage;
23
35
  this.persistence = new BatchedReadIndex(storage);
24
36
  this.tasks = new WindowedTasks(1000, error => this.failed(error));
25
37
  this.sync = new ReadSyncClient({ ...options, persistence: this.persistence, onChange: state => this.publish(state) });
@@ -27,13 +39,13 @@ export class ReadingClient {
27
39
  getSnapshot = () => this.state;
28
40
  subscribe = (listener) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; };
29
41
  publish(state) {
30
- if (this.closed || JSON.stringify(state) === JSON.stringify(this.state))
42
+ if (this.closed || state === this.state || JSON.stringify(state) === JSON.stringify(this.state))
31
43
  return;
32
44
  this.state = state;
33
45
  this.listeners.forEach(listener => listener());
34
46
  }
35
47
  failed(error) {
36
- if (this.closed)
48
+ if (this.closed || isOfflineNetworkFailure(error))
37
49
  return;
38
50
  this.options.onError?.(error);
39
51
  if (/HTTP_(400|401|403)/.test(String(error)) || (typeof navigator !== "undefined" && !navigator.onLine) || this.retry)
@@ -56,8 +68,9 @@ export class ReadingClient {
56
68
  this.refresh();
57
69
  }
58
70
  refresh = () => {
59
- if (!this.closed)
60
- this.tasks.schedule("reading", async () => { await this.synchronize(); });
71
+ if (!this.closed && !isOffline())
72
+ this.tasks.schedule("reading", async () => { if (!isOffline())
73
+ await this.synchronize(); });
61
74
  };
62
75
  async synchronize(targetCursor, profileId) {
63
76
  if (this.closed)
@@ -84,32 +97,131 @@ export class ReadingClient {
84
97
  }
85
98
  throw new Error("Reading projection has not reached the announced version");
86
99
  }
87
- async update(transform) {
100
+ update(transform) {
101
+ // Advanced transforms may replace profile-wide state. Typed observation
102
+ // methods below only derive changes for their configured team.
103
+ return this.updateScoped(transform);
104
+ }
105
+ updateScoped(transform, teamId, observation) {
88
106
  if (this.closed)
89
- throw new Error("READING_CLIENT_CLOSED");
90
- const next = await this.persistence.update(this.options.appId, this.options.profileId, transform);
91
- if (!this.closed) {
92
- this.publish(next);
93
- if (next.pending.length || next.observedReadIntents?.length)
94
- this.refresh();
95
- }
96
- return next;
107
+ return Promise.reject(new Error("READING_CLIENT_CLOSED"));
108
+ // One shared metadata read per local authority generation, rather than one
109
+ // IndexedDB lookup for every viewport observation.
110
+ const versions = this.versions ??= this.persistence.loadVersions(this.options.appId, this.options.profileId);
111
+ const task = (async () => {
112
+ const expected = await versions;
113
+ const next = await this.persistence.update(this.options.appId, this.options.profileId, (state, currentVersions) => {
114
+ assertReadIndexVersions(expected, currentVersions, teamId);
115
+ const next = transform(state);
116
+ return this.options.metadataOnly ? readingMetadata(next) : next;
117
+ }, observation);
118
+ if (!this.closed) {
119
+ this.publish(next);
120
+ if (next.pending.length || next.observedReadIntents?.length)
121
+ this.refresh();
122
+ }
123
+ return next;
124
+ })().catch(error => {
125
+ if (String(error).includes("READ_SCOPE_CHANGED")) {
126
+ if (teamId !== undefined)
127
+ this.withdraw();
128
+ else
129
+ this.versions = undefined;
130
+ }
131
+ throw error;
132
+ });
133
+ this.accepted.add(task);
134
+ void task.finally(() => this.accepted.delete(task)).catch(() => { });
135
+ return task;
136
+ }
137
+ prepareTeam(teamId, version) {
138
+ if (this.closed)
139
+ return Promise.reject(new Error("READING_CLIENT_CLOSED"));
140
+ if (!isValidChatTeamId(teamId) || !Number.isSafeInteger(version) || version < 0)
141
+ return Promise.reject(new Error("INVALID_READ_SCOPE_VERSION"));
142
+ const previous = this.prepared.get(teamId);
143
+ if (previous && previous.version >= version)
144
+ return previous.task;
145
+ const task = (async () => {
146
+ if (version > 0)
147
+ await this.persistence.invalidateTeam(this.options.appId, this.options.profileId, teamId, version);
148
+ this.versions = undefined;
149
+ })().catch(error => { if (this.prepared.get(teamId)?.task === task)
150
+ this.prepared.delete(teamId); throw error; });
151
+ this.prepared.set(teamId, { version, task });
152
+ return task;
153
+ }
154
+ assertThreadTeam(state, threadId) {
155
+ if (this.options.teamId !== undefined && state.threads.some(thread => (thread.id === threadId || thread.conversationId === threadId) && thread.teamId !== undefined && thread.teamId !== this.options.teamId))
156
+ throw new Error("READ_CONVERSATION_TEAM_MISMATCH");
157
+ }
158
+ markRead(threadId, messages = []) {
159
+ return this.updateScoped(state => { this.assertThreadTeam(state, threadId); return recordConversationRead(state, threadId, messages); }, this.options.teamId);
97
160
  }
98
161
  recordVisible(threadId, messageIds) { return this.record(threadId, messageIds, "visible"); }
99
162
  recordExplicit(threadId, messageIds) { return this.record(threadId, messageIds, "explicit"); }
100
163
  record(threadId, ids, readPolicy) {
101
164
  const messageIds = [...new Set(ids)];
102
- return this.update(state => messageIds.reduce((next, messageId) => recordReadIntent(next, { threadId, messageId, readPolicy, operationId: crypto.randomUUID() }), state));
165
+ if (!messageIds.length && this.state) {
166
+ try {
167
+ this.assertThreadTeam(this.state, threadId);
168
+ return Promise.resolve(this.state);
169
+ }
170
+ catch (error) {
171
+ return Promise.reject(error);
172
+ }
173
+ }
174
+ return this.updateScoped(state => { this.assertThreadTeam(state, threadId); return messageIds.reduce((next, messageId) => recordReadIntent(next, { threadId, messageId, readPolicy, operationId: crypto.randomUUID() }), state); }, this.options.teamId, this.state && messageIds.length ? { base: this.state, targets: messageIds.map(messageId => ({ threadId, messageId })) } : undefined);
103
175
  }
104
- async close() {
176
+ withdraw() { this.stop(); }
177
+ stop() {
178
+ if (this.closed)
179
+ return;
105
180
  this.closed = true;
106
181
  this.generation++;
107
182
  this.offWake?.();
108
183
  this.tasks.close();
109
184
  clearTimeout(this.retry);
110
185
  this.sync.stop();
186
+ this.state = undefined;
187
+ this.listeners.forEach(listener => listener());
111
188
  this.listeners.clear();
112
- await this.persistence.close();
113
- await this.storage?.close();
189
+ }
190
+ /** This client is retired permanently. Drain accepted local observations
191
+ * before deleting one team's profile-wide projection; sibling teams survive. */
192
+ revokeTeam(teamId, version, knownThreadIds = []) {
193
+ if (this.revoking)
194
+ return this.revoking;
195
+ if (this.closing)
196
+ return Promise.reject(new Error("READING_CLIENT_CLOSED"));
197
+ this.stop();
198
+ return this.revoking = (async () => {
199
+ try {
200
+ await Promise.allSettled([...this.accepted]);
201
+ await this.persistence.close();
202
+ if (!this.backing.invalidateTeam)
203
+ throw new Error("READ_SCOPE_INVALIDATION_UNAVAILABLE");
204
+ await this.backing.invalidateTeam(this.options.appId, this.options.profileId, teamId, version, knownThreadIds);
205
+ }
206
+ finally {
207
+ await this.storage?.close();
208
+ }
209
+ })();
210
+ }
211
+ close() {
212
+ if (this.revoking)
213
+ return this.revoking;
214
+ if (this.closing)
215
+ return this.closing;
216
+ this.stop();
217
+ return this.closing = (async () => {
218
+ try {
219
+ await Promise.allSettled([...this.accepted]);
220
+ await this.persistence.close();
221
+ }
222
+ finally {
223
+ await this.storage?.close();
224
+ }
225
+ })();
114
226
  }
115
227
  }
@@ -0,0 +1,5 @@
1
+ /** Social control envelopes do not contribute to message unread counts. */
2
+ export declare function isReadingControl(payload: unknown, appId: string): boolean;
3
+ /** Mirrors the server's voice policy for ordinary and quoted wire envelopes. */
4
+ export declare function messageRequiresPlayback(body: unknown): boolean;
5
+ export declare function messageMentionsProfile(body: unknown, profileId: string): boolean;
@@ -0,0 +1,23 @@
1
+ /** Social control envelopes do not contribute to message unread counts. */
2
+ export function isReadingControl(payload, appId) {
3
+ if (!payload || typeof payload !== "object")
4
+ return false;
5
+ const value = payload;
6
+ if (value.body !== undefined)
7
+ return isReadingControl(value.body, appId);
8
+ return value.kind === "message" && value.content?.appId === appId && (value.content.reaction !== undefined || value.content.recall !== undefined);
9
+ }
10
+ /** Mirrors the server's voice policy for ordinary and quoted wire envelopes. */
11
+ export function messageRequiresPlayback(body) {
12
+ if (!body || typeof body !== "object")
13
+ return false;
14
+ const value = body;
15
+ return value.contentKind === "voice" || value.content?.contentKind === "voice" || [value.content?.voice?.url, value.content?.content?.voice?.url].some(url => typeof url === "string" && url.length > 0);
16
+ }
17
+ export function messageMentionsProfile(body, profileId) {
18
+ if (!body || typeof body !== "object")
19
+ return false;
20
+ const content = body.content;
21
+ const mentions = content?.mentions !== undefined ? content.mentions : content?.content?.mentions;
22
+ return Array.isArray(mentions) && mentions.some(mention => mention?.id === profileId);
23
+ }
@@ -0,0 +1,59 @@
1
+ export type ResponseCacheAccess = () => Promise<{
2
+ version: number;
3
+ allowed: boolean;
4
+ }>;
5
+ export declare function isResponseCacheAuthorityError(error: unknown): boolean;
6
+ export declare function assertResponseCacheAccess(access?: ResponseCacheAccess, expectedVersion?: number): Promise<number | undefined>;
7
+ export type ResponseCacheOptions<T> = {
8
+ indexedDB?: IDBFactory;
9
+ name?: string;
10
+ access?: ResponseCacheAccess;
11
+ /** Immutable identity metadata must survive ordinary response-window eviction. */
12
+ retainAll?: boolean;
13
+ recordBytes?: number;
14
+ entries?: number;
15
+ batchRecords?: number;
16
+ revision?: (value: T) => string;
17
+ };
18
+ /** Small response windows, isolated by identity. Epochs fence late writes after
19
+ * access withdrawal. No localStorage or synchronous writes on the read path. */
20
+ export declare class IndexedDbResponseCache<T> {
21
+ private scope;
22
+ private options;
23
+ private db;
24
+ private rows;
25
+ private epochs;
26
+ private pending;
27
+ private tasks;
28
+ private running?;
29
+ private invalidations;
30
+ private closed;
31
+ private closing?;
32
+ constructor(scope: string, options?: ResponseCacheOptions<T>);
33
+ /** Resolve shared message-scope authority before opening our transaction.
34
+ * A newer authority version retires response windows exactly once; delayed
35
+ * callers can never roll the authority backwards or delete recovered data. */
36
+ private synchronizeAccess;
37
+ read(key: string): Promise<{
38
+ epoch: number;
39
+ cached: {
40
+ value: T;
41
+ time: number;
42
+ } | undefined;
43
+ }>;
44
+ /** Key-only callers can share one bounded metadata read transaction. */
45
+ readMany(keys: readonly string[]): Promise<Map<string, {
46
+ epoch: number;
47
+ cached: {
48
+ value: T;
49
+ time: number;
50
+ } | undefined;
51
+ }>>;
52
+ write(key: string, value: T, epoch: number, expectedRevision?: string | null): Promise<void>;
53
+ /** Idempotent shared-scope retirement: an old cleanup cannot erase windows
54
+ * created after the same authority version was already recovered. */
55
+ retire(version: number): Promise<void>;
56
+ invalidate(): Promise<void>;
57
+ flush(): Promise<void>;
58
+ close(): Promise<void>;
59
+ }
@@ -0,0 +1,232 @@
1
+ import { Dexie } from "dexie";
2
+ import { WindowedTasks } from "./coalescer.js";
3
+ export function isResponseCacheAuthorityError(error) {
4
+ return /RESPONSE_CACHE_(ACCESS_REVOKED|SCOPE_CHANGED|INVALIDATED)/.test(String(error));
5
+ }
6
+ export async function assertResponseCacheAccess(access, expectedVersion) {
7
+ if (!access)
8
+ return undefined;
9
+ const current = await access();
10
+ if (!current.allowed)
11
+ throw new Error("RESPONSE_CACHE_ACCESS_REVOKED");
12
+ if (expectedVersion !== undefined && current.version !== expectedVersion)
13
+ throw new Error("RESPONSE_CACHE_SCOPE_CHANGED");
14
+ return current.version;
15
+ }
16
+ /** Small response windows, isolated by identity. Epochs fence late writes after
17
+ * access withdrawal. No localStorage or synchronous writes on the read path. */
18
+ export class IndexedDbResponseCache {
19
+ scope;
20
+ options;
21
+ db;
22
+ rows;
23
+ epochs;
24
+ pending = [];
25
+ tasks = new WindowedTasks(16, () => { });
26
+ running;
27
+ invalidations = new Set();
28
+ closed = false;
29
+ closing;
30
+ constructor(scope, options = {}) {
31
+ this.scope = scope;
32
+ this.options = options;
33
+ for (const [value, max] of [[options.recordBytes ?? 65536, 1048576], [options.entries ?? 256, 256], [options.batchRecords ?? 128, 128]])
34
+ if (!Number.isSafeInteger(value) || value < 1 || value > max)
35
+ throw new Error("INVALID_RESPONSE_CACHE_LIMIT");
36
+ this.db = new Dexie(options.name ?? "pmate-chat-response-windows", { indexedDB: options.indexedDB ?? globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange });
37
+ this.db.version(1).stores({ windows: "[scope+key],scope", epochs: "scope" });
38
+ this.rows = this.db.table("windows");
39
+ this.epochs = this.db.table("epochs");
40
+ }
41
+ /** Resolve shared message-scope authority before opening our transaction.
42
+ * A newer authority version retires response windows exactly once; delayed
43
+ * callers can never roll the authority backwards or delete recovered data. */
44
+ async synchronizeAccess() {
45
+ if (!this.options.access)
46
+ return;
47
+ const access = await this.options.access();
48
+ const stored = await this.epochs.get(this.scope);
49
+ const storedVersion = stored?.accessVersion ?? 0;
50
+ if (access.version < storedVersion)
51
+ throw new Error("RESPONSE_CACHE_SCOPE_CHANGED");
52
+ // Ordinary cache reads must not take an IndexedDB write lock. Only an
53
+ // authority transition needs the atomic epoch bump and range deletion.
54
+ if (access.version > storedVersion)
55
+ await this.db.transaction("rw", this.rows, this.epochs, async () => {
56
+ const current = await this.epochs.get(this.scope);
57
+ const version = current?.accessVersion ?? 0;
58
+ if (access.version < version)
59
+ throw new Error("RESPONSE_CACHE_SCOPE_CHANGED");
60
+ if (access.version > version) {
61
+ await this.epochs.put({ scope: this.scope, epoch: (current?.epoch ?? 0) + 1, accessVersion: access.version });
62
+ await this.rows.where("[scope+key]").between([this.scope, Dexie.minKey], [this.scope, Dexie.maxKey], true, true).delete();
63
+ }
64
+ });
65
+ if (!access.allowed)
66
+ throw new Error("RESPONSE_CACHE_ACCESS_REVOKED");
67
+ }
68
+ async read(key) {
69
+ if (this.closed)
70
+ throw new Error("RESPONSE_CACHE_CLOSED");
71
+ await this.synchronizeAccess();
72
+ return this.db.transaction("r", this.rows, this.epochs, async () => {
73
+ const epoch = (await this.epochs.get(this.scope))?.epoch ?? 0;
74
+ const row = await this.rows.get([this.scope, key]);
75
+ return { epoch, cached: row?.epoch === epoch ? { value: row.value, time: row.time } : undefined };
76
+ });
77
+ }
78
+ /** Key-only callers can share one bounded metadata read transaction. */
79
+ async readMany(keys) {
80
+ if (this.closed)
81
+ throw new Error("RESPONSE_CACHE_CLOSED");
82
+ if (keys.length > 128)
83
+ throw new Error("RESPONSE_CACHE_SELECTION_TOO_LARGE");
84
+ await this.synchronizeAccess();
85
+ return this.db.transaction("r", this.rows, this.epochs, async () => {
86
+ const epoch = (await this.epochs.get(this.scope))?.epoch ?? 0, unique = [...new Set(keys)];
87
+ const rows = await this.rows.bulkGet(unique.map(key => [this.scope, key]));
88
+ return new Map(unique.map((key, index) => { const row = rows[index]; return [key, { epoch, cached: row?.epoch === epoch ? { value: row.value, time: row.time } : undefined }]; }));
89
+ });
90
+ }
91
+ write(key, value, epoch, expectedRevision) {
92
+ if (this.closed)
93
+ return Promise.reject(new Error("RESPONSE_CACHE_CLOSED"));
94
+ if (expectedRevision !== undefined && !this.options.revision)
95
+ return Promise.reject(new Error("RESPONSE_CACHE_REVISION_UNAVAILABLE"));
96
+ const copy = structuredClone(value), bytes = new TextEncoder().encode(JSON.stringify(copy)).byteLength;
97
+ // Count in-flight data as well as queued data; requests cannot create an
98
+ // unbounded backlog while IndexedDB is blocked by another tab.
99
+ if (bytes > (this.options.recordBytes ?? 65536) || this.pending.length >= 128 || this.pending.reduce((n, w) => n + w.row.bytes, 0) + bytes > 1048576)
100
+ return Promise.reject(new Error("RESPONSE_CACHE_BACKPRESSURE"));
101
+ const promise = new Promise((resolve, reject) => this.pending.push({ row: { scope: this.scope, key, epoch, time: Date.now(), bytes, value: copy }, expectedRevision, resolve, reject }));
102
+ this.tasks.schedule("write", () => this.flush());
103
+ return promise;
104
+ }
105
+ /** Idempotent shared-scope retirement: an old cleanup cannot erase windows
106
+ * created after the same authority version was already recovered. */
107
+ retire(version) {
108
+ if (this.closed)
109
+ return Promise.reject(new Error("RESPONSE_CACHE_CLOSED"));
110
+ if (!Number.isSafeInteger(version) || version < 1)
111
+ return Promise.reject(new Error("INVALID_RESPONSE_SCOPE_VERSION"));
112
+ const task = this.db.transaction("rw", this.rows, this.epochs, async () => {
113
+ const current = await this.epochs.get(this.scope);
114
+ if ((current?.accessVersion ?? 0) >= version)
115
+ return;
116
+ await this.epochs.put({ scope: this.scope, epoch: (current?.epoch ?? 0) + 1, accessVersion: version });
117
+ await this.rows.where("[scope+key]").between([this.scope, Dexie.minKey], [this.scope, Dexie.maxKey], true, true).delete();
118
+ });
119
+ this.invalidations.add(task);
120
+ return task.finally(() => this.invalidations.delete(task));
121
+ }
122
+ invalidate() {
123
+ if (this.closed)
124
+ return Promise.reject(new Error("RESPONSE_CACHE_CLOSED"));
125
+ const task = (async () => {
126
+ await this.db.transaction("rw", this.rows, this.epochs, async () => {
127
+ const current = await this.epochs.get(this.scope);
128
+ const epoch = (current?.epoch ?? 0) + 1;
129
+ await this.epochs.put({ scope: this.scope, epoch, accessVersion: current?.accessVersion });
130
+ await this.rows.where("[scope+key]").between([this.scope, Dexie.minKey], [this.scope, Dexie.maxKey], true, true).delete();
131
+ });
132
+ })();
133
+ this.invalidations.add(task);
134
+ return task.finally(() => this.invalidations.delete(task));
135
+ }
136
+ async flush() {
137
+ if (this.running) {
138
+ await this.running;
139
+ if (this.pending.length)
140
+ return this.flush();
141
+ return;
142
+ }
143
+ if (!this.pending.length)
144
+ return;
145
+ const task = (async () => {
146
+ let failed = false, failure;
147
+ // Each batch commits and resolves independently. A configured smaller
148
+ // batch still drains all accepted requests, including during close.
149
+ while (this.pending.length) {
150
+ const batch = this.pending.slice(0, this.options.batchRecords ?? 128);
151
+ try {
152
+ await this.synchronizeAccess();
153
+ const outcome = await this.db.transaction("rw", this.rows, this.epochs, async () => {
154
+ const epoch = (await this.epochs.get(this.scope))?.epoch ?? 0;
155
+ const valid = batch.filter(write => write.row.epoch === epoch);
156
+ const conditional = valid.filter(write => write.expectedRevision !== undefined);
157
+ const keys = [...new Set(conditional.map(write => write.row.key))];
158
+ const current = conditional.length ? await this.rows.bulkGet(keys.map(key => [this.scope, key])) : [];
159
+ const projected = new Map(keys.map((key, index) => [key, current[index]?.epoch === epoch ? current[index] : undefined]));
160
+ const accepted = new Set(), changed = new Set(), unique = new Map();
161
+ for (const write of valid) {
162
+ if (write.expectedRevision !== undefined) {
163
+ const previous = projected.get(write.row.key);
164
+ const revision = previous ? this.options.revision(previous.value) : null;
165
+ if (revision !== write.expectedRevision) {
166
+ // Another document may have already committed this exact
167
+ // revision; it is an idempotent success, never an overwrite.
168
+ if (revision === this.options.revision(write.row.value) && JSON.stringify(previous.value) === JSON.stringify(write.row.value))
169
+ accepted.add(write);
170
+ else
171
+ changed.add(write);
172
+ continue;
173
+ }
174
+ }
175
+ unique.set(write.row.key, write.row);
176
+ projected.set(write.row.key, write.row);
177
+ accepted.add(write);
178
+ }
179
+ if (unique.size) {
180
+ await this.rows.bulkPut([...unique.values()]);
181
+ if (!this.options.retainAll) {
182
+ const stored = await this.rows.where("scope").equals(this.scope).toArray();
183
+ stored.sort((a, b) => b.time - a.time || a.key.localeCompare(b.key));
184
+ let bytes = 0;
185
+ const evicted = [];
186
+ stored.forEach((row, index) => { bytes += row.bytes; if (index >= (this.options.entries ?? 256) || bytes > 1048576)
187
+ evicted.push([this.scope, row.key]); });
188
+ if (evicted.length)
189
+ await this.rows.bulkDelete(evicted);
190
+ }
191
+ }
192
+ return { accepted, changed };
193
+ });
194
+ for (const write of batch) {
195
+ if (outcome.accepted.has(write))
196
+ write.resolve();
197
+ else
198
+ write.reject(new Error(outcome.changed.has(write) ? "RESPONSE_CACHE_CHANGED" : "RESPONSE_CACHE_INVALIDATED"));
199
+ }
200
+ }
201
+ catch (error) {
202
+ batch.forEach(write => write.reject(error));
203
+ if (!failed)
204
+ failure = error;
205
+ failed = true;
206
+ }
207
+ finally {
208
+ this.pending.splice(0, batch.length);
209
+ }
210
+ }
211
+ if (failed)
212
+ throw failure;
213
+ })().finally(() => { if (this.running === task)
214
+ this.running = undefined; });
215
+ this.running = task;
216
+ return task;
217
+ }
218
+ close() {
219
+ if (this.closing)
220
+ return this.closing;
221
+ this.closed = true;
222
+ this.tasks.close();
223
+ return this.closing = (async () => {
224
+ try {
225
+ await Promise.all([this.flush(), ...this.invalidations]);
226
+ }
227
+ finally {
228
+ this.db.close();
229
+ }
230
+ })();
231
+ }
232
+ }