@tanstack/db 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/dist/cjs/{change-events.cjs → collection/change-events.cjs} +13 -42
  2. package/dist/cjs/collection/change-events.cjs.map +1 -0
  3. package/dist/{esm/change-events.d.ts → cjs/collection/change-events.d.cts} +6 -6
  4. package/dist/cjs/collection/changes.cjs +108 -0
  5. package/dist/cjs/collection/changes.cjs.map +1 -0
  6. package/dist/cjs/collection/changes.d.cts +53 -0
  7. package/dist/cjs/collection/events.cjs +90 -0
  8. package/dist/cjs/collection/events.cjs.map +1 -0
  9. package/dist/cjs/collection/events.d.cts +53 -0
  10. package/dist/cjs/collection/index.cjs +417 -0
  11. package/dist/cjs/collection/index.cjs.map +1 -0
  12. package/dist/{esm/collection.d.ts → cjs/collection/index.d.cts} +56 -172
  13. package/dist/cjs/collection/indexes.cjs +124 -0
  14. package/dist/cjs/collection/indexes.cjs.map +1 -0
  15. package/dist/cjs/collection/indexes.d.cts +47 -0
  16. package/dist/cjs/collection/lifecycle.cjs +150 -0
  17. package/dist/cjs/collection/lifecycle.cjs.map +1 -0
  18. package/dist/cjs/collection/lifecycle.d.cts +70 -0
  19. package/dist/cjs/collection/mutations.cjs +315 -0
  20. package/dist/cjs/collection/mutations.cjs.map +1 -0
  21. package/dist/cjs/collection/mutations.d.cts +33 -0
  22. package/dist/cjs/collection/state.cjs +597 -0
  23. package/dist/cjs/collection/state.cjs.map +1 -0
  24. package/dist/cjs/collection/state.d.cts +122 -0
  25. package/dist/cjs/collection/subscription.cjs +160 -0
  26. package/dist/cjs/collection/subscription.cjs.map +1 -0
  27. package/dist/cjs/collection/subscription.d.cts +57 -0
  28. package/dist/cjs/collection/sync.cjs +154 -0
  29. package/dist/cjs/collection/sync.cjs.map +1 -0
  30. package/dist/cjs/collection/sync.d.cts +34 -0
  31. package/dist/cjs/index.cjs +8 -8
  32. package/dist/cjs/index.d.cts +2 -2
  33. package/dist/cjs/indexes/auto-index.cjs.map +1 -1
  34. package/dist/cjs/indexes/auto-index.d.cts +1 -1
  35. package/dist/cjs/indexes/base-index.cjs.map +1 -1
  36. package/dist/cjs/indexes/base-index.d.cts +2 -2
  37. package/dist/cjs/indexes/btree-index.cjs +2 -2
  38. package/dist/cjs/indexes/btree-index.cjs.map +1 -1
  39. package/dist/cjs/indexes/btree-index.d.cts +1 -1
  40. package/dist/cjs/query/builder/index.cjs +2 -2
  41. package/dist/cjs/query/builder/index.cjs.map +1 -1
  42. package/dist/cjs/query/builder/types.d.cts +1 -1
  43. package/dist/cjs/query/compiler/index.cjs +5 -2
  44. package/dist/cjs/query/compiler/index.cjs.map +1 -1
  45. package/dist/cjs/query/compiler/index.d.cts +3 -2
  46. package/dist/cjs/query/compiler/joins.cjs +22 -24
  47. package/dist/cjs/query/compiler/joins.cjs.map +1 -1
  48. package/dist/cjs/query/compiler/joins.d.cts +3 -2
  49. package/dist/cjs/query/compiler/order-by.cjs.map +1 -1
  50. package/dist/cjs/query/compiler/order-by.d.cts +1 -1
  51. package/dist/cjs/query/ir.cjs.map +1 -1
  52. package/dist/cjs/query/ir.d.cts +1 -1
  53. package/dist/cjs/query/live/collection-config-builder.cjs +29 -12
  54. package/dist/cjs/query/live/collection-config-builder.cjs.map +1 -1
  55. package/dist/cjs/query/live/collection-config-builder.d.cts +3 -0
  56. package/dist/cjs/query/live/collection-subscriber.cjs +43 -104
  57. package/dist/cjs/query/live/collection-subscriber.cjs.map +1 -1
  58. package/dist/cjs/query/live/collection-subscriber.d.cts +4 -7
  59. package/dist/cjs/query/live-query-collection.cjs +2 -2
  60. package/dist/cjs/query/live-query-collection.cjs.map +1 -1
  61. package/dist/cjs/query/live-query-collection.d.cts +1 -1
  62. package/dist/cjs/transactions.cjs +3 -3
  63. package/dist/cjs/transactions.cjs.map +1 -1
  64. package/dist/cjs/types.d.cts +12 -10
  65. package/dist/{cjs/change-events.d.cts → esm/collection/change-events.d.ts} +6 -6
  66. package/dist/esm/{change-events.js → collection/change-events.js} +13 -42
  67. package/dist/esm/collection/change-events.js.map +1 -0
  68. package/dist/esm/collection/changes.d.ts +53 -0
  69. package/dist/esm/collection/changes.js +108 -0
  70. package/dist/esm/collection/changes.js.map +1 -0
  71. package/dist/esm/collection/events.d.ts +53 -0
  72. package/dist/esm/collection/events.js +90 -0
  73. package/dist/esm/collection/events.js.map +1 -0
  74. package/dist/{cjs/collection.d.cts → esm/collection/index.d.ts} +56 -172
  75. package/dist/esm/collection/index.js +417 -0
  76. package/dist/esm/collection/index.js.map +1 -0
  77. package/dist/esm/collection/indexes.d.ts +47 -0
  78. package/dist/esm/collection/indexes.js +124 -0
  79. package/dist/esm/collection/indexes.js.map +1 -0
  80. package/dist/esm/collection/lifecycle.d.ts +70 -0
  81. package/dist/esm/collection/lifecycle.js +150 -0
  82. package/dist/esm/collection/lifecycle.js.map +1 -0
  83. package/dist/esm/collection/mutations.d.ts +33 -0
  84. package/dist/esm/collection/mutations.js +315 -0
  85. package/dist/esm/collection/mutations.js.map +1 -0
  86. package/dist/esm/collection/state.d.ts +122 -0
  87. package/dist/esm/collection/state.js +597 -0
  88. package/dist/esm/collection/state.js.map +1 -0
  89. package/dist/esm/collection/subscription.d.ts +57 -0
  90. package/dist/esm/collection/subscription.js +160 -0
  91. package/dist/esm/collection/subscription.js.map +1 -0
  92. package/dist/esm/collection/sync.d.ts +34 -0
  93. package/dist/esm/collection/sync.js +154 -0
  94. package/dist/esm/collection/sync.js.map +1 -0
  95. package/dist/esm/index.d.ts +2 -2
  96. package/dist/esm/index.js +1 -1
  97. package/dist/esm/indexes/auto-index.d.ts +1 -1
  98. package/dist/esm/indexes/auto-index.js.map +1 -1
  99. package/dist/esm/indexes/base-index.d.ts +2 -2
  100. package/dist/esm/indexes/base-index.js.map +1 -1
  101. package/dist/esm/indexes/btree-index.d.ts +1 -1
  102. package/dist/esm/indexes/btree-index.js +2 -2
  103. package/dist/esm/indexes/btree-index.js.map +1 -1
  104. package/dist/esm/proxy.js +1 -1
  105. package/dist/esm/query/builder/index.js +1 -1
  106. package/dist/esm/query/builder/index.js.map +1 -1
  107. package/dist/esm/query/builder/types.d.ts +1 -1
  108. package/dist/esm/query/compiler/index.d.ts +3 -2
  109. package/dist/esm/query/compiler/index.js +5 -2
  110. package/dist/esm/query/compiler/index.js.map +1 -1
  111. package/dist/esm/query/compiler/joins.d.ts +3 -2
  112. package/dist/esm/query/compiler/joins.js +22 -24
  113. package/dist/esm/query/compiler/joins.js.map +1 -1
  114. package/dist/esm/query/compiler/order-by.d.ts +1 -1
  115. package/dist/esm/query/compiler/order-by.js.map +1 -1
  116. package/dist/esm/query/ir.d.ts +1 -1
  117. package/dist/esm/query/ir.js.map +1 -1
  118. package/dist/esm/query/live/collection-config-builder.d.ts +3 -0
  119. package/dist/esm/query/live/collection-config-builder.js +29 -12
  120. package/dist/esm/query/live/collection-config-builder.js.map +1 -1
  121. package/dist/esm/query/live/collection-subscriber.d.ts +4 -7
  122. package/dist/esm/query/live/collection-subscriber.js +43 -104
  123. package/dist/esm/query/live/collection-subscriber.js.map +1 -1
  124. package/dist/esm/query/live-query-collection.d.ts +1 -1
  125. package/dist/esm/query/live-query-collection.js +1 -1
  126. package/dist/esm/query/live-query-collection.js.map +1 -1
  127. package/dist/esm/transactions.js +3 -3
  128. package/dist/esm/transactions.js.map +1 -1
  129. package/dist/esm/types.d.ts +12 -10
  130. package/package.json +2 -2
  131. package/src/{change-events.ts → collection/change-events.ts} +25 -39
  132. package/src/collection/changes.ts +163 -0
  133. package/src/collection/events.ts +171 -0
  134. package/src/collection/index.ts +808 -0
  135. package/src/collection/indexes.ts +172 -0
  136. package/src/collection/lifecycle.ts +221 -0
  137. package/src/collection/mutations.ts +535 -0
  138. package/src/collection/state.ts +866 -0
  139. package/src/collection/subscription.ts +239 -0
  140. package/src/collection/sync.ts +235 -0
  141. package/src/index.ts +2 -2
  142. package/src/indexes/auto-index.ts +1 -1
  143. package/src/indexes/base-index.ts +3 -3
  144. package/src/indexes/btree-index.ts +2 -2
  145. package/src/query/builder/index.ts +1 -1
  146. package/src/query/builder/types.ts +1 -1
  147. package/src/query/compiler/index.ts +7 -1
  148. package/src/query/compiler/joins.ts +28 -41
  149. package/src/query/compiler/order-by.ts +1 -1
  150. package/src/query/ir.ts +1 -1
  151. package/src/query/live/collection-config-builder.ts +48 -22
  152. package/src/query/live/collection-subscriber.ts +63 -168
  153. package/src/query/live-query-collection.ts +2 -2
  154. package/src/transactions.ts +3 -3
  155. package/src/types.ts +14 -15
  156. package/dist/cjs/change-events.cjs.map +0 -1
  157. package/dist/cjs/collection.cjs +0 -1580
  158. package/dist/cjs/collection.cjs.map +0 -1
  159. package/dist/esm/change-events.js.map +0 -1
  160. package/dist/esm/collection.js +0 -1580
  161. package/dist/esm/collection.js.map +0 -1
  162. package/src/collection.ts +0 -2488
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle.cjs","sources":["../../../src/collection/lifecycle.ts"],"sourcesContent":["import {\n CollectionInErrorStateError,\n InvalidCollectionStatusTransitionError,\n} from \"../errors\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\nimport type { CollectionConfig, CollectionStatus } from \"../types\"\nimport type { CollectionEventsManager } from \"./events\"\nimport type { CollectionIndexesManager } from \"./indexes\"\nimport type { CollectionChangesManager } from \"./changes\"\nimport type { CollectionSyncManager } from \"./sync\"\nimport type { CollectionStateManager } from \"./state\"\n\nexport class CollectionLifecycleManager<\n TOutput extends object = Record<string, unknown>,\n TKey extends string | number = string | number,\n TSchema extends StandardSchemaV1 = StandardSchemaV1,\n TInput extends object = TOutput,\n> {\n private config: CollectionConfig<TOutput, TKey, TSchema>\n private id: string\n private indexes!: CollectionIndexesManager<TOutput, TKey, TSchema, TInput>\n private events!: CollectionEventsManager\n private changes!: CollectionChangesManager<TOutput, TKey, TSchema, TInput>\n private sync!: CollectionSyncManager<TOutput, TKey, TSchema, TInput>\n private state!: CollectionStateManager<TOutput, TKey, TSchema, TInput>\n\n public status: CollectionStatus = `idle`\n public hasBeenReady = false\n public hasReceivedFirstCommit = false\n public onFirstReadyCallbacks: Array<() => void> = []\n public gcTimeoutId: ReturnType<typeof setTimeout> | null = null\n\n /**\n * Creates a new CollectionLifecycleManager instance\n */\n constructor(config: CollectionConfig<TOutput, TKey, TSchema>, id: string) {\n this.config = config\n this.id = id\n }\n\n setDeps(deps: {\n indexes: CollectionIndexesManager<TOutput, TKey, TSchema, TInput>\n events: CollectionEventsManager\n changes: CollectionChangesManager<TOutput, TKey, TSchema, TInput>\n sync: CollectionSyncManager<TOutput, TKey, TSchema, TInput>\n state: CollectionStateManager<TOutput, TKey, TSchema, TInput>\n }) {\n this.indexes = deps.indexes\n this.events = deps.events\n this.changes = deps.changes\n this.sync = deps.sync\n this.state = deps.state\n }\n\n /**\n * Validates state transitions to prevent invalid status changes\n */\n public validateStatusTransition(\n from: CollectionStatus,\n to: CollectionStatus\n ): void {\n if (from === to) {\n // Allow same state transitions\n return\n }\n const validTransitions: Record<\n CollectionStatus,\n Array<CollectionStatus>\n > = {\n idle: [`loading`, `error`, `cleaned-up`],\n loading: [`initialCommit`, `ready`, `error`, `cleaned-up`],\n initialCommit: [`ready`, `error`, `cleaned-up`],\n ready: [`cleaned-up`, `error`],\n error: [`cleaned-up`, `idle`],\n \"cleaned-up\": [`loading`, `error`],\n }\n\n if (!validTransitions[from].includes(to)) {\n throw new InvalidCollectionStatusTransitionError(from, to, this.id)\n }\n }\n\n /**\n * Safely update the collection status with validation\n * @private\n */\n public setStatus(newStatus: CollectionStatus): void {\n this.validateStatusTransition(this.status, newStatus)\n const previousStatus = this.status\n this.status = newStatus\n\n // Resolve indexes when collection becomes ready\n if (newStatus === `ready` && !this.indexes.isIndexesResolved) {\n // Resolve indexes asynchronously without blocking\n this.indexes.resolveAllIndexes().catch((error) => {\n console.warn(`Failed to resolve indexes:`, error)\n })\n }\n\n // Emit event\n this.events.emitStatusChange(newStatus, previousStatus)\n }\n\n /**\n * Validates that the collection is in a usable state for data operations\n * @private\n */\n public validateCollectionUsable(operation: string): void {\n switch (this.status) {\n case `error`:\n throw new CollectionInErrorStateError(operation, this.id)\n case `cleaned-up`:\n // Automatically restart the collection when operations are called on cleaned-up collections\n this.sync.startSync()\n break\n }\n }\n\n /**\n * Mark the collection as ready for use\n * This is called by sync implementations to explicitly signal that the collection is ready,\n * providing a more intuitive alternative to using commits for readiness signaling\n * @private - Should only be called by sync implementations\n */\n public markReady(): void {\n // Can transition to ready from loading or initialCommit states\n if (this.status === `loading` || this.status === `initialCommit`) {\n this.setStatus(`ready`)\n\n // Call any registered first ready callbacks (only on first time becoming ready)\n if (!this.hasBeenReady) {\n this.hasBeenReady = true\n\n // Also mark as having received first commit for backwards compatibility\n if (!this.hasReceivedFirstCommit) {\n this.hasReceivedFirstCommit = true\n }\n\n const callbacks = [...this.onFirstReadyCallbacks]\n this.onFirstReadyCallbacks = []\n callbacks.forEach((callback) => callback())\n }\n }\n\n // Always notify dependents when markReady is called, after status is set\n // This ensures live queries get notified when their dependencies become ready\n if (this.changes.changeSubscriptions.size > 0) {\n this.changes.emitEmptyReadyEvent()\n }\n }\n\n /**\n * Start the garbage collection timer\n * Called when the collection becomes inactive (no subscribers)\n */\n public startGCTimer(): void {\n if (this.gcTimeoutId) {\n clearTimeout(this.gcTimeoutId)\n }\n\n const gcTime = this.config.gcTime ?? 300000 // 5 minutes default\n\n // If gcTime is 0, GC is disabled\n if (gcTime === 0) {\n return\n }\n\n this.gcTimeoutId = setTimeout(() => {\n if (this.changes.activeSubscribersCount === 0) {\n // We call the main collection cleanup, not just the one for the\n // lifecycle manager\n this.cleanup()\n }\n }, gcTime)\n }\n\n /**\n * Cancel the garbage collection timer\n * Called when the collection becomes active again\n */\n public cancelGCTimer(): void {\n if (this.gcTimeoutId) {\n clearTimeout(this.gcTimeoutId)\n this.gcTimeoutId = null\n }\n }\n\n /**\n * Register a callback to be executed when the collection first becomes ready\n * Useful for preloading collections\n * @param callback Function to call when the collection first becomes ready\n */\n public onFirstReady(callback: () => void): void {\n // If already ready, call immediately\n if (this.hasBeenReady) {\n callback()\n return\n }\n\n this.onFirstReadyCallbacks.push(callback)\n }\n\n public cleanup(): void {\n this.events.cleanup()\n this.sync.cleanup()\n this.state.cleanup()\n this.changes.cleanup()\n this.indexes.cleanup()\n\n if (this.gcTimeoutId) {\n clearTimeout(this.gcTimeoutId)\n this.gcTimeoutId = null\n }\n\n this.hasBeenReady = false\n this.onFirstReadyCallbacks = []\n\n // Set status to cleaned-up\n this.setStatus(`cleaned-up`)\n }\n}\n"],"names":["InvalidCollectionStatusTransitionError","CollectionInErrorStateError"],"mappings":";;;AAYO,MAAM,2BAKX;AAAA;AAAA;AAAA;AAAA,EAkBA,YAAY,QAAkD,IAAY;AAT1E,SAAO,SAA2B;AAClC,SAAO,eAAe;AACtB,SAAO,yBAAyB;AAChC,SAAO,wBAA2C,CAAA;AAClD,SAAO,cAAoD;AAMzD,SAAK,SAAS;AACd,SAAK,KAAK;AAAA,EACZ;AAAA,EAEA,QAAQ,MAML;AACD,SAAK,UAAU,KAAK;AACpB,SAAK,SAAS,KAAK;AACnB,SAAK,UAAU,KAAK;AACpB,SAAK,OAAO,KAAK;AACjB,SAAK,QAAQ,KAAK;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAKO,yBACL,MACA,IACM;AACN,QAAI,SAAS,IAAI;AAEf;AAAA,IACF;AACA,UAAM,mBAGF;AAAA,MACF,MAAM,CAAC,WAAW,SAAS,YAAY;AAAA,MACvC,SAAS,CAAC,iBAAiB,SAAS,SAAS,YAAY;AAAA,MACzD,eAAe,CAAC,SAAS,SAAS,YAAY;AAAA,MAC9C,OAAO,CAAC,cAAc,OAAO;AAAA,MAC7B,OAAO,CAAC,cAAc,MAAM;AAAA,MAC5B,cAAc,CAAC,WAAW,OAAO;AAAA,IAAA;AAGnC,QAAI,CAAC,iBAAiB,IAAI,EAAE,SAAS,EAAE,GAAG;AACxC,YAAM,IAAIA,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AM,SAAS,KAAK,OAAO,UAAU;AAGrC,QAAI,WAAW,GAAG;AAChB;AAAA,IACF;AAEA,SAAK,cAAc,WAAW,MAAM;AAClC,UAAI,KAAK,QAAQ,2BAA2B,GAAG;AAG7C,aAAK,QAAA;AAAA,MACP;AAAA,IACF,GAAG,MAAM;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA,EAMO,gBAAsB;AAC3B,QAAI,KAAK,aAAa;AACpB,mBAAa,KAAK,WAAW;AAC7B,WAAK,cAAc;AAAA,IACrB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,aAAa,UAA4B;AAE9C,QAAI,KAAK,cAAc;AACrB,eAAA;AACA;AAAA,IACF;AAEA,SAAK,sBAAsB,KAAK,QAAQ;AAAA,EAC1C;AAAA,EAEO,UAAgB;AACrB,SAAK,OAAO,QAAA;AACZ,SAAK,KAAK,QAAA;AACV,SAAK,MAAM,QAAA;AACX,SAAK,QAAQ,QAAA;AACb,SAAK,QAAQ,QAAA;AAEb,QAAI,KAAK,aAAa;AACpB,mBAAa,KAAK,WAAW;AAC7B,WAAK,cAAc;AAAA,IACrB;AAEA,SAAK,eAAe;AACpB,SAAK,wBAAwB,CAAA;AAG7B,SAAK,UAAU,YAAY;AAAA,EAC7B;AACF;;"}
@@ -0,0 +1,70 @@
1
+ import { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import { CollectionConfig, CollectionStatus } from '../types.cjs';
3
+ import { CollectionEventsManager } from './events.cjs';
4
+ import { CollectionIndexesManager } from './indexes.cjs';
5
+ import { CollectionChangesManager } from './changes.cjs';
6
+ import { CollectionSyncManager } from './sync.cjs';
7
+ import { CollectionStateManager } from './state.cjs';
8
+ export declare class CollectionLifecycleManager<TOutput extends object = Record<string, unknown>, TKey extends string | number = string | number, TSchema extends StandardSchemaV1 = StandardSchemaV1, TInput extends object = TOutput> {
9
+ private config;
10
+ private id;
11
+ private indexes;
12
+ private events;
13
+ private changes;
14
+ private sync;
15
+ private state;
16
+ status: CollectionStatus;
17
+ hasBeenReady: boolean;
18
+ hasReceivedFirstCommit: boolean;
19
+ onFirstReadyCallbacks: Array<() => void>;
20
+ gcTimeoutId: ReturnType<typeof setTimeout> | null;
21
+ /**
22
+ * Creates a new CollectionLifecycleManager instance
23
+ */
24
+ constructor(config: CollectionConfig<TOutput, TKey, TSchema>, id: string);
25
+ setDeps(deps: {
26
+ indexes: CollectionIndexesManager<TOutput, TKey, TSchema, TInput>;
27
+ events: CollectionEventsManager;
28
+ changes: CollectionChangesManager<TOutput, TKey, TSchema, TInput>;
29
+ sync: CollectionSyncManager<TOutput, TKey, TSchema, TInput>;
30
+ state: CollectionStateManager<TOutput, TKey, TSchema, TInput>;
31
+ }): void;
32
+ /**
33
+ * Validates state transitions to prevent invalid status changes
34
+ */
35
+ validateStatusTransition(from: CollectionStatus, to: CollectionStatus): void;
36
+ /**
37
+ * Safely update the collection status with validation
38
+ * @private
39
+ */
40
+ setStatus(newStatus: CollectionStatus): void;
41
+ /**
42
+ * Validates that the collection is in a usable state for data operations
43
+ * @private
44
+ */
45
+ validateCollectionUsable(operation: string): void;
46
+ /**
47
+ * Mark the collection as ready for use
48
+ * This is called by sync implementations to explicitly signal that the collection is ready,
49
+ * providing a more intuitive alternative to using commits for readiness signaling
50
+ * @private - Should only be called by sync implementations
51
+ */
52
+ markReady(): void;
53
+ /**
54
+ * Start the garbage collection timer
55
+ * Called when the collection becomes inactive (no subscribers)
56
+ */
57
+ startGCTimer(): void;
58
+ /**
59
+ * Cancel the garbage collection timer
60
+ * Called when the collection becomes active again
61
+ */
62
+ cancelGCTimer(): void;
63
+ /**
64
+ * Register a callback to be executed when the collection first becomes ready
65
+ * Useful for preloading collections
66
+ * @param callback Function to call when the collection first becomes ready
67
+ */
68
+ onFirstReady(callback: () => void): void;
69
+ cleanup(): void;
70
+ }
@@ -0,0 +1,315 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const proxy = require("../proxy.cjs");
4
+ const transactions = require("../transactions.cjs");
5
+ const errors = require("../errors.cjs");
6
+ class CollectionMutationsManager {
7
+ constructor(config, id) {
8
+ this.insert = (data, config2) => {
9
+ this.lifecycle.validateCollectionUsable(`insert`);
10
+ const state = this.state;
11
+ const ambientTransaction = transactions.getActiveTransaction();
12
+ if (!ambientTransaction && !this.config.onInsert) {
13
+ throw new errors.MissingInsertHandlerError();
14
+ }
15
+ const items = Array.isArray(data) ? data : [data];
16
+ const mutations = [];
17
+ items.forEach((item) => {
18
+ var _a, _b;
19
+ const validatedData = this.validateData(item, `insert`);
20
+ const key = this.config.getKey(validatedData);
21
+ if (this.state.has(key)) {
22
+ throw new errors.DuplicateKeyError(key);
23
+ }
24
+ const globalKey = this.generateGlobalKey(key, item);
25
+ const mutation = {
26
+ mutationId: crypto.randomUUID(),
27
+ original: {},
28
+ modified: validatedData,
29
+ // Pick the values from validatedData based on what's passed in - this is for cases
30
+ // where a schema has default values. The validated data has the extra default
31
+ // values but for changes, we just want to show the data that was actually passed in.
32
+ changes: Object.fromEntries(
33
+ Object.keys(item).map((k) => [
34
+ k,
35
+ validatedData[k]
36
+ ])
37
+ ),
38
+ globalKey,
39
+ key,
40
+ metadata: config2 == null ? void 0 : config2.metadata,
41
+ syncMetadata: ((_b = (_a = this.config.sync).getSyncMetadata) == null ? void 0 : _b.call(_a)) || {},
42
+ optimistic: (config2 == null ? void 0 : config2.optimistic) ?? true,
43
+ type: `insert`,
44
+ createdAt: /* @__PURE__ */ new Date(),
45
+ updatedAt: /* @__PURE__ */ new Date(),
46
+ collection: this.collection
47
+ };
48
+ mutations.push(mutation);
49
+ });
50
+ if (ambientTransaction) {
51
+ ambientTransaction.applyMutations(mutations);
52
+ state.transactions.set(ambientTransaction.id, ambientTransaction);
53
+ state.scheduleTransactionCleanup(ambientTransaction);
54
+ state.recomputeOptimisticState(true);
55
+ return ambientTransaction;
56
+ } else {
57
+ const directOpTransaction = transactions.createTransaction({
58
+ mutationFn: async (params) => {
59
+ return await this.config.onInsert({
60
+ transaction: params.transaction,
61
+ collection: this.collection
62
+ });
63
+ }
64
+ });
65
+ directOpTransaction.applyMutations(mutations);
66
+ directOpTransaction.commit();
67
+ state.transactions.set(directOpTransaction.id, directOpTransaction);
68
+ state.scheduleTransactionCleanup(directOpTransaction);
69
+ state.recomputeOptimisticState(true);
70
+ return directOpTransaction;
71
+ }
72
+ };
73
+ this.delete = (keys, config2) => {
74
+ const state = this.state;
75
+ this.lifecycle.validateCollectionUsable(`delete`);
76
+ const ambientTransaction = transactions.getActiveTransaction();
77
+ if (!ambientTransaction && !this.config.onDelete) {
78
+ throw new errors.MissingDeleteHandlerError();
79
+ }
80
+ if (Array.isArray(keys) && keys.length === 0) {
81
+ throw new errors.NoKeysPassedToDeleteError();
82
+ }
83
+ const keysArray = Array.isArray(keys) ? keys : [keys];
84
+ const mutations = [];
85
+ for (const key of keysArray) {
86
+ if (!this.state.has(key)) {
87
+ throw new errors.DeleteKeyNotFoundError(key);
88
+ }
89
+ const globalKey = this.generateGlobalKey(key, this.state.get(key));
90
+ const mutation = {
91
+ mutationId: crypto.randomUUID(),
92
+ original: this.state.get(key),
93
+ modified: this.state.get(key),
94
+ changes: this.state.get(key),
95
+ globalKey,
96
+ key,
97
+ metadata: config2 == null ? void 0 : config2.metadata,
98
+ syncMetadata: state.syncedMetadata.get(key) || {},
99
+ optimistic: (config2 == null ? void 0 : config2.optimistic) ?? true,
100
+ type: `delete`,
101
+ createdAt: /* @__PURE__ */ new Date(),
102
+ updatedAt: /* @__PURE__ */ new Date(),
103
+ collection: this.collection
104
+ };
105
+ mutations.push(mutation);
106
+ }
107
+ if (ambientTransaction) {
108
+ ambientTransaction.applyMutations(mutations);
109
+ state.transactions.set(ambientTransaction.id, ambientTransaction);
110
+ state.scheduleTransactionCleanup(ambientTransaction);
111
+ state.recomputeOptimisticState(true);
112
+ return ambientTransaction;
113
+ }
114
+ const directOpTransaction = transactions.createTransaction({
115
+ autoCommit: true,
116
+ mutationFn: async (params) => {
117
+ return this.config.onDelete({
118
+ transaction: params.transaction,
119
+ collection: this.collection
120
+ });
121
+ }
122
+ });
123
+ directOpTransaction.applyMutations(mutations);
124
+ directOpTransaction.commit();
125
+ state.transactions.set(directOpTransaction.id, directOpTransaction);
126
+ state.scheduleTransactionCleanup(directOpTransaction);
127
+ state.recomputeOptimisticState(true);
128
+ return directOpTransaction;
129
+ };
130
+ this.id = id;
131
+ this.config = config;
132
+ }
133
+ setDeps(deps) {
134
+ this.lifecycle = deps.lifecycle;
135
+ this.state = deps.state;
136
+ this.collection = deps.collection;
137
+ }
138
+ ensureStandardSchema(schema) {
139
+ if (schema && `~standard` in schema) {
140
+ return schema;
141
+ }
142
+ throw new errors.InvalidSchemaError();
143
+ }
144
+ validateData(data, type, key) {
145
+ if (!this.config.schema) return data;
146
+ const standardSchema = this.ensureStandardSchema(this.config.schema);
147
+ if (type === `update` && key) {
148
+ const existingData = this.state.get(key);
149
+ if (existingData && data && typeof data === `object` && typeof existingData === `object`) {
150
+ const mergedData = Object.assign({}, existingData, data);
151
+ const result2 = standardSchema[`~standard`].validate(mergedData);
152
+ if (result2 instanceof Promise) {
153
+ throw new errors.SchemaMustBeSynchronousError();
154
+ }
155
+ if (`issues` in result2 && result2.issues) {
156
+ const typedIssues = result2.issues.map((issue) => {
157
+ var _a;
158
+ return {
159
+ message: issue.message,
160
+ path: (_a = issue.path) == null ? void 0 : _a.map((p) => String(p))
161
+ };
162
+ });
163
+ throw new errors.SchemaValidationError(type, typedIssues);
164
+ }
165
+ const validatedMergedData = result2.value;
166
+ const modifiedKeys = Object.keys(data);
167
+ const extractedChanges = Object.fromEntries(
168
+ modifiedKeys.map((k) => [k, validatedMergedData[k]])
169
+ );
170
+ return extractedChanges;
171
+ }
172
+ }
173
+ const result = standardSchema[`~standard`].validate(data);
174
+ if (result instanceof Promise) {
175
+ throw new errors.SchemaMustBeSynchronousError();
176
+ }
177
+ if (`issues` in result && result.issues) {
178
+ const typedIssues = result.issues.map((issue) => {
179
+ var _a;
180
+ return {
181
+ message: issue.message,
182
+ path: (_a = issue.path) == null ? void 0 : _a.map((p) => String(p))
183
+ };
184
+ });
185
+ throw new errors.SchemaValidationError(type, typedIssues);
186
+ }
187
+ return result.value;
188
+ }
189
+ generateGlobalKey(key, item) {
190
+ if (typeof key === `undefined`) {
191
+ throw new errors.UndefinedKeyError(item);
192
+ }
193
+ return `KEY::${this.id}/${key}`;
194
+ }
195
+ /**
196
+ * Updates one or more items in the collection using a callback function
197
+ */
198
+ update(keys, configOrCallback, maybeCallback) {
199
+ if (typeof keys === `undefined`) {
200
+ throw new errors.MissingUpdateArgumentError();
201
+ }
202
+ const state = this.state;
203
+ this.lifecycle.validateCollectionUsable(`update`);
204
+ const ambientTransaction = transactions.getActiveTransaction();
205
+ if (!ambientTransaction && !this.config.onUpdate) {
206
+ throw new errors.MissingUpdateHandlerError();
207
+ }
208
+ const isArray = Array.isArray(keys);
209
+ const keysArray = isArray ? keys : [keys];
210
+ if (isArray && keysArray.length === 0) {
211
+ throw new errors.NoKeysPassedToUpdateError();
212
+ }
213
+ const callback = typeof configOrCallback === `function` ? configOrCallback : maybeCallback;
214
+ const config = typeof configOrCallback === `function` ? {} : configOrCallback;
215
+ const currentObjects = keysArray.map((key) => {
216
+ const item = this.state.get(key);
217
+ if (!item) {
218
+ throw new errors.UpdateKeyNotFoundError(key);
219
+ }
220
+ return item;
221
+ });
222
+ let changesArray;
223
+ if (isArray) {
224
+ changesArray = proxy.withArrayChangeTracking(
225
+ currentObjects,
226
+ callback
227
+ );
228
+ } else {
229
+ const result = proxy.withChangeTracking(
230
+ currentObjects[0],
231
+ callback
232
+ );
233
+ changesArray = [result];
234
+ }
235
+ const mutations = keysArray.map((key, index) => {
236
+ const itemChanges = changesArray[index];
237
+ if (!itemChanges || Object.keys(itemChanges).length === 0) {
238
+ return null;
239
+ }
240
+ const originalItem = currentObjects[index];
241
+ const validatedUpdatePayload = this.validateData(
242
+ itemChanges,
243
+ `update`,
244
+ key
245
+ );
246
+ const modifiedItem = Object.assign(
247
+ {},
248
+ originalItem,
249
+ validatedUpdatePayload
250
+ );
251
+ const originalItemId = this.config.getKey(originalItem);
252
+ const modifiedItemId = this.config.getKey(modifiedItem);
253
+ if (originalItemId !== modifiedItemId) {
254
+ throw new errors.KeyUpdateNotAllowedError(originalItemId, modifiedItemId);
255
+ }
256
+ const globalKey = this.generateGlobalKey(modifiedItemId, modifiedItem);
257
+ return {
258
+ mutationId: crypto.randomUUID(),
259
+ original: originalItem,
260
+ modified: modifiedItem,
261
+ // Pick the values from modifiedItem based on what's passed in - this is for cases
262
+ // where a schema has default values or transforms. The modified data has the extra
263
+ // default or transformed values but for changes, we just want to show the data that
264
+ // was actually passed in.
265
+ changes: Object.fromEntries(
266
+ Object.keys(itemChanges).map((k) => [
267
+ k,
268
+ modifiedItem[k]
269
+ ])
270
+ ),
271
+ globalKey,
272
+ key,
273
+ metadata: config.metadata,
274
+ syncMetadata: state.syncedMetadata.get(key) || {},
275
+ optimistic: config.optimistic ?? true,
276
+ type: `update`,
277
+ createdAt: /* @__PURE__ */ new Date(),
278
+ updatedAt: /* @__PURE__ */ new Date(),
279
+ collection: this.collection
280
+ };
281
+ }).filter(Boolean);
282
+ if (mutations.length === 0) {
283
+ const emptyTransaction = transactions.createTransaction({
284
+ mutationFn: async () => {
285
+ }
286
+ });
287
+ emptyTransaction.commit();
288
+ state.scheduleTransactionCleanup(emptyTransaction);
289
+ return emptyTransaction;
290
+ }
291
+ if (ambientTransaction) {
292
+ ambientTransaction.applyMutations(mutations);
293
+ state.transactions.set(ambientTransaction.id, ambientTransaction);
294
+ state.scheduleTransactionCleanup(ambientTransaction);
295
+ state.recomputeOptimisticState(true);
296
+ return ambientTransaction;
297
+ }
298
+ const directOpTransaction = transactions.createTransaction({
299
+ mutationFn: async (params) => {
300
+ return this.config.onUpdate({
301
+ transaction: params.transaction,
302
+ collection: this.collection
303
+ });
304
+ }
305
+ });
306
+ directOpTransaction.applyMutations(mutations);
307
+ directOpTransaction.commit();
308
+ state.transactions.set(directOpTransaction.id, directOpTransaction);
309
+ state.scheduleTransactionCleanup(directOpTransaction);
310
+ state.recomputeOptimisticState(true);
311
+ return directOpTransaction;
312
+ }
313
+ }
314
+ exports.CollectionMutationsManager = CollectionMutationsManager;
315
+ //# sourceMappingURL=mutations.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mutations.cjs","sources":["../../../src/collection/mutations.ts"],"sourcesContent":["import { withArrayChangeTracking, withChangeTracking } from \"../proxy\"\nimport { createTransaction, getActiveTransaction } from \"../transactions\"\nimport {\n DeleteKeyNotFoundError,\n DuplicateKeyError,\n InvalidSchemaError,\n KeyUpdateNotAllowedError,\n MissingDeleteHandlerError,\n MissingInsertHandlerError,\n MissingUpdateArgumentError,\n MissingUpdateHandlerError,\n NoKeysPassedToDeleteError,\n NoKeysPassedToUpdateError,\n SchemaMustBeSynchronousError,\n SchemaValidationError,\n UndefinedKeyError,\n UpdateKeyNotFoundError,\n} from \"../errors\"\nimport type { Collection, CollectionImpl } from \"./index.js\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\nimport type {\n CollectionConfig,\n InsertConfig,\n OperationConfig,\n PendingMutation,\n StandardSchema,\n Transaction as TransactionType,\n TransactionWithMutations,\n UtilsRecord,\n WritableDeep,\n} from \"../types\"\nimport type { CollectionLifecycleManager } from \"./lifecycle\"\nimport type { CollectionStateManager } from \"./state\"\n\nexport class CollectionMutationsManager<\n TOutput extends object = Record<string, unknown>,\n TKey extends string | number = string | number,\n TUtils extends UtilsRecord = {},\n TSchema extends StandardSchemaV1 = StandardSchemaV1,\n TInput extends object = TOutput,\n> {\n private lifecycle!: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput>\n private state!: CollectionStateManager<TOutput, TKey, TSchema, TInput>\n private collection!: CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n private config!: CollectionConfig<TOutput, TKey, TSchema>\n private id: string\n\n constructor(config: CollectionConfig<TOutput, TKey, TSchema>, id: string) {\n this.id = id\n this.config = config\n }\n\n setDeps(deps: {\n lifecycle: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput>\n state: CollectionStateManager<TOutput, TKey, TSchema, TInput>\n collection: CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n }) {\n this.lifecycle = deps.lifecycle\n this.state = deps.state\n this.collection = deps.collection\n }\n\n private ensureStandardSchema(schema: unknown): StandardSchema<TOutput> {\n // If the schema already implements the standard-schema interface, return it\n if (schema && `~standard` in (schema as {})) {\n return schema as StandardSchema<TOutput>\n }\n\n throw new InvalidSchemaError()\n }\n\n public validateData(\n data: unknown,\n type: `insert` | `update`,\n key?: TKey\n ): TOutput | never {\n if (!this.config.schema) return data as TOutput\n\n const standardSchema = this.ensureStandardSchema(this.config.schema)\n\n // For updates, we need to merge with the existing data before validation\n if (type === `update` && key) {\n // Get the existing data for this key\n const existingData = this.state.get(key)\n\n if (\n existingData &&\n data &&\n typeof data === `object` &&\n typeof existingData === `object`\n ) {\n // Merge the update with the existing data\n const mergedData = Object.assign({}, existingData, data)\n\n // Validate the merged data\n const result = standardSchema[`~standard`].validate(mergedData)\n\n // Ensure validation is synchronous\n if (result instanceof Promise) {\n throw new SchemaMustBeSynchronousError()\n }\n\n // If validation fails, throw a SchemaValidationError with the issues\n if (`issues` in result && result.issues) {\n const typedIssues = result.issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.map((p) => String(p)),\n }))\n throw new SchemaValidationError(type, typedIssues)\n }\n\n // Extract only the modified keys from the validated result\n const validatedMergedData = result.value as TOutput\n const modifiedKeys = Object.keys(data)\n const extractedChanges = Object.fromEntries(\n modifiedKeys.map((k) => [k, validatedMergedData[k as keyof TOutput]])\n ) as TOutput\n\n return extractedChanges\n }\n }\n\n // For inserts or updates without existing data, validate the data directly\n const result = standardSchema[`~standard`].validate(data)\n\n // Ensure validation is synchronous\n if (result instanceof Promise) {\n throw new SchemaMustBeSynchronousError()\n }\n\n // If validation fails, throw a SchemaValidationError with the issues\n if (`issues` in result && result.issues) {\n const typedIssues = result.issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.map((p) => String(p)),\n }))\n throw new SchemaValidationError(type, typedIssues)\n }\n\n return result.value as TOutput\n }\n\n public generateGlobalKey(key: any, item: any): string {\n if (typeof key === `undefined`) {\n throw new UndefinedKeyError(item)\n }\n\n return `KEY::${this.id}/${key}`\n }\n\n /**\n * Inserts one or more items into the collection\n */\n insert = (data: TInput | Array<TInput>, config?: InsertConfig) => {\n this.lifecycle.validateCollectionUsable(`insert`)\n const state = this.state\n const ambientTransaction = getActiveTransaction()\n\n // If no ambient transaction exists, check for an onInsert handler early\n if (!ambientTransaction && !this.config.onInsert) {\n throw new MissingInsertHandlerError()\n }\n\n const items = Array.isArray(data) ? data : [data]\n const mutations: Array<PendingMutation<TOutput>> = []\n\n // Create mutations for each item\n items.forEach((item) => {\n // Validate the data against the schema if one exists\n const validatedData = this.validateData(item, `insert`)\n\n // Check if an item with this ID already exists in the collection\n const key = this.config.getKey(validatedData)\n if (this.state.has(key)) {\n throw new DuplicateKeyError(key)\n }\n const globalKey = this.generateGlobalKey(key, item)\n\n const mutation: PendingMutation<TOutput, `insert`> = {\n mutationId: crypto.randomUUID(),\n original: {},\n modified: validatedData,\n // Pick the values from validatedData based on what's passed in - this is for cases\n // where a schema has default values. The validated data has the extra default\n // values but for changes, we just want to show the data that was actually passed in.\n changes: Object.fromEntries(\n Object.keys(item).map((k) => [\n k,\n validatedData[k as keyof typeof validatedData],\n ])\n ) as TInput,\n globalKey,\n key,\n metadata: config?.metadata as unknown,\n syncMetadata: this.config.sync.getSyncMetadata?.() || {},\n optimistic: config?.optimistic ?? true,\n type: `insert`,\n createdAt: new Date(),\n updatedAt: new Date(),\n collection: this.collection,\n }\n\n mutations.push(mutation)\n })\n\n // If an ambient transaction exists, use it\n if (ambientTransaction) {\n ambientTransaction.applyMutations(mutations)\n\n state.transactions.set(ambientTransaction.id, ambientTransaction)\n state.scheduleTransactionCleanup(ambientTransaction)\n state.recomputeOptimisticState(true)\n\n return ambientTransaction\n } else {\n // Create a new transaction with a mutation function that calls the onInsert handler\n const directOpTransaction = createTransaction<TOutput>({\n mutationFn: async (params) => {\n // Call the onInsert handler with the transaction and collection\n return await this.config.onInsert!({\n transaction:\n params.transaction as unknown as TransactionWithMutations<\n TOutput,\n `insert`\n >,\n collection: this.collection as unknown as Collection<TOutput, TKey>,\n })\n },\n })\n\n // Apply mutations to the new transaction\n directOpTransaction.applyMutations(mutations)\n directOpTransaction.commit()\n\n // Add the transaction to the collection's transactions store\n state.transactions.set(directOpTransaction.id, directOpTransaction)\n state.scheduleTransactionCleanup(directOpTransaction)\n state.recomputeOptimisticState(true)\n\n return directOpTransaction\n }\n }\n\n /**\n * Updates one or more items in the collection using a callback function\n */\n update(\n keys: (TKey | unknown) | Array<TKey | unknown>,\n configOrCallback:\n | ((draft: WritableDeep<TInput>) => void)\n | ((drafts: Array<WritableDeep<TInput>>) => void)\n | OperationConfig,\n maybeCallback?:\n | ((draft: WritableDeep<TInput>) => void)\n | ((drafts: Array<WritableDeep<TInput>>) => void)\n ) {\n if (typeof keys === `undefined`) {\n throw new MissingUpdateArgumentError()\n }\n\n const state = this.state\n this.lifecycle.validateCollectionUsable(`update`)\n\n const ambientTransaction = getActiveTransaction()\n\n // If no ambient transaction exists, check for an onUpdate handler early\n if (!ambientTransaction && !this.config.onUpdate) {\n throw new MissingUpdateHandlerError()\n }\n\n const isArray = Array.isArray(keys)\n const keysArray = isArray ? keys : [keys]\n\n if (isArray && keysArray.length === 0) {\n throw new NoKeysPassedToUpdateError()\n }\n\n const callback =\n typeof configOrCallback === `function` ? configOrCallback : maybeCallback!\n const config =\n typeof configOrCallback === `function` ? {} : configOrCallback\n\n // Get the current objects or empty objects if they don't exist\n const currentObjects = keysArray.map((key) => {\n const item = this.state.get(key)\n if (!item) {\n throw new UpdateKeyNotFoundError(key)\n }\n\n return item\n }) as unknown as Array<TInput>\n\n let changesArray\n if (isArray) {\n // Use the proxy to track changes for all objects\n changesArray = withArrayChangeTracking(\n currentObjects,\n callback as (draft: Array<TInput>) => void\n )\n } else {\n const result = withChangeTracking(\n currentObjects[0]!,\n callback as (draft: TInput) => void\n )\n changesArray = [result]\n }\n\n // Create mutations for each object that has changes\n const mutations: Array<\n PendingMutation<\n TOutput,\n `update`,\n CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n >\n > = keysArray\n .map((key, index) => {\n const itemChanges = changesArray[index] // User-provided changes for this specific item\n\n // Skip items with no changes\n if (!itemChanges || Object.keys(itemChanges).length === 0) {\n return null\n }\n\n const originalItem = currentObjects[index] as unknown as TOutput\n // Validate the user-provided changes for this item\n const validatedUpdatePayload = this.validateData(\n itemChanges,\n `update`,\n key\n )\n\n // Construct the full modified item by applying the validated update payload to the original item\n const modifiedItem = Object.assign(\n {},\n originalItem,\n validatedUpdatePayload\n )\n\n // Check if the ID of the item is being changed\n const originalItemId = this.config.getKey(originalItem)\n const modifiedItemId = this.config.getKey(modifiedItem)\n\n if (originalItemId !== modifiedItemId) {\n throw new KeyUpdateNotAllowedError(originalItemId, modifiedItemId)\n }\n\n const globalKey = this.generateGlobalKey(modifiedItemId, modifiedItem)\n\n return {\n mutationId: crypto.randomUUID(),\n original: originalItem,\n modified: modifiedItem,\n // Pick the values from modifiedItem based on what's passed in - this is for cases\n // where a schema has default values or transforms. The modified data has the extra\n // default or transformed values but for changes, we just want to show the data that\n // was actually passed in.\n changes: Object.fromEntries(\n Object.keys(itemChanges).map((k) => [\n k,\n modifiedItem[k as keyof typeof modifiedItem],\n ])\n ) as TInput,\n globalKey,\n key,\n metadata: config.metadata as unknown,\n syncMetadata: (state.syncedMetadata.get(key) || {}) as Record<\n string,\n unknown\n >,\n optimistic: config.optimistic ?? true,\n type: `update`,\n createdAt: new Date(),\n updatedAt: new Date(),\n collection: this.collection,\n }\n })\n .filter(Boolean) as Array<\n PendingMutation<\n TOutput,\n `update`,\n CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n >\n >\n\n // If no changes were made, return an empty transaction early\n if (mutations.length === 0) {\n const emptyTransaction = createTransaction({\n mutationFn: async () => {},\n })\n emptyTransaction.commit()\n // Schedule cleanup for empty transaction\n state.scheduleTransactionCleanup(emptyTransaction)\n return emptyTransaction\n }\n\n // If an ambient transaction exists, use it\n if (ambientTransaction) {\n ambientTransaction.applyMutations(mutations)\n\n state.transactions.set(ambientTransaction.id, ambientTransaction)\n state.scheduleTransactionCleanup(ambientTransaction)\n state.recomputeOptimisticState(true)\n\n return ambientTransaction\n }\n\n // No need to check for onUpdate handler here as we've already checked at the beginning\n\n // Create a new transaction with a mutation function that calls the onUpdate handler\n const directOpTransaction = createTransaction<TOutput>({\n mutationFn: async (params) => {\n // Call the onUpdate handler with the transaction and collection\n return this.config.onUpdate!({\n transaction:\n params.transaction as unknown as TransactionWithMutations<\n TOutput,\n `update`\n >,\n collection: this.collection as unknown as Collection<TOutput, TKey>,\n })\n },\n })\n\n // Apply mutations to the new transaction\n directOpTransaction.applyMutations(mutations)\n directOpTransaction.commit()\n\n // Add the transaction to the collection's transactions store\n\n state.transactions.set(directOpTransaction.id, directOpTransaction)\n state.scheduleTransactionCleanup(directOpTransaction)\n state.recomputeOptimisticState(true)\n\n return directOpTransaction\n }\n\n /**\n * Deletes one or more items from the collection\n */\n delete = (\n keys: Array<TKey> | TKey,\n config?: OperationConfig\n ): TransactionType<any> => {\n const state = this.state\n this.lifecycle.validateCollectionUsable(`delete`)\n\n const ambientTransaction = getActiveTransaction()\n\n // If no ambient transaction exists, check for an onDelete handler early\n if (!ambientTransaction && !this.config.onDelete) {\n throw new MissingDeleteHandlerError()\n }\n\n if (Array.isArray(keys) && keys.length === 0) {\n throw new NoKeysPassedToDeleteError()\n }\n\n const keysArray = Array.isArray(keys) ? keys : [keys]\n const mutations: Array<\n PendingMutation<\n TOutput,\n `delete`,\n CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n >\n > = []\n\n for (const key of keysArray) {\n if (!this.state.has(key)) {\n throw new DeleteKeyNotFoundError(key)\n }\n const globalKey = this.generateGlobalKey(key, this.state.get(key)!)\n const mutation: PendingMutation<\n TOutput,\n `delete`,\n CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n > = {\n mutationId: crypto.randomUUID(),\n original: this.state.get(key)!,\n modified: this.state.get(key)!,\n changes: this.state.get(key)!,\n globalKey,\n key,\n metadata: config?.metadata as unknown,\n syncMetadata: (state.syncedMetadata.get(key) || {}) as Record<\n string,\n unknown\n >,\n optimistic: config?.optimistic ?? true,\n type: `delete`,\n createdAt: new Date(),\n updatedAt: new Date(),\n collection: this.collection,\n }\n\n mutations.push(mutation)\n }\n\n // If an ambient transaction exists, use it\n if (ambientTransaction) {\n ambientTransaction.applyMutations(mutations)\n\n state.transactions.set(ambientTransaction.id, ambientTransaction)\n state.scheduleTransactionCleanup(ambientTransaction)\n state.recomputeOptimisticState(true)\n\n return ambientTransaction\n }\n\n // Create a new transaction with a mutation function that calls the onDelete handler\n const directOpTransaction = createTransaction<TOutput>({\n autoCommit: true,\n mutationFn: async (params) => {\n // Call the onDelete handler with the transaction and collection\n return this.config.onDelete!({\n transaction:\n params.transaction as unknown as TransactionWithMutations<\n TOutput,\n `delete`\n >,\n collection: this.collection as unknown as Collection<TOutput, TKey>,\n })\n },\n })\n\n // Apply mutations to the new transaction\n directOpTransaction.applyMutations(mutations)\n directOpTransaction.commit()\n\n state.transactions.set(directOpTransaction.id, directOpTransaction)\n state.scheduleTransactionCleanup(directOpTransaction)\n state.recomputeOptimisticState(true)\n\n return directOpTransaction\n }\n}\n"],"names":["config","getActiveTransaction","MissingInsertHandlerError","DuplicateKeyError","createTransaction","MissingDeleteHandlerError","NoKeysPassedToDeleteError","DeleteKeyNotFoundError","InvalidSchemaError","result","SchemaMustBeSynchronousError","SchemaValidationError","UndefinedKeyError","MissingUpdateArgumentError","MissingUpdateHandlerError","NoKeysPassedToUpdateError","UpdateKeyNotFoundError","withArrayChangeT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AG;AAC1B,YAAM,mBAAmBf,aAAAA,kBAAkB;AAAA,QACzC,YAAY,YAAY;AAAA,QAAC;AAAA,MAAA,CAC1B;AACD,uBAAiB,OAAA;AAEjB,YAAM,2BAA2B,gBAAgB;AACjD,aAAO;AAAA,IACT;AAGA,QAAI,oBAAoB;AACtB,yBAAmB,eAAe,SAAS;AAE3C,YAAM,aAAa,IAAI,mBAAmB,IAAI,kBAAkB;AAChE,YAAM,2BAA2B,kBAAkB;AACnD,YAAM,yBAAyB,IAAI;AAEnC,aAAO;AAAA,IACT;AAKA,UAAM,sBAAsBA,aAAAA,kBAA2B;AAAA,MACrD,YAAY,OAAO,WAAW;AAE5B,eAAO,KAAK,OAAO,SAAU;AAAA,UAC3B,aACE,OAAO;AAAA,UAIT,YAAY,KAAK;AAAA,QAAA,CAClB;AAAA,MACH;AAAA,IAAA,CACD;AAGD,wBAAoB,eAAe,SAAS;AAC5C,wBAAoB,OAAA;AAIpB,UAAM,aAAa,IAAI,oBAAoB,IAAI,mBAAmB;AAClE,UAAM,2BAA2B,mBAAmB;AACpD,UAAM,yBAAyB,IAAI;AAEnC,WAAO;AAAA,EACT;AAoGF;;"}
@@ -0,0 +1,33 @@
1
+ import { CollectionImpl } from './index.js';
2
+ import { StandardSchemaV1 } from '@standard-schema/spec';
3
+ import { CollectionConfig, InsertConfig, OperationConfig, Transaction as TransactionType, UtilsRecord, WritableDeep } from '../types.cjs';
4
+ import { CollectionLifecycleManager } from './lifecycle.cjs';
5
+ import { CollectionStateManager } from './state.cjs';
6
+ export declare class CollectionMutationsManager<TOutput extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord = {}, TSchema extends StandardSchemaV1 = StandardSchemaV1, TInput extends object = TOutput> {
7
+ private lifecycle;
8
+ private state;
9
+ private collection;
10
+ private config;
11
+ private id;
12
+ constructor(config: CollectionConfig<TOutput, TKey, TSchema>, id: string);
13
+ setDeps(deps: {
14
+ lifecycle: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput>;
15
+ state: CollectionStateManager<TOutput, TKey, TSchema, TInput>;
16
+ collection: CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>;
17
+ }): void;
18
+ private ensureStandardSchema;
19
+ validateData(data: unknown, type: `insert` | `update`, key?: TKey): TOutput | never;
20
+ generateGlobalKey(key: any, item: any): string;
21
+ /**
22
+ * Inserts one or more items into the collection
23
+ */
24
+ insert: (data: TInput | Array<TInput>, config?: InsertConfig) => TransactionType<Record<string, unknown>> | TransactionType<TOutput>;
25
+ /**
26
+ * Updates one or more items in the collection using a callback function
27
+ */
28
+ update(keys: (TKey | unknown) | Array<TKey | unknown>, configOrCallback: ((draft: WritableDeep<TInput>) => void) | ((drafts: Array<WritableDeep<TInput>>) => void) | OperationConfig, maybeCallback?: ((draft: WritableDeep<TInput>) => void) | ((drafts: Array<WritableDeep<TInput>>) => void)): TransactionType<Record<string, unknown>> | TransactionType<TOutput>;
29
+ /**
30
+ * Deletes one or more items from the collection
31
+ */
32
+ delete: (keys: Array<TKey> | TKey, config?: OperationConfig) => TransactionType<any>;
33
+ }