@agentshouse/mdruntime 0.1.0-ca68e8b4bbebc → 0.1.0-ca69b8fe1fa9f

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 (233) hide show
  1. package/README.md +19 -16
  2. package/dist/adapter.d.ts +142 -70
  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 +38 -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 +26 -11
  11. package/dist/bootstrap.d.ts.map +1 -1
  12. package/dist/bootstrap.js +181 -103
  13. package/dist/chain.d.ts +12 -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 +19 -10
  23. package/dist/client.d.ts.map +1 -1
  24. package/dist/client.js +86 -9
  25. package/dist/collection.d.ts +11 -21
  26. package/dist/collection.d.ts.map +1 -1
  27. package/dist/collection.js +39 -291
  28. package/dist/compile.d.ts +11 -0
  29. package/dist/compile.d.ts.map +1 -0
  30. package/dist/compile.js +589 -0
  31. package/dist/connection.d.ts +28 -17
  32. package/dist/connection.d.ts.map +1 -1
  33. package/dist/connection.js +3147 -1396
  34. package/dist/context.d.ts +2 -0
  35. package/dist/context.d.ts.map +1 -0
  36. package/dist/{chat/context.js → context.js} +1 -4
  37. package/dist/conversation.d.ts +29 -14
  38. package/dist/conversation.d.ts.map +1 -1
  39. package/dist/conversation.js +423 -198
  40. package/dist/digest.d.ts +7 -0
  41. package/dist/digest.d.ts.map +1 -0
  42. package/dist/digest.js +113 -0
  43. package/dist/durability.d.ts +2 -5
  44. package/dist/durability.d.ts.map +1 -1
  45. package/dist/durability.js +5 -0
  46. package/dist/entry.d.ts +5 -2
  47. package/dist/entry.d.ts.map +1 -1
  48. package/dist/entry.js +31 -27
  49. package/dist/file.d.ts +2 -19
  50. package/dist/file.d.ts.map +1 -1
  51. package/dist/file.js +7 -122
  52. package/dist/host.d.ts +3 -10
  53. package/dist/host.d.ts.map +1 -1
  54. package/dist/host.js +65 -39
  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 +19 -13
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +8 -2
  61. package/dist/job.d.ts +14 -0
  62. package/dist/job.d.ts.map +1 -0
  63. package/dist/job.js +28 -0
  64. package/dist/live.d.ts +23 -0
  65. package/dist/live.d.ts.map +1 -0
  66. package/dist/live.js +127 -0
  67. package/dist/media.d.ts +8 -0
  68. package/dist/media.d.ts.map +1 -0
  69. package/dist/media.js +218 -0
  70. package/dist/memory.d.ts +12 -6
  71. package/dist/memory.d.ts.map +1 -1
  72. package/dist/memory.js +202 -103
  73. package/dist/messages.d.ts +28 -0
  74. package/dist/messages.d.ts.map +1 -0
  75. package/dist/messages.js +89 -0
  76. package/dist/model.d.ts +7 -3
  77. package/dist/model.d.ts.map +1 -1
  78. package/dist/model.js +7 -13
  79. package/dist/name.d.ts +4 -0
  80. package/dist/name.d.ts.map +1 -0
  81. package/dist/name.js +122 -0
  82. package/dist/observation.d.ts +17 -2
  83. package/dist/observation.d.ts.map +1 -1
  84. package/dist/observation.js +100 -5
  85. package/dist/opened.d.ts +22 -0
  86. package/dist/opened.d.ts.map +1 -0
  87. package/dist/opened.js +107 -0
  88. package/dist/outcome.d.ts +45 -7
  89. package/dist/outcome.d.ts.map +1 -1
  90. package/dist/outcome.js +39 -0
  91. package/dist/overlay.d.ts +2 -5
  92. package/dist/overlay.d.ts.map +1 -1
  93. package/dist/overlay.js +87 -172
  94. package/dist/paths.d.ts +1 -0
  95. package/dist/paths.d.ts.map +1 -1
  96. package/dist/paths.js +4 -0
  97. package/dist/query.d.ts +16 -190
  98. package/dist/query.d.ts.map +1 -1
  99. package/dist/query.js +3 -470
  100. package/dist/reach.d.ts +17 -8
  101. package/dist/reach.d.ts.map +1 -1
  102. package/dist/reach.js +219 -90
  103. package/dist/react.d.ts +4 -3
  104. package/dist/react.d.ts.map +1 -1
  105. package/dist/react.js +2 -14
  106. package/dist/readiness.d.ts +14 -17
  107. package/dist/readiness.d.ts.map +1 -1
  108. package/dist/readiness.js +2 -8
  109. package/dist/recovery.d.ts +3 -2
  110. package/dist/recovery.d.ts.map +1 -1
  111. package/dist/recovery.js +34 -7
  112. package/dist/refresh.d.ts +18 -15
  113. package/dist/refresh.d.ts.map +1 -1
  114. package/dist/refresh.js +155 -58
  115. package/dist/replica.d.ts +56 -33
  116. package/dist/replica.d.ts.map +1 -1
  117. package/dist/replica.js +301 -191
  118. package/dist/room-draft.d.ts +23 -4
  119. package/dist/room-draft.d.ts.map +1 -1
  120. package/dist/room-draft.js +158 -71
  121. package/dist/rows.d.ts +22 -30
  122. package/dist/rows.d.ts.map +1 -1
  123. package/dist/rows.js +63 -114
  124. package/dist/save.d.ts +53 -14
  125. package/dist/save.d.ts.map +1 -1
  126. package/dist/save.js +529 -185
  127. package/dist/search.d.ts +12 -82
  128. package/dist/search.d.ts.map +1 -1
  129. package/dist/search.js +10 -207
  130. package/dist/seed.d.ts.map +1 -1
  131. package/dist/seed.js +18 -4
  132. package/dist/shared.d.ts +7 -3
  133. package/dist/shared.d.ts.map +1 -1
  134. package/dist/shared.js +119 -66
  135. package/dist/status.d.ts +4 -3
  136. package/dist/status.d.ts.map +1 -1
  137. package/dist/status.js +3 -1
  138. package/dist/store.d.ts +92 -98
  139. package/dist/store.d.ts.map +1 -1
  140. package/dist/store.js +330 -675
  141. package/dist/stored.d.ts +162 -0
  142. package/dist/stored.d.ts.map +1 -0
  143. package/dist/stored.js +543 -0
  144. package/dist/tables.d.ts +353 -0
  145. package/dist/tables.d.ts.map +1 -0
  146. package/dist/tables.js +588 -0
  147. package/dist/transfer.d.ts +0 -5
  148. package/dist/transfer.d.ts.map +1 -1
  149. package/dist/turn.d.ts +5 -3
  150. package/dist/turn.d.ts.map +1 -1
  151. package/dist/turn.js +51 -21
  152. package/dist/validation.d.ts +29 -0
  153. package/dist/validation.d.ts.map +1 -0
  154. package/dist/validation.js +104 -0
  155. package/dist/windows.d.ts +11 -0
  156. package/dist/windows.d.ts.map +1 -0
  157. package/dist/windows.js +16 -0
  158. package/dist/wire.d.ts +34 -5
  159. package/dist/wire.d.ts.map +1 -1
  160. package/dist/wire.js +10 -2
  161. package/package.json +18 -19
  162. package/AGENTS.md +0 -299
  163. package/dist/acquisition.d.ts +0 -14
  164. package/dist/acquisition.d.ts.map +0 -1
  165. package/dist/acquisition.js +0 -24
  166. package/dist/chat/acts.d.ts +0 -33
  167. package/dist/chat/acts.d.ts.map +0 -1
  168. package/dist/chat/acts.js +0 -36
  169. package/dist/chat/context.d.ts +0 -3
  170. package/dist/chat/context.d.ts.map +0 -1
  171. package/dist/chat/input.d.ts +0 -9
  172. package/dist/chat/input.d.ts.map +0 -1
  173. package/dist/chat/input.js +0 -99
  174. package/dist/chat/kit.d.ts +0 -61
  175. package/dist/chat/kit.d.ts.map +0 -1
  176. package/dist/chat/kit.js +0 -123
  177. package/dist/chat/lasting.d.ts +0 -6
  178. package/dist/chat/lasting.d.ts.map +0 -1
  179. package/dist/chat/lasting.js +0 -19
  180. package/dist/chat/list.d.ts +0 -27
  181. package/dist/chat/list.d.ts.map +0 -1
  182. package/dist/chat/list.js +0 -63
  183. package/dist/chat/markdown.d.ts +0 -20
  184. package/dist/chat/markdown.d.ts.map +0 -1
  185. package/dist/chat/markdown.js +0 -188
  186. package/dist/chat/message.d.ts +0 -6
  187. package/dist/chat/message.d.ts.map +0 -1
  188. package/dist/chat/message.js +0 -192
  189. package/dist/chat/messages.d.ts +0 -22
  190. package/dist/chat/messages.d.ts.map +0 -1
  191. package/dist/chat/messages.js +0 -155
  192. package/dist/chat/name.d.ts +0 -6
  193. package/dist/chat/name.d.ts.map +0 -1
  194. package/dist/chat/name.js +0 -37
  195. package/dist/chat/opened.d.ts +0 -11
  196. package/dist/chat/opened.d.ts.map +0 -1
  197. package/dist/chat/opened.js +0 -17
  198. package/dist/chat/overlay.d.ts +0 -31
  199. package/dist/chat/overlay.d.ts.map +0 -1
  200. package/dist/chat/overlay.js +0 -97
  201. package/dist/chat/parts.d.ts +0 -57
  202. package/dist/chat/parts.d.ts.map +0 -1
  203. package/dist/chat/parts.js +0 -119
  204. package/dist/chat/process.d.ts +0 -20
  205. package/dist/chat/process.d.ts.map +0 -1
  206. package/dist/chat/process.js +0 -32
  207. package/dist/chat/provider.d.ts +0 -63
  208. package/dist/chat/provider.d.ts.map +0 -1
  209. package/dist/chat/provider.js +0 -629
  210. package/dist/chat/question.d.ts +0 -9
  211. package/dist/chat/question.d.ts.map +0 -1
  212. package/dist/chat/question.js +0 -80
  213. package/dist/chat/questions.d.ts +0 -31
  214. package/dist/chat/questions.d.ts.map +0 -1
  215. package/dist/chat/questions.js +0 -111
  216. package/dist/chat/read.d.ts +0 -5
  217. package/dist/chat/read.d.ts.map +0 -1
  218. package/dist/chat/read.js +0 -13
  219. package/dist/chat/ready.d.ts +0 -34
  220. package/dist/chat/ready.d.ts.map +0 -1
  221. package/dist/chat/ready.js +0 -91
  222. package/dist/chat/style.d.ts +0 -4
  223. package/dist/chat/style.d.ts.map +0 -1
  224. package/dist/chat/style.js +0 -302
  225. package/dist/chat.d.ts +0 -14
  226. package/dist/chat.d.ts.map +0 -1
  227. package/dist/chat.js +0 -8
  228. package/dist/read-side.d.ts +0 -25
  229. package/dist/read-side.d.ts.map +0 -1
  230. package/dist/read-side.js +0 -642
  231. package/dist/reads.d.ts +0 -11
  232. package/dist/reads.d.ts.map +0 -1
  233. package/dist/reads.js +0 -98
