@tanstack/vue-db 0.0.128 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,20 @@
1
+ <div align="center">
2
+ <picture>
3
+ <source
4
+ media="(prefers-color-scheme: dark)"
5
+ srcset="https://tanstack.com/api/readme/db.png?framework=vue&theme=dark"
6
+ />
7
+ <source
8
+ media="(prefers-color-scheme: light)"
9
+ srcset="https://tanstack.com/api/readme/db.png?framework=vue"
10
+ />
11
+ <img
12
+ src="https://tanstack.com/api/readme/db.png?framework=vue"
13
+ alt="TanStack Vue DB"
14
+ width="900"
15
+ />
16
+ </picture>
17
+ </div>
1
18
  # @tanstack/vue-db
2
19
 
3
20
  Vue composables for TanStack DB. See [TanStack/db](https://github.com/TanStack/db) for more details.
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const useLiveQuery = require("./useLiveQuery.cjs");
4
+ const useLiveInfiniteQuery = require("./useLiveInfiniteQuery.cjs");
4
5
  const db = require("@tanstack/db");
5
6
  exports.useLiveQuery = useLiveQuery.useLiveQuery;
7
+ exports.useLiveInfiniteQuery = useLiveInfiniteQuery.useLiveInfiniteQuery;
6
8
  Object.defineProperty(exports, "createTransaction", {
7
9
  enumerable: true,
8
10
  get: () => db.createTransaction
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;"}
@@ -1,4 +1,5 @@
1
1
  export * from './useLiveQuery.cjs';
2
+ export * from './useLiveInfiniteQuery.cjs';
2
3
  export * from '@tanstack/db';
3
4
  export type { Collection } from '@tanstack/db';
4
5
  export { createTransaction } from '@tanstack/db';
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const vue = require("vue");
4
+ const db = require("@tanstack/db");
5
+ const DEFAULT_GC_TIME_MS = 1;
6
+ function useLiveInfiniteQuery(queryFnOrCollection, config, deps = []) {
7
+ let validatedCollection = null;
8
+ let previousController = null;
9
+ let previousInput = null;
10
+ let previousDependencies = null;
11
+ let previousPageSize = null;
12
+ let previousInitialPageParam = null;
13
+ const controller = vue.computed(() => {
14
+ const dependencies = deps.map((dependency) => vue.toValue(dependency));
15
+ const pageSize = db.normalizeLiveQueryWindowPageSize(config.pageSize);
16
+ const initialPageParam = config.initialPageParam ?? 0;
17
+ const unwrappedInput = typeof queryFnOrCollection === `function` ? queryFnOrCollection : vue.toValue(queryFnOrCollection);
18
+ const input = db.resolveLiveQueryWindowInput(unwrappedInput);
19
+ const dependencyComparison = db.compareLiveQueryWindowDependencies(
20
+ previousDependencies,
21
+ dependencies
22
+ );
23
+ const dependenciesChanged = dependencyComparison.changed;
24
+ const dependenciesStructurallyEqual = dependencyComparison.structurallyEqual;
25
+ const pageShapeChanged = previousPageSize !== pageSize || previousInitialPageParam !== initialPageParam;
26
+ const sameCollection = input.kind === `collection` && previousInput?.kind === `collection` && previousInput.collection === input.collection;
27
+ const canPreservePageCount = db.shouldPreserveLiveQueryWindowPageCount({
28
+ hasPreviousController: previousController !== null,
29
+ previousInputKind: previousInput?.kind,
30
+ inputKind: input.kind,
31
+ sameCollection,
32
+ dependenciesChanged,
33
+ dependenciesStructurallyEqual,
34
+ pageShapeChanged
35
+ });
36
+ const previousPageCount = previousController ? Math.max(1, previousController.getSnapshot().pages.length) : 1;
37
+ const initialPageCount = canPreservePageCount ? previousPageCount : 1;
38
+ previousInput = input;
39
+ previousDependencies = [...dependencies];
40
+ previousPageSize = pageSize;
41
+ previousInitialPageParam = initialPageParam;
42
+ if (input.kind === `collection`) {
43
+ const collection2 = input.collection;
44
+ const warning = db.getLiveQueryWindowCollectionWarning(
45
+ collection2,
46
+ pageSize + 1
47
+ );
48
+ if (validatedCollection !== collection2) {
49
+ validatedCollection = collection2;
50
+ if (warning) console.warn(warning);
51
+ }
52
+ const currentController2 = db.createLiveQueryWindowController(collection2, {
53
+ pageSize,
54
+ initialPageParam,
55
+ initialPageCount
56
+ });
57
+ previousController = currentController2;
58
+ return currentController2;
59
+ }
60
+ const collection = db.createLiveQueryCollection({
61
+ query: input.query.limit(pageSize + 1).offset(0),
62
+ startSync: false,
63
+ gcTime: DEFAULT_GC_TIME_MS
64
+ });
65
+ db.assertLiveQueryWindowManyResult(collection);
66
+ const currentController = db.createLiveQueryWindowController(collection, {
67
+ pageSize,
68
+ initialPageParam,
69
+ initialPageCount
70
+ });
71
+ previousController = currentController;
72
+ return currentController;
73
+ });
74
+ const snapshot = vue.shallowRef(controller.value.getSnapshot());
75
+ vue.watchEffect(
76
+ (onInvalidate) => {
77
+ const currentController = controller.value;
78
+ const updateSnapshot = () => {
79
+ snapshot.value = currentController.getSnapshot();
80
+ };
81
+ updateSnapshot();
82
+ const unsubscribe = currentController.subscribe(updateSnapshot);
83
+ updateSnapshot();
84
+ onInvalidate(() => {
85
+ unsubscribe();
86
+ currentController.dispose();
87
+ });
88
+ },
89
+ { flush: `sync` }
90
+ );
91
+ return {
92
+ state: vue.computed(
93
+ () => snapshot.value.state
94
+ ),
95
+ data: vue.computed(() => snapshot.value.data),
96
+ collection: vue.computed(
97
+ () => snapshot.value.collection
98
+ ),
99
+ status: vue.computed(() => snapshot.value.status),
100
+ isLoading: vue.computed(() => snapshot.value.isLoading),
101
+ isReady: vue.computed(() => snapshot.value.isReady),
102
+ isIdle: vue.computed(() => snapshot.value.isIdle),
103
+ isError: vue.computed(() => snapshot.value.isError),
104
+ isCleanedUp: vue.computed(() => snapshot.value.isCleanedUp),
105
+ pages: vue.computed(
106
+ () => snapshot.value.pages
107
+ ),
108
+ pageParams: vue.computed(() => snapshot.value.pageParams),
109
+ fetchNextPage: () => db.fetchNextLiveQueryWindowPage(controller.value),
110
+ hasNextPage: vue.computed(() => snapshot.value.hasNextPage),
111
+ isFetchingNextPage: vue.computed(() => snapshot.value.isFetchingNextPage),
112
+ error: vue.computed(() => snapshot.value.error)
113
+ };
114
+ }
115
+ exports.useLiveInfiniteQuery = useLiveInfiniteQuery;
116
+ //# sourceMappingURL=useLiveInfiniteQuery.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useLiveInfiniteQuery.cjs","sources":["../../src/useLiveInfiniteQuery.ts"],"sourcesContent":["import { computed, shallowRef, toValue, watchEffect } from 'vue'\nimport {\n assertLiveQueryWindowManyResult,\n compareLiveQueryWindowDependencies,\n createLiveQueryCollection,\n createLiveQueryWindowController,\n fetchNextLiveQueryWindowPage,\n getLiveQueryWindowCollectionWarning,\n normalizeLiveQueryWindowPageSize,\n resolveLiveQueryWindowInput,\n shouldPreserveLiveQueryWindowPageCount,\n} from '@tanstack/db'\nimport type {\n Collection,\n CollectionStatus,\n Context,\n GetResult,\n InferResultType,\n InitialQueryBuilder,\n NonSingleResult,\n QueryBuilder,\n UtilsRecord,\n} from '@tanstack/db'\nimport type { ComputedRef, MaybeRefOrGetter } from 'vue'\n\nconst DEFAULT_GC_TIME_MS = 1\n\ntype InternalCollection = Collection<object, string | number, UtilsRecord>\n\ntype PreviousController = {\n getSnapshot: () => { pages: ReadonlyArray<ReadonlyArray<unknown>> }\n}\n\ntype InfiniteQueryOptions = {\n pageSize?: number\n initialPageParam?: number\n}\n\nexport type LiveInfiniteQueryConfig<TRow> = InfiniteQueryOptions & {\n /**\n * @deprecated Pagination uses the shared controller's peek-ahead strategy.\n * This remains for compatibility with TanStack Query conventions.\n */\n getNextPageParam?: (\n lastPage: Array<TRow>,\n allPages: Array<Array<TRow>>,\n lastPageParam: number,\n allPageParams: Array<number>,\n ) => number | undefined\n}\n\nexport type UseLiveInfiniteQueryConfig<\n TContext extends Context & NonSingleResult,\n> = LiveInfiniteQueryConfig<InferResultType<TContext>[number]>\n\nexport interface UseLiveInfiniteQueryReturn<\n TContext extends Context & NonSingleResult,\n> {\n state: ComputedRef<Map<string | number, GetResult<TContext>>>\n data: ComputedRef<InferResultType<TContext>>\n collection: ComputedRef<\n Collection<GetResult<TContext>, string | number, UtilsRecord>\n >\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n pages: ComputedRef<Array<Array<InferResultType<TContext>[number]>>>\n pageParams: ComputedRef<Array<number>>\n fetchNextPage: () => Promise<void>\n hasNextPage: ComputedRef<boolean>\n isFetchingNextPage: ComputedRef<boolean>\n error: ComputedRef<unknown>\n}\n\nexport interface UseLiveInfiniteQueryReturnWithCollection<\n TResult extends object,\n TKey extends string | number,\n TUtils extends UtilsRecord,\n> {\n state: ComputedRef<Map<TKey, TResult>>\n data: ComputedRef<Array<TResult>>\n collection: ComputedRef<Collection<TResult, TKey, TUtils>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n pages: ComputedRef<Array<Array<TResult>>>\n pageParams: ComputedRef<Array<number>>\n fetchNextPage: () => Promise<void>\n hasNextPage: ComputedRef<boolean>\n isFetchingNextPage: ComputedRef<boolean>\n error: ComputedRef<unknown>\n}\n\n/**\n * Create a Vue-native reactive view over the shared live-query window\n * controller. The query must include an `orderBy` clause.\n */\nexport function useLiveInfiniteQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends UtilsRecord,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & NonSingleResult\n >,\n config: LiveInfiniteQueryConfig<TResult>,\n): UseLiveInfiniteQueryReturnWithCollection<TResult, TKey, TUtils>\n\nexport function useLiveInfiniteQuery<\n TContext extends Context & NonSingleResult,\n>(\n queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,\n config: UseLiveInfiniteQueryConfig<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveInfiniteQueryReturn<TContext>\n\nexport function useLiveInfiniteQuery<\n TContext extends Context & NonSingleResult,\n>(\n queryFnOrCollection: unknown,\n config: InfiniteQueryOptions,\n deps: Array<MaybeRefOrGetter<unknown>> = [],\n): UseLiveInfiniteQueryReturn<TContext> {\n let validatedCollection: InternalCollection | null = null\n let previousController: PreviousController | null = null\n let previousInput: ReturnType<\n typeof resolveLiveQueryWindowInput<TContext>\n > | null = null\n let previousDependencies: Array<unknown> | null = null\n let previousPageSize: number | null = null\n let previousInitialPageParam: number | null = null\n\n const controller = computed(() => {\n const dependencies = deps.map((dependency) => toValue(dependency))\n\n const pageSize = normalizeLiveQueryWindowPageSize(config.pageSize)\n const initialPageParam = config.initialPageParam ?? 0\n const unwrappedInput =\n typeof queryFnOrCollection === `function`\n ? queryFnOrCollection\n : toValue(queryFnOrCollection)\n const input = resolveLiveQueryWindowInput<TContext>(unwrappedInput)\n const dependencyComparison = compareLiveQueryWindowDependencies(\n previousDependencies,\n dependencies,\n )\n const dependenciesChanged = dependencyComparison.changed\n const dependenciesStructurallyEqual = dependencyComparison.structurallyEqual\n const pageShapeChanged =\n previousPageSize !== pageSize ||\n previousInitialPageParam !== initialPageParam\n const sameCollection =\n input.kind === `collection` &&\n previousInput?.kind === `collection` &&\n previousInput.collection === input.collection\n const canPreservePageCount = shouldPreserveLiveQueryWindowPageCount({\n hasPreviousController: previousController !== null,\n previousInputKind: previousInput?.kind,\n inputKind: input.kind,\n sameCollection,\n dependenciesChanged,\n dependenciesStructurallyEqual,\n pageShapeChanged,\n })\n const previousPageCount = previousController\n ? Math.max(1, previousController.getSnapshot().pages.length)\n : 1\n const initialPageCount = canPreservePageCount ? previousPageCount : 1\n\n previousInput = input\n previousDependencies = [...dependencies]\n previousPageSize = pageSize\n previousInitialPageParam = initialPageParam\n\n if (input.kind === `collection`) {\n const collection = input.collection\n const warning = getLiveQueryWindowCollectionWarning(\n collection,\n pageSize + 1,\n )\n\n if (validatedCollection !== collection) {\n validatedCollection = collection\n if (warning) console.warn(warning)\n }\n\n const currentController = createLiveQueryWindowController(collection, {\n pageSize,\n initialPageParam,\n initialPageCount,\n })\n previousController = currentController\n return currentController\n }\n\n const collection = createLiveQueryCollection({\n query: input.query.limit(pageSize + 1).offset(0),\n startSync: false,\n gcTime: DEFAULT_GC_TIME_MS,\n })\n assertLiveQueryWindowManyResult(collection)\n const currentController = createLiveQueryWindowController(collection, {\n pageSize,\n initialPageParam,\n initialPageCount,\n })\n previousController = currentController\n return currentController\n })\n\n const snapshot = shallowRef(controller.value.getSnapshot())\n\n watchEffect(\n (onInvalidate) => {\n const currentController = controller.value\n const updateSnapshot = () => {\n snapshot.value = currentController.getSnapshot()\n }\n\n updateSnapshot()\n const unsubscribe = currentController.subscribe(updateSnapshot)\n updateSnapshot()\n\n onInvalidate(() => {\n unsubscribe()\n currentController.dispose()\n })\n },\n { flush: `sync` },\n )\n\n return {\n state: computed(\n () => snapshot.value.state as Map<string | number, GetResult<TContext>>,\n ),\n data: computed(() => snapshot.value.data as InferResultType<TContext>),\n collection: computed(\n () =>\n snapshot.value.collection as Collection<\n GetResult<TContext>,\n string | number,\n UtilsRecord\n >,\n ),\n status: computed(() => snapshot.value.status as CollectionStatus),\n isLoading: computed(() => snapshot.value.isLoading),\n isReady: computed(() => snapshot.value.isReady),\n isIdle: computed(() => snapshot.value.isIdle),\n isError: computed(() => snapshot.value.isError),\n isCleanedUp: computed(() => snapshot.value.isCleanedUp),\n pages: computed(\n () =>\n snapshot.value.pages as Array<Array<InferResultType<TContext>[number]>>,\n ),\n pageParams: computed(() => snapshot.value.pageParams as Array<number>),\n fetchNextPage: () => fetchNextLiveQueryWindowPage(controller.value),\n hasNextPage: computed(() => snapshot.value.hasNextPage),\n isFetchingNextPage: computed(() => snapshot.value.isFetchingNextPage),\n error: computed(() => snapshot.value.error),\n }\n}\n"],"names":["computed","toValue","normalizeLiveQueryWindowPageSize","resolveLiveQueryWindowInput","compareLiveQueryWindowDependencies","shouldPreserveLiveQueryWindowPageCount","collection","getLiveQueryWindowCollectionWarning","currentController","createLiveQueryWindowController","createLiveQueryCollection","assertLiveQueryWindowManyResult","shallowRef","watchEffect","fetchNextLiveQueryWindowPage"],"mappings":";;;;AAyBA,MAAM,qBAAqB;AAiGpB,SAAS,qBAGd,qBACA,QACA,OAAyC,CAAA,GACH;AACtC,MAAI,sBAAiD;AACrD,MAAI,qBAAgD;AACpD,MAAI,gBAEO;AACX,MAAI,uBAA8C;AAClD,MAAI,mBAAkC;AACtC,MAAI,2BAA0C;AAE9C,QAAM,aAAaA,IAAAA,SAAS,MAAM;AAChC,UAAM,eAAe,KAAK,IAAI,CAAC,eAAeC,IAAAA,QAAQ,UAAU,CAAC;AAEjE,UAAM,WAAWC,GAAAA,iCAAiC,OAAO,QAAQ;AACjE,UAAM,mBAAmB,OAAO,oBAAoB;AACpD,UAAM,iBACJ,OAAO,wBAAwB,aAC3B,sBACAD,IAAAA,QAAQ,mBAAmB;AACjC,UAAM,QAAQE,GAAAA,4BAAsC,cAAc;AAClE,UAAM,uBAAuBC,GAAAA;AAAAA,MAC3B;AAAA,MACA;AAAA,IAAA;AAEF,UAAM,sBAAsB,qBAAqB;AACjD,UAAM,gCAAgC,qBAAqB;AAC3D,UAAM,mBACJ,qBAAqB,YACrB,6BAA6B;AAC/B,UAAM,iBACJ,MAAM,SAAS,gBACf,eAAe,SAAS,gBACxB,cAAc,eAAe,MAAM;AACrC,UAAM,uBAAuBC,GAAAA,uCAAuC;AAAA,MAClE,uBAAuB,uBAAuB;AAAA,MAC9C,mBAAmB,eAAe;AAAA,MAClC,WAAW,MAAM;AAAA,MACjB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA,CACD;AACD,UAAM,oBAAoB,qBACtB,KAAK,IAAI,GAAG,mBAAmB,YAAA,EAAc,MAAM,MAAM,IACzD;AACJ,UAAM,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IAAA;AAAA,IAEvB,MAAMA,IAAAA,SAAS,MAAM,SAAS,MAAM,IAAiC;AAAA,IACrE,YAAYA,IAAAA;AAAAA,MACV,MACE,SAAS,MAAM;AAAA,IAAA;AAAA,IAMnB,QAAQA,IAAAA,SAAS,MAAM,SAAS,MAAM,MAA0B;AAAA,IAChE,WAAWA,IAAAA,SAAS,MAAM,SAAS,MAAM,SAAS;AAAA,IAClD,SAASA,IAAAA,SAAS,MAAM,SAAS,MAAM,OAAO;AAAA,IAC9C,QAAQA,IAAAA,SAAS,MAAM,SAAS,MAAM,MAAM;AAAA,IAC5C,SAASA,IAAAA,SAAS,MAAM,SAAS,MAAM,OAAO;AAAA,IAC9C,aAAaA,IAAAA,SAAS,MAAM,SAAS,MAAM,WAAW;AAAA,IACtD,OAAOA,IAAAA;AAAAA,MACL,MACE,SAAS,MAAM;AAAA,IAAA;AAAA,IAEnB,YAAYA,IAAAA,SAAS,MAAM,SAAS,MAAM,UAA2B;AAAA,IACrE,eAAe,MAAMc,GAAAA,6BAA6B,WAAW,KAAK;AAAA,IAClE,aAAad,IAAAA,SAAS,MAAM,SAAS,MAAM,WAAW;AAAA,IACtD,oBAAoBA,IAAAA,SAAS,MAAM,SAAS,MAAM,kBAAkB;AAAA,IACpE,OAAOA,IAAAA,SAAS,MAAM,SAAS,MAAM,KAAK;AAAA,EAAA;AAE9C;;"}
@@ -0,0 +1,55 @@
1
+ import { Collection, CollectionStatus, Context, GetResult, InferResultType, InitialQueryBuilder, NonSingleResult, QueryBuilder, UtilsRecord } from '@tanstack/db';
2
+ import { ComputedRef, MaybeRefOrGetter } from 'vue';
3
+ type InfiniteQueryOptions = {
4
+ pageSize?: number;
5
+ initialPageParam?: number;
6
+ };
7
+ export type LiveInfiniteQueryConfig<TRow> = InfiniteQueryOptions & {
8
+ /**
9
+ * @deprecated Pagination uses the shared controller's peek-ahead strategy.
10
+ * This remains for compatibility with TanStack Query conventions.
11
+ */
12
+ getNextPageParam?: (lastPage: Array<TRow>, allPages: Array<Array<TRow>>, lastPageParam: number, allPageParams: Array<number>) => number | undefined;
13
+ };
14
+ export type UseLiveInfiniteQueryConfig<TContext extends Context & NonSingleResult> = LiveInfiniteQueryConfig<InferResultType<TContext>[number]>;
15
+ export interface UseLiveInfiniteQueryReturn<TContext extends Context & NonSingleResult> {
16
+ state: ComputedRef<Map<string | number, GetResult<TContext>>>;
17
+ data: ComputedRef<InferResultType<TContext>>;
18
+ collection: ComputedRef<Collection<GetResult<TContext>, string | number, UtilsRecord>>;
19
+ status: ComputedRef<CollectionStatus>;
20
+ isLoading: ComputedRef<boolean>;
21
+ isReady: ComputedRef<boolean>;
22
+ isIdle: ComputedRef<boolean>;
23
+ isError: ComputedRef<boolean>;
24
+ isCleanedUp: ComputedRef<boolean>;
25
+ pages: ComputedRef<Array<Array<InferResultType<TContext>[number]>>>;
26
+ pageParams: ComputedRef<Array<number>>;
27
+ fetchNextPage: () => Promise<void>;
28
+ hasNextPage: ComputedRef<boolean>;
29
+ isFetchingNextPage: ComputedRef<boolean>;
30
+ error: ComputedRef<unknown>;
31
+ }
32
+ export interface UseLiveInfiniteQueryReturnWithCollection<TResult extends object, TKey extends string | number, TUtils extends UtilsRecord> {
33
+ state: ComputedRef<Map<TKey, TResult>>;
34
+ data: ComputedRef<Array<TResult>>;
35
+ collection: ComputedRef<Collection<TResult, TKey, TUtils>>;
36
+ status: ComputedRef<CollectionStatus>;
37
+ isLoading: ComputedRef<boolean>;
38
+ isReady: ComputedRef<boolean>;
39
+ isIdle: ComputedRef<boolean>;
40
+ isError: ComputedRef<boolean>;
41
+ isCleanedUp: ComputedRef<boolean>;
42
+ pages: ComputedRef<Array<Array<TResult>>>;
43
+ pageParams: ComputedRef<Array<number>>;
44
+ fetchNextPage: () => Promise<void>;
45
+ hasNextPage: ComputedRef<boolean>;
46
+ isFetchingNextPage: ComputedRef<boolean>;
47
+ error: ComputedRef<unknown>;
48
+ }
49
+ /**
50
+ * Create a Vue-native reactive view over the shared live-query window
51
+ * controller. The query must include an `orderBy` clause.
52
+ */
53
+ export declare function useLiveInfiniteQuery<TResult extends object, TKey extends string | number, TUtils extends UtilsRecord>(liveQueryCollection: MaybeRefOrGetter<Collection<TResult, TKey, TUtils> & NonSingleResult>, config: LiveInfiniteQueryConfig<TResult>): UseLiveInfiniteQueryReturnWithCollection<TResult, TKey, TUtils>;
54
+ export declare function useLiveInfiniteQuery<TContext extends Context & NonSingleResult>(queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>, config: UseLiveInfiniteQueryConfig<TContext>, deps?: Array<MaybeRefOrGetter<unknown>>): UseLiveInfiniteQueryReturn<TContext>;
55
+ export {};
@@ -76,71 +76,57 @@ Or switch to syncMode "eager" if you want all data to sync automatically.`
76
76
  internalData.length = 0;
77
77
  internalData.push(...Array.from(currentCollection.values()));
78
78
  };
79
- let currentUnsubscribe = null;
79
+ let currentObserver = null;
80
+ const syncFromObserver = (observer, currentCollection) => {
81
+ status.value = observer.getSnapshot().status;
82
+ syncDataFromCollection(currentCollection);
83
+ };
80
84
  vue.watchEffect((onInvalidate) => {
81
85
  const currentCollection = collection.value;
86
+ currentObserver?.dispose();
87
+ currentObserver = null;
82
88
  if (!currentCollection) {
83
89
  status.value = `disabled`;
84
90
  state.clear();
85
91
  internalData.length = 0;
86
- if (currentUnsubscribe) {
87
- currentUnsubscribe();
88
- currentUnsubscribe = null;
89
- }
90
92
  return;
91
93
  }
92
- status.value = currentCollection.status;
93
- if (currentUnsubscribe) {
94
- currentUnsubscribe();
95
- }
94
+ const observer = db.createLiveQueryObserver(currentCollection);
95
+ currentObserver = observer;
96
96
  state.clear();
97
- for (const [key, value] of currentCollection.entries()) {
98
- state.set(key, value);
99
- }
100
- syncDataFromCollection(currentCollection);
101
- currentCollection.onFirstReady(() => {
102
- vue.nextTick(() => {
103
- status.value = currentCollection.status;
104
- });
105
- });
106
- const subscription = currentCollection.subscribeChanges(
97
+ const unsubscribe = observer.subscribe(
107
98
  (changes) => {
108
- for (const change of changes) {
109
- switch (change.type) {
110
- case `insert`:
111
- case `update`:
112
- state.set(change.key, change.value);
113
- break;
114
- case `delete`:
115
- state.delete(change.key);
116
- break;
99
+ if (changes) {
100
+ for (const change of changes) {
101
+ switch (change.type) {
102
+ case `insert`:
103
+ case `update`:
104
+ state.set(change.key, change.value);
105
+ break;
106
+ case `delete`:
107
+ state.delete(change.key);
108
+ break;
109
+ }
110
+ }
111
+ } else {
112
+ state.clear();
113
+ for (const [key, value] of observer.getSnapshot().state ?? []) {
114
+ state.set(key, value);
117
115
  }
118
116
  }
119
- syncDataFromCollection(currentCollection);
120
- status.value = currentCollection.status;
121
- },
122
- {
123
- includeInitialState: true
117
+ syncFromObserver(observer, currentCollection);
124
118
  }
125
119
  );
126
- currentUnsubscribe = subscription.unsubscribe.bind(subscription);
127
- if (currentCollection.status === `idle`) {
128
- currentCollection.preload().catch(console.error);
129
- }
120
+ syncFromObserver(observer, currentCollection);
130
121
  onInvalidate(() => {
131
- if (currentUnsubscribe) {
132
- currentUnsubscribe();
133
- currentUnsubscribe = null;
134
- }
122
+ unsubscribe();
123
+ observer.dispose();
124
+ currentObserver = null;
135
125
  });
136
126
  });
137
127
  const instance = vue.getCurrentInstance();
138
128
  if (instance) {
139
- vue.onUnmounted(() => {
140
- if (currentUnsubscribe) {
141
- currentUnsubscribe();
142
- }
143
- });
129
+ vue.onUnmounted(() => currentObserver?.dispose());
144
130
  }
145
131
  return {
146
132
  state: vue.computed(() => state),
@@ -1 +1 @@
1
- {"version":3,"file":"useLiveQuery.cjs","sources":["../../src/useLiveQuery.ts"],"sourcesContent":["import {\n computed,\n getCurrentInstance,\n nextTick,\n onUnmounted,\n reactive,\n ref,\n toValue,\n watchEffect,\n} from 'vue'\nimport {\n createLiveQueryCollection,\n isCollection,\n isSingleResultCollection,\n} from '@tanstack/db'\nimport type {\n ChangeMessage,\n Collection,\n CollectionStatus,\n Context,\n GetResult,\n InferResultType,\n InitialQueryBuilder,\n LiveQueryCollectionConfig,\n NonSingleResult,\n QueryBuilder,\n SingleResult,\n} from '@tanstack/db'\nimport type { ComputedRef, MaybeRefOrGetter } from 'vue'\n\n/**\n * Return type for useLiveQuery hook\n * @property state - Reactive Map of query results (key → item)\n * @property data - Reactive array of query results in order, or single result for findOne queries\n * @property collection - The underlying query collection instance\n * @property status - Current query status\n * @property isLoading - True while initial query data is loading\n * @property isReady - True when query has received first data and is ready\n * @property isIdle - True when query hasn't started yet\n * @property isError - True when query encountered an error\n * @property isCleanedUp - True when query has been cleaned up\n */\nexport interface UseLiveQueryReturn<TContext extends Context> {\n state: ComputedRef<Map<string | number, GetResult<TContext>>>\n data: ComputedRef<InferResultType<TContext>>\n collection: ComputedRef<Collection<GetResult<TContext>, string | number, {}>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\nexport interface UseLiveQueryReturnWithCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<Array<T>>\n collection: ComputedRef<Collection<T, TKey, TUtils>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\nexport interface UseLiveQueryReturnWithSingleResultCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<T | undefined>\n collection: ComputedRef<Collection<T, TKey, TUtils> & SingleResult>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\n/**\n * Create a live query using a query function\n * @param queryFn - Query function that defines what data to fetch\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic query with object syntax\n * const { data, isLoading } = useLiveQuery((q) =>\n * q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.completed, false))\n * .select(({ todos }) => ({ id: todos.id, text: todos.text }))\n * )\n *\n * @example\n * // With reactive dependencies\n * const minPriority = ref(5)\n * const { data, state } = useLiveQuery(\n * (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => gt(todos.priority, minPriority.value)),\n * [minPriority] // Re-run when minPriority changes\n * )\n *\n * @example\n * // Join pattern\n * const { data } = useLiveQuery((q) =>\n * q.from({ issues: issueCollection })\n * .join({ persons: personCollection }, ({ issues, persons }) =>\n * eq(issues.userId, persons.id)\n * )\n * .select(({ issues, persons }) => ({\n * id: issues.id,\n * title: issues.title,\n * userName: persons.name\n * }))\n * )\n *\n * @example\n * // Handle loading and error states in template\n * const { data, isLoading, isError, status } = useLiveQuery((q) =>\n * q.from({ todos: todoCollection })\n * )\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error: {{ status }}</div>\n * // <ul v-else>\n * // <li v-for=\"todo in data\" :key=\"todo.id\">{{ todo.text }}</li>\n * // </ul>\n */\n// Overload 1: Accept query function that always returns QueryBuilder\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n// Overload 1b: Accept query function that can return undefined/null\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (\n q: InitialQueryBuilder,\n ) => QueryBuilder<TContext> | undefined | null,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n/**\n * Create a live query using configuration object\n * @param config - Configuration object with query and options\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic config object usage\n * const { data, status } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection }),\n * gcTime: 60000\n * })\n *\n * @example\n * // With reactive dependencies\n * const filter = ref('active')\n * const { data, isReady } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.status, filter.value))\n * }, [filter])\n *\n * @example\n * // Handle all states uniformly\n * const { data, isLoading, isReady, isError } = useLiveQuery({\n * query: (q) => q.from({ items: itemCollection })\n * })\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Something went wrong</div>\n * // <div v-else-if=\"!isReady\">Preparing...</div>\n * // <div v-else>{{ data.length }} items loaded</div>\n */\n// Overload 2: Accept config object\nexport function useLiveQuery<TContext extends Context>(\n config: LiveQueryCollectionConfig<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n/**\n * Subscribe to an existing query collection (can be reactive)\n * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a ref)\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Using pre-created query collection\n * const myLiveQuery = createLiveQueryCollection((q) =>\n * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))\n * )\n * const { data, collection } = useLiveQuery(myLiveQuery)\n *\n * @example\n * // Reactive query collection reference\n * const selectedQuery = ref(todosQuery)\n * const { data, collection } = useLiveQuery(selectedQuery)\n *\n * // Switch queries reactively\n * selectedQuery.value = archiveQuery\n *\n * @example\n * // Access query collection methods directly\n * const { data, collection, isReady } = useLiveQuery(existingQuery)\n *\n * // Use underlying collection for mutations\n * const handleToggle = (id) => {\n * collection.value.update(id, draft => { draft.completed = !draft.completed })\n * }\n *\n * @example\n * // Handle states consistently\n * const { data, isLoading, isError } = useLiveQuery(sharedQuery)\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error loading data</div>\n * // <div v-else>\n * // <Item v-for=\"item in data\" :key=\"item.id\" v-bind=\"item\" />\n * // </div>\n */\n// Overload 3: Accept pre-created live query collection (can be reactive) - non-single result\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & NonSingleResult\n >,\n): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils>\n\n// Overload 4: Accept pre-created live query collection with singleResult: true\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & SingleResult\n >,\n): UseLiveQueryReturnWithSingleResultCollection<TResult, TKey, TUtils>\n\n// Implementation\nexport function useLiveQuery(\n configOrQueryOrCollection: any,\n deps: Array<MaybeRefOrGetter<unknown>> = [],\n): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {\n const collection = computed(() => {\n // First check if the original parameter might be a ref/getter\n // by seeing if toValue returns something different than the original\n // NOTE: Don't call toValue on functions - toValue treats functions as getters and calls them!\n let unwrappedParam = configOrQueryOrCollection\n if (typeof configOrQueryOrCollection !== `function`) {\n try {\n const potentiallyUnwrapped = toValue(configOrQueryOrCollection)\n if (potentiallyUnwrapped !== configOrQueryOrCollection) {\n unwrappedParam = potentiallyUnwrapped\n }\n } catch {\n // If toValue fails, use original parameter\n unwrappedParam = configOrQueryOrCollection\n }\n }\n\n // Check if it's already a collection\n const inputIsCollection = isCollection(unwrappedParam)\n\n if (inputIsCollection) {\n // Warn when passing a collection directly with on-demand sync mode\n // In on-demand mode, data is only loaded when queries with predicates request it\n // Passing the collection directly doesn't provide any predicates, so no data loads\n const syncMode = (unwrappedParam as { config?: { syncMode?: string } })\n .config?.syncMode\n if (syncMode === `on-demand`) {\n console.warn(\n `[useLiveQuery] Warning: Passing a collection with syncMode \"on-demand\" directly to useLiveQuery ` +\n `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\\n\\n` +\n `Instead, use a query builder function:\\n` +\n ` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\\n\\n` +\n `Or switch to syncMode \"eager\" if you want all data to sync automatically.`,\n )\n }\n // It's already a collection, ensure sync is started for Vue hooks\n // Only start sync if the collection is in idle state\n if (unwrappedParam.status === `idle`) {\n unwrappedParam.startSyncImmediate()\n }\n return unwrappedParam\n }\n\n // Reference deps to make computed reactive to them\n deps.forEach((dep) => toValue(dep))\n\n // Ensure we always start sync for Vue hooks\n if (typeof unwrappedParam === `function`) {\n // To avoid calling the query function twice, we wrap it to handle null/undefined returns\n // The wrapper will be called once by createLiveQueryCollection\n const wrappedQuery = (q: InitialQueryBuilder) => {\n const result = unwrappedParam(q)\n // If the query function returns null/undefined, throw a special error\n // that we'll catch to return null collection\n if (result === undefined || result === null) {\n throw new Error(`__DISABLED_QUERY__`)\n }\n return result\n }\n\n try {\n return createLiveQueryCollection({\n query: wrappedQuery,\n startSync: true,\n })\n } catch (error) {\n // Check if this is our special disabled query marker\n if (error instanceof Error && error.message === `__DISABLED_QUERY__`) {\n return null\n }\n // Re-throw other errors\n throw error\n }\n } else {\n return createLiveQueryCollection({\n ...unwrappedParam,\n startSync: true,\n })\n }\n })\n\n // Reactive state that gets updated granularly through change events\n const state = reactive(new Map<string | number, any>())\n\n // Reactive data array that maintains sorted order\n const internalData = reactive<Array<any>>([])\n\n // Computed wrapper for the data to match expected return type\n // Returns single item for singleResult collections, array otherwise\n const data = computed(() => {\n const currentCollection = collection.value\n if (!currentCollection) {\n return internalData\n }\n return isSingleResultCollection(currentCollection)\n ? internalData[0]\n : internalData\n })\n\n // Track collection status reactively\n const status = ref(\n collection.value ? collection.value.status : (`disabled` as const),\n )\n\n // Helper to sync data array from collection in correct order\n const syncDataFromCollection = (\n currentCollection: Collection<any, any, any>,\n ) => {\n internalData.length = 0\n internalData.push(...Array.from(currentCollection.values()))\n }\n\n // Track current unsubscribe function\n let currentUnsubscribe: (() => void) | null = null\n\n // Watch for collection changes and subscribe to updates\n watchEffect((onInvalidate) => {\n const currentCollection = collection.value\n\n // Handle null collection (disabled query)\n if (!currentCollection) {\n status.value = `disabled` as const\n state.clear()\n internalData.length = 0\n if (currentUnsubscribe) {\n currentUnsubscribe()\n currentUnsubscribe = null\n }\n return\n }\n\n // Update status ref whenever the effect runs\n status.value = currentCollection.status\n\n // Clean up previous subscription\n if (currentUnsubscribe) {\n currentUnsubscribe()\n }\n\n // Initialize state with current collection data\n state.clear()\n for (const [key, value] of currentCollection.entries()) {\n state.set(key, value)\n }\n\n // Initialize data array in correct order\n syncDataFromCollection(currentCollection)\n\n // Listen for the first ready event to catch status transitions\n // that might not trigger change events (fixes async status transition bug)\n currentCollection.onFirstReady(() => {\n // Use nextTick to ensure Vue reactivity updates properly\n nextTick(() => {\n status.value = currentCollection.status\n })\n })\n\n // Subscribe to collection changes with granular updates\n const subscription = currentCollection.subscribeChanges(\n (changes: Array<ChangeMessage<any>>) => {\n // Apply each change individually to the reactive state\n for (const change of changes) {\n switch (change.type) {\n case `insert`:\n case `update`:\n state.set(change.key, change.value)\n break\n case `delete`:\n state.delete(change.key)\n break\n }\n }\n\n // Update the data array to maintain sorted order\n syncDataFromCollection(currentCollection)\n // Update status ref on every change\n status.value = currentCollection.status\n },\n {\n includeInitialState: true,\n },\n )\n\n currentUnsubscribe = subscription.unsubscribe.bind(subscription)\n\n // Preload collection data if not already started\n if (currentCollection.status === `idle`) {\n currentCollection.preload().catch(console.error)\n }\n\n // Cleanup when effect is invalidated\n onInvalidate(() => {\n if (currentUnsubscribe) {\n currentUnsubscribe()\n currentUnsubscribe = null\n }\n })\n })\n\n // Cleanup on unmount (only if we're in a component context)\n const instance = getCurrentInstance()\n if (instance) {\n onUnmounted(() => {\n if (currentUnsubscribe) {\n currentUnsubscribe()\n }\n })\n }\n\n return {\n state: computed(() => state),\n data,\n collection: computed(() => collection.value),\n status: computed(() => status.value),\n isLoading: computed(() => status.value === `loading`),\n isReady: computed(\n () => status.value === `ready` || status.value === `disabled`,\n ),\n isIdle: computed(() => status.value === `idle`),\n isError: computed(() => status.value === `error`),\n isCleanedUp: computed(() => status.value === `cleaned-up`),\n }\n}\n"],"names":["computed","toValue","isCollection","createLiveQueryCollection","reactive","isSingleResultCollection","ref","watchEffect","nextTick","getCurrentInstance","onUnmounted"],"mappings":";;;;AAyPO,SAAS,aACd,2BACA,OAAyC,IACkC;AAC3E,QAAM,aAAaA,IAAAA,SAAS,MAAM;AAIhC,QAAI,iBAAiB;AACrB,QAAI,OAAO,8BAA8B,YAAY;AACnD,UAAI;AACF,cAAM,uBAAuBC,IAAAA,QAAQ,yBAAyB;AAC9D,YAAI,yBAAyB,2BAA2B;AACtD,2BAAiB;AAAA,QACnB;AAAA,MACF,QAAQ;AAEN,yBAAiB;AAAA,MACnB;AAAA,IACF;AAGA,UAAM,oBAAoBC,GAAAA,aAAa,cAAc;AAErD,QAAI,mBAAmB;AAIrB,YAAM,WAAY,eACf,QAAQ;AACX,UAAI,aAAa,aAAa;AAC5B,gBAAQ;AAAA,UACN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAAA;AAAA,MAMJ;AAGA,UAAI,eAAe,WAAW,QAAQ;AACpC,uBAAe,mBAAA;AAAA,MACjB;AACA,aAAO;AAAA,IACT;AAGA,SAAK,QAAQ,CAAC,QAAQD,IAAAA,QAAQ,GAAG,CAAC;AAGlC,QAAI,OAAO,mBAAmB,YAAY;AAGxC,YAAM,eAAe,CAAC,MAA2B;AAC/C,cAAM,SAAS,eAAe,CAAC;AAG/B,YAAI,WAAW,UAAa,WAAW,MAAM;AAC3C,gBAAM,IAAI,MAAM,oBAAoB;AAAA,QACtC;AACA,eAAO;AAAA,MACT;AAEA,UAAI;AACF,eAAOE,6BAA0B;AAAA,UAC/B,OAAO;AAAA,UACP,WAAW;AAAA,QAAA,CACZ;AAAA,MACH,SAAS,OAAO;AAEd,YAAI,iBAAiB,SAAS,MAAM,YAAY,sBAAsB;AACpE,iBAAO;AAAA,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,EAAA;AAE7D;;"}
1
+ {"version":3,"file":"useLiveQuery.cjs","sources":["../../src/useLiveQuery.ts"],"sourcesContent":["import {\n computed,\n getCurrentInstance,\n onUnmounted,\n reactive,\n ref,\n toValue,\n watchEffect,\n} from 'vue'\nimport {\n createLiveQueryCollection,\n createLiveQueryObserver,\n isCollection,\n isSingleResultCollection,\n} from '@tanstack/db'\nimport type {\n ChangeMessage,\n Collection,\n CollectionStatus,\n Context,\n GetResult,\n InferResultType,\n InitialQueryBuilder,\n LiveQueryCollectionConfig,\n LiveQueryObserver,\n NonSingleResult,\n QueryBuilder,\n SingleResult,\n} from '@tanstack/db'\nimport type { ComputedRef, MaybeRefOrGetter } from 'vue'\n\n/**\n * Return type for useLiveQuery hook\n * @property state - Reactive Map of query results (key → item)\n * @property data - Reactive array of query results in order, or single result for findOne queries\n * @property collection - The underlying query collection instance\n * @property status - Current query status\n * @property isLoading - True while initial query data is loading\n * @property isReady - True when query has received first data and is ready\n * @property isIdle - True when query hasn't started yet\n * @property isError - True when query encountered an error\n * @property isCleanedUp - True when query has been cleaned up\n */\nexport interface UseLiveQueryReturn<TContext extends Context> {\n state: ComputedRef<Map<string | number, GetResult<TContext>>>\n data: ComputedRef<InferResultType<TContext>>\n collection: ComputedRef<Collection<GetResult<TContext>, string | number, {}>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\nexport interface UseLiveQueryReturnWithCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<Array<T>>\n collection: ComputedRef<Collection<T, TKey, TUtils>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\nexport interface UseLiveQueryReturnWithSingleResultCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<T | undefined>\n collection: ComputedRef<Collection<T, TKey, TUtils> & SingleResult>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\n/**\n * Create a live query using a query function\n * @param queryFn - Query function that defines what data to fetch\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic query with object syntax\n * const { data, isLoading } = useLiveQuery((q) =>\n * q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.completed, false))\n * .select(({ todos }) => ({ id: todos.id, text: todos.text }))\n * )\n *\n * @example\n * // With reactive dependencies\n * const minPriority = ref(5)\n * const { data, state } = useLiveQuery(\n * (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => gt(todos.priority, minPriority.value)),\n * [minPriority] // Re-run when minPriority changes\n * )\n *\n * @example\n * // Join pattern\n * const { data } = useLiveQuery((q) =>\n * q.from({ issues: issueCollection })\n * .join({ persons: personCollection }, ({ issues, persons }) =>\n * eq(issues.userId, persons.id)\n * )\n * .select(({ issues, persons }) => ({\n * id: issues.id,\n * title: issues.title,\n * userName: persons.name\n * }))\n * )\n *\n * @example\n * // Handle loading and error states in template\n * const { data, isLoading, isError, status } = useLiveQuery((q) =>\n * q.from({ todos: todoCollection })\n * )\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error: {{ status }}</div>\n * // <ul v-else>\n * // <li v-for=\"todo in data\" :key=\"todo.id\">{{ todo.text }}</li>\n * // </ul>\n */\n// Overload 1: Accept query function that always returns QueryBuilder\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n// Overload 1b: Accept query function that can return undefined/null\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (\n q: InitialQueryBuilder,\n ) => QueryBuilder<TContext> | undefined | null,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n/**\n * Create a live query using configuration object\n * @param config - Configuration object with query and options\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic config object usage\n * const { data, status } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection }),\n * gcTime: 60000\n * })\n *\n * @example\n * // With reactive dependencies\n * const filter = ref('active')\n * const { data, isReady } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.status, filter.value))\n * }, [filter])\n *\n * @example\n * // Handle all states uniformly\n * const { data, isLoading, isReady, isError } = useLiveQuery({\n * query: (q) => q.from({ items: itemCollection })\n * })\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Something went wrong</div>\n * // <div v-else-if=\"!isReady\">Preparing...</div>\n * // <div v-else>{{ data.length }} items loaded</div>\n */\n// Overload 2: Accept config object\nexport function useLiveQuery<TContext extends Context>(\n config: LiveQueryCollectionConfig<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n/**\n * Subscribe to an existing query collection (can be reactive)\n * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a ref)\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Using pre-created query collection\n * const myLiveQuery = createLiveQueryCollection((q) =>\n * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))\n * )\n * const { data, collection } = useLiveQuery(myLiveQuery)\n *\n * @example\n * // Reactive query collection reference\n * const selectedQuery = ref(todosQuery)\n * const { data, collection } = useLiveQuery(selectedQuery)\n *\n * // Switch queries reactively\n * selectedQuery.value = archiveQuery\n *\n * @example\n * // Access query collection methods directly\n * const { data, collection, isReady } = useLiveQuery(existingQuery)\n *\n * // Use underlying collection for mutations\n * const handleToggle = (id) => {\n * collection.value.update(id, draft => { draft.completed = !draft.completed })\n * }\n *\n * @example\n * // Handle states consistently\n * const { data, isLoading, isError } = useLiveQuery(sharedQuery)\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error loading data</div>\n * // <div v-else>\n * // <Item v-for=\"item in data\" :key=\"item.id\" v-bind=\"item\" />\n * // </div>\n */\n// Overload 3: Accept pre-created live query collection (can be reactive) - non-single result\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & NonSingleResult\n >,\n): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils>\n\n// Overload 4: Accept pre-created live query collection with singleResult: true\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & SingleResult\n >,\n): UseLiveQueryReturnWithSingleResultCollection<TResult, TKey, TUtils>\n\n// Implementation\nexport function useLiveQuery(\n configOrQueryOrCollection: any,\n deps: Array<MaybeRefOrGetter<unknown>> = [],\n): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {\n const collection = computed(() => {\n // First check if the original parameter might be a ref/getter\n // by seeing if toValue returns something different than the original\n // NOTE: Don't call toValue on functions - toValue treats functions as getters and calls them!\n let unwrappedParam = configOrQueryOrCollection\n if (typeof configOrQueryOrCollection !== `function`) {\n try {\n const potentiallyUnwrapped = toValue(configOrQueryOrCollection)\n if (potentiallyUnwrapped !== configOrQueryOrCollection) {\n unwrappedParam = potentiallyUnwrapped\n }\n } catch {\n // If toValue fails, use original parameter\n unwrappedParam = configOrQueryOrCollection\n }\n }\n\n // Check if it's already a collection\n const inputIsCollection = isCollection(unwrappedParam)\n\n if (inputIsCollection) {\n // Warn when passing a collection directly with on-demand sync mode\n // In on-demand mode, data is only loaded when queries with predicates request it\n // Passing the collection directly doesn't provide any predicates, so no data loads\n const syncMode = (unwrappedParam as { config?: { syncMode?: string } })\n .config?.syncMode\n if (syncMode === `on-demand`) {\n console.warn(\n `[useLiveQuery] Warning: Passing a collection with syncMode \"on-demand\" directly to useLiveQuery ` +\n `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\\n\\n` +\n `Instead, use a query builder function:\\n` +\n ` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\\n\\n` +\n `Or switch to syncMode \"eager\" if you want all data to sync automatically.`,\n )\n }\n // It's already a collection, ensure sync is started for Vue hooks\n // Only start sync if the collection is in idle state\n if (unwrappedParam.status === `idle`) {\n unwrappedParam.startSyncImmediate()\n }\n return unwrappedParam\n }\n\n // Reference deps to make computed reactive to them\n deps.forEach((dep) => toValue(dep))\n\n // Ensure we always start sync for Vue hooks\n if (typeof unwrappedParam === `function`) {\n // To avoid calling the query function twice, we wrap it to handle null/undefined returns\n // The wrapper will be called once by createLiveQueryCollection\n const wrappedQuery = (q: InitialQueryBuilder) => {\n const result = unwrappedParam(q)\n // If the query function returns null/undefined, throw a special error\n // that we'll catch to return null collection\n if (result === undefined || result === null) {\n throw new Error(`__DISABLED_QUERY__`)\n }\n return result\n }\n\n try {\n return createLiveQueryCollection({\n query: wrappedQuery,\n startSync: true,\n })\n } catch (error) {\n // Check if this is our special disabled query marker\n if (error instanceof Error && error.message === `__DISABLED_QUERY__`) {\n return null\n }\n // Re-throw other errors\n throw error\n }\n } else {\n return createLiveQueryCollection({\n ...unwrappedParam,\n startSync: true,\n })\n }\n })\n\n // Reactive state that gets updated granularly through change events\n const state = reactive(new Map<string | number, any>())\n\n // Reactive data array that maintains sorted order\n const internalData = reactive<Array<any>>([])\n\n // Computed wrapper for the data to match expected return type\n // Returns single item for singleResult collections, array otherwise\n const data = computed(() => {\n const currentCollection = collection.value\n if (!currentCollection) {\n return internalData\n }\n return isSingleResultCollection(currentCollection)\n ? internalData[0]\n : internalData\n })\n\n // Track collection status reactively\n const status = ref(\n collection.value ? collection.value.status : (`disabled` as const),\n )\n\n // Helper to sync data array from collection in correct order\n const syncDataFromCollection = (\n currentCollection: Collection<any, any, any>,\n ) => {\n internalData.length = 0\n internalData.push(...Array.from(currentCollection.values()))\n }\n\n // The shared observer owns subscription, the ready-race, and status; Vue\n // materializes into its own reactive map (granular) + ordered array.\n let currentObserver: LiveQueryObserver<any, any> | null = null\n\n const syncFromObserver = (\n observer: LiveQueryObserver<any, any>,\n currentCollection: Collection<any, any, any>,\n ) => {\n status.value = observer.getSnapshot().status as CollectionStatus\n syncDataFromCollection(currentCollection)\n }\n\n // Watch for collection changes and subscribe to updates\n watchEffect((onInvalidate) => {\n const currentCollection = collection.value\n\n // Tear down any previous observer.\n currentObserver?.dispose()\n currentObserver = null\n\n // Handle null collection (disabled query)\n if (!currentCollection) {\n status.value = `disabled` as const\n state.clear()\n internalData.length = 0\n return\n }\n\n const observer = createLiveQueryObserver(currentCollection)\n currentObserver = observer\n\n // Initial rows arrive as the observer's first delta (includeInitialState);\n // apply them and every subsequent delta granularly to the reactive map.\n state.clear()\n\n const unsubscribe = observer.subscribe(\n (changes: Array<ChangeMessage<any>> | undefined) => {\n if (changes) {\n for (const change of changes) {\n switch (change.type) {\n case `insert`:\n case `update`:\n state.set(change.key, change.value)\n break\n case `delete`:\n state.delete(change.key)\n break\n }\n }\n } else {\n // Cleanup and other status-only publications carry no row deltas.\n // Rebuild the keyed view so it cannot diverge from ordered data.\n state.clear()\n for (const [key, value] of observer.getSnapshot().state ?? []) {\n state.set(key, value)\n }\n }\n syncFromObserver(observer, currentCollection)\n },\n )\n syncFromObserver(observer, currentCollection)\n\n // Cleanup when effect is invalidated\n onInvalidate(() => {\n unsubscribe()\n observer.dispose()\n currentObserver = null\n })\n })\n\n // Cleanup on unmount (only if we're in a component context)\n const instance = getCurrentInstance()\n if (instance) {\n onUnmounted(() => currentObserver?.dispose())\n }\n\n return {\n state: computed(() => state),\n data,\n collection: computed(() => collection.value),\n status: computed(() => status.value),\n isLoading: computed(() => status.value === `loading`),\n isReady: computed(\n () => status.value === `ready` || status.value === `disabled`,\n ),\n isIdle: computed(() => status.value === `idle`),\n isError: computed(() => status.value === `error`),\n isCleanedUp: computed(() => status.value === `cleaned-up`),\n }\n}\n"],"names":["computed","toValue","isCollection","createLiveQueryCollection","reactive","isSingleResultCollection","ref","watchEffect","createLiveQueryObserver","getCurrentInstance","onUnmounted"],"mappings":";;;;AA0PO,SAAS,aACd,2BACA,OAAyC,IACkC;AAC3E,QAAM,aAAaA,IAAAA,SAAS,MAAM;AAIhC,QAAI,iBAAiB;AACrB,QAAI,OAAO,8BAA8B,YAAY;AACnD,UAAI;AACF,cAAM,uBAAuBC,IAAAA,QAAQ,yBAAyB;AAC9D,YAAI,yBAAyB,2BAA2B;AACtD,2BAAiB;AAAA,QACnB;AAAA,MACF,QAAQ;AAEN,yBAAiB;AAAA,MACnB;AAAA,IACF;AAGA,UAAM,oBAAoBC,GAAAA,aAAa,cAAc;AAErD,QAAI,mBAAmB;AAIrB,YAAM,WAAY,eACf,QAAQ;AACX,UAAI,aAAa,aAAa;AAC5B,gBAAQ;AAAA,UACN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAAA;AAAA,MAMJ;AAGA,UAAI,eAAe,WAAW,QAAQ;AACpC,uBAAe,mBAAA;AAAA,MACjB;AACA,aAAO;AAAA,IACT;AAGA,SAAK,QAAQ,CAAC,QAAQD,IAAAA,QAAQ,GAAG,CAAC;AAGlC,QAAI,OAAO,mBAAmB,YAAY;AAGxC,YAAM,eAAe,CAAC,MAA2B;AAC/C,cAAM,SAAS,eAAe,CAAC;AAG/B,YAAI,WAAW,UAAa,WAAW,MAAM;AAC3C,gBAAM,IAAI,MAAM,oBAAoB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AA;AAE7D;;"}
@@ -1,4 +1,5 @@
1
1
  export * from './useLiveQuery.js';
2
+ export * from './useLiveInfiniteQuery.js';
2
3
  export * from '@tanstack/db';
3
4
  export type { Collection } from '@tanstack/db';
4
5
  export { createTransaction } from '@tanstack/db';
package/dist/esm/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { useLiveQuery } from "./useLiveQuery.js";
2
+ import { useLiveInfiniteQuery } from "./useLiveInfiniteQuery.js";
2
3
  export * from "@tanstack/db";
3
4
  import { createTransaction } from "@tanstack/db";
4
5
  export {
5
6
  createTransaction,
7
+ useLiveInfiniteQuery,
6
8
  useLiveQuery
7
9
  };
8
10
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}
@@ -0,0 +1,55 @@
1
+ import { Collection, CollectionStatus, Context, GetResult, InferResultType, InitialQueryBuilder, NonSingleResult, QueryBuilder, UtilsRecord } from '@tanstack/db';
2
+ import { ComputedRef, MaybeRefOrGetter } from 'vue';
3
+ type InfiniteQueryOptions = {
4
+ pageSize?: number;
5
+ initialPageParam?: number;
6
+ };
7
+ export type LiveInfiniteQueryConfig<TRow> = InfiniteQueryOptions & {
8
+ /**
9
+ * @deprecated Pagination uses the shared controller's peek-ahead strategy.
10
+ * This remains for compatibility with TanStack Query conventions.
11
+ */
12
+ getNextPageParam?: (lastPage: Array<TRow>, allPages: Array<Array<TRow>>, lastPageParam: number, allPageParams: Array<number>) => number | undefined;
13
+ };
14
+ export type UseLiveInfiniteQueryConfig<TContext extends Context & NonSingleResult> = LiveInfiniteQueryConfig<InferResultType<TContext>[number]>;
15
+ export interface UseLiveInfiniteQueryReturn<TContext extends Context & NonSingleResult> {
16
+ state: ComputedRef<Map<string | number, GetResult<TContext>>>;
17
+ data: ComputedRef<InferResultType<TContext>>;
18
+ collection: ComputedRef<Collection<GetResult<TContext>, string | number, UtilsRecord>>;
19
+ status: ComputedRef<CollectionStatus>;
20
+ isLoading: ComputedRef<boolean>;
21
+ isReady: ComputedRef<boolean>;
22
+ isIdle: ComputedRef<boolean>;
23
+ isError: ComputedRef<boolean>;
24
+ isCleanedUp: ComputedRef<boolean>;
25
+ pages: ComputedRef<Array<Array<InferResultType<TContext>[number]>>>;
26
+ pageParams: ComputedRef<Array<number>>;
27
+ fetchNextPage: () => Promise<void>;
28
+ hasNextPage: ComputedRef<boolean>;
29
+ isFetchingNextPage: ComputedRef<boolean>;
30
+ error: ComputedRef<unknown>;
31
+ }
32
+ export interface UseLiveInfiniteQueryReturnWithCollection<TResult extends object, TKey extends string | number, TUtils extends UtilsRecord> {
33
+ state: ComputedRef<Map<TKey, TResult>>;
34
+ data: ComputedRef<Array<TResult>>;
35
+ collection: ComputedRef<Collection<TResult, TKey, TUtils>>;
36
+ status: ComputedRef<CollectionStatus>;
37
+ isLoading: ComputedRef<boolean>;
38
+ isReady: ComputedRef<boolean>;
39
+ isIdle: ComputedRef<boolean>;
40
+ isError: ComputedRef<boolean>;
41
+ isCleanedUp: ComputedRef<boolean>;
42
+ pages: ComputedRef<Array<Array<TResult>>>;
43
+ pageParams: ComputedRef<Array<number>>;
44
+ fetchNextPage: () => Promise<void>;
45
+ hasNextPage: ComputedRef<boolean>;
46
+ isFetchingNextPage: ComputedRef<boolean>;
47
+ error: ComputedRef<unknown>;
48
+ }
49
+ /**
50
+ * Create a Vue-native reactive view over the shared live-query window
51
+ * controller. The query must include an `orderBy` clause.
52
+ */
53
+ export declare function useLiveInfiniteQuery<TResult extends object, TKey extends string | number, TUtils extends UtilsRecord>(liveQueryCollection: MaybeRefOrGetter<Collection<TResult, TKey, TUtils> & NonSingleResult>, config: LiveInfiniteQueryConfig<TResult>): UseLiveInfiniteQueryReturnWithCollection<TResult, TKey, TUtils>;
54
+ export declare function useLiveInfiniteQuery<TContext extends Context & NonSingleResult>(queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>, config: UseLiveInfiniteQueryConfig<TContext>, deps?: Array<MaybeRefOrGetter<unknown>>): UseLiveInfiniteQueryReturn<TContext>;
55
+ export {};
@@ -0,0 +1,116 @@
1
+ import { computed, toValue, shallowRef, watchEffect } from "vue";
2
+ import { normalizeLiveQueryWindowPageSize, resolveLiveQueryWindowInput, compareLiveQueryWindowDependencies, shouldPreserveLiveQueryWindowPageCount, getLiveQueryWindowCollectionWarning, createLiveQueryWindowController, createLiveQueryCollection, assertLiveQueryWindowManyResult, fetchNextLiveQueryWindowPage } from "@tanstack/db";
3
+ const DEFAULT_GC_TIME_MS = 1;
4
+ function useLiveInfiniteQuery(queryFnOrCollection, config, deps = []) {
5
+ let validatedCollection = null;
6
+ let previousController = null;
7
+ let previousInput = null;
8
+ let previousDependencies = null;
9
+ let previousPageSize = null;
10
+ let previousInitialPageParam = null;
11
+ const controller = computed(() => {
12
+ const dependencies = deps.map((dependency) => toValue(dependency));
13
+ const pageSize = normalizeLiveQueryWindowPageSize(config.pageSize);
14
+ const initialPageParam = config.initialPageParam ?? 0;
15
+ const unwrappedInput = typeof queryFnOrCollection === `function` ? queryFnOrCollection : toValue(queryFnOrCollection);
16
+ const input = resolveLiveQueryWindowInput(unwrappedInput);
17
+ const dependencyComparison = compareLiveQueryWindowDependencies(
18
+ previousDependencies,
19
+ dependencies
20
+ );
21
+ const dependenciesChanged = dependencyComparison.changed;
22
+ const dependenciesStructurallyEqual = dependencyComparison.structurallyEqual;
23
+ const pageShapeChanged = previousPageSize !== pageSize || previousInitialPageParam !== initialPageParam;
24
+ const sameCollection = input.kind === `collection` && previousInput?.kind === `collection` && previousInput.collection === input.collection;
25
+ const canPreservePageCount = shouldPreserveLiveQueryWindowPageCount({
26
+ hasPreviousController: previousController !== null,
27
+ previousInputKind: previousInput?.kind,
28
+ inputKind: input.kind,
29
+ sameCollection,
30
+ dependenciesChanged,
31
+ dependenciesStructurallyEqual,
32
+ pageShapeChanged
33
+ });
34
+ const previousPageCount = previousController ? Math.max(1, previousController.getSnapshot().pages.length) : 1;
35
+ const initialPageCount = canPreservePageCount ? previousPageCount : 1;
36
+ previousInput = input;
37
+ previousDependencies = [...dependencies];
38
+ previousPageSize = pageSize;
39
+ previousInitialPageParam = initialPageParam;
40
+ if (input.kind === `collection`) {
41
+ const collection2 = input.collection;
42
+ const warning = getLiveQueryWindowCollectionWarning(
43
+ collection2,
44
+ pageSize + 1
45
+ );
46
+ if (validatedCollection !== collection2) {
47
+ validatedCollection = collection2;
48
+ if (warning) console.warn(warning);
49
+ }
50
+ const currentController2 = createLiveQueryWindowController(collection2, {
51
+ pageSize,
52
+ initialPageParam,
53
+ initialPageCount
54
+ });
55
+ previousController = currentController2;
56
+ return currentController2;
57
+ }
58
+ const collection = createLiveQueryCollection({
59
+ query: input.query.limit(pageSize + 1).offset(0),
60
+ startSync: false,
61
+ gcTime: DEFAULT_GC_TIME_MS
62
+ });
63
+ assertLiveQueryWindowManyResult(collection);
64
+ const currentController = createLiveQueryWindowController(collection, {
65
+ pageSize,
66
+ initialPageParam,
67
+ initialPageCount
68
+ });
69
+ previousController = currentController;
70
+ return currentController;
71
+ });
72
+ const snapshot = shallowRef(controller.value.getSnapshot());
73
+ watchEffect(
74
+ (onInvalidate) => {
75
+ const currentController = controller.value;
76
+ const updateSnapshot = () => {
77
+ snapshot.value = currentController.getSnapshot();
78
+ };
79
+ updateSnapshot();
80
+ const unsubscribe = currentController.subscribe(updateSnapshot);
81
+ updateSnapshot();
82
+ onInvalidate(() => {
83
+ unsubscribe();
84
+ currentController.dispose();
85
+ });
86
+ },
87
+ { flush: `sync` }
88
+ );
89
+ return {
90
+ state: computed(
91
+ () => snapshot.value.state
92
+ ),
93
+ data: computed(() => snapshot.value.data),
94
+ collection: computed(
95
+ () => snapshot.value.collection
96
+ ),
97
+ status: computed(() => snapshot.value.status),
98
+ isLoading: computed(() => snapshot.value.isLoading),
99
+ isReady: computed(() => snapshot.value.isReady),
100
+ isIdle: computed(() => snapshot.value.isIdle),
101
+ isError: computed(() => snapshot.value.isError),
102
+ isCleanedUp: computed(() => snapshot.value.isCleanedUp),
103
+ pages: computed(
104
+ () => snapshot.value.pages
105
+ ),
106
+ pageParams: computed(() => snapshot.value.pageParams),
107
+ fetchNextPage: () => fetchNextLiveQueryWindowPage(controller.value),
108
+ hasNextPage: computed(() => snapshot.value.hasNextPage),
109
+ isFetchingNextPage: computed(() => snapshot.value.isFetchingNextPage),
110
+ error: computed(() => snapshot.value.error)
111
+ };
112
+ }
113
+ export {
114
+ useLiveInfiniteQuery
115
+ };
116
+ //# sourceMappingURL=useLiveInfiniteQuery.js.map