@verdant-web/store 3.12.1 → 4.0.0-next.1

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 (279) hide show
  1. package/dist/bundle/index.js +11 -13
  2. package/dist/bundle/index.js.map +4 -4
  3. package/dist/esm/__tests__/batching.test.js +5 -5
  4. package/dist/esm/__tests__/batching.test.js.map +1 -1
  5. package/dist/esm/__tests__/entities.test.js +1 -1
  6. package/dist/esm/__tests__/entities.test.js.map +1 -1
  7. package/dist/esm/__tests__/fixtures/testStorage.d.ts +1 -3
  8. package/dist/esm/__tests__/fixtures/testStorage.js +3 -3
  9. package/dist/esm/__tests__/fixtures/testStorage.js.map +1 -1
  10. package/dist/esm/__tests__/queries.test.js.map +1 -1
  11. package/dist/esm/backup.d.ts +3 -4
  12. package/dist/esm/backup.js.map +1 -1
  13. package/dist/esm/client/Client.d.ts +28 -33
  14. package/dist/esm/client/Client.js +50 -161
  15. package/dist/esm/client/Client.js.map +1 -1
  16. package/dist/esm/client/ClientDescriptor.d.ts +8 -11
  17. package/dist/esm/client/ClientDescriptor.js +39 -141
  18. package/dist/esm/client/ClientDescriptor.js.map +1 -1
  19. package/dist/esm/context/Time.d.ts +13 -0
  20. package/dist/esm/context/Time.js +27 -0
  21. package/dist/esm/context/Time.js.map +1 -0
  22. package/dist/esm/context/context.d.ts +170 -0
  23. package/dist/esm/{context.js.map → context/context.js.map} +1 -1
  24. package/dist/esm/entities/DocumentManager.js.map +1 -1
  25. package/dist/esm/entities/Entity.d.ts +4 -5
  26. package/dist/esm/entities/Entity.js +5 -3
  27. package/dist/esm/entities/Entity.js.map +1 -1
  28. package/dist/esm/entities/Entity.test.js +4 -3
  29. package/dist/esm/entities/Entity.test.js.map +1 -1
  30. package/dist/esm/entities/EntityCache.d.ts +0 -3
  31. package/dist/esm/entities/EntityCache.js +0 -9
  32. package/dist/esm/entities/EntityCache.js.map +1 -1
  33. package/dist/esm/entities/EntityMetadata.d.ts +1 -1
  34. package/dist/esm/entities/EntityMetadata.js +6 -5
  35. package/dist/esm/entities/EntityMetadata.js.map +1 -1
  36. package/dist/esm/entities/EntityStore.d.ts +2 -6
  37. package/dist/esm/entities/EntityStore.js +22 -16
  38. package/dist/esm/entities/EntityStore.js.map +1 -1
  39. package/dist/esm/entities/OperationBatcher.d.ts +2 -5
  40. package/dist/esm/entities/OperationBatcher.js +9 -7
  41. package/dist/esm/entities/OperationBatcher.js.map +1 -1
  42. package/dist/esm/errors.d.ts +8 -0
  43. package/dist/esm/errors.js +12 -0
  44. package/dist/esm/errors.js.map +1 -0
  45. package/dist/esm/files/EntityFile.d.ts +6 -3
  46. package/dist/esm/files/EntityFile.js +22 -19
  47. package/dist/esm/files/EntityFile.js.map +1 -1
  48. package/dist/esm/files/FileManager.d.ts +8 -39
  49. package/dist/esm/files/FileManager.js +26 -170
  50. package/dist/esm/files/FileManager.js.map +1 -1
  51. package/dist/esm/files/utils.d.ts +0 -1
  52. package/dist/esm/files/utils.js +0 -14
  53. package/dist/esm/files/utils.js.map +1 -1
  54. package/dist/esm/index.d.ts +1 -2
  55. package/dist/esm/index.js +0 -1
  56. package/dist/esm/index.js.map +1 -1
  57. package/dist/esm/{metadata → persistence}/MessageCreator.d.ts +5 -6
  58. package/dist/esm/{metadata → persistence}/MessageCreator.js +31 -38
  59. package/dist/esm/persistence/MessageCreator.js.map +1 -0
  60. package/dist/esm/persistence/PersistenceFiles.d.ts +48 -0
  61. package/dist/esm/persistence/PersistenceFiles.js +160 -0
  62. package/dist/esm/persistence/PersistenceFiles.js.map +1 -0
  63. package/dist/esm/persistence/PersistenceMetadata.d.ts +69 -0
  64. package/dist/esm/persistence/PersistenceMetadata.js +302 -0
  65. package/dist/esm/persistence/PersistenceMetadata.js.map +1 -0
  66. package/dist/esm/persistence/PersistenceQueries.d.ts +34 -0
  67. package/dist/esm/persistence/PersistenceQueries.js +15 -0
  68. package/dist/esm/persistence/PersistenceQueries.js.map +1 -0
  69. package/dist/esm/persistence/PersistenceRebaser.d.ts +32 -0
  70. package/dist/esm/persistence/PersistenceRebaser.js +120 -0
  71. package/dist/esm/persistence/PersistenceRebaser.js.map +1 -0
  72. package/dist/esm/{IDBService.d.ts → persistence/idb/IdbService.d.ts} +9 -7
  73. package/dist/esm/{IDBService.js → persistence/idb/IdbService.js} +29 -8
  74. package/dist/esm/persistence/idb/IdbService.js.map +1 -0
  75. package/dist/esm/persistence/idb/files/IdbPersistenceFileDb.d.ts +58 -0
  76. package/dist/esm/{files/FileStorage.js → persistence/idb/files/IdbPersistenceFileDb.js} +85 -50
  77. package/dist/esm/persistence/idb/files/IdbPersistenceFileDb.js.map +1 -0
  78. package/dist/esm/persistence/idb/idbPersistence.d.ts +19 -0
  79. package/dist/esm/persistence/idb/idbPersistence.js +80 -0
  80. package/dist/esm/persistence/idb/idbPersistence.js.map +1 -0
  81. package/dist/esm/persistence/idb/metadata/IdbMetadataDb.d.ts +72 -0
  82. package/dist/esm/persistence/idb/metadata/IdbMetadataDb.js +235 -0
  83. package/dist/esm/persistence/idb/metadata/IdbMetadataDb.js.map +1 -0
  84. package/dist/esm/{metadata → persistence/idb/metadata}/openMetadataDatabase.d.ts +3 -1
  85. package/dist/esm/{metadata → persistence/idb/metadata}/openMetadataDatabase.js +12 -3
  86. package/dist/esm/persistence/idb/metadata/openMetadataDatabase.js.map +1 -0
  87. package/dist/esm/persistence/idb/queries/IdbQueryDb.d.ts +41 -0
  88. package/dist/esm/persistence/idb/queries/IdbQueryDb.js +174 -0
  89. package/dist/esm/persistence/idb/queries/IdbQueryDb.js.map +1 -0
  90. package/dist/esm/{migration → persistence/idb/queries/migration}/db.d.ts +1 -1
  91. package/dist/esm/{migration → persistence/idb/queries/migration}/db.js +10 -48
  92. package/dist/esm/persistence/idb/queries/migration/db.js.map +1 -0
  93. package/dist/esm/persistence/idb/queries/migration/engine.d.ts +12 -0
  94. package/dist/esm/{migration → persistence/idb/queries/migration}/engine.js +29 -46
  95. package/dist/esm/persistence/idb/queries/migration/engine.js.map +1 -0
  96. package/dist/esm/{migration → persistence/idb/queries/migration}/migrations.d.ts +1 -3
  97. package/dist/esm/{migration → persistence/idb/queries/migration}/migrations.js +11 -10
  98. package/dist/esm/persistence/idb/queries/migration/migrations.js.map +1 -0
  99. package/dist/esm/{migration → persistence/idb/queries/migration}/openQueryDatabase.d.ts +1 -3
  100. package/dist/esm/{migration → persistence/idb/queries/migration}/openQueryDatabase.js +4 -7
  101. package/dist/esm/persistence/idb/queries/migration/openQueryDatabase.js.map +1 -0
  102. package/dist/esm/{migration → persistence/idb/queries/migration}/paths.js +2 -2
  103. package/dist/esm/persistence/idb/queries/migration/paths.js.map +1 -0
  104. package/dist/esm/persistence/idb/queries/migration/paths.test.js.map +1 -0
  105. package/dist/esm/persistence/idb/queries/migration/types.d.ts +6 -0
  106. package/dist/esm/persistence/idb/queries/migration/types.js.map +1 -0
  107. package/dist/esm/persistence/idb/queries/ranges.d.ts +2 -0
  108. package/dist/esm/persistence/idb/queries/ranges.js +66 -0
  109. package/dist/esm/persistence/idb/queries/ranges.js.map +1 -0
  110. package/dist/esm/{idb.d.ts → persistence/idb/util.d.ts} +11 -0
  111. package/dist/esm/{idb.js → persistence/idb/util.js} +58 -1
  112. package/dist/esm/persistence/idb/util.js.map +1 -0
  113. package/dist/esm/persistence/interfaces.d.ts +181 -0
  114. package/dist/esm/persistence/interfaces.js +2 -0
  115. package/dist/esm/persistence/interfaces.js.map +1 -0
  116. package/dist/esm/persistence/persistence.d.ts +4 -0
  117. package/dist/esm/persistence/persistence.js +126 -0
  118. package/dist/esm/persistence/persistence.js.map +1 -0
  119. package/dist/esm/queries/BaseQuery.d.ts +2 -1
  120. package/dist/esm/queries/BaseQuery.js +3 -0
  121. package/dist/esm/queries/BaseQuery.js.map +1 -1
  122. package/dist/esm/queries/CollectionQueries.d.ts +1 -1
  123. package/dist/esm/queries/FindAllQuery.js +1 -3
  124. package/dist/esm/queries/FindAllQuery.js.map +1 -1
  125. package/dist/esm/queries/FindInfiniteQuery.js +2 -5
  126. package/dist/esm/queries/FindInfiniteQuery.js.map +1 -1
  127. package/dist/esm/queries/FindOneQuery.js +1 -3
  128. package/dist/esm/queries/FindOneQuery.js.map +1 -1
  129. package/dist/esm/queries/FindPageQuery.js +1 -3
  130. package/dist/esm/queries/FindPageQuery.js.map +1 -1
  131. package/dist/esm/queries/QueryCache.d.ts +1 -1
  132. package/dist/esm/queries/QueryCache.js +4 -0
  133. package/dist/esm/queries/QueryCache.js.map +1 -1
  134. package/dist/esm/sync/FileSync.d.ts +23 -8
  135. package/dist/esm/sync/FileSync.js +76 -28
  136. package/dist/esm/sync/FileSync.js.map +1 -1
  137. package/dist/esm/sync/PresenceManager.d.ts +4 -3
  138. package/dist/esm/sync/PresenceManager.js +2 -2
  139. package/dist/esm/sync/PresenceManager.js.map +1 -1
  140. package/dist/esm/sync/PushPullSync.d.ts +4 -6
  141. package/dist/esm/sync/PushPullSync.js +13 -12
  142. package/dist/esm/sync/PushPullSync.js.map +1 -1
  143. package/dist/esm/sync/Sync.d.ts +10 -11
  144. package/dist/esm/sync/Sync.js +55 -30
  145. package/dist/esm/sync/Sync.js.map +1 -1
  146. package/dist/esm/sync/WebSocketSync.d.ts +4 -6
  147. package/dist/esm/sync/WebSocketSync.js +20 -22
  148. package/dist/esm/sync/WebSocketSync.js.map +1 -1
  149. package/dist/esm/utils/Disposable.d.ts +5 -2
  150. package/dist/esm/utils/Disposable.js +3 -2
  151. package/dist/esm/utils/Disposable.js.map +1 -1
  152. package/dist/esm/utils/wip.d.ts +2 -0
  153. package/dist/esm/utils/wip.js +5 -0
  154. package/dist/esm/utils/wip.js.map +1 -0
  155. package/package.json +2 -2
  156. package/src/__tests__/batching.test.ts +6 -6
  157. package/src/__tests__/entities.test.ts +1 -1
  158. package/src/__tests__/fixtures/testStorage.ts +2 -10
  159. package/src/__tests__/queries.test.ts +1 -1
  160. package/src/backup.ts +3 -4
  161. package/src/client/Client.ts +69 -226
  162. package/src/client/ClientDescriptor.ts +53 -184
  163. package/src/context/Time.ts +35 -0
  164. package/src/context/context.ts +200 -0
  165. package/src/entities/DocumentManager.ts +0 -3
  166. package/src/entities/Entity.test.ts +9 -9
  167. package/src/entities/Entity.ts +6 -12
  168. package/src/entities/EntityCache.ts +0 -9
  169. package/src/entities/EntityMetadata.ts +4 -4
  170. package/src/entities/EntityStore.ts +26 -29
  171. package/src/entities/OperationBatcher.ts +9 -11
  172. package/src/errors.ts +13 -0
  173. package/src/files/EntityFile.ts +16 -5
  174. package/src/files/FileManager.ts +35 -245
  175. package/src/files/utils.ts +0 -15
  176. package/src/index.ts +2 -1
  177. package/src/{metadata → persistence}/MessageCreator.ts +46 -36
  178. package/src/persistence/PersistenceFiles.ts +227 -0
  179. package/src/persistence/PersistenceMetadata.ts +425 -0
  180. package/src/persistence/PersistenceQueries.ts +22 -0
  181. package/src/persistence/PersistenceRebaser.ts +171 -0
  182. package/src/{IDBService.ts → persistence/idb/IdbService.ts} +45 -12
  183. package/src/{files/FileStorage.ts → persistence/idb/files/IdbPersistenceFileDb.ts} +128 -86
  184. package/src/persistence/idb/idbPersistence.ts +116 -0
  185. package/src/persistence/idb/metadata/IdbMetadataDb.ts +460 -0
  186. package/src/{metadata → persistence/idb/metadata}/openMetadataDatabase.ts +21 -4
  187. package/src/persistence/idb/queries/IdbQueryDb.ts +251 -0
  188. package/src/{migration → persistence/idb/queries/migration}/db.ts +18 -72
  189. package/src/{migration → persistence/idb/queries/migration}/engine.ts +39 -62
  190. package/src/{migration → persistence/idb/queries/migration}/migrations.ts +13 -18
  191. package/src/{migration → persistence/idb/queries/migration}/openQueryDatabase.ts +5 -14
  192. package/src/{migration → persistence/idb/queries/migration}/paths.ts +4 -3
  193. package/src/persistence/idb/queries/migration/types.ts +8 -0
  194. package/src/persistence/idb/queries/ranges.ts +107 -0
  195. package/src/{idb.ts → persistence/idb/util.ts} +75 -0
  196. package/src/persistence/interfaces.ts +240 -0
  197. package/src/persistence/persistence.ts +223 -0
  198. package/src/queries/BaseQuery.ts +5 -1
  199. package/src/queries/CollectionQueries.ts +2 -2
  200. package/src/queries/FindAllQuery.ts +1 -3
  201. package/src/queries/FindInfiniteQuery.ts +2 -5
  202. package/src/queries/FindOneQuery.ts +1 -3
  203. package/src/queries/FindPageQuery.ts +1 -3
  204. package/src/queries/QueryCache.ts +20 -1
  205. package/src/sync/FileSync.ts +93 -30
  206. package/src/sync/PresenceManager.ts +5 -7
  207. package/src/sync/PushPullSync.ts +23 -19
  208. package/src/sync/Sync.ts +71 -37
  209. package/src/sync/WebSocketSync.ts +41 -27
  210. package/src/utils/Disposable.ts +7 -4
  211. package/src/utils/wip.ts +5 -0
  212. package/dist/esm/IDBService.js.map +0 -1
  213. package/dist/esm/__tests__/legacyOids.test.d.ts +0 -1
  214. package/dist/esm/__tests__/legacyOids.test.js +0 -352
  215. package/dist/esm/__tests__/legacyOids.test.js.map +0 -1
  216. package/dist/esm/context.d.ts +0 -45
  217. package/dist/esm/files/FileStorage.d.ts +0 -47
  218. package/dist/esm/files/FileStorage.js.map +0 -1
  219. package/dist/esm/idb.js.map +0 -1
  220. package/dist/esm/metadata/AckInfoStore.d.ts +0 -10
  221. package/dist/esm/metadata/AckInfoStore.js +0 -22
  222. package/dist/esm/metadata/AckInfoStore.js.map +0 -1
  223. package/dist/esm/metadata/BaselinesStore.d.ts +0 -40
  224. package/dist/esm/metadata/BaselinesStore.js +0 -102
  225. package/dist/esm/metadata/BaselinesStore.js.map +0 -1
  226. package/dist/esm/metadata/LocalReplicaStore.d.ts +0 -19
  227. package/dist/esm/metadata/LocalReplicaStore.js +0 -56
  228. package/dist/esm/metadata/LocalReplicaStore.js.map +0 -1
  229. package/dist/esm/metadata/MessageCreator.js.map +0 -1
  230. package/dist/esm/metadata/Metadata.d.ts +0 -146
  231. package/dist/esm/metadata/Metadata.js +0 -452
  232. package/dist/esm/metadata/Metadata.js.map +0 -1
  233. package/dist/esm/metadata/OperationsStore.d.ts +0 -62
  234. package/dist/esm/metadata/OperationsStore.js +0 -175
  235. package/dist/esm/metadata/OperationsStore.js.map +0 -1
  236. package/dist/esm/metadata/SchemaStore.d.ts +0 -9
  237. package/dist/esm/metadata/SchemaStore.js +0 -35
  238. package/dist/esm/metadata/SchemaStore.js.map +0 -1
  239. package/dist/esm/metadata/openMetadataDatabase.js.map +0 -1
  240. package/dist/esm/migration/db.js.map +0 -1
  241. package/dist/esm/migration/engine.d.ts +0 -15
  242. package/dist/esm/migration/engine.js.map +0 -1
  243. package/dist/esm/migration/errors.d.ts +0 -5
  244. package/dist/esm/migration/errors.js +0 -8
  245. package/dist/esm/migration/errors.js.map +0 -1
  246. package/dist/esm/migration/migrations.js.map +0 -1
  247. package/dist/esm/migration/openQueryDatabase.js.map +0 -1
  248. package/dist/esm/migration/openWIPDatabase.d.ts +0 -11
  249. package/dist/esm/migration/openWIPDatabase.js +0 -65
  250. package/dist/esm/migration/openWIPDatabase.js.map +0 -1
  251. package/dist/esm/migration/paths.js.map +0 -1
  252. package/dist/esm/migration/paths.test.js.map +0 -1
  253. package/dist/esm/migration/types.d.ts +0 -3
  254. package/dist/esm/migration/types.js.map +0 -1
  255. package/dist/esm/queries/QueryableStorage.d.ts +0 -20
  256. package/dist/esm/queries/QueryableStorage.js +0 -90
  257. package/dist/esm/queries/QueryableStorage.js.map +0 -1
  258. package/dist/esm/queries/dbQueries.d.ts +0 -22
  259. package/dist/esm/queries/dbQueries.js +0 -130
  260. package/dist/esm/queries/dbQueries.js.map +0 -1
  261. package/src/__tests__/legacyOids.test.ts +0 -375
  262. package/src/context.ts +0 -55
  263. package/src/metadata/AckInfoStore.ts +0 -30
  264. package/src/metadata/BaselinesStore.ts +0 -188
  265. package/src/metadata/LocalReplicaStore.ts +0 -79
  266. package/src/metadata/Metadata.ts +0 -685
  267. package/src/metadata/OperationsStore.ts +0 -332
  268. package/src/metadata/SchemaStore.ts +0 -47
  269. package/src/migration/errors.ts +0 -7
  270. package/src/migration/openWIPDatabase.ts +0 -97
  271. package/src/migration/types.ts +0 -4
  272. package/src/queries/QueryableStorage.ts +0 -122
  273. package/src/queries/dbQueries.ts +0 -161
  274. /package/dist/esm/{context.js → context/context.js} +0 -0
  275. /package/dist/esm/{migration → persistence/idb/queries/migration}/paths.d.ts +0 -0
  276. /package/dist/esm/{migration → persistence/idb/queries/migration}/paths.test.d.ts +0 -0
  277. /package/dist/esm/{migration → persistence/idb/queries/migration}/paths.test.js +0 -0
  278. /package/dist/esm/{migration → persistence/idb/queries/migration}/types.js +0 -0
  279. /package/src/{migration → persistence/idb/queries/migration}/paths.test.ts +0 -0
