@tanstack/solid-query 6.0.0-rc.4 → 6.0.0-rc.6
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 +2 -2
- package/build/dev.cjs +1470 -849
- package/build/dev.js +1455 -842
- package/build/index.cjs +3 -913
- package/build/index.d.cts +1191 -177
- package/build/index.d.cts.map +1 -0
- package/build/index.d.ts +1191 -177
- package/build/index.d.ts.map +1 -0
- package/build/index.js +4 -896
- package/build/index.js.map +1 -0
- package/package.json +23 -24
- package/src/QueryClient.ts +24 -0
- package/src/QueryClientProvider.tsx +33 -16
- package/src/cacheAggregate.ts +6 -3
- package/src/dehydrateSettled.ts +3 -0
- package/src/index.ts +1 -1
- package/src/infiniteQueryOptions.ts +117 -8
- package/src/isRestoring.ts +6 -0
- package/src/mutationOptions.ts +51 -0
- package/src/queryOptions.ts +112 -13
- package/src/types.ts +115 -3
- package/src/useBaseQuery.ts +93 -53
- package/src/useInfiniteQuery.ts +133 -11
- package/src/useIsFetching.ts +21 -1
- package/src/useIsMutating.ts +20 -1
- package/src/useMutation.ts +19 -9
- package/src/useMutationState.ts +108 -7
- package/src/useQueries.ts +86 -1
- package/src/useQuery.ts +207 -4
- package/build/_tsup-dts-rollup.d.cts +0 -922
- package/build/_tsup-dts-rollup.d.ts +0 -922
- package/build/dev.d.cts +0 -177
- package/build/dev.d.ts +0 -177
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["QueryCoreClient","createContext","isHydratable","onCleanup","useContext","REVALIDATE_HEADER","getHydrationWriter","hydrate","subscribeFlightData","isServer","window","HYDRATION_KEY_PREFIX","FLIGHT_DATA_SOURCE","REVALIDATE_ALL","sweepRevalidatedQueries","client","payload","response","declared","headers","get","covered","Set","queries","map","query","queryHash","uncovered","has","keys","split","includes","invalidateQueries","predicate","catch","undefined","key","queryKey","QueryClientContext","useQueryClient","queryClient","Error","serializeCacheOnServer","writer","async","cache","getQueryCache","shouldDehydrateQuery","getDefaultOptions","dehydrate","seen","serializeQuery","state","status","add","write","data","t","dataUpdatedAt","fetchStatus","promise","then","getAll","subscribe","event","QueryClientProvider","props","mount","unmount","cancelQueries","clear","context","_$createComponent","value","children","isServer","_$createComponent","isServer","isPending","isValuePending","isServer","QueryClient$1","QueryClient","config","isServer$3","FLIGHT_DATA_SOURCE","sweepRevalidatedQueries","declared","response","REVALIDATE_HEADER","covered","payload","query","uncovered","keys","client","key","QueryClientContext","createContext","useQueryClient","queryClient","useContext","serializeCacheOnServer","writer","getHydrationWriter","isHydratable","cache","shouldDehydrateQuery","seen","serializeQuery","state","promise","onCleanup","event","QueryClientProvider","props","subscribeFlightData","data","hydrate","context","createComponent","IsRestoringContext","useIsRestoring","isServer$2","NEVER","noop","metaFrom","useBaseQuery","useBaseQueryLayer","options","Observer","createMemo","isRestoring","latestHash","latestOptions","defaultedOptions","defaulted","observer","untrack","lastAppliedHash","createRenderEffect","opts","hydratedMount","isHydrating","version","setVersion","createSignal","primed","setPrimed","onCacheEvent","v","observerSub","cacheSub","disposed","shouldAttach","activeClient","lastQuery","attach","syncClient","c","prime","entry","runWithOwner","registryKey","primeAndAttach","settle","takeHydrationValue","restoring","lookupQuery","existing","isEnabled","resolvePlaceholder","placeholder","chained","chainOnce","base","select","wrap","computeData","q","d","prev","shouldThrowError","dataStore","createProjection","draft","serverMeta","metaProjection","meta","mountedAt","hasPlaceholder","status","isPending$1","isFetching","isPending","isError","isStale","staleTime","resolve","refetchOptions","useQuery","QueryObserver","queryOptions","dehydrateSettled","pending","dehydrate","isServer$1","createCacheAggregate","durable","setDurable","empty","read","value","setValue","createOptimistic","sync","next","unsubscribe","subscribe","createEffect","useIsFetching","onEvent","filters","hasNextPage","lastIndex","hasPreviousPage","useInfiniteQuery","layer","InfiniteQueryObserver","direction","pageOptions","infiniteData","isFetchingPage","current","expected","isFetchingNextPage","isFetchingPreviousPage","fetchOptions","infiniteQueryOptions","isServer","IDLE","drain","input","result","iterator","useMutation","flight","setFlight","settled","setSettled","activeMutation","unsubscribeFlight","flightVersion","setFlightVersion","run","callbackContext","variables","mutation","settleFlight","settleFailure","error","callbackError","invoke","action","mutate","args","mutationOptions","useIsMutating","getResult","mutationCache","useMutationState","replaceEqualDeep","useQueries","length","queriesOptions","results","repeat","lastOptions","index","combined","combine","list","prop","$TRACK","descriptor"],"sources":["../src/QueryClient.ts","../src/QueryClientProvider.tsx","../src/isRestoring.ts","../src/useBaseQuery.ts","../src/useQuery.ts","../src/queryOptions.ts","../src/dehydrateSettled.ts","../src/cacheAggregate.ts","../src/useIsFetching.ts","../src/useInfiniteQuery.ts","../src/infiniteQueryOptions.ts","../src/useMutation.ts","../src/mutationOptions.ts","../src/useIsMutating.ts","../src/useMutationState.ts","../src/useQueries.ts","../src/index.ts"],"sourcesContent":["import { QueryClient as QueryCoreClient } from '@tanstack/query-core'\nimport type {\n DefaultOptions as CoreDefaultOptions,\n DefaultError,\n OmitKeyof,\n QueryClientConfig as QueryCoreClientConfig,\n InfiniteQueryObserverOptions as QueryCoreInfiniteQueryObserverOptions,\n QueryObserverOptions as QueryCoreObserverOptions,\n QueryKey,\n} from '@tanstack/query-core'\n\n/**\n * Core observer options pass through unchanged. The old adapter omitted\n * `structuralSharing` and replaced it with a store-level `reconcile`\n * option; with reads derived directly from cache state, core's\n * cache-level structural sharing is exactly what keeps the data memo\n * referentially stable, so it is exposed again and `reconcile` is gone.\n */\nexport type QueryObserverOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = never,\n> = QueryCoreObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey,\n TPageParam\n>\n\n/**\n * The core `InfiniteQueryObserverOptions`, passed through unchanged.\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type InfiniteQueryObserverOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = QueryCoreInfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n>\n\n/**\n * The default options a `QueryClient` applies to every query and mutation.\n * @template TError - The default type of errors thrown by queries and mutations using this `QueryClient`.\n */\nexport interface DefaultOptions<\n TError = DefaultError,\n> extends CoreDefaultOptions<TError> {\n /**\n * Default options applied to every query, unless overridden per-query.\n */\n queries?: OmitKeyof<QueryObserverOptions<unknown, TError>, 'queryKey'>\n}\n\n/**\n * The config accepted by `new QueryClient(config)`, with Solid's {@link DefaultOptions}.\n */\nexport interface QueryClientConfig extends QueryCoreClientConfig {\n /**\n * The default options of the queries and mutations of this `QueryClient`.\n */\n defaultOptions?: DefaultOptions\n}\n\n/**\n * The core `@tanstack/query-core` `QueryClient`, typed with Solid's {@link QueryClientConfig}.\n */\nexport class QueryClient extends QueryCoreClient {\n constructor(config: QueryClientConfig = {}) {\n super(config)\n }\n}\n","import { createContext, isHydratable, onCleanup, useContext } from 'solid-js'\nimport { REVALIDATE_HEADER, getHydrationWriter } from '@solidjs/web'\nimport { hydrate } from '@tanstack/query-core'\nimport { subscribeFlightData } from '@solidjs/web/server-functions'\nimport type { DehydratedState, Query } from '@tanstack/query-core'\nimport type { QueryClient } from './QueryClient'\nimport type { JSX } from '@solidjs/web'\n\nconst isServer = typeof window === 'undefined'\n\n/**\n * Namespace prefix for cache entries in Solid's hydration registry — the\n * registry is shared with positional node ids and other libraries'\n * content-addressed keys (Solid Router uses its own cache keys), so query\n * hashes get their own prefix.\n */\nexport const HYDRATION_KEY_PREFIX = 'sq:'\n\n/**\n * The query cache's single-flight source id. Mutation responses can fold\n * fresh data for multiple caches at once (Solid's multi-source\n * single-flight protocol); this is the slice the query cache claims — the\n * provider subscribes its consumer under it, and server collectors\n * register under it to produce the data:\n *\n * ```ts\n * import { registerFlightDataSource } from '@solidjs/web/server-functions/server'\n * import { FLIGHT_DATA_SOURCE, dehydrate } from '@tanstack/solid-query'\n *\n * registerFlightDataSource(FLIGHT_DATA_SOURCE, async (event, outcome) => {\n * // rebuild the data for outcome.targetUrl into a QueryClient, then\n * return dehydrate(queryClient)\n * })\n * ```\n *\n * The slice's payload is a `DehydratedState`; the provider consumes it\n * with `hydrate()`, so every mounted query on those keys updates before\n * the mutation's promise resolves — no follow-up refetches.\n *\n * A mutation can additionally declare its invalidation SCOPE with\n * `X-Revalidate` keys (the `revalidate` option of Solid's `reload`/\n * `redirect`/`respond` response helpers). The payload covers the slice of\n * that scope the server could recompute; whatever a declared key matches\n * beyond it is swept client-side (see the consumer below). The transport\n * delivers a response carrying keys to the consumer whether or not the\n * collector contributed a slice — with no slice, the whole scope is swept.\n */\nexport const FLIGHT_DATA_SOURCE = 'sq'\n\n/**\n * The reserved `X-Revalidate` key meaning every entry: `revalidate: '*'`\n * on Solid's response helpers. Named so a host that keys its cache\n * differently still reads the same spelling as \"all\".\n */\nconst REVALIDATE_ALL = '*'\n\n/**\n * The client half of key-scoped invalidation. A mutation declares its\n * invalidation scope with `X-Revalidate` keys; the flight payload covers\n * the part of that scope the server's collector recomputed (typically the\n * target page's loader graph). Whatever a declared key matches BEYOND the\n * payload — parameterized instances only this client holds, queries no\n * loader owns — is invalidated here: active queries refetch in the\n * background, inactive ones are marked stale for their next mount. This\n * mirrors how Solid Router consumes the same header for its own cache.\n *\n * A key matches by queryKey prefix — `revalidate: 'users'` sweeps every\n * query whose key begins with `'users'`. Payload-covered hashes are exempt:\n * they hydrated with fresh data a moment ago, and refetching them would\n * spend the round trip single flight just saved. The payload is absent\n * when the server folded no slice for this cache (no collector registered,\n * a redirect leaving the app) — then nothing is covered and the declared\n * scope is swept in full.\n *\n * The header's three states are three scopes. Absent: the mutation\n * declared nothing, and this cache is left as it is — the route data the\n * router reloads is its own business, and a response helper without\n * `revalidate` is a host-default that Solid Router reads as \"everything\"\n * but the query cache does not presume. Empty (`revalidate: []`): nothing,\n * explicitly. The reserved key `*` (`revalidate: '*'`): every query in the\n * cache, minus what the payload covered — the way to say \"all\" to any\n * host, rather than relying on one host's default.\n * @param client - The `QueryClient` whose queries are invalidated.\n * @param payload - The dehydrated slice the response carried for this cache, if any.\n * @param response - The mutation response, read for its `X-Revalidate` header.\n */\nfunction sweepRevalidatedQueries(\n client: QueryClient,\n payload: DehydratedState | undefined,\n response: Response,\n): void {\n const declared = response.headers.get(REVALIDATE_HEADER)\n if (declared === null) return\n const covered = new Set(\n payload?.queries.map((query) => query.queryHash) ?? [],\n )\n const uncovered = (query: Query) => !covered.has(query.queryHash)\n const keys = declared.split(',')\n // Background refetch failures surface through the queries' own error\n // states; an unhandled rejection here would fail the mutation instead.\n if (keys.includes(REVALIDATE_ALL)) {\n client.invalidateQueries({ predicate: uncovered }).catch(() => undefined)\n return\n }\n for (const key of keys) {\n // An empty key is the empty declaration's spelling, not a prefix that\n // happens to match everything.\n if (!key) continue\n client\n .invalidateQueries({ queryKey: [key], predicate: uncovered })\n .catch(() => undefined)\n }\n}\n\nexport const QueryClientContext = createContext<(() => QueryClient) | null>(\n null,\n)\n\n/**\n * The `useQueryClient` primitive returns the current `QueryClient` instance.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns The current `QueryClient` instance.\n * @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the\n * component tree.\n */\nexport const useQueryClient = (queryClient?: QueryClient) => {\n if (queryClient) {\n return queryClient\n }\n const client = useContext(QueryClientContext)\n\n if (!client) {\n throw new Error('No QueryClient set, use QueryClientProvider to set one')\n }\n\n return client()\n}\n\n/**\n * The props accepted by `QueryClientProvider`.\n */\nexport type QueryClientProviderProps = {\n /**\n * **Required**\n *\n * The `QueryClient` instance to provide.\n */\n client: QueryClient\n /**\n * The components that get access to the provided `QueryClient`.\n */\n children?: JSX.Element\n}\n\n/**\n * Server side of hydration: serialize every query the request touches into\n * Solid's hydration registry, content-addressed by query hash (the Solid\n * Router `query()` pattern). Serialization happens at fetch-DISPATCH time —\n * synchronously, while the request's serialization context is live — by\n * handing seroval the fetch promise; it streams the `{ data, t }` payload\n * whenever the fetch settles. Settled entries (initialData, setQueryData,\n * loader prefetches that already landed) serialize their value directly.\n *\n * Content addressing is what makes this cover MORE than rendered\n * components: a query prefetched in a loader and never read by any\n * component still transfers, and any client hook (hydrating or mounted\n * long after) finds it by hash. One entry per hash regardless of how many\n * hooks read it; the payload object is the same reference the data nodes\n * serialize, so seroval's cross-reference dedupe emits it once.\n * @param client - The request's `QueryClient`.\n */\nfunction serializeCacheOnServer(client: QueryClient): void {\n const writer = getHydrationWriter()\n if (!writer || !writer.async || !isHydratable()) return\n\n const cache = client.getQueryCache()\n // The standard dehydrate filter gates the wire here too, so apps keep\n // sensitive or oversized queries out of the HTML with the same option\n // they'd pass any other transport.\n const shouldDehydrateQuery =\n client.getDefaultOptions().dehydrate?.shouldDehydrateQuery\n const seen = new Set<string>()\n const serializeQuery = (query: Query<any, any, any, any>) => {\n if (seen.has(query.queryHash)) return\n // Consulted per cache event until it passes, so a filter that rejects\n // pending queries (e.g. the core default) still admits the settled\n // value if it lands while the request's serialization context is live.\n if (shouldDehydrateQuery && !shouldDehydrateQuery(query)) return\n const state = query.state\n if (state.status === 'success') {\n seen.add(query.queryHash)\n writer.write(HYDRATION_KEY_PREFIX + query.queryHash, {\n data: state.data,\n t: state.dataUpdatedAt,\n })\n } else if (state.fetchStatus !== 'idle') {\n // Serialize the PROMISE now, while the context is live — the settle\n // event fires from IO, where no request context exists anymore.\n const promise = query.promise as Promise<unknown> | undefined\n if (!promise) return\n seen.add(query.queryHash)\n writer.write(\n HYDRATION_KEY_PREFIX + query.queryHash,\n promise.then(() => ({\n data: query.state.data,\n t: query.state.dataUpdatedAt,\n })),\n )\n }\n }\n\n for (const query of cache.getAll()) serializeQuery(query)\n onCleanup(cache.subscribe((event) => serializeQuery(event.query)))\n}\n\n/**\n * Provides the QueryClient and manages its mount lifecycle. On the server\n * it also registers the cache serializer above; on the client, hooks prime\n * the cache from their hash-keyed registry entries themselves (see\n * `useBaseQuery`) and the provider subscribes the cache's single-flight\n * consumer: mutation responses carrying a `FLIGHT_DATA_SOURCE` slice (a\n * `DehydratedState` produced by a server collector registered under the\n * same id) hydrate this client before the mutation's promise resolves.\n * Subscribing is inert when no server collector exists — the server just\n * folds nothing — so it is unconditional. One consumer per source: with\n * nested providers, the innermost mounted one owns the slice.\n * @param props - The `client` to provide, and the `children` that get access to it.\n * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.\n */\nexport const QueryClientProvider = (\n props: QueryClientProviderProps,\n): JSX.Element => {\n props.client.mount()\n onCleanup(() => props.client.unmount())\n if (isServer) {\n serializeCacheOnServer(props.client)\n // Render disposal ends the request: abort what's still in flight and\n // drop the cache so user-configured finite gcTime timers can't pin\n // the per-request client (and whatever its queries closed over) until\n // they fire. Serialized promises are already in seroval's hands, so\n // clearing here can't affect the streamed payload.\n onCleanup(() => {\n props.client.cancelQueries().catch(() => undefined)\n props.client.clear()\n })\n } else {\n // Client-only: the server's consumer registry is module state shared\n // across requests — registering there would leak between them.\n onCleanup(\n subscribeFlightData<DehydratedState>(\n FLIGHT_DATA_SOURCE,\n (data, context) => {\n // `data` is undefined for a response that carried metadata but\n // no slice for this cache.\n if (data) hydrate(props.client, data)\n // Fresh data first, then the declared-scope sweep: stale marks\n // land synchronously, refetches run in the background — the\n // mutation's promise never waits on them.\n sweepRevalidatedQueries(props.client, data, context.response)\n },\n ),\n )\n }\n\n return (\n <QueryClientContext value={() => props.client}>\n {props.children}\n </QueryClientContext>\n )\n}\n","import { createContext, useContext } from 'solid-js'\nimport type { Accessor } from 'solid-js'\n\nexport const IsRestoringContext = createContext<Accessor<boolean>>(() => false)\n\n/**\n * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` primitive alongside it to\n * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid\n * race conditions between the restore and mounting queries.\n * @returns An accessor that reads `true` while a persisted client is being restored, `false` otherwise.\n */\nexport const useIsRestoring = () => useContext(IsRestoringContext)\n","import { hydrate, noop, shouldThrowError } from '@tanstack/query-core'\nimport {\n createMemo,\n createProjection,\n createRenderEffect,\n createSignal,\n isHydrating,\n isPending as isValuePending,\n onCleanup,\n resolve,\n runWithOwner,\n untrack,\n} from 'solid-js'\nimport { takeHydrationValue } from '@solidjs/web'\nimport { HYDRATION_KEY_PREFIX, useQueryClient } from './QueryClientProvider'\nimport { useIsRestoring } from './isRestoring'\nimport type { UseBaseQueryOptions, UseBaseQueryResult } from './types'\nimport type { Accessor } from 'solid-js'\nimport type { QueryClient } from './QueryClient'\nimport type {\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserver,\n QueryObserverResult,\n QueryState,\n} from '@tanstack/query-core'\n\nconst isServer = typeof window === 'undefined'\n\n/**\n * A read of a pending-idle query (disabled, or reset with nothing in flight)\n * has no value and nothing to wait on. Parking the reader on a promise that\n * never resolves suspends it into the nearest `<Loading>` boundary until the\n * query actually starts fetching (enabling it, a refetch, a cache write) —\n * at which point the version bump re-runs the compute and the superseded\n * in-flight is ignored by the engine.\n */\nconst NEVER: Promise<never> = new Promise(noop)\n\n/** The scalar half of QueryState — `data` flows through the async node, not here. */\ntype MetaState = Omit<QueryState<unknown, unknown>, 'data' | 'fetchMeta'>\n\n/**\n * A cache entry in Solid's hydration registry, serialized by the\n * provider under `sq:<queryHash>` — see `serializeCacheOnServer`.\n */\ninterface HydratedEntry {\n data: unknown\n t: number\n}\n\n/**\n * Copies the scalar fields of a query's state, leaving out `data` and `fetchMeta`.\n * @param state - The query state to copy from.\n * @returns The scalar metadata.\n */\nfunction metaFrom(state: QueryState<any, any>): MetaState {\n return {\n dataUpdateCount: state.dataUpdateCount,\n dataUpdatedAt: state.dataUpdatedAt,\n error: state.error,\n errorUpdateCount: state.errorUpdateCount,\n errorUpdatedAt: state.errorUpdatedAt,\n fetchFailureCount: state.fetchFailureCount,\n fetchFailureReason: state.fetchFailureReason,\n fetchStatus: state.fetchStatus,\n isInvalidated: state.isInvalidated,\n status: state.status,\n }\n}\n\n/**\n * Internal seam: everything the read layer builds, for hooks that extend\n * the base result (`useInfiniteQuery` pagers ride the same entry).\n */\ninterface BaseQueryLayer<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n> {\n result: UseBaseQueryResult<TData, TError>\n observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>\n /** Version-tracked: reading it subscribes to this query's cache events. */\n query: () => Query<TQueryFnData, TError, TQueryData, TQueryKey>\n defaultedOptions: Accessor<ReturnType<QueryClient['defaultQueryOptions']>>\n isFetching: () => boolean\n status: () => 'pending' | 'error' | 'success'\n}\n\n/**\n * Base Query Function that is used to create the query.\n * @param options - A function that returns the query options.\n * @param Observer - The observer class from query-core (`QueryObserver` or\n * `InfiniteQueryObserver`).\n * @param queryClient - A function that returns a custom `QueryClient`. Otherwise, the one from the\n * nearest context is used.\n * @returns The reactive query result.\n */\nexport function useBaseQuery<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: Accessor<\n UseBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>\n >,\n Observer: typeof QueryObserver,\n queryClient?: Accessor<QueryClient>,\n): UseBaseQueryResult<TData, TError> {\n return useBaseQueryLayer(options, Observer, queryClient).result\n}\n\n/**\n * Builds the read layer behind `useBaseQuery` and exposes its internals to hooks that extend it.\n * @param options - A function that returns the query options.\n * @param Observer - The observer class from query-core (`QueryObserver` or\n * `InfiniteQueryObserver`).\n * @param queryClient - A function that returns a custom `QueryClient`. Otherwise, the one from the\n * nearest context is used.\n * @returns The query result, with the observer, the version-tracked query accessor, the defaulted\n * options, and the `isFetching` and `status` accessors.\n */\nexport function useBaseQueryLayer<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: Accessor<\n UseBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>\n >,\n Observer: typeof QueryObserver,\n queryClient?: Accessor<QueryClient>,\n): BaseQueryLayer<TQueryFnData, TError, TData, TQueryData, TQueryKey> {\n const client = createMemo(() => useQueryClient(queryClient?.()))\n const isRestoring = useIsRestoring()\n\n /**\n * The most recently computed hash, updated on every options compute —\n * including holds, where the memo's committed face still serves the old\n * options. The cache-event filter below must match both: on a key switch\n * the new key's fetch settles *before* the hold commits, so filtering by\n * the committed hash alone drops that settle event and nothing downstream\n * (data recompute, meta projection) ever learns the fetch finished.\n */\n let latestHash: string | undefined\n let latestOptions:\n | DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >\n | undefined\n const defaultedOptions = createMemo(() => {\n const defaulted = client().defaultQueryOptions(options())\n defaulted._optimisticResults = isRestoring() ? 'isRestoring' : 'optimistic'\n if (isServer) {\n defaulted.retry = false\n defaulted.throwOnError = true\n }\n latestHash = defaulted.queryHash\n latestOptions = defaulted\n return defaulted\n })\n\n /**\n * The observer is a lifecycle/policy engine only. Registering it pins the\n * query against garbage collection, engages mount-fetch policy\n * (`shouldFetchOnMount`), schedules `refetchInterval`, and gates\n * focus/reconnect refetches — all of which live behind observer\n * registration in query-core. Reactivity never touches its notifications\n * or result objects: the listener is a noop, and the reactive layer below\n * derives everything from cache events and fetch promises.\n *\n * `let`, not `const`: a reactive `queryClient` accessor can swap clients\n * mid-life, and the observer must be rebuilt against the new client (see\n * `syncClient` below).\n */\n let observer = untrack(() => new Observer(client(), defaultedOptions()))\n // Fetching and refetching can advance observer.options during a hold.\n let lastAppliedHash = observer.options.queryHash\n\n createRenderEffect(\n () => defaultedOptions(),\n (opts) => {\n lastAppliedHash = opts.queryHash\n observer.setOptions(opts)\n },\n )\n\n /**\n * Solid's own \"this component is being hydrated\" answer, captured at\n * setup. Always false on the server.\n */\n const hydratedMount = isHydrating()\n\n /**\n * One version signal per hook, bumped by cache events for this query hash.\n * This is the entire subscription model: any state transition on the query\n * (fetch dispatch, settle, invalidation, `setQueryData`, removal) re-runs\n * the derived reads below, which pull fresh state/promises from the cache.\n *\n * `ownedWrite`: a compute that reads through `query()` can itself create\n * the cache entry (`cache.build` → synchronous 'added' event → this\n * write), so the first bump can land inside whatever computation pulled\n * the entry into existence. This is channel-owned state, not that\n * computation's own — the same pattern as the router's per-key version\n * signals.\n */\n const [version, setVersion] = createSignal(0, { ownedWrite: true })\n /**\n * Whether this hook's serialized data entry has been applied to the\n * cache (or was determined not to exist). Non-hydrated mounts are born\n * primed. Gates the pull-model fetch: hydration's takeover recompute can\n * run against a cache the priming hasn't reached yet, and fetching there\n * would race data the stream already delivered. Created on both sides\n * (unread on the server) for hydration id parity.\n */\n const [primed, setPrimed] = createSignal(!hydratedMount, {\n ownedWrite: true,\n })\n const onCacheEvent = (event: { query: { queryHash: string } }) => {\n // Match the last hash applied by the render effect OR the latest\n // computed one without reading a potentially held memo.\n if (\n event.query.queryHash === lastAppliedHash ||\n event.query.queryHash === latestHash\n ) {\n setVersion((v) => v + 1)\n }\n }\n\n let observerSub: (() => void) | null = null\n let cacheSub: (() => void) | null = null\n let disposed = false\n /**\n * Set once the mount flow decides the observer should be live — a client\n * swap re-attaches the rebuilt observer iff its predecessor was attached.\n */\n let shouldAttach = false\n let activeClient = untrack(client)\n /**\n * The entry this hook last read at its current hash, and the fallback for\n * `query()` when the cache no longer holds that hash. Removal is the case\n * that needs it: `removeQueries()` (or `clear()`) fires 'removed' for a\n * hash this hook is mounted on, which bumps `version` and re-runs every\n * derived read, and a plain `build()` there would re-create the entry the\n * caller just removed. That resurrection is not passive, since the 'added'\n * entry also re-points the still-live observer, whose mount-fetch policy\n * then refetches and repopulates the key, contrary to `removeQueries`\n * being documented to remove entries instead of refetching them.\n *\n * The removed instance keeps its final state, so reads hold their last\n * value until options change or a real entry returns (`setQueryData`, a\n * refetch, a later mount). That is what the other adapters do: a React\n * observer keeps rendering the removed query's last result while the\n * cache stays empty.\n *\n * Cleared on a client swap, below: the fallback is only meaningful for the\n * cache it was read from.\n */\n let lastQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n\n const attach = () => {\n if (!disposed && !observerSub && !untrack(isRestoring)) {\n shouldAttach = true\n observerSub = observer.subscribe(noop)\n }\n }\n\n /**\n * Idempotent client re-pointing, called from the tracked `query()` read\n * (which every derived compute goes through) rather than a dedicated\n * watcher node — hydration id assignment is positional, so a client-only\n * effect here would shift every downstream id. On a swap the version\n * subscription moves to the new cache and the observer is rebuilt against\n * the new client, so policy fetches and cache events both follow the\n * client the hook is actually reading.\n * @param c - The `QueryClient` the hook currently resolves to.\n */\n const syncClient = (c: QueryClient) => {\n if (isServer || c === activeClient) return\n activeClient = c\n lastQuery = undefined\n cacheSub?.()\n cacheSub = c.getQueryCache().subscribe(onCacheEvent)\n observerSub?.()\n observerSub = null\n observer = new Observer(c, untrack(defaultedOptions))\n if (shouldAttach && !disposed && !untrack(isRestoring)) {\n observerSub = observer.subscribe(noop)\n }\n }\n\n /**\n * Hydration priming — content-addressed, the Solid Router `query()`\n * pattern. The provider serialized every query this request touched\n * into Solid's hydration registry under `sq:<queryHash>` (raw pre-select\n * data plus `dataUpdatedAt`); here the hook looks its hash up directly\n * and reconstructs the cache entry through query-core `hydrate()`, so\n * staleness policy stays honest. Content addressing means coverage is\n * the CACHE's, not the rendered tree's: prefetched-never-rendered\n * queries transfer, shared keys prime from whichever hook consumes the\n * entry first, and — like the router — the registry can still be\n * consulted past hydration end, so a component mounted long after (lazy route,\n * post-hydration navigation) still adopts the server's payload instead\n * of refetching. Entries are consumed one-shot (deleted on load): once\n * the cache owns the data, a stale registry payload must never shadow\n * it.\n *\n * Ordering matters twice over. The observer attaches only after priming\n * resolves (on hydrated mounts via `primeAndAttach`; on later mounts by\n * priming HERE, before the attach render effect below even exists —\n * its effect half runs synchronously inside an active flush, and mount\n * policy against a still-cold cache would refetch data the registry\n * already holds). Settled entries prime synchronously at setup;\n * streamed entries prime when their chunk lands, per query, so early\n * components go live while later boundaries still stream. No entry\n * (placeholder queries serialize nothing; SSR errors adopt at their\n * boundary) attaches immediately and lets mount policy decide.\n * @param entry - The hydration registry entry for this query's hash, if one exists.\n */\n const prime = (entry?: Partial<HydratedEntry> | null) => {\n if (entry != null && typeof entry === 'object' && (entry.t ?? 0) > 0) {\n const c = untrack(client)\n const opts = untrack(defaultedOptions)\n // Escape the setup/owned scope: hydrate() synchronously notifies\n // cache subscribers, which may write into other hooks' stores.\n runWithOwner(null, () =>\n hydrate(c, {\n mutations: [],\n queries: [\n {\n queryKey: opts.queryKey,\n queryHash: opts.queryHash,\n dehydratedAt: entry.t,\n ...(opts.meta && { meta: opts.meta }),\n ...((opts as { _type?: string })._type && {\n queryType: (opts as { _type?: string })._type,\n }),\n state: {\n data: entry.data,\n dataUpdatedAt: entry.t,\n dataUpdateCount: 1,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: 'success',\n fetchStatus: 'idle',\n },\n },\n ],\n } as Parameters<typeof hydrate>[1]),\n )\n }\n }\n\n if (!isServer) {\n cacheSub = activeClient.getQueryCache().subscribe(onCacheEvent)\n const registryKey =\n HYDRATION_KEY_PREFIX + untrack(defaultedOptions).queryHash\n const primeAndAttach = (entry?: Partial<HydratedEntry> | null) => {\n prime(entry)\n setPrimed(true)\n attach()\n }\n const settle = hydratedMount ? primeAndAttach : prime\n const entry = takeHydrationValue<Partial<HydratedEntry> | null>(registryKey)\n if (entry?.status === 'resolved') settle(entry.value)\n else if (entry?.status === 'rejected') settle()\n else if (entry?.status === 'pending')\n entry.promise.then(settle, () => settle())\n else if (hydratedMount) primeAndAttach()\n if (!hydratedMount) {\n createRenderEffect(\n () => isRestoring(),\n (restoring) => {\n if (!restoring) attach()\n },\n )\n }\n onCleanup(() => {\n disposed = true\n observerSub?.()\n observerSub = null\n cacheSub?.()\n cacheSub = null\n })\n }\n\n /**\n * The cache entry for the current options, without the `version` read —\n * for the setup-time snapshots below (`metaProjection`'s seed,\n * `mountedAt`), which run in whatever computation is instantiating this\n * component. Under hydration that matters: priming bumps `version`\n * during setup, and Solid holds a write made during the hydration pass —\n * a computation in the pass that reads the written signal, tracked or\n * not, is served the pre-write snapshot and replays at release. For the\n * hook's own derived nodes that replay is the takeover. For the\n * instantiating computation (a boundary's children, a `<Show>` branch)\n * it is a remount: the hydrated component is disposed and re-created as\n * a client render, and the server value stops holding the DOM. So the\n * snapshots read the cache, never the signal.\n * @returns The cache entry for the current options.\n */\n const lookupQuery = (): Query<\n TQueryFnData,\n TError,\n TQueryData,\n TQueryKey\n > => {\n const c = client()\n syncClient(c)\n const cache = c.getQueryCache()\n const opts = defaultedOptions()\n const existing = cache.get<TQueryFnData, TError, TQueryData, TQueryKey>(\n opts.queryHash,\n )\n if (existing) return (lastQuery = existing)\n if (lastQuery?.queryHash === opts.queryHash) return lastQuery\n return (lastQuery = cache.build(c, opts as any) as any)\n }\n const query = (): Query<TQueryFnData, TError, TQueryData, TQueryKey> => {\n version()\n return lookupQuery()\n }\n\n const isEnabled = () => {\n const opts = defaultedOptions()\n const enabled =\n typeof opts.enabled === 'function'\n ? (opts.enabled as (q: any) => boolean)(untrack(query))\n : opts.enabled\n return enabled !== false\n }\n\n const resolvePlaceholder = (\n opts: ReturnType<typeof defaultedOptions>,\n ): TQueryData | undefined => {\n const placeholder = opts.placeholderData\n if (placeholder === undefined) return undefined\n // The function form receives previous data/query in React Query as a\n // `keepPreviousData` vehicle. Solid 2 holds the previous committed value\n // natively while a new promise is pending, so previous-data plumbing is\n // unnecessary here; a function placeholder computes from nothing.\n return typeof placeholder === 'function'\n ? (placeholder as () => TQueryData | undefined)()\n : placeholder\n }\n\n /**\n * The data compute. It returns either the settled `{ value }` root or a\n * promise of it — the engine does the rest: pending reads suspend into\n * `<Loading>` (holding the previous committed value on refetch),\n * rejections surface to `<Errored>`, transitions hold commits until\n * in-flight answers land, and on the server the settled value serializes\n * for hydration adoption on the client.\n */\n // Stable promise identity across recomputes: mid-flight version bumps\n // (fetch dispatch, observer updates) re-run the data compute while the\n // same underlying fetch is pending. Chaining a fresh `.then` each time\n // would hand the engine a new pending promise per recompute — the node\n // keeps restarting its pending tracking and the settle can be missed\n // (observed as `isPending` probes stuck true after the fetch lands).\n let chained: {\n base: Promise<unknown>\n select: unknown\n value: Promise<{ value: TData }>\n } | null = null\n const chainOnce = (\n base: Promise<any>,\n select: unknown,\n wrap: (d: any) => { value: TData },\n ): Promise<{ value: TData }> => {\n if (chained?.base !== base || chained.select !== select) {\n chained = { base, select, value: base.then(wrap) }\n }\n return chained.value\n }\n\n const computeData = (\n prev?: TData,\n ): { value: TData } | Promise<{ value: TData }> => {\n const opts = defaultedOptions()\n const q = query()\n const state = q.state\n const select = opts.select\n const wrap = (d: any): { value: TData } => ({\n value: select ? select(d as TQueryData) : (d as TData),\n })\n\n // Placeholder: show immediately instead of suspending while the first\n // fetch runs. When the fetch lands the version bump swaps in real data.\n if (state.data === undefined && state.status === 'pending') {\n const placeholder = resolvePlaceholder(opts)\n if (placeholder !== undefined) return wrap(placeholder)\n }\n\n // A fetch in flight (including paused-offline with a retryer attached):\n // hand the engine the promise. First load suspends; refetch holds the\n // previous committed value and marks the node pending — which is what\n // lets a mutation's invalidations hold its settle transition until\n // fresh data lands.\n //\n // Exception: a FIRST compute that already has a value to show\n // (initialData, hydrated or shared cache data with a mount refetch in\n // flight) returns the value — suspending would have nothing committed\n // to hold, blanking the UI on mount. The refetch stays observable via\n // fetchStatus; the settle lands through the next version bump.\n if (state.fetchStatus !== 'idle') {\n if (state.data === undefined || prev !== undefined) {\n const promise = q.promise\n if (promise) return chainOnce(promise, select, wrap)\n }\n }\n\n if (state.status === 'error') {\n // No stale value to serve means the read cannot produce TData — the\n // rejection surfaces through the graph to the nearest <Errored>.\n // With stale data present, throw only if throwOnError opts in.\n if (\n state.data === undefined ||\n shouldThrowError(opts.throwOnError as any, [\n state.error as any,\n q as any,\n ])\n ) {\n throw state.error\n }\n }\n\n if (state.data !== undefined) return wrap(state.data)\n\n // Pending-idle: nothing in flight, nothing cached. If the query is\n // enabled, the tracked read itself starts the fetch (the router\n // `query()` model — reads pull the async). This is not just the server\n // path: on the client it is what revives a query whose enabling change\n // arrives while the subtree is parked under a suspended boundary —\n // parked boundaries hold effects, so the observer's option-driven fetch\n // can never fire there, but computes still re-run. `q.fetch` dedupes\n // against any fetch the observer already started.\n if (isEnabled()) {\n /**\n * Never start a fetch inside the hydration window. Adoption\n * trace-runs this compute even on a hit (solid mocks `fetch` there,\n * but a TanStack fetch is invisible to that mock) — a query fetching\n * here would wedge on hydration's Promise mock inside its queryFn\n * and then swallow every later legitimate refetch through retryer\n * dedupe. During hydration the value comes from adoption or node\n * priming; if a fetch is genuinely needed, the post-priming observer\n * attach issues it outside the window.\n */\n if (isHydrating()) {\n return NEVER\n }\n /**\n * Same discipline until this hook's serialized node entry has primed\n * the cache (or was found absent): the takeover recompute at\n * hydration end can land before a streamed entry does, and fetching\n * against the still-empty cache would race data the stream already\n * carries. The read is tracked — priming resolves through\n * `setPrimed`, re-running this compute, and an entry-less query\n * falls through to a normal fetch here.\n */\n if (!primed()) {\n return NEVER\n }\n /**\n * Same discipline while a persister is restoring: the restored value\n * is about to land in the cache, so pulling a fetch now would race\n * it. The read is tracked — `isRestoring` flipping false re-runs\n * this compute (and the deferred observer attach engages mount\n * policy), so the fetch fires then if the restore left a gap.\n */\n if (isRestoring()) {\n return NEVER\n }\n /**\n * Sync observer policy before pulling. Under a suspended boundary\n * the options render effect is deferred, so on an enabled flip or\n * key change this compute runs first and the effect only lands\n * after the revival fetch settles — at which point a \"changed\"\n * options diff against now-stale data would issue a redundant\n * policy refetch. Syncing here means any policy fetch starts now\n * (and `q.fetch` dedupes into it), and the deferred effect later\n * sees the identical options object — a no-op diff.\n */\n if (!isServer) observer.setOptions(opts)\n return chainOnce(q.fetch(opts), select, wrap)\n }\n /**\n * Disabled, with nothing cached. The three guards above are all\n * unreachable on the server, but this one is not, and parking here has\n * no server meaning: the render has to finish, and nothing will enable\n * the query or write the cache before it does. So commit the idle\n * value — 'pending' with no data IS a disabled query's settled SSR\n * truth, which is the contract `serverMeta` already honors by not\n * tying its read to this node while disabled, and it is the state the\n * client hydrates to. Committed rather than passed through `wrap`:\n * `select` must not be invoked on absent data.\n */\n if (isServer) return { value: undefined as TData }\n return NEVER\n }\n\n /**\n * THE data node: one projection, identical on both sides — the router\n * \"feed `query()` into `createProjection`\" shape. The derive asks the\n * cache for the answer (`computeData`) and the engine owns everything\n * else: the server runs the derive, waits, and serializes the settled\n * store under this node's id (`deferStream` holds the flush); pending\n * reads suspend into `<Loading>`; a hydrating client adopts the\n * serialized value and re-derives once hydration hands over; and every\n * landing — refetch, invalidation, placeholder upgrade — auto-reconciles\n * into the existing proxy graph (keyed by `reconcile`, default `'id'`),\n * so deep reads are fine-grained and item identity survives fetches.\n *\n * The root wrapper exists because store roots must be objects —\n * primitive data rides the `value` leaf as a plain signal read. The\n * draft's committed `value` doubles as the previous-data signal for the\n * first-paint exception in `computeData`.\n *\n * Default ('server') hydration semantics: the serialized value owns the\n * node while it hydrates. Outside every still-pending streamed boundary,\n * a cache write commits immediately. Under a pending boundary it waits\n * for that boundary to resume, which hydrates against the server\n * snapshot.\n */\n const dataStore = createProjection<{ value: TData }>(\n (draft) => computeData(draft.value),\n {} as { value: TData },\n {\n key: untrack(() => options().reconcile),\n deferStream: untrack(() => options().deferStream),\n },\n )\n const data = () => dataStore.value\n\n /**\n * Scalar result metadata.\n *\n * Client: a projection reconciled per-field from query state on every\n * cache event, so each field is its own fine-grained signal — a component\n * reading only `isFetching` re-runs on fetchStatus flips, not on every\n * state transition.\n *\n * Server: boundaries guarantee that only settled state serializes, and\n * meta must honor the same contract (solid's own `isPending` suspends\n * rather than ever serialize `true`). A projection cannot: its compute\n * runs once at setup and never re-pulls, freezing an in-flight snapshot\n * ('pending'/'fetching') into HTML that the hydrating client — reading\n * the primed, settled cache — contradicts. So on the server every meta\n * read pulls live query state, and while the entry is unsettled (pending\n * with a fetch in flight, or one it can start) the read ties itself to the data\n * node, which throws the pending read and holds the boundary until\n * settle. A disabled pending query is served as-is: 'pending' IS its\n * settled SSR truth, and the client hydrates the identical state.\n * @returns The scalar metadata read live from the query's state.\n */\n const serverMeta = (): MetaState => {\n if (query().state.status === 'pending' && isEnabled()) data()\n return metaFrom(query().state)\n }\n /**\n * Created on BOTH sides even though the server never reads it: hydration\n * id assignment is positional, so every reactive node a hook creates on\n * the client must have a server counterpart (and vice versa) or every id\n * downstream shifts and hydration key-misses the whole subtree.\n */\n const metaProjection = createProjection<MetaState>(\n (draft) => {\n Object.assign(draft, metaFrom(query().state))\n },\n untrack(() => metaFrom(lookupQuery().state)),\n )\n const meta = isServer\n ? new Proxy({} as MetaState, {\n get: (_, key) => serverMeta()[key as keyof MetaState],\n })\n : metaProjection\n\n /**\n * Server: read live counts instead of a setup snapshot — \"mount\" resolves\n * post-settle there, so `isFetchedAfterMount` serializes `false`, which is\n * exactly what the hydrating client computes (its mount snapshot equals\n * the hydrated counts).\n */\n const mountedAt = isServer\n ? {\n get dataUpdateCount() {\n return untrack(query).state.dataUpdateCount\n },\n get errorUpdateCount() {\n return untrack(query).state.errorUpdateCount\n },\n }\n : untrack(() => {\n const state = lookupQuery().state\n return {\n dataUpdateCount: state.dataUpdateCount,\n errorUpdateCount: state.errorUpdateCount,\n }\n })\n\n const hasPlaceholder = () =>\n meta.status === 'pending' &&\n untrack(() => resolvePlaceholder(defaultedOptions())) !== undefined\n const status = () => (hasPlaceholder() ? 'success' : meta.status)\n const isPending = () => status() === 'pending'\n /**\n * A refetch of settled data is a transition: the state write that flips\n * `fetchStatus` to 'fetching' is held in the same batch as the pending\n * data node, so the committed meta channel cannot show it mid-hold — by\n * design, held updates commit atomically. The observable channel for\n * \"a new answer is in flight\" during a hold is core's pending probe.\n * The committed `fetchStatus` covers the first load (where the probe\n * would see an uninitialized node) and untracked/imperative reads.\n * @returns `true` while a fetch for this query is in flight.\n */\n const isFetching = () =>\n meta.fetchStatus === 'fetching' || isValuePending(() => data())\n const isError = () => status() === 'error'\n const isStale = () => {\n const opts = defaultedOptions()\n const q = untrack(query)\n const staleTime =\n typeof opts.staleTime === 'function'\n ? (opts.staleTime as (q: any) => number | 'static')(q)\n : opts.staleTime\n version()\n return q.isStaleByTime(staleTime)\n }\n\n const result = {\n get data() {\n return data()\n },\n get error() {\n return meta.error as TError | null\n },\n get status() {\n return status()\n },\n get fetchStatus() {\n return meta.fetchStatus\n },\n get isPending() {\n return isPending()\n },\n get isSuccess() {\n return status() === 'success'\n },\n get isError() {\n return isError()\n },\n get isLoading() {\n return isPending() && isFetching()\n },\n get isFetching() {\n return isFetching()\n },\n get isRefetching() {\n return isFetching() && !isPending()\n },\n get isPaused() {\n return meta.fetchStatus === 'paused'\n },\n get isEnabled() {\n return isEnabled()\n },\n get isLoadingError() {\n return isError() && meta.dataUpdatedAt === 0\n },\n get isRefetchError() {\n return isError() && meta.dataUpdatedAt !== 0\n },\n get isPlaceholderData() {\n return hasPlaceholder()\n },\n get isStale() {\n return isStale()\n },\n get isFetched() {\n return meta.dataUpdateCount > 0 || meta.errorUpdateCount > 0\n },\n get isFetchedAfterMount() {\n return (\n meta.dataUpdateCount > mountedAt.dataUpdateCount ||\n meta.errorUpdateCount > mountedAt.errorUpdateCount\n )\n },\n get dataUpdatedAt() {\n return meta.dataUpdatedAt\n },\n get errorUpdatedAt() {\n return meta.errorUpdatedAt\n },\n get failureCount() {\n return meta.fetchFailureCount\n },\n get failureReason() {\n return meta.fetchFailureReason as TError | null\n },\n get errorUpdateCount() {\n return meta.errorUpdateCount\n },\n get promise() {\n return resolve(() => data())\n },\n refetch: ((refetchOptions) => {\n // A held transition defers the setOptions render effect, so after a\n // key switch the observer can still carry the previous key's options.\n // Sync to the latest computed options first: an imperative refetch\n // targets what the UI is currently asking for, not what last\n // committed.\n if (!isServer && latestOptions) {\n observer.setOptions(latestOptions)\n }\n return observer.refetch(refetchOptions)\n }) as QueryObserverResult<TData, TError>['refetch'],\n }\n\n return {\n result: result as unknown as UseBaseQueryResult<TData, TError>,\n observer,\n query,\n defaultedOptions,\n isFetching,\n status,\n } as unknown as BaseQueryLayer<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >\n}\n","import { QueryObserver } from '@tanstack/query-core'\nimport { createMemo } from 'solid-js'\nimport { useBaseQuery } from './useBaseQuery'\nimport type { DefaultError, QueryKey } from '@tanstack/query-core'\nimport type { QueryClient } from './QueryClient'\nimport type { Accessor } from 'solid-js'\nimport type {\n DefinedUseQueryResult,\n UseQueryOptions,\n UseQueryResult,\n} from './types'\nimport type {\n DefinedInitialDataOptions,\n UndefinedInitialDataOptions,\n} from './queryOptions'\n\n/**\n * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.\n * The query runs when the options call for it — `enabled: false` skips the initial fetch.\n *\n * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never\n * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined`\n * if `select` throws on its first call.\n * @param options - An accessor returning the {@link DefinedInitialDataOptions} to use — everything you can\n * pass to `useQuery`, with `initialData` known to be defined.\n * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The current query result, as a Solid store, typed so that `status` is `success` or `error`\n * (`status` never resolves to `pending` in this overload's type, since `initialData` guarantees data upfront).\n * `status` is `error` if the query has an error from a fetch that failed after its retries or if `select`\n * threw, and `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience.\n * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.\n * @example\n * ```tsx\n * import { For } from 'solid-js'\n * import { useQuery } from '@tanstack/solid-query'\n *\n * function Posts() {\n * // `postsQuery.data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the\n * // list stays visible alongside the error.\n * const postsQuery = useQuery(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * initialData: [],\n * }))\n *\n * return (\n * <div>\n * {postsQuery.isError ? <span>Error: {postsQuery.error.message}</span> : null}\n * <ul>\n * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>\n * </ul>\n * </div>\n * )\n * }\n * ```\n */\nexport function useQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,\n queryClient?: () => QueryClient,\n): DefinedUseQueryResult<TData, TError>\n\n/**\n * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.\n * The query runs when the options call for it — `enabled: false` skips the initial fetch.\n * @param options - An accessor returning the {@link UndefinedInitialDataOptions} to use — everything you can\n * pass to `useQuery`.\n * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The current query result, as a Solid store. `status` is `error` if the query has an error from\n * a fetch that failed after its retries or if `select` threw, `success` if the query has data to display\n * (including `placeholderData`), and `pending` otherwise. `isPending`/`isSuccess`/`isError` are derived\n * booleans for convenience.\n * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.\n * @example\n * ```tsx\n * import { For, Match, Switch } from 'solid-js'\n * import { useQuery } from '@tanstack/solid-query'\n *\n * function Posts() {\n * const postsQuery = useQuery(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * }))\n *\n * return (\n * <Switch>\n * <Match when={postsQuery.isPending}>Loading...</Match>\n * <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>\n * <Match when={postsQuery.isSuccess}>\n * <ul>\n * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>\n * </ul>\n * <div>{postsQuery.isFetching ? 'Background Updating...' : ' '}</div>\n * </Match>\n * </Switch>\n * )\n * }\n * ```\n * @example\n * `select` derives whatever `data` a component needs from the cached value, without changing what's\n * actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`:\n * ```tsx\n * import { Match, Switch } from 'solid-js'\n * import { useQuery } from '@tanstack/solid-query'\n *\n * function PostCount() {\n * const postsQuery = useQuery(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * select: (posts) => posts.length,\n * }))\n *\n * return (\n * <Switch>\n * <Match when={postsQuery.isPending}>Loading...</Match>\n * <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>\n * <Match when={postsQuery.isSuccess}>{postsQuery.data} posts</Match>\n * </Switch>\n * )\n * }\n * ```\n * @example\n * A dependent query, only enabled once `postId` is set:\n * ```tsx\n * import { Match, Switch } from 'solid-js'\n * import { useQuery } from '@tanstack/solid-query'\n *\n * function Post(props: { postId: number | undefined }) {\n * const postQuery = useQuery(() => ({\n * queryKey: ['post', props.postId],\n * queryFn: () => fetchPost(props.postId!),\n * enabled: props.postId != null,\n * }))\n *\n * return (\n * <Switch fallback={<h1>{postQuery.data?.title}</h1>}>\n * <Match when={props.postId == null}>Select a post</Match>\n * <Match when={postQuery.isLoading}>Loading...</Match>\n * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>\n * </Switch>\n * )\n * }\n * ```\n * @example\n * The same dependent query, using `skipToken` to disable it in a type-safe way instead of relying on\n * `enabled`. The non-null assertion is still needed — Solid's `props` narrowing doesn't survive into the\n * `queryFn` closure the way a local `const` would — but `skipToken` keeps `queryFn`'s return type accurate\n * without it. `refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you\n * need to trigger the query manually:\n * ```tsx\n * import { Match, Switch } from 'solid-js'\n * import { skipToken, useQuery } from '@tanstack/solid-query'\n *\n * function Post(props: { postId: number | undefined }) {\n * const postQuery = useQuery(() => ({\n * queryKey: ['post', props.postId],\n * queryFn: props.postId != null ? () => fetchPost(props.postId!) : skipToken,\n * }))\n *\n * return (\n * <Switch fallback={<h1>{postQuery.data?.title}</h1>}>\n * <Match when={props.postId == null}>Select a post</Match>\n * <Match when={postQuery.isLoading}>Loading...</Match>\n * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>\n * </Switch>\n * )\n * }\n * ```\n * @example\n * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries\n * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was\n * fetched rather than from now:\n * ```tsx\n * import { useQuery, useQueryClient } from '@tanstack/solid-query'\n *\n * function Post(props: { postId: number }) {\n * const queryClient = useQueryClient()\n *\n * const postQuery = useQuery(() => ({\n * queryKey: ['post', props.postId],\n * queryFn: () => fetchPost(props.postId),\n * initialData: () =>\n * queryClient\n * .getQueryData<Array<Post>>(['posts'])\n * ?.find((post) => post.id === props.postId),\n * initialDataUpdatedAt: () =>\n * queryClient.getQueryState(['posts'])?.dataUpdatedAt,\n * }))\n *\n * return postQuery.isError ? <span>Error: {postQuery.error.message}</span> : <h1>{postQuery.data?.title}</h1>\n * }\n * ```\n * @example\n * Paginated data, keeping the previous page's data visible while the next page loads:\n * ```tsx\n * import { For, createSignal } from 'solid-js'\n * import { keepPreviousData, useQuery } from '@tanstack/solid-query'\n *\n * function Posts() {\n * const [page, setPage] = createSignal(0)\n *\n * const postsQuery = useQuery(() => ({\n * queryKey: ['posts', page()],\n * queryFn: () => fetchPosts(page()),\n * placeholderData: keepPreviousData,\n * }))\n *\n * return (\n * <div>\n * <ul>\n * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>\n * </ul>\n * <button\n * disabled={postsQuery.isPlaceholderData}\n * onClick={() => setPage((old) => old + 1)}\n * >\n * Next Page\n * </button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,\n queryClient?: () => QueryClient,\n): UseQueryResult<TData, TError>\nexport function useQuery<\n TQueryFnData,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n queryClient?: Accessor<QueryClient>,\n) {\n return useBaseQuery(\n createMemo(() => options()),\n QueryObserver,\n queryClient,\n )\n}\n","import type {\n DefaultError,\n InitialDataFunction,\n NonUndefinedGuard,\n QueryKey,\n QueryKeyWithDataTag,\n} from '@tanstack/query-core'\nimport type { QueryOptions } from './types'\nimport type { Accessor } from 'solid-js'\n\n/**\n * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be\n * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is\n * `pending`. `queryOptions` itself accepts and returns a plain object (its parameter type is\n * `ReturnType<UndefinedInitialDataOptions<...>>`, i.e. this `Accessor` called); Solid's reactivity applies\n * where the result is consumed instead, e.g. `useQuery(() => options)`.\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type UndefinedInitialDataOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = Accessor<\n QueryOptions<TQueryFnData, TError, TData, TQueryKey> & {\n initialData?:\n | undefined\n | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>\n | NonUndefinedGuard<TQueryFnData>\n }\n>\n\n/**\n * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined —\n * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type DefinedInitialDataOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = Accessor<\n QueryOptions<TQueryFnData, TError, TData, TQueryKey> & {\n initialData:\n | NonUndefinedGuard<TQueryFnData>\n | (() => NonUndefinedGuard<TQueryFnData>)\n }\n>\n\n/**\n * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can\n * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and\n * is the query key to generate options for.\n *\n * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never\n * `undefined` (unless a `select` changes `TData` to include `undefined`).\n * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n * @see {@link useQuery} to run a query with these options.\n * @example\n * ```tsx\n * import { For } from 'solid-js'\n * import { queryOptions, useQuery } from '@tanstack/solid-query'\n *\n * const postsOptions = queryOptions({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * initialData: [],\n * })\n *\n * function Posts() {\n * // `postsQuery.data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,\n * // so the list stays visible alongside the error.\n * const postsQuery = useQuery(() => postsOptions)\n *\n * return (\n * <div>\n * {postsQuery.isError ? <span>Error: {postsQuery.error.message}</span> : null}\n * <ul>\n * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>\n * </ul>\n * </div>\n * )\n * }\n * ```\n */\nexport function queryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: ReturnType<\n DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>\n >,\n): ReturnType<\n DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>\n> &\n QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>\n\n/**\n * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can\n * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and\n * is the query key to generate options for.\n * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n * @see {@link useQuery} to run a query with these options.\n * @example\n * A parameterized factory, so the same options object can be reused per `id`:\n * ```tsx\n * import { Match, Switch } from 'solid-js'\n * import { queryOptions, useQuery } from '@tanstack/solid-query'\n *\n * const postOptions = (id: string) =>\n * queryOptions({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })\n *\n * function Post(props: { id: string }) {\n * const postQuery = useQuery(() => postOptions(props.id))\n *\n * return (\n * <Switch>\n * <Match when={postQuery.isPending}>Loading...</Match>\n * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>\n * <Match when={postQuery.isSuccess}>\n * <h1>{postQuery.data.title}</h1>\n * </Match>\n * </Switch>\n * )\n * }\n * ```\n */\nexport function queryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: ReturnType<\n UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>\n >,\n): ReturnType<\n UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>\n> &\n QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>\n\nexport function queryOptions(options: unknown) {\n return options\n}\n","import { dehydrate } from '@tanstack/query-core'\nimport type { DehydrateOptions, DehydratedState } from '@tanstack/query-core'\nimport type { QueryClient } from './QueryClient'\n\n/**\n * Waits for every fetch the client has in flight to settle, then\n * dehydrates. This is the extraction half of a single-flight collector:\n * after route data functions run for the mutation's target URL, loaders\n * commonly kick off prefetches without awaiting them — plain\n * `dehydrate()` would snapshot those mid-fetch and ship nothing.\n *\n * ```ts\n * registerFlightDataSource(FLIGHT_DATA_SOURCE, (event, outcome) =>\n * loadFlightTarget({\n * router,\n * event,\n * outcome,\n * collect: () => dehydrateSettled(queryClient),\n * }),\n * )\n * ```\n *\n * Settling is chased to quiescence — awaiting one batch of fetches can\n * dispatch more (dependent queries keyed off a first result) — so an\n * unconditionally self-refetching query would keep this pending; that's\n * an app bug mirrored, not guarded.\n * @param client - The `QueryClient` whose cache is dehydrated.\n * @param options - The `DehydrateOptions` forwarded to `dehydrate`.\n * @returns A promise for the dehydrated state, taken once no fetch is in flight.\n */\nexport async function dehydrateSettled(\n client: QueryClient,\n options?: DehydrateOptions,\n): Promise<DehydratedState> {\n const cache = client.getQueryCache()\n for (;;) {\n const pending = cache\n .getAll()\n .filter((query) => query.state.fetchStatus !== 'idle')\n .map((query) => query.promise)\n if (pending.length === 0) break\n await Promise.allSettled(pending)\n }\n return dehydrate(client, options)\n}\n","import {\n createEffect,\n createOptimistic,\n createSignal,\n isHydrating,\n onCleanup,\n untrack,\n} from 'solid-js'\nimport type { Accessor } from 'solid-js'\n\nconst isServer = typeof window === 'undefined'\n\n/**\n * Shared reactive core for the cross-cache aggregate hooks — `useIsFetching`,\n * `useIsMutating`, `useMutationState` — which all reduce to \"a value derived\n * from a whole cache, refreshed on its events\". Two invariants live here so\n * each hook doesn't restate them:\n *\n * Dual write. Cache events can fire inside an action transaction\n * (`useMutation` rides core `action`; an onSuccess invalidation dispatches\n * refetches mid-action), where a plain signal write is held until settle —\n * the in-flight value would be invisible. An optimistic override alone fails\n * the other way: outside a transaction, overrides drop at batch end. So a\n * durable signal carries committed state and an optimistic node tracks it as\n * its base; in-transaction values surface through the override, and the held\n * durable write becomes the base when the settle lands.\n *\n * Hydration. A cross-cache aggregate is not tied to a single async source,\n * so it cannot ride the boundary contract per-query meta uses (suspend until\n * settled). Its contract is fixed by construction instead: a hydrating\n * client can only ever observe the empty value at claim time — its own\n * fetches are held inside the hydration window, channel-primed entries are\n * settled, and mutations do not transfer across SSR. So the server\n * serializes the empty value, and a hydrated mount latches there until its\n * window closes: the subscription and first sync run from an effect half,\n * deferred past hydration — the earliest globally-safe moment for a\n * cross-cache read to go live (on a streamed page, an already-hydrated\n * region's refetch can be in flight while this region is still claiming).\n *\n * Every node here is created on the server too, where it is never read or\n * written: hydration id assignment is positional, so both sides must create\n * the same reactive nodes or every id downstream shifts and the subtree\n * key-misses.\n * @param subscribe - Subscribes to the cache's events and returns the unsubscribe function.\n * @param read - Computes the aggregate from the cache, given the previously committed value.\n * @param empty - The value served on the server and while a hydrated mount is still hydrating.\n * @returns An accessor for the current aggregate.\n */\nexport function createCacheAggregate<T>(\n subscribe: (onEvent: () => void) => () => void,\n read: (prev: T) => T,\n empty: T,\n): Accessor<T> {\n const hydratedMount = isHydrating()\n\n // Cast: createSignal's value overload excludes functions (a function\n // argument means a compute); aggregate values are counts and arrays.\n const [durable, setDurable] = createSignal<T>(\n (hydratedMount || isServer ? empty : untrack(() => read(empty))) as Exclude<\n T,\n Function\n >,\n { ownedWrite: true },\n )\n const [value, setValue] = createOptimistic(() => durable(), {\n ownedWrite: true,\n })\n\n const sync = () => {\n const next = untrack(() => read(untrack(durable)))\n setDurable(() => next)\n setValue(() => next)\n }\n let unsubscribe: (() => void) | null = null\n const attach = () => {\n unsubscribe ??= untrack(() => subscribe(sync))\n }\n onCleanup(() => unsubscribe?.())\n\n createEffect(\n () => undefined,\n () => {\n if (hydratedMount) {\n attach()\n sync()\n }\n },\n )\n\n if (isServer) return () => empty\n if (!hydratedMount) attach()\n return value\n}\n","import { createMemo } from 'solid-js'\nimport { createCacheAggregate } from './cacheAggregate'\nimport { useQueryClient } from './QueryClientProvider'\nimport type { QueryFilters } from '@tanstack/query-core'\nimport type { QueryClient } from './QueryClient'\nimport type { Accessor } from 'solid-js'\n\n/**\n * The `useIsFetching` primitive returns the `number` of the queries that your application is loading or fetching\n * in the background (useful for app-wide loading indicators).\n * @param filters - An accessor returning the {@link QueryFilters} to narrow down the matched queries.\n * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns An accessor for the `number` of the queries that your application is currently loading or fetching\n * in the background.\n * @example\n * ```tsx\n * import { useIsFetching } from '@tanstack/solid-query'\n *\n * function GlobalLoadingIndicator() {\n * // How many queries matching the posts prefix are fetching?\n * const isFetchingPosts = useIsFetching(() => ({ queryKey: ['posts'] }))\n *\n * return isFetchingPosts() > 0 ? <span>Loading posts...</span> : null\n * }\n * ```\n */\nexport function useIsFetching(\n filters?: Accessor<Omit<QueryFilters, 'fetchStatus'>>,\n queryClient?: Accessor<QueryClient>,\n): Accessor<number> {\n const client = createMemo(() => useQueryClient(queryClient?.()))\n return createCacheAggregate(\n (onEvent) => client().getQueryCache().subscribe(onEvent),\n () => client().isFetching(filters?.()),\n 0,\n )\n}\n","import { InfiniteQueryObserver } from '@tanstack/query-core'\nimport { createMemo } from 'solid-js'\nimport { useBaseQueryLayer } from './useBaseQuery'\nimport type {\n DefaultError,\n FetchNextPageOptions,\n FetchPreviousPageOptions,\n InfiniteData,\n InfiniteQueryObserverResult,\n QueryKey,\n QueryObserver,\n} from '@tanstack/query-core'\nimport type { QueryClient } from './QueryClient'\nimport type {\n DefinedUseInfiniteQueryResult,\n UseInfiniteQueryOptions,\n UseInfiniteQueryResult,\n} from './types'\nimport type { Accessor } from 'solid-js'\nimport type {\n DefinedInitialDataInfiniteOptions,\n UndefinedInitialDataInfiniteOptions,\n} from './infiniteQueryOptions'\n\n/**\n * Page-boundary checks, mirrored from query-core's `infiniteQueryBehavior`\n * (they are module-private there — not exported through the package index).\n * Pure functions of options + cached data; keep byte-compatible with core.\n */\ninterface PageParamsOptions {\n getNextPageParam: (\n lastPage: unknown,\n pages: Array<unknown>,\n lastPageParam: unknown,\n pageParams: Array<unknown>,\n ) => unknown\n getPreviousPageParam?: (\n firstPage: unknown,\n pages: Array<unknown>,\n firstPageParam: unknown,\n pageParams: Array<unknown>,\n ) => unknown\n}\n\n/**\n * Checks whether `getNextPageParam` yields a param for the page after the last cached one.\n * @param options - The options holding `getNextPageParam`.\n * @param data - The cached infinite data, if any.\n * @returns `true` if there is a next page to fetch.\n */\nfunction hasNextPage(\n options: PageParamsOptions,\n data?: InfiniteData<unknown>,\n): boolean {\n if (!data || data.pages.length === 0) return false\n const lastIndex = data.pages.length - 1\n return (\n options.getNextPageParam(\n data.pages[lastIndex],\n data.pages,\n data.pageParams[lastIndex],\n data.pageParams,\n ) != null\n )\n}\n\n/**\n * Checks whether `getPreviousPageParam` yields a param for the page before the first cached one.\n * @param options - The options holding `getPreviousPageParam`.\n * @param data - The cached infinite data, if any.\n * @returns `true` if there is a previous page to fetch.\n */\nfunction hasPreviousPage(\n options: PageParamsOptions,\n data?: InfiniteData<unknown>,\n): boolean {\n if (!data || data.pages.length === 0 || !options.getPreviousPageParam)\n return false\n return (\n options.getPreviousPageParam(\n data.pages[0],\n data.pages,\n data.pageParams[0],\n data.pageParams,\n ) != null\n )\n}\n\nexport function useInfiniteQuery<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: DefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n queryClient?: Accessor<QueryClient>,\n): DefinedUseInfiniteQueryResult<TData, TError>\n\n/**\n * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of\n * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.\n * @param options - An accessor returning the {@link UndefinedInitialDataInfiniteOptions} to use — everything\n * you can pass to `useInfiniteQuery`.\n * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,\n * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and\n * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default\n * `InfiniteData<TQueryFnData>` shape.\n * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default\n * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user\n * actions, or add conditions like `hasNextPage && !isFetching`.\n * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.\n * @example\n * Fetching the next page from a \"Load More\" button click:\n * ```tsx\n * import { For, Match, Switch } from 'solid-js'\n * import { useInfiniteQuery } from '@tanstack/solid-query'\n *\n * function Projects() {\n * const projectsQuery = useInfiniteQuery(() => ({\n * queryKey: ['projects'],\n * queryFn: ({ pageParam }) => fetchProjects(pageParam),\n * initialPageParam: 0,\n * getNextPageParam: (lastPage) => lastPage.nextId,\n * }))\n *\n * return (\n * <Switch>\n * <Match when={projectsQuery.isPending}>Loading...</Match>\n * <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>\n * <Match when={projectsQuery.isSuccess}>\n * <ul>\n * <For each={projectsQuery.data.pages}>\n * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}\n * </For>\n * </ul>\n * <button\n * onClick={() => projectsQuery.fetchNextPage()}\n * disabled={!projectsQuery.hasNextPage || projectsQuery.isFetching}\n * >\n * {projectsQuery.isFetchingNextPage\n * ? 'Loading more...'\n * : projectsQuery.hasNextPage\n * ? 'Load More'\n * : 'Nothing more to load'}\n * </button>\n * </Match>\n * </Switch>\n * )\n * }\n * ```\n * @example\n * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a\n * sentinel element after the list:\n * ```tsx\n * import { For, Match, Switch, createEffect, onCleanup } from 'solid-js'\n * import { useInfiniteQuery } from '@tanstack/solid-query'\n *\n * function Projects() {\n * const projectsQuery = useInfiniteQuery(() => ({\n * queryKey: ['projects'],\n * queryFn: ({ pageParam }) => fetchProjects(pageParam),\n * initialPageParam: 0,\n * getNextPageParam: (lastPage) => lastPage.nextId,\n * }))\n *\n * let sentinelRef: HTMLDivElement | undefined\n *\n * createEffect(() => {\n * if (sentinelRef == null || !projectsQuery.hasNextPage || projectsQuery.isFetching) return\n *\n * const observer = new IntersectionObserver(([entry]) => {\n * if (entry?.isIntersecting) projectsQuery.fetchNextPage()\n * })\n * observer.observe(sentinelRef)\n *\n * onCleanup(() => observer.disconnect())\n * })\n *\n * return (\n * <Switch>\n * <Match when={projectsQuery.isPending}>Loading...</Match>\n * <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>\n * <Match when={projectsQuery.isSuccess}>\n * <ul>\n * <For each={projectsQuery.data.pages}>\n * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}\n * </For>\n * </ul>\n * <div ref={sentinelRef}>{projectsQuery.isFetchingNextPage ? 'Loading more...' : null}</div>\n * </Match>\n * </Switch>\n * )\n * }\n * ```\n */\nexport function useInfiniteQuery<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: UndefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n queryClient?: Accessor<QueryClient>,\n): UseInfiniteQueryResult<TData, TError>\n\nexport function useInfiniteQuery<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: UseInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n queryClient?: Accessor<QueryClient>,\n): UseInfiniteQueryResult<TData, TError> {\n /**\n * Pagers ride the same entry as every other read: the base layer owns\n * the data node, meta projection, and lifecycle observer (an\n * `InfiniteQueryObserver`, so mount policy and refetches use the\n * infinite behavior). This layer adds the page surface on top.\n */\n const layer = useBaseQueryLayer(\n // `_type` is how query-core stamps a cache entry as infinite\n // (`Query.setOptions` → `#queryType`), which makes every fetch attach\n // `infiniteQueryBehavior`. Core only sets it inside\n // `InfiniteQueryObserver.setOptions`, but the adapter's pull path can\n // build and fetch the entry first (reactive key change recomputes the\n // data memo before the deferred observer effect runs) — without the\n // stamp that fetch would run as a plain query and corrupt the entry.\n createMemo(() => ({ ...options(), _type: 'infinite' }) as any),\n InfiniteQueryObserver as typeof QueryObserver,\n queryClient,\n )\n const observer = layer.observer as unknown as InfiniteQueryObserver<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >\n\n /**\n * Committed fetch direction — set when a page fetch dispatches,\n * version-tracked through the layer's query accessor.\n * @returns `'forward'` or `'backward'` for a page fetch, `undefined` otherwise.\n */\n const direction = () =>\n (layer.query().state.fetchMeta as any)?.fetchMore?.direction\n\n const pageOptions = () =>\n layer.defaultedOptions() as unknown as PageParamsOptions\n const infiniteData = () =>\n layer.query().state.data as InfiniteData<unknown> | undefined\n\n // Read `direction()` before `isFetching()` to work around solidjs/solid#4966.\n const isFetchingPage = (expected: 'forward' | 'backward') => {\n const current = direction()\n return layer.isFetching() && current === expected\n }\n const isFetchingNextPage = () => isFetchingPage('forward')\n const isFetchingPreviousPage = () => isFetchingPage('backward')\n const isError = () => layer.status() === 'error'\n\n // The base result's getters transfer as-is; the infinite surface layers\n // over them, and isRefetching/isRefetchError narrow to exclude page\n // fetches (matching core's InfiniteQueryObserver result shape).\n const result = Object.defineProperties(\n {},\n {\n ...Object.getOwnPropertyDescriptors(layer.result),\n fetchNextPage: {\n value: (fetchOptions?: FetchNextPageOptions) =>\n observer.fetchNextPage(fetchOptions),\n enumerable: true,\n },\n fetchPreviousPage: {\n value: (fetchOptions?: FetchPreviousPageOptions) =>\n observer.fetchPreviousPage(fetchOptions),\n enumerable: true,\n },\n hasNextPage: {\n get: () => hasNextPage(pageOptions(), infiniteData()),\n enumerable: true,\n },\n hasPreviousPage: {\n get: () => hasPreviousPage(pageOptions(), infiniteData()),\n enumerable: true,\n },\n isFetchingNextPage: {\n get: isFetchingNextPage,\n enumerable: true,\n },\n isFetchingPreviousPage: {\n get: isFetchingPreviousPage,\n enumerable: true,\n },\n isFetchNextPageError: {\n get: () => isError() && direction() === 'forward',\n enumerable: true,\n },\n isFetchPreviousPageError: {\n get: () => isError() && direction() === 'backward',\n enumerable: true,\n },\n isRefetching: {\n get: () => {\n const current = direction()\n return (\n layer.isFetching() &&\n layer.status() !== 'pending' &&\n current !== 'forward' &&\n current !== 'backward'\n )\n },\n enumerable: true,\n },\n isRefetchError: {\n get: () => {\n const errored = isError() && layer.query().state.dataUpdatedAt !== 0\n return errored && direction() === undefined\n },\n enumerable: true,\n },\n },\n ) as InfiniteQueryObserverResult<TData, TError>\n\n return result as unknown as UseInfiniteQueryResult<TData, TError>\n}\n","import type {\n DefaultError,\n InfiniteData,\n InitialDataFunction,\n NonUndefinedGuard,\n QueryKey,\n QueryKeyWithDataTag,\n} from '@tanstack/query-core'\nimport type { InfiniteQueryOptions } from './types'\nimport type { Accessor } from 'solid-js'\n\n/**\n * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is omitted, may be\n * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is\n * `pending`. `infiniteQueryOptions` itself accepts and returns a plain object (its parameter type is\n * `ReturnType<UndefinedInitialDataInfiniteOptions<...>>`, i.e. this `Accessor` called); Solid's reactivity\n * applies where the result is consumed instead, e.g. `useInfiniteQuery(() => options)`.\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type UndefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = Accessor<\n InfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {\n initialData?:\n | undefined\n | NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>\n | InitialDataFunction<\n NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>\n >\n }\n>\n\n/**\n * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is known to be\n * defined — `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type DefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError = DefaultError,\n // should we handle page param correctly\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = Accessor<\n InfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {\n initialData:\n | NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>\n | (() => NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>)\n }\n>\n\n/**\n * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.\n * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.\n * `options.queryKey` is required and is the query key to generate options for.\n *\n * This overload is selected when `initialData` is known to be defined.\n * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n * @see {@link useInfiniteQuery} to run an infinite query with these options.\n * @example\n * ```tsx\n * import { For } from 'solid-js'\n * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/solid-query'\n *\n * const projectsOptions = infiniteQueryOptions({\n * queryKey: ['projects'],\n * queryFn: ({ pageParam }) => fetchProjects(pageParam),\n * initialPageParam: 0,\n * getNextPageParam: (lastPage) => lastPage.nextId,\n * initialData: { pages: [], pageParams: [] },\n * })\n *\n * function Projects() {\n * // `projectsQuery.data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the\n * // list stays visible alongside the error.\n * const projectsQuery = useInfiniteQuery(() => projectsOptions)\n *\n * return (\n * <div>\n * {projectsQuery.isError ? <span>Error: {projectsQuery.error.message}</span> : null}\n * <ul>\n * <For each={projectsQuery.data.pages}>\n * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}\n * </For>\n * </ul>\n * </div>\n * )\n * }\n * ```\n */\nexport function infiniteQueryOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: ReturnType<\n DefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >\n >,\n): ReturnType<\n DefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >\n> &\n QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>\n\n/**\n * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.\n * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.\n * `options.queryKey` is required and is the query key to generate options for.\n * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n * @see {@link useInfiniteQuery} to run an infinite query with these options.\n * @example\n * A parameterized factory, so the same options object can be reused per `postId`:\n * ```tsx\n * import { For, Match, Switch } from 'solid-js'\n * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/solid-query'\n *\n * const commentsOptions = (postId: string) =>\n * infiniteQueryOptions({\n * queryKey: ['post', postId, 'comments'],\n * queryFn: ({ pageParam }) => fetchComments(postId, pageParam),\n * initialPageParam: 0,\n * getNextPageParam: (lastPage) => lastPage.nextId,\n * })\n *\n * function Comments(props: { postId: string }) {\n * const commentsQuery = useInfiniteQuery(() => commentsOptions(props.postId))\n *\n * return (\n * <Switch>\n * <Match when={commentsQuery.isPending}>Loading...</Match>\n * <Match when={commentsQuery.isError}>Error: {commentsQuery.error.message}</Match>\n * <Match when={commentsQuery.isSuccess}>\n * <ul>\n * <For each={commentsQuery.data.pages}>\n * {(page) => <For each={page.comments}>{(c) => <li>{c.text}</li>}</For>}\n * </For>\n * </ul>\n * </Match>\n * </Switch>\n * )\n * }\n * ```\n */\nexport function infiniteQueryOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: ReturnType<\n UndefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >\n >,\n): ReturnType<\n UndefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >\n> &\n QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>\n\nexport function infiniteQueryOptions(options: unknown) {\n return options\n}\n","import { noop, shouldThrowError } from '@tanstack/query-core'\nimport {\n action,\n createMemo,\n createOptimistic,\n createRenderEffect,\n createSignal,\n onCleanup,\n untrack,\n} from 'solid-js'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n DefaultError,\n Mutation,\n MutationFunctionContext,\n} from '@tanstack/query-core'\nimport type { QueryClient } from './QueryClient'\nimport type {\n UseMutateFunction,\n UseMutationOptions,\n UseMutationResult,\n} from './types'\nimport type { Accessor } from 'solid-js'\n\nconst isServer = typeof window === 'undefined'\n\n/**\n * Durable mutation state: written post-`yield` inside the action's\n * transaction, so it commits atomically with everything else the settle\n * carries (invalidation-triggered refetches included).\n */\ninterface SettledState<TData, TError, TVariables> {\n status: 'idle' | 'success' | 'error'\n data: TData | undefined\n error: TError | null\n variables: TVariables | undefined\n submittedAt: number\n}\n\nconst IDLE: SettledState<any, any, any> = {\n status: 'idle',\n data: undefined,\n error: null,\n variables: undefined,\n submittedAt: 0,\n}\n\n/**\n * Drive the mutation generator without transaction semantics — the server\n * has no interactive paint to keep atomic. Yielded thenable values are\n * awaited and their results passed back in, matching what `action` does\n * minus the transition bookkeeping.\n * @param iterator - The mutation generator to run to completion.\n * @returns A promise for the generator's return value.\n */\nasync function drain<TReturn>(\n iterator: AsyncGenerator<unknown, TReturn, unknown>,\n): Promise<TReturn> {\n let input: unknown\n for (;;) {\n const result = await iterator.next(input)\n if (result.done) return result.value\n input = result.value != null ? await result.value : undefined\n }\n}\n\n/**\n * Mutations ride core `action`: each `mutate()` call is one transaction.\n *\n * - Transient flight state (`isPending`, in-flight `variables`) is a\n * `createOptimistic` overlay written at the top of the action — visible\n * immediately, dropped automatically when the transition settles. The\n * engine's revert-on-settle IS the submission state machine.\n * - `options.onMutate(variables)` runs inside the same window: it is the\n * place to apply the caller's own optimistic overlays\n * (`createOptimistic` / `createOptimisticStore` writes). No context\n * object, no rollback plumbing — reverting is the engine's job.\n * - The fetch itself goes through query-core:\n * `mutationCache.build().execute()` supplies retry/backoff, offline\n * pausing, scoped serial execution, and cache-level lifecycle callbacks.\n * No `MutationObserver` — the adapter reads the Mutation's state\n * directly where flight metadata (failureCount, isPaused) is needed.\n * - Options-level callbacks are stripped from the built mutation and\n * re-run *post-`yield`*, inside the transaction: an\n * `onSuccess → invalidateQueries` chain issues version bumps whose\n * refetches hold this very transition, so mutation success and fresh\n * query data land in one atomic paint (and a single-flight payload has\n * already primed the cache by the time `execute` resolves).\n * - One `mutate`, returning a safe-to-ignore promise: rejection is also\n * routed into reactive state, and a no-op catch keeps the ignored\n * branch from surfacing as an unhandled rejection. The\n * `mutate`/`mutateAsync` split existed for React's callback-vs-promise\n * error routing; it has no space here.\n * @param options - An accessor returning the {@link UseMutationOptions} to use.\n * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The mutation state, with `mutate` to run the mutation and `reset` to clear its state.\n */\nexport function useMutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n queryClient?: Accessor<QueryClient>,\n): UseMutationResult<TData, TError, TVariables, TOnMutateResult> {\n const client = createMemo(() => useQueryClient(queryClient?.()))\n\n /** Optimistic overlay: non-null exactly while a mutation is in flight. */\n const [flight, setFlight] = createOptimistic<{\n variables: TVariables\n } | null>(null)\n\n const [settled, setSettled] = createSignal<\n SettledState<TData, TError, TVariables>\n >(IDLE as SettledState<TData, TError, TVariables>)\n\n /**\n * Flight metadata (retry failures, offline pause) lives on the Mutation\n * instance and changes during the await gap; a version bump per cache\n * event for the active mutation keeps reads current without cloning\n * observer results. The subscription is per-flight, created in `run`\n * against the same client the mutation is built on: nothing reactive is\n * read at setup (no client read to untrack), the listener and the\n * mutation can never sit on different clients, and an idle hook holds no\n * cache subscription at all.\n */\n let activeMutation: Mutation<TData, TError, TVariables> | null = null\n let unsubscribeFlight: (() => void) | null = null\n const [flightVersion, setFlightVersion] = createSignal(0)\n if (!isServer)\n onCleanup(() => {\n unsubscribeFlight?.()\n unsubscribeFlight = null\n })\n\n /**\n * Runs one mutation: the flight overlay and `onMutate`, the fetch through query-core, then the\n * options-level callbacks and the durable settle.\n * @param variables - The variables passed to `mutate`.\n * @returns The data the mutation resolved with.\n * @yields {unknown} The promises the surrounding `action` (or `drain` on the server) awaits.\n */\n async function* run(\n variables: TVariables,\n ): AsyncGenerator<unknown, TData, unknown> {\n const opts = untrack(options)\n const callbackContext: MutationFunctionContext = {\n client: untrack(client),\n meta: opts.meta,\n mutationKey: opts.mutationKey,\n }\n // Server render is pure (rc.3 deprecates server setter calls): the\n // drain path only needs the return value/throw, so all reactive\n // bookkeeping — flight overlay and durable settle — is client-only.\n if (!isServer) setFlight({ variables })\n opts.onMutate?.(variables, callbackContext)\n\n const c = untrack(client)\n const mutation = c.getMutationCache().build(c, {\n ...opts,\n // Options-level callbacks re-run below, inside the transaction —\n // executing them here (inside the await gap) would let their\n // cache writes and invalidations escape the atomic settle.\n onMutate: undefined,\n onSuccess: undefined,\n onError: undefined,\n onSettled: undefined,\n })\n activeMutation = mutation\n if (!isServer) {\n // A rapid re-mutate replaces the previous flight's listener.\n unsubscribeFlight?.()\n unsubscribeFlight = c.getMutationCache().subscribe((event) => {\n if ('mutation' in event && event.mutation === activeMutation) {\n setFlightVersion((v) => v + 1)\n }\n })\n }\n const settleFlight = () => {\n if (activeMutation !== mutation) return\n activeMutation = null\n unsubscribeFlight?.()\n unsubscribeFlight = null\n }\n\n /**\n * Failure settle, shared by both paths. Callback routing mirrors\n * query-core's `Mutation.execute` (which never sees these callbacks —\n * they are stripped from the built mutation and re-run here, inside\n * the transaction): `onError` and an error-shaped `onSettled` run,\n * their own failures are reported as unhandled rejections but never\n * displace `error`, then the durable error state commits and the\n * mutate promise rejects with `error`.\n * @param error - The error the mutation or one of its success callbacks failed with.\n * @yields {unknown} The promises returned by `onError` and `onSettled`.\n */\n // Must be an async generator: async `yield` awaits its value in place,\n // so a rejecting callback promise throws at the yield inside the local\n // try/catch. A sync generator delegated from an async one gets its\n // values unwrapped by the async-from-sync adapter *outside* the inner\n // frame — the rejection would bypass these catches and kill the run.\n // eslint-disable-next-line @typescript-eslint/require-await -- async for yield-await semantics, not await expressions\n async function* settleFailure(\n error: TError,\n ): AsyncGenerator<unknown, never, unknown> {\n try {\n if (opts.onError)\n yield opts.onError(error, variables, undefined, callbackContext)\n } catch (callbackError) {\n void Promise.reject(callbackError)\n }\n try {\n if (opts.onSettled)\n yield opts.onSettled(\n undefined,\n error,\n variables,\n undefined,\n callbackContext,\n )\n } catch (callbackError) {\n void Promise.reject(callbackError)\n }\n if (!isServer)\n setSettled({\n status: 'error',\n data: undefined,\n error,\n variables,\n submittedAt: mutation.state.submittedAt,\n })\n settleFlight()\n throw error\n }\n\n let result: TData\n try {\n result = await mutation.execute(variables)\n } catch (error) {\n yield // re-enter the transaction before writing\n yield* settleFailure(error as TError)\n // Unreachable — settleFailure always throws. Explicit for TS's\n // definite-assignment analysis of `result` (yield* delegation is\n // not narrowed as never-returning).\n throw error\n }\n yield // re-enter the transaction before writing\n try {\n if (opts.onSuccess)\n yield opts.onSuccess(\n result,\n variables,\n undefined as TOnMutateResult,\n callbackContext,\n )\n if (opts.onSettled)\n yield opts.onSettled(\n result,\n null,\n variables,\n undefined,\n callbackContext,\n )\n } catch (callbackError) {\n // Mirror core: a success-path callback failure fails the mutation —\n // even though the cache entry committed success, the hook settles\n // to error with the callback error, and awaiting mutate rejects.\n yield* settleFailure(callbackError as TError)\n // Unreachable — settleFailure always throws (see above).\n throw callbackError\n }\n if (!isServer)\n setSettled({\n status: 'success',\n data: result,\n error: null,\n variables,\n submittedAt: mutation.state.submittedAt,\n })\n settleFlight()\n return result\n }\n\n const invoke: (variables: TVariables) => Promise<TData> = isServer\n ? (variables) => drain(run(variables))\n : action(run)\n\n const mutate: UseMutateFunction<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = (...args) => {\n const promise = invoke(args[0] as TVariables)\n // Errors also land in reactive state; ignoring the promise must not\n // surface an unhandled rejection. Awaiting it still rejects.\n promise.catch(noop)\n return promise\n }\n\n const status = () => (flight() !== null ? 'pending' : settled().status)\n const isPending = () => flight() !== null\n\n /**\n * Errors surface to `<Errored>` when `throwOnError` opts in. The throw\n * must happen in the compute half so it routes through notifyStatus and\n * boundary accounting.\n */\n createRenderEffect(\n () => {\n const state = settled()\n if (\n state.status === 'error' &&\n shouldThrowError(untrack(options).throwOnError, [state.error as TError])\n ) {\n throw state.error\n }\n },\n () => {},\n )\n\n const result = {\n mutate,\n get data() {\n return settled().data\n },\n get error() {\n return flight() !== null ? null : settled().error\n },\n get variables() {\n return flight()?.variables ?? settled().variables\n },\n get status() {\n return status()\n },\n get isPending() {\n return isPending()\n },\n get isIdle() {\n return status() === 'idle'\n },\n get isSuccess() {\n return status() === 'success'\n },\n get isError() {\n return status() === 'error'\n },\n get submittedAt() {\n return flight() !== null\n ? (flightVersion(), activeMutation?.state.submittedAt ?? 0)\n : settled().submittedAt\n },\n get failureCount() {\n flightVersion()\n return activeMutation?.state.failureCount ?? 0\n },\n get failureReason() {\n flightVersion()\n return (activeMutation?.state.failureReason ?? null) as TError | null\n },\n get isPaused() {\n flightVersion()\n return activeMutation?.state.isPaused ?? false\n },\n reset: () => {\n setSettled(IDLE as SettledState<TData, TError, TVariables>)\n },\n }\n\n return result\n}\n","import type { DefaultError, WithRequired } from '@tanstack/query-core'\nimport type { MutationOptions } from './types'\n\n/**\n * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A\n * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with\n * `useMutationState`.\n * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a\n * required `mutationKey`.\n * @returns The same options object, unchanged.\n * @see {@link useMutation} to run the mutation these options describe.\n * @example\n * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global \"saving…\" indicator:\n * ```tsx\n * import { mutationOptions, useMutationState } from '@tanstack/solid-query'\n *\n * const createPostOptions = mutationOptions({\n * mutationKey: ['posts', 'create'],\n * mutationFn: createPost,\n * })\n *\n * function SavingIndicator() {\n * const isCreatingPost = useMutationState(() => ({\n * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },\n * }))\n *\n * return isCreatingPost().length > 0 ? <span>Saving…</span> : null\n * }\n * ```\n */\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: WithRequired<\n MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n >,\n): WithRequired<\n MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n>\n/**\n * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No\n * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a\n * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters,\n * such as `status`.\n * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a\n * `mutationKey`.\n * @returns The same options object, unchanged.\n * @remarks See the other overload's example for looking a mutation up via `useMutationState`.\n * @see {@link useMutation} to run the mutation these options describe.\n * @example\n * ```tsx\n * import { mutationOptions, useMutation } from '@tanstack/solid-query'\n *\n * const createPostOptions = mutationOptions({\n * mutationFn: createPost,\n * })\n *\n * function CreatePost() {\n * const createPostMutation = useMutation(() => createPostOptions)\n * return <button onClick={() => createPostMutation.mutate({ title: 'Hello' })}>Create</button>\n * }\n * ```\n */\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: Omit<\n MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n >,\n): Omit<\n MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n>\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n): MutationOptions<TData, TError, TVariables, TOnMutateResult> {\n return options\n}\n","import { createMemo } from 'solid-js'\nimport { createCacheAggregate } from './cacheAggregate'\nimport { useQueryClient } from './QueryClientProvider'\nimport type { MutationFilters } from '@tanstack/query-core'\nimport type { QueryClient } from './QueryClient'\nimport type { Accessor } from 'solid-js'\n\n/**\n * The `useIsMutating` primitive returns the `number` of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n * @param filters - An accessor returning the {@link MutationFilters} to narrow down the matched mutations.\n * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns An accessor for the `number` of the mutations that your application currently has `pending`.\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/solid-query'\n *\n * function PostsMutatingIndicator() {\n * // How many mutations matching the posts prefix are in progress?\n * const isMutatingPosts = useIsMutating(() => ({ mutationKey: ['posts'] }))\n *\n * return isMutatingPosts() > 0 ? <span>Saving posts...</span> : null\n * }\n * ```\n */\nexport function useIsMutating(\n filters?: Accessor<Omit<MutationFilters, 'status'>>,\n queryClient?: Accessor<QueryClient>,\n): Accessor<number> {\n const client = createMemo(() => useQueryClient(queryClient?.()))\n return createCacheAggregate(\n (onEvent) => client().getMutationCache().subscribe(onEvent),\n () => client().isMutating(filters?.()),\n 0,\n )\n}\n","import { createMemo } from 'solid-js'\nimport { replaceEqualDeep } from '@tanstack/query-core'\nimport { createCacheAggregate } from './cacheAggregate'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n} from '@tanstack/query-core'\nimport type { Accessor } from 'solid-js'\nimport type { QueryClient } from './QueryClient'\n\ntype MutationTypeFromResult<TResult> = [TResult] extends [\n MutationState<\n infer TData,\n infer TError,\n infer TVariables,\n infer TOnMutateResult\n >,\n]\n ? Mutation<TData, TError, TVariables, TOnMutateResult>\n : Mutation\n\ntype MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n filters?: MutationFilters\n select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`\n * (or to their state, by default).\n * @param mutationCache - The mutation cache to read.\n * @param options - The `filters` to match and the `select` function to map each mutation with.\n * @returns The selected value of every matching mutation.\n */\nfunction getResult<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n mutationCache: MutationCache,\n options: MutationStateOptions<TResult, TMutation>,\n): Array<TResult> {\n return mutationCache\n .findAll(options.filters)\n .map(\n (mutation): TResult =>\n (options.select\n ? options.select(mutation as TMutation)\n : mutation.state) as TResult,\n )\n}\n\n/**\n * `useMutationState` is a primitive that gives you access to all mutations in the `MutationCache`. You can pass\n * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation\n * state.\n * @param options - An accessor returning the `filters` to narrow down matched mutations, and an optional\n * `select` to transform the mutation state.\n * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns An accessor for an array of whatever `select` returns for each matching mutation.\n * @example\n * Get all variables of all running mutations:\n * ```tsx\n * import { useMutationState } from '@tanstack/solid-query'\n *\n * function PendingPosts() {\n * const pendingVariables = useMutationState(() => ({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * }))\n *\n * return <>{pendingVariables().length} posts saving...</>\n * }\n * ```\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/solid-query'\n *\n * const mutationKey = ['posts']\n *\n * function Posts() {\n * // Some mutation that we want to get the state for\n * const createPostsMutation = useMutation(() => ({\n * mutationKey,\n * mutationFn: createPosts,\n * }))\n *\n * const savedPosts = useMutationState(() => ({\n * // this mutation key needs to match the mutation key of the given mutation (see above)\n * filters: { mutationKey, status: 'success' },\n * select: (mutation) => mutation.state.data,\n * }))\n *\n * return (\n * <button onClick={() => createPostsMutation.mutate(['New Post'])}>\n * Create post ({savedPosts().length} saved so far)\n * </button>\n * )\n * }\n * ```\n * @example\n * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new\n * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the\n * last item that `useMutationState` returns to get the latest successful invocation:\n * ```tsx\n * import { useMutationState } from '@tanstack/solid-query'\n *\n * function LatestPost() {\n * const savedPosts = useMutationState(() => ({\n * filters: { mutationKey: ['posts'], status: 'success' },\n * select: (mutation) => mutation.state.data,\n * }))\n *\n * const latestPost = () => savedPosts()[savedPosts().length - 1]\n *\n * return <span>{latestPost()?.title}</span>\n * }\n * ```\n */\nexport function useMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: Accessor<MutationStateOptions<TResult, TMutation>> = () => ({}),\n queryClient?: Accessor<QueryClient>,\n): Accessor<Array<TResult>> {\n const client = createMemo(() => useQueryClient(queryClient?.()))\n return createCacheAggregate<Array<TResult>>(\n (onEvent) => client().getMutationCache().subscribe(onEvent),\n // Structural sharing against the previous committed value keeps\n // unchanged mutation states referentially stable across syncs.\n (prev) =>\n replaceEqualDeep(prev, getResult(client().getMutationCache(), options())),\n [],\n )\n}\n","import { QueryObserver } from '@tanstack/query-core'\nimport { $TRACK, createMemo, repeat } from 'solid-js'\nimport { useBaseQuery } from './useBaseQuery'\nimport type { QueryOptions, UseQueryResult } from './types'\nimport type { Accessor } from 'solid-js'\nimport type { QueryClient } from './QueryClient'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesPlaceholderDataFunction,\n QueryFunction,\n QueryKey,\n ThrowOnError,\n} from '@tanstack/query-core'\n\n// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function does not have a parameter\ntype UseQueryOptionsForUseQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n /**\n * @deprecated The `suspense` option has been removed. Suspense is the\n * model: each result's `data` is an async read that suspends into the\n * nearest `<Loading>` boundary while its first fetch is in flight, same\n * as `useQuery`. Setting `suspense` is a no-op.\n */\n suspense?: boolean\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForUseQueries = symbol\n\ntype GetOptions<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? UseQueryOptionsForUseQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? UseQueryOptionsForUseQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n UseQueryOptionsForUseQueries\n\ntype GetResults<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? UseQueryResult<TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? UseQueryResult<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? UseQueryResult<TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? UseQueryResult<TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? UseQueryResult<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? UseQueryResult<TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? UseQueryResult<\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n UseQueryResult\n\n/**\n * QueriesOptions reducer recursively snapshots function arguments to infer/enforce type param\n */\ntype QueriesOptions<\n T extends Array<any>,\n TResult extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryOptionsForUseQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResult, GetOptions<Head>]\n : T extends [infer Head, ...infer Tail]\n ? QueriesOptions<\n [...Tail],\n [...TResult, GetOptions<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n UseQueryOptionsForUseQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n UseQueryOptionsForUseQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<UseQueryOptionsForUseQueries>\n\n/**\n * QueriesResults reducer recursively maps type param to results\n */\ntype QueriesResults<\n T extends Array<any>,\n TResult extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResult, GetResults<Head>]\n : T extends [infer Head, ...infer Tail]\n ? QueriesResults<\n [...Tail],\n [...TResult, GetResults<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetResults<T[K]> }\n\n/**\n * The `useQueries` primitive can be used to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects mostly identical to `useQuery` — see\n * `placeholderData` below for the one difference. A custom `QueryClient` is supplied once, as `useQueries`'\n * own top-level second argument, rather than per query.\n *\n * Having the same query key more than once in the array of query objects may cause some data to be shared\n * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value. The result will\n * be structurally shared to be as referentially stable as possible.\n *\n * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from\n * previously rendered queries, because the number of queries can differ between renders.\n * @param queriesOptions - An accessor returning the `queries` array to run, and an optional `combine`\n * function.\n * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The combined result. Without `combine`, this is an array with all the query results, in the same\n * order as the input. When `combine` is provided, this is the value returned by `combine` instead.\n * @example\n * ```tsx\n * import { For } from 'solid-js'\n * import { useQueries } from '@tanstack/solid-query'\n *\n * function Posts(props: { ids: Array<number> }) {\n * const postQueries = useQueries(() => ({\n * queries: props.ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * }))\n *\n * return (\n * <ul>\n * <For each={postQueries}>\n * {(postQuery) => {\n * if (postQuery.isPending) return <li>Loading...</li>\n * if (postQuery.isError) return <li>Error: {postQuery.error.message}</li>\n * return <li>{postQuery.data.title}</li>\n * }}\n * </For>\n * </ul>\n * )\n * }\n * ```\n * @example\n * Combining results into a single value:\n * ```tsx\n * import { For, Match, Switch } from 'solid-js'\n * import { useQueries } from '@tanstack/solid-query'\n *\n * function Posts(props: { ids: Array<number> }) {\n * const combinedPostsQuery = useQueries(() => ({\n * queries: props.ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (postQueries) => {\n * return {\n * data: postQueries.map((postQuery) => postQuery.data),\n * isPending: postQueries.some((postQuery) => postQuery.isPending),\n * isError: postQueries.some((postQuery) => postQuery.isError),\n * }\n * },\n * }))\n *\n * return (\n * <Switch\n * fallback={\n * <ul>\n * <For each={combinedPostsQuery.data}>{(post) => <li>{post?.title}</li>}</For>\n * </ul>\n * }\n * >\n * <Match when={combinedPostsQuery.isPending}>Loading...</Match>\n * <Match when={combinedPostsQuery.isError}>Error loading posts</Match>\n * </Switch>\n * )\n * }\n * ```\n */\nexport function useQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n queriesOptions: Accessor<{\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [...{ [K in keyof T]: GetOptions<T[K]> }]\n combine?: (result: QueriesResults<T>) => TCombinedResult\n }>,\n queryClient?: Accessor<QueryClient>,\n): TCombinedResult {\n /**\n * One read layer per position, count-keyed: each row owns a full\n * `useBaseQuery` (observer lifecycle, version signal, async data node)\n * whose options stay reactive through the per-index accessor — option\n * changes flow into the existing row without tearing it down, while\n * length changes create/dispose tail rows. Every result has identical\n * semantics to `useQuery`: reads suspend, settled data is non-nullable.\n */\n const length = createMemo(() => queriesOptions().queries.length)\n const results = repeat(length, (index) => {\n // When the array shrinks, cache events can reach this row's\n // subscriptions before disposal runs; the row keeps answering with its\n // last options rather than reading past the end of the shorter array.\n let lastOptions: any\n return useBaseQuery(\n () => {\n const next = queriesOptions().queries[index]\n if (next !== undefined) lastOptions = next\n return lastOptions\n },\n QueryObserver,\n queryClient,\n )\n })\n\n const combined = createMemo(() => {\n const combine = queriesOptions().combine\n const list = results() as unknown as QueriesResults<T>\n return combine ? combine(list) : (list as unknown as TCombinedResult)\n })\n\n // A stable facade over the combined result. Property reads pull through\n // the memo so consumers track exactly what they touch; $TRACK hands list\n // helpers (<For>, mapArray) the underlying array for diffing.\n return new Proxy([] as unknown as TCombinedResult & object, {\n get(_, prop) {\n if (prop === $TRACK) return combined()\n return Reflect.get(combined() as object, prop)\n },\n has(_, prop) {\n if (prop === $TRACK) return true\n return Reflect.has(combined() as object, prop)\n },\n ownKeys() {\n return Reflect.ownKeys(combined() as object)\n },\n getOwnPropertyDescriptor(_, prop) {\n const descriptor = Reflect.getOwnPropertyDescriptor(\n combined() as object,\n prop,\n )\n if (descriptor) descriptor.configurable = true\n return descriptor\n },\n })\n}\n","/* istanbul ignore file */\n\n// Re-export core\n// oxlint-disable-next-line tanstack-query/no-restricted-syntax\nexport * from '@tanstack/query-core'\n\n// Solid Query\n\nexport type {\n DefinedUseBaseQueryResult,\n DefinedUseInfiniteQueryResult,\n DefinedUseQueryResult,\n InfiniteQueryOptions,\n MutationOptions,\n QueryOptions,\n UseBaseMutationResult,\n UseBaseQueryOptions,\n UseBaseQueryResult,\n UseInfiniteQueryOptions,\n UseInfiniteQueryResult,\n UseMutateFunction,\n UseMutationOptions,\n UseMutationResult,\n UseQueryOptions,\n UseQueryResult,\n} from './types'\n\nexport { QueryClient } from './QueryClient'\nexport type {\n QueryObserverOptions,\n DefaultOptions,\n QueryClientConfig,\n InfiniteQueryObserverOptions,\n} from './QueryClient'\nexport { useQuery } from './useQuery'\nexport { queryOptions } from './queryOptions'\nexport type {\n DefinedInitialDataOptions,\n UndefinedInitialDataOptions,\n} from './queryOptions'\nexport {\n FLIGHT_DATA_SOURCE,\n QueryClientContext,\n QueryClientProvider,\n useQueryClient,\n} from './QueryClientProvider'\nexport type { QueryClientProviderProps } from './QueryClientProvider'\nexport { dehydrateSettled } from './dehydrateSettled'\nexport { useIsFetching } from './useIsFetching'\nexport { useInfiniteQuery } from './useInfiniteQuery'\nexport { infiniteQueryOptions } from './infiniteQueryOptions'\nexport type {\n DefinedInitialDataInfiniteOptions,\n UndefinedInitialDataInfiniteOptions,\n} from './infiniteQueryOptions'\nexport { useMutation } from './useMutation'\nexport { mutationOptions } from './mutationOptions'\nexport { useIsMutating } from './useIsMutating'\nexport { useMutationState } from './useMutationState'\nexport { useQueries } from './useQueries'\nexport { useIsRestoring, IsRestoringContext } from './isRestoring'\n"],"mappings":"A,qtBAkFA,IAAakF,EAAb,cAAiClF,CAAgB,CAC/C,YAAY,EAA4B,CAAC,EAAG,CAC1C,MAAMmF,CAAM,CACd,CACF,EC9EA,MAAM1E,EAAW,OAAOC,OAAW,IAuCtBE,EAAqB,KAuClC,SAASE,EACPC,EACAC,EACAC,EACM,CACN,IAAMC,EAAWD,EAASE,QAAQC,IAAIf,EAAiB,EACvD,GAAIa,IAAa,KAAM,OACvB,IAAMG,EAAU,IAAIC,IAClBN,GAASO,QAAQC,IAAKC,GAAUA,EAAMC,SAAS,GAAK,CAAA,CACtD,EACMC,EAAaF,GAAiB,CAACJ,EAA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MAAiB,CAChC,IAAMqJ,EAAUN,EAAe,CAAC,CAAC,QAC3BO,EAAON,EAAQ,EACrB,OAAOK,EAAUA,EAAQC,CAAI,EAAKA,CACpC,CAAC,EAKD,OAAO,IAAI,MAAM,CAAC,EAA0C,CAC1D,IAAI,EAAG,EAAM,CAEX,OADIC,IAASC,EAAeJ,EAAS,EAC9B,QAAQ,IAAIA,EAAS,EAAaG,CAAI,CAC/C,EACA,IAAI,EAAG,EAAM,CAEX,OADIA,IAASC,GACN,QAAQ,IAAIJ,EAAS,EAAaG,CAAI,CAC/C,EACA,SAAU,CACR,OAAO,QAAQ,QAAQH,EAAS,CAAW,CAC7C,EACA,yBAAyB,EAAG,EAAM,CAChC,IAAMK,EAAa,QAAQ,yBACzBL,EAAS,EACTG,CACF,EAEA,OADIE,IAAY,EAAW,aAAe,IACnCA,CACT,CACF,CAAC,CACH"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/solid-query",
|
|
3
|
-
"version": "6.0.0-rc.
|
|
3
|
+
"version": "6.0.0-rc.6",
|
|
4
4
|
"description": "Primitives for managing, caching and syncing asynchronous and remote data in Solid",
|
|
5
5
|
"author": "tannerlinsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -46,41 +46,40 @@
|
|
|
46
46
|
"!src/__tests__"
|
|
47
47
|
],
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@tanstack/query-core": "5.
|
|
49
|
+
"@tanstack/query-core": "5.107.1"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@babel/core": "^7.28.0",
|
|
53
53
|
"@babel/preset-typescript": "^7.18.6",
|
|
54
|
+
"@solidjs/babel-plugin": "^2.0.0",
|
|
54
55
|
"@solidjs/testing-library": "^0.8.10",
|
|
55
|
-
"@solidjs/vite-plugin": "^3.0.0
|
|
56
|
-
"@solidjs/web": "^2.0.0
|
|
57
|
-
"
|
|
58
|
-
"
|
|
59
|
-
"solid
|
|
60
|
-
"
|
|
61
|
-
"
|
|
56
|
+
"@solidjs/vite-plugin": "^3.0.0",
|
|
57
|
+
"@solidjs/web": "^2.0.0",
|
|
58
|
+
"@tanstack/query-test-utils": "0.0.0",
|
|
59
|
+
"@types/babel__core": "^7.20.5",
|
|
60
|
+
"eslint-plugin-solid": "^0.18.1",
|
|
61
|
+
"solid-js": "^2.0.0",
|
|
62
|
+
"typescript": "6.0.3"
|
|
62
63
|
},
|
|
63
64
|
"peerDependencies": {
|
|
64
|
-
"@solidjs/web": "
|
|
65
|
-
"solid-js": "
|
|
65
|
+
"@solidjs/web": "^2.0.0",
|
|
66
|
+
"solid-js": "^2.0.0"
|
|
66
67
|
},
|
|
67
68
|
"scripts": {
|
|
68
|
-
"clean": "premove ./build ./coverage ./dist-ts",
|
|
69
|
-
"compile": "tsc --
|
|
70
|
-
"test:
|
|
69
|
+
"clean": "premove ./build ./coverage ./dist-ts ./.cache/test-types",
|
|
70
|
+
"compile": "tsc --project tsconfig.json",
|
|
71
|
+
"test:oxlint": "oxlint ./src",
|
|
71
72
|
"test:types": "npm-run-all --serial test:types:*",
|
|
72
|
-
"test:types:
|
|
73
|
-
"test:types:
|
|
74
|
-
"test:types:
|
|
75
|
-
"test:types:
|
|
76
|
-
"test:types:
|
|
77
|
-
"test:types:
|
|
78
|
-
"test:types:tscurrent": "tsc --build",
|
|
79
|
-
"test:types:ts60": "node ../../node_modules/typescript60/lib/tsc.js --build tsconfig.legacy.json",
|
|
73
|
+
"test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts57 --tsBuildInfoFile .cache/test-types/ts57.tsbuildinfo",
|
|
74
|
+
"test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts58 --tsBuildInfoFile .cache/test-types/ts58.tsbuildinfo",
|
|
75
|
+
"test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts59 --tsBuildInfoFile .cache/test-types/ts59.tsbuildinfo",
|
|
76
|
+
"test:types:tscurrent": "tsc --project tsconfig.json --outDir .cache/test-types/tscurrent --tsBuildInfoFile .cache/test-types/tscurrent.tsbuildinfo",
|
|
77
|
+
"test:types:ts70": "node ../../node_modules/typescript70/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts70 --tsBuildInfoFile .cache/test-types/ts70.tsbuildinfo",
|
|
78
|
+
"test:types:ts71": "node ../../node_modules/typescript71/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts71 --tsBuildInfoFile .cache/test-types/ts71.tsbuildinfo",
|
|
80
79
|
"test:lib": "vitest --retry=3",
|
|
81
80
|
"test:lib:dev": "pnpm run test:lib --watch",
|
|
82
81
|
"test:build": "publint --strict && attw --pack",
|
|
83
|
-
"build": "
|
|
84
|
-
"build:watch": "
|
|
82
|
+
"build": "tsdown --tsconfig tsconfig.prod.json",
|
|
83
|
+
"build:watch": "tsdown --watch"
|
|
85
84
|
}
|
|
86
85
|
}
|
package/src/QueryClient.ts
CHANGED
|
@@ -32,6 +32,14 @@ export type QueryObserverOptions<
|
|
|
32
32
|
TPageParam
|
|
33
33
|
>
|
|
34
34
|
|
|
35
|
+
/**
|
|
36
|
+
* The core `InfiniteQueryObserverOptions`, passed through unchanged.
|
|
37
|
+
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
|
|
38
|
+
* @template TError - The type of errors your `queryFn` may throw.
|
|
39
|
+
* @template TData - The type `data` ends up as after `select` runs.
|
|
40
|
+
* @template TQueryKey - The type of your `queryKey`.
|
|
41
|
+
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
|
|
42
|
+
*/
|
|
35
43
|
export type InfiniteQueryObserverOptions<
|
|
36
44
|
TQueryFnData = unknown,
|
|
37
45
|
TError = DefaultError,
|
|
@@ -46,16 +54,32 @@ export type InfiniteQueryObserverOptions<
|
|
|
46
54
|
TPageParam
|
|
47
55
|
>
|
|
48
56
|
|
|
57
|
+
/**
|
|
58
|
+
* The default options a `QueryClient` applies to every query and mutation.
|
|
59
|
+
* @template TError - The default type of errors thrown by queries and mutations using this `QueryClient`.
|
|
60
|
+
*/
|
|
49
61
|
export interface DefaultOptions<
|
|
50
62
|
TError = DefaultError,
|
|
51
63
|
> extends CoreDefaultOptions<TError> {
|
|
64
|
+
/**
|
|
65
|
+
* Default options applied to every query, unless overridden per-query.
|
|
66
|
+
*/
|
|
52
67
|
queries?: OmitKeyof<QueryObserverOptions<unknown, TError>, 'queryKey'>
|
|
53
68
|
}
|
|
54
69
|
|
|
70
|
+
/**
|
|
71
|
+
* The config accepted by `new QueryClient(config)`, with Solid's {@link DefaultOptions}.
|
|
72
|
+
*/
|
|
55
73
|
export interface QueryClientConfig extends QueryCoreClientConfig {
|
|
74
|
+
/**
|
|
75
|
+
* The default options of the queries and mutations of this `QueryClient`.
|
|
76
|
+
*/
|
|
56
77
|
defaultOptions?: DefaultOptions
|
|
57
78
|
}
|
|
58
79
|
|
|
80
|
+
/**
|
|
81
|
+
* The core `@tanstack/query-core` `QueryClient`, typed with Solid's {@link QueryClientConfig}.
|
|
82
|
+
*/
|
|
59
83
|
export class QueryClient extends QueryCoreClient {
|
|
60
84
|
constructor(config: QueryClientConfig = {}) {
|
|
61
85
|
super(config)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { createContext,
|
|
2
|
-
import { REVALIDATE_HEADER } from '@solidjs/web'
|
|
1
|
+
import { createContext, isHydratable, onCleanup, useContext } from 'solid-js'
|
|
2
|
+
import { REVALIDATE_HEADER, getHydrationWriter } from '@solidjs/web'
|
|
3
3
|
import { hydrate } from '@tanstack/query-core'
|
|
4
4
|
import { subscribeFlightData } from '@solidjs/web/server-functions'
|
|
5
5
|
import type { DehydratedState, Query } from '@tanstack/query-core'
|
|
@@ -80,6 +80,9 @@ const REVALIDATE_ALL = '*'
|
|
|
80
80
|
* explicitly. The reserved key `*` (`revalidate: '*'`): every query in the
|
|
81
81
|
* cache, minus what the payload covered — the way to say "all" to any
|
|
82
82
|
* host, rather than relying on one host's default.
|
|
83
|
+
* @param client - The `QueryClient` whose queries are invalidated.
|
|
84
|
+
* @param payload - The dehydrated slice the response carried for this cache, if any.
|
|
85
|
+
* @param response - The mutation response, read for its `X-Revalidate` header.
|
|
83
86
|
*/
|
|
84
87
|
function sweepRevalidatedQueries(
|
|
85
88
|
client: QueryClient,
|
|
@@ -113,6 +116,14 @@ export const QueryClientContext = createContext<(() => QueryClient) | null>(
|
|
|
113
116
|
null,
|
|
114
117
|
)
|
|
115
118
|
|
|
119
|
+
/**
|
|
120
|
+
* The `useQueryClient` primitive returns the current `QueryClient` instance.
|
|
121
|
+
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
|
|
122
|
+
* be used.
|
|
123
|
+
* @returns The current `QueryClient` instance.
|
|
124
|
+
* @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the
|
|
125
|
+
* component tree.
|
|
126
|
+
*/
|
|
116
127
|
export const useQueryClient = (queryClient?: QueryClient) => {
|
|
117
128
|
if (queryClient) {
|
|
118
129
|
return queryClient
|
|
@@ -126,8 +137,19 @@ export const useQueryClient = (queryClient?: QueryClient) => {
|
|
|
126
137
|
return client()
|
|
127
138
|
}
|
|
128
139
|
|
|
140
|
+
/**
|
|
141
|
+
* The props accepted by `QueryClientProvider`.
|
|
142
|
+
*/
|
|
129
143
|
export type QueryClientProviderProps = {
|
|
144
|
+
/**
|
|
145
|
+
* **Required**
|
|
146
|
+
*
|
|
147
|
+
* The `QueryClient` instance to provide.
|
|
148
|
+
*/
|
|
130
149
|
client: QueryClient
|
|
150
|
+
/**
|
|
151
|
+
* The components that get access to the provided `QueryClient`.
|
|
152
|
+
*/
|
|
131
153
|
children?: JSX.Element
|
|
132
154
|
}
|
|
133
155
|
|
|
@@ -146,18 +168,11 @@ export type QueryClientProviderProps = {
|
|
|
146
168
|
* long after) finds it by hash. One entry per hash regardless of how many
|
|
147
169
|
* hooks read it; the payload object is the same reference the data nodes
|
|
148
170
|
* serialize, so seroval's cross-reference dedupe emits it once.
|
|
171
|
+
* @param client - The request's `QueryClient`.
|
|
149
172
|
*/
|
|
150
173
|
function serializeCacheOnServer(client: QueryClient): void {
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
context?: {
|
|
154
|
-
async?: boolean
|
|
155
|
-
noHydrate?: boolean
|
|
156
|
-
serialize: (key: string, value: unknown) => void
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
).context
|
|
160
|
-
if (!ctx || !ctx.async || ctx.noHydrate) return
|
|
174
|
+
const writer = getHydrationWriter()
|
|
175
|
+
if (!writer || !writer.async || !isHydratable()) return
|
|
161
176
|
|
|
162
177
|
const cache = client.getQueryCache()
|
|
163
178
|
// The standard dehydrate filter gates the wire here too, so apps keep
|
|
@@ -175,7 +190,7 @@ function serializeCacheOnServer(client: QueryClient): void {
|
|
|
175
190
|
const state = query.state
|
|
176
191
|
if (state.status === 'success') {
|
|
177
192
|
seen.add(query.queryHash)
|
|
178
|
-
|
|
193
|
+
writer.write(HYDRATION_KEY_PREFIX + query.queryHash, {
|
|
179
194
|
data: state.data,
|
|
180
195
|
t: state.dataUpdatedAt,
|
|
181
196
|
})
|
|
@@ -185,7 +200,7 @@ function serializeCacheOnServer(client: QueryClient): void {
|
|
|
185
200
|
const promise = query.promise as Promise<unknown> | undefined
|
|
186
201
|
if (!promise) return
|
|
187
202
|
seen.add(query.queryHash)
|
|
188
|
-
|
|
203
|
+
writer.write(
|
|
189
204
|
HYDRATION_KEY_PREFIX + query.queryHash,
|
|
190
205
|
promise.then(() => ({
|
|
191
206
|
data: query.state.data,
|
|
@@ -210,6 +225,8 @@ function serializeCacheOnServer(client: QueryClient): void {
|
|
|
210
225
|
* Subscribing is inert when no server collector exists — the server just
|
|
211
226
|
* folds nothing — so it is unconditional. One consumer per source: with
|
|
212
227
|
* nested providers, the innermost mounted one owns the slice.
|
|
228
|
+
* @param props - The `client` to provide, and the `children` that get access to it.
|
|
229
|
+
* @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
|
|
213
230
|
*/
|
|
214
231
|
export const QueryClientProvider = (
|
|
215
232
|
props: QueryClientProviderProps,
|
|
@@ -235,8 +252,8 @@ export const QueryClientProvider = (
|
|
|
235
252
|
FLIGHT_DATA_SOURCE,
|
|
236
253
|
(data, context) => {
|
|
237
254
|
// `data` is undefined for a response that carried metadata but
|
|
238
|
-
// no slice for this cache
|
|
239
|
-
hydrate(props.client, data)
|
|
255
|
+
// no slice for this cache.
|
|
256
|
+
if (data) hydrate(props.client, data)
|
|
240
257
|
// Fresh data first, then the declared-scope sweep: stale marks
|
|
241
258
|
// land synchronously, refetches run in the background — the
|
|
242
259
|
// mutation's promise never waits on them.
|