@verdant-web/store 2.8.5 → 3.0.0

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 (278) hide show
  1. package/dist/bundle/index.js +9 -10
  2. package/dist/bundle/index.js.map +4 -4
  3. package/dist/cjs/DocumentManager.d.ts +1 -1
  4. package/dist/cjs/DocumentManager.js +1 -1
  5. package/dist/cjs/DocumentManager.js.map +1 -1
  6. package/dist/cjs/IDBService.d.ts +28 -7
  7. package/dist/cjs/IDBService.js +50 -13
  8. package/dist/cjs/IDBService.js.map +1 -1
  9. package/dist/cjs/UndoHistory.d.ts +1 -1
  10. package/dist/cjs/UndoHistory.js +6 -2
  11. package/dist/cjs/UndoHistory.js.map +1 -1
  12. package/dist/cjs/__tests__/batching.test.js +3 -1
  13. package/dist/cjs/__tests__/batching.test.js.map +1 -1
  14. package/dist/cjs/__tests__/documents.test.js +37 -6
  15. package/dist/cjs/__tests__/documents.test.js.map +1 -1
  16. package/dist/cjs/__tests__/fixtures/testStorage.d.ts +2 -2
  17. package/dist/cjs/__tests__/fixtures/testStorage.js +2 -1
  18. package/dist/cjs/__tests__/fixtures/testStorage.js.map +1 -1
  19. package/dist/cjs/__tests__/legacyOids.test.js +50 -17
  20. package/dist/cjs/__tests__/legacyOids.test.js.map +1 -1
  21. package/dist/cjs/__tests__/mutations.test.js +9 -3
  22. package/dist/cjs/__tests__/mutations.test.js.map +1 -1
  23. package/dist/cjs/__tests__/queries.test.js +6 -2
  24. package/dist/cjs/__tests__/queries.test.js.map +1 -1
  25. package/dist/cjs/__tests__/setup/indexedDB.d.ts +1 -1
  26. package/dist/cjs/__tests__/setup/indexedDB.js +8 -1
  27. package/dist/cjs/__tests__/setup/indexedDB.js.map +1 -1
  28. package/dist/cjs/__tests__/undo.test.js +16 -9
  29. package/dist/cjs/__tests__/undo.test.js.map +1 -1
  30. package/dist/cjs/client/Client.d.ts +1 -1
  31. package/dist/cjs/client/Client.js +7 -3
  32. package/dist/cjs/client/Client.js.map +1 -1
  33. package/dist/cjs/client/ClientDescriptor.js +21 -6
  34. package/dist/cjs/client/ClientDescriptor.js.map +1 -1
  35. package/dist/cjs/context.d.ts +10 -1
  36. package/dist/cjs/entities/Entity.d.ts +106 -178
  37. package/dist/cjs/entities/Entity.js +558 -376
  38. package/dist/cjs/entities/Entity.js.map +1 -1
  39. package/dist/cjs/entities/Entity.test.d.ts +1 -0
  40. package/dist/cjs/entities/Entity.test.js +194 -0
  41. package/dist/cjs/entities/Entity.test.js.map +1 -0
  42. package/dist/cjs/entities/EntityCache.d.ts +15 -0
  43. package/dist/cjs/entities/EntityCache.js +39 -0
  44. package/dist/cjs/entities/EntityCache.js.map +1 -0
  45. package/dist/cjs/entities/EntityMetadata.d.ts +68 -0
  46. package/dist/cjs/entities/EntityMetadata.js +261 -0
  47. package/dist/cjs/entities/EntityMetadata.js.map +1 -0
  48. package/dist/cjs/entities/EntityStore.d.ts +63 -68
  49. package/dist/cjs/entities/EntityStore.js +294 -438
  50. package/dist/cjs/entities/EntityStore.js.map +1 -1
  51. package/dist/cjs/entities/OperationBatcher.d.ts +52 -0
  52. package/dist/cjs/entities/OperationBatcher.js +165 -0
  53. package/dist/cjs/entities/OperationBatcher.js.map +1 -0
  54. package/dist/cjs/entities/types.d.ts +84 -0
  55. package/dist/cjs/entities/types.js +3 -0
  56. package/dist/cjs/entities/types.js.map +1 -0
  57. package/dist/cjs/files/EntityFile.d.ts +5 -2
  58. package/dist/cjs/files/EntityFile.js +8 -4
  59. package/dist/cjs/files/EntityFile.js.map +1 -1
  60. package/dist/cjs/files/FileManager.d.ts +3 -1
  61. package/dist/cjs/files/FileManager.js +5 -3
  62. package/dist/cjs/files/FileManager.js.map +1 -1
  63. package/dist/cjs/files/FileStorage.js +7 -7
  64. package/dist/cjs/files/FileStorage.js.map +1 -1
  65. package/dist/cjs/files/utils.d.ts +2 -0
  66. package/dist/cjs/files/utils.js +5 -2
  67. package/dist/cjs/files/utils.js.map +1 -1
  68. package/dist/cjs/idb.d.ts +2 -0
  69. package/dist/cjs/idb.js +50 -4
  70. package/dist/cjs/idb.js.map +1 -1
  71. package/dist/cjs/index.d.ts +1 -1
  72. package/dist/cjs/metadata/AckInfoStore.js +1 -1
  73. package/dist/cjs/metadata/AckInfoStore.js.map +1 -1
  74. package/dist/cjs/metadata/BaselinesStore.d.ts +4 -1
  75. package/dist/cjs/metadata/BaselinesStore.js +19 -10
  76. package/dist/cjs/metadata/BaselinesStore.js.map +1 -1
  77. package/dist/cjs/metadata/LocalReplicaStore.d.ts +1 -1
  78. package/dist/cjs/metadata/LocalReplicaStore.js +11 -5
  79. package/dist/cjs/metadata/LocalReplicaStore.js.map +1 -1
  80. package/dist/cjs/metadata/Metadata.d.ts +26 -5
  81. package/dist/cjs/metadata/Metadata.js +55 -18
  82. package/dist/cjs/metadata/Metadata.js.map +1 -1
  83. package/dist/cjs/metadata/OperationsStore.d.ts +3 -0
  84. package/dist/cjs/metadata/OperationsStore.js +35 -15
  85. package/dist/cjs/metadata/OperationsStore.js.map +1 -1
  86. package/dist/cjs/migration/openDatabase.js +31 -10
  87. package/dist/cjs/migration/openDatabase.js.map +1 -1
  88. package/dist/cjs/queries/BaseQuery.js +13 -1
  89. package/dist/cjs/queries/BaseQuery.js.map +1 -1
  90. package/dist/cjs/queries/CollectionQueries.js +1 -1
  91. package/dist/cjs/queries/CollectionQueries.js.map +1 -1
  92. package/dist/cjs/queries/FindAllQuery.js +1 -0
  93. package/dist/cjs/queries/FindAllQuery.js.map +1 -1
  94. package/dist/cjs/queries/QueryCache.d.ts +1 -0
  95. package/dist/cjs/queries/QueryCache.js +4 -0
  96. package/dist/cjs/queries/QueryCache.js.map +1 -1
  97. package/dist/cjs/queries/QueryableStorage.d.ts +20 -0
  98. package/dist/cjs/queries/QueryableStorage.js +84 -0
  99. package/dist/cjs/queries/QueryableStorage.js.map +1 -0
  100. package/dist/cjs/queries/dbQueries.js +13 -3
  101. package/dist/cjs/queries/dbQueries.js.map +1 -1
  102. package/dist/cjs/sync/FileSync.d.ts +1 -0
  103. package/dist/cjs/sync/FileSync.js +1 -0
  104. package/dist/cjs/sync/FileSync.js.map +1 -1
  105. package/dist/cjs/sync/PushPullSync.d.ts +2 -1
  106. package/dist/cjs/sync/PushPullSync.js +7 -1
  107. package/dist/cjs/sync/PushPullSync.js.map +1 -1
  108. package/dist/cjs/sync/Sync.d.ts +6 -3
  109. package/dist/cjs/sync/Sync.js +9 -4
  110. package/dist/cjs/sync/Sync.js.map +1 -1
  111. package/dist/cjs/sync/WebSocketSync.d.ts +4 -1
  112. package/dist/cjs/sync/WebSocketSync.js +41 -11
  113. package/dist/cjs/sync/WebSocketSync.js.map +1 -1
  114. package/dist/esm/DocumentManager.d.ts +1 -1
  115. package/dist/esm/DocumentManager.js +1 -1
  116. package/dist/esm/DocumentManager.js.map +1 -1
  117. package/dist/esm/IDBService.d.ts +28 -7
  118. package/dist/esm/IDBService.js +51 -14
  119. package/dist/esm/IDBService.js.map +1 -1
  120. package/dist/esm/UndoHistory.d.ts +1 -1
  121. package/dist/esm/UndoHistory.js +6 -2
  122. package/dist/esm/UndoHistory.js.map +1 -1
  123. package/dist/esm/__tests__/batching.test.js +3 -1
  124. package/dist/esm/__tests__/batching.test.js.map +1 -1
  125. package/dist/esm/__tests__/documents.test.js +37 -6
  126. package/dist/esm/__tests__/documents.test.js.map +1 -1
  127. package/dist/esm/__tests__/fixtures/testStorage.d.ts +2 -2
  128. package/dist/esm/__tests__/fixtures/testStorage.js +2 -1
  129. package/dist/esm/__tests__/fixtures/testStorage.js.map +1 -1
  130. package/dist/esm/__tests__/legacyOids.test.js +50 -17
  131. package/dist/esm/__tests__/legacyOids.test.js.map +1 -1
  132. package/dist/esm/__tests__/mutations.test.js +9 -3
  133. package/dist/esm/__tests__/mutations.test.js.map +1 -1
  134. package/dist/esm/__tests__/queries.test.js +6 -2
  135. package/dist/esm/__tests__/queries.test.js.map +1 -1
  136. package/dist/esm/__tests__/setup/indexedDB.d.ts +1 -1
  137. package/dist/esm/__tests__/setup/indexedDB.js +8 -1
  138. package/dist/esm/__tests__/setup/indexedDB.js.map +1 -1
  139. package/dist/esm/__tests__/undo.test.js +16 -9
  140. package/dist/esm/__tests__/undo.test.js.map +1 -1
  141. package/dist/esm/client/Client.d.ts +1 -1
  142. package/dist/esm/client/Client.js +7 -3
  143. package/dist/esm/client/Client.js.map +1 -1
  144. package/dist/esm/client/ClientDescriptor.js +21 -6
  145. package/dist/esm/client/ClientDescriptor.js.map +1 -1
  146. package/dist/esm/context.d.ts +10 -1
  147. package/dist/esm/entities/Entity.d.ts +106 -178
  148. package/dist/esm/entities/Entity.js +559 -376
  149. package/dist/esm/entities/Entity.js.map +1 -1
  150. package/dist/esm/entities/Entity.test.d.ts +1 -0
  151. package/dist/esm/entities/Entity.test.js +192 -0
  152. package/dist/esm/entities/Entity.test.js.map +1 -0
  153. package/dist/esm/entities/EntityCache.d.ts +15 -0
  154. package/dist/esm/entities/EntityCache.js +35 -0
  155. package/dist/esm/entities/EntityCache.js.map +1 -0
  156. package/dist/esm/entities/EntityMetadata.d.ts +68 -0
  157. package/dist/esm/entities/EntityMetadata.js +256 -0
  158. package/dist/esm/entities/EntityMetadata.js.map +1 -0
  159. package/dist/esm/entities/EntityStore.d.ts +63 -68
  160. package/dist/esm/entities/EntityStore.js +295 -439
  161. package/dist/esm/entities/EntityStore.js.map +1 -1
  162. package/dist/esm/entities/OperationBatcher.d.ts +52 -0
  163. package/dist/esm/entities/OperationBatcher.js +161 -0
  164. package/dist/esm/entities/OperationBatcher.js.map +1 -0
  165. package/dist/esm/entities/types.d.ts +84 -0
  166. package/dist/esm/entities/types.js +2 -0
  167. package/dist/esm/entities/types.js.map +1 -0
  168. package/dist/esm/files/EntityFile.d.ts +5 -2
  169. package/dist/esm/files/EntityFile.js +8 -4
  170. package/dist/esm/files/EntityFile.js.map +1 -1
  171. package/dist/esm/files/FileManager.d.ts +3 -1
  172. package/dist/esm/files/FileManager.js +5 -3
  173. package/dist/esm/files/FileManager.js.map +1 -1
  174. package/dist/esm/files/FileStorage.js +7 -7
  175. package/dist/esm/files/FileStorage.js.map +1 -1
  176. package/dist/esm/files/utils.d.ts +2 -0
  177. package/dist/esm/files/utils.js +4 -2
  178. package/dist/esm/files/utils.js.map +1 -1
  179. package/dist/esm/idb.d.ts +2 -0
  180. package/dist/esm/idb.js +47 -3
  181. package/dist/esm/idb.js.map +1 -1
  182. package/dist/esm/index.d.ts +1 -1
  183. package/dist/esm/metadata/AckInfoStore.js +1 -1
  184. package/dist/esm/metadata/AckInfoStore.js.map +1 -1
  185. package/dist/esm/metadata/BaselinesStore.d.ts +4 -1
  186. package/dist/esm/metadata/BaselinesStore.js +19 -10
  187. package/dist/esm/metadata/BaselinesStore.js.map +1 -1
  188. package/dist/esm/metadata/LocalReplicaStore.d.ts +1 -1
  189. package/dist/esm/metadata/LocalReplicaStore.js +11 -5
  190. package/dist/esm/metadata/LocalReplicaStore.js.map +1 -1
  191. package/dist/esm/metadata/Metadata.d.ts +26 -5
  192. package/dist/esm/metadata/Metadata.js +56 -19
  193. package/dist/esm/metadata/Metadata.js.map +1 -1
  194. package/dist/esm/metadata/OperationsStore.d.ts +3 -0
  195. package/dist/esm/metadata/OperationsStore.js +35 -15
  196. package/dist/esm/metadata/OperationsStore.js.map +1 -1
  197. package/dist/esm/migration/openDatabase.js +32 -11
  198. package/dist/esm/migration/openDatabase.js.map +1 -1
  199. package/dist/esm/queries/BaseQuery.js +13 -1
  200. package/dist/esm/queries/BaseQuery.js.map +1 -1
  201. package/dist/esm/queries/CollectionQueries.js +1 -1
  202. package/dist/esm/queries/CollectionQueries.js.map +1 -1
  203. package/dist/esm/queries/FindAllQuery.js +1 -0
  204. package/dist/esm/queries/FindAllQuery.js.map +1 -1
  205. package/dist/esm/queries/QueryCache.d.ts +1 -0
  206. package/dist/esm/queries/QueryCache.js +4 -0
  207. package/dist/esm/queries/QueryCache.js.map +1 -1
  208. package/dist/esm/queries/QueryableStorage.d.ts +20 -0
  209. package/dist/esm/queries/QueryableStorage.js +80 -0
  210. package/dist/esm/queries/QueryableStorage.js.map +1 -0
  211. package/dist/esm/queries/dbQueries.js +13 -3
  212. package/dist/esm/queries/dbQueries.js.map +1 -1
  213. package/dist/esm/sync/FileSync.d.ts +1 -0
  214. package/dist/esm/sync/FileSync.js +1 -0
  215. package/dist/esm/sync/FileSync.js.map +1 -1
  216. package/dist/esm/sync/PushPullSync.d.ts +2 -1
  217. package/dist/esm/sync/PushPullSync.js +7 -1
  218. package/dist/esm/sync/PushPullSync.js.map +1 -1
  219. package/dist/esm/sync/Sync.d.ts +6 -3
  220. package/dist/esm/sync/Sync.js +9 -4
  221. package/dist/esm/sync/Sync.js.map +1 -1
  222. package/dist/esm/sync/WebSocketSync.d.ts +4 -1
  223. package/dist/esm/sync/WebSocketSync.js +41 -11
  224. package/dist/esm/sync/WebSocketSync.js.map +1 -1
  225. package/dist/tsconfig-cjs.tsbuildinfo +1 -1
  226. package/dist/tsconfig.tsbuildinfo +1 -1
  227. package/package.json +8 -7
  228. package/src/DocumentManager.ts +1 -1
  229. package/src/IDBService.ts +78 -17
  230. package/src/UndoHistory.ts +5 -3
  231. package/src/__tests__/batching.test.ts +5 -2
  232. package/src/__tests__/documents.test.ts +44 -6
  233. package/src/__tests__/fixtures/testStorage.ts +3 -0
  234. package/src/__tests__/legacyOids.test.ts +53 -17
  235. package/src/__tests__/mutations.test.ts +9 -3
  236. package/src/__tests__/queries.test.ts +6 -2
  237. package/src/__tests__/setup/indexedDB.ts +8 -1
  238. package/src/__tests__/undo.test.ts +17 -9
  239. package/src/client/Client.ts +7 -3
  240. package/src/client/ClientDescriptor.ts +24 -8
  241. package/src/context.ts +16 -1
  242. package/src/entities/Entity.test.ts +218 -0
  243. package/src/entities/Entity.ts +696 -616
  244. package/src/entities/EntityCache.ts +41 -0
  245. package/src/entities/EntityMetadata.ts +364 -0
  246. package/src/entities/EntityStore.ts +384 -621
  247. package/src/entities/OperationBatcher.ts +251 -0
  248. package/src/entities/types.ts +154 -0
  249. package/src/files/EntityFile.ts +9 -4
  250. package/src/files/FileManager.ts +5 -3
  251. package/src/files/FileStorage.ts +7 -13
  252. package/src/files/utils.ts +6 -2
  253. package/src/idb.ts +51 -3
  254. package/src/index.ts +1 -1
  255. package/src/metadata/AckInfoStore.ts +1 -1
  256. package/src/metadata/BaselinesStore.ts +16 -24
  257. package/src/metadata/LocalReplicaStore.ts +13 -6
  258. package/src/metadata/Metadata.ts +109 -24
  259. package/src/metadata/OperationsStore.ts +37 -16
  260. package/src/migration/openDatabase.ts +32 -10
  261. package/src/queries/BaseQuery.ts +14 -1
  262. package/src/queries/CollectionQueries.ts +1 -1
  263. package/src/queries/FindAllQuery.ts +4 -0
  264. package/src/queries/QueryCache.ts +5 -0
  265. package/src/queries/QueryableStorage.ts +107 -0
  266. package/src/queries/dbQueries.ts +10 -3
  267. package/src/sync/FileSync.ts +2 -0
  268. package/src/sync/PushPullSync.ts +8 -1
  269. package/src/sync/Sync.ts +14 -6
  270. package/src/sync/WebSocketSync.ts +47 -10
  271. package/dist/cjs/entities/DocumentFamiliyCache.d.ts +0 -96
  272. package/dist/cjs/entities/DocumentFamiliyCache.js +0 -287
  273. package/dist/cjs/entities/DocumentFamiliyCache.js.map +0 -1
  274. package/dist/esm/entities/DocumentFamiliyCache.d.ts +0 -96
  275. package/dist/esm/entities/DocumentFamiliyCache.js +0 -283
  276. package/dist/esm/entities/DocumentFamiliyCache.js.map +0 -1
  277. package/src/entities/DocumentFamiliyCache.ts +0 -426
  278. package/src/entities/design.tldr +0 -808
