@pmate/chat-sdk 0.12.0-next.20 → 0.12.0-next.22

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.
@@ -5,8 +5,15 @@ import { messageScopeKey } from "./messageStore.js";
5
5
  export class DurableChatSender {
6
6
  client;
7
7
  onError;
8
+ options;
8
9
  db;
9
10
  outbox;
11
+ epochs;
12
+ version = 0;
13
+ withdrawn = false;
14
+ revoking;
15
+ channel;
16
+ accepted = new Set();
10
17
  scope;
11
18
  identity;
12
19
  values = new Map();
@@ -14,30 +21,129 @@ export class DurableChatSender {
14
21
  listeners = new Set();
15
22
  running = new Map();
16
23
  closed = false;
24
+ closing = false;
25
+ empty = [];
17
26
  offConnection;
18
27
  ready;
19
28
  constructor(client, scope, onError, options = {}) {
20
29
  this.client = client;
21
30
  this.onError = onError;
31
+ this.options = options;
22
32
  this.scope = messageScopeKey(scope);
23
33
  this.identity = { ...scope };
24
34
  this.db = new Dexie(options.name ?? "pmate-chat-outbox", { indexedDB: options.indexedDB ?? globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange });
25
35
  this.db.version(1).stores({ outbox: "[scope+hash],scope,[scope+threadId]" });
36
+ this.db.version(2).stores({ scopeEpochs: "scope" });
26
37
  this.outbox = this.db.table("outbox");
27
- this.ready = this.outbox.where("scope").equals(this.scope).toArray().then(records => {
28
- if (this.closed)
29
- return;
30
- records.filter(record => !record.confirmed).forEach(record => this.values.set(record.hash, record));
31
- this.emit();
32
- });
38
+ this.epochs = this.db.table("scopeEpochs");
39
+ this.db.on("versionchange", () => { this.db.close({ disableAutoOpen: false }); return false; });
40
+ this.ready = this.restore();
41
+ void this.ready.catch(() => { });
42
+ if (typeof BroadcastChannel !== "undefined") {
43
+ this.channel = new BroadcastChannel(`pmate-chat-outbox:${this.scope}:${this.db.name}`);
44
+ this.channel.onmessage = event => { if (Number.isSafeInteger(event.data?.version) && event.data.version > this.version)
45
+ this.withdraw(); };
46
+ }
33
47
  this.offConnection = client.watchConnection(state => {
34
48
  if (state === "connected")
35
49
  void this.resume().catch(onError);
36
50
  });
37
51
  }
52
+ async readAccess() {
53
+ const access = await this.options.access?.();
54
+ if (access && (!Number.isSafeInteger(access.version) || access.version < 0 || typeof access.allowed !== "boolean"))
55
+ throw new Error("INVALID_OUTBOX_ACCESS");
56
+ return access;
57
+ }
58
+ async restore() {
59
+ const access = await this.readAccess();
60
+ const loaded = await this.db.transaction("rw", this.outbox, this.epochs, async () => {
61
+ const current = (await this.epochs.get(this.scope))?.version ?? 0;
62
+ const version = access?.version ?? current;
63
+ if (version < current)
64
+ throw new Error("OUTBOX_SCOPE_CHANGED");
65
+ if (version > current) {
66
+ await this.epochs.put({ scope: this.scope, version });
67
+ await this.deleteRows();
68
+ }
69
+ return { version, advanced: version > current, records: access?.allowed === false ? [] : await this.outbox.where("scope").equals(this.scope).toArray() };
70
+ });
71
+ this.version = loaded.version;
72
+ if (loaded.advanced)
73
+ this.channel?.postMessage({ version: this.version });
74
+ if (this.closed || this.withdrawn)
75
+ return;
76
+ const current = await this.readAccess();
77
+ if (current && (!current.allowed || current.version !== this.version))
78
+ return;
79
+ loaded.records.filter(record => !record.confirmed && (record.accessVersion ?? 0) === this.version).forEach(record => this.values.set(record.hash, record));
80
+ this.emit();
81
+ }
82
+ async checkAccess() {
83
+ if (this.closed)
84
+ throw new Error("CHAT_SENDER_CLOSED");
85
+ if (this.withdrawn)
86
+ throw new Error("OUTBOX_ACCESS_REVOKED");
87
+ const access = await this.readAccess();
88
+ if (access && access.version !== this.version) {
89
+ this.withdraw();
90
+ throw new Error("OUTBOX_SCOPE_CHANGED");
91
+ }
92
+ if (access && !access.allowed)
93
+ throw new Error("OUTBOX_ACCESS_REVOKED");
94
+ }
95
+ async withEpoch(mode, operation) {
96
+ await this.checkAccess();
97
+ try {
98
+ return await this.db.transaction(mode, this.outbox, this.epochs, async () => {
99
+ if (this.closed || this.withdrawn)
100
+ throw new Error("OUTBOX_ACCESS_REVOKED");
101
+ if (((await this.epochs.get(this.scope))?.version ?? 0) !== this.version)
102
+ throw new Error("OUTBOX_SCOPE_CHANGED");
103
+ return operation();
104
+ });
105
+ }
106
+ catch (error) {
107
+ if (String(error).includes("OUTBOX_SCOPE_CHANGED"))
108
+ this.withdraw();
109
+ throw error;
110
+ }
111
+ }
112
+ deleteRows() { return this.outbox.where("[scope+hash]").between([this.scope, Dexie.minKey], [this.scope, Dexie.maxKey], true, true).delete(); }
113
+ /** Stop disclosure immediately; durable invalidation is coordinated separately. */
114
+ withdraw() {
115
+ this.withdrawn = true;
116
+ this.values.clear();
117
+ this.emit();
118
+ }
119
+ revoke(targetVersion) {
120
+ if (this.closed || this.closing)
121
+ return Promise.reject(new Error("CHAT_SENDER_CLOSED"));
122
+ if (this.revoking)
123
+ return this.revoking;
124
+ this.withdraw();
125
+ return this.revoking = (async () => {
126
+ await this.ready.catch(error => { if (!String(error).includes("OUTBOX_SCOPE_CHANGED"))
127
+ throw error; });
128
+ const version = await this.db.transaction("rw", this.outbox, this.epochs, async () => {
129
+ const current = (await this.epochs.get(this.scope))?.version ?? 0;
130
+ const target = targetVersion ?? this.version + 1;
131
+ if (!Number.isSafeInteger(target) || target < 0)
132
+ throw new Error("INVALID_OUTBOX_EPOCH");
133
+ if (current >= target)
134
+ return current;
135
+ await this.epochs.put({ scope: this.scope, version: target });
136
+ await this.deleteRows();
137
+ return target;
138
+ });
139
+ this.channel?.postMessage({ version });
140
+ })();
141
+ }
38
142
  initialize() { return this.ready; }
39
143
  subscribe(listener) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
40
144
  snapshot(threadId) {
145
+ if (this.closed || this.closing || this.withdrawn)
146
+ return this.empty;
41
147
  let snapshot = this.snapshots.get(threadId);
42
148
  if (!snapshot) {
43
149
  snapshot = [...this.values.values()].filter(record => threadId === undefined || record.threadId === threadId);
@@ -50,7 +156,8 @@ export class DurableChatSender {
50
156
  /** Resolves after the exact wire message is durable, independently of network delivery. */
51
157
  async enqueue(threadId, input) {
52
158
  const message = await this.persistOutgoing(threadId, input);
53
- void this.retry(message.hash).catch(error => this.onError(error));
159
+ if (!this.closed && !this.closing && !this.withdrawn)
160
+ void this.retry(message.hash).catch(error => this.onError(error));
54
161
  return message;
55
162
  }
56
163
  /** Compatibility API: resolves only after transport delivery. */
@@ -58,23 +165,27 @@ export class DurableChatSender {
58
165
  const message = await this.persistOutgoing(threadId, input);
59
166
  return this.retry(message.hash);
60
167
  }
61
- async persistOutgoing(threadId, input) {
62
- await this.ready;
63
- if (this.closed)
64
- throw new Error("CHAT_SENDER_CLOSED");
65
- const message = this.client.prepareChat(input.to, withChatTeam(input.body, this.identity.teamId), input.recipients);
66
- if (message.from !== this.identity.profileId)
67
- throw new Error("OUTGOING_MESSAGE_IDENTITY_MISMATCH");
68
- const record = { scope: this.scope, threadId, hash: message.hash, message, status: "sending" };
69
- await this.outbox.put(record);
70
- if (this.closed)
71
- throw new Error("CHAT_SENDER_CLOSED");
72
- this.values.set(record.hash, record);
73
- this.emit();
74
- return message;
168
+ persistOutgoing(threadId, input) {
169
+ if (this.closed || this.closing || this.withdrawn)
170
+ return Promise.reject(new Error("OUTBOX_ACCESS_REVOKED"));
171
+ const pending = (async () => {
172
+ await this.ready;
173
+ await this.checkAccess();
174
+ const message = this.client.prepareChat(input.to, withChatTeam(input.body, this.identity.teamId), input.recipients);
175
+ if (message.from !== this.identity.profileId)
176
+ throw new Error("OUTGOING_MESSAGE_IDENTITY_MISMATCH");
177
+ const record = { scope: this.scope, threadId, hash: message.hash, message, status: "sending", accessVersion: this.version };
178
+ await this.withEpoch("rw", async () => { await this.outbox.put(record); });
179
+ await this.checkAccess();
180
+ this.values.set(record.hash, record);
181
+ this.emit();
182
+ return message;
183
+ })().finally(() => this.accepted.delete(pending));
184
+ this.accepted.add(pending);
185
+ return pending;
75
186
  }
76
187
  retry(hash) {
77
- if (this.closed)
188
+ if (this.closed || this.closing || this.withdrawn)
78
189
  return Promise.reject(new Error("CHAT_SENDER_CLOSED"));
79
190
  const running = this.running.get(hash);
80
191
  if (running)
@@ -85,8 +196,8 @@ export class DurableChatSender {
85
196
  }
86
197
  async transmit(hash) {
87
198
  await this.ready;
88
- const record = await this.outbox.get([this.scope, hash]);
89
- if (!record || this.closed)
199
+ const record = await this.withEpoch("r", async () => this.outbox.get([this.scope, hash]));
200
+ if (!record || this.closed || this.withdrawn)
90
201
  throw new Error("OUTGOING_MESSAGE_UNAVAILABLE");
91
202
  if (record.status === "sent" || record.confirmed)
92
203
  return record.message;
@@ -96,6 +207,7 @@ export class DurableChatSender {
96
207
  if (!latest || latest.confirmed || latest.status === "sent")
97
208
  return latest?.message ?? record.message;
98
209
  }
210
+ await this.checkAccess();
99
211
  if (this.values.get(hash)?.status !== "sending") {
100
212
  this.values.set(hash, sending);
101
213
  this.emit();
@@ -104,7 +216,7 @@ export class DurableChatSender {
104
216
  const message = await this.client.sendPrepared(record.message);
105
217
  const sent = { ...record, message, status: "sent" };
106
218
  const committed = await this.save(sent);
107
- if (!this.closed) {
219
+ if (!this.closed && !this.withdrawn) {
108
220
  if (committed?.confirmed || !committed)
109
221
  this.values.delete(hash);
110
222
  else
@@ -114,7 +226,7 @@ export class DurableChatSender {
114
226
  return message;
115
227
  }
116
228
  catch (error) {
117
- if (!this.closed) {
229
+ if (!this.closed && !this.withdrawn) {
118
230
  const failed = { ...record, status: "failed" };
119
231
  const committed = await this.save(failed);
120
232
  if (committed?.confirmed || committed?.status === "sent") {
@@ -132,7 +244,7 @@ export class DurableChatSender {
132
244
  }
133
245
  }
134
246
  async save(record) {
135
- return this.db.transaction("rw", this.outbox, async () => {
247
+ return this.withEpoch("rw", async () => {
136
248
  const previous = await this.outbox.get([this.scope, record.hash]);
137
249
  if (!previous || previous.confirmed || previous.status === "sent")
138
250
  return previous;
@@ -147,7 +259,7 @@ export class DurableChatSender {
147
259
  if (!hashes.length)
148
260
  return;
149
261
  await this.ready;
150
- await this.db.transaction("rw", this.outbox, async () => {
262
+ await this.withEpoch("rw", async () => {
151
263
  const previous = await this.outbox.bulkGet(hashes.map(hash => [this.scope, hash]));
152
264
  const confirmed = previous.filter((record) => Boolean(record && !record.confirmed)).map(record => ({ ...record, status: "sent", confirmed: true }));
153
265
  if (confirmed.length)
@@ -161,12 +273,12 @@ export class DurableChatSender {
161
273
  }
162
274
  async resume() {
163
275
  await this.ready;
164
- if (this.closed)
276
+ if (this.closed || this.closing || this.withdrawn)
165
277
  return;
166
278
  // Only interrupted, unconfirmed sends resume automatically; failed sends require retry.
167
279
  for (const record of this.values.values())
168
280
  if (record.status === "sending") {
169
- if (this.closed)
281
+ if (this.closed || this.withdrawn)
170
282
  return;
171
283
  try {
172
284
  await this.retry(record.hash);
@@ -177,11 +289,19 @@ export class DurableChatSender {
177
289
  }
178
290
  }
179
291
  async close() {
180
- this.closed = true;
292
+ this.closing = true;
181
293
  this.offConnection();
182
294
  this.listeners.clear();
183
- await this.ready;
184
- await Promise.allSettled([...this.running.values()]);
185
- this.db.close();
295
+ this.channel?.close();
296
+ try {
297
+ await this.ready;
298
+ await Promise.allSettled([...this.accepted, ...this.running.values(), ...(this.revoking ? [this.revoking] : [])]);
299
+ }
300
+ finally {
301
+ this.closed = true;
302
+ this.values.clear();
303
+ this.snapshots.clear();
304
+ this.db.close();
305
+ }
186
306
  }
187
307
  }
@@ -36,6 +36,7 @@ export declare class MessageClient<T extends StoredMessage> {
36
36
  private options;
37
37
  private storage;
38
38
  private watches;
39
+ private accessListeners;
39
40
  private allListeners;
40
41
  private reads;
41
42
  private syncing;
@@ -55,7 +56,20 @@ export declare class MessageClient<T extends StoredMessage> {
55
56
  private pendingBytes;
56
57
  private pendingRecords;
57
58
  private legacyImports;
59
+ private revokingScope?;
60
+ private scopeReady?;
61
+ private scopeVersion;
62
+ private scopeAllowed;
63
+ private scopeDenied;
64
+ private enqueuing;
65
+ private ensureScope;
58
66
  constructor(options: MessageClientOptions<T>);
67
+ /** Shared guard for sibling caches; it never authorizes a denied old instance. */
68
+ subscribeAccessRevoked(listener: () => void): () => void;
69
+ scopeAccess(): Promise<{
70
+ version: number;
71
+ allowed: boolean;
72
+ }>;
59
73
  getSnapshot(thread: string): MessageSnapshot<T> | undefined;
60
74
  subscribe(thread: string, listener: () => void): () => void;
61
75
  subscribeAll(listener: (threadId: string) => void): () => void;
@@ -82,6 +96,8 @@ export declare class MessageClient<T extends StoredMessage> {
82
96
  }, limit?: number): Promise<MessageSnapshot<T>>;
83
97
  private fillWindow;
84
98
  private denyView;
99
+ private denyScope;
100
+ revokeScope(): Promise<number>;
85
101
  revoke(thread: string): Promise<void>;
86
- close(): Promise<void>;
102
+ close(beforeDispose?: Promise<unknown>): Promise<void>;
87
103
  }