@blaze-cache/react-query 0.2.1-beta → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -51,9 +51,145 @@ up with TanStack's own hashing, so a custom `queryKeyHashFn` is honoured.
51
51
  paint.
52
52
  * Renders never touch cache statistics: the pre-fetch lookup prefers `peek` over `get`,
53
53
  so StrictMode's double render cannot move the hit rate or influence eviction.
54
+ * That holds for events too — `peek` emits nothing, so renders are silent; the writes the
55
+ mirror performs surface as `set` events on the shared cache:
56
+
57
+ ```ts
58
+ cache.on('set', ({ key }) => console.log('mirrored', key));
59
+ ```
60
+
61
+ `on` returns its own unsubscribe function; the full event table is in the
62
+ [repository README](https://github.com/blaze-cache/blaze-cache#events).
54
63
  * Error states stay in TanStack — only data crosses into the cache.
55
64
  * TanStack owns freshness *within* a session; Blaze Cache owns it *across* sessions.
56
65
 
66
+ ## API
67
+
68
+ The integration is one cache + a set of hooks, helpers and hydration functions. All of
69
+ them take `(cache, client?, options?)` — the cache first, then the `QueryClient` (from
70
+ context when omitted by a hook), then the options.
71
+
72
+ | Export | What it does |
73
+ | --- | --- |
74
+ | `createBlazeQueryClient` / `syncBlazeQueryCache` | Mirror TanStack cache writes into the Blaze Cache (see [Behaviour](#behaviour)). |
75
+ | `useBlazeQuery` | `useQuery` seeded from the mirror. |
76
+ | `useBlazeInfiniteQuery` | `useInfiniteQuery` seeded with the whole `InfiniteData` (all pages) as `initialData`. |
77
+ | `useBlazeQueries` | `useQueries` over several keys, each seeded independently. |
78
+ | `useBlazeMutation` | `useMutation` that invalidates queries after success. |
79
+ | `prefetchBlazeQuery` | Imperatively seed + prefetch, mirroring the fetched result. |
80
+ | `setBlazeQueryData` | Write data through to the mirror (TanStack first, then Blaze). |
81
+ | `invalidateBlazeQueries` | Invalidate in TanStack **and** purge the mirror. |
82
+ | `removeBlazeQueries` | Remove from TanStack **and** purge the mirror. |
83
+ | `dehydrateBlazeQueryClient` / `hydrateBlazeQueryClient` | Serialize / restore the mirror as a TanStack `DehydratedState`. |
84
+
85
+ ## Example usage
86
+
87
+ ### `useBlazeQuery` — instant first paint
88
+
89
+ ```tsx
90
+ import { useBlazeQuery } from '@blaze-cache/react-query';
91
+
92
+ function Todos({ userId }: { userId: string }) {
93
+ const todos = useBlazeQuery(cache, {
94
+ queryKey: ['todos', userId],
95
+ queryFn: () => api.get('/todos', { userId }).then((r) => r.data),
96
+ });
97
+ // renders cached data immediately; refetches stale data in the background
98
+ }
99
+ ```
100
+
101
+ ### `useBlazeInfiniteQuery` — instant first paint for infinite lists
102
+
103
+ ```tsx
104
+ const feed = useBlazeInfiniteQuery(cache, {
105
+ queryKey: ['feed', userId],
106
+ queryFn: ({ pageParam }) => api.get('/feed', { userId, pageParam }),
107
+ initialPageParam: 0,
108
+ getNextPageParam: (lastPage) => lastPage.nextCursor,
109
+ });
110
+ // feed.data?.pages — every page cached before the reload, immediately
111
+ ```
112
+
113
+ The whole `InfiniteData` payload (pages + page params) is mirrored as one entry and seeded
114
+ back as `initialData`, with the original `dataUpdatedAt`, so the first paint after a reload
115
+ shows all previously loaded pages while TanStack still refetches.
116
+
117
+ ### `useBlazeQueries` — parallel instant first paint
118
+
119
+ ```tsx
120
+ const [profile, settings, notifications] = useBlazeQueries(cache, {
121
+ queries: [
122
+ { queryKey: ['profile', userId], queryFn: () => api.profile(userId) },
123
+ { queryKey: ['settings'], queryFn: () => api.settings },
124
+ { queryKey: ['notifications', userId], queryFn: () => api.notifications(userId) },
125
+ ],
126
+ });
127
+ ```
128
+
129
+ ### `useBlazeMutation` — keep the mirror in sync after writes
130
+
131
+ ```tsx
132
+ const addTodo = useBlazeMutation(cache, {
133
+ mutationFn: (text: string) => api.post('/todos', { userId, text }),
134
+ invalidate: { queryKey: ['todos', userId] }, // or { tags: ['todos', `user:${userId}`] }
135
+ onSuccess: (data) => toast('Todo added'),
136
+ });
137
+ ```
138
+
139
+ On success the mutation invalidates the given queries — TanStack marks them stale (active
140
+ ones refetch) and the matching persisted records are purged, so a reload cannot paint
141
+ pre-write data. Your own `onSuccess` still runs first, and invalidation is skipped if it
142
+ throws.
143
+
144
+ ### `prefetchBlazeQuery` — warm the mirror before navigation
145
+
146
+ ```ts
147
+ await prefetchBlazeQuery(cache, queryClient, {
148
+ queryKey: ['todos', userId],
149
+ queryFn: () => api.get('/todos', { userId }).then((r) => r.data),
150
+ staleTime: 5 * 60_000, // serve within the window from the mirror
151
+ });
152
+ ```
153
+
154
+ ### `setBlazeQueryData` — write through to the mirror
155
+
156
+ ```ts
157
+ setBlazeQueryData(cache, queryClient, ['settings', userId], settings, {
158
+ tags: ['settings', `user:${userId}`],
159
+ });
160
+ ```
161
+
162
+ ### `invalidateBlazeQueries` / `removeBlazeQueries` — purge persisted data on writes
163
+
164
+ ```ts
165
+ // After a mutation that changes a list:
166
+ await invalidateBlazeQueries(cache, queryClient, { queryKey: ['todos', userId] });
167
+ // …or by tag, which also covers queries from earlier sessions:
168
+ invalidateBlazeQueries(cache, queryClient, { tags: ['todos', `user:${userId}`] });
169
+
170
+ removeBlazeQueries(cache, queryClient, { tags: ['todos', `user:${userId}`] }); // after logout
171
+ removeBlazeQueries(cache, queryClient); // every mirror record — and only those
172
+ ```
173
+
174
+ Purges are scoped to **mirror records** (the `dataUpdatedAt` shape TanStack writes), so on
175
+ a cache shared with `@blaze-cache/axios`, `@blaze-cache/fetch` or `@blaze-cache/swr` they
176
+ leave other integrations' entries alone — including unfiltered calls and tag purges, even
177
+ when a caller domain tag (`'todos'`) is one the other integrations also use. The selection
178
+ enumerates `entries()`, so the concrete `BlazeCache` (or anything with `entries`) is
179
+ required for tag and non-exact-key filters.
180
+
181
+ ### `dehydrateBlazeQueryClient` / `hydrateBlazeQueryClient` — server-side persistence
182
+
183
+ ```ts
184
+ // Server: serialize whatever the mirror holds for this request.
185
+ const dehydratedState = dehydrateBlazeQueryClient(cache);
186
+
187
+ // Client: restore into the (synced) client, then keep it persisted again.
188
+ hydrateBlazeQueryClient(cache, queryClient, dehydratedState, {
189
+ tags: ['ssr', `user:${userId}`],
190
+ });
191
+ ```
192
+
57
193
  ## Documentation
58
194
 
59
195
  Setup and the full integration reference live in the
@@ -63,6 +199,7 @@ Setup and the full integration reference live in the
63
199
 
64
200
  * [`@blaze-cache/core`](https://www.npmjs.com/package/@blaze-cache/core) — the cache itself
65
201
  * [`@blaze-cache/axios`](https://www.npmjs.com/package/@blaze-cache/axios) — HTTP adapter
202
+ * [`@blaze-cache/fetch`](https://www.npmjs.com/package/@blaze-cache/fetch) — drop-in `fetch()` replacement
66
203
 
67
204
  ## License
68
205
 
@@ -0,0 +1,74 @@
1
+ import type { DehydratedState, HydrateOptions, QueryClient } from '@tanstack/react-query';
2
+ import type { BlazeMirrorOptions, BlazeQueryCacheLike, BlazeQueryRecord } from './types.js';
3
+ /** Options for {@link dehydrateBlazeQueryClient}. */
4
+ export interface DehydrateBlazeOptions {
5
+ /**
6
+ * Transforms each record's `data` before it lands in the snapshot — the same escape
7
+ * hatch as TanStack's `DehydrateOptions.serializeData`, for data that is not
8
+ * JSON-serializable as-is (Dates, Map, class instances).
9
+ */
10
+ serializeData?: (data: unknown) => unknown;
11
+ /**
12
+ * Include only records this predicate accepts — filter by key, tag (via
13
+ * `cache.entries()`), age (`dataUpdatedAt`), anything readable from the record.
14
+ *
15
+ * ```ts
16
+ * dehydrateBlazeQueryClient(cache, {
17
+ * predicate: (record) => record.dataUpdatedAt > Date.now() - 60_000,
18
+ * });
19
+ * ```
20
+ */
21
+ predicate?: (record: BlazeQueryRecord, queryHash: string) => boolean;
22
+ }
23
+ /** Options for {@link hydrateBlazeQueryClient}. */
24
+ export interface HydrateBlazeOptions extends BlazeMirrorOptions {
25
+ /** Forwarded to TanStack's `hydrate` — per-query defaults, `deserializeData`, … */
26
+ defaultOptions?: HydrateOptions['defaultOptions'];
27
+ }
28
+ /**
29
+ * Builds a TanStack `DehydratedState` from the persisted Blaze mirror alone — no
30
+ * `QueryClient` involved.
31
+ *
32
+ * Every live record that carries a `queryKey` becomes a `DehydratedQuery` filed under its
33
+ * mirror key (which *is* the query hash), with `dataUpdatedAt` preserved so the restored
34
+ * session's staleness arithmetic matches the original one. Embed the result in server
35
+ * markup and call {@link hydrateBlazeQueryClient} on the client for a first paint with
36
+ * zero network and zero re-read of IndexedDB.
37
+ *
38
+ * ```ts
39
+ * const state = dehydrateBlazeQueryClient(cache);
40
+ * // … in the server response:
41
+ * `<script>window.__HYDRATED__ = ${JSON.stringify(state)}</script>`;
42
+ * ```
43
+ *
44
+ * Rejections follow the package's rule of never under-delivering silently: records written
45
+ * before `queryKey` existed cannot be rebuilt and are skipped (they still seed the hooks
46
+ * directly), and a cache without `entries()` throws rather than returning a hollow
47
+ * snapshot.
48
+ *
49
+ * Infinite queries round trip too: the record's `queryType` is carried through, so
50
+ * `hydrate` rebuilds them as infinite queries with all their pages intact.
51
+ */
52
+ export declare function dehydrateBlazeQueryClient(cache: BlazeQueryCacheLike, options?: DehydrateBlazeOptions): DehydratedState;
53
+ /**
54
+ * Restores a `DehydratedState` into a `QueryClient` **and** persists it in the Blaze
55
+ * Cache — the counterpart to {@link dehydrateBlazeQueryClient}, and the durable half of
56
+ * TanStack's plain `hydrate`.
57
+ *
58
+ * TanStack's hydration is in-session only: its result lives in the query cache and dies
59
+ * with the tab. This writes each restored query back into the mirror as well (self-
60
+ * describing `queryKey`/`queryType`, original `dataUpdatedAt`, per-call `ttlMs`/`tags`),
61
+ * so the state you just hydrated is what the *next* session paints from — which is
62
+ * exactly the server-payload flow: hydrate on arrival, persist for the reload after.
63
+ *
64
+ * The mirror write reads each query back from TanStack **after** hydration, so whatever
65
+ * `deserializeData` produced and TanStack's "keep the newer data" rule are what gets
66
+ * persisted — TanStack remains the source of truth for the values.
67
+ *
68
+ * ```ts
69
+ * const state = JSON.parse(window.__HYDRATED__) as DehydratedState;
70
+ * hydrateBlazeQueryClient(cache, client, state, { tags: ['ssr', 'user:42'] });
71
+ * ```
72
+ */
73
+ export declare function hydrateBlazeQueryClient(cache: BlazeQueryCacheLike, client: QueryClient, dehydratedState: Partial<DehydratedState>, options?: HydrateBlazeOptions): void;
74
+ //# sourceMappingURL=hydration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration.d.ts","sourceRoot":"","sources":["../src/hydration.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAI1F,OAAO,KAAK,EACV,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EACjB,MAAM,YAAY,CAAC;AAKpB,qDAAqD;AACrD,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,aAAa,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,OAAO,CAAC;IAC3C;;;;;;;;;OASG;IACH,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC;CACtE;AAED,mDAAmD;AACnD,MAAM,WAAW,mBAAoB,SAAQ,kBAAkB;IAC7D,mFAAmF;IACnF,cAAc,CAAC,EAAE,cAAc,CAAC,gBAAgB,CAAC,CAAC;CACnD;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,mBAAmB,EAC1B,OAAO,GAAE,qBAA0B,GAClC,eAAe,CA6CjB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,mBAAmB,EAC1B,MAAM,EAAE,WAAW,EACnB,eAAe,EAAE,OAAO,CAAC,eAAe,CAAC,EACzC,OAAO,CAAC,EAAE,mBAAmB,GAC5B,IAAI,CAuBN"}
@@ -0,0 +1,107 @@
1
+ import { hydrate } from '@tanstack/react-query';
2
+ import { isMirrorRecord } from './record.js';
3
+ import { DEFAULT_TAGS, DEFAULT_TTL_MS } from './sync.js';
4
+ /**
5
+ * Builds a TanStack `DehydratedState` from the persisted Blaze mirror alone — no
6
+ * `QueryClient` involved.
7
+ *
8
+ * Every live record that carries a `queryKey` becomes a `DehydratedQuery` filed under its
9
+ * mirror key (which *is* the query hash), with `dataUpdatedAt` preserved so the restored
10
+ * session's staleness arithmetic matches the original one. Embed the result in server
11
+ * markup and call {@link hydrateBlazeQueryClient} on the client for a first paint with
12
+ * zero network and zero re-read of IndexedDB.
13
+ *
14
+ * ```ts
15
+ * const state = dehydrateBlazeQueryClient(cache);
16
+ * // … in the server response:
17
+ * `<script>window.__HYDRATED__ = ${JSON.stringify(state)}</script>`;
18
+ * ```
19
+ *
20
+ * Rejections follow the package's rule of never under-delivering silently: records written
21
+ * before `queryKey` existed cannot be rebuilt and are skipped (they still seed the hooks
22
+ * directly), and a cache without `entries()` throws rather than returning a hollow
23
+ * snapshot.
24
+ *
25
+ * Infinite queries round trip too: the record's `queryType` is carried through, so
26
+ * `hydrate` rebuilds them as infinite queries with all their pages intact.
27
+ */
28
+ export function dehydrateBlazeQueryClient(cache, options = {}) {
29
+ if (!cache.entries) {
30
+ throw new Error('[blaze-cache/react-query] Dehydrating the mirror must enumerate every persisted ' +
31
+ 'entry, but the cache does not implement `entries()`. Refusing to return an ' +
32
+ 'empty snapshot.');
33
+ }
34
+ const queries = [];
35
+ for (const entry of cache.entries()) {
36
+ // Shape gate first: a cache shared with another integration can hold foreign values,
37
+ // and only a mirror record carries the `data`/`dataUpdatedAt` pair a dehydrated query
38
+ // needs — an axios body would dehydrate as data dated `undefined`. Pre-`queryKey`
39
+ // records still skip, as before: they cannot be rebuilt into a TanStack query.
40
+ if (!isMirrorRecord(entry.value))
41
+ continue;
42
+ const record = entry.value;
43
+ if (record.queryKey === undefined)
44
+ continue;
45
+ if (options.predicate && !options.predicate(record, entry.key))
46
+ continue;
47
+ queries.push({
48
+ queryHash: entry.key,
49
+ queryKey: record.queryKey,
50
+ // Freshness comes from `dataUpdatedAt`; `dehydratedAt` is simply "now", as in
51
+ // TanStack's own `dehydrateQuery`.
52
+ dehydratedAt: Date.now(),
53
+ ...(record.queryType ? { queryType: record.queryType } : null),
54
+ state: {
55
+ data: options.serializeData ? options.serializeData(record.data) : record.data,
56
+ dataUpdateCount: 1,
57
+ dataUpdatedAt: record.dataUpdatedAt,
58
+ error: null,
59
+ errorUpdateCount: 0,
60
+ errorUpdatedAt: 0,
61
+ fetchFailureCount: 0,
62
+ fetchFailureReason: null,
63
+ fetchMeta: null,
64
+ isInvalidated: false,
65
+ status: 'success',
66
+ fetchStatus: 'idle',
67
+ },
68
+ });
69
+ }
70
+ return { mutations: [], queries };
71
+ }
72
+ /**
73
+ * Restores a `DehydratedState` into a `QueryClient` **and** persists it in the Blaze
74
+ * Cache — the counterpart to {@link dehydrateBlazeQueryClient}, and the durable half of
75
+ * TanStack's plain `hydrate`.
76
+ *
77
+ * TanStack's hydration is in-session only: its result lives in the query cache and dies
78
+ * with the tab. This writes each restored query back into the mirror as well (self-
79
+ * describing `queryKey`/`queryType`, original `dataUpdatedAt`, per-call `ttlMs`/`tags`),
80
+ * so the state you just hydrated is what the *next* session paints from — which is
81
+ * exactly the server-payload flow: hydrate on arrival, persist for the reload after.
82
+ *
83
+ * The mirror write reads each query back from TanStack **after** hydration, so whatever
84
+ * `deserializeData` produced and TanStack's "keep the newer data" rule are what gets
85
+ * persisted — TanStack remains the source of truth for the values.
86
+ *
87
+ * ```ts
88
+ * const state = JSON.parse(window.__HYDRATED__) as DehydratedState;
89
+ * hydrateBlazeQueryClient(cache, client, state, { tags: ['ssr', 'user:42'] });
90
+ * ```
91
+ */
92
+ export function hydrateBlazeQueryClient(cache, client, dehydratedState, options) {
93
+ hydrate(client, dehydratedState, options?.defaultOptions ? { defaultOptions: options.defaultOptions } : undefined);
94
+ for (const dehydrated of dehydratedState.queries ?? []) {
95
+ const query = client.getQueryCache().get(dehydrated.queryHash);
96
+ const data = query?.state.data;
97
+ if (!query || data === undefined)
98
+ continue; // nothing landed — nothing to persist
99
+ cache.set(dehydrated.queryHash, {
100
+ data,
101
+ dataUpdatedAt: query.state.dataUpdatedAt,
102
+ queryKey: dehydrated.queryKey,
103
+ ...(query.queryType === 'infinite' ? { queryType: 'infinite' } : null),
104
+ }, { ttlMs: options?.ttlMs ?? DEFAULT_TTL_MS, tags: options?.tags ?? DEFAULT_TAGS });
105
+ }
106
+ }
107
+ //# sourceMappingURL=hydration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration.js","sourceRoot":"","sources":["../src/hydration.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,101 @@
1
+ import type { DefaultError, FetchQueryOptions, QueryClient, QueryKey } from '@tanstack/react-query';
2
+ import type { BlazeMirrorOptions, BlazeQueryCacheLike, BlazeQueryFilters } from './types.js';
3
+ /**
4
+ * The options {@link prefetchBlazeQuery} accepts: TanStack's own `FetchQueryOptions` plus
5
+ * how the fetched result should be stamped into the Blaze Cache.
6
+ */
7
+ export interface BlazeFetchQueryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> extends FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey> {
8
+ /** TTL for the mirror entry. Defaults to the same 24 h the sync layer uses. */
9
+ ttlMs?: number;
10
+ /** Tags for the mirror entry. Defaults to `['react-query']`. */
11
+ tags?: readonly string[];
12
+ }
13
+ /**
14
+ * `prefetchQuery` that starts from the Blaze Cache.
15
+ *
16
+ * Mirrors {@link useBlazeQuery} imperatively: the persisted record is seeded as
17
+ * `initialData` with its original `dataUpdatedAt` before prefetching, so a `staleTime`
18
+ * window can be satisfied from disk without touching the network at all. When a fetch
19
+ * does run, its result is written back to the mirror under the same record (tags, TTL and
20
+ * self-describing `queryKey` included) — even on a client with no sync layer attached.
21
+ *
22
+ * Errors are swallowed exactly like TanStack's `prefetchQuery`.
23
+ *
24
+ * ```ts
25
+ * await prefetchBlazeQuery(cache, client, {
26
+ * queryKey: ['todos', userId],
27
+ * queryFn: () => fetchTodos(userId),
28
+ * staleTime: 5 * 60_000,
29
+ * tags: ['todos', `user:${userId}`],
30
+ * });
31
+ * ```
32
+ */
33
+ export declare function prefetchBlazeQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(cache: BlazeQueryCacheLike, client: QueryClient, options: BlazeFetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<void>;
34
+ /**
35
+ * `setQueryData` that also writes the Blaze Cache mirror.
36
+ *
37
+ * The TanStack write goes through first (so its exact `dataUpdatedAt` — and structural
38
+ * sharing, which may keep the previous object — is what both caches record), then the
39
+ * mirror is written synchronously under the resolved query hash, tagged per `options`.
40
+ * With a sync layer attached, its batched write sees this identical record and leaves the
41
+ * helper's `ttlMs`/`tags` in place.
42
+ *
43
+ * `data` is a plain value, not an updater — pass a function to TanStack's own
44
+ * `client.setQueryData` when you need to read the previous value first. `undefined` is
45
+ * ignored on both sides, exactly as TanStack ignores it.
46
+ *
47
+ * ```ts
48
+ * setBlazeQueryData(cache, client, ['settings', userId], settings, {
49
+ * tags: ['settings', `user:${userId}`],
50
+ * });
51
+ * ```
52
+ *
53
+ * @returns The stored data, or `undefined` when `data` was `undefined`.
54
+ */
55
+ export declare function setBlazeQueryData<TData = unknown, TQueryKey extends QueryKey = QueryKey>(cache: BlazeQueryCacheLike, client: QueryClient, queryKey: TQueryKey, data: TData, options?: BlazeMirrorOptions): TData | undefined;
56
+ /**
57
+ * `invalidateQueries` for both caches at once: TanStack marks the matching queries stale
58
+ * (active ones refetch, as usual), and the matching **persisted** records are purged so a
59
+ * reload cannot paint pre-invalidation data.
60
+ *
61
+ * Keeping the mirror entry instead would defeat the call — `dataUpdatedAt` is TanStack's
62
+ * staleness clock, and a persisted record would come back as `initialData` on the next
63
+ * session regardless of when it was invalidated. In-session behaviour is untouched:
64
+ * the refetched results re-mirror themselves through the sync layer, stale-while-revalidate
65
+ * included. This mirrors the sync layer's own contract that *explicit* purges remove
66
+ * mirror entries (see {@link syncBlazeQueryCache}).
67
+ *
68
+ * Filters work on both sides; see {@link BlazeQueryFilters} for how `tags`, keys and
69
+ * query-state selectors combine. Purging by tag or by non-exact key needs
70
+ * `cache.entries` — both **throw** when it is absent rather than under-delivering.
71
+ * (Tag purges deliberately enumerate rather than call `cache.invalidateTags`: the core's
72
+ * tag index is one global namespace, so that call would reach other integrations' entries
73
+ * on a shared cache. Enumeration keeps the purge on mirror records — see
74
+ * {@link isMirrorRecord}.)
75
+ *
76
+ * ```ts
77
+ * await invalidateBlazeQueries(cache, client, { queryKey: ['todos', userId] });
78
+ * await invalidateBlazeQueries(cache, client, { tags: [`user:${userId}`] });
79
+ * ```
80
+ *
81
+ * @returns Resolves like TanStack's `invalidateQueries` — once the triggered refetches settle.
82
+ */
83
+ export declare function invalidateBlazeQueries(cache: BlazeQueryCacheLike, client: QueryClient, filters?: BlazeQueryFilters): Promise<void>;
84
+ /**
85
+ * `removeQueries` for both caches at once: TanStack drops the matching queries outright,
86
+ * and the matching persisted records are purged — the explicit-purge half of the sync
87
+ * layer's contract (see {@link syncBlazeQueryCache}).
88
+ *
89
+ * The same mirror-side rules and rejections as {@link invalidateBlazeQueries} apply; the
90
+ * difference between the two helpers is what happens on TanStack's side (dropped vs.
91
+ * marked stale), not what happens in the mirror.
92
+ *
93
+ * ```ts
94
+ * // After a logout — including queries from earlier sessions TanStack never loaded:
95
+ * removeBlazeQueries(cache, client, { tags: [`user:${userId}`] });
96
+ * // Every mirror record — and only those, so foreign entries on a shared cache stay:
97
+ * removeBlazeQueries(cache, client);
98
+ * ```
99
+ */
100
+ export declare function removeBlazeQueries(cache: BlazeQueryCacheLike, client: QueryClient, filters?: BlazeQueryFilters): void;
101
+ //# sourceMappingURL=imperative.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"imperative.d.ts","sourceRoot":"","sources":["../src/imperative.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,YAAY,EACZ,iBAAiB,EACjB,WAAW,EAEX,QAAQ,EAET,MAAM,uBAAuB,CAAC;AAM/B,OAAO,KAAK,EAEV,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,YAAY,CAAC;AAEpB;;;GAGG;AACH,MAAM,WAAW,sBAAsB,CACrC,YAAY,GAAG,OAAO,EACtB,MAAM,GAAG,YAAY,EACrB,KAAK,GAAG,YAAY,EACpB,SAAS,SAAS,QAAQ,GAAG,QAAQ,CACrC,SAAQ,iBAAiB,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC;IACjE,+EAA+E;IAC/E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gEAAgE;IAChE,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC1B;AA6ID;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,kBAAkB,CACtC,YAAY,GAAG,OAAO,EACtB,MAAM,GAAG,YAAY,EACrB,KAAK,GAAG,YAAY,EACpB,SAAS,SAAS,QAAQ,GAAG,QAAQ,EAErC,KAAK,EAAE,mBAAmB,EAC1B,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,sBAAsB,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,GACtE,OAAO,CAAC,IAAI,CAAC,CAoBf;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,GAAG,OAAO,EAAE,SAAS,SAAS,QAAQ,GAAG,QAAQ,EACtF,KAAK,EAAE,mBAAmB,EAC1B,MAAM,EAAE,WAAW,EACnB,QAAQ,EAAE,SAAS,EACnB,IAAI,EAAE,KAAK,EACX,OAAO,CAAC,EAAE,kBAAkB,GAC3B,KAAK,GAAG,SAAS,CAanB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,mBAAmB,EAC1B,MAAM,EAAE,WAAW,EACnB,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,IAAI,CAAC,CAGf;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,mBAAmB,EAC1B,MAAM,EAAE,WAAW,EACnB,OAAO,GAAE,iBAAsB,GAC9B,IAAI,CAGN"}