@pmate/chat-sdk 0.12.0-next.8 → 0.12.0-next.81

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 (111) hide show
  1. package/README.md +170 -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 +151 -0
  7. package/lib/chatContract.js +1 -0
  8. package/lib/chatError.d.ts +14 -0
  9. package/lib/chatError.js +16 -0
  10. package/lib/chatTypes.d.ts +127 -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 +5 -0
  31. package/lib/index.js +5 -0
  32. package/lib/internal/chatEngine.d.ts +130 -0
  33. package/lib/internal/chatEngine.js +284 -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 +52 -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 +7 -0
  45. package/lib/runtime/chatClient.js +14 -3
  46. package/lib/runtime/chatError.d.ts +5 -0
  47. package/lib/runtime/chatError.js +20 -0
  48. package/lib/runtime/chatSession.d.ts +128 -13
  49. package/lib/runtime/chatSession.js +759 -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 +13 -0
  55. package/lib/runtime/conversationRead.js +34 -0
  56. package/lib/runtime/conversationReading.d.ts +28 -0
  57. package/lib/runtime/conversationReading.js +47 -0
  58. package/lib/runtime/createChat.d.ts +11 -7
  59. package/lib/runtime/createChat.js +46 -23
  60. package/lib/runtime/durableSender.d.ts +97 -14
  61. package/lib/runtime/durableSender.js +786 -71
  62. package/lib/runtime/groupClient.d.ts +91 -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/index.d.ts +7 -0
  67. package/lib/runtime/index.js +5 -0
  68. package/lib/runtime/indexedDbRecovery.d.ts +4 -0
  69. package/lib/runtime/indexedDbRecovery.js +27 -0
  70. package/lib/runtime/messageClient.d.ts +35 -8
  71. package/lib/runtime/messageClient.js +364 -66
  72. package/lib/runtime/messageControls.d.ts +19 -0
  73. package/lib/runtime/messageControls.js +44 -0
  74. package/lib/runtime/messageLaunch.d.ts +44 -0
  75. package/lib/runtime/messageLaunch.js +137 -0
  76. package/lib/runtime/messageQuotes.d.ts +3 -0
  77. package/lib/runtime/messageQuotes.js +17 -0
  78. package/lib/runtime/messageReaders.d.ts +5 -1
  79. package/lib/runtime/messageReaders.js +16 -5
  80. package/lib/runtime/messageStore.d.ts +43 -2
  81. package/lib/runtime/messageStore.js +248 -14
  82. package/lib/runtime/messageTimeline.d.ts +50 -0
  83. package/lib/runtime/messageTimeline.js +120 -0
  84. package/lib/runtime/outboxSchema.d.ts +5 -0
  85. package/lib/runtime/outboxSchema.js +59 -0
  86. package/lib/runtime/outgoingContent.d.ts +94 -0
  87. package/lib/runtime/outgoingContent.js +118 -0
  88. package/lib/runtime/readBatchJournal.d.ts +35 -0
  89. package/lib/runtime/readBatchJournal.js +210 -0
  90. package/lib/runtime/readCounts.d.ts +15 -1
  91. package/lib/runtime/readCounts.js +97 -9
  92. package/lib/runtime/readIndex.d.ts +68 -7
  93. package/lib/runtime/readIndex.js +460 -22
  94. package/lib/runtime/readSchema.d.ts +2 -0
  95. package/lib/runtime/readSchema.js +58 -0
  96. package/lib/runtime/readSync.d.ts +1 -0
  97. package/lib/runtime/readSync.js +26 -9
  98. package/lib/runtime/readingClient.d.ts +19 -0
  99. package/lib/runtime/readingClient.js +131 -19
  100. package/lib/runtime/readingContent.d.ts +5 -0
  101. package/lib/runtime/readingContent.js +23 -0
  102. package/lib/runtime/responseCache.d.ts +40 -5
  103. package/lib/runtime/responseCache.js +182 -44
  104. package/lib/runtime/socialReadClient.d.ts +9 -4
  105. package/lib/runtime/socialReadClient.js +12 -8
  106. package/lib/runtime/voiceUpload.d.ts +2 -0
  107. package/lib/runtime/voiceUpload.js +27 -0
  108. package/lib/snapshot.d.ts +36 -0
  109. package/lib/snapshot.js +52 -0
  110. package/lib/types/chatInput.d.ts +3 -0
  111. package/package.json +32 -2
