@agentshouse/mdruntime 0.1.0-c7274d650bd05 → 0.1.0-c7997f069801e

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 (211) hide show
  1. package/AGENTS.md +283 -232
  2. package/README.md +20 -10
  3. package/dist/adapter.d.ts +113 -28
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/attempt.d.ts +16 -0
  6. package/dist/attempt.d.ts.map +1 -0
  7. package/dist/attempt.js +70 -0
  8. package/dist/binary.d.ts +23 -0
  9. package/dist/binary.d.ts.map +1 -0
  10. package/dist/binary.js +8 -0
  11. package/dist/bootstrap.d.ts +18 -5
  12. package/dist/bootstrap.d.ts.map +1 -1
  13. package/dist/bootstrap.js +147 -40
  14. package/dist/change-set.d.ts +7 -2
  15. package/dist/change-set.d.ts.map +1 -1
  16. package/dist/change-set.js +50 -16
  17. package/dist/change.d.ts +46 -0
  18. package/dist/change.d.ts.map +1 -1
  19. package/dist/change.js +35 -1
  20. package/dist/chat/acts.d.ts +33 -0
  21. package/dist/chat/acts.d.ts.map +1 -0
  22. package/dist/chat/acts.js +36 -0
  23. package/dist/chat/context.d.ts +3 -0
  24. package/dist/chat/context.d.ts.map +1 -0
  25. package/dist/chat/context.js +10 -0
  26. package/dist/chat/earlier.d.ts +10 -0
  27. package/dist/chat/earlier.d.ts.map +1 -0
  28. package/dist/chat/earlier.js +54 -0
  29. package/dist/chat/house.d.ts +25 -0
  30. package/dist/chat/house.d.ts.map +1 -0
  31. package/dist/chat/house.js +38 -0
  32. package/dist/chat/input.d.ts +11 -0
  33. package/dist/chat/input.d.ts.map +1 -0
  34. package/dist/chat/input.js +99 -0
  35. package/dist/chat/kit.d.ts +61 -0
  36. package/dist/chat/kit.d.ts.map +1 -0
  37. package/dist/chat/kit.js +123 -0
  38. package/dist/chat/lasting.d.ts +6 -0
  39. package/dist/chat/lasting.d.ts.map +1 -0
  40. package/dist/chat/lasting.js +19 -0
  41. package/dist/chat/list.d.ts +28 -0
  42. package/dist/chat/list.d.ts.map +1 -0
  43. package/dist/chat/list.js +103 -0
  44. package/dist/chat/markdown.d.ts +21 -0
  45. package/dist/chat/markdown.d.ts.map +1 -0
  46. package/dist/chat/markdown.js +246 -0
  47. package/dist/chat/message.d.ts +7 -0
  48. package/dist/chat/message.d.ts.map +1 -0
  49. package/dist/chat/message.js +221 -0
  50. package/dist/chat/messages.d.ts +30 -0
  51. package/dist/chat/messages.d.ts.map +1 -0
  52. package/dist/chat/messages.js +198 -0
  53. package/dist/chat/name.d.ts +7 -0
  54. package/dist/chat/name.d.ts.map +1 -0
  55. package/dist/chat/name.js +37 -0
  56. package/dist/chat/opened.d.ts +12 -0
  57. package/dist/chat/opened.d.ts.map +1 -0
  58. package/dist/chat/opened.js +19 -0
  59. package/dist/chat/overlay.d.ts +32 -0
  60. package/dist/chat/overlay.d.ts.map +1 -0
  61. package/dist/chat/overlay.js +107 -0
  62. package/dist/chat/parts.d.ts +57 -0
  63. package/dist/chat/parts.d.ts.map +1 -0
  64. package/dist/chat/parts.js +119 -0
  65. package/dist/chat/pieces.d.ts +62 -0
  66. package/dist/chat/pieces.d.ts.map +1 -0
  67. package/dist/chat/pieces.js +1110 -0
  68. package/dist/chat/process.d.ts +20 -0
  69. package/dist/chat/process.d.ts.map +1 -0
  70. package/dist/chat/process.js +32 -0
  71. package/dist/chat/provider.d.ts +66 -0
  72. package/dist/chat/provider.d.ts.map +1 -0
  73. package/dist/chat/provider.js +643 -0
  74. package/dist/chat/question.d.ts +9 -0
  75. package/dist/chat/question.d.ts.map +1 -0
  76. package/dist/chat/question.js +69 -0
  77. package/dist/chat/questions.d.ts +31 -0
  78. package/dist/chat/questions.d.ts.map +1 -0
  79. package/dist/chat/questions.js +111 -0
  80. package/dist/chat/read.d.ts +5 -0
  81. package/dist/chat/read.d.ts.map +1 -0
  82. package/dist/chat/read.js +13 -0
  83. package/dist/chat/ready.d.ts +36 -0
  84. package/dist/chat/ready.d.ts.map +1 -0
  85. package/dist/chat/ready.js +93 -0
  86. package/dist/chat/steady.d.ts +3 -0
  87. package/dist/chat/steady.d.ts.map +1 -0
  88. package/dist/chat/steady.js +26 -0
  89. package/dist/chat/style.d.ts +4 -0
  90. package/dist/chat/style.d.ts.map +1 -0
  91. package/dist/chat/style.js +305 -0
  92. package/dist/chat.d.ts +15 -0
  93. package/dist/chat.d.ts.map +1 -0
  94. package/dist/chat.js +8 -0
  95. package/dist/client.d.ts +29 -13
  96. package/dist/client.d.ts.map +1 -1
  97. package/dist/client.js +47 -18
  98. package/dist/collection.d.ts +23 -13
  99. package/dist/collection.d.ts.map +1 -1
  100. package/dist/collection.js +367 -38
  101. package/dist/connection.d.ts +51 -16
  102. package/dist/connection.d.ts.map +1 -1
  103. package/dist/connection.js +2530 -485
  104. package/dist/conversation.d.ts +37 -10
  105. package/dist/conversation.d.ts.map +1 -1
  106. package/dist/conversation.js +556 -170
  107. package/dist/durability.d.ts +7 -1
  108. package/dist/durability.d.ts.map +1 -1
  109. package/dist/entry.d.ts +17 -0
  110. package/dist/entry.d.ts.map +1 -0
  111. package/dist/entry.js +157 -0
  112. package/dist/expectation.d.ts +21 -0
  113. package/dist/expectation.d.ts.map +1 -0
  114. package/dist/expectation.js +70 -0
  115. package/dist/failure.d.ts +13 -0
  116. package/dist/failure.d.ts.map +1 -0
  117. package/dist/failure.js +19 -0
  118. package/dist/fence.d.ts +6 -0
  119. package/dist/fence.d.ts.map +1 -0
  120. package/dist/fence.js +10 -0
  121. package/dist/host.d.ts +15 -3
  122. package/dist/host.d.ts.map +1 -1
  123. package/dist/host.js +104 -20
  124. package/dist/identity.d.ts +5 -0
  125. package/dist/identity.d.ts.map +1 -1
  126. package/dist/identity.js +19 -1
  127. package/dist/index.d.ts +19 -9
  128. package/dist/index.d.ts.map +1 -1
  129. package/dist/index.js +7 -0
  130. package/dist/memory.d.ts +10 -4
  131. package/dist/memory.d.ts.map +1 -1
  132. package/dist/memory.js +93 -27
  133. package/dist/model.d.ts +7 -4
  134. package/dist/model.d.ts.map +1 -1
  135. package/dist/model.js +10 -1
  136. package/dist/observation.d.ts +7 -2
  137. package/dist/observation.d.ts.map +1 -1
  138. package/dist/observation.js +29 -12
  139. package/dist/open.d.ts +2 -0
  140. package/dist/open.d.ts.map +1 -0
  141. package/dist/open.js +1 -0
  142. package/dist/outcome.d.ts +57 -3
  143. package/dist/outcome.d.ts.map +1 -1
  144. package/dist/outcome.js +67 -1
  145. package/dist/overlay.d.ts +18 -5
  146. package/dist/overlay.d.ts.map +1 -1
  147. package/dist/overlay.js +271 -165
  148. package/dist/query.d.ts +61 -4
  149. package/dist/query.d.ts.map +1 -1
  150. package/dist/query.js +40 -7
  151. package/dist/reach.d.ts +13 -4
  152. package/dist/reach.d.ts.map +1 -1
  153. package/dist/reach.js +197 -47
  154. package/dist/react.d.ts +12 -8
  155. package/dist/react.d.ts.map +1 -1
  156. package/dist/react.js +8 -17
  157. package/dist/read-side.d.ts +18 -9
  158. package/dist/read-side.d.ts.map +1 -1
  159. package/dist/read-side.js +903 -157
  160. package/dist/readiness.d.ts +53 -0
  161. package/dist/readiness.d.ts.map +1 -0
  162. package/dist/readiness.js +33 -0
  163. package/dist/reads.d.ts +11 -0
  164. package/dist/reads.d.ts.map +1 -0
  165. package/dist/reads.js +98 -0
  166. package/dist/recovery.d.ts +25 -0
  167. package/dist/recovery.d.ts.map +1 -0
  168. package/dist/recovery.js +198 -0
  169. package/dist/refresh.d.ts +13 -3
  170. package/dist/refresh.d.ts.map +1 -1
  171. package/dist/refresh.js +73 -43
  172. package/dist/replica.d.ts +16 -8
  173. package/dist/replica.d.ts.map +1 -1
  174. package/dist/replica.js +193 -92
  175. package/dist/room-draft.d.ts +40 -9
  176. package/dist/room-draft.d.ts.map +1 -1
  177. package/dist/room-draft.js +154 -37
  178. package/dist/rows.d.ts +10 -13
  179. package/dist/rows.d.ts.map +1 -1
  180. package/dist/rows.js +19 -14
  181. package/dist/save.d.ts +72 -4
  182. package/dist/save.d.ts.map +1 -1
  183. package/dist/save.js +812 -145
  184. package/dist/search.d.ts +52 -8
  185. package/dist/search.d.ts.map +1 -1
  186. package/dist/search.js +242 -46
  187. package/dist/seed.d.ts +16 -0
  188. package/dist/seed.d.ts.map +1 -0
  189. package/dist/seed.js +75 -0
  190. package/dist/shared.d.ts +19 -0
  191. package/dist/shared.d.ts.map +1 -0
  192. package/dist/shared.js +461 -0
  193. package/dist/status.d.ts +6 -2
  194. package/dist/status.d.ts.map +1 -1
  195. package/dist/status.js +0 -8
  196. package/dist/store.d.ts +90 -20
  197. package/dist/store.d.ts.map +1 -1
  198. package/dist/store.js +705 -288
  199. package/dist/turn.d.ts +9 -0
  200. package/dist/turn.d.ts.map +1 -0
  201. package/dist/turn.js +67 -0
  202. package/dist/windows.d.ts +21 -0
  203. package/dist/windows.d.ts.map +1 -0
  204. package/dist/windows.js +84 -0
  205. package/dist/wire.d.ts +160 -33
  206. package/dist/wire.d.ts.map +1 -1
  207. package/dist/wire.js +65 -31
  208. package/package.json +26 -14
  209. package/dist/attachment.d.ts +0 -3
  210. package/dist/attachment.d.ts.map +0 -1
  211. package/dist/attachment.js +0 -8