package/dist/store.js CHANGED
@@ -1,750 +1,405 @@
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);
1
+ import { composedOf } from './collection.js';
2
+ import { binaryLocalId } from './identity.js';
3
+ const FILE = '\u0000file';
4
+ function batchFiles(batch) {
5
+ return batch.changes.flatMap((change) => (change.kind === 'binary' ? [change.localId] : []));
99
6
  }
100
- function accepted({ conversation: _held, ...message }) {
101
- return message;
7
+ function draftFiles(drafts) {
8
+ return drafts.flatMap(({ parts }) => (parts.file === undefined ? [] : [parts.file.localId]));
102
9
  }
103
- function roomRecord(record) {
104
- const { documents, binaries, revisions, fileIds, changes, written, ...room } = record;
105
- return room;
10
+ function roomDraftRow(record) {
11
+ return { path: record.path, record: JSON.stringify(record), files: draftFiles([record]) };
106
12
  }
107
- function chatDraftRecord(record) {
108
- return { ...record, revision: record.revision ?? '' };
109
- }
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
- }
128
- }
129
- function emptyLayer() {
130
- return { documents: {}, binaries: {}, revisions: {}, fileIds: {}, changes: {}, written: {} };
131
- }
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) {
155
- return {
156
- 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) {
13
+ function authoredRows({ locator, queue, founded, saved, roomDrafts, consumedRoomDrafts }, held) {
167
14
  return {
168
15
  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],
16
+ ...(queue === undefined
17
+ ? {}
18
+ : {
19
+ order: queue.map(({ id }) => id),
20
+ added: queue
21
+ .filter(({ id }) => held?.has(id) !== true)
22
+ .map((batch) => {
23
+ const drafts = saved?.get(batch.id) ?? [];
24
+ return {
25
+ id: batch.id,
26
+ batch: JSON.stringify(batch),
27
+ state: JSON.stringify({
28
+ drafts,
29
+ submission: { state: 'waiting' },
30
+ lost: false,
31
+ }),
32
+ files: [...batchFiles(batch), ...draftFiles(drafts)],
33
+ };
34
+ }),
35
+ }),
36
+ ...(founded === undefined
37
+ ? {}
38
+ : {
39
+ founded: founded.map((batch) => ({
40
+ id: batch.id,
41
+ batch: JSON.stringify(batch),
42
+ files: batchFiles(batch),
43
+ })),
44
+ }),
45
+ ...(roomDrafts === undefined ? {} : { roomDrafts: roomDrafts.map(roomDraftRow) }),
46
+ ...(consumedRoomDrafts === undefined ? {} : { consumedRoomDrafts }),
175
47
  };
176
48
  }
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
- }
49
+ function marked(value) {
50
+ return typeof value === 'object' && value !== null && FILE in value;
204
51
  }
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);
52
+ function keyed(keys, value) {
53
+ const stored = [];
54
+ const files = [];
55
+ const record = JSON.stringify(value, (_name, held) => {
56
+ if (!(held instanceof Blob))
57
+ return held;
58
+ let key = keys.get(held);
59
+ if (key === undefined) {
60
+ key = binaryLocalId();
61
+ keys.set(held, key);
211
62
  }
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);
63
+ stored.push({ key, blob: held });
64
+ files.push(key);
65
+ return { [FILE]: key, type: held.type };
219
66
  });
