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 begin: () => void
39 write: (message: Omit<ChangeMessage<TRow>, `key`>) => void
40 commit: () => void
41}
42
43interface NormalizedOperation<
44 TRow extends object,
45 TKey extends string | number = string | number,
46> {
47 type: `insert` | `update` | `delete` | `upsert`
48 key: TKey
49 data?: TRow | Partial<TRow>
50}
51
52// Normalize operations into a consistent format
53function normalizeOperations<
54 TRow extends object,
55 TKey extends string | number = string | number,
56 TInsertInput extends object = TRow,
57>(
58 ops:
59 | SyncOperation<TRow, TKey, TInsertInput>
60 | Array<SyncOperation<TRow, TKey, TInsertInput>>,
61 ctx: SyncContext<TRow, TKey>
62): Array<NormalizedOperation<TRow, TKey>> {
63 const operations = Array.isArray(ops) ? ops : [ops]
64 const normalized: Array<NormalizedOperation<TRow, TKey>> = []
65
66 for (const op of operations) {
67 if (op.type === `delete`) {
68 const keys = Array.isArray(op.key) ? op.key : [op.key]
69 for (const key of keys) {
70 normalized.push({ type: `delete`, key })
71 }
72 } else {
73 const items = Array.isArray(op.data) ? op.data : [op.data]
74 for (const item of items) {
75 let key: TKey
76 if (op.type === `update`) {
77 // For updates, we need to get the key from the partial data
78 key = ctx.getKey(item as TRow)
79 } else {
80 // For insert/upsert, validate and resolve the full item first
81 const resolved = ctx.collection.validateData(
82 item,
83 op.type === `upsert` ? `insert` : op.type
84 )
85 key = ctx.getKey(resolved)
86 }
87 normalized.push({ type: op.type, key, data: item })
88 }
89 }
90 }
91
92 return normalized
93}
94
95// Validate operations before executing
96function validateOperations<
97 TRow extends object,
98 TKey extends string | number = string | number,
99>(
100 operations: Array<NormalizedOperation<TRow, TKey>>,
101 ctx: SyncContext<TRow, TKey>
102): void {
103 const seenKeys = new Set<TKey>()
104
105 for (const op of operations) {
106 // Check for duplicate keys within the batch
107 if (seenKeys.has(op.key)) {
108 throw new DuplicateKeyInBatchError(op.key)
109 }
110 seenKeys.add(op.key)
111
112 // Validate operation-specific requirements
113 if (op.type === `update`) {
114 if (!ctx.collection.has(op.key)) {
115 throw new UpdateOperationItemNotFoundError(op.key)
116 }
117 } else if (op.type === `delete`) {
118 if (!ctx.collection.has(op.key)) {
119 throw new DeleteOperationItemNotFoundError(op.key)
120 }
121 }
122 }
123}
124
125// Execute a batch of operations
126export function performWriteOperations<
127 TRow extends object,
128 TKey extends string | number = string | number,
129 TInsertInput extends object = TRow,
130>(
131 operations:
132 | SyncOperation<TRow, TKey, TInsertInput>
133 | Array<SyncOperation<TRow, TKey, TInsertInput>>,
134 ctx: SyncContext<TRow, TKey>
135): void {
136 const normalized = normalizeOperations(operations, ctx)
137 validateOperations(normalized, ctx)
138
139 ctx.begin()
140
141 for (const op of normalized) {
142 switch (op.type) {
143 case `insert`: {
144 const resolved = ctx.collection.validateData(op.data, `insert`)
145 ctx.write({
146 type: `insert`,
147 value: resolved,
148 })
149 break
150 }
151 case `update`: {
152 const currentItem = ctx.collection.get(op.key)!
153 const updatedItem = {
154 ...currentItem,
155 ...op.data,
156 }
157 const resolved = ctx.collection.validateData(
158 updatedItem,
159 `update`,
160 op.key
161 )
162 ctx.write({
163 type: `update`,
164 value: resolved,
165 })
166 break
167 }
168 case `delete`: {
169 const currentItem = ctx.collection.get(op.key)!
170 ctx.write({
171 type: `delete`,
172 value: currentItem,
173 })
174 break
175 }
176 case `upsert`: {
177 const resolved = ctx.collection.validateData(
178 op.data,
179 ctx.collection.has(op.key) ? `update` : `insert`,
180 op.key
181 )
182 if (ctx.collection.has(op.key)) {
183 ctx.write({
184 type: `update`,
185 value: resolved,
186 })
187 } else {
188 ctx.write({
189 type: `insert`,
190 value: resolved,
191 })
192 }
193 break
194 }
195 }
196 }
197
198 ctx.commit()
199
200 // Update query cache after successful commit
201 const updatedData = ctx.collection.toArray
202 ctx.queryClient.setQueryData(ctx.queryKey, updatedData)
203}
204
205// Factory function to create write utils
206export function createWriteUtils<
207 TRow extends object,
208 TKey extends string | number = string | number,
209 TInsertInput extends object = TRow,
210>(getContext: () => SyncContext<TRow, TKey> | null) {
211 function ensureContext(): SyncContext<TRow, TKey> {
212 const context = getContext()
213 if (!context) {
214 throw new SyncNotInitializedError()
215 }
216 return context
217 }
218
219 return {
220 writeInsert(data: TInsertInput | Array<TInsertInput>) {
221 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
222 type: `insert`,
223 data,
224 }
225
226 const ctx = ensureContext()
227 const batchContext = activeBatchContexts.get(ctx)
228
229 // If we're in a batch, just add to the batch operations
230 if (batchContext?.isActive) {
231 batchContext.operations.push(operation)
232 return
233 }
234
235 // Otherwise, perform the operation immediately
236 performWriteOperations(operation, ctx)
237 },
238
239 writeUpdate(data: Partial<TRow> | Array<Partial<TRow>>) {
240 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
241 type: `update`,
242 data,
243 }
244
245 const ctx = ensureContext()
246 const batchContext = activeBatchContexts.get(ctx)
247
248 if (batchContext?.isActive) {
249 batchContext.operations.push(operation)
250 return
251 }
252
253 performWriteOperations(operation, ctx)
254 },
255
256 writeDelete(key: TKey | Array<TKey>) {
257 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
258 type: `delete`,
259 key,
260 }
261
262 const ctx = ensureContext()
263 const batchContext = activeBatchContexts.get(ctx)
264
265 if (batchContext?.isActive) {
266 batchContext.operations.push(operation)
267 return
268 }
269
270 performWriteOperations(operation, ctx)
271 },
272
273 writeUpsert(data: Partial<TRow> | Array<Partial<TRow>>) {
274 const operation: SyncOperation<TRow, TKey, TInsertInput> = {
275 type: `upsert`,
276 data,
277 }
278
279 const ctx = ensureContext()
280 const batchContext = activeBatchContexts.get(ctx)
281
282 if (batchContext?.isActive) {
283 batchContext.operations.push(operation)
284 return
285 }
286
287 performWriteOperations(operation, ctx)
288 },
289
290 writeBatch(callback: () => void) {
291 const ctx = ensureContext()
292
293 // Check if we're already in a batch (nested batch)
294 const existingBatch = activeBatchContexts.get(ctx)
295 if (existingBatch?.isActive) {
296 throw new Error(
297 `Cannot nest writeBatch calls. Complete the current batch before starting a new one.`
298 )
299 }
300
301 // Set up the batch context for this specific collection
302 const batchContext = {
303 operations: [] as Array<SyncOperation<TRow, TKey, TInsertInput>>,
304 isActive: true,
305 }
306 activeBatchContexts.set(ctx, batchContext)
307
308 try {
309 // Execute the callback - any write operations will be collected
310 const result = callback()
311
312 // Check if callback returns a promise (async function)
313 if (
314 // @ts-expect-error - Runtime check for async callback, callback is typed as () => void but user might pass async
315 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
316 result &&
317 typeof result === `object` &&
318 `then` in result &&
319 // @ts-expect-error - Runtime check for async callback, callback is typed as () => void but user might pass async
320 typeof result.then === `function`
321 ) {
322 throw new Error(
323 `writeBatch does not support async callbacks. The callback must be synchronous.`
324 )
325 }
326
327 // Perform all collected operations
328 if (batchContext.operations.length > 0) {
329 performWriteOperations(batchContext.operations, ctx)
330 }
331 } finally {
332 // Always clear the batch context
333 batchContext.isActive = false
334 activeBatchContexts.delete(ctx)
335 }
336 },
337 }
338}