Open History to see the last commit
1import {
2 DeleteOperationItemNotFoundError,
3 DuplicateKeyInBatchError,
4 SyncNotInitializedError,
5 UpdateOperationItemNotFoundError,
6} from './errors'
7import type { QueryClient } from '@tanstack/query-core'
8import type { ChangeMessage, Collection } from '@tanstack/db'
9
10// Track active batch operations per context to prevent cross-collection contamination
11const activeBatchContexts = new WeakMap<
12 SyncContext<any, any>,
13 {
14 operations: Array<SyncOperation<any, any, any>>
15 isActive: boolean
16 }
17>()
18
19// Types for sync operations
20export type SyncOperation<
21 TRow extends object,
22 TKey extends string | number = string | number,
23 TInsertInput extends object = TRow,
24> =
25 | { type: `insert`; data: TInsertInput | Array<TInsertInput> }
26 | { type: `update`; data: Partial<TRow> | Array<Partial<TRow>> }
27 | { type: `delete`; key: TKey | Array<TKey> }
28 | { type: `upsert`; data: Partial<TRow> | Array<Partial<TRow>> }
29
30export interface SyncContext<
31 TRow extends object,
32 TKey extends string | number = string | number,
33> {
34 collection: Collection<TRow>
35 queryClient: QueryClient
36 queryKey: Array<unknown>
37 getKey: (item: TRow) => TKey
38 /**
39 * Begin a new sync transaction.
40 * @param options.immediate - When true, the transaction will be processed immediately
41 * even if there are persisting user transactions. Used by manual write operations.
42 */
43 begin: (options?: { immediate?: boolean }) => void
44 write: (message: Omit<ChangeMessage<TRow>, `key`>) => void
45 commit: () => void
46 /**
47 * Optional function to update the query cache with the latest synced data.
48 * Handles both direct array caches and wrapped response formats (when `select` is used).
49 * If not provided, falls back to directly setting the cache with the raw array.
50 */
51 updateCacheData?: (items: Array<TRow>) => void
52}
53
54interface NormalizedOperation<
55 TRow extends object,
56 TKey extends string | number = string | number,
57> {
58 type: `insert` | `update` | `delete` | `upsert`
59 key: TKey
60 data?: TRow | Partial<TRow>
61}
62
63// Normalize operations into a consistent format
64function normalizeOperations<
65 TRow extends object,
66 TKey extends string | number = string | number,
67 TInsertInput extends object = TRow,
68>(
69 ops:
70 | SyncOperation<TRow, TKey, TInsertInput>
71 | Array<SyncOperation<TRow, TKey, TInsertInput>>,
72 ctx: SyncContext<TRow, TKey>,
73): Array<NormalizedOperation<TRow, TKey>> {
74 const operations = Array.isArray(ops) ? ops : [ops]
75 const normalized: Array<NormalizedOperation<TRow, TKey>> = []
76
77 for (const op of operations) {
78 if (op.type === `delete`) {
79 const keys = Array.isArray(op.key) ? op.key : [op.key]
80 for (const key of keys) {
81 normalized.push({ type: `delete`, key })
82 }
83 } else {
84 const items = Array.isArray(op.data) ? op.data : [op.data]
85 for (const item of items) {
86 let key: TKey
87 if (op.type === `update`) {
88 // For updates, we need to get the key from the partial data
89 key = ctx.getKey(item as TRow)
90 } else {
91 // For insert/upsert, validate and resolve the full item first
92 const resolved = ctx.collection.validateData(
93 item,
94 op.type === `upsert` ? `insert` : op.type,
95 )
96 key = ctx.getKey(resolved)
97 }
98 normalized.push({ type: op.type, key, data: item })
99 }
100 }
101 }
102
103 return normalized
104}
105
106// Validate operations before executing
107function validateOperations<
108 TRow extends object,
109 TKey extends string | number = string | number,
110>(
111 operations: Array<NormalizedOperation<TRow, TKey>>,
112 ctx: SyncContext<TRow, TKey>,
113): void {
114 const seenKeys = new Set<TKey>()
115
116 for (const op of operations) {
117 // Check for duplicate keys within the batch
118 if (seenKeys.has(op.key)) {
119 throw new DuplicateKeyInBatchError(op.key)
120 }
121 seenKeys.add(op.key)
122
123 // Validate operation-specific requirements
124 // NOTE: These validations check the synced store only, not the combined view (synced + optimistic)
125 // This allows write operations to work correctly even when items are optimistically modified
126 if (op.type === `update`) {
127 if (!ctx.collection._state.syncedData.has(op.key)) {
128 throw new UpdateOperationItemNotFoundError(op.key)
129 }
130 } else if (op.type === `delete`) {
131 if (!ctx.collection._state.syncedData.has(op.key)) {
132 throw new DeleteOperationItemNotFoundError(op.key)
133 }
134 }
135 }
136}
137
138// Execute a batch of operations
139export function performWriteOperations<
140 TRow extends object,
141 TKey extends string | number = string | number,
142 TInsertInput extends object = TRow,
143>(
144 operations:
145 | SyncOperation<TRow, TKey, TInsertInput>
146 | Array<SyncOperation<TRow, TKey, TInsertInput>>,
147 ctx: SyncContext<TRow, TKey>,
148): void {
149 const normalized = normalizeOperations(operations, ctx)
150 validateOperations(normalized, ctx)
151
152 // Use immediate: true to ensure syncedData is updated synchronously,
153 // even when called from within a mutationFn with an active persisting transaction
154 ctx.begin({ immediate: true })
155
156 for (const op of normalized) {
157 switch (op.type) {
158 case `insert`: {
159 const resolved = ctx.collection.validateData(op.data, `insert`)
160 ctx.write({
161 type: `insert`,
162 value: resolved,
163 })
164 break
165 }
166 case `update`: {
167 // Get from synced store only, not the combined view
168 const currentItem = ctx.collection._state.syncedData.get(op.key)!
169 const updatedItem = {
170 ...currentItem,
171 ...op.data,
172 }
173 const resolved = ctx.collection.validateData(
174 updatedItem,
175 `update`,
176 op.key,
177 )
178 ctx.write({
179 type: `update`,
180 value: resolved,
181 })
182 break
183 }
184 case `delete`: {
185 // Get from synced store only, not the combined view
186 const currentItem = ctx.collection._state.syncedData.get(op.key)!
187 ctx.write({
188 type: `delete`,
189 value: currentItem,
190 })
191 break
192 }
193 case `upsert`: {
194 // Check synced store only, not the combined view
195 const existsInSyncedStore = ctx.collection._state.syncedData.has(op.key)
196 const resolved = ctx.collection.validateData(
197 op.data,
198 existsInSyncedStore ? `update` : `insert`,
199 op.key,
200 )
201 if (existsInSyncedStore) {
202 ctx.write({
203 type: `update`,
204 value: resolved,
205 })
206 } else {
207 ctx.write({
208 type: `insert`,
209 value: resolved,
210 })
211 }
212 break
213 }
214 }
215 }
216
217 ctx.commit()
218
219 // Update query cache after successful commit
220 const updatedData = Array.from(ctx.collection._state.syncedData.values())
221 if (ctx.updateCacheData) {
222 ctx.updateCacheData(updatedData)
223 } else {
224 // Fallback: directly set the cache with raw array (for non-Query Collection consumers)
225 ctx.queryClient.setQueryData(ctx.queryKey, updatedData)
226 }
227}
228
229// Factory function to create write utils
230export function createWriteUtils<
231 TRow extends object,
232 TKey extends string | number = string | number,
233 TInsertInput extends object = TRow,
234>(getContext: () => SyncContext<TRow, TKey> | null) {
235 function ensureContext(): SyncContext<TRow, TKey> {
236 const context = getContext()
237 if (!context) {
238 throw new SyncNotInitializedError()
239 }
240 return context
241 }
242
243 return {
244 writeInsert(data: TInsertInput | Array<TInsertInput>) {
245 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
246 type: `insert`,
247 data,
248 }
249
250 const ctx = ensureContext()
251 const batchContext = activeBatchContexts.get(ctx)
252
253 // If we're in a batch, just add to the batch operations
254 if (batchContext?.isActive) {
255 batchContext.operations.push(operation)
256 return
257 }
258
259 // Otherwise, perform the operation immediately
260 performWriteOperations(operation, ctx)
261 },
262
263 writeUpdate(data: Partial<TRow> | Array<Partial<TRow>>) {
264 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
265 type: `update`,
266 data,
267 }
268
269 const ctx = ensureContext()
270 const batchContext = activeBatchContexts.get(ctx)
271
272 if (batchContext?.isActive) {
273 batchContext.operations.push(operation)
274 return
275 }
276
277 performWriteOperations(operation, ctx)
278 },
279
280 writeDelete(key: TKey | Array<TKey>) {
281 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
282 type: `delete`,
283 key,
284 }
285
286 const ctx = ensureContext()
287 const batchContext = activeBatchContexts.get(ctx)
288
289 if (batchContext?.isActive) {
290 batchContext.operations.push(operation)
291 return
292 }
293
294 performWriteOperations(operation, ctx)
295 },
296
297 writeUpsert(data: Partial<TRow> | Array<Partial<TRow>>) {
298 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
299 type: `upsert`,
300 data,
301 }
302
303 const ctx = ensureContext()
304 const batchContext = activeBatchContexts.get(ctx)
305
306 if (batchContext?.isActive) {
307 batchContext.operations.push(operation)
308 return
309 }
310
311 performWriteOperations(operation, ctx)
312 },
313
314 writeBatch(callback: () => void) {
315 const ctx = ensureContext()
316
317 // Check if we're already in a batch (nested batch)
318 const existingBatch = activeBatchContexts.get(ctx)
319 if (existingBatch?.isActive) {
320 throw new Error(
321 `Cannot nest writeBatch calls. Complete the current batch before starting a new one.`,
322 )
323 }
324
325 // Set up the batch context for this specific collection
326 const batchContext = {
327 operations: [] as Array<SyncOperation<TRow, TKey, TInsertInput>>,
328 isActive: true,
329 }
330 activeBatchContexts.set(ctx, batchContext)
331
332 try {
333 // Execute the callback - any write operations will be collected
334 const result = callback()
335
336 // Check if callback returns a promise (async function)
337 if (
338 // @ts-expect-error - Runtime check for async callback, callback is typed as () => void but user might pass async
339 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
340 result &&
341 typeof result === `object` &&
342 `then` in result &&
343 // @ts-expect-error - Runtime check for async callback, callback is typed as () => void but user might pass async
344 typeof result.then === `function`
345 ) {
346 throw new Error(
347 `writeBatch does not support async callbacks. The callback must be synchronous.`,
348 )
349 }
350
351 // Perform all collected operations
352 if (batchContext.operations.length > 0) {
353 performWriteOperations(batchContext.operations, ctx)
354 }
355 } finally {
356 // Always clear the batch context
357 batchContext.isActive = false
358 activeBatchContexts.delete(ctx)
359 }
360 },
361 }
362}