67
+ return { record, files, stored };
220
68
  }
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
- }
275
- }
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;
282
- }
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
- });
69
+ async function filed(value, read) {
70
+ if (Array.isArray(value))
71
+ return Promise.all(value.map((item) => filed(item, read)));
72
+ if (marked(value))
73
+ return read(value[FILE], value.type);
74
+ if (typeof value !== 'object' || value === null)
75
+ return value;
76
+ const restored = {};
77
+ for (const [name, item] of Object.entries(value))
78
+ restored[name] = await filed(item, read);
79
+ return restored;
298
80
  }
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
- });
81
+ function json(value, fallback) {
82
+ return value === undefined ? fallback : JSON.parse(value);
317
83
  }
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);
84
+ export function openRuntimeStore(fenced, authored) {
85
+ const keys = new WeakMap();
86
+ const read = async (key, type) => {
87
+ const blob = await authored.ask({ kind: 'authored.file', key, type });
88
+ keys.set(blob, key);
89
+ return blob;
90
+ };
91
+ const restored = async (records) => Promise.all(records.map(async (record) => (await filed(JSON.parse(record), read))));
92
+ const amend = async (locator, id, amendment) => {
93
+ if (fenced(locator))
94
+ return;
95
+ await authored.ask({
96
+ kind: 'authored.amend',
97
+ locator,
98
+ id,
99
+ amendment: JSON.stringify(amendment),
100
+ });
101
+ };
102
+ const fact = (name) => authored.ask({ kind: 'authored.fact', name });
103
+ const queued = new Map();
104
+ const changed = new Map();
105
+ const change = (key) => changed.set(key, (changed.get(key) ?? 0) + 1);
106
+ const rows = (writes) => writes.map((write) => authoredRows(write, queued.get(write.locator)));
107
+ const noted = (writes) => {
108
+ for (const { locator, queue } of writes) {
109
+ if (queue !== undefined)
110
+ queued.set(locator, new Set(queue.map(({ id }) => id)));
324
111
  }
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
- });
112
+ };
333
113
  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)) });
