@agentshouse/mdruntime 0.1.0-ca68e8b4bbebc → 0.1.0-ca6edc1abd618

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