Open History to see the last commit
1import { QueryObserver, hashKey } from '@tanstack/query-core'
2import { deepEquals } from '@tanstack/db'
3import {
4 GetKeyRequiredError,
5 QueryClientRequiredError,
6 QueryFnRequiredError,
7 QueryKeyRequiredError,
8} from './errors'
9import { createWriteUtils } from './manual-sync'
10import { serializeLoadSubsetOptions } from './serialization'
11import type {
12 BaseCollectionConfig,
13 ChangeMessage,
14 CollectionConfig,
15 DeleteMutationFnParams,
16 InsertMutationFnParams,
17 LoadSubsetOptions,
18 SyncConfig,
19 UpdateMutationFnParams,
20 UtilsRecord,
21} from '@tanstack/db'
22import type {
23 FetchStatus,
24 QueryClient,
25 QueryFunctionContext,
26 QueryKey,
27 QueryObserverOptions,
28 QueryObserverResult,
29} from '@tanstack/query-core'
30import type { StandardSchemaV1 } from '@standard-schema/spec'
31
32// Re-export for external use
33export type { SyncOperation } from './manual-sync'
34
35// Schema output type inference helper (matches electric.ts pattern)
36type InferSchemaOutput<T> = T extends StandardSchemaV1
37 ? StandardSchemaV1.InferOutput<T> extends object
38 ? StandardSchemaV1.InferOutput<T>
39 : Record<string, unknown>
40 : Record<string, unknown>
41
42// Schema input type inference helper (matches electric.ts pattern)
43type InferSchemaInput<T> = T extends StandardSchemaV1
44 ? StandardSchemaV1.InferInput<T> extends object
45 ? StandardSchemaV1.InferInput<T>
46 : Record<string, unknown>
47 : Record<string, unknown>
48
49type TQueryKeyBuilder<TQueryKey> = (opts: LoadSubsetOptions) => TQueryKey
50
51/**
52 * Configuration options for creating a Query Collection
53 * @template T - The explicit type of items stored in the collection
54 * @template TQueryFn - The queryFn type
55 * @template TError - The type of errors that can occur during queries
56 * @template TQueryKey - The type of the query key
57 * @template TKey - The type of the item keys
58 * @template TSchema - The schema type for validation
59 */
60export interface QueryCollectionConfig<
61 T extends object = object,
62 TQueryFn extends (context: QueryFunctionContext<any>) => any = (
63 context: QueryFunctionContext<any>,
64 ) => any,
65 TError = unknown,
66 TQueryKey extends QueryKey = QueryKey,
67 TKey extends string | number = string | number,
68 TSchema extends StandardSchemaV1 = never,
69 TQueryData = Awaited<ReturnType<TQueryFn>>,
70> extends BaseCollectionConfig<T, TKey, TSchema> {
71 /** The query key used by TanStack Query to identify this query */
72 queryKey: TQueryKey | TQueryKeyBuilder<TQueryKey>
73 /** Function that fetches data from the server. Must return the complete collection state */
74 queryFn: TQueryFn extends (
75 context: QueryFunctionContext<TQueryKey>,
76 ) => Promise<Array<any>> | Array<any>
77 ? (context: QueryFunctionContext<TQueryKey>) => Promise<Array<T>> | Array<T>
78 : TQueryFn
79 /* Function that extracts array items from wrapped API responses (e.g metadata, pagination) */
80 select?: (data: TQueryData) => Array<T>
81 /** The TanStack Query client instance */
82 queryClient: QueryClient
83
84 // Query-specific options
85 /** Whether the query should automatically run (default: true) */
86 enabled?: QueryObserverOptions<
87 TQueryData,
88 TError,
89 Array<T>,
90 TQueryData,
91 TQueryKey
92 >[`enabled`]
93 refetchInterval?: QueryObserverOptions<
94 TQueryData,
95 TError,
96 Array<T>,
97 TQueryData,
98 TQueryKey
99 >[`refetchInterval`]
100 retry?: QueryObserverOptions<
101 TQueryData,
102 TError,
103 Array<T>,
104 TQueryData,
105 TQueryKey
106 >[`retry`]
107 retryDelay?: QueryObserverOptions<
108 TQueryData,
109 TError,
110 Array<T>,
111 TQueryData,
112 TQueryKey
113 >[`retryDelay`]
114 staleTime?: QueryObserverOptions<
115 TQueryData,
116 TError,
117 Array<T>,
118 TQueryData,
119 TQueryKey
120 >[`staleTime`]
121
122 /**
123 * Metadata to pass to the query.
124 * Available in queryFn via context.meta
125 *
126 * @example
127 * // Using meta for error context
128 * queryFn: async (context) => {
129 * try {
130 * return await api.getTodos(userId)
131 * } catch (error) {
132 * // Use meta for better error messages
133 * throw new Error(
134 * context.meta?.errorMessage || 'Failed to load todos'
135 * )
136 * }
137 * },
138 * meta: {
139 * errorMessage: `Failed to load todos for user ${userId}`
140 * }
141 */
142 meta?: Record<string, unknown>
143}
144
145/**
146 * Type for the refetch utility function
147 * Returns the QueryObserverResult from TanStack Query
148 */
149export type RefetchFn = (opts?: {
150 throwOnError?: boolean
151}) => Promise<Array<QueryObserverResult<any, any> | void>>
152
153/**
154 * Utility methods available on Query Collections for direct writes and manual operations.
155 * Direct writes bypass the normal query/mutation flow and write directly to the synced data store.
156 * @template TItem - The type of items stored in the collection
157 * @template TKey - The type of the item keys
158 * @template TInsertInput - The type accepted for insert operations
159 * @template TError - The type of errors that can occur during queries
160 */
161export interface QueryCollectionUtils<
162 TItem extends object = Record<string, unknown>,
163 TKey extends string | number = string | number,
164 TInsertInput extends object = TItem,
165 TError = unknown,
166> extends UtilsRecord {
167 /** Manually trigger a refetch of the query */
168 refetch: RefetchFn
169 /** Insert one or more items directly into the synced data store without triggering a query refetch or optimistic update */
170 writeInsert: (data: TInsertInput | Array<TInsertInput>) => void
171 /** Update one or more items directly in the synced data store without triggering a query refetch or optimistic update */
172 writeUpdate: (updates: Partial<TItem> | Array<Partial<TItem>>) => void
173 /** Delete one or more items directly from the synced data store without triggering a query refetch or optimistic update */
174 writeDelete: (keys: TKey | Array<TKey>) => void
175 /** Insert or update one or more items directly in the synced data store without triggering a query refetch or optimistic update */
176 writeUpsert: (data: Partial<TItem> | Array<Partial<TItem>>) => void
177 /** Execute multiple write operations as a single atomic batch to the synced data store */
178 writeBatch: (callback: () => void) => void
179
180 // Query Observer State (getters)
181 /** Get the last error encountered by the query (if any); reset on success */
182 lastError: TError | undefined
183 /** Check if the collection is in an error state */
184 isError: boolean
185 /**
186 * Get the number of consecutive sync failures.
187 * Incremented only when query fails completely (not per retry attempt); reset on success.
188 */
189 errorCount: number
190 /** Check if query is currently fetching (initial or background) */
191 isFetching: boolean
192 /** Check if query is refetching in background (not initial fetch) */
193 isRefetching: boolean
194 /** Check if query is loading for the first time (no data yet) */
195 isLoading: boolean
196 /** Get timestamp of last successful data update (in milliseconds) */
197 dataUpdatedAt: number
198 /** Get current fetch status */
199 fetchStatus: `fetching` | `paused` | `idle`
200
201 /**
202 * Clear the error state and trigger a refetch of the query
203 * @returns Promise that resolves when the refetch completes successfully
204 * @throws Error if the refetch fails
205 */
206 clearError: () => Promise<void>
207}
208
209/**
210 * Internal state object for tracking query observer and errors
211 */
212interface QueryCollectionState {
213 lastError: any
214 errorCount: number
215 lastErrorUpdatedAt: number
216 observers: Map<
217 string,
218 QueryObserver<Array<any>, any, Array<any>, Array<any>, any>
219 >
220}
221
222/**
223 * Implementation class for QueryCollectionUtils with explicit dependency injection
224 * for better testability and architectural clarity
225 */
226class QueryCollectionUtilsImpl {
227 private state: QueryCollectionState
228 private refetchFn: RefetchFn
229
230 // Write methods
231 public refetch: RefetchFn
232 public writeInsert: any
233 public writeUpdate: any
234 public writeDelete: any
235 public writeUpsert: any
236 public writeBatch: any
237
238 constructor(
239 state: QueryCollectionState,
240 refetch: RefetchFn,
241 writeUtils: ReturnType<typeof createWriteUtils>,
242 ) {
243 this.state = state
244 this.refetchFn = refetch
245
246 // Initialize methods to use passed dependencies
247 this.refetch = refetch
248 this.writeInsert = writeUtils.writeInsert
249 this.writeUpdate = writeUtils.writeUpdate
250 this.writeDelete = writeUtils.writeDelete
251 this.writeUpsert = writeUtils.writeUpsert
252 this.writeBatch = writeUtils.writeBatch
253 }
254
255 public async clearError() {
256 this.state.lastError = undefined
257 this.state.errorCount = 0
258 this.state.lastErrorUpdatedAt = 0
259 await this.refetchFn({ throwOnError: true })
260 }
261
262 // Getters for error state
263 public get lastError() {
264 return this.state.lastError
265 }
266
267 public get isError() {
268 return !!this.state.lastError
269 }
270
271 public get errorCount() {
272 return this.state.errorCount
273 }
274
275 // Getters for QueryObserver state
276 public get isFetching() {
277 // check if any observer is fetching
278 return Array.from(this.state.observers.values()).some(
279 (observer) => observer.getCurrentResult().isFetching,
280 )
281 }
282
283 public get isRefetching() {
284 // check if any observer is refetching
285 return Array.from(this.state.observers.values()).some(
286 (observer) => observer.getCurrentResult().isRefetching,
287 )
288 }
289
290 public get isLoading() {
291 // check if any observer is loading
292 return Array.from(this.state.observers.values()).some(
293 (observer) => observer.getCurrentResult().isLoading,
294 )
295 }
296
297 public get dataUpdatedAt() {
298 // compute the max dataUpdatedAt of all observers
299 return Math.max(
300 0,
301 ...Array.from(this.state.observers.values()).map(
302 (observer) => observer.getCurrentResult().dataUpdatedAt,
303 ),
304 )
305 }
306
307 public get fetchStatus(): Array<FetchStatus> {
308 return Array.from(this.state.observers.values()).map(
309 (observer) => observer.getCurrentResult().fetchStatus,
310 )
311 }
312}
313
314/**
315 * Creates query collection options for use with a standard Collection.
316 * This integrates TanStack Query with TanStack DB for automatic synchronization.
317 *
318 * Supports automatic type inference following the priority order:
319 * 1. Schema inference (highest priority)
320 * 2. QueryFn return type inference (second priority)
321 *
322 * @template T - Type of the schema if a schema is provided otherwise it is the type of the values returned by the queryFn
323 * @template TError - The type of errors that can occur during queries
324 * @template TQueryKey - The type of the query key
325 * @template TKey - The type of the item keys
326 * @param config - Configuration options for the Query collection
327 * @returns Collection options with utilities for direct writes and manual operations
328 *
329 * @example
330 * // Type inferred from queryFn return type (NEW!)
331 * const todosCollection = createCollection(
332 * queryCollectionOptions({
333 * queryKey: ['todos'],
334 * queryFn: async () => {
335 * const response = await fetch('/api/todos')
336 * return response.json() as Todo[] // Type automatically inferred!
337 * },
338 * queryClient,
339 * getKey: (item) => item.id, // item is typed as Todo
340 * })
341 * )
342 *
343 * @example
344 * // Explicit type
345 * const todosCollection = createCollection<Todo>(
346 * queryCollectionOptions({
347 * queryKey: ['todos'],
348 * queryFn: async () => fetch('/api/todos').then(r => r.json()),
349 * queryClient,
350 * getKey: (item) => item.id,
351 * })
352 * )
353 *
354 * @example
355 * // Schema inference
356 * const todosCollection = createCollection(
357 * queryCollectionOptions({
358 * queryKey: ['todos'],
359 * queryFn: async () => fetch('/api/todos').then(r => r.json()),
360 * queryClient,
361 * schema: todoSchema, // Type inferred from schema
362 * getKey: (item) => item.id,
363 * })
364 * )
365 *
366 * @example
367 * // With persistence handlers
368 * const todosCollection = createCollection(
369 * queryCollectionOptions({
370 * queryKey: ['todos'],
371 * queryFn: fetchTodos,
372 * queryClient,
373 * getKey: (item) => item.id,
374 * onInsert: async ({ transaction }) => {
375 * await api.createTodos(transaction.mutations.map(m => m.modified))
376 * },
377 * onUpdate: async ({ transaction }) => {
378 * await api.updateTodos(transaction.mutations)
379 * },
380 * onDelete: async ({ transaction }) => {
381 * await api.deleteTodos(transaction.mutations.map(m => m.key))
382 * }
383 * })
384 * )
385 *
386 * @example
387 * // The select option extracts the items array from a response with metadata
388 * const todosCollection = createCollection(
389 * queryCollectionOptions({
390 * queryKey: ['todos'],
391 * queryFn: async () => fetch('/api/todos').then(r => r.json()),
392 * select: (data) => data.items, // Extract the array of items
393 * queryClient,
394 * schema: todoSchema,
395 * getKey: (item) => item.id,
396 * })
397 * )
398 */
399// Overload for when schema is provided and select present
400export function queryCollectionOptions<
401 T extends StandardSchemaV1,
402 TQueryFn extends (context: QueryFunctionContext<any>) => any,
403 TError = unknown,
404 TQueryKey extends QueryKey = QueryKey,
405 TKey extends string | number = string | number,
406 TQueryData = Awaited<ReturnType<TQueryFn>>,
407>(
408 config: QueryCollectionConfig<
409 InferSchemaOutput<T>,
410 TQueryFn,
411 TError,
412 TQueryKey,
413 TKey,
414 T
415 > & {
416 schema: T
417 select: (data: TQueryData) => Array<InferSchemaInput<T>>
418 },
419): CollectionConfig<
420 InferSchemaOutput<T>,
421 TKey,
422 T,
423 QueryCollectionUtils<InferSchemaOutput<T>, TKey, InferSchemaInput<T>, TError>
424> & {
425 schema: T
426 utils: QueryCollectionUtils<
427 InferSchemaOutput<T>,
428 TKey,
429 InferSchemaInput<T>,
430 TError
431 >
432}
433
434// Overload for when no schema is provided and select present
435export function queryCollectionOptions<
436 T extends object,
437 TQueryFn extends (context: QueryFunctionContext<any>) => any = (
438 context: QueryFunctionContext<any>,
439 ) => any,
440 TError = unknown,
441 TQueryKey extends QueryKey = QueryKey,
442 TKey extends string | number = string | number,
443 TQueryData = Awaited<ReturnType<TQueryFn>>,
444>(
445 config: QueryCollectionConfig<
446 T,
447 TQueryFn,
448 TError,
449 TQueryKey,
450 TKey,
451 never,
452 TQueryData
453 > & {
454 schema?: never // prohibit schema
455 select: (data: TQueryData) => Array<T>
456 },
457): CollectionConfig<
458 T,
459 TKey,
460 never,
461 QueryCollectionUtils<T, TKey, T, TError>
462> & {
463 schema?: never // no schema in the result
464 utils: QueryCollectionUtils<T, TKey, T, TError>
465}
466
467// Overload for when schema is provided
468export function queryCollectionOptions<
469 T extends StandardSchemaV1,
470 TError = unknown,
471 TQueryKey extends QueryKey = QueryKey,
472 TKey extends string | number = string | number,
473>(
474 config: QueryCollectionConfig<
475 InferSchemaOutput<T>,
476 (
477 context: QueryFunctionContext<any>,
478 ) => Array<InferSchemaOutput<T>> | Promise<Array<InferSchemaOutput<T>>>,
479 TError,
480 TQueryKey,
481 TKey,
482 T
483 > & {
484 schema: T
485 },
486): CollectionConfig<
487 InferSchemaOutput<T>,
488 TKey,
489 T,
490 QueryCollectionUtils<InferSchemaOutput<T>, TKey, InferSchemaInput<T>, TError>
491> & {
492 schema: T
493 utils: QueryCollectionUtils<
494 InferSchemaOutput<T>,
495 TKey,
496 InferSchemaInput<T>,
497 TError
498 >
499}
500
501// Overload for when no schema is provided
502export function queryCollectionOptions<
503 T extends object,
504 TError = unknown,
505 TQueryKey extends QueryKey = QueryKey,
506 TKey extends string | number = string | number,
507>(
508 config: QueryCollectionConfig<
509 T,
510 (context: QueryFunctionContext<any>) => Array<T> | Promise<Array<T>>,
511 TError,
512 TQueryKey,
513 TKey
514 > & {
515 schema?: never // prohibit schema
516 },
517): CollectionConfig<
518 T,
519 TKey,
520 never,
521 QueryCollectionUtils<T, TKey, T, TError>
522> & {
523 schema?: never // no schema in the result
524 utils: QueryCollectionUtils<T, TKey, T, TError>
525}
526
527export function queryCollectionOptions(
528 config: QueryCollectionConfig<
529 Record<string, unknown>,
530 (context: QueryFunctionContext<any>) => any
531 >,
532): CollectionConfig<
533 Record<string, unknown>,
534 string | number,
535 never,
536 QueryCollectionUtils
537> & {
538 utils: QueryCollectionUtils
539} {
540 const {
541 queryKey,
542 queryFn,
543 select,
544 queryClient,
545 enabled,
546 refetchInterval,
547 retry,
548 retryDelay,
549 staleTime,
550 getKey,
551 onInsert,
552 onUpdate,
553 onDelete,
554 meta,
555 ...baseCollectionConfig
556 } = config
557
558 // Default to eager sync mode if not provided
559 const syncMode = baseCollectionConfig.syncMode ?? `eager`
560
561 // Validate required parameters
562
563 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
564 if (!queryKey) {
565 throw new QueryKeyRequiredError()
566 }
567
568 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
569 if (!queryFn) {
570 throw new QueryFnRequiredError()
571 }
572
573 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
574 if (!queryClient) {
575 throw new QueryClientRequiredError()
576 }
577
578 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
579 if (!getKey) {
580 throw new GetKeyRequiredError()
581 }
582
583 /** State object to hold error tracking and observer reference */
584 const state: QueryCollectionState = {
585 lastError: undefined as any,
586 errorCount: 0,
587 lastErrorUpdatedAt: 0,
588 observers: new Map<
589 string,
590 QueryObserver<Array<any>, any, Array<any>, Array<any>, any>
591 >(),
592 }
593
594 // hashedQueryKey → queryKey
595 const hashToQueryKey = new Map<string, QueryKey>()
596
597 // queryKey → Set<RowKey>
598 const queryToRows = new Map<string, Set<string | number>>()
599
600 // RowKey → Set<queryKey>
601 const rowToQueries = new Map<string | number, Set<string>>()
602
603 // queryKey → QueryObserver's unsubscribe function
604 const unsubscribes = new Map<string, () => void>()
605
606 // queryKey → reference count (how many loadSubset calls are active)
607 // Reference counting for QueryObserver lifecycle management
608 // =========================================================
609 // Tracks how many live query subscriptions are using each QueryObserver.
610 // Multiple live queries with identical predicates share the same QueryObserver for efficiency.
611 //
612 // Lifecycle:
613 // - Increment: when createQueryFromOpts creates or reuses an observer
614 // - Decrement: when subscription.unsubscribe() passes predicates to collection._sync.unloadSubset()
615 // - Reset: when cleanupQuery() is triggered by TanStack Query's cache GC
616 //
617 // When refcount reaches 0, unloadSubset():
618 // 1. Computes the same queryKey from the predicates
619 // 2. Uses existing machinery (queryToRows map) to find rows that query loaded
620 // 3. Decrements refcount and GCs rows where count reaches 0
621 const queryRefCounts = new Map<string, number>()
622
623 // Helper function to add a row to the internal state
624 const addRow = (rowKey: string | number, hashedQueryKey: string) => {
625 const rowToQueriesSet = rowToQueries.get(rowKey) || new Set()
626 rowToQueriesSet.add(hashedQueryKey)
627 rowToQueries.set(rowKey, rowToQueriesSet)
628
629 const queryToRowsSet = queryToRows.get(hashedQueryKey) || new Set()
630 queryToRowsSet.add(rowKey)
631 queryToRows.set(hashedQueryKey, queryToRowsSet)
632 }
633
634 // Helper function to remove a row from the internal state
635 const removeRow = (rowKey: string | number, hashedQuerKey: string) => {
636 const rowToQueriesSet = rowToQueries.get(rowKey) || new Set()
637 rowToQueriesSet.delete(hashedQuerKey)
638 rowToQueries.set(rowKey, rowToQueriesSet)
639
640 const queryToRowsSet = queryToRows.get(hashedQuerKey) || new Set()
641 queryToRowsSet.delete(rowKey)
642 queryToRows.set(hashedQuerKey, queryToRowsSet)
643
644 return rowToQueriesSet.size === 0
645 }
646
647 const internalSync: SyncConfig<any>[`sync`] = (params) => {
648 const { begin, write, commit, markReady, collection } = params
649
650 // Track whether sync has been started
651 let syncStarted = false
652
653 /**
654 * Generate a consistent query key from LoadSubsetOptions.
655 * CRITICAL: Must use identical logic in both createQueryFromOpts and unloadSubset
656 * so that refcount increment/decrement operations target the same hashedQueryKey.
657 * Inconsistent keys would cause refcount leaks and prevent proper cleanup.
658 */
659 const generateQueryKeyFromOptions = (opts: LoadSubsetOptions): QueryKey => {
660 if (typeof queryKey === `function`) {
661 // Function-based queryKey: use it to build the key from opts
662 return queryKey(opts)
663 } else if (syncMode === `on-demand`) {
664 // Static queryKey in on-demand mode: automatically append serialized predicates
665 // to create separate cache entries for different predicate combinations
666 const serialized = serializeLoadSubsetOptions(opts)
667 return serialized !== undefined ? [...queryKey, serialized] : queryKey
668 } else {
669 // Static queryKey in eager mode: use as-is
670 return queryKey
671 }
672 }
673
674 const createQueryFromOpts = (
675 opts: LoadSubsetOptions = {},
676 queryFunction: typeof queryFn = queryFn,
677 ): true | Promise<void> => {
678 // Generate key using common function
679 const key = generateQueryKeyFromOptions(opts)
680 const hashedQueryKey = hashKey(key)
681 const extendedMeta = { ...meta, loadSubsetOptions: opts }
682
683 if (state.observers.has(hashedQueryKey)) {
684 // We already have a query for this queryKey
685 // Increment reference count since another consumer is using this observer
686 queryRefCounts.set(
687 hashedQueryKey,
688 (queryRefCounts.get(hashedQueryKey) || 0) + 1,
689 )
690
691 // Get the current result and return based on its state
692 const observer = state.observers.get(hashedQueryKey)!
693 const currentResult = observer.getCurrentResult()
694
695 if (currentResult.isSuccess) {
696 // Data is already available, return true synchronously
697 return true
698 } else if (currentResult.isError) {
699 // Error already occurred, reject immediately
700 return Promise.reject(currentResult.error)
701 } else {
702 // Check QueryClient cache directly - observer's getCurrentResult() may show
703 // a loading state even when data exists in cache. This happens because observer
704 // state can lag behind the QueryClient cache during unsubscribe/resubscribe
705 // cycles (e.g., when a live query is cleaned up and recreated).
706 const cachedData = queryClient.getQueryData(key)
707 if (cachedData !== undefined) {
708 return true
709 }
710
711 // Query is still loading, wait for the first result
712 return new Promise<void>((resolve, reject) => {
713 const unsubscribe = observer.subscribe((result) => {
714 // Use a microtask in case `subscribe` is called synchronously, before `unsubscribe` is initialized
715 queueMicrotask(() => {
716 if (result.isSuccess) {
717 unsubscribe()
718 resolve()
719 } else if (result.isError) {
720 unsubscribe()
721 reject(result.error)
722 }
723 })
724 })
725 })
726 }
727 }
728
729 const observerOptions: QueryObserverOptions<
730 Array<any>,
731 any,
732 Array<any>,
733 Array<any>,
734 any
735 > = {
736 queryKey: key,
737 queryFn: queryFunction,
738 meta: extendedMeta,
739 structuralSharing: true,
740 notifyOnChangeProps: `all`,
741
742 // Only include options that are explicitly defined to allow QueryClient defaultOptions to be used
743 ...(enabled !== undefined && { enabled }),
744 ...(refetchInterval !== undefined && { refetchInterval }),
745 ...(retry !== undefined && { retry }),
746 ...(retryDelay !== undefined && { retryDelay }),
747 ...(staleTime !== undefined && { staleTime }),
748 }
749
750 const localObserver = new QueryObserver<
751 Array<any>,
752 any,
753 Array<any>,
754 Array<any>,
755 any
756 >(queryClient, observerOptions)
757
758 hashToQueryKey.set(hashedQueryKey, key)
759 state.observers.set(hashedQueryKey, localObserver)
760
761 // Increment reference count for this query
762 queryRefCounts.set(
763 hashedQueryKey,
764 (queryRefCounts.get(hashedQueryKey) || 0) + 1,
765 )
766
767 // Check if data already exists in QueryClient cache (persisted within gcTime from
768 // a previous observer). This avoids creating unnecessary promises and subscription
769 // delays when recreating an observer for data that's already cached.
770 const cachedData = queryClient.getQueryData(key)
771 if (cachedData !== undefined) {
772 // Still subscribe if sync is active so we receive future updates
773 if (syncStarted || collection.subscriberCount > 0) {
774 subscribeToQuery(localObserver, hashedQueryKey)
775 }
776 return true
777 }
778
779 // Create a promise that resolves when the query result is first available
780 const readyPromise = new Promise<void>((resolve, reject) => {
781 const unsubscribe = localObserver.subscribe((result) => {
782 // Use a microtask in case `subscribe` is called synchronously, before `unsubscribe` is initialized
783 queueMicrotask(() => {
784 if (result.isSuccess) {
785 unsubscribe()
786 resolve()
787 } else if (result.isError) {
788 unsubscribe()
789 reject(result.error)
790 }
791 })
792 })
793 })
794
795 // If sync has started or there are subscribers to the collection, subscribe to the query straight away
796 // This creates the main subscription that handles data updates
797 if (syncStarted || collection.subscriberCount > 0) {
798 subscribeToQuery(localObserver, hashedQueryKey)
799 }
800
801 return readyPromise
802 }
803
804 type UpdateHandler = Parameters<QueryObserver[`subscribe`]>[0]
805
806 // eslint-disable-next-line no-shadow
807 const makeQueryResultHandler = (queryKey: QueryKey) => {
808 const hashedQueryKey = hashKey(queryKey)
809 const handleQueryResult: UpdateHandler = (result) => {
810 if (result.isSuccess) {
811 // Clear error state
812 state.lastError = undefined
813 state.errorCount = 0
814
815 const rawData = result.data
816 const newItemsArray = select ? select(rawData) : rawData
817
818 if (
819 !Array.isArray(newItemsArray) ||
820 newItemsArray.some((item) => typeof item !== `object`)
821 ) {
822 const errorMessage = select
823 ? `@tanstack/query-db-collection: select() must return an array of objects. Got: ${typeof newItemsArray} for queryKey ${JSON.stringify(queryKey)}`
824 : `@tanstack/query-db-collection: queryFn must return an array of objects. Got: ${typeof newItemsArray} for queryKey ${JSON.stringify(queryKey)}`
825
826 console.error(errorMessage)
827 return
828 }
829
830 const currentSyncedItems: Map<string | number, any> = new Map(
831 collection._state.syncedData.entries(),
832 )
833 const newItemsMap = new Map<string | number, any>()
834 newItemsArray.forEach((item) => {
835 const key = getKey(item)
836 newItemsMap.set(key, item)
837 })
838
839 begin()
840
841 currentSyncedItems.forEach((oldItem, key) => {
842 const newItem = newItemsMap.get(key)
843 if (!newItem) {
844 const needToRemove = removeRow(key, hashedQueryKey) // returns true if the row is no longer referenced by any queries
845 if (needToRemove) {
846 write({ type: `delete`, value: oldItem })
847 }
848 } else if (!deepEquals(oldItem, newItem)) {
849 // Only update if there are actual differences in the properties
850 write({ type: `update`, value: newItem })
851 }
852 })
853
854 newItemsMap.forEach((newItem, key) => {
855 addRow(key, hashedQueryKey)
856 if (!currentSyncedItems.has(key)) {
857 write({ type: `insert`, value: newItem })
858 }
859 })
860
861 commit()
862
863 // Mark collection as ready after first successful query result
864 markReady()
865 } else if (result.isError) {
866 const isNewError =
867 result.errorUpdatedAt !== state.lastErrorUpdatedAt ||
868 result.error !== state.lastError
869 if (isNewError) {
870 state.lastError = result.error
871 state.errorCount++
872 state.lastErrorUpdatedAt = result.errorUpdatedAt
873 }
874
875 console.error(
876 `[QueryCollection] Error observing query ${String(queryKey)}:`,
877 result.error,
878 )
879
880 // Mark collection as ready even on error to avoid blocking apps
881 markReady()
882 }
883 }
884 return handleQueryResult
885 }
886
887 const isSubscribed = (hashedQueryKey: string) => {
888 return unsubscribes.has(hashedQueryKey)
889 }
890
891 const subscribeToQuery = (
892 observer: QueryObserver<Array<any>, any, Array<any>, Array<any>, any>,
893 hashedQueryKey: string,
894 ) => {
895 if (!isSubscribed(hashedQueryKey)) {
896 const cachedQueryKey = hashToQueryKey.get(hashedQueryKey)!
897 const handleQueryResult = makeQueryResultHandler(cachedQueryKey)
898 const unsubscribeFn = observer.subscribe(handleQueryResult)
899 unsubscribes.set(hashedQueryKey, unsubscribeFn)
900
901 // Process the current result immediately if available
902 // This ensures data is synced when resubscribing to a query with cached data
903 const currentResult = observer.getCurrentResult()
904 if (currentResult.isSuccess || currentResult.isError) {
905 handleQueryResult(currentResult)
906 }
907 }
908 }
909
910 const subscribeToQueries = () => {
911 state.observers.forEach(subscribeToQuery)
912 }
913
914 const unsubscribeFromQueries = () => {
915 unsubscribes.forEach((unsubscribeFn) => {
916 unsubscribeFn()
917 })
918 unsubscribes.clear()
919 }
920
921 // Mark that sync has started
922 syncStarted = true
923
924 // Set up event listener for subscriber changes
925 const unsubscribeFromCollectionEvents = collection.on(
926 `subscribers:change`,
927 ({ subscriberCount }) => {
928 if (subscriberCount > 0) {
929 subscribeToQueries()
930 } else if (subscriberCount === 0) {
931 unsubscribeFromQueries()
932 }
933 },
934 )
935
936 // If syncMode is eager, create the initial query without any predicates
937 if (syncMode === `eager`) {
938 // Catch any errors to prevent unhandled rejections
939 const initialResult = createQueryFromOpts({})
940 if (initialResult instanceof Promise) {
941 initialResult.catch(() => {
942 // Errors are already handled by the query result handler
943 })
944 }
945 } else {
946 // In on-demand mode, mark ready immediately since there's no initial query
947 markReady()
948 }
949
950 // Always subscribe when sync starts (this could be from preload(), startSync config, or first subscriber)
951 // We'll dynamically unsubscribe/resubscribe based on subscriber count to maintain staleTime behavior
952 subscribeToQueries()
953
954 // Ensure we process any existing query data (QueryObserver doesn't invoke its callback automatically with initial state)
955 state.observers.forEach((observer, hashedQueryKey) => {
956 const cachedQueryKey = hashToQueryKey.get(hashedQueryKey)!
957 const handleQueryResult = makeQueryResultHandler(cachedQueryKey)
958 handleQueryResult(observer.getCurrentResult())
959 })
960
961 /**
962 * Perform row-level cleanup and remove all tracking for a query.
963 * Callers are responsible for ensuring the query is safe to cleanup.
964 */
965 const cleanupQueryInternal = (hashedQueryKey: string) => {
966 unsubscribes.get(hashedQueryKey)?.()
967 unsubscribes.delete(hashedQueryKey)
968
969 const rowKeys = queryToRows.get(hashedQueryKey) ?? new Set()
970 const rowsToDelete: Array<any> = []
971
972 rowKeys.forEach((rowKey) => {
973 const queries = rowToQueries.get(rowKey)
974
975 if (!queries) {
976 return
977 }
978
979 queries.delete(hashedQueryKey)
980
981 if (queries.size === 0) {
982 rowToQueries.delete(rowKey)
983
984 if (collection.has(rowKey)) {
985 rowsToDelete.push(collection.get(rowKey))
986 }
987 }
988 })
989
990 if (rowsToDelete.length > 0) {
991 begin()
992 rowsToDelete.forEach((row) => {
993 write({ type: `delete`, value: row })
994 })
995 commit()
996 }
997
998 state.observers.delete(hashedQueryKey)
999 queryToRows.delete(hashedQueryKey)
1000 hashToQueryKey.delete(hashedQueryKey)
1001 queryRefCounts.delete(hashedQueryKey)
1002 }
1003
1004 /**
1005 * Attempt to cleanup a query when it appears unused.
1006 * Respects refcounts and invalidateQueries cycles via hasListeners().
1007 */
1008 const cleanupQueryIfIdle = (hashedQueryKey: string) => {
1009 const refcount = queryRefCounts.get(hashedQueryKey) || 0
1010 const observer = state.observers.get(hashedQueryKey)
1011
1012 if (refcount <= 0) {
1013 // Drop our subscription so hasListeners reflects only active consumers
1014 unsubscribes.get(hashedQueryKey)?.()
1015 unsubscribes.delete(hashedQueryKey)
1016 }
1017
1018 const hasListeners = observer?.hasListeners() ?? false
1019
1020 if (hasListeners) {
1021 // During invalidateQueries, TanStack Query keeps internal listeners alive.
1022 // Leave refcount at 0 but keep observer so it can resubscribe.
1023 queryRefCounts.set(hashedQueryKey, 0)
1024 return
1025 }
1026
1027 // No listeners means the query is truly idle.
1028 // Even if refcount > 0, we treat hasListeners as authoritative to prevent leaks.
1029 // This can happen if subscriptions are GC'd without calling unloadSubset.
1030 if (refcount > 0) {
1031 console.warn(
1032 `[cleanupQueryIfIdle] Invariant violation: refcount=${refcount} but no listeners. Cleaning up to prevent leak.`,
1033 { hashedQueryKey },
1034 )
1035 }
1036
1037 cleanupQueryInternal(hashedQueryKey)
1038 }
1039
1040 /**
1041 * Force cleanup used by explicit collection cleanup.
1042 * Ignores refcounts/hasListeners and removes everything.
1043 */
1044 const forceCleanupQuery = (hashedQueryKey: string) => {
1045 cleanupQueryInternal(hashedQueryKey)
1046 }
1047
1048 // Subscribe to the query client's cache to handle queries that are GCed by tanstack query
1049 const unsubscribeQueryCache = queryClient
1050 .getQueryCache()
1051 .subscribe((event) => {
1052 const hashedKey = event.query.queryHash
1053 if (event.type === `removed`) {
1054 // Only cleanup if this is OUR query (we track it)
1055 if (hashToQueryKey.has(hashedKey)) {
1056 // TanStack Query GC'd this query after gcTime expired.
1057 // Use the guarded cleanup path to avoid deleting rows for active queries.
1058 cleanupQueryIfIdle(hashedKey)
1059 }
1060 }
1061 })
1062
1063 const cleanup = async () => {
1064 unsubscribeFromCollectionEvents()
1065 unsubscribeFromQueries()
1066
1067 const allQueryKeys = [...hashToQueryKey.values()]
1068 const allHashedKeys = [...state.observers.keys()]
1069
1070 // Force cleanup all queries (explicit cleanup path)
1071 // This ignores hasListeners and always cleans up
1072 for (const hashedKey of allHashedKeys) {
1073 forceCleanupQuery(hashedKey)
1074 }
1075
1076 // Unsubscribe from cache events (cleanup already happened above)
1077 unsubscribeQueryCache()
1078
1079 // Remove queries from TanStack Query cache
1080 await Promise.all(
1081 allQueryKeys.map(async (qKey) => {
1082 await queryClient.cancelQueries({ queryKey: qKey, exact: true })
1083 queryClient.removeQueries({ queryKey: qKey, exact: true })
1084 }),
1085 )
1086 }
1087
1088 /**
1089 * Unload a query subset - the subscription-based cleanup path (on-demand mode).
1090 *
1091 * Called when a live query subscription unsubscribes (via collection._sync.unloadSubset()).
1092 *
1093 * Flow:
1094 * 1. Receives the same predicates that were passed to loadSubset
1095 * 2. Computes the queryKey using generateQueryKeyFromOptions (same logic as loadSubset)
1096 * 3. Decrements refcount
1097 * 4. If refcount reaches 0:
1098 * - Checks hasListeners() to detect invalidateQueries cycles
1099 * - If hasListeners is true: resets refcount (TanStack Query keeping observer alive)
1100 * - If hasListeners is false: calls forceCleanupQuery() to perform row-level GC
1101 *
1102 * The hasListeners() check prevents premature cleanup during invalidateQueries:
1103 * - invalidateQueries causes temporary unsubscribe/resubscribe
1104 * - During unsubscribe, our refcount drops to 0
1105 * - But observer.hasListeners() is still true (TanStack Query's internal listeners)
1106 * - We skip cleanup and reset refcount, allowing resubscribe to succeed
1107 *
1108 * We don't cancel in-flight requests. Unsubscribing from the observer is sufficient
1109 * to prevent late-arriving data from being processed. The request completes and is cached
1110 * by TanStack Query, allowing quick remounts to restore data without refetching.
1111 */
1112 const unloadSubset = (options: LoadSubsetOptions) => {
1113 // 1. Same predicates → 2. Same queryKey
1114 const key = generateQueryKeyFromOptions(options)
1115 const hashedQueryKey = hashKey(key)
1116
1117 // 3. Decrement refcount
1118 const currentCount = queryRefCounts.get(hashedQueryKey) || 0
1119 const newCount = currentCount - 1
1120
1121 // Update refcount
1122 if (newCount <= 0) {
1123 queryRefCounts.set(hashedQueryKey, 0)
1124 cleanupQueryIfIdle(hashedQueryKey)
1125 } else {
1126 // Still have other references, just decrement
1127 queryRefCounts.set(hashedQueryKey, newCount)
1128 }
1129 }
1130
1131 // Create deduplicated loadSubset wrapper for non-eager modes
1132 // This prevents redundant snapshot requests when multiple concurrent
1133 // live queries request overlapping or subset predicates
1134 const loadSubsetDedupe =
1135 syncMode === `eager` ? undefined : createQueryFromOpts
1136
1137 return {
1138 loadSubset: loadSubsetDedupe,
1139 unloadSubset: syncMode === `eager` ? undefined : unloadSubset,
1140 cleanup,
1141 }
1142 }
1143
1144 /**
1145 * Refetch the query data
1146 *
1147 * Uses queryObserver.refetch() because:
1148 * - Bypasses `enabled: false` to support manual/imperative refetch patterns (e.g., button-triggered fetch)
1149 * - Ensures clearError() works even when enabled: false
1150 * - Always refetches THIS specific collection (exact targeting via observer)
1151 * - Respects retry, retryDelay, and other observer options
1152 *
1153 * This matches TanStack Query's hook behavior where refetch() bypasses enabled: false.
1154 * See: https://tanstack.com/query/latest/docs/framework/react/guides/disabling-queries
1155 *
1156 * Used by both:
1157 * - utils.refetch() - for explicit user-triggered refetches
1158 * - Internal handlers (onInsert/onUpdate/onDelete) - after mutations to get fresh data
1159 *
1160 * @returns Promise that resolves when the refetch is complete, with QueryObserverResult
1161 */
1162 const refetch: RefetchFn = async (opts) => {
1163 const allQueryKeys = [...hashToQueryKey.values()]
1164 const refetchPromises = allQueryKeys.map((qKey) => {
1165 const queryObserver = state.observers.get(hashKey(qKey))!
1166 return queryObserver.refetch({
1167 throwOnError: opts?.throwOnError,
1168 })
1169 })
1170
1171 return Promise.all(refetchPromises)
1172 }
1173
1174 /**
1175 * Updates a single query key in the cache with new items, handling both direct arrays
1176 * and wrapped response formats (when `select` is used).
1177 */
1178 const updateCacheDataForKey = (key: QueryKey, items: Array<any>): void => {
1179 if (select) {
1180 // When `select` is used, the cache contains a wrapped response (e.g., { data: [...], meta: {...} })
1181 // We need to update the cache while preserving the wrapper structure
1182 queryClient.setQueryData(key, (oldData: any) => {
1183 if (!oldData || typeof oldData !== `object`) {
1184 // No existing cache or not an object - don't corrupt the cache
1185 return oldData
1186 }
1187
1188 if (Array.isArray(oldData)) {
1189 // Cache is already a raw array (shouldn't happen with select, but handle it)
1190 return items
1191 }
1192
1193 // Use the select function to identify which property contains the items array.
1194 // This is more robust than guessing based on property order.
1195 const selectedArray = select(oldData)
1196
1197 if (Array.isArray(selectedArray)) {
1198 // Find the property that matches the selected array by reference equality
1199 for (const propKey of Object.keys(oldData)) {
1200 if (oldData[propKey] === selectedArray) {
1201 // Found the exact property - create a shallow copy with updated items
1202 return { ...oldData, [propKey]: items }
1203 }
1204 }
1205 }
1206
1207 // Fallback: check common property names used for data arrays
1208 if (Array.isArray(oldData.data)) {
1209 return { ...oldData, data: items }
1210 }
1211 if (Array.isArray(oldData.items)) {
1212 return { ...oldData, items: items }
1213 }
1214 if (Array.isArray(oldData.results)) {
1215 return { ...oldData, results: items }
1216 }
1217
1218 // Last resort: find first array property
1219 for (const propKey of Object.keys(oldData)) {
1220 if (Array.isArray(oldData[propKey])) {
1221 return { ...oldData, [propKey]: items }
1222 }
1223 }
1224
1225 // Couldn't safely identify the array property - don't corrupt the cache
1226 // Return oldData unchanged to avoid breaking select
1227 return oldData
1228 })
1229 } else {
1230 // No select - cache contains raw array, just set it directly
1231 queryClient.setQueryData(key, items)
1232 }
1233 }
1234
1235 /**
1236 * Updates the query cache with new items for ALL active query keys.
1237 * This is critical for on-demand mode where multiple query keys may exist
1238 * (each with different predicates).
1239 */
1240 const updateCacheData = (items: Array<any>): void => {
1241 // Get all active query keys from the hashToQueryKey map
1242 const activeQueryKeys = Array.from(hashToQueryKey.values())
1243
1244 if (activeQueryKeys.length > 0) {
1245 // Update all active query keys in the cache
1246 for (const key of activeQueryKeys) {
1247 updateCacheDataForKey(key, items)
1248 }
1249 } else {
1250 // Fallback: no active queries yet, use the base query key
1251 // This handles the case where updateCacheData is called before any queries are created
1252 const baseKey =
1253 typeof queryKey === `function`
1254 ? queryKey({})
1255 : (queryKey as unknown as QueryKey)
1256 updateCacheDataForKey(baseKey, items)
1257 }
1258 }
1259
1260 // Create write context for manual write operations
1261 let writeContext: {
1262 collection: any
1263 queryClient: QueryClient
1264 queryKey: Array<unknown>
1265 getKey: (item: any) => string | number
1266 begin: () => void
1267 write: (message: Omit<ChangeMessage<any>, `key`>) => void
1268 commit: () => void
1269 updateCacheData?: (items: Array<any>) => void
1270 } | null = null
1271
1272 // Enhanced internalSync that captures write functions for manual use
1273 const enhancedInternalSync: SyncConfig<any>[`sync`] = (params) => {
1274 const { begin, write, commit, collection } = params
1275
1276 // Get the base query key for the context (handle both static and function-based keys)
1277 const contextQueryKey =
1278 typeof queryKey === `function`
1279 ? (queryKey({}) as unknown as Array<unknown>)
1280 : (queryKey as unknown as Array<unknown>)
1281
1282 // Store references for manual write operations
1283 writeContext = {
1284 collection,
1285 queryClient,
1286 queryKey: contextQueryKey,
1287 getKey: getKey as (item: any) => string | number,
1288 begin,
1289 write,
1290 commit,
1291 updateCacheData,
1292 }
1293
1294 // Call the original internalSync logic
1295 return internalSync(params)
1296 }
1297
1298 // Create write utils using the manual-sync module
1299 const writeUtils = createWriteUtils<any, string | number, any>(
1300 () => writeContext,
1301 )
1302
1303 // Create wrapper handlers for direct persistence operations that handle refetching
1304 const wrappedOnInsert = onInsert
1305 ? async (params: InsertMutationFnParams<any>) => {
1306 const handlerResult = (await onInsert(params)) ?? {}
1307 const shouldRefetch =
1308 (handlerResult as { refetch?: boolean }).refetch !== false
1309
1310 if (shouldRefetch) {
1311 await refetch()
1312 }
1313
1314 return handlerResult
1315 }
1316 : undefined
1317
1318 const wrappedOnUpdate = onUpdate
1319 ? async (params: UpdateMutationFnParams<any>) => {
1320 const handlerResult = (await onUpdate(params)) ?? {}
1321 const shouldRefetch =
1322 (handlerResult as { refetch?: boolean }).refetch !== false
1323
1324 if (shouldRefetch) {
1325 await refetch()
1326 }
1327
1328 return handlerResult
1329 }
1330 : undefined
1331
1332 const wrappedOnDelete = onDelete
1333 ? async (params: DeleteMutationFnParams<any>) => {
1334 const handlerResult = (await onDelete(params)) ?? {}
1335 const shouldRefetch =
1336 (handlerResult as { refetch?: boolean }).refetch !== false
1337
1338 if (shouldRefetch) {
1339 await refetch()
1340 }
1341
1342 return handlerResult
1343 }
1344 : undefined
1345
1346 // Create utils instance with state and dependencies passed explicitly
1347 const utils: any = new QueryCollectionUtilsImpl(state, refetch, writeUtils)
1348
1349 return {
1350 ...baseCollectionConfig,
1351 getKey,
1352 syncMode,
1353 sync: { sync: enhancedInternalSync },
1354 onInsert: wrappedOnInsert,
1355 onUpdate: wrappedOnUpdate,
1356 onDelete: wrappedOnDelete,
1357 utils,
1358 }
1359}