114
+ async opened() {
115
+ const held = await authored.ask({ kind: 'replica.open' });
116
+ const unindexed = new Set(held.keys.flatMap(({ key, rederiving }) => (rederiving === null ? [] : [key])));
117
+ const overlaid = new Map();
118
+ for (const { key, path } of held.overlaid) {
119
+ const paths = overlaid.get(key) ?? new Set();
120
+ paths.add(path);
121
+ overlaid.set(key, paths);
340
122
  }
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
- }
123
+ return {
124
+ rooms: new Map(held.rooms
125
+ .filter(({ locator }) => !fenced(locator))
126
+ .map(({ locator, key, record }) => [
127
+ locator,
128
+ { ...JSON.parse(record), key },
129
+ ])),
130
+ unindexed,
131
+ overlaid,
132
+ erasing: held.erasing.length > 0,
133
+ orphans: held.orphans,
134
+ lastCompleted: json(held.facts.lastCompleted, null),
135
+ providerLimits: json(held.facts.providerLimits, []),
136
+ capabilities: json(held.facts.capabilities, []),
137
+ member: json(held.facts.member, null),
138
+ targets: json(held.facts.targets, {}),
139
+ presentation: held.presentation.map(({ app, value }) => ({
140
+ app,
141
+ value: JSON.parse(value),
142
+ })),
143
+ conversationList: json(held.facts.conversationList, null),
144
+ conversationCursor: json(held.facts.conversationCursor, null),
373
145
  };
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
146
  },
