diff --git a/.changeset/react-query-pluggable.md b/.changeset/react-query-pluggable.md new file mode 100644 index 00000000000..aa648f0d60c --- /dev/null +++ b/.changeset/react-query-pluggable.md @@ -0,0 +1,16 @@ +--- +'@tanstack/query-core-pluggable': minor +'@tanstack/react-query-pluggable': minor +--- + +Add an experimental ESM-only pair for React. `@tanstack/react-query-pluggable` depends on `@tanstack/query-core-pluggable`. Prepare each `useQuery` call with `queryOptions`, `suspenseQueryOptions`, `infiniteQueryOptions`, or `suspenseInfiniteQueryOptions`. Each factory selects the observer and return type. The Suspense factories delegate an initial fetch to the nearest boundary. + +Import optional features such as `refetchInterval`, `select`, `placeholderData`, and `serialScope` where the application uses them. Call the v6 imperative readers as `query(client, options)` and `infiniteQuery(client, options)`. Both use fresh cached data and fetch when stale. Other client operations follow the same client-first convention, including `invalidateQueries(client, filters)`. Mutation hooks acquire their cache on demand. Use `getMutationCache(client)` for direct access. + +The single-query reader gets its render behavior from the factory. Import result predicates such as `isSuccess(result)`, `isLoading(result)`, and `isFetchingNextPage(result)` wherever a component needs them. They narrow the result for TypeScript. Use `countFetchingQueries(client)` to count fetching queries across a cache. For a variable-length list, use `useQueries` or `useSuspenseQueries`. + +Cache-wide lookups and query-state checks are named imports, including `findCachedQuery(cache, filters)`, `findCachedQueries(cache, filters)`, `clearQueryCache(cache)`, and `isQueryActive(query)`. + +Four methods on an individual cache entry are now named imports. Use `invalidateCachedQuery(entry)` to mark it invalidated, `resetCachedQuery(entry)` to cancel its fetch and restore its initial state, `getQueryObserverCount(entry)` to count subscribed observers, and `isQueryFetched(entry)` to check for a data or error update. For a filtered operation that also refetches eligible active queries by default, use `invalidateQueries(client, filters)` or `resetQueries(client, filters)`. Inside a component, `isFetched(result)` reads the update history from the hook result. + +Ordinary readers handle failures inline by default. Import `throwOnError` and set `throwOnError: [throwOnError, true]` or `throwOnError: [throwOnError, predicate]` to opt into React error boundaries. Suspense readers include boundary handling automatically. Ordinary queries retain default structural sharing. The infinite query fetcher prepares page requests only when the application uses pagination. diff --git a/.github/workflows/react-query-bundle-size.yml b/.github/workflows/react-query-bundle-size.yml new file mode 100644 index 00000000000..043888e83d7 --- /dev/null +++ b/.github/workflows/react-query-bundle-size.yml @@ -0,0 +1,104 @@ +name: React Query app bundle size + +on: + pull_request: + paths: + - '.github/workflows/react-query-bundle-size.yml' + - 'integrations/react/bundle-size/**' + - 'packages/query-core/**' + - 'packages/query-core-pluggable/**' + - 'packages/react-query/**' + - 'packages/react-query-pluggable/**' + - 'scripts/getTsdownConfig.js' + - '.nvmrc' + - 'package.json' + - 'pnpm-lock.yaml' + - 'pnpm-workspace.yaml' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.number }} + cancel-in-progress: true + +permissions: {} + +jobs: + measure: + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + report: ${{ steps.measure.outputs.report }} + analyzer_url: ${{ steps.analyzer.outputs.artifact-url }} + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 + - name: Check out the unmodified PR base + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: ${{ github.event.pull_request.base.sha }} + path: .bundle-base + persist-credentials: false + - name: Install and build the baseline adapter + working-directory: .bundle-base + run: | + pnpm --filter root --filter '@tanstack/react-query...' install --frozen-lockfile + pnpm --filter '@tanstack/react-query...' run build + - name: Build workspace dependencies + run: pnpm --filter '@tanstack/query-integration-react-bundle-size^...' run build + - name: Type-check the benchmark and both adapters' screens + working-directory: integrations/react/bundle-size + run: pnpm run test:types + - name: Build and measure production apps + id: measure + env: + QUERY_BASE_CHECKOUT: ${{ github.workspace }}/.bundle-base + working-directory: integrations/react/bundle-size + run: | + pnpm run measure + cat dist/report.md >> "$GITHUB_STEP_SUMMARY" + jq -Rsr '"report=" + tojson' dist/report.md >> "$GITHUB_OUTPUT" + - name: Install Chromium + working-directory: integrations/react/bundle-size + run: pnpm run browser:install + - name: Exercise production apps in Chromium + working-directory: integrations/react/bundle-size + run: pnpm run test:browser + - name: Upload interactive bundle treemaps + id: analyzer + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: react-query-bundle-analyzer + path: integrations/react/bundle-size/dist/analyzer/ + if-no-files-found: error + retention-days: 30 + comment: + if: github.event.pull_request.head.repo.full_name == github.repository + needs: measure + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - name: Update bundle size comment + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + PR_NUMBER: ${{ github.event.number }} + REPORT: ${{ needs.measure.outputs.report }} + ANALYZER_URL: ${{ needs.measure.outputs.analyzer_url }} + run: | + comments="repos/$REPO/issues/$PR_NUMBER/comments" + marker='' + id=$(gh api --paginate --slurp "$comments?per_page=100" | + jq -r --arg marker "$marker" '[.[][] | select(.user.login == "github-actions[bot]" and (.body | startswith($marker)))][0].id // empty') + endpoint="$comments" + method=POST + if [[ -n "$id" ]]; then + endpoint="repos/$REPO/issues/comments/$id" + method=PATCH + fi + jq -n --arg marker "$marker" --argjson report "$REPORT" --arg analyzer "$ANALYZER_URL" \ + '{body: ($marker + "\n" + $report + "\n[Download the interactive bundle treemaps](" + $analyzer + ")")}' | + gh api --silent --method "$method" "$endpoint" --input - diff --git a/integrations/react/bundle-size/.gitignore b/integrations/react/bundle-size/.gitignore new file mode 100644 index 00000000000..7a6c09645fe --- /dev/null +++ b/integrations/react/bundle-size/.gitignore @@ -0,0 +1 @@ +.vitest/ diff --git a/integrations/react/bundle-size/README.md b/integrations/react/bundle-size/README.md new file mode 100644 index 00000000000..10a5db0db0b --- /dev/null +++ b/integrations/react/bundle-size/README.md @@ -0,0 +1,76 @@ +# React Query app bundle size + +This workspace builds four browser apps against each adapter’s public package entry point. The read-only app fetches a book list with `useQuery(options)` in v6 and `useQuery(queryOptions(options))` in the pluggable adapter. The paginated app uses the query, infinite-query and mutation option factories to fetch additional pages and save bookmarks in browser storage. The polling app refreshes regular and infinite queries, both with and without Suspense. The pluggable app calls `useQuery` with `queryOptions(options)`, `infiniteQueryOptions(options)`, `suspenseQueryOptions(options)` or `suspenseInfiniteQueryOptions(options)` for each subscriber. The browser test holds the first responses until both dedicated Suspense boundaries show their fallbacks, then checks the resolved data and subsequent refetches. The options app keeps the previous page while fetching, selects the displayed titles, saves bookmarks in a serial scope, and invalidates the bookmark list. Each app uses the default client. The original adapter accepts a numeric interval. The pluggable adapter imports its interval scheduler through the `refetchInterval` option helper. + +CI builds the original adapter and its dependencies from the PR's base commit. The stock pair is `@tanstack/react-query` and `@tanstack/query-core`. The experimental pair is `@tanstack/react-query-pluggable` and `@tanstack/query-core-pluggable`. The experimental packages, fixture, bundler and React dependencies come from the PR head. The report records both commit IDs. + +## What the PR comment measures + +The opening table compares the gzipped Query runtime for each workload. It shows the byte difference and percentage change from v6. The next table lists implementations shipped by v6 that the pluggable build omits for each workload. The comparison checks emitted modules, retained exports and the source map symbols of v6’s built-in polling, selection, placeholder and scope handling. For bulk cache operations it also checks v6's emitted public method names. Expand the Query runtime table for the minified, gzip level 9 and Brotli quality 11 byte counts. + +Vite builds the same HTML and React entry points with React, React DOM and their subpaths external. Rolldown groups the retained modules from the adapter and its core package into one ESM chunk. The app and its workload-specific helpers stay in a separate entry chunk. The benchmark measures and compresses the emitted Query chunk directly, including its ESM import and export bindings. Each percentage uses the stock pair’s chunk for the same workload and encoding. + +The read-only app displays a failed query through its returned result. Its Query chunk must omit the error reset boundary, render-time error handling and the `shouldThrowError` predicate. The emitted JavaScript must also omit calls to the boundary’s `clearReset` API. The polling app includes the reset boundary for its Suspense queries. A separate consumer builds an ordinary `useQuery` with `throwOnError: [throwOnError, true]`. It must retain the boundary handling and exclude Suspense fetching. All four pluggable workloads must retain `replaceData` and `replaceEqualDeep`, which implement default structural sharing. + +The pluggable options app calls `invalidateQueries(client, { queryKey: ['bookmarks'] })`. Every named client operation takes the client first. The benchmark checks retained exports to verify that importing `QueryClient` leaves out `query(client, options)`, `infiniteQuery(client, options)`, `setQueryData` and bulk operations, and that each named operation is available when imported. + +For each app, the benchmark verifies that the isolated Query chunk contains the same retained Query module IDs and exports as the deployable browser build and imports only React peer entry points. Both builds reject runtime modules from the other pair or another checkout. Individual probes import operations directly from the public `@tanstack/query-core-pluggable` entry using the React adapter’s dependency scope. Both the read-only and polling apps construct a `QueryClient` and use queries. The pluggable build must retain the query cache and observer and exclude the mutation cache, mutation and mutation observer. Both bookmark apps call `useMutation` and must retain all three mutation modules. The ordinary and infinite option factories select their respective observers. The pluggable adapter exposes `useQuery` for all four modes. Its bundle contains no `useBaseQuery` wrapper, and the bare `useQuery` export leaves out both concrete observers. The benchmark checks the minified Query chunk for the optimistic fetch `Promise.race` in the Suspense workload and its absence in the other three. Each Suspense option factory is also tested independently against its ordinary counterpart. The read-only app excludes the infinite observer, both Suspense factories and their common policy. The polling app exercises all four factories. A separate probe verifies that `suspenseQueryOptions` excludes the infinite factory and observer, and that `suspenseInfiniteQueryOptions` excludes the regular-only factories. Pagination and polling retain the infinite query builder, observer and page fetcher. The read-only and selection apps exclude the page fetcher. Chromium exercises the included implementation by requesting and rendering the second page. All four hook-driven apps exclude both imperative operations. The regular operation is the named `query` export of the client module. Hook-driven apps still retain the core `Query` class. The `infiniteQuery` operation adds page fetching when imported. Additional checks cover polling, infinite queries, selection, placeholder data, serial queues and bulk cache operations. Individual public export probes also check selection, placeholder data and serial queues. The query cache lookups (`findCachedQuery` and `findCachedQueries`), `clearQueryCache`, and active, disabled, static and stale query predicates are measured as named core exports. The invalidation workload retains the filters and refetch predicates it calls, including `invalidateCachedQuery`, `getQueryObserverCount` and `isQueryFetched`. The other three workloads omit these functions. All four omit `resetCachedQuery`; a separate public import probe verifies that it remains available. The benchmark checks all fourteen query result helpers in isolation, then verifies the exact set retained by each screen. The read-only and options apps import `isPending` and `isError`. Pagination additionally imports `isFetching`, and polling reads the query data without any status helpers. The React hydration boundary only restores queries. The universal `hydrate` also restores serial queues from saved mutations. + +The PR comment links to the workflow artifact containing an interactive HTML bundle analyzer for each package and workload. Open `dist/analyzer//.html` locally after running the benchmark. Select the `query-runtime` chunk to explore its constituent sources. The treemap shows module contributions from source maps. The tables use actual compressed chunk bytes. + +## Lazy route navigation + +Open the catalog, visit Bookmarks, load a second page, then return to the catalog. One React root and one `QueryClientProvider` stay mounted for the whole visit. The shell imports the catalog at startup. `React.lazy` loads the bookmarks screen on its first render, and a React `Suspense` boundary shows a fallback while that JavaScript arrives. The catalog uses an ordinary data query. + +For the above-the-fold (ATF) and below-the-fold (BTF) layout, open the same app with `?layout=scroll`. The catalog renders immediately. An `IntersectionObserver` mounts the bookmarks component the first time its shelf intersects the viewport. Merely placing a mounted `React.lazy` component below the fold would request its module on the initial render. The navigation and scroll examples share the same dynamic import and emitted files. [React shell and viewport trigger](./src/lazy/main.tsx) + +The catalog imports its ordinary-query helper from a dedicated module. Keeping pagination and mutation imports on the bookmarks side gives the bundler a route boundary to follow. In stock v6 the shared client constructs a mutation cache, and its core fetch path references infinite-page behavior. The pluggable pair can defer both implementations until the bookmarks component loads. [v6 client](../../../packages/query-core/src/queryClient.ts) · [v6 fetch path](../../../packages/query-core/src/query.ts) · [Catalog hook](./src/pluggable-catalog.ts) · [Paginated hook](./src/pluggable-query.ts) + +The lazy-route table reports Query bytes for the cold catalog, the first trip to Bookmarks, both screens together, and the return trip. Each URL is counted once in the cumulative total. A larger incremental download on the second route can go along with a smaller first load when more of the feature's code can wait for the click. Read the phase rows alongside the total. [Measurement](./lazyRoutes.ts) · [Chromium navigation test](./browser/lazyRoutes.test.ts) + +| To explore | Example code | +| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| Reading a list and handling pending and error states | [Catalog](./src/query.tsx) | +| Fetching another page and saving a bookmark | [Paginated list and mutation](./src/paginated.tsx) | +| Selecting titles, showing placeholders and invalidating after queued writes | [Screen](./src/options.tsx) · [v6 options](./src/v6-options.ts) · [Pluggable options](./src/pluggable-options.ts) | +| Polling regular, infinite and Suspense queries | [Polling screen](./src/polling.tsx) · [Pluggable interval](./src/pluggable-interval.ts) | + +## Microfrontend navigation + +A shell loads the catalog first and the paginated bookmarks screen on navigation. Both remotes use the host’s React and React DOM and create a client when mounted. In the independent deployment, each remote is built on its own and has a separate Query URL. In the shared deployment, the shell serves one ESM Query chunk containing both routes’ imports. The table reports the gzip bytes of the Query URLs needed for the catalog alone and for the complete journey. Chromium verifies the requests on both visits and on returning to the catalog. The measured bytes describe JavaScript transfer. They do not measure cross-client data caching. + +## Run locally + +After installing workspace dependencies, build the packages, type-check the fixture, and measure both adapters from the repository root. + +```sh +pnpm --filter '@tanstack/query-integration-react-bundle-size^...' run build +pnpm --filter @tanstack/query-integration-react-bundle-size run test:types +pnpm --filter @tanstack/query-integration-react-bundle-size run measure +``` + +`test:types` checks the measurement tools, microfrontend host and browser tests. It checks the workload apps and remotes against both adapters' public types. The command also opens the app, remote and adapter hooks in the TypeScript language server to check that the editor resolves the same imports. + +To reproduce the CI comparison, use a clean worktree of the base commit. Replace `BASE_SHA` with the base commit from the report. + +```sh +git worktree add --detach ../query-bundle-base BASE_SHA +pnpm --dir ../query-bundle-base --filter root --filter '@tanstack/react-query...' install --frozen-lockfile +pnpm --dir ../query-bundle-base --filter '@tanstack/react-query...' run build +QUERY_BASE_CHECKOUT="$PWD/../query-bundle-base" pnpm --filter @tanstack/query-integration-react-bundle-size run measure +``` + +Read the summary and detailed tables in `integrations/react/bundle-size/dist/report.md`. Serve a directory under `dist//` to try the built app. + +To try the lazy routes, run `pnpm exec vite preview --outDir dist` from this directory after measuring. Open `/lazy-routes/react-query/` or `/lazy-routes/react-query-pluggable/` on the printed URL. Append `?layout=scroll` to try scrolling to the shelf. The Network panel shows which JavaScript each visit requests. + +Run the production apps, lazy routes and microfrontend journeys in Chromium after measuring. + +```sh +cd integrations/react/bundle-size +pnpm exec playwright install chromium +pnpm test:browser +pnpm test:browser:ui +``` + +The last command starts Vitest in watch mode with a browser UI for inspecting and rerunning each adapter’s scenarios. diff --git a/integrations/react/bundle-size/analyze.ts b/integrations/react/bundle-size/analyze.ts new file mode 100644 index 00000000000..da0e68c5392 --- /dev/null +++ b/integrations/react/bundle-size/analyze.ts @@ -0,0 +1,19 @@ +import path from 'node:path' +import { visualizer } from 'rollup-plugin-visualizer' + +export function adapterTreemap(screen: string, packageName: string) { + const name = path.posix.basename(packageName) + return visualizer({ + filename: path.join( + import.meta.dirname, + 'dist/analyzer', + screen, + name + '.html', + ), + title: `${packageName} · ${screen}`, + template: 'treemap', + sourcemap: true, + // Make source names comparable across the PR base and head checkouts. + projectRoot: /^.*\/(?=(?:packages|integrations)\/)/, + }) +} diff --git a/integrations/react/bundle-size/browser/apps.test.ts b/integrations/react/bundle-size/browser/apps.test.ts new file mode 100644 index 00000000000..f09e6949000 --- /dev/null +++ b/integrations/react/bundle-size/browser/apps.test.ts @@ -0,0 +1,152 @@ +import { afterEach, assert, describe, expect, it } from 'vitest' +import { commands } from 'vitest/browser' + +const adapters = ['react-query', 'react-query-pluggable'] as const +type Adapter = (typeof adapters)[number] +type Scenario = 'query' | 'paginated' | 'options' | 'polling' + +function mountApp(scenario: Scenario, adapter: Adapter) { + const frame = document.createElement('iframe') + frame.title = adapter + frame.src = `/${scenario}/${adapter}/index.html` + document.body.append(frame) + return frame +} + +async function openApp(scenario: Scenario, adapter: Adapter) { + const frame = mountApp(scenario, adapter) + await expect + .poll(() => frame.contentDocument?.querySelector('li')?.textContent) + .toContain('Middlemarch') + const app = frame.contentDocument + assert(app, 'Missing document for ' + frame.src) + return app +} + +afterEach(() => { + document.querySelector('iframe')?.remove() + localStorage.removeItem('bookmark') + localStorage.removeItem('bookmarks') +}) + +describe.each(adapters)('@tanstack/%s', (adapter) => { + it('renders a fetched reading list', async () => { + const app = await openApp('query', adapter) + expect( + Array.from(app.querySelectorAll('li'), (row) => row.textContent), + ).toEqual(['Middlemarch', 'Persuasion']) + }) + + it('loads the next page and saves a bookmark', async () => { + const app = await openApp('paginated', adapter) + const more = Array.from(app.querySelectorAll('button')).find( + (button) => button.textContent === 'Load more', + ) + assert(more, 'Missing Load more button') + more.click() + await expect.poll(() => app.querySelectorAll('li').length).toBe(4) + const third = app.querySelectorAll('li')[2] + assert(third, 'Missing third book') + expect(third.textContent).toContain('Villette') + const bookmark = third.querySelector('button') + assert(bookmark, 'Missing bookmark button') + bookmark.click() + await expect + .poll(() => app.body.textContent) + .toContain('Bookmarked: Villette') + expect(localStorage.getItem('bookmark')).toBe('Villette') + }) + + it('retains the previous selection, queues bookmarks and refreshes the cache', async () => { + const app = await openApp('options', adapter) + const view = app.defaultView + assert(view, 'Missing app window') + const originalFetch = view.fetch.bind(view) + const gate = Promise.withResolvers() + view.fetch = async (...args) => { + if (String(args[0]).endsWith('books-2.json')) await gate.promise + return originalFetch(...args) + } + const button = (label: string) => { + const element = Array.from(app.querySelectorAll('button')).find( + (item) => item.textContent === label, + ) + assert(element, 'Missing button: ' + label) + return element + } + try { + button('Next page').click() + await expect + .poll(() => app.querySelector('[role="status"]')?.textContent) + .toBe('Showing the previous page') + expect(app.querySelector('ul')?.textContent).toContain('Middlemarch') + } finally { + gate.resolve() + view.fetch = originalFetch + } + await expect + .poll(() => app.querySelector('ul')?.textContent) + .toContain('Villette') + button('Bookmark this page').click() + await expect + .poll(() => app.body.textContent) + .toContain('Bookmarks: Villette, North and South') + expect( + Array.from(app.querySelectorAll('ol li'), (item) => item.textContent), + ).toEqual([ + 'Saving Villette', + 'Saved Villette', + 'Saving North and South', + 'Saved North and South', + ]) + }) + + it('periodically refetches regular, infinite and suspense queries', async () => { + await commands.holdPollingBooks(adapter) + const frame = mountApp('polling', adapter) + try { + await commands.waitForPollingRequest(adapter) + await expect + .poll(() => + Array.from( + frame.contentDocument?.querySelectorAll('[role="status"]') ?? [], + (element) => element.textContent, + ), + ) + .toEqual(['Loading suspense query…', 'Loading suspense pages…']) + } finally { + await commands.releasePollingBooks(adapter) + } + const app = frame.contentDocument + assert(app, 'Missing polling app') + await expect + .poll(() => + Array.from(app.querySelectorAll('li'), (item) => + item.textContent.includes('Middlemarch'), + ), + ) + .toEqual([true, true, true, true]) + const timestamps = () => + Array.from(app.querySelectorAll('time'), (time) => time.dateTime) + await expect.poll(() => timestamps().length).toBe(4) + // Two successive refreshes for every hook distinguish interval polling from a mount refetch. + for (let refresh = 0; refresh < 2; refresh++) { + const previous = timestamps() + await expect + .poll( + () => { + const current = timestamps() + return ( + current.length === 4 && + current.every((value, index) => { + const lastUpdate = previous[index] + return lastUpdate !== undefined && value > lastUpdate + }) + ) + }, + { timeout: 4000 }, + ) + .toBe(true) + } + }) +}) diff --git a/integrations/react/bundle-size/browser/lazyRoutes.test.ts b/integrations/react/bundle-size/browser/lazyRoutes.test.ts new file mode 100644 index 00000000000..c4a374b1ac2 --- /dev/null +++ b/integrations/react/bundle-size/browser/lazyRoutes.test.ts @@ -0,0 +1,144 @@ +import { afterEach, assert, describe, expect, it, vi } from 'vitest' + +interface RequestManifest { + catalog: Array + bookmarks: Array + routeEntries: { catalog: string; bookmarks: string } +} + +async function openCatalog(adapter: string, layout: 'routes' | 'scroll') { + const prefix = '/lazy-routes/' + adapter + '/' + const response = await fetch(prefix + 'query-requests.json') + assert(response.ok, 'Missing measured Query requests for ' + adapter) + const manifest: RequestManifest = await response.json() + + const frame = document.createElement('iframe') + frame.height = '500' + frame.width = '640' + frame.src = + prefix + 'index.html' + (layout === 'scroll' ? '?layout=scroll' : '') + document.body.append(frame) + await expect + .poll(() => frame.contentDocument?.querySelector('li')?.textContent) + .toBe('Middlemarch') + const app = frame.contentDocument + const view = app?.defaultView + assert(app && view, 'Missing lazy app') + + const resources = () => + view.performance.getEntriesByType('resource').flatMap((entry) => { + const url = new URL(entry.name) + return url.pathname.startsWith(prefix) + ? [{ file: url.pathname.slice(prefix.length), start: entry.startTime }] + : [] + }) + const queryFiles = () => + resources() + .map(({ file }) => file) + .filter((file) => /^assets\/query-(catalog|bookmarks)-/.test(file)) + .sort() + const copiesOf = (file: string) => + resources().filter((entry) => entry.file === file).length + await expect.poll(queryFiles).toEqual([...manifest.catalog].sort()) + await expect.poll(() => copiesOf(manifest.routeEntries.catalog)).toBe(1) + expect(copiesOf(manifest.routeEntries.bookmarks)).toBe(0) + await expect.poll(() => copiesOf('books-1.json')).toBe(1) + + const allQueryFiles = [...manifest.catalog, ...manifest.bookmarks].sort() + async function expectDeferredRequests(start: number) { + await expect.poll(queryFiles).toEqual(allQueryFiles) + for (const file of [ + manifest.routeEntries.bookmarks, + ...manifest.bookmarks, + ]) { + await expect.poll(() => copiesOf(file)).toBe(1) + const resource = resources().find((entry) => entry.file === file) + assert(resource) + expect(resource.start).toBeGreaterThanOrEqual(start) + } + } + function expectReusedFiles() { + expect(queryFiles()).toEqual(allQueryFiles) + expect(copiesOf(manifest.routeEntries.catalog)).toBe(1) + expect(copiesOf(manifest.routeEntries.bookmarks)).toBe(1) + } + return { app, view, copiesOf, expectDeferredRequests, expectReusedFiles } +} + +function click(parent: ParentNode, label: string) { + const button = [...parent.querySelectorAll('button')].find( + (item) => item.textContent === label, + ) + assert(button, 'Missing button ' + label) + button.click() +} + +afterEach(() => { + document.querySelector('iframe')?.remove() + localStorage.removeItem('bookmark') +}) + +describe.each(['react-query', 'react-query-pluggable'])( + '%s lazy bookmarks', + (adapter) => { + it('downloads bookmarks on navigation and reuses its code and cached pages on revisit', async () => { + const { app, view, copiesOf, expectDeferredRequests, expectReusedFiles } = + await openCatalog(adapter, 'routes') + const beforeNavigation = view.performance.now() + click(app, 'Bookmarks') + await expect + .poll(() => app.querySelector('li button')?.textContent) + .toBe('Bookmark') + await expectDeferredRequests(beforeNavigation) + click(app, 'Load more') + await expect.poll(() => app.querySelectorAll('li').length).toBe(4) + const villette = [...app.querySelectorAll('li')].find((row) => + row.textContent.includes('Villette'), + ) + assert(villette, 'Missing second page of books') + click(villette, 'Bookmark') + await expect + .poll(() => app.body.textContent) + .toContain('Bookmarked: Villette') + await expect.poll(() => copiesOf('books-1.json')).toBe(2) + await expect.poll(() => copiesOf('books-2.json')).toBe(1) + + const revisitFetch = vi.spyOn(view, 'fetch') + click(app, 'Catalog') + await expect + .poll(() => app.querySelector('li')?.textContent) + .toBe('Middlemarch') + click(app, 'Bookmarks') + await expect.poll(() => app.querySelectorAll('li').length).toBe(4) + await expect + .poll(() => app.body.textContent) + .toContain('Bookmarked: Villette') + expect(revisitFetch).not.toHaveBeenCalled() + expectReusedFiles() + }) + + it('downloads the below-fold shelf when scrolled into view and reuses its code on a second scroll', async () => { + const { app, view, expectDeferredRequests, expectReusedFiles } = + await openCatalog(adapter, 'scroll') + const shelf = app.querySelector('#bookmarks-shelf') + assert(shelf, 'Missing bookmarks shelf') + const top = () => shelf.getBoundingClientRect().top + expect(top()).toBeGreaterThanOrEqual(view.innerHeight) + expect(shelf.querySelector('li button')).toBeNull() + const beforeScroll = view.performance.now() + shelf.scrollIntoView() + await expect.poll(top).toBeLessThan(view.innerHeight) + await expect + .poll(() => shelf.querySelector('li')?.textContent) + .toContain('Middlemarch') + await expectDeferredRequests(beforeScroll) + + view.scrollTo(0, 0) + await expect.poll(top).toBeGreaterThanOrEqual(view.innerHeight) + shelf.scrollIntoView() + await expect.poll(top).toBeLessThan(view.innerHeight) + expect(shelf.querySelector('li button')?.textContent).toBe('Bookmark') + expectReusedFiles() + }) + }, +) diff --git a/integrations/react/bundle-size/browser/microfrontend.test.ts b/integrations/react/bundle-size/browser/microfrontend.test.ts new file mode 100644 index 00000000000..13df9ec9505 --- /dev/null +++ b/integrations/react/bundle-size/browser/microfrontend.test.ts @@ -0,0 +1,49 @@ +import { afterEach, assert, describe, expect, it } from 'vitest' + +afterEach(() => document.querySelector('iframe')?.remove()) + +describe.each(['react-query', 'react-query-pluggable'])( + '%s microfrontends', + (adapter) => { + it.each(['independent', 'shared'])( + 'loads each Query URL once with %s chunks', + async (deployment) => { + const prefix = '/microfrontends/' + adapter + '/' + deployment + '/' + const frame = document.createElement('iframe') + frame.src = prefix + 'index.html' + document.body.append(frame) + const list = () => + frame.contentDocument?.querySelector('li')?.textContent + const queryUrls = () => { + const view = frame.contentWindow + assert(view, 'Missing microfrontend window') + return view.performance + .getEntriesByType('resource') + .map((resource) => new URL(resource.name).pathname) + .filter((pathname) => pathname.endsWith('/query-runtime.js')) + } + const navigate = (id: string) => { + const button = + frame.contentDocument?.querySelector(id) + assert(button, 'Missing route button ' + id) + button.click() + } + await expect.poll(list).toBe('Middlemarch') + const expected = [ + prefix + + (deployment === 'shared' ? '' : 'query/') + + 'query-runtime.js', + ] + expect(queryUrls()).toEqual(expected) + navigate('#bookmarks') + await expect.poll(list).toContain('Bookmark') + if (deployment === 'independent') + expected.push(prefix + 'paginated/query-runtime.js') + expect(queryUrls()).toEqual(expected) + navigate('#catalog') + await expect.poll(list).toBe('Middlemarch') + expect(queryUrls()).toEqual(expected) + }, + ) + }, +) diff --git a/integrations/react/bundle-size/check-editor.ts b/integrations/react/bundle-size/check-editor.ts new file mode 100644 index 00000000000..65ce5f103ec --- /dev/null +++ b/integrations/react/bundle-size/check-editor.ts @@ -0,0 +1,54 @@ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { createRequire } from 'node:module' +import { resolve } from 'node:path' +import type ts from 'typescript' + +const files = [ + 'src/main.tsx', + 'src/remote.tsx', + 'src/v6-query.ts', + 'src/pluggable-query.ts', +] +const requests = files.flatMap((name, index) => { + const file = resolve(import.meta.dirname, name) + return ['open', 'semanticDiagnosticsSync'].map((command, offset) => + JSON.stringify({ + seq: index * 2 + offset + 1, + type: 'request', + command, + arguments: { file }, + }), + ) +}) +const tsserver = createRequire(import.meta.url).resolve( + 'typescript/lib/tsserver.js', +) +const run = spawnSync( + process.execPath, + [tsserver, '--disableAutomaticTypingAcquisition'], + { + input: requests.join('\n') + '\n', + encoding: 'utf8', + }, +) +if (run.error) throw run.error +assert.equal(run.status, 0, run.stderr) + +// tsserver frames each JSON message with a Content-Length header. +const diagnostics: Array = + run.stdout + .split('\n') + .filter((line) => line.startsWith('{')) + .map((line) => JSON.parse(line)) + .filter((message) => message.command === 'semanticDiagnosticsSync') +for (const [index, file] of files.entries()) { + const report = diagnostics.find( + (response) => response.request_seq === index * 2 + 2, + ) + assert.ok( + report?.success, + report?.message ?? `Missing editor diagnostics for ${file}`, + ) + assert.deepEqual(report.body, [], file) +} diff --git a/integrations/react/bundle-size/host/navigation.ts b/integrations/react/bundle-size/host/navigation.ts new file mode 100644 index 00000000000..743c2e26214 --- /dev/null +++ b/integrations/react/bundle-size/host/navigation.ts @@ -0,0 +1,24 @@ +export type MountRemote = (container: Element) => () => void + +const container = document.querySelector('main') +const catalog = document.querySelector('#catalog') +const bookmarks = document.querySelector('#bookmarks') +if (!container || !catalog || !bookmarks) + throw new Error('Missing reading list shell') + +let unmount: ReturnType | undefined + +async function openRoute(button: HTMLButtonElement, main: HTMLElement) { + const entry = button.dataset.entry + if (!entry) throw new Error('Missing remote entry for ' + button.id) + const url = new URL(entry, document.baseURI) + const remote: { mount: MountRemote } = await import( + /* @vite-ignore */ url.href + ) + unmount?.() + unmount = remote.mount(main) +} + +catalog.onclick = () => openRoute(catalog, container) +bookmarks.onclick = () => openRoute(bookmarks, container) +await openRoute(catalog, container) diff --git a/integrations/react/bundle-size/index.html b/integrations/react/bundle-size/index.html new file mode 100644 index 00000000000..5536836fde7 --- /dev/null +++ b/integrations/react/bundle-size/index.html @@ -0,0 +1,12 @@ + + + + + + Reading list + + +
+ + + diff --git a/integrations/react/bundle-size/lazyRoutes.ts b/integrations/react/bundle-size/lazyRoutes.ts new file mode 100644 index 00000000000..e63a10b4961 --- /dev/null +++ b/integrations/react/bundle-size/lazyRoutes.ts @@ -0,0 +1,342 @@ +import assert from 'node:assert/strict' +import { readFile, writeFile } from 'node:fs/promises' +import { SourceMap } from 'node:module' +import path from 'node:path' +import { gzipSync } from 'node:zlib' +import { build, normalizePath } from 'vite' +import type { Rolldown } from 'vite' + +type Chunk = Rolldown.OutputChunk +type Adapter = '@tanstack/react-query' | '@tanstack/react-query-pluggable' +type Phase = 'catalog' | 'bookmarks' +const phases = ['catalog', 'bookmarks'] as const +const queryPackage = + /\/(?:packages|node_modules\/@tanstack)\/(?:query-core|react-query)(?:-pluggable)?\// + +// Follow static imports only. The bookmark route starts a second traversal +// when React.lazy invokes its dynamic import. +function routeGraph(chunks: Array) { + const byName = new Map(chunks.map((chunk) => [chunk.fileName, chunk])) + function dependencies(entry: Chunk) { + const reached = new Set() + function visit(chunk: Chunk) { + if (reached.has(chunk)) return + reached.add(chunk) + for (const file of chunk.imports) { + const dependency = byName.get(file) + assert(dependency, `Missing static dependency ${file}`) + visit(dependency) + } + } + visit(entry) + return reached + } + const entries = chunks.filter((chunk) => chunk.isEntry) + assert.equal(entries.length, 1, 'Expected one application entry') + const [catalog] = entries + const bookmarks = chunks.find((chunk) => + chunk.facadeModuleId?.endsWith('/src/paginated.tsx'), + ) + assert( + catalog && bookmarks && bookmarks.isDynamicEntry, + 'Missing lazy route entries', + ) + const initial = dependencies(catalog) + assert(!initial.has(bookmarks), 'Bookmarks was loaded with the catalog') + assert( + [...initial].some((chunk) => + chunk.dynamicImports.includes(bookmarks.fileName), + ), + 'Missing dynamic import to bookmarks', + ) + const deferred = new Set( + [...dependencies(bookmarks)].filter((chunk) => !initial.has(chunk)), + ) + assert.equal( + initial.size + deferred.size, + chunks.length, + 'Unmeasured application chunk', + ) + return { + catalog: initial, + bookmarks: deferred, + entries: { catalog: catalog.fileName, bookmarks: bookmarks.fileName }, + } +} + +function queryExports(chunks: Set, owns: (id: string) => boolean) { + const exports = new Map>() + for (const chunk of chunks) { + for (const [id, module] of Object.entries(chunk.modules)) { + if (!module.renderedLength) continue + assert( + !queryPackage.test(id) || owns(id), + `Unexpected Query package ${id}`, + ) + if (owns(id)) { + assert(!exports.has(id), `Query module appears in two chunks: ${id}`) + exports.set(id, new Set(module.renderedExports)) + } + } + } + return exports +} + +// Final minification can discard functions after Rolldown has recorded its +// rendered exports. Compare the Query sources still mapped to output bytes. +function mappedQuerySources( + chunks: Set, + outDir: string, + owns: (id: string) => boolean, +) { + const sources = new Set() + for (const chunk of chunks) { + if (!Object.keys(chunk.modules).some(owns)) continue + const map = chunk.map + assert(map, `Missing source map for ${chunk.fileName}`) + const querySources = new Map() + for (const source of map.sources) { + const id = normalizePath( + path.resolve(outDir, path.dirname(chunk.fileName), source), + ) + if (owns(id)) querySources.set(source, id) + } + const trace = new SourceMap({ ...map, sourceRoot: '' }) + for (const [line, content] of chunk.code.split('\n').entries()) { + for (let column = 0; column < content.length; column++) { + const entry = trace.findEntry(line, column) + if (!('originalSource' in entry)) continue + const source = querySources.get(entry.originalSource) + if (source) sources.add(source) + } + } + } + assert(sources.size > 0, 'Expected mapped Query bytes on this route') + return sources +} + +async function measureAdapter( + root: string, + source: string, + adapter: Adapter, + owners: ReadonlyArray, +) { + const pluggable = adapter === '@tanstack/react-query-pluggable' + const owns = (id: string) => + owners.some((directory) => id.startsWith(directory)) + const name = path.posix.basename(adapter) + const outDir = path.join(root, 'dist/lazy-routes', name) + const packageScope = path.join(source, 'packages', name, 'package.json') + async function routeBuild(groups?: Record>>) { + const result = await build({ + root: path.join(root, 'src/lazy'), + publicDir: path.join(root, 'public'), + base: './', + configFile: false, + mode: 'production', + logLevel: 'warn', + resolve: { + dedupe: ['react', 'react-dom'], + alias: { + '#catalog-hooks': path.join( + root, + 'src', + pluggable ? 'pluggable-catalog.ts' : 'v6-catalog.ts', + ), + '#query-hooks': path.join( + root, + 'src', + pluggable ? 'pluggable-query.ts' : 'v6-query.ts', + ), + }, + }, + plugins: [ + { + name: 'resolve-lazy-route-adapter', + enforce: 'pre', + resolveId(id) { + if (id === '#adapter') + return this.resolve(adapter, packageScope, { skipSelf: true }) + return null + }, + }, + ], + build: { + outDir, + emptyOutDir: true, + write: !!groups, + sourcemap: 'hidden', + reportCompressedSize: false, + rolldownOptions: { + checks: { moduleLevelDirective: false }, + ...(groups && { + output: { + codeSplitting: { + groups: [ + // Query imports React, and the shell imports Query. Keep React and + // its CommonJS interop outside the shell to avoid a chunk cycle. + { + name: 'react-vendor', + test: (id: string) => + /\/node_modules\/(?:react|react-dom|scheduler)\//.test( + id, + ) || id.includes('rolldown/runtime'), + includeDependenciesRecursively: true, + }, + ...phases.map((phase) => ({ + name: `query-${phase}`, + test: (id: string) => groups[phase].has(id), + includeDependenciesRecursively: false, + })), + ], + }, + }, + }), + }, + }, + }) + assert('output' in result) + return result.output.filter((output) => output.type === 'chunk') + } + const ordinary = routeGraph(await routeBuild()) + const groups = { + catalog: queryExports(ordinary.catalog, owns), + bookmarks: queryExports(ordinary.bookmarks, owns), + } + assert( + [...groups.catalog.keys()].every((id) => !groups.bookmarks.has(id)), + 'A Query module was assigned to both routes', + ) + for (const dir of owners) + assert( + [...groups.catalog.keys()].some((id) => id.startsWith(dir)), + `Missing eager runtime from ${dir}`, + ) + const published = routeGraph(await routeBuild(groups)) + const requests = { + catalog: [] as Array, + bookmarks: [] as Array, + routeEntries: published.entries, + } + const bytes = { catalog: 0, bookmarks: 0 } + for (const phase of phases) { + const chunks = published[phase] + assert.deepEqual( + queryExports(chunks, owns), + groups[phase], + `${name} changed retained Query exports for ${phase}`, + ) + const sources = mappedQuerySources(ordinary[phase], outDir, owns) + assert.deepEqual( + mappedQuerySources(chunks, outDir, owns), + sources, + `${name} changed emitted Query sources for ${phase}`, + ) + // v6 constructs a mutation cache on startup and includes its infinite fetch behavior. + // The pluggable pair first needs both when the bookmarks route opens. + const firstVisit: Record = { + mutationCache: pluggable ? 'bookmarks' : 'catalog', + infiniteQueryBehavior: pluggable ? 'bookmarks' : 'catalog', + mutationObserver: 'bookmarks', + useMutation: 'bookmarks', + infiniteQueryObserver: 'bookmarks', + } + for (const [feature, visit] of Object.entries(firstVisit)) { + assert.equal( + [...sources].some((id) => path.basename(id) === feature + '.js'), + visit === phase, + `${name} ${phase}: ${feature}`, + ) + } + for (const chunk of chunks) { + const ids = Object.entries(chunk.modules) + .filter(([, module]) => module.renderedLength > 0) + .map(([id]) => id) + if (!ids.some(owns)) continue + assert.equal(chunk.name, `query-${phase}`) + assert( + !chunk.imports.some( + (file) => + file === published.entries.catalog || + file === published.entries.bookmarks, + ), + `Query runtime imports an application entry: ${chunk.fileName}`, + ) + assert(ids.every(owns), `Foreign code in ${chunk.fileName}`) + const file = await readFile(path.join(outDir, chunk.fileName)) + assert.equal( + file.toString('utf8'), + chunk.code, + `Emitted contents differ for ${chunk.fileName}`, + ) + bytes[phase] += gzipSync(file, { level: 9 }).length + requests[phase].push(chunk.fileName) + } + assert(requests[phase].length, `No Query requests for ${phase}`) + } + await writeFile( + path.join(outDir, 'query-requests.json'), + JSON.stringify(requests), + ) + return bytes +} + +export async function measureLazyRoutes({ + root, + checkout, + baseCheckout, + baseline, + pluggable, + runtimeOwners, + formatChange, +}: { + root: string + checkout: string + baseCheckout?: string + baseline: Adapter + pluggable: Adapter + runtimeOwners: (source: string, adapter: Adapter) => ReadonlyArray + formatChange: (bytes: number, baselineBytes: number) => string +}) { + const source = baseCheckout ?? checkout + const stock = await measureAdapter( + root, + source, + baseline, + runtimeOwners(source, baseline), + ) + const experiment = await measureAdapter( + root, + checkout, + pluggable, + runtimeOwners(checkout, pluggable), + ) + const rows = [ + ['Cold catalog', stock.catalog, experiment.catalog], + [ + 'First bookmarks render (additional)', + stock.bookmarks, + experiment.bookmarks, + ], + [ + 'Catalog and bookmarks (cumulative)', + stock.catalog + stock.bookmarks, + experiment.catalog + experiment.bookmarks, + ], + ['Return to catalog (additional, checked in Chromium)', 0, 0], + ] as const + return [ + '### Lazy bookmarks on navigation or scroll', + '', + 'One React app keeps its QueryClient mounted. The catalog loads at startup. React.lazy imports the same bookmarks module when the user opens the route or scrolls the shelf into view. Each Query-only file is gzipped individually at level 9. The benchmark checks module and export placement against Vite’s default production build. The cumulative row counts each URL once.', + '', + 'The v6 catalog includes the mutation cache and infinite fetch behavior. Pluggable downloads those with bookmarks. Both apps defer the mutation hook and infinite observer until bookmarks are first rendered.', + '', + '| User action | React Query v6 | React Query Pluggable | Change vs v6 |', + '| --- | ---: | ---: | ---: |', + ...rows.map( + ([visit, base, next]) => + `| ${visit} | ${base.toLocaleString('en-US')} B | ${next.toLocaleString('en-US')} B | ${base ? formatChange(next, base) : '0 B'} |`, + ), + ].join('\n') +} diff --git a/integrations/react/bundle-size/measure.ts b/integrations/react/bundle-size/measure.ts new file mode 100644 index 00000000000..e63f2398447 --- /dev/null +++ b/integrations/react/bundle-size/measure.ts @@ -0,0 +1,954 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { realpath, writeFile } from 'node:fs/promises' +import path from 'node:path' +import { brotliCompressSync, constants, gzipSync } from 'node:zlib' +import { build, normalizePath } from 'vite' +import { adapterTreemap } from './analyze.ts' +import { measureLazyRoutes } from './lazyRoutes.ts' +import { measureMicrofrontends } from './microfrontends.ts' +import type { Rolldown } from 'vite' + +const root = import.meta.dirname +const checkout = path.resolve(root, '../../..') +const baseCheckout = process.env.QUERY_BASE_CHECKOUT + ? await realpath(process.env.QUERY_BASE_CHECKOUT) + : undefined +const basePackage = + baseCheckout && path.join(baseCheckout, 'packages/react-query') +const baseline = '@tanstack/react-query' +const pluggable = '@tanstack/react-query-pluggable' +const pluggableCore = '@tanstack/query-core-pluggable' +type Adapter = typeof baseline | typeof pluggable +type Chunk = Rolldown.OutputChunk +type ModuleEntry = [id: string, module: Chunk['modules'][string]] +const workloads = [ + { screen: 'query', title: 'Read-only list' }, + { screen: 'paginated', title: 'Paginated bookmarks' }, + { + screen: 'options', + title: 'Selection, serial bookmarks and invalidation', + }, + { + screen: 'polling', + title: 'Polling', + }, +] as const +type Screen = (typeof workloads)[number]['screen'] + +const otherFrameworks = [ + /\/(?:packages|node_modules\/@tanstack)\/(?:angular|lit|preact|solid|svelte|vue)-query[^/]*\//, + /\/node_modules\/(?:@angular|@lit|@vue|lit|lit-element|lit-html|preact|solid-js|svelte|vue)\//, +] + +function buildDirectory(directory: string, packageName: string) { + return ( + normalizePath( + path.join( + directory, + 'packages', + path.posix.basename(packageName), + 'build', + ), + ) + '/' + ) +} + +function runtimeOwners(directory: string, adapter: Adapter) { + const core = adapter === baseline ? '@tanstack/query-core' : pluggableCore + return [adapter, core].map((name) => buildDirectory(directory, name)) +} + +const pluggableOwners = runtimeOwners(checkout, pluggable) +const pluggableCoreDirectory = buildDirectory(checkout, pluggableCore) +function rendersFeature(id: string, feature: string) { + return ( + id.endsWith(`/${feature}.js`) && + pluggableOwners.some((dir) => id.startsWith(dir)) + ) +} + +async function buildApp( + packageName: Adapter, + screen: Screen, + belongsToAdapter?: (id: string) => boolean, +) { + const outDir = path.join( + root, + 'dist', + screen, + path.posix.basename(packageName), + ) + const result = await build({ + root, + base: './', + configFile: false, + mode: 'production', + logLevel: 'warn', + plugins: [ + ...(belongsToAdapter ? [adapterTreemap(screen, packageName)] : []), + { + name: 'resolve-benchmark-adapter', + enforce: 'pre', + resolveId(id, importer) { + if (id !== '#adapter') return + // Resolve the public browser export using the requested checkout's package scope. + const from = + packageName === baseline && basePackage + ? path.join(basePackage, 'package.json') + : importer + return this.resolve(packageName, from, { skipSelf: true }) + }, + }, + ], + resolve: { + dedupe: ['react', 'react-dom'], + alias: { + '#catalog-hooks': path.join( + root, + 'src', + packageName === pluggable ? 'pluggable-catalog.ts' : 'v6-catalog.ts', + ), + '#query-hooks': path.join( + root, + 'src', + packageName === pluggable ? 'pluggable-query.ts' : 'v6-query.ts', + ), + '#polling-option': path.join( + root, + 'src', + packageName === pluggable + ? 'pluggable-interval.ts' + : 'numeric-interval.ts', + ), + '#feature-options': path.join( + root, + 'src', + packageName === pluggable ? 'pluggable-options.ts' : 'v6-options.ts', + ), + '#screen': path.join(root, 'src', `${screen}.tsx`), + }, + }, + build: { + outDir, + write: !belongsToAdapter, + sourcemap: belongsToAdapter ? 'hidden' : false, + reportCompressedSize: false, + // All modules in these apps execute on the client. + rolldownOptions: { + checks: { moduleLevelDirective: false }, + ...(belongsToAdapter && { + external: reactPeer, + output: { + codeSplitting: { + groups: [ + { + name: 'query-runtime', + test: belongsToAdapter, + includeDependenciesRecursively: false, + }, + ], + }, + }, + }), + }, + }, + }) + assert('output' in result, 'Expected a single application build') + const chunks = result.output.filter((output) => output.type === 'chunk') + if (!chunks.some((chunk) => chunk.isEntry)) { + throw new Error(`Missing browser entry chunk for ${packageName}`) + } + return chunks +} + +function renderedModules(chunks: Array): Array { + return chunks.flatMap((chunk) => + Object.entries(chunk.modules).filter( + ([, module]) => module.renderedLength > 0, + ), + ) +} + +// These operations can retain the named helpers they use internally. +const filterPredicates = [ + 'isQueryActive', + 'isQueryStale', + 'getQueryObserverCount', +] +const filteredQueries = ['findCachedQueries', ...filterPredicates] +const refetchFilters = [ + ...filteredQueries, + 'isQueryDisabled', + 'isQueryStatic', + 'isQueryFetched', +] +const bulkOperations: Record> = { + getQueriesData: filteredQueries, + setQueriesData: ['setQueryData', ...filteredQueries], + removeQueries: filteredQueries, + resetQueries: ['resetCachedQuery', 'refetchQueries', ...refetchFilters], + cancelQueries: filteredQueries, + invalidateQueries: [ + 'invalidateCachedQuery', + 'refetchQueries', + ...refetchFilters, + ], + refetchQueries: refetchFilters, +} +const cacheHelpers: Record> = { + findCachedQuery: filterPredicates, + findCachedQueries: filterPredicates, + clearQueryCache: [], + isQueryActive: [], + isQueryDisabled: ['isQueryActive', 'isQueryFetched', 'getQueryObserverCount'], + isQueryStatic: ['getQueryObserverCount'], + isQueryStale: ['getQueryObserverCount'], + isQueryFetched: [], + getQueryObserverCount: [], + resetCachedQuery: [], + invalidateCachedQuery: [], +} + +const resultHelpers = [ + 'isPending', + 'isSuccess', + 'isError', + 'isFetching', + 'isPaused', + 'isLoading', + 'isRefetching', + 'isLoadingError', + 'isRefetchError', + 'isFetched', + 'isFetchingNextPage', + 'isFetchingPreviousPage', + 'isFetchNextPageError', + 'isFetchPreviousPageError', +] + +function checkResultHelpers( + modules: Array, + expected: Array, + context: string, +) { + const included = modules + .filter(([id]) => rendersFeature(id, 'queryResult')) + .flatMap(([, module]) => module.renderedExports) + assert.deepEqual( + new Set(included), + new Set(expected), + `${context} retained unexpected query result helpers`, + ) +} + +function checkOptimisticFetch( + chunks: Array, + expected: boolean, + context: string, +) { + // Inspect the emitted Query JS. This catches a race left inside an otherwise + // essential class even if the dedicated Suspense module was tree-shaken. + const included = chunks.some(({ code }) => /\bPromise\.race\s*\(/.test(code)) + assert.equal( + included, + expected, + `${context} retained optimistic fetch race: ${included}`, + ) +} + +function checkErrorReset( + chunks: Array, + expected: boolean, + context: string, +) { + // The generic reader must not keep a call to the public boundary reset API. + const included = chunks.some(({ code }) => /\.clearReset\b/.test(code)) + assert.equal( + included, + expected, + `${context} retained error-boundary reset access: ${included}`, + ) +} + +function checkClientOperations( + modules: Array, + workload: string, + required?: string, +) { + const tracked = new Set([ + ...Object.keys(bulkOperations), + ...Object.keys(cacheHelpers), + 'infiniteQuery', + 'query', + 'setQueryData', + ]) + const operations = new Set( + modules + .filter(([id]) => id.startsWith(pluggableCoreDirectory)) + .flatMap(([, module]) => + module.renderedExports.filter((name) => tracked.has(name)), + ), + ) + const allowed = [ + required, + ...(required + ? (bulkOperations[required] ?? cacheHelpers[required] ?? []) + : []), + ...(required === 'infiniteQuery' ? ['query'] : []), + ] + for (const name of operations) { + assert( + allowed.includes(name), + `${workload} retained unused client operation ${name}`, + ) + } + if (required) + assert(operations.has(required), `${workload} is missing ${required}`) + if (required === 'invalidateQueries') { + for (const used of [ + 'invalidateCachedQuery', + 'getQueryObserverCount', + 'isQueryFetched', + ]) + assert(operations.has(used), `${workload} is missing ${used}`) + } +} + +// Query modules may only come from the two packages built in the selected checkout. +function checkPairOwnership( + modules: Array, + owners: Array, + context: string, +) { + const foreign = modules.find( + ([id]) => + /\/(?:packages|node_modules\/@tanstack)\/(?:query-core|react-query)(?:-pluggable)?\//.test( + id, + ) && !owners.some((dir) => id.startsWith(dir)), + ) + if (foreign) + throw new Error( + `${context} retained Query code outside the selected package pair: ${foreign[0]}`, + ) +} + +function checkApp(chunks: Array, packageName: Adapter, screen: Screen) { + if (packageName === pluggable) { + const retained = renderedModules(chunks) + const modules = retained.map(([id]) => id) + const foreignRuntime = modules.find((id) => + otherFrameworks.some((pattern) => pattern.test(id)), + ) + if (foreignRuntime) { + throw new Error( + `${packageName} bundled unexpected runtime code: ${foreignRuntime}`, + ) + } + if ( + chunks.some((chunk) => + chunk.moduleIds.some( + (id) => + id.endsWith('/build/runtime/index.js') || + rendersFeature(id, 'useBaseQuery'), + ), + ) + ) { + throw new Error( + `${packageName} included an internal runtime barrel or useBaseQuery in the app`, + ) + } + const usesMutations = screen === 'paginated' || screen === 'options' + const usesPages = screen === 'paginated' || screen === 'polling' + const features = { + queryClient: true, + queryCache: true, + query: true, + queryObserver: true, + mutationCache: usesMutations, + mutation: usesMutations, + mutationObserver: usesMutations, + suspenseQueryOptions: screen === 'polling', + suspenseInfiniteQueryOptions: screen === 'polling', + suspense: screen === 'polling', + QueryErrorResetBoundary: screen === 'polling', + errorBoundaryUtils: screen === 'polling', + fetchOptimistic: screen === 'polling', + refetchInterval: screen === 'polling', + infiniteQuery: false, + queryOptions: true, + infiniteQueryOptions: usesPages, + infiniteQueryObserver: usesPages, + infiniteQueryBehavior: usesPages, + select: screen === 'options', + placeholderData: screen === 'options', + serialScope: screen === 'options', + cacheOperations: screen === 'options', + queryCacheOperations: screen === 'options', + queryPredicates: screen === 'options', + } + for (const [feature, expected] of Object.entries(features)) { + const included = modules.some((id) => rendersFeature(id, feature)) + if (included !== expected) { + throw new Error( + `Unexpected ${feature} implementation in ${screen}: included=${included}`, + ) + } + } + const pageFetcher = retained.some( + ([id, module]) => + rendersFeature(id, 'infiniteQueryBehavior') && + module.renderedExports.includes('createInfiniteFetch'), + ) + assert.equal(pageFetcher, usesPages, `${screen} infinite page fetcher`) + const utilities = retained + .filter(([id]) => rendersFeature(id, 'utils')) + .flatMap(([, module]) => module.renderedExports) + assert( + utilities.includes('replaceEqualDeep') && + utilities.includes('replaceData'), + `${screen} is missing default structural sharing`, + ) + if (screen === 'query') { + assert( + !modules.some((id) => rendersFeature(id, 'throwOnError')), + 'Read-only list retained the optional throwOnError implementation', + ) + assert( + !utilities.includes('shouldThrowError'), + 'Read-only list retained the error boundary predicate', + ) + } + const selectedStatus = screen === 'polling' ? [] : ['isPending', 'isError'] + if (screen === 'paginated') selectedStatus.push('isFetching') + checkResultHelpers(retained, selectedStatus, screen) + checkClientOperations( + retained, + screen, + screen === 'options' ? 'invalidateQueries' : undefined, + ) + } +} + +const reactPeer = /^react(?:-dom)?(?:\/|$)/ + +function retainedExports(modules: Array) { + return new Map( + modules.map(([id, module]) => [id, new Set(module.renderedExports)]), + ) +} + +// v6 keeps some features inside classes. The emitted chunk's source map names +// their retained implementations even when the production minifier renames them. +function workloadFeatures( + packageName: Adapter, + chunk: Chunk, + modules: Array, +) { + const files = new Set(modules.map(([id]) => path.basename(id, '.js'))) + assert(chunk.map, 'Expected a source map for the attributed Query chunk') + const symbols = new Set(chunk.map.names) + const exports = new Set( + modules.flatMap(([, module]) => module.renderedExports), + ) + const stock = packageName === baseline + const bulk = [ + 'getQueriesData', + 'setQueriesData', + 'cancelQueries', + 'resetQueries', + ] + const features = { + 'Manual cached-query reset': stock + ? /\breset\(\)\{[^}]*\bthis\.resetState\b/.test(chunk.code) + : exports.has('resetCachedQuery'), + 'Cached-query invalidation and observer/fetch checks': stock + ? ['invalidate', 'getObserversCount', 'isFetched'].every((method) => + chunk.code.includes(`${method}(){`), + ) + : [ + 'invalidateCachedQuery', + 'getQueryObserverCount', + 'isQueryFetched', + ].some((operation) => exports.has(operation)), + 'Mutation cache': files.has('mutationCache'), + 'Serial mutation queues': stock + ? symbols.has('scopeFor') + : files.has('serialScope'), + 'Infinite page fetching': files.has('infiniteQueryBehavior'), + 'Interval polling': stock + ? symbols.has('#updateRefetchInterval') + : files.has('refetchInterval'), + 'Result selection and placeholder data': stock + ? symbols.has('selection') && symbols.has('#resolvePlaceholder') + : files.has('select') || files.has('placeholderData'), + 'Optimistic observer fetch (`fetchOptimistic`)': stock + ? chunk.code.includes('fetchOptimistic(') + : files.has('fetchOptimistic'), + 'Query error reset handling': files.has('QueryErrorResetBoundary'), + 'Bulk cache reads, writes, cancellation and reset': stock + ? bulk.every((method) => chunk.code.includes(`${method}(`)) + : bulk.some((operation) => exports.has(operation)), + } + return Object.entries(features) + .filter(([, included]) => included) + .map(([name]) => name) +} + +async function measure(packageName: Adapter, screen: Screen) { + const app = await buildApp(packageName, screen) + checkApp(app, packageName, screen) + + // Only published package JS from the appropriate checkout may enter the + // Query chunk. Keep the original app entrypoint so it drives tree-shaking. + const source = + packageName === baseline && baseCheckout ? baseCheckout : checkout + const owners = runtimeOwners(source, packageName) + const belongsToAdapter = (id: string) => + owners.some((dir) => id.startsWith(dir)) + checkPairOwnership( + renderedModules(app), + owners, + `${packageName} ${screen} app`, + ) + const attributed = await buildApp(packageName, screen, belongsToAdapter) + checkPairOwnership( + renderedModules(attributed), + owners, + `${packageName} ${screen} attribution`, + ) + const library = attributed.filter((chunk) => chunk.name === 'query-runtime') + const [queryChunk] = library + assert( + queryChunk && library.length === 1, + `Expected one Query chunk in ${packageName} ${screen}`, + ) + if (packageName === pluggable) { + checkOptimisticFetch(library, screen === 'polling', screen) + checkErrorReset(library, screen === 'polling', screen) + } + const actual = renderedModules(library) + const expected = renderedModules(app).filter(([id]) => belongsToAdapter(id)) + for (const dir of owners) { + if (!expected.some(([id]) => id.startsWith(dir))) { + throw new Error(`Missing Query runtime from ${dir} in ${screen}`) + } + } + assert.deepEqual( + retainedExports(actual), + retainedExports(expected), + `Query modules or exports differ from the production ${packageName} ${screen} app`, + ) + if ( + renderedModules(attributed.filter((chunk) => chunk !== queryChunk)).some( + ([id]) => belongsToAdapter(id), + ) || + [...queryChunk.imports, ...queryChunk.dynamicImports].some( + (id) => !reactPeer.test(id), + ) + ) { + throw new Error( + `Query runtime spans additional chunks in ${packageName} ${screen}`, + ) + } + const largestModules = actual + .sort(([, a], [, b]) => b.renderedLength - a.renderedLength) + .slice(0, 5) + .map(([id]) => + normalizePath(path.relative(path.join(source, 'packages'), id)), + ) + const js = Buffer.from(queryChunk.code) + return { + name: packageName, + library: { + raw: js.length, + gzip: gzipSync(js, { level: 9 }).length, + brotli: brotliCompressSync(js, { + params: { [constants.BROTLI_PARAM_QUALITY]: 11 }, + }).length, + }, + largestModules, + features: workloadFeatures(packageName, queryChunk, actual), + } +} + +// A combined app cannot tell whether each projection pulls in its sibling, +// or whether rendering a boundary pulls in paused-mutation restoration. +async function checkPluggableExports() { + const adapter = await import('@tanstack/react-query-pluggable') + const { QueryClient, QueriesObserver, notifyManager } = adapter + for (const alias of [ + 'fetchQuery', + 'fetchInfiniteQuery', + 'suspense', + 'suspenseQuery', + 'useBaseQuery', + 'useInfiniteQuery', + 'useSuspenseQuery', + 'useSuspenseInfiniteQuery', + ]) { + assert(!Object.hasOwn(adapter, alias), `Unexpected retired export ${alias}`) + } + const client = new QueryClient() + const key = ['public-export-probe'] + const initial = await adapter.query(client, { + queryKey: key, + queryFn: () => ({ titles: ['A'], page: 1 }), + }) + const updated = adapter.setQueryData(client, key, { + titles: ['A'], + page: 2, + }) + assert(updated) + assert.equal(updated.page, 2) + assert.strictEqual( + updated.titles, + initial.titles, + 'Default structural sharing', + ) + assert.deepEqual( + await adapter.infiniteQuery(client, { + queryKey: ['public-infinite-export-probe'], + initialPageParam: 0, + queryFn: ({ pageParam }) => pageParam, + getNextPageParam: () => undefined, + }), + { pages: [0], pageParams: [0] }, + ) + assert.deepEqual( + Object.getOwnPropertyNames(QueryClient.prototype), + ['constructor'], + 'QueryClient operations must be independently importable', + ) + if ( + 'getQueries' in QueriesObserver.prototype || + 'setBatchNotifyFunction' in notifyManager + ) { + throw new Error( + `${pluggable} exposed another adapter's observer or batch notification API`, + ) + } + for (const [type, members] of [ + [adapter.QueryObserver, ['fetchOptimistic']], + [adapter.QueryCache, ['find', 'findAll', 'clear']], + [ + adapter.Query, + [ + 'isActive', + 'isDisabled', + 'isStatic', + 'isStale', + 'reset', + 'invalidate', + 'getObserversCount', + 'isFetched', + ], + ], + ] as const) { + for (const member of members) + assert( + !(member in type.prototype), + `${type.name}.${member} would ship to every consumer`, + ) + } + const reactExports = { + useQuery: [], + queryOptions: ['queryOptions', 'queryObserver'], + infiniteQueryOptions: [ + 'infiniteQueryOptions', + 'infiniteQueryObserver', + 'queryObserver', + 'infiniteQueryBehavior', + ], + mutationOptions: [], + throwOnError: [ + 'queryOptions', + 'queryObserver', + 'throwOnError', + 'QueryErrorResetBoundary', + 'errorBoundaryUtils', + ], + suspenseQueryOptions: [ + 'suspenseQueryOptions', + 'queryObserver', + 'suspense', + 'QueryErrorResetBoundary', + 'errorBoundaryUtils', + 'fetchOptimistic', + ], + suspenseInfiniteQueryOptions: [ + 'suspenseInfiniteQueryOptions', + 'infiniteQueryObserver', + 'queryObserver', + 'infiniteQueryBehavior', + 'suspense', + 'QueryErrorResetBoundary', + 'errorBoundaryUtils', + 'fetchOptimistic', + ], + HydrationBoundary: ['infiniteQueryBehavior'], + } + const coreExports = { + ...Object.fromEntries(resultHelpers.map((name) => [name, ['queryResult']])), + fetchOptimistic: ['fetchOptimistic'], + infiniteQuery: ['infiniteQuery', 'infiniteQueryBehavior'], + QueryClient: [], + query: [], + setQueryData: [], + getMutationCache: ['mutationCache'], + select: ['select', 'projectResult'], + placeholderData: ['placeholderData', 'projectResult'], + serialScope: ['serialScope'], + findCachedQuery: ['queryCacheOperations', 'queryPredicates'], + findCachedQueries: ['queryCacheOperations', 'queryPredicates'], + clearQueryCache: ['queryCacheOperations'], + isQueryActive: ['queryPredicates'], + isQueryDisabled: ['queryPredicates'], + isQueryStatic: ['queryPredicates'], + isQueryStale: ['queryPredicates'], + isQueryFetched: ['queryPredicates'], + getQueryObserverCount: ['queryPredicates'], + resetCachedQuery: [], + invalidateCachedQuery: [], + ...Object.fromEntries( + Object.keys(bulkOperations).map((name) => [ + name, + ['cacheOperations', 'queryCacheOperations', 'queryPredicates'], + ]), + ), + dehydrate: [], + hydrate: [ + 'infiniteQueryBehavior', + 'mutation', + 'mutationCache', + 'serialScope', + ], + } + const expected: Record> = { + ...reactExports, + ...coreExports, + } + const features = new Set(Object.values(expected).flat()) + const entry = path.join(root, 'public-export-probe.ts') + for (const [name, required] of Object.entries(expected)) { + const coreOnly = Object.hasOwn(coreExports, name) + const source = coreOnly ? pluggableCore : pluggable + const results = await build({ + root, + configFile: false, + logLevel: 'error', + plugins: [ + { + name: 'import-one-public-export', + resolveId(id) { + if (id === entry) return id + if (id === pluggableCore) { + const importer = path.join( + checkout, + 'packages/react-query-pluggable/package.json', + ) + return this.resolve(id, importer, { skipSelf: true }) + } + return undefined + }, + load(id) { + if (id !== entry) return + if (name === 'throwOnError') { + return ` + import { queryOptions, throwOnError, useQuery } from '${source}' + export function useThrowingQuery() { + return useQuery(queryOptions({ queryKey: ['boundary-probe'], queryFn: () => 1, throwOnError: [throwOnError, true] })) + } + ` + } + return `export { ${name} } from '${source}'` + }, + }, + ], + build: { + write: false, + lib: { entry, formats: ['es'], fileName: 'probe' }, + rolldownOptions: { + external: reactPeer, + checks: { moduleLevelDirective: false }, + }, + }, + }) + assert(Array.isArray(results), 'Expected an ESM library build') + const chunks = results.flatMap(({ output }) => + output.filter((file) => file.type === 'chunk'), + ) + const modules = renderedModules(chunks) + const owners = coreOnly ? [pluggableCoreDirectory] : pluggableOwners + checkPairOwnership(modules, owners, `Importing ${name} from ${source}`) + if ( + coreOnly && + !modules.some(([id]) => id.startsWith(pluggableCoreDirectory)) + ) { + throw new Error( + `Core export ${name} did not render any code from ${source}`, + ) + } + if ( + coreOnly && + chunks.some((chunk) => + [...chunk.imports, ...chunk.dynamicImports].some((id) => + reactPeer.test(id), + ), + ) + ) { + throw new Error(`Core export ${name} imported React`) + } + for (const feature of features) { + // Suspense can share the error policy used by the explicit option helper. + if (feature === 'throwOnError' && required.includes('suspense')) continue + const included = modules.some(([id]) => rendersFeature(id, feature)) + if (included !== required.includes(feature)) { + throw new Error( + `Importing ${name} unexpectedly ${included ? 'included' : 'excluded'} ${feature}`, + ) + } + } + if (resultHelpers.includes(name)) checkResultHelpers(modules, [name], name) + if (!coreOnly) + checkErrorReset( + chunks, + required.includes('QueryErrorResetBoundary'), + name, + ) + if (!coreOnly || name === 'fetchOptimistic') + checkOptimisticFetch(chunks, required.includes('fetchOptimistic'), name) + if ( + ['QueryClient', 'query', 'infiniteQuery', 'setQueryData'].includes( + name, + ) || + Object.hasOwn(bulkOperations, name) || + Object.hasOwn(cacheHelpers, name) + ) { + checkClientOperations( + modules, + name, + name === 'QueryClient' ? undefined : name, + ) + } + } +} +await checkPluggableExports() + +const integer = new Intl.NumberFormat('en-US') +function formatChange(bytes: number, baselineBytes: number) { + const difference = bytes - baselineBytes + const sign = difference > 0 ? '+' : '' + const percent = ((100 * difference) / baselineBytes).toFixed(2) + return `${sign}${integer.format(difference)} B (${sign}${percent}%)` +} + +function formatSize(bytes: number, baselineBytes: number, isBaseline: boolean) { + const size = `${integer.format(bytes)} B` + if (isBaseline) return size + return `${size}
${formatChange(bytes, baselineBytes)}` +} + +function revision(directory: string) { + return execFileSync('git', ['-C', directory, 'rev-parse', 'HEAD'], { + encoding: 'utf8', + }).trim() +} + +const head = revision(root) +const base = baseCheckout ? revision(baseCheckout) : head +const lines = [ + '## React Query bundle size', + '', + '### Gzipped Query runtime', + '', + 'Each row compares the Query JavaScript used by the same app. The change is measured against v6 for that row. Negative values mean fewer bytes.', + '', + '| Workload | React Query v6 | React Query Pluggable | Change vs v6 |', + '| --- | ---: | ---: | ---: |', +] +const results = [] +for (const { screen, title } of workloads) { + const stock = await measure(baseline, screen) + const experiment = await measure(pluggable, screen) + results.push({ screen, title, rows: [stock, experiment] as const }) + const v6Gzip = stock.library.gzip + const pluggableGzip = experiment.library.gzip + lines.push( + `| ${title} | ${integer.format(v6Gzip)} B | ${integer.format(pluggableGzip)} B | ${formatChange(pluggableGzip, v6Gzip)} |`, + ) +} +lines.push( + '', + '### What each workload leaves out', + '', + 'These implementations are present in the v6 Query chunk and absent from the pluggable chunk for the same screen.', + '', + '| Workload | Code removed compared with v6 |', + '| --- | --- |', +) +for (const { + title, + rows: [stock, experiment], +} of results) { + const removed = stock.features.filter( + (feature) => !experiment.features.includes(feature), + ) + lines.push( + `| ${title} | ${removed.join(' · ') || 'None of the tracked features'} |`, + ) +} +lines.push( + '', + 'All four screens retain default structural sharing. Both bookmark screens retain mutation support. The selection screen retains invalidation and refetching. The polling screen retains Suspense, pagination and polling.', + '', + `Baseline adapter and core at \`${base}\` (${baseCheckout ? 'base checkout' : 'current checkout'}). Pluggable adapter, core and fixture at \`${head}\`.`, +) +lines.push( + '', + '
', + 'Query runtime sizes · minified JS, gzip and Brotli', + '', + 'The app entry drives tree-shaking. Each isolated ESM chunk includes the React adapter and its matching core. React and React DOM are external. Sizes are bytes of the Query chunk measured directly, with gzip level 9 and Brotli quality 11.', + '', + '| Workload | Package | Minified JS | Gzip | Brotli |', + '| --- | --- | ---: | ---: | ---: |', +) +for (const { title, rows } of results) { + const baselineSizes = rows[0].library + for (const row of rows) { + const cells = (['raw', 'gzip', 'brotli'] as const).map((metric) => + formatSize( + row.library[metric], + baselineSizes[metric], + row.name === baseline, + ), + ) + lines.push(`| ${title} | \`${row.name}\` | ${cells.join(' | ')} |`) + } +} +const comparison = { + root, + checkout, + baseCheckout, + baseline, + pluggable, + runtimeOwners, + formatChange, +} as const +const readOnly = results.find(({ screen }) => screen === 'query')?.rows[1] +assert(readOnly, 'Expected a read-only pluggable workload') +lines.push( + '', + `Largest modules in the read-only pluggable chunk, by rendered size before minification: ${readOnly.largestModules.map((name) => `\`${name}\``).join(', ')}.`, + '', + '
', + '', + await measureLazyRoutes(comparison), + '', + await measureMicrofrontends(comparison), + '', +) +const report = lines.join('\n') +await writeFile(path.join(root, 'dist/report.md'), report) +process.stdout.write(report) diff --git a/integrations/react/bundle-size/microfrontends.ts b/integrations/react/bundle-size/microfrontends.ts new file mode 100644 index 00000000000..169cfd44b52 --- /dev/null +++ b/integrations/react/bundle-size/microfrontends.ts @@ -0,0 +1,249 @@ +import assert from 'node:assert/strict' +import { cp, mkdir, writeFile } from 'node:fs/promises' +import path from 'node:path' +import { gzipSync } from 'node:zlib' +import { build } from 'vite' + +const screens = ['query', 'paginated'] as const +type Screen = (typeof screens)[number] +type Adapter = '@tanstack/react-query' | '@tanstack/react-query-pluggable' +const deployments = ['independent', 'shared'] as const +type Deployment = (typeof deployments)[number] + +// Both remotes use the host's React and React DOM. A shared Query deployment +// serves one ESM chunk at one URL; each remote still owns its QueryClient. +async function buildHost(root: string, directory: string) { + const peers: Record = { + react: + "export { default, createContext, use, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'", + dom: "export { createRoot } from 'react-dom/client'", + jsx: "export { Fragment, jsx, jsxs } from 'react/jsx-runtime'", + } + const input = { + navigation: path.join(root, 'host/navigation.ts'), + ...Object.fromEntries( + Object.keys(peers).map((name) => [name, 'host:' + name]), + ), + } + await build({ + root, + configFile: false, + publicDir: false, + logLevel: 'warn', + plugins: [ + { + name: 'microfrontend-host-peers', + resolveId(id) { + return id.startsWith('host:') ? '\0' + id : null + }, + load(id) { + if (!id.startsWith('\0host:')) return + return peers[id.slice(6)] + }, + }, + ], + build: { + outDir: path.join(directory, 'host'), + rolldownOptions: { + input, + preserveEntrySignatures: 'strict', + output: { entryFileNames: '[name].js' }, + }, + }, + }) +} + +function routeDirectory(deployment: Deployment, screen: Screen) { + return deployment === 'shared' ? '.' : './' + screen +} + +function shell(deployment: Deployment) { + const catalog = routeDirectory(deployment, 'query') + '/query.js' + const bookmarks = routeDirectory(deployment, 'paginated') + '/paginated.js' + return ` +Reading list + +
+` +} + +async function buildRemotes({ + root, + outDir, + included, + packageName, + owners, + packageScope, + pluggable, +}: { + root: string + outDir: string + included: ReadonlyArray + packageName: Adapter + owners: ReadonlyArray + packageScope: string + pluggable: Adapter +}) { + const entries = Object.fromEntries( + included.map((screen) => [screen, 'remote:' + screen]), + ) + const belongs = (id: string) => owners.some((dir) => id.startsWith(dir)) + const result = await build({ + root, + configFile: false, + publicDir: false, + base: './', + logLevel: 'warn', + resolve: { + alias: { + '#catalog-hooks': path.join( + root, + 'src', + packageName === pluggable ? 'pluggable-catalog.ts' : 'v6-catalog.ts', + ), + '#query-hooks': path.join( + root, + 'src', + packageName === pluggable ? 'pluggable-query.ts' : 'v6-query.ts', + ), + }, + }, + plugins: [ + { + name: 'microfrontend-routes', + enforce: 'pre', + resolveId(id, importer) { + if (id.startsWith('remote:')) + return path.join(root, 'src', 'remote.tsx') + '?' + id.slice(7) + if (id === '#screen') { + const screen = screens.find((name) => + importer?.endsWith('?' + name), + ) + assert.ok(screen, 'Missing remote screen in ' + importer) + return path.join(root, 'src', screen + '.tsx') + } + if (id === '#adapter') + return this.resolve(packageName, packageScope, { skipSelf: true }) + return null + }, + }, + ], + build: { + outDir, + rolldownOptions: { + input: entries, + preserveEntrySignatures: 'allow-extension', + external: /^react(?:-dom)?(?:\/|$)/, + checks: { moduleLevelDirective: false }, + output: { + entryFileNames: '[name].js', + chunkFileNames: '[name].js', + codeSplitting: { + groups: [ + { + name: 'query-runtime', + test: belongs, + includeDependenciesRecursively: false, + }, + ], + }, + }, + }, + }, + }) + assert.ok('output' in result, 'Expected one build output for ' + packageName) + const chunks = result.output.filter((chunk) => chunk.type === 'chunk') + const runtime = chunks.find((chunk) => chunk.name === 'query-runtime') + assert.ok(runtime, 'Missing Query runtime for ' + packageName) + const modules = Object.entries(runtime.modules).filter( + ([, mod]) => mod.renderedLength > 0, + ) + assert.ok(modules.every(([id]) => belongs(id))) + for (const owner of owners) + assert.ok(modules.some(([id]) => id.startsWith(owner))) + for (const chunk of chunks.filter((item) => item !== runtime)) { + assert.ok( + !Object.entries(chunk.modules).some( + ([id, mod]) => mod.renderedLength && belongs(id), + ), + ) + } + return gzipSync(runtime.code, { level: 9 }).length +} + +export async function measureMicrofrontends({ + root, + checkout, + baseCheckout, + baseline, + pluggable, + runtimeOwners, + formatChange, +}: { + root: string + checkout: string + baseCheckout?: string + baseline: Adapter + pluggable: Adapter + runtimeOwners: (directory: string, adapter: Adapter) => ReadonlyArray + formatChange: (bytes: number, baselineBytes: number) => string +}) { + const directory = path.join(root, 'dist', 'microfrontends') + await buildHost(root, directory) + const results: Array = [] + for (const deployment of deployments) { + async function measureAdapter(packageName: Adapter) { + const source = + packageName === baseline && baseCheckout ? baseCheckout : checkout + const name = path.basename(packageName) + const dir = path.join(directory, name, deployment) + const groups = + deployment === 'shared' + ? [screens] + : screens.map((screen) => [screen] as const) + let catalog = 0 + let journey = 0 + for (const included of groups) { + const prefix = routeDirectory(deployment, included[0]) + const size = await buildRemotes({ + root, + outDir: path.join(dir, prefix), + included, + packageName, + pluggable, + packageScope: path.join(source, 'packages', name, 'package.json'), + owners: runtimeOwners(source, packageName), + }) + if (included.includes('query')) catalog = size + journey += size + } + await mkdir(dir, { recursive: true }) + await cp(path.join(root, 'public'), dir, { recursive: true }) + await writeFile(path.join(dir, 'index.html'), shell(deployment)) + return { catalog, journey } + } + const stock = await measureAdapter(baseline) + const experimental = await measureAdapter(pluggable) + for (const [key, journey] of [ + ['catalog', 'Catalog only'], + ['journey', 'Catalog then bookmarks'], + ] as const) { + const base = stock[key] + const experiment = experimental[key] + const label = + deployment === 'shared' ? 'Shared Query chunk' : 'Query per remote' + results.push( + `| ${label} | ${journey} | ${base.toLocaleString('en-US')} B | ${experiment.toLocaleString('en-US')} B | ${formatChange(experiment, base)} |`, + ) + } + } + return [ + '### Microfrontend navigation', + '', + 'Cumulative Query JavaScript (gzip) from a cold catalog visit through the first visit to bookmarks. Both remotes share host React and React DOM. The independent builds serve distinct Query URLs. The shared build serves one Query chunk containing the features used across both routes. Chromium checks the requested Query URLs on each visit and revisit.', + '', + '| Deployment | Journey | React Query v6 | React Query Pluggable | Change vs v6 |', + '| --- | --- | ---: | ---: | ---: |', + ...results, + ].join('\n') +} diff --git a/integrations/react/bundle-size/package.json b/integrations/react/bundle-size/package.json new file mode 100644 index 00000000000..ce28804e3c9 --- /dev/null +++ b/integrations/react/bundle-size/package.json @@ -0,0 +1,30 @@ +{ + "name": "@tanstack/query-integration-react-bundle-size", + "private": true, + "type": "module", + "scripts": { + "test:types": "tsc -b && node check-editor.ts", + "measure": "node measure.ts", + "test:browser": "vitest run --config vitest.browser.config.ts", + "test:browser:ui": "vitest --watch --ui --config vitest.browser.config.ts", + "browser:install": "playwright install --with-deps --only-shell chromium" + }, + "dependencies": { + "@tanstack/react-query": "workspace:*", + "@tanstack/react-query-pluggable": "workspace:*", + "react": "catalog:", + "react-dom": "catalog:" + }, + "devDependencies": { + "@types/node": "^24.19.2", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@vitest/browser-playwright": "5.0.5", + "@vitest/ui": "5.0.5", + "playwright": "1.65.1", + "rollup-plugin-visualizer": "7.1.1", + "typescript": "catalog:", + "vite": "^8.3.8", + "vitest": "^5.0.5" + } +} diff --git a/integrations/react/bundle-size/public/books-1.json b/integrations/react/bundle-size/public/books-1.json new file mode 100644 index 00000000000..e64ec490101 --- /dev/null +++ b/integrations/react/bundle-size/public/books-1.json @@ -0,0 +1 @@ +{ "titles": ["Middlemarch", "Persuasion"], "next": 2 } diff --git a/integrations/react/bundle-size/public/books-2.json b/integrations/react/bundle-size/public/books-2.json new file mode 100644 index 00000000000..c58cb48908a --- /dev/null +++ b/integrations/react/bundle-size/public/books-2.json @@ -0,0 +1 @@ +{ "titles": ["Villette", "North and South"], "next": null } diff --git a/integrations/react/bundle-size/src/books.ts b/integrations/react/bundle-size/src/books.ts new file mode 100644 index 00000000000..1e40818494a --- /dev/null +++ b/integrations/react/bundle-size/src/books.ts @@ -0,0 +1,35 @@ +import type { + InfiniteData, + QueryKey, + UseInfiniteQueryOptions, + UseSuspenseInfiniteQueryOptions, +} from '#adapter' + +export interface BookPage { + titles: string[] + next: number | null +} + +export async function fetchBooks( + page: number, + signal: AbortSignal, +): Promise { + const response = await fetch(`./books-${page}.json`, { signal }) + if (!response.ok) throw new Error(`Could not load page ${page}`) + return response.json() as Promise +} + +export type BookPagesOptions = UseInfiniteQueryOptions< + BookPage, + Error, + InfiniteData, + QueryKey, + number +> +export type SuspenseBookPagesOptions = UseSuspenseInfiniteQueryOptions< + BookPage, + Error, + InfiniteData, + QueryKey, + number +> diff --git a/integrations/react/bundle-size/src/lazy/index.html b/integrations/react/bundle-size/src/lazy/index.html new file mode 100644 index 00000000000..3a83fc0e498 --- /dev/null +++ b/integrations/react/bundle-size/src/lazy/index.html @@ -0,0 +1,12 @@ + + + + + + Reading list + + +
+ + + diff --git a/integrations/react/bundle-size/src/lazy/main.tsx b/integrations/react/bundle-size/src/lazy/main.tsx new file mode 100644 index 00000000000..d62386360e1 --- /dev/null +++ b/integrations/react/bundle-size/src/lazy/main.tsx @@ -0,0 +1,80 @@ +import * as React from 'react' +import { createRoot } from 'react-dom/client' +import { QueryClient, QueryClientProvider } from '#adapter' +import { ReadingList as Catalog } from '../query.tsx' + +const LazyBookmarks = React.lazy(() => + import('../paginated.tsx').then(({ ReadingList }) => ({ + default: ReadingList, + })), +) +const client = new QueryClient({ + defaultOptions: { queries: { staleTime: Infinity } }, +}) + +function Bookmarks() { + return ( + Loading bookmarks…

}> + +
+ ) +} + +function Library() { + const [route, setRoute] = React.useState<'catalog' | 'bookmarks'>('catalog') + return ( + <> + +

{route === 'catalog' ? 'Catalog' : 'Bookmarks'}

+ {route === 'catalog' ? : } + + ) +} + +function ScrollingLibrary() { + const shelf = React.useRef(null) + const [showBookmarks, setShowBookmarks] = React.useState(false) + React.useEffect(() => { + const observer = new IntersectionObserver(([entry]) => { + if (entry.isIntersecting) { + setShowBookmarks(true) + observer.disconnect() + } + }) + observer.observe(shelf.current!) + return () => observer.disconnect() + }, []) + + return ( + <> +
+

Catalog

+ +
+
+

Bookmarks

+ {showBookmarks && } +
+ + ) +} + +const scrollLayout = + new URLSearchParams(location.search).get('layout') === 'scroll' + +createRoot(document.getElementById('root')!).render( + + {scrollLayout ? : } + , +) diff --git a/integrations/react/bundle-size/src/main.tsx b/integrations/react/bundle-size/src/main.tsx new file mode 100644 index 00000000000..9fa26663307 --- /dev/null +++ b/integrations/react/bundle-size/src/main.tsx @@ -0,0 +1,13 @@ +import * as React from 'react' +import { createRoot } from 'react-dom/client' +import { QueryClient, QueryClientProvider } from '#adapter' +import { ReadingList } from '#screen' + +const client = new QueryClient() + +createRoot(document.getElementById('root')!).render( + +

Reading list

+ +
, +) diff --git a/integrations/react/bundle-size/src/numeric-interval.ts b/integrations/react/bundle-size/src/numeric-interval.ts new file mode 100644 index 00000000000..b22ad6afd12 --- /dev/null +++ b/integrations/react/bundle-size/src/numeric-interval.ts @@ -0,0 +1 @@ +export const interval = 250 diff --git a/integrations/react/bundle-size/src/options.tsx b/integrations/react/bundle-size/src/options.tsx new file mode 100644 index 00000000000..2f275d731d9 --- /dev/null +++ b/integrations/react/bundle-size/src/options.tsx @@ -0,0 +1,68 @@ +import * as React from 'react' +import { useMutation, useQueryClient } from '#adapter' +import { + bookmarkScope, + previousPage, + refreshBookmarks, + selectTitles, +} from '#feature-options' +import { isError, isPending, useBookQuery } from '#query-hooks' +import { fetchBooks } from './books.ts' + +function savedBooks(): string[] { + return JSON.parse(localStorage.getItem('bookmarks') ?? '[]') as string[] +} + +export function ReadingList() { + const client = useQueryClient() + const [page, setPage] = React.useState(1) + const [events, setEvents] = React.useState([]) + const books = useBookQuery({ + queryKey: ['books', page], + queryFn: ({ signal }) => fetchBooks(page, signal), + select: selectTitles, + placeholderData: previousPage, + }) + const saved = useBookQuery({ queryKey: ['bookmarks'], queryFn: savedBooks }) + const bookmark = useMutation({ + scope: bookmarkScope, + mutationFn: async (title: string) => { + setEvents((items) => [...items, `Saving ${title}`]) + await Promise.resolve() + localStorage.setItem( + 'bookmarks', + JSON.stringify([...savedBooks(), title]), + ) + setEvents((items) => [...items, `Saved ${title}`]) + }, + onSuccess: () => refreshBookmarks(client), + }) + if (isPending(books)) return

Loading books…

+ if (isError(books)) return

{books.error.message}

+ return ( + <> +
    + {books.data.map((title) => ( +
  • {title}
  • + ))} +
+ {books.isPlaceholderData && ( +

Showing the previous page

+ )} + + +

Bookmarks: {saved.data?.join(', ')}

+
    + {events.map((event, index) => ( +
  1. {event}
  2. + ))} +
+ + ) +} diff --git a/integrations/react/bundle-size/src/paginated.tsx b/integrations/react/bundle-size/src/paginated.tsx new file mode 100644 index 00000000000..aeec60de82d --- /dev/null +++ b/integrations/react/bundle-size/src/paginated.tsx @@ -0,0 +1,52 @@ +import * as React from 'react' +import { queryOptions, mutationOptions, useMutation, useQuery } from '#adapter' +import { isError, isFetching, isPending, useBookPages } from '#query-hooks' +import { fetchBooks } from './books.ts' + +export function ReadingList() { + const books = useBookPages({ + queryKey: ['books'], + queryFn: ({ pageParam, signal }) => fetchBooks(pageParam, signal), + initialPageParam: 1, + getNextPageParam: (lastPage) => lastPage.next, + }) + const bookmark = useQuery( + queryOptions({ + queryKey: ['bookmark'], + queryFn: () => localStorage.getItem('bookmark'), + }), + ) + const save = useMutation( + mutationOptions({ + mutationFn: async (title: string) => + localStorage.setItem('bookmark', title), + onSuccess: () => bookmark.refetch(), + }), + ) + if (isPending(books)) return

Loading books…

+ if (isError(books)) return

{books.error.message}

+ return ( + <> + {bookmark.data &&

Bookmarked: {bookmark.data}

} +
    + {books.data.pages + .flatMap((page) => page.titles) + .map((title) => ( +
  • + {title}{' '} + +
  • + ))} +
+ {books.hasNextPage && ( + + )} + {save.isError &&

{save.error.message}

} + + ) +} diff --git a/integrations/react/bundle-size/src/pluggable-catalog.ts b/integrations/react/bundle-size/src/pluggable-catalog.ts new file mode 100644 index 00000000000..6a31eb565d1 --- /dev/null +++ b/integrations/react/bundle-size/src/pluggable-catalog.ts @@ -0,0 +1,10 @@ +import { queryOptions, useQuery } from '#adapter' +import type { UndefinedInitialDataOptions } from '#adapter' + +export function useBookQuery( + options: UndefinedInitialDataOptions, +) { + return useQuery(queryOptions(options)) +} + +export { isError, isPending } from '#adapter' diff --git a/integrations/react/bundle-size/src/pluggable-interval.ts b/integrations/react/bundle-size/src/pluggable-interval.ts new file mode 100644 index 00000000000..ca450d5790b --- /dev/null +++ b/integrations/react/bundle-size/src/pluggable-interval.ts @@ -0,0 +1,3 @@ +import { refetchInterval } from '#adapter' + +export const interval = refetchInterval(250) diff --git a/integrations/react/bundle-size/src/pluggable-options.ts b/integrations/react/bundle-size/src/pluggable-options.ts new file mode 100644 index 00000000000..803a35d3f9d --- /dev/null +++ b/integrations/react/bundle-size/src/pluggable-options.ts @@ -0,0 +1,16 @@ +import { + invalidateQueries, + placeholderData, + select, + serialScope, +} from '#adapter' +import type { QueryClient } from '#adapter' +import type { BookPage } from './books.ts' + +export const selectTitles = select((page: BookPage) => page.titles) +export const previousPage = placeholderData( + (previous: BookPage | undefined) => previous, +) +export const bookmarkScope = serialScope('bookmarks') +export const refreshBookmarks = (client: QueryClient) => + invalidateQueries(client, { queryKey: ['bookmarks'] }) diff --git a/integrations/react/bundle-size/src/pluggable-query.ts b/integrations/react/bundle-size/src/pluggable-query.ts new file mode 100644 index 00000000000..bf60d7a878f --- /dev/null +++ b/integrations/react/bundle-size/src/pluggable-query.ts @@ -0,0 +1,29 @@ +import { + infiniteQueryOptions, + suspenseQueryOptions, + suspenseInfiniteQueryOptions, + useQuery, +} from '#adapter' +import type { UseSuspenseQueryOptions } from '#adapter' +import type { + BookPage, + BookPagesOptions, + SuspenseBookPagesOptions, +} from './books.ts' + +export function useSuspenseBookQuery( + options: UseSuspenseQueryOptions, +) { + return useQuery(suspenseQueryOptions(options)) +} + +export function useBookPages(options: BookPagesOptions) { + return useQuery(infiniteQueryOptions(options)) +} + +export function useSuspenseBookPages(options: SuspenseBookPagesOptions) { + return useQuery(suspenseInfiniteQueryOptions(options)) +} + +export { isError, isPending, useBookQuery } from './pluggable-catalog.ts' +export { isFetching } from '#adapter' diff --git a/integrations/react/bundle-size/src/polling.tsx b/integrations/react/bundle-size/src/polling.tsx new file mode 100644 index 00000000000..c3183c8839f --- /dev/null +++ b/integrations/react/bundle-size/src/polling.tsx @@ -0,0 +1,92 @@ +import * as React from 'react' +import { interval } from '#polling-option' +import { + useBookPages, + useBookQuery, + useSuspenseBookPages, + useSuspenseBookQuery, +} from '#query-hooks' +import { fetchBooks } from './books.ts' +import type { UseQueryResult } from '#adapter' +import type { BookPage } from './books.ts' + +function options(name: string) { + return { + queryKey: ['books', name], + queryFn: ({ + pageParam, + signal, + }: { + pageParam?: unknown + signal: AbortSignal + }) => fetchBooks(typeof pageParam === 'number' ? pageParam : 1, signal), + refetchInterval: interval, + refetchIntervalInBackground: true, + } +} + +const pagination = { + initialPageParam: 1, + getNextPageParam: (page: BookPage) => page.next, +} + +function BookRow({ + label, + result, + page, +}: { + label: string + result: Pick + page: BookPage | undefined +}) { + return ( +
  • + {label}: {page?.titles.join(', ')}{' '} + {result.dataUpdatedAt > 0 && ( + + )} +
  • + ) +} + +function SuspenseBook() { + const result = useSuspenseBookQuery(options('suspense')) + return +} + +function SuspensePages() { + const result = useSuspenseBookPages({ + ...options('suspense-infinite'), + ...pagination, + }) + return ( + + ) +} + +export function ReadingList() { + const query = useBookQuery(options('query')) + const infinite = useBookPages({ ...options('infinite'), ...pagination }) + return ( +
      + + + Loading suspense query…}> + + + Loading suspense pages…}> + + +
    + ) +} diff --git a/integrations/react/bundle-size/src/query.tsx b/integrations/react/bundle-size/src/query.tsx new file mode 100644 index 00000000000..24899d1022d --- /dev/null +++ b/integrations/react/bundle-size/src/query.tsx @@ -0,0 +1,19 @@ +import * as React from 'react' +import { isError, isPending, useBookQuery } from '#catalog-hooks' +import { fetchBooks } from './books.ts' + +export function ReadingList() { + const books = useBookQuery({ + queryKey: ['books', 1], + queryFn: ({ signal }) => fetchBooks(1, signal), + }) + if (isPending(books)) return

    Loading books…

    + if (isError(books)) return

    {books.error.message}

    + return ( +
      + {books.data.titles.map((title) => ( +
    • {title}
    • + ))} +
    + ) +} diff --git a/integrations/react/bundle-size/src/remote.tsx b/integrations/react/bundle-size/src/remote.tsx new file mode 100644 index 00000000000..11308766250 --- /dev/null +++ b/integrations/react/bundle-size/src/remote.tsx @@ -0,0 +1,16 @@ +import * as React from 'react' +import { createRoot } from 'react-dom/client' +import { QueryClient, QueryClientProvider } from '#adapter' +import { ReadingList } from '#screen' +import type { MountRemote } from '../host/navigation.ts' + +export const mount: MountRemote = (container) => { + const root = createRoot(container) + const client = new QueryClient() + root.render( + + + , + ) + return () => root.unmount() +} diff --git a/integrations/react/bundle-size/src/screen-types.ts b/integrations/react/bundle-size/src/screen-types.ts new file mode 100644 index 00000000000..af6ab547c21 --- /dev/null +++ b/integrations/react/bundle-size/src/screen-types.ts @@ -0,0 +1,6 @@ +// Vite resolves #screen to one of these modules for each browser build. +export declare const ReadingList: + | typeof import('./query.tsx').ReadingList + | typeof import('./paginated.tsx').ReadingList + | typeof import('./polling.tsx').ReadingList + | typeof import('./options.tsx').ReadingList diff --git a/integrations/react/bundle-size/src/v6-catalog.ts b/integrations/react/bundle-size/src/v6-catalog.ts new file mode 100644 index 00000000000..b51fe308726 --- /dev/null +++ b/integrations/react/bundle-size/src/v6-catalog.ts @@ -0,0 +1,8 @@ +export { useQuery as useBookQuery } from '#adapter' + +export const isPending = ( + result: T, +): result is T & { isPending: true } => result.isPending +export const isError = ( + result: T, +): result is T & { isError: true } => result.isError diff --git a/integrations/react/bundle-size/src/v6-options.ts b/integrations/react/bundle-size/src/v6-options.ts new file mode 100644 index 00000000000..a390f6d0c03 --- /dev/null +++ b/integrations/react/bundle-size/src/v6-options.ts @@ -0,0 +1,8 @@ +import type { QueryClient } from '#adapter' +import type { BookPage } from './books.ts' + +export const selectTitles = (page: BookPage) => page.titles +export const previousPage = (previous: BookPage | undefined) => previous +export const bookmarkScope = { id: 'bookmarks' } +export const refreshBookmarks = (client: QueryClient) => + client.invalidateQueries({ queryKey: ['bookmarks'] }) diff --git a/integrations/react/bundle-size/src/v6-query.ts b/integrations/react/bundle-size/src/v6-query.ts new file mode 100644 index 00000000000..f3c7f31f019 --- /dev/null +++ b/integrations/react/bundle-size/src/v6-query.ts @@ -0,0 +1,14 @@ +import { infiniteQueryOptions, useInfiniteQuery } from '#adapter' +import type { BookPagesOptions } from './books.ts' + +export { + useSuspenseInfiniteQuery as useSuspenseBookPages, + useSuspenseQuery as useSuspenseBookQuery, +} from '#adapter' + +export function useBookPages(options: BookPagesOptions) { + return useInfiniteQuery(infiniteQueryOptions(options)) +} + +export { isError, isPending, useBookQuery } from './v6-catalog.ts' +export const isFetching = (result: { isFetching: boolean }) => result.isFetching diff --git a/integrations/react/bundle-size/tsconfig.json b/integrations/react/bundle-size/tsconfig.json new file mode 100644 index 00000000000..8c02fcb4c64 --- /dev/null +++ b/integrations/react/bundle-size/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ES2024", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2024", "DOM", "DOM.Iterable"], + "jsx": "react-jsx", + "strict": true, + "noEmit": true, + "outDir": "./.cache/test-types", + "skipLibCheck": true, + "allowImportingTsExtensions": true, + "erasableSyntaxOnly": true, + "verbatimModuleSyntax": true + }, + "files": [], + "references": [ + { "path": "./tsconfig.v6.json" }, + { "path": "./tsconfig.pluggable.json" }, + { "path": "./tsconfig.tools.json" } + ] +} diff --git a/integrations/react/bundle-size/tsconfig.pluggable.json b/integrations/react/bundle-size/tsconfig.pluggable.json new file mode 100644 index 00000000000..debd6b78436 --- /dev/null +++ b/integrations/react/bundle-size/tsconfig.pluggable.json @@ -0,0 +1,15 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "paths": { + "#adapter": ["./node_modules/@tanstack/react-query-pluggable"], + "#catalog-hooks": ["./src/pluggable-catalog.ts"], + "#query-hooks": ["./src/pluggable-query.ts"], + "#feature-options": ["./src/pluggable-options.ts"], + "#polling-option": ["./src/pluggable-interval.ts"], + "#screen": ["./src/screen-types.ts"] + } + }, + "include": ["src/**/*.ts", "src/**/*.tsx"], + "exclude": ["src/v6-*.ts", "src/numeric-interval.ts"] +} diff --git a/integrations/react/bundle-size/tsconfig.tools.json b/integrations/react/bundle-size/tsconfig.tools.json new file mode 100644 index 00000000000..891fb8b62d9 --- /dev/null +++ b/integrations/react/bundle-size/tsconfig.tools.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "include": ["*.ts", "browser/**/*.ts", "host/**/*.ts"] +} diff --git a/integrations/react/bundle-size/tsconfig.v6.json b/integrations/react/bundle-size/tsconfig.v6.json new file mode 100644 index 00000000000..a905219718e --- /dev/null +++ b/integrations/react/bundle-size/tsconfig.v6.json @@ -0,0 +1,15 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "paths": { + "#adapter": ["./node_modules/@tanstack/react-query"], + "#catalog-hooks": ["./src/v6-catalog.ts"], + "#query-hooks": ["./src/v6-query.ts"], + "#feature-options": ["./src/v6-options.ts"], + "#polling-option": ["./src/numeric-interval.ts"], + "#screen": ["./src/screen-types.ts"] + } + }, + "include": ["src/**/*.ts", "src/**/*.tsx"], + "exclude": ["src/pluggable-*.ts"] +} diff --git a/integrations/react/bundle-size/vitest.browser.config.ts b/integrations/react/bundle-size/vitest.browser.config.ts new file mode 100644 index 00000000000..b200c327367 --- /dev/null +++ b/integrations/react/bundle-size/vitest.browser.config.ts @@ -0,0 +1,68 @@ +import assert from 'node:assert/strict' +import { playwright } from '@vitest/browser-playwright' +import { defineConfig } from 'vitest/config' + +interface PollingGate { + requested: PromiseWithResolvers + response: PromiseWithResolvers +} + +declare module 'vitest/browser' { + interface BrowserCommands { + holdPollingBooks: (adapter: string) => Promise + waitForPollingRequest: (adapter: string) => Promise + releasePollingBooks: (adapter: string) => Promise + } +} + +const pendingBooks = new Map() +const booksUrl = (adapter: string) => `/polling/${adapter}/books-1.json` + +export default defineConfig({ + root: import.meta.dirname, + // Serve the measured apps from disk, including their production JS chunks. + publicDir: 'dist', + plugins: [ + { + name: 'hold-polling-fixtures', + configureServer(server) { + server.middlewares.use((request, response, next) => { + const gate = request.url && pendingBooks.get(request.url) + if (gate) { + gate.requested.resolve() + gate.response.promise.then(() => next(), next) + } else next() + }) + }, + }, + ], + test: { + include: ['browser/*.test.ts'], + browser: { + enabled: true, + headless: true, + provider: playwright(), + instances: [{ browser: 'chromium' }], + commands: { + holdPollingBooks(_, adapter: string) { + pendingBooks.set(booksUrl(adapter), { + requested: Promise.withResolvers(), + response: Promise.withResolvers(), + }) + }, + waitForPollingRequest(_, adapter: string) { + const gate = pendingBooks.get(booksUrl(adapter)) + assert(gate, 'Missing polling gate for ' + adapter) + return gate.requested.promise + }, + releasePollingBooks(_, adapter: string) { + const url = booksUrl(adapter) + const gate = pendingBooks.get(url) + assert(gate, 'Missing polling gate for ' + adapter) + gate.response.resolve() + pendingBooks.delete(url) + }, + }, + }, + }, +}) diff --git a/integrations/react/nodenext/README.md b/integrations/react/nodenext/README.md index 0cbec8b73d7..f724b66634e 100644 --- a/integrations/react/nodenext/README.md +++ b/integrations/react/nodenext/README.md @@ -6,6 +6,8 @@ Checks that `@tanstack/react-query` resolves and emits declarations under `modul - `src/hooks.ts` (ESM, since `package.json` sets `"type": "module"`) exports a hook that calls `useQuery`. - `tsconfig.json` sets `module` and `moduleResolution` to `nodenext` with `declaration` and `emitDeclarationOnly`, so TypeScript writes declarations to `dist/`. +- `src/sharedTypes.ts` augments each core’s `Register` independently, reads tagged keys through the matching client, and exports prepared query options through the published ESM entry points. +- The emitted declarations for regular and conditionally skipped queries must refer to public package names so another project can resolve them after installation. - The check runs with TypeScript 6, TypeScript 7.0, and TypeScript 7.1 (dev build) from the root `node_modules`. - CI runs the `test:types` script, which runs `test:types:ts6`, `test:types:ts7`, and `test:types:ts71`. diff --git a/integrations/react/nodenext/check-declarations.mjs b/integrations/react/nodenext/check-declarations.mjs new file mode 100644 index 00000000000..b8196fc1566 --- /dev/null +++ b/integrations/react/nodenext/check-declarations.mjs @@ -0,0 +1,19 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' + +const types = readFileSync( + new URL('./dist/sharedTypes.d.ts', import.meta.url), + 'utf8', +) +const publicPackages = new Set([ + '@tanstack/query-core', + '@tanstack/query-core-pluggable', + '@tanstack/react-query', + '@tanstack/react-query-pluggable', +]) +for (const [, specifier] of types.matchAll(/import\(["']([^"']+)["']\)/g)) { + assert.ok( + publicPackages.has(specifier), + 'Private declaration import: ' + specifier, + ) +} diff --git a/integrations/react/nodenext/package.json b/integrations/react/nodenext/package.json index c587035a285..11983a461bb 100644 --- a/integrations/react/nodenext/package.json +++ b/integrations/react/nodenext/package.json @@ -4,12 +4,15 @@ "type": "module", "scripts": { "test:types": "pnpm run test:types:ts6 && pnpm run test:types:ts7 && pnpm run test:types:ts71", - "test:types:ts6": "node ../../../node_modules/typescript/lib/tsc.js --pretty false --project tsconfig.json", - "test:types:ts7": "node ../../../node_modules/typescript70/lib/tsc.js --pretty false --project tsconfig.json", - "test:types:ts71": "node ../../../node_modules/typescript71/lib/tsc.js --pretty false --project tsconfig.json" + "test:types:ts6": "node ../../../node_modules/typescript/lib/tsc.js --pretty false --project tsconfig.json && node check-declarations.mjs", + "test:types:ts7": "node ../../../node_modules/typescript70/lib/tsc.js --pretty false --project tsconfig.json && node check-declarations.mjs", + "test:types:ts71": "node ../../../node_modules/typescript71/lib/tsc.js --pretty false --project tsconfig.json && node check-declarations.mjs" }, "dependencies": { - "@tanstack/react-query": "workspace:*" + "@tanstack/query-core": "workspace:*", + "@tanstack/query-core-pluggable": "workspace:*", + "@tanstack/react-query": "workspace:*", + "@tanstack/react-query-pluggable": "workspace:*" }, "devDependencies": { "@types/react": "^19.3.0" diff --git a/integrations/react/nodenext/src/sharedTypes.ts b/integrations/react/nodenext/src/sharedTypes.ts new file mode 100644 index 00000000000..0d82bc8ed74 --- /dev/null +++ b/integrations/react/nodenext/src/sharedTypes.ts @@ -0,0 +1,90 @@ +import { QueryClient as StockClient } from '@tanstack/query-core' +import { + QueryClient, + getQueryData, + query, +} from '@tanstack/query-core-pluggable' +import { queryOptions as stockOptions } from '@tanstack/react-query' +import { + infiniteQuery, + infiniteQueryOptions, + isSuccess, + queryOptions, + skipToken, + suspenseInfiniteQueryOptions, + suspenseQueryOptions, + useQuery, +} from '@tanstack/react-query-pluggable' +import type { QueryMeta as StockMeta } from '@tanstack/react-query' +import type { QueryMeta as PluggableMeta } from '@tanstack/react-query-pluggable' + +declare module '@tanstack/query-core' { + interface Register { + queryMeta: { shelf: 'stock' } + } +} +declare module '@tanstack/query-core-pluggable' { + interface Register { + queryMeta: { shelf: 'pluggable' } + } +} + +type Assert = Matches +type Same = [A, B] extends [B, A] ? true : false + +export type AdapterMetadata = [ + Assert>, + Assert>, +] + +const options = { queryKey: ['book'], queryFn: () => 'Dune' } +export const book = queryOptions(options) +export const cachedBook: typeof book = { ...book, staleTime: 30_000 } +const pageOptions = { + queryKey: ['books', 'pages'], + initialPageParam: 1, + queryFn: ({ pageParam }: { pageParam: number }) => ({ + page: pageParam, + title: 'Dune', + }), + getNextPageParam: (lastPage: { page: number }) => lastPage.page + 1, +} +export const paged = infiniteQueryOptions(pageOptions) +export const suspendedBook = suspenseQueryOptions(options) +export const suspendedPages = suspenseInfiniteQueryOptions(pageOptions) +export function optionalBook(enabled: boolean) { + return suspenseQueryOptions({ + ...options, + queryFn: enabled ? options.queryFn : skipToken, + }) +} +export function optionalPages(enabled: boolean) { + return suspenseInfiniteQueryOptions({ + ...pageOptions, + queryFn: enabled ? pageOptions.queryFn : skipToken, + }) +} +export const fromStock: string | undefined = new StockClient().getQueryData( + stockOptions(options).queryKey, +) +export const fromPluggable: string | undefined = getQueryData( + new QueryClient(), + book.queryKey, +) + +export function useFirstBookPage() { + const feed = useQuery(paged) + if (isSuccess(feed)) { + const cursor: number | undefined = feed.data.pageParams[0] + return { cursor, first: feed.data.pages[0] } + } +} + +export function readBook(client: QueryClient): Promise { + return query(client, book) +} + +export async function readPageCursors(client: QueryClient): Promise { + const data = await infiniteQuery(client, paged) + return data.pageParams +} diff --git a/knip.config.ts b/knip.config.ts index 802c9b9a485..79f6b779d35 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -1,6 +1,7 @@ import reactQueryDevtools from './packages/react-query-devtools/package.json' import reactQueryNextExperimental from './packages/react-query-next-experimental/package.json' import reactQueryPersistClient from './packages/react-query-persist-client/package.json' +import reactQueryPluggable from './packages/react-query-pluggable/package.json' import reactQuery from './packages/react-query/package.json' import type { KnipConfig } from 'knip' @@ -38,9 +39,24 @@ export default { entry: ['src/v4/**/*.cjs', 'src/v5/**/*.cjs'], ignore: ['**/__testfixtures__/**'], }, + 'packages/query-core-pluggable': { + // Copied v6 compatibility suites import helpers and types directly from these modules. + entry: [ + 'src/infiniteQueryBehavior.ts', + 'src/notifyManager.ts', + 'src/query.ts', + 'src/timeoutManager.ts', + 'src/utils.ts', + ], + }, 'packages/react-query': { ignoreDependencies: optionalPeerDependencies(reactQuery), }, + 'packages/react-query-pluggable': { + // These internal imports are exercised by the upstream compatibility suites. + entry: ['src/suspense.ts', 'tests/compat-*.ts'], + ignoreDependencies: optionalPeerDependencies(reactQueryPluggable), + }, 'packages/react-query-devtools': { ignoreDependencies: optionalPeerDependencies(reactQueryDevtools), }, diff --git a/nx.json b/nx.json index 84ef0aa852b..741140b3dd6 100644 --- a/nx.json +++ b/nx.json @@ -24,6 +24,21 @@ "!{projectRoot}/tests/**/*", "!{projectRoot}/eslint.config.js", "!{projectRoot}/oxlint.config.ts" + ], + "reactQueryCompatibility": [ + "{workspaceRoot}/scripts/test-react-query-compat.mjs", + "{workspaceRoot}/scripts/port-query-client-tests.mjs", + "{workspaceRoot}/scripts/port-query-projection-tests.mjs", + "{workspaceRoot}/scripts/port-query-result-tests.mjs", + "{workspaceRoot}/scripts/react-query-compat.config.ts", + "{workspaceRoot}/packages/query-core/src/__tests__/**/*", + "{workspaceRoot}/packages/query-core/vite.config.ts", + "{workspaceRoot}/packages/query-core-pluggable/tests/compat/*.patch", + "{workspaceRoot}/packages/react-query/src/__tests__/**/*", + "{workspaceRoot}/packages/react-query/test-setup.ts", + "{workspaceRoot}/packages/react-query/vite.config.ts", + "{workspaceRoot}/packages/query-persist-client-core/src/**/*", + "{workspaceRoot}/packages/query-test-utils/src/**/*" ] }, "targetDefaults": { diff --git a/packages/query-core-pluggable/README.md b/packages/query-core-pluggable/README.md new file mode 100644 index 00000000000..115bfae6356 --- /dev/null +++ b/packages/query-core-pluggable/README.md @@ -0,0 +1,55 @@ +# @tanstack/query-core-pluggable + +An experimental ESM query and mutation cache for JavaScript and TypeScript. It provides the runtime for `@tanstack/react-query-pluggable` and can also be used directly. + +Create a `QueryClient` and pass it as the first argument to each operation. This example fetches a list of titles, then marks the matching cached queries stale. + +```ts +import { + QueryClient, + query, + invalidateQueries, +} from '@tanstack/query-core-pluggable' + +const client = new QueryClient() + +const titles = await query(client, { + queryKey: ['books', 'featured'], + queryFn: async (): Promise => { + const response = await fetch('/api/featured-titles') + if (!response.ok) throw new Error('Could not load featured titles') + return response.json() + }, +}) + +await invalidateQueries(client, { queryKey: ['books'] }) +``` + +Import `infiniteQuery` for pagination, `refetchInterval` for observer polling, or `getMutationCache` to access the client's mutation cache. Pass the same client to the React adapter's `QueryClientProvider` to share cached data between direct calls and components. + +Use `findCachedQuery(cache, filters)` to look up a key, `findCachedQueries(cache, filters)` to filter a cache, and `clearQueryCache(cache)` to remove its queries. The predicates `isQueryActive(query)`, `isQueryDisabled(query)`, `isQueryStatic(query)`, and `isQueryStale(query)` inspect individual queries. Import `fetchOptimistic(client, observer, options)` when an observer needs a result as soon as data becomes available during a fetch. + +For code that already holds a cache entry, import the operation that takes that entry directly. + +| v6 method | Pluggable import | Effect | +| --------------------------- | ------------------------------ | ----------------------------------------------------------------------------- | +| `entry.invalidate()` | `invalidateCachedQuery(entry)` | Marks the entry invalidated and notifies its observers. | +| `entry.reset()` | `resetCachedQuery(entry)` | Cancels any active fetch and restores the entry's initial state. | +| `entry.getObserversCount()` | `getQueryObserverCount(entry)` | Counts subscribed observers, including disabled observers. | +| `entry.isFetched()` | `isQueryFetched(entry)` | Checks for a data or error update. Manual cache writes count as data updates. | + +The filtered client operations `invalidateQueries(client, filters)` and `resetQueries(client, filters)` also refetch eligible active matches by default. + +## Register application types + +Augment `Register` on `@tanstack/query-core-pluggable` to configure default errors, query and mutation keys, or metadata across the pluggable package pair. + +```ts +import '@tanstack/query-core-pluggable' + +declare module '@tanstack/query-core-pluggable' { + interface Register { + queryMeta: { requestId?: string } + } +} +``` diff --git a/packages/query-core-pluggable/oxlint.config.ts b/packages/query-core-pluggable/oxlint.config.ts new file mode 100644 index 00000000000..396987b4462 --- /dev/null +++ b/packages/query-core-pluggable/oxlint.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'oxlint' +import rootConfig from './root.oxlint.config.ts' + +export default defineConfig({ + extends: [rootConfig], + settings: rootConfig.settings, +}) diff --git a/packages/query-core-pluggable/package.json b/packages/query-core-pluggable/package.json new file mode 100644 index 00000000000..4943f5c50a1 --- /dev/null +++ b/packages/query-core-pluggable/package.json @@ -0,0 +1,54 @@ +{ + "name": "@tanstack/query-core-pluggable", + "version": "5.108.4", + "description": "Framework-agnostic query and mutation runtime with independently imported features", + "author": "tannerlinsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/TanStack/query.git", + "directory": "packages/query-core-pluggable" + }, + "homepage": "https://tanstack.com/query", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "scripts": { + "clean": "premove ./build ./coverage ./dist-ts ./.cache/test-types", + "compile": "tsc --project tsconfig.json", + "test:oxlint": "oxlint ./src", + "test:types": "npm-run-all --serial test:types:*", + "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts57 --tsBuildInfoFile .cache/test-types/ts57.tsbuildinfo", + "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts58 --tsBuildInfoFile .cache/test-types/ts58.tsbuildinfo", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts59 --tsBuildInfoFile .cache/test-types/ts59.tsbuildinfo", + "test:types:tscurrent": "tsc --project tsconfig.json --outDir .cache/test-types/tscurrent --tsBuildInfoFile .cache/test-types/tscurrent.tsbuildinfo", + "test:types:ts70": "node ../../node_modules/typescript70/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts70 --tsBuildInfoFile .cache/test-types/ts70.tsbuildinfo", + "test:types:ts71": "node ../../node_modules/typescript71/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts71 --tsBuildInfoFile .cache/test-types/ts71.tsbuildinfo", + "test:lib": "vitest", + "test:lib:dev": "pnpm run test:lib --watch", + "test:build": "publint --strict && attw --pack --profile esm-only", + "build": "tsdown --tsconfig tsconfig.prod.json" + }, + "type": "module", + "types": "./build/index.d.ts", + "main": "./build/index.js", + "react-native": "src/index.ts", + "exports": { + ".": { + "@tanstack/custom-condition": "./src/index.ts", + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "build", + "src", + "!src/__tests__" + ], + "devDependencies": { + "typescript": "catalog:" + } +} diff --git a/packages/query-core-pluggable/root.oxlint.config.ts b/packages/query-core-pluggable/root.oxlint.config.ts new file mode 120000 index 00000000000..56565c65534 --- /dev/null +++ b/packages/query-core-pluggable/root.oxlint.config.ts @@ -0,0 +1 @@ +../../oxlint.config.ts \ No newline at end of file diff --git a/packages/query-core-pluggable/root.tsdown.config.js b/packages/query-core-pluggable/root.tsdown.config.js new file mode 120000 index 00000000000..a997d5d337c --- /dev/null +++ b/packages/query-core-pluggable/root.tsdown.config.js @@ -0,0 +1 @@ +../../scripts/getTsdownConfig.js \ No newline at end of file diff --git a/packages/query-core-pluggable/src/__tests__/cacheOperations.test.ts b/packages/query-core-pluggable/src/__tests__/cacheOperations.test.ts new file mode 100644 index 00000000000..7a050069bb5 --- /dev/null +++ b/packages/query-core-pluggable/src/__tests__/cacheOperations.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it, vi } from 'vitest' +import { + QueryClient, + QueryObserver, + clearQueryClient, + getQueriesData, + getQueryCache, + getQueryObserverCount, + invalidateCachedQuery, + invalidateQueries, + isQueryFetched, + removeQueries, + resetCachedQuery, + setQueriesData, +} from '..' +import { getQueryData, getQueryState, setQueryData } from '../queryClient' + +describe('cache operations', () => { + it('applies imported cache operations to the supplied client', async () => { + const client = new QueryClient() + const otherClient = new QueryClient() + const filters = { queryKey: ['posts'] } + setQueryData(client, ['posts', 1], 2) + setQueryData(client, ['posts', 2], 3) + setQueryData(otherClient, ['posts', 1], 10) + + setQueriesData(client, filters, (count = 0) => count * 2) + expect(getQueriesData(client, filters)).toStrictEqual([ + [['posts', 1], 4], + [['posts', 2], 6], + ]) + await invalidateQueries(client, { ...filters, refetchType: 'none' }) + expect(getQueryState(client, ['posts', 1])?.isInvalidated).toBe(true) + removeQueries(client, filters) + expect(getQueriesData(client, filters)).toStrictEqual([]) + expect(getQueryData(otherClient, ['posts', 1])).toBe(10) + }) +}) + +describe('cached query operations', () => { + it('invalidates an observed query once without starting a fetch', () => { + const client = new QueryClient() + const queryFn = vi.fn<() => string>(() => 'fetched') + const options = { + queryKey: ['book'], + initialData: 'seed', + staleTime: Infinity, + queryFn, + } + const first = new QueryObserver(client, options) + const second = new QueryObserver(client, { ...options, enabled: false }) + const entry = first.getCurrentQuery() + + expect(getQueryObserverCount(entry)).toBe(0) + const unsubscribeFirst = first.subscribe(() => {}) + const unsubscribeSecond = second.subscribe(() => {}) + expect(getQueryObserverCount(entry)).toBe(2) + + const actions: Array = [] + const unsubscribeCache = getQueryCache(client).subscribe((event) => { + if (event.type === 'updated' && event.query === entry) { + actions.push(event.action.type) + } + }) + invalidateCachedQuery(entry) + invalidateCachedQuery(entry) + + expect(actions).toStrictEqual(['invalidate']) + expect(first.getCurrentResult().isStale).toBe(true) + expect(queryFn).not.toHaveBeenCalled() + expect(isQueryFetched(entry)).toBe(false) + + unsubscribeCache() + unsubscribeSecond() + expect(getQueryObserverCount(entry)).toBe(1) + unsubscribeFirst() + expect(getQueryObserverCount(entry)).toBe(0) + clearQueryClient(client) + }) + + it('restores initial data and clears recorded fetches after success or failure', async () => { + const client = new QueryClient() + const queryFn = vi.fn<() => Promise>() + const entry = new QueryObserver(client, { + queryKey: ['book'], + initialData: 'seed', + initialDataUpdatedAt: 123, + retry: false, + queryFn, + }).getCurrentQuery() + const initialState = entry.state + expect(isQueryFetched(entry)).toBe(false) + + queryFn.mockResolvedValueOnce('fresh') + await expect(entry.fetch()).resolves.toBe('fresh') + expect(isQueryFetched(entry)).toBe(true) + resetCachedQuery(entry) + expect(entry.state).toStrictEqual(initialState) + expect(isQueryFetched(entry)).toBe(false) + + queryFn.mockRejectedValueOnce(new Error('offline')) + await expect(entry.fetch()).rejects.toThrow('offline') + expect(isQueryFetched(entry)).toBe(true) + resetCachedQuery(entry) + expect(entry.state).toStrictEqual(initialState) + expect(isQueryFetched(entry)).toBe(false) + expect(queryFn).toHaveBeenCalledTimes(2) + clearQueryClient(client) + }) +}) diff --git a/packages/query-core-pluggable/src/__tests__/getMutationCache.test.ts b/packages/query-core-pluggable/src/__tests__/getMutationCache.test.ts new file mode 100644 index 00000000000..9796992740e --- /dev/null +++ b/packages/query-core-pluggable/src/__tests__/getMutationCache.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it, vi } from 'vitest' +import { + MutationCache, + MutationObserver, + QueryClient, + dehydrate, + getMutationCache, + hydrate, +} from '..' +import { + clearQueryClient, + getQueryData, + isMutating, + mutationCacheKey, + resumePausedMutations, + setQueryData, +} from '../queryClient' + +describe('getMutationCache', () => { + it('keeps query-only hydration, resume and clear free of mutation caches', async () => { + const server = new QueryClient() + const client = new QueryClient() + setQueryData(server, ['books'], ['Dune']) + hydrate(client, dehydrate(server)) + + expect(getQueryData(client, ['books'])).toStrictEqual(['Dune']) + expect(isMutating(client)).toBe(0) + await expect(resumePausedMutations(client)).resolves.toStrictEqual([]) + clearQueryClient(client) + expect(getQueryData(client, ['books'])).toBeUndefined() + expect(server[mutationCacheKey]).toBeUndefined() + expect(client[mutationCacheKey]).toBeUndefined() + }) + + it('creates a stable cache per client and reuses it across mutations and clear', async () => { + const first = new QueryClient() + const second = new QueryClient() + const cache = getMutationCache(first) + const otherCache = getMutationCache(second) + expect(cache).not.toBe(otherCache) + const mutation = new MutationObserver(first, { + mutationFn: (title: string) => Promise.resolve(title), + }) + + await mutation.mutate('Dune') + expect(cache.getAll().map((entry) => entry.state.data)).toStrictEqual([ + 'Dune', + ]) + expect(otherCache.getAll()).toStrictEqual([]) + clearQueryClient(first) + expect(cache.getAll()).toStrictEqual([]) + expect(getMutationCache(first)).toBe(cache) + }) + + it('uses an injected cache for the first mutation and its callbacks', async () => { + const onSuccess = vi.fn<() => void>() + const cache = new MutationCache({ onSuccess }) + const client = new QueryClient({ mutationCache: cache }) + const mutation = new MutationObserver(client, { + mutationKey: ['save'], + mutationFn: () => Promise.resolve('saved'), + }) + + await mutation.mutate() + expect(onSuccess).toHaveBeenCalledTimes(1) + expect(getMutationCache(client)).toBe(cache) + expect(cache.find({ mutationKey: ['save'] })?.state.data).toBe('saved') + clearQueryClient(client) + expect(cache.getAll()).toStrictEqual([]) + }) +}) diff --git a/packages/query-core-pluggable/src/__tests__/infiniteQuery.test.ts b/packages/query-core-pluggable/src/__tests__/infiniteQuery.test.ts new file mode 100644 index 00000000000..e41f9b079ca --- /dev/null +++ b/packages/query-core-pluggable/src/__tests__/infiniteQuery.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, expectTypeOf, it, vi } from 'vitest' +import { + QueryClient, + dehydrate, + getQueryCache, + hydrate, + infiniteQuery, + query, + refetchQueries, +} from '..' +import { + clearQueryClient, + getQueryData, + setQueryDefaults, +} from '../queryClient' +import type { InfiniteData } from '..' + +describe('infiniteQuery', () => { + it('retains the page fetcher if a cache listener replaces the query options', async () => { + const client = new QueryClient() + getQueryCache(client).subscribe((event) => { + if (event.type === 'updated' && event.action.type === 'fetch') { + event.query.setOptions({ + ...event.query.options, + queryFn: () => 'replacement', + }) + } + }) + const pages = await infiniteQuery(client, { + queryKey: ['infinite'], + queryFn: ({ pageParam }) => pageParam, + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage + 1, + pages: 2, + }) + expect(pages).toStrictEqual({ pages: [0, 1], pageParams: [0, 1] }) + + // An ordinary fetch looks up its query function when the retryer starts. + await expect( + query(client, { queryKey: ['ordinary'], queryFn: () => 'original' }), + ).resolves.toBe('replacement') + clearQueryClient(client) + }) + + it('refetches hydrated pages before any observer subscribes', async () => { + const server = new QueryClient() + const client = new QueryClient() + const queryKey = ['pages'] + const fetchPage = vi.fn<(context: { pageParam?: unknown }) => number>( + ({ pageParam }) => (typeof pageParam === 'number' ? pageParam : -1), + ) + const options = { + queryKey, + queryFn: fetchPage, + initialPageParam: 0, + getNextPageParam: (lastPage: number) => lastPage + 1, + pages: 2, + } + + const promise = infiniteQuery(server, options) + expectTypeOf(promise).toEqualTypeOf>>() + expect( + fetchPage.mock.calls.map(([context]) => context.pageParam), + ).toStrictEqual([0]) + await promise + + setQueryDefaults(client, queryKey, options) + hydrate(client, dehydrate(server)) + fetchPage.mockClear() + await refetchQueries(client, { queryKey }) + expect( + fetchPage.mock.calls.map(([context]) => context.pageParam), + ).toStrictEqual([0, 1]) + expect(getQueryData(client, queryKey)).toStrictEqual({ + pages: [0, 1], + pageParams: [0, 1], + }) + clearQueryClient(client) + clearQueryClient(server) + }) +}) diff --git a/packages/query-core-pluggable/src/__tests__/projection.test.ts b/packages/query-core-pluggable/src/__tests__/projection.test.ts new file mode 100644 index 00000000000..d6c189617fa --- /dev/null +++ b/packages/query-core-pluggable/src/__tests__/projection.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it, vi } from 'vitest' +import { QueryClient, QueryObserver, placeholderData, select } from '..' +import { getQueryData, setQueryData, setQueryDefaults } from '../queryClient' + +describe('projection options', () => { + it('reuses a stable selector and placeholder factory when option pairs are recreated', () => { + const client = new QueryClient() + const placeholder = vi.fn<() => { count: number }>(() => ({ count: 1 })) + const count = vi.fn<(value: { count: number }) => number>( + (value) => value.count, + ) + const options = () => ({ + queryKey: ['count'], + queryFn: () => Promise.resolve({ count: 2 }), + placeholderData: placeholderData(placeholder), + select: select(count), + }) + const observer = new QueryObserver(client, options()) + expect(observer.getCurrentResult()).toMatchObject({ + data: 1, + isPlaceholderData: true, + }) + observer.setOptions(options()) + expect(placeholder).toHaveBeenCalledTimes(1) + expect(count).toHaveBeenCalledTimes(1) + setQueryData(client, ['count'], { count: 2 }) + observer.setOptions(options()) + expect(observer.getCurrentResult()).toMatchObject({ + data: 2, + isPlaceholderData: false, + }) + }) + + it('keeps selection state and errors separate for observers sharing a default', () => { + const client = new QueryClient() + const transform = (value: unknown) => { + if (typeof value !== 'number') throw new TypeError('Expected a number') + return value * 2 + } + setQueryDefaults(client, ['entry'], { select: select(transform) }) + const a = new QueryObserver(client, { + queryKey: ['entry', 'a'], + queryFn: () => 2, + initialData: 2, + }) + const b = new QueryObserver(client, { + queryKey: ['entry', 'b'], + queryFn: () => 'invalid', + initialData: 'invalid', + }) + expect(a.getCurrentResult()).toMatchObject({ status: 'success', data: 4 }) + expect(b.getCurrentResult()).toMatchObject({ + status: 'error', + data: undefined, + error: expect.any(TypeError), + }) + expect(getQueryData(client, ['entry', 'b'])).toBe('invalid') + }) +}) diff --git a/packages/query-core-pluggable/src/__tests__/queryResult.test-d.tsx b/packages/query-core-pluggable/src/__tests__/queryResult.test-d.tsx new file mode 100644 index 00000000000..3dcff595f50 --- /dev/null +++ b/packages/query-core-pluggable/src/__tests__/queryResult.test-d.tsx @@ -0,0 +1,60 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { + isError, + isFetchPreviousPageError, + isFetchingNextPage, + isLoading, + isLoadingError, + isPending, + isRefetchError, + isSuccess, +} from '../queryResult' +import type { + DefinedQueryObserverResult, + InfiniteData, + InfiniteQueryObserverResult, + QueryObserverResult, +} from '../types' + +describe('query result type guards', () => { + it('narrows regular, nullable, defined and infinite results without losing their types', () => { + const regular = {} as QueryObserverResult + if (isPending(regular)) { + expectTypeOf(regular.data).toEqualTypeOf() + expectTypeOf(regular.error).toEqualTypeOf() + } + if (isLoading(regular)) + expectTypeOf(regular.fetchStatus).toEqualTypeOf<'fetching'>() + if (isError(regular)) + expectTypeOf(regular.error).toEqualTypeOf() + if (isLoadingError(regular)) + expectTypeOf(regular.data).toEqualTypeOf() + if (isRefetchError(regular)) + expectTypeOf(regular.data).toEqualTypeOf() + if (!isPending(regular) && !isError(regular)) + expectTypeOf(regular.data).toEqualTypeOf() + const selected = {} as DefinedQueryObserverResult< + string | undefined, + RangeError + > + if (isSuccess(selected)) + expectTypeOf(selected.data).toEqualTypeOf() + const pages = {} as InfiniteQueryObserverResult< + InfiniteData, + RangeError + > + if (isSuccess(pages)) { + expectTypeOf(pages.data.pages).toEqualTypeOf>() + expectTypeOf(pages.data.pageParams).toEqualTypeOf>() + expectTypeOf(pages.fetchNextPage).toEqualTypeOf< + typeof pages.fetchPreviousPage + >() + } + if (isFetchPreviousPageError(pages)) { + expectTypeOf(pages.error).toEqualTypeOf() + expectTypeOf(pages.fetchDirection).toEqualTypeOf<'backward'>() + } + if (isFetchingNextPage(pages)) + expectTypeOf(pages.fetchDirection).toEqualTypeOf<'forward'>() + }) +}) diff --git a/packages/query-core-pluggable/src/__tests__/queryResult.test.ts b/packages/query-core-pluggable/src/__tests__/queryResult.test.ts new file mode 100644 index 00000000000..839906dfb8e --- /dev/null +++ b/packages/query-core-pluggable/src/__tests__/queryResult.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it, vi } from 'vitest' +import { + InfiniteQueryObserver, + QueryClient, + QueryObserver, + setQueryData, +} from '..' +import { + isError, + isFetchNextPageError, + isFetchPreviousPageError, + isFetched, + isFetching, + isFetchingNextPage, + isFetchingPreviousPage, + isLoading, + isLoadingError, + isPaused, + isPending, + isRefetchError, + isRefetching, + isSuccess, +} from '../queryResult' + +describe('query result helpers', () => { + it('subscribes to status when a consumer only reads isPending', () => { + const client = new QueryClient() + const queryKey = ['tracked'] + const observer = new QueryObserver(client, { + queryKey, + queryFn: () => 'unused', + enabled: false, + }) + const tracked = vi.fn<(key: string) => void>() + const initial = observer.trackResult(observer.getCurrentResult(), tracked) + expect(isPending(initial)).toBe(true) + expect(tracked.mock.calls).toStrictEqual([['status']]) + const notify = vi.fn<() => void>() + const unsubscribe = observer.subscribe(notify) + try { + setQueryData(client, queryKey, 'first') + setQueryData(client, queryKey, 'second') + expect(notify).toHaveBeenCalledTimes(1) + const result = observer.getCurrentResult() + expect(isSuccess(result)).toBe(true) + expect(isFetched(result)).toBe(true) + expect(result.dataUpdateCount).toBe(2) + for (const field of [ + 'isPending', + 'isSuccess', + 'isError', + 'isFetched', + 'isFetching', + 'isRefetching', + ]) + expect(result).not.toHaveProperty(field) + } finally { + unsubscribe() + } + }) + + it('distinguishes a directional page request and error from a background refetch', async () => { + const request = Promise.withResolvers() + const observer = new InfiniteQueryObserver(new QueryClient(), { + queryKey: ['pages'], + initialPageParam: 1, + initialData: { pages: [1], pageParams: [1] }, + staleTime: Infinity, + retry: false, + queryFn: () => request.promise, + getNextPageParam: (page) => page + 1, + }) + const unsubscribe = observer.subscribe(() => {}) + try { + const next = observer.fetchNextPage() + const fetching = observer.getCurrentResult() + expect(isFetching(fetching)).toBe(true) + expect(isFetchingNextPage(fetching)).toBe(true) + expect(isFetchingPreviousPage(fetching)).toBe(false) + expect(isRefetching(fetching)).toBe(false) + request.reject(new Error('page unavailable')) + const failed = await next + expect(failed.fetchDirection).toBe('forward') + expect(isError(failed)).toBe(true) + expect(isFetchNextPageError(failed)).toBe(true) + expect(isFetchPreviousPageError(failed)).toBe(false) + expect(isLoadingError(failed)).toBe(false) + expect(isRefetchError(failed)).toBe(false) + expect(isLoading(failed)).toBe(false) + expect(isPaused(failed)).toBe(false) + } finally { + unsubscribe() + } + }) + + it('keeps the direction of a failed first page when there is no data', async () => { + const observer = new InfiniteQueryObserver(new QueryClient(), { + queryKey: ['empty-pages'], + enabled: false, + initialPageParam: 0, + retry: false, + queryFn: () => Promise.reject(new Error('first request failed')), + getNextPageParam: () => undefined, + }) + const unsubscribe = observer.subscribe(() => {}) + try { + const failed = await observer.fetchPreviousPage() + expect(failed.data).toBeUndefined() + expect(isLoadingError(failed)).toBe(true) + expect(isRefetchError(failed)).toBe(false) + expect(isFetchPreviousPageError(failed)).toBe(true) + expect(isFetchNextPageError(failed)).toBe(false) + } finally { + unsubscribe() + } + }) +}) diff --git a/packages/query-core-pluggable/src/__tests__/refetchInterval.test.ts b/packages/query-core-pluggable/src/__tests__/refetchInterval.test.ts new file mode 100644 index 00000000000..b9a89dc2a6c --- /dev/null +++ b/packages/query-core-pluggable/src/__tests__/refetchInterval.test.ts @@ -0,0 +1,152 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + MutationObserver, + QueryClient, + QueryObserver, + environmentManager, + focusManager, + infiniteQuery, + refetchInterval, +} from '..' + +const wasServer = environmentManager.isServer() + +describe('refetchInterval', () => { + beforeEach(() => { + vi.useFakeTimers() + environmentManager.setIsServer(() => false) + focusManager.setFocused(true) + }) + + afterEach(() => { + focusManager.setFocused(undefined) + environmentManager.setIsServer(() => wasServer) + vi.useRealTimers() + }) + + it('keeps the timer cadence on rerender and stops on option removal or unsubscribe', async () => { + const queryFn = vi.fn<() => number>(() => 1) + const options = { + queryKey: ['orders'], + queryFn, + initialData: 1, + staleTime: Infinity, + } + const observer = new QueryObserver(new QueryClient(), { + ...options, + refetchInterval: refetchInterval(100), + }) + const unsubscribe = observer.subscribe(() => {}) + await vi.advanceTimersByTimeAsync(90) + observer.setOptions({ ...options, refetchInterval: refetchInterval(100) }) + await vi.advanceTimersByTimeAsync(10) + expect(queryFn).toHaveBeenCalledTimes(1) + + observer.setOptions({ ...options, refetchInterval: refetchInterval(50) }) + await vi.advanceTimersByTimeAsync(50) + expect(queryFn).toHaveBeenCalledTimes(2) + observer.setOptions(options) + await vi.advanceTimersByTimeAsync(100) + expect(queryFn).toHaveBeenCalledTimes(2) + + observer.setOptions({ ...options, refetchInterval: refetchInterval(50) }) + unsubscribe() + await vi.advanceTimersByTimeAsync(100) + expect(queryFn).toHaveBeenCalledTimes(2) + }) + + it('respects data-dependent intervals, background changes and disabled observers', async () => { + const queryFn = vi.fn<() => number>(() => 2) + const options = { + queryKey: ['orders'], + queryFn, + initialData: 1, + staleTime: Infinity, + } + const client = new QueryClient() + const observer = new QueryObserver(client, { + ...options, + refetchInterval: (query) => + refetchInterval(query.state.data === 1 ? 100 : false), + }) + const unsubscribe = observer.subscribe(() => {}) + focusManager.setFocused(false) + await vi.advanceTimersByTimeAsync(100) + expect(queryFn).not.toHaveBeenCalled() + observer.setOptions({ + ...observer.options, + refetchIntervalInBackground: true, + }) + await vi.advanceTimersByTimeAsync(300) + expect(queryFn).toHaveBeenCalledTimes(1) + observer.setOptions({ + ...observer.options, + enabled: false, + refetchInterval: refetchInterval(100), + }) + await vi.advanceTimersByTimeAsync(100) + expect(queryFn).toHaveBeenCalledTimes(1) + unsubscribe() + }) + + it('shares a default polling option without sharing its timers', async () => { + const client = new QueryClient({ + defaultOptions: { + queries: { refetchInterval: refetchInterval(60), staleTime: Infinity }, + }, + }) + const first = vi.fn<() => number>(() => 1) + const second = vi.fn<() => number>(() => 2) + const a = new QueryObserver(client, { + queryKey: ['a'], + queryFn: first, + initialData: 1, + }) + const b = new QueryObserver(client, { + queryKey: ['b'], + queryFn: second, + initialData: 2, + }) + const unsubscribeA = a.subscribe(() => {}) + const unsubscribeB = b.subscribe(() => {}) + await vi.advanceTimersByTimeAsync(60) + unsubscribeA() + await vi.advanceTimersByTimeAsync(60) + expect(first).toHaveBeenCalledTimes(1) + expect(second).toHaveBeenCalledTimes(2) + unsubscribeB() + }) + + it('keeps server rendering free of polling timers', async () => { + environmentManager.setIsServer(() => true) + const queryFn = vi.fn<() => number>(() => 1) + const observer = new QueryObserver(new QueryClient(), { + queryKey: ['orders'], + queryFn, + initialData: 1, + staleTime: Infinity, + refetchInterval: refetchInterval(100), + }) + const unsubscribe = observer.subscribe(() => {}) + await vi.advanceTimersByTimeAsync(500) + expect(queryFn).not.toHaveBeenCalled() + unsubscribe() + }) + + it('supports mutations and infinite queries on a default client', async () => { + const client = new QueryClient() + const mutation = new MutationObserver(client, { + mutationFn: () => Promise.resolve(42), + }) + await expect(mutation.mutate()).resolves.toBe(42) + await expect( + infiniteQuery(client, { + queryKey: ['pages'], + initialPageParam: 1, + pages: 2, + queryFn: ({ pageParam }) => pageParam, + getNextPageParam: (page) => page + 1, + }), + ).resolves.toStrictEqual({ pages: [1, 2], pageParams: [1, 2] }) + }) +}) diff --git a/packages/query-core-pluggable/src/__tests__/serialScope.test.ts b/packages/query-core-pluggable/src/__tests__/serialScope.test.ts new file mode 100644 index 00000000000..d4b6889db23 --- /dev/null +++ b/packages/query-core-pluggable/src/__tests__/serialScope.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest' +import { + MutationObserver, + QueryClient, + dehydrate, + hydrate, + onlineManager, + serialScope, +} from '..' +import { clearQueryClient, resumePausedMutations } from '../queryClient' + +describe('serialScope', () => { + it('restores the queue from JSON and resumes its mutations in order', async () => { + const source = new QueryClient() + const started = Promise.withResolvers() + const release = Promise.withResolvers() + const events: Array = [] + const target = new QueryClient({ + defaultOptions: { + mutations: { + mutationFn: async (value) => { + events.push(`start ${value}`) + if (value === 1) { + started.resolve() + await release.promise + } + events.push(`finish ${value}`) + }, + }, + }, + }) + const wasOnline = onlineManager.isOnline() + try { + onlineManager.setOnline(false) + const observer = new MutationObserver(source, { + scope: serialScope('orders'), + mutationFn: (value: number) => Promise.resolve(value), + }) + const first = observer.mutate(1) + const second = observer.mutate(2) + const snapshot = JSON.parse(JSON.stringify(dehydrate(source))) + expect( + snapshot.mutations.map((m: { scope: unknown }) => m.scope), + ).toStrictEqual([{ id: 'orders' }, { id: 'orders' }]) + + hydrate(target, snapshot) + onlineManager.setOnline(true) + const resumed = resumePausedMutations(target) + await started.promise + expect(events).toStrictEqual(['start 1']) + release.resolve() + await resumed + expect(events).toStrictEqual([ + 'start 1', + 'finish 1', + 'start 2', + 'finish 2', + ]) + await resumePausedMutations(source) + await Promise.all([first, second]) + } finally { + release.resolve() + onlineManager.setOnline(wasOnline) + clearQueryClient(source) + clearQueryClient(target) + } + }) +}) diff --git a/packages/query-core-pluggable/src/cacheOperations.ts b/packages/query-core-pluggable/src/cacheOperations.ts new file mode 100644 index 00000000000..2e3f39f87ac --- /dev/null +++ b/packages/query-core-pluggable/src/cacheOperations.ts @@ -0,0 +1,280 @@ +import { notifyManager } from './notifyManager' +import { invalidateCachedQuery, resetCachedQuery } from './query' +import { findCachedQueries } from './queryCacheOperations' +import { getQueryCache, setQueryData } from './queryClient' +import { isQueryDisabled, isQueryStatic } from './queryPredicates' +import { noop } from './utils' +import type { QueryClient } from './queryClient' +import type { + CancelOptions, + InvalidateOptions, + InvalidateQueryFilters, + QueryKey, + RefetchOptions, + RefetchQueryFilters, + ResetOptions, + SetDataOptions, +} from './types' +import type { QueryFilters, Updater } from './utils' + +/** + * Imperative (non-reactive) way to retrieve the cached data of multiple queries at once. + * Only queries matching the given filters are returned; if none match, an empty array is + * returned. + * + * Because the matched queries can hold data of different shapes (e.g. a broad filter can match + * queries with unrelated data types), the `TQueryFnData` generic defaults to `unknown` rather + * than being inferred. Passing a more specific type is a convenience for call sites that know + * every matched query holds the same shape — it is not checked against the actual cache + * contents. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to read. + * @returns An array of query key and data pairs. The data is `undefined` for a query with no cached data. + * @see {@link getQueryData} + * @example + * ```ts + * const data = getQueriesData(queryClient, { queryKey: ['posts'] }) + * ``` + */ +export function getQueriesData< + TQueryFnData = unknown, + TQueryFilters extends QueryFilters = QueryFilters, +>( + client: QueryClient, + filters: TQueryFilters, +): Array<[QueryKey, TQueryFnData | undefined]> { + return findCachedQueries(getQueryCache(client), filters).map( + ({ queryKey, state }) => { + const data = state.data as TQueryFnData | undefined + return [queryKey, data] + }, + ) +} + +/** + * Synchronous way to immediately update the cached data of multiple queries at once, using + * filters or partial query key matching. Only queries that already exist and match the given + * filters are updated; no new cache entries are created. Internally this calls + * {@link setQueryData} for each matching query. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which existing queries to update. + * @param updater - Either the new data, or a function that receives each matched query's current + * data (which may be `undefined`) and returns the new data. + * @param options - Set `updatedAt` to override the timestamp the written data is recorded with. + * @returns One `[queryKey, data]` tuple per matched query, in the same shape and with the same + * `undefined` case as {@link setQueryData}. + * @example + * ```ts + * setQueriesData(queryClient, { queryKey: ['posts'] }, (oldPosts) => + * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts) + * ``` + */ +export function setQueriesData< + TQueryFnData, + TQueryFilters extends QueryFilters = QueryFilters, +>( + client: QueryClient, + filters: TQueryFilters, + updater: Updater< + NoInfer | undefined, + NoInfer | undefined + >, + options?: SetDataOptions, +): Array<[QueryKey, TQueryFnData | undefined]> { + return notifyManager.batch(() => + findCachedQueries(getQueryCache(client), filters).map(({ queryKey }) => [ + queryKey, + setQueryData(client, queryKey, updater, options), + ]), + ) +} + +/** + * Removes queries from the cache that match the given filters. Unlike + * {@link invalidateQueries} or {@link refetchQueries}, this removes + * matching queries from the cache instead of refetching them. Without filters, every query in + * the cache is removed. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to remove. Without filters, every query + * is removed. + * @example + * ```ts + * removeQueries(queryClient, { queryKey: ['posts'], exact: true }) + * ``` + */ +export function removeQueries( + client: QueryClient, + filters?: QueryFilters, +): void { + const queryCache = getQueryCache(client) + notifyManager.batch(() => { + findCachedQueries(queryCache, filters).forEach((query) => { + queryCache.remove(query) + }) + }) +} + +/** + * Resets queries matching the given filters back to their initial state (e.g. any + * `initialData`), notifying subscribers rather than removing them. Active queries among the + * matched set are then refetched, and the returned promise resolves once that refetch settles. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to reset. Without filters, every query + * is reset. + * @param options - Passed to the refetch of the active matched queries, e.g. `cancelRefetch` and + * `throwOnError`. + * @returns A promise that resolves once the refetch of the active matched queries settles. + * @example + * ```ts + * await resetQueries(queryClient, { queryKey: ['posts'], exact: true }) + * ``` + */ +export function resetQueries( + client: QueryClient, + filters?: QueryFilters, + options?: ResetOptions, +): Promise { + const queryCache = getQueryCache(client) + + return notifyManager.batch(() => { + const matched = findCachedQueries(queryCache, filters) + const queriesToRefetch = new Set(matched) + matched.forEach((query) => { + resetCachedQuery(query) + }) + return refetchQueries( + client, + { + type: 'active', + predicate: (query) => queriesToRefetch.has(query), + }, + options, + ) + }) +} + +/** + * Cancels outgoing fetches for queries matching the given filters. Most useful when performing + * optimistic updates, since any outgoing refetch that resolves afterwards would otherwise + * overwrite the optimistic update. By default (`revert: true`), a cancelled query's data is + * reverted to its state before the outgoing fetch started. + * + * The returned promise never rejects, even if individual cancellations fail. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to cancel. Without filters, every query + * is cancelled. + * @param cancelOptions - Passed to each matched query's cancellation. `revert` defaults to + * `true`. + * @returns A promise that resolves once every cancellation has settled. + * @example + * ```ts + * await cancelQueries(queryClient, { queryKey: ['posts'], exact: true }) + * ``` + */ +export function cancelQueries( + client: QueryClient, + filters?: QueryFilters, + cancelOptions: CancelOptions = {}, +): Promise { + const defaultedCancelOptions = { revert: true, ...cancelOptions } + + const promises = notifyManager.batch(() => + findCachedQueries(getQueryCache(client), filters).map((query) => + query.cancel(defaultedCancelOptions), + ), + ) + + return Promise.all(promises).then(noop, noop) +} + +/** + * Marks queries matching the given filters as invalidated. Unlike + * {@link removeQueries}, invalidated queries stay in the cache. + * + * Unless `filters.refetchType` is `'none'`, matching queries are then refetched via + * {@link refetchQueries}, using `filters.refetchType` if set, otherwise + * `filters.type`, otherwise `'active'`. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to invalidate, plus `refetchType` to + * control which of them to refetch afterwards. Without filters, every query is invalidated. + * @param options - Passed to {@link refetchQueries}, e.g. `cancelRefetch` and + * `throwOnError`. + * @returns A promise that resolves once the refetch settles, or immediately if `refetchType` is + * `'none'`. + * @example + * ```ts + * await invalidateQueries(queryClient, { queryKey: ['posts'], refetchType: 'active' }) + * ``` + */ +export function invalidateQueries( + client: QueryClient, + filters?: InvalidateQueryFilters, + options?: InvalidateOptions, +): Promise { + return notifyManager.batch(() => { + findCachedQueries(getQueryCache(client), filters).forEach((query) => { + invalidateCachedQuery(query) + }) + + if (filters?.refetchType === 'none') { + return Promise.resolve() + } + return refetchQueries( + client, + { + ...filters, + type: filters?.refetchType ?? filters?.type ?? 'active', + }, + options, + ) + }) +} + +/** + * Refetches queries matching the given filters, regardless of whether they are stale. Without + * filters, every query in the cache is refetched. Queries that are disabled, or static (only + * have observers with a static `staleTime`), are never refetched. + * + * By default (`cancelRefetch: true`), a currently running fetch is cancelled before the new + * one starts. The returned promise does not reject on individual query failures unless + * `throwOnError` is `true`. + * + * Initially paused fetches do not delay the returned promise. Their later errors are handled + * even when `throwOnError` is `true`. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to refetch. Without filters, every query + * in the cache is included. + * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling + * it, and `throwOnError` to `true` to reject when a refetch that was not initially paused fails. + * @returns A promise that resolves once all matching refetches that were not initially paused + * have settled. + * @example + * ```ts + * // refetch all active queries partially matching a query key: + * await refetchQueries(queryClient, { queryKey: ['posts'], type: 'active' }) + * ``` + */ +export function refetchQueries( + client: QueryClient, + filters?: RefetchQueryFilters, + options?: RefetchOptions, +): Promise { + const fetchOptions = { + ...options, + cancelRefetch: options?.cancelRefetch ?? true, + } + const promises = notifyManager.batch(() => + findCachedQueries(getQueryCache(client), filters) + .filter((query) => !isQueryDisabled(query) && !isQueryStatic(query)) + .map((query) => { + let promise = query.fetch(undefined, fetchOptions) + const isPaused = query.state.fetchStatus === 'paused' + if (!fetchOptions.throwOnError || isPaused) { + promise = promise.catch(noop) + } + return isPaused ? Promise.resolve() : promise + }), + ) + + return Promise.all(promises).then(noop) +} diff --git a/packages/query-core-pluggable/src/environmentManager.ts b/packages/query-core-pluggable/src/environmentManager.ts new file mode 100644 index 00000000000..6cdede3a64a --- /dev/null +++ b/packages/query-core-pluggable/src/environmentManager.ts @@ -0,0 +1,42 @@ +/** + * A function that returns whether the code is running on the server. + */ +export type IsServerValue = () => boolean + +const defaultIsServer = typeof window === 'undefined' || 'Deno' in globalThis + +let isServerFn: IsServerValue = () => defaultIsServer + +/** + * Returns whether the current runtime should be treated as a server environment. + * @returns `true` if the runtime is treated as a server. + */ +export const isServer = (): boolean => isServerFn() + +/** + * Manages how TanStack Query detects whether the current runtime should be treated as + * server-side, which disables scheduling refetch timers and changes the default `retry` count + * and `gcTime`. By default, the detection treats a missing `window` (or the presence of a + * `Deno` global) as server. + * + * Override this for runtimes where that default detection would give the wrong answer — for + * example, a Service Worker, where `window` is undefined even though the environment should + * behave like a client. + * @example + * ```ts + * import { environmentManager } from '@tanstack/query-core-pluggable' + * + * environmentManager.setIsServer(() => false) + * ``` + */ +export const environmentManager = { + isServer, + /** + * Overrides the server check globally. + * @param isServerValue - A function that returns whether the runtime should be treated as a + * server. + */ + setIsServer(isServerValue: IsServerValue): void { + isServerFn = isServerValue + }, +} diff --git a/packages/query-core-pluggable/src/fetchOptimistic.ts b/packages/query-core-pluggable/src/fetchOptimistic.ts new file mode 100644 index 00000000000..b8ca97e8793 --- /dev/null +++ b/packages/query-core-pluggable/src/fetchOptimistic.ts @@ -0,0 +1,67 @@ +import { defaultQueryOptions, getQueryCache } from './queryClient' +import type { QueryClient } from './queryClient' +import type { ObserverOptionsInput, QueryObserver } from './queryObserver' +import type { QueryKey, QueryObserverResult } from './types' + +/** + * Fetches a query defined by the given options without affecting this + * observer's own tracked query or result, and returns a promise that + * resolves with the `QueryObserverResult` for that fetch. This is useful + * for prefetching data that another observer (e.g. a query about to be + * navigated to) will need, ahead of time. + * @param client - The client that owns the observer and its query cache. + * @param observer - The observer that computes the result. + * @param options - The observer options of the query to fetch. + * @returns A promise that resolves with the result for the fetched query. + * @example + * ```ts + * const result = await fetchOptimistic(client, observer, { + * queryKey: ['posts', 2], + * queryFn: () => fetchPost(2), + * }) + * console.log(result.data) + * ``` + */ +export function fetchOptimistic< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + client: QueryClient, + observer: QueryObserver, + options: NoInfer< + ObserverOptionsInput + >, +): Promise> { + const defaultedOptions = defaultQueryOptions(client, options) + + const cache = getQueryCache(client) + const query = cache.build(client, defaultedOptions) + + const cached = Promise.withResolvers>() + const unsubscribe = cache.subscribe((event) => { + if ( + event.type === 'updated' && + event.query.queryHash === query.queryHash && + query.state.data !== undefined + ) { + unsubscribe() + cached.resolve(observer.createResult(query, defaultedOptions)) + } + }) + + return Promise.race([ + query + .fetch(defaultedOptions) + .then(() => { + const result = observer.createResult(query, defaultedOptions) + // Resolve the cache wait when the fetch succeeds. + cached.resolve(result) + return result + }) + .finally(unsubscribe), + cached.promise, + ]) +} diff --git a/packages/query-core-pluggable/src/focusManager.ts b/packages/query-core-pluggable/src/focusManager.ts new file mode 100644 index 00000000000..6a434c80af4 --- /dev/null +++ b/packages/query-core-pluggable/src/focusManager.ts @@ -0,0 +1,144 @@ +import { Subscribable } from './subscribable' + +type Listener = (focused: boolean) => void + +type SetupFn = ( + setFocused: (focused?: boolean) => void, +) => (() => void) | undefined + +/** + * The `FocusManager` manages the focus state within TanStack Query. + * + * It can be used to change the default event listeners or to manually change the focus state. + */ +export class FocusManager extends Subscribable { + #focused?: boolean + #cleanup?: () => void + + #setup: SetupFn + + constructor() { + super() + this.#setup = (onFocus) => { + // addEventListener does not exist in React Native, but window does + // oxlint-disable-next-line typescript/no-unnecessary-condition + if (typeof window !== 'undefined' && window.addEventListener) { + const listener = () => onFocus() + // Listen to visibilitychange + window.addEventListener('visibilitychange', listener, false) + + return () => { + // Be sure to unsubscribe if a new handler is set + window.removeEventListener('visibilitychange', listener) + } + } + return + } + } + + protected override onSubscribe(): void { + if (!this.#cleanup) { + this.setEventListener(this.#setup) + } + } + + protected override onUnsubscribe() { + if (!this.hasListeners()) { + this.#cleanup?.() + this.#cleanup = undefined + } + } + + /** + * `setEventListener` can be used to set a custom event listener that will + * be used to determine the focus state. The provided `setup` function + * receives a `setFocused` callback: call it with a `boolean` to manually + * set the focus state, or with no arguments to re-evaluate the current + * focus state and notify subscribers. + * @param setup - Receives the `setFocused` callback, registers the event listener, and may return + * a cleanup function that is called when the listener is replaced or no longer needed. + * @example + * ```ts + * import { focusManager } from '@tanstack/query-core-pluggable' + * + * focusManager.setEventListener((handleFocus) => { + * const listener = () => handleFocus() + * // Listen to visibilitychange + * if (typeof window !== 'undefined' && window.addEventListener) { + * window.addEventListener('visibilitychange', listener, false) + * } + * + * return () => { + * // Be sure to unsubscribe if a new handler is set + * window.removeEventListener('visibilitychange', listener) + * } + * }) + * ``` + */ + setEventListener(setup: SetupFn): void { + this.#setup = setup + this.#cleanup?.() + this.#cleanup = setup((focused) => { + if (typeof focused === 'boolean') { + this.setFocused(focused) + } else { + this.onFocus() + } + }) + } + + /** + * `setFocused` can be used to manually set the focus state. Set `undefined` + * to fall back to the default focus check. + * @param focused - The focus state, or `undefined` to use the default focus check. + * @example + * ```ts + * import { focusManager } from '@tanstack/query-core-pluggable' + * + * // Set focused + * focusManager.setFocused(true) + * + * // Set unfocused + * focusManager.setFocused(false) + * + * // Fallback to the default focus check + * focusManager.setFocused(undefined) + * ``` + */ + setFocused(focused?: boolean): void { + const changed = this.#focused !== focused + if (changed) { + this.#focused = focused + this.onFocus() + } + } + + /** + * `onFocus` notifies all subscribed listeners with the current focus state. + */ + onFocus(): void { + const isFocused = this.isFocused() + this.listeners.forEach((listener) => { + listener(isFocused) + }) + } + + /** + * `isFocused` can be used to get the current focus state. + * @returns The focus state set with `setFocused`, or otherwise whether the document is visible. + */ + isFocused(): boolean { + if (typeof this.#focused === 'boolean') { + return this.#focused + } + + // document global can be unavailable in react native + // oxlint-disable-next-line typescript/no-unnecessary-condition + return globalThis.document?.visibilityState !== 'hidden' + } +} + +/** + * Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query. + */ +export const focusManager = new FocusManager() diff --git a/packages/query-core-pluggable/src/hydration.ts b/packages/query-core-pluggable/src/hydration.ts new file mode 100644 index 00000000000..ff543b6bc37 --- /dev/null +++ b/packages/query-core-pluggable/src/hydration.ts @@ -0,0 +1,461 @@ +import { createInfiniteFetch } from './infiniteQueryBehavior' +import { Mutation } from './mutation' +import { + getDefaultOptions, + getQueryCache, + mutationCacheKey, +} from './queryClient' +import { serialScope } from './serialScope' +import { noop } from './utils' +import type { MutationState } from './mutation' +import type { Query, QueryState } from './query' +import type { QueryClient } from './queryClient' +import type { + DefaultError, + MutationKey, + MutationMeta, + MutationOptions, + MutationScope, + QueryKey, + QueryMeta, + QueryOptions, +} from './types' + +interface DehydratedMutation { + mutationKey?: MutationKey + state: MutationState + meta?: MutationMeta + scope?: MutationScope +} + +interface DehydratedQuery { + queryHash: string + queryKey: QueryKey + state: QueryState + dehydratedAt: number + promise?: Promise + meta?: QueryMeta + queryType?: 'infinite' +} + +// TYPES +type TransformerFn = (data: any) => any + +/** + * Options for `dehydrate`, controlling which queries/mutations are included in the resulting `DehydratedState` and + * how their data/errors are transformed before being serialized (e.g. for embedding in server-rendered markup). + */ +export interface DehydrateOptions { + /** Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. */ + serializeData?: TransformerFn + /** Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. */ + shouldDehydrateMutation?: (mutation: Mutation) => boolean + /** Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. */ + shouldDehydrateQuery?: (query: Query) => boolean + /** + * Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted + * (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the + * given error, in which case the original error is kept. + */ + shouldRedactErrors?: (error: unknown) => boolean +} + +/** + * Options for `hydrate`, controlling the default options applied to queries/mutations restored from a + * `DehydratedState`, and how to reverse any transformation applied by `DehydrateOptions.serializeData`. + */ +export interface HydrateOptions { + /** Options applied to the queries and mutations restored from the dehydrated state. */ + defaultOptions?: { + /** Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. */ + deserializeData?: TransformerFn + /** Default options merged into every query restored from the dehydrated state. */ + queries?: QueryOptions + /** Default options merged into every mutation restored from the dehydrated state. */ + mutations?: MutationOptions + } +} + +/** + * Reads the value of a promise synchronously if it has already resolved, e.g. a thenable that + * resolves within its `then` call. + * @param promise - The promise to read. + * @returns An object with the resolved `data`, or `undefined` if the promise hasn't resolved + * synchronously (or resolved with `undefined`). + */ +function tryResolveSync(promise: PromiseLike) { + let data: unknown + + const thenResult = promise.then((result) => { + data = result + return result + }, noop) as Partial> | undefined + + // A synchronous thenable may return an object without a catch method. + thenResult?.catch?.(noop) + + if (data !== undefined) { + return { data } + } + + return undefined +} + +// FUNCTIONS + +/** + * Dehydrates a single `Mutation` into a serializable snapshot of its key, state, scope, and meta. + * @param mutation - The mutation to dehydrate. + * @returns The dehydrated mutation. + */ +function dehydrateMutation(mutation: Mutation): DehydratedMutation { + return { + mutationKey: mutation.options.mutationKey, + state: mutation.state, + ...(mutation.options.scope && { scope: { id: mutation.options.scope.id } }), + ...(mutation.meta && { meta: mutation.meta }), + } +} + +/** + * Prepares the in-flight promise of a pending query for dehydration: applies `serializeData` to its + * result, and redacts its rejection error unless `shouldRedactErrors` returns `false` for it. + * @param query - The pending query whose promise is dehydrated. + * @param serializeData - Optional transform applied to the resolved data. + * @param shouldRedactErrors - Optional predicate; if it returns `false` for the rejection error, + * that + * error is kept as-is instead of being redacted. + * @returns The transformed promise, or `undefined` if the query has no in-flight promise. + */ +function dehydratePromise( + query: Query, + serializeData?: TransformerFn, + shouldRedactErrors?: (error: unknown) => boolean, +): Promise | undefined { + const promise = query.promise?.then(serializeData).catch((error) => { + if (shouldRedactErrors?.(error) === false) { + // Reject original error if it should not be redacted + return Promise.reject(error) + } + // If not in production, log original error before rejecting redacted error + if (process.env.NODE_ENV !== 'production') { + console.error( + `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`, + ) + } + return Promise.reject(new Error('redacted')) + }) + + // Avoid unhandled promise rejections + // We need the promise we dehydrate to reject to get the correct result into + // the query cache, but we also want to avoid unhandled promise rejections + // in whatever environment the prefetches are happening in. + promise?.catch(noop) + + return promise +} + +/** + * Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot. Note that most query config (e.g. + * `queryFn`, `staleTime`) is not dehydrated but instead meant to be configured again when consuming the + * de/rehydrated data, typically with `useQuery` on the client. If the query is still `pending`, its in-flight + * promise is dehydrated too so it can be resumed on the other side instead of re-fetched. + * @param query - The query to dehydrate. + * @param serializeData - Optional transform applied to `query.state.data` before it is included in the snapshot. + * @param shouldRedactErrors - Optional predicate; if it returns `false` for the promise's rejection error, that + * error is kept as-is instead of being redacted. + * @returns The dehydrated query. + */ +export function dehydrateQuery( + query: Query, + serializeData?: TransformerFn, + shouldRedactErrors?: (error: unknown) => boolean, +): DehydratedQuery { + return { + dehydratedAt: Date.now(), + state: { + ...query.state, + ...(query.state.data !== undefined && { + data: serializeData + ? serializeData(query.state.data) + : query.state.data, + }), + }, + queryKey: query.queryKey, + queryHash: query.queryHash, + ...(query.state.status === 'pending' && { + promise: dehydratePromise(query, serializeData, shouldRedactErrors), + }), + ...(query.meta && { meta: query.meta }), + ...(query.queryType && { queryType: query.queryType }), + } +} + +/** + * The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only dehydrates mutations that are + * currently paused (e.g. paused by `networkMode` while offline). + * @param mutation - The mutation to check. + * @returns `true` if the mutation is paused. + */ +export function defaultShouldDehydrateMutation(mutation: Mutation) { + return mutation.state.isPaused +} + +/** + * The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only dehydrates queries whose status is + * `'success'`. + * @param query - The query to check. + * @returns `true` if the query's status is `'success'`. + */ +export function defaultShouldDehydrateQuery(query: Query) { + return query.state.status === 'success' +} + +/** + * Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain, serializable `DehydratedState`, + * typically to embed in server-rendered markup and later restore into a client-side `QueryClient` via `hydrate`. + * Which queries/mutations are included, and how their data/errors are transformed, is controlled by `options`, + * falling back to the client's `dehydrate` default options, and finally to `defaultShouldDehydrateQuery` / + * `defaultShouldDehydrateMutation`. + * @param client - The client whose cache is dehydrated. + * @param options - Controls which queries and mutations are included and how their data and errors + * are transformed. Each option falls back to the client's `defaultOptions.dehydrate`. + * @returns The dehydrated state, with the included `queries` and `mutations`. + * @example + * ```ts + * const queryClient = new QueryClient() + * + * await query(queryClient, { + * queryKey: ['posts'], + * queryFn: getPosts, + * }) + * + * const dehydratedState = dehydrate(queryClient) + * ``` + */ +export function dehydrate( + client: QueryClient, + options: DehydrateOptions = {}, +): DehydratedState { + const filterMutation = + options.shouldDehydrateMutation ?? + getDefaultOptions(client).dehydrate?.shouldDehydrateMutation ?? + defaultShouldDehydrateMutation + + const mutations = + client[mutationCacheKey] + ?.getAll() + .flatMap((mutation) => + filterMutation(mutation) ? [dehydrateMutation(mutation)] : [], + ) ?? [] + + const filterQuery = + options.shouldDehydrateQuery ?? + getDefaultOptions(client).dehydrate?.shouldDehydrateQuery ?? + defaultShouldDehydrateQuery + + const shouldRedactErrors = + options.shouldRedactErrors ?? + getDefaultOptions(client).dehydrate?.shouldRedactErrors + + const serializeData = + options.serializeData ?? getDefaultOptions(client).dehydrate?.serializeData + + const queries = getQueryCache(client) + .getAll() + .flatMap((query) => + filterQuery(query) + ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] + : [], + ) + + return { mutations, queries } +} + +/** + * Restores a `DehydratedState` (as produced by `dehydrate`) into a `QueryClient`'s cache, typically to seed the + * client with data already fetched on the server. `mutations` and `queries` are each optional on `dehydratedState`. + * Queries not yet in the cache are built from the dehydrated snapshot; queries that already exist are only updated + * when the dehydrated data is newer than what's already cached. Newly built queries have their `fetchStatus` reset + * to `'idle'` so they don't hydrate stuck in a fetching state. If a dehydrated query still had an in-flight + * promise, it is resumed via `query.fetch()` (reusing that promise as `initialPromise`) rather than re-invoking + * `queryFn`. + * @param client - The client whose cache is restored into. + * @param dehydratedState - The dehydrated state, e.g. produced by `dehydrate` on the server. + * @param options - `defaultOptions` merged into every restored query and mutation (on top of the + * client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`. + * @example + * ```ts + * // dehydratedState was produced by `dehydrate` on the server + * // and sent to the client, e.g. embedded in server-rendered markup. + * const queryClient = new QueryClient() + * + * hydrate(queryClient, dehydratedState) + * ``` + */ +export function hydrate( + client: QueryClient, + dehydratedState: Partial, + options?: HydrateOptions, +): void { + dehydratedState.mutations?.forEach(({ state, scope, ...mutationOptions }) => { + Mutation.build( + client, + { + ...getDefaultOptions(client).hydrate?.mutations, + ...options?.defaultOptions?.mutations, + ...mutationOptions, + ...(scope && { scope: serialScope(scope.id) }), + }, + state, + ) + }) + + if (dehydratedState.queries) + hydrateQueries(client, dehydratedState.queries, options) +} + +/** + * Restores just the queries accepted by a React hydration boundary. + * @internal + * @param client - The client receiving the entries. + * @param queries - The serialized query entries. + * @param options - Query restoration settings. + */ +export function hydrateQueries( + client: QueryClient, + queries: Array, + options?: HydrateOptions, +): void { + const queryCache = getQueryCache(client) + const deserializeData = + options?.defaultOptions?.deserializeData ?? + getDefaultOptions(client).hydrate?.deserializeData + + queries.forEach( + ({ + queryKey, + state, + queryHash, + meta, + promise, + dehydratedAt, + queryType, + }) => { + const syncData = promise ? tryResolveSync(promise) : undefined + const rawData = state.data === undefined ? syncData?.data : state.data + const data = + rawData === undefined + ? rawData + : deserializeData + ? deserializeData(rawData) + : rawData + + let query = queryCache.get(queryHash) + const existingQueryIsPending = query?.state.status === 'pending' + const existingQueryIsFetching = query?.state.fetchStatus === 'fetching' + + // Do not hydrate if an existing query exists with newer data + if (query) { + const hasNewerSyncData = + syncData && dehydratedAt > query.state.dataUpdatedAt + if ( + state.dataUpdatedAt > query.state.dataUpdatedAt || + hasNewerSyncData + ) { + // Omit fetchStatus from dehydrated state so that query stays in its current fetchStatus + const { fetchStatus: _ignored, ...serializedState } = state + query.setState({ + ...serializedState, + data, + // If the query was pending at the moment of dehydration, but resolved to have data + // before hydration, we can assume the query should be hydrated as successful. + // + // Since you can opt into dehydrating failed queries, and those can have data from + // previous successful fetches, we make sure we only do this for pending queries. + ...(state.status === 'pending' && + data !== undefined && { + status: 'success' as const, + dataUpdatedAt: dehydratedAt, + // Preserve existing fetchStatus if the existing query is actively fetching. + ...(!existingQueryIsFetching && { + fetchStatus: 'idle' as const, + }), + }), + }) + } + } else { + // Restore query + query = queryCache.build( + client, + { + ...getDefaultOptions(client).hydrate?.queries, + ...options?.defaultOptions?.queries, + queryKey, + queryHash, + meta, + ...(queryType === 'infinite' && { + _type: queryType, + _prepareInfiniteFetch: createInfiniteFetch, + }), + }, + // Reset fetch status to idle to avoid + // query being stuck in fetching state upon hydration + { + ...state, + data, + fetchStatus: 'idle', + // Like above, if the query was pending at the moment of dehydration but has data, + // we can assume it should be hydrated as successful. + status: + state.status === 'pending' && data !== undefined + ? 'success' + : state.status, + ...(state.status === 'pending' && + data !== undefined && { + dataUpdatedAt: dehydratedAt, + }), + }, + ) + } + + if ( + promise && + // If the data was synchronously available, there is no need to set up + // a retryer and thus no reason to call fetch + !syncData && + !existingQueryIsPending && + !existingQueryIsFetching && + // Only hydrate if dehydration is newer than any existing data, + // this is always true for new queries + dehydratedAt > query.state.dataUpdatedAt + ) { + // This doesn't actually fetch - it just creates a retryer + // which will re-use the passed `initialPromise` + query + .fetch(undefined, { + // RSC transformed promises are not thenable + initialPromise: Promise.resolve(promise).then(deserializeData), + }) + // Avoid unhandled promise rejections + .catch(noop) + } + }, + ) +} + +/** + * A serializable snapshot of a `QueryClient`'s cache, as produced by `dehydrate` and consumed by `hydrate`. Typically + * transported from server to client (e.g. embedded in server-rendered markup) to seed the client's cache with data + * that has already been fetched, avoiding a redundant fetch on the client. + */ +export interface DehydratedState { + /** + * The dehydrated mutations, by default only the paused ones. + */ + mutations: Array + /** + * The dehydrated queries, by default only the successful ones. + */ + queries: Array +} diff --git a/packages/query-core-pluggable/src/index.ts b/packages/query-core-pluggable/src/index.ts new file mode 100644 index 00000000000..f84e385ca80 --- /dev/null +++ b/packages/query-core-pluggable/src/index.ts @@ -0,0 +1,236 @@ +/* istanbul ignore file */ + +export { + getQueriesData, + setQueriesData, + removeQueries, + resetQueries, + cancelQueries, + invalidateQueries, + refetchQueries, +} from './cacheOperations' +export { environmentManager } from './environmentManager' +export { infiniteQuery } from './infiniteQuery' +export { fetchOptimistic } from './fetchOptimistic' +export { focusManager } from './focusManager' +export type { FocusManager } from './focusManager' +export { + hydrateQueries, + defaultShouldDehydrateMutation, + defaultShouldDehydrateQuery, + dehydrate, + dehydrateQuery, + hydrate, +} from './hydration' +export type { + DehydratedState, + HydrateOptions, + DehydrateOptions, +} from './hydration' +export { InfiniteQueryObserver } from './infiniteQueryObserver' +export { Mutation } from './mutation' +export type { MutationState } from './mutation' +export { MutationCache, getMutationCache } from './mutationCache' +export type { + MutationCacheNotifyEvent, + MutationCacheConfig, +} from './mutationCache' +export { MutationObserver } from './mutationObserver' +export { defaultScheduler, notifyManager } from './notifyManager' +export { onlineManager } from './onlineManager' +export type { OnlineManager } from './onlineManager' +export { placeholderData } from './placeholderData' +export type { Select, PlaceholderData } from './projectionTypes' +export { QueriesObserver } from './queriesObserver' +export type { + QueriesObserverOptions, + QueriesObserverResultReader, +} from './queriesObserver' +export { Query, invalidateCachedQuery, resetCachedQuery } from './query' +export type { QueryState } from './query' +export { QueryCache } from './queryCache' +export { + clearQueryCache, + findCachedQuery, + findCachedQueries, +} from './queryCacheOperations' +export { + getQueryObserverCount, + isQueryFetched, + isQueryActive, + isQueryDisabled, + isQueryStale, + isQueryStatic, +} from './queryPredicates' +export type { QueryCacheNotifyEvent, QueryCacheConfig } from './queryCache' +export { + getQueryCache, + mountQueryClient, + unmountQueryClient, + QueryClient, + countFetchingQueries, + isMutating, + getQueryData, + setQueryData, + getQueryState, + query, + resumePausedMutations, + getDefaultOptions, + setDefaultOptions, + setQueryDefaults, + getQueryDefaults, + setMutationDefaults, + getMutationDefaults, + defaultQueryOptions, + defaultMutationOptions, + clearQueryClient, +} from './queryClient' +export { QueryObserver } from './queryObserver' +export type { QueryObserverResultReader } from './queryObserver' +export { + isPending, + isSuccess, + isError, + isFetching, + isPaused, + isLoading, + isRefetching, + isLoadingError, + isRefetchError, + isFetched, + isFetchingNextPage, + isFetchingPreviousPage, + isFetchNextPageError, + isFetchPreviousPageError, +} from './queryResult' +export { refetchInterval } from './refetchInterval' +export type { RefetchInterval } from './refetchInterval' +export { CancelledError } from './retryer' +export { select } from './select' +export { serialScope } from './serialScope' +export type { SerialScope } from './serialScope' +export { streamedQuery } from './streamedQuery' +export { timeoutManager } from './timeoutManager' +export type { + TimeoutManager, + ManagedTimerId, + TimeoutCallback, + TimeoutProvider, +} from './timeoutManager' +export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './types' +export type { + OmitKeyof, + QueryKey, + QueryObserverResult, + DefaultedQueryObserverOptions, + ThrowOnError, + QueryErrorBoundaryOption, + QueryErrorBoundaryPolicy, + QueryFunction, + StaleTimeFunction, + QueryBooleanOption, + QueryPersister, + QueryFunctionContext, + PlaceholderDataFunction, + QueryOptions, + QueryObserverOptions, + InfiniteQueryObserverOptions, + DefaultedInfiniteQueryObserverOptions, + QueryExecuteOptions, + InfiniteQueryExecuteOptions, + InvalidateQueryFilters, + RefetchQueryFilters, + MutationFunctionContext, + MutationFunction, + MutationOptions, + MutationObserverOptions, + MutateOptions, + MutateFunctionRest, + MutateFunction, + MutationObserverBaseResult, + MutationObserverIdleResult, + MutationObserverLoadingResult, + MutationObserverErrorResult, + MutationObserverSuccessResult, + MutationObserverResult, + QueryClientConfig, + DefaultOptions, + NonUndefinedGuard, + DistributiveOmit, + Override, + Register, + DefaultError, + UnsetMarker, + AnyDataTag, + DataTag, + QueryKeyWithDataTag, + InferDataFromTag, + InferErrorFromTag, + StaleTime, + InitialDataFunction, + QueriesPlaceholderDataFunction, + EqualityFn, + CacheKeyHashFunction, + CacheKeyConfig, + GetPreviousPageParamFunction, + GetNextPageParamFunction, + InfiniteData, + QueryMeta, + NetworkMode, + NotifyOnChangeProps, + InitialPageParam, + InfiniteQueryPageParamsOptions, + WithRequired, + ResultOptions, + RefetchOptions, + InvalidateOptions, + ResetOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + QueryStatus, + FetchStatus, + QueryObserverBaseResult, + QueryObserverPendingResult, + QueryObserverLoadingResult, + QueryObserverLoadingErrorResult, + QueryObserverRefetchErrorResult, + QueryObserverSuccessResult, + QueryObserverPlaceholderResult, + DefinedQueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from './types' +export { + shouldThrowError, + hashKey, + noop, + partialMatchKey, + replaceEqualDeep, + defaultQueryFn, + skipToken, + keepPreviousData, + matchMutation, + matchQuery, +} from './utils' +export type { + DefaultQueryFn, + SkipToken, + Updater, + MutationFilters, + QueryFilters, +} from './utils' diff --git a/packages/query-core-pluggable/src/infiniteQuery.ts b/packages/query-core-pluggable/src/infiniteQuery.ts new file mode 100644 index 00000000000..a901149cedf --- /dev/null +++ b/packages/query-core-pluggable/src/infiniteQuery.ts @@ -0,0 +1,105 @@ +import { infiniteFetchOptions } from './infiniteQueryBehavior' +import { query } from './queryClient' +import type { QueryClient, WithoutSkipToken } from './queryClient' +import type { + DefaultError, + InfiniteData, + InfiniteQueryExecuteOptions, + QueryKey, +} from './types' + +/** + * Asynchronous method to fetch and cache an infinite query, resolving with an + * {@link InfiniteData} object or throwing with the error. + * + * Requires `initialPageParam` and `getNextPageParam`. Use `pages` to specify how many + * pages to fetch. If you omit `pages`, the client fetches up to the number of cached + * pages, or one page if the cache has no pages. + * If shared infinite query options contain `skipToken` as their `queryFn`, the call skips fetching + * and resolves with existing data or `undefined` on a cache miss. Use {@link getQueryData} + * to read the cache directly. + * @param client - The client that stores the query. + * @param options - The query to fetch and the options that control which pages to fetch. + * @returns A promise that resolves to the {@link InfiniteData}, or to the result of `select` if + * provided. It rejects with the error from the fetch or from `select`. + * @example + * ```ts + * try { + * const data = await infiniteQuery(queryClient, { + * queryKey, + * queryFn, + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextCursor, + * }) + * console.log(data.pages) + * } catch (error) { + * console.log(error) + * } + * ``` + */ +export function infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + client: QueryClient, + options: WithoutSkipToken< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + >, +): Promise< + Array extends Array> + ? InfiniteData + : TData +> +export function infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + client: QueryClient, + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): Promise< + | undefined + | (Array extends Array> + ? InfiniteData + : TData) +> +export function infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + client: QueryClient, + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): Promise< + | undefined + | (Array extends Array> + ? InfiniteData + : TData) +> { + return query(client, infiniteFetchOptions(options) as any) +} diff --git a/packages/query-core-pluggable/src/infiniteQueryBehavior.ts b/packages/query-core-pluggable/src/infiniteQueryBehavior.ts new file mode 100644 index 00000000000..94b70bba2ef --- /dev/null +++ b/packages/query-core-pluggable/src/infiniteQueryBehavior.ts @@ -0,0 +1,231 @@ +import { + addConsumeAwareSignal, + addToArray, + ensureQueryFn, + fetchSignal, +} from './utils' +import type { FetchContext, FetchOptions, Query } from './query' +import type { QueryClient } from './queryClient' +import type { + DefaultError, + InfiniteData, + InfiniteQueryPageParamsOptions, +} from './types' +import type { FetchSignalContext } from './utils' + +/** + * Captures the options and cached pages for this fetch before the cache notifies listeners. + * @param client - Client that owns the query. + * @param query - The cached infinite query. + * @param fetchOptions - Options for the fetch in progress. + * @param addSignal - Attaches the query's cancellation signal without consuming it. + * @returns The fetcher to use for the first attempt and subsequent retries. + */ +export function createInfiniteFetch( + client: QueryClient, + query: Query, + fetchOptions: FetchOptions | undefined, + addSignal: (context: object) => asserts context is { signal: AbortSignal }, +) { + const { queryKey, options, state } = query as Query< + unknown, + DefaultError, + InfiniteData + > + const context = { client, queryKey, options, state, fetchOptions } + addSignal(context) + return prepareInfiniteFetch(context, query) +} + +/** + * Creates the page fetcher for an infinite query. A retry continues from the + * failed page. A new fetch starts with the most recently cached pages. + * @param context - The fetch in progress, including its options and cached pages. + * @param query - The query supplied to a custom persister. + * @returns A fetcher that resumes pagination at the failed page on retry. + */ +export function prepareInfiniteFetch( + context: Omit< + FetchContext>, + 'fetchFn' + >, + query: Query, +) { + const options = context.options as InfiniteQueryPageParamsOptions & { + pages?: number + } + const direction = context.fetchOptions?.meta?.fetchMore?.direction + const oldPages = context.state.data?.pages || [] + const oldPageParams = context.state.data?.pageParams || [] + let result: InfiniteData = { pages: [], pageParams: [] } + let currentPage = 0 + + const fetchFn = async () => { + let cancelled = false + const signalContext: FetchSignalContext = context + const queryFn = ensureQueryFn(context.options, context.fetchOptions) + + // Create function to fetch a page + const fetchPage = async ( + data: InfiniteData, + param: unknown, + previous?: boolean, + ): Promise> => { + if (cancelled) { + return Promise.reject(context.signal.reason) + } + + if (param == null && data.pages.length) { + return Promise.resolve(data) + } + + const queryFnContext = addConsumeAwareSignal( + { + client: context.client, + queryKey: context.queryKey, + pageParam: param, + meta: context.options.meta, + }, + () => context.signal, + () => (cancelled = true), + signalContext[fetchSignal], + ) + + const page = await queryFn(queryFnContext) + + const { maxPages } = context.options + return { + pages: addToArray(data.pages, page, maxPages, previous), + pageParams: addToArray(data.pageParams, param, maxPages, previous), + } + } + + // fetch next / previous page? + if (direction && oldPages.length) { + const previous = direction === 'backward' + const pageParamFn = previous ? getPreviousPageParam : getNextPageParam + const oldData = { + pages: oldPages, + pageParams: oldPageParams, + } + const param = pageParamFn(options, oldData) + + result = await fetchPage(oldData, param, previous) + } else { + const remainingPages = options.pages ?? oldPages.length + + // Fetch all pages + do { + const param = + currentPage === 0 + ? oldPageParams[0] === undefined + ? options.initialPageParam + : oldPageParams[0] + : getNextPageParam(options, result) + if (currentPage > 0 && param == null) { + break + } + result = await fetchPage(result, param) + currentPage++ + } while (currentPage < remainingPages) + } + + return result + } + if (context.options.persister) { + return () => { + return context.options.persister?.( + fetchFn as any, + { + client: context.client, + queryKey: context.queryKey, + meta: context.options.meta, + signal: context.signal, + }, + query, + ) + } + } + return fetchFn +} + +/** + * Computes the page param of the page after the last one, with the `getNextPageParam` option. + * @param options - The infinite query options. + * @param data - The current pages and page params. + * @returns The next page param, or `undefined` if there are no pages yet. + */ +function getNextPageParam( + options: InfiniteQueryPageParamsOptions, + { pages, pageParams }: InfiniteData, +): unknown | undefined { + return pages.length > 0 + ? options.getNextPageParam( + pages.at(-1), + pages, + pageParams.at(-1), + pageParams, + ) + : undefined +} + +/** + * Computes the page param of the page before the first one, with the `getPreviousPageParam` + * option. + * @param options - The infinite query options. + * @param data - The current pages and page params. + * @returns The previous page param, or `undefined` if there are no pages yet or no + * `getPreviousPageParam` option. + */ +function getPreviousPageParam( + options: InfiniteQueryPageParamsOptions, + { pages, pageParams }: InfiniteData, +): unknown | undefined { + return pages.length > 0 + ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) + : undefined +} + +/** + * Checks if there is a next page. + * @param options - The infinite query options with `getNextPageParam`. + * @param data - The current pages and page params. + * @returns `true` if `getNextPageParam` returns a value other than `null` or `undefined`. + */ +export function hasNextPage( + options: InfiniteQueryPageParamsOptions, + data?: InfiniteData, +): boolean { + if (!data) return false + return getNextPageParam(options, data) != null +} + +/** + * Checks if there is a previous page. + * @param options - The infinite query options with `getPreviousPageParam`. + * @param data - The current pages and page params. + * @returns `true` if `getPreviousPageParam` is set and returns a value other than `null` or + * `undefined`. + */ +export function hasPreviousPage( + options: InfiniteQueryPageParamsOptions, + data?: InfiniteData, +): boolean { + if (!data || !options.getPreviousPageParam) return false + return getPreviousPageParam(options, data) != null +} + +/** + * Attaches paging to the options that create or restore an infinite query. + * @param options - Options accepted by an infinite query or observer. + * @returns Options that install the page fetcher on the cached query. + */ +export function infiniteFetchOptions( + options: TOptions, +) { + return { + ...options, + _type: 'infinite' as const, + _prepareInfiniteFetch: createInfiniteFetch, + } +} diff --git a/packages/query-core-pluggable/src/infiniteQueryObserver.ts b/packages/query-core-pluggable/src/infiniteQueryObserver.ts new file mode 100644 index 00000000000..e354ec1e9fc --- /dev/null +++ b/packages/query-core-pluggable/src/infiniteQueryObserver.ts @@ -0,0 +1,283 @@ +import { + hasNextPage, + hasPreviousPage, + infiniteFetchOptions, +} from './infiniteQueryBehavior' +import { QueryObserver } from './queryObserver' +import type { Query } from './query' +import type { QueryClient } from './queryClient' +import type { + QueryObserverResultContext, + QueryObserverResultReader, +} from './queryObserver' +import type { Subscribable } from './subscribable' +import type { + DefaultError, + DefaultedInfiniteQueryObserverOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + InfiniteData, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverOptions, + InfiniteQueryObserverResult, + QueryKey, + QueryObserverResult, +} from './types' + +type InfiniteQueryObserverListener = ( + result: InfiniteQueryObserverResult, +) => void + +type ReplaceReturnType< + TFunction extends (...args: Array) => unknown, + TReturn, +> = (...args: Parameters) => TReturn + +type InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, + TPageParam, +> = + | InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + | DefaultedInfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + +/** + * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch + * between infinite queries. It augments the base `QueryObserverResult` with + * infinite-query-specific fields and methods, such as `hasNextPage` and + * `fetchNextPage`. The React adapter uses this observer for + * `useQuery(infiniteQueryOptions(options))` and `useQuery(suspenseInfiniteQueryOptions(options))`. + * @example + * ```ts + * const observer = new InfiniteQueryObserver(queryClient, { + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextCursor, + * }) + * + * const unsubscribe = observer.subscribe((result) => console.log(result)) + * ``` + */ +export class InfiniteQueryObserver< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends QueryObserver< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey +> { + // Type override + override subscribe!: Subscribable< + InfiniteQueryObserverListener + >['subscribe'] + + // Type override + override getCurrentResult!: ReplaceReturnType< + QueryObserver< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey + >['getCurrentResult'], + InfiniteQueryObserverResult + > + + // Type override + protected override fetch!: ReplaceReturnType< + QueryObserver< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey + >['fetch'], + Promise> + > + + constructor( + client: QueryClient, + options: InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ) { + super(client, options) + } + + protected override bindMethods(): void { + super.bindMethods() + this.fetchNextPage = this.fetchNextPage.bind(this) + this.fetchPreviousPage = this.fetchPreviousPage.bind(this) + } + + /** + * Updates the observer's options. Behaves the same as + * `QueryObserver.setOptions`, additionally marking the options as + * belonging to an infinite query before delegating to the base + * implementation. + * @param options - The new infinite query observer options. + */ + override setOptions( + options: InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): void { + super.setOptions(infiniteFetchOptions(options)) + } + + /** + * Creates a cached snapshot reader for an infinite query. + * @param options - The defaulted options used to read and commit the query result. + * @returns A reader that keeps its result and computation state until commit. + */ + override createResultReader( + options: DefaultedInfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): QueryObserverResultReader> { + return super.createResultReader( + infiniteFetchOptions(options), + ) as QueryObserverResultReader> + } + + /** + * Fetches the next page of the infinite query and returns a promise that + * resolves with the resulting `InfiniteQueryObserverResult`. The page + * param used for the fetch is determined by `getNextPageParam`, which + * receives the current pages/page params and whose result also determines + * `hasNextPage`. + * @param options - Set `cancelRefetch` to `false` to ignore the call while a fetch is running, + * and `throwOnError` to `true` to reject when the fetch fails. + * @returns A promise that resolves with the result after the next page is fetched. With + * `cancelRefetch: false`, a running fetch is reused instead, so the next page may not be fetched. + * @see {@link InfiniteQueryObserver#fetchPreviousPage} + * @example + * ```ts + * const { hasNextPage } = observer.getCurrentResult() + * + * if (hasNextPage) { + * await observer.fetchNextPage() + * } + * ``` + */ + fetchNextPage( + options?: FetchNextPageOptions, + ): Promise> { + return this.fetch({ + ...options, + meta: { + fetchMore: { direction: 'forward' }, + }, + }) + } + + /** + * Fetches the previous page of the infinite query and returns a promise + * that resolves with the resulting `InfiniteQueryObserverResult`. The page + * param used for the fetch is determined by `getPreviousPageParam`, which + * receives the current pages/page params and whose result also determines + * `hasPreviousPage`. + * @param options - Set `cancelRefetch` to `false` to ignore the call while a fetch is running, + * and `throwOnError` to `true` to reject when the fetch fails. + * @returns A promise that resolves with the result after the previous page is fetched. With + * `cancelRefetch: false`, a running fetch is reused instead, so the previous page may not be fetched. + * @see {@link InfiniteQueryObserver#fetchNextPage} + * @example + * ```ts + * const { hasPreviousPage } = observer.getCurrentResult() + * + * if (hasPreviousPage) { + * await observer.fetchPreviousPage() + * } + * ``` + */ + fetchPreviousPage( + options?: FetchPreviousPageOptions, + ): Promise> { + return this.fetch({ + ...options, + meta: { + fetchMore: { direction: 'backward' }, + }, + }) + } + + /** + * Adds pagination controls and fetch direction to the observer result. + * @internal + * @param query - The cached infinite query. + * @param options - Options used to read the pages. + * @param context - Selection and placeholder state for this read. + * @param prevResult - The preceding result for structural sharing. + * @returns The observer snapshot with page controls and direction-specific status. + */ + override createResult( + query: Query< + TQueryFnData, + TError, + InfiniteData, + TQueryKey + >, + options: InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + context?: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey + >, + prevResult?: QueryObserverResult, + ): InfiniteQueryObserverResult { + const { state } = query + const parentResult = super.createResult(query, options, context, prevResult) + + const result: InfiniteQueryObserverBaseResult = { + ...parentResult, + fetchNextPage: this.fetchNextPage, + fetchPreviousPage: this.fetchPreviousPage, + hasNextPage: hasNextPage(options, state.data), + hasPreviousPage: hasPreviousPage(options, state.data), + fetchDirection: state.fetchMeta?.fetchMore?.direction, + } + + return result as InfiniteQueryObserverResult + } +} diff --git a/packages/query-core-pluggable/src/mutation.ts b/packages/query-core-pluggable/src/mutation.ts new file mode 100644 index 00000000000..2062c7ffa6f --- /dev/null +++ b/packages/query-core-pluggable/src/mutation.ts @@ -0,0 +1,590 @@ +import { getMutationCache } from './mutationCache' +import { notifyManager } from './notifyManager' +import { defaultMutationOptions } from './queryClient' +import { Removable } from './removable' +import { createRetryer } from './retryer' +import type { MutationCache } from './mutationCache' +import type { MutationObserver } from './mutationObserver' +import type { QueryClient } from './queryClient' +import type { Retryer } from './retryer' +import type { + DefaultError, + MutationFunctionContext, + MutationMeta, + MutationOptions, + MutationStatus, +} from './types' + +interface MutationConfig { + client: QueryClient + mutationId: number + mutationCache: MutationCache + options: MutationOptions + state?: MutationState +} + +// CLASS + +/** + * Represents a single mutation attempt. A `Mutation` holds the mutation's + * options, state (data/error/status), and the `MutationObserver`s currently + * subscribed to it. + * + * Instances are created and managed internally by `MutationCache`; application + * code typically interacts with mutations indirectly through `QueryClient` or + * a framework hook like `useMutation`. Direct access to a `Mutation` instance + * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state. + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * const mutation = mutationCache.find({ mutationKey: ['addPost'] }) + * ``` + */ +export class Mutation< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> extends Removable { + state: MutationState + options!: MutationOptions + readonly mutationId: number + + #client: QueryClient + #observers: Array< + MutationObserver + > + #mutationCache: MutationCache + #retryer?: Retryer + + /** + * Creates a mutation with the client's defaults and adds it to the cache. + * @param client - Supplies defaults and the mutation cache. + * @param options - The options for the new mutation. + * @param state - The initial state, for example when hydrating a paused mutation. + * @returns The registered mutation. + */ + static build( + client: QueryClient, + options: MutationOptions, + state?: MutationState, + ): Mutation { + const cache = getMutationCache(client) + return cache.register( + (mutationId) => + new Mutation({ + client, + mutationCache: cache, + mutationId, + options: defaultMutationOptions(client, options), + state, + }), + ) + } + + constructor( + config: MutationConfig, + ) { + super() + + this.#client = config.client + this.mutationId = config.mutationId + this.#mutationCache = config.mutationCache + this.#observers = [] + this.state = config.state || getDefaultState() + + this.options = config.options + this.updateGcTime(config.options.gcTime) + this.scheduleGc() + } + + /** + * Replaces the mutation's options and applies their `gcTime`. + * @internal + * @param options - The new mutation options. + */ + setOptions( + options: MutationOptions, + ): void { + // An observer may change options while its previous mutation is still queued. + const scope = this.options.scope + this.options = options.scope === scope ? options : { ...options, scope } + this.updateGcTime(options.gcTime) + } + + /** + * The `meta` object passed in the mutation's options, if any. + * @returns The mutation's `meta`, or `undefined` if none was set. + */ + get meta(): MutationMeta | undefined { + return this.options.meta + } + + /** + * Subscribes an observer to the mutation and stops its garbage collection. + * @internal + * @param observer - The observer to add. Adding an observer that is already subscribed does + * nothing. + */ + addObserver(observer: MutationObserver): void { + if (!this.#observers.includes(observer)) { + this.#observers.push(observer) + + // Stop the mutation from being garbage collected + this.clearGcTimeout() + + this.#mutationCache.notify({ + type: 'observerAdded', + mutation: this, + observer, + }) + } + } + + /** + * Unsubscribes an observer from the mutation. + * @internal + * @param observer - The observer to remove. Schedules garbage collection if the mutation + * is still in the cache. + */ + removeObserver(observer: MutationObserver): void { + this.#observers = this.#observers.filter((x) => x !== observer) + + if (this.#mutationCache.has(this)) { + this.scheduleGc() + } + + this.#mutationCache.notify({ + type: 'observerRemoved', + mutation: this, + observer, + }) + } + + protected override optionalRemove() { + if (!this.#observers.length) { + if (this.state.status === 'pending') { + this.scheduleGc() + } else { + this.#mutationCache.remove(this) + } + } + } + + /** + * Resumes a mutation that is currently paused or was restored from a + * dehydrated, still-`pending` state. + * + * - If this mutation has an active retryer (it paused mid-attempt, e.g. due + * to the network mode or scope-based queuing), its retryer is resumed. + * - Otherwise, if the mutation's status is still `pending` (e.g. it was + * dehydrated while an attempt was in flight and never got a retryer in + * this instance), `execute` is called again with the last known variables. + * - Otherwise the mutation has already settled and this resolves immediately + * without running anything again. + * @returns A promise that settles with the resumed mutation: it rejects if the mutation fails. + * It resolves immediately if the mutation has already settled. + * @see {@link Mutation#execute} + * @example + * ```ts + * // typically driven by reconnect handling, e.g. resumePausedMutations() + * const mutation = mutationCache.find({ mutationKey: ['addPost'] }) + * await mutation?.continue() + * ``` + */ + continue(): Promise { + return ( + this.#retryer?.continue() ?? + // continuing a mutation assumes that variables are set, mutation must have been dehydrated before. + // a settled mutation has no retryer to continue and must not run again + (this.state.status === 'pending' + ? this.execute(this.state.variables!) + : Promise.resolve()) + ) + } + + /** + * Runs the mutation function for the given variables through a retryer, and + * drives the mutation's state and lifecycle callbacks through to settlement. + * + * If this mutation's state is already `pending` when `execute` is called + * (i.e. it was restored, still in-flight, from a dehydrated state), the + * `onMutate` step is skipped and a `continue` action is dispatched to + * unpause it; otherwise a `pending` action is dispatched first, then the + * mutation cache's `onMutate` and the mutation's own `onMutate` option are + * awaited in that order, and the resulting context is stored. + * + * The mutation function is then run (subject to `retry`/`retryDelay`/ + * `networkMode`, and to the mutation cache's scope-based serialization). + * On success, the cache's `onSuccess`/`onSettled` callbacks run before the + * mutation's own `onSuccess`/`onSettled` options, a `success` action is + * dispatched, and the resolved data is returned. On failure, the same + * cache-then-option ordering is used for `onError`/`onSettled`, but each of + * those four callbacks is individually caught so that a throwing callback + * cannot mask the original error; an `error` action is then dispatched and + * the original error is re-thrown. + * @param variables - The variables passed to the `mutationFn`. + * @returns A promise that resolves with the mutation's data, or rejects with its error. + * @see {@link Mutation#continue} + * @example + * ```ts + * // Called internally by `MutationObserver.mutate` and `Mutation.continue` — + * // applications normally trigger mutations through those, not this method. + * const data = await mutation.execute(variables) + * ``` + */ + async execute(variables: TVariables): Promise { + const onContinue = () => { + this.#dispatch({ type: 'continue' }) + } + + const mutationFnContext = { + client: this.#client, + meta: this.options.meta, + mutationKey: this.options.mutationKey, + } satisfies MutationFunctionContext + + const retryer = (this.#retryer = createRetryer({ + fn: () => { + if (!this.options.mutationFn) { + return Promise.reject(new Error('No mutationFn found')) + } + + return this.options.mutationFn(variables, mutationFnContext) + }, + onFail: (failureCount, error) => { + this.#dispatch({ type: 'failed', failureCount, error }) + }, + onPause: () => { + this.#dispatch({ type: 'pause' }) + }, + onContinue, + retry: this.options.retry ?? 0, + retryDelay: this.options.retryDelay, + networkMode: this.options.networkMode, + canRun: () => this.#mutationCache.canRun(this), + })) + + const restored = this.state.status === 'pending' + const isPaused = !retryer.canStart() + + try { + if (restored) { + // Dispatch continue action to unpause restored mutation + onContinue() + } else { + this.#dispatch({ type: 'pending', variables, isPaused }) + // Notify cache callback + if (this.#mutationCache.config.onMutate) { + await this.#mutationCache.config.onMutate( + variables, + this as Mutation, + mutationFnContext, + ) + } + const context = await this.options.onMutate?.( + variables, + mutationFnContext, + ) + if (context !== this.state.context) { + this.#dispatch({ + type: 'pending', + context, + variables, + isPaused, + }) + } + } + // Unpause a mutation that became able to start while onMutate was running + if (this.state.isPaused && retryer.canStart()) { + onContinue() + } + const data = await retryer.start() + + // Notify cache callback + await this.#mutationCache.config.onSuccess?.( + data, + variables, + this.state.context, + this as Mutation, + mutationFnContext, + ) + + await this.options.onSuccess?.( + data, + variables, + this.state.context!, + mutationFnContext, + ) + + // Notify cache callback + await this.#mutationCache.config.onSettled?.( + data, + null, + this.state.variables, + this.state.context, + this as Mutation, + mutationFnContext, + ) + + await this.options.onSettled?.( + data, + null, + variables, + this.state.context, + mutationFnContext, + ) + + this.#dispatch({ type: 'success', data }) + return data + } catch (error) { + try { + // Notify cache callback + await this.#mutationCache.config.onError?.( + error as any, + variables, + this.state.context, + this as Mutation, + mutationFnContext, + ) + } catch (e) { + void Promise.reject(e) + } + + try { + await this.options.onError?.( + error as TError, + variables, + this.state.context, + mutationFnContext, + ) + } catch (e) { + void Promise.reject(e) + } + + try { + // Notify cache callback + await this.#mutationCache.config.onSettled?.( + undefined, + error as any, + this.state.variables, + this.state.context, + this as Mutation, + mutationFnContext, + ) + } catch (e) { + void Promise.reject(e) + } + + try { + await this.options.onSettled?.( + undefined, + error as TError, + variables, + this.state.context, + mutationFnContext, + ) + } catch (e) { + void Promise.reject(e) + } + + this.#dispatch({ type: 'error', error: error as TError }) + throw error + } finally { + // The settled retryer's promise would otherwise pin this mutation's + // result, variables and context for as long as the cache keeps it + if (this.#retryer === retryer) { + this.#retryer = undefined + } + this.#mutationCache.runNext(this) + } + } + + #dispatch(action: Action): void { + const reducer = ( + state: MutationState, + ): MutationState => { + switch (action.type) { + case 'failed': + return { + ...state, + failureCount: action.failureCount, + failureReason: action.error, + } + case 'pause': + return { + ...state, + isPaused: true, + } + case 'continue': + return { + ...state, + isPaused: false, + } + case 'pending': + return { + ...state, + context: action.context, + data: undefined, + failureCount: 0, + failureReason: null, + error: null, + isPaused: action.isPaused, + status: 'pending', + variables: action.variables, + submittedAt: Date.now(), + } + case 'success': + return { + ...state, + data: action.data, + failureCount: 0, + failureReason: null, + error: null, + status: 'success', + isPaused: false, + } + case 'error': + return { + ...state, + data: undefined, + error: action.error, + failureCount: state.failureCount + 1, + failureReason: action.error, + isPaused: false, + status: 'error', + } + } + } + this.state = reducer(this.state) + + notifyManager.batch(() => { + this.#observers.forEach((observer) => { + observer.onMutationUpdate(action) + }) + this.#mutationCache.notify({ + mutation: this, + type: 'updated', + action, + }) + }) + } +} + +/** + * Returns the initial state of a mutation: `'idle'`, with no data, error, or variables. + * @returns The initial mutation state. + */ +export function getDefaultState< + TData, + TError, + TVariables, + TOnMutateResult, +>(): MutationState { + return { + context: undefined, + data: undefined, + error: null, + failureCount: 0, + failureReason: null, + isPaused: false, + status: 'idle', + variables: undefined, + submittedAt: 0, + } +} + +/** + * The raw state stored on a `Mutation` instance. This is the underlying state + * that observer results (e.g. `MutationObserverResult`) are derived from. + */ +export interface MutationState< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> { + /** + * The value returned by `onMutate`, if defined. Passed to `onSuccess`, + * `onError` and `onSettled` as the mutation's context. + */ + context: TOnMutateResult | undefined + /** + * The last successfully resolved data for the mutation. + */ + data: TData | undefined + /** + * The error object for the mutation, if the last attempt resulted in an error. + * - Defaults to `null`. + */ + error: TError | null + /** + * The number of times the mutation function has failed for the current attempt. + */ + failureCount: number + /** + * The reason the current attempt failed, as reported by the retryer. + */ + failureReason: TError | null + /** + * Whether the mutation is currently paused (see network mode), or is + * waiting for another mutation with the same `scope` to finish. + */ + isPaused: boolean + /** + * The status of the mutation. + */ + status: MutationStatus + /** + * The variables the mutation was last called with. + */ + variables: TVariables | undefined + /** + * The timestamp for when the mutation was submitted. + */ + submittedAt: number +} + +interface FailedAction { + type: 'failed' + failureCount: number + error: TError | null +} + +interface PendingAction { + type: 'pending' + isPaused: boolean + variables?: TVariables + context?: TOnMutateResult +} + +interface SuccessAction { + type: 'success' + data: TData +} + +interface ErrorAction { + type: 'error' + error: TError +} + +interface PauseAction { + type: 'pause' +} + +interface ContinueAction { + type: 'continue' +} + +/** + * The actions a mutation dispatches to update its state, e.g. when it starts, fails, pauses, or + * succeeds. + */ +export type Action = + | ContinueAction + | ErrorAction + | FailedAction + | PendingAction + | PauseAction + | SuccessAction diff --git a/packages/query-core-pluggable/src/mutationCache.ts b/packages/query-core-pluggable/src/mutationCache.ts new file mode 100644 index 00000000000..eeff7fef932 --- /dev/null +++ b/packages/query-core-pluggable/src/mutationCache.ts @@ -0,0 +1,345 @@ +import { notifyManager } from './notifyManager' +import { mutationCacheKey } from './queryClient' +import { Subscribable } from './subscribable' +import { matchMutation, noop } from './utils' +import type { Mutation, Action as MutationAction } from './mutation' +import type { MutationObserver } from './mutationObserver' +import type { QueryClient } from './queryClient' +import type { + CacheKeyConfig, + DefaultError, + MutationFunctionContext, + MutationKey, + NotifyEvent, +} from './types' +import type { MutationFilters } from './utils' + +/** + * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which + * component or observer triggered it. They differ from the `defaultOptions` provided to a + * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these + * callbacks are always called, and `onMutate` here does not allow returning a result. + * + * If a callback returns a promise, it will be awaited before the mutation continues. + */ +export interface MutationCacheConfig { + /** + * Configures mutation key comparison and hashing globally. + * `equalityFn` compares individual values during partial matching and defaults to strict equality. + * `hashFn` hashes mutation keys for exact matching and mutation defaults. + */ + mutationKey?: CacheKeyConfig + /** Called when any mutation in the cache encounters an error. */ + onError?: ( + error: DefaultError, + variables: unknown, + onMutateResult: unknown, + mutation: Mutation, + context: MutationFunctionContext, + ) => Promise | unknown + /** Called when any mutation in the cache is successful. */ + onSuccess?: ( + data: unknown, + variables: unknown, + onMutateResult: unknown, + mutation: Mutation, + context: MutationFunctionContext, + ) => Promise | unknown + /** Called before any mutation in the cache executes. */ + onMutate?: ( + variables: unknown, + mutation: Mutation, + context: MutationFunctionContext, + ) => Promise | unknown + /** Called when any mutation in the cache is settled, either successfully or with an error. */ + onSettled?: ( + data: unknown | undefined, + error: DefaultError | null, + variables: unknown, + onMutateResult: unknown, + mutation: Mutation, + context: MutationFunctionContext, + ) => Promise | unknown +} + +/** + * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed + * from the cache, its state is updated, or one of its observers is added, removed, or has its + * options updated. + */ +export type MutationCacheNotifyEvent = + | NotifyEventMutationAdded + | NotifyEventMutationRemoved + | NotifyEventMutationObserverAdded + | NotifyEventMutationObserverRemoved + | NotifyEventMutationObserverOptionsUpdated + | NotifyEventMutationUpdated + +type MutationCacheListener = (event: MutationCacheNotifyEvent) => void + +interface NotifyEventMutationAdded extends NotifyEvent { + type: 'added' + mutation: Mutation +} + +interface NotifyEventMutationRemoved extends NotifyEvent { + type: 'removed' + mutation: Mutation +} + +interface NotifyEventMutationObserverAdded extends NotifyEvent { + type: 'observerAdded' + mutation: Mutation + observer: MutationObserver +} + +interface NotifyEventMutationObserverRemoved extends NotifyEvent { + type: 'observerRemoved' + mutation: Mutation + observer: MutationObserver +} + +interface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent { + type: 'observerOptionsUpdated' + mutation?: Mutation + observer: MutationObserver +} + +interface NotifyEventMutationUpdated extends NotifyEvent { + type: 'updated' + mutation: Mutation + action: MutationAction +} + +/** + * Returns the client's configured mutation cache, creating a default cache on + * first use. Mutation hooks and hydration share this cache. + * @param client - The client whose mutations you want to access. + * @returns The same mutation cache on every call for this client. + * @example + * ```ts + * import { getMutationCache } from '@tanstack/query-core-pluggable' + * + * const pending = getMutationCache(queryClient).findAll({ status: 'pending' }) + * ``` + */ +export function getMutationCache(client: QueryClient): MutationCache { + return (client[mutationCacheKey] ??= new MutationCache()) +} + +/** + * Stores the mutations executed through a client. Use {@link getMutationCache} to + * access the cache that mutation hooks use. Subscribe to it to receive updates + * when a mutation is added, removed, or changes state. + * @example + * ```ts + * const unsubscribe = mutationCache.subscribe((event) => { + * console.log(event.type, event.mutation) + * }) + * ``` + */ +export class MutationCache extends Subscribable { + #mutations: Set> + #mutationId: number + + constructor(public config: MutationCacheConfig = {}) { + super() + this.#mutations = new Set() + this.#mutationId = 0 + } + + /** + * Assigns the next cache-local ID and registers the mutation. + * @internal + * @param create - Constructs the mutation with the assigned ID. + * @returns The mutation added to this cache. + */ + register>( + create: (id: number) => T, + ): T { + const mutation = create(++this.#mutationId) + this.add(mutation) + return mutation + } + + /** + * Adds a mutation to the cache. + * @internal + * @param mutation - The mutation to add. If it has a `scope`, it is queued in that scope. + */ + add(mutation: Mutation): void { + this.#mutations.add(mutation) + mutation.options.scope?.add(this, mutation) + this.notify({ type: 'added', mutation }) + } + + /** + * Removes a mutation from the cache and clears its garbage collection timer. + * @internal + * @param mutation - The mutation to remove, also from its scope's queue. + */ + remove(mutation: Mutation): void { + if (this.#mutations.delete(mutation)) { + mutation.destroy() + mutation.options.scope?.remove(this, mutation) + } + + // Currently we notify the removal even if the mutation was already removed. + // Consider making this an error or not notifying of the removal depending on the desired semantics. + this.notify({ type: 'removed', mutation }) + } + + /** + * Checks whether this cache still holds the given mutation. + * @internal + * @param mutation - The mutation to check. + * @returns Whether the mutation is in the cache. + */ + has(mutation: Mutation): boolean { + return this.#mutations.has(mutation) + } + + /** + * Checks whether a mutation can run now, given the other mutations in its `scope`. + * @internal + * @param mutation - The mutation to check. + * @returns `true` if the mutation has no `scope`, or no other mutation in its scope is pending + * ahead of it. + */ + canRun(mutation: Mutation): boolean { + return mutation.options.scope?.canRun(this, mutation) ?? true + } + + /** + * Continues the next paused mutation in the same `scope` after a mutation finishes. + * @internal + * @param mutation - The mutation that finished. + * @returns A promise that resolves once the next paused mutation in the same scope has continued, + * or immediately if there is none. + */ + runNext(mutation: Mutation): Promise { + return mutation.options.scope?.runNext(this, mutation) ?? Promise.resolve() + } + + /** + * Removes all mutations and clears their garbage collection timers. + * Mutations that are already running continue to execute. + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * mutationCache.clear() + * ``` + */ + clear(): void { + notifyManager.batch(() => { + const mutations = this.getAll() + this.#mutations.clear() + mutations.forEach((mutation) => { + mutation.options.scope?.remove(this, mutation) + mutation.destroy() + }) + mutations.forEach((mutation) => { + this.notify({ type: 'removed', mutation }) + }) + }) + } + + /** + * Returns all mutations within the cache. + * + * This is not typically needed for most applications, but can come in handy when needing more + * information about a mutation in rare scenarios. + * @returns Every mutation in the cache. + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * const mutations = mutationCache.getAll() + * ``` + */ + getAll(): Array { + return Array.from(this.#mutations) + } + + /** + * A slightly more advanced method that can be used to get an existing mutation instance from + * the cache. If the mutation does not exist, `undefined` is returned. + * + * This is not typically needed for most applications, but can come in handy when needing more + * information about a mutation in rare scenarios. + * @param filters - The filters to match. `exact` defaults to `true`. + * @returns The first matching mutation, or `undefined`. + * @see {@link MutationCache#findAll} + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * const mutation = mutationCache.find({ mutationKey: ['addPost'] }) + * ``` + */ + find< + TData = unknown, + TError = DefaultError, + TVariables = any, + TOnMutateResult = unknown, + >( + filters: MutationFilters, + ): Mutation | undefined { + const defaultedFilters = { exact: true, ...filters } + + return this.getAll().find((mutation) => + matchMutation(defaultedFilters, mutation, this.config.mutationKey), + ) as Mutation | undefined + } + + /** + * An even more advanced method that can be used to get existing mutation instances from the + * cache that match the given filters. If no mutations match, an empty array is returned. + * + * This is not typically needed for most applications, but can come in handy when needing more + * information about mutations in rare scenarios. + * @param filters - The filters to match. Without filters, every mutation is returned. + * @returns The matching mutations. + * @see {@link MutationCache#find} + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] }) + * ``` + */ + findAll(filters: MutationFilters = {}): Array { + return this.getAll().filter((mutation) => + matchMutation(filters, mutation, this.config.mutationKey), + ) + } + + /** + * Notifies every cache listener of an event, in one batch. + * @internal + * @param event - The event passed to every listener. + */ + notify(event: MutationCacheNotifyEvent) { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(event) + }) + }) + } + + /** + * Continues every paused mutation, e.g. when the app comes back online. + * @internal + * @returns A promise that resolves once every paused mutation has continued and settled. + */ + resumePausedMutations(): Promise { + const pausedMutations = this.getAll().filter((x) => x.state.isPaused) + + return notifyManager.batch(() => + Promise.all( + pausedMutations.map((mutation) => mutation.continue().catch(noop)), + ), + ) + } +} diff --git a/packages/query-core-pluggable/src/mutationObserver.ts b/packages/query-core-pluggable/src/mutationObserver.ts new file mode 100644 index 00000000000..3f888fe228d --- /dev/null +++ b/packages/query-core-pluggable/src/mutationObserver.ts @@ -0,0 +1,327 @@ +import { Mutation, getDefaultState } from './mutation' +import { getMutationCache } from './mutationCache' +import { notifyManager } from './notifyManager' +import { defaultMutationOptions } from './queryClient' +import { Subscribable } from './subscribable' +import { hashKeyByOptions, shallowEqualObjects } from './utils' +import type { Action } from './mutation' +import type { QueryClient } from './queryClient' +import type { + DefaultError, + MutateOptions, + MutationFunctionContext, + MutationObserverOptions, + MutationObserverResult, +} from './types' + +type MutationObserverListener = ( + result: MutationObserverResult, +) => void + +// CLASS + +/** + * Observes a single mutation and derives a `MutationObserverResult` from it. + * A framework hook like `useMutation` creates one `MutationObserver` per hook + * call, keeps it stable across re-renders, calls `setOptions` when the options + * passed to the hook change, subscribes to it to re-render on updates, and + * reads `getCurrentResult()` for the value to return. Calling `mutate()` + * builds a new underlying `Mutation` in the `MutationCache` and executes it. + * @example + * ```ts + * const observer = new MutationObserver(queryClient, { + * mutationFn: (variables: { title: string }) => addPost(variables), + * }) + * ``` + */ +export class MutationObserver< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends Subscribable< + MutationObserverListener +> { + options!: MutationObserverOptions + + #client: QueryClient + #currentResult: MutationObserverResult< + TData, + TError, + TVariables, + TOnMutateResult + > = undefined! + #currentMutation?: Mutation + #mutateOptions?: MutateOptions + + constructor( + client: QueryClient, + options: MutationObserverOptions< + TData, + TError, + TVariables, + TOnMutateResult + >, + ) { + super() + + this.#client = client + this.setOptions(options) + this.bindMethods() + this.#updateResult() + } + + /** + * Binds the methods of the result (`mutate` and `reset`) to the observer, so they keep working when + * destructured from it. + */ + protected bindMethods(): void { + this.mutate = this.mutate.bind(this) + this.reset = this.reset.bind(this) + } + + /** + * Updates the observer's options. + * + * If the new `mutationKey` differs from the previous one (and both were + * defined), the observer is reset, detaching it from the mutation it was + * observing. Otherwise, if the currently observed mutation is still + * `pending`, its options are updated in place as well. + * @param options - The new mutation observer options. They are defaulted with {@link + * defaultMutationOptions} before being applied. + * @example + * ```ts + * observer.setOptions({ + * mutationFn: (variables: { title: string }) => addPost(variables), + * onSuccess: (data) => console.log(data), + * }) + * ``` + */ + setOptions( + options: MutationObserverOptions< + TData, + TError, + TVariables, + TOnMutateResult + >, + ) { + const prevOptions = this.options as + | MutationObserverOptions + | undefined + this.options = defaultMutationOptions(this.#client, options) + const mutationCache = getMutationCache(this.#client) + if (!shallowEqualObjects(this.options, prevOptions)) { + mutationCache.notify({ + type: 'observerOptionsUpdated', + mutation: this.#currentMutation, + observer: this, + }) + } + + if ( + prevOptions?.mutationKey && + this.options.mutationKey && + hashKeyByOptions( + prevOptions.mutationKey, + mutationCache.config.mutationKey, + ) !== + hashKeyByOptions( + this.options.mutationKey, + mutationCache.config.mutationKey, + ) + ) { + this.reset() + } else if (this.#currentMutation?.state.status === 'pending') { + this.#currentMutation.setOptions(this.options) + } + } + + protected override onSubscribe(): void { + if (this.listeners.size === 1 && this.#currentMutation) { + this.#currentMutation.addObserver(this) + + this.#updateResult() + } + } + + protected override onUnsubscribe(): void { + if (!this.hasListeners()) { + this.#currentMutation?.removeObserver(this) + } + } + + /** + * Updates the observer's result when the observed mutation changes, and notifies its listeners. + * @internal + * @param action - The action that updated the observed mutation, passed on to the observer's + * callbacks. + */ + onMutationUpdate( + action: Action, + ): void { + this.#updateResult() + + this.#notify(action) + } + + /** + * Returns the observer's current result, derived from the observed + * mutation's state (or the default, `idle` state if no mutation has been + * built yet, e.g. before the first `mutate()` call or after `reset()`). + * @returns The observer's latest result. + */ + getCurrentResult(): MutationObserverResult< + TData, + TError, + TVariables, + TOnMutateResult + > { + return this.#currentResult + } + + /** + * Detaches the observer from the mutation it is currently observing (if + * any) and resets the observed result back to its default, `idle` state. + * + * This does not cancel an in-flight mutation; the mutation itself keeps + * running to completion and its own callbacks still fire, but this + * observer stops reflecting its state and a subsequent `mutate()` call + * will build a brand new mutation. + * @see {@link MutationObserver#mutate} + * @example + * ```ts + * observer.reset() + * ``` + */ + reset(): void { + // reset needs to remove the observer from the mutation because there is no way to "get it back" + // another mutate call will yield a new mutation! + this.#currentMutation?.removeObserver(this) + this.#currentMutation = undefined + this.#updateResult() + this.#notify() + } + + /** + * Builds a new `Mutation` in the `MutationCache` using the observer's + * current options, detaches this observer from any previously observed + * mutation, attaches it to the new one, and executes it with the given + * variables. + * + * The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are + * invoked once the mutation settles, in addition to any callbacks defined + * on the observer's own options. + * @param variables - The variables passed to the `mutationFn`. + * @param options - Per-call `onSuccess`, `onError`, and `onSettled` callbacks. + * @returns A promise that resolves with the mutation's data, or rejects with its error. + * @example + * ```ts + * await observer.mutate( + * { title: 'New post' }, + * { onSuccess: (data) => console.log(data) }, + * ) + * ``` + */ + mutate( + variables: TVariables, + options?: MutateOptions, + ): Promise { + this.#mutateOptions = options + + this.#currentMutation?.removeObserver(this) + + this.#currentMutation = Mutation.build(this.#client, this.options) + + this.#currentMutation.addObserver(this) + + return this.#currentMutation.execute(variables) + } + + #updateResult(): void { + const state = + this.#currentMutation?.state ?? + getDefaultState() + + this.#currentResult = { + ...state, + isPending: state.status === 'pending', + isSuccess: state.status === 'success', + isError: state.status === 'error', + isIdle: state.status === 'idle', + mutate: this.mutate, + reset: this.reset, + } as MutationObserverResult + } + + #notify(action?: Action): void { + notifyManager.batch(() => { + // First trigger the mutate callbacks + // Snapshot mutateOptions before dispatching — a callback (e.g. onSuccess) + // may call mutate() again, which overwrites this.#mutateOptions in place. + // Without the snapshot, onSettled would fire with the *next* mutation's + // options but the *current* mutation's data/variables. + const mutateOptions = this.#mutateOptions + if (mutateOptions && this.hasListeners()) { + const variables = this.#currentResult.variables! + const onMutateResult = this.#currentResult.context + + const context = { + client: this.#client, + meta: this.options.meta, + mutationKey: this.options.mutationKey, + } satisfies MutationFunctionContext + + if (action?.type === 'success') { + try { + mutateOptions.onSuccess?.( + action.data, + variables, + onMutateResult, + context, + ) + } catch (e) { + void Promise.reject(e) + } + try { + mutateOptions.onSettled?.( + action.data, + null, + variables, + onMutateResult, + context, + ) + } catch (e) { + void Promise.reject(e) + } + } else if (action?.type === 'error') { + try { + mutateOptions.onError?.( + action.error, + variables, + onMutateResult, + context, + ) + } catch (e) { + void Promise.reject(e) + } + try { + mutateOptions.onSettled?.( + undefined, + action.error, + variables, + onMutateResult, + context, + ) + } catch (e) { + void Promise.reject(e) + } + } + } + + // Then trigger the listeners + this.listeners.forEach((listener) => { + listener(this.#currentResult) + }) + }) + } +} diff --git a/packages/query-core-pluggable/src/notifyManager.ts b/packages/query-core-pluggable/src/notifyManager.ts new file mode 100644 index 00000000000..983e8d03539 --- /dev/null +++ b/packages/query-core-pluggable/src/notifyManager.ts @@ -0,0 +1,127 @@ +type BatchCallsCallback> = (...args: T) => void + +type NotifyCallback = () => void + +type NotifyFunction = (callback: () => void) => void + +type ScheduleFunction = (callback: () => void) => void + +/** + * Default scheduling function used by the notify manager. + * Schedules the callback in a microtask with `queueMicrotask`. + */ +export const defaultScheduler: ScheduleFunction = queueMicrotask + +/** + * Creates a notify manager, which schedules and batches notifications to subscribers. Query uses a + * single instance of it, exported as {@link notifyManager}. + * @returns A new notify manager. + */ +export function createNotifyManager() { + let queue: Array = [] + let transactions = 0 + let notifyFn: NotifyFunction = (callback) => { + callback() + } + let scheduleFn = defaultScheduler + + const schedule = (callback: NotifyCallback): void => { + if (transactions) { + queue.push(callback) + } else { + scheduleFn(() => { + notifyFn(callback) + }) + } + } + const flush = (): void => { + const originalQueue = queue + queue = [] + if (originalQueue.length) { + scheduleFn(() => { + originalQueue.forEach((callback) => { + notifyFn(callback) + }) + }) + } + } + + return { + /** + * Batches all updates scheduled inside the passed callback. + * This is mainly used internally to optimize query client updating. + * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes. + * The return value of `callback` is passed through. + * @param callback - The function to run in the batch. + * @returns The return value of `callback`. + */ + batch: (callback: () => T): T => { + let result + transactions++ + try { + result = callback() + } finally { + transactions-- + if (!transactions) { + flush() + } + } + return result + }, + /** + * All calls to the wrapped function will be batched. + * @param callback - The function to wrap. + * @returns A function that schedules a call to `callback` with the given arguments. + */ + batchCalls: >( + callback: BatchCallsCallback, + ): BatchCallsCallback => { + return (...args) => { + schedule(() => { + callback(...args) + }) + } + }, + /** + * Schedules a function to be run on the next batch. + * By default, the batch runs in a microtask. Use `setScheduler` to change when it runs. + */ + schedule, + /** + * Use this method to set a custom notify function. + * This can be used to for example wrap notifications with `React.act` while running tests. + * @param fn - Receives each notification callback and must call it. + */ + setNotifyFunction: (fn: NotifyFunction) => { + notifyFn = fn + }, + /** + * Configures a custom callback that schedules when the next batch runs. + * The default behavior is `queueMicrotask(callback)`. + * @param fn - Receives a callback that runs the next batch, and schedules it. + * @example + * ```ts + * import { notifyManager } from '@tanstack/query-core-pluggable' + * + * // Use the v5 timer-based scheduler + * notifyManager.setScheduler((cb) => setTimeout(cb, 0)) + * + * // Schedule batches before the next frame is rendered + * notifyManager.setScheduler(requestAnimationFrame) + * + * // Schedule batches some time in the future + * notifyManager.setScheduler((cb) => setTimeout(cb, 10)) + * ``` + */ + setScheduler: (fn: ScheduleFunction) => { + scheduleFn = fn + }, + } as const +} + +// SINGLETON + +/** + * Handles scheduling and batching callbacks in TanStack Query. + */ +export const notifyManager = createNotifyManager() diff --git a/packages/query-core-pluggable/src/onlineManager.ts b/packages/query-core-pluggable/src/onlineManager.ts new file mode 100644 index 00000000000..8a7bc30aebc --- /dev/null +++ b/packages/query-core-pluggable/src/onlineManager.ts @@ -0,0 +1,119 @@ +import { Subscribable } from './subscribable' + +type Listener = (online: boolean) => void +type SetupFn = (setOnline: Listener) => (() => void) | undefined + +/** + * The `OnlineManager` manages the online state within TanStack Query. It can + * be used to change the default event listeners or to manually change the + * online state. + * + * By default, the `onlineManager` assumes an active network connection, and + * listens to the `online` and `offline` events on the `window` object to + * detect changes. + */ +export class OnlineManager extends Subscribable { + #online = true + #cleanup?: () => void + + #setup: SetupFn + + constructor() { + super() + this.#setup = (onOnline) => { + // addEventListener does not exist in React Native, but window does + // oxlint-disable-next-line typescript/no-unnecessary-condition + if (typeof window !== 'undefined' && window.addEventListener) { + const onlineListener = () => onOnline(true) + const offlineListener = () => onOnline(false) + // Listen to online + window.addEventListener('online', onlineListener, false) + window.addEventListener('offline', offlineListener, false) + + return () => { + // Be sure to unsubscribe if a new handler is set + window.removeEventListener('online', onlineListener) + window.removeEventListener('offline', offlineListener) + } + } + + return + } + } + + protected override onSubscribe(): void { + if (!this.#cleanup) { + this.setEventListener(this.#setup) + } + } + + protected override onUnsubscribe() { + if (!this.hasListeners()) { + this.#cleanup?.() + this.#cleanup = undefined + } + } + + /** + * `setEventListener` can be used to set a custom event listener that will + * be used to determine the online state. The provided `setup` function + * receives a `setOnline` callback that should be called with a `boolean` + * whenever the online state changes. + * @param setup - Receives the `setOnline` callback, registers the event listener, and may return + * a cleanup function that is called when the listener is replaced or no longer needed. + * @example + * ```ts + * import NetInfo from '@react-native-community/netinfo' + * import { onlineManager } from '@tanstack/query-core-pluggable' + * + * onlineManager.setEventListener((setOnline) => { + * return NetInfo.addEventListener((state) => { + * setOnline(!!state.isConnected) + * }) + * }) + * ``` + */ + setEventListener(setup: SetupFn): void { + this.#setup = setup + this.#cleanup?.() + this.#cleanup = setup(this.setOnline.bind(this)) + } + + /** + * `setOnline` can be used to manually set the online state. + * @param online - The online state. + * @example + * ```ts + * import { onlineManager } from '@tanstack/query-core-pluggable' + * + * // Set to online + * onlineManager.setOnline(true) + * + * // Set to offline + * onlineManager.setOnline(false) + * ``` + */ + setOnline(online: boolean): void { + const changed = this.#online !== online + + if (changed) { + this.#online = online + this.listeners.forEach((listener) => { + listener(online) + }) + } + } + + /** + * `isOnline` can be used to get the current online state. + * @returns `true` if online. + */ + isOnline(): boolean { + return this.#online + } +} + +/** + * Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query. + */ +export const onlineManager = new OnlineManager() diff --git a/packages/query-core-pluggable/src/placeholderData.ts b/packages/query-core-pluggable/src/placeholderData.ts new file mode 100644 index 00000000000..b1113e8a099 --- /dev/null +++ b/packages/query-core-pluggable/src/placeholderData.ts @@ -0,0 +1,98 @@ +import { projectResult } from './projectResult' +import { replaceData, shallowEqualObjects } from './utils' +import type { Query } from './query' +import type { + ProjectionFailure, + QueryObserverResultContext, +} from './queryObserver' +import type { QueryKey, QueryObserverOptionsBase } from './types' + +/* #__NO_SIDE_EFFECTS__ */ +/** + * Supplies temporary data while an observed query has no cached result. + * @param value - A placeholder value or a factory receiving the previous query and its data. + * @returns A query placeholder option. + */ +export function placeholderData( + value: TValue, +): readonly [typeof placeholderData, TValue] { + return [placeholderData, value] +} + +placeholderData.project = projectResult +placeholderData.resolve = resolvePlaceholder + +/** + * Reuses a pending query's placeholder until its factory, source query or sharing policy changes. + * @param options - Options that supply the placeholder. + * @param context - This observer or reader's cached placeholder. + * @param previousData - The previous data for structural sharing. + * @param previousQuery - The last observed query with defined data. + * @returns Placeholder data or the error thrown by its factory. + */ +function resolvePlaceholder< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + context: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + previousData: TData | undefined, + previousQuery: Query | undefined, +): QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +>['placeholder'] { + const value = options.placeholderData![1] + const previousState = previousQuery?.state + const key: NonNullable['key'] = { + placeholderData: value, + structuralSharing: options.structuralSharing, + previousQuery, + previousState, + previousOptions: previousQuery?.options, + } + const memo = context.placeholder + if (shallowEqualObjects(key, memo?.key)) return memo + + let input: TQueryData | undefined + let sourceQuery: typeof previousQuery + let failure: ProjectionFailure | undefined + if (typeof value === 'function') { + try { + input = ( + value as unknown as ( + previous: TQueryData | undefined, + query: typeof previousQuery, + ) => TQueryData | undefined + )(previousState?.data, previousQuery) + } catch (error) { + failure = { error: error as TError, errorUpdatedAt: Date.now() } + } + if (previousState?.data !== undefined) sourceQuery = previousQuery + } else { + input = value + } + if (input !== undefined) + input = replaceData(previousData, input as unknown, options) as TQueryData + return input !== undefined || failure + ? { key, input, sourceQuery, failure } + : undefined +} diff --git a/packages/query-core-pluggable/src/projectResult.ts b/packages/query-core-pluggable/src/projectResult.ts new file mode 100644 index 00000000000..ecdf5182269 --- /dev/null +++ b/packages/query-core-pluggable/src/projectResult.ts @@ -0,0 +1,89 @@ +import type { Query, QueryState } from './query' +import type { QueryObserverResultContext } from './queryObserver' +import type { QueryKey, QueryObserverOptionsBase } from './types' + +/** + * Computes the data, status and error visible to one observer. + * @param query - The query whose cached data is being read. + * @param state - The query state for this read, including optimistic fetch state. + * @param options - The selection, placeholder and structural sharing options. + * @param context - Memoized results for this observer or uncommitted result reader. + * @param previousData - The preceding observer result for structural sharing. + * @param previousQuery - The preceding query with defined cached data. + * @returns The projected fields, including whether the result contains placeholder data. + */ +export function projectResult< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + query: Query, + state: QueryState, + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + context: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + previousData: TData | undefined, + previousQuery: Query | undefined, +): Pick< + QueryState, + 'data' | 'status' | 'error' | 'errorUpdatedAt' +> & { isPlaceholderData: boolean } { + context.project = projectResult + const { select, placeholderData } = options + context.placeholder = + state.data === undefined && state.status === 'pending' && placeholderData + ? placeholderData[0].resolve( + options, + context, + previousData, + previousQuery, + ) + : undefined + const placeholder = context.placeholder + const input = placeholder ? placeholder.input : state.data + // A previously selected query may have lost its data even if this render has no selector. + if ( + context.selected?.query && + context.selected.query.state.data === undefined + ) { + context.selected = undefined + if (!context.selection?.failure) context.selection = undefined + } + if (select && input !== undefined) { + select[0].resolve( + options, + select[1], + context, + previousData, + input, + placeholder ? placeholder.sourceQuery : query, + ) + } else { + context.selection = undefined + } + const failure = placeholder?.failure ?? context.selection?.failure + const isPlaceholderData = !!placeholder && input !== undefined && !failure + const { error, errorUpdatedAt } = failure ?? state + return { + data: context.selection + ? context.selected?.data + : (input as unknown as TData | undefined), + error, + errorUpdatedAt, + status: failure ? 'error' : isPlaceholderData ? 'success' : state.status, + isPlaceholderData, + } +} diff --git a/packages/query-core-pluggable/src/projectionTypes.ts b/packages/query-core-pluggable/src/projectionTypes.ts new file mode 100644 index 00000000000..856fb0dfc7f --- /dev/null +++ b/packages/query-core-pluggable/src/projectionTypes.ts @@ -0,0 +1,20 @@ +import type { placeholderData } from './placeholderData' +import type { select } from './select' + +/** A selector and its opt-in observer implementation. */ +export type Select = readonly [ + feature: typeof select, + value: (data: TInput) => TData, +] + +/** Placeholder data (or a factory) paired with its observer implementation. */ +export type PlaceholderData = readonly [ + feature: typeof placeholderData, + value: + // oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes all callable and constructable values + | (TData extends Function ? never : TData) + | (( + previousData: TData | undefined, + previousQuery: TQuery | undefined, + ) => TData | undefined), +] diff --git a/packages/query-core-pluggable/src/queriesObserver.ts b/packages/query-core-pluggable/src/queriesObserver.ts new file mode 100644 index 00000000000..cdeead23d2e --- /dev/null +++ b/packages/query-core-pluggable/src/queriesObserver.ts @@ -0,0 +1,495 @@ +import { notifyManager } from './notifyManager' +import { defaultQueryOptions } from './queryClient' +import { QueryObserver } from './queryObserver' +import { Subscribable } from './subscribable' +import { + replaceEqualDeep, + shallowEqualObjects, + shouldThrowError, +} from './utils' +import type { QueryClient } from './queryClient' +import type { + ObserverOptionsInput, + QueryObserverResultReader, +} from './queryObserver' +import type { + DefaultedQueryObserverOptions, + QueryObserverResult, +} from './types' + +type CombineContext = { + result?: Array + combine?: CombineFn + value?: TCombinedResult + queryHashes?: Array +} + +type CombineFn = ( + result: Array, +) => TCombinedResult + +type QueriesObserverListener = (result: Array) => void + +type QueryObserverMatch = { + defaultedQueryOptions: DefaultedQueryObserverOptions + observer: QueryObserver + reader?: QueryObserverResultReader +} + +/** + * Returns the items of `array1` that are not in `array2`. + * @param array1 - The items to filter. + * @param array2 - The items to exclude. + * @returns A new array with the items of `array1` that are not in `array2`. + */ +function difference(array1: Array, array2: Array): Array { + const excludeSet = new Set(array2) + return array1.filter((x) => !excludeSet.has(x)) +} + +/** + * Compares two arrays of results by position and field value. + * @param result - The new results. + * @param previous - The previous results, if available. + * @returns Whether the results match. + */ +function equalResults( + result: Array, + previous: Array | undefined, +): boolean { + return ( + !!previous && + result.length === previous.length && + result.every((value, index) => shallowEqualObjects(value, previous[index])) + ) +} + +/** + * A `QueriesObserver` watches an array of queries at once, exposing them as + * a single array of `QueryObserverResult`s (or, when a `combine` option is + * given, as a combined value derived from that array). It manages one + * internal `QueryObserver` per query, and is the primitive that framework + * adapters (e.g. `useQueries`) build their hooks on top of. + * @example + * ```ts + * const observer = new QueriesObserver(queryClient, [ + * { queryKey: ['post', 1], queryFn: fetchPost }, + * { queryKey: ['post', 2], queryFn: fetchPost }, + * ]) + * + * const unsubscribe = observer.subscribe((result) => { + * console.log(result) + * }) + * ``` + */ +export class QueriesObserver< + TCombinedResult = Array, +> extends Subscribable { + #client: QueryClient + #result: Array + #options?: QueriesObserverOptions + #observers: Array + #combinedResult?: TCombinedResult + #combineContext: CombineContext = {} + #observerMatches: Array = [] + #updatingQueries = false + + constructor( + client: QueryClient, + queries: Array>, + options?: QueriesObserverOptions, + ) { + super() + + this.#client = client + this.#options = options + this.#observers = [] + this.#result = [] + + this.setQueries(queries) + } + + protected override onSubscribe(): void { + if (this.listeners.size === 1) { + this.#observers.forEach((observer) => this.#subscribeTo(observer)) + } + } + + protected override onUnsubscribe(): void { + if (!this.listeners.size) { + this.destroy() + } + } + + /** + * Stops observing all queries: clears all listeners and destroys every + * underlying `QueryObserver` this observer manages. + */ + destroy(): void { + this.listeners = new Set() + this.#observers.forEach((observer) => { + observer.destroy() + }) + } + + /** + * Replaces the set of queries being observed. Existing `QueryObserver`s + * are reused for queries that match an already-observed query hash; + * observers for queries that are no longer present are destroyed, and new + * observers are created and subscribed to for newly added queries. + * @param queries - The options of the queries to observe. + * @param options - Replaces the observer's options, e.g. its `combine` function. + * @example + * ```ts + * observer.setQueries([ + * { queryKey: ['post', 1], queryFn: fetchPost }, + * { queryKey: ['post', 3], queryFn: fetchPost }, + * ]) + * ``` + */ + setQueries( + queries: Array, + options?: QueriesObserverOptions, + ): void { + this.#setQueries(this.#findMatchingObservers(queries), options) + } + + #setQueries( + newObserverMatches: Array, + options?: QueriesObserverOptions, + ): void { + this.#options = options + + if (process.env.NODE_ENV !== 'production') { + const queryHashes = newObserverMatches.map( + (match) => match.defaultedQueryOptions.queryHash, + ) + if (new Set(queryHashes).size !== queryHashes.length) { + console.warn( + '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.', + ) + } + } + + notifyManager.batch(() => { + const prevObservers = this.#observers + + // Apply all options before combining or notifying with the new results. + this.#updatingQueries = true + try { + newObserverMatches.forEach((match) => { + if (match.reader) { + match.reader.commit() + } else { + match.observer.setOptions(match.defaultedQueryOptions) + } + }) + } finally { + this.#updatingQueries = false + } + + const newObservers = newObserverMatches.map((match) => match.observer) + const newResult = newObservers.map((observer) => + observer.getCurrentResult(), + ) + + const hasStructuralChange = + prevObservers.length !== newObservers.length || + newObservers.some( + (observer, index) => observer !== prevObservers[index], + ) + + if (!hasStructuralChange && equalResults(newResult, this.#result)) return + + if (hasStructuralChange) { + this.#observerMatches = newObserverMatches.map( + ({ defaultedQueryOptions, observer }) => ({ + defaultedQueryOptions, + observer, + }), + ) + this.#observers = newObservers + } + + this.#result = newResult + + if (!this.hasListeners()) return + + if (hasStructuralChange) { + difference(prevObservers, newObservers).forEach((observer) => { + observer.destroy() + }) + difference(newObservers, prevObservers).forEach((observer) => + this.#subscribeTo(observer), + ) + } + + this.#notify() + }) + } + + /** + * Returns the most recently computed array of `QueryObserverResult`s, one + * per observed query, in the same order as the queries passed to the + * constructor or `setQueries`. + * @returns The current results. + * @example + * ```ts + * const results = observer.getCurrentResult() + * const data = results.map((result) => result.data) + * ``` + */ + getCurrentResult(): Array { + return this.#result + } + + /** + * Returns the underlying `QueryObserver` instances this observer manages, + * in the same order as the queries passed to the constructor or + * `setQueries`. + * @returns The managed query observers. + */ + getObservers() { + return this.#observers + } + + /** + * Creates a reader for the supplied queries and combine function. Reads keep + * result and combine caches local until commit applies the queries and reuses + * their computation state. Abandoned readers do not change active observers. + * @param queries - The options of the queries to read and commit. + * @param options - The combine function used for this reader. + * @returns A reader with local snapshot and combine caches. + */ + createResultReader( + queries: Array>, + options?: QueriesObserverOptions, + ): QueriesObserverResultReader { + const matches = this.#findMatchingObservers(queries).map((match) => ({ + ...match, + reader: match.observer.createResultReader(match.defaultedQueryOptions), + })) + const queryHashes = matches.map( + (match) => match.defaultedQueryOptions.queryHash, + ) + const combine = options?.combine + const context = { ...this.#combineContext } + let result = this.#result + + const getSnapshot = () => { + const nextResult = matches.map((match) => match.reader.getSnapshot()) + if (!shallowEqualObjects(nextResult, result)) { + result = nextResult + } + return result + } + + return { + getSnapshot, + combineResult: (input) => { + // Notifications may have already combined these results. + const committed = this.#combineContext + if ( + committed.combine === combine && + equalResults(input, committed.result) && + shallowEqualObjects(queryHashes, committed.queryHashes) + ) { + Object.assign(context, committed) + } + return this.#combineResult( + this.#trackResult(input, matches), + combine, + queryHashes, + context, + input, + ) + }, + commit: () => { + this.#combineContext = { ...context } + this.#setQueries(matches, { combine }) + if ( + this.#options?.combine === combine && + equalResults(this.#result, context.result) + ) { + this.#combinedResult = context.value + } + }, + } + } + + #trackResult( + result: Array, + matches: Array, + ) { + const trackedProps = new Set() + + return matches.map((match, index) => { + const observerResult = result[index]! + return !match.defaultedQueryOptions.notifyOnChangeProps + ? match.observer.trackResult(observerResult, (accessedProp) => { + // track property on all observers to ensure proper (synchronized) tracking (#7000) + if (!trackedProps.has(accessedProp)) { + trackedProps.add(accessedProp) + matches.forEach((m) => { + m.observer.trackProp(accessedProp) + }) + } + }) + : observerResult + }) + } + + #combineResult( + input: Array, + combine: CombineFn | undefined, + queryHashes?: Array, + context = this.#combineContext, + result = this.#result, + ): TCombinedResult { + if (combine) { + const queryHashesChanged = + queryHashes !== undefined && + context.queryHashes !== undefined && + !shallowEqualObjects(queryHashes, context.queryHashes) + + if ( + !equalResults(result, context.result) || + queryHashesChanged || + combine !== context.combine + ) { + context.value = replaceEqualDeep(context.value, combine(input)) + context.combine = combine + context.result = result + if (queryHashes !== undefined) { + context.queryHashes = queryHashes + } + } + + return context.value as TCombinedResult + } + return input as any + } + + #shouldSkipCombine(): boolean { + return ( + !this.#options?.combine || + this.#observers.some((observer, index) => { + const result = this.#result[index] + const rule = observer.options.throwOnError + return ( + (observer.options.suspense && result?.data === undefined) || + (result?.status === 'error' && + result.fetchStatus !== 'fetching' && + shouldThrowError(typeof rule === 'object' ? rule[1] : rule, [ + result.error, + observer.getCurrentQuery(), + ])) + ) + }) + ) + } + + #findMatchingObservers( + queries: Array, + ): Array { + const prevObserversMap = new Map>() + + this.#observers.forEach((observer) => { + const key = observer.options.queryHash + if (!key) return + + const previousObservers = prevObserversMap.get(key) + + if (previousObservers) { + previousObservers.push(observer) + } else { + prevObserversMap.set(key, [observer]) + } + }) + + const observers: Array = [] + + queries.forEach((options) => { + const defaultedOptions = defaultQueryOptions(this.#client, options) + const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift() + const observer = + match ?? new QueryObserver(this.#client, defaultedOptions) + + observers.push({ + defaultedQueryOptions: defaultedOptions, + observer, + }) + }) + + return observers + } + + #subscribeTo(observer: QueryObserver): void { + // Create the listener here, not in `setQueries`: a listener created there + // keeps the previous observers, and their queries, alive (#12656) + observer.subscribe((result) => { + this.#onUpdate(observer, result) + }) + } + + #onUpdate(observer: QueryObserver, result: QueryObserverResult): void { + if (this.#updatingQueries) return + + const index = this.#observers.indexOf(observer) + if (index !== -1) { + this.#result = this.#result.slice() + this.#result[index] = result + this.#notify() + } + } + + #notify(): void { + if (this.hasListeners()) { + const shouldSkipCombine = this.#shouldSkipCombine() + const previousResult = this.#combinedResult + const newResult = shouldSkipCombine + ? previousResult + : this.#combineResult( + this.#trackResult(this.#result, this.#observerMatches), + this.#options?.combine, + this.#observerMatches.map( + (match) => match.defaultedQueryOptions.queryHash, + ), + ) + + this.#combinedResult = newResult + if (shouldSkipCombine || previousResult !== newResult) { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(this.#result) + }) + }) + } + } + } +} + +/** + * Options for a `QueriesObserver` that apply to all of its queries at once. + */ +export interface QueriesObserverOptions< + TCombinedResult = Array, +> { + /** + * A function that combines the array of `QueryObserverResult`s (one per + * observed query) into a single value. The combined value is memoized and + * only recomputed when one of the underlying results, the query hashes, or + * the `combine` function itself changes. + * + * Defaults to returning the array of `QueryObserverResult`s unchanged. + */ + combine?: CombineFn +} + +/** A cached reader for multiple query results and their combined value. */ +export interface QueriesObserverResultReader< + TCombinedResult, +> extends QueryObserverResultReader> { + /** Track result properties and combine the results with this reader's options. */ + combineResult: (result: Array) => TCombinedResult +} diff --git a/packages/query-core-pluggable/src/query.ts b/packages/query-core-pluggable/src/query.ts new file mode 100644 index 00000000000..cafaf723192 --- /dev/null +++ b/packages/query-core-pluggable/src/query.ts @@ -0,0 +1,874 @@ +import { notifyManager } from './notifyManager' +import { getQueryCache } from './queryClient' +import { fetchState, getDefaultQueryState, successState } from './queryState' +import { Removable } from './removable' +import { CancelledError, createRetryer } from './retryer' +import { + ensureQueryFn, + fetchSignal, + noop, + replaceData, + timeUntilStale, +} from './utils' +import type { createInfiniteFetch } from './infiniteQueryBehavior' +import type { QueryCache } from './queryCache' +import type { QueryClient } from './queryClient' +import type { QueryObserver } from './queryObserver' +import type { Retryer } from './retryer' +import type { + CancelOptions, + DefaultError, + FetchStatus, + QueryKey, + QueryMeta, + QueryOptions, + QueryStatus, + SetDataOptions, + StaleTime, +} from './types' + +interface QueryConfig< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey = QueryKey, +> { + client: QueryClient + queryKey: TQueryKey + queryHash: string + options?: QueryOptions + defaultOptions?: QueryOptions + state?: QueryState +} + +/** + * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace `fetchFn` to change + * how the query fetches (e.g. to fetch pages for an infinite query). + */ +export interface FetchContext< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey = QueryKey, +> { + /** + * The function that runs the fetch. By default it calls `queryFn`; `onFetch` can replace it. + */ + fetchFn: () => unknown | Promise + /** + * The options of this fetch. + */ + fetchOptions?: FetchOptions + /** + * The `AbortSignal` that aborts when the fetch is cancelled. + */ + signal: AbortSignal + /** + * The options of the query. + */ + options: QueryOptions + /** + * The `QueryClient` the query belongs to. + */ + client: QueryClient + /** + * The key of the query. + */ + queryKey: TQueryKey + /** + * The state of the query when the fetch starts. + */ + state: QueryState +} + +/** + * Customizes how a query fetches, e.g. the behavior that fetches the pages of an infinite query. + */ +export interface QueryBehavior< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> { + /** + * Called before each fetch of the query, e.g. to replace `fetchFn` in the context. + */ + onFetch: ( + context: FetchContext, + query: Query, + ) => void +} + +const updateState = Symbol() + +// CLASS + +/** + * Represents a single cached query. A `Query` holds the query's key, options, + * state (data/error/status), and the observers currently subscribed to it. + * + * Instances are created and managed internally by `QueryCache`; application + * code typically interacts with queries indirectly through `QueryClient` or + * a framework hook like `useQuery`. Direct access to a `Query` instance is + * possible via `findCachedQuery` or `findCachedQueries` for inspecting cache state. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * const query = findCachedQuery(queryCache, { queryKey: ['posts'] }) + * + * if (query) { + * console.log(query.state.dataUpdatedAt) + * } + * ``` + */ +export class Query< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends Removable { + queryKey: TQueryKey + queryHash: string + options!: QueryOptions + state: QueryState + #prepareInfiniteFetch?: typeof createInfiniteFetch + + #initialState: QueryState + #revertState?: QueryState + #cache: QueryCache + #client: QueryClient + #retryer?: Retryer + #fetchPromise?: Promise + observers: Array> + #defaultOptions?: QueryOptions + #abortSignalConsumed: boolean + + constructor(config: QueryConfig) { + super() + + this.#abortSignalConsumed = false + this.#defaultOptions = config.defaultOptions + this.setOptions(config.options) + this.observers = [] + this.#client = config.client + this.#cache = getQueryCache(this.#client) + this.queryKey = config.queryKey + this.queryHash = config.queryHash + this.#initialState = getDefaultQueryState(this.options) + this.state = config.state ?? this.#initialState + this.scheduleGc() + } + /** + * The `meta` object passed in the query's options, if any. + * @returns The query's `meta`, or `undefined` if none was set. + */ + get meta(): QueryMeta | undefined { + return this.options.meta + } + + /** + * `'infinite'` for an infinite query, otherwise `undefined`. + * @internal + * @returns The type of the query, determined by its page fetcher. + */ + get queryType(): 'infinite' | undefined { + return this.#prepareInfiniteFetch ? 'infinite' : undefined + } + + /** + * The promise for the currently in-flight fetch, if the query is fetching. + * `undefined` when the query is not fetching. + * @returns The promise of the in-flight fetch, or `undefined`. + */ + get promise(): Promise | undefined { + return this.#retryer?.promise + } + + /** + * Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets + * the `initialData` from the new options, if any. + * @internal + * @param options - The new query options, merged on top of the query's default options. + */ + setOptions( + options?: QueryOptions, + ): void { + this.options = { ...this.#defaultOptions, ...options } + + const internalOptions = options as + | { _prepareInfiniteFetch?: typeof createInfiniteFetch } + | undefined + this.#prepareInfiniteFetch ??= internalOptions?._prepareInfiniteFetch + + this.updateGcTime(this.options.gcTime) + + // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state' + if (this.state && this.state.data === undefined) { + const defaultState = getDefaultQueryState(this.options) + if (defaultState.data !== undefined) { + this.setState( + successState(defaultState.data, defaultState.dataUpdatedAt), + ) + this.#initialState = defaultState + } + } + } + + protected override optionalRemove() { + if (!this.observers.length && this.state.fetchStatus === 'idle') { + this.#cache.remove(this) + } + } + + /** + * Writes new data to the query and marks it as successfully fetched. + * @internal + * @param newData - The data to write. Structural sharing with the current data is applied. + * @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as + * manual (e.g. from `setQueryData`). + * @returns The data that was written. + */ + setData( + newData: TData, + options?: SetDataOptions & { manual: boolean }, + ): TData { + const data = replaceData(this.state.data, newData, this.options) + + const manual = options?.manual + const dataUpdatedAt = options?.updatedAt + this.state = { + ...this.state, + ...successState(data, dataUpdatedAt), + dataUpdateCount: this.state.dataUpdateCount + 1, + ...(!manual && { + fetchStatus: 'idle' as const, + fetchFailureCount: 0, + fetchFailureReason: null, + }), + } + // A manual write becomes the snapshot to restore if a fetch is cancelled. + this.#revertState = manual ? this.state : undefined + this.#notify({ type: 'success', data, dataUpdatedAt, manual }) + + return data + } + + /** + * Merges the given partial state directly into this query's state, notifying observers. Used + * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a + * user manually trigger a loading/error state or edit the cached data. + * @param state - The partial state to merge into the query's state. + */ + setState(state: Partial>): void { + this[updateState](state, { type: 'setState', state }) + } + + /** + * Cancels the query's currently in-flight fetch, if any. + * - Returns a promise that resolves once the cancellation has settled. + * - If no fetch is in progress, resolves immediately. + * @param options - Set `revert` to restore the state from before the fetch started, and `silent` + * to suppress the cancellation error when a new fetch replaces the cancelled one. + * @returns A promise that resolves once the cancellation has settled. + * @example + * ```ts + * await query.cancel() + * ``` + */ + cancel(options?: CancelOptions): Promise { + const promise = this.#retryer?.promise + this.#retryer?.cancel(options) + return promise ? promise.then(noop, noop) : Promise.resolve() + } + + /** + * Silently cancels any in-flight fetch, then clears the query's garbage + * collection timeout. Called by `QueryCache` when the query is removed from + * the cache. + * @see {@link Query#cancel} + */ + override destroy(): void { + this.cancel({ silent: true }) + // An abort listener can unsubscribe and schedule GC during cancellation. + super.destroy() + } + + /** + * The state the query was created with. + * @internal + * @returns The state the query had when it was first created, used by {@link resetCachedQuery}. + */ + get resetState(): QueryState { + return this.#initialState + } + + /** + * Returns `true` if the query's data is stale relative to the given + * `staleTime` (defaults to `0`). + * - A query with no data is always stale. + * - `staleTime: 'static'` is never stale. + * - An invalidated query is always stale. + * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`. + * @param staleTime - The time, in milliseconds, after which data is considered stale, or + * `'static'` to never treat existing data as stale. A query without data is stale either way. + * @returns `true` if the query's data is stale. + * @see {@link isQueryStale} + * @example + * ```ts + * const isStale = query.isStaleByTime(60 * 1000) + * ``` + */ + isStaleByTime(staleTime: StaleTime = 0): boolean { + // no data is always stale + if (this.state.data === undefined) { + return true + } + // static is never stale + if (staleTime === 'static') { + return false + } + // if the query is invalidated, it is stale + if (this.state.isInvalidated) { + return true + } + + return !timeUntilStale(this.state.dataUpdatedAt, staleTime) + } + + /** + * Refetches the query when the window regains focus, if an observer wants that, and continues a + * paused fetch. + * @internal + */ + onFocus(): void { + const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus()) + + observer?.refetch({ cancelRefetch: false }) + + // Continue fetch if currently paused + this.#retryer?.continue() + } + + /** + * Refetches the query when the app reconnects, if an observer wants that, and continues a paused + * fetch. + * @internal + */ + onOnline(): void { + const observer = this.observers.find((x) => x.shouldFetchOnReconnect()) + + observer?.refetch({ cancelRefetch: false }) + + // Continue fetch if currently paused + this.#retryer?.continue() + } + + /** + * Subscribes an observer to the query and stops its garbage collection. + * @internal + * @param observer - The observer to add. Adding an observer that is already subscribed does + * nothing. + */ + addObserver(observer: QueryObserver): void { + if (!this.observers.includes(observer)) { + this.observers.push(observer) + + // Stop the query from being garbage collected + this.clearGcTimeout() + + this.#cache.notify({ type: 'observerAdded', query: this, observer }) + } + } + + /** + * Unsubscribes an observer from the query. + * @internal + * @param observer - The observer to remove. When the last observer is removed, the in-flight + * fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped), + * and garbage collection is scheduled if the query is still in the cache. + */ + removeObserver(observer: QueryObserver): void { + const index = this.observers.indexOf(observer) + if (index !== -1) { + this.observers.splice(index, 1) + + if (!this.observers.length) { + // If the transport layer does not support cancellation + // we'll let the query continue so the result can be cached + if (this.#retryer) { + if ( + this.#abortSignalConsumed || + (this.state.fetchStatus === 'paused' && + this.state.status === 'pending') + ) { + this.#retryer.cancel({ revert: true }) + } else { + this.#retryer.cancelRetry() + } + } + + this.#scheduleGcIfCached() + } + + this.#cache.notify({ type: 'observerRemoved', query: this, observer }) + } + } + + /** + * Fetches the query, i.e. runs its `queryFn` (through any configured + * retryer/behavior) and updates the query's state with the result. + * - If a fetch is already in flight, returns its promise instead of + * starting a new one, unless `fetchOptions.cancelRefetch` is set and the + * query already has data, in which case the current fetch is silently + * cancelled first. + * - If `options` is passed, it replaces the query's current options + * before fetching. + * @param options - Query options that replace the query's current options before fetching. They + * are not applied when an in-flight fetch is reused. + * @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch first (only if the query + * already has data), and `meta` to pass extra information to the query's behavior. + * @returns A promise that resolves with the fetched data, or rejects with the fetch error. If the + * fetch is cancelled with `revert` while the query has data, it resolves with the restored data + * instead. + */ + async fetch( + options?: QueryOptions, + fetchOptions?: FetchOptions, + ): Promise { + if ( + this.state.fetchStatus !== 'idle' && + // If the promise in the retryer is already rejected, we have to definitely + // re-start the fetch; there is a chance that the query is still in a + // pending state when that happens + this.#retryer?.status() !== 'rejected' + ) { + if (this.state.data !== undefined && fetchOptions?.cancelRefetch) { + // Silently cancel current fetch if the user wants to cancel refetch + this.cancel({ silent: true }) + } else if (this.#retryer && this.#fetchPromise) { + // make sure that retries that were potentially cancelled due to unmounts can continue + this.#retryer.continueRetry() + // Return current promise if we are already fetching + return this.#fetchPromise + } + } + + // Update config if passed, otherwise the config from the last execution is used + if (options) { + this.setOptions(options) + } + + // Use the options from the first observer with a query function if no function is found. + // This can happen when the query is hydrated or created with setQueryData. + if (!this.options.queryFn) { + const observer = this.observers.find((x) => x.options.queryFn) + if (observer) { + this.setOptions(observer.options) + } + } + + if (process.env.NODE_ENV !== 'production') { + if (!Array.isArray(this.options.queryKey)) { + console.error( + `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']`, + ) + } + } + + const abortController = new AbortController() + + const addSignalProperty: ( + object: object, + ) => asserts object is { signal: AbortSignal } = (object) => { + Object.defineProperties(object, { + [fetchSignal]: { value: abortController.signal, enumerable: true }, + signal: { + enumerable: true, + get: () => { + this.#abortSignalConsumed = true + return abortController.signal + }, + }, + }) + } + + const activeOptions = this.options + const runFetch = + this.#prepareInfiniteFetch?.( + this.#client, + this as unknown as Query, + fetchOptions, + addSignalProperty, + ) ?? + (() => { + const queryFn = ensureQueryFn(this.options, fetchOptions) + + const queryFnContext = { + client: this.#client, + queryKey: this.queryKey, + meta: this.meta, + } + addSignalProperty(queryFnContext) + + this.#abortSignalConsumed = false + if (this.options.persister) { + return this.options.persister( + queryFn, + queryFnContext, + this as unknown as Query, + ) + } + + return queryFn(queryFnContext) + }) + + // Store state in case the current fetch needs to be reverted + this.#revertState = this.state + + // Set to fetching state if not already in it + if ( + this.state.fetchStatus === 'idle' || + this.state.fetchMeta !== fetchOptions?.meta + ) { + const meta = fetchOptions?.meta + this[updateState]( + { + ...fetchState(this.state.data, this.options), + fetchMeta: meta ?? null, + }, + { type: 'fetch', meta }, + ) + } + + // Try to fetch the data + const retryer = (this.#retryer = createRetryer({ + initialPromise: fetchOptions?.initialPromise as + | Promise + | undefined, + fn: runFetch as () => Promise, + onCancel: (error) => { + if (error instanceof CancelledError && error.revert) { + this.setState({ + ...this.#revertState, + fetchStatus: 'idle' as const, + }) + } + abortController.abort() + }, + onFail: (failureCount, error) => { + this[updateState]( + { fetchFailureCount: failureCount, fetchFailureReason: error }, + { type: 'failed', failureCount, error }, + ) + }, + onPause: () => { + this[updateState]({ fetchStatus: 'paused' }, { type: 'pause' }) + }, + onContinue: () => { + this[updateState]({ fetchStatus: 'fetching' }, { type: 'continue' }) + }, + retry: activeOptions.retry, + retryDelay: activeOptions.retryDelay, + networkMode: activeOptions.networkMode, + canRun: () => true, + })) + + const fetchPromise = (async () => { + try { + const data = await retryer.promise + // this is more of a runtime guard + if (data === undefined) { + if (process.env.NODE_ENV !== 'production') { + console.error( + `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`, + ) + } + throw new Error(`${this.queryHash} data is undefined`) + } + + this.setData(data) + + // Notify cache callback + this.#cache.config.onSuccess?.(data, this as Query) + this.#cache.config.onSettled?.( + data, + this.state.error as any, + this as Query, + ) + return data + } catch (error) { + if (error instanceof CancelledError) { + if (error.silent) { + if (this.#retryer !== retryer && this.#fetchPromise) { + // A new fetch replaced the silently cancelled one, + // so we piggyback onto that promise. + return this.#fetchPromise + } + throw error + } else if (error.revert) { + // transform error into reverted state data + // if the initial fetch was cancelled, we have no data, so we have + // to get reject with a CancelledError + if (this.state.data === undefined) { + throw error + } + return this.state.data + } + } + const fetchError = error as TError + this[updateState]( + { + error: fetchError, + errorUpdatedAt: Date.now(), + errorUpdateCount: this.state.errorUpdateCount + 1, + fetchFailureCount: this.state.fetchFailureCount + 1, + fetchFailureReason: fetchError, + fetchStatus: 'idle', + status: 'error', + isInvalidated: true, + }, + { type: 'error', error: fetchError }, + ) + + // Notify cache callback + this.#cache.config.onError?.( + error as any, + this as Query, + ) + this.#cache.config.onSettled?.( + this.state.data, + error as any, + this as Query, + ) + + throw error // rethrow the error for further handling + } finally { + // The settled retryer's promise would otherwise pin this fetch's raw + // result (a second copy after structural sharing) for the query's lifetime + if (this.#retryer === retryer) { + this.#retryer = undefined + this.#fetchPromise = undefined + } + this.#scheduleGcIfCached() + } + })() + this.#fetchPromise = fetchPromise + retryer.start() + return fetchPromise + } + + #scheduleGcIfCached(): void { + if ( + this.#cache.get( + this.queryHash, + ) === this + ) { + this.scheduleGc() + } + } + + /** + * Merges a state transition and publishes its action to observers and cache listeners. + * @internal + * @param state - The changes to apply before sending the notification. + * @param action - The event that caused this transition. + */ + [updateState]( + state: Partial>, + action: Action, + ): void { + this.state = { ...this.state, ...state } + this.#notify(action) + } + + #notify(action: Action): void { + notifyManager.batch(() => { + // Keep the current iteration stable if an observer unsubscribes + // synchronously while it is being notified. + this.observers.slice().forEach((observer) => { + observer.onQueryUpdate() + }) + + this.#cache.notify({ query: this, type: 'updated', action }) + }) + } +} + +/** + * Cancels the active request and restores the initial state of one cached query. + * @param query - The cache entry to reset. + */ +export function resetCachedQuery(query: Query): void { + query.destroy() + query.setState(query.resetState) +} + +/** + * Marks one cached query as invalidated and notifies its observers once per + * transition. Use {@link invalidateQueries} to also refetch matching queries. + * @param query - The cache entry to invalidate. + */ +export function invalidateCachedQuery(query: Query): void { + if (!query.state.isInvalidated) { + query[updateState]({ isInvalidated: true }, { type: 'invalidate' }) + } +} + +export { fetchState } from './queryState' + +/** + * The raw state stored on a `Query` instance. This is the underlying state + * that observer results (e.g. `QueryObserverResult`) are derived from. + */ +export interface QueryState { + /** + * The last successfully resolved data for the query. + */ + data: TData | undefined + /** + * The number of times the query has successfully resolved. + */ + dataUpdateCount: number + /** + * The timestamp for when the query most recently returned the `status` as `"success"`. + */ + dataUpdatedAt: number + /** + * The error object for the query, if the last attempt resulted in an error. + * - Defaults to `null`. + */ + error: TError | null + /** + * The sum of all errors, incremented every time the query resolves with an error. + */ + errorUpdateCount: number + /** + * The timestamp for when the query most recently returned the `status` as `"error"`. + */ + errorUpdatedAt: number + /** + * The failure count for the current fetch. + * - Incremented every time the fetch fails. + * - Reset to `0` when the fetch succeeds. + */ + fetchFailureCount: number + /** + * The reason the current fetch failed, as reported by the retryer. + * - Reset to `null` when the fetch succeeds. + */ + fetchFailureReason: TError | null + /** + * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the + * `fetchMore` direction for infinite queries. + */ + fetchMeta: FetchMeta | null + /** + * Whether the query has been marked as invalidated via `invalidate()`. + * - Reset to `false` whenever the query resolves successfully. + */ + isInvalidated: boolean + /** + * The status of the query. + * - `pending` if there's no cached data and no attempt was finished yet. + * - `error` if the last attempt resulted in an error. + * - `success` if the query has data. + */ + status: QueryStatus + /** + * The fetch status of the query. + * - `fetching`: the `queryFn` is currently executing. + * - `paused`: a fetch wanted to run but has been paused (see network mode). + * - `idle`: the query is not fetching. + */ + fetchStatus: FetchStatus +} + +/** + * The direction an infinite query fetches in: `'forward'` for the next page, `'backward'` for the + * previous one. + */ +export type FetchDirection = 'forward' | 'backward' + +/** + * Metadata for a fetch, e.g. the direction when an infinite query fetches more pages. + */ +export interface FetchMeta { + /** + * Set when an infinite query fetches another page, with the direction to fetch in. + */ + fetchMore?: { direction: FetchDirection } +} + +/** + * Options for a single fetch of a query. + */ +export interface FetchOptions { + /** + * If `true`, an in-flight fetch is cancelled before starting a new one, when the query already + * has data. Otherwise, the in-flight fetch is reused. + */ + cancelRefetch?: boolean + /** + * Metadata of the fetch, stored in the query's `fetchMeta` state. + */ + meta?: FetchMeta + /** + * A promise to use for the first attempt instead of calling `fetchFn`, e.g. a pending promise + * restored by `hydrate`. + */ + initialPromise?: Promise +} + +interface FailedAction { + type: 'failed' + failureCount: number + error: TError +} + +interface FetchAction { + type: 'fetch' + meta?: FetchMeta +} + +interface SuccessAction { + data: TData | undefined + type: 'success' + dataUpdatedAt?: number + manual?: boolean +} + +interface ErrorAction { + type: 'error' + error: TError +} + +interface InvalidateAction { + type: 'invalidate' +} + +interface PauseAction { + type: 'pause' +} + +interface ContinueAction { + type: 'continue' +} + +interface SetStateAction { + type: 'setState' + state: Partial> +} + +/** + * The actions a query dispatches to update its state, e.g. when it starts fetching, fails, or + * succeeds. + */ +export type Action = + | ContinueAction + | ErrorAction + | FailedAction + | FetchAction + | InvalidateAction + | PauseAction + | SetStateAction + | SuccessAction diff --git a/packages/query-core-pluggable/src/queryCache.ts b/packages/query-core-pluggable/src/queryCache.ts new file mode 100644 index 00000000000..454b786eebe --- /dev/null +++ b/packages/query-core-pluggable/src/queryCache.ts @@ -0,0 +1,328 @@ +import { notifyManager } from './notifyManager' +import { Query } from './query' +import { defaultQueryOptions, getQueryDefaults } from './queryClient' +import { Subscribable } from './subscribable' +import { hashKeyByOptions } from './utils' +import type { Action as QueryAction, QueryState } from './query' +import type { QueryClient } from './queryClient' +import type { QueryObserver } from './queryObserver' +import type { + CacheKeyConfig, + DefaultError, + NotifyEvent, + QueryKey, + QueryOptions, + WithRequired, +} from './types' + +/** + * Global callbacks that fire for every query handled by a `QueryCache`, regardless of which + * component or observer triggered it. Unlike `QueryClient`'s `defaultOptions`, which a query can + * override, these callbacks are always called. Unlike `MutationCacheConfig`'s callbacks, these + * are fire-and-forget: their return value is not awaited before the query settles. + */ +export interface QueryCacheConfig { + /** + * Configures query key comparison and hashing globally. + * `equalityFn` compares individual values during partial matching and defaults to strict equality. + * `hashFn` hashes query keys and defaults to `hashKey`. + */ + queryKey?: CacheKeyConfig + /** Called when any query in the cache encounters an error. */ + onError?: ( + error: DefaultError, + query: Query, + ) => void + /** Called when any query in the cache is successful. */ + onSuccess?: (data: unknown, query: Query) => void + /** Called when any query in the cache is settled, either successfully or with an error. */ + onSettled?: ( + data: unknown | undefined, + error: DefaultError | null, + query: Query, + ) => void +} + +/** + * The event passed to a `QueryCache` subscriber. Fired whenever a query is added or removed from + * the cache, its state is updated (e.g. via `query.setState` or `removeQueries`), or + * one of its observers is added, removed, or has its results or options updated. + */ +export type QueryCacheNotifyEvent = + | NotifyEventQueryAdded + | NotifyEventQueryRemoved + | NotifyEventQueryUpdated + | NotifyEventQueryObserverAdded + | NotifyEventQueryObserverRemoved + | NotifyEventQueryObserverResultsUpdated + | NotifyEventQueryObserverOptionsUpdated + +type QueryCacheListener = (event: QueryCacheNotifyEvent) => void + +/** + * The store a `QueryCache` keeps its queries in, keyed by query hash. + */ +export interface QueryStore { + /** + * Returns whether a query with the given hash is stored. + */ + has: (queryHash: string) => boolean + /** + * Stores a query under its hash. + */ + set: (queryHash: string, query: Query) => void + /** + * Returns the query with the given hash, if any. + */ + get: (queryHash: string) => Query | undefined + /** + * Removes the query with the given hash. + */ + delete: (queryHash: string) => void + /** + * Returns an iterator over all stored queries. + */ + values: () => IterableIterator +} + +interface NotifyEventQueryAdded extends NotifyEvent { + type: 'added' + query: Query +} + +interface NotifyEventQueryRemoved extends NotifyEvent { + type: 'removed' + query: Query +} + +interface NotifyEventQueryUpdated extends NotifyEvent { + type: 'updated' + query: Query + action: QueryAction +} + +interface NotifyEventQueryObserverAdded extends NotifyEvent { + type: 'observerAdded' + query: Query + observer: QueryObserver +} + +interface NotifyEventQueryObserverRemoved extends NotifyEvent { + type: 'observerRemoved' + query: Query + observer: QueryObserver +} + +interface NotifyEventQueryObserverResultsUpdated extends NotifyEvent { + type: 'observerResultsUpdated' + query: Query +} + +interface NotifyEventQueryObserverOptionsUpdated extends NotifyEvent { + type: 'observerOptionsUpdated' + query: Query + observer: QueryObserver +} + +// CLASS + +/** + * The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta + * information, and state of the queries it contains. + * + * Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient` + * for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of + * safe/known updates to the cache, such as queries being added, removed, or updated — updates made + * outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do + * not notify subscribers. + * @example + * ```ts + * const unsubscribe = queryCache.subscribe((event) => { + * console.log(event.type, event.query) + * }) + * ``` + */ +export class QueryCache extends Subscribable { + #queries: QueryStore + + constructor(public config: QueryCacheConfig = {}) { + super() + this.#queries = new Map() + } + + /** + * Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or + * builds and adds a new one to the cache if none exists yet. Used by framework adapters and + * plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing + * the reactive `QueryObserver` machinery. + * @param client - The client the query belongs to, used to default its options. + * @param options - The query options, including the `queryKey`. A new query is created with the + * options defaulted by {@link defaultQueryOptions}. + * @param state - The initial state of a newly created query, e.g. when hydrating. Ignored if the + * query already exists. + * @returns The existing or newly created query. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * const query = queryCache.build(queryClient, { + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * ``` + */ + build< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + client: QueryClient, + options: WithRequired< + QueryOptions, + 'queryKey' + >, + state?: QueryState, + ): Query { + const queryKey = options.queryKey + const queryHash = + options.queryHash ?? hashKeyByOptions(queryKey, this.config.queryKey) + let query = this.get(queryHash) + + if (!query) { + query = new Query({ + client, + queryKey, + queryHash, + options: defaultQueryOptions(client, options), + state, + defaultOptions: getQueryDefaults(client, queryKey), + }) + this.add(query) + } + + return query + } + + /** + * Adds a query to the cache. + * @internal + * @param query - The query to add. If a query with the same hash is already cached, nothing + * happens. + */ + add(query: Query): void { + if (!this.#queries.has(query.queryHash)) { + this.#queries.set(query.queryHash, query) + + this.notify({ + type: 'added', + query, + }) + } + } + + /** + * Destroys the given `Query` and removes it from the cache, notifying subscribers with a + * `'removed'` event. A no-op if the query is no longer the one currently stored under its hash + * (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror + * removals across `QueryCache` instances. + * @param query - The query to remove. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * const query = findCachedQuery(queryCache, { queryKey: ['posts'] }) + * + * if (query) { + * queryCache.remove(query) + * } + * ``` + */ + remove(query: Query): void { + const queryInMap = this.#queries.get(query.queryHash) + + if (queryInMap === query) { + query.destroy() + this.#queries.delete(query.queryHash) + this.notify({ type: 'removed', query }) + } + } + + /** + * Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none + * exists. Unlike {@link findCachedQuery}, this looks up by the already-computed hash rather + * than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash + * to look up directly. + * @param queryHash - The hash of the query to look up. + * @returns The query stored under the hash, or `undefined`. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * const queryHash = hashKey(['posts']) + * + * const query = queryCache.get(queryHash) + * ``` + */ + get< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + queryHash: string, + ): Query | undefined { + return this.#queries.get(queryHash) as + | Query + | undefined + } + + /** + * Returns all queries within the cache. + * @returns Every query in the cache. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * const queries = queryCache.getAll() + * ``` + */ + getAll(): Array { + return [...this.#queries.values()] + } + + /** + * Notifies every cache listener of an event, in one batch. + * @internal + * @param event - The event passed to every listener. + */ + notify(event: QueryCacheNotifyEvent): void { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(event) + }) + }) + } + + /** + * Calls {@link Query#onFocus} on every cached query, in one batch. + * @internal + */ + onFocus(): void { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + query.onFocus() + }) + }) + } + + /** + * Calls {@link Query#onOnline} on every cached query, in one batch. + * @internal + */ + onOnline(): void { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + query.onOnline() + }) + }) + } +} diff --git a/packages/query-core-pluggable/src/queryCacheOperations.ts b/packages/query-core-pluggable/src/queryCacheOperations.ts new file mode 100644 index 00000000000..fb736bc1baf --- /dev/null +++ b/packages/query-core-pluggable/src/queryCacheOperations.ts @@ -0,0 +1,81 @@ +import { notifyManager } from './notifyManager' +import { matchQuery } from './utils' +import type { Query } from './query' +import type { QueryCache } from './queryCache' +import type { DefaultError, WithRequired } from './types' +import type { QueryFilters } from './utils' + +/** + * Looks up the first query matching the supplied key and filters. + * @param cache - The cache to search. + * @param filters - The filters to match, including the required `queryKey`. `exact` defaults to + * `true`. + * @returns The first matching query, or `undefined`. + * @see {@link findCachedQueries} + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * const query = findCachedQuery(queryCache, { queryKey: ['posts'] }) + * ``` + */ +export function findCachedQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, +>( + cache: QueryCache, + filters: WithRequired, +): Query | undefined { + const defaultedFilters = { exact: true, ...filters } + + return cache + .getAll() + .find((query) => + matchQuery(defaultedFilters, query, cache.config.queryKey), + ) as Query | undefined +} + +/** + * Returns every matching query in cache order. Keys match by prefix unless + * `exact` is enabled. + * @param cache - The cache to search. + * @param filters - The filters to match. Without filters, every query is returned. + * @returns The matching queries. + * @see {@link findCachedQuery} + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * const queries = findCachedQueries(queryCache, { queryKey: ['posts'] }) + * ``` + */ +export function findCachedQueries( + cache: QueryCache, + filters: QueryFilters = {}, +): Array { + const queries = cache.getAll() + return Object.keys(filters).length > 0 + ? queries.filter((query) => + matchQuery(filters, query, cache.config.queryKey), + ) + : queries +} + +/** + * Removes all queries from the cache. + * @param cache - The cache to empty. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * clearQueryCache(queryCache) + * ``` + */ +export function clearQueryCache(cache: QueryCache): void { + notifyManager.batch(() => { + cache.getAll().forEach((query) => { + cache.remove(query) + }) + }) +} diff --git a/packages/query-core-pluggable/src/queryClient.ts b/packages/query-core-pluggable/src/queryClient.ts new file mode 100644 index 00000000000..208e75c47e0 --- /dev/null +++ b/packages/query-core-pluggable/src/queryClient.ts @@ -0,0 +1,794 @@ +import { focusManager } from './focusManager' +import { onlineManager } from './onlineManager' +import { QueryCache } from './queryCache' +import { clearQueryCache, findCachedQueries } from './queryCacheOperations' +import { + defaultQueryFn, + functionalUpdate, + hashKeyByOptions, + partialMatchKey, + resolveQueryValue, + skipToken, +} from './utils' +import type { MutationCache } from './mutationCache' +import type { QueryState } from './query' +import type { + CacheKeyConfig, + DefaultError, + DefaultOptions, + DefaultedQueryObserverOptions, + InferDataFromTag, + InferErrorFromTag, + MutationKey, + MutationObserverOptions, + MutationOptions, + OmitKeyof, + QueryClientConfig, + QueryErrorBoundaryOption, + QueryExecuteOptions, + QueryKey, + QueryObserverOptionsBase, + QueryOptions, + SetDataOptions, +} from './types' +import type { MutationFilters, QueryFilters, Updater } from './utils' + +/** Options whose query function always executes. */ +export type WithoutSkipToken = Omit< + T, + 'queryFn' +> & { + queryFn?: Exclude +} + +type QueryDefaults = OmitKeyof, 'queryKey'> +type MutationDefaults = MutationOptions + +class KeyDefaults< + TKey extends ReadonlyArray, + TOptions extends object, +> { + #entries = new Map() + + set(key: TKey, options: TOptions, config?: CacheKeyConfig): void { + this.#entries.set(hashKeyByOptions(key, config), { key, options }) + } + + get(key: TKey, config?: CacheKeyConfig): Partial { + const result: Partial = {} + for (const entry of this.#entries.values()) { + if (partialMatchKey(key, entry.key, config?.equalityFn)) { + Object.assign(result, entry.options) + } + } + return result + } +} + +/** @internal */ +export const mutationCacheKey = Symbol.for( + '@tanstack/query-core-pluggable/mutationCache', +) + +const clientState = Symbol.for('@tanstack/query-core-pluggable/clientState') + +/** Holds the caches, defaults and subscriptions shared by this client's consumers. */ +export class QueryClient { + /** @internal */ + [mutationCacheKey]?: MutationCache + /** @internal */ + readonly [clientState]: { + queryCache: QueryCache + defaultOptions: DefaultOptions + queryDefaults?: KeyDefaults + mutationDefaults?: KeyDefaults + mountCount: number + unsubscribeFocus?: () => void + unsubscribeOnline?: () => void + } + + constructor(config: QueryClientConfig = {}) { + this[mutationCacheKey] = config.mutationCache + this[clientState] = { + queryCache: config.queryCache ?? new QueryCache(), + defaultOptions: config.defaultOptions ?? {}, + mountCount: 0, + } + } +} + +/** + * Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start + * listening for focus/online events and resume paused mutations. Ref-counted via an internal + * mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down + * the shared listeners until the last one unmounts. + * @param client - The client whose subscriptions are managed. + */ +export function mountQueryClient(client: QueryClient): void { + client[clientState].mountCount++ + if (client[clientState].mountCount !== 1) return + + client[clientState].unsubscribeFocus = focusManager.subscribe( + async (focused) => { + if (focused) { + await resumePausedMutations(client) + client[clientState].queryCache.onFocus() + } + }, + ) + client[clientState].unsubscribeOnline = onlineManager.subscribe( + async (online) => { + if (online) { + await resumePausedMutations(client) + client[clientState].queryCache.onOnline() + } + }, + ) +} + +/** + * The inverse of {@link mountQueryClient} — called by a framework adapter's + * `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online + * listeners once the mount count returns to `0`. + * @param client - The client whose subscriptions are managed. + */ +export function unmountQueryClient(client: QueryClient): void { + client[clientState].mountCount-- + if (client[clientState].mountCount !== 0) return + + client[clientState].unsubscribeFocus?.() + client[clientState].unsubscribeFocus = undefined + + client[clientState].unsubscribeOnline?.() + client[clientState].unsubscribeOnline = undefined +} + +/** + * Returns the number of queries in the cache that are currently fetching, optionally + * matching a set of filters. This includes background-fetching, loading new pages, and + * loading more infinite query results. + * @param client - The client that owns this operation. + * @param filters - Narrows down which fetching queries are counted. Without filters, every + * fetching query is counted. + * @returns The number of matching queries whose `fetchStatus` is `'fetching'`. + * @example + * ```ts + * if (countFetchingQueries(queryClient)) { + * console.log('At least one query is fetching!') + * } + * ``` + */ +export function countFetchingQueries( + client: QueryClient, + filters?: Omit, +): number { + return findCachedQueries(client[clientState].queryCache, { + ...filters, + fetchStatus: 'fetching', + }).length +} + +/** + * Returns the number of mutations in the cache that are currently pending, optionally + * matching a set of filters. + * @param client - The client that owns this operation. + * @param filters - Narrows down which pending mutations are counted. Without filters, every + * pending mutation is counted. + * @returns The number of matching mutations whose `status` is `'pending'`. + * @example + * ```ts + * if (isMutating(queryClient)) { + * console.log('At least one mutation is pending!') + * } + * ``` + */ +export function isMutating< + TMutationFilters extends MutationFilters = MutationFilters< + any, + any + >, +>( + client: QueryClient, + filters?: NoInfer>, +): number { + return ( + client[mutationCacheKey]?.findAll({ ...filters, status: 'pending' }) + .length ?? 0 + ) +} + +/** + * Imperative (non-reactive) way to retrieve data for a QueryKey. + * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates. + * + * Hint: Do not use this function inside a component, because it won't receive updates. + * Use `useQuery` to create a `QueryObserver` that subscribes to changes. + * @param client - The client that owns this operation. + * @param queryKey - The query key of the query to read. + * @returns The cached data for the query, or `undefined` if no query with this key has been observed yet. + * @see {@link getQueriesData} + */ +export function getQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, +>( + client: QueryClient, + queryKey: TTaggedQueryKey, +): TInferredQueryFnData | undefined { + const options = defaultQueryOptions(client, { queryKey }) + + return client[clientState].queryCache.get( + options.queryHash, + )?.state.data +} + +/** + * Synchronous way to immediately update a query's cached data. If the updater (or the value + * passed) resolves to `undefined`, the cache is left untouched and no query is created; + * otherwise, if the query does not exist yet, it will be created. To update multiple queries + * at once by partially matching query keys, import `setQueriesData`. + * + * Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved + * via {@link getQueryData}, in place. + * @param client - The client that owns this operation. + * @param queryKey - The query key to set data for. + * @param updater - Either the new data, or a function that receives the current data (which + * may be `undefined`) and returns the new data. + * @param options - Set `updatedAt` to override the timestamp the written data is recorded with. + * @returns The data that was written, or `undefined` if the updater returned `undefined` — in that case + * the write is skipped and the cache is left unchanged. + * @example + * ```ts + * setQueryData(queryClient, ['posts'], newPosts) + * + * // Or, using an updater function that receives the current data: + * setQueryData(queryClient, ['posts'], (oldPosts) => [...oldPosts, newPost]) + * ``` + */ +export function setQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, +>( + client: QueryClient, + queryKey: TTaggedQueryKey, + updater: Updater< + InferDataFromTag, TTaggedQueryKey> | undefined, + NoInfer | undefined + >, + options?: SetDataOptions, +): NoInfer | undefined { + const defaultedOptions = defaultQueryOptions< + any, + any, + unknown, + any, + QueryKey + >(client, { queryKey }) + + const query = client[clientState].queryCache.get< + InferDataFromTag, TTaggedQueryKey> + >(defaultedOptions.queryHash) + const prevData = query?.state.data + const data = functionalUpdate(updater, prevData) + + if (data === undefined) { + return undefined + } + + return client[clientState].queryCache + .build(client, defaultedOptions) + .setData(data, { ...options, manual: true }) +} + +/** + * Imperative (non-reactive) way to retrieve an existing query's state. If the query does not + * exist, `undefined` is returned. + * @param client - The client that owns this operation. + * @param queryKey - The query key of the query to read. + * @returns The query's state, or `undefined` if no query with this key exists. + * @example + * ```ts + * const state = getQueryState(queryClient, ['posts']) + * console.log(state?.dataUpdatedAt) + * ``` + */ +export function getQueryState< + TQueryFnData = unknown, + TError = DefaultError, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + TInferredError = InferErrorFromTag, +>( + client: QueryClient, + queryKey: TTaggedQueryKey, +): QueryState | undefined { + const options = defaultQueryOptions(client, { queryKey }) + return client[clientState].queryCache.get< + TInferredQueryFnData, + TInferredError + >(options.queryHash)?.state +} + +/** + * Asynchronous method to fetch and cache a query, resolving with the data or throwing with + * the error. + * + * If the query already exists in the cache and its data is not stale (per the given + * `staleTime`), the cached data is returned without fetching. Otherwise, the query is fetched + * and the promise resolves once the fetch settles. If a `select` function is provided, it is + * applied to the data in both cases (cached or freshly fetched) before it is returned. + * + * Unlike a reactive observer, retries are disabled by default here (`retry: false`) unless + * explicitly configured, since there is no component to catch a thrown error and retry through + * re-render. + * + * The accepted options are `QueryObserverOptions` minus the fields that only make sense for a + * reactive observer — `enabled`, `refetchInterval`, `refetchIntervalInBackground`, + * `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`, + * `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this + * method's options. + * Shared query options can contain `skipToken` as their `queryFn`. If the supplied options contain + * the token, the call skips fetching and resolves with existing data regardless of freshness. + * It applies `select` when data exists and resolves to `undefined` on a cache miss. + * Use {@link getQueryData} to read the cache directly. + * @param client - The client that owns this operation. + * @param options - The query options, including the `queryKey` and the `queryFn` used if the + * query needs to fetch. + * @returns A promise that resolves to the data, or to the result of `select` if provided. It + * rejects with the error from the fetch or from `select`. + * @example + * ```ts + * try { + * const data = await query(queryClient, { queryKey, queryFn, staleTime: 10000 }) + * } catch (error) { + * console.log(error) + * } + * ``` + */ +export function query< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: WithoutSkipToken< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + >, +): Promise + +export function query< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, +): Promise + +export async function query< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, +): Promise { + const defaultedOptions = defaultQueryOptions(client, options) + let queryData: TQueryData + + if (options.queryFn === skipToken) { + const cachedData = client[clientState].queryCache.get< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >(defaultedOptions.queryHash)?.state.data + if (cachedData === undefined) return undefined + queryData = cachedData + } else { + // https://github.com/tannerlinsley/react-query/issues/652 + if (defaultedOptions.retry === undefined) { + defaultedOptions.retry = false + } + + const cachedQuery = client[clientState].queryCache.build( + client, + defaultedOptions, + ) + + const isStale = cachedQuery.isStaleByTime( + resolveQueryValue(defaultedOptions.staleTime, cachedQuery), + ) + + queryData = isStale + ? await cachedQuery.fetch(defaultedOptions) + : (cachedQuery.state.data as TQueryData) + } + + const select = defaultedOptions.select + + if (select) { + return select[1](queryData) + } + + return queryData as unknown as TData +} + +/** + * Resumes mutations that were paused because there was no network connection. Does nothing + * (resolving immediately) if the client is currently offline. + * @param client - The client that owns this operation. + * @returns A promise that resolves once the resumed mutations have settled. + * @example + * ```ts + * import { QueryClient, resumePausedMutations } from '@tanstack/query-core-pluggable' + * + * const queryClient = new QueryClient() + * await resumePausedMutations(queryClient) + * ``` + */ +export function resumePausedMutations(client: QueryClient): Promise { + if (onlineManager.isOnline()) { + return ( + client[mutationCacheKey]?.resumePausedMutations() ?? Promise.resolve([]) + ) + } + return Promise.resolve() +} + +/** + * Returns the query cache this client is connected to. + * @param client - The client that owns this operation. + * @returns The {@link QueryCache} instance. + * @example + * ```ts + * import { QueryClient, getQueryCache } from '@tanstack/query-core-pluggable' + * + * const queryClient = new QueryClient() + * const queryCache = getQueryCache(queryClient) + * const queries = findCachedQueries(queryCache, { queryKey: ['posts'] }) + * ``` + */ +export function getQueryCache(client: QueryClient): QueryCache { + return client[clientState].queryCache +} + +/** + * Returns the default options that were set when creating the client, or via + * {@link setDefaultOptions}. + * @param client - The client that owns this operation. + * @returns The client's current default options. + * @example + * ```ts + * import { QueryClient, getDefaultOptions } from '@tanstack/query-core-pluggable' + * + * const queryClient = new QueryClient() + * const defaultOptions = getDefaultOptions(queryClient) + * ``` + */ +export function getDefaultOptions(client: QueryClient): DefaultOptions { + return client[clientState].defaultOptions +} + +/** + * Dynamically sets the default options for this client, overwriting any previously defined + * default options. + * @param client - The client that owns this operation. + * @param options - The new default options for queries and mutations. + * @see {@link getDefaultOptions} + * @example + * ```ts + * import { QueryClient, setDefaultOptions } from '@tanstack/query-core-pluggable' + * + * const queryClient = new QueryClient() + * setDefaultOptions(queryClient, { + * queries: { + * staleTime: Infinity, + * }, + * }) + * ``` + */ +export function setDefaultOptions( + client: QueryClient, + options: DefaultOptions, +): void { + client[clientState].defaultOptions = options +} + +/** + * Sets default options for queries whose query key partially matches the given `queryKey`. + * + * If several registered query defaults match a given query key, they are merged together in + * registration order by {@link getQueryDefaults}, so register defaults from the + * most generic key to the least generic one — more specific defaults should be registered + * after more generic ones so they take precedence. + * @param client - The client that owns this operation. + * @param queryKey - The query key that query keys are partially matched against. + * @param options - The default options applied to matching queries. + * @example + * ```ts + * setQueryDefaults(queryClient, ['posts'], { queryFn: fetchPosts }) + * + * await query(queryClient, { queryKey: ['posts'] }) + * ``` + */ +export function setQueryDefaults< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, +>( + client: QueryClient, + queryKey: QueryKey, + options: Partial< + OmitKeyof< + QueryObserverOptionsBase, + 'queryKey' | 'throwOnError' + > + > & { + throwOnError?: QueryErrorBoundaryOption< + TQueryFnData, + TError, + TQueryData, + QueryKey + > + }, +): void { + ;(client[clientState].queryDefaults ??= new KeyDefaults()).set( + queryKey, + options, + client[clientState].queryCache.config.queryKey, + ) +} + +/** + * Returns the default options registered for queries whose query key partially matches the + * given `queryKey`, via {@link setQueryDefaults}. If multiple registered defaults + * match, they are merged together in registration order. + * @param client - The client that owns this operation. + * @param queryKey - The query key to look up registered defaults for. + * @returns The merged default options of every registration that matches, or an empty object if + * none match. + * @example + * ```ts + * const defaultOptions = getQueryDefaults(queryClient, ['posts']) + * ``` + */ +export function getQueryDefaults( + client: QueryClient, + queryKey: QueryKey, +): OmitKeyof, 'queryKey'> { + return ( + client[clientState].queryDefaults?.get( + queryKey, + client[clientState].queryCache.config.queryKey, + ) ?? {} + ) +} + +/** + * Sets default options for mutations whose mutation key partially matches the given + * `mutationKey`. As with {@link setQueryDefaults}, the order of registration + * matters when several registered defaults match the same mutation key. + * @param client - The client that owns this operation. + * @param mutationKey - The mutation key that mutation keys are partially matched against. + * @param options - The default options applied to matching mutations. + * @see {@link getMutationDefaults} + * @example + * ```ts + * setMutationDefaults(queryClient, ['addPost'], { mutationFn: addPost }) + * ``` + */ +export function setMutationDefaults< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + client: QueryClient, + mutationKey: MutationKey, + options: OmitKeyof< + MutationObserverOptions, + 'mutationKey' + >, +): void { + ;(client[clientState].mutationDefaults ??= new KeyDefaults()).set( + mutationKey, + options, + client[mutationCacheKey]?.config.mutationKey, + ) +} + +/** + * Returns the default options registered for mutations whose mutation key partially matches + * the given `mutationKey`, via {@link setMutationDefaults}. If multiple registered + * defaults match, they are merged together in registration order. + * @param client - The client that owns this operation. + * @param mutationKey - The mutation key to look up registered defaults for. + * @returns The merged default options of every registration that matches, or an empty object if + * none match. + * @example + * ```ts + * const defaultOptions = getMutationDefaults(queryClient, ['addPost']) + * ``` + */ +export function getMutationDefaults( + client: QueryClient, + mutationKey: MutationKey, +): OmitKeyof, 'mutationKey'> { + return ( + client[clientState].mutationDefaults?.get( + mutationKey, + client[mutationCacheKey]?.config.mutationKey, + ) ?? {} + ) +} + +/** + * Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the + * caller into their final, defaulted form: merging the client's own `defaultOptions.queries`, + * then `setQueryDefaults` for the given `queryKey`, then the caller's options on + * top. A no-op if the options are already defaulted (`_defaulted: true`). + * @param client - The client that owns this operation. + * @param options - The query options passed by the caller. + * @returns The defaulted options, with `queryHash` and dependent defaults (e.g. + * `refetchOnReconnect`) filled in. + */ +export function defaultQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, +): DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> { + if (options._defaulted) { + return options as DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + } + + const queryDefaults = getQueryDefaults(client, options.queryKey) + const defaultedOptions = { + ...client[clientState].defaultOptions.queries, + ...queryDefaults, + ...options, + _defaulted: true, + } + + if (defaultedOptions.queryFn === defaultQueryFn) { + defaultedOptions.queryFn = + 'queryFn' in queryDefaults + ? queryDefaults.queryFn + : client[clientState].defaultOptions.queries?.queryFn + } + + if (!defaultedOptions.queryHash) { + defaultedOptions.queryHash = hashKeyByOptions( + defaultedOptions.queryKey, + client[clientState].queryCache.config.queryKey, + ) + } + + // dependent default values + if (defaultedOptions.refetchOnReconnect === undefined) { + defaultedOptions.refetchOnReconnect = + defaultedOptions.networkMode !== 'always' + } + if (defaultedOptions.throwOnError === undefined) { + defaultedOptions.throwOnError = !!defaultedOptions.suspense + } + + if (!defaultedOptions.networkMode && defaultedOptions.persister) { + defaultedOptions.networkMode = 'offlineFirst' + } + + if (defaultedOptions.queryFn === skipToken) { + defaultedOptions.enabled = false + } + + return defaultedOptions as DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > +} + +/** + * The mutation counterpart of {@link defaultQueryOptions}. Called by framework + * adapters (e.g. inside `useMutation`) to merge the client's `defaultOptions.mutations`, then + * `setMutationDefaults` for the given `mutationKey`, then the caller's options on + * top. A no-op if the options are already defaulted (`_defaulted: true`). + * @param client - The client that owns this operation. + * @param options - The mutation options passed by the caller. + * @returns The defaulted options. + */ +export function defaultMutationOptions< + T extends MutationOptions, +>(client: QueryClient, options?: T): T { + if (options?._defaulted) { + return options + } + return { + ...client[clientState].defaultOptions.mutations, + ...(options?.mutationKey && + getMutationDefaults(client, options.mutationKey)), + ...options, + _defaulted: true, + } as T +} + +/** + * Clears both the query cache and the mutation cache this client is connected to. + * This clears their garbage collection timers and cancels in-flight query fetches. + * Running mutations continue to execute. + * @param client - The client that owns this operation. + * @example + * ```ts + * import { QueryClient, clearQueryClient } from '@tanstack/query-core-pluggable' + * + * const queryClient = new QueryClient() + * clearQueryClient(queryClient) + * ``` + */ +export function clearQueryClient(client: QueryClient): void { + clearQueryCache(client[clientState].queryCache) + client[mutationCacheKey]?.clear() +} diff --git a/packages/query-core-pluggable/src/queryObserver.ts b/packages/query-core-pluggable/src/queryObserver.ts new file mode 100644 index 00000000000..73099633b2f --- /dev/null +++ b/packages/query-core-pluggable/src/queryObserver.ts @@ -0,0 +1,878 @@ +import { isServer as isServerEnvironment } from './environmentManager' +import { notifyManager } from './notifyManager' +import { defaultQueryOptions, getQueryCache } from './queryClient' +import { fetchState } from './queryState' +import { Subscribable } from './subscribable' +import { timeoutManager } from './timeoutManager' +import { + isValidTimeout, + noop, + resolveQueryValue, + shallowEqualObjects, + timeUntilStale, +} from './utils' +import type { projectResult } from './projectResult' +import type { FetchOptions, Query, QueryState } from './query' +import type { QueryClient } from './queryClient' +import type { PollingTimer } from './refetchInterval' +import type { ManagedTimerId } from './timeoutManager' +import type { + DefaultError, + DefaultedQueryObserverOptions, + PlaceholderValue, + QueryKey, + QueryObserverBaseResult, + QueryObserverOptions, + QueryObserverOptionsBase, + QueryObserverResult, + QueryOptions, + RefetchOptions, +} from './types' + +/** The last selector or placeholder error and when it occurred. */ +export type ProjectionFailure = { + /** The error thrown while computing the result. */ + error: TError + /** Timestamp of the failed computation. */ + errorUpdatedAt: number +} + +interface ObserverFetchOptions extends FetchOptions { + throwOnError?: boolean +} + +type QueryObserverListener = ( + result: QueryObserverResult, +) => void + +/** + * Selection and placeholder computation state shared by reads of the same result. + * @internal + */ +export interface QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +> { + /** The optional result projection that produced this reader’s cached state. */ + project?: typeof projectResult + + /** The memo key and failure of the most recent selection. */ + selection?: { + key: { + input: TQueryData + select: (data: TQueryData) => TData + structuralSharing: QueryOptions< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >['structuralSharing'] + } + failure?: ProjectionFailure + } + /** The last successful selection, used if selection fails. */ + selected?: { + data: TData + query?: Query + } + /** The unselected placeholder or factory error. */ + placeholder?: { + key: { + placeholderData: + | PlaceholderValue + | undefined + structuralSharing: QueryOptions< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >['structuralSharing'] + previousQuery: + | Query + | undefined + previousState: QueryState | undefined + previousOptions: + | QueryOptions + | undefined + } + sourceQuery?: Query + input: TQueryData | undefined + failure?: ProjectionFailure + } +} + +/** + * Options supplied to an observer by a caller or already resolved by the client. + * @internal + */ +export type ObserverOptionsInput< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = + | QueryObserverOptions + | DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > + +/** + * A `QueryObserver` watches a single query in the `QueryCache` and computes a + * `QueryObserverResult` from its state, recomputing and notifying subscribers + * whenever the underlying query (or the observer's options) changes. It is + * the primitive that framework adapters (e.g. `useQuery`) build their hooks + * on top of, but it can also be used directly to observe and switch between + * queries outside of any framework. + * @example + * ```ts + * const observer = new QueryObserver(queryClient, { + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * const unsubscribe = observer.subscribe((result) => { + * console.log(result.data) + * }) + * ``` + */ +export class QueryObserver< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends Subscribable> { + #client: QueryClient + #currentQuery: Query = undefined! + #currentQueryInitialState: QueryState = undefined! + #currentResult: QueryObserverResult = undefined! + #resultContext: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > = {} + // This property keeps track of the last query with defined data. + // It will be used to pass the previous data and query to the placeholder function between renders. + #lastQueryWithDefinedData?: Query + #staleTimeoutId?: ManagedTimerId + #polling?: PollingTimer + #trackedProps = new Set() + + constructor( + client: QueryClient, + public options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ) { + super() + + this.#client = client + + this.bindMethods() + this.setOptions(options) + } + + /** + * Binds the methods of the result (`refetch`) to the observer, so they keep working when destructured + * from it. Subclasses override it to bind their own result methods as well. + */ + protected bindMethods(): void { + this.refetch = this.refetch.bind(this) + } + + protected override onSubscribe(): void { + if (this.listeners.size === 1) { + this.#currentQuery.addObserver(this) + + if (shouldFetchOnMount(this.#currentQuery, this.options)) { + this.#executeFetch() + } else { + this.updateResult() + } + + this.#updateTimers() + } + } + + protected override onUnsubscribe(): void { + if (!this.hasListeners()) { + this.destroy() + } + } + + /** + * Returns whether the observed query is currently stale and configured + * (via the `refetchOnReconnect` option) to refetch when the network + * reconnects. + * @returns `true` if the observer should refetch the query on reconnect. + */ + shouldFetchOnReconnect(): boolean { + return shouldFetchOn( + this.#currentQuery, + this.options, + this.options.refetchOnReconnect, + ) + } + + /** + * Returns whether the observed query is currently stale and configured + * (via the `refetchOnWindowFocus` option) to refetch when the window + * regains focus. + * @returns `true` if the observer should refetch the query on window focus. + */ + shouldFetchOnWindowFocus(): boolean { + return shouldFetchOn( + this.#currentQuery, + this.options, + this.options.refetchOnWindowFocus, + ) + } + + /** + * Stops observing the current query: clears all listeners, cancels the + * stale and refetch-interval timers, and removes this observer from the + * query it was observing. + */ + destroy(): void { + this.listeners = new Set() + this.#clearStaleTimeout() + this.#polling?.stop() + this.#polling = undefined + this.#currentQuery.removeObserver(this) + } + + /** + * Updates the observer's options. This will re-resolve the query being + * observed (switching to a different query if the `queryKey` changed), + * trigger a fetch if the new options require one and the observer has + * subscribers, recompute the current result, and reschedule the stale and + * refetch-interval timers as needed. + * @param options - The new observer options. They are defaulted with {@link + * defaultQueryOptions} before being applied. + * @throws {Error} If `enabled` is neither a boolean nor a function. + * @example + * ```ts + * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) }) + * // later: switch to a different query, reusing the same observer + * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) }) + * ``` + */ + setOptions( + options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): void { + const prevOptions = this.options + const prevQuery = this.#currentQuery + + this.options = defaultQueryOptions(this.#client, options) + + if ( + this.options.enabled !== undefined && + typeof this.options.enabled !== 'boolean' && + typeof this.options.enabled !== 'function' && + typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !== + 'boolean' + ) { + throw new Error( + 'Expected enabled to be a boolean or a callback that returns a boolean', + ) + } + + this.#updateQuery() + this.#currentQuery.setOptions(this.options) + + if ( + prevOptions._defaulted && + !shallowEqualObjects(this.options, prevOptions) + ) { + getQueryCache(this.#client).notify({ + type: 'observerOptionsUpdated', + query: this.#currentQuery, + observer: this, + }) + } + + const mounted = this.hasListeners() + + // Fetch if there are subscribers + if ( + mounted && + shouldFetchOptionally( + this.#currentQuery, + prevQuery, + this.options, + prevOptions, + ) + ) { + this.#executeFetch() + } + + // Update result + this.updateResult() + + // Update stale interval if needed + if ( + mounted && + (this.#currentQuery !== prevQuery || + resolveQueryValue(this.options.enabled, this.#currentQuery) !== + resolveQueryValue(prevOptions.enabled, this.#currentQuery) || + resolveQueryValue(this.options.staleTime, this.#currentQuery) !== + resolveQueryValue(prevOptions.staleTime, this.#currentQuery)) + ) { + this.#updateStaleTimeout() + } + + this.#updatePolling() + } + + /** + * Creates a result reader that captures the supplied query options. + * Reads cache the complete result locally and retain its reference while its + * fields are unchanged. They do not update this observer's committed result, + * options, or selection state. Missing queries are built in the query cache. + * Call `commit` after the render commits to apply the options and reuse the + * reader's computation. An abandoned reader needs no cleanup. + * @param options - The defaulted options used to read and commit the query result. + * @returns A reader with local snapshot and computation caches. + */ + createResultReader( + options: DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): QueryObserverResultReader> { + const readerOptions = { ...options } + const context = { ...this.#resultContext } + let result = this.#currentResult + + const getSnapshot = () => { + const query = getQueryCache(this.#client).build( + this.#client, + readerOptions, + ) + readerOptions.select?.[0].reuse( + readerOptions, + query, + this.#resultContext, + context, + ) + + const nextResult = this.createResult( + query, + readerOptions, + context, + result, + ) + if (!shallowEqualObjects(nextResult, result)) { + result = nextResult + } + return result + } + + return { + getSnapshot, + commit: () => { + // Reuse selections computed since the last read. + getSnapshot() + this.#resultContext = { ...context } + this.setOptions(readerOptions) + }, + } + } + + /** + * Returns the most recently computed `QueryObserverResult` for the + * observed query. This is a point-in-time read; to be notified of updates + * as they happen, subscribe to the observer instead (its inherited + * `subscribe` method). + * @returns The observer's latest result. + * @example + * ```ts + * const result = observer.getCurrentResult() + * console.log(result.status, result.data) + * ``` + */ + getCurrentResult(): QueryObserverResult { + return this.#currentResult + } + + /** + * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via + * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework + * adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on + * properties you actually read" behavior. + * @param result - The result to wrap. + * @param onPropTracked - Called with the name of each property that is read. + * @returns A proxy of `result` that tracks property reads. + */ + trackResult( + result: QueryObserverResult, + onPropTracked?: (key: keyof QueryObserverResult) => void, + ): QueryObserverResult { + return new Proxy(result, { + get: (target, key) => { + this.trackProp(key as keyof QueryObserverResult) + onPropTracked?.(key as keyof QueryObserverResult) + return Reflect.get(target, key) + }, + }) + } + + /** + * Records that the given `QueryObserverResult` property was read, so a subsequent update only + * notifies this observer if a tracked property actually changed. {@link QueryObserver#trackResult} + * calls this on property access. `useQueries` tracks the same property across its observers + * when computing a combined result. + * @param key - The name of the property that was read. + */ + trackProp(key: keyof QueryObserverResult) { + this.#trackedProps.add(key) + } + + /** + * Returns the `Query` instance this observer is currently observing. + * @returns The observed query. + */ + getCurrentQuery(): Query { + return this.#currentQuery + } + + /** + * Refetches the observed query and returns a promise that resolves with + * the resulting `QueryObserverResult`. + * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling + * it, and `throwOnError` to `true` to reject when the refetch fails. + * @returns A promise that resolves with the result after the refetch. + * @example + * ```ts + * const result = await observer.refetch({ cancelRefetch: false }) + * console.log(result.data) + * ``` + */ + refetch( + options: RefetchOptions = {}, + ): Promise> { + return this.fetch(options) + } + + /** + * Fetches the observed query and updates the result once the fetch settles. Used by `refetch` and, + * in `InfiniteQueryObserver`, to fetch more pages. + * @param fetchOptions - Options for this fetch. `cancelRefetch` defaults to `true`. + * @returns A promise that resolves with the updated result. + */ + protected fetch( + fetchOptions: ObserverFetchOptions, + ): Promise> { + return this.#executeFetch({ + ...fetchOptions, + cancelRefetch: fetchOptions.cancelRefetch ?? true, + }).then(() => { + this.updateResult() + return this.#currentResult + }) + } + + #executeFetch( + fetchOptions?: Omit, + ): Promise { + // Make sure we reference the latest query as the current one might have been removed + this.#updateQuery() + + // Fetch + let promise: Promise = this.#currentQuery.fetch( + this.options, + fetchOptions, + ) + + if (!fetchOptions?.throwOnError) { + promise = promise.catch(noop) + } + + return promise + } + + #shouldScheduleTimer(timeout: unknown): timeout is number { + return ( + !isServerEnvironment() && + resolveQueryValue(this.options.enabled, this.#currentQuery) !== false && + isValidTimeout(timeout) + ) + } + + #updateStaleTimeout(): void { + this.#clearStaleTimeout() + const staleTime = resolveQueryValue( + this.options.staleTime, + this.#currentQuery, + ) + + if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) { + return + } + + const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime) + + // The timeout is sometimes triggered 1 ms before the stale time expiration. + // To mitigate this issue we always add 1 ms to the timeout. + const timeout = time + 1 + + this.#staleTimeoutId = timeoutManager.setTimeout(() => { + if (!this.#currentResult.isStale) { + this.updateResult() + } + }, timeout) + } + + #updatePolling(restart = false): void { + const polling = resolveQueryValue( + this.options.refetchInterval, + this.#currentQuery, + ) + if (polling) { + this.#polling = polling.update(this, this.#polling, restart, () => + this.#executeFetch(), + ) + } else { + this.#polling?.stop() + this.#polling = undefined + } + } + + #updateTimers(): void { + this.#updateStaleTimeout() + this.#updatePolling(true) + } + + #clearStaleTimeout(): void { + if (this.#staleTimeoutId !== undefined) { + timeoutManager.clearTimeout(this.#staleTimeoutId) + this.#staleTimeoutId = undefined + } + } + + /** + * Computes the result for a query and options from the query's state, applying `select`, + * `placeholderData`, and observer-specific values. Subclasses add their own fields. + * @internal + * @param query - The query to compute the result for. + * @param options - The observer options to compute the result with. + * @param context - The selection and placeholder state reused between computations. + * @param prevResult - The previous result used for structural sharing. + * @returns The computed result. + */ + createResult( + query: Query, + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + context = this.#resultContext, + prevResult = this.#currentResult as + | QueryObserverResult + | undefined, + ): QueryObserverResult { + const prevQuery = this.#currentQuery + const prevOptions = this.options + const queryChange = query !== prevQuery + const queryInitialState = queryChange + ? query.state + : this.#currentQueryInitialState + + const { state } = query + const fetchOptimistically = + options._optimisticResults && + (this.hasListeners() + ? shouldFetchOptionally(query, prevQuery, options, prevOptions) + : shouldFetchOnMount(query, options)) + const newState = fetchOptimistically + ? { ...state, ...fetchState(state.data, query.options) } + : state + const fetchStatus = + options._optimisticResults === 'isRestoring' + ? 'idle' + : newState.fetchStatus + const feature = options.select?.[0] ?? options.placeholderData?.[0] + const project = feature?.project ?? context.project + const projection = project?.( + query, + newState, + options, + context, + prevResult?.data, + this.#lastQueryWithDefinedData, + ) + const { error, errorUpdatedAt, status } = projection ?? newState + const data = projection + ? projection.data + : (newState.data as unknown as TData | undefined) + const isPlaceholderData = projection?.isPlaceholderData ?? false + const result: QueryObserverBaseResult = { + status, + fetchStatus, + data, + dataUpdatedAt: newState.dataUpdatedAt, + dataUpdateCount: newState.dataUpdateCount, + error, + errorUpdatedAt, + failureCount: newState.fetchFailureCount, + failureReason: newState.fetchFailureReason, + errorUpdateCount: newState.errorUpdateCount, + isFetchedAfterMount: + newState.dataUpdateCount > queryInitialState.dataUpdateCount || + newState.errorUpdateCount > queryInitialState.errorUpdateCount, + isPlaceholderData, + isStale: isStale(query, options), + refetch: this.refetch, + isEnabled: resolveQueryValue(options.enabled, query) !== false, + } + + const nextResult = result as QueryObserverResult + + return nextResult + } + + /** + * Recomputes and stores the current result from the current query/options, notifying listeners + * if it changed. Framework adapters call this right after subscribing to make sure no query + * update was missed in the gap between creating the observer and subscribing to it. + */ + updateResult(): void { + const prevResult = this.#currentResult as + | QueryObserverResult + | undefined + + const nextResult = this.createResult(this.#currentQuery, this.options) + + if (this.#currentQuery.state.data !== undefined) { + this.#lastQueryWithDefinedData = this.#currentQuery + } + + // Only notify and update result if something has changed + if (shallowEqualObjects(nextResult, prevResult)) { + return + } + + this.#currentResult = nextResult + + const shouldNotifyListeners = (): boolean => { + if (!prevResult) { + return true + } + + const { notifyOnChangeProps } = this.options + + if ( + notifyOnChangeProps === 'all' || + (notifyOnChangeProps !== 'none' && !this.#trackedProps.size) + ) { + return true + } + + if ( + this.options.throwOnError && + this.#currentResult.error !== prevResult.error + ) { + return true + } + + if (notifyOnChangeProps === 'none') { + return false + } + + for (const key of this.#trackedProps) { + if (this.#currentResult[key] !== prevResult[key]) { + return true + } + } + return false + } + + const notifyListeners = shouldNotifyListeners() + + notifyManager.batch(() => { + // First, trigger the listeners + if (notifyListeners) { + this.listeners.forEach((listener) => { + listener(this.#currentResult) + }) + } + + // Then the cache listeners + getQueryCache(this.#client).notify({ + query: this.#currentQuery, + type: 'observerResultsUpdated', + }) + }) + } + + #updateQuery(): void { + const query = getQueryCache(this.#client).build(this.#client, this.options) + + if (query === this.#currentQuery) { + return + } + + const prevQuery = this.#currentQuery as + | Query + | undefined + this.#currentQuery = query + this.#currentQueryInitialState = query.state + + if (this.hasListeners()) { + prevQuery?.removeObserver(this) + query.addObserver(this) + } + } + + /** + * Updates the observer's result when the observed query changes, and reschedules its timers if it + * has listeners. + * @internal + */ + onQueryUpdate(): void { + this.updateResult() + + if (this.hasListeners()) { + this.#updateTimers() + } + } +} + +/** + * Checks whether a query has no data yet and should do its initial load when an observer mounts. + * @param query - The query to check. + * @param options - The observer options. + * @returns `true` if the query is enabled, has no data, and isn't in an error state with + * `retryOnMount: false`. + */ +function shouldLoadOnMount( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + resolveQueryValue(options.enabled, query) !== false && + query.state.data === undefined && + !( + query.state.status === 'error' && + resolveQueryValue(options.retryOnMount, query) === false + ) + ) +} + +/** + * Checks whether a query should fetch when an observer mounts: either for its initial load, or + * because it has data and `refetchOnMount` asks for a refetch. + * @param query - The query to check. + * @param options - The observer options. + * @returns `true` if the query should fetch on mount. + */ +function shouldFetchOnMount( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + shouldLoadOnMount(query, options) || + (query.state.data !== undefined && + shouldFetchOn(query, options, options.refetchOnMount)) + ) +} + +/** + * Checks whether a query should fetch for a `refetchOnMount`, `refetchOnWindowFocus`, or + * `refetchOnReconnect` option. + * @param query - The query to check. + * @param options - The observer options. + * @param field - The value of the option to check. + * @returns `true` if the query is enabled, not static, and the option is `'always'`, or is not + * `false` and the query is stale. + */ +function shouldFetchOn( + query: Query, + options: QueryObserverOptionsBase, + field: (typeof options)['refetchOnMount'] & + (typeof options)['refetchOnWindowFocus'] & + (typeof options)['refetchOnReconnect'], +) { + if ( + resolveQueryValue(options.enabled, query) !== false && + resolveQueryValue(options.staleTime, query) !== 'static' + ) { + const value = resolveQueryValue(field, query) + + return value === 'always' || (value !== false && isStale(query, options)) + } + return false +} + +/** + * Checks whether a query should fetch after the observer's options change. + * @param query - The query observed with the new options. + * @param prevQuery - The query observed with the previous options. + * @param options - The new observer options. + * @param prevOptions - The previous observer options. + * @returns `true` if the query changed or was disabled before, it isn't a suspense query in an + * error state, and it is stale. + */ +function shouldFetchOptionally( + query: Query, + prevQuery: Query, + options: QueryObserverOptionsBase, + prevOptions: QueryObserverOptionsBase, +): boolean { + return ( + (query !== prevQuery || + resolveQueryValue(prevOptions.enabled, query) === false) && + (!options.suspense || query.state.status !== 'error') && + isStale(query, options) + ) +} + +/** + * Checks whether a query is stale for the given observer options. + * @param query - The query to check. + * @param options - The observer options, whose `enabled` and `staleTime` are used. + * @returns `true` if the query is enabled and its data is stale for `staleTime`. + */ +function isStale( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + resolveQueryValue(options.enabled, query) !== false && + query.isStaleByTime(resolveQueryValue(options.staleTime, query)) + ) +} + +/** A cached view of an observer for one set of render options. */ +export interface QueryObserverResultReader { + /** Read the result, retaining its reference while all fields are unchanged. */ + getSnapshot: () => TResult + /** Apply this reader's options and reusable computation state after commit. */ + commit: () => void +} diff --git a/packages/query-core-pluggable/src/queryPredicates.ts b/packages/query-core-pluggable/src/queryPredicates.ts new file mode 100644 index 00000000000..7d290198261 --- /dev/null +++ b/packages/query-core-pluggable/src/queryPredicates.ts @@ -0,0 +1,102 @@ +import { resolveQueryValue, skipToken } from './utils' +import type { Query } from './query' + +/** + * Counts observers currently subscribed to a cache entry. + * @param query - The cached query to inspect. + * @returns The number of subscribed observers, including disabled observers. + */ +export function getQueryObserverCount( + query: Query, +): number { + return query.observers.length +} + +/** + * Checks whether a cache entry has received a data or error update. + * @param query - The cached query to inspect. + * @returns Whether data or an error has been recorded since the initial state. + */ +export function isQueryFetched(query: Query): boolean { + return query.state.dataUpdateCount + query.state.errorUpdateCount > 0 +} + +/** + * Returns `true` if the query has at least one observer for which `enabled` + * does not resolve to `false`. + * @param query - The cached query to inspect. + * @returns `true` if the query has an enabled observer. + */ +export function isQueryActive(query: Query): boolean { + return query.observers.some( + (observer) => resolveQueryValue(observer.options.enabled, query) !== false, + ) +} + +/** + * Returns `true` if the query is disabled, meaning it will not fetch + * automatically. + * - If the query has observers, it is disabled when none of them are active + * (see {@link isQueryActive}). + * - If the query has no observers, it is disabled when its `queryFn` is + * `skipToken` or it has never been fetched. + * @param query - The cached query to inspect. + * @returns `true` if the query is disabled. + */ +export function isQueryDisabled(query: Query): boolean { + if (getQueryObserverCount(query) > 0) { + return !isQueryActive(query) + } + // if a query has no observers, it should still be considered disabled if it never attempted a fetch + return query.options.queryFn === skipToken || !isQueryFetched(query) +} + +/** + * Returns `true` if the query has data and at least one observer configured with + * `staleTime: 'static'`, meaning it is treated as never stale. + * @param query - The cached query to inspect. + * @returns `true` if the query is static. + */ +export function isQueryStatic(query: Query): boolean { + if (query.state.data === undefined) { + return false + } + + if (getQueryObserverCount(query) > 0) { + return query.observers.some( + (observer) => + resolveQueryValue(observer.options.staleTime, query) === 'static', + ) + } + + return false +} + +/** + * Returns `true` if the query is stale. + * - If the query has observers, defers to whether any observer's current + * result reports `isStale` (which accounts for each observer's own + * `staleTime` and `enabled` state). + * - If the query has no observers, it is considered stale when it has no + * data or has been invalidated. + * @param query - The cached query to inspect. + * @returns `true` if the query is stale. + * @see {@link Query#isStaleByTime} + * @example + * ```ts + * if (isQueryStale(query)) { + * // refetch or otherwise treat the cached data as outdated + * } + * ``` + */ +export function isQueryStale(query: Query): boolean { + // check observers first, their `isStale` has the source of truth + // calculated with `isStaleByTime` and it takes `enabled` into account + if (getQueryObserverCount(query) > 0) { + return query.observers.some( + (observer) => observer.getCurrentResult().isStale, + ) + } + + return query.state.data === undefined || query.state.isInvalidated +} diff --git a/packages/query-core-pluggable/src/queryResult.ts b/packages/query-core-pluggable/src/queryResult.ts new file mode 100644 index 00000000000..d6d776924d9 --- /dev/null +++ b/packages/query-core-pluggable/src/queryResult.ts @@ -0,0 +1,182 @@ +import type { FetchDirection } from './query' +import type { FetchStatus, QueryStatus } from './types' + +type Status = { status: QueryStatus } +type Fetch = { fetchStatus: FetchStatus } +type Data = { data: unknown } +type Page = { fetchDirection: FetchDirection | undefined } + +/** + * Narrows the result to the pending state, where there is no data to display. + * @param result - The observer snapshot to inspect. + * @returns Whether an observer is pending, including a paused or disabled initial fetch. + */ +export function isPending( + result: TResult, +): result is TResult & { status: 'pending' } { + return result.status === 'pending' +} + +/** + * Narrows the result to the success state and preserves the selected data type. + * @param result - The observer snapshot to inspect. + * @returns Whether the observer has a successful result, including placeholder data. + */ +export function isSuccess( + result: TResult, +): result is TResult & { status: 'success' } { + return result.status === 'success' +} + +/** + * Narrows the result to the error state and exposes the typed error. + * @param result - The observer snapshot to inspect. + * @returns Whether a fetch or selection failed, preserving the observer's error type. + */ +export function isError( + result: TResult, +): result is TResult & { status: 'error' } { + return result.status === 'error' +} + +/** + * Checks the fetch status independently of displayed data and errors. + * @param result - The observer snapshot to inspect. + * @returns Whether the observer is fetching initial data, refreshing, or fetching a page. + */ +export function isFetching( + result: TResult, +): result is TResult & { fetchStatus: 'fetching' } { + return result.fetchStatus === 'fetching' +} + +/** + * Identifies a request waiting for conditions such as network connectivity. + * @param result - The observer snapshot to inspect. + * @returns Whether the fetch is paused until it can continue. + */ +export function isPaused( + result: TResult, +): result is TResult & { fetchStatus: 'paused' } { + return result.fetchStatus === 'paused' +} + +/** + * Distinguishes the first in-flight request from a disabled or paused query. + * @param result - The observer snapshot to inspect. + * @returns Whether the initial fetch is running and the observer is still pending. + */ +export function isLoading( + result: TResult, +): result is TResult & { status: 'pending'; fetchStatus: 'fetching' } { + return result.status === 'pending' && result.fetchStatus === 'fetching' +} + +/** + * Checks the underlying update counts, which also reflect manual cache writes. + * @param result - The observer snapshot to inspect. + * @returns Whether the underlying query has received at least one data update or error. + */ +export function isFetched(result: { + dataUpdateCount: number + errorUpdateCount: number +}): boolean { + return result.dataUpdateCount + result.errorUpdateCount > 0 +} + +/** + * Distinguishes an initial error from an error with data still available. + * @param result - The observer snapshot to inspect. + * @returns Whether a failed fetch or selection left the observer without data. + */ +export function isLoadingError( + result: TResult, +): result is TResult & { status: 'error'; data: undefined } { + return result.status === 'error' && result.data === undefined +} + +/** + * Narrows a failed full refetch to its retained data and error. + * @param result - The observer snapshot to inspect. + * @returns Whether a full refetch failed with existing data, excluding directional page requests. + */ +export function isRefetchError>( + result: TResult, +): result is TResult & { + status: 'error' + data: Exclude + fetchDirection?: undefined +} { + return ( + result.status === 'error' && + result.data !== undefined && + (!('fetchDirection' in result) || result.fetchDirection === undefined) + ) +} + +/** + * Identifies a full background fetch while previously resolved data or an error is visible. + * @param result - The observer snapshot to inspect. + * @returns Whether a full background refetch is running, excluding directional page requests. + */ +export function isRefetching>( + result: TResult, +): result is TResult & { + status: 'success' | 'error' + fetchStatus: 'fetching' + fetchDirection?: undefined +} { + return ( + result.fetchStatus === 'fetching' && + result.status !== 'pending' && + (!('fetchDirection' in result) || result.fetchDirection === undefined) + ) +} + +/** + * Checks for a forward page request currently in flight. + * @param result - The observer snapshot to inspect. + * @returns Whether the infinite observer is fetching its next page. + */ +export function isFetchingNextPage( + result: TResult, +): result is TResult & { fetchStatus: 'fetching'; fetchDirection: 'forward' } { + return ( + result.fetchStatus === 'fetching' && result.fetchDirection === 'forward' + ) +} + +/** + * Checks for a backward page request currently in flight. + * @param result - The observer snapshot to inspect. + * @returns Whether the infinite observer is fetching its previous page. + */ +export function isFetchingPreviousPage( + result: TResult, +): result is TResult & { fetchStatus: 'fetching'; fetchDirection: 'backward' } { + return ( + result.fetchStatus === 'fetching' && result.fetchDirection === 'backward' + ) +} + +/** + * Narrows an infinite result to a failed forward request. + * @param result - The observer snapshot to inspect. + * @returns Whether the most recent forward page request failed. + */ +export function isFetchNextPageError( + result: TResult, +): result is TResult & { status: 'error'; fetchDirection: 'forward' } { + return result.status === 'error' && result.fetchDirection === 'forward' +} + +/** + * Narrows an infinite result to a failed backward request. + * @param result - The observer snapshot to inspect. + * @returns Whether the most recent backward page request failed. + */ +export function isFetchPreviousPageError( + result: TResult, +): result is TResult & { status: 'error'; fetchDirection: 'backward' } { + return result.status === 'error' && result.fetchDirection === 'backward' +} diff --git a/packages/query-core-pluggable/src/queryState.ts b/packages/query-core-pluggable/src/queryState.ts new file mode 100644 index 00000000000..cf8b318a0ce --- /dev/null +++ b/packages/query-core-pluggable/src/queryState.ts @@ -0,0 +1,84 @@ +import { canFetch } from './retryer' +import type { QueryState } from './query' +import type { InitialDataFunction, QueryOptions } from './types' + +/** + * Returns the state changes applied when a query starts fetching. + * @param data - The query's current data. If it is `undefined`, the query is also reset to + * `'pending'` with no error. + * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'` + * or `'paused'`. + * @returns The partial query state for a starting fetch. + */ +export function fetchState( + data: TData | undefined, + options: Pick, +) { + return { + fetchFailureCount: 0, + fetchFailureReason: null, + fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused', + ...(data === undefined && + ({ + error: null, + status: 'pending', + } as const)), + } as const +} + +/** + * Returns the state changes applied when a query receives data. + * @param data - The new data. + * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time. + * @returns The partial query state for a successful update. + */ +export function successState( + data: TData | undefined, + dataUpdatedAt?: number, +) { + return { + data, + dataUpdatedAt: dataUpdatedAt ?? Date.now(), + error: null, + isInvalidated: false, + status: 'success' as const, + } +} + +/** + * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt` + * options. + * @param options - Supplies the initial cache value and its update time. + * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`. + */ +export function getDefaultQueryState( + options: Pick, 'initialData' | 'initialDataUpdatedAt'>, +): QueryState { + const data = + typeof options.initialData === 'function' + ? (options.initialData as InitialDataFunction)() + : options.initialData + + const hasData = data !== undefined + + const initialDataUpdatedAt = hasData + ? typeof options.initialDataUpdatedAt === 'function' + ? options.initialDataUpdatedAt() + : options.initialDataUpdatedAt + : 0 + + return { + data, + dataUpdateCount: 0, + dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0, + error: null, + errorUpdateCount: 0, + errorUpdatedAt: 0, + fetchFailureCount: 0, + fetchFailureReason: null, + fetchMeta: null, + isInvalidated: false, + status: hasData ? 'success' : 'pending', + fetchStatus: 'idle', + } +} diff --git a/packages/query-core-pluggable/src/refetchInterval.ts b/packages/query-core-pluggable/src/refetchInterval.ts new file mode 100644 index 00000000000..d633b97eecc --- /dev/null +++ b/packages/query-core-pluggable/src/refetchInterval.ts @@ -0,0 +1,101 @@ +import { isServer } from './environmentManager' +import { focusManager } from './focusManager' +import { timeoutManager } from './timeoutManager' +import { isValidTimeout, resolveQueryValue } from './utils' +import type { Query } from './query' +import type { QueryKey } from './types' + +interface PollingTimer { + query: object + delay: number + stop: () => void +} + +interface PollingObserver { + getCurrentQuery: () => TQuery + hasListeners: () => boolean + options: { + enabled?: boolean | ((query: TQuery) => boolean) + refetchIntervalInBackground?: boolean + } +} + +type Delay = number | false | undefined + +/** An observer option created by {@link refetchInterval}. */ +interface RefetchInterval { + value: Delay | ((query: TQuery) => Delay) + update: typeof updatePolling +} + +/** + * Polls an observed query after the specified delay in milliseconds. + * @param value - A delay or a callback that selects the delay for the current query. + * Returning zero, false or undefined stops the timer. + * @returns A polling option for a query hook or client defaults. + * @example + * ```ts + * const observer = new QueryObserver(client, { + * queryKey: ['orders'], + * queryFn: fetchOrders, + * refetchInterval: refetchInterval(3000), + * }) + * const unsubscribe = observer.subscribe(onResult) + * ``` + */ +export function refetchInterval(value: Delay): RefetchInterval +export function refetchInterval( + value: Delay | ((query: TQuery) => Delay), +): RefetchInterval +/* #__NO_SIDE_EFFECTS__ */ +export function refetchInterval( + value: Delay | ((query: TQuery) => Delay), +): RefetchInterval { + return { value, update: updatePolling } +} + +/** + * Reconciles one observer's timer with its current options and cached query. + * @param observer - Observer receiving the optional schedule. + * @param current - Timer installed during the preceding update. + * @param restart - Restarts the countdown after a query update or subscription. + * @param fetch - Refetches the observer's current query. + * @returns The active timer and its cleanup, when polling is enabled. + */ +function updatePolling( + this: RefetchInterval>, + observer: PollingObserver>, + current: PollingTimer | undefined, + restart: boolean, + fetch: () => void, +): PollingTimer | undefined { + const query = observer.getCurrentQuery() + const delay = resolveQueryValue(this.value, query) + if (!observer.hasListeners()) return + + if ( + isServer() || + !isValidTimeout(delay) || + delay === 0 || + resolveQueryValue(observer.options.enabled, query) === false + ) { + current?.stop() + return + } + if (!restart && current?.query === query && current.delay === delay) { + return current + } + current?.stop() + const id = timeoutManager.setInterval(() => { + if ( + observer.options.refetchIntervalInBackground || + focusManager.isFocused() + ) { + fetch() + } + }, delay) + + return { query, delay, stop: () => timeoutManager.clearInterval(id) } +} + +export type { PollingTimer, RefetchInterval } diff --git a/packages/query-core-pluggable/src/removable.ts b/packages/query-core-pluggable/src/removable.ts new file mode 100644 index 00000000000..d6356c73845 --- /dev/null +++ b/packages/query-core-pluggable/src/removable.ts @@ -0,0 +1,65 @@ +import { isServer as isServerEnvironment } from './environmentManager' +import { timeoutManager } from './timeoutManager' +import { isValidTimeout } from './utils' +import type { ManagedTimerId } from './timeoutManager' + +/** + * The base class for cache entries that are garbage collected once nothing is using them — + * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept. + */ +export abstract class Removable { + gcTime!: number + #gcTimeout?: ManagedTimerId + + /** + * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal. + * A subclass may override this to release what it holds on to as well — `Query` also cancels any + * in-flight fetch. + */ + destroy(): void { + this.clearGcTimeout() + } + + /** + * Schedules the entry to be removed from its cache after `gcTime`, replacing any timeout scheduled + * before. Nothing is scheduled if `gcTime` is `Infinity`. + */ + protected scheduleGc(): void { + this.clearGcTimeout() + + if (isValidTimeout(this.gcTime)) { + this.#gcTimeout = timeoutManager.setTimeout(() => { + this.optionalRemove() + }, this.gcTime) + } + } + + /** + * Updates `gcTime`, keeping the longest one seen so far. Without a value, it defaults to 5 minutes + * on the client and `Infinity` on the server. + * @param newGcTime - The `gcTime` from the latest options, if any. + */ + protected updateGcTime(newGcTime: number | undefined): void { + // Default to 5 minutes (Infinity for server-side) if no gcTime is set + this.gcTime = Math.max( + this.gcTime || 0, + newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000), + ) + } + + /** + * Cancels the scheduled removal, if there is one. + */ + protected clearGcTimeout() { + if (this.#gcTimeout !== undefined) { + timeoutManager.clearTimeout(this.#gcTimeout) + this.#gcTimeout = undefined + } + } + + /** + * Called when the garbage collection timeout fires. Subclasses remove the entry from its cache + * unless it is still in use, e.g. because it has observers. + */ + protected abstract optionalRemove(): void +} diff --git a/packages/query-core-pluggable/src/retryer.ts b/packages/query-core-pluggable/src/retryer.ts new file mode 100644 index 00000000000..3e7ad7bb771 --- /dev/null +++ b/packages/query-core-pluggable/src/retryer.ts @@ -0,0 +1,305 @@ +import { isServer as isServerEnvironment } from './environmentManager' +import { focusManager } from './focusManager' +import { onlineManager } from './onlineManager' +import { noop, sleep } from './utils' +import type { CancelOptions, DefaultError, NetworkMode } from './types' + +// TYPES + +interface RetryerConfig { + fn: () => TData | Promise + initialPromise?: Promise + onCancel?: (error: TError) => void + onFail?: (failureCount: number, error: TError) => void + onPause?: () => void + onContinue?: () => void + retry?: RetryValue + retryDelay?: RetryDelayValue + networkMode: NetworkMode | undefined + canRun: () => boolean +} + +/** + * Runs a function with retries, and can pause, continue, or cancel it. Queries and mutations use + * one for each fetch or execution. + */ +export interface Retryer { + /** + * The promise that resolves with the data, or rejects once retries are exhausted or it is + * cancelled. + */ + promise: Promise + /** + * Cancels the run, rejecting `promise` with a `CancelledError`. + */ + cancel: (cancelOptions?: CancelOptions) => void + /** + * Resumes a paused run, and returns `promise`. + */ + continue: () => Promise + /** + * Stops further retries. The current attempt still finishes. + */ + cancelRetry: () => void + /** + * Allows retries again after `cancelRetry`. + */ + continueRetry: () => void + /** + * Returns whether the run can start now, based on the network mode and `canRun`. + */ + canStart: () => boolean + /** + * Starts the run, or waits until it can start, and returns `promise`. + */ + start: () => Promise + /** + * Returns whether `promise` is still pending, resolved, or rejected. + */ + status: () => 'pending' | 'resolved' | 'rejected' +} + +type RetryerStatus = 'pending' | 'resolved' | 'rejected' + +/** @inline */ +export type RetryValue = boolean | number | ShouldRetryFunction + +/** @inline */ +type ShouldRetryFunction = ( + failureCount: number, + error: TError, +) => boolean + +/** @inline */ +export type RetryDelayValue = number | RetryDelayFunction + +/** @inline */ +type RetryDelayFunction = ( + failureCount: number, + error: TError, +) => number + +/** + * Applies exponential backoff with jitter. The base delay starts at 1 second + * and doubles for each retry, up to 30 seconds. + * @param failureCount - The number of previous failures. Starts at 0 for the first retry. + * @returns A random delay from 80% to 100% of the base delay, in milliseconds. + */ +function defaultRetryDelay(failureCount: number) { + const baseDelay = Math.min(1000 * 2 ** failureCount, 30000) + const maxJitter = baseDelay * 0.2 + return baseDelay - Math.floor(Math.random() * (maxJitter + 1)) +} + +/** + * Checks whether a fetch can run for the given network mode. + * @param networkMode - The `networkMode` option. Defaults to `'online'`. + * @returns `true` if the network mode is not `'online'`, or if it is and the client is online. + */ +export function canFetch(networkMode: NetworkMode | undefined): boolean { + return (networkMode ?? 'online') === 'online' + ? onlineManager.isOnline() + : true +} + +/** + * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via + * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch + * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead + * resolve with the promise of the fetch that triggered the cancellation. + * @example + * ```ts + * query.cancel() + * + * try { + * await query.promise + * } catch (error) { + * if (error instanceof CancelledError) { + * // the fetch was cancelled, e.g. via `query.cancel()` + * } + * } + * ``` + */ +export class CancelledError extends Error { + revert?: boolean + silent?: boolean + constructor(options?: CancelOptions) { + super('CancelledError') + this.revert = options?.revert + this.silent = options?.silent + } +} + +/** + * Creates a retryer, which runs a function and retries it on failure according to the `retry` and + * `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns + * `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and + * `mutationFn`. + * @param config - The function to run, the retry options, and the callbacks for failures, pausing, + * continuing, and cancellation. + * @returns The retryer, whose `promise` settles with the result of the function. + */ +export function createRetryer( + config: RetryerConfig, +): Retryer { + let isRetryCancelled = false + let failureCount = 0 + let continueFn: ((value?: unknown) => void) | undefined + let status: RetryerStatus = 'pending' + const { + promise, + resolve: promiseResolve, + reject: promiseReject, + } = Promise.withResolvers() + promise.catch(noop) + + const isResolved = () => status !== 'pending' + + const cancel = (cancelOptions?: CancelOptions): void => { + if (!isResolved()) { + const error = new CancelledError(cancelOptions) as TError + reject(error) + + config.onCancel?.(error) + } + } + const cancelRetry = () => { + isRetryCancelled = true + } + + const continueRetry = () => { + isRetryCancelled = false + } + + const canContinue = () => + focusManager.isFocused() && + (config.networkMode === 'always' || onlineManager.isOnline()) && + config.canRun() + + const canStart = () => canFetch(config.networkMode) && config.canRun() + + const resolve = (value: any) => { + if (!isResolved()) { + continueFn?.() + status = 'resolved' + promiseResolve(value) + } + } + + const reject = (value: any) => { + if (!isResolved()) { + continueFn?.() + status = 'rejected' + promiseReject(value) + } + } + + const pause = (canResume: () => boolean) => { + return new Promise((continueResolve) => { + continueFn = (value) => { + if (isResolved() || canResume()) { + continueResolve(value) + } + } + config.onPause?.() + }).then(() => { + continueFn = undefined + if (!isResolved()) { + config.onContinue?.() + } + }) + } + + // Create loop function + const run = () => { + // Do nothing if already resolved + if (isResolved()) { + return + } + + let promiseOrValue: any + + // we can re-use config.initialPromise on the first call of run() + const initialPromise = + failureCount === 0 ? config.initialPromise : undefined + + // Execute query + try { + promiseOrValue = initialPromise ?? config.fn() + } catch (error) { + promiseOrValue = Promise.reject(error) + } + + Promise.resolve(promiseOrValue) + .then(resolve) + .catch((error) => { + // Stop if the fetch is already resolved + if (isResolved()) { + return + } + + // Do we need to retry the request? + const retry = config.retry ?? (isServerEnvironment() ? 0 : 3) + const retryDelay = config.retryDelay ?? defaultRetryDelay + const delay = + typeof retryDelay === 'function' + ? retryDelay(failureCount, error) + : retryDelay + const shouldRetry = + retry === true || + (typeof retry === 'number' && failureCount < retry) || + (typeof retry === 'function' && retry(failureCount, error)) + + if (isRetryCancelled || !shouldRetry) { + // We are done if the query does not need to be retried + reject(error) + return + } + + failureCount++ + + // Notify on fail + config.onFail?.(failureCount, error) + + // Delay + sleep(delay) + // Pause if the document is not visible or when the device is offline + .then(() => { + return isResolved() || canContinue() + ? undefined + : pause(canContinue) + }) + .then(() => { + if (isRetryCancelled) { + reject(error) + } else { + run() + } + }) + }) + } + + return { + promise, + status: () => status, + cancel, + continue: () => { + continueFn?.() + return promise + }, + cancelRetry, + continueRetry, + canStart, + start: () => { + // Start loop + if (canStart()) { + run() + } else { + // Waiting to start (e.g. queued behind a scope) does not depend on focus, + // only on the same conditions that allow starting in the first place + pause(canStart).then(run) + } + return promise + }, + } +} diff --git a/packages/query-core-pluggable/src/select.ts b/packages/query-core-pluggable/src/select.ts new file mode 100644 index 00000000000..7b69dbecc7e --- /dev/null +++ b/packages/query-core-pluggable/src/select.ts @@ -0,0 +1,131 @@ +import { projectResult } from './projectResult' +import { replaceData, shallowEqualObjects } from './utils' +import type { Select } from './projectionTypes' +import type { Query } from './query' +import type { QueryObserverResultContext } from './queryObserver' +import type { QueryKey, QueryObserverOptionsBase } from './types' + +/* #__NO_SIDE_EFFECTS__ */ +/** + * Derives observer data from the cached query data. + * @param transform - Computes the selected data from the cached value. + * @returns A query selection option. + */ +export function select( + transform: (input: TInput) => TData, +): Select { + return [select, transform] +} + +select.project = projectResult +select.reuse = reuseSelection +select.resolve = resolveSelection + +/** + * Reuses the last committed selection when a reader sees the same input and selector. + * @param options - The reader's options. + * @param query - The query being read. + * @param committed - Memoized selections for the active observer. + * @param context - Selections local to this result reader. + */ +function reuseSelection< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + query: Query, + committed: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + context: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, +): void { + const transform = options.select?.[1] + const input = query.state.data + if ( + input !== undefined && + transform && + shallowEqualObjects( + { + input, + select: transform, + structuralSharing: options.structuralSharing, + }, + committed.selection?.key, + ) + ) { + context.selection = committed.selection + context.selected = committed.selected + } +} + +/** + * Memoizes the result or error of applying a selector to query or placeholder data. + * @param options - Options controlling structural sharing. + * @param transform - The caller's selector. + * @param context - Selection state for this observer or render. + * @param previousData - The previous data for structural sharing. + * @param input - The value passed to the selector. + * @param sourceQuery - The query supplying the selected data, if any. + */ +function resolveSelection< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + transform: (data: TQueryData) => TData, + context: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + previousData: TData | undefined, + input: TQueryData, + sourceQuery: Query | undefined, +): void { + const key = { + input, + select: transform, + structuralSharing: options.structuralSharing, + } + if (shallowEqualObjects(key, context.selection?.key)) return + try { + const data = replaceData(previousData, transform(input), options) + context.selected = { data, query: sourceQuery } + context.selection = { key } + } catch (error) { + context.selection = { + key, + failure: { error: error as TError, errorUpdatedAt: Date.now() }, + } + } +} diff --git a/packages/query-core-pluggable/src/serialScope.ts b/packages/query-core-pluggable/src/serialScope.ts new file mode 100644 index 00000000000..96f042d860a --- /dev/null +++ b/packages/query-core-pluggable/src/serialScope.ts @@ -0,0 +1,96 @@ +import type { Mutation } from './mutation' +import type { MutationCache } from './mutationCache' + +type QueuedMutation = Mutation + +// Each cache owns its own queues, even when clients reuse the same option. +const queues = new WeakMap>>() + +/** Runs mutations with the same ID in registration order within one cache. */ +class SerialScope { + constructor(readonly id: string) {} + + /** + * Registers a mutation in this cache's queue. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to register. + */ + add(cache: MutationCache, mutation: QueuedMutation): void { + let scopes = queues.get(cache) + if (!scopes) { + scopes = new Map() + queues.set(cache, scopes) + } + let queue = scopes.get(this.id) + if (!queue) { + queue = new Set() + scopes.set(this.id, queue) + } + queue.add(mutation) + } + + /** + * Releases the mutation and any empty queue. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to remove. + */ + remove(cache: MutationCache, mutation: QueuedMutation): void { + const scopes = queues.get(cache) + if (!scopes) return + const queue = scopes.get(this.id) + if (queue?.delete(mutation) && !queue.size) { + scopes.delete(this.id) + if (!scopes.size) queues.delete(cache) + } + } + + /** + * Checks whether this mutation is the first pending member. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to check. + * @returns Whether this mutation can start or continue. + */ + canRun(cache: MutationCache, mutation: QueuedMutation): boolean { + const queue = queues.get(cache)?.get(this.id) + if (queue) { + for (const entry of queue) { + if (entry.state.status === 'pending') return entry === mutation + } + } + return true + } + + /** + * Resumes the first waiting mutation after its predecessor settles. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to finish. + * @returns The next waiting mutation’s promise, if present. + */ + runNext( + cache: MutationCache, + mutation: QueuedMutation, + ): Promise | undefined { + const queue = queues.get(cache)?.get(this.id) + if (queue) { + for (const entry of queue) { + if (entry !== mutation && entry.state.isPaused) return entry.continue() + } + } + return undefined + } +} + +/** + * Selects FIFO execution for mutations sharing this ID in the same cache. + * @param id - The queue identifier, preserved in dehydrated mutation snapshots. + * @returns The value to pass to the mutation's `scope` option. + */ +export function serialScope(id: string): SerialScope { + return new SerialScope(id) +} + +export type { SerialScope } diff --git a/packages/query-core-pluggable/src/streamedQuery.ts b/packages/query-core-pluggable/src/streamedQuery.ts new file mode 100644 index 00000000000..3088a968b27 --- /dev/null +++ b/packages/query-core-pluggable/src/streamedQuery.ts @@ -0,0 +1,155 @@ +import { findCachedQuery } from './queryCacheOperations' +import { getQueryCache, getQueryData, setQueryData } from './queryClient' +import { isQueryFetched } from './queryPredicates' +import { addConsumeAwareSignal, fetchSignal } from './utils' +import type { + OmitKeyof, + QueryFunction, + QueryFunctionContext, + QueryKey, +} from './types' +import type { FetchSignalContext } from './utils' + +type StreamedQueryParams = + | SimpleStreamedQueryParams + | ReducibleStreamedQueryParams + +type SimpleStreamedQueryParams< + TQueryFnData, + TQueryKey extends QueryKey, +> = BaseStreamedQueryParams & { + reducer?: never + initialValue?: never +} + +type ReducibleStreamedQueryParams< + TQueryFnData, + TData, + TQueryKey extends QueryKey, +> = BaseStreamedQueryParams & { + /** + * Combines the accumulated data with the next chunk. Provide `initialValue` with a custom reducer. + */ + reducer: (acc: TData, chunk: TQueryFnData) => TData + /** + * The starting value for the reducer when there is no cached data or when + * `refetchMode` is `'replace'` during a refetch. + */ + initialValue: TData +} + +type BaseStreamedQueryParams = { + /** Returns an `AsyncIterable` or a promise that resolves to one. */ + streamFn: ( + context: QueryFunctionContext, + ) => AsyncIterable | Promise> + /** + * Defines how refetches are handled. + * - `'reset'` (default): resets the query to its initial state before reading the stream. + * - `'append'`: appends new data to the existing data. + * - `'replace'`: writes all data to the cache once the stream ends. + */ + refetchMode?: 'append' | 'reset' | 'replace' +} + +/** + * Creates a query function that streams data from an `AsyncIterable`. + * By default, the query collects chunks into an array in the order they arrive. + * If there is no cached data, the first chunk moves the query from `pending` to `success`. + * If the stream ends without producing any chunks, the query uses the cached data or + * the initial value. With a `'replace'` refetch, it uses the initial value. + * The query's `fetchStatus` stays `fetching` while the stream is active. + * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`. + * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes. + * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional + * `refetchMode`, `reducer`, and `initialValue` options. + * @returns A query function to pass as `queryFn`. + * @example + * ```ts + * await query(queryClient, { + * queryKey: ['data'], + * queryFn: streamedQuery({ + * streamFn: fetchDataInChunks, + * }), + * }) + * ``` + */ +export function streamedQuery< + TQueryFnData = unknown, + TData = Array, + TQueryKey extends QueryKey = QueryKey, +>({ + streamFn, + refetchMode = 'reset', + reducer = (items, chunk) => + [...(items as Array), chunk] as TData, + initialValue = [] as TData, +}: StreamedQueryParams): QueryFunction< + TData, + TQueryKey +> { + return async (context) => { + const signalContext: FetchSignalContext = context + const signal = signalContext[fetchSignal] + if (signal?.aborted) { + return initialValue + } + + const query = findCachedQuery(getQueryCache(context.client), { + queryKey: context.queryKey, + exact: true, + }) + const isRefetch = !!query && isQueryFetched(query) + if (isRefetch && refetchMode === 'reset') { + query.setState({ + ...query.resetState, + fetchStatus: 'fetching', + }) + } + + let result = initialValue + + let cancelled = false as boolean + const streamFnContext = addConsumeAwareSignal< + OmitKeyof + >( + { + client: context.client, + meta: context.meta, + queryKey: context.queryKey, + pageParam: context.pageParam, + }, + () => context.signal, + () => (cancelled = true), + signal, + ) + + const isStreamInactive = () => cancelled || signal?.aborted === true + const stream = await streamFn(streamFnContext) + + const isReplaceRefetch = isRefetch && refetchMode === 'replace' + + for await (const chunk of stream) { + if (isStreamInactive()) { + break + } + + if (isReplaceRefetch) { + // don't append to the cache directly when replace-refetching + result = reducer(result, chunk) + } else { + setQueryData(context.client, context.queryKey, (prev) => + reducer(prev === undefined ? initialValue : prev, chunk), + ) + } + } + + // finalize result: replace-refetching needs to write to the cache + if (isReplaceRefetch && !isStreamInactive()) { + setQueryData(context.client, context.queryKey, result) + } + + const data = getQueryData(context.client, context.queryKey) + return data === undefined ? initialValue : data + } +} diff --git a/packages/query-core-pluggable/src/subscribable.ts b/packages/query-core-pluggable/src/subscribable.ts new file mode 100644 index 00000000000..8b40e3ce868 --- /dev/null +++ b/packages/query-core-pluggable/src/subscribable.ts @@ -0,0 +1,65 @@ +/** + * The base class behind everything in Query that you can subscribe to: `QueryCache`, `MutationCache`, + * the observers, and the `FocusManager`/`OnlineManager` behind `focusManager` and `onlineManager`. + * Subclasses decide what a listener receives and when it is called. + */ +export class Subscribable< + // oxlint-disable-next-line typescript/no-unsafe-function-type -- also accepts construct signatures and functions with extra properties, which a call signature would reject + TListener extends Function, +> { + protected listeners = new Set() + + constructor() { + this.subscribe = this.subscribe.bind(this) + } + + /** + * Registers a listener to be called on every update this object notifies about. Returns a function + * that removes the listener again — call it to stop listening. The base class never drops a listener + * on its own, though some subclasses clear all of theirs in `destroy()`. + * @param listener - Called on each update, with whatever the subclass passes to its subscribers. + * @returns A function that removes the listener. + * @example + * ```ts + * const unsubscribe = subscribable.subscribe(() => { + * // react to the update + * }) + * + * unsubscribe() + * ``` + */ + subscribe(listener: TListener): () => void { + this.listeners.add(listener) + + this.onSubscribe() + + return () => { + this.listeners.delete(listener) + this.onUnsubscribe() + } + } + + /** + * Returns `true` while at least one listener is registered, `false` once they have all unsubscribed. + * @returns `true` if at least one listener is registered. + */ + hasListeners(): boolean { + return this.listeners.size > 0 + } + + /** + * Called after a listener is added. Does nothing here; subclasses override it, e.g. to start + * tracking what they observe once the first listener subscribes. + */ + protected onSubscribe(): void { + // Do nothing + } + + /** + * Called after a listener is removed. Does nothing here; subclasses override it, e.g. to clean up + * once the last listener unsubscribes. + */ + protected onUnsubscribe(): void { + // Do nothing + } +} diff --git a/packages/query-core-pluggable/src/timeoutManager.ts b/packages/query-core-pluggable/src/timeoutManager.ts new file mode 100644 index 00000000000..9ec946a0087 --- /dev/null +++ b/packages/query-core-pluggable/src/timeoutManager.ts @@ -0,0 +1,248 @@ +/** + * {@link TimeoutManager} does not support passing arguments to the callback. + * + * `(_: void)` is the argument type inferred by TypeScript's default typings for + * `setTimeout(cb, number)`. + * If we don't accept a single void argument, then + * `new Promise(resolve => timeoutManager.setTimeout(resolve, N))` is a type error. + */ +export type TimeoutCallback = (_: void) => void + +/** + * Wrapping `setTimeout` is awkward from a typing perspective because platform + * typings may extend the return type of `setTimeout`. For example, NodeJS + * typings add `NodeJS.Timeout`; but a non-default `timeoutManager` may not be + * able to return such a type. + */ +export type ManagedTimerId = number | { [Symbol.toPrimitive]: () => number } + +/** + * Backend for timer functions. + * + * Timers are performance-sensitive: short-lived timers (delays under a few seconds) tend to be + * latency-sensitive, while long-lived ones may benefit more from coalescing — batching timers + * with similar deadlines together — which the default provider (backed by the platform's global + * `setTimeout`/`setInterval`) does not do. A custom provider can implement coalescing, and can + * also support delays longer than the ~24-day maximum of the global `setTimeout`. + */ +export type TimeoutProvider = + { + /** + * Schedules `callback` to run once after `delay` milliseconds, like the global `setTimeout`. + */ + readonly setTimeout: (callback: TimeoutCallback, delay: number) => TTimerId + /** + * Cancels a timeout scheduled with `setTimeout`. + */ + readonly clearTimeout: (timeoutId: TTimerId | undefined) => void + + /** + * Schedules `callback` to run every `delay` milliseconds, like the global `setInterval`. + */ + readonly setInterval: (callback: TimeoutCallback, delay: number) => TTimerId + /** + * Cancels an interval scheduled with `setInterval`. + */ + readonly clearInterval: (intervalId: TTimerId | undefined) => void + } + +type SystemTimerId = ReturnType + +export const defaultTimeoutProvider: TimeoutProvider = { + // We need the wrapper function syntax below instead of direct references to + // global setTimeout etc. + // + // BAD: `setTimeout: setTimeout` + // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)` + // + // If we use direct references here, then anything that wants to spy on or + // replace the global setTimeout (like tests) won't work since we'll already + // have a hard reference to the original implementation at the time when this + // file was imported. + setTimeout: (callback, delay) => setTimeout(callback, delay), + clearTimeout: (timeoutId) => + clearTimeout(timeoutId as SystemTimerId | undefined), + + setInterval: (callback, delay) => setInterval(callback, delay), + clearInterval: (intervalId) => + clearInterval(intervalId as SystemTimerId | undefined), +} + +/** + * Allows customization of how timeouts are created. + * + * The query runtime uses timeouts to implement `staleTime` + * and `gcTime`. The default TimeoutManager provider uses the platform's global + * `setTimeout` implementation, which is known to have scalability issues with + * thousands of timeouts on the event loop. + * + * If you hit this limitation, consider providing a custom TimeoutProvider that + * coalesces timeouts. + */ +export class TimeoutManager implements Omit { + // We cannot have TimeoutManager as we must instantiate it with a concrete + // type at app boot; and if we leave that type, then any new timer provider + // would need to support the default provider's concrete timer ID, which is + // infeasible across environments. + // + // We settle for type safety for the TimeoutProvider type, and accept that + // this class is unsafe internally to allow for extension. + #provider: TimeoutProvider = defaultTimeoutProvider + #providerCalled = false + + /** + * `setTimeoutProvider` can be used to set a custom implementation of the + * `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval` functions, + * called a `TimeoutProvider`. + * + * This may be useful if you notice event loop performance issues with + * thousands of queries. A custom TimeoutProvider could also support timer + * delays longer than the global `setTimeout` maximum delay value of about + * 24 days. + * + * It is important to call `setTimeoutProvider` before creating a + * QueryClient or queries, so that the same provider is used consistently + * for all timers in the application, since different TimeoutProviders + * cannot cancel each others' timers. + * @param provider - The `TimeoutProvider` to use for all timers from now on. + * @example + * ```ts + * import { timeoutManager, QueryClient } from '@tanstack/query-core-pluggable' + * import { CustomTimeoutProvider } from './CustomTimeoutProvider' + * + * timeoutManager.setTimeoutProvider(new CustomTimeoutProvider()) + * + * export const queryClient = new QueryClient() + * ``` + */ + setTimeoutProvider( + provider: TimeoutProvider, + ): void { + if (process.env.NODE_ENV !== 'production') { + if (this.#providerCalled && provider !== this.#provider) { + // After changing providers, `clearTimeout` will not work as expected for + // timeouts from the previous provider. + // + // Since they may allocate the same timeout ID, clearTimeout may cancel an + // arbitrary different timeout, or unexpected no-op. + // + // We could protect against this by mixing the timeout ID bits + // deterministically with some per-provider bits. + // + // We could internally queue `setTimeout` calls to `TimeoutManager` until + // some API call to set the initial provider. + console.error( + `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`, + { previous: this.#provider, provider }, + ) + } + } + + this.#provider = provider + if (process.env.NODE_ENV !== 'production') { + this.#providerCalled = false + } + } + + /** + * `setTimeout` schedules a callback to run after approximately `delay` + * milliseconds, like the global `setTimeout` function. The callback can be + * canceled with `clearTimeout`. + * + * It returns a timer ID, which may be a number or an object that can be + * coerced to a number via `Symbol.toPrimitive`. + * @param callback - The function to call when the timeout elapses. + * @param delay - The time to wait before calling `callback`, in milliseconds. + * @returns The timer ID, to pass to {@link TimeoutManager#clearTimeout}. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/query-core-pluggable' + * + * const timeoutId = timeoutManager.setTimeout( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * + * const timeoutIdNumber: number = Number(timeoutId) + * ``` + */ + setTimeout(callback: TimeoutCallback, delay: number): ManagedTimerId { + if (process.env.NODE_ENV !== 'production') { + this.#providerCalled = true + } + return this.#provider.setTimeout(callback, delay) + } + + /** + * `clearTimeout` cancels a timeout callback scheduled with `setTimeout`, + * like the global `clearTimeout` function. It should be called with a + * timer ID returned by `setTimeout`. + * @param timeoutId - The timer ID returned by `setTimeout`, or `undefined`. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/query-core-pluggable' + * + * const timeoutId = timeoutManager.setTimeout( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * + * timeoutManager.clearTimeout(timeoutId) + * ``` + */ + clearTimeout(timeoutId: ManagedTimerId | undefined): void { + this.#provider.clearTimeout(timeoutId) + } + + /** + * `setInterval` schedules a callback to be called approximately every + * `delay` milliseconds, like the global `setInterval` function. + * + * Like `setTimeout`, it returns a timer ID, which may be a number or an + * object that can be coerced to a number via `Symbol.toPrimitive`. + * @param callback - The function to call on every interval. + * @param delay - The time between calls, in milliseconds. + * @returns The timer ID, to pass to {@link TimeoutManager#clearInterval}. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/query-core-pluggable' + * + * const intervalId = timeoutManager.setInterval( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * ``` + */ + setInterval(callback: TimeoutCallback, delay: number): ManagedTimerId { + if (process.env.NODE_ENV !== 'production') { + this.#providerCalled = true + } + return this.#provider.setInterval(callback, delay) + } + + /** + * `clearInterval` can be used to cancel an interval, like the global + * `clearInterval` function. It should be called with an interval ID + * returned by `setInterval`. + * @param intervalId - The timer ID returned by `setInterval`, or `undefined`. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/query-core-pluggable' + * + * const intervalId = timeoutManager.setInterval( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * + * timeoutManager.clearInterval(intervalId) + * ``` + */ + clearInterval(intervalId: ManagedTimerId | undefined): void { + this.#provider.clearInterval(intervalId) + } +} + +/** + * Singleton instance of {@link TimeoutManager}, used throughout TanStack Query to schedule and cancel timers. + */ +export const timeoutManager = new TimeoutManager() diff --git a/packages/query-core-pluggable/src/types.ts b/packages/query-core-pluggable/src/types.ts new file mode 100644 index 00000000000..a7fe4436800 --- /dev/null +++ b/packages/query-core-pluggable/src/types.ts @@ -0,0 +1,2067 @@ +/* istanbul ignore file */ + +import type { DehydrateOptions, HydrateOptions } from './hydration' +import type { MutationState } from './mutation' +import type { MutationCache } from './mutationCache' +import type { placeholderData } from './placeholderData' +import type { Select } from './projectionTypes' +import type { Query } from './query' +import type { QueryCache } from './queryCache' +import type { QueryClient } from './queryClient' +import type { RefetchInterval } from './refetchInterval' +import type { RetryDelayValue, RetryValue } from './retryer' +import type { SerialScope } from './serialScope' +import type { + DefaultQueryFn, + QueryFilters, + QueryTypeFilter, + SkipToken, +} from './utils' + +/** + * Excludes `undefined` from `T`. Used where a value must be defined, such as the data type that a + * defined `initialData` resolves to. + */ +export type NonUndefinedGuard = T extends undefined ? never : T + +/** + * Like `Omit`, but applied to each member of a union separately, so each member keeps its own keys. + */ +export type DistributiveOmit< + TObject, + TKey extends keyof TObject, +> = TObject extends any ? Omit : never + +/** + * Like `Omit`, but by default (`'strictly'`) `TKey` must be a key of `TObject`, so omitting a key + * that doesn't exist is a type error. Pass `'safely'` to allow other keys too. + */ +export type OmitKeyof< + TObject, + TKey extends (TStrictly extends 'safely' + ? | keyof TObject + | (string & Record) + | (number & Record) + | (symbol & Record) + : keyof TObject), + TStrictly extends 'strictly' | 'safely' = 'strictly', +> = Omit + +/** + * Replaces the types of the properties of `TTargetA` that also exist in `TTargetB` with their types + * in `TTargetB`. Properties that only exist in `TTargetB` are not added. + */ +export type Override = { + [AKey in keyof TTargetA]: AKey extends keyof TTargetB + ? TTargetB[AKey] + : TTargetA[AKey] +} + +/** + * The interface to augment via declaration merging to override Query's default types repository-wide. + * Each field it declares replaces the default of the matching type: `defaultError` for {@link DefaultError}, + * `queryKey` for {@link QueryKey}, `mutationKey` for {@link MutationKey}, `queryMeta` for {@link QueryMeta} and + * `mutationMeta` for {@link MutationMeta}. Leave a field out to keep that type's default. + * Augment `@tanstack/query-core-pluggable` or `@tanstack/react-query-pluggable` to + * configure types for the pluggable client and its React adapter. + * @example + * ```ts + * // Configure the pluggable runtime and its adapters. + * declare module '@tanstack/query-core-pluggable' { + * interface Register { + * defaultError: AxiosError + * } + * } + * ``` + */ +export interface Register { + // defaultError: Error + // queryMeta: Record + // mutationMeta: Record + // queryKey: ReadonlyArray + // mutationKey: ReadonlyArray +} + +/** + * The error type used wherever an error is not given an explicit type parameter. + * Defaults to `Error`; declare `defaultError` on {@link Register} to change it everywhere at once. + */ +export type DefaultError = Register extends { + defaultError: infer TError +} + ? TError + : Error + +/** + * The type of a query key — the serializable array that identifies a query in the cache. + * Defaults to `ReadonlyArray`; declare `queryKey` on {@link Register} to narrow it repository-wide. + */ +export type QueryKey = Register extends { + queryKey: infer TQueryKey +} + ? TQueryKey extends ReadonlyArray + ? TQueryKey + : TQueryKey extends Array + ? TQueryKey + : ReadonlyArray + : ReadonlyArray + +export const dataTagSymbol = Symbol() +/** + * The type of the `dataTagSymbol` key, under which a {@link DataTag} stores its data type. + */ +export type dataTagSymbol = typeof dataTagSymbol +export const dataTagErrorSymbol = Symbol() +/** + * The type of the `dataTagErrorSymbol` key, under which a {@link DataTag} stores its error type. + */ +export type dataTagErrorSymbol = typeof dataTagErrorSymbol +export const unsetMarker = Symbol() +/** + * The type of `unsetMarker`, the default error type of a {@link DataTag}. It marks that no error + * type was tagged. + */ +export type UnsetMarker = typeof unsetMarker +/** + * Matches any type that has been tagged with {@link DataTag}, whatever its data and error types. + */ +export type AnyDataTag = { + /** + * The data type the key was tagged with. + */ + [dataTagSymbol]: any + /** + * The error type the key was tagged with. + */ + [dataTagErrorSymbol]: any +} +/** + * Tags `TType` (usually a query key) with a data type and an optional error type, so that APIs that + * receive it, like `getQueryData`, can infer them. A type that is already tagged is + * returned as is. + */ +export type DataTag< + TType, + TValue, + TError = UnsetMarker, +> = TType extends AnyDataTag + ? TType + : TType & { + [dataTagSymbol]: TValue + [dataTagErrorSymbol]: TError + } + +/** + * An object whose `queryKey` is tagged with {@link DataTag}, like the options returned by + * `queryOptions`. + */ +export type QueryKeyWithDataTag< + TQueryKey extends QueryKey = QueryKey, + TQueryFnData = unknown, + TError = DefaultError, +> = { + /** + * The query key, tagged with the query's data and error types. + */ + queryKey: DataTag +} + +/** + * The data type tagged on a query key by {@link DataTag}, or `TQueryFnData` if the key is not + * tagged. + */ +export type InferDataFromTag = + TTaggedQueryKey extends DataTag + ? TaggedValue + : TQueryFnData + +/** + * The error type tagged on a query key by {@link DataTag}, or `TError` if the key is not tagged or + * was tagged without an error type. + */ +export type InferErrorFromTag = + TTaggedQueryKey extends DataTag + ? TaggedError extends UnsetMarker + ? TError + : TaggedError + : TError + +/** @inline */ +export type QueryFunction< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = (context: QueryFunctionContext) => T | Promise + +/** @inline */ +export type StaleTime = number | 'static' + +/** @inline */ +export type StaleTimeFunction< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = + | StaleTime + | ((query: Query) => StaleTime) + +/** @inline */ +export type QueryBooleanOption< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = + | boolean + | ((query: Query) => boolean) + +/** @inline */ +export type QueryPersister< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = [TPageParam] extends [never] + ? ( + queryFn: QueryFunction, + context: QueryFunctionContext, + query: Query, + ) => T | Promise + : ( + queryFn: QueryFunction, + context: QueryFunctionContext, + query: Query, + ) => T | Promise + +/** + * The object passed to `queryFn`: the `QueryClient`, the `queryKey`, an `AbortSignal` that aborts + * when the query is cancelled, the query's `meta`, and for infinite queries the `pageParam` of the + * page being fetched. + */ +export type QueryFunctionContext< + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = [TPageParam] extends [never] + ? { + client: QueryClient + queryKey: TQueryKey + signal: AbortSignal + meta: QueryMeta | undefined + pageParam?: unknown + } + : { + client: QueryClient + queryKey: TQueryKey + signal: AbortSignal + pageParam: TPageParam + meta: QueryMeta | undefined + } + +/** @inline */ +export type InitialDataFunction = () => T | undefined + +// oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch +type NonFunctionGuard = T extends Function ? never : T + +/** @inline */ +export type PlaceholderDataFunction< + TQueryFnData = unknown, + TError = DefaultError, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = ( + previousData: TQueryData | undefined, + previousQuery: Query | undefined, +) => TQueryData | undefined + +/** + * The `placeholderData` function of a query in `useQueries` and its counterparts. Unlike + * {@link PlaceholderDataFunction}, it receives no previous data or query, because the number of + * queries can differ between renders. + */ +export type QueriesPlaceholderDataFunction = ( + previousData: undefined, + previousQuery: undefined, +) => TQueryData | undefined + +/** @inline */ +export type EqualityFn = (a: unknown, b: unknown) => boolean + +/** @inline */ +export type CacheKeyHashFunction< + TCacheKey extends ReadonlyArray = ReadonlyArray, +> = (cacheKey: TCacheKey) => string + +/** Configures the comparison and hashing of query or mutation keys for a cache. */ +export interface CacheKeyConfig< + TCacheKey extends ReadonlyArray = ReadonlyArray, +> { + /** + * Function used to compare values while partially matching keys. + * Defaults to strict equality. + */ + equalityFn?: EqualityFn + /** + * Function used to hash keys globally. + */ + hashFn?: CacheKeyHashFunction +} + +/** @inline */ +export type GetPreviousPageParamFunction = ( + firstPage: TQueryFnData, + allPages: Array, + firstPageParam: TPageParam, + allPageParams: Array, +) => TPageParam | undefined | null + +/** @inline */ +export type GetNextPageParamFunction = ( + lastPage: TQueryFnData, + allPages: Array, + lastPageParam: TPageParam, + allPageParams: Array, +) => TPageParam | undefined | null + +/** + * The data shape of an infinite query: every page fetched so far, plus the page param each one was fetched with. + * `pages` and `pageParams` are index-aligned — `pageParams[i]` is the param that produced `pages[i]`. + */ +export interface InfiniteData { + /** + * The data of every page fetched so far, in order. + */ + pages: Array + /** + * The page param each page was fetched with, aligned by index with `pages`. + */ + pageParams: Array +} + +/** + * The type of the `meta` object that can be attached to a query and read back from `queryFn`, callbacks and + * cache-level handlers. Defaults to `Record`; declare `queryMeta` on {@link Register} to narrow it. + */ +export type QueryMeta = Register extends { + queryMeta: infer TQueryMeta +} + ? TQueryMeta extends Record + ? TQueryMeta + : Record + : Record + +/** @inline */ +export type NetworkMode = 'online' | 'always' | 'offlineFirst' + +/** @inline */ +export type NotifyOnChangeProps = 'all' | 'none' + +/** + * The options of a query itself — its `queryKey`, `queryFn`, retries, `gcTime`, `initialData`, + * `meta`, and so on — shared by observers and the `QueryClient` methods that fetch queries. + */ +export interface QueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> { + /** + * If `false`, failed queries will not retry by default. + * If `true`, failed queries will retry infinitely. + * If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. + * If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. + * + * Defaults to `3` on the client and `0` on the server. + */ + retry?: RetryValue + /** + * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives + * the failure count and error and returns the delay. The count starts at 0 for the first retry. + * + * A function like `attempt => Math.min(1000 * 2 ** attempt, 30000)` applies exponential + * backoff. + * + * A function like `attempt => attempt * 1000` applies linear backoff. + * + * By default, each retry waits a random duration from 80% to 100% of the base delay. + * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. + */ + retryDelay?: RetryDelayValue + /** + * Controls whether a query is allowed to run based on the current network connectivity. + * @defaultValue 'online' + * @see [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. + */ + networkMode?: NetworkMode + /** + * The time in milliseconds that unused/inactive cache data remains in memory. + * When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. + * When different garbage collection times are specified, the longest one will be used. + * Setting it to `Infinity` will disable garbage collection. + * + * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. + * + * Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see + * `timeoutManager.setTimeoutProvider` for a workaround. + */ + gcTime?: number + /** + * The function that the query will use to request data. + * Pass `defaultQueryFn` to use the function configured in the client's query defaults. + * Pass `skipToken` to disable a query without a function where supported. + * Receives a {@link QueryFunctionContext}. + * Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. + */ + queryFn?: + | QueryFunction + | SkipToken + | DefaultQueryFn + /** + * This option can be used to persist the result of a query to an external storage, bypassing the need to actually + * call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. + */ + persister?: QueryPersister, TPageParam> + /** + * The cache key. If omitted, the query cache computes it from `queryKey` + * using its configured `hashFn` or the default hash function. + */ + queryHash?: string + /** + * The query key to use for this query. + * + * The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) + * for more information. + * + * The query will automatically update when this key changes (as long as `enabled` is not set to `false`). + */ + queryKey?: TQueryKey + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). + * If set to a function, the function will be called **once** during the shared/root query initialization, and be + * expected to synchronously return the initial data. + * Initial data is considered stale by default unless a `staleTime` has been set. + * `initialData` **is persisted** to the cache. + */ + initialData?: TData | InitialDataFunction + /** + * If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. + */ + initialDataUpdatedAt?: number | (() => number | undefined) + /** + * Set this to `false` to disable structural sharing between query results. + * Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. + * @defaultValue true + */ + structuralSharing?: + | boolean + | ((oldData: unknown | undefined, newData: unknown) => unknown) + /** @internal */ + _defaulted?: boolean + /** @internal */ + _type?: 'infinite' + /** + * Additional payload to be stored on each query. + * Use this property to pass information that can be used in other places. + */ + meta?: QueryMeta + /** + * Maximum number of pages to store in the data of an infinite query. + */ + maxPages?: number +} + +/** + * Holds the `initialPageParam` option that every infinite query requires. + */ +export interface InitialPageParam { + /** + * The page param to start from when an infinite query has no pages yet. + * It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the + * value returned by `getNextPageParam` or `getPreviousPageParam`. + * It only applies while the query has no pages: once a first page exists, refetching starts from + * that page's own param instead. + */ + initialPageParam: TPageParam +} + +/** + * The page param options of an infinite query: `initialPageParam`, and the `getNextPageParam` and + * `getPreviousPageParam` functions that compute the params of the pages around it. + */ +export interface InfiniteQueryPageParamsOptions< + TQueryFnData = unknown, + TPageParam = unknown, +> extends InitialPageParam { + /** + * This function can be set to automatically get the previous cursor for infinite queries. + * The result will also be used to determine the value of `hasPreviousPage`. + */ + getPreviousPageParam?: GetPreviousPageParamFunction + /** + * This function can be set to automatically get the next cursor for infinite queries. + * The result will also be used to determine the value of `hasNextPage`. + */ + getNextPageParam: GetNextPageParamFunction +} + +/** @inline */ +export type ThrowOnError< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = + | boolean + | (( + error: TError, + query: Query, + ) => boolean) + +/** + * The adapter supplies a context and a per-render error check. The core only carries this + * value through query defaults and never subscribes to the context. + */ +export interface QueryErrorBoundaryPolicy { + /** The context read by the adapter when boundary handling is enabled. */ + readonly context: TContext + /** Prepares the checks and commit callback for this render. */ + prepare: ( + client: QueryClient, + options: DefaultedQueryObserverOptions, + boundary: TBoundary, + ) => { + /** Runs after a successful commit when the boundary changes. */ + onCommit: () => void + /** Checks a settled snapshot during render. */ + check: (result: QueryObserverResult) => void + } +} + +/** A paired error-boundary policy and a rule evaluated against the cached query. */ +export type QueryErrorBoundaryOption< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = + | false + | readonly [ + policy: QueryErrorBoundaryPolicy, + rule: + | true + | Exclude< + ThrowOnError, + boolean + >, + ] + +/** + * Shared options for default resolution and resolved observer state. + * @internal + */ +export interface QueryObserverOptionsBase< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> extends WithRequired< + QueryOptions, + 'queryKey' +> { + /** + * Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. + * To refetch the query, use the `refetch` method returned from the `useQuery` instance. + * Accepts a boolean or function that returns a boolean. + * @defaultValue true + */ + enabled?: QueryBooleanOption + /** + * The time in milliseconds after data is considered stale. + * If set to `Infinity`, the data will never be considered stale. + * If set to `'static'`, the data will never be considered stale. + * If set to a function, the function will be executed with the query to compute a `staleTime`. + * @defaultValue 0 + */ + staleTime?: StaleTimeFunction + + /** Set refetchInterval(milliseconds) or return it from a callback to poll the query. */ + refetchInterval?: + | false + | RefetchInterval> + | (( + query: Query, + ) => + | false + | undefined + | RefetchInterval>) + + /** + * If set to `true`, the query will continue to refetch while their tab/window is in the background. + * @defaultValue false + */ + refetchIntervalInBackground?: boolean + /** + * If set to `true`, the query will refetch on window focus if the data is stale. + * If set to `false`, the query will not refetch on window focus. + * If set to `'always'`, the query will always refetch on window focus (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value. + * @defaultValue true + */ + refetchOnWindowFocus?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `true`, the query will refetch on reconnect if the data is stale. + * If set to `false`, the query will not refetch on reconnect. + * If set to `'always'`, the query will always refetch on reconnect (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value. + * + * Defaults to `true` unless `networkMode` is `'always'`. + */ + refetchOnReconnect?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `true`, the query will refetch on mount if the data is stale. + * If set to `false`, will disable additional instances of a query to trigger background refetch. + * If set to `'always'`, the query will always refetch on mount (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value + * @defaultValue true + */ + refetchOnMount?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `false`, the query will not be retried on mount if it contains an error. + * If set to a function, the function will be executed with the query to compute the value. + * @defaultValue true + */ + retryOnMount?: QueryBooleanOption + /** + * Controls when changes to the query result notify this observer's listeners. + * Use `'all'` to notify on every result change. + * Use `'none'` to suppress notifications while the query remains subscribed and can fetch. + * If `throwOnError` is set, changes to `error` still notify listeners. + * + * By default, adapters that track property reads notify listeners when a tracked property changes. + * If no properties are tracked, every result change notifies listeners. + */ + notifyOnChangeProps?: NotifyOnChangeProps + /** + * Whether errors should be thrown instead of setting the `error` property. + * If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. + * If set to `false` and `suspense` is `false`, errors are returned as state. + * If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`). + * @defaultValue false + */ + throwOnError?: + | ThrowOnError + | QueryErrorBoundaryOption + + /** Pass [select, transform] to derive the data returned by this observer. */ + select?: Select + + /** + * If set to `true`, the query will suspend when `status === 'pending'` + * and throw errors when `status === 'error'`. + * @defaultValue false + */ + suspense?: boolean + + /** Wrap a value or factory with placeholderData to display it while the query loads. */ + placeholderData?: readonly [ + feature: typeof placeholderData, + value: PlaceholderValue, + ] + + /** @internal */ + _optimisticResults?: 'optimistic' | 'isRestoring' +} + +/** + * The options of a `QueryObserver`, and of the hooks built on it like `useQuery`: the + * {@link QueryOptions} of the query, plus options that control the observer, such as `enabled`, + * `staleTime`, `refetchInterval`, `select`, and `placeholderData`. + * Pass a `queryFn` or use `defaultQueryFn` to select the client defaults. + */ +export interface QueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> extends WithRequired< + QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'queryFn' +> {} + +/** + * Makes the `TKey` properties of `TTarget` required and non-nullable. + */ +export type WithRequired = TTarget & { + [_ in TKey]: {} +} + +/** + * The {@link QueryObserverOptions} after `defaultQueryOptions` has applied the + * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + */ +export type DefaultedQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = WithRequired< + QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'throwOnError' | 'refetchOnReconnect' | 'queryHash' +> + +/** + * The options of an `InfiniteQueryObserver`: {@link QueryObserverOptions} whose query data is + * {@link InfiniteData}, plus the page param options. + */ +export interface InfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> + extends + QueryObserverOptions< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam + >, + InfiniteQueryPageParamsOptions {} + +/** + * The {@link InfiniteQueryObserverOptions} after `defaultQueryOptions` has applied the + * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + */ +export type DefaultedInfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam +> & + InfiniteQueryPageParamsOptions + +/** + * The options of `query`: the {@link QueryOptions} of the query, plus a `staleTime` + * that decides whether cached data is returned instead of fetching, and a `select` that only + * transforms the value the call resolves with. + */ +export interface QueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> extends WithRequired< + QueryOptions, + 'queryKey' +> { + /** + * Not allowed here, since `initialPageParam` only applies to infinite queries. + */ + initialPageParam?: never + + /** Pass [select, transform] to derive the resolved value while retaining the fetched data in the cache. */ + select?: Select + + /** + * The time in milliseconds after data is considered stale. + * If the data is fresh it will be returned from the cache. + */ + staleTime?: StaleTimeFunction +} + +type InfiniteQueryFetchPageOptions = Pick< + InfiniteQueryPageParamsOptions, + 'initialPageParam' | 'getNextPageParam' +> & { + /** + * The number of pages to fetch. Defaults to the number of cached pages, + * or one page if the cache has no pages. + */ + pages?: number +} + +/** + * The options of `infiniteQuery`. Extends {@link QueryExecuteOptions} + * with `initialPageParam`, `getNextPageParam`, and the optional `pages` count. + */ +export type InfiniteQueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = Omit< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam + >, + 'initialPageParam' +> & + InfiniteQueryFetchPageOptions + +/** + * Options shared by the `QueryClient` and observer methods that refetch queries, controlling + * whether a failed refetch makes the returned promise reject. + */ +export interface ResultOptions { + /** + * If set to `true`, the method throws if any of the underlying query refetch tasks fail. + * If set to `false`, failed refetches are swallowed and not surfaced to the caller. + * @defaultValue false + */ + throwOnError?: boolean +} + +/** + * Options of the methods that refetch queries, like `refetch` and `refetchQueries`. + */ +export interface RefetchOptions extends ResultOptions { + /** + * If set to `true`, a currently running request will be cancelled before a new request is made + * + * If set to `false`, no refetch will be made if there is already a request running. + * @defaultValue true + */ + cancelRefetch?: boolean +} + +/** + * The filters of `invalidateQueries`: the {@link QueryFilters} that select the queries + * to invalidate, plus `refetchType` to choose which of them are refetched. + */ +export interface InvalidateQueryFilters< + TQueryKey extends QueryKey = QueryKey, +> extends QueryFilters { + /** + * Controls which of the matched (now-invalidated) queries are refetched in the background. + * + * - `'active'`: only queries with at least one active observer are refetched. + * - `'inactive'`: only queries with no active observer are refetched. + * - `'all'`: every matched query is refetched, active or not. + * - `'none'`: no query is refetched; matched queries are only marked as invalidated. + * @defaultValue 'active' + */ + refetchType?: QueryTypeFilter | 'none' +} + +/** + * The filters of `refetchQueries`, which select the queries to refetch. + */ +export interface RefetchQueryFilters< + TQueryKey extends QueryKey = QueryKey, +> extends QueryFilters {} + +/** + * Options of `invalidateQueries`, applied to the refetch that follows the invalidation. + */ +export interface InvalidateOptions extends RefetchOptions {} +/** + * Options of `resetQueries`, applied to the refetch of the active queries after the + * reset. + */ +export interface ResetOptions extends RefetchOptions {} + +/** + * Options of `fetchNextPage` on an infinite query result. + */ +export interface FetchNextPageOptions extends ResultOptions { + /** + * If set to `true`, calling `fetchNextPage` repeatedly will invoke `queryFn` every time, + * whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored. + * + * If set to `false`, calling `fetchNextPage` repeatedly won't have any effect until the first invocation has resolved. + * @defaultValue true + */ + cancelRefetch?: boolean +} + +/** + * Options of `fetchPreviousPage` on an infinite query result. + */ +export interface FetchPreviousPageOptions extends ResultOptions { + /** + * If set to `true`, calling `fetchPreviousPage` repeatedly will invoke `queryFn` every time, + * whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored. + * + * If set to `false`, calling `fetchPreviousPage` repeatedly won't have any effect until the first invocation has resolved. + * @defaultValue true + */ + cancelRefetch?: boolean +} + +/** @inline */ +export type QueryStatus = 'pending' | 'error' | 'success' +/** @inline */ +export type FetchStatus = 'fetching' | 'paused' | 'idle' + +/** + * The properties shared by every state of a query result, like `data`, `error`, `status`, + * `fetchStatus`, and `refetch`. Each `QueryObserver*Result` narrows them for one state. + */ +export interface QueryObserverBaseResult< + TData = unknown, + TError = DefaultError, +> { + /** + * The last successfully resolved data for the query. + */ + data: TData | undefined + /** + * The timestamp for when the query most recently returned the `status` as `"success"`. + */ + dataUpdatedAt: number + /** Number of writes to the underlying query data, including manual updates. */ + dataUpdateCount: number + /** + * The error object for the query, if an error was thrown. + * - Defaults to `null`. + */ + error: TError | null + /** + * The timestamp for when the query most recently returned the `status` as `"error"`. + */ + errorUpdatedAt: number + /** + * The failure count for the query. + * - Incremented every time the query fails. + * - Reset to `0` when the query succeeds. + */ + failureCount: number + /** + * The failure reason for the query retry. + * - Reset to `null` when the query succeeds. + */ + failureReason: TError | null + /** + * The sum of all errors. + */ + errorUpdateCount: number + /** + * Will be `true` if the query has been fetched after the component mounted. + * - This property can be used to not show any previously cached data. + */ + isFetchedAfterMount: boolean + /** + * Will be `true` if the data shown is the placeholder data. + */ + isPlaceholderData: boolean + /** + * Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. + */ + isStale: boolean + /** + * `true` if this observer is enabled, `false` otherwise. + */ + isEnabled: boolean + /** + * A function to manually refetch the query. + */ + refetch: ( + options?: RefetchOptions, + ) => Promise> + /** + * The status of the query. + * - Will be: + * - `error` if the query has an error from a fetch that failed after its retries, or if `select` threw. + * - `success` if the query has cached data (even if `select` returns `undefined`) or data from `placeholderData`, and no error. + * - `pending` otherwise, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: QueryStatus + /** + * The fetch status of the query. + * - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. + * - `paused`: The query wanted to fetch, but has been `paused`. + * - `idle`: The query is not fetching. + * - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. + */ + fetchStatus: FetchStatus +} + +/** + * A query result in the `pending` state: the query has no data yet. + */ +export interface QueryObserverPendingResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** Fetch state while this query is pending. */ + fetchStatus: 'idle' | 'paused' + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * A pending query result while its first fetch is in flight. + */ +export interface QueryObserverLoadingResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** The initial fetch is running. */ + fetchStatus: 'fetching' + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * A query result in the `error` state with no data to display, since a fetch or `select` failed. + */ +export interface QueryObserverLoadingErrorResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * `undefined`, since there was no data to display when a fetch or `select` failed. + */ + data: undefined + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * A query result in the `error` state that keeps the data from before a fetch or `select` failed. + */ +export interface QueryObserverRefetchErrorResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * The data from before the fetch or `select` failed, which is kept. + */ + data: TData + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * A query result in the `success` state with data from the cache. + */ +export interface QueryObserverSuccessResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * The last successfully resolved data for the query. + */ + data: TData + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'success'`, since the query has cached data and no error from a fetch or from + * `select`. + */ + status: 'success' +} + +/** + * A query result in the `success` state that shows `placeholderData` while the query has no data + * yet. + */ +export interface QueryObserverPlaceholderResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * The `placeholderData` shown while the query has no data yet. + */ + data: TData + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `true`, since the data shown is the `placeholderData`. + */ + isPlaceholderData: true + /** + * `'success'`, since the query shows `placeholderData` and has no error from a fetch or + * from `select`. + */ + status: 'success' +} + +/** + * A query result that always has `data`: the success and refetch error states. + */ +export type DefinedQueryObserverResult< + TData = unknown, + TError = DefaultError, +> = + | QueryObserverRefetchErrorResult + | QueryObserverSuccessResult + +/** + * The result of a `QueryObserver`, and of the hooks built on it like `useQuery`. Narrow it by + * `status` or a result type guard such as `isSuccess(result)`. + */ +export type QueryObserverResult = + | DefinedQueryObserverResult + | QueryObserverLoadingErrorResult + | QueryObserverLoadingResult + | QueryObserverPendingResult + | QueryObserverPlaceholderResult + +/** + * The properties shared by every state of an infinite query result: those of + * {@link QueryObserverBaseResult}, plus `fetchNextPage`, `fetchPreviousPage`, page availability + * and the direction of the most recent page request. + */ +export interface InfiniteQueryObserverBaseResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * This function allows you to fetch the next "page" of results. + */ + fetchNextPage: ( + options?: FetchNextPageOptions, + ) => Promise> + /** + * This function allows you to fetch the previous "page" of results. + */ + fetchPreviousPage: ( + options?: FetchPreviousPageOptions, + ) => Promise> + /** + * Will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). + */ + hasNextPage: boolean + /** + * Will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). + */ + hasPreviousPage: boolean + /** Direction of the current or last page request. A full refetch has no direction. */ + fetchDirection: 'forward' | 'backward' | undefined +} + +/** + * An infinite query result in the `pending` state: the query has no data yet. + */ +export interface InfiniteQueryObserverPendingResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** Fetch state while this query is pending. */ + fetchStatus: 'idle' | 'paused' + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * A pending infinite query result while its first fetch is in flight. + */ +export interface InfiniteQueryObserverLoadingResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** The initial fetch is running. */ + fetchStatus: 'fetching' + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * An infinite query result in the `error` state with no data to display, since a fetch or `select` failed. + */ +export interface InfiniteQueryObserverLoadingErrorResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * `undefined`, since there was no data to display when a fetch or `select` failed. + */ + data: undefined + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * An infinite query result in the `error` state that keeps the data from before a fetch or `select` + * failed. + */ +export interface InfiniteQueryObserverRefetchErrorResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * The data from before the fetch or `select` failed, which is kept. + */ + data: TData + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * An infinite query result in the `success` state with data from the cache. + */ +export interface InfiniteQueryObserverSuccessResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * The last successfully resolved data for the query. + */ + data: TData + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'success'`, since the query has cached data and no error from a fetch or from + * `select`. + */ + status: 'success' +} + +/** + * An infinite query result in the `success` state that shows `placeholderData` while the query has + * no data yet. + */ +export interface InfiniteQueryObserverPlaceholderResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * The `placeholderData` shown while the query has no data yet. + */ + data: TData + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `true`, since the data shown is the `placeholderData`. + */ + isPlaceholderData: true + /** + * `'success'`, since the query shows `placeholderData` and has no error from a fetch or + * from `select`. + */ + status: 'success' +} + +/** + * An infinite query result that always has `data`: the success and refetch error states. + */ +export type DefinedInfiniteQueryObserverResult< + TData = unknown, + TError = DefaultError, +> = + | InfiniteQueryObserverRefetchErrorResult + | InfiniteQueryObserverSuccessResult + +/** + * The result of an `InfiniteQueryObserver`, including `useQuery(infiniteQueryOptions(options))`. + * Narrow it by `status` or a result type guard such as `isSuccess(result)`. + */ +export type InfiniteQueryObserverResult< + TData = unknown, + TError = DefaultError, +> = + | DefinedInfiniteQueryObserverResult + | InfiniteQueryObserverLoadingErrorResult + | InfiniteQueryObserverLoadingResult + | InfiniteQueryObserverPendingResult + | InfiniteQueryObserverPlaceholderResult + +/** + * The type of a mutation key — the serializable array used to identify and filter mutations. + * Defaults to `ReadonlyArray`; declare `mutationKey` on {@link Register} to narrow it repository-wide. + */ +export type MutationKey = Register extends { + mutationKey: infer TMutationKey +} + ? TMutationKey extends ReadonlyArray + ? TMutationKey + : TMutationKey extends Array + ? TMutationKey + : ReadonlyArray + : ReadonlyArray + +/** @inline */ +export type MutationStatus = 'idle' | 'pending' | 'success' | 'error' + +/** + * Groups mutations so they run one after another instead of in parallel. + * Mutations that share the same `id` form a queue: while one is running, the others wait in `isPaused: true` + * state and resume automatically when their turn comes. Mutations with no scope always run in parallel. + */ +export type MutationScope = { + /** + * The scope's identifier. Mutations with the same `id` run one after another. + */ + id: string +} + +/** + * The type of the `meta` object that can be attached to a mutation and read back from `mutationFn`, callbacks and + * cache-level handlers. Defaults to `Record`; declare `mutationMeta` on {@link Register} to narrow it. + */ +export type MutationMeta = Register extends { + mutationMeta: infer TMutationMeta +} + ? TMutationMeta extends Record + ? TMutationMeta + : Record + : Record + +/** + * The object passed to `mutationFn` and the mutation callbacks: the `QueryClient`, the mutation's + * `meta`, and its `mutationKey`. + */ +export type MutationFunctionContext = { + /** + * The `QueryClient` the mutation runs in. + */ + client: QueryClient + /** + * The `meta` of the mutation options. + */ + meta: MutationMeta | undefined + /** + * The `mutationKey` of the mutation options, if set. + */ + mutationKey?: MutationKey +} + +/** @inline */ +export type MutationFunction = ( + variables: TVariables, + context: MutationFunctionContext, +) => Promise + +/** + * The options of a mutation: its `mutationFn`, `mutationKey`, callbacks, retries, `scope`, and so + * on. + */ +export interface MutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> { + /** + * The function that performs the asynchronous task this mutation runs. + * Required, unless a default mutation function has been set for the matching `mutationKey` via + * `setMutationDefaults`. + * Receives the `variables` passed to `mutate`, and a {@link MutationFunctionContext} holding the + * `QueryClient`, the `mutationKey` and `meta`. + * Must return a promise that resolves the mutation's data. + */ + mutationFn?: MutationFunction + /** + * The key to use for this mutation. Optional, but required to inherit defaults registered with + * `setMutationDefaults`, and to match this mutation with `useMutationState` or + * `isMutating`. + */ + mutationKey?: MutationKey + /** + * This function fires before the mutation function runs, and receives the same variables. + * Useful for optimistic updates applied in the hope that the mutation succeeds. + * The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, + * which is where an optimistic update is usually rolled back. + * If a promise is returned, it is awaited before the mutation function runs. + */ + onMutate?: ( + variables: TVariables, + context: MutationFunctionContext, + ) => Promise | TOnMutateResult + /** + * This function fires when the mutation succeeds, and is passed the mutation's result. + * If a promise is returned, it is awaited before `onSettled` runs. + */ + onSuccess?: ( + data: TData, + variables: TVariables, + onMutateResult: TOnMutateResult, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * This function fires when the mutation encounters an error, and is passed the error. + * If a promise is returned, it is awaited before `onSettled` runs. + */ + onError?: ( + error: TError, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * This function fires when the mutation either succeeds or errors, and is passed either the data + * or the error. + * If a promise is returned, it is awaited before the mutation settles. + */ + onSettled?: ( + data: TData | undefined, + error: TError | null, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * If `false`, failed mutations will not retry by default. + * If `true`, failed mutations will retry infinitely. + * If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. + * If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. + * @defaultValue 0 + */ + retry?: RetryValue + /** + * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives + * the failure count and error and returns the delay. The count starts at 0 for the first retry. + * + * By default, each retry waits a random duration from 80% to 100% of the base delay. + * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. + */ + retryDelay?: RetryDelayValue + /** + * Controls whether a mutation is allowed to run based on the current network connectivity. + * @defaultValue 'online' + * @see [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. + */ + networkMode?: NetworkMode + /** + * The time in milliseconds that an unused/inactive mutation remains in memory before it is + * garbage collected. + * + * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. + */ + gcTime?: number + /** @internal */ + _defaulted?: boolean + /** + * Additional payload to be stored on the mutation cache entry. + * Use it to pass information that can be read wherever the `mutation` is available, such as the + * `onError` and `onSuccess` callbacks of the `MutationCache`. + */ + meta?: MutationMeta + + /** Pass serialScope(id) to run mutations with this ID in order. */ + scope?: SerialScope +} + +/** + * The options of a `MutationObserver`, and of the hooks built on it like `useMutation`: the + * {@link MutationOptions}, plus `throwOnError`. + */ +export interface MutationObserverOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationOptions { + /** + * Whether errors should be thrown instead of setting the `error` property. + * If set to `true`, all errors will be thrown to the nearest error boundary. + * If set to a function, it will be passed the error and should return a boolean indicating whether to throw the + * error (`true`) or return it as state (`false`). + * @defaultValue false + */ + throwOnError?: boolean | ((error: TError) => boolean) +} + +/** + * The callbacks that can be passed to `mutate` for a single call. They run after the callbacks of + * the mutation options. + */ +export interface MutateOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> { + /** + * Called when the mutation of this call succeeds, after the `onSuccess` of the mutation options. + */ + onSuccess?: ( + data: TData, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void + /** + * Called when the mutation of this call fails, after the `onError` of the mutation options. + */ + onError?: ( + error: TError, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void + /** + * Called when the mutation of this call succeeds or fails, after the `onSettled` of the mutation + * options. + */ + onSettled?: ( + data: TData | undefined, + error: TError | null, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void +} + +/** + * The parameters of {@link MutateFunction}: `variables`, optional when `TVariables` accepts + * `undefined`, and the {@link MutateOptions} for that call. + */ +export type MutateFunctionRest< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = undefined extends TVariables + ? [ + variables?: TVariables, + options?: MutateOptions, + ] + : [ + variables: TVariables, + options?: MutateOptions, + ] + +/** + * The `mutate` function of a `MutationObserver`: runs the mutation with the given variables and + * resolves with its data. + */ +export type MutateFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = ( + ...rest: MutateFunctionRest +) => Promise + +/** + * The properties shared by every state of a mutation result, like `data`, `error`, `variables`, + * `status`, the `is*` flags, `mutate`, and `reset`. + */ +export interface MutationObserverBaseResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationState { + /** + * The last successfully resolved data for the mutation. + */ + data: TData | undefined + /** + * The variables object passed to the `mutationFn`. + */ + variables: TVariables | undefined + /** + * The error object for the mutation, if an error was encountered. + * - Defaults to `null`. + */ + error: TError | null + /** + * A boolean variable derived from `status`. + * - `true` if the last mutation attempt resulted in an error. + */ + isError: boolean + /** + * A boolean variable derived from `status`. + * - `true` if the mutation is in its initial state prior to executing. + */ + isIdle: boolean + /** + * A boolean variable derived from `status`. + * - `true` if the mutation is currently executing. + */ + isPending: boolean + /** + * A boolean variable derived from `status`. + * - `true` if the last mutation attempt was successful. + */ + isSuccess: boolean + /** + * The status of the mutation. + * - Will be: + * - `idle` initial status prior to the mutation function executing. + * - `pending` if the mutation is currently executing. + * - `error` if the last mutation attempt resulted in an error. + * - `success` if the last mutation attempt was successful. + */ + status: MutationStatus + /** + * The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. + * @param variables - The variables object to pass to the `mutationFn`. + * @param options.onSuccess - This function will fire when the mutation is successful and will be passed the mutation's result. + * @param options.onError - This function will fire if the mutation encounters an error and will be passed the error. + * @param options.onSettled - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error. + * @remarks + * - If you make multiple requests, `onSuccess` will fire only after the latest call you've made. + * - All the callback functions (`onSuccess`, `onError`, `onSettled`) are void functions, and the returned value will be ignored. + */ + mutate: MutateFunction + /** + * A function to clean the mutation internal state (i.e., it resets the mutation to its initial state). + */ + reset: () => void +} + +/** + * A mutation result in the `idle` state: the mutation hasn't run yet, or was reset. + */ +export interface MutationObserverIdleResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationObserverBaseResult< + TData, + TError, + TVariables, + TOnMutateResult +> { + /** + * `undefined`, since the mutation hasn't run. + */ + data: undefined + /** + * `undefined`, since the mutation hasn't run. + */ + variables: undefined + /** + * `null`, since the mutation hasn't failed. + */ + error: null + /** + * `false`, since the mutation hasn't failed. + */ + isError: false + /** + * `true`, since the mutation hasn't run yet or was reset. + */ + isIdle: true + /** + * `false`, since the mutation isn't running. + */ + isPending: false + /** + * `false`, since the mutation hasn't succeeded. + */ + isSuccess: false + /** + * `'idle'`, since the mutation hasn't run yet or was reset. + */ + status: 'idle' +} + +/** + * A mutation result in the `pending` state while the mutation runs. + */ +export interface MutationObserverLoadingResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationObserverBaseResult< + TData, + TError, + TVariables, + TOnMutateResult +> { + /** + * `undefined`, since the mutation hasn't succeeded. + */ + data: undefined + /** + * The variables passed to `mutate` for this mutation. + */ + variables: TVariables + /** + * `null`, since the mutation hasn't failed. + */ + error: null + /** + * `false`, since the mutation hasn't failed. + */ + isError: false + /** + * `false`, since the mutation has run. + */ + isIdle: false + /** + * `true`, since the mutation is running. + */ + isPending: true + /** + * `false`, since the mutation hasn't succeeded. + */ + isSuccess: false + /** + * `'pending'`, since the mutation is running. + */ + status: 'pending' +} + +/** + * A mutation result in the `error` state after the mutation failed. + */ +export interface MutationObserverErrorResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationObserverBaseResult< + TData, + TError, + TVariables, + TOnMutateResult +> { + /** + * `undefined`, since the mutation hasn't succeeded. + */ + data: undefined + /** + * The error the mutation failed with. + */ + error: TError + /** + * The variables passed to `mutate` for this mutation. + */ + variables: TVariables + /** + * `true`, since the mutation failed. + */ + isError: true + /** + * `false`, since the mutation has run. + */ + isIdle: false + /** + * `false`, since the mutation isn't running. + */ + isPending: false + /** + * `false`, since the mutation hasn't succeeded. + */ + isSuccess: false + /** + * `'error'`, since the mutation failed. + */ + status: 'error' +} + +/** + * A mutation result in the `success` state after the mutation succeeded. + */ +export interface MutationObserverSuccessResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationObserverBaseResult< + TData, + TError, + TVariables, + TOnMutateResult +> { + /** + * The data the mutation resolved with. + */ + data: TData + /** + * `null`, since the mutation hasn't failed. + */ + error: null + /** + * The variables passed to `mutate` for this mutation. + */ + variables: TVariables + /** + * `false`, since the mutation hasn't failed. + */ + isError: false + /** + * `false`, since the mutation has run. + */ + isIdle: false + /** + * `false`, since the mutation isn't running. + */ + isPending: false + /** + * `true`, since the mutation succeeded. + */ + isSuccess: true + /** + * `'success'`, since the mutation succeeded. + */ + status: 'success' +} + +/** + * The result of a `MutationObserver`, and of the hooks built on it like `useMutation`. Narrow it by + * `status` or the `is*` flags to get the type of each state. + */ +export type MutationObserverResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = + | MutationObserverIdleResult + | MutationObserverLoadingResult + | MutationObserverErrorResult + | MutationObserverSuccessResult + +/** + * The options of `new QueryClient()`: the `queryCache` and `mutationCache` to use, and the + * `defaultOptions` for its queries and mutations. + */ +export interface QueryClientConfig { + /** The query cache this client is connected to. A new `QueryCache` is created if not provided. */ + queryCache?: QueryCache + /** + * The mutation cache this client is connected to. A new `MutationCache` is created if not + * provided. + */ + mutationCache?: MutationCache + /** Default options for all queries and mutations created through this client. */ + defaultOptions?: DefaultOptions +} + +/** + * The default options of a `QueryClient`, applied to every query (`queries`), mutation + * (`mutations`), `hydrate`, and `dehydrate` call unless overridden. + */ +export interface DefaultOptions { + /** Default options applied to every query, unless overridden per-query. */ + queries?: OmitKeyof< + QueryObserverOptionsBase, + 'suspense' | 'queryKey' | 'throwOnError' + > & { + throwOnError?: QueryErrorBoundaryOption + } + /** Default options applied to every mutation, unless overridden per-mutation. */ + mutations?: MutationObserverOptions + /** Default options used when hydrating queries and mutations; see {@link HydrateOptions}. */ + hydrate?: HydrateOptions['defaultOptions'] + /** Default options used when dehydrating the client's caches; see {@link DehydrateOptions}. */ + dehydrate?: DehydrateOptions +} + +/** + * Options for cancelling an in-flight fetch, e.g. via `query.cancel()`. + * They are carried on the {@link CancelledError} that the cancelled fetch rejects with. + */ +export interface CancelOptions { + /** + * If `true`, the query goes back to the state it had before the fetch started, instead of getting + * the cancellation error. + */ + revert?: boolean + /** + * If `true`, the cancellation error isn't surfaced, e.g. because another fetch replaces the + * cancelled one. + */ + silent?: boolean +} + +/** + * Options for writing data into the cache, e.g. via `setQueryData()`. + * `updatedAt` overrides the timestamp the data is recorded with, which is what staleness is measured from; + * omit it to use the current time. + */ +export interface SetDataOptions { + /** + * The timestamp to record the data with, instead of the current time. Staleness is measured from + * it. + */ + updatedAt?: number +} + +/** @inline */ +export type NotifyEventType = + | 'added' + | 'removed' + | 'updated' + | 'observerAdded' + | 'observerRemoved' + | 'observerResultsUpdated' + | 'observerOptionsUpdated' + +/** + * The base shape of the events that the query and mutation caches send to their listeners. + */ +export interface NotifyEvent { + /** + * The kind of event, e.g. `'added'`, `'removed'`, or `'updated'`. + */ + type: NotifyEventType +} + +/** A raw placeholder value or the callback that supplies it for a query. */ +export type PlaceholderValue = + | NonFunctionGuard + | PlaceholderDataFunction< + NonFunctionGuard, + TError, + NonFunctionGuard, + TQueryKey + > diff --git a/packages/query-core-pluggable/src/utils.ts b/packages/query-core-pluggable/src/utils.ts new file mode 100644 index 00000000000..f9427374707 --- /dev/null +++ b/packages/query-core-pluggable/src/utils.ts @@ -0,0 +1,823 @@ +import { isQueryActive, isQueryStale } from './queryPredicates' +import { timeoutManager } from './timeoutManager' +import type { Mutation } from './mutation' +import type { FetchOptions, Query } from './query' +import type { + CacheKeyConfig, + DefaultError, + EqualityFn, + FetchStatus, + MutationKey, + MutationStatus, + QueryFunction, + QueryKey, + QueryOptions, +} from './types' + +// TYPES + +type DropLast> = T extends readonly [ + ...infer R, + unknown, +] + ? readonly [...R] + : never + +type TuplePrefixes> = T extends readonly [] + ? readonly [] + : TuplePrefixes> | T + +/** + * Filters used to select queries, for example in `getQueriesData` or `invalidateQueries`. + * All provided filters must match; filters that are left unspecified are ignored. + */ +export interface QueryFilters { + /** + * Filter to active queries, inactive queries or all queries + * @defaultValue 'all' + */ + type?: QueryTypeFilter + /** + * Match query key exactly + */ + exact?: boolean + /** + * Include queries matching this predicate function + */ + predicate?: (query: Query) => boolean + /** + * Include queries matching this query key + */ + queryKey?: TQueryKey | TuplePrefixes + /** + * Include or exclude stale queries + */ + stale?: boolean + /** + * Include queries matching their fetchStatus + */ + fetchStatus?: FetchStatus +} + +/** + * Filters used to select mutations, for example in `mutationCache.findAll` or `isMutating`. + * All provided filters must match; filters that are left unspecified are ignored. + */ +export interface MutationFilters< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> { + /** + * Match mutation key exactly + */ + exact?: boolean + /** + * Include mutations matching this predicate function + */ + predicate?: ( + mutation: Mutation, + ) => boolean + /** + * Include mutations matching this mutation key + */ + mutationKey?: TuplePrefixes + /** + * Filter by mutation status + */ + status?: MutationStatus +} + +/** + * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`. + * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a + * function that computes it from the previous data. See {@link functionalUpdate}. + * @example + * ```ts + * setQueryData(queryClient, ['posts'], newPosts) + * + * // Or, using an updater function that receives the current data: + * setQueryData(queryClient, ['posts'], (oldPosts) => + * oldPosts ? [...oldPosts, newPost] : oldPosts, + * ) + * ``` + */ +export type Updater = TOutput | ((input: TInput) => TOutput) + +/** + * Which queries a filter matches: all of them, only active ones (with enabled observers), or only + * inactive ones. + */ +export type QueryTypeFilter = 'all' | 'active' | 'inactive' + +// UTILS + +/** + * A function that does nothing. + */ +export function noop(): void +export function noop(): undefined +export function noop() {} + +/** + * Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as + * is. + * @param updater - The new value, or a function that receives `input` and returns the new value. + * @param input - The current value, passed to `updater` if it is a function. + * @returns The new value. + */ +export function functionalUpdate( + updater: Updater, + input: TInput, +): TOutput { + return typeof updater === 'function' + ? (updater as (_: TInput) => TOutput)(input) + : updater +} + +/** + * Checks whether a value can be used as a timeout: a non-negative, finite number. + * @param value - The value to check. + * @returns `true` if `value` is a number that is `>= 0` and not `Infinity`. + */ +export function isValidTimeout(value: unknown): value is number { + return typeof value === 'number' && value >= 0 && value !== Infinity +} + +/** + * Calculates how long until data updated at `updatedAt` becomes stale. + * @param updatedAt - The timestamp, in milliseconds, at which the data was last updated. + * @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to + * `0`. + * @returns The remaining time in milliseconds, or `0` if the data is already stale. + */ +export function timeUntilStale(updatedAt: number, staleTime?: number): number { + return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0) +} + +/** + * Resolves an option that can be given either as a value or as a function of the query, such as + * `staleTime`. + * @param value - The option value, or a function that receives `query` and returns the value. + * @param query - The query passed to `value` if it is a function. + * @returns The resolved value, or `undefined` if `value` is `undefined`. + */ +export function resolveQueryValue< + TValue, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + value: + | undefined + | TValue + | ((query: Query) => TValue), + query: Query, +): TValue | undefined { + return typeof value === 'function' + ? ( + value as ( + query: Query, + ) => TValue + )(query) + : value +} + +/** + * Checks whether a query matches the given {@link QueryFilters}. + * Every filter that is specified must match; filters that are left unspecified are ignored. + * @param filters - The filters to check the query against. + * @param query - The query to check. + * @param keyConfig - The cache configuration for key comparison and hashing. + * @returns `true` if the query matches every specified filter. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * const matchingQueries = queryCache + * .getAll() + * .filter((query) => matchQuery({ queryKey: ['posts'] }, query)) + * ``` + */ +export function matchQuery( + filters: QueryFilters, + query: Query, + keyConfig?: CacheKeyConfig, +): boolean { + const { + type = 'all', + exact, + fetchStatus, + predicate, + queryKey, + stale, + } = filters + + if (queryKey) { + if (exact) { + if (query.queryHash !== hashKeyByOptions(queryKey, keyConfig)) { + return false + } + } else if ( + !partialMatchKey(query.queryKey, queryKey, keyConfig?.equalityFn) + ) { + return false + } + } + + if (type !== 'all') { + const isActive = isQueryActive(query) + if (type === 'active' && !isActive) { + return false + } + if (type === 'inactive' && isActive) { + return false + } + } + + if (typeof stale === 'boolean' && isQueryStale(query) !== stale) { + return false + } + + if (fetchStatus && fetchStatus !== query.state.fetchStatus) { + return false + } + + if (predicate && !predicate(query)) { + return false + } + + return true +} + +/** + * Checks whether a mutation matches the given {@link MutationFilters}. + * Every filter that is specified must match; filters that are left unspecified are ignored. + * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match. + * @param filters - The filters to check the mutation against. + * @param mutation - The mutation to check. + * @param keyConfig - The cache configuration for key comparison and hashing. + * @returns `true` if the mutation matches every specified filter. + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * const matchingMutations = mutationCache + * .getAll() + * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation)) + * ``` + */ +export function matchMutation( + filters: MutationFilters, + mutation: Mutation, + keyConfig?: CacheKeyConfig, +): boolean { + const { exact, status, predicate, mutationKey } = filters + if (mutationKey) { + if (!mutation.options.mutationKey) { + return false + } + if (exact) { + if ( + hashKeyByOptions(mutation.options.mutationKey, keyConfig) !== + hashKeyByOptions(mutationKey, keyConfig) + ) { + return false + } + } else if ( + !partialMatchKey( + mutation.options.mutationKey, + mutationKey, + keyConfig?.equalityFn, + ) + ) { + return false + } + } + + if (status && mutation.state.status !== status) { + return false + } + + if (predicate && !predicate(mutation)) { + return false + } + + return true +} + +/** + * Hashes a cache key with the cache's `hashFn`, falling back to {@link hashKey}. + * @param cacheKey - The query or mutation key to hash. + * @param keyConfig - The cache configuration that may provide a custom `hashFn`. + * @returns The hash, a string that identifies the key in the cache. + */ +export function hashKeyByOptions< + TCacheKey extends ReadonlyArray = ReadonlyArray, +>( + cacheKey: TCacheKey, + keyConfig: CacheKeyConfig | undefined, +): string { + const hashFn = keyConfig?.hashFn ?? hashKey + return hashFn(cacheKey) +} + +/** + * Default query & mutation keys hash function. + * Hashes the value into a stable hash. + * @param queryKey - The query or mutation key to hash. + * @returns The stable hash of the key, as a JSON string. + * @example + * ```ts + * // Object keys are sorted, so key order doesn't affect the hash: + * hashKey(['todos', { page: 1, filter: 'done' }]) // === '["todos",{"filter":"done","page":1}]' + * ``` + */ +export function hashKey(queryKey: QueryKey | MutationKey): string { + return JSON.stringify(queryKey, (_, val) => + isPlainObject(val) + ? Object.keys(val) + .sort() + .reduce((result, key) => { + result[key] = val[key] + return result + }, {} as any) + : val, + ) +} + +const defaultEqualityFn: EqualityFn = (a, b) => a === b + +/** + * Checks if key `b` partially matches with key `a`. + * @param a - The key to check, e.g. a query's own key. + * @param b - The (partial) key to match against `a`. + * @param equalityFn - Compares individual key values. Defaults to strict equality. + * @returns `true` if every array element or object property in `b` matches the one at the same + * position in `a`. + */ +export function partialMatchKey( + a: QueryKey, + b: QueryKey, + equalityFn?: EqualityFn, +): boolean +export function partialMatchKey( + a: unknown, + b: unknown, + equalityFn?: EqualityFn, +): boolean +export function partialMatchKey( + a: any, + b: any, + equalityFn: EqualityFn = defaultEqualityFn, +): boolean { + if (equalityFn(a, b)) { + return true + } + + if (typeof a !== typeof b) { + return false + } + + if (isPlainArray(a) && isPlainArray(b)) { + if (b.length > a.length) return false + for (let i = 0; i < b.length; i++) { + if (!partialMatchKey(a[i], b[i], equalityFn)) { + return false + } + } + return true + } + + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b) + for (const key of bKeys) { + if (!partialMatchKey(a[key], b[key], equalityFn)) { + return false + } + } + return true + } + + return false +} + +/** + * This function returns `a` if `b` is deeply equal. + * If not, it will replace any deeply equal children of `b` with those of `a`. + * This can be used for structural sharing between JSON values for example. + * An optional equality function can be used for custom value types. + * @param a - The previous value, whose deeply equal parts are reused. + * @param b - The new value. + * @param equalityFn - Compares values for structural sharing. Defaults to strict equality. + * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by + * those of `a`. + */ +export function replaceEqualDeep( + a: unknown, + b: T, + equalityFn?: EqualityFn, +): T +export function replaceEqualDeep( + a: any, + b: any, + equalityFn: EqualityFn = defaultEqualityFn, +): any { + return replaceEqualDeepInternal(a, b, equalityFn, 0) +} + +/** + * Reuses deeply equal values while limiting recursion to 500 levels. + * @param a - The previous value. + * @param b - The new value. + * @param equalityFn - Compares values for structural sharing. + * @param depth - The current recursion depth. + * @returns The new value with deeply equal parts of the previous value reused. + */ +function replaceEqualDeepInternal( + a: any, + b: any, + equalityFn: EqualityFn, + depth: number, +): any { + if (equalityFn(a, b)) { + return a + } + + if (depth > 500) return b + + const array = isPlainArray(a) && isPlainArray(b) + + if (!array && !(isPlainObject(a) && isPlainObject(b))) return b + + const aItems = array ? a : Object.keys(a) + const aSize = aItems.length + const bItems = array ? b : Object.keys(b) + const bSize = bItems.length + const copy: any = array ? new Array(bSize) : {} + + let equalItems = 0 + + for (let i = 0; i < bSize; i++) { + const key: any = array ? i : bItems[i] + const aItem = a[key] + const bItem = b[key] + + if (equalityFn(aItem, bItem)) { + copy[key] = aItem + if (array ? i < aSize : Object.hasOwn(a, key)) equalItems++ + continue + } + + if ( + aItem === null || + bItem === null || + typeof aItem !== 'object' || + typeof bItem !== 'object' + ) { + copy[key] = bItem + continue + } + + const v = replaceEqualDeepInternal(aItem, bItem, equalityFn, depth + 1) + copy[key] = v + if (v === aItem) equalItems++ + } + + return aSize === bSize && equalItems === aSize ? a : copy +} + +/** + * Shallow compare objects. + * @param a - The first object. + * @param b - The second object, or `undefined`. + * @returns `true` if both objects have the same keys, with strictly equal values for each key. + */ +export function shallowEqualObjects>( + a: T, + b: T | undefined, +): boolean { + if (!b || Object.keys(a).length !== Object.keys(b).length) { + return false + } + + for (const key of Object.keys(a)) { + if (!Object.hasOwn(b, key) || a[key] !== b[key]) { + return false + } + } + + return true +} + +/** + * Checks whether a value is an array with no holes and no extra properties. + * @param value - The value to check. + * @returns `true` if `value` is an array whose number of own keys equals its `length`. + */ +export function isPlainArray(value: unknown): value is Array { + return Array.isArray(value) && value.length === Object.keys(value).length +} + +// Copied from: https://github.com/jonschlinkert/is-plain-object +/** + * Checks whether a value is a plain object, e.g. created with an object literal or + * `Object.create(null)`. + * @param o - The value to check. + * @returns `true` if `o` is a plain object. + */ +export function isPlainObject(o: any): o is Record { + if (!hasObjectPrototype(o)) { + return false + } + + // If has no constructor + const objectPrototype = Object.getPrototypeOf(o) + const ctor = objectPrototype?.constructor + if (ctor === undefined) { + return true + } + + if (typeof ctor !== 'function') { + return false + } + + // If has modified prototype + const prot = ctor.prototype + if (!hasObjectPrototype(prot)) { + return false + } + + // If constructor does not have an Object-specific method + if (!prot.hasOwnProperty('isPrototypeOf')) { + return false + } + + // Handles Objects created by Object.create() + if (objectPrototype !== Object.prototype) { + return false + } + + // Most likely a plain Object + return true +} + +/** + * Checks whether a value's `Object.prototype.toString` tag is `[object Object]`. + * @param o - The value to check. + * @returns `true` if the tag is `[object Object]`. + */ +function hasObjectPrototype(o: any): boolean { + return Object.prototype.toString.call(o) === '[object Object]' +} + +/** + * Waits for the given time, using the configured {@link timeoutManager}. + * @param timeout - The time to wait, in milliseconds. + * @returns A promise that resolves after `timeout` milliseconds. + */ +export function sleep(timeout: number): Promise { + return new Promise((resolve) => { + timeoutManager.setTimeout(resolve, timeout) + }) +} + +/** + * Applies a query's `structuralSharing` option when writing new data. + * @param prevData - The previously cached data. + * @param data - The new data. + * @param options - The query options, whose `structuralSharing` decides how the data is merged. + * @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts + * replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`. + * @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable. + * Outside production, it is also logged to the console. + */ +export function replaceData< + TData, + TOptions extends Pick, +>(prevData: TData | undefined, data: TData, options: TOptions): TData { + if (typeof options.structuralSharing === 'function') { + return options.structuralSharing(prevData, data) as TData + } else if (options.structuralSharing !== false) { + if (process.env.NODE_ENV !== 'production') { + try { + return replaceEqualDeep(prevData, data) + } catch (error) { + console.error( + `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`, + ) + + // Prevent the replaceEqualDeep from being called again down below. + throw error + } + } + // Structurally share data between prev and new data if needed + return replaceEqualDeep(prevData, data) + } + return data +} + +/** + * Intended to be passed as a query's `placeholderData` option, for example + * `placeholderData: placeholderData(keepPreviousData)`. Instead of resetting the query's data to `undefined` while a new + * query key is fetching, it keeps displaying the previously fetched data until the new data arrives. + * @param previousData - The data of the previous query key, passed by the observer. + * @returns The previous data, unchanged. + * @example + * ```ts + * new QueryObserver(queryClient, { + * queryKey: ['posts', page], + * queryFn: () => fetchPosts(page), + * placeholderData: placeholderData(keepPreviousData), + * }) + * ``` + */ +export function keepPreviousData( + previousData: T | undefined, +): T | undefined { + return previousData +} + +/** + * Adds an item to one end of a new array. If the result exceeds `max`, removes + * excess items from the opposite end. + * @param items - The current items. + * @param item - The value to add. + * @param max - The maximum number of items to keep. Omit it or use `0` for no limit. + * @param prepend - Pass `true` to add at the start. The default is to add at the end. + * @returns A new array with `item` added. + */ +export function addToArray( + items: Array, + item: T, + max?: number, + prepend?: boolean, +): Array { + const newItems = prepend ? [item, ...items] : [...items, item] + if (max && newItems.length > max) { + return prepend ? newItems.slice(0, max) : newItems.slice(-max) + } + return newItems +} + +/** + * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent + * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`, + * a query disabled via `skipToken` cannot be triggered with `refetch`. + * @example + * ```ts + * new QueryObserver(queryClient, { + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * ``` + */ +export const skipToken = Symbol() +/** + * The type of the {@link skipToken} sentinel value. + */ +export type SkipToken = typeof skipToken + +/** + * Pass this as `queryFn` to use the query function configured on the client. + * The defaults for the query key take precedence over the client's global query defaults. + * If no query function is configured, a fetch fails with a `Missing queryFn` error. + */ +export const defaultQueryFn = Symbol() + +/** The type of the {@link defaultQueryFn} sentinel value. */ +export type DefaultQueryFn = typeof defaultQueryFn + +/** + * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from + * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn`, the returned + * function rejects with a `Missing queryFn` error. + * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages. + * @param fetchOptions - The fetch options, which may carry an `initialPromise`. + * @returns The function to call for the fetch. + */ +export function ensureQueryFn< + TQueryFnData = unknown, + TQueryKey extends QueryKey = QueryKey, +>( + options: { + queryFn?: + | QueryFunction + | SkipToken + | DefaultQueryFn + queryHash?: string + }, + fetchOptions?: FetchOptions, +): QueryFunction { + if (process.env.NODE_ENV !== 'production') { + if (options.queryFn === skipToken) { + console.error( + `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`, + ) + } + } + + // if we attempt to retry a fetch that was triggered from an initialPromise + // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise + // if an observer has already mounted, we will be able to retry with that queryFn + if (!options.queryFn && fetchOptions?.initialPromise) { + return () => fetchOptions.initialPromise! + } + + if ( + !options.queryFn || + options.queryFn === skipToken || + options.queryFn === defaultQueryFn + ) { + return () => + Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`)) + } + + return options.queryFn +} + +/** + * Resolves a `throwOnError` option to a boolean. + * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller, + * additional context such as the query or mutation) and its result is returned, allowing the throwing + * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined` + * resolves to `false`). + * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or + * `undefined`. + * @param params - The arguments passed to `throwOnError` if it is a function. + * @returns Whether the error should be thrown. + * @example + * ```ts + * const throwOnError = + * query.state.error && typeof options.throwOnError === 'function' + * ? shouldThrowError(options.throwOnError, [query.state.error, query]) + * : options.throwOnError + * ``` + */ +export function shouldThrowError) => boolean>( + throwOnError: boolean | T | undefined, + params: Parameters, +): boolean { + // Allow throwOnError function to override throwing behavior on a per-error basis + if (typeof throwOnError === 'function') { + return throwOnError(...params) + } + + return !!throwOnError +} + +export const fetchSignal = Symbol() + +/** Internal view of a context that can expose its signal without consuming it. */ +export type FetchSignalContext = { + /** The public signal, whose getter can mark it consumed. */ + readonly signal: AbortSignal + /** The original fetch signal, absent on application-created contexts. */ + readonly [fetchSignal]?: AbortSignal +} + +/** + * Adds a lazy `signal` getter to an object, such as a query function context. The first time + * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right + * away if it is already aborted), so cancellation is only tracked when the signal is actually used. + * @param object - The object to add the `signal` property to. + * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read. + * @param onCancelled - Called when the signal is aborted, if `signal` was read. + * @param internalSignal - The fetch signal to forward without consuming the getter. + * @returns The same object, with the `signal` property added. + */ +export function addConsumeAwareSignal( + object: T, + getSignal: () => AbortSignal, + onCancelled: () => void, + internalSignal?: AbortSignal, +): T & { signal: AbortSignal } { + let consumed = false + let signal: AbortSignal | undefined + + Object.defineProperties(object, { + [fetchSignal]: { value: internalSignal }, + signal: { + enumerable: true, + get: () => { + signal ??= getSignal() + if (consumed) { + return signal + } + + consumed = true + if (signal.aborted) { + onCancelled() + } else { + signal.addEventListener('abort', onCancelled, { once: true }) + } + + return signal + }, + }, + }) + + return object as T & { signal: AbortSignal } +} diff --git a/packages/query-core-pluggable/tests/compat/query-core.patch b/packages/query-core-pluggable/tests/compat/query-core.patch new file mode 100644 index 00000000000..0406eb8f1c7 --- /dev/null +++ b/packages/query-core-pluggable/tests/compat/query-core.patch @@ -0,0 +1,354 @@ +diff --git a/src/__tests__/infiniteQueryBehavior.test.tsx b/src/__tests__/infiniteQueryBehavior.test.tsx +--- a/src/__tests__/infiniteQueryBehavior.test.tsx ++++ b/src/__tests__/infiniteQueryBehavior.test.tsx +@@ -7,5 +7,5 @@ + defaultQueryFn, + } from '..' +-import { infiniteQueryBehavior } from '../infiniteQueryBehavior' ++import { prepareInfiniteFetch } from '../infiniteQueryBehavior' + import type { + InfiniteData, +@@ -352,5 +352,4 @@ + }) + +- const behavior = infiniteQueryBehavior() + const context = { + client: queryClient, +@@ -373,7 +372,10 @@ + } + +- behavior.onFetch(context as any, {} as any) +- +- await expect(context.fetchFn()).rejects.toBe(abortController.signal.reason) ++ const fetchPages = prepareInfiniteFetch( ++ context as any, ++ {} as any, ++ ) ++ ++ await expect(fetchPages()).rejects.toBe(abortController.signal.reason) + expect(queryFn).toHaveBeenCalledTimes(1) + }) +diff --git a/src/__tests__/infiniteQueryObserver.test-d.tsx b/src/__tests__/infiniteQueryObserver.test-d.tsx +--- a/src/__tests__/infiniteQueryObserver.test-d.tsx ++++ b/src/__tests__/infiniteQueryObserver.test-d.tsx +@@ -1,3 +1,4 @@ + import { createKey } from '@tanstack/query-test-utils' ++import { projectionInput } from '#compat/projection' + import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest' + import { InfiniteQueryObserver, QueryClient } from '..' +@@ -392,8 +393,5 @@ + | 'hasNextPage' + | 'hasPreviousPage' +- | 'isFetchNextPageError' +- | 'isFetchPreviousPageError' +- | 'isFetchingNextPage' +- | 'isFetchingPreviousPage' ++ | 'fetchDirection' + >() + }) +@@ -712,6 +710,6 @@ + expectTypeOf(result.isLoadingError).toEqualTypeOf() + expectTypeOf(result.isRefetchError).toEqualTypeOf() +- expectTypeOf(result.isFetchNextPageError).toEqualTypeOf() +- expectTypeOf(result.isFetchPreviousPageError).toEqualTypeOf() ++ expectTypeOf(result.isFetchNextPageError).toEqualTypeOf() ++ expectTypeOf(result.isFetchPreviousPageError).toEqualTypeOf() + expectTypeOf(result.isSuccess).toEqualTypeOf() + expectTypeOf(result.status).toEqualTypeOf<'error'>() +@@ -737,5 +735,5 @@ + }) + +- it('should leave the page error flags unpinned', () => { ++ it('should expose the page error types during a full refetch', () => { + type RefetchError = Extract< + InfiniteQueryObserverResult>, +@@ -745,8 +743,8 @@ + expectTypeOf< + RefetchError['isFetchNextPageError'] +- >().toEqualTypeOf() ++ >().toEqualTypeOf() + expectTypeOf< + RefetchError['isFetchPreviousPageError'] +- >().toEqualTypeOf() ++ >().toEqualTypeOf() + }) + +@@ -1005,5 +1003,5 @@ + }) + +- expectTypeOf(observer.options.select).toEqualTypeOf< ++ expectTypeOf(projectionInput(observer.options.select)).toEqualTypeOf< + | (( + data: InfiniteData<{ value: string }, number>, +diff --git a/src/__tests__/mutation.test-d.tsx b/src/__tests__/mutation.test-d.tsx +--- a/src/__tests__/mutation.test-d.tsx ++++ b/src/__tests__/mutation.test-d.tsx +@@ -2,4 +2,5 @@ + import { Mutation } from '../mutation' + import { QueryClient } from '../queryClient' ++import type { serialScope } from '#compat/scope' + import type { Action, MutationState } from '../mutation' + import type { MutationObserver } from '../mutationObserver' +@@ -491,5 +492,5 @@ + it('should be an optional scope carrying a string id', () => { + expectTypeOf().toEqualTypeOf< +- { id: string } | undefined ++ ReturnType | undefined + >() + }) +diff --git a/src/__tests__/notifyManager.test-d.tsx b/src/__tests__/notifyManager.test-d.tsx +--- a/src/__tests__/notifyManager.test-d.tsx ++++ b/src/__tests__/notifyManager.test-d.tsx +@@ -27,5 +27,4 @@ + | 'schedule' + | 'setNotifyFunction' +- | 'setBatchNotifyFunction' + | 'setScheduler' + >() +@@ -162,22 +161,4 @@ + }) + +- describe('setBatchNotifyFunction', () => { +- it('should only accept a function taking a callback', () => { +- const localNotifyManager = createNotifyManager() +- +- expectTypeOf( +- localNotifyManager.setBatchNotifyFunction, +- ).parameters.toEqualTypeOf<[fn: (callback: () => void) => void]>() +- }) +- +- it('should return void', () => { +- const localNotifyManager = createNotifyManager() +- +- expectTypeOf( +- localNotifyManager.setBatchNotifyFunction, +- ).returns.toEqualTypeOf() +- }) +- }) +- + describe('setScheduler', () => { + it('should only accept a function taking a callback', () => { +diff --git a/src/__tests__/notifyManager.test.tsx b/src/__tests__/notifyManager.test.tsx +--- a/src/__tests__/notifyManager.test.tsx ++++ b/src/__tests__/notifyManager.test.tsx +@@ -77,23 +77,4 @@ + }) + +- it('should use custom batch notify function', async () => { +- const notifyManagerTest = createNotifyManager() +- const batchNotifySpy = vi.fn<(callback: () => void) => void>((cb) => cb()) +- const callbackSpy1 = vi.fn<() => void>() +- const callbackSpy2 = vi.fn<() => void>() +- +- notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) +- +- notifyManagerTest.batch(() => { +- notifyManagerTest.schedule(callbackSpy1) +- notifyManagerTest.schedule(callbackSpy2) +- }) +- +- await vi.advanceTimersByTimeAsync(0) +- expect(batchNotifySpy).toHaveBeenCalledWith(expect.any(Function)) +- expect(callbackSpy1).toHaveBeenCalledWith() +- expect(callbackSpy2).toHaveBeenCalledWith() +- }) +- + it('should batch calls correctly', async () => { + const notifyManagerTest = createNotifyManager() +diff --git a/src/__tests__/queriesObserver.test-d.tsx b/src/__tests__/queriesObserver.test-d.tsx +--- a/src/__tests__/queriesObserver.test-d.tsx ++++ b/src/__tests__/queriesObserver.test-d.tsx +@@ -2,5 +2,5 @@ + import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest' + import { QueriesObserver, QueryClient, defaultQueryFn } from '..' +-import type { Query, QueryObserver, QueryObserverResult } from '..' ++import type { QueryObserver, QueryObserverResult } from '..' + import type { QueriesObserverOptions } from '../queriesObserver' + import type { ObserverOptionsInput } from '../queryObserver' +@@ -26,5 +26,4 @@ + | 'setQueries' + | 'getCurrentResult' +- | 'getQueries' + | 'getObservers' + | 'createResultReader' +@@ -186,12 +185,4 @@ + }) + +- describe('getQueries', () => { +- it('should return the observed queries', () => { +- const observer = new QueriesObserver(queryClient, []) +- +- expectTypeOf(observer.getQueries()).toEqualTypeOf>() +- }) +- }) +- + describe('getObservers', () => { + it('should return the underlying observers', () => { +diff --git a/src/__tests__/queriesObserver.test.tsx b/src/__tests__/queriesObserver.test.tsx +--- a/src/__tests__/queriesObserver.test.tsx ++++ b/src/__tests__/queriesObserver.test.tsx +@@ -85,5 +85,7 @@ + readerB.commit() + expect(listener).toHaveBeenCalledTimes(1) +- expect(observer.getQueries()[0]!.queryKey).toStrictEqual(keyB) ++ expect( ++ observer.getObservers()[0]!.getCurrentQuery().queryKey, ++ ).toStrictEqual(keyB) + listener.mockClear() + queryClient.setQueryData(keyA, 3) +@@ -145,5 +147,7 @@ + expect(observer.getCurrentResult()[0]!.data).toBe(snapshot[0]!.data) + expect( +- observer.getQueries().map((query) => query.queryKey), ++ observer ++ .getObservers() ++ .map((entry) => entry.getCurrentQuery().queryKey), + ).toStrictEqual([keyB, keyA]) + unsubscribe() +@@ -299,25 +303,4 @@ + }) + +- it('should return current queries via getQueries', async () => { +- const key1 = createKey() +- const key2 = createKey() +- const queryFn1 = vi.fn<() => number>().mockReturnValue(1) +- const queryFn2 = vi.fn<() => number>().mockReturnValue(2) +- const observer = new QueriesObserver(queryClient, [ +- { queryKey: key1, queryFn: queryFn1 }, +- { queryKey: key2, queryFn: queryFn2 }, +- ]) +- const unsubscribe = observer.subscribe(() => undefined) +- await vi.advanceTimersByTimeAsync(0) +- +- const queries = observer.getQueries() +- +- expect(queries).toHaveLength(2) +- expect(queries[0]?.queryKey).toStrictEqual(key1) +- expect(queries[1]?.queryKey).toStrictEqual(key2) +- +- unsubscribe() +- }) +- + it('should update when a query updates', async () => { + const key1 = createKey() +diff --git a/src/__tests__/queryClient.test.tsx b/src/__tests__/queryClient.test.tsx +--- a/src/__tests__/queryClient.test.tsx ++++ b/src/__tests__/queryClient.test.tsx +@@ -378,5 +378,5 @@ + : newData + }, +- } as QueryObserverOptions ++ } as Pick + + queryClient.setDefaultOptions({ queries: queryObserverOptions }) +diff --git a/src/__tests__/queryObserver.test-d.tsx b/src/__tests__/queryObserver.test-d.tsx +--- a/src/__tests__/queryObserver.test-d.tsx ++++ b/src/__tests__/queryObserver.test-d.tsx +@@ -1,3 +1,4 @@ + import { createKey } from '@tanstack/query-test-utils' ++import { projectionInput } from '#compat/projection' + import { + afterEach, +@@ -9,4 +10,7 @@ + } from 'vitest' + import { QueryClient, QueryObserver, defaultQueryFn } from '..' ++import type { QueryBoundaryTuple } from '#compat/descriptors' ++import type { IntervalInput } from '#compat/polling' ++import type { ProjectionInput } from '#compat/projection' + import type { + DefaultError, +@@ -70,5 +74,5 @@ + it('should derive its remaining type parameters from the data type', () => { + expectTypeOf< +- QueryObserverOptions<{ value: string }>['select'] ++ ProjectionInput['select']> + >().toEqualTypeOf< + ((data: { value: string }) => { value: string }) | undefined +@@ -207,5 +211,5 @@ + expectTypeOf< + Extract< +- QueryObserverOptions['refetchInterval'], ++ IntervalInput, + (...args: Array) => any + > +@@ -213,5 +217,5 @@ + expectTypeOf< + Exclude< +- QueryObserverOptions['refetchInterval'], ++ IntervalInput, + (...args: Array) => any + > +@@ -380,5 +384,5 @@ + (...args: Array) => any + > +- >().toEqualTypeOf() ++ >().toEqualTypeOf() + }) + }) +@@ -531,10 +535,12 @@ + + expectTypeOf< +- QueryObserverOptions< +- { count: number }, +- DefaultError, +- number, +- { count: number } +- >['placeholderData'] ++ ProjectionInput< ++ QueryObserverOptions< ++ { count: number }, ++ DefaultError, ++ number, ++ { count: number } ++ >['placeholderData'] ++ > + >() + .extract<(...args: Array) => any>() +@@ -586,5 +592,7 @@ + expectTypeOf< + Exclude< +- QueryObserverOptions<{ value: string }>['placeholderData'], ++ ProjectionInput< ++ QueryObserverOptions<{ value: string }>['placeholderData'] ++ >, + (...args: Array) => any + > +@@ -1474,5 +1482,5 @@ + .parameter(0) + .toEqualTypeOf() +- expectTypeOf(observer.options.select).toEqualTypeOf< ++ expectTypeOf(projectionInput(observer.options.select)).toEqualTypeOf< + ((data: { value: string }) => { value: string }) | undefined + >() +@@ -1767,10 +1775,11 @@ + >() + +- expectTypeOf(observer.fetchOptimistic) +- .parameter(0) +- .toHaveProperty('select') +- .toEqualTypeOf< +- ((data: { value: string }) => { value: string }) | undefined +- >() ++ expectTypeOf< ++ ProjectionInput< ++ Parameters[0]['select'] ++ > ++ >().toEqualTypeOf< ++ ((data: { value: string }) => { value: string }) | undefined ++ >() + }) + }) +diff --git a/src/__tests__/utils.test-d.tsx b/src/__tests__/utils.test-d.tsx +--- a/src/__tests__/utils.test-d.tsx ++++ b/src/__tests__/utils.test-d.tsx +@@ -126,8 +126,9 @@ + const queryKey: Key = ['foo', 'bar'] as any as Key + +- expectTypeOf(new QueryClient().invalidateQueries).toBeCallableWith({ ++ const result = new QueryClient().invalidateQueries({ + queryKey, + }) ++ expectTypeOf(result).toEqualTypeOf>() + }) + + it('should error on invalid query keys', () => { diff --git a/packages/query-core-pluggable/tsconfig.json b/packages/query-core-pluggable/tsconfig.json new file mode 100644 index 00000000000..0cc454b2a77 --- /dev/null +++ b/packages/query-core-pluggable/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "./dist-ts", + "rootDir": "." + }, + "include": ["src", "*.config.ts", "*.config.js", "package.json"] +} diff --git a/packages/query-core-pluggable/tsconfig.legacy.json b/packages/query-core-pluggable/tsconfig.legacy.json new file mode 100644 index 00000000000..84ebe1a984b --- /dev/null +++ b/packages/query-core-pluggable/tsconfig.legacy.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "./dist-ts/legacy" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/query-core-pluggable/tsconfig.prod.json b/packages/query-core-pluggable/tsconfig.prod.json new file mode 100644 index 00000000000..2bb29fdf02a --- /dev/null +++ b/packages/query-core-pluggable/tsconfig.prod.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "incremental": false, + "composite": false, + "rootDir": "../../" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/query-core-pluggable/tsdown.config.ts b/packages/query-core-pluggable/tsdown.config.ts new file mode 100644 index 00000000000..5814c5185dd --- /dev/null +++ b/packages/query-core-pluggable/tsdown.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'tsdown' +import { getTsdownConfig } from './root.tsdown.config.js' + +export default defineConfig({ + ...getTsdownConfig({ entry: ['src/index.ts'] }), + unbundle: true, +}) diff --git a/packages/query-core-pluggable/vite.config.ts b/packages/query-core-pluggable/vite.config.ts new file mode 100644 index 00000000000..dddd40d2fbb --- /dev/null +++ b/packages/query-core-pluggable/vite.config.ts @@ -0,0 +1,30 @@ +import { defineConfig } from 'vitest/config' +import packageJson from './package.json' + +export default defineConfig({ + // fix from https://github.com/vitest-dev/vitest/issues/6992#issuecomment-2509408660 + resolve: { + conditions: ['@tanstack/custom-condition'], + }, + environments: { + ssr: { + resolve: { + conditions: ['@tanstack/custom-condition'], + }, + }, + }, + test: { + name: packageJson.name, + dir: './src', + watch: false, + environment: 'jsdom', + coverage: { + enabled: !!process.env.CI, + provider: 'istanbul', + include: ['src/**/*'], + exclude: ['src/__tests__/**'], + }, + typecheck: { enabled: true }, + restoreMocks: true, + }, +}) diff --git a/packages/react-query-pluggable/README.md b/packages/react-query-pluggable/README.md new file mode 100644 index 00000000000..03e9b8c81a2 --- /dev/null +++ b/packages/react-query-pluggable/README.md @@ -0,0 +1,297 @@ +# @tanstack/react-query-pluggable + +An experimental ESM React Query adapter for React 19. A `QueryClient` holds cache state and configuration. Import client operations and optional query features where you use them. + +The React adapter depends on `@tanstack/query-core-pluggable`, which owns the cache, observers, client operations and optional features. The React entry re-exports that core. Direct core callers and React components can use the same pluggable client, cache and managers. + +```tsx +import { + QueryClient, + QueryClientProvider, + refetchInterval, + queryOptions, + useQuery, +} from '@tanstack/react-query-pluggable' + +const client = new QueryClient() + +function Orders() { + const { data } = useQuery( + queryOptions({ + queryKey: ['orders'], + queryFn: fetchOrders, + refetchInterval: refetchInterval(3000), + }), + ) + return

    {data?.length} orders

    +} + +export function App() { + return ( + + + + ) +} +``` + +All four single-query option factories accept the same interval helper. Query defaults also accept it. Pass a callback to compute the next interval from the cached query. Return `false` or `undefined` to stop polling. + +```ts +useQuery( + queryOptions({ + queryKey: ['job', jobId], + queryFn: () => fetchJob(jobId), + refetchInterval: (query) => + query.state.data?.status === 'complete' ? false : refetchInterval(3000), + }), +) +``` + +Polling runs while an enabled observer has subscribers and the window is focused. Set `refetchIntervalInBackground: true` to keep polling in the background. Each observer manages its own timer, including when several observers share a client default. + +## Choosing how a query renders + +Choose an option factory for the data you read and the loading behavior you want. Pass its result to `useQuery`. Each factory attaches the observer and tags the key with the cached data and error types. Ordinary and Suspense readers can use the same client and cache key. + +You can spread a descriptor to override options at a hook call. In a library that emits TypeScript declarations, export the factory call, or annotate an exported copy with `typeof originalDescriptor`. That gives the declaration emitter a name for its tagged key and observer type. + +| Reader | Ordinary query | Paginated query | +| --------------------------------------------- | ----------------------------------------- | ------------------------------------------------- | +| Component handles pending state | `useQuery(queryOptions(options))` | `useQuery(infiniteQueryOptions(options))` | +| React Suspense boundary handles pending state | `useQuery(suspenseQueryOptions(options))` | `useQuery(suspenseInfiniteQueryOptions(options))` | + +```tsx +import { + isPending, + queryOptions, + suspenseQueryOptions, + useQuery, +} from '@tanstack/react-query-pluggable' + +const postQueryOptions = (id: number) => + queryOptions({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + }) + +const postSuspenseQueryOptions = (id: number) => + suspenseQueryOptions({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + }) + +function PostPreview({ id }: { id: number }) { + const post = useQuery(postQueryOptions(id)) + return

    {isPending(post) ? 'Loading…' : post.data?.title}

    +} + +// Render inside Loading…

    }>. +function PostTitle({ id }: { id: number }) { + const post = useQuery(postSuspenseQueryOptions(id)) + return

    {post.data.title}

    +} +``` + +The Suspense policy sends a failed query without cached data to the nearest error boundary. +Suspense factories own `enabled` and `throwOnError`. Pass `skipToken` as the fetcher for a conditional Suspense query. A skipped query renders with cached data or `undefined`. + +Ordinary single and paginated queries return failures in `result.error` by default. To send a failure to a React error boundary, import `throwOnError` and pass it in the descriptor or the client's query defaults. Use `[throwOnError, true]` for every error, or put a predicate in the second slot. For example, this reader keeps displaying a cached post when a background refresh fails. + +```ts +import { queryOptions, throwOnError } from '@tanstack/react-query-pluggable' + +const postQueryOptions = (id: number) => + queryOptions({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + throwOnError: [ + throwOnError, + (_error, query) => query.state.data === undefined, + ], + }) +``` + +Set `throwOnError: false` on a query to override a client or key default. Use `QueryErrorResetBoundary` to allow a failed boundary reader to retry. An ordinary reader that handles errors inline leaves a pending boundary reset available for its siblings. + +### Reading query state + +Read `status` (`pending`, `error`, or `success`) and `fetchStatus` (`idle`, `fetching`, or `paused`) directly, or import the predicates your component uses. The predicates work on single, infinite, and parallel query results. TypeScript narrows the result along with its `data` and `error`. For example, a failed background refetch can retain data. A loading error has no data. + +```tsx +import { + isLoadingError, + isPending, + queryOptions, + useQuery, +} from '@tanstack/react-query-pluggable' + +const articleQueryOptions = (id: number) => + queryOptions({ + queryKey: ['article', id], + queryFn: () => fetchArticle(id), + }) + +function Article({ id }: { id: number }) { + const article = useQuery(articleQueryOptions(id)) + if (isPending(article)) return

    Loading…

    + if (isLoadingError(article)) return

    {article.error.message}

    + return

    {article.data.title}

    +} +``` + +| Result question | Named predicates | +| --------------------------- | -------------------------------------------------------------------------------------------------- | +| Query status | `isPending`, `isError`, `isSuccess` | +| Fetch status and history | `isFetching`, `isPaused`, `isLoading`, `isRefetching`, `isFetched` | +| Initial or background error | `isLoadingError`, `isRefetchError` | +| Page request direction | `isFetchingNextPage`, `isFetchingPreviousPage`, `isFetchNextPageError`, `isFetchPreviousPageError` | + +Predicates read through the tracked result. For example, `isFetching(result)` subscribes a component to `fetchStatus`. If a component supplies `notifyOnChangeProps`, list the source fields there. A change to a source field can trigger a render even when the predicate still returns the same boolean. + +`isFetchedAfterMount`, `isPlaceholderData`, `isStale`, and `isEnabled` describe the observer and remain result properties. Mutation results retain their existing status flags. To count fetching queries across a client, call `countFetchingQueries(client, filters)` or subscribe with `useIsFetching(filters)`. + +In a component, `isFetched(result)` reads the data and error update counts from the hook's tracked result. In cache management code, `isQueryFetched(entry)` reads those counts directly from a `Query` returned by `findCachedQuery`. + +### Paginated queries with the same hook + +Choose `infiniteQueryOptions` to handle a pending first page in the component, or `suspenseInfiniteQueryOptions` to show the nearest React fallback. Both forms expose `fetchNextPage`, +`hasNextPage`, and the cached `pages` and `pageParams`. + +```tsx +import { + suspenseInfiniteQueryOptions, + useQuery, +} from '@tanstack/react-query-pluggable' + +const postPages = suspenseInfiniteQueryOptions({ + queryKey: ['posts', 'pages'], + initialPageParam: 0, + queryFn: ({ pageParam }) => fetchPostPage(pageParam), + getNextPageParam: (lastPage) => lastPage.nextCursor, +}) + +function Posts() { + const result = useQuery(postPages) + return ( + <> + {result.data.pages.map((page) => ( + + ))} + + + ) +} +``` + +For component-managed loading, prepare the same options with `infiniteQueryOptions`. Outside React, import +`infiniteQuery` to fetch and cache pages by calling `infiniteQuery(client, postPages)`. + +### Parallel queries + +`useQueries` accepts a dynamic list of regular query options. `useSuspenseQueries` applies its boundary to the entire group and starts the missing requests together. This example renders once both values are available. Each result’s type is inferred independently inside `combine`. + +```tsx +import { + queryOptions, + useSuspenseQueries, +} from '@tanstack/react-query-pluggable' + +function Dashboard() { + const summary = useSuspenseQueries({ + queries: [ + queryOptions({ queryKey: ['profile'], queryFn: fetchProfile }), + queryOptions({ queryKey: ['orders'], queryFn: fetchOrders }), + ], + combine: ([profile, orders]) => + `${profile.data.name} has ${orders.data.length} orders`, + }) + return

    {summary}

    +} +``` + +Use `useQueries` when the number of keys changes between renders or individual entries can be disabled or skipped. Here the dashboard subscribes to a different set of books whenever the user changes their selection. + +```tsx +import { useQueries } from '@tanstack/react-query-pluggable' + +function BookList({ ids }: { ids: number[] }) { + const books = useQueries({ + queries: ids.map((id) => ({ + queryKey: ['book', id], + queryFn: () => fetchBook(id), + })), + }) + return ( +
      + {books.map((book, index) => ( +
    • {book.data?.title ?? book.status}
    • + ))} +
    + ) +} +``` + +Filter conditional entries before passing a list to `useSuspenseQueries`. + +## Selecting and keeping data + +`select` maps the cached value for one observer. `placeholderData` supplies a temporary value for a pending query. Wrap a typed selector in `select(getTitle)`, or use the tuple form to infer an inline callback's argument from the query. For example, this hook keeps displaying the previous post title while the next post loads. + +```tsx +import { + keepPreviousData, + placeholderData, + queryOptions, + select, + useQuery, +} from '@tanstack/react-query-pluggable' + +function usePostTitle(id: number) { + return useQuery( + queryOptions({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), // Promise<{ title: string }> + select: [select, (post) => post.title], + placeholderData: placeholderData(keepPreviousData), + }), + ) +} +``` + +## Client operations + +The `QueryClient` constructor creates the state shared by hooks, providers and imperative callers. All operations on that client are named functions. Pass the client first, followed by the arguments you would pass to the v6 method. + +```ts +import { + query, + infiniteQuery, + getQueryData, + invalidateQueries, + setQueryData, +} from '@tanstack/react-query-pluggable' + +const order = await query(client, orderOptions) +const cached = getQueryData(client, orderOptions.queryKey) +setQueryData(client, orderOptions.queryKey, updatedOrder) +await infiniteQuery(client, orderPageOptions) +await invalidateQueries(client, { queryKey: ['orders'] }) +``` + +For example, `client.query(options)` becomes `query(client, options)` and `client.clear()` becomes `clearQueryClient(client)`. The provider manages mounting for React users. Integrations that managed the v6 lifecycle directly can call `mountQueryClient(client)` and `unmountQueryClient(client)`. The same client-first convention applies to defaults, mutation resumption and bulk cache operations. + +Use `getQueryCache(client)` and `getMutationCache(client)` for direct cache access. Use `findCachedQuery(cache, filters)`, `findCachedQueries(cache, filters)`, or `clearQueryCache(cache)` for query cache searches and clearing. Query caches expose `.subscribe(listener)`, `.get(hash)`, and `.getAll()`. The stock `@tanstack/query-persist-client-core` subscription calls `client.getQueryCache()` and `client.getMutationCache()`. A custom persistence integration for this adapter must subscribe through the named accessors and use this adapter’s `hydrate` and `dehydrate`. + +For one cache entry, `getQueryObserverCount(entry)` counts subscribed observers, `invalidateCachedQuery(entry)` marks it invalidated, and `resetCachedQuery(entry)` cancels its fetch and restores its initial state. To apply an operation to matching keys and refetch eligible active matches by default, call `invalidateQueries(client, filters)` or `resetQueries(client, filters)`. + +## Mutations + +`useMutation`, `useMutationState`, and `useIsMutating` acquire the client's mutation cache on demand. `getMutationCache(client)` creates a default cache on first use or returns a cache supplied to the constructor. A query-only app can omit the mutation cache implementation. + +Pass `scope: serialScope('orders')` to `useMutation` to run mutations with that ID one at a time within a cache. The scope ID survives dehydration and hydration. `mutationOptions` preserves the supplied mutation options by reference. diff --git a/packages/react-query-pluggable/oxlint.config.ts b/packages/react-query-pluggable/oxlint.config.ts new file mode 100644 index 00000000000..91da02f7ef4 --- /dev/null +++ b/packages/react-query-pluggable/oxlint.config.ts @@ -0,0 +1,51 @@ +import pluginReact from '@eslint-react/eslint-plugin' +import reactHooks from 'eslint-plugin-react-hooks' +import { defineConfig } from 'oxlint' +import rootConfig from './root.oxlint.config.ts' + +export default defineConfig({ + extends: [rootConfig], + settings: rootConfig.settings, + jsPlugins: [ + // 'react-hooks' is reserved for Oxlint's native plugin, which lacks the React Compiler rules + { name: 'react-hooks-js', specifier: 'eslint-plugin-react-hooks' }, + '@eslint-react/eslint-plugin', + ], + rules: { + ...Object.fromEntries( + Object.entries(reactHooks.configs.flat.recommended.rules).map( + ([name, value]) => [ + name.replace(/^react-hooks\//, 'react-hooks-js/'), + value, + ], + ), + ), + ...pluginReact.configs.recommended.rules, + 'react-hooks-js/exhaustive-deps': 'error', + 'react-hooks-js/unsupported-syntax': 'error', + 'react-hooks-js/incompatible-library': 'error', + '@eslint-react/no-context-provider': 'off', // We need to be React 18 compatible + '@eslint-react/no-use-context': 'off', // We need to be React 18 compatible + // Covered by 'eslint-plugin-react-hooks' + '@eslint-react/error-boundaries': 'off', + '@eslint-react/exhaustive-deps': 'off', + '@eslint-react/globals': 'off', + '@eslint-react/immutability': 'off', + '@eslint-react/purity': 'off', + '@eslint-react/refs': 'off', + '@eslint-react/rules-of-hooks': 'off', + '@eslint-react/set-state-in-effect': 'off', + '@eslint-react/set-state-in-render': 'off', + '@eslint-react/static-components': 'off', + '@eslint-react/unsupported-syntax': 'off', + '@eslint-react/use-memo': 'off', + }, + overrides: [ + { + files: ['**/__tests__/**'], + rules: { + 'typescript/no-unnecessary-condition': 'off', + }, + }, + ], +}) diff --git a/packages/react-query-pluggable/package.json b/packages/react-query-pluggable/package.json new file mode 100644 index 00000000000..eeacab081d4 --- /dev/null +++ b/packages/react-query-pluggable/package.json @@ -0,0 +1,84 @@ +{ + "name": "@tanstack/react-query-pluggable", + "version": "5.108.4", + "description": "Experimental ESM React Query adapter with per-option features and tree-shakable cache operations", + "author": "tannerlinsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/TanStack/query.git", + "directory": "packages/react-query-pluggable" + }, + "homepage": "https://tanstack.com/query", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "scripts": { + "clean": "premove ./build ./coverage ./dist-ts ./.cache/test-types", + "compile": "tsc --project tsconfig.json", + "test:oxlint": "oxlint ./src ./tests", + "test:types": "npm-run-all --serial test:types:*", + "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts57 --tsBuildInfoFile .cache/test-types/ts57.tsbuildinfo", + "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts58 --tsBuildInfoFile .cache/test-types/ts58.tsbuildinfo", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts59 --tsBuildInfoFile .cache/test-types/ts59.tsbuildinfo", + "test:types:tscurrent": "tsc --project tsconfig.json --outDir .cache/test-types/tscurrent --tsBuildInfoFile .cache/test-types/tscurrent.tsbuildinfo", + "test:types:ts70": "node ../../node_modules/typescript70/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts70 --tsBuildInfoFile .cache/test-types/ts70.tsbuildinfo", + "test:types:ts71": "node ../../node_modules/typescript71/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts71 --tsBuildInfoFile .cache/test-types/ts71.tsbuildinfo", + "test:lib": "vitest run --typecheck src/__tests__ && node ../../scripts/test-react-query-compat.mjs", + "test:lib:dev": "vitest --watch src/__tests__", + "test:build": "publint --strict && attw --pack --profile esm-only", + "build": "tsdown --tsconfig tsconfig.prod.json" + }, + "type": "module", + "types": "./build/index.d.ts", + "main": "./build/index.js", + "react-native": "src/index.ts", + "exports": { + ".": { + "@tanstack/custom-condition": "./src/index.ts", + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "build", + "src", + "!src/__tests__" + ], + "dependencies": { + "@tanstack/query-core-pluggable": "workspace:*" + }, + "devDependencies": { + "@eslint-react/eslint-plugin": "catalog:", + "@testing-library/react": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "typescript": "catalog:" + }, + "peerDependencies": { + "@types/react": "^19", + "react": "^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + }, + "nx": { + "targets": { + "test:lib": { + "inputs": [ + "default", + "^production", + "reactQueryCompatibility" + ] + } + } + } +} diff --git a/packages/react-query-pluggable/root.oxlint.config.ts b/packages/react-query-pluggable/root.oxlint.config.ts new file mode 120000 index 00000000000..56565c65534 --- /dev/null +++ b/packages/react-query-pluggable/root.oxlint.config.ts @@ -0,0 +1 @@ +../../oxlint.config.ts \ No newline at end of file diff --git a/packages/react-query-pluggable/root.tsdown.config.js b/packages/react-query-pluggable/root.tsdown.config.js new file mode 120000 index 00000000000..a997d5d337c --- /dev/null +++ b/packages/react-query-pluggable/root.tsdown.config.js @@ -0,0 +1 @@ +../../scripts/getTsdownConfig.js \ No newline at end of file diff --git a/packages/react-query-pluggable/src/HydrationBoundary.tsx b/packages/react-query-pluggable/src/HydrationBoundary.tsx new file mode 100644 index 00000000000..617a84d726a --- /dev/null +++ b/packages/react-query-pluggable/src/HydrationBoundary.tsx @@ -0,0 +1,139 @@ +'use client' +import { getQueryCache, hydrateQueries } from '@tanstack/query-core-pluggable' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import type { + DehydratedState, + HydrateOptions, + OmitKeyof, + QueryClient, +} from '@tanstack/query-core-pluggable' + +/** + * The props accepted by `HydrationBoundary`. + */ +export interface HydrationBoundaryProps { + /** + * The state to hydrate. Pass the result of `dehydrate(queryClient)`. + */ + state: DehydratedState + /** + * Optional. Note: unlike `hydrate`, `mutations` cannot be set here. + */ + options?: OmitKeyof & { + defaultOptions?: OmitKeyof< + Exclude, + 'mutations' + > + } + /** + * The components to render — always rendered unconditionally, not gated on hydration. New queries are + * hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated + * data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it + * lands. + */ + children?: React.ReactNode + /** + * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. + */ + queryClient?: QueryClient +} + +/** + * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by + * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on + * update timestamp. + * + * Note: Only `queries` can be dehydrated with an `HydrationBoundary`. + * @param props - The dehydrated `state` to hydrate, the hydrate `options`, an optional custom + * `queryClient`, and the `children` to render. + * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the + * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect + * after commit. + * @example + * ```tsx + * import { HydrationBoundary } from '@tanstack/react-query-pluggable' + * + * function App() { + * return ... + * } + * ``` + * @example + * Server-side prefetch handed off to the client via `dehydrate`: + * ```tsx + * import { HydrationBoundary, dehydrate, noop, query } from '@tanstack/react-query-pluggable' + * + * async function ServerComponent() { + * const queryClient = getQueryClient() + * + * await query(queryClient, { + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * .catch(noop) + * + * return ( + * + * + * + * ) + * } + * ``` + */ +export const HydrationBoundary = ({ + children, + options = {}, + state, + queryClient, +}: HydrationBoundaryProps) => { + const client = useQueryClient(queryClient) + + const optionsRef = React.useRef(options) + React.useEffect(() => { + optionsRef.current = options + }) + + // Hydrate new queries during render so children can read their data. + // Hydrate existing queries after commit so an aborted transition cannot update them. + const hydrationQueue: DehydratedState['queries'] | undefined = + React.useMemo(() => { + const queryCache = getQueryCache(client) + + const newQueries: DehydratedState['queries'] = [] + const existingQueries: DehydratedState['queries'] = [] + for (const dehydratedQuery of state.queries) { + const existingQuery = queryCache.get(dehydratedQuery.queryHash) + + if (!existingQuery) { + newQueries.push(dehydratedQuery) + continue + } + + const hydrationIsNewer = + dehydratedQuery.state.dataUpdatedAt > + existingQuery.state.dataUpdatedAt || + (dehydratedQuery.promise && + existingQuery.state.status !== 'pending' && + existingQuery.state.fetchStatus !== 'fetching' && + dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt) + + if (hydrationIsNewer) { + existingQueries.push(dehydratedQuery) + } + } + + if (newQueries.length > 0) { + // oxlint-disable-next-line react-hooks-js/refs -- new queries are hydrated during render on purpose, and 'options' is read through a ref so that a new 'options' object does not rerun this memo + hydrateQueries(client, newQueries, optionsRef.current) + } + return existingQueries.length > 0 ? existingQueries : undefined + }, [client, state]) + + React.useEffect(() => { + if (hydrationQueue) { + hydrateQueries(client, hydrationQueue, optionsRef.current) + } + }, [client, hydrationQueue]) + + return children as React.ReactElement +} diff --git a/packages/react-query-pluggable/src/IsRestoringProvider.ts b/packages/react-query-pluggable/src/IsRestoringProvider.ts new file mode 100644 index 00000000000..abb353406a6 --- /dev/null +++ b/packages/react-query-pluggable/src/IsRestoringProvider.ts @@ -0,0 +1,18 @@ +'use client' +import * as React from 'react' + +const IsRestoringContext = React.createContext(false) + +/** + * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to + * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid + * race conditions between the restore and mounting queries. + * @returns `true` while a persisted client is being restored, `false` otherwise. + */ +export const useIsRestoring = () => React.useContext(IsRestoringContext) + +/** + * The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently + * being restored, read by `useIsRestoring`. + */ +export const IsRestoringProvider = IsRestoringContext.Provider diff --git a/packages/react-query-pluggable/src/QueryClientProvider.tsx b/packages/react-query-pluggable/src/QueryClientProvider.tsx new file mode 100644 index 00000000000..b5d08cb1241 --- /dev/null +++ b/packages/react-query-pluggable/src/QueryClientProvider.tsx @@ -0,0 +1,88 @@ +'use client' +import { + mountQueryClient, + unmountQueryClient, +} from '@tanstack/query-core-pluggable' +import * as React from 'react' +import type { QueryClient } from '@tanstack/query-core-pluggable' + +/** + * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. + */ +export const QueryClientContext = React.createContext( + undefined, +) + +/** + * The `useQueryClient` hook returns the current `QueryClient` instance. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current `QueryClient` instance. + * @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the + * component tree. + */ +export const useQueryClient = (queryClient?: QueryClient) => { + const client = React.useContext(QueryClientContext) + + if (queryClient) { + return queryClient + } + + if (!client) { + throw new Error('No QueryClient set, use QueryClientProvider to set one') + } + + return client +} + +/** + * The props accepted by `QueryClientProvider`. + */ +export type QueryClientProviderProps = { + /** + * **Required** + * + * The `QueryClient` instance to provide. + */ + client: QueryClient + /** + * The components that get access to the provided `QueryClient`. + */ + children?: React.ReactNode +} + +/** + * Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also + * calls `mountQueryClient(client)`/`unmountQueryClient(client)` as this component mounts/unmounts, which subscribes the client to + * focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or + * comes back online). + * @param props - The `client` to provide, and the `children` that get access to it. + * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`. + * @example + * ```tsx + * import { QueryClient, QueryClientProvider } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * + * function App() { + * return ... + * } + * ``` + */ +export const QueryClientProvider = ({ + client, + children, +}: QueryClientProviderProps): React.JSX.Element => { + React.useEffect(() => { + mountQueryClient(client) + return () => { + unmountQueryClient(client) + } + }, [client]) + + return ( + + {children} + + ) +} diff --git a/packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx b/packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx new file mode 100644 index 00000000000..2397b22be97 --- /dev/null +++ b/packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx @@ -0,0 +1,170 @@ +'use client' +import * as React from 'react' + +// CONTEXT + +/** + * Resets any query errors within the boundary, so queries know they can try again. + */ +export type QueryErrorResetFunction = () => void + +/** + * Returns whether the boundary has been reset and not yet cleared. + */ +export type QueryErrorIsResetFunction = () => boolean + +/** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ +export type QueryErrorClearResetFunction = () => void + +/** + * The value a `QueryErrorResetBoundary` shares through context, used to reset query errors within + * it and to check whether a reset was requested. + */ +export interface QueryErrorResetBoundaryValue { + /** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ + clearReset: QueryErrorClearResetFunction + /** + * Returns whether the boundary has been reset and not yet cleared. + */ + isReset: QueryErrorIsResetFunction + /** + * Resets any query errors within the boundary, so queries know they can try again. + */ + reset: QueryErrorResetFunction +} + +/** + * Creates the value shared through the boundary's context, which tracks whether a reset was + * requested. + * @returns The `clearReset`, `isReset`, and `reset` functions of the boundary. + */ +function createValue(): QueryErrorResetBoundaryValue { + let isReset = false + return { + /** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ + clearReset: () => { + isReset = false + }, + /** + * Resets any query errors within the boundary, so queries know they can try again. + */ + reset: () => { + isReset = true + }, + /** + * Returns whether the boundary has been reset and not yet cleared. + * @returns `true` if the boundary has been reset and not yet cleared. + */ + isReset: () => { + return isReset + }, + } +} + +/** Shares the reset state used by error-boundary readers. */ +export const QueryErrorResetBoundaryContext = React.createContext(createValue()) + +// HOOK + +/** + * This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary + * defined it will reset them globally. + * @returns The boundary's {@link QueryErrorResetBoundaryValue}. + * @example + * ```tsx + * import { ErrorBoundary } from 'react-error-boundary' + * import { useQueryErrorResetBoundary } from '@tanstack/react-query-pluggable' + * + * function App({ children }: { children: React.ReactNode }) { + * const { reset } = useQueryErrorResetBoundary() + * + * return ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * {children} + *
    + * ) + * } + * ``` + */ +export const useQueryErrorResetBoundary = () => + React.useContext(QueryErrorResetBoundaryContext) + +// COMPONENT + +/** + * A render-prop function usable as `children` on `QueryErrorResetBoundary`. + * @param value - The boundary's {@link QueryErrorResetBoundaryValue}. + * @returns The children to render. + */ +export type QueryErrorResetBoundaryFunction = ( + value: QueryErrorResetBoundaryValue, +) => React.ReactNode + +/** + * The props accepted by `QueryErrorResetBoundary`. + */ +export interface QueryErrorResetBoundaryProps { + /** + * Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and + * returns a node. + */ + children: QueryErrorResetBoundaryFunction | React.ReactNode +} + +/** + * When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to + * try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can + * reset any query errors within the boundaries of the component. + * @param props - The `children` to render. + * @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue} + * if `children` is a function. + * @example + * ```tsx + * import { ErrorBoundary } from 'react-error-boundary' + * import { QueryErrorResetBoundary } from '@tanstack/react-query-pluggable' + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * + *
    + * )} + *
    + * ) + * } + * ``` + */ +export const QueryErrorResetBoundary = ({ + children, +}: QueryErrorResetBoundaryProps) => { + const [value] = React.useState(() => createValue()) + return ( + + {typeof children === 'function' ? children(value) : children} + + ) +} diff --git a/packages/react-query-pluggable/src/__tests__/projection.test-d.ts b/packages/react-query-pluggable/src/__tests__/projection.test-d.ts new file mode 100644 index 00000000000..5f0b22dfc3c --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/projection.test-d.ts @@ -0,0 +1,81 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { + infiniteQueryOptions, + keepPreviousData, + placeholderData, + queryOptions, + select, + suspenseInfiniteQueryOptions, + suspenseQueryOptions, + useQuery, +} from '..' +import type { InfiniteData } from '..' + +describe('projection feature types', () => { + const options = { queryKey: ['orders'], queryFn: () => ({ count: 2 }) } + const count = (order: { count: number }) => order.count + + it('infers the output of a typed selector and preserves the query function data', () => { + const result = useQuery( + queryOptions({ + ...options, + placeholderData: placeholderData(keepPreviousData), + select: select(count), + }), + ) + expectTypeOf(result.data).toEqualTypeOf() + const suspense = useQuery( + suspenseQueryOptions({ + ...options, + select: [ + select, + (order) => { + expectTypeOf(order).toEqualTypeOf<{ count: number }>() + return order.count + }, + ], + }), + ) + expectTypeOf(suspense.data).toEqualTypeOf() + }) + + it('infers cached pages and the page parameter before selection', () => { + const paging = { + ...options, + initialPageParam: 0, + getNextPageParam: () => 1, + } + const regular = useQuery( + infiniteQueryOptions({ + ...paging, + select: [ + select, + (data) => { + expectTypeOf(data).toEqualTypeOf< + InfiniteData<{ count: number }, number> + >() + return data.pages.length + }, + ], + }), + ) + const suspense = useQuery( + suspenseInfiniteQueryOptions({ + ...paging, + select: [select, (data) => data.pageParams.join(',')], + }), + ) + expectTypeOf(regular.data).toEqualTypeOf() + expectTypeOf(suspense.data).toEqualTypeOf() + }) + + it('requires the feature for observer selectors and placeholders', () => { + expectTypeOf(select(count)).toEqualTypeOf< + readonly [typeof select, typeof count] + >() + // @ts-expect-error Plain selector callbacks do not install the projection feature. + useQuery(queryOptions({ ...options, select: count })) + // @ts-expect-error Plain placeholder data does not install the placeholder feature. + useQuery(queryOptions({ ...options, placeholderData: { count: 1 } })) + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/queryBuilders.test.ts b/packages/react-query-pluggable/src/__tests__/queryBuilders.test.ts new file mode 100644 index 00000000000..c6bb9678cec --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/queryBuilders.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'vitest' +import { + InfiniteQueryObserver, + QueryObserver, + infiniteQueryOptions, + queryOptions, + skipToken, + suspenseInfiniteQueryOptions, + suspenseQueryOptions, +} from '..' + +describe('query descriptors', () => { + it('selects the regular observer and scopes suspense to an individual reader', () => { + const input = Object.freeze({ queryKey: ['post'], queryFn: () => 'Dune' }) + const regular = queryOptions(input) + const [key] = Object.getOwnPropertySymbols(regular) + expect(Reflect.get(regular, key!)).toBe(QueryObserver) + expect(Reflect.get({ ...regular }, key!)).toBe(QueryObserver) + expect(regular.queryFn).toBe(input.queryFn) + expect(suspenseQueryOptions(input).renderPolicy.suspense).toBe(true) + expect( + suspenseQueryOptions({ ...input, queryFn: skipToken }).renderPolicy, + ).toBe(regular.renderPolicy) + expect(regular.renderPolicy.suspense).toBe(false) + expect(Object.getOwnPropertySymbols(input)).toHaveLength(0) + }) + + it('selects the infinite observer without changing the supplied options', () => { + const input = Object.freeze({ + queryKey: ['pages'], + initialPageParam: 0, + queryFn: ({ pageParam }: { pageParam: number }) => pageParam, + getNextPageParam: () => 1, + }) + const options = infiniteQueryOptions(input) + const [key] = Object.getOwnPropertySymbols(options) + expect(Reflect.get(options, key!)).toBe(InfiniteQueryObserver) + expect(Reflect.get(suspenseInfiniteQueryOptions(input), key!)).toBe( + InfiniteQueryObserver, + ) + expect(options.renderPolicy.suspense).toBe(false) + expect(suspenseInfiniteQueryOptions(input).renderPolicy.suspense).toBe(true) + expect(Object.getOwnPropertySymbols(input)).toHaveLength(0) + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/queryModes.test-d.ts b/packages/react-query-pluggable/src/__tests__/queryModes.test-d.ts new file mode 100644 index 00000000000..0a6490bdef3 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/queryModes.test-d.ts @@ -0,0 +1,239 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { + InfiniteQueryObserver, + QueryObserver, + dataTagSymbol, + infiniteQueryOptions, + isLoadingError, + isPending, + isSuccess, + queryOptions, + select, + skipToken, + suspenseInfiniteQueryOptions, + suspenseQueryOptions, + throwOnError, + useQuery, +} from '..' +import type { InfiniteData, PreparedQuery } from '..' + +describe('query render modes', () => { + it('infers the ordinary boundary predicate from the prepared query', () => { + const options = queryOptions({ + queryKey: ['post'] as const, + queryFn: () => ({ title: 'Dune' }), + throwOnError: [ + throwOnError, + (error, query) => { + expectTypeOf(error).toEqualTypeOf() + expectTypeOf(query.state.data).toEqualTypeOf< + { title: string } | undefined + >() + expectTypeOf(query.queryKey).toEqualTypeOf() + return query.state.data === undefined + }, + ], + }) + expectTypeOf(useQuery(options).data).toEqualTypeOf< + { title: string } | undefined + >() + // @ts-expect-error A regular reader opts in with the imported error policy. + queryOptions({ ...options, throwOnError: true }) + }) + + it('infers data for each render mode from the same query', () => { + const options = { queryKey: ['post'], queryFn: () => ({ title: 'Dune' }) } + expectTypeOf(useQuery(queryOptions(options)).data).toEqualTypeOf< + { title: string } | undefined + >() + expectTypeOf(useQuery(suspenseQueryOptions(options)).data).toEqualTypeOf<{ + title: string + }>() + // @ts-expect-error The observer must be selected by a factory. + useQuery(options) + // @ts-expect-error Inline options also require a factory. + useQuery({ queryKey: ['post'], queryFn: () => 'Dune' }) + const lookalike = { ...options, Observer: QueryObserver } + // @ts-expect-error Hand-writing the observer property does not create a descriptor. + useQuery(lookalike) + const copied = { ...queryOptions(options), staleTime: 1000 } + expectTypeOf(useQuery(copied).data).toEqualTypeOf< + { title: string } | undefined + >() + const disabled = queryOptions({ + queryKey: ['disabled'], + queryFn: () => 7, + enabled: false, + }) + expectTypeOf(useQuery(disabled).data).toEqualTypeOf() + // @ts-expect-error A prepared disabled query cannot be converted into a running Suspense reader. + suspenseQueryOptions(disabled) + const scheduled = suspenseQueryOptions(options) + expectTypeOf(scheduled.enabled).toEqualTypeOf() + const seeded = queryOptions({ + ...options, + initialData: { title: 'Seed' }, + select: [select, (post) => post.title], + }) + expectTypeOf(useQuery(seeded).data).toEqualTypeOf() + const conflicting = { ...options, throwOnError: true } + // @ts-expect-error Suspense owns throwOnError even when options come from a variable. + suspenseQueryOptions(conflicting) + const title = useQuery( + suspenseQueryOptions({ + ...options, + select: [select, (post) => post.title], + }), + ) + expectTypeOf(title.data).toEqualTypeOf() + const maybeFetch = Math.random() > 0.5 ? options.queryFn : skipToken + expectTypeOf( + useQuery(suspenseQueryOptions({ ...options, queryFn: maybeFetch })).data, + ).toEqualTypeOf<{ title: string } | undefined>() + // @ts-expect-error Suspense manages whether the query runs. + suspenseQueryOptions({ ...options, enabled: false }) + }) + + it('can read a descriptor with erased data types', () => { + function usePrepared(options: PreparedQuery) { + const result = useQuery(options) + expectTypeOf(result.data).toEqualTypeOf() + return result + } + expectTypeOf(usePrepared).toBeFunction() + }) + + it('accepts a fetcher that always rejects', () => { + const input = { + queryKey: ['broken'], + queryFn: () => Promise.reject(new Error('broken')), + } + const regular = useQuery(queryOptions(input)) + const suspended = useQuery(suspenseQueryOptions(input)) + expectTypeOf(regular.data).toEqualTypeOf() + expectTypeOf(suspended.data).toEqualTypeOf() + expectTypeOf(suspended.error).toEqualTypeOf() + }) + + it('narrows the hook result from its status and retains undefined in selected data', () => { + const result = useQuery( + queryOptions({ + queryKey: ['post'], + queryFn: () => ({ title: 'Dune' }), + }), + ) + // @ts-expect-error Query status flags are imported as predicates. + result.isPending + if (isPending(result)) { + expectTypeOf(result.data).toEqualTypeOf() + } else if (isLoadingError(result)) { + expectTypeOf(result.error).toEqualTypeOf() + } else { + expectTypeOf(result.data).toEqualTypeOf<{ title: string }>() + } + + const selected = useQuery( + queryOptions({ + queryKey: ['books'], + queryFn: (): Array => [], + select: [select, (titles) => titles.at(0)], + }), + ) + if (isSuccess(selected)) { + expectTypeOf(selected.data).toEqualTypeOf() + } + }) + + it('infers the raw page and cursor inside one suspense factory call', () => { + const lookalike = { + queryKey: ['pages'], + queryFn: () => 'page', + initialPageParam: 0, + getNextPageParam: () => 1, + Observer: InfiniteQueryObserver, + } + // @ts-expect-error A raw object cannot select an infinite observer by hand either. + useQuery(lookalike) + const descriptor = suspenseInfiniteQueryOptions({ + queryKey: ['archive'], + initialPageParam: { cursor: 0 }, + queryFn: ({ pageParam }) => { + expectTypeOf(pageParam).toEqualTypeOf<{ cursor: number }>() + return [pageParam.cursor.toString()] + }, + getNextPageParam: (_lastPage, pages) => ({ cursor: pages.length }), + select: [ + select, + (data) => { + expectTypeOf(data).toEqualTypeOf< + InfiniteData, { cursor: number }> + >() + return data.pages.flat().join(',') + }, + ], + }) + expectTypeOf(descriptor.queryKey[dataTagSymbol]).toEqualTypeOf< + InfiniteData, { cursor: number }> + >() + expectTypeOf(useQuery(descriptor).data).toEqualTypeOf() + }) + + it('preserves page data, controls and selection in both infinite modes', () => { + const options = infiniteQueryOptions({ + queryKey: ['pages'], + initialPageParam: 0, + queryFn: ({ pageParam }) => { + expectTypeOf(pageParam).toEqualTypeOf() + return String(pageParam) + }, + getNextPageParam: (_last, pages) => pages.length, + }) + // @ts-expect-error Suspense owns the error boundary policy for either kind of observer. + suspenseInfiniteQueryOptions({ ...options, throwOnError: false }) + expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf< + InfiniteData + >() + const explicit = infiniteQueryOptions< + string, + TypeError, + number, + readonly ['pages'], + number + >({ + queryKey: ['pages'], + queryFn: ({ pageParam }) => String(pageParam), + initialPageParam: 0, + getNextPageParam: () => 1, + select: [select, (data) => data.pages.length], + }) + expectTypeOf( + useQuery(suspenseInfiniteQueryOptions(explicit)).error, + ).toEqualTypeOf() + expectTypeOf(useQuery(explicit).data).toEqualTypeOf() + const skipped = suspenseInfiniteQueryOptions({ + ...options, + queryFn: Math.random() > 0.5 ? skipToken : () => 'page', + }) + expectTypeOf(skipped.enabled).toEqualTypeOf() + expectTypeOf(useQuery(skipped).data).toEqualTypeOf< + InfiniteData | undefined + >() + const regular = useQuery(options) + expectTypeOf(regular.data).toEqualTypeOf< + InfiniteData | undefined + >() + expectTypeOf(regular.hasNextPage).toEqualTypeOf() + const suspended = useQuery(suspenseInfiniteQueryOptions(options)) + expectTypeOf(suspended.data).toEqualTypeOf>() + expectTypeOf(suspended.fetchNextPage).toEqualTypeOf< + typeof regular.fetchNextPage + >() + const selected = useQuery( + suspenseInfiniteQueryOptions({ + ...options, + select: [select, (pages) => pages.pages.join(',')], + }), + ) + expectTypeOf(selected.data).toEqualTypeOf() + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/queryModes.test.tsx b/packages/react-query-pluggable/src/__tests__/queryModes.test.tsx new file mode 100644 index 00000000000..e3cc41f130a --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/queryModes.test.tsx @@ -0,0 +1,244 @@ +// @vitest-environment jsdom + +import { setQueryData } from '@tanstack/query-core-pluggable' +import { fireEvent, render, screen } from '@testing-library/react' +import * as React from 'react' +import { describe, expect, it, vi } from 'vitest' +import { + QueryClient, + QueryClientProvider, + QueryErrorResetBoundary, + QueryObserver, + infiniteQueryOptions, + queryOptions, + setQueryDefaults, + suspenseQueryOptions, + throwOnError, + useQuery, +} from '..' + +type PostErrorPolicy = readonly [typeof throwOnError, (error: Error) => boolean] +const defaults = [ + { + scope: 'client', + createClient: (policy: PostErrorPolicy) => + new QueryClient({ + defaultOptions: { queries: { throwOnError: policy } }, + }), + }, + { + scope: 'key', + createClient: (policy: PostErrorPolicy) => { + const client = new QueryClient() + setQueryDefaults(client, ['post'], { throwOnError: policy }) + return client + }, + }, +] + +describe('query render modes', () => { + it.each(defaults)( + 'switches a mounted reader from inline errors to its $scope boundary default', + async ({ createClient }) => { + const failure = new Error('Unable to load post') + const shouldThrow = vi.fn<(error: Error) => boolean>( + (error) => error === failure, + ) + const client = createClient([throwOnError, shouldThrow]) + + const post = queryOptions({ + queryKey: ['post', 1], + retry: false, + queryFn: () => Promise.reject(failure), + }) + function Post({ inline }: { inline: boolean }) { + const result = useQuery( + inline ? { ...post, throwOnError: false as const } : post, + client, + ) + return

    {result.error?.message}

    + } + + const view = render() + await view.findByText('Unable to load post') + expect(shouldThrow).not.toHaveBeenCalled() + expect(() => view.rerender()).toThrow(failure) + expect(shouldThrow).toHaveBeenCalledWith( + failure, + expect.objectContaining({ queryKey: post.queryKey }), + ) + view.unmount() + }, + ) + + it('leaves a pending boundary reset available when a sibling handles its error inline', async () => { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }) + const checkReset = vi.fn<(wasReset: boolean) => void>() + const post = queryOptions({ + queryKey: ['post'], + queryFn: () => Promise.reject(new Error('Post unavailable')), + }) + + function Post() { + return

    {useQuery(post, client).error?.message}

    + } + + function App() { + const [showPost, setShowPost] = React.useState(false) + return ( + + {({ reset, isReset }) => ( + <> + + {showPost && } + + + )} + + ) + } + + const view = render() + fireEvent.click(view.getByRole('button', { name: 'Retry' })) + await view.findByText('Post unavailable') + fireEvent.click(view.getByRole('button', { name: 'Check reset' })) + expect(checkReset).toHaveBeenCalledWith(true) + view.unmount() + }) + + it.each([ + undefined, + null, + { queryKey: ['post'], queryFn: (): string => 'Dune' }, + { + queryKey: ['post'], + queryFn: (): string => 'Dune', + Observer: QueryObserver, + }, + ])('explains the required factory for an unchecked input', (options) => { + function Page() { + // @ts-expect-error Exercise an unchecked JavaScript caller. + useQuery(options) + return null + } + expect(() => render()).toThrow( + 'Pass a descriptor from queryOptions, suspenseQueryOptions, infiniteQueryOptions, or suspenseInfiniteQueryOptions', + ) + }) + + it('uses the same cached result when a reader starts suspending', () => { + const client = new QueryClient() + const queryFn = vi.fn<() => string>(() => 'fetched post') + const options = { + queryKey: ['post'], + queryFn, + staleTime: Infinity, + } + setQueryData(client, options.queryKey, 'cached post') + + function Post({ suspend }: { suspend: boolean }) { + const result = useQuery( + suspend ? suspenseQueryOptions(options) : queryOptions(options), + ) + return

    {result.data}

    + } + + function App({ suspend }: { suspend: boolean }) { + return ( + + Loading post

    }> + +
    +
    + ) + } + + const view = render() + screen.getByText('cached post') + view.rerender() + screen.getByText('cached post') + expect(queryFn).not.toHaveBeenCalled() + view.unmount() + }) + + it('switches observers when a mounted reader receives a different client', () => { + const first = new QueryClient() + const second = new QueryClient() + const queryFn = vi.fn<() => string>(() => 'fetched') + const descriptor = queryOptions({ + queryKey: ['book'], + queryFn, + staleTime: Infinity, + }) + setQueryData(first, descriptor.queryKey, 'Dune') + setQueryData(second, descriptor.queryKey, 'Silo') + + function Reader({ client }: { client: QueryClient }) { + return

    {useQuery(descriptor, client).data}

    + } + + const view = render() + screen.getByText('Dune') + view.rerender() + screen.getByText('Silo') + expect(queryFn).not.toHaveBeenCalled() + view.unmount() + }) + + it('can switch the mounted hook to a paginated reader and back', async () => { + const client = new QueryClient() + const post = queryOptions({ + queryKey: ['post'], + queryFn: () => 'single post', + }) + const pages = infiniteQueryOptions({ + queryKey: ['pages'], + initialPageParam: 1, + queryFn: ({ pageParam }) => 'page ' + pageParam, + getNextPageParam: (_last, allPages) => allPages.length + 1, + }) + + function Reader({ paged }: { paged: boolean }) { + const result = useQuery(paged ? pages : post) + if ('fetchNextPage' in result) { + return ( + <> +

    {result.data?.pages.join(', ')}

    + + + ) + } + return

    {result.data}

    + } + + function App({ paged }: { paged: boolean }) { + return ( + + + + ) + } + + const view = render() + await screen.findByText('single post') + view.rerender() + await screen.findByText('page 1') + fireEvent.click(screen.getByRole('button', { name: 'Next page' })) + await screen.findByText('page 1, page 2') + view.rerender() + await screen.findByText('single post') + expect(screen.queryAllByRole('button')).toHaveLength(0) + view.unmount() + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/refetchInterval.test-d.ts b/packages/react-query-pluggable/src/__tests__/refetchInterval.test-d.ts new file mode 100644 index 00000000000..3a19f85deb1 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/refetchInterval.test-d.ts @@ -0,0 +1,67 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { + infiniteQueryOptions, + queryOptions, + refetchInterval, + select, + suspenseInfiniteQueryOptions, + suspenseQueryOptions, + useQuery, +} from '..' +import type { InfiniteData } from '..' + +describe('refetchInterval types', () => { + it('infers cached data in polling callbacks for regular and suspense hooks', () => { + const options = { queryKey: ['book'], queryFn: () => 'Dune' } + useQuery( + queryOptions({ + ...options, + select: [select, (book) => book.length], + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf() + return refetchInterval(query.state.data ? false : 3000) + }, + }), + ) + useQuery( + suspenseQueryOptions({ + ...options, + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf() + return undefined + }, + }), + ) + }) + + it('infers cached pages in both infinite query hooks', () => { + const options = { + queryKey: ['list'], + initialPageParam: 1, + queryFn: () => 'Dune', + getNextPageParam: () => 2, + } + useQuery( + infiniteQueryOptions({ + ...options, + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf< + InfiniteData | undefined + >() + return refetchInterval(3000) + }, + }), + ) + useQuery( + suspenseInfiniteQueryOptions({ + ...options, + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf< + InfiniteData | undefined + >() + return refetchInterval(3000) + }, + }), + ) + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/sharedCore.test.ts b/packages/react-query-pluggable/src/__tests__/sharedCore.test.ts new file mode 100644 index 00000000000..4a65e414de8 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/sharedCore.test.ts @@ -0,0 +1,45 @@ +import { + CancelledError, + clearQueryClient, + getQueryState, + mountQueryClient, + onlineManager, + query, + unmountQueryClient, +} from '@tanstack/query-core-pluggable' +import { describe, expect, it } from 'vitest' +import { QueryClient, cancelQueries } from '..' + +describe('shared query-core runtime', () => { + it('pauses when core goes offline and resumes when core reconnects', async () => { + const client = new QueryClient() + const wasOnline = onlineManager.isOnline() + mountQueryClient(client) + try { + onlineManager.setOnline(false) + const queryKey = ['connection'] + const pending = query(client, { queryKey, queryFn: () => 'online' }) + expect(getQueryState(client, queryKey)?.fetchStatus).toBe('paused') + onlineManager.setOnline(true) + await expect(pending).resolves.toBe('online') + } finally { + unmountQueryClient(client) + onlineManager.setOnline(wasOnline) + clearQueryClient(client) + } + }) + + it('rejects cancelled queries with the core cancellation error', async () => { + const client = new QueryClient() + const queryKey = ['cancel'] + const pending = query(client, { + queryKey, + queryFn: () => new Promise(() => {}), + }) + await Promise.all([ + expect(pending).rejects.toBeInstanceOf(CancelledError), + cancelQueries(client, { queryKey }), + ]) + clearQueryClient(client) + }) +}) diff --git a/packages/react-query-pluggable/src/errorBoundaryUtils.ts b/packages/react-query-pluggable/src/errorBoundaryUtils.ts new file mode 100644 index 00000000000..f95d806ff1b --- /dev/null +++ b/packages/react-query-pluggable/src/errorBoundaryUtils.ts @@ -0,0 +1,66 @@ +'use client' + +import { shouldThrowError } from '@tanstack/query-core-pluggable' +import type { + DefaultedQueryObserverOptions, + Query, + QueryObserverResult, +} from '@tanstack/query-core-pluggable' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' + +type Options = DefaultedQueryObserverOptions +type CachedQuery = Query + +/** + * Stops a failed query retrying on mount until the boundary requests a reset. + * @param options - The observer options for this reader. + * @param boundary - The nearest reset boundary. + * @param query - The cache entry at the start of the render. + */ +export function prepareErrorBoundary( + options: Options, + boundary: QueryErrorResetBoundaryValue, + query: CachedQuery | undefined, +) { + const rule = + typeof options.throwOnError === 'object' + ? options.throwOnError[1] + : options.throwOnError + if ( + (options.suspense || + (query?.state.status === 'error' && typeof rule === 'function' + ? rule(query.state.error, query) + : rule)) && + !boundary.isReset() + ) + options.retryOnMount = false +} + +/** + * Checks whether a settled observer error belongs to the nearest boundary. + * @param result - The snapshot being rendered. + * @param options - The observer options for this reader. + * @param query - The cache entry at the start of the render. + * @param boundary - The nearest reset boundary. + * @returns Whether React should receive the settled error. + */ +export function getHasError( + result: QueryObserverResult, + options: Options, + query: CachedQuery | undefined, + boundary: QueryErrorResetBoundaryValue, +) { + return ( + result.status === 'error' && + !boundary.isReset() && + result.fetchStatus !== 'fetching' && + !!query && + ((options.suspense && result.data === undefined) || + shouldThrowError( + typeof options.throwOnError === 'object' + ? options.throwOnError[1] + : options.throwOnError, + [result.error, query], + )) + ) +} diff --git a/packages/react-query-pluggable/src/index.ts b/packages/react-query-pluggable/src/index.ts new file mode 100644 index 00000000000..24440e019b1 --- /dev/null +++ b/packages/react-query-pluggable/src/index.ts @@ -0,0 +1,302 @@ +// React Query +export type { + AnyUseBaseQueryOptions, + UseBaseQueryOptions, + UsePrefetchQueryOptions, + UsePrefetchInfiniteQueryOptions, + AnyUseQueryOptions, + UseQueryOptions, + AnyUseSuspenseQueryOptions, + UseSuspenseQueryOptions, + AnyUseInfiniteQueryOptions, + UseInfiniteQueryOptions, + AnyUseSuspenseInfiniteQueryOptions, + UseSuspenseInfiniteQueryOptions, + UseBaseQueryResult, + UseQueryResult, + UseSuspenseQueryResult, + DefinedUseQueryResult, + UseInfiniteQueryResult, + DefinedUseInfiniteQueryResult, + UseSuspenseInfiniteQueryResult, + AnyUseMutationOptions, + UseMutationOptions, + UseMutateFunction, + UseMutateAsyncFunction, + UseBaseMutationResult, + UseMutationResult, +} from './types' +export { useQueries } from './useQueries' +export type { QueriesResults, QueriesOptions } from './useQueries' +export type { PreparedQuery } from './useQuery' +export { useQuery } from './useQuery' +export { throwOnError } from './throwOnError' +export { suspenseQueryOptions } from './suspenseQueryOptions' +export type { SkippableSuspenseQueryOptions } from './suspenseQueryOptions' +export { suspenseInfiniteQueryOptions } from './suspenseInfiniteQueryOptions' +export type { SkippableSuspenseInfiniteQueryOptions } from './suspenseInfiniteQueryOptions' +export type { SuspenseControls, SuspenseQueryMode } from './suspenseQuery' +export { useSuspenseQueries } from './useSuspenseQueries' +export type { + SuspenseQueriesResults, + SuspenseQueriesOptions, +} from './useSuspenseQueries' +export { usePrefetchQuery } from './usePrefetchQuery' +export { usePrefetchInfiniteQuery } from './usePrefetchInfiniteQuery' +export { queryOptions } from './queryOptions' +export type { + DefinedInitialDataOptions, + QueryMode, + UndefinedInitialDataOptions, + UnusedSkipTokenOptions, +} from './queryOptions' +export { infiniteQueryOptions } from './infiniteQueryOptions' +export type { + DefinedInitialDataInfiniteOptions, + UndefinedInitialDataInfiniteOptions, + UnusedSkipTokenInfiniteOptions, +} from './infiniteQueryOptions' +export { + QueryClientContext, + QueryClientProvider, + useQueryClient, +} from './QueryClientProvider' +export type { QueryClientProviderProps } from './QueryClientProvider' +export type { QueryErrorResetBoundaryProps } from './QueryErrorResetBoundary' +export { HydrationBoundary } from './HydrationBoundary' +export type { HydrationBoundaryProps } from './HydrationBoundary' +export type { + QueryErrorClearResetFunction, + QueryErrorIsResetFunction, + QueryErrorResetBoundaryFunction, + QueryErrorResetFunction, +} from './QueryErrorResetBoundary' +export { + QueryErrorResetBoundary, + useQueryErrorResetBoundary, +} from './QueryErrorResetBoundary' +export { useIsFetching } from './useIsFetching' +export { useIsMutating, useMutationState } from './useMutationState' +export { useMutation } from './useMutation' +export { mutationOptions } from './mutationOptions' +export { useIsRestoring, IsRestoringProvider } from './IsRestoringProvider' + +export { + focusManager, + environmentManager, + onlineManager, + CancelledError, + timeoutManager, + hashKey, + noop, + partialMatchKey, + replaceEqualDeep, + shouldThrowError, + defaultQueryFn, + skipToken, + defaultShouldDehydrateMutation, + defaultShouldDehydrateQuery, + dehydrate, + dehydrateQuery, + hydrate, + infiniteQuery, + fetchOptimistic, + InfiniteQueryObserver, + MutationCache, + getMutationCache, + MutationObserver, + defaultScheduler, + notifyManager, + QueriesObserver, + QueryCache, + QueryClient, + mountQueryClient, + unmountQueryClient, + countFetchingQueries, + isPending, + isSuccess, + isError, + isFetching, + isPaused, + isLoading, + isRefetching, + isLoadingError, + isRefetchError, + isFetched, + isFetchingNextPage, + isFetchingPreviousPage, + isFetchNextPageError, + isFetchPreviousPageError, + isMutating, + getQueryData, + setQueryData, + getQueryState, + query, + resumePausedMutations, + getQueryCache, + findCachedQuery, + findCachedQueries, + clearQueryCache, + getQueryObserverCount, + invalidateCachedQuery, + resetCachedQuery, + isQueryFetched, + isQueryActive, + isQueryDisabled, + isQueryStatic, + isQueryStale, + getDefaultOptions, + setDefaultOptions, + setQueryDefaults, + getQueryDefaults, + setMutationDefaults, + getMutationDefaults, + defaultQueryOptions, + defaultMutationOptions, + clearQueryClient, + getQueriesData, + setQueriesData, + removeQueries, + resetQueries, + cancelQueries, + invalidateQueries, + refetchQueries, + serialScope, + select, + placeholderData, + refetchInterval, + QueryObserver, + keepPreviousData, + matchMutation, + matchQuery, + streamedQuery, + Mutation, + Query, + dataTagSymbol, + dataTagErrorSymbol, + unsetMarker, +} from '@tanstack/query-core-pluggable' +export type { + FocusManager, + OnlineManager, + TimeoutManager, + ManagedTimerId, + TimeoutCallback, + TimeoutProvider, + DefaultQueryFn, + SkipToken, + Updater, + MutationCacheNotifyEvent, + MutationCacheConfig, + QueryCacheNotifyEvent, + QueryCacheConfig, + SerialScope, + Select, + PlaceholderData, + RefetchInterval, + MutationFilters, + QueryFilters, + DehydrateOptions, + HydrateOptions, + QueryFunction, + StaleTimeFunction, + QueryBooleanOption, + QueryPersister, + QueryFunctionContext, + PlaceholderDataFunction, + QueryOptions, + ThrowOnError, + QueryErrorBoundaryOption, + QueryObserverOptions, + DefaultedQueryObserverOptions, + InfiniteQueryObserverOptions, + DefaultedInfiniteQueryObserverOptions, + QueryExecuteOptions, + InfiniteQueryExecuteOptions, + InvalidateQueryFilters, + RefetchQueryFilters, + MutationFunctionContext, + MutationFunction, + MutationOptions, + MutationObserverOptions, + MutateOptions, + MutateFunctionRest, + MutateFunction, + MutationObserverBaseResult, + MutationObserverIdleResult, + MutationObserverLoadingResult, + MutationObserverErrorResult, + MutationObserverSuccessResult, + MutationObserverResult, + QueryClientConfig, + DefaultOptions, + QueryObserverResultReader, + DehydratedState, + MutationState, + QueriesObserverOptions, + QueriesObserverResultReader, + QueryState, + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + UnsetMarker, + AnyDataTag, + DataTag, + QueryKeyWithDataTag, + InferDataFromTag, + InferErrorFromTag, + StaleTime, + InitialDataFunction, + QueriesPlaceholderDataFunction, + EqualityFn, + CacheKeyHashFunction, + CacheKeyConfig, + GetPreviousPageParamFunction, + GetNextPageParamFunction, + InfiniteData, + QueryMeta, + NetworkMode, + NotifyOnChangeProps, + InitialPageParam, + InfiniteQueryPageParamsOptions, + WithRequired, + ResultOptions, + RefetchOptions, + InvalidateOptions, + ResetOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + QueryStatus, + FetchStatus, + QueryObserverBaseResult, + QueryObserverPendingResult, + QueryObserverLoadingResult, + QueryObserverLoadingErrorResult, + QueryObserverRefetchErrorResult, + QueryObserverSuccessResult, + QueryObserverPlaceholderResult, + DefinedQueryObserverResult, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from '@tanstack/query-core-pluggable' +export type { InfiniteQueryMode } from './infiniteQueryOptions' diff --git a/packages/react-query-pluggable/src/infiniteQueryOptions.ts b/packages/react-query-pluggable/src/infiniteQueryOptions.ts new file mode 100644 index 00000000000..efb191f4cbc --- /dev/null +++ b/packages/react-query-pluggable/src/infiniteQueryOptions.ts @@ -0,0 +1,352 @@ +import { InfiniteQueryObserver } from '@tanstack/query-core-pluggable' +import { observerKey } from './queryDescriptor' +import { queryPolicy } from './queryPolicy' +import type { + DefaultError, + InfiniteData, + InitialDataFunction, + NonUndefinedGuard, + OmitKeyof, + QueryKey, + QueryKeyWithDataTag, + SkipToken, +} from '@tanstack/query-core-pluggable' +import type { QueryDescriptor } from './queryDescriptor' +import type { SuspenseControls } from './suspenseQuery' +import type { UseInfiniteQueryOptions } from './types' + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is omitted, may be + * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is + * `pending`. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData?: + | undefined + | NonUndefinedGuard> + | InitialDataFunction< + NonUndefinedGuard> + > +} + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `queryFn` is not `skipToken` and + * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as + * {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be `skipToken`. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export interface UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends OmitKeyof< + UseInfiniteQueryOptions, + 'queryFn' +> { + /** The query function or the configured client default. */ + queryFn: Exclude< + UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken + > +} + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is known to be + * defined — `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData: + | NonUndefinedGuard> + | (() => NonUndefinedGuard>) +} + +/** Identifies the observer selected at definition time by infiniteQueryOptions. */ +export type InfiniteQueryMode = QueryDescriptor + +// A private type-only default distinguishes an omitted selector output from an +// explicitly selected value while keeping the public v6 generic parameter order. +declare const unselectedPages: unique symbol +/** Marks an omitted selector type while allowing an inferred page parameter in its default. */ +export type UnselectedPages = typeof unselectedPages +/** Preserves a custom projection or supplies the cached pages with their inferred cursor type. */ +export type ResolvedPages = TData extends UnselectedPages + ? InfiniteData + : TData + +type InfiniteQueryOptionsFactory = { + /** + * The factory accepts the fetcher, pagination callbacks, and observer options for the query. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(client, options)`. + * `options.queryKey` is required and is the query key to generate options for. + * + * This overload is selected when `initialData` is known to be defined. + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — all paginated observer options, with `initialData` known to be defined. + * @returns A descriptor with its observer and a typed key, so that `queryKey` carries the inferred data type. + * @remarks See {@link useQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useQuery} to run an infinite query with these options. + * @example + * ```tsx + * import { infiniteQueryOptions, useQuery } from '@tanstack/react-query-pluggable' + * + * export const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * initialData: { pages: [], pageParams: [] }, + * }) + * + * function Projects() { + * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the + * // list stays visible alongside the error. + * const { data, status, error } = useQuery(projectsOptions) + * + * return ( + *
    + * {status === 'error' ? Error: {error.message} : null} + *
      + * {data.pages.map((page) => page.projects.map((p) =>
    • {p.name}
    • ))} + *
    + *
    + * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = UnselectedPages, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > & + TPolicy, + ): DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + ResolvedPages, + TQueryKey, + TPageParam + > & + QueryKeyWithDataTag< + TQueryKey, + InfiniteData, + TError + > & + InfiniteQueryMode & + TPolicy + + /** + * The factory accepts the fetcher, pagination callbacks, and observer options for the query. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(client, options)`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — the fetcher, pagination, and observer options. + * @returns A descriptor with its observer and a typed key, so that `queryKey` carries the inferred data type. + * @remarks See {@link useQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useQuery } from '@tanstack/react-query-pluggable' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, status, error } = useQuery(commentsOptions(postId)) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return ( + *
      + * {data.pages.map((page) => page.comments.map((c) =>
    • {c.text}
    • ))} + *
    + * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = UnselectedPages, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > & + TPolicy, + ): UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + ResolvedPages, + TQueryKey, + TPageParam + > & + QueryKeyWithDataTag< + TQueryKey, + InfiniteData, + TError + > & + InfiniteQueryMode & + TPolicy + + /** + * The factory accepts the fetcher, pagination callbacks, and observer options for the query. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(client, options)`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — the fetcher, pagination, and observer options. + * @returns A descriptor with its observer and a typed key, so that `queryKey` carries the inferred data type. + * @remarks See {@link useQuery} for examples that fetch further pages (from a button click or + * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set. + * @see {@link useQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useQuery } from '@tanstack/react-query-pluggable' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, status, error } = useQuery(commentsOptions(postId)) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return ( + *
      + * {data.pages.map((page) => page.comments.map((c) =>
    • {c.text}
    • ))} + *
    + * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = UnselectedPages, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > & + TPolicy, + ): UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + ResolvedPages, + TQueryKey, + TPageParam + > & + QueryKeyWithDataTag< + TQueryKey, + InfiniteData, + TError + > & + InfiniteQueryMode & + TPolicy +} + +/** + * Prepares a descriptor and tags its cache key with the data and error types. + * @param options - The fetcher and its configuration for the selected observer. + * @returns A new descriptor backed by InfiniteQueryObserver. + */ +export const infiniteQueryOptions: InfiniteQueryOptionsFactory & + InfiniteQueryOptionsFactory = (options: T) => ({ + ...options, + renderPolicy: queryPolicy, + [observerKey]: InfiniteQueryObserver, +}) diff --git a/packages/react-query-pluggable/src/mutationOptions.ts b/packages/react-query-pluggable/src/mutationOptions.ts new file mode 100644 index 00000000000..5d1de8f4c0e --- /dev/null +++ b/packages/react-query-pluggable/src/mutationOptions.ts @@ -0,0 +1,92 @@ +import type { DefaultError, WithRequired } from '@tanstack/query-core-pluggable' +import type { UseMutationOptions } from './types' + +type MutationOptionsFn = { + /** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A + * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with + * `useMutationState`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a + * required `mutationKey`. + * @returns The same options object, unchanged. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: + * ```tsx + * import { mutationOptions, useMutationState } from '@tanstack/react-query-pluggable' + * + * const createPostOptions = mutationOptions({ + * mutationKey: ['posts', 'create'], + * mutationFn: createPost, + * }) + * + * function SavingIndicator() { + * const isCreatingPost = useMutationState({ + * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, + * }).length > 0 + * + * return isCreatingPost ? Saving… : null + * } + * ``` + */ + < + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + options: WithRequired< + UseMutationOptions, + 'mutationKey' + >, + ): WithRequired< + UseMutationOptions, + 'mutationKey' + > + + /** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No + * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a + * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, + * such as `status`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a + * `mutationKey`. + * @returns The same options object, unchanged. + * @remarks See the other overload's example for looking a mutation up via `useMutationState`. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * ```tsx + * import { mutationOptions, useMutation } from '@tanstack/react-query-pluggable' + * + * export const createPostOptions = mutationOptions({ + * mutationFn: createPost, + * }) + * + * function CreatePost() { + * const mutation = useMutation(createPostOptions) + * return + * } + * ``` + */ + < + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + options: Omit< + UseMutationOptions, + 'mutationKey' + >, + ): Omit< + UseMutationOptions, + 'mutationKey' + > +} + +/** + * Preserves mutation option types when reusing the same options in multiple places. + * @param options - The mutation function, its key and lifecycle callbacks. + * @returns The supplied options. + */ +export const mutationOptions: MutationOptionsFn = (options: T) => options diff --git a/packages/react-query-pluggable/src/queryDescriptor.ts b/packages/react-query-pluggable/src/queryDescriptor.ts new file mode 100644 index 00000000000..eeaf0cecf64 --- /dev/null +++ b/packages/react-query-pluggable/src/queryDescriptor.ts @@ -0,0 +1,48 @@ +import type { + DefaultedQueryObserverOptions, + QueryClient, + QueryErrorBoundaryPolicy, + QueryObserver, + QueryObserverResult, + QueryObserverResultReader, +} from '@tanstack/query-core-pluggable' +import type { Context } from 'react' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' + +/** The observer chosen by a React option factory. Enumerable so descriptor spreads preserve it. */ +export const observerKey = Symbol('queryObserver') + +type Options = DefaultedQueryObserverOptions +type Result = QueryObserverResult + +/** The optional behavior supplied by the error-boundary feature. */ +export type QueryBoundaryPolicy = QueryErrorBoundaryPolicy< + Context, + QueryErrorResetBoundaryValue +> + +/** Render behavior selected by a single-query or parallel-query factory. */ +export interface QueryRenderPolicy { + /** Whether the observer uses Suspense defaults. */ + readonly suspense: TSuspense + /** Adjusts the observer options before reading its snapshot. */ + prepare?: (options: Options) => void + /** An optional policy for throwing errors during render. */ + errorBoundary?: QueryBoundaryPolicy + /** May start a render-time fetch and read its promise with React.use. */ + readQuery?: ( + options: Options, + reader: QueryObserverResultReader, + observer: QueryObserver, + client: QueryClient, + boundary: QueryErrorResetBoundaryValue, + ) => void +} + +/** A prepared descriptor selects its observer and its render behavior. */ +export interface QueryDescriptor { + /** The constructor to use for this observer. */ + readonly [observerKey]: TObserver + /** The behavior selected by the option factory. */ + readonly renderPolicy: QueryRenderPolicy +} diff --git a/packages/react-query-pluggable/src/queryOptions.ts b/packages/react-query-pluggable/src/queryOptions.ts new file mode 100644 index 00000000000..b9fcc103395 --- /dev/null +++ b/packages/react-query-pluggable/src/queryOptions.ts @@ -0,0 +1,272 @@ +import { QueryObserver } from '@tanstack/query-core-pluggable' +import { observerKey } from './queryDescriptor' +import { queryPolicy } from './queryPolicy' +import type { + DefaultError, + DefaultQueryFn, + InitialDataFunction, + NonUndefinedGuard, + OmitKeyof, + QueryFunction, + QueryKey, + QueryKeyWithDataTag, + SkipToken, +} from '@tanstack/query-core-pluggable' +import type { QueryDescriptor } from './queryDescriptor' +import type { SuspenseControls } from './suspenseQuery' +import type { UseQueryOptions } from './types' + +/** + * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be + * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is + * `pending`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UndefinedInitialDataOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = UseQueryOptions & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData?: + | undefined + | InitialDataFunction> + | NonUndefinedGuard +} + +/** + * The options accepted by the `queryOptions` overload selected when `queryFn` is not `skipToken` and + * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as + * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UnusedSkipTokenOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends OmitKeyof< + UseQueryOptions, + 'queryFn' +> { + /** The query function or the configured client default. */ + queryFn: Exclude< + UseQueryOptions['queryFn'], + SkipToken + > +} + +/** + * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined — + * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type DefinedInitialDataOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Omit, 'queryFn'> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData: + | NonUndefinedGuard + | (() => NonUndefinedGuard) + queryFn: QueryFunction | DefaultQueryFn +} + +/** Identifies the observer selected at definition time by queryOptions. */ +export type QueryMode = QueryDescriptor + +type QueryOptionsFactory = { + /** + * Creates a regular query descriptor for `useQuery`. The tagged key also carries the cache data + * and error types into client operations. + * + * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never + * `undefined` (unless a `select` changes `TData` to include `undefined`). + * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. + * @returns A descriptor with its observer and a typed key, so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable' + * + * export const postsOptions = queryOptions({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * initialData: [], + * }) + * + * function Posts() { + * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, + * // so the list stays visible alongside the error. + * const { data, status, error } = useQuery(postsOptions) + * + * return ( + *
    + * {status === 'error' ? Error: {error.message} : null} + *
      + * {data.map((post) =>
    • {post.title}
    • )} + *
    + *
    + * ) + * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: DefinedInitialDataOptions & + TPolicy, + ): DefinedInitialDataOptions & + QueryKeyWithDataTag & + QueryMode & + TPolicy + + /** + * Creates a regular query descriptor for `useQuery`. The tagged key also carries the cache data + * and error types into client operations. + * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`. + * @returns A descriptor with its observer and a typed key, so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, status, error } = useQuery(postOptions(id)) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return

    {data.title}

    + * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: UnusedSkipTokenOptions & + TPolicy, + ): UnusedSkipTokenOptions & + QueryKeyWithDataTag & + QueryMode & + TPolicy + + /** + * Creates a regular query descriptor for `useQuery`. The tagged key also carries the cache data + * and error types into client operations. + * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. + * @returns A descriptor with its observer and a typed key, so that `queryKey` carries the inferred data type. + * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, status, error } = useQuery(postOptions(id)) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return

    {data.title}

    + * } + * ``` + * @example + * A factory that disables the query, type safe, until `postId` is set: + * ```tsx + * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-pluggable' + * + * export const postOptions = (postId: number | undefined) => + * queryOptions({ + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, status, fetchStatus, error } = useQuery(postOptions(postId)) + * + * if (postId == null) return 'Select a post' + * if (status === 'pending' && fetchStatus === 'fetching') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return

    {data?.title}

    + * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: UndefinedInitialDataOptions< + TQueryFnData, + TError, + TData, + TQueryKey + > & + TPolicy, + ): UndefinedInitialDataOptions & + QueryKeyWithDataTag & + QueryMode & + TPolicy +} + +/** + * Prepares a descriptor and tags its cache key with the data and error types. + * @param options - The fetcher and its configuration for the selected observer. + * @returns A new descriptor backed by QueryObserver. + */ +export const queryOptions: QueryOptionsFactory & + QueryOptionsFactory = (options: T) => ({ + ...options, + renderPolicy: queryPolicy, + [observerKey]: QueryObserver, +}) diff --git a/packages/react-query-pluggable/src/queryPolicy.ts b/packages/react-query-pluggable/src/queryPolicy.ts new file mode 100644 index 00000000000..0c10073b5dd --- /dev/null +++ b/packages/react-query-pluggable/src/queryPolicy.ts @@ -0,0 +1,6 @@ +import type { QueryRenderPolicy } from './queryDescriptor' + +/** Ordinary queries expose their observer state directly. */ +export const queryPolicy = { + suspense: false, +} as const satisfies QueryRenderPolicy diff --git a/packages/react-query-pluggable/src/suspense.ts b/packages/react-query-pluggable/src/suspense.ts new file mode 100644 index 00000000000..104ac7b91b8 --- /dev/null +++ b/packages/react-query-pluggable/src/suspense.ts @@ -0,0 +1,233 @@ +import { + QueryObserver, + fetchOptimistic, + getQueryCache, +} from '@tanstack/query-core-pluggable' +import { use } from 'react' +import { throwOnError } from './throwOnError' +import type { + DefaultError, + DefaultedQueryObserverOptions, + Query, + QueryClient, + QueryKey, + QueryObserverResult, +} from '@tanstack/query-core-pluggable' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { QueryRenderPolicy } from './queryDescriptor' + +type SuspensePromiseEntry = { + fetchPromise: Promise + promise: Promise + settled: boolean +} + +const suspensePromiseCache = new WeakMap< + Query, + SuspensePromiseEntry +>() + +/** + * Uses the nearest error boundary when the query has no data to show. + * @param _error - The query error. + * @param query - The query that failed. + * @returns Whether the query has no data. + */ +export const defaultThrowOnError = < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + _error: TError, + query: Query, +) => query.state.data === undefined + +/** + * Raises `staleTime` and a numeric `gcTime` to at least 1000ms when `suspense` is enabled, so a + * component that remounts after suspending doesn't refetch right away or find the query garbage + * collected. A `'static'` `staleTime` is kept as is. Mutates the options. + * @param defaultedOptions - The defaulted query options to adjust. + */ +export const ensureSuspenseTimers = ( + defaultedOptions: DefaultedQueryObserverOptions, +) => { + if (defaultedOptions.suspense) { + // Handle staleTime to ensure minimum 1000ms in Suspense mode + // This prevents unnecessary refetching when components remount after suspending + const MIN_SUSPENSE_TIME_MS = 1000 + + const clamp = (value: number | 'static' | undefined) => + value === 'static' + ? value + : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS) + + const originalStaleTime = defaultedOptions.staleTime + defaultedOptions.staleTime = + typeof originalStaleTime === 'function' + ? (...args) => clamp(originalStaleTime(...args)) + : clamp(originalStaleTime) + + if (typeof defaultedOptions.gcTime === 'number') { + defaultedOptions.gcTime = Math.max( + defaultedOptions.gcTime, + MIN_SUSPENSE_TIME_MS, + ) + } + } +} + +/** + * Decides whether a Suspense query needs to fetch during render. + * @param result - The result for this render. + * @param errorResetBoundary - The nearest query error reset boundary. + * @param query - The query to fetch. + * @returns `undefined` to skip the fetch, `false` to fetch in the background, or `true` to suspend. + */ +const shouldSuspend = ( + result: QueryObserverResult, + errorResetBoundary: QueryErrorResetBoundaryValue, + query: Query, +): boolean | undefined => { + if ( + result.status === 'pending' || + (query.state.status === 'error' && errorResetBoundary.isReset()) + ) { + return true + } + + if (result.fetchStatus === 'fetching' && result.isPlaceholderData) { + return false + } + + return undefined +} + +/** + * Starts a fetch during render or reuses a promise for an existing fetch. + * @param client - The client that owns the query. + * @param defaultedOptions - The options of the query. + * @param observer - The observer that starts the fetch. + * @param errorResetBoundary - The nearest query error reset boundary. + * @param query - The query used to key the promise cache. + * @returns A promise that resolves when the fetch settles. + */ +export function getSuspensePromise( + client: QueryClient, + defaultedOptions: DefaultedQueryObserverOptions, + observer: QueryObserver, + errorResetBoundary: QueryErrorResetBoundaryValue, + query: Query, +): Promise { + let entry = suspensePromiseCache.get(query) + if (!entry || entry.settled) { + const fetchPromise = fetchOptimistic(client, observer, defaultedOptions) + const settle = () => { + pending.settled = true + } + const pending: SuspensePromiseEntry = { + fetchPromise, + // Retry the render when the fetch settles, even on failure. + promise: fetchPromise.then(settle, settle), + settled: false, + } + suspensePromiseCache.set(query, pending) + entry = pending + } + + entry.fetchPromise.catch(() => errorResetBoundary.clearReset()) + return entry.promise +} + +type SuspenseOptions = DefaultedQueryObserverOptions +type SuspenseResult = QueryObserverResult +type SnapshotReader = { getSnapshot: () => T } + +const useReadSuspenseQuery = ( + defaultedOptions: SuspenseOptions, + reader: SnapshotReader, + observer: QueryObserver, + client: QueryClient, + errorResetBoundary: QueryErrorResetBoundaryValue, +) => { + if (!defaultedOptions.suspense) return + + const snapshot = reader.getSnapshot() + const query = getQueryCache(client).build(client, defaultedOptions) + const suspend = shouldSuspend(snapshot, errorResetBoundary, query) + if (suspend === undefined) return + + const promise = getSuspensePromise( + client, + defaultedOptions, + observer, + errorResetBoundary, + query, + ) + if (suspend) { + use(promise) + } +} + +const suspensePolicy: QueryRenderPolicy = { + suspense: true, + prepare: ensureSuspenseTimers, + errorBoundary: throwOnError, +} + +/** Supplies Suspense behavior for one query. */ +export const suspenseQueryPolicy: QueryRenderPolicy = { + ...suspensePolicy, + readQuery: useReadSuspenseQuery, +} + +const useReadSuspenseQueries = ( + defaultedQueries: Array, + reader: SnapshotReader>, + client: QueryClient, + errorResetBoundary: QueryErrorResetBoundaryValue, +) => { + const snapshot = reader.getSnapshot() + + const suspensePromises = snapshot.map((result, index) => { + const opts = defaultedQueries[index] + + if (!opts?.suspense) { + return undefined + } + + const query = getQueryCache(client).build(client, opts) + const suspend = shouldSuspend(result, errorResetBoundary, query) + + if (suspend === undefined) { + return undefined + } + + const queryObserver = new QueryObserver(client, opts) + const promise = getSuspensePromise( + client, + opts, + queryObserver, + errorResetBoundary, + query, + ) + + return suspend ? promise : undefined + }) + + // Start every fetch before calling use(), because use() suspends immediately. + for (const promise of suspensePromises) { + if (promise) { + use(promise) + } + } +} + +/** Supplies Suspense behavior for parallel queries. */ +export const suspenseQueriesPolicy: QueryRenderPolicy & { + /** Starts each member fetch before suspending the group. */ + readQueries: typeof useReadSuspenseQueries +} = { + ...suspensePolicy, + readQueries: useReadSuspenseQueries, +} diff --git a/packages/react-query-pluggable/src/suspenseInfiniteQueryOptions.ts b/packages/react-query-pluggable/src/suspenseInfiniteQueryOptions.ts new file mode 100644 index 00000000000..c3e0b84f3c4 --- /dev/null +++ b/packages/react-query-pluggable/src/suspenseInfiniteQueryOptions.ts @@ -0,0 +1,107 @@ +import { InfiniteQueryObserver } from '@tanstack/query-core-pluggable' +import { prepareSuspenseOptions } from './suspenseQuery' +import type { + DefaultError, + InfiniteData, + OmitKeyof, + QueryKey, + QueryKeyWithDataTag, +} from '@tanstack/query-core-pluggable' +import type { + InfiniteQueryMode, + ResolvedPages, + UnselectedPages, +} from './infiniteQueryOptions' +import type { SuspenseControls, SuspenseQueryMode } from './suspenseQuery' +import type { + AnyUseInfiniteQueryOptions, + UseInfiniteQueryOptions, + UseSuspenseInfiniteQueryOptions, +} from './types' + +/** The infinite query options accepted when the fetcher may be disabled with skipToken. */ +export type SkippableSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, + TPageParam, +> = OmitKeyof< + UseInfiniteQueryOptions, + 'enabled' | 'throwOnError' +> + +/** + * Prepares a running paginated query for a Suspense boundary. + * @param options - The page fetcher, its key and observer options. Suspense owns enabled and throwOnError. + * @returns A descriptor for useQuery with a tagged cache key and pagination controls. + */ +export function suspenseInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = UnselectedPages, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UseSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > & + SuspenseControls, +): UseSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + ResolvedPages, + TQueryKey, + TPageParam +> & + QueryKeyWithDataTag< + TQueryKey, + InfiniteData, + TError + > & + InfiniteQueryMode & + SuspenseQueryMode + +/** + * Prepares a query whose fetcher may be skipToken. Skipping lets the component render with cached or undefined data. + * @param options - The page fetcher, its key and observer options. Suspense owns enabled and throwOnError. + * @returns A descriptor for useQuery with a tagged cache key and pagination controls. + */ +export function suspenseInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = UnselectedPages, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: SkippableSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > & + SuspenseControls, +): SkippableSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + ResolvedPages, + TQueryKey, + TPageParam +> & + QueryKeyWithDataTag< + TQueryKey, + InfiniteData, + TError + > & + InfiniteQueryMode & + SuspenseQueryMode +export function suspenseInfiniteQueryOptions( + options: AnyUseInfiniteQueryOptions, +) { + return prepareSuspenseOptions(options, InfiniteQueryObserver) +} diff --git a/packages/react-query-pluggable/src/suspenseQuery.ts b/packages/react-query-pluggable/src/suspenseQuery.ts new file mode 100644 index 00000000000..3ae8327dd92 --- /dev/null +++ b/packages/react-query-pluggable/src/suspenseQuery.ts @@ -0,0 +1,52 @@ +import { skipToken } from '@tanstack/query-core-pluggable' +import { observerKey } from './queryDescriptor' +import { queryPolicy } from './queryPolicy' +import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' +import { throwOnError } from './throwOnError' +import type { QueryDescriptor } from './queryDescriptor' + +/** Options that allow Suspense to control execution and error handling. */ +export type SuspenseControls = { + /** A skipped query disables the Suspense reader. */ + enabled?: undefined + /** The nearest boundary handles errors when no data is cached. */ + throwOnError?: undefined +} + +/** A skipped query uses the ordinary render policy and can render without cached data. */ +export interface SuspenseQueryMode { + /** Running queries suspend, and skipped queries can read cached data. */ + readonly enabled: TSkippable extends true ? boolean : true + /** Routes errors without cached data to the nearest boundary. */ + readonly throwOnError: readonly [ + typeof throwOnError, + typeof defaultThrowOnError, + ] + /** The reader uses this policy when the query is enabled. */ + readonly renderPolicy: TSkippable extends true + ? typeof suspenseQueryPolicy | typeof queryPolicy + : typeof suspenseQueryPolicy +} + +/** + * Attaches the selected observer and its Suspense policy in one copy. + * @param options - The fetcher and options supplied by the caller. + * @param Observer - The observer selected by the public factory. + * @returns A descriptor that uses the ordinary render policy for a skipped fetcher. + */ +export function prepareSuspenseOptions< + TOptions extends { queryFn?: unknown }, + TObserver, +>( + options: TOptions, + Observer: TObserver, +): TOptions & QueryDescriptor & SuspenseQueryMode { + const enabled = options.queryFn !== skipToken + return { + ...options, + [observerKey]: Observer, + enabled, + throwOnError: [throwOnError, defaultThrowOnError], + renderPolicy: enabled ? suspenseQueryPolicy : queryPolicy, + } +} diff --git a/packages/react-query-pluggable/src/suspenseQueryOptions.ts b/packages/react-query-pluggable/src/suspenseQueryOptions.ts new file mode 100644 index 00000000000..b6f5a0ba7bf --- /dev/null +++ b/packages/react-query-pluggable/src/suspenseQueryOptions.ts @@ -0,0 +1,70 @@ +import { QueryObserver } from '@tanstack/query-core-pluggable' +import { prepareSuspenseOptions } from './suspenseQuery' +import type { + DefaultError, + OmitKeyof, + QueryKey, + QueryKeyWithDataTag, +} from '@tanstack/query-core-pluggable' +import type { QueryMode } from './queryOptions' +import type { SuspenseControls, SuspenseQueryMode } from './suspenseQuery' +import type { + AnyUseQueryOptions, + UseQueryOptions, + UseSuspenseQueryOptions, +} from './types' + +/** Options for a Suspense reader whose query function can be skipped. */ +export type SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'enabled' | 'throwOnError' +> + +/** + * Prepares a running query for a Suspense boundary. + * @param options - The fetcher, its key and observer options. Suspense owns enabled and throwOnError. + * @returns A descriptor for useQuery with a tagged cache key. + */ +export function suspenseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseSuspenseQueryOptions & + SuspenseControls, +): UseSuspenseQueryOptions & + QueryKeyWithDataTag & + QueryMode & + SuspenseQueryMode + +/** + * Prepares a query whose fetcher may be skipToken. Skipping lets the component render with cached or undefined data. + * @param options - The fetcher, its key and observer options. Suspense owns enabled and throwOnError. + * @returns A descriptor for useQuery with a tagged cache key. + */ +export function suspenseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + > & + SuspenseControls, +): SkippableSuspenseQueryOptions & + QueryKeyWithDataTag & + QueryMode & + SuspenseQueryMode +export function suspenseQueryOptions(options: AnyUseQueryOptions) { + return prepareSuspenseOptions(options, QueryObserver) +} diff --git a/packages/react-query-pluggable/src/throwOnError.ts b/packages/react-query-pluggable/src/throwOnError.ts new file mode 100644 index 00000000000..952ea4776e2 --- /dev/null +++ b/packages/react-query-pluggable/src/throwOnError.ts @@ -0,0 +1,19 @@ +import { getQueryCache } from '@tanstack/query-core-pluggable' +import { QueryErrorResetBoundaryContext } from './QueryErrorResetBoundary' +import { getHasError, prepareErrorBoundary } from './errorBoundaryUtils' +import type { QueryBoundaryPolicy } from './queryDescriptor' + +/** Routes settled query errors to React. Pass [throwOnError, true] or [throwOnError, (error, query) => boolean] to a query or its client defaults. */ +export const throwOnError: QueryBoundaryPolicy = { + context: QueryErrorResetBoundaryContext, + prepare(client, options, boundary) { + const query = getQueryCache(client).get(options.queryHash) + prepareErrorBoundary(options, boundary, query) + return { + onCommit: boundary.clearReset, + check(result) { + if (getHasError(result, options, query, boundary)) throw result.error + }, + } + }, +} diff --git a/packages/react-query-pluggable/src/types.ts b/packages/react-query-pluggable/src/types.ts new file mode 100644 index 00000000000..05e4cd7f558 --- /dev/null +++ b/packages/react-query-pluggable/src/types.ts @@ -0,0 +1,497 @@ +import type { + DefaultError, + DefinedInfiniteQueryObserverResult, + DefinedQueryObserverResult, + DistributiveOmit, + InferErrorFromTag, + InfiniteData, + InfiniteQueryExecuteOptions, + InfiniteQueryObserverOptions, + InfiniteQueryObserverPlaceholderResult, + InfiniteQueryObserverResult, + MutateFunction, + MutationObserverOptions, + MutationObserverResult, + OmitKeyof, + Override, + QueryErrorBoundaryOption, + QueryExecuteOptions, + QueryKey, + QueryObserverOptions, + QueryObserverPlaceholderResult, + QueryObserverResult, + SkipToken, + ThrowOnError, +} from '@tanstack/query-core-pluggable' + +/** Error options recognized when inferring a query inside a parallel group. */ +export type GroupThrowOnError = + | ThrowOnError + | QueryErrorBoundaryOption + +/** + * {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseBaseQueryOptions = UseBaseQueryOptions< + any, + any, + any, + any, + any +> +/** + * The options shared by `useQuery` and `useQuery(suspenseQueryOptions(...))`. Extends {@link QueryObserverOptions} + * with the React-specific `subscribed` option. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and + * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseBaseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends QueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> { + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * The options accepted by `usePrefetchQuery` — everything you can pass to `query`, with a + * required `queryFn`. Pass `defaultQueryFn` to use the client defaults. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and + * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UsePrefetchQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = DistributiveOmit< + QueryExecuteOptions, + 'queryFn' +> & { + /** + * Pass a query function or `defaultQueryFn` to use the client defaults. Prefetch hooks do not accept `skipToken`. + */ + queryFn: Exclude< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >['queryFn'], + SkipToken | undefined + > +} + +/** + * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `infiniteQuery(client, options)`, + * with a required `queryFn`. Pass `defaultQueryFn` to use the client defaults. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params — a prefetch never reads `data` back out, so this + * parameter only matters if you reuse these options elsewhere with `select` applied. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type UsePrefetchInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = DistributiveOmit< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + 'queryFn' +> & { + /** + * Pass a query function or `defaultQueryFn` to use the client defaults. Prefetch hooks do not accept `skipToken`. + */ + queryFn: Exclude< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken | undefined + > +} + +/** + * {@link UseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseQueryOptions = UseQueryOptions +/** + * The ordinary options accepted by {@link queryOptions}. The factory selects the render policy for `useQuery`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends OmitKeyof< + UseBaseQueryOptions, + 'suspense' | 'throwOnError' +> { + /** Pass [throwOnError, true] or [throwOnError, predicate] to route a settled error to React. */ + throwOnError?: QueryErrorBoundaryOption< + TQueryFnData, + TError, + TQueryFnData, + TQueryKey + > +} + +/** + * {@link UseSuspenseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseSuspenseQueryOptions = UseSuspenseQueryOptions< + any, + any, + any, + any +> +/** + * Options for a `useQuery(suspenseQueryOptions(...))` call whose data is defined. The options match those of + * {@link UseQueryOptions} except for `throwOnError` and `enabled`. + * Use the other overload for a query function that can be `skipToken`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseSuspenseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends OmitKeyof< + UseQueryOptions, + 'queryFn' | 'enabled' | 'throwOnError' +> { + /** + * The query function. Use `defaultQueryFn` to use the client's configured function. + */ + queryFn: Exclude< + UseQueryOptions['queryFn'], + SkipToken + > +} + +/** + * {@link UseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseInfiniteQueryOptions = UseInfiniteQueryOptions< + any, + any, + any, + any, + any +> +/** + * The options accepted by `useQuery(infiniteQueryOptions(...))`. Extends {@link InfiniteQueryObserverOptions} + * with the React-specific `subscribed` option. {@link infiniteQueryOptions} and {@link suspenseInfiniteQueryOptions} select the render policy. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export interface UseInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends OmitKeyof< + InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + 'suspense' | 'throwOnError' +> { + /** Enables error boundary handling for the paginated query. */ + throwOnError?: QueryErrorBoundaryOption< + TQueryFnData, + TError, + InfiniteData, + TQueryKey + > + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * {@link UseSuspenseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types + * aren't relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseSuspenseInfiniteQueryOptions = + UseSuspenseInfiniteQueryOptions +/** + * The options accepted by `useQuery(suspenseInfiniteQueryOptions(...))`. Same as {@link UseInfiniteQueryOptions}, except for + * `enabled` and `throwOnError`. If `placeholderData` provides data, the query can render while the fetch runs. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export interface UseSuspenseInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends OmitKeyof< + UseInfiniteQueryOptions, + 'queryFn' | 'enabled' | 'throwOnError' +> { + /** + * The query function. Use `defaultQueryFn` to use the client defaults. Use the other overload when the function can be `skipToken`. + */ + queryFn: Exclude< + UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken + > +} + +/** + * The result of `useQuery` when `initialData` isn't set — `data` may be `undefined` while the query is + * `pending`. Re-exports {@link QueryObserverResult}. `useQuery(infiniteQueryOptions(...))` returns + * {@link UseInfiniteQueryResult} instead. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseBaseQueryResult< + TData = unknown, + TError = DefaultError, +> = QueryObserverResult + +/** + * The result of `useQuery`. Same as {@link UseBaseQueryResult}. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseQueryResult< + TData = unknown, + TError = DefaultError, +> = UseBaseQueryResult + +/** The result of `useQuery(suspenseQueryOptions(...))`, including defined placeholder data when configured. */ +export type UseSuspenseQueryResult = + | DefinedQueryObserverResult + | QueryObserverPlaceholderResult + +/** + * The result of `useQuery` when `initialData` is set. The `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * Re-exports {@link DefinedQueryObserverResult}. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type DefinedUseQueryResult< + TData = unknown, + TError = DefaultError, +> = DefinedQueryObserverResult + +/** + * The result of `useQuery(infiniteQueryOptions(...))` when `initialData` isn't set — `data` may be `undefined` while the query is + * `pending`. Re-exports {@link InfiniteQueryObserverResult}. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = InfiniteQueryObserverResult + +/** + * The result of `useQuery(infiniteQueryOptions(...))` when `initialData` is set — `data` is never `undefined` (unless a + * `select` changes `TData` to include `undefined`). Re-exports {@link DefinedInfiniteQueryObserverResult} + *. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type DefinedUseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = DefinedInfiniteQueryObserverResult + +/** + * The result of `useQuery(suspenseInfiniteQueryOptions(...))`, including defined placeholder data when configured. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseSuspenseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = + | DefinedInfiniteQueryObserverResult + | InfiniteQueryObserverPlaceholderResult + +/** + * {@link UseMutationOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any mutation in a helper function. + */ +export type AnyUseMutationOptions = UseMutationOptions +/** + * The options accepted by `useMutation`. Same as {@link MutationObserverOptions}, + * minus the internal `_defaulted` flag. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export interface UseMutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends OmitKeyof< + MutationObserverOptions, + '_defaulted' +> {} + +/** + * The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call + * `onSuccess`/`onError`/`onSettled`) to the underlying `mutate` call. Fire-and-forget — errors are surfaced + * through the mutation result instead of being thrown by `mutate`, unless `throwOnError` makes `useMutation` + * rethrow them. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutateFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = ( + ...args: Parameters< + MutateFunction + > +) => void + +/** + * The type of `mutateAsync`, as returned by `useMutation`. Similar to {@link UseMutateFunction}, but returns a + * promise which can be awaited. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutateAsyncFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = MutateFunction + +/** + * The result of `useMutation`. Same as {@link MutationObserverResult}, with + * `mutate` narrowed to the fire-and-forget {@link UseMutateFunction} signature, plus the added `mutateAsync`. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseBaseMutationResult< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = Override< + MutationObserverResult, + { mutate: UseMutateFunction } +> & { + /** + * Similar to `mutate`, but returns a promise which can be awaited. + */ + mutateAsync: UseMutateAsyncFunction< + TData, + TError, + TVariables, + TOnMutateResult + > +} + +/** + * The result of `useMutation`. Same as {@link UseBaseMutationResult}. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutationResult< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = UseBaseMutationResult + +/** Recovers the error type retained in a prepared query key when an error handler is absent. */ +export type TaggedQueryError = T extends { + queryKey: infer K extends QueryKey +} + ? InferErrorFromTag + : TFallback diff --git a/packages/react-query-pluggable/src/useIsFetching.ts b/packages/react-query-pluggable/src/useIsFetching.ts new file mode 100644 index 00000000000..e810c9388cc --- /dev/null +++ b/packages/react-query-pluggable/src/useIsFetching.ts @@ -0,0 +1,60 @@ +'use client' +import { + countFetchingQueries, + getQueryCache, + notifyManager, +} from '@tanstack/query-core-pluggable' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import type { QueryClient, QueryFilters } from '@tanstack/query-core-pluggable' + +/** + * The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching in + * the background (useful for app-wide loading indicators). + * @param filters - The {@link QueryFilters} to narrow down the matched queries. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be the `number` of the queries that your application is currently loading or fetching in the + * background. + * @example + * ```tsx + * import { useIsFetching } from '@tanstack/react-query-pluggable' + * + * function PostsFetchingIndicator() { + * // How many queries matching the posts prefix are fetching? + * const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) + * + * return isFetchingPosts ? Refreshing posts... : null + * } + * ``` + * @example + * A global loading indicator for any query fetching in the background, not just the ones on screen: + * ```tsx + * import { useIsFetching } from '@tanstack/react-query-pluggable' + * + * function GlobalLoadingIndicator() { + * const isFetching = useIsFetching() + * + * return isFetching ? ( + *
    Queries are fetching in the background...
    + * ) : null + * } + * ``` + */ +export function useIsFetching( + filters?: Omit, + queryClient?: QueryClient, +): number { + const client = useQueryClient(queryClient) + const queryCache = getQueryCache(client) + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + queryCache.subscribe(notifyManager.batchCalls(onStoreChange)), + [queryCache], + ), + () => countFetchingQueries(client, filters), + () => countFetchingQueries(client, filters), + ) +} diff --git a/packages/react-query-pluggable/src/useMutation.ts b/packages/react-query-pluggable/src/useMutation.ts new file mode 100644 index 00000000000..5322c7618ae --- /dev/null +++ b/packages/react-query-pluggable/src/useMutation.ts @@ -0,0 +1,242 @@ +'use client' + +import { + MutationObserver, + noop, + notifyManager, + shouldThrowError, +} from '@tanstack/query-core-pluggable' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import type { DefaultError, QueryClient } from '@tanstack/query-core-pluggable' +import type { + UseMutateFunction, + UseMutationOptions, + UseMutationResult, +} from './types' + +// HOOK + +/** + * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. + * `useMutation` is the hook for that. + * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second + * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared + * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks + * fire only for the latest call you've made, and only while the component is still mounted — unmounting before + * the mutation settles removes the subscription and prevents them from firing. + * @throws {Error} The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is + * thrown to the nearest error boundary. + * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look + * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`). + * @example + * ```tsx + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Rendering the mutation's own state, rather than just firing it off: + * ```tsx + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), + * }) + * + * return ( + *
    + * {addMutation.isPending ? ( + * 'Adding todo...' + * ) : ( + * <> + * {addMutation.isError ? ( + *
    An error occurred: {addMutation.error.message}
    + * ) : null} + * + * + * )} + *
    + * ) + * } + * ``` + * @example + * Optimistic update via `onMutate`, rolling back on `onError`: + * ```tsx + * import { useMutation, useQueryClient, cancelQueries, getQueryData, setQueryData, invalidateQueries } from '@tanstack/react-query-pluggable' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onMutate: async (newTodo) => { + * await cancelQueries(queryClient, { queryKey: ['todos'] }) + * const previousTodos = getQueryData(queryClient, ['todos']) + * + * setQueryData(queryClient, ['todos'], (old) => [ + * ...(old ?? []), + * newTodo, + * ]) + * + * // Passed to `onError` as `onMutateResult` if the mutation fails. + * return { previousTodos } + * }, + * onError: (_err, _newTodo, onMutateResult) => { + * setQueryData(queryClient, ['todos'], onMutateResult?.previousTodos) + * }, + * onSettled: () => { + * invalidateQueries(queryClient, { queryKey: ['todos'] }) + * }, + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a + * promise per call instead, so you can wait for all of them when they succeed: + * ```tsx + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' + * + * function AddTodos() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), + * }) + * + * async function handleAddAll(todos: Array) { + * try { + * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo))) + * } catch (error) { + * console.error('Failed to add todos:', error) + * } + * } + * + * return ( + * + * ) + * } + * ``` + * @example + * If some of the mutations above can fail independently of the others, and you want to know which ones + * did — rather than losing that information the moment the first one rejects — swap `Promise.all` for + * `Promise.allSettled`: + * ```tsx + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' + * + * function AddTodos() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), + * }) + * + * async function handleAddAll(todos: Array) { + * const addResults = await Promise.allSettled( + * todos.map((todo) => addMutation.mutateAsync(todo)), + * ) + * + * addResults.forEach((addResult, index) => { + * if (addResult.status === 'rejected') { + * console.error(`Failed to add "${todos[index]}":`, addResult.reason) + * } + * }) + * } + * + * return ( + * + * ) + * } + * ``` + */ +export function useMutation< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: UseMutationOptions, + queryClient?: QueryClient, +): UseMutationResult { + const client = useQueryClient(queryClient) + + const [observer] = React.useState( + () => + new MutationObserver( + client, + options, + ), + ) + + React.useEffect(() => { + observer.setOptions(options) + }, [observer, options]) + + const result = React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + observer.subscribe(notifyManager.batchCalls(onStoreChange)), + [observer], + ), + () => observer.getCurrentResult(), + () => observer.getCurrentResult(), + ) + + const mutate = React.useCallback< + UseMutateFunction + >( + ( + ...args: Parameters< + UseMutateFunction + > + ) => { + observer.mutate(args[0] as TVariables, args[1]).catch(noop) + }, + [observer], + ) + + if ( + result.error && + shouldThrowError(observer.options.throwOnError, [result.error]) + ) { + throw result.error + } + + return { ...result, mutate, mutateAsync: result.mutate } +} diff --git a/packages/react-query-pluggable/src/useMutationState.ts b/packages/react-query-pluggable/src/useMutationState.ts new file mode 100644 index 00000000000..517a6073c5b --- /dev/null +++ b/packages/react-query-pluggable/src/useMutationState.ts @@ -0,0 +1,210 @@ +'use client' + +import { + getMutationCache, + notifyManager, + replaceEqualDeep, +} from '@tanstack/query-core-pluggable' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import type { + Mutation, + MutationCache, + MutationFilters, + MutationState, + QueryClient, +} from '@tanstack/query-core-pluggable' + +/** + * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending` + * (useful for app-wide loading indicators). + * @param filters - The {@link MutationFilters} to narrow down the matched mutations. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be the `number` of the mutations that your application currently has `pending`. + * @example + * ```tsx + * import { useIsMutating } from '@tanstack/react-query-pluggable' + * + * function PostsMutatingIndicator() { + * // How many mutations matching the posts prefix are in progress? + * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] }) + * + * return isMutatingPosts ? Saving posts... : null + * } + * ``` + */ +export function useIsMutating( + filters?: Omit, + queryClient?: QueryClient, +): number { + const client = useQueryClient(queryClient) + return useMutationState( + { filters: { ...filters, status: 'pending' } }, + client, + ).length +} + +type MutationTypeFromResult = [TResult] extends [ + MutationState< + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult + >, +] + ? Mutation + : Mutation + +type MutationStateOptions< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +> = { + filters?: MutationFilters + select?: (mutation: TMutation) => TResult +} + +/** + * Creates snapshot getters that share equal selected results across renders. + * A new getter is created on each render. Each getter caches its snapshot until the matching mutations + * or their states change. + * @returns A factory for snapshot getters with a shared result cache. + */ +function createSnapshotFactory< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +>() { + let previousResult: Array | undefined + + return ( + mutationCache: MutationCache, + options: MutationStateOptions, + ) => { + let inputs: Array = [] + let snapshot: Array | undefined + + return (): Array => { + const mutations = mutationCache.findAll(options.filters) + const nextInputs = mutations.flatMap((mutation) => [ + mutation, + mutation.state, + ]) + + if ( + !snapshot || + nextInputs.length !== inputs.length || + nextInputs.some((input, index) => !Object.is(input, inputs[index])) + ) { + inputs = nextInputs + snapshot = replaceEqualDeep( + previousResult, + mutations.map( + (mutation): TResult => + (options.select + ? options.select(mutation as TMutation) + : mutation.state) as TResult, + ), + ) + previousResult = snapshot + } + + return snapshot + } + } +} + +/** + * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass + * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation + * state. + * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the + * mutation state. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be an Array of whatever `select` returns for each matching mutation. + * @example + * Get all variables of all running mutations: + * ```tsx + * import { useMutationState } from '@tanstack/react-query-pluggable' + * + * function PendingPosts() { + * const pendingVariables = useMutationState({ + * filters: { status: 'pending' }, + * select: (mutation) => mutation.state.variables, + * }) + * + * return <>{pendingVariables.length} posts saving... + * } + * ``` + * @example + * Get all data for specific mutations via the `mutationKey`: + * ```tsx + * import { useMutation, useMutationState } from '@tanstack/react-query-pluggable' + * + * const mutationKey = ['posts'] + * + * function Posts() { + * // Some mutation that we want to get the state for + * const mutation = useMutation({ + * mutationKey, + * mutationFn: createPosts, + * }) + * + * const savedPosts = useMutationState({ + * // this mutation key needs to match the mutation key of the given mutation (see above) + * filters: { mutationKey, status: 'success' }, + * select: (mutation) => mutation.state.data, + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new + * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the + * last item that `useMutationState` returns to get the latest successful invocation: + * ```tsx + * import { useMutationState } from '@tanstack/react-query-pluggable' + * + * function LatestPost() { + * const savedPosts = useMutationState({ + * filters: { mutationKey: ['posts'], status: 'success' }, + * select: (mutation) => mutation.state.data, + * }) + * + * const latestSavedPost = savedPosts[savedPosts.length - 1] + * + * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'} + * } + * ``` + */ +export function useMutationState< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +>( + options: MutationStateOptions = {}, + queryClient?: QueryClient, +): Array { + const mutationCache = getMutationCache(useQueryClient(queryClient)) + const [createSnapshot] = React.useState(() => + createSnapshotFactory(), + ) + const getSnapshot = createSnapshot(mutationCache, options) + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)), + [mutationCache], + ), + getSnapshot, + getSnapshot, + ) +} diff --git a/packages/react-query-pluggable/src/useObserverSnapshot.ts b/packages/react-query-pluggable/src/useObserverSnapshot.ts new file mode 100644 index 00000000000..c33780e425e --- /dev/null +++ b/packages/react-query-pluggable/src/useObserverSnapshot.ts @@ -0,0 +1,42 @@ +'use client' +import { noop, notifyManager } from '@tanstack/query-core-pluggable' +import * as React from 'react' +import type { QueryObserverResultReader } from '@tanstack/query-core-pluggable' + +interface ObserverStore { + subscribe: (listener: () => void) => () => void +} + +/** + * Commits a reader and subscribes React to its cached snapshots. + * @param observer - The observer that owns the subscription. + * @param reader - The reader scoped to the current render options. + * @param subscribed - Whether this render subscribes to updates. + * @param refresh - Includes updates that occurred before the subscription started. + * @returns The current snapshot. + */ +export function useObserverSnapshot( + observer: TObserver, + reader: QueryObserverResultReader, + subscribed: boolean, + refresh: (observer: TObserver) => void, +): TResult { + React.useEffect(() => { + reader.commit() + }, [reader]) + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => { + const unsubscribe = subscribed + ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) + : noop + refresh(observer) + return unsubscribe + }, + [observer, subscribed, refresh], + ), + reader.getSnapshot, + reader.getSnapshot, + ) +} diff --git a/packages/react-query-pluggable/src/usePrefetchInfiniteQuery.tsx b/packages/react-query-pluggable/src/usePrefetchInfiniteQuery.tsx new file mode 100644 index 00000000000..9783d44fcdc --- /dev/null +++ b/packages/react-query-pluggable/src/usePrefetchInfiniteQuery.tsx @@ -0,0 +1,76 @@ +import { + getQueryState, + infiniteQuery, + noop, +} from '@tanstack/query-core-pluggable' +import { useQueryClient } from './QueryClientProvider' +import type { + DefaultError, + InfiniteData, + QueryClient, + QueryKey, +} from '@tanstack/query-core-pluggable' +import type { UsePrefetchInfiniteQueryOptions } from './types' + +/** + * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, + * before a suspense boundary that wraps a component that uses `useQuery(suspenseInfiniteQueryOptions(...))`. You can pass + * everything to `usePrefetchInfiniteQuery` that you can pass to `infiniteQuery(client, options)`, though + * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. + * + * `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages, + * as well as pageParam information, and should return a single variable that will be passed to your query + * function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available. + * + * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left + * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's + * already there or already in flight. + * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `infiniteQuery(client, options)`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @example + * ```tsx + * import { Suspense } from 'react' + * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/react-query-pluggable' + * + * const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function App() { + * // Fire the prefetch during render, before the suspense boundary below. + * usePrefetchInfiniteQuery(projectsOptions) + * + * return ( + * Loading projects...}> + * + * + * ) + * } + * ``` + */ +export function usePrefetchInfiniteQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UsePrefetchInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): void { + const client = useQueryClient(queryClient) + + if (!getQueryState(client, options.queryKey)) { + void infiniteQuery(client, options).catch(noop) + } +} diff --git a/packages/react-query-pluggable/src/usePrefetchQuery.tsx b/packages/react-query-pluggable/src/usePrefetchQuery.tsx new file mode 100644 index 00000000000..3c1343938b3 --- /dev/null +++ b/packages/react-query-pluggable/src/usePrefetchQuery.tsx @@ -0,0 +1,63 @@ +import { getQueryState, noop, query } from '@tanstack/query-core-pluggable' +import { useQueryClient } from './QueryClientProvider' +import type { + DefaultError, + QueryClient, + QueryKey, +} from '@tanstack/query-core-pluggable' +import type { UsePrefetchQueryOptions } from './types' + +/** + * `usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before + * a suspense boundary that wraps a component that uses `useQuery(suspenseQueryOptions(...))`. You can pass everything to + * `usePrefetchQuery` that you can pass to `query`, though `queryKey` is always required, and + * `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. + * + * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left + * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's + * already there or already in flight. + * @param options - The {@link UsePrefetchQueryOptions} to use — everything you can pass to `query`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @example + * ```tsx + * import { Suspense } from 'react' + * import { usePrefetchQuery } from '@tanstack/react-query-pluggable' + * + * function App() { + * // Fire the prefetch during render, before the suspense boundary below. + * usePrefetchQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * return ( + * Loading posts...}> + * + * + * ) + * } + * ``` + */ +export function usePrefetchQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UsePrefetchQueryOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + queryClient?: QueryClient, +): void { + const client = useQueryClient(queryClient) + + if (!getQueryState(client, options.queryKey)) { + void query(client, options).catch(noop) + } +} diff --git a/packages/react-query-pluggable/src/useQueries.ts b/packages/react-query-pluggable/src/useQueries.ts new file mode 100644 index 00000000000..bc424d88cee --- /dev/null +++ b/packages/react-query-pluggable/src/useQueries.ts @@ -0,0 +1,498 @@ +'use client' +import { + QueriesObserver, + defaultQueryOptions, + getQueryCache, +} from '@tanstack/query-core-pluggable' +import * as React from 'react' +import { useIsRestoring } from './IsRestoringProvider' +import { useQueryClient } from './QueryClientProvider' +import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' +import { getHasError, prepareErrorBoundary } from './errorBoundaryUtils' +import { useObserverSnapshot } from './useObserverSnapshot' +import type { + DefaultError, + OmitKeyof, + QueriesObserverOptions, + QueriesPlaceholderDataFunction, + QueryClient, + QueryFunction, + QueryKey, + QueryObserverOptions, + Select, + placeholderData, +} from '@tanstack/query-core-pluggable' +import type { suspenseQueriesPolicy } from './suspense' +import type { + DefinedUseQueryResult, + GroupThrowOnError, + TaggedQueryError, + UseQueryOptions, + UseQueryResult, +} from './types' + +// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`. +// `placeholderData` function always gets undefined passed +type UseQueryOptionsForUseQueries< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'placeholderData' | 'subscribed' | 'throwOnError' +> & { + throwOnError?: QueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryFnData, + TQueryKey + >['throwOnError'] + placeholderData?: readonly [ + typeof placeholderData, + TQueryFnData | QueriesPlaceholderDataFunction, + ] +} + +// Avoid TS depth-limit error in case of large array literal +type MAXIMUM_DEPTH = 20 + +// Widen the type of the symbol to enable type inference even if skipToken is not immutable. +type SkipTokenForUseQueries = symbol + +type GetUseQueryOptionsForUseQueries = + // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData } + T extends { + queryFnData: infer TQueryFnData + error?: infer TError + data: infer TData + } + ? UseQueryOptionsForUseQueries + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseQueryOptionsForUseQueries + : T extends { data: infer TData; error?: infer TError } + ? UseQueryOptionsForUseQueries + : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData] + T extends [infer TQueryFnData, infer TError, infer TData] + ? UseQueryOptionsForUseQueries + : T extends [infer TQueryFnData, infer TError] + ? UseQueryOptionsForUseQueries + : T extends [infer TQueryFnData] + ? UseQueryOptionsForUseQueries + : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: Select + throwOnError?: GroupThrowOnError + } + ? UseQueryOptionsForUseQueries< + TQueryFnData, + TaggedQueryError< + T, + unknown extends TError ? DefaultError : TError + >, + unknown extends TData ? TQueryFnData : TData, + TQueryKey + > + : // Fallback + UseQueryOptionsForUseQueries + +// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult +type GetDefinedOrUndefinedQueryResult = T extends { + initialData?: infer TInitialData +} + ? unknown extends TInitialData + ? UseQueryResult + : TInitialData extends TData + ? DefinedUseQueryResult + : TInitialData extends () => infer TInitialDataResult + ? unknown extends TInitialDataResult + ? UseQueryResult + : TInitialDataResult extends TData + ? DefinedUseQueryResult + : UseQueryResult + : UseQueryResult + : UseQueryResult + +type GetUseQueryResult = + // Part 1: responsible for mapping explicit type parameter to function result, if object + T extends { queryFnData: any; error?: infer TError; data: infer TData } + ? GetDefinedOrUndefinedQueryResult + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? GetDefinedOrUndefinedQueryResult + : T extends { data: infer TData; error?: infer TError } + ? GetDefinedOrUndefinedQueryResult + : // Part 2: responsible for mapping explicit type parameter to function result, if tuple + T extends [any, infer TError, infer TData] + ? GetDefinedOrUndefinedQueryResult + : T extends [infer TQueryFnData, infer TError] + ? GetDefinedOrUndefinedQueryResult + : T extends [infer TQueryFnData] + ? GetDefinedOrUndefinedQueryResult + : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: Select + throwOnError?: GroupThrowOnError + } + ? GetDefinedOrUndefinedQueryResult< + T, + unknown extends TData ? TQueryFnData : TData, + TaggedQueryError< + T, + unknown extends TError ? DefaultError : TError + > + > + : // Fallback + UseQueryResult + +/** + * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's + * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements — past that, a tuple falls + * back to a single homogeneous options type. + * + * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally + * matches a query options object is mapped per-element instead, still inferring each entry individually; any + * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to + * that same homogeneous options type too. + * @template T - The type of the `queries` array as written at the call site. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type QueriesOptions< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseQueryOptionsForUseQueries] + : T extends [infer Head, ...infer Tails] + ? QueriesOptions< + [...Tails], + [...TResults, GetUseQueryOptionsForUseQueries], + [...TDepth, 1] + > + : ReadonlyArray extends T + ? T + : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type! + // use this to infer the param types in the case of Array.map() argument + T extends Array< + UseQueryOptionsForUseQueries< + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey + > + > + ? Array< + UseQueryOptionsForUseQueries< + TQueryFnData, + TError, + TData, + TQueryKey + > + > + : // Fallback + Array + +/** + * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each + * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped + * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a + * single homogeneous {@link UseQueryResult} type. + * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type QueriesResults< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseQueryResult] + : T extends [infer Head, ...infer Tails] + ? QueriesResults< + [...Tails], + [...TResults, GetUseQueryResult], + [...TDepth, 1] + > + : { [K in keyof T]: GetUseQueryResult } + +type UseQueriesInput, TCombinedResult> = { + /** + * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and + * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and + * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData` + * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function. + */ + queries: + | readonly [...QueriesOptions] + | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries }] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: QueriesResults) => TCombinedResult + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * The `useQueries` hook can be used to fetch a variable number of queries. + * + * The `queries` key accepts an array with query option objects mostly identical to `useQuery` — the top-level + * `subscribed` option isn't accepted per query (see `placeholderData` below for another difference). A custom + * `QueryClient` is supplied once, as `useQueries`' own top-level second argument, rather than per query. + * + * Having the same query key more than once in the array of query objects may cause some data to be shared + * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired + * structure. + * + * The `combine` option can be used to combine the results of the queries into a single value. The result will + * be structurally shared to be as referentially stable as possible. + * @param options - The `queries` array to run, and the optional `combine` and `subscribed` options. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The combined result. Without `combine`, this is an array with all the query results, in the same + * order as the input. When `combine` is provided, this is the value returned by `combine` instead. + * @throws {Error} The error of the first query that should be thrown to the nearest error boundary (see + * `throwOnError`). While suspending, it throws a promise instead. + * @remarks The `combine` function only re-runs if it changed referentially, or if any of the query results + * changed. An inlined `combine` function, as shown in the example below, therefore runs on every render — wrap + * it in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies, to + * avoid that. + * + * Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling + * `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter + * of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls + * back to `unknown` — a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate + * the `select` parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in + * a single object _before_ it reaches `useQueries`, to work around this — see the example below. The same + * limitation applies to {@link useSuspenseQueries}. + * + * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from + * previously rendered queries, because the number of queries can differ between renders. + * @example + * ```tsx + * import { useQueries } from '@tanstack/react-query-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * const postQueries = useQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * staleTime: Infinity, + * })), + * }) + * + * return ( + *
      + * {postQueries.map((query, index) => { + * if (query.status === 'pending') return
    • Loading...
    • + * if (query.status === 'error') return
    • Error: {query.error.message}
    • + * return
    • {query.data.title}
    • + * })} + *
    + * ) + * } + * ``` + * @example + * Combining results into a single value: + * ```tsx + * import { useQueries } from '@tanstack/react-query-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * const { data, isPending, isError } = useQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * combine: (postQueries) => { + * return { + * data: postQueries.map((query) => query.data), + * isPending: postQueries.some((query) => query.status === 'pending'), + * isError: postQueries.some((query) => query.status === 'error'), + * } + * }, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return 'Error loading posts' + * + * return ( + *
      + * {data.map((post) => ( + *
    • {post?.title}
    • + * ))} + *
    + * ) + * } + * ``` + * @example + * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding + * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is + * resolved before it reaches `useQueries`: + * ```tsx + * import { queryOptions, select, useQueries } from '@tanstack/react-query-pluggable' + * + * const postOptions = (id: number) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function PostTitle({ id }: { id: number }) { + * const [{ data: broken }] = useQueries({ + * queries: [ + * { + * ...postOptions(id), + * // ❌ `data` is `unknown` here + * select: [select, (data) => data.title], + * }, + * ], + * }) + * + * const [{ data: fixed }] = useQueries({ + * queries: [ + * queryOptions({ + * ...postOptions(id), + * // ✅ `data` is `Post` + * select: [select, (data) => data.title], + * }), + * ], + * }) + * + * return

    {fixed}

    + * } + * ``` + */ +export function useQueries< + T extends Array, + TCombinedResult = QueriesResults, +>( + options: UseQueriesInput, + queryClient?: QueryClient, +): TCombinedResult { + return useBaseQueries(options, queryClient) +} + +/** + * Reads and subscribes to multiple queries. The dedicated Suspense hook can + * supply a render-time policy. + * @param options - The queries, combiner, and subscription setting. + * @param queryClient - The client to use in place of the nearest provider. + * @param suspense - The policy that prepares and reads queries during render. + * @returns The individual query results or the combined result. + * @throws {Error} The first query error configured to reach the error boundary. + */ +export function useBaseQueries< + T extends Array, + TCombinedResult = QueriesResults, +>( + { queries, ...options }: UseQueriesInput, + queryClient?: QueryClient, + suspense?: typeof suspenseQueriesPolicy, +): TCombinedResult { + const client = useQueryClient(queryClient) + const isRestoring = useIsRestoring() + const errorResetBoundary = useQueryErrorResetBoundary() + const subscribed = options.subscribed !== false + + const defaultedQueries = React.useMemo( + () => + queries.map((opts) => { + const defaultedOptions = defaultQueryOptions(client, { + ...opts, + suspense: !!suspense, + } as QueryObserverOptions) + + // Make sure the results are already in fetching state before subscribing or updating options + defaultedOptions._optimisticResults = isRestoring + ? 'isRestoring' + : subscribed + ? 'optimistic' + : undefined + + return defaultedOptions + }), + [queries, client, isRestoring, subscribed, suspense], + ) + + defaultedQueries.forEach((queryOptions) => { + const query = getQueryCache(client).get(queryOptions.queryHash) + suspense?.prepare?.(queryOptions) + prepareErrorBoundary(queryOptions, errorResetBoundary, query) + }) + + React.useEffect(() => errorResetBoundary.clearReset(), [errorResetBoundary]) + + const [observer] = React.useState( + () => + new QueriesObserver( + client, + defaultedQueries, + options as QueriesObserverOptions, + ), + ) + + const reader = observer.createResultReader( + defaultedQueries, + options as QueriesObserverOptions, + ) + suspense?.readQueries(defaultedQueries, reader, client, errorResetBoundary) + + const results = useObserverSnapshot( + observer, + reader, + !isRestoring && subscribed, + refreshQueries, + ) + + const firstErrorResult = results.find((result, index) => { + const query = defaultedQueries[index] + return ( + query && + getHasError( + result, + query, + getQueryCache(client).get(query.queryHash), + errorResetBoundary, + ) + ) + }) + + if (firstErrorResult) { + throw firstErrorResult.error + } + + return reader.combineResult(results) +} + +/** + * Refreshes each query after the group subscribes. + * @param observer - The observer that was subscribed. + */ +function refreshQueries(observer: Pick): void { + observer + .getObservers() + .forEach((queryObserver) => queryObserver.updateResult()) +} diff --git a/packages/react-query-pluggable/src/useQuery.ts b/packages/react-query-pluggable/src/useQuery.ts new file mode 100644 index 00000000000..11a747a3347 --- /dev/null +++ b/packages/react-query-pluggable/src/useQuery.ts @@ -0,0 +1,164 @@ +'use client' + +import { defaultQueryOptions } from '@tanstack/query-core-pluggable' +import * as React from 'react' +import { useIsRestoring } from './IsRestoringProvider' +import { useQueryClient } from './QueryClientProvider' +import { observerKey } from './queryDescriptor' +import { useObserverSnapshot } from './useObserverSnapshot' +import type { + InfiniteData, + QueryClient, + QueryKey, + QueryObserver, +} from '@tanstack/query-core-pluggable' +import type { InfiniteQueryMode } from './infiniteQueryOptions' +import type { QueryBoundaryPolicy, QueryRenderPolicy } from './queryDescriptor' +import type { QueryMode } from './queryOptions' +import type { + AnyUseQueryOptions, + DefinedUseInfiniteQueryResult, + DefinedUseQueryResult, + UseInfiniteQueryOptions, + UseInfiniteQueryResult, + UseQueryOptions, + UseQueryResult, + UseSuspenseInfiniteQueryResult, + UseSuspenseQueryResult, +} from './types' + +/** A regular or paginated observer descriptor produced by the React option factories. */ +export type PreparedQuery = (QueryMode | InfiniteQueryMode) & { + /** The cache key attached to the prepared fetcher. */ + queryKey: QueryKey + /** The fetcher or query function token supplied to the factory. */ + queryFn: unknown + /** Whether this reader should subscribe to future updates. */ + subscribed?: boolean +} + +type HasInitialData = T extends { + initialData: TQueryData | (() => TQueryData) +} + ? true + : false + +type PreparedQueryResult = T extends InfiniteQueryMode & + UseInfiniteQueryOptions< + infer TPage, + infer TError, + infer TData, + any, + infer TPageParam + > + ? T extends { renderPolicy: { suspense: true } } + ? UseSuspenseInfiniteQueryResult + : HasInitialData> extends true + ? DefinedUseInfiniteQueryResult + : UseInfiniteQueryResult + : T extends UseQueryOptions< + infer TQueryFnData, + infer TError, + infer TData, + any + > + ? T extends { renderPolicy: { suspense: true } } + ? UseSuspenseQueryResult + : HasInitialData> extends true + ? DefinedUseQueryResult + : UseQueryResult + : T extends InfiniteQueryMode + ? UseInfiniteQueryResult + : UseQueryResult + +/** + * Reads a descriptor produced by queryOptions, suspenseQueryOptions, infiniteQueryOptions, or suspenseInfiniteQueryOptions. Its factory selects the observer and render policy. + * @param options - Query options prepared for the selected observer and render policy. + * @param queryClient - The client to use. Defaults to the nearest provider. + * @returns The result for the selected query, including pagination controls for infinite queries. + */ +export function useQuery( + options: T, + queryClient?: QueryClient, +): PreparedQueryResult + +export function useQuery( + options: PreparedQuery | null | undefined, + queryClient?: QueryClient, +) { + if (!options?.[observerKey]) { + throw new TypeError( + process.env.NODE_ENV === 'production' + ? 'Expected a query options descriptor.' + : 'Bad argument type. Pass a descriptor from queryOptions, suspenseQueryOptions, infiniteQueryOptions, or suspenseInfiniteQueryOptions.', + ) + } + + const Observer = options[observerKey] as typeof QueryObserver + const client = useQueryClient(queryClient) + const isRestoring = useIsRestoring() + + const policy: QueryRenderPolicy = options.renderPolicy + const defaulted = defaultQueryOptions(client, { + ...(options as AnyUseQueryOptions), + suspense: policy.suspense, + }) + if (process.env.NODE_ENV !== 'production' && !defaulted.queryFn) { + console.error( + `[${defaulted.queryHash}]: No query function was provided or configured in the query defaults. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`, + ) + } + const subscribed = options.subscribed !== false + defaulted._optimisticResults = isRestoring + ? 'isRestoring' + : subscribed + ? 'optimistic' + : undefined + policy.prepare?.(defaulted) + const rule = defaulted.throwOnError + const boundaryPolicy = + policy.errorBoundary ?? + (typeof rule === 'object' ? (rule[0] as QueryBoundaryPolicy) : undefined) + if (process.env.NODE_ENV !== 'production' && rule && !boundaryPolicy) + throw new TypeError( + 'Pass [throwOnError, true] or [throwOnError, predicate] to a query.', + ) + const boundary = boundaryPolicy && React.use(boundaryPolicy.context) + const handling = + boundary && boundaryPolicy.prepare(client, defaulted, boundary) + const onCommit = handling?.onCommit + React.useEffect(() => onCommit?.(), [onCommit]) + + const createObserver = () => ({ + client, + Observer, + observer: new Observer(client, defaulted), + }) + const [saved, setSaved] = React.useState(createObserver) + let current = saved + if (current.Observer !== Observer || current.client !== client) { + current = createObserver() + setSaved(current) + } + + const { observer } = current + const reader = observer.createResultReader(defaulted) + if (boundary) + policy.readQuery?.(defaulted, reader, observer, client, boundary) + const result = useObserverSnapshot( + observer, + reader, + !isRestoring && subscribed, + refreshQuery, + ) + handling?.check(result) + return defaulted.notifyOnChangeProps ? result : observer.trackResult(result) +} + +/** + * Reads updates queued between render and subscription. + * @param observer - The newly subscribed observer. + */ +function refreshQuery(observer: Pick) { + observer.updateResult() +} diff --git a/packages/react-query-pluggable/src/useSuspenseQueries.ts b/packages/react-query-pluggable/src/useSuspenseQueries.ts new file mode 100644 index 00000000000..96ca2928f22 --- /dev/null +++ b/packages/react-query-pluggable/src/useSuspenseQueries.ts @@ -0,0 +1,562 @@ +'use client' + +import { skipToken } from '@tanstack/query-core-pluggable' +import { defaultThrowOnError, suspenseQueriesPolicy } from './suspense' +import { useBaseQueries } from './useQueries' +import type { + DefaultError, + OmitKeyof, + QueriesPlaceholderDataFunction, + QueryClient, + QueryFunction, + QueryKey, + Select, + placeholderData, +} from '@tanstack/query-core-pluggable' +import type { + GroupThrowOnError, + TaggedQueryError, + UseSuspenseQueryOptions, + UseSuspenseQueryResult, +} from './types' + +// `placeholderData` functions in useQueries never receive previous query data. +type UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + UseSuspenseQueryOptions, + 'placeholderData' +> & { + placeholderData?: readonly [ + typeof placeholderData, + TQueryFnData | QueriesPlaceholderDataFunction, + ] +} + +// Avoid TS depth-limit error in case of large array literal +type MAXIMUM_DEPTH = 20 + +// Widen the type of the symbol to enable type inference even if skipToken is not immutable. +type SkipTokenForUseQueries = symbol + +type GetUseSuspenseQueryOptions = + // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData } + T extends { + queryFnData: infer TQueryFnData + error?: infer TError + data: infer TData + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends { data: infer TData; error?: infer TError } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData] + T extends [infer TQueryFnData, infer TError, infer TData] + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TData + > + : T extends [infer TQueryFnData, infer TError] + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends [infer TQueryFnData] + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: Select + throwOnError?: GroupThrowOnError + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TaggedQueryError, + TData, + TQueryKey + > + : T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + throwOnError?: GroupThrowOnError + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TaggedQueryError, + TQueryFnData, + TQueryKey + > + : // Fallback + UseSuspenseQueryOptionsForUseSuspenseQueries + +type GetUseSuspenseQueryResult = + // Part 1: responsible for mapping explicit type parameter to function result, if object + T extends { queryFnData: any; error?: infer TError; data: infer TData } + ? UseSuspenseQueryResult + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseSuspenseQueryResult + : T extends { data: infer TData; error?: infer TError } + ? UseSuspenseQueryResult + : // Part 2: responsible for mapping explicit type parameter to function result, if tuple + T extends [any, infer TError, infer TData] + ? UseSuspenseQueryResult + : T extends [infer TQueryFnData, infer TError] + ? UseSuspenseQueryResult + : T extends [infer TQueryFnData] + ? UseSuspenseQueryResult + : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: Select + throwOnError?: GroupThrowOnError + } + ? UseSuspenseQueryResult< + unknown extends TData ? TQueryFnData : TData, + TaggedQueryError< + T, + unknown extends TError ? DefaultError : TError + > + > + : T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + throwOnError?: GroupThrowOnError + } + ? UseSuspenseQueryResult< + TQueryFnData, + TaggedQueryError< + T, + unknown extends TError ? DefaultError : TError + > + > + : // Fallback + UseSuspenseQueryResult + +/** + * The `queries` array accepted by `useSuspenseQueries`. Recursively unwraps each tuple element so every + * entry's `queryFn`/`select` are inferred individually, up to 20 elements — past that, a tuple falls back to + * a single homogeneous {@link UseSuspenseQueryOptions} type. + * + * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally + * matches a query options object is mapped per-element instead, still inferring each entry individually; any + * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to + * that same homogeneous options type too. + * @template T - The type of the `queries` array as written at the call site. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type SuspenseQueriesOptions< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseSuspenseQueryOptions] + : T extends [infer Head, ...infer Tails] + ? SuspenseQueriesOptions< + [...Tails], + [...TResults, GetUseSuspenseQueryOptions], + [...TDepth, 1] + > + : Array extends T + ? T + : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type! + // use this to infer the param types in the case of Array.map() argument + T extends Array< + UseSuspenseQueryOptionsForUseSuspenseQueries< + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey + > + > + ? Array< + UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TData, + TQueryKey + > + > + : // Fallback + Array + +/** + * The result type returned by `useSuspenseQueries`, when no `combine` is provided. Mirrors + * {@link SuspenseQueriesOptions}: each tuple element's result type is inferred individually, up to 20 elements. + * A non-tuple array is mapped per-element instead, still inferring each entry individually; only past 20 + * elements does this fall back to a single homogeneous {@link UseSuspenseQueryResult} type. + * @template T - The type of the `queries` array, as inferred by {@link SuspenseQueriesOptions}. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type SuspenseQueriesResults< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseSuspenseQueryResult] + : T extends [infer Head, ...infer Tails] + ? SuspenseQueriesResults< + [...Tails], + [...TResults, GetUseSuspenseQueryResult], + [...TDepth, 1] + > + : { [K in keyof T]: GetUseSuspenseQueryResult } + +/** + * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` + * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. + * @param options - The `queries` array to run in Suspense, and an optional `combine` function. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be + * defined and `status` is either `success` or `error`. + * + * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone + * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid + * this, make sure to set a high enough `staleTime`. Cancellation does not work. + * @example + * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * // Every result is guaranteed to be defined — no pending-state check for each query needed. + * const postQueries = useSuspenseQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * }) + * + * return ( + *
      + * {postQueries.map((query) => ( + *
    • {query.data.title}
    • + * ))} + *
    + * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading posts...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + * @example + * Several different queries — use `useSuspenseQueries` instead of multiple `useQuery(suspenseQueryOptions(...))` calls, so + * they fetch in parallel rather than suspending one after another: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-pluggable' + * + * function Dashboard() { + * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * { queryKey: ['projects'], queryFn: fetchProjects }, + * ], + * }) + * + * return ( + *
    + * + * + * + *
    + * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading dashboard...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + * @example + * `combine`s the results into a single boolean, so `Refresh` only re-renders when that boolean changes, + * not on every individual query update. This overload is the only one that accepts `combine`: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-pluggable' + * + * function Refresh() { + * const anyFetching = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * ], + * combine: (results) => results.some((result) => result.fetchStatus === 'fetching'), + * }) + * + * return anyFetching ? Refreshing… : null + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading dashboard...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + */ +export function useSuspenseQueries< + T extends Array, + TCombinedResult = SuspenseQueriesResults, +>( + options: { + /** + * An array with query option objects identical to `useQuery(suspenseQueryOptions(...))`. + */ + queries: + | readonly [...SuspenseQueriesOptions] + | readonly [...{ [K in keyof T]: GetUseSuspenseQueryOptions }] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: SuspenseQueriesResults) => TCombinedResult + }, + queryClient?: QueryClient, +): TCombinedResult + +/** + * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` + * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. + * @param options - The `queries` array to run in Suspense, and an optional `combine` function. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be + * defined and `status` is either `success` or `error`. + * + * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone + * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid + * this, make sure to set a high enough `staleTime`. Cancellation does not work. + * @example + * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * // Every result is guaranteed to be defined — no pending-state check for each query needed. + * const postQueries = useSuspenseQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * }) + * + * return ( + *
      + * {postQueries.map((query) => ( + *
    • {query.data.title}
    • + * ))} + *
    + * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading posts...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + * @example + * Several different queries — use `useSuspenseQueries` instead of multiple `useQuery(suspenseQueryOptions(...))` calls, so + * they fetch in parallel rather than suspending one after another: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-pluggable' + * + * function Dashboard() { + * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * { queryKey: ['projects'], queryFn: fetchProjects }, + * ], + * }) + * + * return ( + *
    + * + * + * + *
    + * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading dashboard...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + */ +export function useSuspenseQueries< + T extends Array, + TCombinedResult = SuspenseQueriesResults, +>( + options: { + /** + * An array with query option objects identical to `useQuery(suspenseQueryOptions(...))`. + */ + queries: readonly [...SuspenseQueriesOptions] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: SuspenseQueriesResults) => TCombinedResult + }, + queryClient?: QueryClient, +): TCombinedResult + +export function useSuspenseQueries(options: any, queryClient?: QueryClient) { + return useBaseQueries( + { + ...options, + queries: options.queries.map((query: any) => { + if (process.env.NODE_ENV !== 'production') { + if (query.queryFn === skipToken) { + console.error('skipToken is not allowed for useSuspenseQueries') + } + } + + return { + ...query, + throwOnError: defaultThrowOnError, + enabled: true, + } + }), + }, + queryClient, + suspenseQueriesPolicy, + ) +} diff --git a/packages/react-query-pluggable/tests/compat-descriptors.ts b/packages/react-query-pluggable/tests/compat-descriptors.ts new file mode 100644 index 00000000000..a7e1e3266c3 --- /dev/null +++ b/packages/react-query-pluggable/tests/compat-descriptors.ts @@ -0,0 +1,11 @@ +import type { + DefaultError, + QueryErrorBoundaryOption, + QueryKey, +} from '@tanstack/query-core-pluggable' + +/** The pluggable observer also accepts an adapter-supplied boundary policy. */ +export type QueryBoundaryTuple = Exclude< + QueryErrorBoundaryOption, + false +> diff --git a/packages/react-query-pluggable/tests/compat-polling.ts b/packages/react-query-pluggable/tests/compat-polling.ts new file mode 100644 index 00000000000..8642784f3fd --- /dev/null +++ b/packages/react-query-pluggable/tests/compat-polling.ts @@ -0,0 +1,4 @@ +export type IntervalInput = Extract< + TOption, + { value: unknown } +>['value'] diff --git a/packages/react-query-pluggable/tests/compat-projection.ts b/packages/react-query-pluggable/tests/compat-projection.ts new file mode 100644 index 00000000000..05dfcbbfcdc --- /dev/null +++ b/packages/react-query-pluggable/tests/compat-projection.ts @@ -0,0 +1,39 @@ +import { placeholderData, select } from '@tanstack/query-core-pluggable' + +export type ProjectionInput = T extends readonly [unknown, infer Input] + ? Input + : T + +/** Returns the input supplied to a projection feature. */ +export function projectionInput( + option: readonly [unknown, T] | undefined, +): T | undefined { + return option?.[1] +} + +/** Preserves a shared test's optional callback when migrating a stored reference. */ +export function portSelect( + input: T, +): T extends undefined ? undefined : readonly [typeof select, T] { + return ( + input === undefined ? undefined : [select, input] + ) as T extends undefined ? undefined : readonly [typeof select, T] +} + +/** Preserves a shared test's optional placeholder when migrating a stored reference. */ +export function portPlaceholder( + input: T, +): T extends undefined ? undefined : readonly [typeof placeholderData, T] { + return ( + input === undefined ? undefined : [placeholderData, input] + ) as T extends undefined ? undefined : readonly [typeof placeholderData, T] +} + +/** A stored pluggable selection option for a shared React test. */ +export type SelectSetting = readonly [typeof select, TValue] + +/** A stored pluggable placeholder option for a shared React test. */ +export type PlaceholderSetting = readonly [ + typeof placeholderData, + TValue, +] diff --git a/packages/react-query-pluggable/tests/compat-result.ts b/packages/react-query-pluggable/tests/compat-result.ts new file mode 100644 index 00000000000..efdecf7f296 --- /dev/null +++ b/packages/react-query-pluggable/tests/compat-result.ts @@ -0,0 +1,83 @@ +import { + isError, + isFetchNextPageError, + isFetchPreviousPageError, + isFetched, + isFetching, + isFetchingNextPage, + isFetchingPreviousPage, + isLoading, + isLoadingError, + isPaused, + isPending, + isRefetchError, + isRefetching, + isSuccess, +} from '@tanstack/query-core-pluggable' +import type { + InfiniteQueryObserverResult, + QueryObserverResult, +} from '@tanstack/query-core-pluggable' + +/** The narrowed result type guaranteed by a public query predicate. */ +export type Guarded = TGuard extends (( + result: any, +) => result is infer T) + ? T + : never + +// Materialize intersections before comparing property modifiers. This preserves +// readonly properties, which the original writable-branch assertions detect. +type Properties = { [K in keyof T]: T[K] } +/** The individual properties of a result narrowed by the public predicate. */ +export type GuardedProperties = Properties> + +// For the v6 tests that pin literal flag types, compare the known result +// variant with what the real predicate accepts when it returns true. +type Possible = T extends { data: never } | { fetchDirection: never } + ? never + : T +/** Whether a result always, never, or sometimes satisfies a predicate. */ +export type FlagFor = [TResult] extends [Guarded] + ? true + : [Possible>] extends [never] + ? false + : boolean + +/** Reads a legacy expected object through the public helpers when comparing snapshots. */ +export function resultForComparison(value: unknown): unknown { + if (Array.isArray(value)) return value.map(resultForComparison) + if ( + !value || + typeof value !== 'object' || + !('dataUpdateCount' in value) || + !('refetch' in value) + ) + return value + const result = value as QueryObserverResult | InfiniteQueryObserverResult + const { dataUpdateCount: _dataUpdates, ...rest } = result + const queryFlags = { + isPending: isPending(result), + isSuccess: isSuccess(result), + isError: isError(result), + isFetching: isFetching(result), + isPaused: isPaused(result), + isLoading: isLoading(result), + isRefetching: isRefetching(result), + isLoadingError: isLoadingError(result), + isRefetchError: isRefetchError(result), + isFetched: isFetched(result), + } + if ('fetchDirection' in result && 'fetchDirection' in rest) { + const { fetchDirection: _direction, ...pages } = rest + return { + ...pages, + ...queryFlags, + isFetchingNextPage: isFetchingNextPage(result), + isFetchingPreviousPage: isFetchingPreviousPage(result), + isFetchNextPageError: isFetchNextPageError(result), + isFetchPreviousPageError: isFetchPreviousPageError(result), + } + } + return { ...rest, ...queryFlags } +} diff --git a/packages/react-query-pluggable/tests/compat-scope.ts b/packages/react-query-pluggable/tests/compat-scope.ts new file mode 100644 index 00000000000..9f77dca2c1d --- /dev/null +++ b/packages/react-query-pluggable/tests/compat-scope.ts @@ -0,0 +1 @@ +export { serialScope } from '@tanstack/query-core-pluggable' diff --git a/packages/react-query-pluggable/tests/compat-useQuery.ts b/packages/react-query-pluggable/tests/compat-useQuery.ts new file mode 100644 index 00000000000..f86bb504eed --- /dev/null +++ b/packages/react-query-pluggable/tests/compat-useQuery.ts @@ -0,0 +1,48 @@ +import { queryOptions, useQuery as usePreparedQuery } from '../src' +import type { + AnyUseQueryOptions, + DefaultError, + DefinedInitialDataOptions, + DefinedUseQueryResult, + QueryClient, + QueryKey, + UndefinedInitialDataOptions, + UseQueryOptions, + UseQueryResult, +} from '../src' + +/** Runs v6's raw-options tests through the pluggable package's public factory and hook. */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: DefinedInitialDataOptions, + client?: QueryClient, +): DefinedUseQueryResult +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UndefinedInitialDataOptions, + client?: QueryClient, +): UseQueryResult +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseQueryOptions, + client?: QueryClient, +): UseQueryResult +export function useQuery(options: AnyUseQueryOptions, client?: QueryClient) { + // The v6 bad-arguments test passes an array; exercise the real hook's diagnostic. + const prepared = Array.isArray(options) + ? (options as never) + : queryOptions(options) + return usePreparedQuery(prepared, client) +} diff --git a/packages/react-query-pluggable/tests/compat/react-query.patch b/packages/react-query-pluggable/tests/compat/react-query.patch new file mode 100644 index 00000000000..5565b32620b --- /dev/null +++ b/packages/react-query-pluggable/tests/compat/react-query.patch @@ -0,0 +1,483 @@ +diff --git a/src/__tests__/infiniteQueryOptions.test-d.tsx b/src/__tests__/infiniteQueryOptions.test-d.tsx +--- a/src/__tests__/infiniteQueryOptions.test-d.tsx ++++ b/src/__tests__/infiniteQueryOptions.test-d.tsx +@@ -59,9 +59,8 @@ + + const { data } = useInfiniteQuery(options) + +- // known issue: type of pageParams is unknown when returned from useInfiniteQuery +- expectTypeOf(data).toEqualTypeOf< +- InfiniteData | undefined ++ expectTypeOf(data).toEqualTypeOf< ++ InfiniteData | undefined + >() + }) + +@@ -76,7 +75,6 @@ + + const { data } = useInfiniteQuery(options) + +- // known issue: type of pageParams is unknown when returned from useInfiniteQuery + expectTypeOf(data).toEqualTypeOf | undefined>() + }) + +@@ -90,7 +88,7 @@ + + const { data } = useSuspenseInfiniteQuery(options) + +- expectTypeOf(data).toEqualTypeOf>() ++ expectTypeOf(data).toEqualTypeOf>() + }) + + it('should work when passed to useSuspenseInfiniteQuery with select', () => { +@@ -171,7 +169,9 @@ + initialPageParam: 1, + }) + +- expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf>() ++ expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf< ++ InfiniteData ++ >() + }) + + it('should tag the queryKey even if no promise is returned', () => { +@@ -182,7 +182,9 @@ + initialPageParam: 1, + }) + +- expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf>() ++ expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf< ++ InfiniteData ++ >() + }) + + it('should tag the queryKey with the result type of the QueryFn if select is used', () => { +@@ -194,7 +196,9 @@ + initialPageParam: 1, + }) + +- expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf>() ++ expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf< ++ InfiniteData ++ >() + }) + + it('should return the proper type when passed to getQueryData', () => { +@@ -209,7 +213,7 @@ + const data = queryClient.getQueryData(tagged) + + expectTypeOf(data).toEqualTypeOf< +- InfiniteData | undefined ++ InfiniteData | undefined + >() + }) + +@@ -224,13 +228,13 @@ + const queryClient = new QueryClient() + const data = queryClient.setQueryData(tagged, (prev) => { + expectTypeOf(prev).toEqualTypeOf< +- InfiniteData | undefined ++ InfiniteData | undefined + >() + return prev + }) + + expectTypeOf(data).toEqualTypeOf< +- InfiniteData | undefined ++ InfiniteData | undefined + >() + }) + +@@ -244,7 +248,7 @@ + }) + const { data } = useSuspenseInfiniteQuery(options) + expectTypeOf(data).toEqualTypeOf< +- InfiniteData | undefined ++ InfiniteData | undefined + >() + }) + +@@ -316,7 +320,7 @@ + + const { data } = useInfiniteQuery(options) + expectTypeOf(data).toEqualTypeOf< +- InfiniteData<{ example: boolean }, unknown> | undefined ++ InfiniteData<{ example: boolean }, number> | undefined + >() + }) + +@@ -331,7 +335,7 @@ + }) + + expectTypeOf(options.queryKey).toEqualTypeOf< +- DataTag, Error> ++ DataTag, Error> + >() + }) + +diff --git a/src/__tests__/infiniteQueryOptions.test.tsx b/src/__tests__/infiniteQueryOptions.test.tsx +--- a/src/__tests__/infiniteQueryOptions.test.tsx ++++ b/src/__tests__/infiniteQueryOptions.test.tsx +@@ -4,7 +4,7 @@ + import type { UseInfiniteQueryOptions } from '../types' + + describe('infiniteQueryOptions', () => { +- it('should return the object received as a parameter without any modification.', () => { ++ it('should create a new descriptor and preserve the supplied options', () => { + const object: UseInfiniteQueryOptions = { + queryKey: createKey(), + queryFn: () => Promise.resolve(5), +@@ -12,6 +12,8 @@ + initialPageParam: null, + } + +- expect(infiniteQueryOptions(object)).toBe(object) ++ const result = infiniteQueryOptions(object) ++ expect(result).not.toBe(object) ++ expect(result).toMatchObject(object) + }) + }) +diff --git a/src/__tests__/placeholderData.test.ts b/src/__tests__/placeholderData.test.ts +--- a/src/__tests__/placeholderData.test.ts ++++ b/src/__tests__/placeholderData.test.ts +@@ -2,6 +2,10 @@ + import { renderHook } from '@testing-library/react' + import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + import { QueryClient, useQueries, useQuery } from '..' ++import type { ++ PlaceholderSetting, ++ SelectSetting, ++} from '#compat/projection' + + class Placeholder { + constructor(readonly value: number) {} +@@ -10,8 +14,8 @@ + type Options = { + queryKey: ReadonlyArray + queryFn: () => Promise +- placeholderData: Placeholder +- select?: (data: Placeholder) => Placeholder | Set ++ placeholderData: PlaceholderSetting ++ select?: SelectSetting<(data: Placeholder) => Placeholder | Set> + } + + function useMultiple(options: Options, client: QueryClient) { +diff --git a/src/__tests__/queryOptions.test.tsx b/src/__tests__/queryOptions.test.tsx +--- a/src/__tests__/queryOptions.test.tsx ++++ b/src/__tests__/queryOptions.test.tsx +@@ -3,12 +3,14 @@ + import type { UseQueryOptions } from '../types' + + describe('queryOptions', () => { +- it('should return the object received as a parameter without any modification.', () => { ++ it('should create a new descriptor and preserve the supplied options', () => { + const object: UseQueryOptions = { + queryKey: ['key'], + queryFn: () => Promise.resolve(5), + } as const + +- expect(queryOptions(object)).toBe(object) ++ const result = queryOptions(object) ++ expect(result).not.toBe(object) ++ expect(result).toMatchObject(object) + }) + }) +diff --git a/src/__tests__/ssr-hydration.test.tsx b/src/__tests__/ssr-hydration.test.tsx +--- a/src/__tests__/ssr-hydration.test.tsx ++++ b/src/__tests__/ssr-hydration.test.tsx +@@ -13,6 +13,7 @@ + useQuery, + } from '..' + import { setIsServer } from './utils' ++import type { UseQueryResult } from '..' + + const ReactHydrate = (element: React.ReactElement, container: Element) => { + let root: any +@@ -29,7 +30,13 @@ + return value + } + +-function PrintStateComponent({ componentName, result }: any): any { ++function PrintStateComponent({ ++ componentName, ++ result, ++}: { ++ componentName: string ++ result: UseQueryResult ++}) { + return `${componentName} - status:${result.status} fetching:${result.isFetching} data:${result.data}` + } + +diff --git a/src/__tests__/useInfiniteQuery.test-d.tsx b/src/__tests__/useInfiniteQuery.test-d.tsx +--- a/src/__tests__/useInfiniteQuery.test-d.tsx ++++ b/src/__tests__/useInfiniteQuery.test-d.tsx +@@ -42,9 +42,8 @@ + getNextPageParam: () => undefined, + }) + +- // TODO: Order of generics prevents pageParams to be typed correctly. Using `unknown` for now + expectTypeOf(infiniteQuery.data).toEqualTypeOf< +- InfiniteData | undefined ++ InfiniteData | undefined + >() + }) + +@@ -95,21 +94,15 @@ + }, + }) + +- // TODO: Order of generics prevents pageParams to be typed correctly. Using `unknown` for now + expectTypeOf(infiniteQuery.data).toEqualTypeOf< +- InfiniteData | undefined ++ InfiniteData | undefined + >() + }) + }) + + describe('error booleans', () => { + it('should not be permanently `false`', () => { +- const { +- isFetchNextPageError, +- isFetchPreviousPageError, +- isLoadingError, +- isRefetchError, +- } = useInfiniteQuery({ ++ const result = useInfiniteQuery({ + queryKey: createKey(), + queryFn: ({ pageParam }) => { + return pageParam * 5 +@@ -117,6 +110,10 @@ + initialPageParam: 1, + getNextPageParam: () => undefined, + }) ++ const isFetchNextPageError = result.isFetchNextPageError ++ const isFetchPreviousPageError = result.isFetchPreviousPageError ++ const isLoadingError = result.isLoadingError ++ const isRefetchError = result.isRefetchError + + expectTypeOf(isFetchNextPageError).toEqualTypeOf() + expectTypeOf(isFetchPreviousPageError).toEqualTypeOf() +diff --git a/src/__tests__/useInfiniteQuery.test.tsx b/src/__tests__/useInfiniteQuery.test.tsx +--- a/src/__tests__/useInfiniteQuery.test.tsx ++++ b/src/__tests__/useInfiniteQuery.test.tsx +@@ -1478,21 +1481,16 @@ + + function Page() { + const fetchCountRef = React.useRef(0) +- const { +- status, +- data, +- error, +- isFetchingNextPage, +- fetchNextPage, +- hasNextPage, +- refetch, +- } = useInfiniteQuery({ ++ const result = useInfiniteQuery({ + queryKey: key, + queryFn: ({ pageParam }) => + fetchItemsWithLimit(pageParam, fetchCountRef.current++), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) ++ const { status, data, error, fetchNextPage, hasNextPage, refetch } = ++ result ++ const isFetchingNextPage = result.isFetchingNextPage + + return ( +
    +@@ -1604,16 +1604,7 @@ + const fetchCountRef = React.useRef(0) + const [isRemovedLastPage, setIsRemovedLastPage] = + React.useState(false) +- const { +- status, +- data, +- error, +- isFetching, +- isFetchingNextPage, +- fetchNextPage, +- hasNextPage, +- refetch, +- } = useInfiniteQuery({ ++ const result = useInfiniteQuery({ + queryKey: key, + queryFn: ({ pageParam }): Promise => { + const noNext = +@@ -1630,6 +1621,10 @@ + getNextPageParam: (lastPage) => lastPage.nextId, + initialPageParam: 0, + }) ++ const { status, data, error, fetchNextPage, hasNextPage, refetch } = ++ result ++ const isFetching = result.isFetching ++ const isFetchingNextPage = result.isFetchingNextPage + + return ( +
    +@@ -1803,12 +1798,14 @@ + function Page() { + const [postId, setPostId] = React.useState() + +- const { data, isFetching } = useInfiniteQuery({ ++ const result = useInfiniteQuery({ + queryKey: key, + queryFn: postId != null ? queryFn : skipToken, + initialPageParam: 0, + getNextPageParam: () => 12, + }) ++ const { data } = result ++ const isFetching = result.isFetching + + return ( +
    +diff --git a/src/__tests__/useQuery.test-d.tsx b/src/__tests__/useQuery.test-d.tsx +--- a/src/__tests__/useQuery.test-d.tsx ++++ b/src/__tests__/useQuery.test-d.tsx +@@ -279,7 +279,7 @@ + }) + + it('should narrow TData after an isSuccess check when initialData is provided as a function which can return undefined', () => { +- const { data, isSuccess } = useQuery({ ++ const result = useQuery({ + queryKey: createKey(), + queryFn: () => { + return { +@@ -289,8 +289,8 @@ + initialData: () => undefined as { wow: boolean } | undefined, + }) + +- if (isSuccess) { +- expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>() ++ if (result.isSuccess) { ++ expectTypeOf(result.data).toEqualTypeOf<{ wow: boolean }>() + } + }) + +diff --git a/src/__tests__/useQuery.test.tsx b/src/__tests__/useQuery.test.tsx +--- a/src/__tests__/useQuery.test.tsx ++++ b/src/__tests__/useQuery.test.tsx +@@ -4288,31 +4288,27 @@ + await vi.advanceTimersByTimeAsync(0) + rendered.getByText('Data: data') + +- expect(states).toMatchObject([ ++ expect( ++ states.map(({ count, state }) => ({ ++ count, ++ data: state.data, ++ isPlaceholderData: state.isPlaceholderData, ++ isSuccess: state.isSuccess, ++ })), ++ ).toStrictEqual([ + { +- state: { +- isSuccess: true, +- isPlaceholderData: true, +- data: 'placeholder', +- }, + count: 0, ++ data: 'placeholder', ++ isPlaceholderData: true, ++ isSuccess: true, + }, + { +- state: { +- isSuccess: true, +- isPlaceholderData: true, +- data: 'placeholder', +- }, + count: 1, ++ data: 'placeholder', ++ isPlaceholderData: true, ++ isSuccess: true, + }, +- { +- state: { +- isSuccess: true, +- isPlaceholderData: false, +- data: 'data', +- }, +- count: 1, +- }, ++ { count: 1, data: 'data', isPlaceholderData: false, isSuccess: true }, + ]) + }) + +@@ -4910,7 +4906,7 @@ + ) + + function Page({ enabled }: { enabled: boolean }) { +- const { error, isPending } = useQuery({ ++ const result = useQuery({ + queryKey: key, + queryFn, + enabled, +@@ -4919,6 +4915,8 @@ + refetchOnMount: false, + refetchOnWindowFocus: false, + }) ++ const { error } = result ++ const isPending = result.isPending + + if (isPending) { + return
    status: pending
    +@@ -4965,7 +4963,7 @@ + + it('should refetch when query key changed when previous status is error', async () => { + function Page({ id }: { id: number }) { +- const { error, isPending } = useQuery({ ++ const result = useQuery({ + queryKey: [id], + queryFn: () => + sleep(10).then(() => { +@@ -4980,6 +4978,8 @@ + refetchOnMount: false, + refetchOnWindowFocus: false, + }) ++ const { error } = result ++ const isPending = result.isPending + + if (isPending) { + return
    status: pending
    +@@ -5025,7 +5025,7 @@ + + it('should refetch when query key changed when switching between erroneous queries', async () => { + function Page({ id }: { id: boolean }) { +- const { error, isFetching } = useQuery({ ++ const result = useQuery({ + queryKey: [id], + queryFn: () => + sleep(10).then(() => Promise.reject(new Error('Error'))), +@@ -5034,6 +5034,8 @@ + refetchOnMount: false, + refetchOnWindowFocus: false, + }) ++ const { error } = result ++ const isFetching = result.isFetching + + if (isFetching) { + return
    status: fetching
    +diff --git a/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx b/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx +--- a/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx ++++ b/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx +@@ -14,7 +14,7 @@ + getNextPageParam: () => 1, + }) + +- expectTypeOf(data).toEqualTypeOf>() ++ expectTypeOf(data).toEqualTypeOf>() + }) + + it('should allow undefined data when queryFn can be skipToken', () => { +@@ -57,7 +57,9 @@ + placeholderData: keepPreviousData, + }) + +- expectTypeOf(query.data).toEqualTypeOf>() ++ expectTypeOf(query.data).toEqualTypeOf< ++ InfiniteData ++ >() + expectTypeOf(query.isPlaceholderData).toEqualTypeOf() + + const selected = useSuspenseInfiniteQuery({ diff --git a/packages/react-query-pluggable/tsconfig.json b/packages/react-query-pluggable/tsconfig.json new file mode 100644 index 00000000000..58e959cbe0f --- /dev/null +++ b/packages/react-query-pluggable/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "./dist-ts", + "rootDir": ".", + "jsx": "react-jsx" + }, + "include": ["src", "tests", "*.config.ts", "*.config.js", "package.json"] +} diff --git a/packages/react-query-pluggable/tsconfig.legacy.json b/packages/react-query-pluggable/tsconfig.legacy.json new file mode 100644 index 00000000000..20f2156d95b --- /dev/null +++ b/packages/react-query-pluggable/tsconfig.legacy.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "outDir": "./dist-ts/legacy" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/react-query-pluggable/tsconfig.prod.json b/packages/react-query-pluggable/tsconfig.prod.json new file mode 100644 index 00000000000..2bb29fdf02a --- /dev/null +++ b/packages/react-query-pluggable/tsconfig.prod.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "incremental": false, + "composite": false, + "rootDir": "../../" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/react-query-pluggable/tsdown.config.ts b/packages/react-query-pluggable/tsdown.config.ts new file mode 100644 index 00000000000..a486c9a8d14 --- /dev/null +++ b/packages/react-query-pluggable/tsdown.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'tsdown' +import { getTsdownConfig } from './root.tsdown.config.js' + +export default defineConfig({ + ...getTsdownConfig({ entry: ['src/index.ts'] }), + // Preserve React's client boundaries and let the consuming app remove unused plugins. + unbundle: true, +}) diff --git a/packages/react-query-pluggable/vitest.config.ts b/packages/react-query-pluggable/vitest.config.ts new file mode 100644 index 00000000000..97c015c1add --- /dev/null +++ b/packages/react-query-pluggable/vitest.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vitest/config' + +// Run the workspace core from source even when its published ESM has not been built. +const resolve = { conditions: ['@tanstack/custom-condition'] } + +export default defineConfig({ + resolve, + environments: { ssr: { resolve } }, + test: { dir: './src' }, +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 65452fc2569..d2b53b03c28 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -406,7 +406,7 @@ importers: version: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) vitest: specifier: ^5.0.5 - version: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) examples/angular/auto-refetching: dependencies: @@ -7258,6 +7258,52 @@ importers: specifier: ^6.0.3 version: 6.0.3 + integrations/react/bundle-size: + dependencies: + '@tanstack/react-query': + specifier: workspace:* + version: link:../../../packages/react-query + '@tanstack/react-query-pluggable': + specifier: workspace:* + version: link:../../../packages/react-query-pluggable + react: + specifier: 'catalog:' + version: 19.3.1 + react-dom: + specifier: 'catalog:' + version: 19.3.1(react@19.3.1) + devDependencies: + '@types/node': + specifier: ^24.19.2 + version: 24.19.2 + '@types/react': + specifier: ^19.3.0 + version: 19.3.0 + '@types/react-dom': + specifier: ^19.3.0 + version: 19.3.0(@types/react@19.3.0) + '@vitest/browser-playwright': + specifier: 5.0.5 + version: 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5) + '@vitest/ui': + specifier: 5.0.5 + version: 5.0.5(vitest@5.0.5) + playwright: + specifier: 1.65.1 + version: 1.65.1 + rollup-plugin-visualizer: + specifier: 7.1.1 + version: 7.1.1(rolldown@1.3.1)(rollup@4.65.1) + typescript: + specifier: 'catalog:' + version: 6.0.3 + vite: + specifier: ^8.3.8 + version: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) + vitest: + specifier: ^5.0.5 + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + integrations/react/next-14: dependencies: '@tanstack/react-query': @@ -7347,9 +7393,18 @@ importers: integrations/react/nodenext: dependencies: + '@tanstack/query-core': + specifier: workspace:* + version: link:../../../packages/query-core + '@tanstack/query-core-pluggable': + specifier: workspace:* + version: link:../../../packages/query-core-pluggable '@tanstack/react-query': specifier: workspace:* version: link:../../../packages/react-query + '@tanstack/react-query-pluggable': + specifier: workspace:* + version: link:../../../packages/react-query-pluggable devDependencies: '@types/react': specifier: ^19.3.0 @@ -7774,7 +7829,7 @@ importers: version: 5.1.4(supports-color@10.2.2)(typescript@6.0.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) vitest: specifier: ^5.0.5 - version: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) zone.js: specifier: ^0.16.0 version: 0.16.1 @@ -8005,6 +8060,12 @@ importers: specifier: 'catalog:' version: 6.0.3 + packages/query-core-pluggable: + devDependencies: + typescript: + specifier: 'catalog:' + version: 6.0.3 + packages/query-devtools: dependencies: '@kobalte/core': @@ -8068,7 +8129,7 @@ importers: dependencies: vitest: specifier: ^5.0.5 - version: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) devDependencies: typescript: specifier: 'catalog:' @@ -8212,6 +8273,37 @@ importers: specifier: 'catalog:' version: 6.0.3 + packages/react-query-pluggable: + dependencies: + '@tanstack/query-core-pluggable': + specifier: workspace:* + version: link:../query-core-pluggable + devDependencies: + '@eslint-react/eslint-plugin': + specifier: 'catalog:' + version: 5.28.8(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3) + '@testing-library/react': + specifier: 'catalog:' + version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@types/react': + specifier: ^19.3.0 + version: 19.3.0 + '@types/react-dom': + specifier: ^19.3.0 + version: 19.3.0(@types/react@19.3.0) + eslint-plugin-react-hooks: + specifier: 'catalog:' + version: 7.1.1(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2) + react: + specifier: 'catalog:' + version: 19.3.1 + react-dom: + specifier: 'catalog:' + version: 19.3.1(react@19.3.1) + typescript: + specifier: 'catalog:' + version: 6.0.3 + packages/solid-query: dependencies: '@tanstack/query-core': @@ -9672,6 +9764,9 @@ packages: resolution: {integrity: sha512-eBREGwDHRPHtdsg44t071GE2KRDEuJrf0J2uT5/qvJPB2+pfPZOKlx93dMZOFkE7QW5G0JWoczySD7a01Jf0iw==} engines: {node: ^22.18.0 || >=24.11.0} + '@blazediff/core@1.10.0': + resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==} + '@bomb.sh/tab@0.0.19': resolution: {integrity: sha512-dTRfo9Q9B+lbLG3JCu8a/AGQSfD2XXcFcnakQzVjSOX+VvR/s9zpsH8TlqV3iHqazniRn1Ypwd1hcRlXcu/4BA==} hasBin: true @@ -15239,6 +15334,17 @@ packages: vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 vue: ^3.2.25 || ^3.6.0-rc.10 + '@vitest/browser-playwright@5.0.5': + resolution: {integrity: sha512-lcdThFUUcMV9mGGV1SUiZXPxfjgW4CssA7o3STxzh8WK0tT2r526kc12tZIBRZfoLMwkhxjLmMXkWXONzdsDQw==} + peerDependencies: + playwright: '*' + vitest: 5.0.5 + + '@vitest/browser@5.0.5': + resolution: {integrity: sha512-IDMoZX/iZ8rkilw7weaSgN8tJ7iZ9hUv0wYoKXyiyjWjWFwLSWAY707DcVTgxTYOudWC1E3HA9LYn7kVa9a7uQ==} + peerDependencies: + vitest: 5.0.5 + '@vitest/coverage-istanbul@5.0.5': resolution: {integrity: sha512-nmbE0+e1JSH9kYEoHGp/iKCQq6+TqwvQ4EcH2zKPULOIrY7rPHxDHsipYGGr+0xMDdzCy46F8zj3edz8dsqvdg==} peerDependencies: @@ -15287,9 +15393,20 @@ packages: vite: optional: true + '@vitest/pretty-format@5.0.5': + resolution: {integrity: sha512-24sSdIlMA9DVPXnYiB9siwU0bTd887Y9jX3+vabztCSsvHwo7ipvJ/a2L3Rljw8+2rK1f5fCj3h5U9I/Jsqgbw==} + '@vitest/spy@5.0.5': resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + '@vitest/ui@5.0.5': + resolution: {integrity: sha512-dCoGUOdgmCaSB2g+WQ/spPCBkytAWdNUkFSXY4z+eYp2d8JEOY8v0uDRaJTG9qf/kTlTVZ4CuYMYMz/f1HS/qQ==} + peerDependencies: + vitest: 5.0.5 + + '@vitest/utils@5.0.5': + resolution: {integrity: sha512-/rBu7gzLDQI/SC79Tn98b5DwOgaHU/Gt4I9OVeP3YofzNaYtbImRCOJQmT1S6vOJg9gEIlWC+r3QxKkjuSa1nQ==} + '@volar/kit@2.4.28': resolution: {integrity: sha512-cKX4vK9dtZvDRaAzeoUdaAJEew6IdxHNCRrdp5Kvcl6zZOqb6jTOfk3kXkIkG3T7oTFXguEMt5+9ptyqYR84Pg==} peerDependencies: @@ -17958,8 +18075,8 @@ packages: resolution: {integrity: sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==} hasBin: true - flatted@3.4.2: - resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==} + flatted@3.4.4: + resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} flattie@1.1.1: resolution: {integrity: sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ==} @@ -20440,6 +20557,16 @@ packages: pkg-types@2.4.0: resolution: {integrity: sha512-07Fys7iVx0X6TcviMOgogM1Lk33ZyqOezMnU79S+kffWqwolG/5W9V8EgQSeYCIfFTYVgssRbnH630Oa2+soBA==} + playwright-core@1.65.1: + resolution: {integrity: sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.65.1: + resolution: {integrity: sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==} + engines: {node: '>=20'} + hasBin: true + plist@3.1.0: resolution: {integrity: sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==} engines: {node: '>=10.4.0'} @@ -20452,6 +20579,10 @@ packages: resolution: {integrity: sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w==} engines: {node: '>=4.0.0'} + pngjs@7.0.0: + resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==} + engines: {node: '>=14.19.0'} + possible-typed-array-names@1.1.0: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} @@ -23748,7 +23879,7 @@ snapshots: postcss: 8.5.32 rollup: 4.65.1 tailwindcss: 4.3.3 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) transitivePeerDependencies: - '@types/node' - '@vitejs/devtools' @@ -23812,7 +23943,7 @@ snapshots: postcss: 8.5.32 rollup: 4.65.1 tailwindcss: 4.3.3 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) transitivePeerDependencies: - '@types/node' - '@vitejs/devtools' @@ -25302,6 +25433,8 @@ snapshots: '@babel/helper-string-parser': 8.1.3 '@babel/helper-validator-identifier': 8.0.6 + '@blazediff/core@1.10.0': {} + '@bomb.sh/tab@0.0.19(cac@6.7.14)(citty@0.2.2)': optionalDependencies: cac: 6.7.14 @@ -31845,7 +31978,7 @@ snapshots: svelte: 5.57.1(@typescript-eslint/types@8.72.2) optionalDependencies: vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) '@tsconfig/svelte@5.0.8': {} @@ -32557,6 +32690,70 @@ snapshots: vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) vue: 3.5.44(typescript@6.0.3) + '@vitest/browser-playwright@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5)': + dependencies: + '@vitest/browser': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5) + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + playwright: 1.65.1 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + + '@vitest/browser-playwright@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5)': + dependencies: + '@vitest/browser': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5) + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + playwright: 1.65.1 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + + '@vitest/browser@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5)': + dependencies: + '@blazediff/core': 1.10.0 + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + '@vitest/ui': 5.0.5(vitest@5.0.5) + '@vitest/utils': 5.0.5 + magic-string: 1.4.5 + pngjs: 7.0.0 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + ws: 8.22.1 + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + + '@vitest/browser@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5)': + dependencies: + '@blazediff/core': 1.10.0 + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + '@vitest/ui': 5.0.5(vitest@5.0.5) + '@vitest/utils': 5.0.5 + magic-string: 1.4.5 + pngjs: 7.0.0 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + ws: 8.22.1 + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + '@vitest/coverage-istanbul@5.0.5(vitest@5.0.5)': dependencies: '@jridgewell/gen-mapping': 0.3.13 @@ -32568,7 +32765,7 @@ snapshots: magicast: 0.5.5 obug: 3.0.0 tinyrainbow: 3.2.0 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) '@vitest/eslint-plugin@1.6.28(@typescript-eslint/eslint-plugin@8.72.2(@typescript-eslint/parser@8.72.2(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3)(vitest@5.0.5)': dependencies: @@ -32578,7 +32775,7 @@ snapshots: optionalDependencies: '@typescript-eslint/eslint-plugin': 8.72.2(@typescript-eslint/parser@8.72.2(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3) typescript: 6.0.3 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) transitivePeerDependencies: - supports-color @@ -32622,8 +32819,28 @@ snapshots: msw: 2.15.0(@types/node@24.19.2)(typescript@6.0.3) vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) + '@vitest/pretty-format@5.0.5': + dependencies: + tinyrainbow: 3.2.0 + '@vitest/spy@5.0.5': {} + '@vitest/ui@5.0.5(vitest@5.0.5)': + dependencies: + '@vitest/utils': 5.0.5 + fflate: 0.8.3 + flatted: 3.4.4 + pathe: 2.0.3 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + + '@vitest/utils@5.0.5': + dependencies: + '@vitest/pretty-format': 5.0.5 + convert-source-map: 2.0.0 + tinyrainbow: 3.2.0 + '@volar/kit@2.4.28(typescript@6.0.3)': dependencies: '@volar/language-service': 2.4.28(typescript@6.0.3) @@ -35921,12 +36138,12 @@ snapshots: flat-cache@4.0.1: dependencies: - flatted: 3.4.2 + flatted: 3.4.4 keyv: 4.5.4 flat@5.0.2: {} - flatted@3.4.2: {} + flatted@3.4.4: {} flattie@1.1.1: {} @@ -40471,6 +40688,12 @@ snapshots: exsolve: 1.1.3 pathe: 2.0.3 + playwright-core@1.65.1: {} + + playwright@1.65.1: + dependencies: + playwright-core: 1.65.1 + plist@3.1.0: dependencies: '@xmldom/xmldom': 0.8.15 @@ -40481,6 +40704,8 @@ snapshots: pngjs@3.4.0: {} + pngjs@7.0.0: {} + possible-typed-array-names@1.1.0: {} postcss-calc@10.1.1(postcss@8.5.32): @@ -43518,7 +43743,7 @@ snapshots: optionalDependencies: vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) - vitest@5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): + vitest@5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) @@ -43536,13 +43761,15 @@ snapshots: why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 24.19.2 + '@vitest/browser-playwright': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5) '@vitest/coverage-istanbul': 5.0.5(vitest@5.0.5) + '@vitest/ui': 5.0.5(vitest@5.0.5) jsdom: 27.4.0(supports-color@10.2.2) transitivePeerDependencies: - msw optional: true - vitest@5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)): + vitest@5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) @@ -43560,12 +43787,14 @@ snapshots: why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 24.19.2 + '@vitest/browser-playwright': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5) '@vitest/coverage-istanbul': 5.0.5(vitest@5.0.5) + '@vitest/ui': 5.0.5(vitest@5.0.5) jsdom: 27.4.0(supports-color@10.2.2) transitivePeerDependencies: - msw - vitest@5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): + vitest@5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) @@ -43583,7 +43812,9 @@ snapshots: why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 24.19.2 + '@vitest/browser-playwright': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5) '@vitest/coverage-istanbul': 5.0.5(vitest@5.0.5) + '@vitest/ui': 5.0.5(vitest@5.0.5) jsdom: 27.4.0(supports-color@7.2.0) transitivePeerDependencies: - msw diff --git a/scripts/port-query-client-tests.mjs b/scripts/port-query-client-tests.mjs new file mode 100644 index 00000000000..a086c5c0f72 --- /dev/null +++ b/scripts/port-query-client-tests.mjs @@ -0,0 +1,424 @@ +// Identify removed instance methods by their upstream declarations. This keeps +// identically named methods on unrelated objects intact in the copied tests. +import path from 'node:path' +import ts from 'typescript' +import { queryResultTestPort } from './port-query-result-tests.mjs' + +const renamed = { + mount: 'mountQueryClient', + unmount: 'unmountQueryClient', + clear: 'clearQueryClient', + isFetching: 'countFetchingQueries', +} + +const cacheOperations = { + find: 'findCachedQuery', + findAll: 'findCachedQueries', + clear: 'clearQueryCache', +} +const queryOperations = { + reset: 'resetCachedQuery', + invalidate: 'invalidateCachedQuery', + getObserversCount: 'getQueryObserverCount', + isFetched: 'isQueryFetched', + isActive: 'isQueryActive', + isDisabled: 'isQueryDisabled', + isStatic: 'isQueryStatic', + isStale: 'isQueryStale', +} +const queryFactories = { + useInfiniteQuery: 'infiniteQueryOptions', + useSuspenseQuery: 'suspenseQueryOptions', + useSuspenseInfiniteQuery: 'suspenseInfiniteQueryOptions', +} + +export function queryClientTestPort( + upstream, + files, + packageName, + copies, + paths, +) { + const config = ts.readConfigFile( + path.join(upstream, 'tsconfig.json'), + ts.sys.readFile, + ) + const { options } = ts.parseJsonConfigFileContent( + config.config, + ts.sys, + upstream, + ) + // Resolve v6 symbols at their original locations, reading the adapted test + // text from the isolated project. All implementation files are read as-is. + options.paths = { ...options.paths, ...paths } + const host = ts.createCompilerHost(options) + const readFile = host.readFile + host.readFile = (name) => readFile(copies.get(name) ?? name) + const program = ts.createProgram(files, options, host) + const checker = program.getTypeChecker() + + function methodName(receiver, name) { + const declarations = + checker + .getNonNullableType(checker.getTypeAtLocation(receiver)) + .getProperty(name)?.declarations ?? [] + for (const declaration of declarations) { + if ( + !/\/query-core\/(?:src|build|dist-ts)\//.test( + declaration.getSourceFile().fileName, + ) + ) + continue + switch (declaration.parent.name?.text) { + case 'QueryClient': + return renamed[name] ?? name + case 'QueryCache': + return cacheOperations[name] + case 'Query': + return queryOperations[name] + case 'QueryObserver': + return name === 'fetchOptimistic' ? name : undefined + } + } + } + + return function port(file) { + const source = program.getSourceFile(file) + const edits = [] + const resultPort = queryResultTestPort(checker, source, edit, packageName) + const api = '__clientOperations' + let usesOperations = false + const factories = new Map() + let usesBoundaryOption = false + let usesOptionalReceiver = false + let checksArguments = false + let checksOptimisticOptions = false + function edit(start, end, text) { + edits.push({ start, end, text }) + } + function operation(name) { + usesOperations = true + return api + '.' + name + } + function typeReference(node) { + if ( + ts.isIndexedAccessTypeNode(node) && + ts.isLiteralTypeNode(node.indexType) && + ts.isStringLiteral(node.indexType.literal) && + methodName(node.objectType, node.indexType.literal.text) + ) { + return { + operation: + 'typeof ' + + operation(methodName(node.objectType, node.indexType.literal.text)), + client: api + '.QueryClient', + } + } + if ( + ts.isTypeQueryNode(node) && + ts.isQualifiedName(node.exprName) && + methodName(node.exprName.left, node.exprName.right.text) + ) { + const generic = node.typeArguments?.length + ? '<' + + node.typeArguments.map((t) => t.getText(source)).join(', ') + + '>' + : '' + return { + operation: + 'typeof ' + + operation( + methodName(node.exprName.left, node.exprName.right.text), + ) + + generic, + client: 'typeof ' + node.exprName.left.getText(source), + } + } + } + function visit(node) { + resultPort.visit(node) + if ( + (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && + node.moduleSpecifier && + ts.isStringLiteral(node.moduleSpecifier) && + node.moduleSpecifier.text === '@tanstack/query-core' + ) { + edit( + node.moduleSpecifier.getStart(), + node.moduleSpecifier.end, + JSON.stringify(packageName), + ) + return + } + if ( + ts.isImportDeclaration(node) && + source.fileName.includes('/react-query/src/__tests__/') && + node.importClause?.namedBindings && + ts.isNamedImports(node.importClause.namedBindings) + ) { + const bindings = node.importClause.namedBindings + const keep = bindings.elements.filter((entry) => { + const name = (entry.propertyName ?? entry.name).text + if (!Object.hasOwn(queryFactories, name)) return true + const symbol = checker.getSymbolAtLocation(entry.name) + const target = symbol && checker.getAliasedSymbol(symbol) + if ( + !target?.declarations?.some((d) => + d + .getSourceFile() + .fileName.endsWith('/react-query/src/' + name + '.ts'), + ) + ) + return true + factories.set(symbol, queryFactories[name]) + return false + }) + if (keep.length !== bindings.elements.length) { + if (keep.length) + edit( + bindings.getStart(), + bindings.end, + '{' + keep.map((e) => e.getText(source)).join(', ') + '}', + ) + else edit(node.getStart(), node.end, '') + return + } + } + if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) { + const factory = + factories.size && + factories.get(checker.getSymbolAtLocation(node.expression)) + // Single-query readers opt into the React boundary policy explicitly. + const options = node.arguments[0] + if ( + (node.expression.text === 'useQuery' || + factory === 'infiniteQueryOptions') && + options && + ts.isObjectLiteralExpression(options) + ) { + for (const prop of options.properties) { + if ( + ts.isPropertyAssignment(prop) && + prop.name.getText(source) === 'throwOnError' + ) { + usesBoundaryOption = true + edit( + prop.initializer.getStart(), + prop.initializer.getStart(), + '[__prepared.throwOnError, ', + ) + edit(prop.initializer.end, prop.initializer.end, ']') + } + } + } + if (factory) { + edit( + node.expression.getStart(), + node.expression.end, + '__prepared.useQuery(__prepared.' + factory, + ) + edit(node.arguments[0].end, node.arguments[0].end, ')') + } else if ( + node.expression.text === 'getSuspensePromise' && + path.basename(file) === 'suspense.test.tsx' + ) { + edit(node.arguments.pos, node.arguments.pos, 'queryClient, ') + } + } + if ( + ts.isCallExpression(node) && + ts.isPropertyAccessExpression(node.expression) + ) { + const member = node.expression + const name = methodName(member.expression, member.name.text) + if (name) { + visit(member.expression) + const generics = node.typeArguments?.length + ? '<' + + node.typeArguments.map((t) => t.getText(source)).join(', ') + + '>' + : '' + const call = + operation(name) + + generics + + '(' + + (name === 'fetchOptimistic' ? 'queryClient, ' : '') + const separator = node.arguments.length ? ', ' : '' + if (ts.isOptionalChain(member)) { + usesOptionalReceiver = true + edit(member.getStart(), member.getStart(), '__whenPresent(') + edit( + member.expression.end, + node.arguments.pos, + ', (receiver) => ' + call + 'receiver' + separator, + ) + edit(node.end, node.end, ')') + } else { + edit(member.getStart(), member.getStart(), call) + edit(member.expression.end, node.arguments.pos, separator) + } + for (const arg of node.arguments) visit(arg) + return + } + } + // Tests that inspect the old parameter tuple still check every original + // argument. The new first argument must be compatible with the receiver. + if ( + ts.isTypeReferenceNode(node) && + node.typeName.getText(source) === 'Parameters' && + node.typeArguments?.length === 1 + ) { + const target = node.typeArguments[0] + if ( + ts.isTypeQueryNode(target) && + ts.isQualifiedName(target.exprName) && + methodName(target.exprName.left, target.exprName.right.text) === + 'fetchOptimistic' + ) { + usesOperations = true + checksOptimisticOptions = true + edit( + node.getStart(), + node.end, + '__OptimisticArgs', + ) + return + } + const ref = typeReference(target) + if (ref) { + checksArguments = true + edit( + node.getStart(), + node.end, + '__OperationArgs<' + ref.operation + ', ' + ref.client + '>', + ) + return + } + } + if ( + ts.isPropertyAccessExpression(node) && + node.name.text === 'parameters' && + ts.isCallExpression(node.expression) + ) { + const assertion = node.expression, + member = assertion.arguments[0] + if ( + assertion.expression.getText(source) === 'expectTypeOf' && + member && + ts.isPropertyAccessExpression(member) && + methodName(member.expression, member.name.text) + ) { + checksArguments = true + edit( + node.getStart(), + node.end, + 'expectTypeOf<__OperationArgs>()', + ) + return + } + } + if ( + ts.isCallExpression(node) && + node.expression.getText(source) === 'expectTypeOf' && + node.arguments.length === 1 + ) { + const member = node.arguments[0] + if (ts.isPropertyAccessExpression(member)) { + const name = methodName(member.expression, member.name.text) + if (name) { + if (name === 'fetchOptimistic') { + edit( + member.getStart(), + member.end, + '() => ' + + operation(name) + + '(queryClient, ' + + member.expression.getText(source) + + ', ' + + member.expression.getText(source) + + '.options)', + ) + } else if (Object.hasOwn(queryOperations, member.name.text)) { + edit( + member.getStart(), + member.end, + '() => ' + + operation(name) + + '(' + + member.expression.getText(source) + + ')', + ) + } else { + edit(member.getStart(), member.end, operation(name)) + } + } + } + } + ts.forEachChild(node, visit) + } + visit(source) + let result = source.text + for (const { start, end, text } of edits.sort( + (a, b) => b.start - a.start || b.end - a.end, + )) { + result = result.slice(0, start) + text + result.slice(end) + } + result = resultPort.imports() + result + if (factories.size || usesBoundaryOption) + result = + "import * as __prepared from '@tanstack/react-query-pluggable'\n" + + result + if (path.basename(file) === 'queryCache.test-d.tsx') { + result = result + .replace(/^ *\| '(?:clear|find|findAll)'\n/gm, '') + .replace( + /(expectTypeOf\(__clientOperations.findCachedQuery\)\s*\.parameter\()0\)/g, + (_match, prefix) => prefix + '1)', + ) + } + if (path.basename(file) === 'query.test-d.tsx') { + // The cache entry also has a module-private symbol used to publish state updates. + // Compare its public, named API with the equivalent standalone operations removed. + const publicMembers = result.indexOf('expectTypeOf()') + if (publicMembers !== -1) { + result = + result.slice(0, publicMembers) + + result + .slice(publicMembers) + .replace( + 'expectTypeOf()', + 'expectTypeOf>()', + ) + .replace( + /^ *\| '(?:reset|invalidate|getObserversCount|isFetched|isActive|isDisabled|isStatic|isStale)'\n/gm, + '', + ) + } + } + if (!usesOperations) return result + const argumentsType = checksArguments + ? 'type __OperationArgs unknown, Client> = Parameters extends [Client, ...infer Args] ? Args : never\n' + : '' + return ( + 'import * as ' + + api + + ' from ' + + JSON.stringify(packageName) + + '\n' + + (usesOptionalReceiver + ? 'function __whenPresent(value: T | null | undefined, run: (receiver: T) => R): R | undefined { return value == null ? undefined : run(value) }\n' + : '') + + argumentsType + + (checksOptimisticOptions + ? 'type __OptimisticArgs = O extends __clientOperations.QueryObserver ? [Parameters>[2]] : never\n' + : '') + + result + ) + } +} diff --git a/scripts/port-query-projection-tests.mjs b/scripts/port-query-projection-tests.mjs new file mode 100644 index 00000000000..e29f51c731d --- /dev/null +++ b/scripts/port-query-projection-tests.mjs @@ -0,0 +1,156 @@ +// Adapt v6 option values only in the experimental copy. A tuple literal keeps +// inline selectors contextually typed by the real options factory. +import { readdirSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import ts from 'typescript' + +export function portProjectionOptions(directory) { + for (const file of readdirSync(directory, { withFileTypes: true })) { + const path = join(directory, file.name) + if (file.isDirectory()) { + portProjectionOptions(path) + continue + } + if (!/\.tsx?$/.test(file.name)) continue + const text = readFileSync(path, 'utf8') + const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true) + const edits = [] + const imports = new Set() + + function option(node) { + if ( + !ts.isObjectLiteralExpression(node.parent) || + !node.name || + !ts.isIdentifier(node.name) + ) + return + const name = node.name.text + const isSelect = name === 'select' + // The mutation-state suite also passes selectors through local variables. + if (isSelect && file.name.startsWith('useMutationState.test')) return + if ( + name === 'scope' && + ts.isPropertyAssignment(node) && + ts.isObjectLiteralExpression(node.initializer) + ) { + const [id] = node.initializer.properties + if ( + node.initializer.properties.length === 1 && + ts.isPropertyAssignment(id) && + id.name.getText(source) === 'id' + ) { + imports.add( + "import { serialScope as __serialScope } from '@tanstack/query-core-pluggable'", + ) + edits.push( + [ + node.initializer.getStart(source), + id.initializer.getStart(source), + '__serialScope(', + ], + [id.initializer.end, node.initializer.end, ')'], + ) + } + return + } + const polling = name === 'refetchInterval' + if (!isSelect && !polling && name !== 'placeholderData') return + const helper = polling + ? '__refetchInterval' + : isSelect + ? '__querySelect' + : '__queryPlaceholder' + const input = ts.isShorthandPropertyAssignment(node) + ? node.name + : node.initializer + if (polling) { + imports.add( + "import { refetchInterval as __refetchInterval } from '@tanstack/query-core-pluggable'", + ) + // Let the query options infer the callback's query and data types. + if ( + input && + ts.isArrowFunction(input) && + input.parameters.some((p) => !p.type) + ) { + function wrapDelay(value) { + edits.push( + [value.getStart(source), value.getStart(source), helper + '('], + [value.end, value.end, ')'], + ) + } + function visitReturn(child) { + if (ts.isFunctionLike(child)) return + if (ts.isReturnStatement(child) && child.expression) + wrapDelay(child.expression) + else ts.forEachChild(child, visitReturn) + } + if (ts.isBlock(input.body)) visitReturn(input.body) + else wrapDelay(input.body) + return + } + } else if ( + ts.isMethodDeclaration(node) || + (input && + (ts.isArrowFunction(input) || ts.isFunctionExpression(input)) && + input.parameters.some((p) => !p.type)) + ) { + imports.add( + 'import { ' + + name + + ' as ' + + helper + + " } from '@tanstack/query-core-pluggable'", + ) + if (ts.isMethodDeclaration(node)) { + edits.push( + [node.name.end, node.name.end, ': [' + helper + ', function'], + [node.end, node.end, ']'], + ) + } else { + edits.push( + [ + input.getStart(source), + input.getStart(source), + '[' + helper + ', ', + ], + [input.end, input.end, ']'], + ) + } + return + } + if (!input || input.getText(source) === 'undefined') return + const wrapper = polling + ? helper + : isSelect + ? 'portSelect' + : 'portPlaceholder' + if (!polling) + imports.add('import { ' + wrapper + " } from '#compat/projection'") + if (ts.isShorthandPropertyAssignment(node)) { + edits.push([node.end, node.end, ': ' + wrapper + '(' + name + ')']) + } else { + edits.push( + [input.getStart(source), input.getStart(source), wrapper + '('], + [input.end, input.end, ')'], + ) + } + } + function visit(node) { + if ( + ts.isPropertyAssignment(node) || + ts.isShorthandPropertyAssignment(node) || + ts.isMethodDeclaration(node) + ) + option(node) + ts.forEachChild(node, visit) + } + visit(source) + if (!edits.length) continue + let result = text + for (const [start, end, replacement] of edits.sort((a, b) => b[0] - a[0])) { + result = result.slice(0, start) + replacement + result.slice(end) + } + writeFileSync(path, [...imports].join('\n') + '\n' + result) + } +} diff --git a/scripts/port-query-result-tests.mjs b/scripts/port-query-result-tests.mjs new file mode 100644 index 00000000000..df97cd45e79 --- /dev/null +++ b/scripts/port-query-result-tests.mjs @@ -0,0 +1,216 @@ +import ts from 'typescript' + +const flags = new Set([ + 'isPending', + 'isSuccess', + 'isError', + 'isFetching', + 'isPaused', + 'isLoading', + 'isRefetching', + 'isLoadingError', + 'isRefetchError', + 'isFetched', + 'isFetchingNextPage', + 'isFetchingPreviousPage', + 'isFetchNextPageError', + 'isFetchPreviousPageError', +]) + +// The stock checker distinguishes query flags from mutation flags and application +// fields with the same names. Keep each original expectation and use the public +// predicate, including the narrowed result type for old literal-flag assertions. +export function queryResultTestPort(checker, source, edit, packageName) { + const api = '__queryFlags' + const imports = new Set() + let usesFlags = false + function fromQueryResult(type, name = 'isPending') { + const definite = checker.getNonNullableType(type) + return definite + .getProperty(name) + ?.declarations?.some( + (d) => + /^(?:Infinite)?QueryObserver\w*Result$/.test( + d.parent.name?.text ?? '', + ) && + /\/query-core\/(?:src|build|dist-ts)\//.test( + d.getSourceFile().fileName, + ), + ) + } + function isResultOrArray(type) { + if (fromQueryResult(type)) return true + const element = checker.getIndexTypeOfType( + checker.getNonNullableType(type), + ts.IndexKind.Number, + ) + return element && element !== type && isResultOrArray(element) + } + function containsFlag(node) { + if (ts.isPropertyAssignment(node) && flags.has(node.name.text)) return true + return ts.forEachChild(node, containsFlag) + } + function predicateType(flag, input) { + usesFlags = true + return 'typeof ' + api + '.' + flag + '<' + input + '>' + } + function valueType(input, flag) { + imports.add('type FlagFor') + return 'FlagFor<' + input + ', ' + predicateType(flag, input) + '>' + } + function extraction(node) { + if ( + !ts.isTypeReferenceNode(node) || + !node.typeArguments?.some(ts.isTypeLiteralNode) + ) + return + if ( + node.typeName.getText(source) === 'Extract' && + node.typeArguments.length === 2 + ) + return node.typeArguments + // Both observer suites also define Branch = Extract. + // Resolve the alias so its writable-branch assertions keep selecting real variants. + const alias = checker.getSymbolAtLocation(node.typeName)?.declarations?.[0] + if ( + !alias || + alias.getSourceFile() !== source || + !ts.isTypeAliasDeclaration(alias) || + alias.typeParameters?.length !== 1 || + node.typeArguments.length !== 1 || + !ts.isTypeReferenceNode(alias.type) || + alias.type.typeName.getText(source) !== 'Extract' || + alias.type.typeArguments?.length !== 2 || + alias.type.typeArguments[1].getText(source) !== + alias.typeParameters[0].name.text + ) + return + return [alias.type.typeArguments[0], node.typeArguments[0]] + } + function visit(node) { + const extracted = extraction(node) + if (extracted) { + const [input, selector] = extracted + if ( + ts.isTypeLiteralNode(selector) && + fromQueryResult(checker.getTypeAtLocation(input)) + ) { + for (const prop of selector.members) { + const name = prop.name?.getText(source) + if (!flags.has(name)) continue + if ( + name === 'isLoading' && + prop.type?.kind === ts.SyntaxKind.BooleanKeyword + ) { + edit(prop.getStart(source), prop.end, '') + } else if (prop.type?.getText(source) === 'true') { + const type = + node.typeName.getText(source) === 'Extract' + ? 'Guarded' + : 'GuardedProperties' + imports.add('type ' + type) + edit( + node.getStart(source), + node.end, + type + '<' + predicateType(name, input.getText(source)) + '>', + ) + } + } + } + } + if ( + ts.isIndexedAccessTypeNode(node) && + ts.isLiteralTypeNode(node.indexType) && + flags.has(node.indexType.literal.text) && + fromQueryResult( + checker.getTypeAtLocation(node.objectType), + node.indexType.literal.text, + ) + ) { + const flag = node.indexType.literal.text, + input = node.objectType.getText(source) + edit(node.getStart(source), node.end, valueType(input, flag)) + } + if ( + ts.isCallExpression(node) && + ts.isPropertyAccessExpression(node.expression) && + ['toMatchObject', 'toStrictEqual', 'toEqual'].includes( + node.expression.name.text, + ) + ) { + const expect = node.expression.expression + if ( + ts.isCallExpression(expect) && + expect.expression.getText(source) === 'expect' && + expect.arguments.length === 1 && + node.arguments[0] && + containsFlag(node.arguments[0]) && + isResultOrArray(checker.getTypeAtLocation(expect.arguments[0])) + ) { + imports.add('resultForComparison') + const actual = expect.arguments[0] + edit( + actual.getStart(source), + actual.getStart(source), + 'resultForComparison(', + ) + edit(actual.end, actual.end, ')') + } + } + if ( + !ts.isPropertyAccessExpression(node) || + !flags.has(node.name.text) || + !fromQueryResult( + checker.getTypeAtLocation(node.expression), + node.name.text, + ) + ) + return + const name = node.name.text, + receiver = node.expression + const expect = node.parent + if ( + // isFetched computes a boolean from counters and has no type predicate. + name !== 'isFetched' && + ts.isCallExpression(expect) && + expect.expression.getText(source) === 'expectTypeOf' && + ts.isPropertyAccessExpression(expect.parent) && + ts.isCallExpression(expect.parent.parent) && + /^(?:true|false|boolean)$/.test( + expect.parent.parent.typeArguments?.[0]?.getText(source), + ) && + ts.isIdentifier(receiver) + ) { + edit( + expect.getStart(source), + expect.end, + 'expectTypeOf<' + valueType('typeof ' + receiver.text, name) + '>()', + ) + return + } + usesFlags = true + const optional = + node.questionDotToken && + checker.getTypeAtLocation(receiver) !== + checker.getNonNullableType(checker.getTypeAtLocation(receiver)) + const prefix = optional + ? '(' + receiver.getText(source) + ' == null ? undefined : ' + : '' + edit( + receiver.getStart(source), + receiver.getStart(source), + prefix + api + '.' + name + '(', + ) + edit(receiver.end, node.end, optional ? '))' : ')') + } + return { + visit, + imports: () => + (usesFlags + ? 'import * as ' + api + ' from ' + JSON.stringify(packageName) + '\n' + : '') + + (imports.size + ? 'import { ' + [...imports].join(', ') + ' } from "#compat/result"\n' + : ''), + } +} diff --git a/scripts/react-query-compat.config.ts b/scripts/react-query-compat.config.ts new file mode 100644 index 00000000000..0f7c7e7e2f6 --- /dev/null +++ b/scripts/react-query-compat.config.ts @@ -0,0 +1,40 @@ +import { readFileSync } from 'node:fs' +import { basename, join, resolve } from 'node:path' +import { defineConfig } from 'vitest/config' +import core from '../packages/query-core/vite.config.ts' +import react from '../packages/react-query/vite.config.ts' + +const adapter = process.env.REACT_QUERY_COMPAT_ADAPTER! +const suite = basename(resolve(process.cwd(), '..')) +const isReact = suite === 'react-query' + +const base = isReact ? react : core +const { paths } = JSON.parse(readFileSync('tsconfig.json', 'utf8')) + .compilerOptions as { paths: Record } + +export default defineConfig({ + ...base, + resolve: { + ...base.resolve, + // Use the same entry points for test execution and type checking. + alias: Object.fromEntries( + Object.entries(paths).map(([name, [file]]) => [name, file]), + ), + }, + test: { + ...base.test, + name: `${basename(adapter)}/${suite}`, + // Override the relative paths inherited from the upstream project. + setupFiles: isReact ? [resolve('test-setup.ts')] : [], + coverage: { + ...base.test?.coverage, + include: [ + isReact + ? join(adapter, 'src/*.{ts,tsx}') + : join(adapter, '../query-core-pluggable/src/**/*.ts'), + ], + reportsDirectory: join(adapter, 'coverage', suite), + allowExternal: true, + }, + }, +}) diff --git a/scripts/test-react-query-compat.mjs b/scripts/test-react-query-compat.mjs new file mode 100644 index 00000000000..2b8ad52e4a0 --- /dev/null +++ b/scripts/test-react-query-compat.mjs @@ -0,0 +1,172 @@ +// Run the original runtime and type suites against the pluggable adapter. The temporary +// projects preserve the suites' relative imports without duplicating test cases. +import { execFileSync } from 'node:child_process' +import { + cpSync, + mkdirSync, + mkdtempSync, + readdirSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs' +import { createRequire } from 'node:module' +import { join, relative, resolve, sep } from 'node:path' +import { queryClientTestPort } from './port-query-client-tests.mjs' +import { portProjectionOptions } from './port-query-projection-tests.mjs' + +const adapter = process.cwd() +const repository = resolve(import.meta.dirname, '..') +const require = createRequire(import.meta.url) +const entry = join(adapter, 'src/index.ts') +const packageName = '@tanstack/react-query-pluggable' +const coreName = '@tanstack/query-core-pluggable' +const coreSource = join(repository, 'packages/query-core-pluggable/src') + +// Only adapt imports in copies of the upstream tests and their setup. The +// implementation and its workspace dependencies resolve the real core package. +function importPath(from, to) { + return './' + relative(from, to).split(sep).join('/') +} + +const args = process.argv.slice(2) +const selected = args.find((arg) => arg.startsWith('--suite='))?.slice(8) +if (selected && !['query-core', 'react-query'].includes(selected)) + throw new Error('Unknown test suite ' + selected) +for (const suite of selected ? [selected] : ['query-core', 'react-query']) { + const upstream = join(repository, 'packages', suite) + const experiment = join(repository, 'packages', suite + '-pluggable') + const cache = join(experiment, '.cache', suite) + mkdirSync(cache, { recursive: true }) + const project = mkdtempSync(join(cache, 'compat-')) + try { + const source = join(project, 'src') + const implementation = + suite === 'query-core' ? coreSource : join(adapter, 'src') + const tests = join(source, '__tests__') + const originals = join(upstream, 'src/__tests__') + cpSync(originals, tests, { recursive: true }) + // Use exactly the dependencies installed for the corresponding v6 suite. + symlinkSync( + join(upstream, 'node_modules'), + join(project, 'node_modules'), + 'junction', + ) + // Only divergent expectations need a patch. Git checks its context so an + // incompatible change to an upstream case fails the compatibility run. + execFileSync( + 'git', + [ + 'apply', + '--directory=' + relative(repository, project), + join(experiment, 'tests/compat', suite + '.patch'), + ], + { cwd: repository }, + ) + const testFiles = readdirSync(tests, { recursive: true }).filter((file) => + /\.tsx?$/.test(file), + ) + const configFiles = + suite === 'react-query' + ? [ + join(upstream, 'test-setup.ts'), + join( + repository, + 'packages/query-persist-client-core/src/createPersister.ts', + ), + ] + : [] + const copies = new Map( + testFiles.map((f) => [join(originals, f), join(tests, f)]), + ) + const compatPaths = { '#compat/*': [join(adapter, 'tests/compat-*.ts')] } + const port = queryClientTestPort( + upstream, + [...copies.keys(), ...configFiles], + coreName, + copies, + compatPaths, + ) + function copyTestModule(from, to) { + writeFileSync(to, port(from)) + } + for (const file of testFiles) + copyTestModule(join(originals, file), join(tests, file)) + portProjectionOptions(tests) + + for (const file of readdirSync(implementation, { withFileTypes: true })) { + if (!file.isFile() || !/\.tsx?$/.test(file.name)) continue + const target = importPath(source, join(implementation, file.name)) + writeFileSync(join(source, file.name), `export * from '${target}'\n`) + } + if (suite === 'react-query') { + // Exercise the same upstream cases through the required descriptor API. + const compat = join(adapter, 'tests/compat-useQuery.ts') + for (const module of ['index', 'useQuery']) { + const real = importPath(source, join(implementation, module)) + writeFileSync( + join(source, module + '.ts'), + `export * from '${real}'\nexport { useQuery } from '${importPath(source, compat)}'\n`, + ) + } + } + + const setup = join(project, 'test-setup.ts') + const persister = join(source, 'createPersister.ts') + if (suite === 'react-query') { + copyTestModule(join(upstream, 'test-setup.ts'), setup) + copyTestModule( + join( + repository, + 'packages/query-persist-client-core/src/createPersister.ts', + ), + persister, + ) + } + const tsconfig = { + extends: join(adapter, 'tsconfig.json'), + compilerOptions: { + rootDir: repository, + composite: false, + incremental: false, + emitDeclarationOnly: false, + noEmit: true, + paths: { + [packageName]: [entry], + [coreName]: [join(coreSource, 'index.ts')], + // This suite exercises only the per-query persistence implementation. + ...(suite === 'react-query' && { + '@tanstack/query-persist-client-core': [persister], + }), + ...Object.fromEntries( + ['polling', 'projection', 'scope', 'descriptors', 'result'].map( + (name) => [ + `#compat/${name}`, + [join(adapter, `tests/compat-${name}.ts`)], + ], + ), + ), + }, + }, + include: suite === 'react-query' ? ['src', setup] : ['src'], + } + writeFileSync(join(project, 'tsconfig.json'), JSON.stringify(tsconfig)) + execFileSync( + process.execPath, + [ + join(require.resolve('vitest/package.json'), '../vitest.mjs'), + 'run', + '--config', + join(import.meta.dirname, 'react-query-compat.config.ts'), + ...args.filter((arg) => !arg.startsWith('--suite=')), + ], + { + cwd: project, + stdio: 'inherit', + env: { ...process.env, REACT_QUERY_COMPAT_ADAPTER: adapter }, + }, + ) + } finally { + rmSync(project, { recursive: true, force: true }) + } +}