@tanstack/solid-query 6.0.0-rc.4 → 6.0.0-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/dev.cjs CHANGED
@@ -1,899 +1,1516 @@
1
- 'use strict';
2
-
3
- var queryCore = require('@tanstack/query-core');
4
- var solidJs = require('solid-js');
5
- var web = require('@solidjs/web');
6
- var serverFunctions = require('@solidjs/web/server-functions');
7
-
8
- // src/index.ts
9
- exports.QueryClient = class QueryClient extends queryCore.QueryClient {
10
- constructor(config = {}) {
11
- super(config);
12
- }
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _tanstack_query_core = require("@tanstack/query-core");
3
+ let solid_js = require("solid-js");
4
+ let _solidjs_web = require("@solidjs/web");
5
+ let _solidjs_web_server_functions = require("@solidjs/web/server-functions");
6
+ // src/QueryClient.ts
7
+ /**
8
+ * The core `@tanstack/query-core` `QueryClient`, typed with Solid's {@link QueryClientConfig}.
9
+ */
10
+ var QueryClient = class extends _tanstack_query_core.QueryClient {
11
+ constructor(config = {}) {
12
+ super(config);
13
+ }
13
14
  };
14
- var isServer = typeof window === "undefined";
15
- var HYDRATION_KEY_PREFIX = "sq:";
16
- exports.FLIGHT_DATA_SOURCE = "sq";
17
- var REVALIDATE_ALL = "*";
15
+ // src/QueryClientProvider.tsx
16
+ const isServer$3 = typeof window === "undefined";
17
+ /**
18
+ * The query cache's single-flight source id. Mutation responses can fold
19
+ * fresh data for multiple caches at once (Solid's multi-source
20
+ * single-flight protocol); this is the slice the query cache claims — the
21
+ * provider subscribes its consumer under it, and server collectors
22
+ * register under it to produce the data:
23
+ *
24
+ * ```ts
25
+ * import { registerFlightDataSource } from '@solidjs/web/server-functions/server'
26
+ * import { FLIGHT_DATA_SOURCE, dehydrate } from '@tanstack/solid-query'
27
+ *
28
+ * registerFlightDataSource(FLIGHT_DATA_SOURCE, async (event, outcome) => {
29
+ * // rebuild the data for outcome.targetUrl into a QueryClient, then
30
+ * return dehydrate(queryClient)
31
+ * })
32
+ * ```
33
+ *
34
+ * The slice's payload is a `DehydratedState`; the provider consumes it
35
+ * with `hydrate()`, so every mounted query on those keys updates before
36
+ * the mutation's promise resolves — no follow-up refetches.
37
+ *
38
+ * A mutation can additionally declare its invalidation SCOPE with
39
+ * `X-Revalidate` keys (the `revalidate` option of Solid's `reload`/
40
+ * `redirect`/`respond` response helpers). The payload covers the slice of
41
+ * that scope the server could recompute; whatever a declared key matches
42
+ * beyond it is swept client-side (see the consumer below). The transport
43
+ * delivers a response carrying keys to the consumer whether or not the
44
+ * collector contributed a slice — with no slice, the whole scope is swept.
45
+ */
46
+ const FLIGHT_DATA_SOURCE = "sq";
47
+ /**
48
+ * The reserved `X-Revalidate` key meaning every entry: `revalidate: '*'`
49
+ * on Solid's response helpers. Named so a host that keys its cache
50
+ * differently still reads the same spelling as "all".
51
+ */
52
+ const REVALIDATE_ALL = "*";
53
+ /**
54
+ * The client half of key-scoped invalidation. A mutation declares its
55
+ * invalidation scope with `X-Revalidate` keys; the flight payload covers
56
+ * the part of that scope the server's collector recomputed (typically the
57
+ * target page's loader graph). Whatever a declared key matches BEYOND the
58
+ * payload — parameterized instances only this client holds, queries no
59
+ * loader owns — is invalidated here: active queries refetch in the
60
+ * background, inactive ones are marked stale for their next mount. This
61
+ * mirrors how Solid Router consumes the same header for its own cache.
62
+ *
63
+ * A key matches by queryKey prefix — `revalidate: 'users'` sweeps every
64
+ * query whose key begins with `'users'`. Payload-covered hashes are exempt:
65
+ * they hydrated with fresh data a moment ago, and refetching them would
66
+ * spend the round trip single flight just saved. The payload is absent
67
+ * when the server folded no slice for this cache (no collector registered,
68
+ * a redirect leaving the app) — then nothing is covered and the declared
69
+ * scope is swept in full.
70
+ *
71
+ * The header's three states are three scopes. Absent: the mutation
72
+ * declared nothing, and this cache is left as it is — the route data the
73
+ * router reloads is its own business, and a response helper without
74
+ * `revalidate` is a host-default that Solid Router reads as "everything"
75
+ * but the query cache does not presume. Empty (`revalidate: []`): nothing,
76
+ * explicitly. The reserved key `*` (`revalidate: '*'`): every query in the
77
+ * cache, minus what the payload covered — the way to say "all" to any
78
+ * host, rather than relying on one host's default.
79
+ * @param client - The `QueryClient` whose queries are invalidated.
80
+ * @param payload - The dehydrated slice the response carried for this cache, if any.
81
+ * @param response - The mutation response, read for its `X-Revalidate` header.
82
+ */
18
83
  function sweepRevalidatedQueries(client, payload, response) {
19
- const declared = response.headers.get(web.REVALIDATE_HEADER);
20
- if (declared === null) return;
21
- const covered = new Set(payload?.queries.map((query) => query.queryHash) ?? []);
22
- const uncovered = (query) => !covered.has(query.queryHash);
23
- const keys = declared.split(",");
24
- if (keys.includes(REVALIDATE_ALL)) {
25
- client.invalidateQueries({
26
- predicate: uncovered
27
- }).catch(() => void 0);
28
- return;
29
- }
30
- for (const key of keys) {
31
- if (!key) continue;
32
- client.invalidateQueries({
33
- queryKey: [key],
34
- predicate: uncovered
35
- }).catch(() => void 0);
36
- }
84
+ const declared = response.headers.get(_solidjs_web.REVALIDATE_HEADER);
85
+ if (declared === null) return;
86
+ const covered = new Set(payload?.queries.map((query) => query.queryHash) ?? []);
87
+ const uncovered = (query) => !covered.has(query.queryHash);
88
+ const keys = declared.split(",");
89
+ if (keys.includes(REVALIDATE_ALL)) {
90
+ client.invalidateQueries({ predicate: uncovered }).catch(() => void 0);
91
+ return;
92
+ }
93
+ for (const key of keys) {
94
+ if (!key) continue;
95
+ client.invalidateQueries({
96
+ queryKey: [key],
97
+ predicate: uncovered
98
+ }).catch(() => void 0);
99
+ }
37
100
  }
38
- exports.QueryClientContext = solidJs.createContext(null);
39
- exports.useQueryClient = (queryClient) => {
40
- if (queryClient) {
41
- return queryClient;
42
- }
43
- const client = solidJs.useContext(exports.QueryClientContext);
44
- if (!client) {
45
- throw new Error("No QueryClient set, use QueryClientProvider to set one");
46
- }
47
- return client();
101
+ const QueryClientContext = (0, solid_js.createContext)(null);
102
+ /**
103
+ * The `useQueryClient` primitive returns the current `QueryClient` instance.
104
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
105
+ * be used.
106
+ * @returns The current `QueryClient` instance.
107
+ * @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the
108
+ * component tree.
109
+ */
110
+ const useQueryClient = (queryClient) => {
111
+ if (queryClient) return queryClient;
112
+ const client = (0, solid_js.useContext)(QueryClientContext);
113
+ if (!client) throw new Error("No QueryClient set, use QueryClientProvider to set one");
114
+ return client();
48
115
  };
116
+ /**
117
+ * The props accepted by `QueryClientProvider`.
118
+ */
119
+ /**
120
+ * Server side of hydration: serialize every query the request touches into
121
+ * Solid's hydration registry, content-addressed by query hash (the Solid
122
+ * Router `query()` pattern). Serialization happens at fetch-DISPATCH time —
123
+ * synchronously, while the request's serialization context is live — by
124
+ * handing seroval the fetch promise; it streams the `{ data, t }` payload
125
+ * whenever the fetch settles. Settled entries (initialData, setQueryData,
126
+ * loader prefetches that already landed) serialize their value directly.
127
+ *
128
+ * Content addressing is what makes this cover MORE than rendered
129
+ * components: a query prefetched in a loader and never read by any
130
+ * component still transfers, and any client hook (hydrating or mounted
131
+ * long after) finds it by hash. One entry per hash regardless of how many
132
+ * hooks read it; the payload object is the same reference the data nodes
133
+ * serialize, so seroval's cross-reference dedupe emits it once.
134
+ * @param client - The request's `QueryClient`.
135
+ */
49
136
  function serializeCacheOnServer(client) {
50
- const ctx = solidJs.sharedConfig.context;
51
- if (!ctx || !ctx.async || ctx.noHydrate) return;
52
- const cache = client.getQueryCache();
53
- const shouldDehydrateQuery = client.getDefaultOptions().dehydrate?.shouldDehydrateQuery;
54
- const seen = /* @__PURE__ */ new Set();
55
- const serializeQuery = (query) => {
56
- if (seen.has(query.queryHash)) return;
57
- if (shouldDehydrateQuery && !shouldDehydrateQuery(query)) return;
58
- const state = query.state;
59
- if (state.status === "success") {
60
- seen.add(query.queryHash);
61
- ctx.serialize(HYDRATION_KEY_PREFIX + query.queryHash, {
62
- data: state.data,
63
- t: state.dataUpdatedAt
64
- });
65
- } else if (state.fetchStatus !== "idle") {
66
- const promise = query.promise;
67
- if (!promise) return;
68
- seen.add(query.queryHash);
69
- ctx.serialize(HYDRATION_KEY_PREFIX + query.queryHash, promise.then(() => ({
70
- data: query.state.data,
71
- t: query.state.dataUpdatedAt
72
- })));
73
- }
74
- };
75
- for (const query of cache.getAll()) serializeQuery(query);
76
- solidJs.onCleanup(cache.subscribe((event) => serializeQuery(event.query)));
137
+ const writer = (0, _solidjs_web.getHydrationWriter)();
138
+ if (!writer || !writer.async || !(0, solid_js.isHydratable)()) return;
139
+ const cache = client.getQueryCache();
140
+ const shouldDehydrateQuery = client.getDefaultOptions().dehydrate?.shouldDehydrateQuery;
141
+ const seen = /* @__PURE__ */ new Set();
142
+ const serializeQuery = (query) => {
143
+ if (seen.has(query.queryHash)) return;
144
+ if (shouldDehydrateQuery && !shouldDehydrateQuery(query)) return;
145
+ const state = query.state;
146
+ if (state.status === "success") {
147
+ seen.add(query.queryHash);
148
+ writer.write("sq:" + query.queryHash, {
149
+ data: state.data,
150
+ t: state.dataUpdatedAt
151
+ });
152
+ } else if (state.fetchStatus !== "idle") {
153
+ const promise = query.promise;
154
+ if (!promise) return;
155
+ seen.add(query.queryHash);
156
+ writer.write("sq:" + query.queryHash, promise.then(() => ({
157
+ data: query.state.data,
158
+ t: query.state.dataUpdatedAt
159
+ })));
160
+ }
161
+ };
162
+ for (const query of cache.getAll()) serializeQuery(query);
163
+ (0, solid_js.onCleanup)(cache.subscribe((event) => serializeQuery(event.query)));
77
164
  }
78
- exports.QueryClientProvider = (props) => {
79
- props.client.mount();
80
- solidJs.onCleanup(() => props.client.unmount());
81
- if (isServer) {
82
- serializeCacheOnServer(props.client);
83
- solidJs.onCleanup(() => {
84
- props.client.cancelQueries().catch(() => void 0);
85
- props.client.clear();
86
- });
87
- } else {
88
- solidJs.onCleanup(serverFunctions.subscribeFlightData(exports.FLIGHT_DATA_SOURCE, (data, context) => {
89
- queryCore.hydrate(props.client, data);
90
- sweepRevalidatedQueries(props.client, data, context.response);
91
- }));
92
- }
93
- return web.createComponent(exports.QueryClientContext, {
94
- value: () => props.client,
95
- get children() {
96
- return props.children;
97
- }
98
- });
165
+ /**
166
+ * Provides the QueryClient and manages its mount lifecycle. On the server
167
+ * it also registers the cache serializer above; on the client, hooks prime
168
+ * the cache from their hash-keyed registry entries themselves (see
169
+ * `useBaseQuery`) and the provider subscribes the cache's single-flight
170
+ * consumer: mutation responses carrying a `FLIGHT_DATA_SOURCE` slice (a
171
+ * `DehydratedState` produced by a server collector registered under the
172
+ * same id) hydrate this client before the mutation's promise resolves.
173
+ * Subscribing is inert when no server collector exists — the server just
174
+ * folds nothing — so it is unconditional. One consumer per source: with
175
+ * nested providers, the innermost mounted one owns the slice.
176
+ * @param props - The `client` to provide, and the `children` that get access to it.
177
+ * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
178
+ */
179
+ const QueryClientProvider = (props) => {
180
+ props.client.mount();
181
+ (0, solid_js.onCleanup)(() => props.client.unmount());
182
+ if (isServer$3) {
183
+ serializeCacheOnServer(props.client);
184
+ (0, solid_js.onCleanup)(() => {
185
+ props.client.cancelQueries().catch(() => void 0);
186
+ props.client.clear();
187
+ });
188
+ } else (0, solid_js.onCleanup)((0, _solidjs_web_server_functions.subscribeFlightData)("sq", (data, context) => {
189
+ if (data) (0, _tanstack_query_core.hydrate)(props.client, data);
190
+ sweepRevalidatedQueries(props.client, data, context.response);
191
+ }));
192
+ return (0, _solidjs_web.createComponent)(QueryClientContext, {
193
+ value: () => props.client,
194
+ get children() {
195
+ return props.children;
196
+ }
197
+ });
99
198
  };
100
- exports.IsRestoringContext = solidJs.createContext(() => false);
101
- exports.useIsRestoring = () => solidJs.useContext(exports.IsRestoringContext);
102
-
199
+ // src/isRestoring.ts
200
+ const IsRestoringContext = (0, solid_js.createContext)(() => false);
201
+ /**
202
+ * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` primitive alongside it to
203
+ * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid
204
+ * race conditions between the restore and mounting queries.
205
+ * @returns An accessor that reads `true` while a persisted client is being restored, `false` otherwise.
206
+ */
207
+ const useIsRestoring = () => (0, solid_js.useContext)(IsRestoringContext);
103
208
  // src/useBaseQuery.ts
104
- var isServer2 = typeof window === "undefined";
105
- var NEVER = new Promise(queryCore.noop);
209
+ const isServer$2 = typeof window === "undefined";
210
+ /**
211
+ * A read of a pending-idle query (disabled, or reset with nothing in flight)
212
+ * has no value and nothing to wait on. Parking the reader on a promise that
213
+ * never resolves suspends it into the nearest `<Loading>` boundary until the
214
+ * query actually starts fetching (enabling it, a refetch, a cache write) —
215
+ * at which point the version bump re-runs the compute and the superseded
216
+ * in-flight is ignored by the engine.
217
+ */
218
+ const NEVER = new Promise(_tanstack_query_core.noop);
219
+ /**
220
+ * Copies the scalar fields of a query's state, leaving out `data` and `fetchMeta`.
221
+ * @param state - The query state to copy from.
222
+ * @returns The scalar metadata.
223
+ */
106
224
  function metaFrom(state) {
107
- return {
108
- dataUpdateCount: state.dataUpdateCount,
109
- dataUpdatedAt: state.dataUpdatedAt,
110
- error: state.error,
111
- errorUpdateCount: state.errorUpdateCount,
112
- errorUpdatedAt: state.errorUpdatedAt,
113
- fetchFailureCount: state.fetchFailureCount,
114
- fetchFailureReason: state.fetchFailureReason,
115
- fetchStatus: state.fetchStatus,
116
- isInvalidated: state.isInvalidated,
117
- status: state.status
118
- };
225
+ return {
226
+ dataUpdateCount: state.dataUpdateCount,
227
+ dataUpdatedAt: state.dataUpdatedAt,
228
+ error: state.error,
229
+ errorUpdateCount: state.errorUpdateCount,
230
+ errorUpdatedAt: state.errorUpdatedAt,
231
+ fetchFailureCount: state.fetchFailureCount,
232
+ fetchFailureReason: state.fetchFailureReason,
233
+ fetchStatus: state.fetchStatus,
234
+ isInvalidated: state.isInvalidated,
235
+ status: state.status
236
+ };
119
237
  }
238
+ /**
239
+ * Base Query Function that is used to create the query.
240
+ * @param options - A function that returns the query options.
241
+ * @param Observer - The observer class from query-core (`QueryObserver` or
242
+ * `InfiniteQueryObserver`).
243
+ * @param queryClient - A function that returns a custom `QueryClient`. Otherwise, the one from the
244
+ * nearest context is used.
245
+ * @returns The reactive query result.
246
+ */
120
247
  function useBaseQuery(options, Observer, queryClient) {
121
- return useBaseQueryLayer(options, Observer, queryClient).result;
248
+ return useBaseQueryLayer(options, Observer, queryClient).result;
122
249
  }
250
+ /**
251
+ * Builds the read layer behind `useBaseQuery` and exposes its internals to hooks that extend it.
252
+ * @param options - A function that returns the query options.
253
+ * @param Observer - The observer class from query-core (`QueryObserver` or
254
+ * `InfiniteQueryObserver`).
255
+ * @param queryClient - A function that returns a custom `QueryClient`. Otherwise, the one from the
256
+ * nearest context is used.
257
+ * @returns The query result, with the observer, the version-tracked query accessor, the defaulted
258
+ * options, and the `isFetching` and `status` accessors.
259
+ */
123
260
  function useBaseQueryLayer(options, Observer, queryClient) {
124
- const client = solidJs.createMemo(() => exports.useQueryClient(queryClient?.()));
125
- const isRestoring = exports.useIsRestoring();
126
- let latestHash;
127
- let latestOptions;
128
- const defaultedOptions = solidJs.createMemo(() => {
129
- const defaulted = client().defaultQueryOptions(options());
130
- defaulted._optimisticResults = isRestoring() ? "isRestoring" : "optimistic";
131
- if (isServer2) {
132
- defaulted.retry = false;
133
- defaulted.throwOnError = true;
134
- }
135
- latestHash = defaulted.queryHash;
136
- latestOptions = defaulted;
137
- return defaulted;
138
- });
139
- let observer = solidJs.untrack(() => new Observer(client(), defaultedOptions()));
140
- solidJs.createRenderEffect(
141
- () => defaultedOptions(),
142
- (opts) => observer.setOptions(opts)
143
- );
144
- const hydratedMount = !isServer2 && solidJs.sharedConfig.hydrating === true;
145
- const [version, setVersion] = solidJs.createSignal(0, { ownedWrite: true });
146
- const [primed, setPrimed] = solidJs.createSignal(!hydratedMount, {
147
- ownedWrite: true
148
- });
149
- const onCacheEvent = (event) => {
150
- if (event.query.queryHash === solidJs.untrack(defaultedOptions).queryHash || event.query.queryHash === latestHash) {
151
- setVersion((v) => v + 1);
152
- }
153
- };
154
- let observerSub = null;
155
- let cacheSub = null;
156
- let disposed = false;
157
- let shouldAttach = false;
158
- let activeClient = solidJs.untrack(client);
159
- let lastQuery;
160
- const attach = () => {
161
- if (!disposed && !observerSub && !solidJs.untrack(isRestoring)) {
162
- shouldAttach = true;
163
- observerSub = observer.subscribe(queryCore.noop);
164
- }
165
- };
166
- const syncClient = (c) => {
167
- if (isServer2 || c === activeClient) return;
168
- activeClient = c;
169
- lastQuery = void 0;
170
- cacheSub?.();
171
- cacheSub = c.getQueryCache().subscribe(onCacheEvent);
172
- observerSub?.();
173
- observerSub = null;
174
- observer = new Observer(c, solidJs.untrack(defaultedOptions));
175
- if (shouldAttach && !disposed && !solidJs.untrack(isRestoring)) {
176
- observerSub = observer.subscribe(queryCore.noop);
177
- }
178
- };
179
- const prime = (entry) => {
180
- if (entry != null && typeof entry === "object" && (entry.t ?? 0) > 0) {
181
- const c = solidJs.untrack(client);
182
- const opts = solidJs.untrack(defaultedOptions);
183
- solidJs.runWithOwner(
184
- null,
185
- () => queryCore.hydrate(c, {
186
- mutations: [],
187
- queries: [
188
- {
189
- queryKey: opts.queryKey,
190
- queryHash: opts.queryHash,
191
- dehydratedAt: entry.t,
192
- ...opts.meta && { meta: opts.meta },
193
- ...opts._type && {
194
- queryType: opts._type
195
- },
196
- state: {
197
- data: entry.data,
198
- dataUpdatedAt: entry.t,
199
- dataUpdateCount: 1,
200
- error: null,
201
- errorUpdateCount: 0,
202
- errorUpdatedAt: 0,
203
- fetchFailureCount: 0,
204
- fetchFailureReason: null,
205
- fetchMeta: null,
206
- isInvalidated: false,
207
- status: "success",
208
- fetchStatus: "idle"
209
- }
210
- }
211
- ]
212
- })
213
- );
214
- }
215
- };
216
- if (!isServer2) {
217
- cacheSub = activeClient.getQueryCache().subscribe(onCacheEvent);
218
- const sc = solidJs.sharedConfig;
219
- const registryKey = HYDRATION_KEY_PREFIX + solidJs.untrack(defaultedOptions).queryHash;
220
- const primeAndAttach = (entry) => {
221
- prime(entry);
222
- setPrimed(true);
223
- attach();
224
- };
225
- const settle = hydratedMount ? primeAndAttach : prime;
226
- if (sc.has?.(registryKey)) {
227
- const entry = sc.load(registryKey);
228
- delete globalThis._$HY.r[registryKey];
229
- if (entry != null && typeof entry === "object") {
230
- if (entry.s === 1) settle(entry.v);
231
- else if (entry.s === 2) settle();
232
- else if (typeof entry.then === "function")
233
- entry.then(settle, () => settle());
234
- else settle(entry);
235
- } else {
236
- settle(entry);
237
- }
238
- } else if (hydratedMount) {
239
- primeAndAttach();
240
- }
241
- if (!hydratedMount) {
242
- solidJs.createRenderEffect(
243
- () => isRestoring(),
244
- (restoring) => {
245
- if (!restoring) attach();
246
- }
247
- );
248
- }
249
- solidJs.onCleanup(() => {
250
- disposed = true;
251
- observerSub?.();
252
- observerSub = null;
253
- cacheSub?.();
254
- cacheSub = null;
255
- });
256
- }
257
- const query = () => {
258
- version();
259
- const c = client();
260
- syncClient(c);
261
- const cache = c.getQueryCache();
262
- const opts = defaultedOptions();
263
- const existing = cache.get(
264
- opts.queryHash
265
- );
266
- if (existing) return lastQuery = existing;
267
- if (lastQuery?.queryHash === opts.queryHash) return lastQuery;
268
- return lastQuery = cache.build(c, opts);
269
- };
270
- const isEnabled = () => {
271
- const opts = defaultedOptions();
272
- const enabled = typeof opts.enabled === "function" ? opts.enabled(solidJs.untrack(query)) : opts.enabled;
273
- return enabled !== false;
274
- };
275
- const resolvePlaceholder = (opts) => {
276
- const placeholder = opts.placeholderData;
277
- if (placeholder === void 0) return void 0;
278
- return typeof placeholder === "function" ? placeholder() : placeholder;
279
- };
280
- let chained = null;
281
- const chainOnce = (base, select, wrap) => {
282
- if (chained?.base !== base || chained.select !== select) {
283
- chained = { base, select, value: base.then(wrap) };
284
- }
285
- return chained.value;
286
- };
287
- const computeData = (prev) => {
288
- const opts = defaultedOptions();
289
- const q = query();
290
- const state = q.state;
291
- const select = opts.select;
292
- const wrap = (d) => ({
293
- value: select ? select(d) : d
294
- });
295
- if (state.data === void 0 && state.status === "pending") {
296
- const placeholder = resolvePlaceholder(opts);
297
- if (placeholder !== void 0) return wrap(placeholder);
298
- }
299
- if (state.fetchStatus !== "idle") {
300
- if (state.data === void 0 || prev !== void 0) {
301
- const promise = q.promise;
302
- if (promise) return chainOnce(promise, select, wrap);
303
- }
304
- }
305
- if (state.status === "error") {
306
- if (state.data === void 0 || queryCore.shouldThrowError(opts.throwOnError, [
307
- state.error,
308
- q
309
- ])) {
310
- throw state.error;
311
- }
312
- }
313
- if (state.data !== void 0) return wrap(state.data);
314
- if (isEnabled()) {
315
- if (!isServer2 && solidJs.sharedConfig.hydrating) {
316
- return NEVER;
317
- }
318
- if (!primed()) {
319
- return NEVER;
320
- }
321
- if (isRestoring()) {
322
- return NEVER;
323
- }
324
- if (!isServer2) observer.setOptions(opts);
325
- return chainOnce(q.fetch(opts), select, wrap);
326
- }
327
- if (isServer2) return { value: void 0 };
328
- return NEVER;
329
- };
330
- const dataStore = solidJs.createProjection(
331
- (draft) => computeData(draft.value),
332
- {},
333
- {
334
- key: solidJs.untrack(() => options().reconcile),
335
- deferStream: solidJs.untrack(() => options().deferStream)
336
- }
337
- );
338
- const data = () => dataStore.value;
339
- const serverMeta = () => {
340
- if (query().state.status === "pending" && isEnabled()) data();
341
- return metaFrom(query().state);
342
- };
343
- const metaProjection = solidJs.createProjection(
344
- (draft) => {
345
- Object.assign(draft, metaFrom(query().state));
346
- },
347
- solidJs.untrack(() => metaFrom(query().state))
348
- );
349
- const meta = isServer2 ? new Proxy({}, {
350
- get: (_, key) => serverMeta()[key]
351
- }) : metaProjection;
352
- const mountedAt = isServer2 ? {
353
- get dataUpdateCount() {
354
- return solidJs.untrack(query).state.dataUpdateCount;
355
- },
356
- get errorUpdateCount() {
357
- return solidJs.untrack(query).state.errorUpdateCount;
358
- }
359
- } : solidJs.untrack(() => {
360
- const state = query().state;
361
- return {
362
- dataUpdateCount: state.dataUpdateCount,
363
- errorUpdateCount: state.errorUpdateCount
364
- };
365
- });
366
- const hasPlaceholder = () => meta.status === "pending" && solidJs.untrack(() => resolvePlaceholder(defaultedOptions())) !== void 0;
367
- const status = () => hasPlaceholder() ? "success" : meta.status;
368
- const isPending = () => status() === "pending";
369
- const isFetching = () => meta.fetchStatus === "fetching" || solidJs.isPending(() => data());
370
- const isError = () => status() === "error";
371
- const isStale = () => {
372
- const opts = defaultedOptions();
373
- const q = solidJs.untrack(query);
374
- const staleTime = typeof opts.staleTime === "function" ? opts.staleTime(q) : opts.staleTime;
375
- version();
376
- return q.isStaleByTime(staleTime);
377
- };
378
- const result = {
379
- get data() {
380
- return data();
381
- },
382
- get error() {
383
- return meta.error;
384
- },
385
- get status() {
386
- return status();
387
- },
388
- get fetchStatus() {
389
- return meta.fetchStatus;
390
- },
391
- get isPending() {
392
- return isPending();
393
- },
394
- get isSuccess() {
395
- return status() === "success";
396
- },
397
- get isError() {
398
- return isError();
399
- },
400
- get isLoading() {
401
- return isPending() && isFetching();
402
- },
403
- get isFetching() {
404
- return isFetching();
405
- },
406
- get isRefetching() {
407
- return isFetching() && !isPending();
408
- },
409
- get isPaused() {
410
- return meta.fetchStatus === "paused";
411
- },
412
- get isEnabled() {
413
- return isEnabled();
414
- },
415
- get isLoadingError() {
416
- return isError() && meta.dataUpdatedAt === 0;
417
- },
418
- get isRefetchError() {
419
- return isError() && meta.dataUpdatedAt !== 0;
420
- },
421
- get isPlaceholderData() {
422
- return hasPlaceholder();
423
- },
424
- get isStale() {
425
- return isStale();
426
- },
427
- get isFetched() {
428
- return meta.dataUpdateCount > 0 || meta.errorUpdateCount > 0;
429
- },
430
- get isFetchedAfterMount() {
431
- return meta.dataUpdateCount > mountedAt.dataUpdateCount || meta.errorUpdateCount > mountedAt.errorUpdateCount;
432
- },
433
- get dataUpdatedAt() {
434
- return meta.dataUpdatedAt;
435
- },
436
- get errorUpdatedAt() {
437
- return meta.errorUpdatedAt;
438
- },
439
- get failureCount() {
440
- return meta.fetchFailureCount;
441
- },
442
- get failureReason() {
443
- return meta.fetchFailureReason;
444
- },
445
- get errorUpdateCount() {
446
- return meta.errorUpdateCount;
447
- },
448
- get promise() {
449
- return solidJs.resolve(() => data());
450
- },
451
- refetch: ((refetchOptions) => {
452
- if (!isServer2 && latestOptions) {
453
- observer.setOptions(latestOptions);
454
- }
455
- return observer.refetch(refetchOptions);
456
- })
457
- };
458
- return {
459
- result,
460
- observer,
461
- query,
462
- defaultedOptions,
463
- isFetching,
464
- status
465
- };
261
+ const client = (0, solid_js.createMemo)(() => useQueryClient(queryClient?.()));
262
+ const isRestoring = useIsRestoring();
263
+ /**
264
+ * The most recently computed hash, updated on every options compute —
265
+ * including holds, where the memo's committed face still serves the old
266
+ * options. The cache-event filter below must match both: on a key switch
267
+ * the new key's fetch settles *before* the hold commits, so filtering by
268
+ * the committed hash alone drops that settle event and nothing downstream
269
+ * (data recompute, meta projection) ever learns the fetch finished.
270
+ */
271
+ let latestHash;
272
+ let latestOptions;
273
+ const defaultedOptions = (0, solid_js.createMemo)(() => {
274
+ const defaulted = client().defaultQueryOptions(options());
275
+ defaulted._optimisticResults = isRestoring() ? "isRestoring" : "optimistic";
276
+ if (isServer$2) {
277
+ defaulted.retry = false;
278
+ defaulted.throwOnError = true;
279
+ }
280
+ latestHash = defaulted.queryHash;
281
+ latestOptions = defaulted;
282
+ return defaulted;
283
+ });
284
+ /**
285
+ * The observer is a lifecycle/policy engine only. Registering it pins the
286
+ * query against garbage collection, engages mount-fetch policy
287
+ * (`shouldFetchOnMount`), schedules `refetchInterval`, and gates
288
+ * focus/reconnect refetches — all of which live behind observer
289
+ * registration in query-core. Reactivity never touches its notifications
290
+ * or result objects: the listener is a noop, and the reactive layer below
291
+ * derives everything from cache events and fetch promises.
292
+ *
293
+ * `let`, not `const`: a reactive `queryClient` accessor can swap clients
294
+ * mid-life, and the observer must be rebuilt against the new client (see
295
+ * `syncClient` below).
296
+ */
297
+ let observer = (0, solid_js.untrack)(() => new Observer(client(), defaultedOptions()));
298
+ let lastAppliedHash = observer.options.queryHash;
299
+ (0, solid_js.createRenderEffect)(() => defaultedOptions(), (opts) => {
300
+ lastAppliedHash = opts.queryHash;
301
+ observer.setOptions(opts);
302
+ });
303
+ /**
304
+ * Solid's own "this component is being hydrated" answer, captured at
305
+ * setup. Always false on the server.
306
+ */
307
+ const hydratedMount = (0, solid_js.isHydrating)();
308
+ /**
309
+ * One version signal per hook, bumped by cache events for this query hash.
310
+ * This is the entire subscription model: any state transition on the query
311
+ * (fetch dispatch, settle, invalidation, `setQueryData`, removal) re-runs
312
+ * the derived reads below, which pull fresh state/promises from the cache.
313
+ *
314
+ * `ownedWrite`: a compute that reads through `query()` can itself create
315
+ * the cache entry (`cache.build` → synchronous 'added' event → this
316
+ * write), so the first bump can land inside whatever computation pulled
317
+ * the entry into existence. This is channel-owned state, not that
318
+ * computation's own — the same pattern as the router's per-key version
319
+ * signals.
320
+ */
321
+ const [version, setVersion] = (0, solid_js.createSignal)(0, { ownedWrite: true });
322
+ /**
323
+ * Whether this hook's serialized data entry has been applied to the
324
+ * cache (or was determined not to exist). Non-hydrated mounts are born
325
+ * primed. Gates the pull-model fetch: hydration's takeover recompute can
326
+ * run against a cache the priming hasn't reached yet, and fetching there
327
+ * would race data the stream already delivered. Created on both sides
328
+ * (unread on the server) for hydration id parity.
329
+ */
330
+ const [primed, setPrimed] = (0, solid_js.createSignal)(!hydratedMount, { ownedWrite: true });
331
+ const onCacheEvent = (event) => {
332
+ if (event.query.queryHash === lastAppliedHash || event.query.queryHash === latestHash) setVersion((v) => v + 1);
333
+ };
334
+ let observerSub = null;
335
+ let cacheSub = null;
336
+ let disposed = false;
337
+ /**
338
+ * Set once the mount flow decides the observer should be live — a client
339
+ * swap re-attaches the rebuilt observer iff its predecessor was attached.
340
+ */
341
+ let shouldAttach = false;
342
+ let activeClient = (0, solid_js.untrack)(client);
343
+ /**
344
+ * The entry this hook last read at its current hash, and the fallback for
345
+ * `query()` when the cache no longer holds that hash. Removal is the case
346
+ * that needs it: `removeQueries()` (or `clear()`) fires 'removed' for a
347
+ * hash this hook is mounted on, which bumps `version` and re-runs every
348
+ * derived read, and a plain `build()` there would re-create the entry the
349
+ * caller just removed. That resurrection is not passive, since the 'added'
350
+ * entry also re-points the still-live observer, whose mount-fetch policy
351
+ * then refetches and repopulates the key, contrary to `removeQueries`
352
+ * being documented to remove entries instead of refetching them.
353
+ *
354
+ * The removed instance keeps its final state, so reads hold their last
355
+ * value until options change or a real entry returns (`setQueryData`, a
356
+ * refetch, a later mount). That is what the other adapters do: a React
357
+ * observer keeps rendering the removed query's last result while the
358
+ * cache stays empty.
359
+ *
360
+ * Cleared on a client swap, below: the fallback is only meaningful for the
361
+ * cache it was read from.
362
+ */
363
+ let lastQuery;
364
+ const attach = () => {
365
+ if (!disposed && !observerSub && !(0, solid_js.untrack)(isRestoring)) {
366
+ shouldAttach = true;
367
+ observerSub = observer.subscribe(_tanstack_query_core.noop);
368
+ }
369
+ };
370
+ /**
371
+ * Idempotent client re-pointing, called from the tracked `query()` read
372
+ * (which every derived compute goes through) rather than a dedicated
373
+ * watcher node — hydration id assignment is positional, so a client-only
374
+ * effect here would shift every downstream id. On a swap the version
375
+ * subscription moves to the new cache and the observer is rebuilt against
376
+ * the new client, so policy fetches and cache events both follow the
377
+ * client the hook is actually reading.
378
+ * @param c - The `QueryClient` the hook currently resolves to.
379
+ */
380
+ const syncClient = (c) => {
381
+ if (isServer$2 || c === activeClient) return;
382
+ activeClient = c;
383
+ lastQuery = void 0;
384
+ cacheSub?.();
385
+ cacheSub = c.getQueryCache().subscribe(onCacheEvent);
386
+ observerSub?.();
387
+ observerSub = null;
388
+ observer = new Observer(c, (0, solid_js.untrack)(defaultedOptions));
389
+ if (shouldAttach && !disposed && !(0, solid_js.untrack)(isRestoring)) observerSub = observer.subscribe(_tanstack_query_core.noop);
390
+ };
391
+ /**
392
+ * Hydration priming — content-addressed, the Solid Router `query()`
393
+ * pattern. The provider serialized every query this request touched
394
+ * into Solid's hydration registry under `sq:<queryHash>` (raw pre-select
395
+ * data plus `dataUpdatedAt`); here the hook looks its hash up directly
396
+ * and reconstructs the cache entry through query-core `hydrate()`, so
397
+ * staleness policy stays honest. Content addressing means coverage is
398
+ * the CACHE's, not the rendered tree's: prefetched-never-rendered
399
+ * queries transfer, shared keys prime from whichever hook consumes the
400
+ * entry first, and — like the router — the registry can still be
401
+ * consulted past hydration end, so a component mounted long after (lazy route,
402
+ * post-hydration navigation) still adopts the server's payload instead
403
+ * of refetching. Entries are consumed one-shot (deleted on load): once
404
+ * the cache owns the data, a stale registry payload must never shadow
405
+ * it.
406
+ *
407
+ * Ordering matters twice over. The observer attaches only after priming
408
+ * resolves (on hydrated mounts via `primeAndAttach`; on later mounts by
409
+ * priming HERE, before the attach render effect below even exists —
410
+ * its effect half runs synchronously inside an active flush, and mount
411
+ * policy against a still-cold cache would refetch data the registry
412
+ * already holds). Settled entries prime synchronously at setup;
413
+ * streamed entries prime when their chunk lands, per query, so early
414
+ * components go live while later boundaries still stream. No entry
415
+ * (placeholder queries serialize nothing; SSR errors adopt at their
416
+ * boundary) attaches immediately and lets mount policy decide.
417
+ * @param entry - The hydration registry entry for this query's hash, if one exists.
418
+ */
419
+ const prime = (entry) => {
420
+ if (entry != null && typeof entry === "object" && (entry.t ?? 0) > 0) {
421
+ const c = (0, solid_js.untrack)(client);
422
+ const opts = (0, solid_js.untrack)(defaultedOptions);
423
+ (0, solid_js.runWithOwner)(null, () => (0, _tanstack_query_core.hydrate)(c, {
424
+ mutations: [],
425
+ queries: [{
426
+ queryKey: opts.queryKey,
427
+ queryHash: opts.queryHash,
428
+ dehydratedAt: entry.t,
429
+ ...opts.meta && { meta: opts.meta },
430
+ ...opts._type && { queryType: opts._type },
431
+ state: {
432
+ data: entry.data,
433
+ dataUpdatedAt: entry.t,
434
+ dataUpdateCount: 1,
435
+ error: null,
436
+ errorUpdateCount: 0,
437
+ errorUpdatedAt: 0,
438
+ fetchFailureCount: 0,
439
+ fetchFailureReason: null,
440
+ fetchMeta: null,
441
+ isInvalidated: false,
442
+ status: "success",
443
+ fetchStatus: "idle"
444
+ }
445
+ }]
446
+ }));
447
+ }
448
+ };
449
+ if (!isServer$2) {
450
+ cacheSub = activeClient.getQueryCache().subscribe(onCacheEvent);
451
+ const registryKey = "sq:" + (0, solid_js.untrack)(defaultedOptions).queryHash;
452
+ const primeAndAttach = (entry) => {
453
+ prime(entry);
454
+ setPrimed(true);
455
+ attach();
456
+ };
457
+ const settle = hydratedMount ? primeAndAttach : prime;
458
+ const entry = (0, _solidjs_web.takeHydrationValue)(registryKey);
459
+ if (entry?.status === "resolved") settle(entry.value);
460
+ else if (entry?.status === "rejected") settle();
461
+ else if (entry?.status === "pending") entry.promise.then(settle, () => settle());
462
+ else if (hydratedMount) primeAndAttach();
463
+ if (!hydratedMount) (0, solid_js.createRenderEffect)(() => isRestoring(), (restoring) => {
464
+ if (!restoring) attach();
465
+ });
466
+ (0, solid_js.onCleanup)(() => {
467
+ disposed = true;
468
+ observerSub?.();
469
+ observerSub = null;
470
+ cacheSub?.();
471
+ cacheSub = null;
472
+ });
473
+ }
474
+ /**
475
+ * The cache entry for the current options, without the `version` read —
476
+ * for the setup-time snapshots below (`metaProjection`'s seed,
477
+ * `mountedAt`), which run in whatever computation is instantiating this
478
+ * component. Under hydration that matters: priming bumps `version`
479
+ * during setup, and Solid holds a write made during the hydration pass —
480
+ * a computation in the pass that reads the written signal, tracked or
481
+ * not, is served the pre-write snapshot and replays at release. For the
482
+ * hook's own derived nodes that replay is the takeover. For the
483
+ * instantiating computation (a boundary's children, a `<Show>` branch)
484
+ * it is a remount: the hydrated component is disposed and re-created as
485
+ * a client render, and the server value stops holding the DOM. So the
486
+ * snapshots read the cache, never the signal.
487
+ * @returns The cache entry for the current options.
488
+ */
489
+ const lookupQuery = () => {
490
+ const c = client();
491
+ syncClient(c);
492
+ const cache = c.getQueryCache();
493
+ const opts = defaultedOptions();
494
+ const existing = cache.get(opts.queryHash);
495
+ if (existing) return lastQuery = existing;
496
+ if (lastQuery?.queryHash === opts.queryHash) return lastQuery;
497
+ return lastQuery = cache.build(c, opts);
498
+ };
499
+ const query = () => {
500
+ version();
501
+ return lookupQuery();
502
+ };
503
+ const isEnabled = () => {
504
+ const opts = defaultedOptions();
505
+ return (typeof opts.enabled === "function" ? opts.enabled((0, solid_js.untrack)(query)) : opts.enabled) !== false;
506
+ };
507
+ const resolvePlaceholder = (opts) => {
508
+ const placeholder = opts.placeholderData;
509
+ if (placeholder === void 0) return void 0;
510
+ return typeof placeholder === "function" ? placeholder() : placeholder;
511
+ };
512
+ /**
513
+ * The data compute. It returns either the settled `{ value }` root or a
514
+ * promise of it — the engine does the rest: pending reads suspend into
515
+ * `<Loading>` (holding the previous committed value on refetch),
516
+ * rejections surface to `<Errored>`, transitions hold commits until
517
+ * in-flight answers land, and on the server the settled value serializes
518
+ * for hydration adoption on the client.
519
+ */
520
+ let chained = null;
521
+ const chainOnce = (base, select, wrap) => {
522
+ if (chained?.base !== base || chained.select !== select) chained = {
523
+ base,
524
+ select,
525
+ value: base.then(wrap)
526
+ };
527
+ return chained.value;
528
+ };
529
+ const computeData = (prev) => {
530
+ const opts = defaultedOptions();
531
+ const q = query();
532
+ const state = q.state;
533
+ const select = opts.select;
534
+ const wrap = (d) => ({ value: select ? select(d) : d });
535
+ if (state.data === void 0 && state.status === "pending") {
536
+ const placeholder = resolvePlaceholder(opts);
537
+ if (placeholder !== void 0) return wrap(placeholder);
538
+ }
539
+ if (state.fetchStatus !== "idle") {
540
+ if (state.data === void 0 || prev !== void 0) {
541
+ const promise = q.promise;
542
+ if (promise) return chainOnce(promise, select, wrap);
543
+ }
544
+ }
545
+ if (state.status === "error") {
546
+ if (state.data === void 0 || (0, _tanstack_query_core.shouldThrowError)(opts.throwOnError, [state.error, q])) throw state.error;
547
+ }
548
+ if (state.data !== void 0) return wrap(state.data);
549
+ if (isEnabled()) {
550
+ /**
551
+ * Never start a fetch inside the hydration window. Adoption
552
+ * trace-runs this compute even on a hit (solid mocks `fetch` there,
553
+ * but a TanStack fetch is invisible to that mock) — a query fetching
554
+ * here would wedge on hydration's Promise mock inside its queryFn
555
+ * and then swallow every later legitimate refetch through retryer
556
+ * dedupe. During hydration the value comes from adoption or node
557
+ * priming; if a fetch is genuinely needed, the post-priming observer
558
+ * attach issues it outside the window.
559
+ */
560
+ if ((0, solid_js.isHydrating)()) return NEVER;
561
+ /**
562
+ * Same discipline until this hook's serialized node entry has primed
563
+ * the cache (or was found absent): the takeover recompute at
564
+ * hydration end can land before a streamed entry does, and fetching
565
+ * against the still-empty cache would race data the stream already
566
+ * carries. The read is tracked — priming resolves through
567
+ * `setPrimed`, re-running this compute, and an entry-less query
568
+ * falls through to a normal fetch here.
569
+ */
570
+ if (!primed()) return NEVER;
571
+ /**
572
+ * Same discipline while a persister is restoring: the restored value
573
+ * is about to land in the cache, so pulling a fetch now would race
574
+ * it. The read is tracked — `isRestoring` flipping false re-runs
575
+ * this compute (and the deferred observer attach engages mount
576
+ * policy), so the fetch fires then if the restore left a gap.
577
+ */
578
+ if (isRestoring()) return NEVER;
579
+ /**
580
+ * Sync observer policy before pulling. Under a suspended boundary
581
+ * the options render effect is deferred, so on an enabled flip or
582
+ * key change this compute runs first and the effect only lands
583
+ * after the revival fetch settles — at which point a "changed"
584
+ * options diff against now-stale data would issue a redundant
585
+ * policy refetch. Syncing here means any policy fetch starts now
586
+ * (and `q.fetch` dedupes into it), and the deferred effect later
587
+ * sees the identical options object — a no-op diff.
588
+ */
589
+ if (!isServer$2) observer.setOptions(opts);
590
+ return chainOnce(q.fetch(opts), select, wrap);
591
+ }
592
+ /**
593
+ * Disabled, with nothing cached. The three guards above are all
594
+ * unreachable on the server, but this one is not, and parking here has
595
+ * no server meaning: the render has to finish, and nothing will enable
596
+ * the query or write the cache before it does. So commit the idle
597
+ * value — 'pending' with no data IS a disabled query's settled SSR
598
+ * truth, which is the contract `serverMeta` already honors by not
599
+ * tying its read to this node while disabled, and it is the state the
600
+ * client hydrates to. Committed rather than passed through `wrap`:
601
+ * `select` must not be invoked on absent data.
602
+ */
603
+ if (isServer$2) return { value: void 0 };
604
+ return NEVER;
605
+ };
606
+ /**
607
+ * THE data node: one projection, identical on both sides — the router
608
+ * "feed `query()` into `createProjection`" shape. The derive asks the
609
+ * cache for the answer (`computeData`) and the engine owns everything
610
+ * else: the server runs the derive, waits, and serializes the settled
611
+ * store under this node's id (`deferStream` holds the flush); pending
612
+ * reads suspend into `<Loading>`; a hydrating client adopts the
613
+ * serialized value and re-derives once hydration hands over; and every
614
+ * landing — refetch, invalidation, placeholder upgrade — auto-reconciles
615
+ * into the existing proxy graph (keyed by `reconcile`, default `'id'`),
616
+ * so deep reads are fine-grained and item identity survives fetches.
617
+ *
618
+ * The root wrapper exists because store roots must be objects —
619
+ * primitive data rides the `value` leaf as a plain signal read. The
620
+ * draft's committed `value` doubles as the previous-data signal for the
621
+ * first-paint exception in `computeData`.
622
+ *
623
+ * Default ('server') hydration semantics: the serialized value owns the
624
+ * node while it hydrates. Outside every still-pending streamed boundary,
625
+ * a cache write commits immediately. Under a pending boundary it waits
626
+ * for that boundary to resume, which hydrates against the server
627
+ * snapshot.
628
+ */
629
+ const dataStore = (0, solid_js.createProjection)((draft) => computeData(draft.value), {}, {
630
+ key: (0, solid_js.untrack)(() => options().reconcile),
631
+ deferStream: (0, solid_js.untrack)(() => options().deferStream)
632
+ });
633
+ const data = () => dataStore.value;
634
+ /**
635
+ * Scalar result metadata.
636
+ *
637
+ * Client: a projection reconciled per-field from query state on every
638
+ * cache event, so each field is its own fine-grained signal — a component
639
+ * reading only `isFetching` re-runs on fetchStatus flips, not on every
640
+ * state transition.
641
+ *
642
+ * Server: boundaries guarantee that only settled state serializes, and
643
+ * meta must honor the same contract (solid's own `isPending` suspends
644
+ * rather than ever serialize `true`). A projection cannot: its compute
645
+ * runs once at setup and never re-pulls, freezing an in-flight snapshot
646
+ * ('pending'/'fetching') into HTML that the hydrating client — reading
647
+ * the primed, settled cache — contradicts. So on the server every meta
648
+ * read pulls live query state, and while the entry is unsettled (pending
649
+ * with a fetch in flight, or one it can start) the read ties itself to the data
650
+ * node, which throws the pending read and holds the boundary until
651
+ * settle. A disabled pending query is served as-is: 'pending' IS its
652
+ * settled SSR truth, and the client hydrates the identical state.
653
+ * @returns The scalar metadata read live from the query's state.
654
+ */
655
+ const serverMeta = () => {
656
+ if (query().state.status === "pending" && isEnabled()) data();
657
+ return metaFrom(query().state);
658
+ };
659
+ /**
660
+ * Created on BOTH sides even though the server never reads it: hydration
661
+ * id assignment is positional, so every reactive node a hook creates on
662
+ * the client must have a server counterpart (and vice versa) or every id
663
+ * downstream shifts and hydration key-misses the whole subtree.
664
+ */
665
+ const metaProjection = (0, solid_js.createProjection)((draft) => {
666
+ Object.assign(draft, metaFrom(query().state));
667
+ }, (0, solid_js.untrack)(() => metaFrom(lookupQuery().state)));
668
+ const meta = isServer$2 ? new Proxy({}, { get: (_, key) => serverMeta()[key] }) : metaProjection;
669
+ /**
670
+ * Server: read live counts instead of a setup snapshot — "mount" resolves
671
+ * post-settle there, so `isFetchedAfterMount` serializes `false`, which is
672
+ * exactly what the hydrating client computes (its mount snapshot equals
673
+ * the hydrated counts).
674
+ */
675
+ const mountedAt = isServer$2 ? {
676
+ get dataUpdateCount() {
677
+ return (0, solid_js.untrack)(query).state.dataUpdateCount;
678
+ },
679
+ get errorUpdateCount() {
680
+ return (0, solid_js.untrack)(query).state.errorUpdateCount;
681
+ }
682
+ } : (0, solid_js.untrack)(() => {
683
+ const state = lookupQuery().state;
684
+ return {
685
+ dataUpdateCount: state.dataUpdateCount,
686
+ errorUpdateCount: state.errorUpdateCount
687
+ };
688
+ });
689
+ const hasPlaceholder = () => meta.status === "pending" && (0, solid_js.untrack)(() => resolvePlaceholder(defaultedOptions())) !== void 0;
690
+ const status = () => hasPlaceholder() ? "success" : meta.status;
691
+ const isPending = () => status() === "pending";
692
+ /**
693
+ * A refetch of settled data is a transition: the state write that flips
694
+ * `fetchStatus` to 'fetching' is held in the same batch as the pending
695
+ * data node, so the committed meta channel cannot show it mid-hold — by
696
+ * design, held updates commit atomically. The observable channel for
697
+ * "a new answer is in flight" during a hold is core's pending probe.
698
+ * The committed `fetchStatus` covers the first load (where the probe
699
+ * would see an uninitialized node) and untracked/imperative reads.
700
+ * @returns `true` while a fetch for this query is in flight.
701
+ */
702
+ const isFetching = () => meta.fetchStatus === "fetching" || (0, solid_js.isPending)(() => data());
703
+ const isError = () => status() === "error";
704
+ const isStale = () => {
705
+ const opts = defaultedOptions();
706
+ const q = (0, solid_js.untrack)(query);
707
+ const staleTime = typeof opts.staleTime === "function" ? opts.staleTime(q) : opts.staleTime;
708
+ version();
709
+ return q.isStaleByTime(staleTime);
710
+ };
711
+ return {
712
+ result: {
713
+ get data() {
714
+ return data();
715
+ },
716
+ get error() {
717
+ return meta.error;
718
+ },
719
+ get status() {
720
+ return status();
721
+ },
722
+ get fetchStatus() {
723
+ return meta.fetchStatus;
724
+ },
725
+ get isPending() {
726
+ return isPending();
727
+ },
728
+ get isSuccess() {
729
+ return status() === "success";
730
+ },
731
+ get isError() {
732
+ return isError();
733
+ },
734
+ get isLoading() {
735
+ return isPending() && isFetching();
736
+ },
737
+ get isFetching() {
738
+ return isFetching();
739
+ },
740
+ get isRefetching() {
741
+ return isFetching() && !isPending();
742
+ },
743
+ get isPaused() {
744
+ return meta.fetchStatus === "paused";
745
+ },
746
+ get isEnabled() {
747
+ return isEnabled();
748
+ },
749
+ get isLoadingError() {
750
+ return isError() && meta.dataUpdatedAt === 0;
751
+ },
752
+ get isRefetchError() {
753
+ return isError() && meta.dataUpdatedAt !== 0;
754
+ },
755
+ get isPlaceholderData() {
756
+ return hasPlaceholder();
757
+ },
758
+ get isStale() {
759
+ return isStale();
760
+ },
761
+ get isFetched() {
762
+ return meta.dataUpdateCount > 0 || meta.errorUpdateCount > 0;
763
+ },
764
+ get isFetchedAfterMount() {
765
+ return meta.dataUpdateCount > mountedAt.dataUpdateCount || meta.errorUpdateCount > mountedAt.errorUpdateCount;
766
+ },
767
+ get dataUpdatedAt() {
768
+ return meta.dataUpdatedAt;
769
+ },
770
+ get errorUpdatedAt() {
771
+ return meta.errorUpdatedAt;
772
+ },
773
+ get failureCount() {
774
+ return meta.fetchFailureCount;
775
+ },
776
+ get failureReason() {
777
+ return meta.fetchFailureReason;
778
+ },
779
+ get errorUpdateCount() {
780
+ return meta.errorUpdateCount;
781
+ },
782
+ get promise() {
783
+ return (0, solid_js.resolve)(() => data());
784
+ },
785
+ refetch: ((refetchOptions) => {
786
+ if (!isServer$2 && latestOptions) observer.setOptions(latestOptions);
787
+ return observer.refetch(refetchOptions);
788
+ })
789
+ },
790
+ observer,
791
+ query,
792
+ defaultedOptions,
793
+ isFetching,
794
+ status
795
+ };
466
796
  }
467
-
468
797
  // src/useQuery.ts
469
798
  function useQuery(options, queryClient) {
470
- return useBaseQuery(
471
- solidJs.createMemo(() => options()),
472
- queryCore.QueryObserver,
473
- queryClient
474
- );
799
+ return useBaseQuery((0, solid_js.createMemo)(() => options()), _tanstack_query_core.QueryObserver, queryClient);
475
800
  }
476
-
477
801
  // src/queryOptions.ts
478
802
  function queryOptions(options) {
479
- return options;
803
+ return options;
480
804
  }
805
+ // src/dehydrateSettled.ts
806
+ /**
807
+ * Waits for every fetch the client has in flight to settle, then
808
+ * dehydrates. This is the extraction half of a single-flight collector:
809
+ * after route data functions run for the mutation's target URL, loaders
810
+ * commonly kick off prefetches without awaiting them — plain
811
+ * `dehydrate()` would snapshot those mid-fetch and ship nothing.
812
+ *
813
+ * ```ts
814
+ * registerFlightDataSource(FLIGHT_DATA_SOURCE, (event, outcome) =>
815
+ * loadFlightTarget({
816
+ * router,
817
+ * event,
818
+ * outcome,
819
+ * collect: () => dehydrateSettled(queryClient),
820
+ * }),
821
+ * )
822
+ * ```
823
+ *
824
+ * Settling is chased to quiescence — awaiting one batch of fetches can
825
+ * dispatch more (dependent queries keyed off a first result) — so an
826
+ * unconditionally self-refetching query would keep this pending; that's
827
+ * an app bug mirrored, not guarded.
828
+ * @param client - The `QueryClient` whose cache is dehydrated.
829
+ * @param options - The `DehydrateOptions` forwarded to `dehydrate`.
830
+ * @returns A promise for the dehydrated state, taken once no fetch is in flight.
831
+ */
481
832
  async function dehydrateSettled(client, options) {
482
- const cache = client.getQueryCache();
483
- for (; ; ) {
484
- const pending = cache.getAll().filter((query) => query.state.fetchStatus !== "idle").map((query) => query.promise);
485
- if (pending.length === 0) break;
486
- await Promise.allSettled(pending);
487
- }
488
- return queryCore.dehydrate(client, options);
833
+ const cache = client.getQueryCache();
834
+ for (;;) {
835
+ const pending = cache.getAll().filter((query) => query.state.fetchStatus !== "idle").map((query) => query.promise);
836
+ if (pending.length === 0) break;
837
+ await Promise.allSettled(pending);
838
+ }
839
+ return (0, _tanstack_query_core.dehydrate)(client, options);
489
840
  }
490
- var isServer3 = typeof window === "undefined";
841
+ // src/cacheAggregate.ts
842
+ const isServer$1 = typeof window === "undefined";
843
+ /**
844
+ * Shared reactive core for the cross-cache aggregate hooks — `useIsFetching`,
845
+ * `useIsMutating`, `useMutationState` — which all reduce to "a value derived
846
+ * from a whole cache, refreshed on its events". Two invariants live here so
847
+ * each hook doesn't restate them:
848
+ *
849
+ * Dual write. Cache events can fire inside an action transaction
850
+ * (`useMutation` rides core `action`; an onSuccess invalidation dispatches
851
+ * refetches mid-action), where a plain signal write is held until settle —
852
+ * the in-flight value would be invisible. An optimistic override alone fails
853
+ * the other way: outside a transaction, overrides drop at batch end. So a
854
+ * durable signal carries committed state and an optimistic node tracks it as
855
+ * its base; in-transaction values surface through the override, and the held
856
+ * durable write becomes the base when the settle lands.
857
+ *
858
+ * Hydration. A cross-cache aggregate is not tied to a single async source,
859
+ * so it cannot ride the boundary contract per-query meta uses (suspend until
860
+ * settled). Its contract is fixed by construction instead: a hydrating
861
+ * client can only ever observe the empty value at claim time — its own
862
+ * fetches are held inside the hydration window, channel-primed entries are
863
+ * settled, and mutations do not transfer across SSR. So the server
864
+ * serializes the empty value, and a hydrated mount latches there until its
865
+ * window closes: the subscription and first sync run from an effect half,
866
+ * deferred past hydration — the earliest globally-safe moment for a
867
+ * cross-cache read to go live (on a streamed page, an already-hydrated
868
+ * region's refetch can be in flight while this region is still claiming).
869
+ *
870
+ * Every node here is created on the server too, where it is never read or
871
+ * written: hydration id assignment is positional, so both sides must create
872
+ * the same reactive nodes or every id downstream shifts and the subtree
873
+ * key-misses.
874
+ * @param subscribe - Subscribes to the cache's events and returns the unsubscribe function.
875
+ * @param read - Computes the aggregate from the cache, given the previously committed value.
876
+ * @param empty - The value served on the server and while a hydrated mount is still hydrating.
877
+ * @returns An accessor for the current aggregate.
878
+ */
491
879
  function createCacheAggregate(subscribe, read, empty) {
492
- const hydratedMount = !isServer3 && solidJs.sharedConfig.hydrating === true;
493
- const [durable, setDurable] = solidJs.createSignal(
494
- hydratedMount || isServer3 ? empty : solidJs.untrack(() => read(empty)),
495
- { ownedWrite: true }
496
- );
497
- const [value, setValue] = solidJs.createOptimistic(() => durable(), {
498
- ownedWrite: true
499
- });
500
- const sync = () => {
501
- const next = solidJs.untrack(() => read(solidJs.untrack(durable)));
502
- setDurable(() => next);
503
- setValue(() => next);
504
- };
505
- let unsubscribe = null;
506
- const attach = () => {
507
- unsubscribe ??= solidJs.untrack(() => subscribe(sync));
508
- };
509
- solidJs.onCleanup(() => unsubscribe?.());
510
- solidJs.createEffect(
511
- () => void 0,
512
- () => {
513
- if (hydratedMount) {
514
- attach();
515
- sync();
516
- }
517
- }
518
- );
519
- if (isServer3) return () => empty;
520
- if (!hydratedMount) attach();
521
- return value;
880
+ const hydratedMount = (0, solid_js.isHydrating)();
881
+ const [durable, setDurable] = (0, solid_js.createSignal)(hydratedMount || isServer$1 ? empty : (0, solid_js.untrack)(() => read(empty)), { ownedWrite: true });
882
+ const [value, setValue] = (0, solid_js.createOptimistic)(() => durable(), { ownedWrite: true });
883
+ const sync = () => {
884
+ const next = (0, solid_js.untrack)(() => read((0, solid_js.untrack)(durable)));
885
+ setDurable(() => next);
886
+ setValue(() => next);
887
+ };
888
+ let unsubscribe = null;
889
+ const attach = () => {
890
+ unsubscribe ??= (0, solid_js.untrack)(() => subscribe(sync));
891
+ };
892
+ (0, solid_js.onCleanup)(() => unsubscribe?.());
893
+ (0, solid_js.createEffect)(() => void 0, () => {
894
+ if (hydratedMount) {
895
+ attach();
896
+ sync();
897
+ }
898
+ });
899
+ if (isServer$1) return () => empty;
900
+ if (!hydratedMount) attach();
901
+ return value;
522
902
  }
523
-
524
903
  // src/useIsFetching.ts
904
+ /**
905
+ * The `useIsFetching` primitive returns the `number` of the queries that your application is loading or fetching
906
+ * in the background (useful for app-wide loading indicators).
907
+ * @param filters - An accessor returning the {@link QueryFilters} to narrow down the matched queries.
908
+ * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
909
+ * will be used.
910
+ * @returns An accessor for the `number` of the queries that your application is currently loading or fetching
911
+ * in the background.
912
+ * @example
913
+ * ```tsx
914
+ * import { useIsFetching } from '@tanstack/solid-query'
915
+ *
916
+ * function GlobalLoadingIndicator() {
917
+ * // How many queries matching the posts prefix are fetching?
918
+ * const isFetchingPosts = useIsFetching(() => ({ queryKey: ['posts'] }))
919
+ *
920
+ * return isFetchingPosts() > 0 ? <span>Loading posts...</span> : null
921
+ * }
922
+ * ```
923
+ */
525
924
  function useIsFetching(filters, queryClient) {
526
- const client = solidJs.createMemo(() => exports.useQueryClient(queryClient?.()));
527
- return createCacheAggregate(
528
- (onEvent) => client().getQueryCache().subscribe(onEvent),
529
- () => client().isFetching(filters?.()),
530
- 0
531
- );
925
+ const client = (0, solid_js.createMemo)(() => useQueryClient(queryClient?.()));
926
+ return createCacheAggregate((onEvent) => client().getQueryCache().subscribe(onEvent), () => client().isFetching(filters?.()), 0);
532
927
  }
928
+ // src/useInfiniteQuery.ts
929
+ /**
930
+ * Checks whether `getNextPageParam` yields a param for the page after the last cached one.
931
+ * @param options - The options holding `getNextPageParam`.
932
+ * @param data - The cached infinite data, if any.
933
+ * @returns `true` if there is a next page to fetch.
934
+ */
533
935
  function hasNextPage(options, data) {
534
- if (!data || data.pages.length === 0) return false;
535
- const lastIndex = data.pages.length - 1;
536
- return options.getNextPageParam(
537
- data.pages[lastIndex],
538
- data.pages,
539
- data.pageParams[lastIndex],
540
- data.pageParams
541
- ) != null;
936
+ if (!data || data.pages.length === 0) return false;
937
+ const lastIndex = data.pages.length - 1;
938
+ return options.getNextPageParam(data.pages[lastIndex], data.pages, data.pageParams[lastIndex], data.pageParams) != null;
542
939
  }
940
+ /**
941
+ * Checks whether `getPreviousPageParam` yields a param for the page before the first cached one.
942
+ * @param options - The options holding `getPreviousPageParam`.
943
+ * @param data - The cached infinite data, if any.
944
+ * @returns `true` if there is a previous page to fetch.
945
+ */
543
946
  function hasPreviousPage(options, data) {
544
- if (!data || data.pages.length === 0 || !options.getPreviousPageParam)
545
- return false;
546
- return options.getPreviousPageParam(
547
- data.pages[0],
548
- data.pages,
549
- data.pageParams[0],
550
- data.pageParams
551
- ) != null;
947
+ if (!data || data.pages.length === 0 || !options.getPreviousPageParam) return false;
948
+ return options.getPreviousPageParam(data.pages[0], data.pages, data.pageParams[0], data.pageParams) != null;
552
949
  }
553
950
  function useInfiniteQuery(options, queryClient) {
554
- const layer = useBaseQueryLayer(
555
- // `_type` is how query-core stamps a cache entry as infinite
556
- // (`Query.setOptions` → `#queryType`), which makes every fetch attach
557
- // `infiniteQueryBehavior`. Core only sets it inside
558
- // `InfiniteQueryObserver.setOptions`, but the adapter's pull path can
559
- // build and fetch the entry first (reactive key change recomputes the
560
- // data memo before the deferred observer effect runs) — without the
561
- // stamp that fetch would run as a plain query and corrupt the entry.
562
- solidJs.createMemo(() => ({ ...options(), _type: "infinite" })),
563
- queryCore.InfiniteQueryObserver,
564
- queryClient
565
- );
566
- const observer = layer.observer;
567
- const direction = () => layer.query().state.fetchMeta?.fetchMore?.direction;
568
- const pageOptions = () => layer.defaultedOptions();
569
- const infiniteData = () => layer.query().state.data;
570
- const isFetchingNextPage = () => layer.isFetching() && direction() === "forward";
571
- const isFetchingPreviousPage = () => layer.isFetching() && direction() === "backward";
572
- const isError = () => layer.status() === "error";
573
- const result = Object.defineProperties(
574
- {},
575
- {
576
- ...Object.getOwnPropertyDescriptors(layer.result),
577
- fetchNextPage: {
578
- value: (fetchOptions) => observer.fetchNextPage(fetchOptions),
579
- enumerable: true
580
- },
581
- fetchPreviousPage: {
582
- value: (fetchOptions) => observer.fetchPreviousPage(fetchOptions),
583
- enumerable: true
584
- },
585
- hasNextPage: {
586
- get: () => hasNextPage(pageOptions(), infiniteData()),
587
- enumerable: true
588
- },
589
- hasPreviousPage: {
590
- get: () => hasPreviousPage(pageOptions(), infiniteData()),
591
- enumerable: true
592
- },
593
- isFetchingNextPage: {
594
- get: isFetchingNextPage,
595
- enumerable: true
596
- },
597
- isFetchingPreviousPage: {
598
- get: isFetchingPreviousPage,
599
- enumerable: true
600
- },
601
- isFetchNextPageError: {
602
- get: () => isError() && direction() === "forward",
603
- enumerable: true
604
- },
605
- isFetchPreviousPageError: {
606
- get: () => isError() && direction() === "backward",
607
- enumerable: true
608
- },
609
- isRefetching: {
610
- get: () => layer.isFetching() && layer.status() !== "pending" && !isFetchingNextPage() && !isFetchingPreviousPage(),
611
- enumerable: true
612
- },
613
- isRefetchError: {
614
- get: () => {
615
- const errored = isError() && layer.query().state.dataUpdatedAt !== 0;
616
- return errored && direction() === void 0;
617
- },
618
- enumerable: true
619
- }
620
- }
621
- );
622
- return result;
951
+ /**
952
+ * Pagers ride the same entry as every other read: the base layer owns
953
+ * the data node, meta projection, and lifecycle observer (an
954
+ * `InfiniteQueryObserver`, so mount policy and refetches use the
955
+ * infinite behavior). This layer adds the page surface on top.
956
+ */
957
+ const layer = useBaseQueryLayer((0, solid_js.createMemo)(() => ({
958
+ ...options(),
959
+ _type: "infinite"
960
+ })), _tanstack_query_core.InfiniteQueryObserver, queryClient);
961
+ const observer = layer.observer;
962
+ /**
963
+ * Committed fetch direction — set when a page fetch dispatches,
964
+ * version-tracked through the layer's query accessor.
965
+ * @returns `'forward'` or `'backward'` for a page fetch, `undefined` otherwise.
966
+ */
967
+ const direction = () => layer.query().state.fetchMeta?.fetchMore?.direction;
968
+ const pageOptions = () => layer.defaultedOptions();
969
+ const infiniteData = () => layer.query().state.data;
970
+ const isFetchingPage = (expected) => {
971
+ const current = direction();
972
+ return layer.isFetching() && current === expected;
973
+ };
974
+ const isFetchingNextPage = () => isFetchingPage("forward");
975
+ const isFetchingPreviousPage = () => isFetchingPage("backward");
976
+ const isError = () => layer.status() === "error";
977
+ return Object.defineProperties({}, {
978
+ ...Object.getOwnPropertyDescriptors(layer.result),
979
+ fetchNextPage: {
980
+ value: (fetchOptions) => observer.fetchNextPage(fetchOptions),
981
+ enumerable: true
982
+ },
983
+ fetchPreviousPage: {
984
+ value: (fetchOptions) => observer.fetchPreviousPage(fetchOptions),
985
+ enumerable: true
986
+ },
987
+ hasNextPage: {
988
+ get: () => hasNextPage(pageOptions(), infiniteData()),
989
+ enumerable: true
990
+ },
991
+ hasPreviousPage: {
992
+ get: () => hasPreviousPage(pageOptions(), infiniteData()),
993
+ enumerable: true
994
+ },
995
+ isFetchingNextPage: {
996
+ get: isFetchingNextPage,
997
+ enumerable: true
998
+ },
999
+ isFetchingPreviousPage: {
1000
+ get: isFetchingPreviousPage,
1001
+ enumerable: true
1002
+ },
1003
+ isFetchNextPageError: {
1004
+ get: () => isError() && direction() === "forward",
1005
+ enumerable: true
1006
+ },
1007
+ isFetchPreviousPageError: {
1008
+ get: () => isError() && direction() === "backward",
1009
+ enumerable: true
1010
+ },
1011
+ isRefetching: {
1012
+ get: () => {
1013
+ const current = direction();
1014
+ return layer.isFetching() && layer.status() !== "pending" && current !== "forward" && current !== "backward";
1015
+ },
1016
+ enumerable: true
1017
+ },
1018
+ isRefetchError: {
1019
+ get: () => {
1020
+ return isError() && layer.query().state.dataUpdatedAt !== 0 && direction() === void 0;
1021
+ },
1022
+ enumerable: true
1023
+ }
1024
+ });
623
1025
  }
624
-
625
1026
  // src/infiniteQueryOptions.ts
626
1027
  function infiniteQueryOptions(options) {
627
- return options;
1028
+ return options;
628
1029
  }
629
- var isServer4 = typeof window === "undefined";
630
- var IDLE = {
631
- status: "idle",
632
- data: void 0,
633
- error: null,
634
- variables: void 0,
635
- submittedAt: 0
1030
+ // src/useMutation.ts
1031
+ const isServer = typeof window === "undefined";
1032
+ const IDLE = {
1033
+ status: "idle",
1034
+ data: void 0,
1035
+ error: null,
1036
+ variables: void 0,
1037
+ submittedAt: 0
636
1038
  };
1039
+ /**
1040
+ * Drive the mutation generator without transaction semantics — the server
1041
+ * has no interactive paint to keep atomic. Yielded thenable values are
1042
+ * awaited and their results passed back in, matching what `action` does
1043
+ * minus the transition bookkeeping.
1044
+ * @param iterator - The mutation generator to run to completion.
1045
+ * @returns A promise for the generator's return value.
1046
+ */
637
1047
  async function drain(iterator) {
638
- let input;
639
- for (; ; ) {
640
- const result = await iterator.next(input);
641
- if (result.done) return result.value;
642
- input = result.value != null ? await result.value : void 0;
643
- }
1048
+ let input;
1049
+ for (;;) {
1050
+ const result = await iterator.next(input);
1051
+ if (result.done) return result.value;
1052
+ input = result.value != null ? await result.value : void 0;
1053
+ }
644
1054
  }
1055
+ /**
1056
+ * Mutations ride core `action`: each `mutate()` call is one transaction.
1057
+ *
1058
+ * - Transient flight state (`isPending`, in-flight `variables`) is a
1059
+ * `createOptimistic` overlay written at the top of the action — visible
1060
+ * immediately, dropped automatically when the transition settles. The
1061
+ * engine's revert-on-settle IS the submission state machine.
1062
+ * - `options.onMutate(variables)` runs inside the same window: it is the
1063
+ * place to apply the caller's own optimistic overlays
1064
+ * (`createOptimistic` / `createOptimisticStore` writes). No context
1065
+ * object, no rollback plumbing — reverting is the engine's job.
1066
+ * - The fetch itself goes through query-core:
1067
+ * `mutationCache.build().execute()` supplies retry/backoff, offline
1068
+ * pausing, scoped serial execution, and cache-level lifecycle callbacks.
1069
+ * No `MutationObserver` — the adapter reads the Mutation's state
1070
+ * directly where flight metadata (failureCount, isPaused) is needed.
1071
+ * - Options-level callbacks are stripped from the built mutation and
1072
+ * re-run *post-`yield`*, inside the transaction: an
1073
+ * `onSuccess → invalidateQueries` chain issues version bumps whose
1074
+ * refetches hold this very transition, so mutation success and fresh
1075
+ * query data land in one atomic paint (and a single-flight payload has
1076
+ * already primed the cache by the time `execute` resolves).
1077
+ * - One `mutate`, returning a safe-to-ignore promise: rejection is also
1078
+ * routed into reactive state, and a no-op catch keeps the ignored
1079
+ * branch from surfacing as an unhandled rejection. The
1080
+ * `mutate`/`mutateAsync` split existed for React's callback-vs-promise
1081
+ * error routing; it has no space here.
1082
+ * @param options - An accessor returning the {@link UseMutationOptions} to use.
1083
+ * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
1084
+ * will be used.
1085
+ * @returns The mutation state, with `mutate` to run the mutation and `reset` to clear its state.
1086
+ */
645
1087
  function useMutation(options, queryClient) {
646
- const client = solidJs.createMemo(() => exports.useQueryClient(queryClient?.()));
647
- const [flight, setFlight] = solidJs.createOptimistic(null);
648
- const [settled, setSettled] = solidJs.createSignal(IDLE);
649
- let activeMutation = null;
650
- let unsubscribeFlight = null;
651
- const [flightVersion, setFlightVersion] = solidJs.createSignal(0);
652
- if (!isServer4)
653
- solidJs.onCleanup(() => {
654
- unsubscribeFlight?.();
655
- unsubscribeFlight = null;
656
- });
657
- async function* run(variables) {
658
- const opts = solidJs.untrack(options);
659
- const callbackContext = {
660
- client: solidJs.untrack(client),
661
- meta: opts.meta,
662
- mutationKey: opts.mutationKey
663
- };
664
- if (!isServer4) setFlight({ variables });
665
- opts.onMutate?.(variables, callbackContext);
666
- const c = solidJs.untrack(client);
667
- const mutation = c.getMutationCache().build(c, {
668
- ...opts,
669
- // Options-level callbacks re-run below, inside the transaction —
670
- // executing them here (inside the await gap) would let their
671
- // cache writes and invalidations escape the atomic settle.
672
- onMutate: void 0,
673
- onSuccess: void 0,
674
- onError: void 0,
675
- onSettled: void 0
676
- });
677
- activeMutation = mutation;
678
- if (!isServer4) {
679
- unsubscribeFlight?.();
680
- unsubscribeFlight = c.getMutationCache().subscribe((event) => {
681
- if ("mutation" in event && event.mutation === activeMutation) {
682
- setFlightVersion((v) => v + 1);
683
- }
684
- });
685
- }
686
- const settleFlight = () => {
687
- if (activeMutation !== mutation) return;
688
- activeMutation = null;
689
- unsubscribeFlight?.();
690
- unsubscribeFlight = null;
691
- };
692
- async function* settleFailure(error) {
693
- try {
694
- if (opts.onError)
695
- yield opts.onError(error, variables, void 0, callbackContext);
696
- } catch (callbackError) {
697
- void Promise.reject(callbackError);
698
- }
699
- try {
700
- if (opts.onSettled)
701
- yield opts.onSettled(
702
- void 0,
703
- error,
704
- variables,
705
- void 0,
706
- callbackContext
707
- );
708
- } catch (callbackError) {
709
- void Promise.reject(callbackError);
710
- }
711
- if (!isServer4)
712
- setSettled({
713
- status: "error",
714
- data: void 0,
715
- error,
716
- variables,
717
- submittedAt: mutation.state.submittedAt
718
- });
719
- settleFlight();
720
- throw error;
721
- }
722
- let result2;
723
- try {
724
- result2 = await mutation.execute(variables);
725
- } catch (error) {
726
- yield;
727
- yield* settleFailure(error);
728
- throw error;
729
- }
730
- yield;
731
- try {
732
- if (opts.onSuccess)
733
- yield opts.onSuccess(
734
- result2,
735
- variables,
736
- void 0,
737
- callbackContext
738
- );
739
- if (opts.onSettled)
740
- yield opts.onSettled(
741
- result2,
742
- null,
743
- variables,
744
- void 0,
745
- callbackContext
746
- );
747
- } catch (callbackError) {
748
- yield* settleFailure(callbackError);
749
- throw callbackError;
750
- }
751
- if (!isServer4)
752
- setSettled({
753
- status: "success",
754
- data: result2,
755
- error: null,
756
- variables,
757
- submittedAt: mutation.state.submittedAt
758
- });
759
- settleFlight();
760
- return result2;
761
- }
762
- const invoke = isServer4 ? (variables) => drain(run(variables)) : solidJs.action(run);
763
- const mutate = (variables) => {
764
- const promise = invoke(variables);
765
- promise.catch(queryCore.noop);
766
- return promise;
767
- };
768
- const status = () => flight() !== null ? "pending" : settled().status;
769
- const isPending = () => flight() !== null;
770
- solidJs.createRenderEffect(
771
- () => {
772
- const state = settled();
773
- if (state.status === "error" && queryCore.shouldThrowError(solidJs.untrack(options).throwOnError, [state.error])) {
774
- throw state.error;
775
- }
776
- },
777
- () => {
778
- }
779
- );
780
- const result = {
781
- mutate,
782
- get data() {
783
- return settled().data;
784
- },
785
- get error() {
786
- return flight() !== null ? null : settled().error;
787
- },
788
- get variables() {
789
- return flight()?.variables ?? settled().variables;
790
- },
791
- get status() {
792
- return status();
793
- },
794
- get isPending() {
795
- return isPending();
796
- },
797
- get isIdle() {
798
- return status() === "idle";
799
- },
800
- get isSuccess() {
801
- return status() === "success";
802
- },
803
- get isError() {
804
- return status() === "error";
805
- },
806
- get submittedAt() {
807
- return flight() !== null ? (flightVersion(), activeMutation?.state.submittedAt ?? 0) : settled().submittedAt;
808
- },
809
- get failureCount() {
810
- flightVersion();
811
- return activeMutation?.state.failureCount ?? 0;
812
- },
813
- get failureReason() {
814
- flightVersion();
815
- return activeMutation?.state.failureReason ?? null;
816
- },
817
- get isPaused() {
818
- flightVersion();
819
- return activeMutation?.state.isPaused ?? false;
820
- },
821
- reset: () => {
822
- setSettled(IDLE);
823
- }
824
- };
825
- return result;
1088
+ const client = (0, solid_js.createMemo)(() => useQueryClient(queryClient?.()));
1089
+ /** Optimistic overlay: non-null exactly while a mutation is in flight. */
1090
+ const [flight, setFlight] = (0, solid_js.createOptimistic)(null);
1091
+ const [settled, setSettled] = (0, solid_js.createSignal)(IDLE);
1092
+ /**
1093
+ * Flight metadata (retry failures, offline pause) lives on the Mutation
1094
+ * instance and changes during the await gap; a version bump per cache
1095
+ * event for the active mutation keeps reads current without cloning
1096
+ * observer results. The subscription is per-flight, created in `run`
1097
+ * against the same client the mutation is built on: nothing reactive is
1098
+ * read at setup (no client read to untrack), the listener and the
1099
+ * mutation can never sit on different clients, and an idle hook holds no
1100
+ * cache subscription at all.
1101
+ */
1102
+ let activeMutation = null;
1103
+ let unsubscribeFlight = null;
1104
+ const [flightVersion, setFlightVersion] = (0, solid_js.createSignal)(0);
1105
+ if (!isServer) (0, solid_js.onCleanup)(() => {
1106
+ unsubscribeFlight?.();
1107
+ unsubscribeFlight = null;
1108
+ });
1109
+ /**
1110
+ * Runs one mutation: the flight overlay and `onMutate`, the fetch through query-core, then the
1111
+ * options-level callbacks and the durable settle.
1112
+ * @param variables - The variables passed to `mutate`.
1113
+ * @returns The data the mutation resolved with.
1114
+ * @yields {unknown} The promises the surrounding `action` (or `drain` on the server) awaits.
1115
+ */
1116
+ async function* run(variables) {
1117
+ const opts = (0, solid_js.untrack)(options);
1118
+ const callbackContext = {
1119
+ client: (0, solid_js.untrack)(client),
1120
+ meta: opts.meta,
1121
+ mutationKey: opts.mutationKey
1122
+ };
1123
+ if (!isServer) setFlight({ variables });
1124
+ opts.onMutate?.(variables, callbackContext);
1125
+ const c = (0, solid_js.untrack)(client);
1126
+ const mutation = c.getMutationCache().build(c, {
1127
+ ...opts,
1128
+ onMutate: void 0,
1129
+ onSuccess: void 0,
1130
+ onError: void 0,
1131
+ onSettled: void 0
1132
+ });
1133
+ activeMutation = mutation;
1134
+ if (!isServer) {
1135
+ unsubscribeFlight?.();
1136
+ unsubscribeFlight = c.getMutationCache().subscribe((event) => {
1137
+ if ("mutation" in event && event.mutation === activeMutation) setFlightVersion((v) => v + 1);
1138
+ });
1139
+ }
1140
+ const settleFlight = () => {
1141
+ if (activeMutation !== mutation) return;
1142
+ activeMutation = null;
1143
+ unsubscribeFlight?.();
1144
+ unsubscribeFlight = null;
1145
+ };
1146
+ /**
1147
+ * Failure settle, shared by both paths. Callback routing mirrors
1148
+ * query-core's `Mutation.execute` (which never sees these callbacks —
1149
+ * they are stripped from the built mutation and re-run here, inside
1150
+ * the transaction): `onError` and an error-shaped `onSettled` run,
1151
+ * their own failures are reported as unhandled rejections but never
1152
+ * displace `error`, then the durable error state commits and the
1153
+ * mutate promise rejects with `error`.
1154
+ * @param error - The error the mutation or one of its success callbacks failed with.
1155
+ * @yields {unknown} The promises returned by `onError` and `onSettled`.
1156
+ */
1157
+ async function* settleFailure(error) {
1158
+ try {
1159
+ if (opts.onError) yield opts.onError(error, variables, void 0, callbackContext);
1160
+ } catch (callbackError) {
1161
+ Promise.reject(callbackError);
1162
+ }
1163
+ try {
1164
+ if (opts.onSettled) yield opts.onSettled(void 0, error, variables, void 0, callbackContext);
1165
+ } catch (callbackError) {
1166
+ Promise.reject(callbackError);
1167
+ }
1168
+ if (!isServer) setSettled({
1169
+ status: "error",
1170
+ data: void 0,
1171
+ error,
1172
+ variables,
1173
+ submittedAt: mutation.state.submittedAt
1174
+ });
1175
+ settleFlight();
1176
+ throw error;
1177
+ }
1178
+ let result;
1179
+ try {
1180
+ result = await mutation.execute(variables);
1181
+ } catch (error) {
1182
+ yield;
1183
+ yield* settleFailure(error);
1184
+ throw error;
1185
+ }
1186
+ yield;
1187
+ try {
1188
+ if (opts.onSuccess) yield opts.onSuccess(result, variables, void 0, callbackContext);
1189
+ if (opts.onSettled) yield opts.onSettled(result, null, variables, void 0, callbackContext);
1190
+ } catch (callbackError) {
1191
+ yield* settleFailure(callbackError);
1192
+ throw callbackError;
1193
+ }
1194
+ if (!isServer) setSettled({
1195
+ status: "success",
1196
+ data: result,
1197
+ error: null,
1198
+ variables,
1199
+ submittedAt: mutation.state.submittedAt
1200
+ });
1201
+ settleFlight();
1202
+ return result;
1203
+ }
1204
+ const invoke = isServer ? (variables) => drain(run(variables)) : (0, solid_js.action)(run);
1205
+ const mutate = (...args) => {
1206
+ const promise = invoke(args[0]);
1207
+ promise.catch(_tanstack_query_core.noop);
1208
+ return promise;
1209
+ };
1210
+ const status = () => flight() !== null ? "pending" : settled().status;
1211
+ const isPending = () => flight() !== null;
1212
+ /**
1213
+ * Errors surface to `<Errored>` when `throwOnError` opts in. The throw
1214
+ * must happen in the compute half so it routes through notifyStatus and
1215
+ * boundary accounting.
1216
+ */
1217
+ (0, solid_js.createRenderEffect)(() => {
1218
+ const state = settled();
1219
+ if (state.status === "error" && (0, _tanstack_query_core.shouldThrowError)((0, solid_js.untrack)(options).throwOnError, [state.error])) throw state.error;
1220
+ }, () => {});
1221
+ return {
1222
+ mutate,
1223
+ get data() {
1224
+ return settled().data;
1225
+ },
1226
+ get error() {
1227
+ return flight() !== null ? null : settled().error;
1228
+ },
1229
+ get variables() {
1230
+ return flight()?.variables ?? settled().variables;
1231
+ },
1232
+ get status() {
1233
+ return status();
1234
+ },
1235
+ get isPending() {
1236
+ return isPending();
1237
+ },
1238
+ get isIdle() {
1239
+ return status() === "idle";
1240
+ },
1241
+ get isSuccess() {
1242
+ return status() === "success";
1243
+ },
1244
+ get isError() {
1245
+ return status() === "error";
1246
+ },
1247
+ get submittedAt() {
1248
+ return flight() !== null ? (flightVersion(), activeMutation?.state.submittedAt ?? 0) : settled().submittedAt;
1249
+ },
1250
+ get failureCount() {
1251
+ flightVersion();
1252
+ return activeMutation?.state.failureCount ?? 0;
1253
+ },
1254
+ get failureReason() {
1255
+ flightVersion();
1256
+ return activeMutation?.state.failureReason ?? null;
1257
+ },
1258
+ get isPaused() {
1259
+ flightVersion();
1260
+ return activeMutation?.state.isPaused ?? false;
1261
+ },
1262
+ reset: () => {
1263
+ setSettled(IDLE);
1264
+ }
1265
+ };
826
1266
  }
827
-
828
1267
  // src/mutationOptions.ts
829
1268
  function mutationOptions(options) {
830
- return options;
1269
+ return options;
831
1270
  }
1271
+ // src/useIsMutating.ts
1272
+ /**
1273
+ * The `useIsMutating` primitive returns the `number` of mutations that your application currently has `pending`
1274
+ * (useful for app-wide loading indicators).
1275
+ * @param filters - An accessor returning the {@link MutationFilters} to narrow down the matched mutations.
1276
+ * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
1277
+ * will be used.
1278
+ * @returns An accessor for the `number` of the mutations that your application currently has `pending`.
1279
+ * @example
1280
+ * ```tsx
1281
+ * import { useIsMutating } from '@tanstack/solid-query'
1282
+ *
1283
+ * function PostsMutatingIndicator() {
1284
+ * // How many mutations matching the posts prefix are in progress?
1285
+ * const isMutatingPosts = useIsMutating(() => ({ mutationKey: ['posts'] }))
1286
+ *
1287
+ * return isMutatingPosts() > 0 ? <span>Saving posts...</span> : null
1288
+ * }
1289
+ * ```
1290
+ */
832
1291
  function useIsMutating(filters, queryClient) {
833
- const client = solidJs.createMemo(() => exports.useQueryClient(queryClient?.()));
834
- return createCacheAggregate(
835
- (onEvent) => client().getMutationCache().subscribe(onEvent),
836
- () => client().isMutating(filters?.()),
837
- 0
838
- );
1292
+ const client = (0, solid_js.createMemo)(() => useQueryClient(queryClient?.()));
1293
+ return createCacheAggregate((onEvent) => client().getMutationCache().subscribe(onEvent), () => client().isMutating(filters?.()), 0);
839
1294
  }
1295
+ // src/useMutationState.ts
1296
+ /**
1297
+ * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`
1298
+ * (or to their state, by default).
1299
+ * @param mutationCache - The mutation cache to read.
1300
+ * @param options - The `filters` to match and the `select` function to map each mutation with.
1301
+ * @returns The selected value of every matching mutation.
1302
+ */
840
1303
  function getResult(mutationCache, options) {
841
- return mutationCache.findAll(options.filters).map(
842
- (mutation) => options.select ? options.select(mutation) : mutation.state
843
- );
1304
+ return mutationCache.findAll(options.filters).map((mutation) => options.select ? options.select(mutation) : mutation.state);
844
1305
  }
1306
+ /**
1307
+ * `useMutationState` is a primitive that gives you access to all mutations in the `MutationCache`. You can pass
1308
+ * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
1309
+ * state.
1310
+ * @param options - An accessor returning the `filters` to narrow down matched mutations, and an optional
1311
+ * `select` to transform the mutation state.
1312
+ * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
1313
+ * will be used.
1314
+ * @returns An accessor for an array of whatever `select` returns for each matching mutation.
1315
+ * @example
1316
+ * Get all variables of all running mutations:
1317
+ * ```tsx
1318
+ * import { useMutationState } from '@tanstack/solid-query'
1319
+ *
1320
+ * function PendingPosts() {
1321
+ * const pendingVariables = useMutationState(() => ({
1322
+ * filters: { status: 'pending' },
1323
+ * select: (mutation) => mutation.state.variables,
1324
+ * }))
1325
+ *
1326
+ * return <>{pendingVariables().length} posts saving...</>
1327
+ * }
1328
+ * ```
1329
+ * @example
1330
+ * Get all data for specific mutations via the `mutationKey`:
1331
+ * ```tsx
1332
+ * import { useMutation, useMutationState } from '@tanstack/solid-query'
1333
+ *
1334
+ * const mutationKey = ['posts']
1335
+ *
1336
+ * function Posts() {
1337
+ * // Some mutation that we want to get the state for
1338
+ * const createPostsMutation = useMutation(() => ({
1339
+ * mutationKey,
1340
+ * mutationFn: createPosts,
1341
+ * }))
1342
+ *
1343
+ * const savedPosts = useMutationState(() => ({
1344
+ * // this mutation key needs to match the mutation key of the given mutation (see above)
1345
+ * filters: { mutationKey, status: 'success' },
1346
+ * select: (mutation) => mutation.state.data,
1347
+ * }))
1348
+ *
1349
+ * return (
1350
+ * <button onClick={() => createPostsMutation.mutate(['New Post'])}>
1351
+ * Create post ({savedPosts().length} saved so far)
1352
+ * </button>
1353
+ * )
1354
+ * }
1355
+ * ```
1356
+ * @example
1357
+ * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
1358
+ * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
1359
+ * last item that `useMutationState` returns to get the latest successful invocation:
1360
+ * ```tsx
1361
+ * import { useMutationState } from '@tanstack/solid-query'
1362
+ *
1363
+ * function LatestPost() {
1364
+ * const savedPosts = useMutationState(() => ({
1365
+ * filters: { mutationKey: ['posts'], status: 'success' },
1366
+ * select: (mutation) => mutation.state.data,
1367
+ * }))
1368
+ *
1369
+ * const latestPost = () => savedPosts()[savedPosts().length - 1]
1370
+ *
1371
+ * return <span>{latestPost()?.title}</span>
1372
+ * }
1373
+ * ```
1374
+ */
845
1375
  function useMutationState(options = () => ({}), queryClient) {
846
- const client = solidJs.createMemo(() => exports.useQueryClient(queryClient?.()));
847
- return createCacheAggregate(
848
- (onEvent) => client().getMutationCache().subscribe(onEvent),
849
- // Structural sharing against the previous committed value keeps
850
- // unchanged mutation states referentially stable across syncs.
851
- (prev) => queryCore.replaceEqualDeep(prev, getResult(client().getMutationCache(), options())),
852
- []
853
- );
1376
+ const client = (0, solid_js.createMemo)(() => useQueryClient(queryClient?.()));
1377
+ return createCacheAggregate((onEvent) => client().getMutationCache().subscribe(onEvent), (prev) => (0, _tanstack_query_core.replaceEqualDeep)(prev, getResult(client().getMutationCache(), options())), []);
854
1378
  }
1379
+ // src/useQueries.ts
1380
+ /**
1381
+ * The `useQueries` primitive can be used to fetch a variable number of queries.
1382
+ *
1383
+ * The `queries` key accepts an array with query option objects mostly identical to `useQuery` — see
1384
+ * `placeholderData` below for the one difference. A custom `QueryClient` is supplied once, as `useQueries`'
1385
+ * own top-level second argument, rather than per query.
1386
+ *
1387
+ * Having the same query key more than once in the array of query objects may cause some data to be shared
1388
+ * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
1389
+ * structure.
1390
+ *
1391
+ * The `combine` option can be used to combine the results of the queries into a single value. The result will
1392
+ * be structurally shared to be as referentially stable as possible.
1393
+ *
1394
+ * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
1395
+ * previously rendered queries, because the number of queries can differ between renders.
1396
+ * @param queriesOptions - An accessor returning the `queries` array to run, and an optional `combine`
1397
+ * function.
1398
+ * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
1399
+ * will be used.
1400
+ * @returns The combined result. Without `combine`, this is an array with all the query results, in the same
1401
+ * order as the input. When `combine` is provided, this is the value returned by `combine` instead.
1402
+ * @example
1403
+ * ```tsx
1404
+ * import { For } from 'solid-js'
1405
+ * import { useQueries } from '@tanstack/solid-query'
1406
+ *
1407
+ * function Posts(props: { ids: Array<number> }) {
1408
+ * const postQueries = useQueries(() => ({
1409
+ * queries: props.ids.map((id) => ({
1410
+ * queryKey: ['post', id],
1411
+ * queryFn: () => fetchPost(id),
1412
+ * staleTime: Infinity,
1413
+ * })),
1414
+ * }))
1415
+ *
1416
+ * return (
1417
+ * <ul>
1418
+ * <For each={postQueries}>
1419
+ * {(postQuery) => {
1420
+ * if (postQuery.isPending) return <li>Loading...</li>
1421
+ * if (postQuery.isError) return <li>Error: {postQuery.error.message}</li>
1422
+ * return <li>{postQuery.data.title}</li>
1423
+ * }}
1424
+ * </For>
1425
+ * </ul>
1426
+ * )
1427
+ * }
1428
+ * ```
1429
+ * @example
1430
+ * Combining results into a single value:
1431
+ * ```tsx
1432
+ * import { For, Match, Switch } from 'solid-js'
1433
+ * import { useQueries } from '@tanstack/solid-query'
1434
+ *
1435
+ * function Posts(props: { ids: Array<number> }) {
1436
+ * const combinedPostsQuery = useQueries(() => ({
1437
+ * queries: props.ids.map((id) => ({
1438
+ * queryKey: ['post', id],
1439
+ * queryFn: () => fetchPost(id),
1440
+ * })),
1441
+ * combine: (postQueries) => {
1442
+ * return {
1443
+ * data: postQueries.map((postQuery) => postQuery.data),
1444
+ * isPending: postQueries.some((postQuery) => postQuery.isPending),
1445
+ * isError: postQueries.some((postQuery) => postQuery.isError),
1446
+ * }
1447
+ * },
1448
+ * }))
1449
+ *
1450
+ * return (
1451
+ * <Switch
1452
+ * fallback={
1453
+ * <ul>
1454
+ * <For each={combinedPostsQuery.data}>{(post) => <li>{post?.title}</li>}</For>
1455
+ * </ul>
1456
+ * }
1457
+ * >
1458
+ * <Match when={combinedPostsQuery.isPending}>Loading...</Match>
1459
+ * <Match when={combinedPostsQuery.isError}>Error loading posts</Match>
1460
+ * </Switch>
1461
+ * )
1462
+ * }
1463
+ * ```
1464
+ */
855
1465
  function useQueries(queriesOptions, queryClient) {
856
- const length = solidJs.createMemo(() => queriesOptions().queries.length);
857
- const results = solidJs.repeat(length, (index) => {
858
- let lastOptions;
859
- return useBaseQuery(
860
- () => {
861
- const next = queriesOptions().queries[index];
862
- if (next !== void 0) lastOptions = next;
863
- return lastOptions;
864
- },
865
- queryCore.QueryObserver,
866
- queryClient
867
- );
868
- });
869
- const combined = solidJs.createMemo(() => {
870
- const combine = queriesOptions().combine;
871
- const list = results();
872
- return combine ? combine(list) : list;
873
- });
874
- return new Proxy([], {
875
- get(_, prop) {
876
- if (prop === solidJs.$TRACK) return combined();
877
- return Reflect.get(combined(), prop);
878
- },
879
- has(_, prop) {
880
- if (prop === solidJs.$TRACK) return true;
881
- return Reflect.has(combined(), prop);
882
- },
883
- ownKeys() {
884
- return Reflect.ownKeys(combined());
885
- },
886
- getOwnPropertyDescriptor(_, prop) {
887
- const descriptor = Reflect.getOwnPropertyDescriptor(
888
- combined(),
889
- prop
890
- );
891
- if (descriptor) descriptor.configurable = true;
892
- return descriptor;
893
- }
894
- });
1466
+ /**
1467
+ * One read layer per position, count-keyed: each row owns a full
1468
+ * `useBaseQuery` (observer lifecycle, version signal, async data node)
1469
+ * whose options stay reactive through the per-index accessor — option
1470
+ * changes flow into the existing row without tearing it down, while
1471
+ * length changes create/dispose tail rows. Every result has identical
1472
+ * semantics to `useQuery`: reads suspend, settled data is non-nullable.
1473
+ */
1474
+ const length = (0, solid_js.createMemo)(() => queriesOptions().queries.length);
1475
+ const results = (0, solid_js.repeat)(length, (index) => {
1476
+ let lastOptions;
1477
+ return useBaseQuery(() => {
1478
+ const next = queriesOptions().queries[index];
1479
+ if (next !== void 0) lastOptions = next;
1480
+ return lastOptions;
1481
+ }, _tanstack_query_core.QueryObserver, queryClient);
1482
+ });
1483
+ const combined = (0, solid_js.createMemo)(() => {
1484
+ const combine = queriesOptions().combine;
1485
+ const list = results();
1486
+ return combine ? combine(list) : list;
1487
+ });
1488
+ return new Proxy([], {
1489
+ get(_, prop) {
1490
+ if (prop === solid_js.$TRACK) return combined();
1491
+ return Reflect.get(combined(), prop);
1492
+ },
1493
+ has(_, prop) {
1494
+ if (prop === solid_js.$TRACK) return true;
1495
+ return Reflect.has(combined(), prop);
1496
+ },
1497
+ ownKeys() {
1498
+ return Reflect.ownKeys(combined());
1499
+ },
1500
+ getOwnPropertyDescriptor(_, prop) {
1501
+ const descriptor = Reflect.getOwnPropertyDescriptor(combined(), prop);
1502
+ if (descriptor) descriptor.configurable = true;
1503
+ return descriptor;
1504
+ }
1505
+ });
895
1506
  }
896
-
1507
+ // src/index.ts
1508
+ /* istanbul ignore file */
1509
+ exports.FLIGHT_DATA_SOURCE = FLIGHT_DATA_SOURCE;
1510
+ exports.IsRestoringContext = IsRestoringContext;
1511
+ exports.QueryClient = QueryClient;
1512
+ exports.QueryClientContext = QueryClientContext;
1513
+ exports.QueryClientProvider = QueryClientProvider;
897
1514
  exports.dehydrateSettled = dehydrateSettled;
898
1515
  exports.infiniteQueryOptions = infiniteQueryOptions;
899
1516
  exports.mutationOptions = mutationOptions;
@@ -901,13 +1518,17 @@ exports.queryOptions = queryOptions;
901
1518
  exports.useInfiniteQuery = useInfiniteQuery;
902
1519
  exports.useIsFetching = useIsFetching;
903
1520
  exports.useIsMutating = useIsMutating;
1521
+ exports.useIsRestoring = useIsRestoring;
904
1522
  exports.useMutation = useMutation;
905
1523
  exports.useMutationState = useMutationState;
906
1524
  exports.useQueries = useQueries;
907
1525
  exports.useQuery = useQuery;
908
- Object.keys(queryCore).forEach(function (k) {
909
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
910
- enumerable: true,
911
- get: function () { return queryCore[k]; }
912
- });
1526
+ exports.useQueryClient = useQueryClient;
1527
+ Object.keys(_tanstack_query_core).forEach(function(k) {
1528
+ if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
1529
+ enumerable: true,
1530
+ get: function() {
1531
+ return _tanstack_query_core[k];
1532
+ }
1533
+ });
913
1534
  });