408
- async lastCompleted() {
409
- return (await declaration(database)).lastCompleted;
147
+ counts(rooms) {
148
+ return authored.ask({ kind: 'replica.counts', rooms });
410
149
  },
411
- complete(at) {
412
- return updateDeclaration(database, (record) => ({ ...record, lastCompleted: at }));
150
+ query(plan, rooms, budget) {
151
+ return authored.ask({ kind: 'replica.query', plan, rooms, budget });
413
152
  },
414
- async providerLimits() {
415
- return (await declaration(database)).providerLimits;
153
+ changes(keys) {
154
+ return keys.reduce((total, key) => total + (changed.get(key) ?? 0), 0);
416
155
  },
417
- async capabilities() {
418
- return (await declaration(database)).capabilities;
156
+ entries(key, view, paths) {
157
+ return authored.ask({ kind: 'replica.entries', key, view, paths });
419
158
  },
420
- declare(limits, capabilities) {
421
- return updateDeclaration(database, (record) => ({
422
- ...record,
423
- providerLimits: limits,
424
- capabilities,
425
- }));
159
+ typed(key, view, paths) {
160
+ return authored.ask({ kind: 'replica.typed', key, view, paths });
161
+ },
162
+ referrers(key, view, targets, kinds) {
163
+ return authored.ask({ kind: 'replica.referrers', key, view, targets, kinds });
164
+ },
165
+ files(key, view, after, limit) {
166
+ return authored.ask({ kind: 'replica.files', key, view, after, limit });
426
167
  },
427
- async member() {
428
- const transaction = database.transaction(DECLARATIONS, 'readonly');
429
- const held = await settled(transaction.objectStore(DECLARATIONS).get(MEMBER));
430
- return held ?? null;
168
+ folders(key, view, paths) {
169
+ return authored.ask({ kind: 'replica.folders', key, view, paths });
431
170
  },
432
- async keepMember(member) {
433
- const transaction = database.transaction(DECLARATIONS, 'readwrite');
434
- transaction.objectStore(DECLARATIONS).put(member, MEMBER);
435
- await completed(transaction);
171
+ typedWithin(key, view, roots, within) {
172
+ return authored.ask({ kind: 'replica.typedWithin', key, view, roots, within });
436
173
  },
437
- async targets() {
438
- const transaction = database.transaction(DECLARATIONS, 'readonly');
439
- const held = await settled(transaction.objectStore(DECLARATIONS).get(TARGETS));
440
- return held ?? {};
174
+ async stage(record, composition, page) {
175
+ if (fenced(record.locator))
176
+ return null;
177
+ return authored.ask({
178
+ kind: 'replica.stage',
179
+ locator: record.locator,
180
+ transfer: record.transfer,
181
+ key: record.key,
182
+ fingerprint: composedOf(composition).fingerprint,
183
+ entries: page.entries,
184
+ folders: page.folders,
185
+ });
186
+ },
187
+ async refresh(key, composition, page) {
188
+ await authored.ask({
189
+ kind: 'replica.refresh',
190
+ key,
191
+ composed: composedOf(composition),
192
+ entries: page.entries,
193
+ removals: page.removals,
194
+ folders: page.folders,
195
+ folderRemovals: page.folderRemovals,
196
+ });
197
+ },
198
+ async unrefresh(key) {
199
+ await authored.ask({ kind: 'replica.unrefresh', key });
200
+ },
201
+ async hold(locator, key, composition, texts) {
202
+ if (fenced(locator))
203
+ return [];
204
+ change(key);
205
+ return authored.ask({
206
+ kind: 'replica.hold',
207
+ key,
208
+ locator,
209
+ composed: composedOf(composition),
210
+ texts,
211
+ });
212
+ },
213
+ async unhold(locator, key, composition) {
214
+ if (fenced(locator))
215
+ return { paths: [], bytes: 0 };
216
+ change(key);
217
+ return authored.ask({
218
+ kind: 'replica.unhold',
219
+ key,
220
+ locator,
221
+ composed: composedOf(composition),
222
+ });
223
+ },
224
+ async wanted(locator, key) {
225
+ if (fenced(locator))
226
+ return [];
227
+ return authored.ask({ kind: 'replica.wanted', key, locator });
228
+ },
229
+ async remember(locator, key, paths) {
230
+ if (fenced(locator) || paths.length === 0)
231
+ return;
232
+ await authored.ask({ kind: 'replica.remember', key, locator, paths });
233
+ },
234
+ async commit({ rooms, writes = [], files = [], whole = false, discards = [] }) {
235
+ const kept = whole ? writes : writes.filter(({ locator }) => !fenced(locator));
236
+ const refused = whole ? kept.find(({ locator }) => fenced(locator)) : undefined;
237
+ if (refused !== undefined) {
238
+ return { fenced: refused.locator, counts: {}, changed: {}, indexed: {} };
239
+ }
240
+ for (const room of rooms)
241
+ change(room.key);
242
+ const committed = await authored.ask({
243
+ kind: 'replica.commit',
244
+ ...(kept.length === 0 && files.length === 0 && discards.length === 0
245
+ ? {}
246
+ : { authored: { writes: rows(kept), files, whole, discards } }),
247
+ rooms: rooms.filter(({ locator }) => !fenced(locator)),
248
+ });
249
+ if (committed.fenced === null || !whole)
250
+ noted(kept);
251
+ for (const locator of discards)
252
+ queued.delete(locator);
253
+ return committed;
254
+ },
255
+ async fence(locators) {
256
+ await authored.ask({ kind: 'replica.fence', locators });
257
+ for (const locator of locators)
258
+ queued.delete(locator);
259
+ },
260
+ async erase(locator, limit) {
261
+ return (await authored.ask({ kind: 'replica.erase', locator, limit })).remaining;
262
+ },
263
+ async abandon(locator) {
264
+ if (fenced(locator))
265
+ return;
266
+ await authored.ask({ kind: 'replica.abandon', locator });
267
+ },
268
+ async release(key) {
269
+ await authored.ask({ kind: 'replica.release', key });
270
+ },
271
+ async rederive(key, composition, bytes, ms, floor) {
272
+ change(key);
273
+ return authored.ask({
274
+ kind: 'replica.rederive',
275
+ key,
276
+ composed: composedOf(composition),
277
+ bytes,
278
+ ms,
279
+ floor,
280
+ });
441
281
  },
442
- async keepTargets(targets) {
443
- const transaction = database.transaction(DECLARATIONS, 'readwrite');
444
- transaction.objectStore(DECLARATIONS).put(targets, TARGETS);
445
- await completed(transaction);
282
+ async fact(name, value) {
283
+ await authored.ask({ kind: 'replica.fact', name, value: JSON.stringify(value) });
446
284
  },
447
285
  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
- ]);
286
+ const { queues, pending } = await authored.ask({ kind: 'authored.queues' });
287
+ queued.clear();
288
+ for (const queue of queues)
289
+ queued.set(queue.locator, new Set(queue.ids));
453
290
  const byId = new Map(pending.map((record) => [`${record.locator}\0${record.id}`, record]));
454
291
  return queues
455
292
  .filter((queue) => !fenced(queue.locator))
456
293
  .map((queue) => ({
457
294
  locator: queue.locator,
458
- pending: queue.order.map((id) => {
295
+ pending: queue.ids.map((id) => {
459
296
  const record = byId.get(`${queue.locator}\0${id}`);
460
297
  if (record === undefined)
461
298
  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 } };
299
+ return {
300
+ batch: JSON.parse(record.batch),
301
+ state: JSON.parse(record.state),
302
+ };
464
303
  }),
465
304
  }));
466
305
  },
467
- async submit(locator, id, submission, lost) {
468
- if (!fenced(locator))
469
- await amendPending(authored, locator, id, { submission, lost });
306
+ submit(locator, id, submission, lost) {
307
+ return amend(locator, id, { submission, lost });
470
308
  },
471
- async accept(locator, id, roomVersion) {
472
- if (!fenced(locator))
473
- await amendPending(authored, locator, id, { accepted: roomVersion });
474
- },
475
- async keepUpload(locator, id, upload) {
476
- if (!fenced(locator))
477
- await amendPending(authored, locator, id, { upload });
309
+ keepUpload(locator, id, upload) {
310
+ return amend(locator, id, { upload });
478
311
  },
479
312
  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());
313
+ const held = await authored.ask({ kind: 'authored.roomDrafts' });
314
+ return held
315
+ .map((record) => JSON.parse(record))
316
+ .filter((record) => !fenced(record.locator));
487
317
  },
488
318
  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
- };
319
+ await authored.ask({
320
+ kind: 'replica.present',
321
+ app: record.app,
322
+ value: JSON.stringify(record.value ?? null),
516
323
  });
517
- return [...held.values()];
518
324
  },
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;
325
+ conversations() {
326
+ return authored.ask({ kind: 'conversation.held' });
327
+ },
328
+ async keepMessages(write) {
329
+ await authored.ask({ kind: 'conversation.keep', ...write });
330
+ },
331
+ messageWindow(conversation, limit, before, phrase = null) {
332
+ return authored.ask({ kind: 'conversation.window', conversation, limit, before, phrase });
333
+ },
334
+ messageCount(conversation, phrase = null) {
335
+ return authored.ask({ kind: 'conversation.count', conversation, phrase });
336
+ },
337
+ turnArrived(conversation, turn) {
338
+ return authored.ask({ kind: 'conversation.turn', conversation, turn });
579
339
  },
580
340
  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);
341
+ await authored.ask({ kind: 'conversation.drop', conversations });
596
342
  },
597
343
  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);
344
+ const records = await authored.ask({ kind: 'authored.chatDrafts' });
345
+ return records.map((record) => JSON.parse(record));
601
346
  },
