diff --git a/.changeset/remove-tanstack-query.md b/.changeset/remove-tanstack-query.md
new file mode 100644
index 0000000000..21e9e8fbad
--- /dev/null
+++ b/.changeset/remove-tanstack-query.md
@@ -0,0 +1,12 @@
+---
+"@effect-app/vue": minor
+"@effect-app/e2e": patch
+---
+
+Remove the TanStack query engine and its patch, leaving the Atom engine as the only query backend.
+
+- Drop `@tanstack/vue-query` / `@tanstack/query-core` dependencies and the `patches/@tanstack__query-core.patch`.
+- Delete `packages/vue/src/internal/tanstackQuery.ts` (`makeTanstackQuery`, `makeTanstackQueryClient`, `makeTanstackQueryInvalidator`, `makeTanstackQueryCacheUpdater`).
+- `makeClient` no longer accepts `legacyQueryEngine` (always Atom) and no longer returns `tanstackQueryClient`. The `MakeClientOptions` interface is removed.
+- `QueryImpl` no longer takes a `legacyUseQuery` override; `.query()` / `.suspense()` now always run on the Atom engine alongside `.atom()` / `.family()` / `.queryNew()` / `.suspenseNew()`.
+- Tests that exercised the tanstack path are dropped or converted to the Atom path (query-span, suspense-regression structural sharing, dependency-invalidation matrix, e2e repo invalidation).
diff --git a/package.json b/package.json
index 4cbaf9fa21..22fa4ec705 100644
--- a/package.json
+++ b/package.json
@@ -7,7 +7,6 @@
],
"patchedDependencies": {
"ts-plugin-sort-import-suggestions": "patches/ts-plugin-sort-import-suggestions.patch",
- "@tanstack/query-core": "patches/@tanstack__query-core.patch",
"typescript@6.0.3": "patches/typescript.patch",
"@sendgrid/mail": "patches/@sendgrid__mail.patch"
}
diff --git a/packages/e2e/package.json b/packages/e2e/package.json
index 1b12c7da73..ef32898f79 100644
--- a/packages/e2e/package.json
+++ b/packages/e2e/package.json
@@ -13,7 +13,6 @@
"@effect/atom-vue": "^4.0.0-beta.90",
"@effect/platform-node": "4.0.0-beta.90",
"@effect/vitest": "4.0.0-beta.90",
- "@tanstack/vue-query": "5.96.2",
"@types/node": "25.9.1",
"@vitejs/plugin-vue": "^6.0.7",
"effect": "^4.0.0-beta.90",
diff --git a/packages/e2e/test/repoInvalidation.e2e.test.ts b/packages/e2e/test/repoInvalidation.e2e.test.ts
index 7247e22801..414dd3f960 100644
--- a/packages/e2e/test/repoInvalidation.e2e.test.ts
+++ b/packages/e2e/test/repoInvalidation.e2e.test.ts
@@ -4,7 +4,6 @@ import { invalidateQueries } from "@effect-app/vue/mutate"
import { defaultRegistry } from "@effect/atom-vue"
import { NodeHttpServer } from "@effect/platform-node"
import { expect, it } from "@effect/vitest"
-import { QueryClient, VueQueryPlugin } from "@tanstack/vue-query"
import { ApiClientFactory, InvalidStateError, makeRpcClient, NotLoggedInError, OptimisticConcurrencyException } from "effect-app/client"
import * as Context from "effect-app/Context"
import * as Effect from "effect-app/Effect"
@@ -22,12 +21,10 @@ import { FetchHttpClient } from "effect/unstable/http"
import * as Reactivity from "effect/unstable/reactivity/Reactivity"
import { RpcSerialization } from "effect/unstable/rpc"
import { createServer } from "http"
-import { createApp, effectScope, ref } from "vue"
import { RequestContextMiddleware } from "../../infra/src/internal/RequestContextMiddleware.ts"
import { makeRouter } from "../../infra/src/routing.ts"
import { DefaultGenericMiddlewaresLive } from "../../infra/src/routing/middleware.ts"
import { MemoryStoreLive } from "../../infra/src/Store/Memory.ts"
-import { makeTanstackQuery, makeTanstackQueryInvalidator } from "../../vue/src/internal/tanstackQuery.ts"
class RequestContextMap extends RpcContextMap.makeMap({
allowAnonymous: RpcContextMap.makeInverted()(NotLoggedInError)
@@ -210,58 +207,3 @@ it("atom engine: rpc repo write invalidates and refetches; unrelated rpc write d
await runtime.dispose()
}
}, 10_000)
-
-it("tanstack engine: rpc repo write invalidates and refetches; unrelated rpc write does not", async () => {
- const [runtime, client, context] = await setup()
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: Infinity, staleTime: 0 } }
- })
- const useQuery = makeTanstackQuery(() => context, queryClient)
- const invalidator = makeTanstackQueryInvalidator(queryClient)
- const app = createApp({ render: () => null })
- app.use(VueQueryPlugin, { queryClient })
- const scope = effectScope(true)
- let handle: any
- let data: any
- const run = (effect: Effect.Effect) => Effect.runPromise(effect)
- const save = (id: string) =>
- run(
- invalidateQueries(client.SaveRepoItem, undefined, invalidator)(client.SaveRepoItem.handler({ id, label: id }), {
- id,
- label: id
- })
- .pipe(Effect.provide(context)) as any
- )
- const saveOther = (id: string) =>
- run(
- invalidateQueries(client.SaveOtherItem, undefined, invalidator)(client.SaveOtherItem.handler({ id, label: id }), {
- id,
- label: id
- })
- .pipe(Effect.provide(context)) as any
- )
-
- app.runWithContext(() =>
- scope.run(() => {
- const tuple = useQuery(client.GetRepoCount as any)(ref(undefined) as any, {} as any) as any
- data = tuple[1]
- handle = tuple[3]
- })
- )
-
- try {
- expect(await run(handle.refetch())).toBe(0)
-
- await save("1")
- expect(data.value).toBe(1)
-
- const before = await run(client.GetRepoCountRuns.handler().pipe(Effect.provide(context)) as any)
- await saveOther("x")
- const after = await run(client.GetRepoCountRuns.handler().pipe(Effect.provide(context)) as any)
- expect(after).toBe(before)
- } finally {
- scope.stop()
- queryClient.clear()
- await runtime.dispose()
- }
-}, 10_000)
diff --git a/packages/vue/docs/query-key-invalidation.md b/packages/vue/docs/query-key-invalidation.md
index 024e339afd..1396eb9f76 100644
--- a/packages/vue/docs/query-key-invalidation.md
+++ b/packages/vue/docs/query-key-invalidation.md
@@ -73,8 +73,8 @@ Both sides route through `keysToHashes`, which hashes **each element** of the ke
- Registration: `withReactivity(reactivityKeys)` → `registerUnsafe` — `reactivityKeys` is a
list of prefix-arrays, each hashed via `Hash.hash`.
-- Invalidation: mutations pass `ReadonlyArray>` — a *list of
- key-arrays* (`buildInvalidateCache` in [`src/mutate.ts`](../src/mutate.ts)) — so each
+- Invalidation: mutations pass `ReadonlyArray>` — a _list of
+ key-arrays_ (`buildInvalidateCache` in [`src/mutate.ts`](../src/mutate.ts)) — so each
element is a full namespaced array, matching the registration shape.
The await-tracking map (`keyAtoms` in `atomQuery.ts`) keys on the same `Hash.hash(key)`, so
@@ -89,7 +89,7 @@ The await-tracking map (`keyAtoms` in `atomQuery.ts`) keys on the same `Hash.has
the one real semantic divergence from TanStack's exact compare. Same applies to
`keyAtoms` and `uniqueKeys`.
2. **Input is one opaque trailing element** (`[...baseKey, input]`). You can invalidate at
- any namespace granularity but not *within* an input (no "all inputs where
+ any namespace granularity but not _within_ an input (no "all inputs where
status=active"). TanStack with the same key shape behaves identically — parity, just a
granularity ceiling.
3. **O(depth) registrations per live query** (depth+1 prefixes, in both the reactivity
diff --git a/packages/vue/package.json b/packages/vue/package.json
index 6b4b2b5301..5038b412c6 100644
--- a/packages/vue/package.json
+++ b/packages/vue/package.json
@@ -6,7 +6,6 @@
"homepage": "https://github.com/effect-ts-app/libs/tree/main/packages/vue",
"dependencies": {
"@formatjs/intl": "^4.1.12",
- "@tanstack/vue-query": "5.96.2",
"@vueuse/core": "^14.3.0",
"change-case": "^5.4.4",
"effect-app": "workspace:*",
diff --git a/packages/vue/src/internal/tanstackQuery.ts b/packages/vue/src/internal/tanstackQuery.ts
deleted file mode 100644
index 4770349bfe..0000000000
--- a/packages/vue/src/internal/tanstackQuery.ts
+++ /dev/null
@@ -1,289 +0,0 @@
-import { injectRegistry } from "@effect/atom-vue"
-import { QueryClient, useQuery as useTanstackQuery } from "@tanstack/vue-query"
-import { DataDependencies, makeQueryKey, type Req } from "effect-app/client"
-import type { RequestHandlerWithInput } from "effect-app/client/clientFor"
-import { CauseException, ServiceUnavailableError } from "effect-app/client/errors"
-import type * as Context from "effect-app/Context"
-import * as Effect from "effect-app/Effect"
-import * as Option from "effect-app/Option"
-import * as S from "effect-app/Schema"
-import * as Cause from "effect/Cause"
-import * as Ref from "effect/Ref"
-import type * as Tracer from "effect/Tracer"
-import { isHttpClientError } from "effect/unstable/http/HttpClientError"
-import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"
-import * as Atom from "effect/unstable/reactivity/Atom"
-import { computed, type MaybeRefOrGetter, shallowRef, toValue, watch, type WatchSource } from "vue"
-import { replaceEqualDeep } from "../atomQuery.ts"
-import { clearQueryReadDependencies, setQueryReadDependencies } from "../dependencyMetadata.ts"
-import { reportRuntimeError } from "../lib.ts"
-import type { QueryInvalidator } from "../mutate.ts"
-import type { CustomDefinedInitialQueryOptions, CustomDefinedPlaceholderQueryOptions, CustomUndefinedInitialQueryOptions, CustomUseQueryOptions, MakeQuery2, QueryCacheUpdater, QueryHandle, QueryObserverResult, RefetchOptions } from "../query.ts"
-import { makeRunPromise } from "../runtime.ts"
-
-const swrToQuery = (r: {
- readonly error: CauseException | null | undefined
- readonly data: A | undefined
- readonly isValidating: boolean
-}): AsyncResult.AsyncResult => {
- if (r.error !== undefined && r.error !== null) {
- return AsyncResult.failureWithPrevious(
- r.error.originalCause,
- {
- previous: r.data === undefined ? Option.none() : Option.some(AsyncResult.success(r.data)),
- waiting: r.isValidating
- }
- )
- }
- if (r.data !== undefined) {
- return AsyncResult.success(r.data, { waiting: r.isValidating })
- }
-
- return AsyncResult.initial(r.isValidating)
-}
-
-const recoverCauseException = (error: unknown): Effect.Effect =>
- error instanceof CauseException
- ? Effect.failCause(error.originalCause)
- : Effect.die(error)
-
-const isRetryable = (error: unknown) => {
- if (error instanceof CauseException) {
- return isHttpClientError(error.cause) || S.is(ServiceUnavailableError)(error.cause)
- }
- return false
-}
-
-const isInputOption = (value: I | Option.Option | undefined): value is Option.Option => Option.isOption(value)
-
-const resolveInput = (
- arg: I | WatchSource | undefined | WatchSource>,
- mode: "optional" | undefined
-): I | undefined => {
- if (mode === "optional") {
- const option = toValue(arg)
- return isInputOption(option) && Option.isSome(option) ? option.value : undefined
- }
- const value = toValue(arg)
- return isInputOption(value) ? undefined : value
-}
-
-const resolveEnabled = (
- arg: I | WatchSource | undefined | WatchSource>,
- options: {
- readonly mode?: "optional" | undefined
- readonly enabled?: MaybeRefOrGetter | undefined
- } | undefined
-) => {
- if (options?.mode === "optional") {
- return computed(() => {
- const option = toValue(arg)
- return Option.isSome(option)
- })
- }
- return computed(() => {
- const enabled = options?.enabled
- if (enabled === undefined) return true
- return !!toValue(enabled)
- })
-}
-
-type LegacyTanstackOptions =
- & (
- | CustomUndefinedInitialQueryOptions
- | CustomDefinedInitialQueryOptions
- | CustomDefinedPlaceholderQueryOptions
- | CustomUseQueryOptions
- )
- & { readonly mode?: "optional" | undefined }
-
-export const makeTanstackQueryClient = () => new QueryClient()
-
-export const makeTanstackQueryInvalidator = (queryClient: QueryClient): QueryInvalidator => ({
- invalidateAndAwait: (keys) =>
- Effect.gen(function*() {
- const span = yield* Effect.currentParentSpan.pipe(Effect.orElseSucceed(() => undefined))
- yield* Effect.forEach(
- keys,
- (queryKey) => {
- const options = { updateMeta: { span } }
- return Effect.promise(() => queryClient.invalidateQueries({ queryKey }, options))
- },
- { discard: true, concurrency: "inherit" }
- )
- })
-})
-
-const fullQueryKey = (
- q: { readonly queryKeyProjectionHash?: string },
- queryKey: ReadonlyArray,
- input: unknown
-) => q.queryKeyProjectionHash === undefined ? [...queryKey, input] : [...queryKey, q.queryKeyProjectionHash, input]
-
-export const makeTanstackQueryCacheUpdater = (queryClient: QueryClient): QueryCacheUpdater => ({
- update: (
- _registry: ReturnType,
- query: RequestHandlerWithInput,
- input: I,
- updater: (data: NoInfer) => NoInfer
- ) => {
- const queryKey = fullQueryKey(query, makeQueryKey(query), input)
- if (queryClient.getQueryData(queryKey) === undefined) {
- console.warn(`Query ${query.id} has not been used yet; nothing to update`)
- return
- }
- queryClient.setQueryData(queryKey, (data: A | undefined) => data === undefined ? data : updater(data))
- }
-})
-
-export const makeTanstackQuery = (
- getRuntime: () => Context.Context,
- queryClient: QueryClient
-): MakeQuery2 => {
- // Drop a query's recorded read-dependencies when tanstack evicts it from the cache, so the
- // registry mirrors the live queries (mirrors the atom engine's `trackReadDependencies` finalizer).
- queryClient.getQueryCache().subscribe((event) => {
- if (event.type === "removed") clearQueryReadDependencies(event.query.queryKey)
- })
-
- const useQuery: MakeQuery2 = (
- q: RequestHandlerWithInput
- ) =>
- (
- arg: I | WatchSource | undefined | WatchSource>,
- options?: LegacyTanstackOptions, TData>
- ) => {
- const runPromise = makeRunPromise(getRuntime())
- const queryKey = makeQueryKey(q)
- const enabled = resolveEnabled(arg, options)
- const structuralSharing = options?.structuralSharing === false ? false : replaceEqualDeep
- const tanstackOptions = {
- ...(options?.staleTime !== undefined ? { staleTime: options.staleTime } : {}),
- ...(typeof options?.gcTime === "number" ? { gcTime: options.gcTime } : {}),
- ...(options?.refetchOnWindowFocus !== undefined ? { refetchOnWindowFocus: options.refetchOnWindowFocus } : {}),
- structuralSharing,
- ...(options?.refetchInterval !== undefined ? { refetchInterval: options.refetchInterval } : {}),
- ...(options?.select !== undefined ? { select: options.select } : {})
- }
- const tanstack = useTanstackQuery, TData>({
- ...tanstackOptions,
- enabled,
- throwOnError: false,
- retry: (retryCount: number, error: unknown) => isRetryable(error) && retryCount < 5,
- queryKey: computed(() => {
- const input = resolveInput(arg, options?.mode)
- return fullQueryKey(q, queryKey, input)
- }),
- queryFn: (
- { meta, signal }: {
- readonly meta?: { readonly span?: Tracer.AnySpan | undefined } | undefined
- readonly signal: AbortSignal
- }
- ) =>
- runPromise(
- Effect.gen(function*() {
- const input = resolveInput(arg, options?.mode)!
- // Record the repository/server read-dependencies seen while fetching, keyed by the
- // tanstack queryKey, so a later mutation whose writes intersect them derives this query
- // as an invalidation target (the tanstack invalidator invalidates by this same key).
- const readsRef = yield* Ref.make(DataDependencies.empty())
- const writesRef = yield* Ref.make(DataDependencies.empty())
- const recorder = DataDependencies.makeDataDependencyRecorder(readsRef, writesRef)
- const result = yield* q
- .handler(input)
- .pipe(
- Effect.provideService(DataDependencies.DataDependencyRecorder, recorder),
- Effect.tapCauseIf(Cause.hasDies, (cause) => reportRuntimeError(cause)),
- Effect.withSpan(`query ${q.id}`, {}, { captureStackTrace: false }),
- meta?.span === undefined
- ? (effect) => effect
- : Effect.withParentSpan(meta.span, { captureStackTrace: false })
- )
- setQueryReadDependencies(fullQueryKey(q, queryKey, input), yield* Ref.get(readsRef))
- return result
- }),
- { signal }
- )
- }, queryClient)
-
- const latestSuccess = shallowRef()
- const result = computed((): AsyncResult.AsyncResult =>
- swrToQuery({
- error: tanstack.error.value,
- data: tanstack.data.value === undefined ? latestSuccess.value : tanstack.data.value,
- isValidating: tanstack.isFetching.value
- })
- )
- watch(result, (value) => latestSuccess.value = Option.getOrUndefined(AsyncResult.value(value)), { immediate: true })
- const seedLatestSuccess = (data: TData) => {
- if (latestSuccess.value === undefined) {
- latestSuccess.value = data
- }
- }
-
- const registry = injectRegistry()
- const latestSuccessRef = computed(() => latestSuccess.value)
- const atom = computed>>(() => Atom.readable(() => result.value))
-
- const awaitResult = (): Effect.Effect =>
- Effect
- .tryPromise({
- try: async () => {
- const queryResult = await tanstack.suspense()
- const data = queryResult.data
- if (data === undefined) {
- throw new Error("TanStack query resolved without data")
- }
- seedLatestSuccess(data)
- return data
- },
- catch: (error) => error
- })
- .pipe(
- Effect.catch((error) => recoverCauseException(error))
- )
-
- const refetch = (): Effect.Effect =>
- Effect.gen(function*() {
- const span = yield* Effect.currentParentSpan.pipe(Effect.orElseSucceed(() => undefined))
- return yield* Effect
- .tryPromise({
- try: async () => {
- const options = { throwOnError: true, updateMeta: { span } }
- const queryResult = await tanstack.refetch(options)
- const data = queryResult.data
- if (data === undefined) {
- throw new Error("TanStack query refetched without data")
- }
- return data
- },
- catch: (error) => error
- })
- .pipe(
- Effect.catch((error) => recoverCauseException(error))
- )
- })
-
- const handle: QueryHandle = {
- awaitResult,
- refetch,
- refresh: () => {
- void tanstack.refetch()
- },
- registry,
- atom
- }
-
- const fetch = (_options?: RefetchOptions): Effect.Effect>> =>
- refetch().pipe(Effect.exit, Effect.map(AsyncResult.fromExit))
-
- return [
- result,
- latestSuccessRef,
- fetch,
- handle
- ] as const
- }
-
- return useQuery
-}
diff --git a/packages/vue/src/makeClient.ts b/packages/vue/src/makeClient.ts
index 3a71d0220b..cce010a9b9 100644
--- a/packages/vue/src/makeClient.ts
+++ b/packages/vue/src/makeClient.ts
@@ -19,11 +19,10 @@ import * as Reactivity from "effect/unstable/reactivity/Reactivity"
import { computed, type ComputedRef, effectScope, onBeforeUnmount, onScopeDispose, ref, type WatchSource } from "vue"
import { type AtomClientRuntime, invalidateAndAwait, makeAtomClientRuntime } from "./atomQuery.ts"
import { type Commander, CommanderStatic, type Progress } from "./commander.ts"
-import { makeTanstackQuery, makeTanstackQueryCacheUpdater, makeTanstackQueryClient, makeTanstackQueryInvalidator } from "./internal/tanstackQuery.ts"
import { type I18n } from "./intl.ts"
import { type CommanderResolved, makeUseCommand } from "./makeUseCommand.ts"
-import { atomQueryInvalidator, combineQueryInvalidators, type InvalidationEntry, makeMutation, makeStreamMutation2, type MutationOptionsBase, type QueryInvalidator, useMakeMutation } from "./mutate.ts"
-import { atomQueryCacheUpdater, type AtomQueryNewOptions, combineQueryCacheUpdaters, type CustomUndefinedInitialQueryOptions, makeQuery, makeQueryAtom, makeQueryFamily, makeQueryNew, makeStreamQuery, makeStreamQueryAtom, makeStreamQueryFamily, makeStreamQueryNew, optionalAtomQueryCacheUpdater, type QueryObserverResult, type RefetchOptions, setQueryCacheUpdater, type StreamQueryAtomFamily, type SuspenseQueryView, type UseQueryReturnType } from "./query.ts"
+import { atomQueryInvalidator, type InvalidationEntry, makeMutation, makeStreamMutation2, type MutationOptionsBase, type QueryInvalidator, useMakeMutation } from "./mutate.ts"
+import { atomQueryCacheUpdater, type AtomQueryNewOptions, type CustomUndefinedInitialQueryOptions, makeQuery, makeQueryAtom, makeQueryFamily, makeQueryNew, makeStreamQuery, makeStreamQueryAtom, makeStreamQueryFamily, makeStreamQueryNew, type QueryObserverResult, type RefetchOptions, setQueryCacheUpdater, type StreamQueryAtomFamily, type SuspenseQueryView, type UseQueryReturnType } from "./query.ts"
import { makeRunPromise } from "./runtime.ts"
import { type Toast } from "./toast.ts"
@@ -419,24 +418,15 @@ export const useMutationInt = (queryInvalidator: QueryInvalidator): typeof _useM
export type ClientFrom = RequestHandlers>
-export interface MakeClientOptions {
- /**
- * Selects the engine behind legacy `.query()` / `.suspense()` helpers.
- * Atom-native `.atom()` / `.family()` / `.queryNew()` / `.suspenseNew()` always use Atom.
- */
- readonly legacyQueryEngine?: "atom" | "tanstack"
-}
-
export class QueryImpl {
readonly getRuntime: () => Context.Context
constructor(
getRuntime: () => Context.Context,
- getAtomRt: () => AtomClientRuntime,
- legacyUseQuery?: ReturnType>
+ getAtomRt: () => AtomClientRuntime
) {
this.getRuntime = getRuntime
- this.useQuery = legacyUseQuery ?? makeQuery(this.getRuntime, getAtomRt)
+ this.useQuery = makeQuery(this.getRuntime, getAtomRt)
this.useQueryNew = makeQueryNew(this.getRuntime, getAtomRt)
this.useQueryAtom = makeQueryAtom(this.getRuntime, getAtomRt)
this.useQueryFamily = makeQueryFamily(this.getRuntime, getAtomRt)
@@ -702,8 +692,7 @@ export const makeClient = (
// global, but only accessible after startup has completed
getBaseMrt: () => ManagedRuntime.ManagedRuntime,
clientFor_: ReturnType,
- rtHooks: Layer.Layer,
- options?: MakeClientOptions
+ rtHooks: Layer.Layer
) => {
type RT = RT_ | Mix
const getBaseRt = () => managedRuntimeRt(getBaseMrt())
@@ -717,21 +706,9 @@ export const makeClient = (
const getAtomRt =
() => (atomRt ??= makeAtomClientRuntime(() => Layer.succeedContext(getBaseRt()), getBaseMrt().memoMap))
- const legacyQueryEngine = options?.legacyQueryEngine ?? "tanstack"
- let tanstackQueryClient: ReturnType | undefined
- const getTanstackQueryClient = () => tanstackQueryClient ??= makeTanstackQueryClient()
const atomInvalidator = makeResolvedAtomQueryInvalidator(getBaseRt)
- const queryInvalidator = legacyQueryEngine === "tanstack"
- ? combineQueryInvalidators(atomInvalidator, makeTanstackQueryInvalidator(getTanstackQueryClient()))
- : atomInvalidator
- setQueryCacheUpdater(
- legacyQueryEngine === "tanstack"
- ? combineQueryCacheUpdaters(
- makeTanstackQueryCacheUpdater(getTanstackQueryClient()),
- optionalAtomQueryCacheUpdater
- )
- : atomQueryCacheUpdater
- )
+ const queryInvalidator = atomInvalidator
+ setQueryCacheUpdater(atomQueryCacheUpdater)
let m: ReturnType
const useMutation = () => m ??= useMutationInt(queryInvalidator)
@@ -739,10 +716,7 @@ export const makeClient = (
let sm2: ReturnType
const useStreamMutation2 = () => sm2 ??= makeStreamMutation2(queryInvalidator)
- const legacyUseQuery = legacyQueryEngine === "tanstack"
- ? makeTanstackQuery(getBaseRt, getTanstackQueryClient())
- : undefined
- const query = new QueryImpl(getBaseRt, getAtomRt, legacyUseQuery)
+ const query = new QueryImpl(getBaseRt, getAtomRt)
const useQuery = query.useQuery
const useQueryNew = query.useQueryNew
const useQueryAtom = query.useQueryAtom
@@ -1245,8 +1219,7 @@ export const makeClient = (
return {
Command,
useCommand,
- clientFor,
- tanstackQueryClient: getTanstackQueryClient()
+ clientFor
}
}
diff --git a/packages/vue/test/dependencyInvalidation.test.ts b/packages/vue/test/dependencyInvalidation.test.ts
index 9330ba3045..47d812e549 100644
--- a/packages/vue/test/dependencyInvalidation.test.ts
+++ b/packages/vue/test/dependencyInvalidation.test.ts
@@ -1,7 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { defaultRegistry } from "@effect/atom-vue"
import { expect, it } from "@effect/vitest"
-import { QueryClient, VueQueryPlugin } from "@tanstack/vue-query"
import { DataDependencies, type InvalidationKey, InvalidationKeysFromServer, makeQueryKey } from "effect-app/client"
import * as Context from "effect-app/Context"
import * as Effect from "effect-app/Effect"
@@ -10,10 +9,8 @@ import * as Layer from "effect/Layer"
import * as ManagedRuntime from "effect/ManagedRuntime"
import { TestClock } from "effect/testing"
import * as Reactivity from "effect/unstable/reactivity/Reactivity"
-import { createApp, effectScope, ref } from "vue"
import { awaitAtomResult, buildQueryFamily, invalidateAndAwait, makeAtomClientRuntime } from "../src/atomQuery.js"
import { clearQueryReadDependencies, getDerivedInvalidationKeys, setQueryReadDependencies } from "../src/dependencyMetadata.js"
-import { makeTanstackQuery, makeTanstackQueryInvalidator } from "../src/internal/tanstackQuery.js"
import { invalidateQueries, type MutationOptionsBase } from "../src/mutate.js"
const repo = DataDependencies.repo("FrontendRepo")
@@ -126,68 +123,6 @@ it("atom engine: a query records its read deps so a command's writes derive it",
}
})
-// --- legacy tanstack engine: recording + cache-removal cleanup -----------------------------------
-
-const makeTanstackContext = (queryClient: QueryClient) => {
- const app = createApp({ render: () => null })
- app.use(VueQueryPlugin, { queryClient })
- const scope = effectScope(true)
- const run = (fn: () => T): T => {
- let out!: T
- app.runWithContext(() => {
- scope.run(() => {
- out = fn()
- })
- })
- return out
- }
- return { run, dispose: () => scope.stop() }
-}
-
-it("tanstack engine: a query records reads, and a command's writes refetch it", async () => {
- const tsRepo = DataDependencies.repo("TanstackRepo")
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: Infinity, staleTime: 0 } }
- })
- const useQuery = makeTanstackQuery(() => Context.empty(), queryClient)
-
- let runs = 0
- const self = { id: "TanstackInv.List", handler: () => DataDependencies.read(tsRepo).pipe(Effect.as(++runs)) }
- const ctx = makeTanstackContext(queryClient)
- const [, , , handle] = ctx.run(() => useQuery(self as any)(ref(undefined) as any, {} as any)) as any
-
- try {
- await Effect.runPromise(handle.refetch())
- expect(runs).toBe(1)
-
- const fullKey = [...makeQueryKey(self), undefined]
- const derived = getDerivedInvalidationKeys(new Set([tsRepo]))
- expect(derived).toContainEqual(fullKey)
-
- // Invalidating those derived keys via the tanstack invalidator refetches the active query.
- await Effect.runPromise(makeTanstackQueryInvalidator(queryClient).invalidateAndAwait(derived))
- expect(runs).toBe(2)
- } finally {
- ctx.dispose()
- }
-})
-
-it("tanstack engine: evicting a query from the cache clears its recorded reads", () => {
- const tsRepo = DataDependencies.repo("TanstackEvictRepo")
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- // Installs the cache-removal subscription that clears the registry on eviction.
- makeTanstackQuery(() => Context.empty(), queryClient)
-
- const key = ["$TanstackEvict", "List", undefined]
- const cache = queryClient.getQueryCache()
- cache.build(queryClient, { queryKey: key, queryFn: () => Promise.resolve(1) })
- setQueryReadDependencies(key, new Set([tsRepo]))
- expect(getDerivedInvalidationKeys(new Set([tsRepo]))).toContainEqual(key)
-
- cache.clear()
- expect(getDerivedInvalidationKeys(new Set([tsRepo]))).not.toContainEqual(key)
-})
-
// --- atom engine: GC finalizer clears recorded reads --------------------------------------------
it("atom engine: disposing the query atom clears its recorded reads", async () => {
@@ -212,9 +147,9 @@ it("atom engine: disposing the query atom clears its recorded reads", async () =
expect(getDerivedInvalidationKeys(new Set([atomRepo]))).not.toContainEqual(fullKey)
})
-// --- full engine e2e matrix: every invalidation source, on each engine ---------------------------
+// --- full engine e2e matrix: every invalidation source -----------------------------------------
//
-// For each engine, a live query records a repo read; then commands sharing the query's namespace are
+// A live query records a repo read; then commands sharing the query's namespace are
// run through the real mutate path, covering every invalidation source. The command namespace matches
// the query's, so the "no refetch" cases also confirm there is NO implicit namespace invalidation.
@@ -230,27 +165,6 @@ interface EngineHarness {
readonly dispose: () => void
}
-const makeTanstackHarness = (queryRepo: DataDependencies.DataDependency): EngineHarness => {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: Infinity, staleTime: 0 } }
- })
- const useQuery = makeTanstackQuery(() => Context.empty(), queryClient)
- const invalidator = makeTanstackQueryInvalidator(queryClient)
- let runs = 0
- const self = { id: "MatrixTs.List", handler: () => DataDependencies.read(queryRepo).pipe(Effect.as(++runs)) }
- const ctx = makeTanstackContext(queryClient)
- const [, , , handle] = ctx.run(() => useQuery(self as any)(ref(undefined) as any, {} as any)) as any
- return {
- queryFullKey: [...makeQueryKey(self), undefined],
- serverInvalidationKey: makeQueryKey(self),
- fetchInitial: () => Effect.runPromise(handle.refetch()),
- runs: () => runs,
- runCommand: (options, command) =>
- Effect.runPromise(invalidateQueries({ id: "MatrixTs.Save" }, options, invalidator)(command, { id: "x" })),
- dispose: () => ctx.dispose()
- }
-}
-
const makeAtomHarness = (queryRepo: DataDependencies.DataDependency): EngineHarness => {
const mrt = ManagedRuntime.make(Reactivity.layer)
const baseContext = mrt.runSync(Effect.context())
@@ -348,5 +262,4 @@ const runInvalidationMatrix = (engine: string, makeHarness: (repo: DataDependenc
}
})
-runInvalidationMatrix("tanstack", makeTanstackHarness)
runInvalidationMatrix("atom", makeAtomHarness)
diff --git a/packages/vue/test/query-span.test.ts b/packages/vue/test/query-span.test.ts
index 7d7d768b53..62faa64d91 100644
--- a/packages/vue/test/query-span.test.ts
+++ b/packages/vue/test/query-span.test.ts
@@ -1,15 +1,12 @@
import { defaultRegistry, registryKey } from "@effect/atom-vue"
-import { QueryClient, VueQueryPlugin } from "@tanstack/vue-query"
import type { RequestHandlerWithInput } from "effect-app/client/clientFor"
-import * as Context from "effect-app/Context"
import * as Effect from "effect-app/Effect"
-import * as Layer from "effect-app/Layer"
import * as Option from "effect-app/Option"
import type * as Cause from "effect/Cause"
+import * as Layer from "effect/Layer"
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"
-import { createApp, effectScope, nextTick } from "vue"
+import { createApp, nextTick } from "vue"
import { buildQueryFamily, makeAtomClientRuntime } from "../src/atomQuery.js"
-import { makeTanstackQuery } from "../src/internal/tanstackQuery.js"
import { useAtomQuery } from "../src/query.js"
const fakeHandler = (
@@ -30,40 +27,6 @@ const querySpanParentName = Effect.currentSpan.pipe(
)
)
-function makeTanstackContext(queryClient: QueryClient) {
- const app = createApp({ render: () => null })
- app.use(VueQueryPlugin, { queryClient })
- const scope = effectScope(true)
- const run = (fn: () => T): T => {
- let out!: T
- app.runWithContext(() => {
- scope.run(() => {
- out = fn()
- })
- })
- return out
- }
- return { run, dispose: () => scope.stop() }
-}
-
-it("passes the current parent span through legacy TanStack refetch", async () => {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: Infinity, staleTime: 0 } }
- })
- const query = makeTanstackQuery(() => Context.empty(), queryClient)(
- fakeHandler("Test/TanStackSpan", () => querySpanParentName)
- )
- const ctx = makeTanstackContext(queryClient)
-
- const [, , , handle] = ctx.run(() => query(undefined, {}))
- await Effect.runPromise(handle.awaitResult())
-
- const parentName = await Effect.runPromise(handle.refetch().pipe(Effect.withSpan("trigger")))
-
- expect(parentName).toBe("trigger")
- ctx.dispose()
-})
-
it("passes the current parent span through atom query refetch", async () => {
defaultRegistry.reset()
const rt = makeAtomClientRuntime(() => Layer.empty, Layer.makeMemoMapUnsafe())
diff --git a/packages/vue/test/suspense-regression.test.ts b/packages/vue/test/suspense-regression.test.ts
index bdab02884b..bb310db211 100644
--- a/packages/vue/test/suspense-regression.test.ts
+++ b/packages/vue/test/suspense-regression.test.ts
@@ -1,88 +1,16 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
-import { QueryClient, VueQueryPlugin } from "@tanstack/vue-query"
-import * as Context from "effect-app/Context"
+import { defaultRegistry, registryKey } from "@effect/atom-vue"
import * as Effect from "effect-app/Effect"
import * as Option from "effect-app/Option"
-import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"
-import { createApp, effectScope, nextTick, ref } from "vue"
-import { makeTanstackQuery } from "../src/internal/tanstackQuery.js"
-import { QueryImpl } from "../src/makeClient.js"
+import * as Layer from "effect/Layer"
+import { createApp, nextTick } from "vue"
+import { buildQueryFamily, makeAtomClientRuntime, withQueryOptions } from "../src/atomQuery.js"
+import { useAtomQuery } from "../src/query.js"
const fakeHandler = (id: string, run: (input: any) => Effect.Effect) => ({ id, handler: run }) as any
-function makeContext(queryClient: QueryClient) {
- const app = createApp({ render: () => null })
- app.use(VueQueryPlugin, { queryClient })
- const scope = effectScope(true)
- const run = (fn: () => T): T => {
- let out!: T
- app.runWithContext(() => {
- scope.run(() => {
- out = fn()
- })
- })
- return out
- }
- return { run, dispose: () => scope.stop() }
-}
-
-it("makeClient .suspense(): observer re-pointed mid-flight -> resolves (seeded) instead of dying", async () => {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: Infinity, staleTime: 0 } }
- })
- const getRuntime = () => Context.empty()
- const qi = new QueryImpl(
- getRuntime,
- (() => {
- throw new Error("atom runtime is unused by this legacy TanStack regression")
- }) as any,
- makeTanstackQuery(getRuntime, queryClient)
- )
-
- // key "a" resolves via this deferred; any other key hangs forever.
- let resolveA!: (v: string) => void
- const aData = new Promise((res) => {
- resolveA = res
- })
- const handler = fakeHandler(
- "Test/KeyRace",
- (input: any) => Effect.promise(() => (input.id === "a" ? aData : new Promise(() => {})))
- )
-
- const ctx = makeContext(queryClient)
-
- // Keep-alive observer pins key "a" so flipping the suspense arg below does NOT cancel "a".
- ctx.run(() => qi.useQuery(handler)(ref({ id: "a" }) as any, {} as any))
- await nextTick()
-
- // Suspense on key "a" (shares the in-flight "a" query -> no extra handler call).
- const suspenseId = ref<{ id: string }>({ id: "a" })
- const suspense = qi.useSuspenseQuery(handler)
- const promise = ctx.run(() => suspense(suspenseId as any, {} as any))
-
- // Re-point the suspense observer to "b" (pending). "a" still has the keep-alive observer.
- suspenseId.value = { id: "b" }
- await nextTick()
- await nextTick()
-
- // Resolve "a": suspense() resolves with DATA_A while resultRef is parked on the pending "b".
- resolveA("DATA_A")
-
- // BEFORE fix: rejects (die). AFTER fix: resolves, seeded from the suspense value.
- const [resultRef, latestRef] = (await promise) as any
-
- expect(AsyncResult.isSuccess(resultRef.value)).toBe(true)
- expect(Option.getOrUndefined(AsyncResult.value(resultRef.value))).toBe("DATA_A")
- expect(latestRef.value).toBe("DATA_A")
-
- ctx.dispose()
-})
-
-it("makeTanstackQuery structurally shares Effect-Equal leaves by default", async () => {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: Infinity, staleTime: 0 } }
- })
- const getRuntime = () => Context.empty()
+it("atom engine structurally shares Effect-Equal leaves by default", async () => {
+ defaultRegistry.reset()
let calls = 0
const handler = fakeHandler(
"Test/StructuralSharing",
@@ -98,18 +26,32 @@ it("makeTanstackQuery structurally shares Effect-Equal leaves by default", async
}
})
)
- const query = makeTanstackQuery(getRuntime, queryClient)(handler)
- const ctx = makeContext(queryClient)
-
- const [, , , handle] = ctx.run(() => query(undefined, {}))
- const first = await Effect.runPromise(handle.awaitResult())
- const second = await Effect.runPromise(handle.refetch())
-
- expect(second.revision).toBe(2)
- expect(second).not.toBe(first)
- expect(second.stable).toBe(first.stable)
- expect(second.stable.date).toBe(first.stable.date)
- expect(second.stable.option).toBe(first.stable.option)
-
- ctx.dispose()
+ const rt = makeAtomClientRuntime(() => Layer.empty, Layer.makeMemoMapUnsafe())
+ const family = buildQueryFamily(rt, handler)
+ const atom = withQueryOptions(family(undefined))
+ let view!: ReturnType>
+ const host = document.createElement("div")
+ const app = createApp({
+ setup() {
+ view = useAtomQuery(() => atom)
+ return () => null
+ }
+ })
+ app.provide(registryKey, defaultRegistry)
+ app.mount(host)
+
+ try {
+ const first = await Effect.runPromise(view.awaitResult())
+ const second = await Effect.runPromise(view.refetch())
+
+ expect(second.revision).toBe(2)
+ expect(second).not.toBe(first)
+ expect(second.stable).toBe(first.stable)
+ expect(second.stable.date).toBe(first.stable.date)
+ expect(second.stable.option).toBe(first.stable.option)
+ } finally {
+ app.unmount()
+ await nextTick()
+ defaultRegistry.reset()
+ }
})
diff --git a/patches/@tanstack__query-core.patch b/patches/@tanstack__query-core.patch
deleted file mode 100644
index fbc9a42a35..0000000000
--- a/patches/@tanstack__query-core.patch
+++ /dev/null
@@ -1,203 +0,0 @@
-diff --git a/build/legacy/_tsup-dts-rollup.d.cts b/build/legacy/_tsup-dts-rollup.d.cts
-index 1de0866860b39e4bea47f358243bf4dc89024250..99e7c83171704a769e364d238e2eeaa236e1f07b 100644
---- a/build/legacy/_tsup-dts-rollup.d.cts
-+++ b/build/legacy/_tsup-dts-rollup.d.cts
-@@ -295,6 +295,7 @@ export declare interface FetchOptions {
- cancelRefetch?: boolean;
- meta?: FetchMeta;
- initialPromise?: Promise;
-+ updateMeta?: Record;
- }
-
- declare interface FetchPreviousPageOptions extends ResultOptions {
-@@ -1905,6 +1906,7 @@ declare interface RefetchOptions extends ResultOptions {
- * Defaults to `true`.
- */
- cancelRefetch?: boolean;
-+ updateMeta?: Record;
- }
- export { RefetchOptions }
- export { RefetchOptions as RefetchOptions_alias_1 }
-diff --git a/build/legacy/_tsup-dts-rollup.d.ts b/build/legacy/_tsup-dts-rollup.d.ts
-index 1de0866860b39e4bea47f358243bf4dc89024250..99e7c83171704a769e364d238e2eeaa236e1f07b 100644
---- a/build/legacy/_tsup-dts-rollup.d.ts
-+++ b/build/legacy/_tsup-dts-rollup.d.ts
-@@ -295,6 +295,7 @@ export declare interface FetchOptions {
- cancelRefetch?: boolean;
- meta?: FetchMeta;
- initialPromise?: Promise;
-+ updateMeta?: Record;
- }
-
- declare interface FetchPreviousPageOptions extends ResultOptions {
-@@ -1905,6 +1906,7 @@ declare interface RefetchOptions extends ResultOptions {
- * Defaults to `true`.
- */
- cancelRefetch?: boolean;
-+ updateMeta?: Record;
- }
- export { RefetchOptions }
- export { RefetchOptions as RefetchOptions_alias_1 }
-diff --git a/build/legacy/query.cjs b/build/legacy/query.cjs
-index 06ba59fc77879be6c4ac86f5f3ea7984eee234ec..52b588f7d4319864a0c122b1fbf04dd97b69869e 100644
---- a/build/legacy/query.cjs
-+++ b/build/legacy/query.cjs
-@@ -245,7 +245,7 @@ var Query = class extends import_removable.Removable {
- const queryFnContext2 = {
- client: __privateGet(this, _client),
- queryKey: this.queryKey,
-- meta: this.meta
-+ meta: (fetchOptions == null ? void 0 : fetchOptions.updateMeta) ? { ...this.meta, ...fetchOptions.updateMeta } : this.meta
- };
- addSignalProperty(queryFnContext2);
- return queryFnContext2;
-diff --git a/build/legacy/query.cjs.map b/build/legacy/query.cjs.map
-index a96f08c5dd8459039ff319bb8f9c2c8755b576e6..3986e4db23f8648bd108d4feab2c6c4345a2c864 100644
---- a/build/legacy/query.cjs.map
-+++ b/build/legacy/query.cjs.map
-@@ -1 +1 @@
--{"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n resolveStaleTime,\n skipToken,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { CancelledError, canFetch, createRetryer } from './retryer'\nimport { Removable } from './removable'\nimport type { QueryCache } from './queryCache'\nimport type { QueryClient } from './queryClient'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n StaleTime,\n} from './types'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n client: QueryClient\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions\n defaultOptions?: QueryOptions\n state?: QueryState\n}\n\nexport interface QueryState {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions\n client: QueryClient\n queryKey: TQueryKey\n state: QueryState\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise\n}\n\ninterface FailedAction {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction {\n type: 'setState'\n state: Partial>\n setStateOptions?: SetStateOptions\n}\n\nexport type Action =\n | ContinueAction\n | ErrorAction\n | FailedAction\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction\n | SuccessAction\n\nexport interface SetStateOptions {\n meta?: any\n}\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions\n state: QueryState\n\n #initialState: QueryState\n #revertState?: QueryState\n #cache: QueryCache\n #client: QueryClient\n #retryer?: Retryer\n observers: Array>\n #defaultOptions?: QueryOptions\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#client = config.client\n this.#cache = this.#client.getQueryCache()\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get promise(): Promise | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n this.updateGcTime(this.options.gcTime)\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (this.state && this.state.data === undefined) {\n const defaultState = getDefaultState(this.options)\n if (defaultState.data !== undefined) {\n this.setState(\n successState(defaultState.data, defaultState.dataUpdatedAt),\n )\n this.#initialState = defaultState\n }\n }\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(\n state: Partial>,\n setStateOptions?: SetStateOptions,\n ): void {\n this.#dispatch({ type: 'setState', state, setStateOptions })\n }\n\n cancel(options?: CancelOptions): Promise {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n get resetState(): QueryState {\n return this.#initialState\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.resetState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n if (this.getObserversCount() > 0) {\n return !this.isActive()\n }\n // if a query has no observers, it should still be considered disabled if it never attempted a fetch\n return this.options.queryFn === skipToken || !this.isFetched()\n }\n\n isFetched() {\n return this.state.dataUpdateCount + this.state.errorUpdateCount > 0\n }\n\n isStatic(): boolean {\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) =>\n resolveStaleTime(observer.options.staleTime, this) === 'static',\n )\n }\n\n return false\n }\n\n isStale(): boolean {\n // check observers first, their `isStale` has the source of truth\n // calculated with `isStaleByTime` and it takes `enabled` into account\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined || this.state.isInvalidated\n }\n\n isStaleByTime(staleTime: StaleTime = 0): boolean {\n // no data is always stale\n if (this.state.data === undefined) {\n return true\n }\n // static is never stale\n if (staleTime === 'static') {\n return false\n }\n // if the query is invalidated, it is stale\n if (this.state.isInvalidated) {\n return true\n }\n\n return !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver): void {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n #isInitialPausedFetch(): boolean {\n return (\n this.state.fetchStatus === 'paused' && this.state.status === 'pending'\n )\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n async fetch(\n options?: QueryOptions,\n fetchOptions?: FetchOptions,\n ): Promise {\n if (\n this.state.fetchStatus !== 'idle' &&\n // If the promise in the retryer is already rejected, we have to definitely\n // re-start the fetch; there is a chance that the query is still in a\n // pending state when that happens\n this.#retryer?.status() !== 'rejected'\n ) {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const createQueryFnContext = (): QueryFunctionContext => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext,\n 'signal'\n > = {\n client: this.#client,\n queryKey: this.queryKey,\n meta: this.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext\n }\n\n const queryFnContext = createQueryFnContext()\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn,\n queryFnContext,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext)\n }\n\n // Trigger behavior hook\n const createFetchContext = (): FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n > => {\n const context: OmitKeyof<\n FetchContext,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n client: this.#client,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n return context as FetchContext\n }\n\n const context = createFetchContext()\n\n this.options.behavior?.onFetch(context, this as unknown as Query)\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n // Try to fetch the data\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise\n | undefined,\n fn: context.fetchFn as () => Promise,\n onCancel: (error) => {\n if (error instanceof CancelledError && error.revert) {\n this.setState({\n ...this.#revertState,\n fetchStatus: 'idle' as const,\n })\n }\n abortController.abort()\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n })\n\n try {\n const data = await this.#retryer.start()\n // this is more of a runtime guard\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n throw new Error(`${this.queryHash} data is undefined`)\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query,\n )\n return data\n } catch (error) {\n if (error instanceof CancelledError) {\n if (error.silent) {\n // silent cancellation implies a new fetch is going to be started,\n // so we piggyback onto that promise\n return this.#retryer.promise\n } else if (error.revert) {\n // transform error into reverted state data\n // if the initial fetch was cancelled, we have no data, so we have\n // to get reject with a CancelledError\n if (this.state.data === undefined) {\n throw error\n }\n return this.state.data\n }\n }\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query,\n )\n\n throw error // rethrow the error for further handling\n } finally {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n }\n\n #dispatch(action: Action): void {\n const reducer = (\n state: QueryState,\n ): QueryState => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n const newState = {\n ...state,\n ...successState(action.data, action.dataUpdatedAt),\n dataUpdateCount: state.dataUpdateCount + 1,\n ...(!action.manual && {\n fetchStatus: 'idle' as const,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n // If fetching ends successfully, we don't need revertState as a fallback anymore.\n // For manual updates, capture the state to revert to it in case of a cancellation.\n this.#revertState = action.manual ? newState : undefined\n\n return newState\n case 'error':\n const error = action.error\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n // flag existing data as invalidated if we get a background error\n // note that \"no data\" always means stale so we can set unconditionally here\n isInvalidated: true,\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction successState(data: TData | undefined, dataUpdatedAt?: number) {\n return {\n data,\n dataUpdatedAt: dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success' as const,\n }\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions,\n): QueryState {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? options.initialDataUpdatedAt()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAQO;AACP,2BAA8B;AAC9B,qBAAwD;AACxD,uBAA0B;AAX1B;AA8JO,IAAM,QAAN,cAKG,2BAAU;AAAA,EAelB,YAAY,QAA6D;AACvE,UAAM;AArBH;AAWL;AACA;AACA;AACA;AACA;AAEA;AACA;AAKE,uBAAK,sBAAuB;AAC5B,uBAAK,iBAAkB,OAAO;AAC9B,SAAK,WAAW,OAAO,OAAO;AAC9B,SAAK,YAAY,CAAC;AAClB,uBAAK,SAAU,OAAO;AACtB,uBAAK,QAAS,mBAAK,SAAQ,cAAc;AACzC,SAAK,WAAW,OAAO;AACvB,SAAK,YAAY,OAAO;AACxB,uBAAK,eAAgB,gBAAgB,KAAK,OAAO;AACjD,SAAK,QAAQ,OAAO,SAAS,mBAA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KAAK,KAAK;AAE/B,qCAAc,MAAM,MAAM;AACxB,SAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,eAAS,cAAc;AAAA,IACzB,CAAC;AAED,uBAAK,QAAO,OAAO,EAAE,OAAO,MAAM,MAAM,WAAW,OAAO,CAAC;AAAA,EAC7D,CAAC;AACH;AAGK,SAAS,WAMd,MACA,SACA;AACA,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,iBAAa,yBAAS,QAAQ,WAAW,IAAI,aAAa;AAAA,IAC1D,GAAI,SAAS,UACV;AAAA,MACC,OAAO;AAAA,MACP,QAAQ;AAAA,IACV;AAAA,EACJ;AACF;AAEA,SAAS,aAAoB,MAAyB,eAAwB;AAC5E,SAAO;AAAA,IACL;AAAA,IACA,eAAe,iBAAiB,KAAK,IAAI;AAAA,IACzC,OAAO;AAAA,IACP,eAAe;AAAA,IACf,QAAQ;AAAA,EACV;AACF;AAEA,SAAS,gBAMP,SAC2B;AAC3B,QAAM,OACJ,OAAO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;AAEd,QAAM,UAAU,SAAS;AAEzB,QAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACtC,QAAQ,qBAAqB,IAC7B,QAAQ,uBACV;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA,IACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;AAAA,IAChE,OAAO;AAAA,IACP,kBAAkB;AAAA,IAClB,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,WAAW;AAAA,IACX,eAAe;AAAA,IACf,QAAQ,UAAU,YAAY;AAAA,IAC9B,aAAa;AAAA,EACf;AACF;","names":["queryFnContext","context"]}
-\ No newline at end of file
-+{"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n resolveStaleTime,\n skipToken,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { CancelledError, canFetch, createRetryer } from './retryer'\nimport { Removable } from './removable'\nimport type { QueryCache } from './queryCache'\nimport type { QueryClient } from './queryClient'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n StaleTime,\n} from './types'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n client: QueryClient\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions\n defaultOptions?: QueryOptions\n state?: QueryState\n}\n\nexport interface QueryState {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions\n client: QueryClient\n queryKey: TQueryKey\n state: QueryState\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise\n updateMeta?: Record\n}\n\ninterface FailedAction {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction {\n type: 'setState'\n state: Partial>\n setStateOptions?: SetStateOptions\n}\n\nexport type Action =\n | ContinueAction\n | ErrorAction\n | FailedAction\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction\n | SuccessAction\n\nexport interface SetStateOptions {\n meta?: any\n}\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions\n state: QueryState\n\n #initialState: QueryState\n #revertState?: QueryState\n #cache: QueryCache\n #client: QueryClient\n #retryer?: Retryer\n observers: Array>\n #defaultOptions?: QueryOptions\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#client = config.client\n this.#cache = this.#client.getQueryCache()\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get promise(): Promise | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n this.updateGcTime(this.options.gcTime)\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (this.state && this.state.data === undefined) {\n const defaultState = getDefaultState(this.options)\n if (defaultState.data !== undefined) {\n this.setState(\n successState(defaultState.data, defaultState.dataUpdatedAt),\n )\n this.#initialState = defaultState\n }\n }\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(\n state: Partial>,\n setStateOptions?: SetStateOptions,\n ): void {\n this.#dispatch({ type: 'setState', state, setStateOptions })\n }\n\n cancel(options?: CancelOptions): Promise {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n get resetState(): QueryState {\n return this.#initialState\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.resetState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n if (this.getObserversCount() > 0) {\n return !this.isActive()\n }\n // if a query has no observers, it should still be considered disabled if it never attempted a fetch\n return this.options.queryFn === skipToken || !this.isFetched()\n }\n\n isFetched() {\n return this.state.dataUpdateCount + this.state.errorUpdateCount > 0\n }\n\n isStatic(): boolean {\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) =>\n resolveStaleTime(observer.options.staleTime, this) === 'static',\n )\n }\n\n return false\n }\n\n isStale(): boolean {\n // check observers first, their `isStale` has the source of truth\n // calculated with `isStaleByTime` and it takes `enabled` into account\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined || this.state.isInvalidated\n }\n\n isStaleByTime(staleTime: StaleTime = 0): boolean {\n // no data is always stale\n if (this.state.data === undefined) {\n return true\n }\n // static is never stale\n if (staleTime === 'static') {\n return false\n }\n // if the query is invalidated, it is stale\n if (this.state.isInvalidated) {\n return true\n }\n\n return !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver): void {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n #isInitialPausedFetch(): boolean {\n return (\n this.state.fetchStatus === 'paused' && this.state.status === 'pending'\n )\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n async fetch(\n options?: QueryOptions,\n fetchOptions?: FetchOptions,\n ): Promise {\n if (\n this.state.fetchStatus !== 'idle' &&\n // If the promise in the retryer is already rejected, we have to definitely\n // re-start the fetch; there is a chance that the query is still in a\n // pending state when that happens\n this.#retryer?.status() !== 'rejected'\n ) {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const createQueryFnContext = (): QueryFunctionContext => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext,\n 'signal'\n > = {\n client: this.#client,\n queryKey: this.queryKey,\n meta: fetchOptions?.updateMeta ? {...this.meta, ...fetchOptions.updateMeta } : this.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext\n }\n\n const queryFnContext = createQueryFnContext()\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn,\n queryFnContext,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext)\n }\n\n // Trigger behavior hook\n const createFetchContext = (): FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n > => {\n const context: OmitKeyof<\n FetchContext,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n client: this.#client,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n return context as FetchContext\n }\n\n const context = createFetchContext()\n\n this.options.behavior?.onFetch(context, this as unknown as Query)\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n // Try to fetch the data\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise\n | undefined,\n fn: context.fetchFn as () => Promise,\n onCancel: (error) => {\n if (error instanceof CancelledError && error.revert) {\n this.setState({\n ...this.#revertState,\n fetchStatus: 'idle' as const,\n })\n }\n abortController.abort()\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n })\n\n try {\n const data = await this.#retryer.start()\n // this is more of a runtime guard\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n throw new Error(`${this.queryHash} data is undefined`)\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query,\n )\n return data\n } catch (error) {\n if (error instanceof CancelledError) {\n if (error.silent) {\n // silent cancellation implies a new fetch is going to be started,\n // so we piggyback onto that promise\n return this.#retryer.promise\n } else if (error.revert) {\n // transform error into reverted state data\n // if the initial fetch was cancelled, we have no data, so we have\n // to get reject with a CancelledError\n if (this.state.data === undefined) {\n throw error\n }\n return this.state.data\n }\n }\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query,\n )\n\n throw error // rethrow the error for further handling\n } finally {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n }\n\n #dispatch(action: Action): void {\n const reducer = (\n state: QueryState,\n ): QueryState => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n const newState = {\n ...state,\n ...successState(action.data, action.dataUpdatedAt),\n dataUpdateCount: state.dataUpdateCount + 1,\n ...(!action.manual && {\n fetchStatus: 'idle' as const,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n // If fetching ends successfully, we don't need revertState as a fallback anymore.\n // For manual updates, capture the state to revert to it in case of a cancellation.\n this.#revertState = action.manual ? newState : undefined\n\n return newState\n case 'error':\n const error = action.error\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n // flag existing data as invalidated if we get a background error\n // note that \"no data\" always means stale so we can set unconditionally here\n isInvalidated: true,\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction successState(data: TData | undefined, dataUpdatedAt?: number) {\n return {\n data,\n dataUpdatedAt: dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success' as const,\n }\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions,\n): QueryState {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? options.initialDataUpdatedAt()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAQO;AACP,2BAA8B;AAC9B,qBAAwD;AACxD,uBAA0B;AAX1B;AA+JO,IAAM,QAAN,cAKG,2BAAU;AAAA,EAelB,YAAY,QAA6D;AACvE,UAAM;AArBH;AAWL;AACA;AACA;AACA;AACA;AAEA;AACA;AAKE,uBAAK,sBAAuB;AAC5B,uBAAK,iBAAkB,OAAO;AAC9B,SAAK,WAAW,OAAO,OAAO;AAC9B,SAAK,YAAY,CAAC;AAClB,uBAAK,SAAU,OAAO;AACtB,uBAAK,QAAS,mBAAK,SAAQ,cAAc;AACzC,SAAK,WAAW,O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;AAAA,IAC9B,aAAa;AAAA,EACf;AACF;","names":["queryFnContext","context"]}
-\ No newline at end of file
-diff --git a/build/legacy/query.js b/build/legacy/query.js
-index 8971b1935e2096f047d14a8c905aee7ccfbf561e..1583990c058d96a571f2dc0925f162e43f87c4b6 100644
---- a/build/legacy/query.js
-+++ b/build/legacy/query.js
-@@ -227,7 +227,7 @@ var Query = class extends Removable {
- const queryFnContext2 = {
- client: __privateGet(this, _client),
- queryKey: this.queryKey,
-- meta: this.meta
-+ meta: (fetchOptions == null ? void 0 : fetchOptions.updateMeta) ? { ...this.meta, ...fetchOptions.updateMeta } : this.meta
- };
- addSignalProperty(queryFnContext2);
- return queryFnContext2;
-diff --git a/build/legacy/query.js.map b/build/legacy/query.js.map
-index 824dff7ff7935704d1b54646516704a7bf6edb49..e60ee189dc3456576211eb563cb63d7c0ec0f603 100644
---- a/build/legacy/query.js.map
-+++ b/build/legacy/query.js.map
-@@ -1 +1 @@
--{"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n resolveStaleTime,\n skipToken,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { CancelledError, canFetch, createRetryer } from './retryer'\nimport { Removable } from './removable'\nimport type { QueryCache } from './queryCache'\nimport type { QueryClient } from './queryClient'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n StaleTime,\n} from './types'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n client: QueryClient\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions\n defaultOptions?: QueryOptions\n state?: QueryState\n}\n\nexport interface QueryState {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions\n client: QueryClient\n queryKey: TQueryKey\n state: QueryState\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise\n}\n\ninterface FailedAction {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction {\n type: 'setState'\n state: Partial>\n setStateOptions?: SetStateOptions\n}\n\nexport type Action =\n | ContinueAction\n | ErrorAction\n | FailedAction\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction\n | SuccessAction\n\nexport interface SetStateOptions {\n meta?: any\n}\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions\n state: QueryState\n\n #initialState: QueryState\n #revertState?: QueryState\n #cache: QueryCache\n #client: QueryClient\n #retryer?: Retryer\n observers: Array>\n #defaultOptions?: QueryOptions\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#client = config.client\n this.#cache = this.#client.getQueryCache()\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get promise(): Promise | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n this.updateGcTime(this.options.gcTime)\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (this.state && this.state.data === undefined) {\n const defaultState = getDefaultState(this.options)\n if (defaultState.data !== undefined) {\n this.setState(\n successState(defaultState.data, defaultState.dataUpdatedAt),\n )\n this.#initialState = defaultState\n }\n }\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(\n state: Partial>,\n setStateOptions?: SetStateOptions,\n ): void {\n this.#dispatch({ type: 'setState', state, setStateOptions })\n }\n\n cancel(options?: CancelOptions): Promise {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n get resetState(): QueryState {\n return this.#initialState\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.resetState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n if (this.getObserversCount() > 0) {\n return !this.isActive()\n }\n // if a query has no observers, it should still be considered disabled if it never attempted a fetch\n return this.options.queryFn === skipToken || !this.isFetched()\n }\n\n isFetched() {\n return this.state.dataUpdateCount + this.state.errorUpdateCount > 0\n }\n\n isStatic(): boolean {\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) =>\n resolveStaleTime(observer.options.staleTime, this) === 'static',\n )\n }\n\n return false\n }\n\n isStale(): boolean {\n // check observers first, their `isStale` has the source of truth\n // calculated with `isStaleByTime` and it takes `enabled` into account\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined || this.state.isInvalidated\n }\n\n isStaleByTime(staleTime: StaleTime = 0): boolean {\n // no data is always stale\n if (this.state.data === undefined) {\n return true\n }\n // static is never stale\n if (staleTime === 'static') {\n return false\n }\n // if the query is invalidated, it is stale\n if (this.state.isInvalidated) {\n return true\n }\n\n return !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver): void {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n #isInitialPausedFetch(): boolean {\n return (\n this.state.fetchStatus === 'paused' && this.state.status === 'pending'\n )\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n async fetch(\n options?: QueryOptions,\n fetchOptions?: FetchOptions,\n ): Promise {\n if (\n this.state.fetchStatus !== 'idle' &&\n // If the promise in the retryer is already rejected, we have to definitely\n // re-start the fetch; there is a chance that the query is still in a\n // pending state when that happens\n this.#retryer?.status() !== 'rejected'\n ) {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const createQueryFnContext = (): QueryFunctionContext => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext,\n 'signal'\n > = {\n client: this.#client,\n queryKey: this.queryKey,\n meta: this.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext\n }\n\n const queryFnContext = createQueryFnContext()\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn,\n queryFnContext,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext)\n }\n\n // Trigger behavior hook\n const createFetchContext = (): FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n > => {\n const context: OmitKeyof<\n FetchContext,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n client: this.#client,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n return context as FetchContext\n }\n\n const context = createFetchContext()\n\n this.options.behavior?.onFetch(context, this as unknown as Query)\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n // Try to fetch the data\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise\n | undefined,\n fn: context.fetchFn as () => Promise,\n onCancel: (error) => {\n if (error instanceof CancelledError && error.revert) {\n this.setState({\n ...this.#revertState,\n fetchStatus: 'idle' as const,\n })\n }\n abortController.abort()\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n })\n\n try {\n const data = await this.#retryer.start()\n // this is more of a runtime guard\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n throw new Error(`${this.queryHash} data is undefined`)\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query,\n )\n return data\n } catch (error) {\n if (error instanceof CancelledError) {\n if (error.silent) {\n // silent cancellation implies a new fetch is going to be started,\n // so we piggyback onto that promise\n return this.#retryer.promise\n } else if (error.revert) {\n // transform error into reverted state data\n // if the initial fetch was cancelled, we have no data, so we have\n // to get reject with a CancelledError\n if (this.state.data === undefined) {\n throw error\n }\n return this.state.data\n }\n }\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query,\n )\n\n throw error // rethrow the error for further handling\n } finally {\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n }\n\n #dispatch(action: Action): void {\n const reducer = (\n state: QueryState,\n ): QueryState => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n const newState = {\n ...state,\n ...successState(action.data, action.dataUpdatedAt),\n dataUpdateCount: state.dataUpdateCount + 1,\n ...(!action.manual && {\n fetchStatus: 'idle' as const,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n // If fetching ends successfully, we don't need revertState as a fallback anymore.\n // For manual updates, capture the state to revert to it in case of a cancellation.\n this.#revertState = action.manual ? newState : undefined\n\n return newState\n case 'error':\n const error = action.error\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n // flag existing data as invalidated if we get a background error\n // note that \"no data\" always means stale so we can set unconditionally here\n isInvalidated: true,\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction successState(data: TData | undefined, dataUpdatedAt?: number) {\n return {\n data,\n dataUpdatedAt: dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success' as const,\n }\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions,\n): QueryState {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? options.initialDataUpdatedAt()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB,UAAU,qBAAqB;AACxD,SAAS,iBAAiB;AAX1B;AA8JO,IAAM,QAAN,cAKG,UAAU;AAAA,EAelB,YAAY,QAA6D;AACvE,UAAM;AArBH;AAWL;AACA;AACA;AACA;AACA;AAEA;AACA;AAKE,uBAAK,sBAAuB;AAC5B,uBAAK,iBAAkB,OAAO;AAC9B,SAAK,WAAW,OAAO,OAAO;AAC9B,SAAK,YAAY,CAAC;AAClB,uBAAK,SAAU,OAAO;AACtB,uBAAK,QAAS,mBAAK,SAAQ,cAAc;AACzC,SAAK,WAAW,OAAO;AACvB,SAAK,YAAY,OAAO;AACxB,uBAAK,eAAgB,gBAAgB,KAAK,OAAO;AACjD,SAAK,QAAQ,OAAO,SAAS,mBAAK;AAClC,SAAK,WAAW;AAAA,EAClB;AAAA,EACA,IAAI,OAA8B;AAChC,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,UAAsC;AArM5C;AAsMI,YAAO,wBAAK,cAAL,mBAAe;AAAA,EACxB;AAAA,EAEA,WACE,SACM;AACN,SAAK,UAAU,EAAE,GAAG,mBAAK,kBAAiB,GAAG,QAAQ;AAErD,SAAK,aAAa,KAAK,QAAQ,MAAM;AAGrC,QAAI,KAAK,SAAS,KAAK,MAAM,SAAS,QAAW;AAC/C,YAAM,eAAe,gBAAgB,KAAK,OAAO;AACjD,UAAI,aAAa,SAAS,QAAW;AACnC,aAAK;AAAA,UACH,aAAa,aAAa,MA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AC5E,SAAO;AAAA,IACL;AAAA,IACA,eAAe,iBAAiB,KAAK,IAAI;AAAA,IACzC,OAAO;AAAA,IACP,eAAe;AAAA,IACf,QAAQ;AAAA,EACV;AACF;AAEA,SAAS,gBAMP,SAC2B;AAC3B,QAAM,OACJ,OAAO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;AAEd,QAAM,UAAU,SAAS;AAEzB,QAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACtC,QAAQ,qBAAqB,IAC7B,QAAQ,uBACV;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA,IACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;AAAA,IAChE,OAAO;AAAA,IACP,kBAAkB;AAAA,IAClB,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,WAAW;AAAA,IACX,eAAe;AAAA,IACf,QAAQ,UAAU,YAAY;AAAA,IAC9B,aAAa;AAAA,EACf;AACF;","names":["queryFnContext","context"]}
-\ No newline at end of file
-+{"version":3,"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n resolveStaleTime,\n skipToken,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { CancelledError, canFetch, createRetryer } from './retryer'\nimport { Removable } from './removable'\nimport type { QueryCache } from './queryCache'\nimport type { QueryClient } from './queryClient'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n StaleTime,\n} from './types'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n client: QueryClient\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions\n defaultOptions?: QueryOptions\n state?: QueryState\n}\n\nexport interface QueryState {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions\n client: QueryClient\n queryKey: TQueryKey\n state: QueryState\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext