@tanstack/db 0.4.8 → 0.4.10
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.
- package/dist/cjs/collection/events.cjs +9 -51
- package/dist/cjs/collection/events.cjs.map +1 -1
- package/dist/cjs/collection/events.d.cts +18 -7
- package/dist/cjs/collection/index.cjs +9 -12
- package/dist/cjs/collection/index.cjs.map +1 -1
- package/dist/cjs/collection/index.d.cts +13 -14
- package/dist/cjs/collection/subscription.cjs +62 -6
- package/dist/cjs/collection/subscription.cjs.map +1 -1
- package/dist/cjs/collection/subscription.d.cts +16 -3
- package/dist/cjs/collection/sync.cjs +58 -6
- package/dist/cjs/collection/sync.cjs.map +1 -1
- package/dist/cjs/collection/sync.d.cts +18 -4
- package/dist/cjs/errors.cjs +59 -17
- package/dist/cjs/errors.cjs.map +1 -1
- package/dist/cjs/errors.d.cts +44 -8
- package/dist/cjs/event-emitter.cjs +94 -0
- package/dist/cjs/event-emitter.cjs.map +1 -0
- package/dist/cjs/event-emitter.d.cts +45 -0
- package/dist/cjs/index.cjs +9 -4
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/local-only.cjs.map +1 -1
- package/dist/cjs/local-only.d.cts +2 -5
- package/dist/cjs/query/builder/types.d.cts +1 -1
- package/dist/cjs/query/compiler/index.cjs +46 -19
- package/dist/cjs/query/compiler/index.cjs.map +1 -1
- package/dist/cjs/query/compiler/index.d.cts +35 -9
- package/dist/cjs/query/compiler/joins.cjs +91 -66
- package/dist/cjs/query/compiler/joins.cjs.map +1 -1
- package/dist/cjs/query/compiler/joins.d.cts +6 -3
- package/dist/cjs/query/compiler/order-by.cjs +20 -4
- package/dist/cjs/query/compiler/order-by.cjs.map +1 -1
- package/dist/cjs/query/compiler/order-by.d.cts +3 -1
- package/dist/cjs/query/compiler/select.cjs.map +1 -1
- package/dist/cjs/query/compiler/types.d.cts +4 -0
- package/dist/cjs/query/index.d.cts +1 -0
- package/dist/cjs/query/live/collection-config-builder.cjs +306 -46
- package/dist/cjs/query/live/collection-config-builder.cjs.map +1 -1
- package/dist/cjs/query/live/collection-config-builder.d.cts +97 -9
- package/dist/cjs/query/live/collection-registry.cjs +16 -0
- package/dist/cjs/query/live/collection-registry.cjs.map +1 -0
- package/dist/cjs/query/live/collection-registry.d.cts +26 -0
- package/dist/cjs/query/live/collection-subscriber.cjs +86 -58
- package/dist/cjs/query/live/collection-subscriber.cjs.map +1 -1
- package/dist/cjs/query/live/collection-subscriber.d.cts +5 -7
- package/dist/cjs/query/live-query-collection.cjs +11 -5
- package/dist/cjs/query/live-query-collection.cjs.map +1 -1
- package/dist/cjs/query/live-query-collection.d.cts +12 -5
- package/dist/cjs/query/optimizer.cjs +44 -7
- package/dist/cjs/query/optimizer.cjs.map +1 -1
- package/dist/cjs/query/optimizer.d.cts +4 -4
- package/dist/cjs/scheduler.cjs +137 -0
- package/dist/cjs/scheduler.cjs.map +1 -0
- package/dist/cjs/scheduler.d.cts +56 -0
- package/dist/cjs/transactions.cjs +7 -1
- package/dist/cjs/transactions.cjs.map +1 -1
- package/dist/cjs/types.d.cts +82 -11
- package/dist/esm/collection/events.d.ts +18 -7
- package/dist/esm/collection/events.js +9 -51
- package/dist/esm/collection/events.js.map +1 -1
- package/dist/esm/collection/index.d.ts +13 -14
- package/dist/esm/collection/index.js +9 -12
- package/dist/esm/collection/index.js.map +1 -1
- package/dist/esm/collection/subscription.d.ts +16 -3
- package/dist/esm/collection/subscription.js +62 -6
- package/dist/esm/collection/subscription.js.map +1 -1
- package/dist/esm/collection/sync.d.ts +18 -4
- package/dist/esm/collection/sync.js +59 -7
- package/dist/esm/collection/sync.js.map +1 -1
- package/dist/esm/errors.d.ts +44 -8
- package/dist/esm/errors.js +60 -18
- package/dist/esm/errors.js.map +1 -1
- package/dist/esm/event-emitter.d.ts +45 -0
- package/dist/esm/event-emitter.js +94 -0
- package/dist/esm/event-emitter.js.map +1 -0
- package/dist/esm/index.js +10 -5
- package/dist/esm/local-only.d.ts +2 -5
- package/dist/esm/local-only.js.map +1 -1
- package/dist/esm/query/builder/types.d.ts +1 -1
- package/dist/esm/query/compiler/index.d.ts +35 -9
- package/dist/esm/query/compiler/index.js +46 -19
- package/dist/esm/query/compiler/index.js.map +1 -1
- package/dist/esm/query/compiler/joins.d.ts +6 -3
- package/dist/esm/query/compiler/joins.js +93 -68
- package/dist/esm/query/compiler/joins.js.map +1 -1
- package/dist/esm/query/compiler/order-by.d.ts +3 -1
- package/dist/esm/query/compiler/order-by.js +20 -4
- package/dist/esm/query/compiler/order-by.js.map +1 -1
- package/dist/esm/query/compiler/select.js.map +1 -1
- package/dist/esm/query/compiler/types.d.ts +4 -0
- package/dist/esm/query/index.d.ts +1 -0
- package/dist/esm/query/live/collection-config-builder.d.ts +97 -9
- package/dist/esm/query/live/collection-config-builder.js +306 -46
- package/dist/esm/query/live/collection-config-builder.js.map +1 -1
- package/dist/esm/query/live/collection-registry.d.ts +26 -0
- package/dist/esm/query/live/collection-registry.js +16 -0
- package/dist/esm/query/live/collection-registry.js.map +1 -0
- package/dist/esm/query/live/collection-subscriber.d.ts +5 -7
- package/dist/esm/query/live/collection-subscriber.js +86 -58
- package/dist/esm/query/live/collection-subscriber.js.map +1 -1
- package/dist/esm/query/live-query-collection.d.ts +12 -5
- package/dist/esm/query/live-query-collection.js +11 -5
- package/dist/esm/query/live-query-collection.js.map +1 -1
- package/dist/esm/query/optimizer.d.ts +4 -4
- package/dist/esm/query/optimizer.js +44 -7
- package/dist/esm/query/optimizer.js.map +1 -1
- package/dist/esm/scheduler.d.ts +56 -0
- package/dist/esm/scheduler.js +137 -0
- package/dist/esm/scheduler.js.map +1 -0
- package/dist/esm/transactions.js +7 -1
- package/dist/esm/transactions.js.map +1 -1
- package/dist/esm/types.d.ts +82 -11
- package/package.json +2 -2
- package/src/collection/events.ts +25 -74
- package/src/collection/index.ts +15 -19
- package/src/collection/subscription.ts +88 -6
- package/src/collection/sync.ts +81 -9
- package/src/errors.ts +91 -13
- package/src/event-emitter.ts +118 -0
- package/src/local-only.ts +5 -12
- package/src/query/builder/types.ts +1 -1
- package/src/query/compiler/index.ts +124 -33
- package/src/query/compiler/joins.ts +187 -128
- package/src/query/compiler/order-by.ts +30 -2
- package/src/query/compiler/select.ts +2 -3
- package/src/query/compiler/types.ts +5 -0
- package/src/query/index.ts +1 -0
- package/src/query/live/collection-config-builder.ts +501 -60
- package/src/query/live/collection-registry.ts +47 -0
- package/src/query/live/collection-subscriber.ts +137 -105
- package/src/query/live-query-collection.ts +47 -18
- package/src/query/optimizer.ts +85 -15
- package/src/scheduler.ts +198 -0
- package/src/transactions.ts +12 -1
- package/src/types.ts +93 -11
package/dist/esm/transactions.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createDeferred } from "./deferred.js";
|
|
2
2
|
import { MissingMutationFunctionError, TransactionNotPendingMutateError, TransactionAlreadyCompletedRollbackError, TransactionNotPendingCommitError } from "./errors.js";
|
|
3
|
+
import { transactionScopedScheduler } from "./scheduler.js";
|
|
3
4
|
const transactions = [];
|
|
4
5
|
let transactionStack = [];
|
|
5
6
|
let sequenceNumber = 0;
|
|
@@ -61,10 +62,15 @@ function getActiveTransaction() {
|
|
|
61
62
|
}
|
|
62
63
|
}
|
|
63
64
|
function registerTransaction(tx) {
|
|
65
|
+
transactionScopedScheduler.clear(tx.id);
|
|
64
66
|
transactionStack.push(tx);
|
|
65
67
|
}
|
|
66
68
|
function unregisterTransaction(tx) {
|
|
67
|
-
|
|
69
|
+
try {
|
|
70
|
+
transactionScopedScheduler.flush(tx.id);
|
|
71
|
+
} finally {
|
|
72
|
+
transactionStack = transactionStack.filter((t) => t.id !== tx.id);
|
|
73
|
+
}
|
|
68
74
|
}
|
|
69
75
|
function removeFromPendingList(tx) {
|
|
70
76
|
const index = transactions.findIndex((t) => t.id === tx.id);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transactions.js","sources":["../../src/transactions.ts"],"sourcesContent":["import { createDeferred } from \"./deferred\"\nimport {\n MissingMutationFunctionError,\n TransactionAlreadyCompletedRollbackError,\n TransactionNotPendingCommitError,\n TransactionNotPendingMutateError,\n} from \"./errors\"\nimport type { Deferred } from \"./deferred\"\nimport type {\n MutationFn,\n PendingMutation,\n TransactionConfig,\n TransactionState,\n TransactionWithMutations,\n} from \"./types\"\n\nconst transactions: Array<Transaction<any>> = []\nlet transactionStack: Array<Transaction<any>> = []\n\nlet sequenceNumber = 0\n\n/**\n * Merges two pending mutations for the same item within a transaction\n *\n * Merge behavior truth table:\n * - (insert, update) → insert (merge changes, keep empty original)\n * - (insert, delete) → null (cancel both mutations)\n * - (update, delete) → delete (delete dominates)\n * - (update, update) → update (replace with latest, union changes)\n * - (delete, delete) → delete (replace with latest)\n * - (insert, insert) → insert (replace with latest)\n *\n * Note: (delete, update) and (delete, insert) should never occur as the collection\n * layer prevents operations on deleted items within the same transaction.\n *\n * @param existing - The existing mutation in the transaction\n * @param incoming - The new mutation being applied\n * @returns The merged mutation, or null if both should be removed\n */\nfunction mergePendingMutations<T extends object>(\n existing: PendingMutation<T>,\n incoming: PendingMutation<T>\n): PendingMutation<T> | null {\n // Truth table implementation\n switch (`${existing.type}-${incoming.type}` as const) {\n case `insert-update`: {\n // Update after insert: keep as insert but merge changes\n // For insert-update, the key should remain the same since collections don't allow key changes\n return {\n ...existing,\n type: `insert` as const,\n original: {},\n modified: incoming.modified,\n changes: { ...existing.changes, ...incoming.changes },\n // Keep existing keys (key changes not allowed in updates)\n key: existing.key,\n globalKey: existing.globalKey,\n // Merge metadata (last-write-wins)\n metadata: incoming.metadata ?? existing.metadata,\n syncMetadata: { ...existing.syncMetadata, ...incoming.syncMetadata },\n // Update tracking info\n mutationId: incoming.mutationId,\n updatedAt: incoming.updatedAt,\n }\n }\n\n case `insert-delete`:\n // Delete after insert: cancel both mutations\n return null\n\n case `update-delete`:\n // Delete after update: delete dominates\n return incoming\n\n case `update-update`: {\n // Update after update: replace with latest, union changes\n return {\n ...incoming,\n // Keep original from first update\n original: existing.original,\n // Union the changes from both updates\n changes: { ...existing.changes, ...incoming.changes },\n // Merge metadata\n metadata: incoming.metadata ?? existing.metadata,\n syncMetadata: { ...existing.syncMetadata, ...incoming.syncMetadata },\n }\n }\n\n case `delete-delete`:\n case `insert-insert`:\n // Same type: replace with latest\n return incoming\n\n default: {\n // Exhaustiveness check\n const _exhaustive: never = `${existing.type}-${incoming.type}` as never\n throw new Error(`Unhandled mutation combination: ${_exhaustive}`)\n }\n }\n}\n\n/**\n * Creates a new transaction for grouping multiple collection operations\n * @param config - Transaction configuration with mutation function\n * @returns A new Transaction instance\n * @example\n * // Basic transaction usage\n * const tx = createTransaction({\n * mutationFn: async ({ transaction }) => {\n * // Send all mutations to API\n * await api.saveChanges(transaction.mutations)\n * }\n * })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Buy milk\" })\n * collection.update(\"2\", draft => { draft.completed = true })\n * })\n *\n * await tx.isPersisted.promise\n *\n * @example\n * // Handle transaction errors\n * try {\n * const tx = createTransaction({\n * mutationFn: async () => { throw new Error(\"API failed\") }\n * })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"New item\" })\n * })\n *\n * await tx.isPersisted.promise\n * } catch (error) {\n * console.log('Transaction failed:', error)\n * }\n *\n * @example\n * // Manual commit control\n * const tx = createTransaction({\n * autoCommit: false,\n * mutationFn: async () => {\n * // API call\n * }\n * })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Item\" })\n * })\n *\n * // Commit later\n * await tx.commit()\n */\nexport function createTransaction<T extends object = Record<string, unknown>>(\n config: TransactionConfig<T>\n): Transaction<T> {\n const newTransaction = new Transaction<T>(config)\n transactions.push(newTransaction)\n return newTransaction\n}\n\n/**\n * Gets the currently active ambient transaction, if any\n * Used internally by collection operations to join existing transactions\n * @returns The active transaction or undefined if none is active\n * @example\n * // Check if operations will join an ambient transaction\n * const ambientTx = getActiveTransaction()\n * if (ambientTx) {\n * console.log('Operations will join transaction:', ambientTx.id)\n * }\n */\nexport function getActiveTransaction(): Transaction | undefined {\n if (transactionStack.length > 0) {\n return transactionStack.slice(-1)[0]\n } else {\n return undefined\n }\n}\n\nfunction registerTransaction(tx: Transaction<any>) {\n transactionStack.push(tx)\n}\n\nfunction unregisterTransaction(tx: Transaction<any>) {\n transactionStack = transactionStack.filter((t) => t.id !== tx.id)\n}\n\nfunction removeFromPendingList(tx: Transaction<any>) {\n const index = transactions.findIndex((t) => t.id === tx.id)\n if (index !== -1) {\n transactions.splice(index, 1)\n }\n}\n\nclass Transaction<T extends object = Record<string, unknown>> {\n public id: string\n public state: TransactionState\n public mutationFn: MutationFn<T>\n public mutations: Array<PendingMutation<T>>\n public isPersisted: Deferred<Transaction<T>>\n public autoCommit: boolean\n public createdAt: Date\n public sequenceNumber: number\n public metadata: Record<string, unknown>\n public error?: {\n message: string\n error: Error\n }\n\n constructor(config: TransactionConfig<T>) {\n if (typeof config.mutationFn === `undefined`) {\n throw new MissingMutationFunctionError()\n }\n this.id = config.id ?? crypto.randomUUID()\n this.mutationFn = config.mutationFn\n this.state = `pending`\n this.mutations = []\n this.isPersisted = createDeferred<Transaction<T>>()\n this.autoCommit = config.autoCommit ?? true\n this.createdAt = new Date()\n this.sequenceNumber = sequenceNumber++\n this.metadata = config.metadata ?? {}\n }\n\n setState(newState: TransactionState) {\n this.state = newState\n\n if (newState === `completed` || newState === `failed`) {\n removeFromPendingList(this)\n }\n }\n\n /**\n * Execute collection operations within this transaction\n * @param callback - Function containing collection operations to group together\n * @returns This transaction for chaining\n * @example\n * // Group multiple operations\n * const tx = createTransaction({ mutationFn: async () => {\n * // Send to API\n * }})\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Buy milk\" })\n * collection.update(\"2\", draft => { draft.completed = true })\n * collection.delete(\"3\")\n * })\n *\n * await tx.isPersisted.promise\n *\n * @example\n * // Handle mutate errors\n * try {\n * tx.mutate(() => {\n * collection.insert({ id: \"invalid\" }) // This might throw\n * })\n * } catch (error) {\n * console.log('Mutation failed:', error)\n * }\n *\n * @example\n * // Manual commit control\n * const tx = createTransaction({ autoCommit: false, mutationFn: async () => {} })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Item\" })\n * })\n *\n * // Commit later when ready\n * await tx.commit()\n */\n mutate(callback: () => void): Transaction<T> {\n if (this.state !== `pending`) {\n throw new TransactionNotPendingMutateError()\n }\n\n registerTransaction(this)\n try {\n callback()\n } finally {\n unregisterTransaction(this)\n }\n\n if (this.autoCommit) {\n this.commit().catch(() => {\n // Errors from autoCommit are handled via isPersisted.promise\n // This catch prevents unhandled promise rejections\n })\n }\n\n return this\n }\n\n /**\n * Apply new mutations to this transaction, intelligently merging with existing mutations\n *\n * When mutations operate on the same item (same globalKey), they are merged according to\n * the following rules:\n *\n * - **insert + update** → insert (merge changes, keep empty original)\n * - **insert + delete** → removed (mutations cancel each other out)\n * - **update + delete** → delete (delete dominates)\n * - **update + update** → update (union changes, keep first original)\n * - **same type** → replace with latest\n *\n * This merging reduces over-the-wire churn and keeps the optimistic local view\n * aligned with user intent.\n *\n * @param mutations - Array of new mutations to apply\n */\n applyMutations(mutations: Array<PendingMutation<any>>): void {\n for (const newMutation of mutations) {\n const existingIndex = this.mutations.findIndex(\n (m) => m.globalKey === newMutation.globalKey\n )\n\n if (existingIndex >= 0) {\n const existingMutation = this.mutations[existingIndex]!\n const mergeResult = mergePendingMutations(existingMutation, newMutation)\n\n if (mergeResult === null) {\n // Remove the mutation (e.g., delete after insert cancels both)\n this.mutations.splice(existingIndex, 1)\n } else {\n // Replace with merged mutation\n this.mutations[existingIndex] = mergeResult\n }\n } else {\n // Insert new mutation\n this.mutations.push(newMutation)\n }\n }\n }\n\n /**\n * Rollback the transaction and any conflicting transactions\n * @param config - Configuration for rollback behavior\n * @returns This transaction for chaining\n * @example\n * // Manual rollback\n * const tx = createTransaction({ mutationFn: async () => {\n * // Send to API\n * }})\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Buy milk\" })\n * })\n *\n * // Rollback if needed\n * if (shouldCancel) {\n * tx.rollback()\n * }\n *\n * @example\n * // Handle rollback cascade (automatic)\n * const tx1 = createTransaction({ mutationFn: async () => {} })\n * const tx2 = createTransaction({ mutationFn: async () => {} })\n *\n * tx1.mutate(() => collection.update(\"1\", draft => { draft.value = \"A\" }))\n * tx2.mutate(() => collection.update(\"1\", draft => { draft.value = \"B\" })) // Same item\n *\n * tx1.rollback() // This will also rollback tx2 due to conflict\n *\n * @example\n * // Handle rollback in error scenarios\n * try {\n * await tx.isPersisted.promise\n * } catch (error) {\n * console.log('Transaction was rolled back:', error)\n * // Transaction automatically rolled back on mutation function failure\n * }\n */\n rollback(config?: { isSecondaryRollback?: boolean }): Transaction<T> {\n const isSecondaryRollback = config?.isSecondaryRollback ?? false\n if (this.state === `completed`) {\n throw new TransactionAlreadyCompletedRollbackError()\n }\n\n this.setState(`failed`)\n\n // See if there's any other transactions w/ mutations on the same ids\n // and roll them back as well.\n if (!isSecondaryRollback) {\n const mutationIds = new Set()\n this.mutations.forEach((m) => mutationIds.add(m.globalKey))\n for (const t of transactions) {\n t.state === `pending` &&\n t.mutations.some((m) => mutationIds.has(m.globalKey)) &&\n t.rollback({ isSecondaryRollback: true })\n }\n }\n\n // Reject the promise\n this.isPersisted.reject(this.error?.error)\n this.touchCollection()\n\n return this\n }\n\n // Tell collection that something has changed with the transaction\n touchCollection(): void {\n const hasCalled = new Set()\n for (const mutation of this.mutations) {\n if (!hasCalled.has(mutation.collection.id)) {\n mutation.collection._state.onTransactionStateChange()\n\n // Only call commitPendingTransactions if there are pending sync transactions\n if (mutation.collection._state.pendingSyncedTransactions.length > 0) {\n mutation.collection._state.commitPendingTransactions()\n }\n\n hasCalled.add(mutation.collection.id)\n }\n }\n }\n\n /**\n * Commit the transaction and execute the mutation function\n * @returns Promise that resolves to this transaction when complete\n * @example\n * // Manual commit (when autoCommit is false)\n * const tx = createTransaction({\n * autoCommit: false,\n * mutationFn: async ({ transaction }) => {\n * await api.saveChanges(transaction.mutations)\n * }\n * })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Buy milk\" })\n * })\n *\n * await tx.commit() // Manually commit\n *\n * @example\n * // Handle commit errors\n * try {\n * const tx = createTransaction({\n * mutationFn: async () => { throw new Error(\"API failed\") }\n * })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Item\" })\n * })\n *\n * await tx.commit()\n * } catch (error) {\n * console.log('Commit failed, transaction rolled back:', error)\n * }\n *\n * @example\n * // Check transaction state after commit\n * await tx.commit()\n * console.log(tx.state) // \"completed\" or \"failed\"\n */\n async commit(): Promise<Transaction<T>> {\n if (this.state !== `pending`) {\n throw new TransactionNotPendingCommitError()\n }\n\n this.setState(`persisting`)\n\n if (this.mutations.length === 0) {\n this.setState(`completed`)\n this.isPersisted.resolve(this)\n\n return this\n }\n\n // Run mutationFn\n try {\n // At this point we know there's at least one mutation\n // We've already verified mutations is non-empty, so this cast is safe\n // Use a direct type assertion instead of object spreading to preserve the original type\n await this.mutationFn({\n transaction: this as unknown as TransactionWithMutations<T>,\n })\n\n this.setState(`completed`)\n this.touchCollection()\n\n this.isPersisted.resolve(this)\n } catch (error) {\n // Preserve the original error for rethrowing\n const originalError =\n error instanceof Error ? error : new Error(String(error))\n\n // Update transaction with error information\n this.error = {\n message: originalError.message,\n error: originalError,\n }\n\n // rollback the transaction\n this.rollback()\n\n // Re-throw the original error to preserve identity and stack\n throw originalError\n }\n\n return this\n }\n\n /**\n * Compare two transactions by their createdAt time and sequence number in order\n * to sort them in the order they were created.\n * @param other - The other transaction to compare to\n * @returns -1 if this transaction was created before the other, 1 if it was created after, 0 if they were created at the same time\n */\n compareCreatedAt(other: Transaction<any>): number {\n const createdAtComparison =\n this.createdAt.getTime() - other.createdAt.getTime()\n if (createdAtComparison !== 0) {\n return createdAtComparison\n }\n return this.sequenceNumber - other.sequenceNumber\n }\n}\n\nexport type { Transaction }\n"],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AA,MAAA,CACd;AAED,WAAK,SAAS,WAAW;AACzB,WAAK,gBAAA;AAEL,WAAK,YAAY,QAAQ,IAAI;AAAA,IAC/B,SAAS,OAAO;AAEd,YAAM,gBACJ,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AAG1D,WAAK,QAAQ;AAAA,QACX,SAAS,cAAc;AAAA,QACvB,OAAO;AAAA,MAAA;AAIT,WAAK,SAAA;AAGL,YAAM;AAAA,IACR;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,iBAAiB,OAAiC;AAChD,UAAM,sBACJ,KAAK,UAAU,YAAY,MAAM,UAAU,QAAA;AAC7C,QAAI,wBAAwB,GAAG;AAC7B,aAAO;AAAA,IACT;AACA,WAAO,KAAK,iBAAiB,MAAM;AAAA,EACrC;AACF;"}
|
|
1
|
+
{"version":3,"file":"transactions.js","sources":["../../src/transactions.ts"],"sourcesContent":["import { createDeferred } from \"./deferred\"\nimport {\n MissingMutationFunctionError,\n TransactionAlreadyCompletedRollbackError,\n TransactionNotPendingCommitError,\n TransactionNotPendingMutateError,\n} from \"./errors\"\nimport { transactionScopedScheduler } from \"./scheduler.js\"\nimport type { Deferred } from \"./deferred\"\nimport type {\n MutationFn,\n PendingMutation,\n TransactionConfig,\n TransactionState,\n TransactionWithMutations,\n} from \"./types\"\n\nconst transactions: Array<Transaction<any>> = []\nlet transactionStack: Array<Transaction<any>> = []\n\nlet sequenceNumber = 0\n\n/**\n * Merges two pending mutations for the same item within a transaction\n *\n * Merge behavior truth table:\n * - (insert, update) → insert (merge changes, keep empty original)\n * - (insert, delete) → null (cancel both mutations)\n * - (update, delete) → delete (delete dominates)\n * - (update, update) → update (replace with latest, union changes)\n * - (delete, delete) → delete (replace with latest)\n * - (insert, insert) → insert (replace with latest)\n *\n * Note: (delete, update) and (delete, insert) should never occur as the collection\n * layer prevents operations on deleted items within the same transaction.\n *\n * @param existing - The existing mutation in the transaction\n * @param incoming - The new mutation being applied\n * @returns The merged mutation, or null if both should be removed\n */\nfunction mergePendingMutations<T extends object>(\n existing: PendingMutation<T>,\n incoming: PendingMutation<T>\n): PendingMutation<T> | null {\n // Truth table implementation\n switch (`${existing.type}-${incoming.type}` as const) {\n case `insert-update`: {\n // Update after insert: keep as insert but merge changes\n // For insert-update, the key should remain the same since collections don't allow key changes\n return {\n ...existing,\n type: `insert` as const,\n original: {},\n modified: incoming.modified,\n changes: { ...existing.changes, ...incoming.changes },\n // Keep existing keys (key changes not allowed in updates)\n key: existing.key,\n globalKey: existing.globalKey,\n // Merge metadata (last-write-wins)\n metadata: incoming.metadata ?? existing.metadata,\n syncMetadata: { ...existing.syncMetadata, ...incoming.syncMetadata },\n // Update tracking info\n mutationId: incoming.mutationId,\n updatedAt: incoming.updatedAt,\n }\n }\n\n case `insert-delete`:\n // Delete after insert: cancel both mutations\n return null\n\n case `update-delete`:\n // Delete after update: delete dominates\n return incoming\n\n case `update-update`: {\n // Update after update: replace with latest, union changes\n return {\n ...incoming,\n // Keep original from first update\n original: existing.original,\n // Union the changes from both updates\n changes: { ...existing.changes, ...incoming.changes },\n // Merge metadata\n metadata: incoming.metadata ?? existing.metadata,\n syncMetadata: { ...existing.syncMetadata, ...incoming.syncMetadata },\n }\n }\n\n case `delete-delete`:\n case `insert-insert`:\n // Same type: replace with latest\n return incoming\n\n default: {\n // Exhaustiveness check\n const _exhaustive: never = `${existing.type}-${incoming.type}` as never\n throw new Error(`Unhandled mutation combination: ${_exhaustive}`)\n }\n }\n}\n\n/**\n * Creates a new transaction for grouping multiple collection operations\n * @param config - Transaction configuration with mutation function\n * @returns A new Transaction instance\n * @example\n * // Basic transaction usage\n * const tx = createTransaction({\n * mutationFn: async ({ transaction }) => {\n * // Send all mutations to API\n * await api.saveChanges(transaction.mutations)\n * }\n * })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Buy milk\" })\n * collection.update(\"2\", draft => { draft.completed = true })\n * })\n *\n * await tx.isPersisted.promise\n *\n * @example\n * // Handle transaction errors\n * try {\n * const tx = createTransaction({\n * mutationFn: async () => { throw new Error(\"API failed\") }\n * })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"New item\" })\n * })\n *\n * await tx.isPersisted.promise\n * } catch (error) {\n * console.log('Transaction failed:', error)\n * }\n *\n * @example\n * // Manual commit control\n * const tx = createTransaction({\n * autoCommit: false,\n * mutationFn: async () => {\n * // API call\n * }\n * })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Item\" })\n * })\n *\n * // Commit later\n * await tx.commit()\n */\nexport function createTransaction<T extends object = Record<string, unknown>>(\n config: TransactionConfig<T>\n): Transaction<T> {\n const newTransaction = new Transaction<T>(config)\n transactions.push(newTransaction)\n return newTransaction\n}\n\n/**\n * Gets the currently active ambient transaction, if any\n * Used internally by collection operations to join existing transactions\n * @returns The active transaction or undefined if none is active\n * @example\n * // Check if operations will join an ambient transaction\n * const ambientTx = getActiveTransaction()\n * if (ambientTx) {\n * console.log('Operations will join transaction:', ambientTx.id)\n * }\n */\nexport function getActiveTransaction(): Transaction | undefined {\n if (transactionStack.length > 0) {\n return transactionStack.slice(-1)[0]\n } else {\n return undefined\n }\n}\n\nfunction registerTransaction(tx: Transaction<any>) {\n // Clear any stale work that may have been left behind if a previous mutate\n // scope aborted before we could flush.\n transactionScopedScheduler.clear(tx.id)\n transactionStack.push(tx)\n}\n\nfunction unregisterTransaction(tx: Transaction<any>) {\n // Always flush pending work for this transaction before removing it from\n // the ambient stack – this runs even if the mutate callback throws.\n // If flush throws (e.g., due to a job error), we still clean up the stack.\n try {\n transactionScopedScheduler.flush(tx.id)\n } finally {\n transactionStack = transactionStack.filter((t) => t.id !== tx.id)\n }\n}\n\nfunction removeFromPendingList(tx: Transaction<any>) {\n const index = transactions.findIndex((t) => t.id === tx.id)\n if (index !== -1) {\n transactions.splice(index, 1)\n }\n}\n\nclass Transaction<T extends object = Record<string, unknown>> {\n public id: string\n public state: TransactionState\n public mutationFn: MutationFn<T>\n public mutations: Array<PendingMutation<T>>\n public isPersisted: Deferred<Transaction<T>>\n public autoCommit: boolean\n public createdAt: Date\n public sequenceNumber: number\n public metadata: Record<string, unknown>\n public error?: {\n message: string\n error: Error\n }\n\n constructor(config: TransactionConfig<T>) {\n if (typeof config.mutationFn === `undefined`) {\n throw new MissingMutationFunctionError()\n }\n this.id = config.id ?? crypto.randomUUID()\n this.mutationFn = config.mutationFn\n this.state = `pending`\n this.mutations = []\n this.isPersisted = createDeferred<Transaction<T>>()\n this.autoCommit = config.autoCommit ?? true\n this.createdAt = new Date()\n this.sequenceNumber = sequenceNumber++\n this.metadata = config.metadata ?? {}\n }\n\n setState(newState: TransactionState) {\n this.state = newState\n\n if (newState === `completed` || newState === `failed`) {\n removeFromPendingList(this)\n }\n }\n\n /**\n * Execute collection operations within this transaction\n * @param callback - Function containing collection operations to group together\n * @returns This transaction for chaining\n * @example\n * // Group multiple operations\n * const tx = createTransaction({ mutationFn: async () => {\n * // Send to API\n * }})\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Buy milk\" })\n * collection.update(\"2\", draft => { draft.completed = true })\n * collection.delete(\"3\")\n * })\n *\n * await tx.isPersisted.promise\n *\n * @example\n * // Handle mutate errors\n * try {\n * tx.mutate(() => {\n * collection.insert({ id: \"invalid\" }) // This might throw\n * })\n * } catch (error) {\n * console.log('Mutation failed:', error)\n * }\n *\n * @example\n * // Manual commit control\n * const tx = createTransaction({ autoCommit: false, mutationFn: async () => {} })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Item\" })\n * })\n *\n * // Commit later when ready\n * await tx.commit()\n */\n mutate(callback: () => void): Transaction<T> {\n if (this.state !== `pending`) {\n throw new TransactionNotPendingMutateError()\n }\n\n registerTransaction(this)\n try {\n callback()\n } finally {\n unregisterTransaction(this)\n }\n\n if (this.autoCommit) {\n this.commit().catch(() => {\n // Errors from autoCommit are handled via isPersisted.promise\n // This catch prevents unhandled promise rejections\n })\n }\n\n return this\n }\n\n /**\n * Apply new mutations to this transaction, intelligently merging with existing mutations\n *\n * When mutations operate on the same item (same globalKey), they are merged according to\n * the following rules:\n *\n * - **insert + update** → insert (merge changes, keep empty original)\n * - **insert + delete** → removed (mutations cancel each other out)\n * - **update + delete** → delete (delete dominates)\n * - **update + update** → update (union changes, keep first original)\n * - **same type** → replace with latest\n *\n * This merging reduces over-the-wire churn and keeps the optimistic local view\n * aligned with user intent.\n *\n * @param mutations - Array of new mutations to apply\n */\n applyMutations(mutations: Array<PendingMutation<any>>): void {\n for (const newMutation of mutations) {\n const existingIndex = this.mutations.findIndex(\n (m) => m.globalKey === newMutation.globalKey\n )\n\n if (existingIndex >= 0) {\n const existingMutation = this.mutations[existingIndex]!\n const mergeResult = mergePendingMutations(existingMutation, newMutation)\n\n if (mergeResult === null) {\n // Remove the mutation (e.g., delete after insert cancels both)\n this.mutations.splice(existingIndex, 1)\n } else {\n // Replace with merged mutation\n this.mutations[existingIndex] = mergeResult\n }\n } else {\n // Insert new mutation\n this.mutations.push(newMutation)\n }\n }\n }\n\n /**\n * Rollback the transaction and any conflicting transactions\n * @param config - Configuration for rollback behavior\n * @returns This transaction for chaining\n * @example\n * // Manual rollback\n * const tx = createTransaction({ mutationFn: async () => {\n * // Send to API\n * }})\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Buy milk\" })\n * })\n *\n * // Rollback if needed\n * if (shouldCancel) {\n * tx.rollback()\n * }\n *\n * @example\n * // Handle rollback cascade (automatic)\n * const tx1 = createTransaction({ mutationFn: async () => {} })\n * const tx2 = createTransaction({ mutationFn: async () => {} })\n *\n * tx1.mutate(() => collection.update(\"1\", draft => { draft.value = \"A\" }))\n * tx2.mutate(() => collection.update(\"1\", draft => { draft.value = \"B\" })) // Same item\n *\n * tx1.rollback() // This will also rollback tx2 due to conflict\n *\n * @example\n * // Handle rollback in error scenarios\n * try {\n * await tx.isPersisted.promise\n * } catch (error) {\n * console.log('Transaction was rolled back:', error)\n * // Transaction automatically rolled back on mutation function failure\n * }\n */\n rollback(config?: { isSecondaryRollback?: boolean }): Transaction<T> {\n const isSecondaryRollback = config?.isSecondaryRollback ?? false\n if (this.state === `completed`) {\n throw new TransactionAlreadyCompletedRollbackError()\n }\n\n this.setState(`failed`)\n\n // See if there's any other transactions w/ mutations on the same ids\n // and roll them back as well.\n if (!isSecondaryRollback) {\n const mutationIds = new Set()\n this.mutations.forEach((m) => mutationIds.add(m.globalKey))\n for (const t of transactions) {\n t.state === `pending` &&\n t.mutations.some((m) => mutationIds.has(m.globalKey)) &&\n t.rollback({ isSecondaryRollback: true })\n }\n }\n\n // Reject the promise\n this.isPersisted.reject(this.error?.error)\n this.touchCollection()\n\n return this\n }\n\n // Tell collection that something has changed with the transaction\n touchCollection(): void {\n const hasCalled = new Set()\n for (const mutation of this.mutations) {\n if (!hasCalled.has(mutation.collection.id)) {\n mutation.collection._state.onTransactionStateChange()\n\n // Only call commitPendingTransactions if there are pending sync transactions\n if (mutation.collection._state.pendingSyncedTransactions.length > 0) {\n mutation.collection._state.commitPendingTransactions()\n }\n\n hasCalled.add(mutation.collection.id)\n }\n }\n }\n\n /**\n * Commit the transaction and execute the mutation function\n * @returns Promise that resolves to this transaction when complete\n * @example\n * // Manual commit (when autoCommit is false)\n * const tx = createTransaction({\n * autoCommit: false,\n * mutationFn: async ({ transaction }) => {\n * await api.saveChanges(transaction.mutations)\n * }\n * })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Buy milk\" })\n * })\n *\n * await tx.commit() // Manually commit\n *\n * @example\n * // Handle commit errors\n * try {\n * const tx = createTransaction({\n * mutationFn: async () => { throw new Error(\"API failed\") }\n * })\n *\n * tx.mutate(() => {\n * collection.insert({ id: \"1\", text: \"Item\" })\n * })\n *\n * await tx.commit()\n * } catch (error) {\n * console.log('Commit failed, transaction rolled back:', error)\n * }\n *\n * @example\n * // Check transaction state after commit\n * await tx.commit()\n * console.log(tx.state) // \"completed\" or \"failed\"\n */\n async commit(): Promise<Transaction<T>> {\n if (this.state !== `pending`) {\n throw new TransactionNotPendingCommitError()\n }\n\n this.setState(`persisting`)\n\n if (this.mutations.length === 0) {\n this.setState(`completed`)\n this.isPersisted.resolve(this)\n\n return this\n }\n\n // Run mutationFn\n try {\n // At this point we know there's at least one mutation\n // We've already verified mutations is non-empty, so this cast is safe\n // Use a direct type assertion instead of object spreading to preserve the original type\n await this.mutationFn({\n transaction: this as unknown as TransactionWithMutations<T>,\n })\n\n this.setState(`completed`)\n this.touchCollection()\n\n this.isPersisted.resolve(this)\n } catch (error) {\n // Preserve the original error for rethrowing\n const originalError =\n error instanceof Error ? error : new Error(String(error))\n\n // Update transaction with error information\n this.error = {\n message: originalError.message,\n error: originalError,\n }\n\n // rollback the transaction\n this.rollback()\n\n // Re-throw the original error to preserve identity and stack\n throw originalError\n }\n\n return this\n }\n\n /**\n * Compare two transactions by their createdAt time and sequence number in order\n * to sort them in the order they were created.\n * @param other - The other transaction to compare to\n * @returns -1 if this transaction was created before the other, 1 if it was created after, 0 if they were created at the same time\n */\n compareCreatedAt(other: Transaction<any>): number {\n const createdAtComparison =\n this.createdAt.getTime() - other.createdAt.getTime()\n if (createdAtComparison !== 0) {\n return createdAtComparison\n }\n return this.sequenceNumber - other.sequenceNumber\n }\n}\n\nexport type { Transaction }\n"],"names":[],"mappings":";;;AAiBA,MAAM,eAAwC,CAAA;AAC9C,IAAI,mBAA4C,CAAA;AAEhD,IAAI,iBAAiB;AAoBrB,SAAS,sBACP,UACA,UAC2B;AAE3B,UAAQ,GAAG,SAAS,IAAI,IAAI,SAAS,IAAI,IAAA;AAAA,IACvC,KAAK,iBAAiB;AAGpB,aAAO;AAAA,QACL,GAAG;AAAA,QACH,MAAM;AAAA,QACN,UAAU,CAAA;AAAA,QACV,UAAU,SAAS;AAAA,QACnB,SAAS,EAAE,GAAG,SAAS,SAAS,GAAG,SAAS,QAAA;AAAA;AAAA,QAE5C,KAAK,SA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,YAAM;AAAA,IACR;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,iBAAiB,OAAiC;AAChD,UAAM,sBACJ,KAAK,UAAU,YAAY,MAAM,UAAU,QAAA;AAC7C,QAAI,wBAAwB,GAAG;AAC7B,aAAO;AAAA,IACT;AACA,WAAO,KAAK,iBAAiB,MAAM;AAAA,EACrC;AACF;"}
|
package/dist/esm/types.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { Collection } from './collection/index.js';
|
|
|
3
3
|
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
4
4
|
import { Transaction } from './transactions.js';
|
|
5
5
|
import { BasicExpression, OrderBy } from './query/ir.js';
|
|
6
|
+
import { EventEmitter } from './event-emitter.js';
|
|
6
7
|
/**
|
|
7
8
|
* Helper type to extract the output type from a standard schema
|
|
8
9
|
*
|
|
@@ -92,15 +93,74 @@ type Value<TExtensions = never> = string | number | boolean | bigint | null | TE
|
|
|
92
93
|
};
|
|
93
94
|
export type Row<TExtensions = never> = Record<string, Value<TExtensions>>;
|
|
94
95
|
export type OperationType = `insert` | `update` | `delete`;
|
|
95
|
-
|
|
96
|
+
/**
|
|
97
|
+
* Subscription status values
|
|
98
|
+
*/
|
|
99
|
+
export type SubscriptionStatus = `ready` | `loadingSubset`;
|
|
100
|
+
/**
|
|
101
|
+
* Event emitted when subscription status changes
|
|
102
|
+
*/
|
|
103
|
+
export interface SubscriptionStatusChangeEvent {
|
|
104
|
+
type: `status:change`;
|
|
105
|
+
subscription: Subscription;
|
|
106
|
+
previousStatus: SubscriptionStatus;
|
|
107
|
+
status: SubscriptionStatus;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Event emitted when subscription status changes to a specific status
|
|
111
|
+
*/
|
|
112
|
+
export interface SubscriptionStatusEvent<T extends SubscriptionStatus> {
|
|
113
|
+
type: `status:${T}`;
|
|
114
|
+
subscription: Subscription;
|
|
115
|
+
previousStatus: SubscriptionStatus;
|
|
116
|
+
status: T;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Event emitted when subscription is unsubscribed
|
|
120
|
+
*/
|
|
121
|
+
export interface SubscriptionUnsubscribedEvent {
|
|
122
|
+
type: `unsubscribed`;
|
|
123
|
+
subscription: Subscription;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* All subscription events
|
|
127
|
+
*/
|
|
128
|
+
export type SubscriptionEvents = {
|
|
129
|
+
"status:change": SubscriptionStatusChangeEvent;
|
|
130
|
+
"status:ready": SubscriptionStatusEvent<`ready`>;
|
|
131
|
+
"status:loadingSubset": SubscriptionStatusEvent<`loadingSubset`>;
|
|
132
|
+
unsubscribed: SubscriptionUnsubscribedEvent;
|
|
133
|
+
};
|
|
134
|
+
/**
|
|
135
|
+
* Public interface for a collection subscription
|
|
136
|
+
* Used by sync implementations to track subscription lifecycle
|
|
137
|
+
*/
|
|
138
|
+
export interface Subscription extends EventEmitter<SubscriptionEvents> {
|
|
139
|
+
/** Current status of the subscription */
|
|
140
|
+
readonly status: SubscriptionStatus;
|
|
141
|
+
}
|
|
142
|
+
export type LoadSubsetOptions = {
|
|
143
|
+
/** The where expression to filter the data */
|
|
96
144
|
where?: BasicExpression<boolean>;
|
|
145
|
+
/** The order by clause to sort the data */
|
|
97
146
|
orderBy?: OrderBy;
|
|
147
|
+
/** The limit of the data to load */
|
|
98
148
|
limit?: number;
|
|
149
|
+
/**
|
|
150
|
+
* The subscription that triggered the load.
|
|
151
|
+
* Advanced sync implementations can use this for:
|
|
152
|
+
* - LRU caching keyed by subscription
|
|
153
|
+
* - Reference counting to track active subscriptions
|
|
154
|
+
* - Subscribing to subscription events (e.g., finalization/unsubscribe)
|
|
155
|
+
* @optional Available when called from CollectionSubscription, may be undefined for direct calls
|
|
156
|
+
*/
|
|
157
|
+
subscription?: Subscription;
|
|
99
158
|
};
|
|
159
|
+
export type LoadSubsetFn = (options: LoadSubsetOptions) => true | Promise<void>;
|
|
100
160
|
export type CleanupFn = () => void;
|
|
101
161
|
export type SyncConfigRes = {
|
|
102
162
|
cleanup?: CleanupFn;
|
|
103
|
-
|
|
163
|
+
loadSubset?: LoadSubsetFn;
|
|
104
164
|
};
|
|
105
165
|
export interface SyncConfig<T extends object = Record<string, unknown>, TKey extends string | number = string | number> {
|
|
106
166
|
sync: (params: {
|
|
@@ -161,21 +221,21 @@ export interface InsertConfig {
|
|
|
161
221
|
/** Whether to apply optimistic updates immediately. Defaults to true. */
|
|
162
222
|
optimistic?: boolean;
|
|
163
223
|
}
|
|
164
|
-
export type UpdateMutationFnParams<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord =
|
|
224
|
+
export type UpdateMutationFnParams<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord = UtilsRecord> = {
|
|
165
225
|
transaction: TransactionWithMutations<T, `update`>;
|
|
166
226
|
collection: Collection<T, TKey, TUtils>;
|
|
167
227
|
};
|
|
168
|
-
export type InsertMutationFnParams<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord =
|
|
228
|
+
export type InsertMutationFnParams<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord = UtilsRecord> = {
|
|
169
229
|
transaction: TransactionWithMutations<T, `insert`>;
|
|
170
230
|
collection: Collection<T, TKey, TUtils>;
|
|
171
231
|
};
|
|
172
|
-
export type DeleteMutationFnParams<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord =
|
|
232
|
+
export type DeleteMutationFnParams<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord = UtilsRecord> = {
|
|
173
233
|
transaction: TransactionWithMutations<T, `delete`>;
|
|
174
234
|
collection: Collection<T, TKey, TUtils>;
|
|
175
235
|
};
|
|
176
|
-
export type InsertMutationFn<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord =
|
|
177
|
-
export type UpdateMutationFn<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord =
|
|
178
|
-
export type DeleteMutationFn<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord =
|
|
236
|
+
export type InsertMutationFn<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord = UtilsRecord, TReturn = any> = (params: InsertMutationFnParams<T, TKey, TUtils>) => Promise<TReturn>;
|
|
237
|
+
export type UpdateMutationFn<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord = UtilsRecord, TReturn = any> = (params: UpdateMutationFnParams<T, TKey, TUtils>) => Promise<TReturn>;
|
|
238
|
+
export type DeleteMutationFn<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord = UtilsRecord, TReturn = any> = (params: DeleteMutationFnParams<T, TKey, TUtils>) => Promise<TReturn>;
|
|
179
239
|
/**
|
|
180
240
|
* Collection status values for lifecycle management
|
|
181
241
|
* @example
|
|
@@ -202,7 +262,8 @@ export type CollectionStatus =
|
|
|
202
262
|
| `error`
|
|
203
263
|
/** Collection has been cleaned up and resources freed */
|
|
204
264
|
| `cleaned-up`;
|
|
205
|
-
export
|
|
265
|
+
export type SyncMode = `eager` | `on-demand`;
|
|
266
|
+
export interface BaseCollectionConfig<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TSchema extends StandardSchemaV1 = never, TUtils extends UtilsRecord = UtilsRecord, TReturn = any> {
|
|
206
267
|
id?: string;
|
|
207
268
|
schema?: TSchema;
|
|
208
269
|
/**
|
|
@@ -251,6 +312,15 @@ export interface BaseCollectionConfig<T extends object = Record<string, unknown>
|
|
|
251
312
|
* compare: (x, y) => x.createdAt.getTime() - y.createdAt.getTime()
|
|
252
313
|
*/
|
|
253
314
|
compare?: (x: T, y: T) => number;
|
|
315
|
+
/**
|
|
316
|
+
* The mode of sync to use for the collection.
|
|
317
|
+
* @default `eager`
|
|
318
|
+
* @description
|
|
319
|
+
* - `eager`: syncs all data immediately on preload
|
|
320
|
+
* - `on-demand`: syncs data in incremental snapshots when the collection is queried
|
|
321
|
+
* The exact implementation of the sync mode is up to the sync implementation.
|
|
322
|
+
*/
|
|
323
|
+
syncMode?: SyncMode;
|
|
254
324
|
/**
|
|
255
325
|
* Optional asynchronous handler function called before an insert operation
|
|
256
326
|
* @param params Object containing transaction and collection information
|
|
@@ -379,8 +449,9 @@ export interface BaseCollectionConfig<T extends object = Record<string, unknown>
|
|
|
379
449
|
* }
|
|
380
450
|
*/
|
|
381
451
|
onDelete?: DeleteMutationFn<T, TKey, TUtils, TReturn>;
|
|
452
|
+
utils?: TUtils;
|
|
382
453
|
}
|
|
383
|
-
export interface CollectionConfig<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TSchema extends StandardSchemaV1 = never> extends BaseCollectionConfig<T, TKey, TSchema> {
|
|
454
|
+
export interface CollectionConfig<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TSchema extends StandardSchemaV1 = never, TUtils extends UtilsRecord = UtilsRecord> extends BaseCollectionConfig<T, TKey, TSchema, TUtils> {
|
|
384
455
|
sync: SyncConfig<T, TKey>;
|
|
385
456
|
}
|
|
386
457
|
export type SingleResult = {
|
|
@@ -395,7 +466,7 @@ export type MaybeSingleResult = {
|
|
|
395
466
|
*/
|
|
396
467
|
singleResult?: true;
|
|
397
468
|
};
|
|
398
|
-
export type CollectionConfigSingleRowOption<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TSchema extends StandardSchemaV1 = never> = CollectionConfig<T, TKey, TSchema> & MaybeSingleResult;
|
|
469
|
+
export type CollectionConfigSingleRowOption<T extends object = Record<string, unknown>, TKey extends string | number = string | number, TSchema extends StandardSchemaV1 = never, TUtils extends UtilsRecord = {}> = CollectionConfig<T, TKey, TSchema, TUtils> & MaybeSingleResult;
|
|
399
470
|
export type ChangesPayload<T extends object = Record<string, unknown>> = Array<ChangeMessage<T>>;
|
|
400
471
|
/**
|
|
401
472
|
* An input row from a collection
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/db",
|
|
3
3
|
"description": "A reactive client store for building super fast apps on sync",
|
|
4
|
-
"version": "0.4.
|
|
4
|
+
"version": "0.4.10",
|
|
5
5
|
"dependencies": {
|
|
6
6
|
"@standard-schema/spec": "^1.0.0",
|
|
7
|
-
"@tanstack/db-ivm": "0.1.
|
|
7
|
+
"@tanstack/db-ivm": "0.1.11"
|
|
8
8
|
},
|
|
9
9
|
"devDependencies": {
|
|
10
10
|
"@vitest/coverage-istanbul": "^3.2.4",
|
package/src/collection/events.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { EventEmitter } from "../event-emitter.js"
|
|
1
2
|
import type { Collection } from "./index.js"
|
|
2
3
|
import type { CollectionStatus } from "../types.js"
|
|
3
4
|
|
|
@@ -31,9 +32,21 @@ export interface CollectionSubscribersChangeEvent {
|
|
|
31
32
|
subscriberCount: number
|
|
32
33
|
}
|
|
33
34
|
|
|
35
|
+
/**
|
|
36
|
+
* Event emitted when the collection's loading more state changes
|
|
37
|
+
*/
|
|
38
|
+
export interface CollectionLoadingSubsetChangeEvent {
|
|
39
|
+
type: `loadingSubset:change`
|
|
40
|
+
collection: Collection<any, any, any, any, any>
|
|
41
|
+
isLoadingSubset: boolean
|
|
42
|
+
previousIsLoadingSubset: boolean
|
|
43
|
+
loadingSubsetTransition: `start` | `end`
|
|
44
|
+
}
|
|
45
|
+
|
|
34
46
|
export type AllCollectionEvents = {
|
|
35
47
|
"status:change": CollectionStatusChangeEvent
|
|
36
48
|
"subscribers:change": CollectionSubscribersChangeEvent
|
|
49
|
+
"loadingSubset:change": CollectionLoadingSubsetChangeEvent
|
|
37
50
|
} & {
|
|
38
51
|
[K in CollectionStatus as `status:${K}`]: CollectionStatusEvent<K>
|
|
39
52
|
}
|
|
@@ -42,94 +55,32 @@ export type CollectionEvent =
|
|
|
42
55
|
| AllCollectionEvents[keyof AllCollectionEvents]
|
|
43
56
|
| CollectionStatusChangeEvent
|
|
44
57
|
| CollectionSubscribersChangeEvent
|
|
58
|
+
| CollectionLoadingSubsetChangeEvent
|
|
45
59
|
|
|
46
60
|
export type CollectionEventHandler<T extends keyof AllCollectionEvents> = (
|
|
47
61
|
event: AllCollectionEvents[T]
|
|
48
62
|
) => void
|
|
49
63
|
|
|
50
|
-
export class CollectionEventsManager {
|
|
64
|
+
export class CollectionEventsManager extends EventEmitter<AllCollectionEvents> {
|
|
51
65
|
private collection!: Collection<any, any, any, any, any>
|
|
52
|
-
private listeners = new Map<
|
|
53
|
-
keyof AllCollectionEvents,
|
|
54
|
-
Set<CollectionEventHandler<any>>
|
|
55
|
-
>()
|
|
56
66
|
|
|
57
|
-
constructor() {
|
|
67
|
+
constructor() {
|
|
68
|
+
super()
|
|
69
|
+
}
|
|
58
70
|
|
|
59
71
|
setDeps(deps: { collection: Collection<any, any, any, any, any> }) {
|
|
60
72
|
this.collection = deps.collection
|
|
61
73
|
}
|
|
62
74
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
if (!this.listeners.has(event)) {
|
|
68
|
-
this.listeners.set(event, new Set())
|
|
69
|
-
}
|
|
70
|
-
this.listeners.get(event)!.add(callback)
|
|
71
|
-
|
|
72
|
-
return () => {
|
|
73
|
-
this.listeners.get(event)?.delete(callback)
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
once<T extends keyof AllCollectionEvents>(
|
|
78
|
-
event: T,
|
|
79
|
-
callback: CollectionEventHandler<T>
|
|
80
|
-
) {
|
|
81
|
-
const unsubscribe = this.on(event, (eventPayload) => {
|
|
82
|
-
callback(eventPayload)
|
|
83
|
-
unsubscribe()
|
|
84
|
-
})
|
|
85
|
-
return unsubscribe
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
off<T extends keyof AllCollectionEvents>(
|
|
89
|
-
event: T,
|
|
90
|
-
callback: CollectionEventHandler<T>
|
|
91
|
-
) {
|
|
92
|
-
this.listeners.get(event)?.delete(callback)
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
waitFor<T extends keyof AllCollectionEvents>(
|
|
96
|
-
event: T,
|
|
97
|
-
timeout?: number
|
|
98
|
-
): Promise<AllCollectionEvents[T]> {
|
|
99
|
-
return new Promise((resolve, reject) => {
|
|
100
|
-
let timeoutId: NodeJS.Timeout | undefined
|
|
101
|
-
const unsubscribe = this.on(event, (eventPayload) => {
|
|
102
|
-
if (timeoutId) {
|
|
103
|
-
clearTimeout(timeoutId)
|
|
104
|
-
timeoutId = undefined
|
|
105
|
-
}
|
|
106
|
-
resolve(eventPayload)
|
|
107
|
-
unsubscribe()
|
|
108
|
-
})
|
|
109
|
-
if (timeout) {
|
|
110
|
-
timeoutId = setTimeout(() => {
|
|
111
|
-
timeoutId = undefined
|
|
112
|
-
unsubscribe()
|
|
113
|
-
reject(new Error(`Timeout waiting for event ${event}`))
|
|
114
|
-
}, timeout)
|
|
115
|
-
}
|
|
116
|
-
})
|
|
117
|
-
}
|
|
118
|
-
|
|
75
|
+
/**
|
|
76
|
+
* Emit an event to all listeners
|
|
77
|
+
* Public API for emitting collection events
|
|
78
|
+
*/
|
|
119
79
|
emit<T extends keyof AllCollectionEvents>(
|
|
120
80
|
event: T,
|
|
121
81
|
eventPayload: AllCollectionEvents[T]
|
|
122
|
-
) {
|
|
123
|
-
this.
|
|
124
|
-
try {
|
|
125
|
-
listener(eventPayload)
|
|
126
|
-
} catch (error) {
|
|
127
|
-
// Re-throw in a microtask to surface the error
|
|
128
|
-
queueMicrotask(() => {
|
|
129
|
-
throw error
|
|
130
|
-
})
|
|
131
|
-
}
|
|
132
|
-
})
|
|
82
|
+
): void {
|
|
83
|
+
this.emitInner(event, eventPayload)
|
|
133
84
|
}
|
|
134
85
|
|
|
135
86
|
emitStatusChange<T extends CollectionStatus>(
|
|
@@ -166,6 +117,6 @@ export class CollectionEventsManager {
|
|
|
166
117
|
}
|
|
167
118
|
|
|
168
119
|
cleanup() {
|
|
169
|
-
this.
|
|
120
|
+
this.clearListeners()
|
|
170
121
|
}
|
|
171
122
|
}
|
package/src/collection/index.ts
CHANGED
|
@@ -25,7 +25,6 @@ import type {
|
|
|
25
25
|
InferSchemaOutput,
|
|
26
26
|
InsertConfig,
|
|
27
27
|
NonSingleResult,
|
|
28
|
-
OnLoadMoreOptions,
|
|
29
28
|
OperationConfig,
|
|
30
29
|
SingleResult,
|
|
31
30
|
SubscribeChangesOptions,
|
|
@@ -48,7 +47,7 @@ import type { IndexProxy } from "../indexes/lazy-index.js"
|
|
|
48
47
|
export interface Collection<
|
|
49
48
|
T extends object = Record<string, unknown>,
|
|
50
49
|
TKey extends string | number = string | number,
|
|
51
|
-
TUtils extends UtilsRecord =
|
|
50
|
+
TUtils extends UtilsRecord = UtilsRecord,
|
|
52
51
|
TSchema extends StandardSchemaV1 = StandardSchemaV1,
|
|
53
52
|
TInsertInput extends object = T,
|
|
54
53
|
> extends CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput> {
|
|
@@ -131,7 +130,7 @@ export interface Collection<
|
|
|
131
130
|
export function createCollection<
|
|
132
131
|
T extends StandardSchemaV1,
|
|
133
132
|
TKey extends string | number = string | number,
|
|
134
|
-
TUtils extends UtilsRecord =
|
|
133
|
+
TUtils extends UtilsRecord = UtilsRecord,
|
|
135
134
|
>(
|
|
136
135
|
options: CollectionConfig<InferSchemaOutput<T>, TKey, T> & {
|
|
137
136
|
schema: T
|
|
@@ -144,7 +143,7 @@ export function createCollection<
|
|
|
144
143
|
export function createCollection<
|
|
145
144
|
T extends StandardSchemaV1,
|
|
146
145
|
TKey extends string | number = string | number,
|
|
147
|
-
TUtils extends UtilsRecord =
|
|
146
|
+
TUtils extends UtilsRecord = UtilsRecord,
|
|
148
147
|
>(
|
|
149
148
|
options: CollectionConfig<InferSchemaOutput<T>, TKey, T> & {
|
|
150
149
|
schema: T
|
|
@@ -158,7 +157,7 @@ export function createCollection<
|
|
|
158
157
|
export function createCollection<
|
|
159
158
|
T extends object,
|
|
160
159
|
TKey extends string | number = string | number,
|
|
161
|
-
TUtils extends UtilsRecord =
|
|
160
|
+
TUtils extends UtilsRecord = UtilsRecord,
|
|
162
161
|
>(
|
|
163
162
|
options: CollectionConfig<T, TKey, never> & {
|
|
164
163
|
schema?: never // prohibit schema if an explicit type is provided
|
|
@@ -171,7 +170,7 @@ export function createCollection<
|
|
|
171
170
|
export function createCollection<
|
|
172
171
|
T extends object,
|
|
173
172
|
TKey extends string | number = string | number,
|
|
174
|
-
TUtils extends UtilsRecord =
|
|
173
|
+
TUtils extends UtilsRecord = UtilsRecord,
|
|
175
174
|
>(
|
|
176
175
|
options: CollectionConfig<T, TKey, never> & {
|
|
177
176
|
schema?: never // prohibit schema if an explicit type is provided
|
|
@@ -218,7 +217,7 @@ export class CollectionImpl<
|
|
|
218
217
|
private _events: CollectionEventsManager
|
|
219
218
|
private _changes: CollectionChangesManager<TOutput, TKey, TSchema, TInput>
|
|
220
219
|
public _lifecycle: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput>
|
|
221
|
-
|
|
220
|
+
public _sync: CollectionSyncManager<TOutput, TKey, TSchema, TInput>
|
|
222
221
|
private _indexes: CollectionIndexesManager<TOutput, TKey, TSchema, TInput>
|
|
223
222
|
private _mutations: CollectionMutationsManager<
|
|
224
223
|
TOutput,
|
|
@@ -303,6 +302,7 @@ export class CollectionImpl<
|
|
|
303
302
|
collection: this, // Required for passing to config.sync callback
|
|
304
303
|
state: this._state,
|
|
305
304
|
lifecycle: this._lifecycle,
|
|
305
|
+
events: this._events,
|
|
306
306
|
})
|
|
307
307
|
|
|
308
308
|
// Only start sync immediately if explicitly enabled
|
|
@@ -356,23 +356,19 @@ export class CollectionImpl<
|
|
|
356
356
|
}
|
|
357
357
|
|
|
358
358
|
/**
|
|
359
|
-
*
|
|
360
|
-
*
|
|
359
|
+
* Check if the collection is currently loading more data
|
|
360
|
+
* @returns true if the collection has pending load more operations, false otherwise
|
|
361
361
|
*/
|
|
362
|
-
public
|
|
363
|
-
this._sync.
|
|
362
|
+
public get isLoadingSubset(): boolean {
|
|
363
|
+
return this._sync.isLoadingSubset
|
|
364
364
|
}
|
|
365
365
|
|
|
366
366
|
/**
|
|
367
|
-
*
|
|
368
|
-
*
|
|
369
|
-
* @returns If data loading is asynchronous, this method returns a promise that resolves when the data is loaded.
|
|
370
|
-
* If data loading is synchronous, the data is loaded when the method returns.
|
|
367
|
+
* Start sync immediately - internal method for compiled queries
|
|
368
|
+
* This bypasses lazy loading for special cases like live query results
|
|
371
369
|
*/
|
|
372
|
-
public
|
|
373
|
-
|
|
374
|
-
return this._sync.syncOnLoadMoreFn(options)
|
|
375
|
-
}
|
|
370
|
+
public startSyncImmediate(): void {
|
|
371
|
+
this._sync.startSync()
|
|
376
372
|
}
|
|
377
373
|
|
|
378
374
|
/**
|