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 (context: QueryFunctionContext<any>) => Promise<any> = (
56 context: QueryFunctionContext<any>
57 ) => Promise<any>,
58 TError = unknown,
59 TQueryKey extends QueryKey = QueryKey,
60 TKey extends string | number = string | number,
61 TSchema extends StandardSchemaV1 = never,
62 TQueryData = Awaited<ReturnType<TQueryFn>>,
63> extends BaseCollectionConfig<T, TKey, TSchema> {
64 /** The query key used by TanStack Query to identify this query */
65 queryKey: TQueryKey
66 /** Function that fetches data from the server. Must return the complete collection state */
67 queryFn: TQueryFn extends (
68 context: QueryFunctionContext<TQueryKey>
69 ) => Promise<Array<any>>
70 ? (context: QueryFunctionContext<TQueryKey>) => Promise<Array<T>>
71 : TQueryFn
72 /* Function that extracts array items from wrapped API responses (e.g metadata, pagination) */
73 select?: (data: TQueryData) => Array<T>
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 * @example
253 * // The select option extracts the items array from a response with metadata
254 * const todosCollection = createCollection(
255 * queryCollectionOptions({
256 * queryKey: ['todos'],
257 * queryFn: async () => fetch('/api/todos').then(r => r.json()),
258 * select: (data) => data.items, // Extract the array of items
259 * queryClient,
260 * schema: todoSchema,
261 * getKey: (item) => item.id,
262 * })
263 * )
264 */
265// Overload for when schema is provided and select present
266export function queryCollectionOptions<
267 T extends StandardSchemaV1,
268 TQueryFn extends (context: QueryFunctionContext<any>) => Promise<any>,
269 TError = unknown,
270 TQueryKey extends QueryKey = QueryKey,
271 TKey extends string | number = string | number,
272 TQueryData = Awaited<ReturnType<TQueryFn>>,
273>(
274 config: QueryCollectionConfig<
275 InferSchemaOutput<T>,
276 TQueryFn,
277 TError,
278 TQueryKey,
279 TKey,
280 T
281 > & {
282 schema: T
283 select: (data: TQueryData) => Array<InferSchemaInput<T>>
284 }
285): CollectionConfig<InferSchemaOutput<T>, TKey, T> & {
286 schema: T
287 utils: QueryCollectionUtils<
288 InferSchemaOutput<T>,
289 TKey,
290 InferSchemaInput<T>,
291 TError
292 >
293}
294
295// Overload for when no schema is provided and select present
296export function queryCollectionOptions<
297 T extends object,
298 TQueryFn extends (context: QueryFunctionContext<any>) => Promise<any> = (
299 context: QueryFunctionContext<any>
300 ) => Promise<any>,
301 TError = unknown,
302 TQueryKey extends QueryKey = QueryKey,
303 TKey extends string | number = string | number,
304 TQueryData = Awaited<ReturnType<TQueryFn>>,
305>(
306 config: QueryCollectionConfig<
307 T,
308 TQueryFn,
309 TError,
310 TQueryKey,
311 TKey,
312 never,
313 TQueryData
314 > & {
315 schema?: never // prohibit schema
316 select: (data: TQueryData) => Array<T>
317 }
318): CollectionConfig<T, TKey> & {
319 schema?: never // no schema in the result
320 utils: QueryCollectionUtils<T, TKey, T, TError>
321}
322
323// Overload for when schema is provided
324export function queryCollectionOptions<
325 T extends StandardSchemaV1,
326 TError = unknown,
327 TQueryKey extends QueryKey = QueryKey,
328 TKey extends string | number = string | number,
329>(
330 config: QueryCollectionConfig<
331 InferSchemaOutput<T>,
332 (
333 context: QueryFunctionContext<any>
334 ) => Promise<Array<InferSchemaOutput<T>>>,
335 TError,
336 TQueryKey,
337 TKey,
338 T
339 > & {
340 schema: T
341 }
342): CollectionConfig<InferSchemaOutput<T>, TKey, T> & {
343 schema: T
344 utils: QueryCollectionUtils<
345 InferSchemaOutput<T>,
346 TKey,
347 InferSchemaInput<T>,
348 TError
349 >
350}
351
352// Overload for when no schema is provided
353export function queryCollectionOptions<
354 T extends object,
355 TError = unknown,
356 TQueryKey extends QueryKey = QueryKey,
357 TKey extends string | number = string | number,
358>(
359 config: QueryCollectionConfig<
360 T,
361 (context: QueryFunctionContext<any>) => Promise<Array<T>>,
362 TError,
363 TQueryKey,
364 TKey
365 > & {
366 schema?: never // prohibit schema
367 }
368): CollectionConfig<T, TKey> & {
369 schema?: never // no schema in the result
370 utils: QueryCollectionUtils<T, TKey, T, TError>
371}
372
373export function queryCollectionOptions(
374 config: QueryCollectionConfig<Record<string, unknown>>
375): CollectionConfig & {
376 utils: QueryCollectionUtils
377} {
378 const {
379 queryKey,
380 queryFn,
381 select,
382 queryClient,
383 enabled,
384 refetchInterval,
385 retry,
386 retryDelay,
387 staleTime,
388 getKey,
389 onInsert,
390 onUpdate,
391 onDelete,
392 meta,
393 ...baseCollectionConfig
394 } = config
395
396 // Validate required parameters
397
398 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
399 if (!queryKey) {
400 throw new QueryKeyRequiredError()
401 }
402 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
403 if (!queryFn) {
404 throw new QueryFnRequiredError()
405 }
406
407 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
408 if (!queryClient) {
409 throw new QueryClientRequiredError()
410 }
411
412 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
413 if (!getKey) {
414 throw new GetKeyRequiredError()
415 }
416
417 /** The last error encountered by the query */
418 let lastError: any
419 /** The number of consecutive sync failures */
420 let errorCount = 0
421 /** The timestamp for when the query most recently returned the status as "error" */
422 let lastErrorUpdatedAt = 0
423
424 const internalSync: SyncConfig<any>[`sync`] = (params) => {
425 const { begin, write, commit, markReady, collection } = params
426
427 const observerOptions: QueryObserverOptions<
428 Array<any>,
429 any,
430 Array<any>,
431 Array<any>,
432 any
433 > = {
434 queryKey: queryKey,
435 queryFn: queryFn,
436 meta: meta,
437 enabled: enabled,
438 refetchInterval: refetchInterval,
439 retry: retry,
440 retryDelay: retryDelay,
441 staleTime: staleTime,
442 structuralSharing: true,
443 notifyOnChangeProps: `all`,
444 }
445
446 const localObserver = new QueryObserver<
447 Array<any>,
448 any,
449 Array<any>,
450 Array<any>,
451 any
452 >(queryClient, observerOptions)
453
454 let isSubscribed = false
455 let actualUnsubscribeFn: (() => void) | null = null
456
457 type UpdateHandler = Parameters<typeof localObserver.subscribe>[0]
458 const handleQueryResult: UpdateHandler = (result) => {
459 if (result.isSuccess) {
460 // Clear error state
461 lastError = undefined
462 errorCount = 0
463
464 const rawData = result.data
465 const newItemsArray = select ? select(rawData) : rawData
466
467 if (
468 !Array.isArray(newItemsArray) ||
469 newItemsArray.some((item) => typeof item !== `object`)
470 ) {
471 const errorMessage = select
472 ? `@tanstack/query-db-collection: select() must return an array of objects. Got: ${typeof newItemsArray} for queryKey ${JSON.stringify(queryKey)}`
473 : `@tanstack/query-db-collection: queryFn must return an array of objects. Got: ${typeof newItemsArray} for queryKey ${JSON.stringify(queryKey)}`
474
475 console.error(errorMessage)
476 return
477 }
478
479 const currentSyncedItems: Map<string | number, any> = new Map(
480 collection._state.syncedData.entries()
481 )
482 const newItemsMap = new Map<string | number, any>()
483 newItemsArray.forEach((item) => {
484 const key = getKey(item)
485 newItemsMap.set(key, item)
486 })
487
488 begin()
489
490 // Helper function for shallow equality check of objects
491 const shallowEqual = (
492 obj1: Record<string, any>,
493 obj2: Record<string, any>
494 ): boolean => {
495 // Get all keys from both objects
496 const keys1 = Object.keys(obj1)
497 const keys2 = Object.keys(obj2)
498
499 // If number of keys is different, objects are not equal
500 if (keys1.length !== keys2.length) return false
501
502 // Check if all keys in obj1 have the same values in obj2
503 return keys1.every((key) => {
504 // Skip comparing functions and complex objects deeply
505 if (typeof obj1[key] === `function`) return true
506 return obj1[key] === obj2[key]
507 })
508 }
509
510 currentSyncedItems.forEach((oldItem, key) => {
511 const newItem = newItemsMap.get(key)
512 if (!newItem) {
513 write({ type: `delete`, value: oldItem })
514 } else if (
515 !shallowEqual(
516 oldItem as Record<string, any>,
517 newItem as Record<string, any>
518 )
519 ) {
520 // Only update if there are actual differences in the properties
521 write({ type: `update`, value: newItem })
522 }
523 })
524
525 newItemsMap.forEach((newItem, key) => {
526 if (!currentSyncedItems.has(key)) {
527 write({ type: `insert`, value: newItem })
528 }
529 })
530
531 commit()
532
533 // Mark collection as ready after first successful query result
534 markReady()
535 } else if (result.isError) {
536 if (result.errorUpdatedAt !== lastErrorUpdatedAt) {
537 lastError = result.error
538 errorCount++
539 lastErrorUpdatedAt = result.errorUpdatedAt
540 }
541
542 console.error(
543 `[QueryCollection] Error observing query ${String(queryKey)}:`,
544 result.error
545 )
546
547 // Mark collection as ready even on error to avoid blocking apps
548 markReady()
549 }
550 }
551
552 const subscribeToQuery = () => {
553 if (!isSubscribed) {
554 actualUnsubscribeFn = localObserver.subscribe(handleQueryResult)
555 isSubscribed = true
556 }
557 }
558
559 const unsubscribeFromQuery = () => {
560 if (isSubscribed && actualUnsubscribeFn) {
561 actualUnsubscribeFn()
562 actualUnsubscribeFn = null
563 isSubscribed = false
564 }
565 }
566
567 // Always subscribe when sync starts (this could be from preload(), startSync config, or first subscriber)
568 // We'll dynamically unsubscribe/resubscribe based on subscriber count to maintain staleTime behavior
569 subscribeToQuery()
570
571 // Set up event listener for subscriber changes
572 const unsubscribeFromCollectionEvents = collection.on(
573 `subscribers:change`,
574 ({ subscriberCount }) => {
575 if (subscriberCount > 0) {
576 subscribeToQuery()
577 } else if (subscriberCount === 0) {
578 unsubscribeFromQuery()
579 }
580 }
581 )
582
583 // Ensure we process any existing query data (QueryObserver doesn't invoke its callback automatically with initial
584 // state)
585 handleQueryResult(localObserver.getCurrentResult())
586
587 return async () => {
588 unsubscribeFromCollectionEvents()
589 unsubscribeFromQuery()
590 await queryClient.cancelQueries({ queryKey })
591 queryClient.removeQueries({ queryKey })
592 }
593 }
594
595 /**
596 * Refetch the query data
597 * @returns Promise that resolves when the refetch is complete
598 */
599 const refetch: RefetchFn = (opts) => {
600 return queryClient.refetchQueries(
601 {
602 queryKey: queryKey,
603 },
604 {
605 throwOnError: opts?.throwOnError,
606 }
607 )
608 }
609
610 // Create write context for manual write operations
611 let writeContext: {
612 collection: any
613 queryClient: QueryClient
614 queryKey: Array<unknown>
615 getKey: (item: any) => string | number
616 begin: () => void
617 write: (message: Omit<ChangeMessage<any>, `key`>) => void
618 commit: () => void
619 } | null = null
620
621 // Enhanced internalSync that captures write functions for manual use
622 const enhancedInternalSync: SyncConfig<any>[`sync`] = (params) => {
623 const { begin, write, commit, collection } = params
624
625 // Store references for manual write operations
626 writeContext = {
627 collection,
628 queryClient,
629 queryKey: queryKey as unknown as Array<unknown>,
630 getKey: getKey as (item: any) => string | number,
631 begin,
632 write,
633 commit,
634 }
635
636 // Call the original internalSync logic
637 return internalSync(params)
638 }
639
640 // Create write utils using the manual-sync module
641 const writeUtils = createWriteUtils<any, string | number, any>(
642 () => writeContext
643 )
644
645 // Create wrapper handlers for direct persistence operations that handle refetching
646 const wrappedOnInsert = onInsert
647 ? async (params: InsertMutationFnParams<any>) => {
648 const handlerResult = (await onInsert(params)) ?? {}
649 const shouldRefetch =
650 (handlerResult as { refetch?: boolean }).refetch !== false
651
652 if (shouldRefetch) {
653 await refetch()
654 }
655
656 return handlerResult
657 }
658 : undefined
659
660 const wrappedOnUpdate = onUpdate
661 ? async (params: UpdateMutationFnParams<any>) => {
662 const handlerResult = (await onUpdate(params)) ?? {}
663 const shouldRefetch =
664 (handlerResult as { refetch?: boolean }).refetch !== false
665
666 if (shouldRefetch) {
667 await refetch()
668 }
669
670 return handlerResult
671 }
672 : undefined
673
674 const wrappedOnDelete = onDelete
675 ? async (params: DeleteMutationFnParams<any>) => {
676 const handlerResult = (await onDelete(params)) ?? {}
677 const shouldRefetch =
678 (handlerResult as { refetch?: boolean }).refetch !== false
679
680 if (shouldRefetch) {
681 await refetch()
682 }
683
684 return handlerResult
685 }
686 : undefined
687
688 return {
689 ...baseCollectionConfig,
690 getKey,
691 sync: { sync: enhancedInternalSync },
692 onInsert: wrappedOnInsert,
693 onUpdate: wrappedOnUpdate,
694 onDelete: wrappedOnDelete,
695 utils: {
696 refetch,
697 ...writeUtils,
698 lastError: () => lastError,
699 isError: () => !!lastError,
700 errorCount: () => errorCount,
701 clearError: () => {
702 lastError = undefined
703 errorCount = 0
704 lastErrorUpdatedAt = 0
705 return refetch({ throwOnError: true })
706 },
707 },
708 }
709}