package/dist/store.js CHANGED
@@ -1,9 +1,16 @@
1
- import { sameChange } from './overlay.js';
1
+ import { sameBinary, sameChange } from './overlay.js';
2
+ import { differences, keysIn } from './shared.js';
3
+ import { inUnits, ROW_WEIGHT, stepped } from './turn.js';
4
+ import { precedes } from './windows.js';
2
5
  const DATABASE = 'mdruntime';
6
+ const AUTHORED = 'mdruntime-authored';
7
+ const FENCES = 'fences';
3
8
  const ROOMS = 'rooms';
4
9
  const DOCUMENTS = 'documents';
5
- const BINARY_TARGETS = 'binaryTargets';
6
- const ATTACHMENTS = 'attachments';
10
+ const BINARY_FILES = 'binaryFiles';
11
+ const TRANSFERS = 'transfers';
12
+ const RECEIVED = 'received';
13
+ const RECEIVED_PARTS = 'receivedParts';
7
14
  const PENDING_CHANGES = 'pendingChanges';
8
15
  const DECLARATIONS = 'declarations';
9
16
  const ROOM_DRAFTS = 'roomDrafts';
@@ -11,55 +18,242 @@ const PRESENTATION = 'presentation';
11
18
  const CONVERSATIONS = 'conversations';
12
19
  const MESSAGES = 'messages';
13
20
  const CHAT_DRAFTS = 'chatDrafts';
21
+ const CALLS = 'calls';
22
+ const QUEUES = 'queues';
23
+ const FACTS = 'facts';
14
24
  const CURRENT = 'current';
15
25
  const MEMBER = 'member';
16
- export const STORE_SCHEMA = 20;
26
+ const TARGETS = 'targets';
27
+ const GENERATION = 'generation';
28
+ const HOLDER = 'holder';
29
+ const BINDING = 'binding';
30
+ export const STORE_SCHEMA = 25;
31
+ const REPLICA_SHAPE = 23;
32
+ export const AUTHORED_SCHEMA = 3;
33
+ const AUTHORED_STORES = [
34
+ [QUEUES, { keyPath: 'locator' }],
35
+ [PENDING_CHANGES, { keyPath: ['locator', 'id'] }],
36
+ [ROOM_DRAFTS, { keyPath: ['locator', 'path'] }],
37
+ [CHAT_DRAFTS, { keyPath: 'conversation' }],
38
+ [CALLS, { keyPath: 'operation' }],
39
+ [FACTS, undefined],
40
+ [FENCES, { keyPath: 'locator' }],
41
+ ];
42
+ const REPLICA_STORES = [
43
+ [ROOMS, { keyPath: 'locator' }],
44
+ [DOCUMENTS, { keyPath: ['locator', 'transfer', 'path'] }],
45
+ [BINARY_FILES, { keyPath: ['locator', 'transfer', 'path'] }],
46
+ [TRANSFERS, { keyPath: 'locator' }],
47
+ [RECEIVED, { keyPath: 'key' }],
48
+ [RECEIVED_PARTS, { keyPath: ['key', 'index'] }],
49
+ [DECLARATIONS, undefined],
50
+ [PRESENTATION, { keyPath: 'app' }],
51
+ [CONVERSATIONS, { keyPath: 'conversation' }],
52
+ [MESSAGES, { keyPath: ['conversation', 'identity'] }],
53
+ ];
54
+ const READ_BATCH = 256;
55
+ const MESSAGE_INDEXES = [
56
+ ['conversation', 'conversation'],
57
+ ['position', ['conversation', 'position']],
58
+ ['turn', ['conversation', 'turn']],
59
+ ];
17
60
  function settled(request) {
18
61
  return new Promise((resolve, reject) => {
19
62
  request.onsuccess = () => resolve(request.result);
20
63
  request.onerror = () => reject(request.error);
21
64
  });
22
65
  }