602
347
  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);
348
+ await authored.ask({
349
+ kind: 'authored.chatDraft',
350
+ kept: records.map((record) => ({
351
+ conversation: record.conversation,
352
+ record: JSON.stringify(record),
353
+ })),
354
+ dropped: [],
355
+ });
607
356
  },
608
357
  async dropChatDraft(conversation) {
609
- const transaction = authored.transaction(CHAT_DRAFTS, 'readwrite');
610
- transaction.objectStore(CHAT_DRAFTS).delete(conversation);
611
- await completed(transaction);
358
+ await authored.ask({ kind: 'authored.chatDraft', kept: [], dropped: [conversation] });
612
359
  },
613
360
  async calls() {
614
- const transaction = authored.transaction(CALLS, 'readonly');
615
- return settled(transaction.objectStore(CALLS).getAll());
361
+ return restored(await authored.ask({ kind: 'authored.calls' }));
616
362
  },
617
363
  async keepCall(record) {
618
- const transaction = authored.transaction(CALLS, 'readwrite');
619
- transaction.objectStore(CALLS).put(record);
620
- await completed(transaction);
364
+ const { stored, ...kept } = keyed(keys, record);
365
+ await authored.ask({
366
+ kind: 'authored.call',
367
+ operation: record.operation,
368
+ kept,
369
+ files: stored,
370
+ });
621
371
  },
