4196 lines
159 KiB
JavaScript
4196 lines
159 KiB
JavaScript
import {
|
|
require_jsx_runtime
|
|
} from "./chunk-3YC6FNW3.js";
|
|
import {
|
|
__privateAdd,
|
|
__privateGet,
|
|
__privateMethod,
|
|
__privateSet,
|
|
__privateWrapper,
|
|
__toESM,
|
|
require_react
|
|
} from "./chunk-VL44HY2N.js";
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/QueryClientProvider.js
|
|
var React = __toESM(require_react(), 1);
|
|
var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
|
|
var QueryClientContext = React.createContext(void 0);
|
|
var useQueryClient = (queryClient) => {
|
|
const client = React.useContext(QueryClientContext);
|
|
if (queryClient) return queryClient;
|
|
if (!client) throw new Error("No QueryClient set, use QueryClientProvider to set one");
|
|
return client;
|
|
};
|
|
var QueryClientProvider = ({ client, children }) => {
|
|
React.useEffect(() => {
|
|
client.mount();
|
|
return () => {
|
|
client.unmount();
|
|
};
|
|
}, [client]);
|
|
return (0, import_jsx_runtime.jsx)(QueryClientContext.Provider, {
|
|
value: client,
|
|
children
|
|
});
|
|
};
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/HydrationBoundary.js
|
|
var React2 = __toESM(require_react(), 1);
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/timeoutManager.js
|
|
var defaultTimeoutProvider = {
|
|
setTimeout: (callback, delay) => setTimeout(callback, delay),
|
|
clearTimeout: (timeoutId) => clearTimeout(timeoutId),
|
|
setInterval: (callback, delay) => setInterval(callback, delay),
|
|
clearInterval: (intervalId) => clearInterval(intervalId)
|
|
};
|
|
var _provider, _providerCalled, _a;
|
|
var TimeoutManager = (_a = class {
|
|
constructor() {
|
|
__privateAdd(this, _provider, defaultTimeoutProvider);
|
|
__privateAdd(this, _providerCalled, false);
|
|
}
|
|
/**
|
|
* `setTimeoutProvider` can be used to set a custom implementation of the
|
|
* `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval` functions,
|
|
* called a `TimeoutProvider`.
|
|
*
|
|
* This may be useful if you notice event loop performance issues with
|
|
* thousands of queries. A custom TimeoutProvider could also support timer
|
|
* delays longer than the global `setTimeout` maximum delay value of about
|
|
* 24 days.
|
|
*
|
|
* It is important to call `setTimeoutProvider` before creating a
|
|
* QueryClient or queries, so that the same provider is used consistently
|
|
* for all timers in the application, since different TimeoutProviders
|
|
* cannot cancel each others' timers.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { timeoutManager, QueryClient } from '@tanstack/query-core'
|
|
* import { CustomTimeoutProvider } from './CustomTimeoutProvider'
|
|
*
|
|
* timeoutManager.setTimeoutProvider(new CustomTimeoutProvider())
|
|
*
|
|
* export const queryClient = new QueryClient()
|
|
* ```
|
|
*/
|
|
setTimeoutProvider(provider) {
|
|
if (true) {
|
|
if (__privateGet(this, _providerCalled) && provider !== __privateGet(this, _provider)) console.error(`[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`, {
|
|
previous: __privateGet(this, _provider),
|
|
provider
|
|
});
|
|
}
|
|
__privateSet(this, _provider, provider);
|
|
if (true) __privateSet(this, _providerCalled, false);
|
|
}
|
|
/**
|
|
* `setTimeout` schedules a callback to run after approximately `delay`
|
|
* milliseconds, like the global `setTimeout` function. The callback can be
|
|
* canceled with `clearTimeout`.
|
|
*
|
|
* It returns a timer ID, which may be a number or an object that can be
|
|
* coerced to a number via `Symbol.toPrimitive`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { timeoutManager } from '@tanstack/query-core'
|
|
*
|
|
* const timeoutId = timeoutManager.setTimeout(
|
|
* () => console.log('ran at:', new Date()),
|
|
* 1000,
|
|
* )
|
|
*
|
|
* const timeoutIdNumber: number = Number(timeoutId)
|
|
* ```
|
|
*/
|
|
setTimeout(callback, delay) {
|
|
if (true) __privateSet(this, _providerCalled, true);
|
|
return __privateGet(this, _provider).setTimeout(callback, delay);
|
|
}
|
|
/**
|
|
* `clearTimeout` cancels a timeout callback scheduled with `setTimeout`,
|
|
* like the global `clearTimeout` function. It should be called with a
|
|
* timer ID returned by `setTimeout`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { timeoutManager } from '@tanstack/query-core'
|
|
*
|
|
* const timeoutId = timeoutManager.setTimeout(
|
|
* () => console.log('ran at:', new Date()),
|
|
* 1000,
|
|
* )
|
|
*
|
|
* timeoutManager.clearTimeout(timeoutId)
|
|
* ```
|
|
*/
|
|
clearTimeout(timeoutId) {
|
|
__privateGet(this, _provider).clearTimeout(timeoutId);
|
|
}
|
|
/**
|
|
* `setInterval` schedules a callback to be called approximately every
|
|
* `delay` milliseconds, like the global `setInterval` function.
|
|
*
|
|
* Like `setTimeout`, it returns a timer ID, which may be a number or an
|
|
* object that can be coerced to a number via `Symbol.toPrimitive`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { timeoutManager } from '@tanstack/query-core'
|
|
*
|
|
* const intervalId = timeoutManager.setInterval(
|
|
* () => console.log('ran at:', new Date()),
|
|
* 1000,
|
|
* )
|
|
* ```
|
|
*/
|
|
setInterval(callback, delay) {
|
|
if (true) __privateSet(this, _providerCalled, true);
|
|
return __privateGet(this, _provider).setInterval(callback, delay);
|
|
}
|
|
/**
|
|
* `clearInterval` can be used to cancel an interval, like the global
|
|
* `clearInterval` function. It should be called with an interval ID
|
|
* returned by `setInterval`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { timeoutManager } from '@tanstack/query-core'
|
|
*
|
|
* const intervalId = timeoutManager.setInterval(
|
|
* () => console.log('ran at:', new Date()),
|
|
* 1000,
|
|
* )
|
|
*
|
|
* timeoutManager.clearInterval(intervalId)
|
|
* ```
|
|
*/
|
|
clearInterval(intervalId) {
|
|
__privateGet(this, _provider).clearInterval(intervalId);
|
|
}
|
|
}, _provider = new WeakMap(), _providerCalled = new WeakMap(), _a);
|
|
var timeoutManager = new TimeoutManager();
|
|
function systemSetTimeoutZero(callback) {
|
|
setTimeout(callback, 0);
|
|
}
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/utils.js
|
|
var isServer = typeof window === "undefined" || "Deno" in globalThis;
|
|
function noop() {
|
|
}
|
|
function functionalUpdate(updater, input) {
|
|
return typeof updater === "function" ? updater(input) : updater;
|
|
}
|
|
function isValidTimeout(value) {
|
|
return typeof value === "number" && value >= 0 && value !== Infinity;
|
|
}
|
|
function timeUntilStale(updatedAt, staleTime) {
|
|
return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
|
|
}
|
|
function resolveQueryValue(value, query) {
|
|
return typeof value === "function" ? value(query) : value;
|
|
}
|
|
function matchQuery(filters, query) {
|
|
const { type = "all", exact, fetchStatus, predicate, queryKey, stale } = filters;
|
|
if (queryKey) {
|
|
if (exact) {
|
|
if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) return false;
|
|
} else if (!partialMatchKey(query.queryKey, queryKey)) return false;
|
|
}
|
|
if (type !== "all") {
|
|
const isActive = query.isActive();
|
|
if (type === "active" && !isActive) return false;
|
|
if (type === "inactive" && isActive) return false;
|
|
}
|
|
if (typeof stale === "boolean" && query.isStale() !== stale) return false;
|
|
if (fetchStatus && fetchStatus !== query.state.fetchStatus) return false;
|
|
if (predicate && !predicate(query)) return false;
|
|
return true;
|
|
}
|
|
function matchMutation(filters, mutation) {
|
|
const { exact, status, predicate, mutationKey } = filters;
|
|
if (mutationKey) {
|
|
if (!mutation.options.mutationKey) return false;
|
|
if (exact) {
|
|
if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) return false;
|
|
} else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) return false;
|
|
}
|
|
if (status && mutation.state.status !== status) return false;
|
|
if (predicate && !predicate(mutation)) return false;
|
|
return true;
|
|
}
|
|
function hashQueryKeyByOptions(queryKey, options) {
|
|
return ((options == null ? void 0 : options.queryKeyHashFn) || hashKey)(queryKey);
|
|
}
|
|
function hashKey(queryKey) {
|
|
return JSON.stringify(queryKey, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
|
|
result[key] = val[key];
|
|
return result;
|
|
}, {}) : val);
|
|
}
|
|
function partialMatchKey(a, b) {
|
|
if (a === b) return true;
|
|
if (typeof a !== typeof b) return false;
|
|
if (a && b && typeof a === "object" && typeof b === "object") {
|
|
if (Array.isArray(a) && Array.isArray(b)) {
|
|
if (b.length > a.length) return false;
|
|
for (let i = 0; i < b.length; i++) if (!partialMatchKey(a[i], b[i])) return false;
|
|
return true;
|
|
}
|
|
const bKeys = Object.keys(b);
|
|
for (const key of bKeys) if (!partialMatchKey(a[key], b[key])) return false;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
var hasOwn = Object.prototype.hasOwnProperty;
|
|
function replaceEqualDeep(a, b, depth = 0) {
|
|
if (a === b) return a;
|
|
if (depth > 500) return b;
|
|
const array = isPlainArray(a) && isPlainArray(b);
|
|
if (!array && !(isPlainObject(a) && isPlainObject(b))) return b;
|
|
const aSize = (array ? a : Object.keys(a)).length;
|
|
const bItems = array ? b : Object.keys(b);
|
|
const bSize = bItems.length;
|
|
const copy = array ? new Array(bSize) : {};
|
|
let equalItems = 0;
|
|
for (let i = 0; i < bSize; i++) {
|
|
const key = array ? i : bItems[i];
|
|
const aItem = a[key];
|
|
const bItem = b[key];
|
|
if (aItem === bItem) {
|
|
copy[key] = aItem;
|
|
if (array ? i < aSize : hasOwn.call(a, key)) equalItems++;
|
|
continue;
|
|
}
|
|
if (aItem === null || bItem === null || typeof aItem !== "object" || typeof bItem !== "object") {
|
|
copy[key] = bItem;
|
|
continue;
|
|
}
|
|
const v = replaceEqualDeep(aItem, bItem, depth + 1);
|
|
copy[key] = v;
|
|
if (v === aItem) equalItems++;
|
|
}
|
|
return aSize === bSize && equalItems === aSize ? a : copy;
|
|
}
|
|
function shallowEqualObjects(a, b) {
|
|
if (!b || Object.keys(a).length !== Object.keys(b).length) return false;
|
|
for (const key in a) if (a[key] !== b[key]) return false;
|
|
return true;
|
|
}
|
|
function isPlainArray(value) {
|
|
return Array.isArray(value) && value.length === Object.keys(value).length;
|
|
}
|
|
function isPlainObject(o) {
|
|
if (!hasObjectPrototype(o)) return false;
|
|
const objectPrototype = Object.getPrototypeOf(o);
|
|
const ctor = objectPrototype == null ? void 0 : objectPrototype.constructor;
|
|
if (ctor === void 0) return true;
|
|
if (typeof ctor !== "function") return false;
|
|
const prot = ctor.prototype;
|
|
if (!hasObjectPrototype(prot)) return false;
|
|
if (!prot.hasOwnProperty("isPrototypeOf")) return false;
|
|
if (objectPrototype !== Object.prototype) return false;
|
|
return true;
|
|
}
|
|
function hasObjectPrototype(o) {
|
|
return Object.prototype.toString.call(o) === "[object Object]";
|
|
}
|
|
function sleep(timeout) {
|
|
return new Promise((resolve) => {
|
|
timeoutManager.setTimeout(resolve, timeout);
|
|
});
|
|
}
|
|
function replaceData(prevData, data, options) {
|
|
if (typeof options.structuralSharing === "function") return options.structuralSharing(prevData, data);
|
|
else if (options.structuralSharing !== false) {
|
|
if (true) try {
|
|
return replaceEqualDeep(prevData, data);
|
|
} catch (error) {
|
|
console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`);
|
|
throw error;
|
|
}
|
|
return replaceEqualDeep(prevData, data);
|
|
}
|
|
return data;
|
|
}
|
|
function keepPreviousData(previousData) {
|
|
return previousData;
|
|
}
|
|
function addToEnd(items, item, max = 0) {
|
|
const newItems = [...items, item];
|
|
return max && newItems.length > max ? newItems.slice(1) : newItems;
|
|
}
|
|
function addToStart(items, item, max = 0) {
|
|
const newItems = [item, ...items];
|
|
return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
|
|
}
|
|
var skipToken = Symbol();
|
|
function ensureQueryFn(options, fetchOptions) {
|
|
if (true) {
|
|
if (options.queryFn === skipToken) console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`);
|
|
}
|
|
if (!options.queryFn && (fetchOptions == null ? void 0 : fetchOptions.initialPromise)) return () => fetchOptions.initialPromise;
|
|
if (!options.queryFn || options.queryFn === skipToken) return () => Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`));
|
|
return options.queryFn;
|
|
}
|
|
function shouldThrowError(throwOnError, params) {
|
|
if (typeof throwOnError === "function") return throwOnError(...params);
|
|
return !!throwOnError;
|
|
}
|
|
function addConsumeAwareSignal(object, getSignal, onCancelled) {
|
|
let consumed = false;
|
|
let signal;
|
|
Object.defineProperty(object, "signal", {
|
|
enumerable: true,
|
|
get: () => {
|
|
signal ?? (signal = getSignal());
|
|
if (consumed) return signal;
|
|
consumed = true;
|
|
if (signal.aborted) onCancelled();
|
|
else signal.addEventListener("abort", onCancelled, { once: true });
|
|
return signal;
|
|
}
|
|
});
|
|
return object;
|
|
}
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/environmentManager.js
|
|
var isServerFn = () => isServer;
|
|
var isServer2 = () => isServerFn();
|
|
var environmentManager = {
|
|
isServer: isServer2,
|
|
/**
|
|
* Overrides the server check globally.
|
|
*/
|
|
setIsServer(isServerValue) {
|
|
isServerFn = isServerValue;
|
|
}
|
|
};
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/subscribable.js
|
|
var Subscribable = class {
|
|
constructor() {
|
|
this.listeners = /* @__PURE__ */ new Set();
|
|
this.subscribe = this.subscribe.bind(this);
|
|
}
|
|
subscribe(listener) {
|
|
this.listeners.add(listener);
|
|
this.onSubscribe();
|
|
return () => {
|
|
this.listeners.delete(listener);
|
|
this.onUnsubscribe();
|
|
};
|
|
}
|
|
hasListeners() {
|
|
return this.listeners.size > 0;
|
|
}
|
|
onSubscribe() {
|
|
}
|
|
onUnsubscribe() {
|
|
}
|
|
};
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/focusManager.js
|
|
var _focused, _cleanup, _setup, _a2;
|
|
var FocusManager = (_a2 = class extends Subscribable {
|
|
constructor() {
|
|
super();
|
|
__privateAdd(this, _focused);
|
|
__privateAdd(this, _cleanup);
|
|
__privateAdd(this, _setup);
|
|
__privateSet(this, _setup, (onFocus) => {
|
|
if (typeof window !== "undefined" && window.addEventListener) {
|
|
const listener = () => onFocus();
|
|
window.addEventListener("visibilitychange", listener, false);
|
|
return () => {
|
|
window.removeEventListener("visibilitychange", listener);
|
|
};
|
|
}
|
|
});
|
|
}
|
|
onSubscribe() {
|
|
if (!__privateGet(this, _cleanup)) this.setEventListener(__privateGet(this, _setup));
|
|
}
|
|
onUnsubscribe() {
|
|
var _a13;
|
|
if (!this.hasListeners()) {
|
|
(_a13 = __privateGet(this, _cleanup)) == null ? void 0 : _a13.call(this);
|
|
__privateSet(this, _cleanup, void 0);
|
|
}
|
|
}
|
|
/**
|
|
* `setEventListener` can be used to set a custom event listener that will
|
|
* be used to determine the focus state. The provided `setup` function
|
|
* receives a `setFocused` callback: call it with a `boolean` to manually
|
|
* set the focus state, or with no arguments to re-evaluate the current
|
|
* focus state and notify subscribers.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { focusManager } from '@tanstack/query-core'
|
|
*
|
|
* focusManager.setEventListener((handleFocus) => {
|
|
* const listener = () => handleFocus()
|
|
* // Listen to visibilitychange
|
|
* if (typeof window !== 'undefined' && window.addEventListener) {
|
|
* window.addEventListener('visibilitychange', listener, false)
|
|
* }
|
|
*
|
|
* return () => {
|
|
* // Be sure to unsubscribe if a new handler is set
|
|
* window.removeEventListener('visibilitychange', listener)
|
|
* }
|
|
* })
|
|
* ```
|
|
*/
|
|
setEventListener(setup) {
|
|
var _a13;
|
|
__privateSet(this, _setup, setup);
|
|
(_a13 = __privateGet(this, _cleanup)) == null ? void 0 : _a13.call(this);
|
|
__privateSet(this, _cleanup, setup((focused) => {
|
|
if (typeof focused === "boolean") this.setFocused(focused);
|
|
else this.onFocus();
|
|
}));
|
|
}
|
|
/**
|
|
* `setFocused` can be used to manually set the focus state. Set `undefined`
|
|
* to fall back to the default focus check.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { focusManager } from '@tanstack/query-core'
|
|
*
|
|
* // Set focused
|
|
* focusManager.setFocused(true)
|
|
*
|
|
* // Set unfocused
|
|
* focusManager.setFocused(false)
|
|
*
|
|
* // Fallback to the default focus check
|
|
* focusManager.setFocused(undefined)
|
|
* ```
|
|
*/
|
|
setFocused(focused) {
|
|
if (__privateGet(this, _focused) !== focused) {
|
|
__privateSet(this, _focused, focused);
|
|
this.onFocus();
|
|
}
|
|
}
|
|
/**
|
|
* `onFocus` notifies all subscribed listeners with the current focus state.
|
|
*/
|
|
onFocus() {
|
|
const isFocused = this.isFocused();
|
|
this.listeners.forEach((listener) => {
|
|
listener(isFocused);
|
|
});
|
|
}
|
|
/**
|
|
* `isFocused` can be used to get the current focus state.
|
|
*/
|
|
isFocused() {
|
|
var _a13;
|
|
if (typeof __privateGet(this, _focused) === "boolean") return __privateGet(this, _focused);
|
|
return ((_a13 = globalThis.document) == null ? void 0 : _a13.visibilityState) !== "hidden";
|
|
}
|
|
}, _focused = new WeakMap(), _cleanup = new WeakMap(), _setup = new WeakMap(), _a2);
|
|
var focusManager = new FocusManager();
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/hydration.js
|
|
function tryResolveSync(promise) {
|
|
var _a13, _b;
|
|
let data;
|
|
(_b = (_a13 = promise.then((result) => {
|
|
data = result;
|
|
return result;
|
|
}, noop)) == null ? void 0 : _a13.catch) == null ? void 0 : _b.call(_a13, noop);
|
|
if (data !== void 0) return { data };
|
|
}
|
|
function dehydrateMutation(mutation) {
|
|
return {
|
|
mutationKey: mutation.options.mutationKey,
|
|
state: mutation.state,
|
|
...mutation.options.scope && { scope: mutation.options.scope },
|
|
...mutation.meta && { meta: mutation.meta }
|
|
};
|
|
}
|
|
function dehydratePromise(query, serializeData, shouldRedactErrors) {
|
|
var _a13;
|
|
const promise = (_a13 = query.promise) == null ? void 0 : _a13.then(serializeData).catch((error) => {
|
|
if ((shouldRedactErrors == null ? void 0 : shouldRedactErrors(error)) === false) return Promise.reject(error);
|
|
if (true) console.error(`A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`);
|
|
return Promise.reject(new Error("redacted"));
|
|
});
|
|
promise == null ? void 0 : promise.catch(noop);
|
|
return promise;
|
|
}
|
|
function dehydrateQuery(query, serializeData, shouldRedactErrors) {
|
|
return {
|
|
dehydratedAt: Date.now(),
|
|
state: {
|
|
...query.state,
|
|
...query.state.data !== void 0 && { data: serializeData ? serializeData(query.state.data) : query.state.data }
|
|
},
|
|
queryKey: query.queryKey,
|
|
queryHash: query.queryHash,
|
|
...query.state.status === "pending" && { promise: dehydratePromise(query, serializeData, shouldRedactErrors) },
|
|
...query.meta && { meta: query.meta },
|
|
...query.queryType && { queryType: query.queryType }
|
|
};
|
|
}
|
|
function defaultShouldDehydrateMutation(mutation) {
|
|
return mutation.state.isPaused;
|
|
}
|
|
function defaultShouldDehydrateQuery(query) {
|
|
return query.state.status === "success";
|
|
}
|
|
function dehydrate(client, options = {}) {
|
|
var _a13, _b, _c, _d;
|
|
const filterMutation = options.shouldDehydrateMutation ?? ((_a13 = client.getDefaultOptions().dehydrate) == null ? void 0 : _a13.shouldDehydrateMutation) ?? defaultShouldDehydrateMutation;
|
|
const mutations = client.getMutationCache().getAll().flatMap((mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []);
|
|
const filterQuery = options.shouldDehydrateQuery ?? ((_b = client.getDefaultOptions().dehydrate) == null ? void 0 : _b.shouldDehydrateQuery) ?? defaultShouldDehydrateQuery;
|
|
const shouldRedactErrors = options.shouldRedactErrors ?? ((_c = client.getDefaultOptions().dehydrate) == null ? void 0 : _c.shouldRedactErrors);
|
|
const serializeData = options.serializeData ?? ((_d = client.getDefaultOptions().dehydrate) == null ? void 0 : _d.serializeData);
|
|
return {
|
|
mutations,
|
|
queries: client.getQueryCache().getAll().flatMap((query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : [])
|
|
};
|
|
}
|
|
function hydrate(client, dehydratedState, options) {
|
|
var _a13, _b, _c, _d;
|
|
const mutationCache = client.getMutationCache();
|
|
const queryCache = client.getQueryCache();
|
|
const deserializeData = ((_a13 = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _a13.deserializeData) ?? ((_b = client.getDefaultOptions().hydrate) == null ? void 0 : _b.deserializeData);
|
|
(_c = dehydratedState.mutations) == null ? void 0 : _c.forEach(({ state, ...mutationOptions2 }) => {
|
|
var _a14, _b2;
|
|
mutationCache.build(client, {
|
|
...(_a14 = client.getDefaultOptions().hydrate) == null ? void 0 : _a14.mutations,
|
|
...(_b2 = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _b2.mutations,
|
|
...mutationOptions2
|
|
}, state);
|
|
});
|
|
(_d = dehydratedState.queries) == null ? void 0 : _d.forEach(({ queryKey, state, queryHash, meta, promise, dehydratedAt, queryType }) => {
|
|
var _a14, _b2;
|
|
const syncData = promise ? tryResolveSync(promise) : void 0;
|
|
const rawData = state.data === void 0 ? syncData == null ? void 0 : syncData.data : state.data;
|
|
const data = rawData === void 0 ? rawData : deserializeData ? deserializeData(rawData) : rawData;
|
|
let query = queryCache.get(queryHash);
|
|
const existingQueryIsPending = (query == null ? void 0 : query.state.status) === "pending";
|
|
const existingQueryIsFetching = (query == null ? void 0 : query.state.fetchStatus) === "fetching";
|
|
if (query) {
|
|
const hasNewerSyncData = syncData && dehydratedAt > query.state.dataUpdatedAt;
|
|
if (state.dataUpdatedAt > query.state.dataUpdatedAt || hasNewerSyncData) {
|
|
const { fetchStatus: _ignored, ...serializedState } = state;
|
|
query.setState({
|
|
...serializedState,
|
|
data,
|
|
...state.status === "pending" && data !== void 0 && {
|
|
status: "success",
|
|
dataUpdatedAt: dehydratedAt,
|
|
...!existingQueryIsFetching && { fetchStatus: "idle" }
|
|
}
|
|
});
|
|
}
|
|
} else query = queryCache.build(client, {
|
|
...(_a14 = client.getDefaultOptions().hydrate) == null ? void 0 : _a14.queries,
|
|
...(_b2 = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _b2.queries,
|
|
queryKey,
|
|
queryHash,
|
|
meta,
|
|
_type: queryType
|
|
}, {
|
|
...state,
|
|
data,
|
|
fetchStatus: "idle",
|
|
status: state.status === "pending" && data !== void 0 ? "success" : state.status,
|
|
...state.status === "pending" && data !== void 0 && { dataUpdatedAt: dehydratedAt }
|
|
});
|
|
if (promise && !syncData && !existingQueryIsPending && !existingQueryIsFetching && dehydratedAt > query.state.dataUpdatedAt) query.fetch(void 0, { initialPromise: Promise.resolve(promise).then(deserializeData) }).catch(noop);
|
|
});
|
|
}
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/notifyManager.js
|
|
var defaultScheduler = systemSetTimeoutZero;
|
|
function createNotifyManager() {
|
|
let queue = [];
|
|
let transactions = 0;
|
|
let notifyFn = (callback) => {
|
|
callback();
|
|
};
|
|
let batchNotifyFn = (callback) => {
|
|
callback();
|
|
};
|
|
let scheduleFn = defaultScheduler;
|
|
const schedule = (callback) => {
|
|
if (transactions) queue.push(callback);
|
|
else scheduleFn(() => {
|
|
notifyFn(callback);
|
|
});
|
|
};
|
|
const flush = () => {
|
|
const originalQueue = queue;
|
|
queue = [];
|
|
if (originalQueue.length) scheduleFn(() => {
|
|
batchNotifyFn(() => {
|
|
originalQueue.forEach((callback) => {
|
|
notifyFn(callback);
|
|
});
|
|
});
|
|
});
|
|
};
|
|
return {
|
|
/**
|
|
* Batches all updates scheduled inside the passed callback.
|
|
* This is mainly used internally to optimize query client updating.
|
|
* Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.
|
|
* The return value of `callback` is passed through.
|
|
*/
|
|
batch: (callback) => {
|
|
let result;
|
|
transactions++;
|
|
try {
|
|
result = callback();
|
|
} finally {
|
|
transactions--;
|
|
if (!transactions) flush();
|
|
}
|
|
return result;
|
|
},
|
|
/**
|
|
* All calls to the wrapped function will be batched.
|
|
*/
|
|
batchCalls: (callback) => {
|
|
return (...args) => {
|
|
schedule(() => {
|
|
callback(...args);
|
|
});
|
|
};
|
|
},
|
|
/**
|
|
* Schedules a function to be run on the next batch.
|
|
* By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.
|
|
*/
|
|
schedule,
|
|
/**
|
|
* Use this method to set a custom notify function.
|
|
* This can be used to for example wrap notifications with `React.act` while running tests.
|
|
*/
|
|
setNotifyFunction: (fn) => {
|
|
notifyFn = fn;
|
|
},
|
|
/**
|
|
* Use this method to set a custom function to batch notifications together into a single tick.
|
|
* Framework adapters use this to plug in their own batching primitive, so that a single query
|
|
* update only triggers one re-render instead of one per subscriber.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { notifyManager } from '@tanstack/query-core'
|
|
* import { batch } from 'solid-js'
|
|
*
|
|
* notifyManager.setBatchNotifyFunction(batch)
|
|
* ```
|
|
*/
|
|
setBatchNotifyFunction: (fn) => {
|
|
batchNotifyFn = fn;
|
|
},
|
|
/**
|
|
* Configures a custom callback that schedules when the next batch runs.
|
|
* The default behavior is `setTimeout(callback, 0)`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { notifyManager } from '@tanstack/query-core'
|
|
*
|
|
* // Schedule batches in the next microtask
|
|
* notifyManager.setScheduler(queueMicrotask)
|
|
*
|
|
* // Schedule batches before the next frame is rendered
|
|
* notifyManager.setScheduler(requestAnimationFrame)
|
|
*
|
|
* // Schedule batches some time in the future
|
|
* notifyManager.setScheduler((cb) => setTimeout(cb, 10))
|
|
* ```
|
|
*/
|
|
setScheduler: (fn) => {
|
|
scheduleFn = fn;
|
|
}
|
|
};
|
|
}
|
|
var notifyManager = createNotifyManager();
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/onlineManager.js
|
|
var _online, _cleanup2, _setup2, _a3;
|
|
var OnlineManager = (_a3 = class extends Subscribable {
|
|
constructor() {
|
|
super();
|
|
__privateAdd(this, _online, true);
|
|
__privateAdd(this, _cleanup2);
|
|
__privateAdd(this, _setup2);
|
|
__privateSet(this, _setup2, (onOnline) => {
|
|
if (typeof window !== "undefined" && window.addEventListener) {
|
|
const onlineListener = () => onOnline(true);
|
|
const offlineListener = () => onOnline(false);
|
|
window.addEventListener("online", onlineListener, false);
|
|
window.addEventListener("offline", offlineListener, false);
|
|
return () => {
|
|
window.removeEventListener("online", onlineListener);
|
|
window.removeEventListener("offline", offlineListener);
|
|
};
|
|
}
|
|
});
|
|
}
|
|
onSubscribe() {
|
|
if (!__privateGet(this, _cleanup2)) this.setEventListener(__privateGet(this, _setup2));
|
|
}
|
|
onUnsubscribe() {
|
|
var _a13;
|
|
if (!this.hasListeners()) {
|
|
(_a13 = __privateGet(this, _cleanup2)) == null ? void 0 : _a13.call(this);
|
|
__privateSet(this, _cleanup2, void 0);
|
|
}
|
|
}
|
|
/**
|
|
* `setEventListener` can be used to set a custom event listener that will
|
|
* be used to determine the online state. The provided `setup` function
|
|
* receives a `setOnline` callback that should be called with a `boolean`
|
|
* whenever the online state changes.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import NetInfo from '@react-native-community/netinfo'
|
|
* import { onlineManager } from '@tanstack/query-core'
|
|
*
|
|
* onlineManager.setEventListener((setOnline) => {
|
|
* return NetInfo.addEventListener((state) => {
|
|
* setOnline(!!state.isConnected)
|
|
* })
|
|
* })
|
|
* ```
|
|
*/
|
|
setEventListener(setup) {
|
|
var _a13;
|
|
__privateSet(this, _setup2, setup);
|
|
(_a13 = __privateGet(this, _cleanup2)) == null ? void 0 : _a13.call(this);
|
|
__privateSet(this, _cleanup2, setup(this.setOnline.bind(this)));
|
|
}
|
|
/**
|
|
* `setOnline` can be used to manually set the online state.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { onlineManager } from '@tanstack/query-core'
|
|
*
|
|
* // Set to online
|
|
* onlineManager.setOnline(true)
|
|
*
|
|
* // Set to offline
|
|
* onlineManager.setOnline(false)
|
|
* ```
|
|
*/
|
|
setOnline(online) {
|
|
if (__privateGet(this, _online) !== online) {
|
|
__privateSet(this, _online, online);
|
|
this.listeners.forEach((listener) => {
|
|
listener(online);
|
|
});
|
|
}
|
|
}
|
|
/**
|
|
* `isOnline` can be used to get the current online state.
|
|
*/
|
|
isOnline() {
|
|
return __privateGet(this, _online);
|
|
}
|
|
}, _online = new WeakMap(), _cleanup2 = new WeakMap(), _setup2 = new WeakMap(), _a3);
|
|
var onlineManager = new OnlineManager();
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/retryer.js
|
|
function defaultRetryDelay(failureCount) {
|
|
return Math.min(1e3 * 2 ** failureCount, 3e4);
|
|
}
|
|
function canFetch(networkMode) {
|
|
return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true;
|
|
}
|
|
var CancelledError = class extends Error {
|
|
constructor(options) {
|
|
super("CancelledError");
|
|
this.revert = options == null ? void 0 : options.revert;
|
|
this.silent = options == null ? void 0 : options.silent;
|
|
}
|
|
};
|
|
function isCancelledError(value) {
|
|
return value instanceof CancelledError;
|
|
}
|
|
function createRetryer(config) {
|
|
let isRetryCancelled = false;
|
|
let failureCount = 0;
|
|
let continueFn;
|
|
let status = "pending";
|
|
let promiseResolve;
|
|
let promiseReject;
|
|
const promise = new Promise((resolve2, reject2) => {
|
|
promiseResolve = resolve2;
|
|
promiseReject = reject2;
|
|
});
|
|
promise.catch(noop);
|
|
const isResolved = () => status !== "pending";
|
|
const cancel = (cancelOptions) => {
|
|
var _a13;
|
|
if (!isResolved()) {
|
|
const error = new CancelledError(cancelOptions);
|
|
reject(error);
|
|
(_a13 = config.onCancel) == null ? void 0 : _a13.call(config, error);
|
|
}
|
|
};
|
|
const cancelRetry = () => {
|
|
isRetryCancelled = true;
|
|
};
|
|
const continueRetry = () => {
|
|
isRetryCancelled = false;
|
|
};
|
|
const canContinue = () => focusManager.isFocused() && (config.networkMode === "always" || onlineManager.isOnline()) && config.canRun();
|
|
const canStart = () => canFetch(config.networkMode) && config.canRun();
|
|
const resolve = (value) => {
|
|
if (!isResolved()) {
|
|
continueFn == null ? void 0 : continueFn();
|
|
status = "resolved";
|
|
promiseResolve(value);
|
|
}
|
|
};
|
|
const reject = (value) => {
|
|
if (!isResolved()) {
|
|
continueFn == null ? void 0 : continueFn();
|
|
status = "rejected";
|
|
promiseReject(value);
|
|
}
|
|
};
|
|
const pause = () => {
|
|
return new Promise((continueResolve) => {
|
|
var _a13;
|
|
continueFn = (value) => {
|
|
if (isResolved() || canContinue()) continueResolve(value);
|
|
};
|
|
(_a13 = config.onPause) == null ? void 0 : _a13.call(config);
|
|
}).then(() => {
|
|
var _a13;
|
|
continueFn = void 0;
|
|
if (!isResolved()) (_a13 = config.onContinue) == null ? void 0 : _a13.call(config);
|
|
});
|
|
};
|
|
const run = () => {
|
|
if (isResolved()) return;
|
|
let promiseOrValue;
|
|
const initialPromise = failureCount === 0 ? config.initialPromise : void 0;
|
|
try {
|
|
promiseOrValue = initialPromise ?? config.fn();
|
|
} catch (error) {
|
|
promiseOrValue = Promise.reject(error);
|
|
}
|
|
Promise.resolve(promiseOrValue).then(resolve).catch((error) => {
|
|
var _a13;
|
|
if (isResolved()) return;
|
|
const retry = config.retry ?? (isServer2() ? 0 : 3);
|
|
const retryDelay = config.retryDelay ?? defaultRetryDelay;
|
|
const delay = typeof retryDelay === "function" ? retryDelay(failureCount, error) : retryDelay;
|
|
const shouldRetry = retry === true || typeof retry === "number" && failureCount < retry || typeof retry === "function" && retry(failureCount, error);
|
|
if (isRetryCancelled || !shouldRetry) {
|
|
reject(error);
|
|
return;
|
|
}
|
|
failureCount++;
|
|
(_a13 = config.onFail) == null ? void 0 : _a13.call(config, failureCount, error);
|
|
sleep(delay).then(() => {
|
|
return canContinue() ? void 0 : pause();
|
|
}).then(() => {
|
|
if (isRetryCancelled) reject(error);
|
|
else run();
|
|
});
|
|
});
|
|
};
|
|
return {
|
|
promise,
|
|
status: () => status,
|
|
cancel,
|
|
continue: () => {
|
|
continueFn == null ? void 0 : continueFn();
|
|
return promise;
|
|
},
|
|
cancelRetry,
|
|
continueRetry,
|
|
canStart,
|
|
start: () => {
|
|
if (canStart()) run();
|
|
else pause().then(run);
|
|
return promise;
|
|
}
|
|
};
|
|
}
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/removable.js
|
|
var _gcTimeout, _a4;
|
|
var Removable = (_a4 = class {
|
|
constructor() {
|
|
__privateAdd(this, _gcTimeout);
|
|
}
|
|
destroy() {
|
|
this.clearGcTimeout();
|
|
}
|
|
scheduleGc() {
|
|
this.clearGcTimeout();
|
|
if (isValidTimeout(this.gcTime)) __privateSet(this, _gcTimeout, timeoutManager.setTimeout(() => {
|
|
this.optionalRemove();
|
|
}, this.gcTime));
|
|
}
|
|
updateGcTime(newGcTime) {
|
|
this.gcTime = Math.max(this.gcTime || 0, newGcTime ?? (isServer2() ? Infinity : 3e5));
|
|
}
|
|
clearGcTimeout() {
|
|
if (__privateGet(this, _gcTimeout) !== void 0) {
|
|
timeoutManager.clearTimeout(__privateGet(this, _gcTimeout));
|
|
__privateSet(this, _gcTimeout, void 0);
|
|
}
|
|
}
|
|
}, _gcTimeout = new WeakMap(), _a4);
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/infiniteQueryBehavior.js
|
|
function infiniteQueryBehavior(pages) {
|
|
return { onFetch: (context, query) => {
|
|
var _a13, _b, _c, _d, _e;
|
|
const options = context.options;
|
|
const direction = (_c = (_b = (_a13 = context.fetchOptions) == null ? void 0 : _a13.meta) == null ? void 0 : _b.fetchMore) == null ? void 0 : _c.direction;
|
|
const oldPages = ((_d = context.state.data) == null ? void 0 : _d.pages) || [];
|
|
const oldPageParams = ((_e = context.state.data) == null ? void 0 : _e.pageParams) || [];
|
|
let result = {
|
|
pages: [],
|
|
pageParams: []
|
|
};
|
|
let currentPage = 0;
|
|
const fetchFn = async () => {
|
|
let cancelled = false;
|
|
const addSignalProperty = (object) => {
|
|
addConsumeAwareSignal(object, () => context.signal, () => cancelled = true);
|
|
};
|
|
const queryFn = ensureQueryFn(context.options, context.fetchOptions);
|
|
const fetchPage = async (data, param, previous) => {
|
|
if (cancelled) return Promise.reject(context.signal.reason);
|
|
if (param == null && data.pages.length) return Promise.resolve(data);
|
|
const createQueryFnContext = () => {
|
|
const queryFnContext2 = {
|
|
client: context.client,
|
|
queryKey: context.queryKey,
|
|
pageParam: param,
|
|
direction: previous ? "backward" : "forward",
|
|
meta: context.options.meta
|
|
};
|
|
addSignalProperty(queryFnContext2);
|
|
return queryFnContext2;
|
|
};
|
|
const queryFnContext = createQueryFnContext();
|
|
const page = await queryFn(queryFnContext);
|
|
const { maxPages } = context.options;
|
|
const addTo = previous ? addToStart : addToEnd;
|
|
return {
|
|
pages: addTo(data.pages, page, maxPages),
|
|
pageParams: addTo(data.pageParams, param, maxPages)
|
|
};
|
|
};
|
|
if (direction && oldPages.length) {
|
|
const previous = direction === "backward";
|
|
const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
|
|
const oldData = {
|
|
pages: oldPages,
|
|
pageParams: oldPageParams
|
|
};
|
|
result = await fetchPage(oldData, pageParamFn(options, oldData), previous);
|
|
} else {
|
|
const remainingPages = pages ?? oldPages.length;
|
|
do {
|
|
const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);
|
|
if (currentPage > 0 && param == null) break;
|
|
result = await fetchPage(result, param);
|
|
currentPage++;
|
|
} while (currentPage < remainingPages);
|
|
}
|
|
return result;
|
|
};
|
|
if (context.options.persister) context.fetchFn = () => {
|
|
var _a14, _b2;
|
|
return (_b2 = (_a14 = context.options).persister) == null ? void 0 : _b2.call(_a14, fetchFn, {
|
|
client: context.client,
|
|
queryKey: context.queryKey,
|
|
meta: context.options.meta,
|
|
signal: context.signal
|
|
}, query);
|
|
};
|
|
else context.fetchFn = fetchFn;
|
|
} };
|
|
}
|
|
function getNextPageParam(options, { pages, pageParams }) {
|
|
const lastIndex = pages.length - 1;
|
|
return pages.length > 0 ? options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams) : void 0;
|
|
}
|
|
function getPreviousPageParam(options, { pages, pageParams }) {
|
|
var _a13;
|
|
return pages.length > 0 ? (_a13 = options.getPreviousPageParam) == null ? void 0 : _a13.call(options, pages[0], pages, pageParams[0], pageParams) : void 0;
|
|
}
|
|
function hasNextPage(options, data) {
|
|
if (!data) return false;
|
|
return getNextPageParam(options, data) != null;
|
|
}
|
|
function hasPreviousPage(options, data) {
|
|
if (!data || !options.getPreviousPageParam) return false;
|
|
return getPreviousPageParam(options, data) != null;
|
|
}
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/query.js
|
|
var _queryType, _initialState, _revertState, _cache, _client, _retryer, _defaultOptions, _abortSignalConsumed, _Query_instances, dispatch_fn, _a5;
|
|
var Query = (_a5 = class extends Removable {
|
|
constructor(config) {
|
|
super();
|
|
__privateAdd(this, _Query_instances);
|
|
__privateAdd(this, _queryType);
|
|
__privateAdd(this, _initialState);
|
|
__privateAdd(this, _revertState);
|
|
__privateAdd(this, _cache);
|
|
__privateAdd(this, _client);
|
|
__privateAdd(this, _retryer);
|
|
__privateAdd(this, _defaultOptions);
|
|
__privateAdd(this, _abortSignalConsumed);
|
|
__privateSet(this, _abortSignalConsumed, false);
|
|
__privateSet(this, _defaultOptions, config.defaultOptions);
|
|
this.setOptions(config.options);
|
|
this.observers = [];
|
|
__privateSet(this, _client, config.client);
|
|
__privateSet(this, _cache, __privateGet(this, _client).getQueryCache());
|
|
this.queryKey = config.queryKey;
|
|
this.queryHash = config.queryHash;
|
|
__privateSet(this, _initialState, getDefaultState(this.options));
|
|
this.state = config.state ?? __privateGet(this, _initialState);
|
|
this.scheduleGc();
|
|
}
|
|
/**
|
|
* The `meta` object passed in the query's options, if any.
|
|
*/
|
|
get meta() {
|
|
return this.options.meta;
|
|
}
|
|
/** @internal */
|
|
get queryType() {
|
|
return __privateGet(this, _queryType);
|
|
}
|
|
/**
|
|
* The promise for the currently in-flight fetch, if the query is fetching.
|
|
* `undefined` when the query is not fetching.
|
|
*/
|
|
get promise() {
|
|
var _a13;
|
|
return (_a13 = __privateGet(this, _retryer)) == null ? void 0 : _a13.promise;
|
|
}
|
|
/** @internal */
|
|
setOptions(options) {
|
|
this.options = {
|
|
...__privateGet(this, _defaultOptions),
|
|
...options
|
|
};
|
|
if (options == null ? void 0 : options._type) __privateSet(this, _queryType, options._type);
|
|
this.updateGcTime(this.options.gcTime);
|
|
if (this.state && this.state.data === void 0) {
|
|
const defaultState = getDefaultState(this.options);
|
|
if (defaultState.data !== void 0) {
|
|
this.setState(successState(defaultState.data, defaultState.dataUpdatedAt));
|
|
__privateSet(this, _initialState, defaultState);
|
|
}
|
|
}
|
|
}
|
|
optionalRemove() {
|
|
if (!this.observers.length && this.state.fetchStatus === "idle") __privateGet(this, _cache).remove(this);
|
|
}
|
|
/** @internal */
|
|
setData(newData, options) {
|
|
const data = replaceData(this.state.data, newData, this.options);
|
|
__privateMethod(this, _Query_instances, dispatch_fn).call(this, {
|
|
data,
|
|
type: "success",
|
|
dataUpdatedAt: options == null ? void 0 : options.updatedAt,
|
|
manual: options == null ? void 0 : options.manual
|
|
});
|
|
return data;
|
|
}
|
|
/**
|
|
* Merges the given partial state directly into this query's state, notifying observers. Used
|
|
* by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a
|
|
* user manually trigger a loading/error state or edit the cached data.
|
|
*/
|
|
setState(state) {
|
|
__privateMethod(this, _Query_instances, dispatch_fn).call(this, {
|
|
type: "setState",
|
|
state
|
|
});
|
|
}
|
|
/**
|
|
* Cancels the query's currently in-flight fetch, if any.
|
|
* - Returns a promise that resolves once the cancellation has settled.
|
|
* - If no fetch is in progress, resolves immediately.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await query.cancel()
|
|
* ```
|
|
*/
|
|
cancel(options) {
|
|
var _a13, _b;
|
|
const promise = (_a13 = __privateGet(this, _retryer)) == null ? void 0 : _a13.promise;
|
|
(_b = __privateGet(this, _retryer)) == null ? void 0 : _b.cancel(options);
|
|
return promise ? promise.then(noop).catch(noop) : Promise.resolve();
|
|
}
|
|
/**
|
|
* Clears the query's garbage collection timeout and silently cancels any
|
|
* in-flight fetch. Called by `QueryCache` when the query is removed from
|
|
* the cache.
|
|
*
|
|
* @see {@link Query#cancel}
|
|
*/
|
|
destroy() {
|
|
super.destroy();
|
|
this.cancel({ silent: true });
|
|
}
|
|
/** @internal */
|
|
get resetState() {
|
|
return __privateGet(this, _initialState);
|
|
}
|
|
/**
|
|
* Resets the query back to its initial state (the state it had when it was
|
|
* first created, e.g. any `initialData`), destroying it first to cancel any
|
|
* in-flight fetch.
|
|
*/
|
|
reset() {
|
|
this.destroy();
|
|
this.setState(this.resetState);
|
|
}
|
|
/**
|
|
* Returns `true` if the query has at least one observer for which `enabled`
|
|
* does not resolve to `false`.
|
|
*/
|
|
isActive() {
|
|
return this.observers.some((observer) => resolveQueryValue(observer.options.enabled, this) !== false);
|
|
}
|
|
/**
|
|
* Returns `true` if the query is disabled, meaning it will not fetch
|
|
* automatically.
|
|
* - If the query has observers, it is disabled when none of them are active
|
|
* (see `isActive`).
|
|
* - If the query has no observers, it is disabled when its `queryFn` is
|
|
* `skipToken` or it has never been fetched.
|
|
*/
|
|
isDisabled() {
|
|
if (this.getObserversCount() > 0) return !this.isActive();
|
|
return this.options.queryFn === skipToken || !this.isFetched();
|
|
}
|
|
/**
|
|
* Returns `true` if the query has been fetched, i.e. it has resolved with
|
|
* either data or an error at least once.
|
|
*/
|
|
isFetched() {
|
|
return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;
|
|
}
|
|
/**
|
|
* Returns `true` if the query has at least one observer configured with
|
|
* `staleTime: 'static'`, meaning it is treated as never stale.
|
|
*/
|
|
isStatic() {
|
|
if (this.getObserversCount() > 0) return this.observers.some((observer) => resolveQueryValue(observer.options.staleTime, this) === "static");
|
|
return false;
|
|
}
|
|
/**
|
|
* Returns `true` if the query is stale.
|
|
* - If the query has observers, defers to whether any observer's current
|
|
* result reports `isStale` (which accounts for each observer's own
|
|
* `staleTime` and `enabled` state).
|
|
* - If the query has no observers, it is considered stale when it has no
|
|
* data or has been invalidated.
|
|
*
|
|
* @see {@link Query#isStaleByTime}
|
|
* @example
|
|
* ```ts
|
|
* if (query.isStale()) {
|
|
* // refetch or otherwise treat the cached data as outdated
|
|
* }
|
|
* ```
|
|
*/
|
|
isStale() {
|
|
if (this.getObserversCount() > 0) return this.observers.some((observer) => observer.getCurrentResult().isStale);
|
|
return this.state.data === void 0 || this.state.isInvalidated;
|
|
}
|
|
/**
|
|
* Returns `true` if the query's data is stale relative to the given
|
|
* `staleTime` (defaults to `0`).
|
|
* - A query with no data is always stale.
|
|
* - `staleTime: 'static'` is never stale.
|
|
* - An invalidated query is always stale.
|
|
* - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.
|
|
*
|
|
* @see {@link Query#isStale}
|
|
* @example
|
|
* ```ts
|
|
* const isStale = query.isStaleByTime(1000 * 60)
|
|
* ```
|
|
*/
|
|
isStaleByTime(staleTime = 0) {
|
|
if (this.state.data === void 0) return true;
|
|
if (staleTime === "static") return false;
|
|
if (this.state.isInvalidated) return true;
|
|
return !timeUntilStale(this.state.dataUpdatedAt, staleTime);
|
|
}
|
|
/** @internal */
|
|
onFocus() {
|
|
var _a13, _b;
|
|
(_a13 = this.observers.find((x) => x.shouldFetchOnWindowFocus())) == null ? void 0 : _a13.refetch({ cancelRefetch: false });
|
|
(_b = __privateGet(this, _retryer)) == null ? void 0 : _b.continue();
|
|
}
|
|
/** @internal */
|
|
onOnline() {
|
|
var _a13, _b;
|
|
(_a13 = this.observers.find((x) => x.shouldFetchOnReconnect())) == null ? void 0 : _a13.refetch({ cancelRefetch: false });
|
|
(_b = __privateGet(this, _retryer)) == null ? void 0 : _b.continue();
|
|
}
|
|
/** @internal */
|
|
addObserver(observer) {
|
|
if (!this.observers.includes(observer)) {
|
|
this.observers.push(observer);
|
|
this.clearGcTimeout();
|
|
__privateGet(this, _cache).notify({
|
|
type: "observerAdded",
|
|
query: this,
|
|
observer
|
|
});
|
|
}
|
|
}
|
|
/** @internal */
|
|
removeObserver(observer) {
|
|
const index = this.observers.indexOf(observer);
|
|
if (index !== -1) {
|
|
this.observers.splice(index, 1);
|
|
if (!this.observers.length) {
|
|
if (__privateGet(this, _retryer)) {
|
|
if (__privateGet(this, _abortSignalConsumed) || this.state.fetchStatus === "paused" && this.state.status === "pending") __privateGet(this, _retryer).cancel({ revert: true });
|
|
else __privateGet(this, _retryer).cancelRetry();
|
|
}
|
|
this.scheduleGc();
|
|
}
|
|
__privateGet(this, _cache).notify({
|
|
type: "observerRemoved",
|
|
query: this,
|
|
observer
|
|
});
|
|
}
|
|
}
|
|
/**
|
|
* Returns the number of observers currently subscribed to this query.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* if (query.getObserversCount() === 0) {
|
|
* // no component is currently watching this query
|
|
* }
|
|
* ```
|
|
*/
|
|
getObserversCount() {
|
|
return this.observers.length;
|
|
}
|
|
/**
|
|
* Marks the query as invalidated, unless it is already invalidated. This
|
|
* updates `state.isInvalidated` and notifies observers, but does not by
|
|
* itself trigger a refetch.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* query.invalidate()
|
|
* ```
|
|
*/
|
|
invalidate() {
|
|
if (!this.state.isInvalidated) __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "invalidate" });
|
|
}
|
|
/**
|
|
* Fetches the query, i.e. runs its `queryFn` (through any configured
|
|
* retryer/behavior) and updates the query's state with the result.
|
|
* - If a fetch is already in flight, returns its promise instead of
|
|
* starting a new one, unless `fetchOptions.cancelRefetch` is set and the
|
|
* query already has data, in which case the current fetch is silently
|
|
* cancelled first.
|
|
* - If `options` is passed, it replaces the query's current options
|
|
* before fetching.
|
|
*/
|
|
async fetch(options, fetchOptions) {
|
|
var _a13, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
|
|
if (this.state.fetchStatus !== "idle" && ((_a13 = __privateGet(this, _retryer)) == null ? void 0 : _a13.status()) !== "rejected") {
|
|
if (this.state.data !== void 0 && (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch)) this.cancel({ silent: true });
|
|
else if (__privateGet(this, _retryer)) {
|
|
__privateGet(this, _retryer).continueRetry();
|
|
return __privateGet(this, _retryer).promise;
|
|
}
|
|
}
|
|
if (options) this.setOptions(options);
|
|
if (!this.options.queryFn) {
|
|
const observer = this.observers.find((x) => x.options.queryFn);
|
|
if (observer) this.setOptions(observer.options);
|
|
}
|
|
if (true) {
|
|
if (!Array.isArray(this.options.queryKey)) console.error(`As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`);
|
|
}
|
|
const abortController = new AbortController();
|
|
const addSignalProperty = (object) => {
|
|
Object.defineProperty(object, "signal", {
|
|
enumerable: true,
|
|
get: () => {
|
|
__privateSet(this, _abortSignalConsumed, true);
|
|
return abortController.signal;
|
|
}
|
|
});
|
|
};
|
|
const fetchFn = () => {
|
|
const queryFn = ensureQueryFn(this.options, fetchOptions);
|
|
const createQueryFnContext = () => {
|
|
const queryFnContext2 = {
|
|
client: __privateGet(this, _client),
|
|
queryKey: this.queryKey,
|
|
meta: this.meta
|
|
};
|
|
addSignalProperty(queryFnContext2);
|
|
return queryFnContext2;
|
|
};
|
|
const queryFnContext = createQueryFnContext();
|
|
__privateSet(this, _abortSignalConsumed, false);
|
|
if (this.options.persister) return this.options.persister(queryFn, queryFnContext, this);
|
|
return queryFn(queryFnContext);
|
|
};
|
|
const createFetchContext = () => {
|
|
const context2 = {
|
|
fetchOptions,
|
|
options: this.options,
|
|
queryKey: this.queryKey,
|
|
client: __privateGet(this, _client),
|
|
state: this.state,
|
|
fetchFn
|
|
};
|
|
addSignalProperty(context2);
|
|
return context2;
|
|
};
|
|
const context = createFetchContext();
|
|
(_b = __privateGet(this, _queryType) === "infinite" ? infiniteQueryBehavior(this.options.pages) : this.options.behavior) == null ? void 0 : _b.onFetch(context, this);
|
|
__privateSet(this, _revertState, this.state);
|
|
if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== ((_c = context.fetchOptions) == null ? void 0 : _c.meta)) __privateMethod(this, _Query_instances, dispatch_fn).call(this, {
|
|
type: "fetch",
|
|
meta: (_d = context.fetchOptions) == null ? void 0 : _d.meta
|
|
});
|
|
const retryer = __privateSet(this, _retryer, createRetryer({
|
|
initialPromise: fetchOptions == null ? void 0 : fetchOptions.initialPromise,
|
|
fn: context.fetchFn,
|
|
onCancel: (error) => {
|
|
if (error instanceof CancelledError && error.revert) this.setState({
|
|
...__privateGet(this, _revertState),
|
|
fetchStatus: "idle"
|
|
});
|
|
abortController.abort();
|
|
},
|
|
onFail: (failureCount, error) => {
|
|
__privateMethod(this, _Query_instances, dispatch_fn).call(this, {
|
|
type: "failed",
|
|
failureCount,
|
|
error
|
|
});
|
|
},
|
|
onPause: () => {
|
|
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "pause" });
|
|
},
|
|
onContinue: () => {
|
|
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "continue" });
|
|
},
|
|
retry: context.options.retry,
|
|
retryDelay: context.options.retryDelay,
|
|
networkMode: context.options.networkMode,
|
|
canRun: () => true
|
|
}));
|
|
try {
|
|
const data = await retryer.start();
|
|
if (data === void 0) {
|
|
if (true) console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`);
|
|
throw new Error(`${this.queryHash} data is undefined`);
|
|
}
|
|
this.setData(data);
|
|
(_f = (_e = __privateGet(this, _cache).config).onSuccess) == null ? void 0 : _f.call(_e, data, this);
|
|
(_h = (_g = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _h.call(_g, data, this.state.error, this);
|
|
return data;
|
|
} catch (error) {
|
|
if (error instanceof CancelledError) {
|
|
if (error.silent) return __privateGet(this, _retryer).promise;
|
|
else if (error.revert) {
|
|
if (this.state.data === void 0) throw error;
|
|
return this.state.data;
|
|
}
|
|
}
|
|
__privateMethod(this, _Query_instances, dispatch_fn).call(this, {
|
|
type: "error",
|
|
error
|
|
});
|
|
(_j = (_i = __privateGet(this, _cache).config).onError) == null ? void 0 : _j.call(_i, error, this);
|
|
(_l = (_k = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _l.call(_k, this.state.data, error, this);
|
|
throw error;
|
|
} finally {
|
|
if (__privateGet(this, _retryer) === retryer) __privateSet(this, _retryer, void 0);
|
|
this.scheduleGc();
|
|
}
|
|
}
|
|
}, _queryType = new WeakMap(), _initialState = new WeakMap(), _revertState = new WeakMap(), _cache = new WeakMap(), _client = new WeakMap(), _retryer = new WeakMap(), _defaultOptions = new WeakMap(), _abortSignalConsumed = new WeakMap(), _Query_instances = new WeakSet(), dispatch_fn = function(action) {
|
|
const reducer = (state) => {
|
|
switch (action.type) {
|
|
case "failed":
|
|
return {
|
|
...state,
|
|
fetchFailureCount: action.failureCount,
|
|
fetchFailureReason: action.error
|
|
};
|
|
case "pause":
|
|
return {
|
|
...state,
|
|
fetchStatus: "paused"
|
|
};
|
|
case "continue":
|
|
return {
|
|
...state,
|
|
fetchStatus: "fetching"
|
|
};
|
|
case "fetch":
|
|
return {
|
|
...state,
|
|
...fetchState(state.data, this.options),
|
|
fetchMeta: action.meta ?? null
|
|
};
|
|
case "success":
|
|
const newState = {
|
|
...state,
|
|
...successState(action.data, action.dataUpdatedAt),
|
|
dataUpdateCount: state.dataUpdateCount + 1,
|
|
...!action.manual && {
|
|
fetchStatus: "idle",
|
|
fetchFailureCount: 0,
|
|
fetchFailureReason: null
|
|
}
|
|
};
|
|
__privateSet(this, _revertState, action.manual ? newState : void 0);
|
|
return newState;
|
|
case "error":
|
|
const error = action.error;
|
|
return {
|
|
...state,
|
|
error,
|
|
errorUpdateCount: state.errorUpdateCount + 1,
|
|
errorUpdatedAt: Date.now(),
|
|
fetchFailureCount: state.fetchFailureCount + 1,
|
|
fetchFailureReason: error,
|
|
fetchStatus: "idle",
|
|
status: "error",
|
|
isInvalidated: true
|
|
};
|
|
case "invalidate":
|
|
return {
|
|
...state,
|
|
isInvalidated: true
|
|
};
|
|
case "setState":
|
|
return {
|
|
...state,
|
|
...action.state
|
|
};
|
|
}
|
|
};
|
|
this.state = reducer(this.state);
|
|
notifyManager.batch(() => {
|
|
this.observers.slice().forEach((observer) => {
|
|
observer.onQueryUpdate();
|
|
});
|
|
__privateGet(this, _cache).notify({
|
|
query: this,
|
|
type: "updated",
|
|
action
|
|
});
|
|
});
|
|
}, _a5);
|
|
function fetchState(data, options) {
|
|
return {
|
|
fetchFailureCount: 0,
|
|
fetchFailureReason: null,
|
|
fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused",
|
|
...data === void 0 && {
|
|
error: null,
|
|
status: "pending"
|
|
}
|
|
};
|
|
}
|
|
function successState(data, dataUpdatedAt) {
|
|
return {
|
|
data,
|
|
dataUpdatedAt: dataUpdatedAt ?? Date.now(),
|
|
error: null,
|
|
isInvalidated: false,
|
|
status: "success"
|
|
};
|
|
}
|
|
function getDefaultState(options) {
|
|
const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
|
|
const hasData = data !== void 0;
|
|
const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
|
|
return {
|
|
data,
|
|
dataUpdateCount: 0,
|
|
dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
|
|
error: null,
|
|
errorUpdateCount: 0,
|
|
errorUpdatedAt: 0,
|
|
fetchFailureCount: 0,
|
|
fetchFailureReason: null,
|
|
fetchMeta: null,
|
|
isInvalidated: false,
|
|
status: hasData ? "success" : "pending",
|
|
fetchStatus: "idle"
|
|
};
|
|
}
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/queryObserver.js
|
|
var _client2, _currentQuery, _currentQueryInitialState, _currentResult, _currentResultState, _currentResultOptions, _selectError, _selectFn, _selectResult, _lastQueryWithDefinedData, _staleTimeoutId, _refetchIntervalId, _currentRefetchInterval, _trackedProps, _QueryObserver_instances, executeFetch_fn, shouldScheduleTimer_fn, updateStaleTimeout_fn, computeRefetchInterval_fn, updateRefetchInterval_fn, updateTimers_fn, clearStaleTimeout_fn, clearRefetchInterval_fn, updateQuery_fn, _a6;
|
|
var QueryObserver = (_a6 = class extends Subscribable {
|
|
constructor(client, options) {
|
|
super();
|
|
__privateAdd(this, _QueryObserver_instances);
|
|
__privateAdd(this, _client2);
|
|
__privateAdd(this, _currentQuery);
|
|
__privateAdd(this, _currentQueryInitialState);
|
|
__privateAdd(this, _currentResult);
|
|
__privateAdd(this, _currentResultState);
|
|
__privateAdd(this, _currentResultOptions);
|
|
__privateAdd(this, _selectError);
|
|
__privateAdd(this, _selectFn);
|
|
__privateAdd(this, _selectResult);
|
|
__privateAdd(this, _lastQueryWithDefinedData);
|
|
__privateAdd(this, _staleTimeoutId);
|
|
__privateAdd(this, _refetchIntervalId);
|
|
__privateAdd(this, _currentRefetchInterval);
|
|
__privateAdd(this, _trackedProps, /* @__PURE__ */ new Set());
|
|
this.options = options;
|
|
__privateSet(this, _client2, client);
|
|
__privateSet(this, _selectError, null);
|
|
this.bindMethods();
|
|
this.setOptions(options);
|
|
}
|
|
bindMethods() {
|
|
this.refetch = this.refetch.bind(this);
|
|
}
|
|
onSubscribe() {
|
|
if (this.listeners.size === 1) {
|
|
__privateGet(this, _currentQuery).addObserver(this);
|
|
if (shouldFetchOnMount(__privateGet(this, _currentQuery), this.options)) __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
|
|
else this.updateResult();
|
|
__privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this);
|
|
}
|
|
}
|
|
onUnsubscribe() {
|
|
if (!this.hasListeners()) this.destroy();
|
|
}
|
|
/**
|
|
* Returns whether the observed query is currently stale and configured
|
|
* (via the `refetchOnReconnect` option) to refetch when the network
|
|
* reconnects.
|
|
*/
|
|
shouldFetchOnReconnect() {
|
|
return shouldFetchOn(__privateGet(this, _currentQuery), this.options, this.options.refetchOnReconnect);
|
|
}
|
|
/**
|
|
* Returns whether the observed query is currently stale and configured
|
|
* (via the `refetchOnWindowFocus` option) to refetch when the window
|
|
* regains focus.
|
|
*/
|
|
shouldFetchOnWindowFocus() {
|
|
return shouldFetchOn(__privateGet(this, _currentQuery), this.options, this.options.refetchOnWindowFocus);
|
|
}
|
|
/**
|
|
* Stops observing the current query: clears all listeners, cancels the
|
|
* stale and refetch-interval timers, and removes this observer from the
|
|
* query it was observing.
|
|
*/
|
|
destroy() {
|
|
this.listeners = /* @__PURE__ */ new Set();
|
|
__privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this);
|
|
__privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this);
|
|
__privateGet(this, _currentQuery).removeObserver(this);
|
|
}
|
|
/**
|
|
* Updates the observer's options. This will re-resolve the query being
|
|
* observed (switching to a different query if the `queryKey` changed),
|
|
* trigger a fetch if the new options require one and the observer has
|
|
* subscribers, recompute the current result, and reschedule the stale and
|
|
* refetch-interval timers as needed.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) })
|
|
* // later: switch to a different query, reusing the same observer
|
|
* observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) })
|
|
* ```
|
|
*/
|
|
setOptions(options) {
|
|
const prevOptions = this.options;
|
|
const prevQuery = __privateGet(this, _currentQuery);
|
|
this.options = __privateGet(this, _client2).defaultQueryOptions(options);
|
|
if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveQueryValue(this.options.enabled, __privateGet(this, _currentQuery)) !== "boolean") throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");
|
|
__privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this);
|
|
__privateGet(this, _currentQuery).setOptions(this.options);
|
|
if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) __privateGet(this, _client2).getQueryCache().notify({
|
|
type: "observerOptionsUpdated",
|
|
query: __privateGet(this, _currentQuery),
|
|
observer: this
|
|
});
|
|
const mounted = this.hasListeners();
|
|
if (mounted && shouldFetchOptionally(__privateGet(this, _currentQuery), prevQuery, this.options, prevOptions)) __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
|
|
this.updateResult();
|
|
if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveQueryValue(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveQueryValue(prevOptions.enabled, __privateGet(this, _currentQuery)) || resolveQueryValue(this.options.staleTime, __privateGet(this, _currentQuery)) !== resolveQueryValue(prevOptions.staleTime, __privateGet(this, _currentQuery)))) __privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this);
|
|
const nextRefetchInterval = __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this);
|
|
if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveQueryValue(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveQueryValue(prevOptions.enabled, __privateGet(this, _currentQuery)) || nextRefetchInterval !== __privateGet(this, _currentRefetchInterval))) __privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, nextRefetchInterval);
|
|
}
|
|
/**
|
|
* Computes the result the observer would produce for the given (already-defaulted) options
|
|
* right now, building the underlying `Query` if it doesn't exist yet, without waiting for a
|
|
* subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the
|
|
* returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.
|
|
*/
|
|
getOptimisticResult(options) {
|
|
const query = __privateGet(this, _client2).getQueryCache().build(__privateGet(this, _client2), options);
|
|
const result = this.createResult(query, options);
|
|
if (!shallowEqualObjects(this.getCurrentResult(), result)) {
|
|
__privateSet(this, _currentResult, result);
|
|
__privateSet(this, _currentResultOptions, this.options);
|
|
__privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state);
|
|
}
|
|
return result;
|
|
}
|
|
/**
|
|
* Returns the most recently computed `QueryObserverResult` for the
|
|
* observed query. This is a point-in-time read; to be notified of updates
|
|
* as they happen, subscribe to the observer instead (its inherited
|
|
* `subscribe` method).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const result = observer.getCurrentResult()
|
|
* console.log(result.status, result.data)
|
|
* ```
|
|
*/
|
|
getCurrentResult() {
|
|
return __privateGet(this, _currentResult);
|
|
}
|
|
/**
|
|
* Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via
|
|
* {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework
|
|
* adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on
|
|
* properties you actually read" behavior.
|
|
*/
|
|
trackResult(result, onPropTracked) {
|
|
return new Proxy(result, { get: (target, key) => {
|
|
this.trackProp(key);
|
|
onPropTracked == null ? void 0 : onPropTracked(key);
|
|
return Reflect.get(target, key);
|
|
} });
|
|
}
|
|
/**
|
|
* Records that the given `QueryObserverResult` property was read, so a subsequent update only
|
|
* notifies this observer if a tracked property actually changed. Normally called indirectly via
|
|
* {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property
|
|
* access themselves (e.g. through their own reactivity system) instead of via the proxy.
|
|
*/
|
|
trackProp(key) {
|
|
__privateGet(this, _trackedProps).add(key);
|
|
}
|
|
/**
|
|
* Returns the `Query` instance this observer is currently observing.
|
|
*/
|
|
getCurrentQuery() {
|
|
return __privateGet(this, _currentQuery);
|
|
}
|
|
/**
|
|
* Refetches the observed query and returns a promise that resolves with
|
|
* the resulting `QueryObserverResult`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const result = await observer.refetch({ cancelRefetch: false })
|
|
* console.log(result.data)
|
|
* ```
|
|
*/
|
|
refetch({ ...options } = {}) {
|
|
return this.fetch({ ...options });
|
|
}
|
|
/**
|
|
* Fetches a query defined by the given options without affecting this
|
|
* observer's own tracked query or result, and returns a promise that
|
|
* resolves with the `QueryObserverResult` for that fetch. This is useful
|
|
* for prefetching data that another observer (e.g. a query about to be
|
|
* navigated to) will need, ahead of time.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const result = await observer.fetchOptimistic({
|
|
* queryKey: ['posts', 2],
|
|
* queryFn: () => fetchPost(2),
|
|
* })
|
|
* console.log(result.data)
|
|
* ```
|
|
*/
|
|
fetchOptimistic(options) {
|
|
const defaultedOptions = __privateGet(this, _client2).defaultQueryOptions(options);
|
|
const query = __privateGet(this, _client2).getQueryCache().build(__privateGet(this, _client2), defaultedOptions);
|
|
let unsubscribe = () => {
|
|
};
|
|
let resolveEarly;
|
|
const cachePromise = new Promise((resolve) => {
|
|
resolveEarly = resolve;
|
|
unsubscribe = __privateGet(this, _client2).getQueryCache().subscribe((event) => {
|
|
if (event.type === "updated" && event.query.queryHash === query.queryHash && query.state.data !== void 0) {
|
|
unsubscribe();
|
|
resolve(this.createResult(query, defaultedOptions));
|
|
}
|
|
});
|
|
});
|
|
return Promise.race([query.fetch().then(() => {
|
|
const result = this.createResult(query, defaultedOptions);
|
|
resolveEarly == null ? void 0 : resolveEarly(result);
|
|
return result;
|
|
}).finally(() => {
|
|
unsubscribe();
|
|
}), cachePromise]);
|
|
}
|
|
fetch(fetchOptions) {
|
|
return __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this, {
|
|
...fetchOptions,
|
|
cancelRefetch: fetchOptions.cancelRefetch ?? true
|
|
}).then(() => {
|
|
this.updateResult();
|
|
return __privateGet(this, _currentResult);
|
|
});
|
|
}
|
|
createResult(query, options) {
|
|
var _a13;
|
|
const prevQuery = __privateGet(this, _currentQuery);
|
|
const prevOptions = this.options;
|
|
const prevResult = __privateGet(this, _currentResult);
|
|
const prevResultState = __privateGet(this, _currentResultState);
|
|
const prevResultOptions = __privateGet(this, _currentResultOptions);
|
|
const queryInitialState = query !== prevQuery ? query.state : __privateGet(this, _currentQueryInitialState);
|
|
const { state } = query;
|
|
let newState = { ...state };
|
|
let isPlaceholderData = false;
|
|
let data;
|
|
if (options._optimisticResults) {
|
|
const mounted = this.hasListeners();
|
|
const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
|
|
const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
|
|
if (fetchOnMount || fetchOptionally) newState = {
|
|
...newState,
|
|
...fetchState(state.data, query.options)
|
|
};
|
|
if (options._optimisticResults === "isRestoring") newState.fetchStatus = "idle";
|
|
}
|
|
let { error, errorUpdatedAt, status } = newState;
|
|
data = newState.data;
|
|
let skipSelect = false;
|
|
if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
|
|
let placeholderData;
|
|
if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
|
|
placeholderData = prevResult.data;
|
|
skipSelect = true;
|
|
} else placeholderData = typeof options.placeholderData === "function" ? options.placeholderData((_a13 = __privateGet(this, _lastQueryWithDefinedData)) == null ? void 0 : _a13.state.data, __privateGet(this, _lastQueryWithDefinedData)) : options.placeholderData;
|
|
if (placeholderData !== void 0) {
|
|
status = "success";
|
|
data = replaceData(prevResult == null ? void 0 : prevResult.data, placeholderData, options);
|
|
isPlaceholderData = true;
|
|
}
|
|
}
|
|
if (options.select && data !== void 0 && !skipSelect) {
|
|
if (prevResult && data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === __privateGet(this, _selectFn)) data = __privateGet(this, _selectResult);
|
|
else try {
|
|
__privateSet(this, _selectFn, options.select);
|
|
data = options.select(data);
|
|
data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options);
|
|
__privateSet(this, _selectResult, data);
|
|
__privateSet(this, _selectError, null);
|
|
} catch (selectError) {
|
|
__privateSet(this, _selectError, selectError);
|
|
}
|
|
} else if (data === void 0) __privateSet(this, _selectError, null);
|
|
if (__privateGet(this, _selectError)) {
|
|
error = __privateGet(this, _selectError);
|
|
data = __privateGet(this, _selectResult);
|
|
errorUpdatedAt = Date.now();
|
|
status = "error";
|
|
isPlaceholderData = false;
|
|
}
|
|
const isFetching = newState.fetchStatus === "fetching";
|
|
const isPending = status === "pending";
|
|
const isError = status === "error";
|
|
const isLoading = isPending && isFetching;
|
|
const hasData = data !== void 0;
|
|
return {
|
|
status,
|
|
fetchStatus: newState.fetchStatus,
|
|
isPending,
|
|
isSuccess: status === "success",
|
|
isError,
|
|
isInitialLoading: isLoading,
|
|
isLoading,
|
|
data,
|
|
dataUpdatedAt: newState.dataUpdatedAt,
|
|
error,
|
|
errorUpdatedAt,
|
|
failureCount: newState.fetchFailureCount,
|
|
failureReason: newState.fetchFailureReason,
|
|
errorUpdateCount: newState.errorUpdateCount,
|
|
isFetched: query.isFetched(),
|
|
isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,
|
|
isFetching,
|
|
isRefetching: isFetching && !isPending,
|
|
isLoadingError: isError && !hasData,
|
|
isPaused: newState.fetchStatus === "paused",
|
|
isPlaceholderData,
|
|
isRefetchError: isError && hasData,
|
|
isStale: isStale(query, options),
|
|
refetch: this.refetch,
|
|
isEnabled: resolveQueryValue(options.enabled, query) !== false
|
|
};
|
|
}
|
|
/**
|
|
* Recomputes and stores the current result from the current query/options, notifying listeners
|
|
* if it changed. Framework adapters call this right after subscribing to make sure no query
|
|
* update was missed in the gap between creating the observer and subscribing to it.
|
|
*/
|
|
updateResult() {
|
|
const prevResult = __privateGet(this, _currentResult);
|
|
const nextResult = this.createResult(__privateGet(this, _currentQuery), this.options);
|
|
__privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state);
|
|
__privateSet(this, _currentResultOptions, this.options);
|
|
if (__privateGet(this, _currentResultState).data !== void 0) __privateSet(this, _lastQueryWithDefinedData, __privateGet(this, _currentQuery));
|
|
if (shallowEqualObjects(nextResult, prevResult)) return;
|
|
__privateSet(this, _currentResult, nextResult);
|
|
const shouldNotifyListeners = () => {
|
|
if (!prevResult) return true;
|
|
const { notifyOnChangeProps } = this.options;
|
|
const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
|
|
if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !__privateGet(this, _trackedProps).size) return true;
|
|
const includedProps = new Set(notifyOnChangePropsValue ?? __privateGet(this, _trackedProps));
|
|
if (this.options.throwOnError) includedProps.add("error");
|
|
return Object.keys(__privateGet(this, _currentResult)).some((key) => {
|
|
const typedKey = key;
|
|
return __privateGet(this, _currentResult)[typedKey] !== prevResult[typedKey] && includedProps.has(typedKey);
|
|
});
|
|
};
|
|
const notifyListeners = shouldNotifyListeners();
|
|
notifyManager.batch(() => {
|
|
if (notifyListeners) this.listeners.forEach((listener) => {
|
|
listener(__privateGet(this, _currentResult));
|
|
});
|
|
__privateGet(this, _client2).getQueryCache().notify({
|
|
query: __privateGet(this, _currentQuery),
|
|
type: "observerResultsUpdated"
|
|
});
|
|
});
|
|
}
|
|
/** @internal */
|
|
onQueryUpdate() {
|
|
this.updateResult();
|
|
if (this.hasListeners()) __privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this);
|
|
}
|
|
}, _client2 = new WeakMap(), _currentQuery = new WeakMap(), _currentQueryInitialState = new WeakMap(), _currentResult = new WeakMap(), _currentResultState = new WeakMap(), _currentResultOptions = new WeakMap(), _selectError = new WeakMap(), _selectFn = new WeakMap(), _selectResult = new WeakMap(), _lastQueryWithDefinedData = new WeakMap(), _staleTimeoutId = new WeakMap(), _refetchIntervalId = new WeakMap(), _currentRefetchInterval = new WeakMap(), _trackedProps = new WeakMap(), _QueryObserver_instances = new WeakSet(), executeFetch_fn = function(fetchOptions) {
|
|
__privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this);
|
|
let promise = __privateGet(this, _currentQuery).fetch(this.options, fetchOptions);
|
|
if (!(fetchOptions == null ? void 0 : fetchOptions.throwOnError)) promise = promise.catch(noop);
|
|
return promise;
|
|
}, shouldScheduleTimer_fn = function(timeout) {
|
|
return !isServer2() && resolveQueryValue(this.options.enabled, __privateGet(this, _currentQuery)) !== false && isValidTimeout(timeout);
|
|
}, updateStaleTimeout_fn = function() {
|
|
__privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this);
|
|
const staleTime = resolveQueryValue(this.options.staleTime, __privateGet(this, _currentQuery));
|
|
if (__privateGet(this, _currentResult).isStale || !__privateMethod(this, _QueryObserver_instances, shouldScheduleTimer_fn).call(this, staleTime)) return;
|
|
const timeout = timeUntilStale(__privateGet(this, _currentResult).dataUpdatedAt, staleTime) + 1;
|
|
__privateSet(this, _staleTimeoutId, timeoutManager.setTimeout(() => {
|
|
if (!__privateGet(this, _currentResult).isStale) this.updateResult();
|
|
}, timeout));
|
|
}, computeRefetchInterval_fn = function() {
|
|
return resolveQueryValue(this.options.refetchInterval, __privateGet(this, _currentQuery)) ?? false;
|
|
}, updateRefetchInterval_fn = function(nextInterval) {
|
|
__privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this);
|
|
__privateSet(this, _currentRefetchInterval, nextInterval);
|
|
if (__privateGet(this, _currentRefetchInterval) === 0 || !__privateMethod(this, _QueryObserver_instances, shouldScheduleTimer_fn).call(this, __privateGet(this, _currentRefetchInterval))) return;
|
|
__privateSet(this, _refetchIntervalId, timeoutManager.setInterval(() => {
|
|
if (this.options.refetchIntervalInBackground || focusManager.isFocused()) __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
|
|
}, __privateGet(this, _currentRefetchInterval)));
|
|
}, updateTimers_fn = function() {
|
|
__privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this);
|
|
__privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this));
|
|
}, clearStaleTimeout_fn = function() {
|
|
if (__privateGet(this, _staleTimeoutId) !== void 0) {
|
|
timeoutManager.clearTimeout(__privateGet(this, _staleTimeoutId));
|
|
__privateSet(this, _staleTimeoutId, void 0);
|
|
}
|
|
}, clearRefetchInterval_fn = function() {
|
|
if (__privateGet(this, _refetchIntervalId) !== void 0) {
|
|
timeoutManager.clearInterval(__privateGet(this, _refetchIntervalId));
|
|
__privateSet(this, _refetchIntervalId, void 0);
|
|
}
|
|
}, updateQuery_fn = function() {
|
|
const query = __privateGet(this, _client2).getQueryCache().build(__privateGet(this, _client2), this.options);
|
|
if (query === __privateGet(this, _currentQuery)) return;
|
|
const prevQuery = __privateGet(this, _currentQuery);
|
|
__privateSet(this, _currentQuery, query);
|
|
__privateSet(this, _currentQueryInitialState, query.state);
|
|
if (this.hasListeners()) {
|
|
prevQuery == null ? void 0 : prevQuery.removeObserver(this);
|
|
query.addObserver(this);
|
|
}
|
|
}, _a6);
|
|
function shouldLoadOnMount(query, options) {
|
|
return resolveQueryValue(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && resolveQueryValue(options.retryOnMount, query) === false);
|
|
}
|
|
function shouldFetchOnMount(query, options) {
|
|
return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);
|
|
}
|
|
function shouldFetchOn(query, options, field) {
|
|
if (resolveQueryValue(options.enabled, query) !== false && resolveQueryValue(options.staleTime, query) !== "static") {
|
|
const value = resolveQueryValue(field, query);
|
|
return value === "always" || value !== false && isStale(query, options);
|
|
}
|
|
return false;
|
|
}
|
|
function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
|
|
return (query !== prevQuery || resolveQueryValue(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
|
|
}
|
|
function isStale(query, options) {
|
|
return resolveQueryValue(options.enabled, query) !== false && query.isStaleByTime(resolveQueryValue(options.staleTime, query));
|
|
}
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/infiniteQueryObserver.js
|
|
var InfiniteQueryObserver = class extends QueryObserver {
|
|
constructor(client, options) {
|
|
super(client, options);
|
|
}
|
|
bindMethods() {
|
|
super.bindMethods();
|
|
this.fetchNextPage = this.fetchNextPage.bind(this);
|
|
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
|
|
}
|
|
/**
|
|
* Updates the observer's options. Behaves the same as
|
|
* `QueryObserver.setOptions`, additionally marking the options as
|
|
* belonging to an infinite query before delegating to the base
|
|
* implementation.
|
|
*/
|
|
setOptions(options) {
|
|
options._type = "infinite";
|
|
super.setOptions(options);
|
|
}
|
|
/**
|
|
* The infinite-query counterpart of {@link QueryObserver#getOptimisticResult}, marking the
|
|
* options as an infinite query before delegating to it. Called by framework adapters (e.g.
|
|
* `useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`
|
|
* synchronously.
|
|
*/
|
|
getOptimisticResult(options) {
|
|
options._type = "infinite";
|
|
return super.getOptimisticResult(options);
|
|
}
|
|
/**
|
|
* Fetches the next page of the infinite query and returns a promise that
|
|
* resolves with the resulting `InfiniteQueryObserverResult`. The page
|
|
* param used for the fetch is determined by `getNextPageParam`, which
|
|
* receives the current pages/page params and whose result also determines
|
|
* `hasNextPage`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const { hasNextPage } = observer.getCurrentResult()
|
|
*
|
|
* if (hasNextPage) {
|
|
* await observer.fetchNextPage()
|
|
* }
|
|
* ```
|
|
*
|
|
* @see {@link InfiniteQueryObserver#fetchPreviousPage}
|
|
*/
|
|
fetchNextPage(options) {
|
|
return this.fetch({
|
|
...options,
|
|
meta: { fetchMore: { direction: "forward" } }
|
|
});
|
|
}
|
|
/**
|
|
* Fetches the previous page of the infinite query and returns a promise
|
|
* that resolves with the resulting `InfiniteQueryObserverResult`. The page
|
|
* param used for the fetch is determined by `getPreviousPageParam`, which
|
|
* receives the current pages/page params and whose result also determines
|
|
* `hasPreviousPage`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const { hasPreviousPage } = observer.getCurrentResult()
|
|
*
|
|
* if (hasPreviousPage) {
|
|
* await observer.fetchPreviousPage()
|
|
* }
|
|
* ```
|
|
*
|
|
* @see {@link InfiniteQueryObserver#fetchNextPage}
|
|
*/
|
|
fetchPreviousPage(options) {
|
|
return this.fetch({
|
|
...options,
|
|
meta: { fetchMore: { direction: "backward" } }
|
|
});
|
|
}
|
|
createResult(query, options) {
|
|
var _a13, _b;
|
|
const { state } = query;
|
|
const parentResult = super.createResult(query, options);
|
|
const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
|
|
const fetchDirection = (_b = (_a13 = state.fetchMeta) == null ? void 0 : _a13.fetchMore) == null ? void 0 : _b.direction;
|
|
const isFetchNextPageError = isError && fetchDirection === "forward";
|
|
const isFetchingNextPage = isFetching && fetchDirection === "forward";
|
|
const isFetchPreviousPageError = isError && fetchDirection === "backward";
|
|
const isFetchingPreviousPage = isFetching && fetchDirection === "backward";
|
|
return {
|
|
...parentResult,
|
|
fetchNextPage: this.fetchNextPage,
|
|
fetchPreviousPage: this.fetchPreviousPage,
|
|
hasNextPage: hasNextPage(options, state.data),
|
|
hasPreviousPage: hasPreviousPage(options, state.data),
|
|
isFetchNextPageError,
|
|
isFetchingNextPage,
|
|
isFetchPreviousPageError,
|
|
isFetchingPreviousPage,
|
|
isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
|
|
isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
|
|
};
|
|
}
|
|
};
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/mutation.js
|
|
var _client3, _observers, _mutationCache, _retryer2, _Mutation_instances, dispatch_fn2, _a7;
|
|
var Mutation = (_a7 = class extends Removable {
|
|
constructor(config) {
|
|
super();
|
|
__privateAdd(this, _Mutation_instances);
|
|
__privateAdd(this, _client3);
|
|
__privateAdd(this, _observers);
|
|
__privateAdd(this, _mutationCache);
|
|
__privateAdd(this, _retryer2);
|
|
__privateSet(this, _client3, config.client);
|
|
this.mutationId = config.mutationId;
|
|
__privateSet(this, _mutationCache, config.mutationCache);
|
|
__privateSet(this, _observers, []);
|
|
this.state = config.state || getDefaultState2();
|
|
this.setOptions(config.options);
|
|
this.scheduleGc();
|
|
}
|
|
/** @internal */
|
|
setOptions(options) {
|
|
this.options = options;
|
|
this.updateGcTime(this.options.gcTime);
|
|
}
|
|
/**
|
|
* The `meta` object passed in the mutation's options, if any.
|
|
*/
|
|
get meta() {
|
|
return this.options.meta;
|
|
}
|
|
/** @internal */
|
|
addObserver(observer) {
|
|
if (!__privateGet(this, _observers).includes(observer)) {
|
|
__privateGet(this, _observers).push(observer);
|
|
this.clearGcTimeout();
|
|
__privateGet(this, _mutationCache).notify({
|
|
type: "observerAdded",
|
|
mutation: this,
|
|
observer
|
|
});
|
|
}
|
|
}
|
|
/** @internal */
|
|
removeObserver(observer) {
|
|
__privateSet(this, _observers, __privateGet(this, _observers).filter((x) => x !== observer));
|
|
this.scheduleGc();
|
|
__privateGet(this, _mutationCache).notify({
|
|
type: "observerRemoved",
|
|
mutation: this,
|
|
observer
|
|
});
|
|
}
|
|
optionalRemove() {
|
|
if (!__privateGet(this, _observers).length) {
|
|
if (this.state.status === "pending") this.scheduleGc();
|
|
else __privateGet(this, _mutationCache).remove(this);
|
|
}
|
|
}
|
|
/**
|
|
* Resumes a mutation that is currently paused or was restored from a
|
|
* dehydrated, still-`pending` state.
|
|
*
|
|
* - If this mutation has an active retryer (it paused mid-attempt, e.g. due
|
|
* to the network mode or scope-based queuing), its retryer is resumed.
|
|
* - Otherwise, if the mutation's status is still `pending` (e.g. it was
|
|
* dehydrated while an attempt was in flight and never got a retryer in
|
|
* this instance), `execute` is called again with the last known variables.
|
|
* - Otherwise the mutation has already settled and this resolves immediately
|
|
* without running anything again.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()
|
|
* const mutation = mutationCache.find({ mutationKey: ['addPost'] })
|
|
* await mutation?.continue()
|
|
* ```
|
|
*
|
|
* @see {@link Mutation#execute}
|
|
*/
|
|
continue() {
|
|
var _a13;
|
|
return ((_a13 = __privateGet(this, _retryer2)) == null ? void 0 : _a13.continue()) ?? (this.state.status === "pending" ? this.execute(this.state.variables) : Promise.resolve());
|
|
}
|
|
/**
|
|
* Runs the mutation function for the given variables through a retryer, and
|
|
* drives the mutation's state and lifecycle callbacks through to settlement.
|
|
*
|
|
* If this mutation's state is already `pending` when `execute` is called
|
|
* (i.e. it was restored, still in-flight, from a dehydrated state), the
|
|
* `onMutate` step is skipped and a `continue` action is dispatched to
|
|
* unpause it; otherwise a `pending` action is dispatched first, then the
|
|
* mutation cache's `onMutate` and the mutation's own `onMutate` option are
|
|
* awaited in that order, and the resulting context is stored.
|
|
*
|
|
* The mutation function is then run (subject to `retry`/`retryDelay`/
|
|
* `networkMode`, and to the mutation cache's scope-based serialization).
|
|
* On success, the cache's `onSuccess`/`onSettled` callbacks run before the
|
|
* mutation's own `onSuccess`/`onSettled` options, a `success` action is
|
|
* dispatched, and the resolved data is returned. On failure, the same
|
|
* cache-then-option ordering is used for `onError`/`onSettled`, but each of
|
|
* those four callbacks is individually caught so that a throwing callback
|
|
* cannot mask the original error; an `error` action is then dispatched and
|
|
* the original error is re-thrown.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Called internally by `MutationObserver.mutate` and `Mutation.continue` —
|
|
* // applications normally trigger mutations through those, not this method.
|
|
* const data = await mutation.execute(variables)
|
|
* ```
|
|
*
|
|
* @see {@link Mutation#continue}
|
|
*/
|
|
async execute(variables) {
|
|
var _a13, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
|
|
const onContinue = () => {
|
|
__privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "continue" });
|
|
};
|
|
const mutationFnContext = {
|
|
client: __privateGet(this, _client3),
|
|
meta: this.options.meta,
|
|
mutationKey: this.options.mutationKey
|
|
};
|
|
const retryer = __privateSet(this, _retryer2, createRetryer({
|
|
fn: () => {
|
|
if (!this.options.mutationFn) return Promise.reject(new Error("No mutationFn found"));
|
|
return this.options.mutationFn(variables, mutationFnContext);
|
|
},
|
|
onFail: (failureCount, error) => {
|
|
__privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, {
|
|
type: "failed",
|
|
failureCount,
|
|
error
|
|
});
|
|
},
|
|
onPause: () => {
|
|
__privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "pause" });
|
|
},
|
|
onContinue,
|
|
retry: this.options.retry ?? 0,
|
|
retryDelay: this.options.retryDelay,
|
|
networkMode: this.options.networkMode,
|
|
canRun: () => __privateGet(this, _mutationCache).canRun(this)
|
|
}));
|
|
const restored = this.state.status === "pending";
|
|
const isPaused = !retryer.canStart();
|
|
try {
|
|
if (restored) onContinue();
|
|
else {
|
|
__privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, {
|
|
type: "pending",
|
|
variables,
|
|
isPaused
|
|
});
|
|
if (__privateGet(this, _mutationCache).config.onMutate) await __privateGet(this, _mutationCache).config.onMutate(variables, this, mutationFnContext);
|
|
const context = await ((_b = (_a13 = this.options).onMutate) == null ? void 0 : _b.call(_a13, variables, mutationFnContext));
|
|
if (context !== this.state.context) __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, {
|
|
type: "pending",
|
|
context,
|
|
variables,
|
|
isPaused
|
|
});
|
|
}
|
|
const data = await retryer.start();
|
|
await ((_d = (_c = __privateGet(this, _mutationCache).config).onSuccess) == null ? void 0 : _d.call(_c, data, variables, this.state.context, this, mutationFnContext));
|
|
await ((_f = (_e = this.options).onSuccess) == null ? void 0 : _f.call(_e, data, variables, this.state.context, mutationFnContext));
|
|
await ((_h = (_g = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _h.call(_g, data, null, this.state.variables, this.state.context, this, mutationFnContext));
|
|
await ((_j = (_i = this.options).onSettled) == null ? void 0 : _j.call(_i, data, null, variables, this.state.context, mutationFnContext));
|
|
__privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, {
|
|
type: "success",
|
|
data
|
|
});
|
|
return data;
|
|
} catch (error) {
|
|
try {
|
|
await ((_l = (_k = __privateGet(this, _mutationCache).config).onError) == null ? void 0 : _l.call(_k, error, variables, this.state.context, this, mutationFnContext));
|
|
} catch (e) {
|
|
Promise.reject(e);
|
|
}
|
|
try {
|
|
await ((_n = (_m = this.options).onError) == null ? void 0 : _n.call(_m, error, variables, this.state.context, mutationFnContext));
|
|
} catch (e) {
|
|
Promise.reject(e);
|
|
}
|
|
try {
|
|
await ((_p = (_o = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _p.call(_o, void 0, error, this.state.variables, this.state.context, this, mutationFnContext));
|
|
} catch (e) {
|
|
Promise.reject(e);
|
|
}
|
|
try {
|
|
await ((_r = (_q = this.options).onSettled) == null ? void 0 : _r.call(_q, void 0, error, variables, this.state.context, mutationFnContext));
|
|
} catch (e) {
|
|
Promise.reject(e);
|
|
}
|
|
__privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, {
|
|
type: "error",
|
|
error
|
|
});
|
|
throw error;
|
|
} finally {
|
|
if (__privateGet(this, _retryer2) === retryer) __privateSet(this, _retryer2, void 0);
|
|
__privateGet(this, _mutationCache).runNext(this);
|
|
}
|
|
}
|
|
}, _client3 = new WeakMap(), _observers = new WeakMap(), _mutationCache = new WeakMap(), _retryer2 = new WeakMap(), _Mutation_instances = new WeakSet(), dispatch_fn2 = function(action) {
|
|
const reducer = (state) => {
|
|
switch (action.type) {
|
|
case "failed":
|
|
return {
|
|
...state,
|
|
failureCount: action.failureCount,
|
|
failureReason: action.error
|
|
};
|
|
case "pause":
|
|
return {
|
|
...state,
|
|
isPaused: true
|
|
};
|
|
case "continue":
|
|
return {
|
|
...state,
|
|
isPaused: false
|
|
};
|
|
case "pending":
|
|
return {
|
|
...state,
|
|
context: action.context,
|
|
data: void 0,
|
|
failureCount: 0,
|
|
failureReason: null,
|
|
error: null,
|
|
isPaused: action.isPaused,
|
|
status: "pending",
|
|
variables: action.variables,
|
|
submittedAt: Date.now()
|
|
};
|
|
case "success":
|
|
return {
|
|
...state,
|
|
data: action.data,
|
|
failureCount: 0,
|
|
failureReason: null,
|
|
error: null,
|
|
status: "success",
|
|
isPaused: false
|
|
};
|
|
case "error":
|
|
return {
|
|
...state,
|
|
data: void 0,
|
|
error: action.error,
|
|
failureCount: state.failureCount + 1,
|
|
failureReason: action.error,
|
|
isPaused: false,
|
|
status: "error"
|
|
};
|
|
}
|
|
};
|
|
this.state = reducer(this.state);
|
|
notifyManager.batch(() => {
|
|
__privateGet(this, _observers).forEach((observer) => {
|
|
observer.onMutationUpdate(action);
|
|
});
|
|
__privateGet(this, _mutationCache).notify({
|
|
mutation: this,
|
|
type: "updated",
|
|
action
|
|
});
|
|
});
|
|
}, _a7);
|
|
function getDefaultState2() {
|
|
return {
|
|
context: void 0,
|
|
data: void 0,
|
|
error: null,
|
|
failureCount: 0,
|
|
failureReason: null,
|
|
isPaused: false,
|
|
status: "idle",
|
|
variables: void 0,
|
|
submittedAt: 0
|
|
};
|
|
}
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/mutationCache.js
|
|
var _mutations, _scopes, _mutationId, _a8;
|
|
var MutationCache = (_a8 = class extends Subscribable {
|
|
constructor(config = {}) {
|
|
super();
|
|
__privateAdd(this, _mutations);
|
|
__privateAdd(this, _scopes);
|
|
__privateAdd(this, _mutationId);
|
|
this.config = config;
|
|
__privateSet(this, _mutations, /* @__PURE__ */ new Set());
|
|
__privateSet(this, _scopes, /* @__PURE__ */ new Map());
|
|
__privateSet(this, _mutationId, 0);
|
|
}
|
|
/** @internal */
|
|
build(client, options, state) {
|
|
const mutation = new Mutation({
|
|
client,
|
|
mutationCache: this,
|
|
mutationId: ++__privateWrapper(this, _mutationId)._,
|
|
options: client.defaultMutationOptions(options),
|
|
state
|
|
});
|
|
this.add(mutation);
|
|
return mutation;
|
|
}
|
|
/** @internal */
|
|
add(mutation) {
|
|
__privateGet(this, _mutations).add(mutation);
|
|
const scope = scopeFor(mutation);
|
|
if (typeof scope === "string") {
|
|
const scopedMutations = __privateGet(this, _scopes).get(scope);
|
|
if (scopedMutations) scopedMutations.push(mutation);
|
|
else __privateGet(this, _scopes).set(scope, [mutation]);
|
|
}
|
|
this.notify({
|
|
type: "added",
|
|
mutation
|
|
});
|
|
}
|
|
/** @internal */
|
|
remove(mutation) {
|
|
if (__privateGet(this, _mutations).delete(mutation)) {
|
|
const scope = scopeFor(mutation);
|
|
if (typeof scope === "string") {
|
|
const scopedMutations = __privateGet(this, _scopes).get(scope);
|
|
if (scopedMutations) {
|
|
if (scopedMutations.length > 1) {
|
|
const index = scopedMutations.indexOf(mutation);
|
|
if (index !== -1) scopedMutations.splice(index, 1);
|
|
} else if (scopedMutations[0] === mutation) __privateGet(this, _scopes).delete(scope);
|
|
}
|
|
}
|
|
}
|
|
this.notify({
|
|
type: "removed",
|
|
mutation
|
|
});
|
|
}
|
|
/** @internal */
|
|
canRun(mutation) {
|
|
var _a13;
|
|
const scope = scopeFor(mutation);
|
|
if (typeof scope === "string") {
|
|
const firstPendingMutation = (_a13 = __privateGet(this, _scopes).get(scope)) == null ? void 0 : _a13.find((m) => m.state.status === "pending");
|
|
return !firstPendingMutation || firstPendingMutation === mutation;
|
|
} else return true;
|
|
}
|
|
/** @internal */
|
|
runNext(mutation) {
|
|
var _a13, _b;
|
|
const scope = scopeFor(mutation);
|
|
if (typeof scope === "string") return ((_b = (_a13 = __privateGet(this, _scopes).get(scope)) == null ? void 0 : _a13.find((m) => m !== mutation && m.state.isPaused)) == null ? void 0 : _b.continue()) ?? Promise.resolve();
|
|
else return Promise.resolve();
|
|
}
|
|
/**
|
|
* Removes all mutations from the cache.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const mutationCache = queryClient.getMutationCache()
|
|
*
|
|
* mutationCache.clear()
|
|
* ```
|
|
*/
|
|
clear() {
|
|
notifyManager.batch(() => {
|
|
__privateGet(this, _mutations).forEach((mutation) => {
|
|
this.notify({
|
|
type: "removed",
|
|
mutation
|
|
});
|
|
});
|
|
__privateGet(this, _mutations).clear();
|
|
__privateGet(this, _scopes).clear();
|
|
});
|
|
}
|
|
/**
|
|
* Returns all mutations within the cache.
|
|
*
|
|
* This is not typically needed for most applications, but can come in handy when needing more
|
|
* information about a mutation in rare scenarios.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const mutationCache = queryClient.getMutationCache()
|
|
*
|
|
* const mutations = mutationCache.getAll()
|
|
* ```
|
|
*/
|
|
getAll() {
|
|
return Array.from(__privateGet(this, _mutations));
|
|
}
|
|
/**
|
|
* A slightly more advanced method that can be used to get an existing mutation instance from
|
|
* the cache. If the mutation does not exist, `undefined` is returned.
|
|
*
|
|
* This is not typically needed for most applications, but can come in handy when needing more
|
|
* information about a mutation in rare scenarios.
|
|
*
|
|
* @see {@link MutationCache#findAll}
|
|
* @example
|
|
* ```ts
|
|
* const mutationCache = queryClient.getMutationCache()
|
|
*
|
|
* const mutation = mutationCache.find({ mutationKey: ['addPost'] })
|
|
* ```
|
|
*/
|
|
find(filters) {
|
|
const defaultedFilters = {
|
|
exact: true,
|
|
...filters
|
|
};
|
|
return this.getAll().find((mutation) => matchMutation(defaultedFilters, mutation));
|
|
}
|
|
/**
|
|
* An even more advanced method that can be used to get existing mutation instances from the
|
|
* cache that match the given filters. If no mutations match, an empty array is returned.
|
|
*
|
|
* This is not typically needed for most applications, but can come in handy when needing more
|
|
* information about mutations in rare scenarios.
|
|
*
|
|
* @see {@link MutationCache#find}
|
|
* @example
|
|
* ```ts
|
|
* const mutationCache = queryClient.getMutationCache()
|
|
*
|
|
* const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })
|
|
* ```
|
|
*/
|
|
findAll(filters = {}) {
|
|
return this.getAll().filter((mutation) => matchMutation(filters, mutation));
|
|
}
|
|
/** @internal */
|
|
notify(event) {
|
|
notifyManager.batch(() => {
|
|
this.listeners.forEach((listener) => {
|
|
listener(event);
|
|
});
|
|
});
|
|
}
|
|
/** @internal */
|
|
resumePausedMutations() {
|
|
const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
|
|
return notifyManager.batch(() => Promise.all(pausedMutations.map((mutation) => mutation.continue().catch(noop))));
|
|
}
|
|
}, _mutations = new WeakMap(), _scopes = new WeakMap(), _mutationId = new WeakMap(), _a8);
|
|
function scopeFor(mutation) {
|
|
var _a13;
|
|
return (_a13 = mutation.options.scope) == null ? void 0 : _a13.id;
|
|
}
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/mutationObserver.js
|
|
var _client4, _currentResult2, _currentMutation, _mutateOptions, _MutationObserver_instances, updateResult_fn, notify_fn, _a9;
|
|
var MutationObserver = (_a9 = class extends Subscribable {
|
|
constructor(client, options) {
|
|
super();
|
|
__privateAdd(this, _MutationObserver_instances);
|
|
__privateAdd(this, _client4);
|
|
__privateAdd(this, _currentResult2);
|
|
__privateAdd(this, _currentMutation);
|
|
__privateAdd(this, _mutateOptions);
|
|
__privateSet(this, _client4, client);
|
|
this.setOptions(options);
|
|
this.bindMethods();
|
|
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
|
|
}
|
|
bindMethods() {
|
|
this.mutate = this.mutate.bind(this);
|
|
this.reset = this.reset.bind(this);
|
|
}
|
|
/**
|
|
* Updates the observer's options.
|
|
*
|
|
* If the new `mutationKey` differs from the previous one (and both were
|
|
* defined), the observer is reset, detaching it from the mutation it was
|
|
* observing. Otherwise, if the currently observed mutation is still
|
|
* `pending`, its options are updated in place as well.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* observer.setOptions({
|
|
* mutationFn: (variables: { title: string }) => addPost(variables),
|
|
* onSuccess: (data) => console.log(data),
|
|
* })
|
|
* ```
|
|
*/
|
|
setOptions(options) {
|
|
var _a13;
|
|
const prevOptions = this.options;
|
|
this.options = __privateGet(this, _client4).defaultMutationOptions(options);
|
|
if (!shallowEqualObjects(this.options, prevOptions)) __privateGet(this, _client4).getMutationCache().notify({
|
|
type: "observerOptionsUpdated",
|
|
mutation: __privateGet(this, _currentMutation),
|
|
observer: this
|
|
});
|
|
if ((prevOptions == null ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) this.reset();
|
|
else if (((_a13 = __privateGet(this, _currentMutation)) == null ? void 0 : _a13.state.status) === "pending") __privateGet(this, _currentMutation).setOptions(this.options);
|
|
}
|
|
onSubscribe() {
|
|
if (this.listeners.size === 1 && __privateGet(this, _currentMutation)) {
|
|
__privateGet(this, _currentMutation).addObserver(this);
|
|
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
|
|
}
|
|
}
|
|
onUnsubscribe() {
|
|
var _a13;
|
|
if (!this.hasListeners()) (_a13 = __privateGet(this, _currentMutation)) == null ? void 0 : _a13.removeObserver(this);
|
|
}
|
|
/** @internal */
|
|
onMutationUpdate(action) {
|
|
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
|
|
__privateMethod(this, _MutationObserver_instances, notify_fn).call(this, action);
|
|
}
|
|
/**
|
|
* Returns the observer's current result, derived from the observed
|
|
* mutation's state (or the default, `idle` state if no mutation has been
|
|
* built yet, e.g. before the first `mutate()` call or after `reset()`).
|
|
*/
|
|
getCurrentResult() {
|
|
return __privateGet(this, _currentResult2);
|
|
}
|
|
/**
|
|
* Detaches the observer from the mutation it is currently observing (if
|
|
* any) and resets the observed result back to its default, `idle` state.
|
|
*
|
|
* This does not cancel an in-flight mutation; the mutation itself keeps
|
|
* running to completion and its own callbacks still fire, but this
|
|
* observer stops reflecting its state and a subsequent `mutate()` call
|
|
* will build a brand new mutation.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* observer.reset()
|
|
* ```
|
|
*
|
|
* @see {@link MutationObserver#mutate}
|
|
*/
|
|
reset() {
|
|
var _a13;
|
|
(_a13 = __privateGet(this, _currentMutation)) == null ? void 0 : _a13.removeObserver(this);
|
|
__privateSet(this, _currentMutation, void 0);
|
|
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
|
|
__privateMethod(this, _MutationObserver_instances, notify_fn).call(this);
|
|
}
|
|
/**
|
|
* Builds a new `Mutation` in the `MutationCache` using the observer's
|
|
* current options, detaches this observer from any previously observed
|
|
* mutation, attaches it to the new one, and executes it with the given
|
|
* variables.
|
|
*
|
|
* The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are
|
|
* invoked once the mutation settles, in addition to any callbacks defined
|
|
* on the observer's own options.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await observer.mutate(
|
|
* { title: 'New post' },
|
|
* { onSuccess: (data) => console.log(data) },
|
|
* )
|
|
* ```
|
|
*/
|
|
mutate(variables, options) {
|
|
var _a13;
|
|
__privateSet(this, _mutateOptions, options);
|
|
(_a13 = __privateGet(this, _currentMutation)) == null ? void 0 : _a13.removeObserver(this);
|
|
__privateSet(this, _currentMutation, __privateGet(this, _client4).getMutationCache().build(__privateGet(this, _client4), this.options));
|
|
__privateGet(this, _currentMutation).addObserver(this);
|
|
return __privateGet(this, _currentMutation).execute(variables);
|
|
}
|
|
}, _client4 = new WeakMap(), _currentResult2 = new WeakMap(), _currentMutation = new WeakMap(), _mutateOptions = new WeakMap(), _MutationObserver_instances = new WeakSet(), updateResult_fn = function() {
|
|
var _a13;
|
|
const state = ((_a13 = __privateGet(this, _currentMutation)) == null ? void 0 : _a13.state) ?? getDefaultState2();
|
|
__privateSet(this, _currentResult2, {
|
|
...state,
|
|
isPending: state.status === "pending",
|
|
isSuccess: state.status === "success",
|
|
isError: state.status === "error",
|
|
isIdle: state.status === "idle",
|
|
mutate: this.mutate,
|
|
reset: this.reset
|
|
});
|
|
}, notify_fn = function(action) {
|
|
notifyManager.batch(() => {
|
|
var _a13, _b, _c, _d, _e, _f, _g, _h;
|
|
if (__privateGet(this, _mutateOptions) && this.hasListeners()) {
|
|
const variables = __privateGet(this, _currentResult2).variables;
|
|
const onMutateResult = __privateGet(this, _currentResult2).context;
|
|
const context = {
|
|
client: __privateGet(this, _client4),
|
|
meta: this.options.meta,
|
|
mutationKey: this.options.mutationKey
|
|
};
|
|
if ((action == null ? void 0 : action.type) === "success") {
|
|
try {
|
|
(_b = (_a13 = __privateGet(this, _mutateOptions)).onSuccess) == null ? void 0 : _b.call(_a13, action.data, variables, onMutateResult, context);
|
|
} catch (e) {
|
|
Promise.reject(e);
|
|
}
|
|
try {
|
|
(_d = (_c = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _d.call(_c, action.data, null, variables, onMutateResult, context);
|
|
} catch (e) {
|
|
Promise.reject(e);
|
|
}
|
|
} else if ((action == null ? void 0 : action.type) === "error") {
|
|
try {
|
|
(_f = (_e = __privateGet(this, _mutateOptions)).onError) == null ? void 0 : _f.call(_e, action.error, variables, onMutateResult, context);
|
|
} catch (e) {
|
|
Promise.reject(e);
|
|
}
|
|
try {
|
|
(_h = (_g = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _h.call(_g, void 0, action.error, variables, onMutateResult, context);
|
|
} catch (e) {
|
|
Promise.reject(e);
|
|
}
|
|
}
|
|
}
|
|
this.listeners.forEach((listener) => {
|
|
listener(__privateGet(this, _currentResult2));
|
|
});
|
|
});
|
|
}, _a9);
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/queriesObserver.js
|
|
function difference(array1, array2) {
|
|
const excludeSet = new Set(array2);
|
|
return array1.filter((x) => !excludeSet.has(x));
|
|
}
|
|
var _client5, _result, _queries, _options, _observers2, _combinedResult, _lastCombine, _lastResult, _lastQueryHashes, _observerMatches, _QueriesObserver_instances, trackResult_fn, combineResult_fn, shouldSkipCombine_fn, findMatchingObservers_fn, onUpdate_fn, notify_fn2, _a10;
|
|
var QueriesObserver = (_a10 = class extends Subscribable {
|
|
constructor(client, queries, options) {
|
|
super();
|
|
__privateAdd(this, _QueriesObserver_instances);
|
|
__privateAdd(this, _client5);
|
|
__privateAdd(this, _result);
|
|
__privateAdd(this, _queries);
|
|
__privateAdd(this, _options);
|
|
__privateAdd(this, _observers2);
|
|
__privateAdd(this, _combinedResult);
|
|
__privateAdd(this, _lastCombine);
|
|
__privateAdd(this, _lastResult);
|
|
__privateAdd(this, _lastQueryHashes);
|
|
__privateAdd(this, _observerMatches, []);
|
|
__privateSet(this, _client5, client);
|
|
__privateSet(this, _options, options);
|
|
__privateSet(this, _queries, []);
|
|
__privateSet(this, _observers2, []);
|
|
__privateSet(this, _result, []);
|
|
this.setQueries(queries);
|
|
}
|
|
onSubscribe() {
|
|
if (this.listeners.size === 1) __privateGet(this, _observers2).forEach((observer) => {
|
|
observer.subscribe((result) => {
|
|
__privateMethod(this, _QueriesObserver_instances, onUpdate_fn).call(this, observer, result);
|
|
});
|
|
});
|
|
}
|
|
onUnsubscribe() {
|
|
if (!this.listeners.size) this.destroy();
|
|
}
|
|
/**
|
|
* Stops observing all queries: clears all listeners and destroys every
|
|
* underlying `QueryObserver` this observer manages.
|
|
*/
|
|
destroy() {
|
|
this.listeners = /* @__PURE__ */ new Set();
|
|
__privateGet(this, _observers2).forEach((observer) => {
|
|
observer.destroy();
|
|
});
|
|
}
|
|
/**
|
|
* Replaces the set of queries being observed. Existing `QueryObserver`s
|
|
* are reused for queries that match an already-observed query hash;
|
|
* observers for queries that are no longer present are destroyed, and new
|
|
* observers are created and subscribed to for newly added queries.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* observer.setQueries([
|
|
* { queryKey: ['post', 1], queryFn: fetchPost },
|
|
* { queryKey: ['post', 3], queryFn: fetchPost },
|
|
* ])
|
|
* ```
|
|
*/
|
|
setQueries(queries, options) {
|
|
__privateSet(this, _queries, queries);
|
|
__privateSet(this, _options, options);
|
|
if (true) {
|
|
const queryHashes = queries.map((query) => __privateGet(this, _client5).defaultQueryOptions(query).queryHash);
|
|
if (new Set(queryHashes).size !== queryHashes.length) console.warn("[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.");
|
|
}
|
|
notifyManager.batch(() => {
|
|
const prevObservers = __privateGet(this, _observers2);
|
|
const newObserverMatches = __privateMethod(this, _QueriesObserver_instances, findMatchingObservers_fn).call(this, __privateGet(this, _queries));
|
|
newObserverMatches.forEach((match) => match.observer.setOptions(match.defaultedQueryOptions));
|
|
const newObservers = newObserverMatches.map((match) => match.observer);
|
|
const newResult = newObservers.map((observer) => observer.getCurrentResult());
|
|
const hasLengthChange = prevObservers.length !== newObservers.length;
|
|
const hasIndexChange = newObservers.some((observer, index) => observer !== prevObservers[index]);
|
|
const hasStructuralChange = hasLengthChange || hasIndexChange;
|
|
const hasResultChange = hasStructuralChange ? true : newResult.some((result, index) => {
|
|
const prev = __privateGet(this, _result)[index];
|
|
return !prev || !shallowEqualObjects(result, prev);
|
|
});
|
|
if (!hasStructuralChange && !hasResultChange) return;
|
|
if (hasStructuralChange) {
|
|
__privateSet(this, _observerMatches, newObserverMatches);
|
|
__privateSet(this, _observers2, newObservers);
|
|
}
|
|
__privateSet(this, _result, newResult);
|
|
if (!this.hasListeners()) return;
|
|
if (hasStructuralChange) {
|
|
difference(prevObservers, newObservers).forEach((observer) => {
|
|
observer.destroy();
|
|
});
|
|
difference(newObservers, prevObservers).forEach((observer) => {
|
|
observer.subscribe((result) => {
|
|
__privateMethod(this, _QueriesObserver_instances, onUpdate_fn).call(this, observer, result);
|
|
});
|
|
});
|
|
}
|
|
__privateMethod(this, _QueriesObserver_instances, notify_fn2).call(this);
|
|
});
|
|
}
|
|
/**
|
|
* Returns the most recently computed array of `QueryObserverResult`s, one
|
|
* per observed query, in the same order as the queries passed to the
|
|
* constructor or `setQueries`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const results = observer.getCurrentResult()
|
|
* const data = results.map((result) => result.data)
|
|
* ```
|
|
*/
|
|
getCurrentResult() {
|
|
return __privateGet(this, _result);
|
|
}
|
|
/**
|
|
* Returns the underlying `Query` instances currently being observed, in
|
|
* the same order as the queries passed to the constructor or `setQueries`.
|
|
*/
|
|
getQueries() {
|
|
return __privateGet(this, _observers2).map((observer) => observer.getCurrentQuery());
|
|
}
|
|
/**
|
|
* Returns the underlying `QueryObserver` instances this observer manages,
|
|
* in the same order as the queries passed to the constructor or
|
|
* `setQueries`.
|
|
*/
|
|
getObservers() {
|
|
return __privateGet(this, _observers2);
|
|
}
|
|
/**
|
|
* The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} — computes
|
|
* the result for the given (already-defaulted) queries right now, synchronously. Called by
|
|
* framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw
|
|
* per-query results, a function to compute the combined result from them, and a function to
|
|
* wrap the results for property-access tracking.
|
|
*/
|
|
getOptimisticResult(queries, combine) {
|
|
const matches = __privateMethod(this, _QueriesObserver_instances, findMatchingObservers_fn).call(this, queries);
|
|
const result = matches.map((match) => match.observer.getOptimisticResult(match.defaultedQueryOptions));
|
|
const queryHashes = matches.map((match) => match.defaultedQueryOptions.queryHash);
|
|
return [
|
|
result,
|
|
(r) => {
|
|
return __privateMethod(this, _QueriesObserver_instances, combineResult_fn).call(this, r ?? result, combine, queryHashes);
|
|
},
|
|
() => {
|
|
return __privateMethod(this, _QueriesObserver_instances, trackResult_fn).call(this, result, matches);
|
|
}
|
|
];
|
|
}
|
|
}, _client5 = new WeakMap(), _result = new WeakMap(), _queries = new WeakMap(), _options = new WeakMap(), _observers2 = new WeakMap(), _combinedResult = new WeakMap(), _lastCombine = new WeakMap(), _lastResult = new WeakMap(), _lastQueryHashes = new WeakMap(), _observerMatches = new WeakMap(), _QueriesObserver_instances = new WeakSet(), trackResult_fn = function(result, matches) {
|
|
const trackedProps = /* @__PURE__ */ new Set();
|
|
return matches.map((match, index) => {
|
|
const observerResult = result[index];
|
|
return !match.defaultedQueryOptions.notifyOnChangeProps ? match.observer.trackResult(observerResult, (accessedProp) => {
|
|
if (!trackedProps.has(accessedProp)) {
|
|
trackedProps.add(accessedProp);
|
|
matches.forEach((m) => {
|
|
m.observer.trackProp(accessedProp);
|
|
});
|
|
}
|
|
}) : observerResult;
|
|
});
|
|
}, combineResult_fn = function(input, combine, queryHashes) {
|
|
if (combine) {
|
|
const lastHashes = __privateGet(this, _lastQueryHashes);
|
|
const queryHashesChanged = queryHashes !== void 0 && lastHashes !== void 0 && (lastHashes.length !== queryHashes.length || queryHashes.some((hash, i) => hash !== lastHashes[i]));
|
|
if (__privateGet(this, _result) !== __privateGet(this, _lastResult) || queryHashesChanged || combine !== __privateGet(this, _lastCombine)) {
|
|
__privateSet(this, _lastCombine, combine);
|
|
__privateSet(this, _lastResult, __privateGet(this, _result));
|
|
if (queryHashes !== void 0) __privateSet(this, _lastQueryHashes, queryHashes);
|
|
__privateSet(this, _combinedResult, replaceEqualDeep(__privateGet(this, _combinedResult), combine(input)));
|
|
}
|
|
return __privateGet(this, _combinedResult);
|
|
}
|
|
return input;
|
|
}, shouldSkipCombine_fn = function() {
|
|
var _a13;
|
|
return !((_a13 = __privateGet(this, _options)) == null ? void 0 : _a13.combine) || __privateGet(this, _observers2).some((observer, index) => {
|
|
var _a14;
|
|
return observer.options.suspense && ((_a14 = __privateGet(this, _result)[index]) == null ? void 0 : _a14.data) === void 0;
|
|
});
|
|
}, findMatchingObservers_fn = function(queries) {
|
|
const prevObserversMap = /* @__PURE__ */ new Map();
|
|
__privateGet(this, _observers2).forEach((observer) => {
|
|
const key = observer.options.queryHash;
|
|
if (!key) return;
|
|
const previousObservers = prevObserversMap.get(key);
|
|
if (previousObservers) previousObservers.push(observer);
|
|
else prevObserversMap.set(key, [observer]);
|
|
});
|
|
const observers = [];
|
|
queries.forEach((options) => {
|
|
var _a13;
|
|
const defaultedOptions = __privateGet(this, _client5).defaultQueryOptions(options);
|
|
const observer = ((_a13 = prevObserversMap.get(defaultedOptions.queryHash)) == null ? void 0 : _a13.shift()) ?? new QueryObserver(__privateGet(this, _client5), defaultedOptions);
|
|
observers.push({
|
|
defaultedQueryOptions: defaultedOptions,
|
|
observer
|
|
});
|
|
});
|
|
return observers;
|
|
}, onUpdate_fn = function(observer, result) {
|
|
const index = __privateGet(this, _observers2).indexOf(observer);
|
|
if (index !== -1) {
|
|
__privateSet(this, _result, __privateGet(this, _result).slice());
|
|
__privateGet(this, _result)[index] = result;
|
|
__privateMethod(this, _QueriesObserver_instances, notify_fn2).call(this);
|
|
}
|
|
}, notify_fn2 = function() {
|
|
var _a13;
|
|
if (this.hasListeners()) {
|
|
const shouldSkipCombine = __privateMethod(this, _QueriesObserver_instances, shouldSkipCombine_fn).call(this);
|
|
const previousResult = __privateGet(this, _combinedResult);
|
|
const newResult = shouldSkipCombine ? previousResult : __privateMethod(this, _QueriesObserver_instances, combineResult_fn).call(this, __privateMethod(this, _QueriesObserver_instances, trackResult_fn).call(this, __privateGet(this, _result), __privateGet(this, _observerMatches)), (_a13 = __privateGet(this, _options)) == null ? void 0 : _a13.combine);
|
|
if (shouldSkipCombine || previousResult !== newResult) notifyManager.batch(() => {
|
|
this.listeners.forEach((listener) => {
|
|
listener(__privateGet(this, _result));
|
|
});
|
|
});
|
|
}
|
|
}, _a10);
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/queryCache.js
|
|
var _queries2, _a11;
|
|
var QueryCache = (_a11 = class extends Subscribable {
|
|
constructor(config = {}) {
|
|
super();
|
|
__privateAdd(this, _queries2);
|
|
this.config = config;
|
|
__privateSet(this, _queries2, /* @__PURE__ */ new Map());
|
|
}
|
|
/**
|
|
* Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or
|
|
* builds and adds a new one to the cache if none exists yet. Used by framework adapters and
|
|
* plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing
|
|
* the reactive `QueryObserver` machinery.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const queryCache = queryClient.getQueryCache()
|
|
*
|
|
* const query = queryCache.build(queryClient, {
|
|
* queryKey: ['posts'],
|
|
* queryFn: fetchPosts,
|
|
* })
|
|
* ```
|
|
*/
|
|
build(client, options, state) {
|
|
const queryKey = options.queryKey;
|
|
const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
|
|
let query = this.get(queryHash);
|
|
if (!query) {
|
|
query = new Query({
|
|
client,
|
|
queryKey,
|
|
queryHash,
|
|
options: client.defaultQueryOptions(options),
|
|
state,
|
|
defaultOptions: client.getQueryDefaults(queryKey)
|
|
});
|
|
this.add(query);
|
|
}
|
|
return query;
|
|
}
|
|
/** @internal */
|
|
add(query) {
|
|
if (!__privateGet(this, _queries2).has(query.queryHash)) {
|
|
__privateGet(this, _queries2).set(query.queryHash, query);
|
|
this.notify({
|
|
type: "added",
|
|
query
|
|
});
|
|
}
|
|
}
|
|
/**
|
|
* Destroys the given `Query` and removes it from the cache, notifying subscribers with a
|
|
* `'removed'` event. A no-op if the query is no longer the one currently stored under its hash
|
|
* (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror
|
|
* removals across `QueryCache` instances.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const queryCache = queryClient.getQueryCache()
|
|
* const query = queryCache.find({ queryKey: ['posts'] })
|
|
*
|
|
* if (query) {
|
|
* queryCache.remove(query)
|
|
* }
|
|
* ```
|
|
*/
|
|
remove(query) {
|
|
const queryInMap = __privateGet(this, _queries2).get(query.queryHash);
|
|
if (queryInMap) {
|
|
query.destroy();
|
|
if (queryInMap === query) __privateGet(this, _queries2).delete(query.queryHash);
|
|
this.notify({
|
|
type: "removed",
|
|
query
|
|
});
|
|
}
|
|
}
|
|
/**
|
|
* Removes all queries from the cache.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const queryCache = queryClient.getQueryCache()
|
|
*
|
|
* queryCache.clear()
|
|
* ```
|
|
*/
|
|
clear() {
|
|
notifyManager.batch(() => {
|
|
this.getAll().forEach((query) => {
|
|
this.remove(query);
|
|
});
|
|
});
|
|
}
|
|
/**
|
|
* Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none
|
|
* exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather
|
|
* than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash
|
|
* to look up directly.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const queryCache = queryClient.getQueryCache()
|
|
* const queryHash = hashKey(['posts'])
|
|
*
|
|
* const query = queryCache.get(queryHash)
|
|
* ```
|
|
*/
|
|
get(queryHash) {
|
|
return __privateGet(this, _queries2).get(queryHash);
|
|
}
|
|
/**
|
|
* Returns all queries within the cache.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const queryCache = queryClient.getQueryCache()
|
|
*
|
|
* const queries = queryCache.getAll()
|
|
* ```
|
|
*/
|
|
getAll() {
|
|
return [...__privateGet(this, _queries2).values()];
|
|
}
|
|
/**
|
|
* A slightly more advanced method that can be used to get an existing query instance from the
|
|
* cache. This instance not only contains all the state for the query, but all of the instances,
|
|
* and underlying guts of the query as well. If the query does not exist, `undefined` is
|
|
* returned.
|
|
*
|
|
* This is not typically needed for most applications, but can come in handy when needing more
|
|
* information about a query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to
|
|
* decide whether a query is fresh enough to be used as an initial value).
|
|
*
|
|
* @see {@link QueryCache#findAll}
|
|
* @example
|
|
* ```ts
|
|
* const queryCache = queryClient.getQueryCache()
|
|
*
|
|
* const query = queryCache.find({ queryKey: ['posts'] })
|
|
* ```
|
|
*/
|
|
find(filters) {
|
|
const defaultedFilters = {
|
|
exact: true,
|
|
...filters
|
|
};
|
|
return this.getAll().find((query) => matchQuery(defaultedFilters, query));
|
|
}
|
|
/**
|
|
* An even more advanced method that can be used to get existing query instances from the cache
|
|
* that partially match a query key. If no queries match, an empty array is returned.
|
|
*
|
|
* This is not typically needed for most applications, but can come in handy when needing more
|
|
* information about queries in rare scenarios.
|
|
*
|
|
* @see {@link QueryCache#find}
|
|
* @example
|
|
* ```ts
|
|
* const queryCache = queryClient.getQueryCache()
|
|
*
|
|
* const queries = queryCache.findAll({ queryKey: ['posts'] })
|
|
* ```
|
|
*/
|
|
findAll(filters = {}) {
|
|
const queries = this.getAll();
|
|
return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
|
|
}
|
|
/** @internal */
|
|
notify(event) {
|
|
notifyManager.batch(() => {
|
|
this.listeners.forEach((listener) => {
|
|
listener(event);
|
|
});
|
|
});
|
|
}
|
|
/** @internal */
|
|
onFocus() {
|
|
notifyManager.batch(() => {
|
|
this.getAll().forEach((query) => {
|
|
query.onFocus();
|
|
});
|
|
});
|
|
}
|
|
/** @internal */
|
|
onOnline() {
|
|
notifyManager.batch(() => {
|
|
this.getAll().forEach((query) => {
|
|
query.onOnline();
|
|
});
|
|
});
|
|
}
|
|
}, _queries2 = new WeakMap(), _a11);
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/queryClient.js
|
|
var _queryCache, _mutationCache2, _defaultOptions2, _queryDefaults, _mutationDefaults, _mountCount, _unsubscribeFocus, _unsubscribeOnline, _a12;
|
|
var QueryClient = (_a12 = class {
|
|
constructor(config = {}) {
|
|
__privateAdd(this, _queryCache);
|
|
__privateAdd(this, _mutationCache2);
|
|
__privateAdd(this, _defaultOptions2);
|
|
__privateAdd(this, _queryDefaults);
|
|
__privateAdd(this, _mutationDefaults);
|
|
__privateAdd(this, _mountCount);
|
|
__privateAdd(this, _unsubscribeFocus);
|
|
__privateAdd(this, _unsubscribeOnline);
|
|
__privateSet(this, _queryCache, config.queryCache || new QueryCache());
|
|
__privateSet(this, _mutationCache2, config.mutationCache || new MutationCache());
|
|
__privateSet(this, _defaultOptions2, config.defaultOptions || {});
|
|
__privateSet(this, _queryDefaults, /* @__PURE__ */ new Map());
|
|
__privateSet(this, _mutationDefaults, /* @__PURE__ */ new Map());
|
|
__privateSet(this, _mountCount, 0);
|
|
}
|
|
/**
|
|
* Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start
|
|
* listening for focus/online events and resume paused mutations. Ref-counted via an internal
|
|
* mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down
|
|
* the shared listeners until the last one unmounts.
|
|
*/
|
|
mount() {
|
|
__privateWrapper(this, _mountCount)._++;
|
|
if (__privateGet(this, _mountCount) !== 1) return;
|
|
__privateSet(this, _unsubscribeFocus, focusManager.subscribe(async (focused) => {
|
|
if (focused) {
|
|
await this.resumePausedMutations();
|
|
__privateGet(this, _queryCache).onFocus();
|
|
}
|
|
}));
|
|
__privateSet(this, _unsubscribeOnline, onlineManager.subscribe(async (online) => {
|
|
if (online) {
|
|
await this.resumePausedMutations();
|
|
__privateGet(this, _queryCache).onOnline();
|
|
}
|
|
}));
|
|
}
|
|
/**
|
|
* The inverse of {@link QueryClient#mount} — called by a framework adapter's
|
|
* `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online
|
|
* listeners once the mount count returns to `0`.
|
|
*/
|
|
unmount() {
|
|
var _a13, _b;
|
|
__privateWrapper(this, _mountCount)._--;
|
|
if (__privateGet(this, _mountCount) !== 0) return;
|
|
(_a13 = __privateGet(this, _unsubscribeFocus)) == null ? void 0 : _a13.call(this);
|
|
__privateSet(this, _unsubscribeFocus, void 0);
|
|
(_b = __privateGet(this, _unsubscribeOnline)) == null ? void 0 : _b.call(this);
|
|
__privateSet(this, _unsubscribeOnline, void 0);
|
|
}
|
|
/**
|
|
* Returns the number of queries in the cache that are currently fetching, optionally
|
|
* matching a set of filters. This includes background-fetching, loading new pages, and
|
|
* loading more infinite query results.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* if (queryClient.isFetching()) {
|
|
* console.log('At least one query is fetching!')
|
|
* }
|
|
* ```
|
|
*/
|
|
isFetching(filters) {
|
|
return __privateGet(this, _queryCache).findAll({
|
|
...filters,
|
|
fetchStatus: "fetching"
|
|
}).length;
|
|
}
|
|
/**
|
|
* Returns the number of mutations in the cache that are currently pending, optionally
|
|
* matching a set of filters.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* if (queryClient.isMutating()) {
|
|
* console.log('At least one mutation is pending!')
|
|
* }
|
|
* ```
|
|
*/
|
|
isMutating(filters) {
|
|
return __privateGet(this, _mutationCache2).findAll({
|
|
...filters,
|
|
status: "pending"
|
|
}).length;
|
|
}
|
|
/**
|
|
* Imperative (non-reactive) way to retrieve data for a QueryKey.
|
|
* Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.
|
|
*
|
|
* Hint: Do not use this function inside a component, because it won't receive updates.
|
|
* Use `useQuery` to create a `QueryObserver` that subscribes to changes.
|
|
*
|
|
* @see {@link QueryClient#getQueriesData}
|
|
*/
|
|
getQueryData(queryKey) {
|
|
var _a13;
|
|
const options = this.defaultQueryOptions({ queryKey });
|
|
return (_a13 = __privateGet(this, _queryCache).get(options.queryHash)) == null ? void 0 : _a13.state.data;
|
|
}
|
|
/**
|
|
* @deprecated Use queryClient.query({ ...options, staleTime: 'static' }) instead. This method will be removed in the next major version.
|
|
*/
|
|
ensureQueryData(options) {
|
|
const defaultedOptions = this.defaultQueryOptions(options);
|
|
const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
|
|
const cachedData = query.state.data;
|
|
if (cachedData === void 0) return this.fetchQuery(options);
|
|
if (options.revalidateIfStale && query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query))) this.prefetchQuery(defaultedOptions);
|
|
return Promise.resolve(cachedData);
|
|
}
|
|
/**
|
|
* Imperative (non-reactive) way to retrieve the cached data of multiple queries at once.
|
|
* Only queries matching the given filters are returned; if none match, an empty array is
|
|
* returned.
|
|
*
|
|
* Because the matched queries can hold data of different shapes (e.g. a broad filter can match
|
|
* queries with unrelated data types), the `TQueryFnData` generic defaults to `unknown` rather
|
|
* than being inferred. Passing a more specific type is a convenience for call sites that know
|
|
* every matched query holds the same shape — it is not checked against the actual cache
|
|
* contents.
|
|
*
|
|
* @see {@link QueryClient#getQueryData}
|
|
* @example
|
|
* ```ts
|
|
* const data = queryClient.getQueriesData({ queryKey: ['posts'] })
|
|
* ```
|
|
*/
|
|
getQueriesData(filters) {
|
|
return __privateGet(this, _queryCache).findAll(filters).map(({ queryKey, state }) => {
|
|
return [queryKey, state.data];
|
|
});
|
|
}
|
|
/**
|
|
* Synchronous way to immediately update a query's cached data. If the updater (or the value
|
|
* passed) resolves to `undefined`, the cache is left untouched and no query is created;
|
|
* otherwise, if the query does not exist yet, it will be created. To update multiple queries
|
|
* at once by partially matching query keys, use {@link QueryClient#setQueriesData} instead.
|
|
*
|
|
* Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved
|
|
* via {@link QueryClient#getQueryData}, in place.
|
|
*
|
|
* @param queryKey - The query key to set data for.
|
|
* @param updater - Either the new data, or a function that receives the current data (which
|
|
* may be `undefined`) and returns the new data.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* queryClient.setQueryData(['posts'], newPosts)
|
|
*
|
|
* // Or, using an updater function that receives the current data:
|
|
* queryClient.setQueryData(['posts'], (oldPosts) => [...oldPosts, newPost])
|
|
* ```
|
|
*/
|
|
setQueryData(queryKey, updater, options) {
|
|
var _a13;
|
|
const defaultedOptions = this.defaultQueryOptions({ queryKey });
|
|
const prevData = (_a13 = __privateGet(this, _queryCache).get(defaultedOptions.queryHash)) == null ? void 0 : _a13.state.data;
|
|
const data = functionalUpdate(updater, prevData);
|
|
if (data === void 0) return;
|
|
return __privateGet(this, _queryCache).build(this, defaultedOptions).setData(data, {
|
|
...options,
|
|
manual: true
|
|
});
|
|
}
|
|
/**
|
|
* Synchronous way to immediately update the cached data of multiple queries at once, using
|
|
* filters or partial query key matching. Only queries that already exist and match the given
|
|
* filters are updated; no new cache entries are created. Internally this calls
|
|
* {@link QueryClient#setQueryData} for each matching query.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* queryClient.setQueriesData({ queryKey: ['posts'] }, (oldPosts) =>
|
|
* oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts,
|
|
* )
|
|
* ```
|
|
*/
|
|
setQueriesData(filters, updater, options) {
|
|
return notifyManager.batch(() => __privateGet(this, _queryCache).findAll(filters).map(({ queryKey }) => [queryKey, this.setQueryData(queryKey, updater, options)]));
|
|
}
|
|
/**
|
|
* Imperative (non-reactive) way to retrieve an existing query's state. If the query does not
|
|
* exist, `undefined` is returned.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const state = queryClient.getQueryState(['posts'])
|
|
* console.log(state?.dataUpdatedAt)
|
|
* ```
|
|
*/
|
|
getQueryState(queryKey) {
|
|
var _a13;
|
|
const options = this.defaultQueryOptions({ queryKey });
|
|
return (_a13 = __privateGet(this, _queryCache).get(options.queryHash)) == null ? void 0 : _a13.state;
|
|
}
|
|
/**
|
|
* Removes queries from the cache that match the given filters. Unlike
|
|
* {@link QueryClient#invalidateQueries} or {@link QueryClient#refetchQueries}, this removes
|
|
* matching queries from the cache instead of refetching them. Without filters, every query in
|
|
* the cache is removed.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* queryClient.removeQueries({ queryKey: ['posts'], exact: true })
|
|
* ```
|
|
*/
|
|
removeQueries(filters) {
|
|
const queryCache = __privateGet(this, _queryCache);
|
|
notifyManager.batch(() => {
|
|
queryCache.findAll(filters).forEach((query) => {
|
|
queryCache.remove(query);
|
|
});
|
|
});
|
|
}
|
|
/**
|
|
* Resets queries matching the given filters back to their initial state (e.g. any
|
|
* `initialData`), notifying subscribers rather than removing them. Active queries among the
|
|
* matched set are then refetched, and the returned promise resolves once that refetch settles.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await queryClient.resetQueries({ queryKey: ['posts'], exact: true })
|
|
* ```
|
|
*/
|
|
resetQueries(filters, options) {
|
|
const queryCache = __privateGet(this, _queryCache);
|
|
return notifyManager.batch(() => {
|
|
const matched = queryCache.findAll(filters);
|
|
const queriesToRefetch = new Set(matched);
|
|
matched.forEach((query) => {
|
|
query.reset();
|
|
});
|
|
return this.refetchQueries({
|
|
type: "active",
|
|
predicate: (query) => queriesToRefetch.has(query)
|
|
}, options);
|
|
});
|
|
}
|
|
/**
|
|
* Cancels outgoing fetches for queries matching the given filters. Most useful when performing
|
|
* optimistic updates, since any outgoing refetch that resolves afterwards would otherwise
|
|
* overwrite the optimistic update. By default (`revert: true`), a cancelled query's data is
|
|
* reverted to its state before the outgoing fetch started.
|
|
*
|
|
* The returned promise never rejects, even if individual cancellations fail.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await queryClient.cancelQueries({ queryKey: ['posts'], exact: true })
|
|
* ```
|
|
*/
|
|
cancelQueries(filters, cancelOptions = {}) {
|
|
const defaultedCancelOptions = {
|
|
revert: true,
|
|
...cancelOptions
|
|
};
|
|
const promises = notifyManager.batch(() => __privateGet(this, _queryCache).findAll(filters).map((query) => query.cancel(defaultedCancelOptions)));
|
|
return Promise.all(promises).then(noop).catch(noop);
|
|
}
|
|
/**
|
|
* Marks queries matching the given filters as invalidated. Unlike
|
|
* {@link QueryClient#removeQueries}, invalidated queries stay in the cache.
|
|
*
|
|
* Unless `filters.refetchType` is `'none'`, matching queries are then refetched via
|
|
* {@link QueryClient#refetchQueries}, using `filters.refetchType` if set, otherwise
|
|
* `filters.type`, otherwise `'active'`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await queryClient.invalidateQueries({ queryKey: ['posts'], refetchType: 'active' })
|
|
* ```
|
|
*/
|
|
invalidateQueries(filters, options = {}) {
|
|
return notifyManager.batch(() => {
|
|
__privateGet(this, _queryCache).findAll(filters).forEach((query) => {
|
|
query.invalidate();
|
|
});
|
|
if ((filters == null ? void 0 : filters.refetchType) === "none") return Promise.resolve();
|
|
return this.refetchQueries({
|
|
...filters,
|
|
type: (filters == null ? void 0 : filters.refetchType) ?? (filters == null ? void 0 : filters.type) ?? "active"
|
|
}, options);
|
|
});
|
|
}
|
|
/**
|
|
* Refetches queries matching the given filters, regardless of whether they are stale. Without
|
|
* filters, every query in the cache is refetched. Queries that are disabled, or static (only
|
|
* have observers with a static `staleTime`), are never refetched.
|
|
*
|
|
* By default (`cancelRefetch: true`), a currently running fetch is cancelled before the new
|
|
* one starts. The returned promise resolves once all matching queries have settled; it does
|
|
* not reject on individual query failures unless `throwOnError` is set.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // refetch all active queries partially matching a query key:
|
|
* await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })
|
|
* ```
|
|
*/
|
|
refetchQueries(filters, options = {}) {
|
|
const fetchOptions = {
|
|
...options,
|
|
cancelRefetch: options.cancelRefetch ?? true
|
|
};
|
|
const promises = notifyManager.batch(() => __privateGet(this, _queryCache).findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {
|
|
let promise = query.fetch(void 0, fetchOptions);
|
|
if (!fetchOptions.throwOnError) promise = promise.catch(noop);
|
|
return query.state.fetchStatus === "paused" ? Promise.resolve() : promise;
|
|
}));
|
|
return Promise.all(promises).then(noop);
|
|
}
|
|
/**
|
|
* Asynchronous method to fetch and cache a query, resolving with the data or throwing with
|
|
* the error.
|
|
*
|
|
* If the query already exists in the cache and its data is not stale (per the given
|
|
* `staleTime`), the cached data is returned without fetching. Otherwise, the query is fetched
|
|
* and the promise resolves once the fetch settles. If a `select` function is provided, it is
|
|
* applied to the data in both cases (cached or freshly fetched) before it is returned.
|
|
*
|
|
* Unlike a reactive observer, retries are disabled by default here (`retry: false`) unless
|
|
* explicitly configured, since there is no component to catch a thrown error and retry through
|
|
* re-render.
|
|
*
|
|
* The accepted options are `QueryObserverOptions` minus the fields that only make sense for a
|
|
* reactive observer — `enabled`, `refetchInterval`, `refetchIntervalInBackground`,
|
|
* `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`,
|
|
* `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this
|
|
* method's options.
|
|
*
|
|
* This method replaces the deprecated `fetchQuery`, and — combined with
|
|
* `{ staleTime: 'static' }` — the deprecated `ensureQueryData`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* try {
|
|
* const data = await queryClient.query({ queryKey, queryFn, staleTime: 10000 })
|
|
* } catch (error) {
|
|
* console.log(error)
|
|
* }
|
|
* ```
|
|
*/
|
|
async query(options) {
|
|
const defaultedOptions = this.defaultQueryOptions(options);
|
|
if (defaultedOptions.retry === void 0) defaultedOptions.retry = false;
|
|
const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
|
|
const queryData = query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query)) ? await query.fetch(defaultedOptions) : query.state.data;
|
|
const select = defaultedOptions.select;
|
|
if (select) return select(queryData);
|
|
return queryData;
|
|
}
|
|
/**
|
|
* @deprecated Use queryClient.query(options) instead. This method will be removed in the next major version.
|
|
*/
|
|
fetchQuery(options) {
|
|
const defaultedOptions = this.defaultQueryOptions(options);
|
|
if (defaultedOptions.retry === void 0) defaultedOptions.retry = false;
|
|
const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
|
|
return query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query)) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
|
|
}
|
|
/**
|
|
* @deprecated Use queryClient.query(options) instead. You can swallow errors with `.catch(noop)`. This method will be removed in the next major version.
|
|
*/
|
|
prefetchQuery(options) {
|
|
return this.fetchQuery(options).then(noop).catch(noop);
|
|
}
|
|
/**
|
|
* Asynchronous method to fetch and cache an infinite query, resolving with an
|
|
* {@link InfiniteData} object or throwing with the error.
|
|
*
|
|
* Behaves like {@link QueryClient#query}, accepting the same options (minus
|
|
* `initialPageParam`), plus the required `initialPageParam`, and an optional `pages` /
|
|
* `getNextPageParam` pair used to refetch a fixed number of pages from the start.
|
|
*
|
|
* This method replaces the deprecated `fetchInfiniteQuery`, and — combined with
|
|
* `{ staleTime: 'static' }` — the deprecated `ensureInfiniteQueryData`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* try {
|
|
* const data = await queryClient.infiniteQuery({ queryKey, queryFn, initialPageParam: 0 })
|
|
* console.log(data.pages)
|
|
* } catch (error) {
|
|
* console.log(error)
|
|
* }
|
|
* ```
|
|
*/
|
|
infiniteQuery(options) {
|
|
options._type = "infinite";
|
|
return this.query(options);
|
|
}
|
|
/**
|
|
* @deprecated Use queryClient.infiniteQuery(options) instead. This method will be removed in the next major version.
|
|
*/
|
|
fetchInfiniteQuery(options) {
|
|
options._type = "infinite";
|
|
return this.fetchQuery(options);
|
|
}
|
|
/**
|
|
* @deprecated Use queryClient.infiniteQuery(options) instead. You can swallow errors with `.catch(noop)`. This method will be removed in the next major version.
|
|
*/
|
|
prefetchInfiniteQuery(options) {
|
|
return this.fetchInfiniteQuery(options).then(noop).catch(noop);
|
|
}
|
|
/**
|
|
* @deprecated Use queryClient.infiniteQuery({ ...options, staleTime: 'static' }) instead. This method will be removed in the next major version.
|
|
*/
|
|
ensureInfiniteQueryData(options) {
|
|
options._type = "infinite";
|
|
return this.ensureQueryData(options);
|
|
}
|
|
/**
|
|
* Resumes mutations that were paused because there was no network connection. Does nothing
|
|
* (resolving immediately) if the client is currently offline.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { QueryClient } from '@tanstack/query-core'
|
|
*
|
|
* const queryClient = new QueryClient()
|
|
* await queryClient.resumePausedMutations()
|
|
* ```
|
|
*/
|
|
resumePausedMutations() {
|
|
if (onlineManager.isOnline()) return __privateGet(this, _mutationCache2).resumePausedMutations();
|
|
return Promise.resolve();
|
|
}
|
|
/**
|
|
* Returns the query cache this client is connected to.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { QueryClient } from '@tanstack/query-core'
|
|
*
|
|
* const queryClient = new QueryClient()
|
|
* const queryCache = queryClient.getQueryCache()
|
|
* const queries = queryCache.findAll({ queryKey: ['posts'] })
|
|
* ```
|
|
*/
|
|
getQueryCache() {
|
|
return __privateGet(this, _queryCache);
|
|
}
|
|
/**
|
|
* Returns the mutation cache this client is connected to.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { QueryClient } from '@tanstack/query-core'
|
|
*
|
|
* const queryClient = new QueryClient()
|
|
* const mutationCache = queryClient.getMutationCache()
|
|
* const mutations = mutationCache.findAll({ status: 'pending' })
|
|
* ```
|
|
*/
|
|
getMutationCache() {
|
|
return __privateGet(this, _mutationCache2);
|
|
}
|
|
/**
|
|
* Returns the default options that were set when creating the client, or via
|
|
* {@link QueryClient#setDefaultOptions}.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { QueryClient } from '@tanstack/query-core'
|
|
*
|
|
* const queryClient = new QueryClient()
|
|
* const defaultOptions = queryClient.getDefaultOptions()
|
|
* ```
|
|
*/
|
|
getDefaultOptions() {
|
|
return __privateGet(this, _defaultOptions2);
|
|
}
|
|
/**
|
|
* Dynamically sets the default options for this client, overwriting any previously defined
|
|
* default options.
|
|
*
|
|
* @see {@link QueryClient#getDefaultOptions}
|
|
* @example
|
|
* ```ts
|
|
* import { QueryClient } from '@tanstack/query-core'
|
|
*
|
|
* const queryClient = new QueryClient()
|
|
* queryClient.setDefaultOptions({
|
|
* queries: {
|
|
* staleTime: Infinity,
|
|
* },
|
|
* })
|
|
* ```
|
|
*/
|
|
setDefaultOptions(options) {
|
|
__privateSet(this, _defaultOptions2, options);
|
|
}
|
|
/**
|
|
* Sets default options for queries whose query key partially matches the given `queryKey`.
|
|
*
|
|
* If several registered query defaults match a given query key, they are merged together in
|
|
* registration order by {@link QueryClient#getQueryDefaults}, so register defaults from the
|
|
* most generic key to the least generic one — more specific defaults should be registered
|
|
* after more generic ones so they take precedence.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
|
|
*
|
|
* await queryClient.query({ queryKey: ['posts'] })
|
|
* ```
|
|
*/
|
|
setQueryDefaults(queryKey, options) {
|
|
__privateGet(this, _queryDefaults).set(hashKey(queryKey), {
|
|
queryKey,
|
|
defaultOptions: options
|
|
});
|
|
}
|
|
/**
|
|
* Returns the default options registered for queries whose query key partially matches the
|
|
* given `queryKey`, via {@link QueryClient#setQueryDefaults}. If multiple registered defaults
|
|
* match, they are merged together in registration order.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const defaultOptions = queryClient.getQueryDefaults(['posts'])
|
|
* ```
|
|
*/
|
|
getQueryDefaults(queryKey) {
|
|
const defaults = [...__privateGet(this, _queryDefaults).values()];
|
|
const result = {};
|
|
defaults.forEach((queryDefault) => {
|
|
if (partialMatchKey(queryKey, queryDefault.queryKey)) Object.assign(result, queryDefault.defaultOptions);
|
|
});
|
|
return result;
|
|
}
|
|
/**
|
|
* Sets default options for mutations whose mutation key partially matches the given
|
|
* `mutationKey`. As with {@link QueryClient#setQueryDefaults}, the order of registration
|
|
* matters when several registered defaults match the same mutation key.
|
|
*
|
|
* @see {@link QueryClient#getMutationDefaults}
|
|
* @example
|
|
* ```ts
|
|
* queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
|
|
* ```
|
|
*/
|
|
setMutationDefaults(mutationKey, options) {
|
|
__privateGet(this, _mutationDefaults).set(hashKey(mutationKey), {
|
|
mutationKey,
|
|
defaultOptions: options
|
|
});
|
|
}
|
|
/**
|
|
* Returns the default options registered for mutations whose mutation key partially matches
|
|
* the given `mutationKey`, via {@link QueryClient#setMutationDefaults}. If multiple registered
|
|
* defaults match, they are merged together in registration order.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const defaultOptions = queryClient.getMutationDefaults(['addPost'])
|
|
* ```
|
|
*/
|
|
getMutationDefaults(mutationKey) {
|
|
const defaults = [...__privateGet(this, _mutationDefaults).values()];
|
|
const result = {};
|
|
defaults.forEach((queryDefault) => {
|
|
if (partialMatchKey(mutationKey, queryDefault.mutationKey)) Object.assign(result, queryDefault.defaultOptions);
|
|
});
|
|
return result;
|
|
}
|
|
/**
|
|
* Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the
|
|
* caller into their final, defaulted form: merging `queryClient.setQueryDefaults` for the
|
|
* given `queryKey`, then the client's own `defaultOptions.queries`, then the caller's options
|
|
* on top. A no-op if the options are already defaulted (`_defaulted: true`).
|
|
*/
|
|
defaultQueryOptions(options) {
|
|
if (options._defaulted) return options;
|
|
const defaultedOptions = {
|
|
...__privateGet(this, _defaultOptions2).queries,
|
|
...this.getQueryDefaults(options.queryKey),
|
|
...options,
|
|
_defaulted: true
|
|
};
|
|
if (!defaultedOptions.queryHash) defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
|
|
if (defaultedOptions.refetchOnReconnect === void 0) defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
|
|
if (defaultedOptions.throwOnError === void 0) defaultedOptions.throwOnError = !!defaultedOptions.suspense;
|
|
if (!defaultedOptions.networkMode && defaultedOptions.persister) defaultedOptions.networkMode = "offlineFirst";
|
|
if (defaultedOptions.queryFn === skipToken) defaultedOptions.enabled = false;
|
|
return defaultedOptions;
|
|
}
|
|
/**
|
|
* The mutation counterpart of {@link QueryClient#defaultQueryOptions}. Called by framework
|
|
* adapters (e.g. inside `useMutation`) to merge `queryClient.setMutationDefaults` for the
|
|
* given `mutationKey`, then the client's `defaultOptions.mutations`, then the caller's options
|
|
* on top. A no-op if the options are already defaulted (`_defaulted: true`).
|
|
*/
|
|
defaultMutationOptions(options) {
|
|
if (options == null ? void 0 : options._defaulted) return options;
|
|
return {
|
|
...__privateGet(this, _defaultOptions2).mutations,
|
|
...(options == null ? void 0 : options.mutationKey) && this.getMutationDefaults(options.mutationKey),
|
|
...options,
|
|
_defaulted: true
|
|
};
|
|
}
|
|
/**
|
|
* Clears both the query cache and the mutation cache this client is connected to.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { QueryClient } from '@tanstack/query-core'
|
|
*
|
|
* const queryClient = new QueryClient()
|
|
* queryClient.clear()
|
|
* ```
|
|
*/
|
|
clear() {
|
|
__privateGet(this, _queryCache).clear();
|
|
__privateGet(this, _mutationCache2).clear();
|
|
}
|
|
}, _queryCache = new WeakMap(), _mutationCache2 = new WeakMap(), _defaultOptions2 = new WeakMap(), _queryDefaults = new WeakMap(), _mutationDefaults = new WeakMap(), _mountCount = new WeakMap(), _unsubscribeFocus = new WeakMap(), _unsubscribeOnline = new WeakMap(), _a12);
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/streamedQuery.js
|
|
function streamedQuery({ streamFn, refetchMode = "reset", reducer = (items, chunk) => addToEnd(items, chunk), initialValue = [] }) {
|
|
return async (context) => {
|
|
const query = context.client.getQueryCache().find({
|
|
queryKey: context.queryKey,
|
|
exact: true
|
|
});
|
|
const isRefetch = !!query && query.isFetched();
|
|
if (isRefetch && refetchMode === "reset") query.setState({
|
|
...query.resetState,
|
|
fetchStatus: "fetching"
|
|
});
|
|
let result = initialValue;
|
|
let cancelled = false;
|
|
const stream = await streamFn(addConsumeAwareSignal({
|
|
client: context.client,
|
|
meta: context.meta,
|
|
queryKey: context.queryKey,
|
|
pageParam: context.pageParam,
|
|
direction: context.direction
|
|
}, () => context.signal, () => cancelled = true));
|
|
const isReplaceRefetch = isRefetch && refetchMode === "replace";
|
|
for await (const chunk of stream) {
|
|
if (cancelled) break;
|
|
if (isReplaceRefetch) result = reducer(result, chunk);
|
|
else context.client.setQueryData(context.queryKey, (prev) => reducer(prev === void 0 ? initialValue : prev, chunk));
|
|
}
|
|
if (isReplaceRefetch && !cancelled) context.client.setQueryData(context.queryKey, result);
|
|
const data = context.client.getQueryData(context.queryKey);
|
|
return data === void 0 ? initialValue : data;
|
|
};
|
|
}
|
|
|
|
// node_modules/@tanstack/query-core/build/modern/types.js
|
|
var dataTagSymbol = Symbol();
|
|
var dataTagErrorSymbol = Symbol();
|
|
var unsetMarker = Symbol();
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/HydrationBoundary.js
|
|
var HydrationBoundary = ({ children, options = {}, state, queryClient }) => {
|
|
const client = useQueryClient(queryClient);
|
|
const optionsRef = React2.useRef(options);
|
|
React2.useEffect(() => {
|
|
optionsRef.current = options;
|
|
});
|
|
const hydrationQueue = React2.useMemo(() => {
|
|
if (state) {
|
|
if (typeof state !== "object") return;
|
|
const queryCache = client.getQueryCache();
|
|
const queries = state.queries || [];
|
|
const newQueries = [];
|
|
const existingQueries = [];
|
|
for (const dehydratedQuery of queries) {
|
|
const existingQuery = queryCache.get(dehydratedQuery.queryHash);
|
|
if (!existingQuery) newQueries.push(dehydratedQuery);
|
|
else if (dehydratedQuery.state.dataUpdatedAt > existingQuery.state.dataUpdatedAt || dehydratedQuery.promise && existingQuery.state.status !== "pending" && existingQuery.state.fetchStatus !== "fetching" && dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt) existingQueries.push(dehydratedQuery);
|
|
}
|
|
if (newQueries.length > 0) hydrate(client, { queries: newQueries }, optionsRef.current);
|
|
if (existingQueries.length > 0) return existingQueries;
|
|
}
|
|
}, [client, state]);
|
|
React2.useEffect(() => {
|
|
if (hydrationQueue) hydrate(client, { queries: hydrationQueue }, optionsRef.current);
|
|
}, [client, hydrationQueue]);
|
|
return children;
|
|
};
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/IsRestoringProvider.js
|
|
var React3 = __toESM(require_react(), 1);
|
|
var IsRestoringContext = React3.createContext(false);
|
|
var useIsRestoring = () => React3.useContext(IsRestoringContext);
|
|
var IsRestoringProvider = IsRestoringContext.Provider;
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/QueryErrorResetBoundary.js
|
|
var React4 = __toESM(require_react(), 1);
|
|
var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
|
|
function createValue() {
|
|
let isReset = false;
|
|
return {
|
|
/**
|
|
* Clears the reset state, so queries know not to try again until the boundary is reset again.
|
|
*/
|
|
clearReset: () => {
|
|
isReset = false;
|
|
},
|
|
/**
|
|
* Resets any query errors within the boundary, so queries know they can try again.
|
|
*/
|
|
reset: () => {
|
|
isReset = true;
|
|
},
|
|
/**
|
|
* Returns whether the boundary has been reset and not yet cleared.
|
|
*/
|
|
isReset: () => {
|
|
return isReset;
|
|
}
|
|
};
|
|
}
|
|
var QueryErrorResetBoundaryContext = React4.createContext(createValue());
|
|
var useQueryErrorResetBoundary = () => React4.useContext(QueryErrorResetBoundaryContext);
|
|
var QueryErrorResetBoundary = ({ children }) => {
|
|
const [value] = React4.useState(() => createValue());
|
|
return (0, import_jsx_runtime2.jsx)(QueryErrorResetBoundaryContext.Provider, {
|
|
value,
|
|
children: typeof children === "function" ? children(value) : children
|
|
});
|
|
};
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/errorBoundaryUtils.js
|
|
var React5 = __toESM(require_react(), 1);
|
|
var ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {
|
|
const throwOnError = (query == null ? void 0 : query.state.error) && typeof options.throwOnError === "function" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;
|
|
if (options.suspense || throwOnError) {
|
|
if (!errorResetBoundary.isReset()) options.retryOnMount = false;
|
|
}
|
|
};
|
|
var useClearResetErrorBoundary = (errorResetBoundary) => {
|
|
React5.useEffect(() => {
|
|
errorResetBoundary.clearReset();
|
|
}, [errorResetBoundary]);
|
|
};
|
|
var getHasError = ({ result, errorResetBoundary, throwOnError, query, suspense }) => {
|
|
return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && (suspense && result.data === void 0 || shouldThrowError(throwOnError, [result.error, query]));
|
|
};
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/suspense.js
|
|
var defaultThrowOnError = (_error, query) => query.state.data === void 0;
|
|
var ensureSuspenseTimers = (defaultedOptions) => {
|
|
if (defaultedOptions.suspense) {
|
|
const MIN_SUSPENSE_TIME_MS = 1e3;
|
|
const clamp = (value) => value === "static" ? value : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS);
|
|
const originalStaleTime = defaultedOptions.staleTime;
|
|
defaultedOptions.staleTime = typeof originalStaleTime === "function" ? (...args) => clamp(originalStaleTime(...args)) : clamp(originalStaleTime);
|
|
if (typeof defaultedOptions.gcTime === "number") defaultedOptions.gcTime = Math.max(defaultedOptions.gcTime, MIN_SUSPENSE_TIME_MS);
|
|
}
|
|
};
|
|
var shouldSuspend = (defaultedOptions, result) => (defaultedOptions == null ? void 0 : defaultedOptions.suspense) && result.isPending;
|
|
var fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {
|
|
errorResetBoundary.clearReset();
|
|
});
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/useQueries.js
|
|
var React6 = __toESM(require_react(), 1);
|
|
function useQueries({ queries, ...options }, queryClient) {
|
|
const client = useQueryClient(queryClient);
|
|
const isRestoring = useIsRestoring();
|
|
const errorResetBoundary = useQueryErrorResetBoundary();
|
|
const subscribed = options.subscribed !== false;
|
|
const defaultedQueries = React6.useMemo(() => queries.map((opts) => {
|
|
const defaultedOptions = client.defaultQueryOptions(opts);
|
|
defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : subscribed ? "optimistic" : void 0;
|
|
return defaultedOptions;
|
|
}), [
|
|
queries,
|
|
client,
|
|
isRestoring,
|
|
subscribed
|
|
]);
|
|
defaultedQueries.forEach((queryOptions2) => {
|
|
ensureSuspenseTimers(queryOptions2);
|
|
const query = client.getQueryCache().get(queryOptions2.queryHash);
|
|
ensurePreventErrorBoundaryRetry(queryOptions2, errorResetBoundary, query);
|
|
});
|
|
useClearResetErrorBoundary(errorResetBoundary);
|
|
const [observer] = React6.useState(() => new QueriesObserver(client, defaultedQueries, options));
|
|
const [optimisticResult, getCombinedResult, trackResult] = observer.getOptimisticResult(defaultedQueries, options.combine);
|
|
const shouldSubscribe = !isRestoring && subscribed;
|
|
React6.useSyncExternalStore(React6.useCallback((onStoreChange) => shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop, [observer, shouldSubscribe]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
|
|
React6.useEffect(() => {
|
|
observer.setQueries(defaultedQueries, options);
|
|
}, [
|
|
defaultedQueries,
|
|
options,
|
|
observer
|
|
]);
|
|
const suspensePromises = optimisticResult.some((result, index) => shouldSuspend(defaultedQueries[index], result)) ? optimisticResult.flatMap((result, index) => {
|
|
const opts = defaultedQueries[index];
|
|
if (opts && shouldSuspend(opts, result)) {
|
|
const queryObserver = new QueryObserver(client, opts);
|
|
return fetchOptimistic(opts, queryObserver, errorResetBoundary);
|
|
}
|
|
return [];
|
|
}) : [];
|
|
if (suspensePromises.length > 0) throw Promise.all(suspensePromises);
|
|
const firstSingleResultWhichShouldThrow = optimisticResult.find((result, index) => {
|
|
const query = defaultedQueries[index];
|
|
return query && getHasError({
|
|
result,
|
|
errorResetBoundary,
|
|
throwOnError: query.throwOnError,
|
|
query: client.getQueryCache().get(query.queryHash),
|
|
suspense: query.suspense
|
|
});
|
|
});
|
|
if (firstSingleResultWhichShouldThrow) throw firstSingleResultWhichShouldThrow.error;
|
|
return getCombinedResult(trackResult());
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/useBaseQuery.js
|
|
var React7 = __toESM(require_react(), 1);
|
|
function useBaseQuery(options, Observer, queryClient) {
|
|
if (true) {
|
|
if (typeof options !== "object" || Array.isArray(options)) throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');
|
|
}
|
|
const isRestoring = useIsRestoring();
|
|
const errorResetBoundary = useQueryErrorResetBoundary();
|
|
const client = useQueryClient(queryClient);
|
|
const defaultedOptions = client.defaultQueryOptions(options);
|
|
const query = client.getQueryCache().get(defaultedOptions.queryHash);
|
|
if (true) {
|
|
if (!defaultedOptions.queryFn) console.error(`[${defaultedOptions.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`);
|
|
}
|
|
const subscribed = options.subscribed !== false;
|
|
defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : subscribed ? "optimistic" : void 0;
|
|
ensureSuspenseTimers(defaultedOptions);
|
|
ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query);
|
|
useClearResetErrorBoundary(errorResetBoundary);
|
|
const [observer] = React7.useState(() => new Observer(client, defaultedOptions));
|
|
const result = observer.getOptimisticResult(defaultedOptions);
|
|
const shouldSubscribe = !isRestoring && subscribed;
|
|
React7.useSyncExternalStore(React7.useCallback((onStoreChange) => {
|
|
const unsubscribe = shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop;
|
|
observer.updateResult();
|
|
return unsubscribe;
|
|
}, [observer, shouldSubscribe]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
|
|
React7.useEffect(() => {
|
|
observer.setOptions(defaultedOptions);
|
|
}, [defaultedOptions, observer]);
|
|
if (shouldSuspend(defaultedOptions, result)) throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);
|
|
if (getHasError({
|
|
result,
|
|
errorResetBoundary,
|
|
throwOnError: defaultedOptions.throwOnError,
|
|
query,
|
|
suspense: defaultedOptions.suspense
|
|
})) throw result.error;
|
|
return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/useQuery.js
|
|
function useQuery(options, queryClient) {
|
|
return useBaseQuery(options, QueryObserver, queryClient);
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/useSuspenseQuery.js
|
|
function useSuspenseQuery(options, queryClient) {
|
|
if (true) {
|
|
if (options.queryFn === skipToken) console.error("skipToken is not allowed for useSuspenseQuery");
|
|
}
|
|
return useBaseQuery({
|
|
...options,
|
|
enabled: true,
|
|
suspense: true,
|
|
throwOnError: defaultThrowOnError,
|
|
placeholderData: void 0
|
|
}, QueryObserver, queryClient);
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/useSuspenseInfiniteQuery.js
|
|
function useSuspenseInfiniteQuery(options, queryClient) {
|
|
if (true) {
|
|
if (options.queryFn === skipToken) console.error("skipToken is not allowed for useSuspenseInfiniteQuery");
|
|
}
|
|
return useBaseQuery({
|
|
...options,
|
|
enabled: true,
|
|
suspense: true,
|
|
throwOnError: defaultThrowOnError,
|
|
placeholderData: void 0
|
|
}, InfiniteQueryObserver, queryClient);
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/useSuspenseQueries.js
|
|
function useSuspenseQueries(options, queryClient) {
|
|
return useQueries({
|
|
...options,
|
|
queries: options.queries.map((query) => {
|
|
if (true) {
|
|
if (query.queryFn === skipToken) console.error("skipToken is not allowed for useSuspenseQueries");
|
|
}
|
|
return {
|
|
...query,
|
|
suspense: true,
|
|
throwOnError: defaultThrowOnError,
|
|
enabled: true,
|
|
placeholderData: void 0
|
|
};
|
|
})
|
|
}, queryClient);
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/usePrefetchQuery.js
|
|
function usePrefetchQuery(options, queryClient) {
|
|
const client = useQueryClient(queryClient);
|
|
if (!client.getQueryState(options.queryKey)) client.query(options).catch(noop);
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/usePrefetchInfiniteQuery.js
|
|
function usePrefetchInfiniteQuery(options, queryClient) {
|
|
const client = useQueryClient(queryClient);
|
|
if (!client.getQueryState(options.queryKey)) client.infiniteQuery(options).catch(noop);
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/queryOptions.js
|
|
function queryOptions(options) {
|
|
return options;
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/infiniteQueryOptions.js
|
|
function infiniteQueryOptions(options) {
|
|
return options;
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/useIsFetching.js
|
|
var React8 = __toESM(require_react(), 1);
|
|
function useIsFetching(filters, queryClient) {
|
|
const client = useQueryClient(queryClient);
|
|
const queryCache = client.getQueryCache();
|
|
return React8.useSyncExternalStore(React8.useCallback((onStoreChange) => queryCache.subscribe(notifyManager.batchCalls(onStoreChange)), [queryCache]), () => client.isFetching(filters), () => client.isFetching(filters));
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/useMutationState.js
|
|
var React9 = __toESM(require_react(), 1);
|
|
function useIsMutating(filters, queryClient) {
|
|
const client = useQueryClient(queryClient);
|
|
return useMutationState({ filters: {
|
|
...filters,
|
|
status: "pending"
|
|
} }, client).length;
|
|
}
|
|
function getResult(mutationCache, options) {
|
|
return mutationCache.findAll(options.filters).map((mutation) => options.select ? options.select(mutation) : mutation.state);
|
|
}
|
|
function useMutationState(options = {}, queryClient) {
|
|
const mutationCache = useQueryClient(queryClient).getMutationCache();
|
|
const optionsRef = React9.useRef(options);
|
|
const result = React9.useRef(null);
|
|
if (result.current === null) result.current = getResult(mutationCache, options);
|
|
React9.useEffect(() => {
|
|
optionsRef.current = options;
|
|
});
|
|
return React9.useSyncExternalStore(React9.useCallback((onStoreChange) => mutationCache.subscribe(() => {
|
|
const nextResult = replaceEqualDeep(result.current, getResult(mutationCache, optionsRef.current));
|
|
if (result.current !== nextResult) {
|
|
result.current = nextResult;
|
|
notifyManager.schedule(onStoreChange);
|
|
}
|
|
}), [mutationCache]), () => result.current, () => result.current);
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/useMutation.js
|
|
var React10 = __toESM(require_react(), 1);
|
|
function useMutation(options, queryClient) {
|
|
const client = useQueryClient(queryClient);
|
|
const [observer] = React10.useState(() => new MutationObserver(client, options));
|
|
React10.useEffect(() => {
|
|
observer.setOptions(options);
|
|
}, [observer, options]);
|
|
const result = React10.useSyncExternalStore(React10.useCallback((onStoreChange) => observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
|
|
const mutate = React10.useCallback((...args) => {
|
|
observer.mutate(args[0], args[1]).catch(noop);
|
|
}, [observer]);
|
|
if (result.error && shouldThrowError(observer.options.throwOnError, [result.error])) throw result.error;
|
|
return {
|
|
...result,
|
|
mutate,
|
|
mutateAsync: result.mutate
|
|
};
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/mutationOptions.js
|
|
function mutationOptions(options) {
|
|
return options;
|
|
}
|
|
|
|
// node_modules/@tanstack/react-query/build/modern/useInfiniteQuery.js
|
|
function useInfiniteQuery(options, queryClient) {
|
|
return useBaseQuery(options, InfiniteQueryObserver, queryClient);
|
|
}
|
|
export {
|
|
CancelledError,
|
|
HydrationBoundary,
|
|
InfiniteQueryObserver,
|
|
IsRestoringProvider,
|
|
Mutation,
|
|
MutationCache,
|
|
MutationObserver,
|
|
QueriesObserver,
|
|
Query,
|
|
QueryCache,
|
|
QueryClient,
|
|
QueryClientContext,
|
|
QueryClientProvider,
|
|
QueryErrorResetBoundary,
|
|
QueryObserver,
|
|
dataTagErrorSymbol,
|
|
dataTagSymbol,
|
|
defaultScheduler,
|
|
defaultShouldDehydrateMutation,
|
|
defaultShouldDehydrateQuery,
|
|
dehydrate,
|
|
dehydrateQuery,
|
|
environmentManager,
|
|
streamedQuery as experimental_streamedQuery,
|
|
focusManager,
|
|
hashKey,
|
|
hydrate,
|
|
infiniteQueryOptions,
|
|
isCancelledError,
|
|
isServer,
|
|
keepPreviousData,
|
|
matchMutation,
|
|
matchQuery,
|
|
mutationOptions,
|
|
noop,
|
|
notifyManager,
|
|
onlineManager,
|
|
partialMatchKey,
|
|
queryOptions,
|
|
replaceEqualDeep,
|
|
shouldThrowError,
|
|
skipToken,
|
|
timeoutManager,
|
|
unsetMarker,
|
|
useInfiniteQuery,
|
|
useIsFetching,
|
|
useIsMutating,
|
|
useIsRestoring,
|
|
useMutation,
|
|
useMutationState,
|
|
usePrefetchInfiniteQuery,
|
|
usePrefetchQuery,
|
|
useQueries,
|
|
useQuery,
|
|
useQueryClient,
|
|
useQueryErrorResetBoundary,
|
|
useSuspenseInfiniteQuery,
|
|
useSuspenseQueries,
|
|
useSuspenseQuery
|
|
};
|
|
//# sourceMappingURL=@tanstack_react-query.js.map
|