@@ -1,685 +0,0 @@
1
- import {
2
- applyPatch,
3
- assert,
4
- assignOid,
5
- ClientMessage,
6
- DocumentBaseline,
7
- EventSubscriber,
8
- FileRef,
9
- isFileRef,
10
- getOidRoot,
11
- HybridLogicalClockTimestampProvider,
12
- ObjectIdentifier,
13
- Operation,
14
- PatchCreator,
15
- Ref,
16
- StorageSchema,
17
- substituteRefsWithObjects,
18
- } from '@verdant-web/common';
19
- import { AckInfoStore } from './AckInfoStore.js';
20
- import { BaselinesStore } from './BaselinesStore.js';
21
- import {
22
- createAbortableTransaction,
23
- getAllFromObjectStores,
24
- getSizeOfObjectStore,
25
- storeRequestPromise,
26
- } from '../idb.js';
27
- import { LocalReplicaInfo, LocalReplicaStore } from './LocalReplicaStore.js';
28
- import { MessageCreator } from './MessageCreator.js';
29
- import { ClientOperation, OperationsStore } from './OperationsStore.js';
30
- import { SchemaStore } from './SchemaStore.js';
31
- import { Context } from '../context.js';
32
-
33
- export interface ExportData {
34
- operations: Operation[];
35
- baselines: DocumentBaseline[];
36
- localReplica?: LocalReplicaInfo;
37
- schemaVersion: number;
38
- }
39
-
40
- export class Metadata extends EventSubscriber<{
41
- message: (message: ClientMessage) => void;
42
- rebase: (baselines: DocumentBaseline[]) => void;
43
- filesDeleted: (files: FileRef[]) => void;
44
- }> {
45
- readonly operations;
46
- readonly baselines;
47
- readonly localReplica;
48
- readonly ackInfo;
49
- readonly messageCreator;
50
- readonly patchCreator;
51
- readonly schema;
52
- readonly time = new HybridLogicalClockTimestampProvider();
53
-
54
- private readonly disableRebasing: boolean = false;
55
- /**
56
- * indicates the client is shutting down and we should stop
57
- * accessing the database.
58
- */
59
- private _closing = false;
60
-
61
- private context: Omit<Context, 'documentDb' | 'getNow'>;
62
-
63
- private onOperation?: (operation: Operation) => void;
64
-
65
- constructor({
66
- disableRebasing,
67
- context,
68
- onOperation,
69
- }: {
70
- disableRebasing?: boolean;
71
- context: Omit<Context, 'documentDb' | 'getNow'>;
72
- onOperation?: (operation: Operation) => void;
73
- }) {
74
- super();
75
- this.context = context;
76
- this.schema = new SchemaStore(context.metaDb, context.schema.version);
77
- this.operations = new OperationsStore(this.db, { log: context.log });
78
- this.baselines = new BaselinesStore(this.db, { log: context.log });
79
- this.localReplica = new LocalReplicaStore(this.db);
80
- this.ackInfo = new AckInfoStore(this.db);
81
- this.messageCreator = new MessageCreator(this);
82
- this.patchCreator = new PatchCreator(() => this.now);
83
- this.onOperation = onOperation;
84
- if (disableRebasing) this.disableRebasing = disableRebasing;
85
- }
86
-
87
- private get db() {
88
- return this.context.metaDb;
89
- }
90
-
91
- private get log() {
92
- return this.context.log;
93
- }
94
-
95
- setContext = (context: Context) => {
96
- this.context = context;
97
- };
98
-
99
- get now() {
100
- return this.time.now(this.schema.currentVersion);
101
- }
102
-
103
- close = () => {
104
- this._closing = true;
105
- };
106
-
107
- /**
108
- * Methods for accessing data
109
- */
110
-
111
- createTransaction = (
112
- stores: ('operations' | 'baselines')[],
113
- opts: {
114
- abort?: AbortSignal;
115
- write?: boolean;
116
- } = {},
117
- ) => {
118
- return createAbortableTransaction(
119
- this.db,
120
- stores,
121
- opts.write ? 'readwrite' : 'readonly',
122
- opts.abort,
123
- this.context.log,
124
- );
125
- };
126
-
127
- /**
128
- * Gets the OID and every sub-object OID for a given document.
129
- * Includes any sub-objects that are not referenced by the root object
130
- * but still happen to be in storage.
131
- */
132
- getAllDocumentRelatedOids = async (oid: ObjectIdentifier) => {
133
- const oids = new Set<ObjectIdentifier>();
134
- const documentOid = getOidRoot(oid);
135
- assert(documentOid === oid, 'Must be root document OID');
136
- oids.add(documentOid);
137
- // readwrite mode to block on other write transactions
138
- const transaction = this.createTransaction(['baselines', 'operations']);
139
- await Promise.all([
140
- this.baselines.iterateOverAllForDocument(
141
- documentOid,
142
- (baseline) => {
143
- oids.add(baseline.oid);
144
- },
145
- { transaction },
146
- ),
147
- this.operations.iterateOverAllOperationsForDocument(
148
- documentOid,
149
- (patch) => {
150
- oids.add(patch.oid);
151
- },
152
- { transaction },
153
- ),
154
- ]);
155
-
156
- return Array.from(oids);
157
- };
158
-
159
- getAllCollectionRelatedOids = async (oid: ObjectIdentifier) => {
160
- const oids = new Set<ObjectIdentifier>();
161
- const transaction = this.db.transaction(
162
- ['baselines', 'operations'],
163
- 'readwrite',
164
- );
165
- await Promise.all([
166
- this.baselines.iterateOverAllForCollection(
167
- oid,
168
- (baseline) => {
169
- oids.add(baseline.oid);
170
- },
171
- { transaction },
172
- ),
173
- this.operations.iterateOverAllOperationsForCollection(
174
- oid,
175
- (patch) => {
176
- oids.add(patch.oid);
177
- },
178
- { transaction },
179
- ),
180
- ]);
181
-
182
- return Array.from(oids);
183
- };
184
-
185
- getDocumentSnapshot = async (
186
- oid: ObjectIdentifier,
187
- options: { to?: string } = {},
188
- ) => {
189
- const documentOid = getOidRoot(oid);
190
- assert(documentOid === oid, 'Must be root document OID');
191
- const transaction = this.db.transaction(
192
- ['baselines', 'operations'],
193
- 'readwrite',
194
- );
195
- const baselines = await this.baselines.getAllForDocument(documentOid, {
196
- transaction,
197
- });
198
- const objectMap = new Map<ObjectIdentifier, any>();
199
- for (const baseline of baselines) {
200
- if (baseline.snapshot) {
201
- assignOid(baseline.snapshot, baseline.oid);
202
- }
203
- objectMap.set(baseline.oid, baseline.snapshot);
204
- }
205
- await this.operations.iterateOverAllOperationsForDocument(
206
- documentOid,
207
- (op) => {
208
- const obj = objectMap.get(op.oid) || undefined;
209
- const newObj = applyPatch(obj, op.data);
210
- if (newObj) {
211
- assignOid(newObj, op.oid);
212
- }
213
- objectMap.set(op.oid, newObj);
214
- },
215
- {
216
- transaction,
217
- // only apply operations up to the current time
218
- to: options.to || this.now,
219
- },
220
- );
221
- const root = objectMap.get(documentOid);
222
- if (root) {
223
- substituteRefsWithObjects(root, objectMap);
224
- }
225
- return root;
226
- };
227
-
228
- getDocumentData = async (
229
- oid: ObjectIdentifier,
230
- opts?: {
231
- abort?: AbortSignal;
232
- },
233
- ) => {
234
- const transaction = this.createTransaction(
235
- ['baselines', 'operations'],
236
- opts,
237
- );
238
- const baselines: DocumentBaseline[] = [];
239
- const operations: Record<ObjectIdentifier, Operation[]> = {};
240
- await Promise.all([
241
- this.baselines.iterateOverAllForDocument(
242
- oid,
243
- (baseline) => {
244
- baselines.push(baseline);
245
- },
246
- {
247
- transaction,
248
- },
249
- ),
250
- this.operations.iterateOverAllOperationsForDocument(
251
- oid,
252
- (op) => {
253
- operations[op.oid] ??= [];
254
- operations[op.oid].push(op);
255
- },
256
- { transaction },
257
- ),
258
- ]);
259
- return {
260
- baselines,
261
- operations,
262
- };
263
- };
264
-
265
- getDocumentAuthz = async (oid: ObjectIdentifier) => {
266
- const baseline = await this.baselines.get(oid);
267
- if (baseline) {
268
- return baseline.authz;
269
- }
270
- let authz;
271
- await this.operations.iterateOverAllOperationsForEntity(
272
- oid,
273
- (op) => {
274
- if (op.data.op === 'initialize') {
275
- authz = op.authz;
276
- return true;
277
- }
278
- },
279
- {},
280
- );
281
- return authz;
282
- };
283
-
284
- /**
285
- * Methods for writing data
286
- */
287
-
288
- /**
289
- * Acks that we have seen a timestamp to the server
290
- * and stores it as our local ackedLogicalTime if it's
291
- * greater than our current ackedLogicalTime.
292
- */
293
- ack = async (timestamp: string) => {
294
- const localReplicaInfo = await this.localReplica.get();
295
- // can't ack timestamps from the future.
296
- if (timestamp > this.now) return;
297
-
298
- this.emit('message', {
299
- type: 'ack',
300
- replicaId: localReplicaInfo.id,
301
- timestamp,
302
- });
303
- if (
304
- !this._closing &&
305
- (!localReplicaInfo.ackedLogicalTime ||
306
- timestamp > localReplicaInfo.ackedLogicalTime)
307
- ) {
308
- this.localReplica.update({ ackedLogicalTime: timestamp });
309
- }
310
- };
311
-
312
- /**
313
- * Applies a patch to the document and stores it in the database.
314
- * @returns the oldest local history timestamp
315
- */
316
- insertLocalOperations = async (
317
- operations: Operation[],
318
- opts?: { transaction?: IDBTransaction },
319
- ) => {
320
- if (operations.length === 0) return;
321
- // await this.rebaseLock;
322
- this.log(
323
- 'debug',
324
- `Inserting ${operations.length} local operations`,
325
- operations,
326
- );
327
-
328
- // add local flag, in place.
329
- for (const operation of operations) {
330
- (operation as ClientOperation).isLocal = true;
331
- }
332
- await this.operations.addOperations(operations as ClientOperation[], opts);
333
-
334
- const message = await this.messageCreator.createOperation({ operations });
335
- this.emit('message', message);
336
-
337
- // we can now enqueue and check for rebase opportunities
338
- this.tryAutonomousRebase();
339
-
340
- if (this.onOperation) {
341
- operations.forEach((o) => this.onOperation!(o));
342
- }
343
- };
344
-
345
- /**
346
- * Inserts remote operations. This does not affect local history.
347
- * @returns a list of affected document OIDs
348
- */
349
- insertRemoteOperations = async (
350
- operations: Operation[],
351
- opts?: { transaction?: IDBTransaction },
352
- ) => {
353
- if (operations.length === 0) return [];
354
- // await this.rebaseLock;
355
- this.log(
356
- 'debug',
357
- `Inserting ${operations.length} remote operations`,
358
- operations,
359
- );
360
-
361
- const affectedDocumentOids = await this.operations.addOperations(
362
- operations.map((patch) => ({
363
- ...patch,
364
- isLocal: false,
365
- })),
366
- opts,
367
- );
368
-
369
- this.ack(operations[operations.length - 1].timestamp);
370
-
371
- if (this.onOperation) {
372
- operations.forEach((o) => this.onOperation!(o));
373
- }
374
-
375
- return affectedDocumentOids;
376
- };
377
-
378
- insertRemoteBaselines = async (
379
- baselines: DocumentBaseline[],
380
- opts?: { transaction?: IDBTransaction },
381
- ) => {
382
- if (baselines.length === 0) return [];
383
- this.log('debug', `Inserting ${baselines.length} remote baselines`);
384
-
385
- await this.baselines.setAll(baselines, opts);
386
-
387
- // this.ack(baselines[baselines.length - 1].timestamp);
388
-
389
- const affectedOidSet = new Set<ObjectIdentifier>();
390
- baselines.forEach((baseline) => {
391
- affectedOidSet.add(getOidRoot(baseline.oid));
392
- });
393
-
394
- return Array.from(affectedOidSet);
395
- };
396
-
397
- insertData = async (
398
- data: {
399
- baselines?: DocumentBaseline[];
400
- operations?: Operation[];
401
- isLocal?: boolean;
402
- },
403
- opts?: { abort: AbortSignal },
404
- ) => {
405
- const transaction = this.createTransaction(['baselines', 'operations'], {
406
- ...opts,
407
- write: true,
408
- });
409
- if (data.baselines) {
410
- await this.insertRemoteBaselines(data.baselines, { transaction });
411
- }
412
- if (opts?.abort?.aborted) return;
413
- if (data.operations) {
414
- if (data.isLocal) {
415
- await this.insertLocalOperations(data.operations, { transaction });
416
- } else {
417
- await this.insertRemoteOperations(data.operations, { transaction });
418
- }
419
- }
420
- };
421
-
422
- updateLastSynced = async (timestamp: string) => {
423
- if (this._closing) return;
424
-
425
- return this.localReplica.update({
426
- lastSyncedLogicalTime: timestamp,
427
- });
428
- };
429
-
430
- lastSyncedTimestamp = async () => {
431
- const localReplicaInfo = await this.localReplica.get();
432
- return localReplicaInfo.lastSyncedLogicalTime;
433
- };
434
-
435
- private tryAutonomousRebase = async () => {
436
- if (this.disableRebasing) return;
437
-
438
- const localReplicaInfo = await this.localReplica.get();
439
- if (localReplicaInfo.lastSyncedLogicalTime) return; // cannot autonomously rebase if we've synced
440
- // but if we have never synced... we can rebase everything!
441
- await this.runRebase(this.now);
442
- };
443
-
444
- /**
445
- * Attempt to autonomously rebase local documents without server intervention.
446
- * This can currently only happen for a client who has never synced before.
447
- * The goal is to allow local-only clients to compress their history to exactly
448
- * their undo stack.
449
- */
450
- private runRebase = async (globalAckTimestamp: string) => {
451
- if (this._closing) return;
452
-
453
- // find all operations before the global ack
454
- let lastTimestamp;
455
- const toRebase = new Set<ObjectIdentifier>();
456
- const transaction = this.createTransaction(['baselines', 'operations'], {
457
- write: true,
458
- });
459
- let operationCount = 0;
460
- await this.operations.iterateOverAllOperations(
461
- (patch) => {
462
- toRebase.add(patch.oid);
463
- lastTimestamp = patch.timestamp;
464
- operationCount++;
465
- },
466
- {
467
- before: globalAckTimestamp,
468
- transaction,
469
- },
470
- );
471
-
472
- if (!toRebase.size) {
473
- return;
474
- }
475
-
476
- if (this._closing) {
477
- return;
478
- }
479
-
480
- // rebase each affected document
481
- let newBaselines = [];
482
- for (const oid of toRebase) {
483
- newBaselines.push(
484
- await this.rebase(
485
- oid,
486
- lastTimestamp || globalAckTimestamp,
487
- transaction,
488
- ),
489
- );
490
- }
491
- this.emit('rebase', newBaselines);
492
- };
493
-
494
- rebase = async (
495
- oid: ObjectIdentifier,
496
- upTo: string,
497
- providedTx?: IDBTransaction,
498
- ) => {
499
- // including replica Id for testing I guess
500
- const replicaId = (await this.localReplica.get()).id;
501
-
502
- this.log('debug', '[', replicaId, ']', 'Rebasing', oid, 'up to', upTo);
503
- const transaction =
504
- providedTx ||
505
- this.createTransaction(['operations', 'baselines'], { write: true });
506
- const baseline = await this.baselines.get(oid, { transaction });
507
- let current: any = baseline?.snapshot || undefined;
508
- let operationsApplied = 0;
509
- let authz = baseline?.authz;
510
- const deletedRefs: Ref[] = [];
511
- await this.operations.iterateOverAllOperationsForEntity(
512
- oid,
513
- (patch, store) => {
514
- // FIXME: this seems like the wrong place to do this
515
- // but it's here as a safety measure...
516
- if (!baseline || patch.timestamp > baseline.timestamp) {
517
- current = applyPatch(current, patch.data, deletedRefs);
518
- if (patch.data.op === 'initialize') {
519
- authz = patch.authz;
520
- }
521
- }
522
- // delete all prior operations to the baseline
523
- operationsApplied++;
524
- store.delete(patch.oid_timestamp);
525
- },
526
- {
527
- to: upTo,
528
- transaction,
529
- },
530
- );
531
- if (current) {
532
- assignOid(current, oid);
533
- }
534
- const newBaseline = {
535
- oid,
536
- snapshot: current,
537
- timestamp: upTo,
538
- authz,
539
- };
540
- if (newBaseline.snapshot) {
541
- await this.baselines.set(newBaseline, { transaction });
542
- } else {
543
- await this.baselines.delete(oid, { transaction });
544
- }
545
-
546
- this.log(
547
- 'debug',
548
- 'successfully rebased',
549
- oid,
550
- 'up to',
551
- upTo,
552
- ':',
553
- current,
554
- 'and deleted',
555
- operationsApplied,
556
- 'operations',
557
- );
558
-
559
- // cleanup deleted refs
560
- if (deletedRefs.length) {
561
- const fileRefs = deletedRefs.filter(isFileRef);
562
- if (fileRefs.length) {
563
- this.emit('filesDeleted', fileRefs);
564
- }
565
- }
566
-
567
- return newBaseline;
568
- };
569
-
570
- reset = async () => {
571
- await this.operations.reset();
572
- await this.baselines.reset();
573
- await this.localReplica.reset();
574
- };
575
-
576
- updateSchema = async (schema: StorageSchema, overrideConflict?: number) => {
577
- const storedSchema = await this.schema.get();
578
- if (storedSchema) {
579
- // version changes will be handled by migration routines in
580
- // the actual idb database loading code (see: initializeDatabases)
581
-
582
- // but this check determines if the schema has been changed without
583
- // a version change. if so, it will error.
584
- if (
585
- overrideConflict === storedSchema.version &&
586
- storedSchema.version === schema.version &&
587
- JSON.stringify(storedSchema) !== JSON.stringify(schema)
588
- ) {
589
- console.error(
590
- `Schema mismatch for version ${schema.version}
591
- ${JSON.stringify(storedSchema)}
592
- ${JSON.stringify(schema)}`,
593
- );
594
- throw new Error(
595
- 'Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.',
596
- );
597
- }
598
- }
599
- await this.schema.set(schema);
600
- };
601
-
602
- setGlobalAck = async (timestamp: string) => {
603
- if (this._closing) return;
604
- await this.ackInfo.setGlobalAck(timestamp);
605
- if (!this.disableRebasing) {
606
- await this.runRebase(timestamp);
607
- }
608
- };
609
-
610
- /**
611
- * Manually triggers a storage rebase.
612
- * Rebases happen automatically as needed, so
613
- * you probably don't need this.
614
- */
615
- manualRebase = async () => {
616
- if (this._closing || this.disableRebasing) return;
617
- const ackInfo = await this.ackInfo.getAckInfo();
618
- if (ackInfo.globalAckTimestamp) {
619
- this.runRebase(ackInfo.globalAckTimestamp);
620
- }
621
- };
622
-
623
- export = async (): Promise<ExportData> => {
624
- const db = this.db;
625
- const [baselines, operations] = await getAllFromObjectStores(db, [
626
- 'baselines',
627
- 'operations',
628
- ]);
629
- const localReplica = await this.localReplica.get();
630
- const schema = await this.schema.get();
631
- if (!schema) {
632
- throw new Error('Cannot export Client data before initializing');
633
- }
634
- return {
635
- operations,
636
- baselines,
637
- localReplica,
638
- schemaVersion: schema.version,
639
- };
640
- };
641
-
642
- /**
643
- * Resets local metadata and clears operation/baseline stores.
644
- * DOES NOT add operations/baselines - this should be done
645
- * through the normal higher level systems.
646
- */
647
- resetFrom = async (data: ExportData) => {
648
- const db = this.db;
649
- const transaction = db.transaction(
650
- ['baselines', 'operations', 'info'],
651
- 'readwrite',
652
- );
653
- await storeRequestPromise(transaction.objectStore('baselines').clear());
654
- await storeRequestPromise(transaction.objectStore('operations').clear());
655
- await storeRequestPromise(transaction.objectStore('info').clear());
656
- if (data.localReplica) {
657
- await this.localReplica.update(
658
- {
659
- ackedLogicalTime: data.localReplica.ackedLogicalTime,
660
- lastSyncedLogicalTime: data.localReplica.lastSyncedLogicalTime,
661
- },
662
- { transaction },
663
- );
664
- }
665
- };
666
-
667
- stats = async () => {
668
- const db = this.db;
669
- const operationsSize = await getSizeOfObjectStore(db, 'operations');
670
- const baselinesSize = await getSizeOfObjectStore(db, 'baselines');
671
-
672
- return {
673
- operationsSize,
674
- baselinesSize,
675
- };
676
- };
677
- }
678
-
679
- export function supportLegacyExport(exportData: any): ExportData {
680
- if (exportData.schema) {
681
- exportData.schemaVersion = exportData.schema.version;
682
- delete exportData.schema;
683
- }
684
- return exportData;
685
- }