622
372
  async dropCall(operation) {
623
- const transaction = authored.transaction(CALLS, 'readwrite');
624
- transaction.objectStore(CALLS).delete(operation);
625
- await completed(transaction);
373
+ await authored.ask({ kind: 'authored.call', operation, kept: null, files: [] });
626
374
  },
627
- async keepRoomDraft(record) {
375
+ async keepRoomDraft(record, files) {
628
376
  if (fenced(record.locator))
629
377
  return;
630
- const transaction = authored.transaction(ROOM_DRAFTS, 'readwrite');
631
- transaction.objectStore(ROOM_DRAFTS).put(record);
632
- await completed(transaction);
378
+ const { path, ...kept } = roomDraftRow(record);
379
+ await authored.ask({
380
+ kind: 'authored.roomDraft',
381
+ locator: record.locator,
382
+ path,
383
+ kept,
384
+ files,
385
+ });
633
386
  },
634
387
  async discardRoomDraft(locator, path) {
635
388
  if (fenced(locator))
636
389
  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);
668
- },
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);
674
- },
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));
679
- },
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);
390
+ await authored.ask({ kind: 'authored.roomDraft', locator, path, kept: null, files: [] });
691
391
  },
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);
719
- },
720
- 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);
726
- },
727
- 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);
392
+ fences() {
393
+ return authored.ask({ kind: 'authored.fences' });
734
394
  },
735
- async generation() {
736
- const transaction = authored.transaction(FACTS, 'readonly');
737
- const held = await settled(transaction.objectStore(FACTS).get(GENERATION));
738
- return held ?? null;
395
+ generation() {
396
+ return fact('generation');
739
397
  },
740
398
  async rememberGeneration(value) {
741
- const transaction = authored.transaction(FACTS, 'readwrite');
742
- transaction.objectStore(FACTS).put(value, GENERATION);
743
- await completed(transaction);
399
+ await authored.ask({ kind: 'authored.remember', name: 'generation', value });
744
400
  },
745
- close() {
746
- authored.close();
747
- database.close();
401
+ file(key, type) {
402
+ return authored.ask({ kind: 'authored.file', key, type });
748
403
  },
749
404
  };
750
405
  }