23
- function completed(transaction) {
24
- return new Promise((resolve, reject) => {
25
- transaction.oncomplete = () => resolve();
26
- transaction.onerror = () => reject(transaction.error);
27
- transaction.onabort = () => reject(transaction.error);
66
+ const turns = new Map();
67
+ function idle(database) {
68
+ return turns.get(database.name) ?? Promise.resolve();
69
+ }
70
+ export function transacted(database, stores, mode, work) {
71
+ let release = () => { };
72
+ const turn = new Promise((resolve) => {
73
+ release = resolve;
74
+ });
75
+ const before = idle(database);
76
+ const queued = before.then(() => turn);
77
+ turns.set(database.name, queued);
78
+ void queued.then(() => {
79
+ if (turns.get(database.name) === queued)
80
+ turns.delete(database.name);
81
+ });
82
+ return before.then(() => {
83
+ let transaction;
84
+ try {
85
+ transaction = database.transaction(stores, mode);
86
+ }
87
+ catch (error) {
88
+ release();
89
+ throw error;
90
+ }
91
+ const committed = new Promise((resolve, reject) => {
92
+ transaction.oncomplete = () => {
93
+ release();
94
+ resolve();
95
+ };
96
+ transaction.onabort = () => {
97
+ release();
98
+ reject(transaction.error);
99
+ };
100
+ transaction.onerror = () => reject(transaction.error);
101
+ });
102
+ let value;
103
+ try {
104
+ value = work(transaction);
105
+ }
106
+ catch (error) {
107
+ void committed.catch(() => { });
108
+ transaction.abort();
109
+ throw error;
110
+ }
111
+ return Promise.all([value, committed]).then(([held]) => held);
28
112
  });
29
113
  }
30
114
  const EMPTY_DECLARATIONS = {
31
115
  lastCompleted: null,
32
- generation: null,
33
116
  providerLimits: [],
34
117
  capabilities: [],
35
118
  };
36
119
  function declaration(database) {
37
- const transaction = database.transaction(DECLARATIONS, 'readonly');
38
- return settled(transaction.objectStore(DECLARATIONS).get(CURRENT)).then((record) => record ?? EMPTY_DECLARATIONS);
120
+ return transacted(database, DECLARATIONS, 'readonly', (transaction) => settled(transaction.objectStore(DECLARATIONS).get(CURRENT))).then((record) => record ?? EMPTY_DECLARATIONS);
39
121
  }
40
122
  function updateDeclaration(database, update) {
41
- const transaction = database.transaction(DECLARATIONS, 'readwrite');
42
- const store = transaction.objectStore(DECLARATIONS);
43
- const prior = store.get(CURRENT);
44
- prior.onsuccess = () => {
45
- store.put(update(prior.result ?? EMPTY_DECLARATIONS), CURRENT);
46
- };
47
- return completed(transaction);
123
+ return transacted(database, DECLARATIONS, 'readwrite', (transaction) => {
124
+ const store = transaction.objectStore(DECLARATIONS);
125
+ const prior = store.get(CURRENT);
126
+ prior.onsuccess = () => {
127
+ store.put(update(prior.result ?? EMPTY_DECLARATIONS), CURRENT);
128
+ };
129
+ });
48
130
  }
49
131
  function amendPending(database, locator, id, amendment) {
50
- const transaction = database.transaction(PENDING_CHANGES, 'readwrite');
51
- const pending = transaction.objectStore(PENDING_CHANGES);
52
- const request = pending.get([locator, id]);
53
- request.onsuccess = () => {
54
- const record = request.result;
55
- if (record !== undefined)
56
- pending.put({ ...record, ...amendment });
132
+ return transacted(database, PENDING_CHANGES, 'readwrite', (transaction) => {
133
+ const pending = transaction.objectStore(PENDING_CHANGES);
134
+ const request = pending.get([locator, id]);
135
+ request.onsuccess = () => {
136
+ const record = request.result;
137
+ if (record !== undefined)
138
+ pending.put({ ...record, ...amendment });
139
+ };
140
+ });
141
+ }
142
+ function accepted({ conversation: _held, ...message }) {
143
+ return message;
144
+ }
145
+ function roomRecord(record) {
146
+ const { documents, binaries, revisions, fileIds, changes, written, ...room } = record;
147
+ return room;
148
+ }
149
+ function chatDraftRecord(record) {
150
+ return { ...record, revision: record.revision ?? '' };
151
+ }
152
+ function underTransfer(locator, transfer, after) {
153
+ return after === undefined
154
+ ? IDBKeyRange.bound([locator, transfer], [locator, transfer, []])
155
+ : IDBKeyRange.bound([locator, transfer, after], [locator, transfer, []], true);
156
+ }
157
+ function underRoom(locator) {
158
+ return IDBKeyRange.bound([locator], [locator, []]);
159
+ }
160
+ async function readTransfer(store, locator, transfer, receive) {
161
+ let range = underTransfer(locator, transfer);
162
+ for (;;) {
163
+ const batch = await settled(store.getAll(range, READ_BATCH));
164
+ for (const record of batch)
165
+ receive(record);
166
+ if (batch.length < READ_BATCH)
167
+ return;
168
+ range = underTransfer(locator, transfer, batch[batch.length - 1].path);
169
+ }
170
+ }
171
+ function emptyLayer() {
172
+ return { documents: {}, binaries: {}, revisions: {}, fileIds: {}, changes: {}, written: {} };
173
+ }
174
+ async function readLayer(transaction, locator, transfer) {
175
+ const layer = emptyLayer();
176
+ const head = (held) => {
177
+ if (held.revision !== null)
178
+ layer.revisions[held.path] = held.revision;
179
+ if (held.fileId !== null)
180
+ layer.fileIds[held.path] = held.fileId;
181
+ if (held.change !== null)
182
+ layer.changes[held.path] = held.change;
57
183
  };
58
- return completed(transaction);
184
+ await readTransfer(transaction.objectStore(DOCUMENTS), locator, transfer, (document) => {
185
+ layer.documents[document.path] = document.content;
186
+ if (document.written !== null)
187
+ layer.written[document.path] = document.written;
188
+ head(document);
189
+ });
190
+ await readTransfer(transaction.objectStore(BINARY_FILES), locator, transfer, (file) => {
191
+ layer.binaries[file.path] = file.binary;
192
+ head(file);
193
+ });
194
+ return layer;
59
195
  }
60
- function roomRecord(record, queue) {
61
- const { documents, binaryTargets, revisions, changes, written, attachments, ...room } = record;
62
- return { ...room, order: queue.map((batch) => batch.id) };
196
+ function documentRecord(locator, transfer, layer, path) {
197
+ return {
198
+ locator,
199
+ transfer,
200
+ path,
201
+ content: layer.documents[path],
202
+ revision: layer.revisions[path] ?? null,
203
+ fileId: layer.fileIds[path] ?? null,
204
+ change: layer.changes[path] ?? null,
205
+ written: layer.written[path] ?? null,
206
+ };
207
+ }
208
+ function binaryFileRecord(locator, transfer, layer, path) {
209
+ return {
210
+ locator,
211
+ transfer,
212
+ path,
213
+ revision: layer.revisions[path] ?? null,
214
+ fileId: layer.fileIds[path] ?? null,
215
+ change: layer.changes[path] ?? null,
216
+ binary: layer.binaries[path],
217
+ };
218
+ }
219
+ function* changedIn(next, base) {
220
+ if (base === null)
221
+ return yield* keysIn(next.documents, next.binaries);
222
+ return new Set([
223
+ ...(yield* differences(base.documents, next.documents)),
224
+ ...(yield* differences(base.revisions, next.revisions)),
225
+ ...(yield* differences(base.fileIds, next.fileIds)),
226
+ ...(yield* differences(base.written, next.written)),
227
+ ...(yield* differences(base.changes, next.changes, sameChange)),
228
+ ...(yield* differences(base.binaries, next.binaries, sameBinary)),
229
+ ]);
230
+ }
231
+ function writeLayer(transaction, locator, transfer, layer) {
232
+ const { next, base, paths } = layer;
233
+ const documents = transaction.objectStore(DOCUMENTS);
234
+ const files = transaction.objectStore(BINARY_FILES);
235
+ let last = null;
236
+ return inUnits(paths, (path) => {
237
+ if (next.documents[path] !== undefined) {
238
+ last = documents.put(documentRecord(locator, transfer, next, path));
239
+ }
240
+ else if (base?.documents[path] !== undefined) {
241
+ last = documents.delete([locator, transfer, path]);
242
+ }
243
+ if (next.binaries[path] !== undefined) {
244
+ last = files.put(binaryFileRecord(locator, transfer, next, path));
245
+ }
246
+ else if (base?.binaries[path] !== undefined) {
247
+ last = files.delete([locator, transfer, path]);
248
+ }
249
+ return ROW_WEIGHT + (next.documents[path]?.length ?? 0);
250
+ }, () => { }, () => {
251
+ const request = last;
252
+ last = null;
253
+ return request === null
254
+ ? Promise.resolve()
255
+ : new Promise((resolve) => request.addEventListener('success', () => resolve()));
256
+ });
63
257
  }
64
258
  function removeRoomEntries(store, locator) {
65
259
  const keys = store.getAllKeys();
@@ -70,179 +264,220 @@ function removeRoomEntries(store, locator) {
70
264
  }
71
265
  };
72
266
  }
73
- export function removeRuntimeStore() {
267
+ function removeDatabase(name) {
74
268
  return new Promise((resolve, reject) => {
75
- const removal = indexedDB.deleteDatabase(DATABASE);
269
+ const removal = indexedDB.deleteDatabase(name);
76
270
  removal.onsuccess = () => resolve();
77
271
  removal.onerror = () => reject(removal.error);
78
272
  });
79
273
  }
80
- export async function openRuntimeStore() {
81
- const opening = indexedDB.open(DATABASE, STORE_SCHEMA);
82
- opening.onupgradeneeded = () => {
83
- const database = opening.result;
84
- for (const name of [...database.objectStoreNames])
85
- database.deleteObjectStore(name);
86
- database.createObjectStore(ROOMS, { keyPath: 'locator' });
87
- database.createObjectStore(DOCUMENTS, { keyPath: ['locator', 'path'] });
88
- database.createObjectStore(BINARY_TARGETS, { keyPath: ['locator', 'path'] });
89
- database.createObjectStore(ATTACHMENTS, { keyPath: ['locator', 'reference'] });
90
- database.createObjectStore(PENDING_CHANGES, { keyPath: ['locator', 'id'] });
91
- database.createObjectStore(DECLARATIONS);
92
- database.createObjectStore(ROOM_DRAFTS, { keyPath: ['locator', 'path'] });
93
- database.createObjectStore(PRESENTATION, { keyPath: 'app' });
94
- database.createObjectStore(CONVERSATIONS, { keyPath: 'conversation' });
95
- const messages = database.createObjectStore(MESSAGES, {
96
- keyPath: ['conversation', 'identity'],
97
- });
98
- messages.createIndex('conversation', 'conversation');
99
- database.createObjectStore(CHAT_DRAFTS, { keyPath: 'conversation' });
100
- };
101
- const database = await settled(opening);
102
- return {
103
- async all() {
104
- const transaction = database.transaction([ROOMS, DOCUMENTS, BINARY_TARGETS, ATTACHMENTS], 'readonly');
105
- const [rooms, documents, targets, attachments] = await Promise.all([
106
- settled(transaction.objectStore(ROOMS).getAll()),
107
- settled(transaction.objectStore(DOCUMENTS).getAll()),
108
- settled(transaction.objectStore(BINARY_TARGETS).getAll()),
109
- settled(transaction.objectStore(ATTACHMENTS).getAll()),
110
- ]);
111
- const byRoom = new Map();
112
- for (const { order, ...room } of rooms) {
113
- byRoom.set(room.locator, {
114
- ...room,
115
- documents: {},
116
- revisions: {},
117
- changes: {},
118
- written: {},
119
- binaryTargets: [],
120
- attachments: [],
121
- });
122
- }
123
- const head = (room, held) => {
124
- if (held.revision !== null) {
125
- room.revisions[held.path] = held.revision;
126
- }
127
- if (held.change !== null) {
128
- room.changes[held.path] = held.change;
129
- }
274
+ export async function authoredHolder() {
275
+ const authored = await openAuthored();
276
+ try {
277
+ const held = await transacted(authored, FACTS, 'readonly', (transaction) => settled(transaction.objectStore(FACTS).get(HOLDER)));
278
+ return typeof held === 'string' ? held : null;
279
+ }
280
+ finally {
281
+ authored.close();
282
+ }
283
+ }
284
+ export async function authoredBy(holder) {
285
+ const authored = await openAuthored();
286
+ try {
287
+ let owned = true;
288
+ await transacted(authored, FACTS, 'readwrite', (transaction) => {
289
+ const facts = transaction.objectStore(FACTS);
290
+ const held = facts.get(HOLDER);
291
+ held.onsuccess = () => {
292
+ if (held.result === undefined)
293
+ facts.put(holder, HOLDER);
294
+ else
295
+ owned = held.result === holder;
130
296
  };
131
- for (const document of documents) {
132
- const room = byRoom.get(document.locator);
133
- if (room === undefined)
134
- continue;
135
- room.documents[document.path] = document.content;
136
- if (document.written !== null) {
137
- room.written[document.path] = document.written;
138
- }
139
- head(room, document);
140
- }
141
- for (const target of targets) {
142
- const room = byRoom.get(target.locator);
143
- if (room === undefined)
144
- continue;
145
- room.binaryTargets.push(target.path);
146
- head(room, target);
147
- }
148
- for (const { locator, ...attachment } of attachments) {
149
- const room = byRoom.get(locator);
150
- if (room === undefined)
151
- continue;
152
- room.attachments.push(attachment);
153
- }
154
- return [...byRoom.values()];
155
- },
156
- async write({ next, previous, queue, previousQueue, saved, roomDrafts, consumedRoomDrafts }) {
157
- const transaction = database.transaction([ROOMS, DOCUMENTS, BINARY_TARGETS, ATTACHMENTS, PENDING_CHANGES, ROOM_DRAFTS], 'readwrite');
158
- transaction.objectStore(ROOMS).put(roomRecord(next, queue));
159
- const documents = transaction.objectStore(DOCUMENTS);
160
- for (const path of Object.keys(previous?.documents ?? {})) {
161
- if (next.documents[path] === undefined)
162
- documents.delete([next.locator, path]);
297
+ });
298
+ return owned;
299
+ }
300
+ finally {
301
+ authored.close();
302
+ }
303
+ }
304
+ export async function authoredBinding() {
305
+ const authored = await openAuthored();
306
+ try {
307
+ const held = await transacted(authored, FACTS, 'readonly', (transaction) => settled(transaction.objectStore(FACTS).get(BINDING)));
308
+ return typeof held === 'string' ? held : null;
309
+ }
310
+ finally {
311
+ authored.close();
312
+ }
313
+ }
314
+ export async function bindAuthored(binding) {
315
+ const authored = await openAuthored();
316
+ try {
317
+ await transacted(authored, FACTS, 'readwrite', (transaction) => {
318
+ transaction.objectStore(FACTS).put(binding, BINDING);
319
+ });
320
+ }
321
+ finally {
322
+ authored.close();
323
+ }
324
+ }
325
+ export async function removeRuntimeStore(holder) {
326
+ await removeDatabase(DATABASE);
327
+ if (holder !== undefined && (await authoredBy(holder)))
328
+ return true;
329
+ await removeDatabase(AUTHORED);
330
+ return false;
331
+ }
332
+ export function openDatabase(name, version, upgrade) {
333
+ return new Promise((resolve, reject) => {
334
+ const opening = indexedDB.open(name, version);
335
+ opening.onupgradeneeded = (event) => upgrade(opening, event.oldVersion);
336
+ opening.onsuccess = () => resolve(opening.result);
337
+ opening.onerror = () => {
338
+ if (opening.error?.name !== 'VersionError') {
339
+ reject(opening.error);
340
+ return;
163
341
  }
164
- for (const [path, content] of Object.entries(next.documents)) {
165
- if (previous?.documents[path] === content &&
166
- previous.revisions[path] === next.revisions[path] &&
167
- previous.written[path] === next.written[path] &&
168
- sameChange(previous.changes[path], next.changes[path]))
169
- continue;
170
- documents.put({
171
- locator: next.locator,
172
- path,
173
- content,
174
- revision: next.revisions[path] ?? null,
175
- change: next.changes[path] ?? null,
176
- written: next.written[path] ?? null,
342
+ removeDatabase(name)
343
+ .then(() => openDatabase(name, version, upgrade))
344
+ .then(resolve, reject);
345
+ };
346
+ });
347
+ }
348
+ function openReplica() {
349
+ return openDatabase(DATABASE, STORE_SCHEMA, (opening, oldVersion) => {
350
+ const database = opening.result;
351
+ if (oldVersion < REPLICA_SHAPE) {
352
+ for (const name of [...database.objectStoreNames])
353
+ database.deleteObjectStore(name);
354
+ }
355
+ for (const [name, parameters] of REPLICA_STORES) {
356
+ if (database.objectStoreNames.contains(name))
357
+ continue;
358
+ database.createObjectStore(name, parameters);
359
+ }
360
+ const messages = opening.transaction.objectStore(MESSAGES);
361
+ for (const [name, keyPath] of MESSAGE_INDEXES) {
362
+ if (!messages.indexNames.contains(name))
363
+ messages.createIndex(name, keyPath);
364
+ }
365
+ });
366
+ }
367
+ function openAuthored() {
368
+ return openDatabase(AUTHORED, AUTHORED_SCHEMA, (opening) => {
369
+ const database = opening.result;
370
+ for (const [name, parameters] of AUTHORED_STORES) {
371
+ if (!database.objectStoreNames.contains(name))
372
+ database.createObjectStore(name, parameters);
373
+ }
374
+ });
375
+ }
376
+ function authoredIn(transaction, { locator, queue, founded, saved, roomDrafts, consumedRoomDrafts }) {
377
+ const draftStore = transaction.objectStore(ROOM_DRAFTS);
378
+ for (const path of consumedRoomDrafts ?? [])
379
+ draftStore.delete([locator, path]);
380
+ for (const record of roomDrafts ?? [])
381
+ draftStore.put(record);
382
+ if (queue === undefined)
383
+ return;
384
+ const order = transaction.objectStore(QUEUES);
385
+ const pending = transaction.objectStore(PENDING_CHANGES);
386
+ const held = order.get(locator);
387
+ held.onsuccess = () => {
388
+ const before = new Set(held.result?.order ?? []);
389
+ const after = new Set(queue.map((batch) => batch.id));
390
+ if (queue.length === 0)
391
+ order.delete(locator);
392
+ else
393
+ order.put({ locator, order: [...after] });
394
+ for (const id of before) {
395
+ if (!after.has(id))
396
+ pending.delete([locator, id]);
397
+ }
398
+ for (const batch of queue) {
399
+ if (!before.has(batch.id)) {
400
+ pending.put({
401
+ locator,
402
+ id: batch.id,
403
+ batch,
404
+ drafts: saved?.get(batch.id) ?? [],
405
+ submission: { state: 'waiting' },
406
+ lost: false,
177
407
  });
178
408
  }
179
- const targets = transaction.objectStore(BINARY_TARGETS);
180
- const beforeTargets = new Set(previous?.binaryTargets ?? []);
181
- const afterTargets = new Set(next.binaryTargets);
182
- for (const path of beforeTargets) {
183
- if (!afterTargets.has(path))
184
- targets.delete([next.locator, path]);
185
- }
186
- for (const path of afterTargets) {
187
- if (!beforeTargets.has(path) ||
188
- previous?.revisions[path] !== next.revisions[path] ||
189
- !sameChange(previous?.changes[path], next.changes[path])) {
190
- targets.put({
191
- locator: next.locator,
192
- path,
193
- revision: next.revisions[path] ?? null,
194
- change: next.changes[path] ?? null,
409
+ }
410
+ for (const batch of founded ?? []) {
411
+ if (!before.has(batch.id))
412
+ continue;
413
+ const stored = pending.get([locator, batch.id]);
414
+ stored.onsuccess = () => {
415
+ const record = stored.result;
416
+ if (record !== undefined)
417
+ pending.put({ ...record, batch });
418
+ };
419
+ }
420
+ };
421
+ }
422
+ export async function openRuntimeStore(fenced) {
423
+ const authored = await openAuthored();
424
+ const database = await openReplica().catch((error) => {
425
+ authored.close();
426
+ throw error;
427
+ });
428
+ return {
429
+ all() {
430
+ return transacted(database, [ROOMS, DOCUMENTS, BINARY_FILES], 'readonly', async (transaction) => {
431
+ const rooms = await settled(transaction.objectStore(ROOMS).getAll());
432
+ const records = [];
433
+ for (const room of rooms.filter((held) => !fenced(held.locator))) {
434
+ records.push({
435
+ ...room,
436
+ ...(await readLayer(transaction, room.locator, room.transfer)),
195
437
  });
196
438
  }
197
- }
198
- const attachments = transaction.objectStore(ATTACHMENTS);
199
- const held = new Map((previous?.attachments ?? []).map((attachment) => [attachment.reference, attachment]));
200
- const declared = new Set(next.attachments.map((attachment) => attachment.reference));
201
- for (const reference of held.keys()) {
202
- if (!declared.has(reference))
203
- attachments.delete([next.locator, reference]);
204
- }
205
- for (const attachment of next.attachments) {
206
- if (held.get(attachment.reference) === attachment)
207
- continue;
208
- attachments.put({ ...attachment, locator: next.locator });
209
- }
210
- if (previousQueue !== undefined) {
211
- const pending = transaction.objectStore(PENDING_CHANGES);
212
- const before = new Set(previousQueue.map((batch) => batch.id));
213
- const after = new Set(queue.map((batch) => batch.id));
214
- for (const id of before) {
215
- if (!after.has(id))
216
- pending.delete([next.locator, id]);
217
- }
218
- for (const batch of queue) {
219
- if (!before.has(batch.id)) {
220
- pending.put({
221
- locator: next.locator,
222
- id: batch.id,
223
- batch,
224
- drafts: saved ?? [],
225
- submission: { state: 'waiting' },
226
- lost: false,
227
- });
228
- }
439
+ return records;
440
+ });
441
+ },
442
+ async keepAuthored(...writes) {
443
+ const kept = writes.filter(({ locator }) => !fenced(locator));
444
+ if (kept.length === 0)
445
+ return;
446
+ await transacted(authored, [QUEUES, PENDING_CHANGES, ROOM_DRAFTS], 'readwrite', (transaction) => {
447
+ for (const write of kept)
448
+ authoredIn(transaction, write);
449
+ });
450
+ },
451
+ async write({ next, previous, stored }) {
452
+ if (next === previous || fenced(next.locator))
453
+ return;
454
+ const moved = previous?.transfer !== next.transfer;
455
+ const base = moved ? (stored ?? null) : previous;
456
+ const paths = await stepped(changedIn(next, base));
457
+ if (fenced(next.locator))
458
+ return;
459
+ await transacted(database, [ROOMS, DOCUMENTS, BINARY_FILES, TRANSFERS], 'readwrite', (transaction) => {
460
+ transaction.objectStore(ROOMS).put(roomRecord(next));
461
+ if (moved && previous !== null) {
462
+ const range = underTransfer(previous.locator, previous.transfer);
463
+ transaction.objectStore(DOCUMENTS).delete(range);
464
+ transaction.objectStore(BINARY_FILES).delete(range);
229
465
  }
230
- }
231
- const draftStore = transaction.objectStore(ROOM_DRAFTS);
232
- for (const path of consumedRoomDrafts ?? [])
233
- draftStore.delete([next.locator, path]);
234
- for (const record of roomDrafts ?? [])
235
- draftStore.put(record);
236
- await completed(transaction);
466
+ if (moved)
467
+ transaction.objectStore(TRANSFERS).delete(next.locator);
468
+ return writeLayer(transaction, next.locator, next.transfer, { next, base, paths });
469
+ });
237
470
  },
238
471
  async revokeModels(records) {
239
- const transaction = database.transaction(ROOMS, 'readwrite');
240
- const rooms = transaction.objectStore(ROOMS);
241
- const revoked = { status: 'unavailable', reason: 'revoked' };
242
- for (const { record, queue } of records) {
243
- rooms.put(roomRecord({ ...record, model: revoked, selectionModel: revoked }, queue));
244
- }
245
- await completed(transaction);
472
+ await transacted(database, ROOMS, 'readwrite', (transaction) => {
473
+ const rooms = transaction.objectStore(ROOMS);
474
+ const revoked = { status: 'unavailable', reason: 'revoked' };
475
+ for (const record of records) {
476
+ if (fenced(record.locator))
477
+ continue;
478
+ rooms.put(roomRecord({ ...record, model: revoked, selectionModel: revoked }));
479
+ }
480
+ });
246
481
  },
247
482
  async lastCompleted() {
248
483
  return (await declaration(database)).lastCompleted;
@@ -264,143 +499,325 @@ export async function openRuntimeStore() {
264
499
  }));
265
500
  },
266
501
  async member() {
267
- const transaction = database.transaction(DECLARATIONS, 'readonly');
268
- const held = await settled(transaction.objectStore(DECLARATIONS).get(MEMBER));
502
+ const held = await transacted(database, DECLARATIONS, 'readonly', (transaction) => settled(transaction.objectStore(DECLARATIONS).get(MEMBER)));
269
503
  return held ?? null;
270
504
  },
271
505
  async keepMember(member) {
272
- const transaction = database.transaction(DECLARATIONS, 'readwrite');
273
- transaction.objectStore(DECLARATIONS).put(member, MEMBER);
274
- await completed(transaction);
506
+ await transacted(database, DECLARATIONS, 'readwrite', (transaction) => {
507
+ transaction.objectStore(DECLARATIONS).put(member, MEMBER);
508
+ });
509
+ },
510
+ async targets() {
511
+ const held = await transacted(database, DECLARATIONS, 'readonly', (transaction) => settled(transaction.objectStore(DECLARATIONS).get(TARGETS)));
512
+ return held ?? {};
513
+ },
514
+ async keepTargets(targets) {
515
+ await transacted(database, DECLARATIONS, 'readwrite', (transaction) => {
516
+ transaction.objectStore(DECLARATIONS).put(targets, TARGETS);
517
+ });
275
518
  },
276
519
  async queues() {
277
- const transaction = database.transaction([ROOMS, PENDING_CHANGES], 'readonly');
278
- const [rooms, pending] = await Promise.all([
279
- settled(transaction.objectStore(ROOMS).getAll()),
520
+ const [queues, pending] = await transacted(authored, [QUEUES, PENDING_CHANGES], 'readonly', (transaction) => Promise.all([
521
+ settled(transaction.objectStore(QUEUES).getAll()),
280
522
  settled(transaction.objectStore(PENDING_CHANGES).getAll()),
281
- ]);
523
+ ]));
282
524
  const byId = new Map(pending.map((record) => [`${record.locator}\0${record.id}`, record]));
283
- return rooms.map((room) => ({
284
- locator: room.locator,
285
- pending: room.order.map((id) => {
286
- const record = byId.get(`${room.locator}\0${id}`);
525
+ return queues
526
+ .filter((queue) => !fenced(queue.locator))
527
+ .map((queue) => ({
528
+ locator: queue.locator,
529
+ pending: queue.order.map((id) => {
530
+ const record = byId.get(`${queue.locator}\0${id}`);
287
531
  if (record === undefined)
288
- throw new Error(`Missing Pending Change ${room.locator}/${id}`);
532
+ throw new Error(`Missing Pending Change ${queue.locator}/${id}`);
289
533
  const { batch, drafts, submission, lost, upload, accepted } = record;
290
534
  return { batch, state: { drafts, submission, lost, upload, accepted } };
291
535
  }),
292
536
  }));
293
537
  },
294
- submit(locator, id, submission, lost) {
295
- return amendPending(database, locator, id, { submission, lost });
538
+ async submit(locator, id, submission, lost) {
539
+ if (!fenced(locator))
540
+ await amendPending(authored, locator, id, { submission, lost });
296
541
  },
297
- accept(locator, id, roomVersion) {
298
- return amendPending(database, locator, id, { accepted: roomVersion });
542
+ async accept(locator, id, roomVersion) {
543
+ if (!fenced(locator))
544
+ await amendPending(authored, locator, id, { accepted: roomVersion });
299
545
  },
300
- keepUpload(locator, id, upload) {
301
- return amendPending(database, locator, id, { upload });
546
+ async keepUpload(locator, id, upload) {
547
+ if (!fenced(locator))
548
+ await amendPending(authored, locator, id, { upload });
302
549
  },
303
550
  async roomDrafts() {
304
- const transaction = database.transaction(ROOM_DRAFTS, 'readonly');
305
- return settled(transaction.objectStore(ROOM_DRAFTS).getAll());
551
+ const held = await transacted(authored, ROOM_DRAFTS, 'readonly', (transaction) => settled(transaction.objectStore(ROOM_DRAFTS).getAll()));
552
+ return held.filter((record) => !fenced(record.locator));
306
553
  },
307
- async presentation() {
308
- const transaction = database.transaction(PRESENTATION, 'readonly');
309
- return settled(transaction.objectStore(PRESENTATION).getAll());
554
+ presentation() {
555
+ return transacted(database, PRESENTATION, 'readonly', (transaction) => settled(transaction.objectStore(PRESENTATION).getAll()));
310
556
  },
311
557
  async present(record) {
312
- const transaction = database.transaction(PRESENTATION, 'readwrite');
313
- transaction.objectStore(PRESENTATION).put(record);
314
- await completed(transaction);
315
- },
316
- async conversations() {
317
- const transaction = database.transaction([CONVERSATIONS, MESSAGES], 'readonly');
318
- const [reads, messages] = await Promise.all([
319
- settled(transaction.objectStore(CONVERSATIONS).getAll()),
320
- settled(transaction.objectStore(MESSAGES).getAll()),
321
- ]);
322
- const held = new Map();
323
- for (const { conversation, read } of reads) {
324
- held.set(conversation, { conversation, read, messages: [] });
325
- }
326
- for (const { conversation, ...message } of messages) {
327
- const entry = held.get(conversation) ?? { conversation, read: undefined, messages: [] };
328
- entry.messages.push(message);
329
- held.set(conversation, entry);
330
- }
331
- return [...held.values()];
558
+ await transacted(database, PRESENTATION, 'readwrite', (transaction) => {
559
+ transaction.objectStore(PRESENTATION).put(record);
560
+ });
332
561
  },
333
- async keepMessages({ conversation, messages, read, sealed }) {
334
- const transaction = database.transaction([CONVERSATIONS, MESSAGES, CHAT_DRAFTS], 'readwrite');
335
- const stored = transaction.objectStore(MESSAGES);
336
- for (const message of messages) {
337
- stored.put({ ...message, conversation });
338
- }
339
- if (read !== undefined) {
340
- transaction
341
- .objectStore(CONVERSATIONS)
342
- .put({ conversation, read });
343
- }
344
- if (sealed === true)
345
- transaction.objectStore(CHAT_DRAFTS).delete(conversation);
346
- await completed(transaction);
562
+ conversations() {
563
+ return transacted(database, [CONVERSATIONS, MESSAGES], 'readonly', async (transaction) => {
564
+ const records = await settled(transaction.objectStore(CONVERSATIONS).getAll());
565
+ const held = new Map(records.map(({ conversation, read, partial }) => [
566
+ conversation,
567
+ { conversation, read, partial: partial === true },
568
+ ]));
569
+ const keys = transaction.objectStore(MESSAGES).index('conversation');
570
+ await new Promise((resolve, reject) => {
571
+ const cursor = keys.openKeyCursor(null, 'nextunique');
572
+ cursor.onerror = () => reject(cursor.error);
573
+ cursor.onsuccess = () => {
574
+ const at = cursor.result;
575
+ if (at === null) {
576
+ resolve();
577
+ return;
578
+ }
579
+ const conversation = at.key;
580
+ if (!held.has(conversation)) {
581
+ held.set(conversation, { conversation, read: undefined, partial: true });
582
+ }
583
+ at.continue();
584
+ };
585
+ });
586
+ return [...held.values()];
587
+ });
588
+ },
589
+ async keepMessages({ conversation, messages, read }) {
590
+ await transacted(database, [CONVERSATIONS, MESSAGES], 'readwrite', (transaction) => {
591
+ const stored = transaction.objectStore(MESSAGES);
592
+ for (const message of messages) {
593
+ stored.put({ ...message, conversation });
594
+ }
595
+ if (read !== undefined) {
596
+ transaction.objectStore(CONVERSATIONS).put({
597
+ conversation,
598
+ read: read.at,
599
+ ...(read.partial ? { partial: true } : {}),
600
+ });
601
+ }
602
+ });
603
+ },
604
+ messageWindow(conversation, limit, before) {
605
+ return transacted(database, MESSAGES, 'readonly', async (transaction) => {
606
+ const index = transaction.objectStore(MESSAGES).index('position');
607
+ const range = IDBKeyRange.bound([conversation], [conversation, before?.[0] ?? []]);
608
+ const latest = [];
609
+ let more = false;
610
+ await new Promise((resolve, reject) => {
611
+ const cursor = index.openCursor(range, 'prev');
612
+ cursor.onerror = () => reject(cursor.error);
613
+ cursor.onsuccess = () => {
614
+ const at = cursor.result;
615
+ if (at === null) {
616
+ resolve();
617
+ return;
618
+ }
619
+ const record = at.value;
620
+ if (!precedes(record, before)) {
621
+ at.continue();
622
+ return;
623
+ }
624
+ if (latest.length === limit) {
625
+ more = true;
626
+ resolve();
627
+ return;
628
+ }
629
+ latest.push(accepted(record));
630
+ at.continue();
631
+ };
632
+ });
633
+ return { messages: latest.reverse(), more };
634
+ });
635
+ },
636
+ messageCount(conversation) {
637
+ return transacted(database, MESSAGES, 'readonly', (transaction) => settled(transaction.objectStore(MESSAGES).index('conversation').count(conversation)));
638
+ },
639
+ async messagesAfter(conversation, identity) {
640
+ const range = identity === null
641
+ ? IDBKeyRange.bound([conversation], [conversation, []])
642
+ : IDBKeyRange.bound([conversation, identity], [conversation, []], true);
643
+ const held = await transacted(database, MESSAGES, 'readonly', (transaction) => settled(transaction.objectStore(MESSAGES).getAll(range, READ_BATCH)));
644
+ return held.map(accepted);
645
+ },
646
+ async messageIdentities(conversation) {
647
+ const keys = await transacted(database, MESSAGES, 'readonly', (transaction) => settled(transaction.objectStore(MESSAGES).index('conversation').getAllKeys(conversation)));
648
+ return keys.map((key) => key[1]);
649
+ },
650
+ async turnArrived(conversation, turn) {
651
+ const held = await transacted(database, MESSAGES, 'readonly', (transaction) => settled(transaction.objectStore(MESSAGES).index('turn').count([conversation, turn])));
652
+ return held > 0;
347
653
  },
348
654
  async dropConversations(conversations) {
349
- const transaction = database.transaction([CONVERSATIONS, MESSAGES, CHAT_DRAFTS], 'readwrite');
350
- const messages = transaction.objectStore(MESSAGES);
351
- for (const conversation of conversations) {
352
- transaction.objectStore(CONVERSATIONS).delete(conversation);
353
- transaction.objectStore(CHAT_DRAFTS).delete(conversation);
354
- const keys = messages.index('conversation').getAllKeys(conversation);
355
- keys.onsuccess = () => {
356
- for (const key of keys.result)
357
- messages.delete(key);
358
- };
359
- }
360
- await completed(transaction);
655
+ await transacted(authored, CHAT_DRAFTS, 'readwrite', (drafts) => {
656
+ for (const conversation of conversations)
657
+ drafts.objectStore(CHAT_DRAFTS).delete(conversation);
658
+ });
659
+ await transacted(database, [CONVERSATIONS, MESSAGES], 'readwrite', (transaction) => {
660
+ const messages = transaction.objectStore(MESSAGES);
661
+ for (const conversation of conversations) {
662
+ transaction.objectStore(CONVERSATIONS).delete(conversation);
663
+ const keys = messages.index('conversation').getAllKeys(conversation);
664
+ keys.onsuccess = () => {
665
+ for (const key of keys.result)
666
+ messages.delete(key);
667
+ };
668
+ }
669
+ });
361
670
  },
362
671
  async chatDrafts() {
363
- const transaction = database.transaction(CHAT_DRAFTS, 'readonly');
364
- return settled(transaction.objectStore(CHAT_DRAFTS).getAll());
672
+ const held = await transacted(authored, CHAT_DRAFTS, 'readonly', (transaction) => settled(transaction.objectStore(CHAT_DRAFTS).getAll()));
673
+ return held.map(chatDraftRecord);
365
674
  },
366
- async keepChatDraft(record) {
367
- const transaction = database.transaction(CHAT_DRAFTS, 'readwrite');
368
- transaction.objectStore(CHAT_DRAFTS).put(record);
369
- await completed(transaction);
675
+ async keepChatDrafts(records) {
676
+ await transacted(authored, CHAT_DRAFTS, 'readwrite', (transaction) => {
677
+ for (const record of records)
678
+ transaction.objectStore(CHAT_DRAFTS).put(record);
679
+ });
370
680
  },
371
681
  async dropChatDraft(conversation) {
372
- const transaction = database.transaction(CHAT_DRAFTS, 'readwrite');
373
- transaction.objectStore(CHAT_DRAFTS).delete(conversation);
374
- await completed(transaction);
682
+ await transacted(authored, CHAT_DRAFTS, 'readwrite', (transaction) => {
683
+ transaction.objectStore(CHAT_DRAFTS).delete(conversation);
684
+ });
685
+ },
686
+ calls() {
687
+ return transacted(authored, CALLS, 'readonly', (transaction) => settled(transaction.objectStore(CALLS).getAll()));
688
+ },
689
+ async keepCall(record) {
690
+ await transacted(authored, CALLS, 'readwrite', (transaction) => {
691
+ transaction.objectStore(CALLS).put(record);
692
+ });
693
+ },
694
+ async dropCall(operation) {
695
+ await transacted(authored, CALLS, 'readwrite', (transaction) => {
696
+ transaction.objectStore(CALLS).delete(operation);
697
+ });
375
698
  },
376
699
  async keepRoomDraft(record) {
377
- const transaction = database.transaction(ROOM_DRAFTS, 'readwrite');
378
- transaction.objectStore(ROOM_DRAFTS).put(record);
379
- await completed(transaction);
700
+ if (fenced(record.locator))
701
+ return;
702
+ await transacted(authored, ROOM_DRAFTS, 'readwrite', (transaction) => {
703
+ transaction.objectStore(ROOM_DRAFTS).put(record);
704
+ });
380
705
  },
381
706
  async discardRoomDraft(locator, path) {
382
- const transaction = database.transaction(ROOM_DRAFTS, 'readwrite');
383
- transaction.objectStore(ROOM_DRAFTS).delete([locator, path]);
384
- await completed(transaction);
385
- },
386
- async dropRooms(locators) {
387
- const transaction = database.transaction([ROOMS, DOCUMENTS, BINARY_TARGETS, ATTACHMENTS, PENDING_CHANGES, ROOM_DRAFTS], 'readwrite');
388
- for (const locator of locators) {
389
- transaction.objectStore(ROOMS).delete(locator);
390
- for (const name of [DOCUMENTS, BINARY_TARGETS, ATTACHMENTS, PENDING_CHANGES, ROOM_DRAFTS]) {
391
- removeRoomEntries(transaction.objectStore(name), locator);
707
+ if (fenced(locator))
708
+ return;
709
+ await transacted(authored, ROOM_DRAFTS, 'readwrite', (transaction) => {
710
+ transaction.objectStore(ROOM_DRAFTS).delete([locator, path]);
711
+ });
712
+ },
713
+ async fences() {
714
+ const held = await transacted(authored, FENCES, 'readonly', (transaction) => settled(transaction.objectStore(FENCES).getAll()));
715
+ return held.map((fence) => fence.locator);
716
+ },
717
+ async erase(locators) {
718
+ await transacted(authored, [FENCES, QUEUES, PENDING_CHANGES, ROOM_DRAFTS], 'readwrite', (work) => {
719
+ for (const locator of locators) {
720
+ work.objectStore(FENCES).put({ locator });
721
+ work.objectStore(QUEUES).delete(locator);
722
+ for (const name of [PENDING_CHANGES, ROOM_DRAFTS]) {
723
+ removeRoomEntries(work.objectStore(name), locator);
724
+ }
392
725
  }
393
- }
394
- await completed(transaction);
726
+ });
727
+ await transacted(database, [ROOMS, DOCUMENTS, BINARY_FILES, TRANSFERS], 'readwrite', (transaction) => {
728
+ for (const locator of locators) {
729
+ transaction.objectStore(ROOMS).delete(locator);
730
+ transaction.objectStore(TRANSFERS).delete(locator);
731
+ transaction.objectStore(DOCUMENTS).delete(underRoom(locator));
732
+ transaction.objectStore(BINARY_FILES).delete(underRoom(locator));
733
+ }
734
+ });
735
+ await transacted(authored, FENCES, 'readwrite', (fences) => {
736
+ for (const locator of locators)
737
+ fences.objectStore(FENCES).delete(locator);
738
+ });
739
+ },
740
+ async discard(locator) {
741
+ await transacted(authored, [QUEUES, PENDING_CHANGES], 'readwrite', (transaction) => {
742
+ transaction.objectStore(QUEUES).delete(locator);
743
+ removeRoomEntries(transaction.objectStore(PENDING_CHANGES), locator);
744
+ });
745
+ },
746
+ async transfers() {
747
+ const held = await transacted(database, TRANSFERS, 'readonly', (transaction) => settled(transaction.objectStore(TRANSFERS).getAll()));
748
+ return held.filter((record) => !fenced(record.locator));
749
+ },
750
+ staged(record) {
751
+ return transacted(database, [DOCUMENTS, BINARY_FILES], 'readonly', (transaction) => readLayer(transaction, record.locator, record.transfer));
752
+ },
753
+ async stage(record, page) {
754
+ if (fenced(record.locator))
755
+ return;
756
+ const paths = await stepped(changedIn(page, null));
757
+ if (fenced(record.locator))
758
+ return;
759
+ await transacted(database, [TRANSFERS, DOCUMENTS, BINARY_FILES], 'readwrite', (transaction) => {
760
+ transaction.objectStore(TRANSFERS).put(record);
761
+ return writeLayer(transaction, record.locator, record.transfer, {
762
+ next: page,
763
+ base: null,
764
+ paths,
765
+ });
766
+ });
767
+ },
768
+ async abandon(locator) {
769
+ if (fenced(locator))
770
+ return;
771
+ await transacted(database, [TRANSFERS, DOCUMENTS, BINARY_FILES], 'readwrite', (transaction) => {
772
+ const transfers = transaction.objectStore(TRANSFERS);
773
+ const held = transfers.get(locator);
774
+ held.onsuccess = () => {
775
+ const record = held.result;
776
+ if (record === undefined)
777
+ return;
778
+ transfers.delete(locator);
779
+ const range = underTransfer(locator, record.transfer);
780
+ transaction.objectStore(DOCUMENTS).delete(range);
781
+ transaction.objectStore(BINARY_FILES).delete(range);
782
+ };
783
+ });
784
+ },
785
+ receivedHeads() {
786
+ return transacted(database, RECEIVED, 'readonly', (transaction) => settled(transaction.objectStore(RECEIVED).getAll()));
787
+ },
788
+ async receivedParts(key, count) {
789
+ const kept = await transacted(database, RECEIVED_PARTS, 'readonly', (transaction) => settled(transaction
790
+ .objectStore(RECEIVED_PARTS)
791
+ .getAll(IDBKeyRange.bound([key, 0], [key, count], false, true))));
792
+ return kept.map((part) => part.value);
793
+ },
794
+ async keepReceived(key, head, part) {
795
+ await transacted(database, [RECEIVED, RECEIVED_PARTS], 'readwrite', (transaction) => {
796
+ transaction.objectStore(RECEIVED).put({ key, head });
797
+ if (part !== undefined)
798
+ transaction.objectStore(RECEIVED_PARTS).put({ key, ...part });
799
+ });
800
+ },
801
+ async dropReceived(keys) {
802
+ await transacted(database, [RECEIVED, RECEIVED_PARTS], 'readwrite', (transaction) => {
803
+ for (const key of keys) {
804
+ transaction.objectStore(RECEIVED).delete(key);
805
+ transaction.objectStore(RECEIVED_PARTS).delete(IDBKeyRange.bound([key], [key, []]));
806
+ }
807
+ });
395
808
  },
396
809
  async generation() {
397
- return (await declaration(database)).generation;
810
+ const held = await transacted(authored, FACTS, 'readonly', (transaction) => settled(transaction.objectStore(FACTS).get(GENERATION)));
811
+ return held ?? null;
398
812
  },
399
- rememberGeneration(value) {
400
- return updateDeclaration(database, (record) => ({ ...record, generation: value }));
813
+ async rememberGeneration(value) {
814
+ await transacted(authored, FACTS, 'readwrite', (transaction) => {
815
+ transaction.objectStore(FACTS).put(value, GENERATION);
816
+ });
401
817
  },
402
818
  close() {
403
- database.close();
819
+ for (const held of [authored, database])
820
+ void idle(held).then(() => held.close());
404
821
  },
405
822
  };
406
823
  }