@@ -1,3 +1,6 @@
1
+ import { isOffline, isOfflineNetworkFailure } from "./connectivity.js";
2
+ import { IndexedDbResponseCache, isResponseCacheAuthorityError, assertResponseCacheAccess } from "./responseCache.js";
3
+ import { messageScopeKey } from "./messageStore.js";
1
4
  let subscriptionSequence = 0;
2
5
  function nextSubscriptionSequence() { subscriptionSequence = Math.max(Date.now() * 1000, subscriptionSequence + 1); return subscriptionSequence; }
3
6
  /** One active conversation; fixed event window, bounded batches, no count polling. */
@@ -11,29 +14,58 @@ export class ReadCountsClient {
11
14
  generation = 0;
12
15
  retries = 0;
13
16
  closed = false;
17
+ closing;
14
18
  revision = -1;
15
19
  running = false;
16
20
  dirty = false;
17
21
  subscribed = false;
18
22
  subscriptionDenied = false;
19
23
  subscriptionPending;
24
+ cache;
25
+ lastResult;
26
+ publish(value) {
27
+ if (JSON.stringify(value) === JSON.stringify(this.lastResult))
28
+ return;
29
+ this.lastResult = value;
30
+ this.options.onChange(value);
31
+ }
32
+ revoked = false;
33
+ accessVersion = 0;
34
+ requestedRevision = -1;
35
+ force = false;
20
36
  constructor(options) {
21
37
  this.options = options;
38
+ if (options.scope) {
39
+ if (options.scope.appId !== options.appId || options.scope.profileId !== options.profileId)
40
+ throw new Error("READ_COUNTS_SCOPE_MISMATCH");
41
+ this.cache = new IndexedDbResponseCache(messageScopeKey(options.scope), { access: options.access });
42
+ }
43
+ }
44
+ denyCache() {
45
+ this.revoked = true;
46
+ this.accessVersion++;
47
+ this.lastResult = undefined;
48
+ void this.cache?.invalidate().catch(error => this.options.onError?.(error));
22
49
  }
23
50
  async post(path, body, signal) {
51
+ const scopeVersion = this.options.access ? await assertResponseCacheAccess(this.options.access) : undefined;
24
52
  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" });
25
53
  if (!response.ok)
26
- throw new Error(`READ_COUNTS_HTTP_${response.status}`);
54
+ throw Object.assign(new Error(`READ_COUNTS_HTTP_${response.status}`), { status: response.status });
27
55
  const envelope = await response.json();
28
56
  if (envelope.success !== true)
29
57
  throw new Error("INVALID_READ_COUNTS_RESPONSE");
58
+ if (this.options.access)
59
+ await assertResponseCacheAccess(this.options.access, scopeVersion);
30
60
  return envelope.data;
31
61
  }
32
62
  subscription(threadId, release) {
63
+ if (release && isOffline())
64
+ return Promise.resolve();
33
65
  return this.post("/api/social/reading/subscription", { appId: this.options.appId, profileId: this.options.profileId, threadId, clientInstanceId: this.options.clientInstanceId, sequence: nextSubscriptionSequence(), release });
34
66
  }
35
67
  renew() {
36
- if (!this.thread || this.closed || this.subscriptionDenied)
68
+ if (!this.thread || this.closed || this.subscriptionDenied || (typeof navigator !== "undefined" && navigator.onLine === false))
37
69
  return;
38
70
  const threadId = this.thread, generation = this.generation;
39
71
  if (this.subscriptionPending?.generation === generation)
@@ -48,18 +80,29 @@ export class ReadCountsClient {
48
80
  this.heartbeat = setInterval(() => { if (!this.closed && this.thread === threadId)
49
81
  this.renew(); }, 20_000);
50
82
  // Recover changes that occurred before a receiver/subscription became ready.
51
- if (recovered && this.revision >= 0)
83
+ if (recovered) {
84
+ // A fresh cache predates the new lease and cannot cover its delivery gap.
85
+ this.force = true;
52
86
  this.schedule(0);
87
+ }
53
88
  }).catch(error => {
54
89
  if (this.closed || generation !== this.generation)
55
90
  return;
56
91
  this.subscribed = false;
57
92
  if (/READ_COUNTS_HTTP_(401|403)/.test(String(error))) {
58
93
  this.subscriptionDenied = true;
94
+ this.denyCache();
59
95
  clearInterval(this.heartbeat);
60
96
  this.heartbeat = undefined;
61
97
  }
62
- this.options.onError?.(error);
98
+ if (isResponseCacheAuthorityError(error)) {
99
+ this.lastResult = undefined;
100
+ this.subscriptionDenied = true;
101
+ clearInterval(this.heartbeat);
102
+ this.heartbeat = undefined;
103
+ }
104
+ if (!isOfflineNetworkFailure(error))
105
+ this.options.onError?.(error);
63
106
  }).finally(() => { if (this.subscriptionPending === pending)
64
107
  this.subscriptionPending = undefined; });
65
108
  this.subscriptionPending = pending;
@@ -83,9 +126,12 @@ export class ReadCountsClient {
83
126
  clearTimeout(this.timer);
84
127
  clearInterval(this.heartbeat);
85
128
  this.timer = undefined;
129
+ this.lastResult = undefined;
86
130
  this.thread = threadId;
87
131
  this.ids = ids;
88
132
  this.revision = -1;
133
+ this.requestedRevision = -1;
134
+ this.force = false;
89
135
  this.dirty = false;
90
136
  this.retries = 0;
91
137
  this.subscribed = false;
@@ -104,11 +150,13 @@ export class ReadCountsClient {
104
150
  throw new Error("INVALID_READ_COUNTS_EVENT");
105
151
  if (threadId !== this.thread || revision <= this.revision || this.closed)
106
152
  return;
153
+ this.requestedRevision = Math.max(this.requestedRevision, revision);
107
154
  this.schedule(3000);
108
155
  }
109
156
  reconnect() {
110
157
  if (!this.thread || this.closed)
111
158
  return;
159
+ this.force = true;
112
160
  this.subscribed = false;
113
161
  this.subscriptionDenied = false;
114
162
  this.renew();
@@ -137,22 +185,60 @@ export class ReadCountsClient {
137
185
  let retryDelay;
138
186
  const controller = new AbortController();
139
187
  this.controller = controller;
188
+ const accessVersion = this.accessVersion, force = this.force;
189
+ this.force = false;
190
+ const key = JSON.stringify(["counts", threadId, [...ids].sort()]);
140
191
  try {
192
+ const stored = this.cache ? await this.cache.read(key).catch(error => { if (isResponseCacheAuthorityError(error))
193
+ throw error; this.options.onError?.(error); return undefined; }) : undefined;
194
+ if (generation !== this.generation || this.closed || accessVersion !== this.accessVersion)
195
+ return;
196
+ const cached = this.revoked || (stored?.cached && stored.cached.value.revision < this.revision) ? undefined : stored?.cached;
197
+ if (cached) {
198
+ this.revision = cached.value.revision;
199
+ this.publish(cached.value);
200
+ const offline = typeof navigator !== "undefined" && navigator.onLine === false;
201
+ if (offline || (!force && this.requestedRevision <= this.revision && Date.now() - cached.time < 5000))
202
+ return;
203
+ }
204
+ if (isOffline())
205
+ return;
141
206
  const value = await this.post("/api/social/reading/counts", { appId: this.options.appId, profileId: this.options.profileId, threadId, messageIds: ids }, controller.signal);
142
- if (generation !== this.generation || this.closed)
207
+ if (generation !== this.generation || this.closed || accessVersion !== this.accessVersion)
143
208
  return;
144
209
  if (value?.appId !== this.options.appId || value.threadId !== threadId || !Number.isSafeInteger(value.revision) || value.revision < 0 || !value.counts || typeof value.counts !== "object" || ids.some(id => !Number.isSafeInteger(value.counts[id]) || value.counts[id] < 0) || Object.keys(value.counts).some(id => !ids.includes(id)))
145
210
  throw new Error("INVALID_READ_COUNTS_RESULT");
211
+ if (value.revision < this.revision)
212
+ return;
146
213
  this.retries = 0;
214
+ this.revoked = false;
215
+ if (stored)
216
+ await this.cache?.write(key, value, stored.epoch).catch(error => { if (isResponseCacheAuthorityError(error))
217
+ throw error; this.options.onError?.(error); });
218
+ if (generation !== this.generation || this.closed || accessVersion !== this.accessVersion)
219
+ return;
147
220
  this.revision = value.revision;
148
- this.options.onChange(value);
221
+ this.publish(value);
149
222
  if (!this.subscribed)
150
223
  this.renew();
151
224
  }
152
225
  catch (error) {
226
+ if (isOfflineNetworkFailure(error)) {
227
+ this.dirty = false;
228
+ return;
229
+ }
153
230
  if (!controller.signal.aborted && generation === this.generation && !this.closed) {
231
+ if (/READ_COUNTS_HTTP_(401|403)/.test(String(error)))
232
+ this.denyCache();
233
+ if (isResponseCacheAuthorityError(error)) {
234
+ this.lastResult = undefined;
235
+ this.subscriptionDenied = true;
236
+ this.dirty = false;
237
+ clearInterval(this.heartbeat);
238
+ this.heartbeat = undefined;
239
+ }
154
240
  this.options.onError?.(error);
155
- if (!/READ_COUNTS_HTTP_4\d\d|INVALID_READ_COUNTS/.test(String(error)) && this.retries < 3) {
241
+ 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) {
156
242
  retryDelay = 1000 * 2 ** this.retries++;
157
243
  this.dirty = true;
158
244
  }
@@ -166,9 +252,10 @@ export class ReadCountsClient {
166
252
  }
167
253
  }
168
254
  }
255
+ retireScope(version) { return this.cache?.retire(version) ?? Promise.resolve(); }
169
256
  close() {
170
- if (this.closed)
171
- return;
257
+ if (this.closing)
258
+ return this.closing;
172
259
  const old = this.thread;
173
260
  this.closed = true;
174
261
  this.generation++;
@@ -178,5 +265,6 @@ export class ReadCountsClient {
178
265
  if (old)
179
266
  void this.subscription(old, true).catch(() => { });
180
267
  this.thread = undefined;
268
+ return this.closing = this.cache?.close().catch(error => this.options.onError?.(error)) ?? Promise.resolve();
181
269
  }
182
270
  }
@@ -7,9 +7,16 @@ export type IndexedReadMessage = {
7
7
  mentions: string[];
8
8
  readPolicy: "visible" | "explicit";
9
9
  recalled: boolean;
10
- /** Cached payload is retained so an offline reload can render the message. */
10
+ /** Legacy standalone readers may retain payloads; unified sessions use the message store. */
11
11
  payload: unknown;
12
+ /** Body-free control classification retained by metadata-only reading indexes. */
13
+ readingControl?: boolean;
12
14
  };
15
+ /** Retain read semantics without a second durable copy of message bodies. */
16
+ export declare function readingMetadata<T extends {
17
+ appId: string;
18
+ threads: IndexedReadThread[];
19
+ }>(state: T): T;
13
20
  export type ReadingOperation = {
14
21
  operationId: string;
15
22
  threadId: string;
@@ -64,6 +71,7 @@ export declare function installReadSnapshot(current: ReadIndexState, snapshot: R
64
71
  export declare function applyReadChange(current: ReadIndexState, change: ReadChange): ReadIndexState;
65
72
  /** Persist observations even if the message arrived before its Sequence metadata. */
66
73
  export declare function recordReadIntent(current: ReadIndexState, intent: ObservedReadIntent): ReadIndexState;
74
+ export declare function resolveObservedReads(current: ReadIndexState): ReadIndexState;
67
75
  /** Called only for a message the visible viewport actually reached. */
68
76
  export declare function recordVisibleRead(current: ReadIndexState, threadId: string, messageId: string, operationId: string): ReadIndexState;
69
77
  export declare function recordExplicitRead(current: ReadIndexState, threadId: string, messageId: string, operationId: string): ReadIndexState;
@@ -72,32 +80,85 @@ export declare function coalesceReadOperations(current: ReadIndexState): (Readin
72
80
  operationIds: string[];
73
81
  })[];
74
82
  /** Counts are over the indexed message coverage, not an estimate of missing history. */
75
- export declare function unreadInThread(state: ReadIndexState, threadId: string): {
83
+ export declare function unreadInThread(state: ReadIndexState, threadId: string, hidden?: ReadonlyMap<string, ReadonlySet<string>>): {
76
84
  unreadMessageCount: number;
77
85
  unreadMentionCount: number;
78
86
  badgeCount: number;
79
87
  };
88
+ export type ReadIndexVersions = Readonly<Record<string, number>>;
89
+ export type ReadIndexTransform = (current: ReadIndexState, versions?: ReadIndexVersions) => ReadIndexState;
90
+ export declare function assertReadIndexVersions(expected: ReadIndexVersions, current?: ReadIndexVersions, teamId?: string): void;
91
+ /** Remove only the withdrawn team's original sources, logical conversations and
92
+ * queued observations. Other teams' pending operations must survive. */
93
+ export declare function removeReadTeam(state: ReadIndexState, teamId: string, knownThreadIds?: readonly string[]): ReadIndexState;
94
+ /** Internal hint for typed reading observations; arbitrary transforms omit it. */
95
+ export type ReadObservationScope = {
96
+ base: ReadIndexState;
97
+ targets: readonly {
98
+ threadId: string;
99
+ messageId: string;
100
+ }[];
101
+ };
80
102
  export interface ReadIndexPersistence {
81
103
  load(appId: string, profileId: string): Promise<ReadIndexState | undefined>;
104
+ loadVersioned?(appId: string, profileId: string): Promise<{
105
+ state: ReadIndexState | undefined;
106
+ versions: ReadIndexVersions;
107
+ }>;
108
+ loadVersions?(appId: string, profileId: string): Promise<ReadIndexVersions>;
109
+ invalidateTeam?(appId: string, profileId: string, teamId: string, version: number, knownThreadIds?: readonly string[]): Promise<ReadIndexState>;
82
110
  /** Transform and persist atomically; UI publishes only the committed result. */
83
- update(appId: string, profileId: string, transform: (current: ReadIndexState) => ReadIndexState): Promise<ReadIndexState>;
111
+ update(appId: string, profileId: string, transform: ReadIndexTransform, observation?: ReadObservationScope): Promise<ReadIndexState>;
84
112
  }
85
- /** Dexie preserves the legacy database/store and outbound [appId, profileId] keys. */
113
+ /** Preserves the database and logical keys; store renaming fences old format writers. */
86
114
  export declare class IndexedDbReadIndex implements ReadIndexPersistence {
87
115
  private storageScope?;
116
+ private migrateLegacy;
117
+ private metadataOnly;
88
118
  private database;
89
119
  private profiles;
120
+ private threadRows;
121
+ private messageRows;
122
+ private positionRows;
123
+ private normalizedStates;
124
+ private orderedStates;
125
+ private legacyClean;
126
+ private observationMessages;
127
+ private versions;
90
128
  private closed;
91
- constructor(factory?: IDBFactory, name?: string, storageScope?: string | undefined);
129
+ private journal;
130
+ private factory;
131
+ private schemaReady;
132
+ private ownerTail;
133
+ constructor(factory?: IDBFactory, name?: string, storageScope?: string | undefined, migrateLegacy?: boolean, metadataOnly?: boolean);
134
+ private owned;
92
135
  private transaction;
93
136
  private key;
137
+ /** Keyset pages avoid materializing a second, unbounded array of durable rows.
138
+ * Keep the caller's transaction so every page belongs to one consistent view. */
139
+ private readPages;
140
+ private hydrate;
141
+ private loadCurrent;
142
+ private loadStored;
143
+ private cleanupClaimedLegacy;
94
144
  load(appId: string, profileId: string): Promise<ReadIndexState | undefined>;
95
- update(appId: string, profileId: string, transform: (current: ReadIndexState) => ReadIndexState): Promise<ReadIndexState>;
145
+ loadVersioned(appId: string, profileId: string): Promise<{
146
+ state: ReadIndexState | undefined;
147
+ versions: Record<string, number>;
148
+ }>;
149
+ loadVersions(appId: string, profileId: string): Promise<ReadIndexVersions>;
150
+ invalidateTeam(appId: string, profileId: string, teamId: string, version: number, knownThreadIds?: readonly string[]): Promise<ReadIndexState>;
151
+ private observe;
152
+ update(appId: string, profileId: string, transform: ReadIndexTransform, observation?: ReadObservationScope): Promise<ReadIndexState>;
153
+ private updateOwned;
154
+ private writeState;
155
+ private cleanUnreachable;
156
+ private changes;
96
157
  close(): Promise<void>;
97
158
  }
98
159
  export declare function sourcesInConversation(state: ReadIndexState, conversationId: string): IndexedReadThread[];
99
160
  /** Aggregate logical history while each original source retains its own read cursor. */
100
- export declare function unreadInConversation(state: ReadIndexState, conversationId: string): {
161
+ export declare function unreadInConversation(state: ReadIndexState, conversationId: string, hidden?: ReadonlyMap<string, ReadonlySet<string>>): {
101
162
  unreadMessageCount: number;
102
163
  unreadMentionCount: number;
103
164
  badgeCount: number;