Open History to see the last commit
1import { Derived, Store, batch } from "@tanstack/store"
2import { withArrayChangeTracking, withChangeTracking } from "./proxy"
3import { getTransactionManager } from "./TransactionManager"
4import { TransactionStore } from "./TransactionStore"
5import type {
6 ChangeMessage,
7 CollectionConfig,
8 InsertConfig,
9 OperationConfig,
10 PendingMutation,
11 StandardSchema,
12 Transaction,
13 TransactionState,
14} from "./types"
15
16// Store collections in memory using Tanstack store
17
18export const collectionsStore = new Store(new Map<string, Collection<any>>())
19
20// Map to track loading collections
21
22const loadingCollections = new Map<
23 string,
24 Promise<Collection<Record<string, unknown>>>
25>()
26
27interface PendingSyncedTransaction<T extends object = Record<string, unknown>> {
28 committed: boolean
29 operations: Array<ChangeMessage<T>>
30}
31
32/**
33 * Preloads a collection with the given configuration
34 * Returns a promise that resolves once the sync tool has done its first commit (initial sync is finished)
35 * If the collection has already loaded, it resolves immediately
36 *
37 * This function is useful in route loaders or similar pre-rendering scenarios where you want
38 * to ensure data is available before a route transition completes. It uses the same shared collection
39 * instance that will be used by useCollection, ensuring data consistency.
40 *
41 * @example
42 * ```typescript
43 * // In a route loader
44 * async function loader({ params }) {
45 * await preloadCollection({
46 * id: `users-${params.userId}`,
47 * sync: { ... },
48 * mutationFn: { ... }
49 * });
50 *
51 * return null;
52 * }
53 * ```
54 *
55 * @template T - The type of items in the collection
56 * @param config - Configuration for the collection, including id, sync, and mutationFn
57 * @returns Promise that resolves when the initial sync is finished
58 */
59export function preloadCollection<T extends object = Record<string, unknown>>(
60 config: CollectionConfig<T>
61): Promise<Collection<T>> {
62 // If the collection is already fully loaded, return a resolved promise
63 if (
64 collectionsStore.state.has(config.id) &&
65 !loadingCollections.has(config.id)
66 ) {
67 return Promise.resolve(
68 collectionsStore.state.get(config.id)! as Collection<T>
69 )
70 }
71
72 // If the collection is in the process of loading, return its promise
73 if (loadingCollections.has(config.id)) {
74 return loadingCollections.get(config.id)! as Promise<Collection<T>>
75 }
76
77 // Create a new collection instance if it doesn't exist
78 if (!collectionsStore.state.has(config.id)) {
79 collectionsStore.setState((prev) => {
80 const next = new Map(prev)
81 next.set(
82 config.id,
83 new Collection<T>({
84 id: config.id,
85 sync: config.sync,
86 mutationFn: config.mutationFn,
87 schema: config.schema,
88 })
89 )
90 return next
91 })
92 }
93
94 const collection = collectionsStore.state.get(config.id)! as Collection<T>
95
96 // Create a promise that will resolve after the first commit
97 let resolveFirstCommit: () => void
98 const firstCommitPromise = new Promise<Collection<T>>((resolve) => {
99 resolveFirstCommit = () => {
100 resolve(collection)
101 }
102 })
103
104 // Register a one-time listener for the first commit
105 collection.onFirstCommit(() => {
106 if (loadingCollections.has(config.id)) {
107 loadingCollections.delete(config.id)
108 resolveFirstCommit()
109 }
110 })
111
112 // Store the loading promise
113 loadingCollections.set(
114 config.id,
115 firstCommitPromise as Promise<Collection<Record<string, unknown>>>
116 )
117
118 return firstCommitPromise
119}
120
121/**
122 * Custom error class for schema validation errors
123 */
124export class SchemaValidationError extends Error {
125 type: `insert` | `update`
126 issues: ReadonlyArray<{
127 message: string
128 path?: ReadonlyArray<string | number | symbol>
129 }>
130
131 constructor(
132 type: `insert` | `update`,
133 issues: ReadonlyArray<{
134 message: string
135 path?: ReadonlyArray<string | number | symbol>
136 }>,
137 message?: string
138 ) {
139 const defaultMessage = `${type === `insert` ? `Insert` : `Update`} validation failed: ${issues
140 .map((issue) => issue.message)
141 .join(`, `)}`
142
143 super(message || defaultMessage)
144 this.name = `SchemaValidationError`
145 this.type = type
146 this.issues = issues
147 }
148}
149
150export class Collection<T extends object = Record<string, unknown>> {
151 public transactionManager!: ReturnType<typeof getTransactionManager<T>>
152 private transactionStore: TransactionStore
153
154 public optimisticOperations: Derived<Array<ChangeMessage<T>>>
155 public derivedState: Derived<Map<string, T>>
156 public derivedArray: Derived<Array<T>>
157
158 private syncedData = new Store<Map<string, T>>(new Map())
159 public syncedMetadata = new Store(new Map<string, unknown>())
160 private pendingSyncedTransactions: Array<PendingSyncedTransaction<T>> = []
161 public config: CollectionConfig<T>
162 private hasReceivedFirstCommit = false
163
164 // WeakMap to associate objects with their keys
165 public objectKeyMap = new WeakMap<object, string>()
166
167 // Array to store one-time commit listeners
168 private onFirstCommitCallbacks: Array<() => void> = []
169
170 /**
171 * Register a callback to be executed on the next commit
172 * Useful for preloading collections
173 * @param callback Function to call after the next commit
174 */
175 public onFirstCommit(callback: () => void): void {
176 this.onFirstCommitCallbacks.push(callback)
177 }
178
179 public id = crypto.randomUUID()
180
181 /**
182 * Creates a new Collection instance
183 *
184 * @param config - Configuration object for the collection
185 * @throws Error if sync config or mutationFn is missing
186 */
187 constructor(config?: CollectionConfig<T>) {
188 if (!config?.sync) {
189 throw new Error(`Collection requires a sync config`)
190 }
191 if (!config.mutationFn as unknown) {
192 throw new Error(`Collection requires a mutationFn`)
193 }
194
195 this.transactionStore = new TransactionStore()
196 this.transactionManager = getTransactionManager<T>(
197 this.transactionStore,
198 this
199 )
200
201 // Copies of live mutations are stored here and removed once the transaction completes.
202 this.optimisticOperations = new Derived({
203 fn: ({ currDepVals: [transactions] }) => {
204 const result = Array.from(transactions.values())
205 .filter(
206 (transaction) =>
207 transaction.state !== `completed` &&
208 transaction.state !== `failed`
209 )
210 .map((transaction) =>
211 transaction.mutations.map((mutation) => {
212 const message: ChangeMessage<T> = {
213 type: mutation.type,
214 key: mutation.key,
215 value: mutation.modified as T,
216 }
217 if (
218 mutation.metadata !== undefined &&
219 mutation.metadata !== null
220 ) {
221 message.metadata = mutation.metadata as Record<string, unknown>
222 }
223 return message
224 })
225 )
226 .flat()
227
228 return result
229 },
230 deps: [this.transactionManager.transactions],
231 })
232 this.optimisticOperations.mount()
233
234 // Combine together synced data & optimistic operations.
235 this.derivedState = new Derived({
236 fn: ({ currDepVals: [syncedData, operations] }) => {
237 const combined = new Map<string, T>(syncedData)
238 // Apply the optimistic operations on top of the synced state.
239 for (const operation of operations) {
240 let existingValue
241 switch (operation.type) {
242 case `insert`:
243 combined.set(operation.key, operation.value)
244 break
245 case `update`:
246 existingValue = syncedData.get(operation.key)
247 combined.set(operation.key, {
248 ...(existingValue || {}),
249 ...operation.value,
250 })
251 break
252 case `delete`:
253 combined.delete(operation.key)
254 break
255 }
256 }
257
258 // Update object => key mappings
259 const optimisticKeys = new Set<string>()
260 for (const operation of operations) {
261 optimisticKeys.add(operation.key)
262 }
263
264 optimisticKeys.forEach((key) => {
265 if (combined.has(key)) {
266 this.objectKeyMap.set(combined.get(key)!, key)
267 }
268 })
269
270 return combined
271 },
272 deps: [this.syncedData, this.optimisticOperations],
273 })
274
275 // Create a derived array from the map to avoid recalculating it
276 this.derivedArray = new Derived({
277 fn: ({ currDepVals: [stateMap] }) => {
278 return Array.from(stateMap.values())
279 },
280 deps: [this.derivedState],
281 })
282 this.derivedArray.mount()
283
284 this.config = config
285
286 this.derivedState.mount()
287
288 // Start the sync process
289 config.sync.sync({
290 collection: this,
291 begin: () => {
292 this.pendingSyncedTransactions.push({
293 committed: false,
294 operations: [],
295 })
296 },
297 write: (message: ChangeMessage<T>) => {
298 const pendingTransaction =
299 this.pendingSyncedTransactions[
300 this.pendingSyncedTransactions.length - 1
301 ]
302 if (!pendingTransaction) {
303 throw new Error(`No pending sync transaction to write to`)
304 }
305 if (pendingTransaction.committed) {
306 throw new Error(
307 `The pending sync transaction is already committed, you can't still write to it.`
308 )
309 }
310 pendingTransaction.operations.push(message)
311 },
312 commit: () => {
313 const pendingTransaction =
314 this.pendingSyncedTransactions[
315 this.pendingSyncedTransactions.length - 1
316 ]
317 if (!pendingTransaction) {
318 throw new Error(`No pending sync transaction to commit`)
319 }
320 if (pendingTransaction.committed) {
321 throw new Error(
322 `The pending sync transaction is already committed, you can't commit it again.`
323 )
324 }
325
326 pendingTransaction.committed = true
327
328 this.commitPendingTransactions()
329 },
330 })
331
332 // Listen to transactions and re-run commitPendingTransactions on changes
333 // this.transactionManager.transactions.subscribe(
334 // this.commitPendingTransactions
335 // )
336 }
337
338 /**
339 * Attempts to commit pending synced transactions if there are no active transactions
340 * This method processes operations from pending transactions and applies them to the synced data
341 */
342 commitPendingTransactions = () => {
343 // Check if there's any transactions that aren't finished.
344 // If not, proceed.
345 // If so, subscribe to transactions and keep checking if can proceed.
346 //
347 // The plan is to have a finer-grained locking but just blocking applying
348 // synced data until a persisting transaction is finished seems fine.
349 // We also don't yet have support for transactions that don't immediately
350 // persist so right now, blocking sync only delays their application for a
351 // few hundred milliseconds. So not the worse thing in th world.
352 // But something to fix in the future.
353 // Create a Set with only the terminal states
354 const terminalStates = new Set<TransactionState>([`completed`, `failed`])
355
356 // Function to check if a state is NOT a terminal state
357 function isNotTerminalState({ state }: Transaction): boolean {
358 return !terminalStates.has(state)
359 }
360 if (
361 this.transactions.size === 0 ||
362 !Array.from(this.transactions.values()).some(isNotTerminalState)
363 ) {
364 const keys = new Set<string>()
365 batch(() => {
366 for (const transaction of this.pendingSyncedTransactions) {
367 for (const operation of transaction.operations) {
368 keys.add(operation.key)
369 this.syncedMetadata.setState((prevData) => {
370 switch (operation.type) {
371 case `insert`:
372 prevData.set(operation.key, operation.metadata)
373 break
374 case `update`:
375 prevData.set(operation.key, {
376 ...prevData.get(operation.key)!,
377 ...operation.metadata,
378 })
379 break
380 case `delete`:
381 prevData.delete(operation.key)
382 break
383 }
384 return prevData
385 })
386 this.syncedData.setState((prevData) => {
387 switch (operation.type) {
388 case `insert`:
389 prevData.set(operation.key, operation.value)
390 break
391 case `update`:
392 prevData.set(operation.key, {
393 ...prevData.get(operation.key)!,
394 ...operation.value,
395 })
396 break
397 case `delete`:
398 prevData.delete(operation.key)
399 break
400 }
401 return prevData
402 })
403 }
404 }
405 })
406
407 keys.forEach((key) => {
408 const curValue = this.state.get(key)
409 if (curValue) {
410 this.objectKeyMap.set(curValue, key)
411 }
412 })
413
414 this.pendingSyncedTransactions = []
415
416 // Call any registered one-time commit listeners
417 if (!this.hasReceivedFirstCommit) {
418 this.hasReceivedFirstCommit = true
419 const callbacks = [...this.onFirstCommitCallbacks]
420 this.onFirstCommitCallbacks = []
421 callbacks.forEach((callback) => callback())
422 }
423 }
424 }
425
426 private ensureStandardSchema(schema: unknown): StandardSchema<T> {
427 // If the schema already implements the standard-schema interface, return it
428 if (schema && typeof schema === `object` && `~standard` in schema) {
429 return schema as StandardSchema<T>
430 }
431
432 throw new Error(
433 `Schema must either implement the standard-schema interface or be a Zod schema`
434 )
435 }
436
437 private validateData(
438 data: unknown,
439 type: `insert` | `update`,
440 key?: string
441 ): T | never {
442 if (!this.config.schema) return data as T
443
444 const standardSchema = this.ensureStandardSchema(this.config.schema)
445
446 // For updates, we need to merge with the existing data before validation
447 if (type === `update` && key) {
448 // Get the existing data for this key
449 const existingData = this.state.get(key)
450
451 if (
452 existingData &&
453 data &&
454 typeof data === `object` &&
455 typeof existingData === `object`
456 ) {
457 // Merge the update with the existing data
458 const mergedData = { ...existingData, ...data }
459
460 // Validate the merged data
461 const result = standardSchema[`~standard`].validate(mergedData)
462
463 // Ensure validation is synchronous
464 if (result instanceof Promise) {
465 throw new TypeError(`Schema validation must be synchronous`)
466 }
467
468 // If validation fails, throw a SchemaValidationError with the issues
469 if (`issues` in result && result.issues) {
470 const typedIssues = result.issues.map((issue) => ({
471 message: issue.message,
472 path: issue.path?.map((p) => String(p)),
473 }))
474 throw new SchemaValidationError(type, typedIssues)
475 }
476
477 // Return the original update data, not the merged data
478 // We only used the merged data for validation
479 return data as T
480 }
481 }
482
483 // For inserts or updates without existing data, validate the data directly
484 const result = standardSchema[`~standard`].validate(data)
485
486 // Ensure validation is synchronous
487 if (result instanceof Promise) {
488 throw new TypeError(`Schema validation must be synchronous`)
489 }
490
491 // If validation fails, throw a SchemaValidationError with the issues
492 if (`issues` in result && result.issues) {
493 const typedIssues = result.issues.map((issue) => ({
494 message: issue.message,
495 path: issue.path?.map((p) => String(p)),
496 }))
497 throw new SchemaValidationError(type, typedIssues)
498 }
499
500 return result.value as T
501 }
502
503 private generateKey(data: unknown): string {
504 const str = JSON.stringify(data)
505 let h = 0
506
507 for (let i = 0; i < str.length; i++) {
508 h = (Math.imul(31, h) + str.charCodeAt(i)) | 0
509 }
510
511 return Math.abs(h).toString(36)
512 }
513
514 /**
515 * Inserts one or more items into the collection
516 * @param items - Single item or array of items to insert
517 * @param config - Optional configuration including metadata and custom keys
518 * @returns A Transaction object representing the insert operation(s)
519 * @throws {SchemaValidationError} If the data fails schema validation
520 * @example
521 * // Insert a single item
522 * insert({ text: "Buy groceries", completed: false })
523 *
524 * // Insert multiple items
525 * insert([
526 * { text: "Buy groceries", completed: false },
527 * { text: "Walk dog", completed: false }
528 * ])
529 *
530 * // Insert with custom key
531 * insert({ text: "Buy groceries" }, { key: "grocery-task" })
532 */
533 insert = (data: T | Array<T>, config?: InsertConfig) => {
534 const items = Array.isArray(data) ? data : [data]
535 const mutations: Array<PendingMutation> = []
536
537 // Handle keys - convert to array if string, or generate if not provided
538 let keys: Array<string>
539 if (config?.key) {
540 const configKeys = Array.isArray(config.key) ? config.key : [config.key]
541 // If keys are provided, ensure we have the right number or allow sparse array
542 if (Array.isArray(config.key) && configKeys.length > items.length) {
543 throw new Error(`More keys provided than items to insert`)
544 }
545 keys = items.map((_, i) => configKeys[i] ?? this.generateKey(items[i]))
546 } else {
547 // No keys provided, generate for all items
548 keys = items.map((item) => this.generateKey(item))
549 }
550
551 // Create mutations for each item
552 items.forEach((item, index) => {
553 // Validate the data against the schema if one exists
554 const validatedData = this.validateData(item, `insert`)
555 const key = keys[index]!
556
557 const mutation: PendingMutation = {
558 mutationId: crypto.randomUUID(),
559 original: {},
560 modified: validatedData as Record<string, unknown>,
561 changes: validatedData as Record<string, unknown>,
562 key,
563 metadata: config?.metadata as unknown,
564 syncMetadata: this.config.sync.getSyncMetadata?.() || {},
565 type: `insert`,
566 createdAt: new Date(),
567 updatedAt: new Date(),
568 }
569
570 mutations.push(mutation)
571 })
572
573 return this.transactionManager.applyTransaction(mutations, {
574 type: `ordered`,
575 })
576 }
577
578 /**
579 * Updates one or more items in the collection using a callback function
580 * @param items - Single item/key or array of items/keys to update
581 * @param configOrCallback - Either update configuration or update callback
582 * @param maybeCallback - Update callback if config was provided
583 * @returns A Transaction object representing the update operation(s)
584 * @throws {SchemaValidationError} If the updated data fails schema validation
585 * @example
586 * // Update a single item
587 * update(todo, (draft) => { draft.completed = true })
588 *
589 * // Update multiple items
590 * update([todo1, todo2], (drafts) => {
591 * drafts.forEach(draft => { draft.completed = true })
592 * })
593 *
594 * // Update with metadata
595 * update(todo, { metadata: { reason: "user update" } }, (draft) => { draft.text = "Updated text" })
596 */
597
598 update<TItem extends object = T>(
599 item: TItem,
600 configOrCallback: ((draft: TItem) => void) | OperationConfig,
601 maybeCallback?: (draft: TItem) => void
602 ): Transaction
603
604 update<TItem extends object = T>(
605 items: Array<TItem>,
606 configOrCallback: ((draft: Array<TItem>) => void) | OperationConfig,
607 maybeCallback?: (draft: Array<TItem>) => void
608 ): Transaction
609
610 update<TItem extends object = T>(
611 items: TItem | Array<TItem>,
612 configOrCallback: ((draft: TItem | Array<TItem>) => void) | OperationConfig,
613 maybeCallback?: (draft: TItem | Array<TItem>) => void
614 ) {
615 if (typeof items === `undefined`) {
616 throw new Error(`The first argument to update is missing`)
617 }
618 const isArray = Array.isArray(items)
619 const itemsArray = Array.isArray(items) ? items : [items]
620 const callback =
621 typeof configOrCallback === `function` ? configOrCallback : maybeCallback!
622 const config =
623 typeof configOrCallback === `function` ? {} : configOrCallback
624
625 const keys = itemsArray.map((item) => {
626 if (typeof item === `object` && (item as unknown) !== null) {
627 const key = this.objectKeyMap.get(item)
628 if (key === undefined) {
629 throw new Error(`Object not found in collection`)
630 }
631 return key
632 }
633 throw new Error(`Invalid item type for update - must be an object`)
634 })
635
636 // Get the current objects or empty objects if they don't exist
637 const currentObjects = keys.map((key) => ({
638 ...(this.state.get(key) || {}),
639 })) as Array<TItem>
640
641 let changesArray
642 if (isArray) {
643 // Use the proxy to track changes for all objects
644 changesArray = withArrayChangeTracking(
645 currentObjects,
646 callback as (draft: Array<TItem>) => void
647 )
648 } else {
649 const result = withChangeTracking(
650 currentObjects[0] as TItem,
651 callback as (draft: TItem) => void
652 )
653 changesArray = [result]
654 }
655
656 // Create mutations for each object that has changes
657 const mutations: Array<PendingMutation> = keys
658 .map((key, index) => {
659 const changes = changesArray[index]
660
661 // Skip items with no changes
662 if (!changes || Object.keys(changes).length === 0) {
663 return null
664 }
665
666 // Validate the changes for this item
667 const validatedData = this.validateData(changes, `update`, key)
668
669 return {
670 mutationId: crypto.randomUUID(),
671 original: (this.state.get(key) || {}) as Record<string, unknown>,
672 modified: {
673 ...(this.state.get(key) || {}),
674 ...validatedData,
675 } as Record<string, unknown>,
676 changes: validatedData as Record<string, unknown>,
677 key,
678 metadata: config.metadata as unknown,
679 syncMetadata: (this.syncedMetadata.state.get(key) || {}) as Record<
680 string,
681 unknown
682 >,
683 type: `update`,
684 createdAt: new Date(),
685 updatedAt: new Date(),
686 }
687 })
688 .filter(Boolean) as Array<PendingMutation>
689
690 // If no changes were made, return early
691 if (mutations.length === 0) {
692 throw new Error(`No changes were made to any of the objects`)
693 }
694
695 return this.transactionManager.applyTransaction(mutations, {
696 type: `ordered`,
697 })
698 }
699
700 /**
701 * Deletes one or more items from the collection
702 * @param items - Single item/key or array of items/keys to delete
703 * @param config - Optional configuration including metadata
704 * @returns A Transaction object representing the delete operation(s)
705 * @example
706 * // Delete a single item
707 * delete(todo)
708 *
709 * // Delete multiple items
710 * delete([todo1, todo2])
711 *
712 * // Delete with metadata
713 * delete(todo, { metadata: { reason: "completed" } })
714 */
715 delete = (
716 items: Array<T | string> | T | string,
717 config?: OperationConfig
718 ) => {
719 const itemsArray = Array.isArray(items) ? items : [items]
720 const mutations: Array<PendingMutation> = []
721
722 for (const item of itemsArray) {
723 let key: string
724 if (typeof item === `object` && (item as unknown) !== null) {
725 const objectKey = this.objectKeyMap.get(item)
726 if (objectKey === undefined) {
727 throw new Error(`Object not found in collection`)
728 }
729 key = objectKey
730 } else if (typeof item === `string`) {
731 key = item
732 } else {
733 throw new Error(
734 `Invalid item type for delete - must be an object or string key`
735 )
736 }
737
738 const mutation: PendingMutation = {
739 mutationId: crypto.randomUUID(),
740 original: (this.state.get(key) || {}) as Record<string, unknown>,
741 modified: { _deleted: true },
742 changes: { _deleted: true },
743 key,
744 metadata: config?.metadata as unknown,
745 syncMetadata: (this.syncedMetadata.state.get(key) || {}) as Record<
746 string,
747 unknown
748 >,
749 type: `delete`,
750 createdAt: new Date(),
751 updatedAt: new Date(),
752 }
753
754 mutations.push(mutation)
755 }
756
757 // Delete object => key mapping.
758 mutations.forEach((mutation) => {
759 const curValue = this.state.get(mutation.key)
760 if (curValue) {
761 this.objectKeyMap.delete(curValue)
762 }
763 })
764
765 return this.transactionManager.applyTransaction(mutations, {
766 type: `ordered`,
767 })
768 }
769
770 /**
771 * Gets the current state of the collection as a Map
772 *
773 * @returns A Map containing all items in the collection, with keys as identifiers
774 */
775 get state() {
776 return this.derivedState.state
777 }
778
779 /**
780 * Gets the current state of the collection as a Map, but only resolves when data is available
781 * Waits for the first sync commit to complete before resolving
782 *
783 * @returns Promise that resolves to a Map containing all items in the collection
784 */
785 stateWhenReady(): Promise<Map<string, T>> {
786 // If we already have data or there are no loading collections, resolve immediately
787 if (this.state.size > 0 || this.hasReceivedFirstCommit === true) {
788 return Promise.resolve(this.state)
789 }
790
791 // Otherwise, wait for the first commit
792 return new Promise<Map<string, T>>((resolve) => {
793 this.onFirstCommit(() => {
794 resolve(this.state)
795 })
796 })
797 }
798
799 /**
800 * Gets the current state of the collection as an Array
801 *
802 * @returns An Array containing all items in the collection
803 */
804 get toArray() {
805 return this.derivedArray.state
806 }
807
808 /**
809 * Gets the current state of the collection as an Array, but only resolves when data is available
810 * Waits for the first sync commit to complete before resolving
811 *
812 * @returns Promise that resolves to an Array containing all items in the collection
813 */
814 toArrayWhenReady(): Promise<Array<T>> {
815 // If we already have data or there are no loading collections, resolve immediately
816 if (this.toArray.length > 0 || this.hasReceivedFirstCommit === true) {
817 return Promise.resolve(this.toArray)
818 }
819
820 // Otherwise, wait for the first commit
821 return new Promise<Array<T>>((resolve) => {
822 this.onFirstCommit(() => {
823 resolve(this.toArray)
824 })
825 })
826 }
827
828 /**
829 * Gets the current transactions in the collection
830 *
831 * @returns A SortedMap of all transactions in the collection
832 */
833 get transactions() {
834 return this.transactionManager.transactions.state
835 }
836}