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