@@ -1,492 +1,348 @@
1
- import { assert, assignOid, Batcher, decomposeOid, generateId, getIndexValues, getOidRoot, getUndoOperations, groupBaselinesByRootOid, groupPatchesByIdentifier, groupPatchesByRootOid, removeOidsFromAllSubObjects, } from '@verdant-web/common';
1
+ import { assert, assignOid, decomposeOid, getOidRoot, groupBaselinesByRootOid, groupPatchesByOid, groupPatchesByRootOid, isRootOid, removeOidsFromAllSubObjects, } from '@verdant-web/common';
2
+ import { Entity } from './Entity.js';
3
+ import { Disposable } from '../utils/Disposable.js';
4
+ import { EntityFamilyMetadata } from './EntityMetadata.js';
5
+ import { OperationBatcher } from './OperationBatcher.js';
6
+ import { QueryableStorage } from '../queries/QueryableStorage.js';
7
+ import { WeakEvent } from 'weak-event';
2
8
  import { processValueFiles } from '../files/utils.js';
3
- import { storeRequestPromise } from '../idb.js';
4
- import { DocumentFamilyCache } from './DocumentFamiliyCache.js';
5
- const DEFAULT_BATCH_KEY = '@@default';
6
- export class EntityStore {
7
- get log() {
8
- return this.context.log;
9
- }
10
- get db() {
11
- return this.context.documentDb;
12
- }
13
- get undoHistory() {
14
- return this.context.undoHistory;
15
- }
16
- get schema() {
17
- return this.context.schema;
18
- }
19
- constructor({ context, meta, batchTimeout = 200, files, }) {
20
- this.documentFamilyCaches = new Map();
21
- this.unsubscribes = [];
22
- this._disposed = false;
23
- this.currentBatchKey = DEFAULT_BATCH_KEY;
24
- this.setContext = (context) => {
25
- this.context = context;
9
+ var AbortReason;
10
+ (function (AbortReason) {
11
+ AbortReason[AbortReason["Reset"] = 0] = "Reset";
12
+ })(AbortReason || (AbortReason = {}));
13
+ export class EntityStore extends Disposable {
14
+ constructor({ ctx, meta, files, }) {
15
+ super();
16
+ this.events = {
17
+ add: new WeakEvent(),
18
+ replace: new WeakEvent(),
19
+ resetAll: new WeakEvent(),
26
20
  };
27
- this.getDocumentSchema = (oid) => {
28
- const { collection } = decomposeOid(oid);
29
- if (!this.schema.collections[collection]) {
30
- this.log('warn', `Missing schema for collection: ${collection}`);
31
- return { schema: null, readonlyKeys: [] };
32
- }
33
- const schema = this.schema.collections[collection];
34
- return {
35
- readonlyKeys: [schema.primaryKey],
36
- schema: {
37
- type: 'object',
38
- properties: schema.fields,
39
- },
40
- };
41
- };
42
- this.refreshFamilyCache = async (familyCache, dropUnconfirmed = false, dropAll = false) => {
43
- // avoid writing to disposed db
44
- if (this._disposed) {
45
- this.context.log('debug', `EntityStore is disposed, not refreshing ${familyCache.oid} cache`);
21
+ this.cache = new Map();
22
+ this.pendingEntityPromises = new Map();
23
+ // halts the current data queue processing
24
+ this.abortDataQueueController = new AbortController();
25
+ this.ongoingResetPromise = null;
26
+ this.entityFinalizationRegistry = new FinalizationRegistry((oid) => {
27
+ this.ctx.log('debug', 'Entity GC', oid);
28
+ });
29
+ // internal-ish API to load remote / stored data
30
+ this.addData = async (data) => {
31
+ if (this.disposed) {
32
+ this.ctx.log('warn', 'EntityStore is disposed, not adding incoming data');
46
33
  return;
47
34
  }
48
- // metadata must be loaded from database to initialize family cache
49
- const transaction = this.meta.createTransaction([
50
- 'baselines',
51
- 'operations',
52
- ]);
53
- const baselines = [];
54
- const operations = [];
55
- await Promise.all([
56
- this.meta.baselines.iterateOverAllForDocument(familyCache.oid, (baseline) => {
57
- baselines.push(baseline);
58
- }, {
59
- transaction,
60
- mode: 'readwrite',
61
- }),
62
- this.meta.operations.iterateOverAllOperationsForDocument(familyCache.oid, (op) => {
63
- op.confirmed = true;
64
- operations.push(op);
65
- }, { transaction, mode: 'readwrite' }),
66
- ]);
67
- familyCache.reset({
68
- operations,
69
- baselines,
70
- dropExistingUnconfirmed: dropUnconfirmed,
71
- dropAll,
72
- });
73
- };
74
- this.openFamilyCache = async (oid) => {
75
- const documentOid = getOidRoot(oid);
76
- let familyCache = this.documentFamilyCaches.get(documentOid);
77
- if (!familyCache) {
78
- this.context.log('debug', 'opening family cache for', documentOid);
79
- // metadata must be loaded from database to initialize family cache
80
- familyCache = new DocumentFamilyCache({
81
- oid: documentOid,
82
- store: this,
83
- context: this.context,
35
+ // for resets - abort any other changes, reset everything,
36
+ // then proceed
37
+ if (data.reset) {
38
+ this.ctx.log('info', 'Resetting local store to replicate remote synced data - dropping any current transactions');
39
+ // cancel any other ongoing data - it will all
40
+ // be replaced by the reset
41
+ this.abortDataQueueController.abort(AbortReason.Reset);
42
+ this.abortDataQueueController = new AbortController();
43
+ this.ongoingResetPromise = this.resetData().finally(() => {
44
+ this.ongoingResetPromise = null;
84
45
  });
85
- // PROBLEM: because the next line is async, it yields to
86
- // queued promises which may need data from this cache,
87
- // but the cache is empty. But if we move the set to
88
- // after the async, we can clobber an existing cache
89
- // with race conditions...
90
- // So as an attempt to fix that, I've added a promise
91
- // on DocumentFamilyCache which I manually resolve
92
- // with setInitialized, then await initializedPromise
93
- // further down even if there was a cache hit.
94
- // Surely there is a better pattern for this.
95
- // FIXME:
96
- this.documentFamilyCaches.set(documentOid, familyCache);
97
- await this.refreshFamilyCache(familyCache);
98
- familyCache.setInitialized();
99
- // this.unsubscribes.push(
100
- // familyCache.subscribe('change:*', this.onEntityChange),
101
- // );
102
- // TODO: cleanup cache when all documents are disposed
103
46
  }
104
- await familyCache.initializedPromise;
105
- return familyCache;
106
- };
107
- this.onEntityChange = async (oid) => {
108
- // queueMicrotask(() => this.writeDocumentToStorage(oid));
47
+ // await either the reset we just started, or any that was
48
+ // in progress when this data came in.
49
+ if (this.ongoingResetPromise) {
50
+ this.ctx.log('debug', 'Waiting for ongoing reset to complete');
51
+ await this.ongoingResetPromise;
52
+ this.ctx.log('debug', 'Ongoing reset complete');
53
+ }
54
+ await this.processData(data);
109
55
  };
110
- this.writeDocumentToStorage = async (oid) => {
111
- var _a;
112
- if (this._disposed) {
113
- this.log('warn', 'EntityStore is disposed, not writing to storage');
56
+ this.resetData = async () => {
57
+ if (this.disposed) {
58
+ this.ctx.log('warn', 'EntityStore is disposed, not resetting local data');
114
59
  return;
115
60
  }
116
- const rootOid = getOidRoot(oid);
117
- const { id, collection } = decomposeOid(rootOid);
118
- const entity = await this.get(rootOid);
119
- if (this._disposed) {
120
- this.log('warn', 'EntityStore is disposed, not writing to storage');
61
+ await this.meta.reset();
62
+ await this.queryableStorage.reset();
63
+ this.events.resetAll.invoke(this);
64
+ };
65
+ this.processData = async (data) => {
66
+ var _a, _b, _c;
67
+ if (this.disposed) {
68
+ this.ctx.log('warn', 'EntityStore is disposed, not processing incoming data');
121
69
  return;
122
70
  }
123
- const snapshot = entity === null || entity === void 0 ? void 0 : entity.getSnapshot();
124
- if (snapshot) {
125
- const stored = getIndexValues(this.schema.collections[collection], snapshot);
126
- try {
127
- const tx = this.db.transaction(collection, 'readwrite');
128
- const store = tx.objectStore(collection);
129
- await storeRequestPromise(store.put(stored));
130
- this.log('info', '📝', 'wrote', collection, id, 'to storage', stored);
71
+ const baselines = (_a = data === null || data === void 0 ? void 0 : data.baselines) !== null && _a !== void 0 ? _a : [];
72
+ const operations = (_b = data === null || data === void 0 ? void 0 : data.operations) !== null && _b !== void 0 ? _b : [];
73
+ this.ctx.log('debug', 'Processing incoming data', {
74
+ operations: operations.length,
75
+ baselines: baselines.length,
76
+ reset: !!data.reset,
77
+ });
78
+ const allDocumentOids = Array.from(new Set(baselines
79
+ .map((b) => getOidRoot(b.oid))
80
+ .concat(operations.map((o) => getOidRoot(o.oid)))));
81
+ const baselinesGroupedByOid = groupBaselinesByRootOid(baselines);
82
+ const operationsGroupedByOid = groupPatchesByRootOid(operations);
83
+ this.ctx.log('debug', 'Applying data to live entities');
84
+ // synchronously add/replace data in any open entities via eventing
85
+ for (const oid of allDocumentOids) {
86
+ const baselines = baselinesGroupedByOid[oid];
87
+ const operations = (_c = operationsGroupedByOid[oid]) !== null && _c !== void 0 ? _c : [];
88
+ const groupedOperations = groupPatchesByOid(operations);
89
+ // what happens if an entity is being hydrated
90
+ // while this is happening? - we wait for the hydration promise
91
+ // to complete, then invoke the event
92
+ const event = data.reset ? this.events.replace : this.events.add;
93
+ const hydrationPromise = this.pendingEntityPromises.get(oid);
94
+ if (hydrationPromise) {
95
+ hydrationPromise.then(() => {
96
+ event.invoke(this, {
97
+ oid,
98
+ baselines,
99
+ operations: groupedOperations,
100
+ isLocal: false,
101
+ });
102
+ });
131
103
  }
132
- catch (err) {
133
- // if the document can't be written, something's very wrong :(
134
- // log the error and move on...
135
- this.log("⚠️ CRITICAL: possibly corrupt data couldn't be written to queryable storage. This is probably a bug in verdant! Please report at https://github.com/a-type/verdant/issues", '\n', 'Invalid data:', JSON.stringify(stored));
104
+ else {
105
+ if (this.cache.has(oid)) {
106
+ this.ctx.log('debug', 'Cache has', oid, ', an event should follow.');
107
+ }
108
+ event.invoke(this, {
109
+ oid,
110
+ baselines,
111
+ operations: groupedOperations,
112
+ isLocal: false,
113
+ });
136
114
  }
137
115
  }
138
- else {
139
- try {
140
- const tx = this.db.transaction(collection, 'readwrite');
141
- const store = tx.objectStore(collection);
142
- await storeRequestPromise(store.delete(id));
143
- this.log('info', '❌', 'deleted', collection, id, 'from storage');
116
+ const abortOptions = {
117
+ abort: this.abortDataQueueController.signal,
118
+ };
119
+ // then, asynchronously add to the database
120
+ await this.meta.insertData(data, abortOptions);
121
+ // FIXME: entities hydrated here are not seeing
122
+ // the operations just inserted above!!
123
+ // IDEA: can we coordinate here with hydrate promises
124
+ // based on affected OIDs?
125
+ // recompute all affected documents for querying
126
+ const entities = await Promise.all(allDocumentOids.map(async (oid) => {
127
+ const entity = await this.hydrate(oid, abortOptions);
128
+ // if the entity is not found, we return a stub that
129
+ // indicates it's deleted and should be cleared
130
+ return (entity !== null && entity !== void 0 ? entity : {
131
+ oid,
132
+ getSnapshot() {
133
+ return null;
134
+ },
135
+ });
136
+ }));
137
+ try {
138
+ await this.queryableStorage.saveEntities(entities, abortOptions);
139
+ }
140
+ catch (err) {
141
+ if (this.disposed) {
142
+ this.ctx.log('warn', 'Error saving entities to queryable storage - EntityStore is disposed', err);
144
143
  }
145
- catch (err) {
146
- if (err instanceof Error) {
147
- // it's ok if the collection doesn't exist or the document
148
- // doesn't exist.
149
- if (err instanceof DOMException &&
150
- ((_a = err.message) === null || _a === void 0 ? void 0 : _a.includes('not found'))) {
151
- this.log('debug', 'document not found in storage', oid);
152
- }
153
- else {
154
- throw err;
155
- }
156
- }
144
+ else {
145
+ this.ctx.log('error', 'Error saving entities to queryable storage', err);
157
146
  }
158
147
  }
159
148
  };
160
- this.get = async (oid) => {
161
- const familyCache = await this.openFamilyCache(oid);
162
- const { schema, readonlyKeys } = this.getDocumentSchema(oid);
163
- if (!schema) {
164
- return null;
149
+ // internal-ish API for creating Entities from OIDs
150
+ // when query results come in
151
+ this.hydrate = async (oid, opts) => {
152
+ if (!isRootOid(oid)) {
153
+ throw new Error('Cannot hydrate non-root entity');
165
154
  }
166
- return familyCache.getEntity({ oid, fieldSchema: schema, readonlyKeys });
167
- };
168
- /**
169
- * Advanced usage!
170
- * Immediately returns an entity if it exists in the memory cache. An
171
- * entity would be cached if it has been retrieved by a live query.
172
- */
173
- this.getCached = (oid) => {
174
- const cache = this.documentFamilyCaches.get(oid);
175
- if (cache) {
176
- const { schema, readonlyKeys } = this.getDocumentSchema(oid);
177
- if (!schema) {
155
+ if (this.cache.has(oid)) {
156
+ this.ctx.log('debug', 'Hydrating entity from cache', oid);
157
+ const cached = this.cache.get(oid);
158
+ if (cached) {
159
+ const entity = cached.deref();
160
+ if (entity) {
161
+ if (entity.deleted) {
162
+ return null;
163
+ }
164
+ return entity;
165
+ }
166
+ else {
167
+ this.ctx.log('debug', "Removing GC'd entity from cache", oid);
168
+ this.cache.delete(oid);
169
+ }
170
+ }
171
+ }
172
+ // we don't want to hydrate two entities in parallel, so
173
+ // we use a promise to ensure that only one is ever
174
+ // constructed at a time
175
+ const pendingPromise = this.pendingEntityPromises.get(oid);
176
+ if (!pendingPromise) {
177
+ this.ctx.log('debug', 'Hydrating entity from storage', oid);
178
+ const entity = this.constructEntity(oid);
179
+ if (!entity) {
178
180
  return null;
179
181
  }
180
- return cache.getEntity({ oid, fieldSchema: schema, readonlyKeys });
182
+ const pendingPromise = this.loadEntity(entity, opts);
183
+ pendingPromise.finally(() => {
184
+ this.pendingEntityPromises.delete(oid);
185
+ });
186
+ this.pendingEntityPromises.set(oid, pendingPromise);
187
+ return pendingPromise;
188
+ }
189
+ else {
190
+ this.ctx.log('debug', 'Waiting for entity hydration', oid);
191
+ return pendingPromise;
181
192
  }
182
- return null;
183
193
  };
194
+ this.destroy = async () => {
195
+ this.dispose();
196
+ await this.batcher.flushAll();
197
+ };
198
+ // public APIs for manipulating entities
184
199
  /**
185
- * Creates a new document and returns an Entity for it. The created
186
- * document is submitted to storage and sync.
200
+ * Creates a new Entity with the given initial data.
187
201
  */
188
- this.create = async (initial, oid, options) => {
189
- // remove all OID associations from initial data
202
+ this.create = async (initial, oid, { undoable = true } = {}) => {
203
+ this.ctx.log('debug', 'Creating new entity', oid);
204
+ const { collection } = decomposeOid(oid);
205
+ // remove any OID associations from the initial data
190
206
  removeOidsFromAllSubObjects(initial);
191
- // first grab any file and replace them with refs
207
+ // grab files and replace them with refs
192
208
  const processed = processValueFiles(initial, this.files.add);
193
209
  assignOid(processed, oid);
194
- const operations = this.meta.patchCreator.createInitialize(processed, oid);
195
- const familyCache = await this.openFamilyCache(oid);
196
- familyCache.insertLocalOperations(operations);
197
- // don't enqueue these, submit as distinct operation.
198
- // we do this so it can be immediately queryable from storage...
199
- // only holding it in memory would introduce lag before it shows up
200
- // in other queries.
201
- await this.submitOperations(operations, options);
202
- const { schema, readonlyKeys } = this.getDocumentSchema(oid);
203
- if (!schema) {
204
- throw new Error(`Cannot create a document in the ${decomposeOid(oid).collection} collection; it is not defined in the current schema version.`);
210
+ // creating a new Entity with no data, then preloading the operations
211
+ const entity = this.constructEntity(oid);
212
+ if (!entity) {
213
+ throw new Error(`Could not put new document: no schema exists for collection ${collection}`);
205
214
  }
206
- return familyCache.getEntity({ oid, fieldSchema: schema, readonlyKeys });
207
- };
208
- this.addOperationsToOpenCaches = async (operations, info) => {
209
- const operationsByOid = groupPatchesByRootOid(operations);
210
- const oids = Object.keys(operationsByOid);
211
- oids.forEach((oid) => {
212
- const familyCache = this.documentFamilyCaches.get(oid);
213
- if (familyCache) {
214
- this.log('adding', info.confirmed ? 'confirmed' : 'unconfirmed', 'operations to cache', oid, operationsByOid[oid].length);
215
- if (info.isLocal) {
216
- familyCache.insertLocalOperations(operationsByOid[oid]);
217
- }
218
- else {
219
- familyCache.insertOperations(operationsByOid[oid], info);
220
- }
221
- }
215
+ const operations = this.meta.patchCreator.createInitialize(processed, oid);
216
+ await this.batcher.commitOperations(operations, {
217
+ undoable: !!undoable,
218
+ source: entity,
222
219
  });
220
+ // TODO: what happens if you create an entity with an OID that already
221
+ // exists?
222
+ // we still need to synchronously add the initial operations to the Entity
223
+ // even though they are flowing through the system
224
+ // TODO: this could be better aligned to avoid grouping here
225
+ const operationsGroupedByOid = groupPatchesByOid(operations);
226
+ this.events.add.invoke(this, {
227
+ operations: operationsGroupedByOid,
228
+ isLocal: true,
229
+ oid,
230
+ });
231
+ this.cache.set(oid, this.ctx.weakRef(entity));
232
+ return entity;
223
233
  };
224
- this.addBaselinesToOpenCaches = async (baselines, info) => {
225
- const baselinesByOid = groupBaselinesByRootOid(baselines);
226
- const oids = Object.keys(baselinesByOid);
234
+ this.deleteAll = async (oids, options) => {
235
+ this.ctx.log('info', 'Deleting documents', oids);
236
+ assert(oids.every((oid) => oid === getOidRoot(oid)), 'Only root documents may be deleted via client methods');
237
+ const allOids = await Promise.all(oids.flatMap(async (oid) => {
238
+ var _a;
239
+ const entity = await this.hydrate(oid);
240
+ return (_a = entity === null || entity === void 0 ? void 0 : entity.__getFamilyOids__()) !== null && _a !== void 0 ? _a : [];
241
+ }));
242
+ // remove the entities from cache
227
243
  oids.forEach((oid) => {
228
- const cache = this.documentFamilyCaches.get(oid);
229
- if (cache) {
230
- this.log('adding', 'baselines to cache', oid, baselinesByOid[oid].length);
231
- cache.insertBaselines(baselinesByOid[oid], info);
232
- }
244
+ this.cache.delete(oid);
245
+ this.ctx.log('debug', 'Deleted document from cache', oid);
246
+ });
247
+ // create the delete patches and wait for them to be applied
248
+ const operations = this.meta.patchCreator.createDeleteAll(allOids.flat());
249
+ await this.batcher.commitOperations(operations, {
250
+ undoable: (options === null || options === void 0 ? void 0 : options.undoable) === undefined ? true : options.undoable,
233
251
  });
234
252
  };
235
- this.addDataToOpenCaches = ({ baselines, operations, reset, isLocal, }) => {
236
- var _a, _b, _c, _d;
237
- const baselinesByDocumentOid = groupBaselinesByRootOid(baselines);
238
- const operationsByDocumentOid = groupPatchesByRootOid(operations);
239
- const allDocumentOids = Array.from(new Set(Object.keys(baselinesByDocumentOid).concat(Object.keys(operationsByDocumentOid))));
240
- for (const oid of allDocumentOids) {
241
- const familyCache = this.documentFamilyCaches.get(oid);
242
- if (familyCache) {
243
- familyCache.addData({
244
- operations: operationsByDocumentOid[oid] || [],
245
- baselines: baselinesByDocumentOid[oid] || [],
246
- reset,
247
- isLocal,
248
- });
249
- this.log('debug', 'Added data to cache for', oid, (_b = (_a = operationsByDocumentOid[oid]) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0, 'operations', (_d = (_c = baselinesByDocumentOid[oid]) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0, 'baselines');
250
- }
251
- else {
252
- this.log('debug', 'Could not add data to cache for', oid, 'because it is not open');
253
- }
254
- }
255
- return allDocumentOids;
253
+ this.delete = async (oid, options) => {
254
+ return this.deleteAll([oid], options);
256
255
  };
257
- this.addData = async ({ operations, baselines, reset, }) => {
258
- if (this._disposed) {
259
- this.log('warn', 'EntityStore is disposed, not adding data');
260
- return;
261
- }
262
- // convert operations to tagged operations with confirmed = false
263
- // while we process and store them. this is in-place so as to
264
- // not allocate a bunch of objects...
265
- const taggedOperations = operations;
266
- for (const op of taggedOperations) {
267
- op.confirmed = false;
268
- }
269
- let allDocumentOids = [];
270
- // in a reset scenario, it only makes things confusing if we
271
- // optimistically apply incoming operations, since the local
272
- // history is out of sync
273
- if (reset) {
274
- this.log('Resetting local store to replicate remote synced data', baselines.length, 'baselines, and', operations.length, 'operations');
275
- await this.meta.reset();
276
- await this.resetStoredDocuments();
277
- allDocumentOids = Array.from(new Set(baselines
278
- .map((b) => getOidRoot(b.oid))
279
- .concat(operations.map((o) => getOidRoot(o.oid)))));
280
- }
281
- else {
282
- // first, synchronously add data to any open caches for immediate change propagation
283
- allDocumentOids = this.addDataToOpenCaches({
284
- operations: taggedOperations,
285
- baselines,
286
- reset,
287
- });
288
- }
289
- // then, asynchronously add data to storage
290
- await this.meta.insertRemoteBaselines(baselines);
291
- await this.meta.insertRemoteOperations(operations);
292
- if (reset) {
293
- await this.refreshAllCaches(true, true);
294
- }
295
- // recompute all affected documents for querying
296
- for (const oid of allDocumentOids) {
297
- await this.writeDocumentToStorage(oid);
256
+ this.getCollectionSchema = (collectionName) => {
257
+ const schema = this.ctx.schema.collections[collectionName];
258
+ if (!schema) {
259
+ this.ctx.log('warn', `Missing schema for collection: ${collectionName}`);
260
+ return {
261
+ schema: null,
262
+ readonlyKeys: [],
263
+ };
298
264
  }
299
- // notify active queries
300
- const affectedCollections = Array.from(new Set(allDocumentOids.map((oid) => decomposeOid(oid).collection)));
301
- this.context.log('changes to collections', affectedCollections);
302
- this.context.entityEvents.emit('collectionsChanged', affectedCollections);
303
- };
304
- this.addLocalOperations = async (operations) => {
305
- this.log('Adding local operations', operations.length);
306
- this.addOperationsToOpenCaches(operations, {
307
- isLocal: true,
308
- confirmed: false,
309
- });
310
- this.operationBatcher.add({
311
- key: this.currentBatchKey,
312
- items: operations,
313
- });
314
- };
315
- this.batch = ({ undoable = true, batchName = generateId(), max = null, timeout = this.defaultBatchTimeout, } = {}) => {
316
- const internalBatch = this.operationBatcher.add({
317
- key: batchName,
318
- max,
319
- timeout,
320
- items: [],
321
- userData: { undoable },
322
- });
323
- const externalApi = {
324
- run: (fn) => {
325
- // while the provided function runs, operations are forwarded
326
- // to the new batch instead of default. this relies on the function
327
- // being synchronous.
328
- this.currentBatchKey = batchName;
329
- fn();
330
- this.currentBatchKey = DEFAULT_BATCH_KEY;
331
- return externalApi;
332
- },
333
- flush: async () => {
334
- // before running a batch, the default operations must be flushed
335
- // this better preserves undo history behavior...
336
- // if we left the default batch open while flushing a named batch,
337
- // then the default batch would be flushed after the named batch,
338
- // and the default batch could contain operations both prior and
339
- // after the named batch. this would result in a confusing undo
340
- // history where the first undo might reverse changes before and
341
- // after a set of other changes.
342
- await this.operationBatcher.flush(DEFAULT_BATCH_KEY);
343
- return internalBatch.flush();
344
- },
345
- discard: () => {
346
- this.operationBatcher.discard(batchName);
265
+ return {
266
+ // convert to object schema for compatibility
267
+ schema: {
268
+ type: 'object',
269
+ nullable: false,
270
+ properties: schema.fields,
347
271
  },
272
+ readonlyKeys: [schema.primaryKey],
348
273
  };
349
- return externalApi;
350
274
  };
351
275
  /**
352
- * @deprecated use `batch` instead
276
+ * Constructs an entity from an OID, but does not load it.
353
277
  */
354
- this.flushPatches = async () => {
355
- await this.operationBatcher.flush(this.currentBatchKey);
356
- };
357
- this.flushAllBatches = async () => {
358
- await Promise.all(this.operationBatcher.flushAll());
359
- };
360
- this.flushOperations = async (operations, batchKey, meta) => {
361
- if (!operations.length)
362
- return;
363
- this.log('Flushing operations', operations.length, 'to storage / sync');
364
- // rewrite timestamps of all operations to now - this preserves
365
- // the linear history of operations which are sent to the server.
366
- // even if multiple batches are spun up in parallel and flushed
367
- // after delay, the final operations in each one should reflect
368
- // when the batch flushed, not when the changes were made.
369
- // This also corresponds to user-observed behavior, since unconfirmed
370
- // operations are applied universally after confirmed operations locally,
371
- // so even operations which were made before a remote operation but
372
- // have not been confirmed yet will appear to come after the remote one
373
- // despite the provisional timestamp being earlier (see DocumentFamilyCache#computeView)
374
- for (const op of operations) {
375
- op.timestamp = this.meta.now;
376
- }
377
- await this.submitOperations(operations, meta);
378
- };
379
- this.submitOperations = async (operations, { undoable = true } = {}) => {
380
- if (undoable) {
381
- // FIXME: this is too slow and needs to be optimized.
382
- this.undoHistory.addUndo(await this.createUndo(operations));
383
- }
384
- await this.meta.insertLocalOperation(operations);
385
- // confirm the operations
386
- this.addDataToOpenCaches({ operations, baselines: [] });
387
- // recompute all affected documents for querying
388
- const allDocumentOids = Array.from(new Set(operations.map((op) => getOidRoot(op.oid))));
389
- for (const oid of allDocumentOids) {
390
- await this.writeDocumentToStorage(oid);
391
- }
392
- // TODO: find a more efficient and straightforward way to update affected
393
- // queries. Move to Metadata?
394
- const affectedCollections = new Set(operations.map(({ oid }) => decomposeOid(oid).collection));
395
- this.context.log('changes to collections', affectedCollections);
396
- this.context.entityEvents.emit('collectionsChanged', Array.from(affectedCollections));
397
- };
398
- this.getInverseOperations = async (ops) => {
399
- const grouped = groupPatchesByIdentifier(ops);
400
- const inverseOps = [];
401
- const getNow = () => this.meta.now;
402
- for (const [oid, patches] of Object.entries(grouped)) {
403
- const familyCache = await this.openFamilyCache(oid);
404
- let { view, deleted } = familyCache.computeConfirmedView(oid);
405
- const inverse = getUndoOperations(oid, view, patches, getNow);
406
- inverseOps.unshift(...inverse);
407
- }
408
- return inverseOps;
409
- };
410
- this.createUndo = async (ops) => {
411
- const inverseOps = await this.getInverseOperations(ops);
412
- return async () => {
413
- const redo = await this.createUndo(inverseOps);
414
- await this.submitOperations(inverseOps.map((op) => {
415
- op.timestamp = this.meta.now;
416
- return op;
417
- }),
418
- // undos should not generate their own undo operations
419
- // since they already calculate redo as the inverse.
420
- { undoable: false });
421
- return redo;
422
- };
423
- };
424
- this.delete = async (oid, options) => {
425
- assert(oid === getOidRoot(oid), 'Only root documents may be deleted via client methods');
426
- // we need to get all sub-object oids to delete alongside the root
427
- const allOids = await this.meta.getAllDocumentRelatedOids(oid);
428
- const patches = this.meta.patchCreator.createDeleteAll(allOids);
429
- // don't enqueue these, submit as distinct operation
430
- await this.submitOperations(patches, options);
431
- };
432
- this.deleteAll = async (oids, options) => {
433
- const allOids = await Promise.all(oids.map((oid) => this.meta.getAllDocumentRelatedOids(oid)));
434
- const patches = this.meta.patchCreator.createDeleteAll(allOids.flat());
435
- // don't enqueue these, submit as distinct operation
436
- await this.submitOperations(patches, options);
437
- };
438
- this.reset = async () => {
439
- this.context.log('warn', 'Resetting local database');
440
- await this.resetStoredDocuments();
441
- await this.refreshAllCaches(true);
442
- // this.context.entityEvents.emit(
443
- // 'collectionsChanged',
444
- // Object.keys(this.schema.collections),
445
- // );
446
- };
447
- this.destroy = async () => {
448
- this._disposed = true;
449
- for (const unsubscribe of this.unsubscribes) {
450
- unsubscribe();
278
+ this.constructEntity = (oid) => {
279
+ const { collection } = decomposeOid(oid);
280
+ const { schema, readonlyKeys } = this.getCollectionSchema(collection);
281
+ if (!schema) {
282
+ return null;
451
283
  }
452
- for (const cache of this.documentFamilyCaches.values()) {
453
- cache.dispose();
284
+ if (this.disposed) {
285
+ throw new Error('Cannot hydrate entity after store has been disposed');
454
286
  }
455
- this.documentFamilyCaches.clear();
456
- await this.flushAllBatches();
457
- };
458
- this.handleRebase = (baselines) => {
459
- this.log('debug', 'Reacting to rebases', baselines.length);
460
- // update any open caches with new baseline. this will automatically
461
- // drop operations before the baseline.
462
- this.addBaselinesToOpenCaches(baselines, { isLocal: true });
287
+ const metadataFamily = new EntityFamilyMetadata({
288
+ ctx: this.ctx,
289
+ onPendingOperations: this.onPendingOperations,
290
+ rootOid: oid,
291
+ });
292
+ // this is created synchronously so it's immediately available
293
+ // to begin capturing incoming data.
294
+ return new Entity({
295
+ ctx: this.ctx,
296
+ oid,
297
+ schema,
298
+ readonlyKeys,
299
+ files: this.files,
300
+ metadataFamily: metadataFamily,
301
+ patchCreator: this.meta.patchCreator,
302
+ events: this.events,
303
+ });
463
304
  };
464
- this.resetStoredDocuments = async () => {
465
- const tx = this.db.transaction(Object.keys(this.schema.collections), 'readwrite');
466
- for (const collection of Object.keys(this.schema.collections)) {
467
- const store = tx.objectStore(collection);
468
- await storeRequestPromise(store.clear());
469
- }
305
+ this.onPendingOperations = (operations) => {
306
+ this.batcher.addOperations(operations);
470
307
  };
471
- this.refreshAllCaches = async (dropUnconfirmed = false, dropAll = false) => {
472
- for (const [_, cache] of this.documentFamilyCaches) {
473
- await this.refreshFamilyCache(cache, dropUnconfirmed, dropAll);
308
+ /**
309
+ * Loads initial Entity data from storage
310
+ */
311
+ this.loadEntity = async (entity, opts) => {
312
+ const { operations, baselines } = await this.meta.getDocumentData(entity.oid, opts);
313
+ if (!baselines.length && !Object.keys(operations).length) {
314
+ this.ctx.log('debug', 'No data found for entity', entity.oid);
315
+ return null;
474
316
  }
317
+ this.ctx.log('debug', 'Loaded entity from storage', entity.oid);
318
+ this.events.replace.invoke(this, {
319
+ oid: entity.oid,
320
+ baselines,
321
+ operations,
322
+ isLocal: false,
323
+ });
324
+ // only set the cache after loading.
325
+ // TODO: is this cache/promise stuff redundant?
326
+ this.cache.set(entity.oid, this.ctx.weakRef(entity));
327
+ this.entityFinalizationRegistry.register(entity, entity.oid);
328
+ return entity;
475
329
  };
476
- this.context = context;
477
- this.defaultBatchTimeout = batchTimeout;
330
+ this.ctx = ctx;
478
331
  this.meta = meta;
479
332
  this.files = files;
480
- this.operationBatcher = new Batcher(this.flushOperations);
481
- // initialize default batch
482
- this.operationBatcher.add({
483
- key: DEFAULT_BATCH_KEY,
484
- items: [],
485
- max: 100,
486
- timeout: batchTimeout,
487
- userData: { undoable: true },
333
+ this.queryableStorage = new QueryableStorage({ ctx });
334
+ this.batcher = new OperationBatcher({
335
+ ctx,
336
+ meta,
337
+ entities: this,
488
338
  });
489
- this.unsubscribes.push(this.meta.subscribe('rebase', this.handleRebase));
339
+ }
340
+ // expose batch APIs
341
+ get batch() {
342
+ return this.batcher.batch;
343
+ }
344
+ get flushAllBatches() {
345
+ return this.batcher.flushAll;
490
346
  }
491
347
  }
492
348
  //# sourceMappingURL=EntityStore.js.map