Open History to see the last commit
1import { QueryObserver } from "@tanstack/query-core"
2import {
3 GetKeyRequiredError,
4 QueryClientRequiredError,
5 QueryFnRequiredError,
6 QueryKeyRequiredError,
7} from "./errors"
8import { createWriteUtils } from "./manual-sync"
9import type {
10 QueryClient,
11 QueryFunctionContext,
12 QueryKey,
13 QueryObserverOptions,
14} from "@tanstack/query-core"
15import type {
16 BaseCollectionConfig,
17 ChangeMessage,
18 CollectionConfig,
19 DeleteMutationFnParams,
20 InsertMutationFnParams,
21 SyncConfig,
22 UpdateMutationFnParams,
23 UtilsRecord,
24} from "@tanstack/db"
25import type { StandardSchemaV1 } from "@standard-schema/spec"
26
27// Re-export for external use
28export type { SyncOperation } from "./manual-sync"
29
30// Schema output type inference helper (matches electric.ts pattern)
31type InferSchemaOutput<T> = T extends StandardSchemaV1
32 ? StandardSchemaV1.InferOutput<T> extends object
33 ? StandardSchemaV1.InferOutput<T>
34 : Record<string, unknown>
35 : Record<string, unknown>
36
37// Schema input type inference helper (matches electric.ts pattern)
38type InferSchemaInput<T> = T extends StandardSchemaV1
39 ? StandardSchemaV1.InferInput<T> extends object
40 ? StandardSchemaV1.InferInput<T>
41 : Record<string, unknown>
42 : Record<string, unknown>
43
44/**
45 * Configuration options for creating a Query Collection
46 * @template T - The explicit type of items stored in the collection
47 * @template TQueryFn - The queryFn type
48 * @template TError - The type of errors that can occur during queries
49 * @template TQueryKey - The type of the query key
50 * @template TKey - The type of the item keys
51 * @template TSchema - The schema type for validation
52 */
53export interface QueryCollectionConfig<
54 T extends object = object,
55 TQueryFn extends (
56 context: QueryFunctionContext<any>
57 ) => Promise<Array<any>> = (
58 context: QueryFunctionContext<any>
59 ) => Promise<Array<any>>,
60 TError = unknown,
61 TQueryKey extends QueryKey = QueryKey,
62 TKey extends string | number = string | number,
63 TSchema extends StandardSchemaV1 = never,
64> extends BaseCollectionConfig<T, TKey, TSchema> {
65 /** The query key used by TanStack Query to identify this query */
66 queryKey: TQueryKey
67 /** Function that fetches data from the server. Must return the complete collection state */
68 queryFn: TQueryFn extends (
69 context: QueryFunctionContext<TQueryKey>
70 ) => Promise<Array<any>>
71 ? TQueryFn
72 : (context: QueryFunctionContext<TQueryKey>) => Promise<Array<T>>
73
74 /** The TanStack Query client instance */
75 queryClient: QueryClient
76
77 // Query-specific options
78 /** Whether the query should automatically run (default: true) */
79 enabled?: boolean
80 refetchInterval?: QueryObserverOptions<
81 Array<T>,
82 TError,
83 Array<T>,
84 Array<T>,
85 TQueryKey
86 >[`refetchInterval`]
87 retry?: QueryObserverOptions<
88 Array<T>,
89 TError,
90 Array<T>,
91 Array<T>,
92 TQueryKey
93 >[`retry`]
94 retryDelay?: QueryObserverOptions<
95 Array<T>,
96 TError,
97 Array<T>,
98 Array<T>,
99 TQueryKey
100 >[`retryDelay`]
101 staleTime?: QueryObserverOptions<
102 Array<T>,
103 TError,
104 Array<T>,
105 Array<T>,
106 TQueryKey
107 >[`staleTime`]
108
109 /**
110 * Metadata to pass to the query.
111 * Available in queryFn via context.meta
112 *
113 * @example
114 * // Using meta for error context
115 * queryFn: async (context) => {
116 * try {
117 * return await api.getTodos(userId)
118 * } catch (error) {
119 * // Use meta for better error messages
120 * throw new Error(
121 * context.meta?.errorMessage || 'Failed to load todos'
122 * )
123 * }
124 * },
125 * meta: {
126 * errorMessage: `Failed to load todos for user ${userId}`
127 * }
128 */
129 meta?: Record<string, unknown>
130}
131
132/**
133 * Type for the refetch utility function
134 */
135export type RefetchFn = (opts?: { throwOnError?: boolean }) => Promise<void>
136
137/**
138 * Utility methods available on Query Collections for direct writes and manual operations.
139 * Direct writes bypass the normal query/mutation flow and write directly to the synced data store.
140 * @template TItem - The type of items stored in the collection
141 * @template TKey - The type of the item keys
142 * @template TInsertInput - The type accepted for insert operations
143 * @template TError - The type of errors that can occur during queries
144 */
145export interface QueryCollectionUtils<
146 TItem extends object = Record<string, unknown>,
147 TKey extends string | number = string | number,
148 TInsertInput extends object = TItem,
149 TError = unknown,
150> extends UtilsRecord {
151 /** Manually trigger a refetch of the query */
152 refetch: RefetchFn
153 /** Insert one or more items directly into the synced data store without triggering a query refetch or optimistic update */
154 writeInsert: (data: TInsertInput | Array<TInsertInput>) => void
155 /** Update one or more items directly in the synced data store without triggering a query refetch or optimistic update */
156 writeUpdate: (updates: Partial<TItem> | Array<Partial<TItem>>) => void
157 /** Delete one or more items directly from the synced data store without triggering a query refetch or optimistic update */
158 writeDelete: (keys: TKey | Array<TKey>) => void
159 /** Insert or update one or more items directly in the synced data store without triggering a query refetch or optimistic update */
160 writeUpsert: (data: Partial<TItem> | Array<Partial<TItem>>) => void
161 /** Execute multiple write operations as a single atomic batch to the synced data store */
162 writeBatch: (callback: () => void) => void
163 /** Get the last error encountered by the query (if any); reset on success */
164 lastError: () => TError | undefined
165 /** Check if the collection is in an error state */
166 isError: () => boolean
167 /**
168 * Get the number of consecutive sync failures.
169 * Incremented only when query fails completely (not per retry attempt); reset on success.
170 */
171 errorCount: () => number
172 /**
173 * Clear the error state and trigger a refetch of the query
174 * @returns Promise that resolves when the refetch completes successfully
175 * @throws Error if the refetch fails
176 */
177 clearError: () => Promise<void>
178}
179
180/**
181 * Creates query collection options for use with a standard Collection.
182 * This integrates TanStack Query with TanStack DB for automatic synchronization.
183 *
184 * Supports automatic type inference following the priority order:
185 * 1. Schema inference (highest priority)
186 * 2. QueryFn return type inference (second priority)
187 *
188 * @template T - Type of the schema if a schema is provided otherwise it is the type of the values returned by the queryFn
189 * @template TError - The type of errors that can occur during queries
190 * @template TQueryKey - The type of the query key
191 * @template TKey - The type of the item keys
192 * @param config - Configuration options for the Query collection
193 * @returns Collection options with utilities for direct writes and manual operations
194 *
195 * @example
196 * // Type inferred from queryFn return type (NEW!)
197 * const todosCollection = createCollection(
198 * queryCollectionOptions({
199 * queryKey: ['todos'],
200 * queryFn: async () => {
201 * const response = await fetch('/api/todos')
202 * return response.json() as Todo[] // Type automatically inferred!
203 * },
204 * queryClient,
205 * getKey: (item) => item.id, // item is typed as Todo
206 * })
207 * )
208 *
209 * @example
210 * // Explicit type
211 * const todosCollection = createCollection<Todo>(
212 * queryCollectionOptions({
213 * queryKey: ['todos'],
214 * queryFn: async () => fetch('/api/todos').then(r => r.json()),
215 * queryClient,
216 * getKey: (item) => item.id,
217 * })
218 * )
219 *
220 * @example
221 * // Schema inference
222 * const todosCollection = createCollection(
223 * queryCollectionOptions({
224 * queryKey: ['todos'],
225 * queryFn: async () => fetch('/api/todos').then(r => r.json()),
226 * queryClient,
227 * schema: todoSchema, // Type inferred from schema
228 * getKey: (item) => item.id,
229 * })
230 * )
231 *
232 * @example
233 * // With persistence handlers
234 * const todosCollection = createCollection(
235 * queryCollectionOptions({
236 * queryKey: ['todos'],
237 * queryFn: fetchTodos,
238 * queryClient,
239 * getKey: (item) => item.id,
240 * onInsert: async ({ transaction }) => {
241 * await api.createTodos(transaction.mutations.map(m => m.modified))
242 * },
243 * onUpdate: async ({ transaction }) => {
244 * await api.updateTodos(transaction.mutations)
245 * },
246 * onDelete: async ({ transaction }) => {
247 * await api.deleteTodos(transaction.mutations.map(m => m.key))
248 * }
249 * })
250 * )
251 */
252
253// Overload for when schema is provided
254export function queryCollectionOptions<
255 T extends StandardSchemaV1,
256 TError = unknown,
257 TQueryKey extends QueryKey = QueryKey,
258 TKey extends string | number = string | number,
259>(
260 config: QueryCollectionConfig<
261 InferSchemaOutput<T>,
262 (
263 context: QueryFunctionContext<any>
264 ) => Promise<Array<InferSchemaOutput<T>>>,
265 TError,
266 TQueryKey,
267 TKey,
268 T
269 > & {
270 schema: T
271 }
272): CollectionConfig<InferSchemaOutput<T>, TKey, T> & {
273 schema: T
274 utils: QueryCollectionUtils<
275 InferSchemaOutput<T>,
276 TKey,
277 InferSchemaInput<T>,
278 TError
279 >
280}
281
282// Overload for when no schema is provided
283export function queryCollectionOptions<
284 T extends object,
285 TError = unknown,
286 TQueryKey extends QueryKey = QueryKey,
287 TKey extends string | number = string | number,
288>(
289 config: QueryCollectionConfig<
290 T,
291 (context: QueryFunctionContext<any>) => Promise<Array<T>>,
292 TError,
293 TQueryKey,
294 TKey
295 > & {
296 schema?: never // prohibit schema
297 }
298): CollectionConfig<T, TKey> & {
299 schema?: never // no schema in the result
300 utils: QueryCollectionUtils<T, TKey, T, TError>
301}
302
303export function queryCollectionOptions(
304 config: QueryCollectionConfig<Record<string, unknown>>
305): CollectionConfig & {
306 utils: QueryCollectionUtils
307} {
308 const {
309 queryKey,
310 queryFn,
311 queryClient,
312 enabled,
313 refetchInterval,
314 retry,
315 retryDelay,
316 staleTime,
317 getKey,
318 onInsert,
319 onUpdate,
320 onDelete,
321 meta,
322 ...baseCollectionConfig
323 } = config
324
325 // Validate required parameters
326
327 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
328 if (!queryKey) {
329 throw new QueryKeyRequiredError()
330 }
331 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
332 if (!queryFn) {
333 throw new QueryFnRequiredError()
334 }
335
336 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
337 if (!queryClient) {
338 throw new QueryClientRequiredError()
339 }
340
341 if (!getKey) {
342 throw new GetKeyRequiredError()
343 }
344
345 /** The last error encountered by the query */
346 let lastError: any
347 /** The number of consecutive sync failures */
348 let errorCount = 0
349 /** The timestamp for when the query most recently returned the status as "error" */
350 let lastErrorUpdatedAt = 0
351
352 const internalSync: SyncConfig<any>[`sync`] = (params) => {
353 const { begin, write, commit, markReady, collection } = params
354
355 const observerOptions: QueryObserverOptions<
356 Array<any>,
357 any,
358 Array<any>,
359 Array<any>,
360 any
361 > = {
362 queryKey: queryKey,
363 queryFn: queryFn,
364 meta: meta,
365 enabled: enabled,
366 refetchInterval: refetchInterval,
367 retry: retry,
368 retryDelay: retryDelay,
369 staleTime: staleTime,
370 structuralSharing: true,
371 notifyOnChangeProps: `all`,
372 }
373
374 const localObserver = new QueryObserver<
375 Array<any>,
376 any,
377 Array<any>,
378 Array<any>,
379 any
380 >(queryClient, observerOptions)
381
382 type UpdateHandler = Parameters<typeof localObserver.subscribe>[0]
383 const handleUpdate: UpdateHandler = (result) => {
384 if (result.isSuccess) {
385 // Clear error state
386 lastError = undefined
387 errorCount = 0
388
389 const newItemsArray = result.data
390
391 if (
392 !Array.isArray(newItemsArray) ||
393 newItemsArray.some((item) => typeof item !== `object`)
394 ) {
395 console.error(
396 `[QueryCollection] queryFn did not return an array of objects. Skipping update.`,
397 newItemsArray
398 )
399 return
400 }
401
402 const currentSyncedItems: Map<string | number, any> = new Map(
403 collection._state.syncedData.entries()
404 )
405 const newItemsMap = new Map<string | number, any>()
406 newItemsArray.forEach((item) => {
407 const key = getKey(item)
408 newItemsMap.set(key, item)
409 })
410
411 begin()
412
413 // Helper function for shallow equality check of objects
414 const shallowEqual = (
415 obj1: Record<string, any>,
416 obj2: Record<string, any>
417 ): boolean => {
418 // Get all keys from both objects
419 const keys1 = Object.keys(obj1)
420 const keys2 = Object.keys(obj2)
421
422 // If number of keys is different, objects are not equal
423 if (keys1.length !== keys2.length) return false
424
425 // Check if all keys in obj1 have the same values in obj2
426 return keys1.every((key) => {
427 // Skip comparing functions and complex objects deeply
428 if (typeof obj1[key] === `function`) return true
429 return obj1[key] === obj2[key]
430 })
431 }
432
433 currentSyncedItems.forEach((oldItem, key) => {
434 const newItem = newItemsMap.get(key)
435 if (!newItem) {
436 write({ type: `delete`, value: oldItem })
437 } else if (
438 !shallowEqual(
439 oldItem as Record<string, any>,
440 newItem as Record<string, any>
441 )
442 ) {
443 // Only update if there are actual differences in the properties
444 write({ type: `update`, value: newItem })
445 }
446 })
447
448 newItemsMap.forEach((newItem, key) => {
449 if (!currentSyncedItems.has(key)) {
450 write({ type: `insert`, value: newItem })
451 }
452 })
453
454 commit()
455
456 // Mark collection as ready after first successful query result
457 markReady()
458 } else if (result.isError) {
459 if (result.errorUpdatedAt !== lastErrorUpdatedAt) {
460 lastError = result.error
461 errorCount++
462 lastErrorUpdatedAt = result.errorUpdatedAt
463 }
464
465 console.error(
466 `[QueryCollection] Error observing query ${String(queryKey)}:`,
467 result.error
468 )
469
470 // Mark collection as ready even on error to avoid blocking apps
471 markReady()
472 }
473 }
474
475 const actualUnsubscribeFn = localObserver.subscribe(handleUpdate)
476
477 // Ensure we process any existing query data (QueryObserver doesn't invoke its callback automatically with initial
478 // state)
479 handleUpdate(localObserver.getCurrentResult())
480
481 return async () => {
482 actualUnsubscribeFn()
483 await queryClient.cancelQueries({ queryKey })
484 queryClient.removeQueries({ queryKey })
485 }
486 }
487
488 /**
489 * Refetch the query data
490 * @returns Promise that resolves when the refetch is complete
491 */
492 const refetch: RefetchFn = (opts) => {
493 return queryClient.refetchQueries(
494 {
495 queryKey: queryKey,
496 },
497 {
498 throwOnError: opts?.throwOnError,
499 }
500 )
501 }
502
503 // Create write context for manual write operations
504 let writeContext: {
505 collection: any
506 queryClient: QueryClient
507 queryKey: Array<unknown>
508 getKey: (item: any) => string | number
509 begin: () => void
510 write: (message: Omit<ChangeMessage<any>, `key`>) => void
511 commit: () => void
512 } | null = null
513
514 // Enhanced internalSync that captures write functions for manual use
515 const enhancedInternalSync: SyncConfig<any>[`sync`] = (params) => {
516 const { begin, write, commit, collection } = params
517
518 // Store references for manual write operations
519 writeContext = {
520 collection,
521 queryClient,
522 queryKey: queryKey as unknown as Array<unknown>,
523 getKey: getKey as (item: any) => string | number,
524 begin,
525 write,
526 commit,
527 }
528
529 // Call the original internalSync logic
530 return internalSync(params)
531 }
532
533 // Create write utils using the manual-sync module
534 const writeUtils = createWriteUtils<any, string | number, any>(
535 () => writeContext
536 )
537
538 // Create wrapper handlers for direct persistence operations that handle refetching
539 const wrappedOnInsert = onInsert
540 ? async (params: InsertMutationFnParams<any>) => {
541 const handlerResult = (await onInsert(params)) ?? {}
542 const shouldRefetch =
543 (handlerResult as { refetch?: boolean }).refetch !== false
544
545 if (shouldRefetch) {
546 await refetch()
547 }
548
549 return handlerResult
550 }
551 : undefined
552
553 const wrappedOnUpdate = onUpdate
554 ? async (params: UpdateMutationFnParams<any>) => {
555 const handlerResult = (await onUpdate(params)) ?? {}
556 const shouldRefetch =
557 (handlerResult as { refetch?: boolean }).refetch !== false
558
559 if (shouldRefetch) {
560 await refetch()
561 }
562
563 return handlerResult
564 }
565 : undefined
566
567 const wrappedOnDelete = onDelete
568 ? async (params: DeleteMutationFnParams<any>) => {
569 const handlerResult = (await onDelete(params)) ?? {}
570 const shouldRefetch =
571 (handlerResult as { refetch?: boolean }).refetch !== false
572
573 if (shouldRefetch) {
574 await refetch()
575 }
576
577 return handlerResult
578 }
579 : undefined
580
581 return {
582 ...baseCollectionConfig,
583 getKey,
584 sync: { sync: enhancedInternalSync },
585 onInsert: wrappedOnInsert,
586 onUpdate: wrappedOnUpdate,
587 onDelete: wrappedOnDelete,
588 utils: {
589 refetch,
590 ...writeUtils,
591 lastError: () => lastError,
592 isError: () => !!lastError,
593 errorCount: () => errorCount,
594 clearError: () => {
595 lastError = undefined
596 errorCount = 0
597 lastErrorUpdatedAt = 0
598 return refetch({ throwOnError: true })
599 },
600 },
601 }
602}