Server: Phase 2 (REVIEW not respected yet)

This commit is contained in:
Thomas Karner committed 2026-09-21 11:24:43 +02:00
1 parent 5d16ded553
commit 142b47674d
4271 files changed
+1203269

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-present Tanner Linsley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+479
View File
@@ -0,0 +1,479 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/index.ts
var stateIndexKey = "__TSR_index";
var popStateEvent = "popstate";
var beforeUnloadEvent = "beforeunload";
/**
* Turn protocol-relative inputs such as "//evil.example" into paths
* such as "/evil.example", keeping navigation on the current origin.
*
* For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,
* removes tabs/newlines, and treats backslashes as slashes, so inputs like
* "/\evil.example" also need normalization. This only allocates when those
* rules would make the input protocol-relative.
*/
var protocolRelativePrefix = /^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/;
function normalizeProtocolRelative(url) {
const match = protocolRelativePrefix.exec(url);
return match ? "/" + url.slice(match[0].length) : url;
}
function normalizeHref(href) {
if (/[\x00-\x1f\x7f]/.test(href)) href = href.replace(/[\x00-\x1f\x7f]/g, (character) => " \n\r".includes(character) ? "" : encodeURIComponent(character));
return normalizeProtocolRelative(href);
}
function createHistory(opts) {
let location = opts.getLocation();
const subscribers = /* @__PURE__ */ new Set();
const notify = (action) => {
location = opts.getLocation();
subscribers.forEach((subscriber) => subscriber({
location,
action
}));
};
const handleIndexChange = (action) => {
if (opts.notifyOnIndexChange ?? true) notify(action);
else location = opts.getLocation();
};
const tryNavigation = async ({ task, navigateOpts, ...actionInfo }) => {
if (navigateOpts?.ignoreBlocker ?? false) {
task();
return;
}
const blockers = opts.getBlockers?.() ?? [];
const isPushOrReplace = actionInfo.type === "PUSH" || actionInfo.type === "REPLACE";
if (typeof document !== "undefined" && blockers.length && isPushOrReplace) for (const blocker of blockers) {
const nextLocation = parseHref(actionInfo.path, actionInfo.state);
if (await blocker.blockerFn({
currentLocation: location,
nextLocation,
action: actionInfo.type
})) {
opts.onBlocked?.();
return;
}
}
task();
};
return {
get location() {
return location;
},
get length() {
return opts.getLength();
},
subscribers,
subscribe: (cb) => {
subscribers.add(cb);
return () => {
subscribers.delete(cb);
};
},
push: (path, state, navigateOpts) => {
const currentIndex = location.state[stateIndexKey];
state = assignKeyAndIndex(currentIndex + 1, state);
tryNavigation({
task: () => {
opts.pushState(path, state);
notify({ type: "PUSH" });
},
navigateOpts,
type: "PUSH",
path,
state
});
},
replace: (path, state, navigateOpts) => {
const currentIndex = location.state[stateIndexKey];
state = assignKeyAndIndex(currentIndex, state);
tryNavigation({
task: () => {
opts.replaceState(path, state);
notify({ type: "REPLACE" });
},
navigateOpts,
type: "REPLACE",
path,
state
});
},
go: (index, navigateOpts) => {
tryNavigation({
task: () => {
opts.go(index, navigateOpts?.ignoreBlocker ?? false);
handleIndexChange({
type: "GO",
index
});
},
navigateOpts,
type: "GO"
});
},
back: (navigateOpts) => {
tryNavigation({
task: () => {
opts.back(navigateOpts?.ignoreBlocker ?? false);
handleIndexChange({ type: "BACK" });
},
navigateOpts,
type: "BACK"
});
},
forward: (navigateOpts) => {
tryNavigation({
task: () => {
opts.forward(navigateOpts?.ignoreBlocker ?? false);
handleIndexChange({ type: "FORWARD" });
},
navigateOpts,
type: "FORWARD"
});
},
canGoBack: () => location.state[stateIndexKey] !== 0,
createHref: (str) => opts.createHref(str),
block: (blocker) => {
if (!opts.setBlockers) return () => {};
const blockers = opts.getBlockers?.() ?? [];
opts.setBlockers([...blockers, blocker]);
return () => {
const blockers = opts.getBlockers?.() ?? [];
opts.setBlockers?.(blockers.filter((b) => b !== blocker));
};
},
flush: () => opts.flush?.(),
destroy: () => opts.destroy?.(),
notify,
_getBlockers: () => opts.getBlockers?.() ?? []
};
}
function assignKeyAndIndex(index, state) {
const key = createRandomKey();
return {
...state,
key,
__TSR_key: key,
[stateIndexKey]: index
};
}
/**
* Creates a history object that can be used to interact with the browser's
* navigation. This is a lightweight API wrapping the browser's native methods.
* It is designed to work with TanStack Router, but could be used as a standalone API as well.
* IMPORTANT: This API implements history throttling via a microtask to prevent
* excessive calls to the history API. In some browsers, calling history.pushState or
* history.replaceState in quick succession can cause the browser to ignore subsequent
* calls. This API smooths out those differences and ensures that your application
* state will *eventually* match the browser state. In most cases, this is not a problem,
* but if you need to ensure that the browser state is up to date, you can use the
* `history.flush` method to immediately flush all pending state changes to the browser URL.
* @param opts
* @param opts.getHref A function that returns the current href (path + search + hash)
* @param opts.createHref A function that takes a path and returns a href (path + search + hash)
* @returns A history instance
*/
function createBrowserHistory(opts) {
const win = opts?.window ?? (typeof document !== "undefined" ? window : void 0);
const originalPushState = win.history.pushState;
const originalReplaceState = win.history.replaceState;
let blockers = [];
const _getBlockers = () => blockers;
const _setBlockers = (newBlockers) => blockers = newBlockers;
const createHref = (path) => normalizeHref(opts?.createHref ? opts.createHref(path) : path);
const parseLocation = opts?.parseLocation ?? (() => parseHref(`${win.location.pathname}${win.location.search}${win.location.hash}`, win.history.state));
if (!win.history.state?.__TSR_key && !win.history.state?.key) {
const addedKey = createRandomKey();
win.history.replaceState({
[stateIndexKey]: 0,
key: addedKey,
__TSR_key: addedKey
}, "");
}
let currentLocation = parseLocation();
let rollbackLocation;
let nextPopIsGo = false;
let ignoreNextPop = false;
let skipBlockerNextPop = false;
let ignoreNextBeforeUnload = false;
const getLocation = () => currentLocation;
let next;
const flush = () => {
if (!next) return;
history._ignoreSubscribers = true;
(next[2] ? win.history.pushState : win.history.replaceState)(next[1], "", next[0]);
history._ignoreSubscribers = false;
next = void 0;
rollbackLocation = void 0;
};
const queueHistoryAction = (isPush, destHref, state) => {
const href = opts?.createHref ? createHref(destHref) : void 0;
const hasPendingAction = !!next;
if (!hasPendingAction) rollbackLocation = currentLocation;
currentLocation = parseHref(destHref, state);
next = [
href ?? currentLocation.href,
state,
next?.[2] || isPush
];
if (!hasPendingAction) queueMicrotask(() => flush());
};
const onPushPop = (type) => {
currentLocation = parseLocation();
history.notify({ type });
};
const onPushPopEvent = async () => {
ignoreNextBeforeUnload = false;
if (ignoreNextPop) {
ignoreNextPop = false;
return;
}
const nextLocation = parseLocation();
const delta = nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey];
const isForward = delta === 1;
const isBack = delta === -1;
const isGo = !isForward && !isBack || nextPopIsGo;
nextPopIsGo = false;
const action = isGo ? "GO" : isBack ? "BACK" : "FORWARD";
const notify = isGo ? {
type: "GO",
index: delta
} : { type: isBack ? "BACK" : "FORWARD" };
if (skipBlockerNextPop) skipBlockerNextPop = false;
else {
const blockers = _getBlockers();
if (typeof document !== "undefined" && blockers.length) {
for (const blocker of blockers) if (await blocker.blockerFn({
currentLocation,
nextLocation,
action
})) {
ignoreNextPop = true;
win.history.go(-delta);
history.notify(notify);
return;
}
}
}
currentLocation = parseLocation();
history.notify(notify);
};
const onBeforeUnload = (e) => {
if (ignoreNextBeforeUnload) {
ignoreNextBeforeUnload = false;
return;
}
let shouldBlock = false;
const blockers = _getBlockers();
if (typeof document !== "undefined" && blockers.length) for (const blocker of blockers) {
const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true;
if (shouldHaveBeforeUnload === true) {
shouldBlock = true;
break;
}
if (typeof shouldHaveBeforeUnload === "function" && shouldHaveBeforeUnload() === true) {
shouldBlock = true;
break;
}
}
if (shouldBlock) {
e.preventDefault();
return e.returnValue = "";
}
};
const history = createHistory({
getLocation,
getLength: () => win.history.length,
pushState: (href, state) => queueHistoryAction(true, href, state),
replaceState: (href, state) => queueHistoryAction(false, href, state),
back: (ignoreBlocker) => {
if (ignoreBlocker) {
skipBlockerNextPop = true;
ignoreNextBeforeUnload = true;
}
return win.history.back();
},
forward: (ignoreBlocker) => {
if (ignoreBlocker) {
skipBlockerNextPop = true;
ignoreNextBeforeUnload = true;
}
win.history.forward();
},
go: (n, ignoreBlocker) => {
nextPopIsGo = true;
if (ignoreBlocker) {
skipBlockerNextPop = true;
ignoreNextBeforeUnload = true;
}
win.history.go(n);
},
createHref: (href) => createHref(href),
flush,
destroy: () => {
win.history.pushState = originalPushState;
win.history.replaceState = originalReplaceState;
win.removeEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
win.removeEventListener(popStateEvent, onPushPopEvent);
},
onBlocked: () => {
if (rollbackLocation && currentLocation !== rollbackLocation) currentLocation = rollbackLocation;
},
getBlockers: _getBlockers,
setBlockers: _setBlockers,
notifyOnIndexChange: false
});
history._ignoreNextBeforeUnload = (href) => {
ignoreNextBeforeUnload = false;
try {
href = new URL(href, win.document.baseURI).href;
ignoreNextBeforeUnload = /^https?:/.test(href) && (!href.includes("#") || href.split("#")[0] !== win.location.href.split("#")[0]);
} catch {}
};
win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
win.addEventListener(popStateEvent, onPushPopEvent);
win.history.pushState = function(...args) {
const res = originalPushState.apply(win.history, args);
if (!history._ignoreSubscribers) onPushPop("PUSH");
return res;
};
win.history.replaceState = function(...args) {
const res = originalReplaceState.apply(win.history, args);
if (!history._ignoreSubscribers) onPushPop("REPLACE");
return res;
};
return history;
}
/**
* Create a hash-based history implementation.
* Useful for static hosts or environments without server URL rewriting.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
*/
function createHashHistory(opts) {
const win = opts?.window ?? (typeof document !== "undefined" ? window : void 0);
return createBrowserHistory({
window: win,
parseLocation: () => {
const hashSplit = win.location.hash.split("#").slice(1);
const pathPart = hashSplit[0] ?? "/";
const searchPart = win.location.search;
const hashEntries = hashSplit.slice(1);
return parseHref(`${pathPart}${searchPart}${hashEntries.length === 0 ? "" : `#${hashEntries.join("#")}`}`, win.history.state);
},
createHref: (href) => `${win.location.pathname}${win.location.search}#${href}`
});
}
/**
* Create an in-memory history implementation.
* Ideal for server rendering, tests, and non-DOM environments.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
*/
function createMemoryHistory(opts = { initialEntries: ["/"] }) {
const entries = opts.initialEntries;
let index = opts.initialIndex ? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1) : entries.length - 1;
const states = entries.map((_entry, index) => assignKeyAndIndex(index, void 0));
const getLocation = () => parseHref(entries[index], states[index]);
let blockers = [];
const _getBlockers = () => blockers;
const _setBlockers = (newBlockers) => blockers = newBlockers;
return createHistory({
getLocation,
getLength: () => entries.length,
pushState: (path, state) => {
index = index < entries.length - 1 ? index + 1 : entries.length;
states[index] = state;
entries[index] = path;
if (index < entries.length - 1) {
entries.length = index + 1;
states.length = index + 1;
}
},
replaceState: (path, state) => {
states[index] = state;
entries[index] = path;
},
back: () => {
index = Math.max(index - 1, 0);
},
forward: () => {
index = Math.min(index + 1, entries.length - 1);
},
go: (n) => {
index = Math.min(Math.max(index + n, 0), entries.length - 1);
},
createHref: normalizeHref,
getBlockers: _getBlockers,
setBlockers: _setBlockers
});
}
var noop = () => {};
var ServerHistory = class {
constructor(location) {
this.location = location;
}
get length() {
return 1;
}
get subscribers() {
return this._subscribers ??= /* @__PURE__ */ new Set();
}
subscribe() {
return noop;
}
push() {}
replace() {}
go() {}
back() {}
forward() {}
canGoBack() {
return false;
}
createHref(href) {
return normalizeHref(href);
}
block() {
return noop;
}
flush() {}
destroy() {}
notify() {}
_getBlockers() {
return [];
}
};
/** A fixed request location; server navigation is a no-op. */
function createServerHistory(href) {
return new ServerHistory(parseHref(href, void 0));
}
function parseHref(href, state) {
const sanitizedHref = normalizeHref(href);
const hashIndex = sanitizedHref.indexOf("#");
const searchIndex = sanitizedHref.indexOf("?");
if (!state) {
const key = createRandomKey();
state = {
[stateIndexKey]: 0,
key,
__TSR_key: key
};
}
return {
href: sanitizedHref,
pathname: sanitizedHref.substring(0, hashIndex > 0 ? searchIndex > 0 ? Math.min(hashIndex, searchIndex) : hashIndex : searchIndex > 0 ? searchIndex : sanitizedHref.length),
hash: hashIndex > -1 ? sanitizedHref.substring(hashIndex) : "",
search: searchIndex > -1 ? sanitizedHref.slice(searchIndex, hashIndex === -1 ? void 0 : hashIndex) : "",
state
};
}
function createRandomKey() {
return (Math.random() + 1).toString(36).substring(7);
}
//#endregion
exports.createBrowserHistory = createBrowserHistory;
exports.createHashHistory = createHashHistory;
exports.createHistory = createHistory;
exports.createMemoryHistory = createMemoryHistory;
exports.createServerHistory = createServerHistory;
exports.normalizeProtocolRelative = normalizeProtocolRelative;
exports.parseHref = parseHref;
//# sourceMappingURL=index.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["// While the public API was clearly inspired by the \"history\" npm package,\n// This implementation attempts to be more lightweight by\n// making assumptions about the way TanStack Router works\n\nexport interface NavigateOptions {\n ignoreBlocker?: boolean\n}\n\ntype SubscriberHistoryAction =\n | {\n type: Exclude<HistoryAction, 'GO'>\n }\n | {\n type: 'GO'\n index: number\n }\n\ntype SubscriberArgs = {\n location: HistoryLocation\n action: SubscriberHistoryAction\n}\n\nexport interface RouterHistory {\n location: HistoryLocation\n length: number\n subscribers: Set<(opts: SubscriberArgs) => void>\n subscribe: (cb: (opts: SubscriberArgs) => void) => () => void\n push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void\n replace: (path: string, state?: any, navigateOpts?: NavigateOptions) => void\n go: (index: number, navigateOpts?: NavigateOptions) => void\n back: (navigateOpts?: NavigateOptions) => void\n forward: (navigateOpts?: NavigateOptions) => void\n canGoBack: () => boolean\n createHref: (href: string) => string\n block: (blocker: NavigationBlocker) => () => void\n flush: () => void\n destroy: () => void\n notify: (action: SubscriberHistoryAction) => void\n _getBlockers: () => Array<NavigationBlocker>\n _ignoreSubscribers?: boolean\n _ignoreNextBeforeUnload?: (href: string) => void\n}\n\nexport interface HistoryLocation extends ParsedPath {\n state: ParsedHistoryState\n}\n\nexport interface ParsedPath {\n href: string\n pathname: string\n search: string\n hash: string\n}\n\nexport interface HistoryState {}\n\nexport type ParsedHistoryState = HistoryState & {\n key?: string // TODO: Remove in v2 - use __TSR_key instead\n __TSR_key?: string\n __TSR_index: number\n}\n\ntype ShouldAllowNavigation = any\n\nexport type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO'\n\nexport type BlockerFnArgs = {\n currentLocation: HistoryLocation\n nextLocation: HistoryLocation\n action: HistoryAction\n}\n\nexport type BlockerFn = (\n args: BlockerFnArgs,\n) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation\n\nexport type NavigationBlocker = {\n blockerFn: BlockerFn\n enableBeforeUnload?: (() => boolean) | boolean\n}\n\ntype TryNavigateArgs = {\n task: () => void\n type: 'PUSH' | 'REPLACE' | 'BACK' | 'FORWARD' | 'GO'\n navigateOpts?: NavigateOptions\n} & (\n | {\n type: 'PUSH' | 'REPLACE'\n path: string\n state: any\n }\n | {\n type: 'BACK' | 'FORWARD' | 'GO'\n }\n)\n\nconst stateIndexKey = '__TSR_index'\nconst popStateEvent = 'popstate'\nconst beforeUnloadEvent = 'beforeunload'\n\n/**\n * Turn protocol-relative inputs such as \"//evil.example\" into paths\n * such as \"/evil.example\", keeping navigation on the current origin.\n *\n * For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,\n * removes tabs/newlines, and treats backslashes as slashes, so inputs like\n * \"/\\evil.example\" also need normalization. This only allocates when those\n * rules would make the input protocol-relative.\n */\n// eslint-disable-next-line no-control-regex\nconst protocolRelativePrefix = /^[\\x00-\\x20]*(?:[\\\\/][\\t\\n\\r]*){2,}/\n\nexport function normalizeProtocolRelative(url: string): string {\n const match = protocolRelativePrefix.exec(url)\n return match ? '/' + url.slice(match[0].length) : url\n}\n\nfunction normalizeHref(href: string): string {\n // eslint-disable-next-line no-control-regex\n if (/[\\x00-\\x1f\\x7f]/.test(href)) {\n // eslint-disable-next-line no-control-regex\n href = href.replace(/[\\x00-\\x1f\\x7f]/g, (character) =>\n '\\t\\n\\r'.includes(character) ? '' : encodeURIComponent(character),\n )\n }\n return normalizeProtocolRelative(href)\n}\n\nexport function createHistory(opts: {\n getLocation: () => HistoryLocation\n getLength: () => number\n pushState: (path: string, state: any) => void\n replaceState: (path: string, state: any) => void\n go: (n: number, ignoreBlocker: boolean) => void\n back: (ignoreBlocker: boolean) => void\n forward: (ignoreBlocker: boolean) => void\n createHref: (path: string) => string\n flush?: () => void\n destroy?: () => void\n onBlocked?: () => void\n getBlockers?: () => Array<NavigationBlocker>\n setBlockers?: (blockers: Array<NavigationBlocker>) => void\n // Avoid notifying on forward/back/go, used for browser history as we already get notified by the popstate event\n notifyOnIndexChange?: boolean\n}): RouterHistory {\n let location = opts.getLocation()\n const subscribers = new Set<(opts: SubscriberArgs) => void>()\n\n const notify = (action: SubscriberHistoryAction) => {\n location = opts.getLocation()\n subscribers.forEach((subscriber) => subscriber({ location, action }))\n }\n\n const handleIndexChange = (action: SubscriberHistoryAction) => {\n if (opts.notifyOnIndexChange ?? true) notLine truncated
+120
View File
@@ -0,0 +1,120 @@
export interface NavigateOptions {
ignoreBlocker?: boolean;
}
type SubscriberHistoryAction = {
type: Exclude<HistoryAction, 'GO'>;
} | {
type: 'GO';
index: number;
};
type SubscriberArgs = {
location: HistoryLocation;
action: SubscriberHistoryAction;
};
export interface RouterHistory {
location: HistoryLocation;
length: number;
subscribers: Set<(opts: SubscriberArgs) => void>;
subscribe: (cb: (opts: SubscriberArgs) => void) => () => void;
push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void;
replace: (path: string, state?: any, navigateOpts?: NavigateOptions) => void;
go: (index: number, navigateOpts?: NavigateOptions) => void;
back: (navigateOpts?: NavigateOptions) => void;
forward: (navigateOpts?: NavigateOptions) => void;
canGoBack: () => boolean;
createHref: (href: string) => string;
block: (blocker: NavigationBlocker) => () => void;
flush: () => void;
destroy: () => void;
notify: (action: SubscriberHistoryAction) => void;
_getBlockers: () => Array<NavigationBlocker>;
_ignoreSubscribers?: boolean;
_ignoreNextBeforeUnload?: (href: string) => void;
}
export interface HistoryLocation extends ParsedPath {
state: ParsedHistoryState;
}
export interface ParsedPath {
href: string;
pathname: string;
search: string;
hash: string;
}
export interface HistoryState {
}
export type ParsedHistoryState = HistoryState & {
key?: string;
__TSR_key?: string;
__TSR_index: number;
};
type ShouldAllowNavigation = any;
export type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO';
export type BlockerFnArgs = {
currentLocation: HistoryLocation;
nextLocation: HistoryLocation;
action: HistoryAction;
};
export type BlockerFn = (args: BlockerFnArgs) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation;
export type NavigationBlocker = {
blockerFn: BlockerFn;
enableBeforeUnload?: (() => boolean) | boolean;
};
export declare function normalizeProtocolRelative(url: string): string;
export declare function createHistory(opts: {
getLocation: () => HistoryLocation;
getLength: () => number;
pushState: (path: string, state: any) => void;
replaceState: (path: string, state: any) => void;
go: (n: number, ignoreBlocker: boolean) => void;
back: (ignoreBlocker: boolean) => void;
forward: (ignoreBlocker: boolean) => void;
createHref: (path: string) => string;
flush?: () => void;
destroy?: () => void;
onBlocked?: () => void;
getBlockers?: () => Array<NavigationBlocker>;
setBlockers?: (blockers: Array<NavigationBlocker>) => void;
notifyOnIndexChange?: boolean;
}): RouterHistory;
/**
* Creates a history object that can be used to interact with the browser's
* navigation. This is a lightweight API wrapping the browser's native methods.
* It is designed to work with TanStack Router, but could be used as a standalone API as well.
* IMPORTANT: This API implements history throttling via a microtask to prevent
* excessive calls to the history API. In some browsers, calling history.pushState or
* history.replaceState in quick succession can cause the browser to ignore subsequent
* calls. This API smooths out those differences and ensures that your application
* state will *eventually* match the browser state. In most cases, this is not a problem,
* but if you need to ensure that the browser state is up to date, you can use the
* `history.flush` method to immediately flush all pending state changes to the browser URL.
* @param opts
* @param opts.getHref A function that returns the current href (path + search + hash)
* @param opts.createHref A function that takes a path and returns a href (path + search + hash)
* @returns A history instance
*/
export declare function createBrowserHistory(opts?: {
parseLocation?: () => HistoryLocation;
createHref?: (path: string) => string;
window?: any;
}): RouterHistory;
/**
* Create a hash-based history implementation.
* Useful for static hosts or environments without server URL rewriting.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
*/
export declare function createHashHistory(opts?: {
window?: any;
}): RouterHistory;
/**
* Create an in-memory history implementation.
* Ideal for server rendering, tests, and non-DOM environments.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
*/
export declare function createMemoryHistory(opts?: {
initialEntries: Array<string>;
initialIndex?: number;
}): RouterHistory;
/** A fixed request location; server navigation is a no-op. */
export declare function createServerHistory(href: string): RouterHistory;
export declare function parseHref(href: string, state: ParsedHistoryState | undefined): HistoryLocation;
export {};
+120
View File
@@ -0,0 +1,120 @@
export interface NavigateOptions {
ignoreBlocker?: boolean;
}
type SubscriberHistoryAction = {
type: Exclude<HistoryAction, 'GO'>;
} | {
type: 'GO';
index: number;
};
type SubscriberArgs = {
location: HistoryLocation;
action: SubscriberHistoryAction;
};
export interface RouterHistory {
location: HistoryLocation;
length: number;
subscribers: Set<(opts: SubscriberArgs) => void>;
subscribe: (cb: (opts: SubscriberArgs) => void) => () => void;
push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void;
replace: (path: string, state?: any, navigateOpts?: NavigateOptions) => void;
go: (index: number, navigateOpts?: NavigateOptions) => void;
back: (navigateOpts?: NavigateOptions) => void;
forward: (navigateOpts?: NavigateOptions) => void;
canGoBack: () => boolean;
createHref: (href: string) => string;
block: (blocker: NavigationBlocker) => () => void;
flush: () => void;
destroy: () => void;
notify: (action: SubscriberHistoryAction) => void;
_getBlockers: () => Array<NavigationBlocker>;
_ignoreSubscribers?: boolean;
_ignoreNextBeforeUnload?: (href: string) => void;
}
export interface HistoryLocation extends ParsedPath {
state: ParsedHistoryState;
}
export interface ParsedPath {
href: string;
pathname: string;
search: string;
hash: string;
}
export interface HistoryState {
}
export type ParsedHistoryState = HistoryState & {
key?: string;
__TSR_key?: string;
__TSR_index: number;
};
type ShouldAllowNavigation = any;
export type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO';
export type BlockerFnArgs = {
currentLocation: HistoryLocation;
nextLocation: HistoryLocation;
action: HistoryAction;
};
export type BlockerFn = (args: BlockerFnArgs) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation;
export type NavigationBlocker = {
blockerFn: BlockerFn;
enableBeforeUnload?: (() => boolean) | boolean;
};
export declare function normalizeProtocolRelative(url: string): string;
export declare function createHistory(opts: {
getLocation: () => HistoryLocation;
getLength: () => number;
pushState: (path: string, state: any) => void;
replaceState: (path: string, state: any) => void;
go: (n: number, ignoreBlocker: boolean) => void;
back: (ignoreBlocker: boolean) => void;
forward: (ignoreBlocker: boolean) => void;
createHref: (path: string) => string;
flush?: () => void;
destroy?: () => void;
onBlocked?: () => void;
getBlockers?: () => Array<NavigationBlocker>;
setBlockers?: (blockers: Array<NavigationBlocker>) => void;
notifyOnIndexChange?: boolean;
}): RouterHistory;
/**
* Creates a history object that can be used to interact with the browser's
* navigation. This is a lightweight API wrapping the browser's native methods.
* It is designed to work with TanStack Router, but could be used as a standalone API as well.
* IMPORTANT: This API implements history throttling via a microtask to prevent
* excessive calls to the history API. In some browsers, calling history.pushState or
* history.replaceState in quick succession can cause the browser to ignore subsequent
* calls. This API smooths out those differences and ensures that your application
* state will *eventually* match the browser state. In most cases, this is not a problem,
* but if you need to ensure that the browser state is up to date, you can use the
* `history.flush` method to immediately flush all pending state changes to the browser URL.
* @param opts
* @param opts.getHref A function that returns the current href (path + search + hash)
* @param opts.createHref A function that takes a path and returns a href (path + search + hash)
* @returns A history instance
*/
export declare function createBrowserHistory(opts?: {
parseLocation?: () => HistoryLocation;
createHref?: (path: string) => string;
window?: any;
}): RouterHistory;
/**
* Create a hash-based history implementation.
* Useful for static hosts or environments without server URL rewriting.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
*/
export declare function createHashHistory(opts?: {
window?: any;
}): RouterHistory;
/**
* Create an in-memory history implementation.
* Ideal for server rendering, tests, and non-DOM environments.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
*/
export declare function createMemoryHistory(opts?: {
initialEntries: Array<string>;
initialIndex?: number;
}): RouterHistory;
/** A fixed request location; server navigation is a no-op. */
export declare function createServerHistory(href: string): RouterHistory;
export declare function parseHref(href: string, state: ParsedHistoryState | undefined): HistoryLocation;
export {};
+472
View File
@@ -0,0 +1,472 @@
//#region src/index.ts
var stateIndexKey = "__TSR_index";
var popStateEvent = "popstate";
var beforeUnloadEvent = "beforeunload";
/**
* Turn protocol-relative inputs such as "//evil.example" into paths
* such as "/evil.example", keeping navigation on the current origin.
*
* For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,
* removes tabs/newlines, and treats backslashes as slashes, so inputs like
* "/\evil.example" also need normalization. This only allocates when those
* rules would make the input protocol-relative.
*/
var protocolRelativePrefix = /^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/;
function normalizeProtocolRelative(url) {
const match = protocolRelativePrefix.exec(url);
return match ? "/" + url.slice(match[0].length) : url;
}
function normalizeHref(href) {
if (/[\x00-\x1f\x7f]/.test(href)) href = href.replace(/[\x00-\x1f\x7f]/g, (character) => " \n\r".includes(character) ? "" : encodeURIComponent(character));
return normalizeProtocolRelative(href);
}
function createHistory(opts) {
let location = opts.getLocation();
const subscribers = /* @__PURE__ */ new Set();
const notify = (action) => {
location = opts.getLocation();
subscribers.forEach((subscriber) => subscriber({
location,
action
}));
};
const handleIndexChange = (action) => {
if (opts.notifyOnIndexChange ?? true) notify(action);
else location = opts.getLocation();
};
const tryNavigation = async ({ task, navigateOpts, ...actionInfo }) => {
if (navigateOpts?.ignoreBlocker ?? false) {
task();
return;
}
const blockers = opts.getBlockers?.() ?? [];
const isPushOrReplace = actionInfo.type === "PUSH" || actionInfo.type === "REPLACE";
if (typeof document !== "undefined" && blockers.length && isPushOrReplace) for (const blocker of blockers) {
const nextLocation = parseHref(actionInfo.path, actionInfo.state);
if (await blocker.blockerFn({
currentLocation: location,
nextLocation,
action: actionInfo.type
})) {
opts.onBlocked?.();
return;
}
}
task();
};
return {
get location() {
return location;
},
get length() {
return opts.getLength();
},
subscribers,
subscribe: (cb) => {
subscribers.add(cb);
return () => {
subscribers.delete(cb);
};
},
push: (path, state, navigateOpts) => {
const currentIndex = location.state[stateIndexKey];
state = assignKeyAndIndex(currentIndex + 1, state);
tryNavigation({
task: () => {
opts.pushState(path, state);
notify({ type: "PUSH" });
},
navigateOpts,
type: "PUSH",
path,
state
});
},
replace: (path, state, navigateOpts) => {
const currentIndex = location.state[stateIndexKey];
state = assignKeyAndIndex(currentIndex, state);
tryNavigation({
task: () => {
opts.replaceState(path, state);
notify({ type: "REPLACE" });
},
navigateOpts,
type: "REPLACE",
path,
state
});
},
go: (index, navigateOpts) => {
tryNavigation({
task: () => {
opts.go(index, navigateOpts?.ignoreBlocker ?? false);
handleIndexChange({
type: "GO",
index
});
},
navigateOpts,
type: "GO"
});
},
back: (navigateOpts) => {
tryNavigation({
task: () => {
opts.back(navigateOpts?.ignoreBlocker ?? false);
handleIndexChange({ type: "BACK" });
},
navigateOpts,
type: "BACK"
});
},
forward: (navigateOpts) => {
tryNavigation({
task: () => {
opts.forward(navigateOpts?.ignoreBlocker ?? false);
handleIndexChange({ type: "FORWARD" });
},
navigateOpts,
type: "FORWARD"
});
},
canGoBack: () => location.state[stateIndexKey] !== 0,
createHref: (str) => opts.createHref(str),
block: (blocker) => {
if (!opts.setBlockers) return () => {};
const blockers = opts.getBlockers?.() ?? [];
opts.setBlockers([...blockers, blocker]);
return () => {
const blockers = opts.getBlockers?.() ?? [];
opts.setBlockers?.(blockers.filter((b) => b !== blocker));
};
},
flush: () => opts.flush?.(),
destroy: () => opts.destroy?.(),
notify,
_getBlockers: () => opts.getBlockers?.() ?? []
};
}
function assignKeyAndIndex(index, state) {
const key = createRandomKey();
return {
...state,
key,
__TSR_key: key,
[stateIndexKey]: index
};
}
/**
* Creates a history object that can be used to interact with the browser's
* navigation. This is a lightweight API wrapping the browser's native methods.
* It is designed to work with TanStack Router, but could be used as a standalone API as well.
* IMPORTANT: This API implements history throttling via a microtask to prevent
* excessive calls to the history API. In some browsers, calling history.pushState or
* history.replaceState in quick succession can cause the browser to ignore subsequent
* calls. This API smooths out those differences and ensures that your application
* state will *eventually* match the browser state. In most cases, this is not a problem,
* but if you need to ensure that the browser state is up to date, you can use the
* `history.flush` method to immediately flush all pending state changes to the browser URL.
* @param opts
* @param opts.getHref A function that returns the current href (path + search + hash)
* @param opts.createHref A function that takes a path and returns a href (path + search + hash)
* @returns A history instance
*/
function createBrowserHistory(opts) {
const win = opts?.window ?? (typeof document !== "undefined" ? window : void 0);
const originalPushState = win.history.pushState;
const originalReplaceState = win.history.replaceState;
let blockers = [];
const _getBlockers = () => blockers;
const _setBlockers = (newBlockers) => blockers = newBlockers;
const createHref = (path) => normalizeHref(opts?.createHref ? opts.createHref(path) : path);
const parseLocation = opts?.parseLocation ?? (() => parseHref(`${win.location.pathname}${win.location.search}${win.location.hash}`, win.history.state));
if (!win.history.state?.__TSR_key && !win.history.state?.key) {
const addedKey = createRandomKey();
win.history.replaceState({
[stateIndexKey]: 0,
key: addedKey,
__TSR_key: addedKey
}, "");
}
let currentLocation = parseLocation();
let rollbackLocation;
let nextPopIsGo = false;
let ignoreNextPop = false;
let skipBlockerNextPop = false;
let ignoreNextBeforeUnload = false;
const getLocation = () => currentLocation;
let next;
const flush = () => {
if (!next) return;
history._ignoreSubscribers = true;
(next[2] ? win.history.pushState : win.history.replaceState)(next[1], "", next[0]);
history._ignoreSubscribers = false;
next = void 0;
rollbackLocation = void 0;
};
const queueHistoryAction = (isPush, destHref, state) => {
const href = opts?.createHref ? createHref(destHref) : void 0;
const hasPendingAction = !!next;
if (!hasPendingAction) rollbackLocation = currentLocation;
currentLocation = parseHref(destHref, state);
next = [
href ?? currentLocation.href,
state,
next?.[2] || isPush
];
if (!hasPendingAction) queueMicrotask(() => flush());
};
const onPushPop = (type) => {
currentLocation = parseLocation();
history.notify({ type });
};
const onPushPopEvent = async () => {
ignoreNextBeforeUnload = false;
if (ignoreNextPop) {
ignoreNextPop = false;
return;
}
const nextLocation = parseLocation();
const delta = nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey];
const isForward = delta === 1;
const isBack = delta === -1;
const isGo = !isForward && !isBack || nextPopIsGo;
nextPopIsGo = false;
const action = isGo ? "GO" : isBack ? "BACK" : "FORWARD";
const notify = isGo ? {
type: "GO",
index: delta
} : { type: isBack ? "BACK" : "FORWARD" };
if (skipBlockerNextPop) skipBlockerNextPop = false;
else {
const blockers = _getBlockers();
if (typeof document !== "undefined" && blockers.length) {
for (const blocker of blockers) if (await blocker.blockerFn({
currentLocation,
nextLocation,
action
})) {
ignoreNextPop = true;
win.history.go(-delta);
history.notify(notify);
return;
}
}
}
currentLocation = parseLocation();
history.notify(notify);
};
const onBeforeUnload = (e) => {
if (ignoreNextBeforeUnload) {
ignoreNextBeforeUnload = false;
return;
}
let shouldBlock = false;
const blockers = _getBlockers();
if (typeof document !== "undefined" && blockers.length) for (const blocker of blockers) {
const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true;
if (shouldHaveBeforeUnload === true) {
shouldBlock = true;
break;
}
if (typeof shouldHaveBeforeUnload === "function" && shouldHaveBeforeUnload() === true) {
shouldBlock = true;
break;
}
}
if (shouldBlock) {
e.preventDefault();
return e.returnValue = "";
}
};
const history = createHistory({
getLocation,
getLength: () => win.history.length,
pushState: (href, state) => queueHistoryAction(true, href, state),
replaceState: (href, state) => queueHistoryAction(false, href, state),
back: (ignoreBlocker) => {
if (ignoreBlocker) {
skipBlockerNextPop = true;
ignoreNextBeforeUnload = true;
}
return win.history.back();
},
forward: (ignoreBlocker) => {
if (ignoreBlocker) {
skipBlockerNextPop = true;
ignoreNextBeforeUnload = true;
}
win.history.forward();
},
go: (n, ignoreBlocker) => {
nextPopIsGo = true;
if (ignoreBlocker) {
skipBlockerNextPop = true;
ignoreNextBeforeUnload = true;
}
win.history.go(n);
},
createHref: (href) => createHref(href),
flush,
destroy: () => {
win.history.pushState = originalPushState;
win.history.replaceState = originalReplaceState;
win.removeEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
win.removeEventListener(popStateEvent, onPushPopEvent);
},
onBlocked: () => {
if (rollbackLocation && currentLocation !== rollbackLocation) currentLocation = rollbackLocation;
},
getBlockers: _getBlockers,
setBlockers: _setBlockers,
notifyOnIndexChange: false
});
history._ignoreNextBeforeUnload = (href) => {
ignoreNextBeforeUnload = false;
try {
href = new URL(href, win.document.baseURI).href;
ignoreNextBeforeUnload = /^https?:/.test(href) && (!href.includes("#") || href.split("#")[0] !== win.location.href.split("#")[0]);
} catch {}
};
win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
win.addEventListener(popStateEvent, onPushPopEvent);
win.history.pushState = function(...args) {
const res = originalPushState.apply(win.history, args);
if (!history._ignoreSubscribers) onPushPop("PUSH");
return res;
};
win.history.replaceState = function(...args) {
const res = originalReplaceState.apply(win.history, args);
if (!history._ignoreSubscribers) onPushPop("REPLACE");
return res;
};
return history;
}
/**
* Create a hash-based history implementation.
* Useful for static hosts or environments without server URL rewriting.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
*/
function createHashHistory(opts) {
const win = opts?.window ?? (typeof document !== "undefined" ? window : void 0);
return createBrowserHistory({
window: win,
parseLocation: () => {
const hashSplit = win.location.hash.split("#").slice(1);
const pathPart = hashSplit[0] ?? "/";
const searchPart = win.location.search;
const hashEntries = hashSplit.slice(1);
return parseHref(`${pathPart}${searchPart}${hashEntries.length === 0 ? "" : `#${hashEntries.join("#")}`}`, win.history.state);
},
createHref: (href) => `${win.location.pathname}${win.location.search}#${href}`
});
}
/**
* Create an in-memory history implementation.
* Ideal for server rendering, tests, and non-DOM environments.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
*/
function createMemoryHistory(opts = { initialEntries: ["/"] }) {
const entries = opts.initialEntries;
let index = opts.initialIndex ? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1) : entries.length - 1;
const states = entries.map((_entry, index) => assignKeyAndIndex(index, void 0));
const getLocation = () => parseHref(entries[index], states[index]);
let blockers = [];
const _getBlockers = () => blockers;
const _setBlockers = (newBlockers) => blockers = newBlockers;
return createHistory({
getLocation,
getLength: () => entries.length,
pushState: (path, state) => {
index = index < entries.length - 1 ? index + 1 : entries.length;
states[index] = state;
entries[index] = path;
if (index < entries.length - 1) {
entries.length = index + 1;
states.length = index + 1;
}
},
replaceState: (path, state) => {
states[index] = state;
entries[index] = path;
},
back: () => {
index = Math.max(index - 1, 0);
},
forward: () => {
index = Math.min(index + 1, entries.length - 1);
},
go: (n) => {
index = Math.min(Math.max(index + n, 0), entries.length - 1);
},
createHref: normalizeHref,
getBlockers: _getBlockers,
setBlockers: _setBlockers
});
}
var noop = () => {};
var ServerHistory = class {
constructor(location) {
this.location = location;
}
get length() {
return 1;
}
get subscribers() {
return this._subscribers ??= /* @__PURE__ */ new Set();
}
subscribe() {
return noop;
}
push() {}
replace() {}
go() {}
back() {}
forward() {}
canGoBack() {
return false;
}
createHref(href) {
return normalizeHref(href);
}
block() {
return noop;
}
flush() {}
destroy() {}
notify() {}
_getBlockers() {
return [];
}
};
/** A fixed request location; server navigation is a no-op. */
function createServerHistory(href) {
return new ServerHistory(parseHref(href, void 0));
}
function parseHref(href, state) {
const sanitizedHref = normalizeHref(href);
const hashIndex = sanitizedHref.indexOf("#");
const searchIndex = sanitizedHref.indexOf("?");
if (!state) {
const key = createRandomKey();
state = {
[stateIndexKey]: 0,
key,
__TSR_key: key
};
}
return {
href: sanitizedHref,
pathname: sanitizedHref.substring(0, hashIndex > 0 ? searchIndex > 0 ? Math.min(hashIndex, searchIndex) : hashIndex : searchIndex > 0 ? searchIndex : sanitizedHref.length),
hash: hashIndex > -1 ? sanitizedHref.substring(hashIndex) : "",
search: searchIndex > -1 ? sanitizedHref.slice(searchIndex, hashIndex === -1 ? void 0 : hashIndex) : "",
state
};
}
function createRandomKey() {
return (Math.random() + 1).toString(36).substring(7);
}
//#endregion
export { createBrowserHistory, createHashHistory, createHistory, createMemoryHistory, createServerHistory, normalizeProtocolRelative, parseHref };
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["// While the public API was clearly inspired by the \"history\" npm package,\n// This implementation attempts to be more lightweight by\n// making assumptions about the way TanStack Router works\n\nexport interface NavigateOptions {\n ignoreBlocker?: boolean\n}\n\ntype SubscriberHistoryAction =\n | {\n type: Exclude<HistoryAction, 'GO'>\n }\n | {\n type: 'GO'\n index: number\n }\n\ntype SubscriberArgs = {\n location: HistoryLocation\n action: SubscriberHistoryAction\n}\n\nexport interface RouterHistory {\n location: HistoryLocation\n length: number\n subscribers: Set<(opts: SubscriberArgs) => void>\n subscribe: (cb: (opts: SubscriberArgs) => void) => () => void\n push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void\n replace: (path: string, state?: any, navigateOpts?: NavigateOptions) => void\n go: (index: number, navigateOpts?: NavigateOptions) => void\n back: (navigateOpts?: NavigateOptions) => void\n forward: (navigateOpts?: NavigateOptions) => void\n canGoBack: () => boolean\n createHref: (href: string) => string\n block: (blocker: NavigationBlocker) => () => void\n flush: () => void\n destroy: () => void\n notify: (action: SubscriberHistoryAction) => void\n _getBlockers: () => Array<NavigationBlocker>\n _ignoreSubscribers?: boolean\n _ignoreNextBeforeUnload?: (href: string) => void\n}\n\nexport interface HistoryLocation extends ParsedPath {\n state: ParsedHistoryState\n}\n\nexport interface ParsedPath {\n href: string\n pathname: string\n search: string\n hash: string\n}\n\nexport interface HistoryState {}\n\nexport type ParsedHistoryState = HistoryState & {\n key?: string // TODO: Remove in v2 - use __TSR_key instead\n __TSR_key?: string\n __TSR_index: number\n}\n\ntype ShouldAllowNavigation = any\n\nexport type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO'\n\nexport type BlockerFnArgs = {\n currentLocation: HistoryLocation\n nextLocation: HistoryLocation\n action: HistoryAction\n}\n\nexport type BlockerFn = (\n args: BlockerFnArgs,\n) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation\n\nexport type NavigationBlocker = {\n blockerFn: BlockerFn\n enableBeforeUnload?: (() => boolean) | boolean\n}\n\ntype TryNavigateArgs = {\n task: () => void\n type: 'PUSH' | 'REPLACE' | 'BACK' | 'FORWARD' | 'GO'\n navigateOpts?: NavigateOptions\n} & (\n | {\n type: 'PUSH' | 'REPLACE'\n path: string\n state: any\n }\n | {\n type: 'BACK' | 'FORWARD' | 'GO'\n }\n)\n\nconst stateIndexKey = '__TSR_index'\nconst popStateEvent = 'popstate'\nconst beforeUnloadEvent = 'beforeunload'\n\n/**\n * Turn protocol-relative inputs such as \"//evil.example\" into paths\n * such as \"/evil.example\", keeping navigation on the current origin.\n *\n * For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,\n * removes tabs/newlines, and treats backslashes as slashes, so inputs like\n * \"/\\evil.example\" also need normalization. This only allocates when those\n * rules would make the input protocol-relative.\n */\n// eslint-disable-next-line no-control-regex\nconst protocolRelativePrefix = /^[\\x00-\\x20]*(?:[\\\\/][\\t\\n\\r]*){2,}/\n\nexport function normalizeProtocolRelative(url: string): string {\n const match = protocolRelativePrefix.exec(url)\n return match ? '/' + url.slice(match[0].length) : url\n}\n\nfunction normalizeHref(href: string): string {\n // eslint-disable-next-line no-control-regex\n if (/[\\x00-\\x1f\\x7f]/.test(href)) {\n // eslint-disable-next-line no-control-regex\n href = href.replace(/[\\x00-\\x1f\\x7f]/g, (character) =>\n '\\t\\n\\r'.includes(character) ? '' : encodeURIComponent(character),\n )\n }\n return normalizeProtocolRelative(href)\n}\n\nexport function createHistory(opts: {\n getLocation: () => HistoryLocation\n getLength: () => number\n pushState: (path: string, state: any) => void\n replaceState: (path: string, state: any) => void\n go: (n: number, ignoreBlocker: boolean) => void\n back: (ignoreBlocker: boolean) => void\n forward: (ignoreBlocker: boolean) => void\n createHref: (path: string) => string\n flush?: () => void\n destroy?: () => void\n onBlocked?: () => void\n getBlockers?: () => Array<NavigationBlocker>\n setBlockers?: (blockers: Array<NavigationBlocker>) => void\n // Avoid notifying on forward/back/go, used for browser history as we already get notified by the popstate event\n notifyOnIndexChange?: boolean\n}): RouterHistory {\n let location = opts.getLocation()\n const subscribers = new Set<(opts: SubscriberArgs) => void>()\n\n const notify = (action: SubscriberHistoryAction) => {\n location = opts.getLocation()\n subscribers.forEach((subscriber) => subscriber({ location, action }))\n }\n\n const handleIndexChange = (action: SubscriberHistoryAction) => {\n if (opts.notifyOnIndexChange ?? true) notiLine truncated
+70
View File
@@ -0,0 +1,70 @@
{
"name": "@tanstack/history",
"version": "1.162.4",
"description": "Modern and scalable routing for React applications",
"author": "Tanner Linsley",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/TanStack/router.git",
"directory": "packages/history"
},
"homepage": "https://tanstack.com/router",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"keywords": [
"history",
"typescript"
],
"type": "module",
"types": "dist/esm/index.d.ts",
"main": "dist/cjs/index.cjs",
"module": "dist/esm/index.js",
"exports": {
".": {
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
}
},
"./package.json": "./package.json"
},
"sideEffects": false,
"files": [
"dist",
"src"
],
"engines": {
"node": ">=20.19"
},
"devDependencies": {
"vite": "*",
"@tanstack/vite-config": "0.5.2",
"vitest": "^4.1.4",
"jsdom": "^25.0.1",
"@arethetypeswrong/cli": "^0.18.4",
"publint": "^0.3.16",
"rimraf": "^6.1.2"
},
"scripts": {
"clean": "rimraf ./dist && rimraf ./coverage",
"test:eslint": "eslint ./src",
"test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"",
"test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js",
"test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js",
"test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js",
"test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js",
"test:types:ts60": "tsc6",
"test:types:ts70": "tsc",
"test:build": "publint --strict && attw --ignore-rules no-resolution --pack .",
"test:unit": "vitest",
"test:unit:dev": "pnpm run test:unit --watch",
"build": "vite build"
}
}
+781
View File
@@ -0,0 +1,781 @@
// While the public API was clearly inspired by the "history" npm package,
// This implementation attempts to be more lightweight by
// making assumptions about the way TanStack Router works
export interface NavigateOptions {
ignoreBlocker?: boolean
}
type SubscriberHistoryAction =
| {
type: Exclude<HistoryAction, 'GO'>
}
| {
type: 'GO'
index: number
}
type SubscriberArgs = {
location: HistoryLocation
action: SubscriberHistoryAction
}
export interface RouterHistory {
location: HistoryLocation
length: number
subscribers: Set<(opts: SubscriberArgs) => void>
subscribe: (cb: (opts: SubscriberArgs) => void) => () => void
push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void
replace: (path: string, state?: any, navigateOpts?: NavigateOptions) => void
go: (index: number, navigateOpts?: NavigateOptions) => void
back: (navigateOpts?: NavigateOptions) => void
forward: (navigateOpts?: NavigateOptions) => void
canGoBack: () => boolean
createHref: (href: string) => string
block: (blocker: NavigationBlocker) => () => void
flush: () => void
destroy: () => void
notify: (action: SubscriberHistoryAction) => void
_getBlockers: () => Array<NavigationBlocker>
_ignoreSubscribers?: boolean
_ignoreNextBeforeUnload?: (href: string) => void
}
export interface HistoryLocation extends ParsedPath {
state: ParsedHistoryState
}
export interface ParsedPath {
href: string
pathname: string
search: string
hash: string
}
export interface HistoryState {}
export type ParsedHistoryState = HistoryState & {
key?: string // TODO: Remove in v2 - use __TSR_key instead
__TSR_key?: string
__TSR_index: number
}
type ShouldAllowNavigation = any
export type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO'
export type BlockerFnArgs = {
currentLocation: HistoryLocation
nextLocation: HistoryLocation
action: HistoryAction
}
export type BlockerFn = (
args: BlockerFnArgs,
) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation
export type NavigationBlocker = {
blockerFn: BlockerFn
enableBeforeUnload?: (() => boolean) | boolean
}
type TryNavigateArgs = {
task: () => void
type: 'PUSH' | 'REPLACE' | 'BACK' | 'FORWARD' | 'GO'
navigateOpts?: NavigateOptions
} & (
| {
type: 'PUSH' | 'REPLACE'
path: string
state: any
}
| {
type: 'BACK' | 'FORWARD' | 'GO'
}
)
const stateIndexKey = '__TSR_index'
const popStateEvent = 'popstate'
const beforeUnloadEvent = 'beforeunload'
/**
* Turn protocol-relative inputs such as "//evil.example" into paths
* such as "/evil.example", keeping navigation on the current origin.
*
* For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,
* removes tabs/newlines, and treats backslashes as slashes, so inputs like
* "/\evil.example" also need normalization. This only allocates when those
* rules would make the input protocol-relative.
*/
// eslint-disable-next-line no-control-regex
const protocolRelativePrefix = /^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/
export function normalizeProtocolRelative(url: string): string {
const match = protocolRelativePrefix.exec(url)
return match ? '/' + url.slice(match[0].length) : url
}
function normalizeHref(href: string): string {
// eslint-disable-next-line no-control-regex
if (/[\x00-\x1f\x7f]/.test(href)) {
// eslint-disable-next-line no-control-regex
href = href.replace(/[\x00-\x1f\x7f]/g, (character) =>
'\t\n\r'.includes(character) ? '' : encodeURIComponent(character),
)
}
return normalizeProtocolRelative(href)
}
export function createHistory(opts: {
getLocation: () => HistoryLocation
getLength: () => number
pushState: (path: string, state: any) => void
replaceState: (path: string, state: any) => void
go: (n: number, ignoreBlocker: boolean) => void
back: (ignoreBlocker: boolean) => void
forward: (ignoreBlocker: boolean) => void
createHref: (path: string) => string
flush?: () => void
destroy?: () => void
onBlocked?: () => void
getBlockers?: () => Array<NavigationBlocker>
setBlockers?: (blockers: Array<NavigationBlocker>) => void
// Avoid notifying on forward/back/go, used for browser history as we already get notified by the popstate event
notifyOnIndexChange?: boolean
}): RouterHistory {
let location = opts.getLocation()
const subscribers = new Set<(opts: SubscriberArgs) => void>()
const notify = (action: SubscriberHistoryAction) => {
location = opts.getLocation()
subscribers.forEach((subscriber) => subscriber({ location, action }))
}
const handleIndexChange = (action: SubscriberHistoryAction) => {
if (opts.notifyOnIndexChange ?? true) notify(action)
else location = opts.getLocation()
}
const tryNavigation = async ({
task,
navigateOpts,
...actionInfo
}: TryNavigateArgs) => {
const ignoreBlocker = navigateOpts?.ignoreBlocker ?? false
if (ignoreBlocker) {
task()
return
}
const blockers = opts.getBlockers?.() ?? []
const isPushOrReplace =
actionInfo.type === 'PUSH' || actionInfo.type === 'REPLACE'
if (typeof document !== 'undefined' && blockers.length && isPushOrReplace) {
for (const blocker of blockers) {
const nextLocation = parseHref(actionInfo.path, actionInfo.state)
const isBlocked = await blocker.blockerFn({
currentLocation: location,
nextLocation,
action: actionInfo.type,
})
if (isBlocked) {
opts.onBlocked?.()
return
}
}
}
task()
}
return {
get location() {
return location
},
get length() {
return opts.getLength()
},
subscribers,
subscribe: (cb: (opts: SubscriberArgs) => void) => {
subscribers.add(cb)
return () => {
subscribers.delete(cb)
}
},
push: (path, state, navigateOpts) => {
const currentIndex = location.state[stateIndexKey]
state = assignKeyAndIndex(currentIndex + 1, state)
tryNavigation({
task: () => {
opts.pushState(path, state)
notify({ type: 'PUSH' })
},
navigateOpts,
type: 'PUSH',
path,
state,
})
},
replace: (path, state, navigateOpts) => {
const currentIndex = location.state[stateIndexKey]
state = assignKeyAndIndex(currentIndex, state)
tryNavigation({
task: () => {
opts.replaceState(path, state)
notify({ type: 'REPLACE' })
},
navigateOpts,
type: 'REPLACE',
path,
state,
})
},
go: (index, navigateOpts) => {
tryNavigation({
task: () => {
opts.go(index, navigateOpts?.ignoreBlocker ?? false)
handleIndexChange({ type: 'GO', index })
},
navigateOpts,
type: 'GO',
})
},
back: (navigateOpts) => {
tryNavigation({
task: () => {
opts.back(navigateOpts?.ignoreBlocker ?? false)
handleIndexChange({ type: 'BACK' })
},
navigateOpts,
type: 'BACK',
})
},
forward: (navigateOpts) => {
tryNavigation({
task: () => {
opts.forward(navigateOpts?.ignoreBlocker ?? false)
handleIndexChange({ type: 'FORWARD' })
},
navigateOpts,
type: 'FORWARD',
})
},
canGoBack: () => location.state[stateIndexKey] !== 0,
createHref: (str) => opts.createHref(str),
block: (blocker) => {
if (!opts.setBlockers) return () => {}
const blockers = opts.getBlockers?.() ?? []
opts.setBlockers([...blockers, blocker])
return () => {
const blockers = opts.getBlockers?.() ?? []
opts.setBlockers?.(blockers.filter((b) => b !== blocker))
}
},
flush: () => opts.flush?.(),
destroy: () => opts.destroy?.(),
notify,
_getBlockers: () => opts.getBlockers?.() ?? [],
}
}
function assignKeyAndIndex(index: number, state: HistoryState | undefined) {
const key = createRandomKey()
return {
...state,
key, // TODO: Remove in v2 - use __TSR_key instead
__TSR_key: key,
[stateIndexKey]: index,
} as ParsedHistoryState
}
/**
* Creates a history object that can be used to interact with the browser's
* navigation. This is a lightweight API wrapping the browser's native methods.
* It is designed to work with TanStack Router, but could be used as a standalone API as well.
* IMPORTANT: This API implements history throttling via a microtask to prevent
* excessive calls to the history API. In some browsers, calling history.pushState or
* history.replaceState in quick succession can cause the browser to ignore subsequent
* calls. This API smooths out those differences and ensures that your application
* state will *eventually* match the browser state. In most cases, this is not a problem,
* but if you need to ensure that the browser state is up to date, you can use the
* `history.flush` method to immediately flush all pending state changes to the browser URL.
* @param opts
* @param opts.getHref A function that returns the current href (path + search + hash)
* @param opts.createHref A function that takes a path and returns a href (path + search + hash)
* @returns A history instance
*/
export function createBrowserHistory(opts?: {
parseLocation?: () => HistoryLocation
createHref?: (path: string) => string
window?: any
}): RouterHistory {
const win =
opts?.window ??
(typeof document !== 'undefined' ? window : (undefined as any))
const originalPushState = win.history.pushState
const originalReplaceState = win.history.replaceState
let blockers: Array<NavigationBlocker> = []
const _getBlockers = () => blockers
const _setBlockers = (newBlockers: Array<NavigationBlocker>) =>
(blockers = newBlockers)
const createHref = (path: string) =>
normalizeHref(opts?.createHref ? opts.createHref(path) : path)
const parseLocation =
opts?.parseLocation ??
(() =>
parseHref(
`${win.location.pathname}${win.location.search}${win.location.hash}`,
win.history.state,
))
// Ensure there is always a key to start
if (!win.history.state?.__TSR_key && !win.history.state?.key) {
const addedKey = createRandomKey()
win.history.replaceState(
{
[stateIndexKey]: 0,
key: addedKey, // TODO: Remove in v2 - use __TSR_key instead
__TSR_key: addedKey,
},
'',
)
}
let currentLocation = parseLocation()
let rollbackLocation: HistoryLocation | undefined
let nextPopIsGo = false
let ignoreNextPop = false
// TODO: An ignored traversal past a history boundary emits neither popstate
// nor beforeunload, leaving these bypasses active for a later navigation.
// The History API provides no completion signal for such no-op traversals.
let skipBlockerNextPop = false
let ignoreNextBeforeUnload = false
const getLocation = () => currentLocation
let next:
| undefined
| [
// The latest location that we were attempting to push/replace
href: string,
// The latest state that we were attempting to push/replace
state: any,
// Whether any queued update needs to push rather than replace
isPush: boolean,
]
// This function flushes the next update to the browser history
const flush = () => {
if (!next) {
return
}
// We need to ignore any updates to the subscribers while we update the browser history
history._ignoreSubscribers = true
// Update the browser history
;(next[2 /* is push */] ? win.history.pushState : win.history.replaceState)(
next[1 /* state */],
'',
next[0 /* href */],
)
// Stop ignoring subscriber updates
history._ignoreSubscribers = false
// Clear the queued action after it reaches browser history.
next = undefined
rollbackLocation = undefined
}
// This function queues up a call to update the browser history
const queueHistoryAction = (
isPush: boolean,
destHref: string,
state: any,
) => {
// A formatter changes the URL space and must receive the original input.
// Otherwise parseHref below already produces the browser destination.
const href = opts?.createHref ? createHref(destHref) : undefined
const hasPendingAction = !!next
if (!hasPendingAction) {
rollbackLocation = currentLocation
}
// Keep the optimistic location in the router's logical URL space.
currentLocation = parseHref(destHref, state)
// Keep track of the next location we need to flush to the URL
next = [
href ?? currentLocation.href,
state,
next?.[2 /* is push */] || isPush,
]
if (!hasPendingAction) {
// Schedule an update to the browser history
queueMicrotask(() => flush())
}
}
// NOTE: this function can probably be removed
const onPushPop = (type: 'PUSH' | 'REPLACE') => {
currentLocation = parseLocation()
history.notify({ type })
}
const onPushPopEvent = async () => {
// Same-document traversals do not fire beforeunload, so consume their
// exemption here instead of carrying it into a later document navigation.
ignoreNextBeforeUnload = false
if (ignoreNextPop) {
ignoreNextPop = false
return
}
const nextLocation = parseLocation()
const delta =
nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey]
const isForward = delta === 1
const isBack = delta === -1
const isGo = (!isForward && !isBack) || nextPopIsGo
nextPopIsGo = false
const action = isGo ? 'GO' : isBack ? 'BACK' : 'FORWARD'
const notify: SubscriberHistoryAction = isGo
? {
type: 'GO',
index: delta,
}
: {
type: isBack ? 'BACK' : 'FORWARD',
}
if (skipBlockerNextPop) {
skipBlockerNextPop = false
} else {
const blockers = _getBlockers()
if (typeof document !== 'undefined' && blockers.length) {
for (const blocker of blockers) {
const isBlocked = await blocker.blockerFn({
currentLocation,
nextLocation,
action,
})
if (isBlocked) {
ignoreNextPop = true
win.history.go(-delta)
history.notify(notify)
return
}
}
}
}
currentLocation = parseLocation()
history.notify(notify)
}
const onBeforeUnload = (e: BeforeUnloadEvent) => {
if (ignoreNextBeforeUnload) {
ignoreNextBeforeUnload = false
return
}
let shouldBlock = false
// If one blocker has a non-disabled beforeUnload, we should block
const blockers = _getBlockers()
if (typeof document !== 'undefined' && blockers.length) {
for (const blocker of blockers) {
const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true
if (shouldHaveBeforeUnload === true) {
shouldBlock = true
break
}
if (
typeof shouldHaveBeforeUnload === 'function' &&
shouldHaveBeforeUnload() === true
) {
shouldBlock = true
break
}
}
}
if (shouldBlock) {
e.preventDefault()
return (e.returnValue = '')
}
return
}
const history = createHistory({
getLocation,
getLength: () => win.history.length,
pushState: (href, state) => queueHistoryAction(true, href, state),
replaceState: (href, state) => queueHistoryAction(false, href, state),
back: (ignoreBlocker) => {
if (ignoreBlocker) {
skipBlockerNextPop = true
ignoreNextBeforeUnload = true
}
return win.history.back()
},
forward: (ignoreBlocker) => {
if (ignoreBlocker) {
skipBlockerNextPop = true
ignoreNextBeforeUnload = true
}
win.history.forward()
},
go: (n, ignoreBlocker) => {
nextPopIsGo = true
if (ignoreBlocker) {
skipBlockerNextPop = true
ignoreNextBeforeUnload = true
}
win.history.go(n)
},
createHref: (href) => createHref(href),
flush,
destroy: () => {
win.history.pushState = originalPushState
win.history.replaceState = originalReplaceState
win.removeEventListener(beforeUnloadEvent, onBeforeUnload, {
capture: true,
})
win.removeEventListener(popStateEvent, onPushPopEvent)
},
onBlocked: () => {
// If a navigation is blocked, we need to rollback the location
// that we optimistically updated in memory.
if (rollbackLocation && currentLocation !== rollbackLocation) {
currentLocation = rollbackLocation
}
},
getBlockers: _getBlockers,
setBlockers: _setBlockers,
notifyOnIndexChange: false,
})
history._ignoreNextBeforeUnload = (href) => {
ignoreNextBeforeUnload = false
try {
href = new URL(href, win.document.baseURI).href
// External handlers and same-document fragments may emit neither
// beforeunload nor popstate, leaving an exemption for a later departure.
ignoreNextBeforeUnload =
/^https?:/.test(href) &&
(!href.includes('#') ||
href.split('#')[0] !== win.location.href.split('#')[0])
} catch {
// Invalid URLs cannot unload the document.
}
}
win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true })
win.addEventListener(popStateEvent, onPushPopEvent)
win.history.pushState = function (...args: Array<any>) {
const res = originalPushState.apply(win.history, args as any)
if (!history._ignoreSubscribers) onPushPop('PUSH')
return res
}
win.history.replaceState = function (...args: Array<any>) {
const res = originalReplaceState.apply(win.history, args as any)
if (!history._ignoreSubscribers) onPushPop('REPLACE')
return res
}
return history
}
/**
* Create a hash-based history implementation.
* Useful for static hosts or environments without server URL rewriting.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
*/
export function createHashHistory(opts?: { window?: any }): RouterHistory {
const win =
opts?.window ??
(typeof document !== 'undefined' ? window : (undefined as any))
return createBrowserHistory({
window: win,
parseLocation: () => {
const hashSplit = win.location.hash.split('#').slice(1)
const pathPart = hashSplit[0] ?? '/'
const searchPart = win.location.search
const hashEntries = hashSplit.slice(1)
const hashPart =
hashEntries.length === 0 ? '' : `#${hashEntries.join('#')}`
const hashHref = `${pathPart}${searchPart}${hashPart}`
return parseHref(hashHref, win.history.state)
},
createHref: (href) =>
`${win.location.pathname}${win.location.search}#${href}`,
})
}
/**
* Create an in-memory history implementation.
* Ideal for server rendering, tests, and non-DOM environments.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
*/
export function createMemoryHistory(
opts: {
initialEntries: Array<string>
initialIndex?: number
} = {
initialEntries: ['/'],
},
): RouterHistory {
const entries = opts.initialEntries
let index = opts.initialIndex
? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1)
: entries.length - 1
const states = entries.map((_entry, index) =>
assignKeyAndIndex(index, undefined),
)
const getLocation = () => parseHref(entries[index]!, states[index])
let blockers: Array<NavigationBlocker> = []
const _getBlockers = () => blockers
const _setBlockers = (newBlockers: Array<NavigationBlocker>) =>
(blockers = newBlockers)
return createHistory({
getLocation,
getLength: () => entries.length,
pushState: (path, state) => {
// Removes all subsequent entries after the current index to start a new branch
index = index < entries.length - 1 ? index + 1 : entries.length
states[index] = state
entries[index] = path
if (index < entries.length - 1) {
entries.length = index + 1
states.length = index + 1
}
},
replaceState: (path, state) => {
states[index] = state
entries[index] = path
},
back: () => {
index = Math.max(index - 1, 0)
},
forward: () => {
index = Math.min(index + 1, entries.length - 1)
},
go: (n) => {
index = Math.min(Math.max(index + n, 0), entries.length - 1)
},
createHref: normalizeHref,
getBlockers: _getBlockers,
setBlockers: _setBlockers,
})
}
const noop = () => {}
class ServerHistory implements RouterHistory {
declare private _subscribers?: RouterHistory['subscribers']
constructor(public location: HistoryLocation) {}
get length() {
return 1
}
// Preserve the history interface without allocating a Set for each request.
get subscribers() {
return (this._subscribers ??= new Set())
}
subscribe() {
return noop
}
push() {}
replace() {}
go() {}
back() {}
forward() {}
canGoBack() {
return false
}
createHref(href: string) {
return normalizeHref(href)
}
block() {
return noop
}
flush() {}
destroy() {}
notify() {}
_getBlockers(): Array<NavigationBlocker> {
return []
}
}
/** A fixed request location; server navigation is a no-op. */
export function createServerHistory(href: string): RouterHistory {
return new ServerHistory(parseHref(href, undefined))
}
export function parseHref(
href: string,
state: ParsedHistoryState | undefined,
): HistoryLocation {
const sanitizedHref = normalizeHref(href)
const hashIndex = sanitizedHref.indexOf('#')
const searchIndex = sanitizedHref.indexOf('?')
if (!state) {
const key = createRandomKey()
state = { [stateIndexKey]: 0, key, __TSR_key: key }
}
return {
href: sanitizedHref,
pathname: sanitizedHref.substring(
0,
hashIndex > 0
? searchIndex > 0
? Math.min(hashIndex, searchIndex)
: hashIndex
: searchIndex > 0
? searchIndex
: sanitizedHref.length,
),
hash: hashIndex > -1 ? sanitizedHref.substring(hashIndex) : '',
search:
searchIndex > -1
? sanitizedHref.slice(
searchIndex,
hashIndex === -1 ? undefined : hashIndex,
)
: '',
state,
}
}
// Thanks co-pilot!
function createRandomKey() {
return (Math.random() + 1).toString(36).substring(7)
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-present Tanner Linsley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,56 @@
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/checkPrivateRedeclaration.js
function _checkPrivateRedeclaration(e, t) {
if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
}
//#endregion
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldInitSpec.js
function _classPrivateFieldInitSpec(e, t, a) {
_checkPrivateRedeclaration(e, t), t.set(e, a);
}
//#endregion
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/assertClassBrand.js
function _assertClassBrand(e, t, n) {
if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
throw new TypeError("Private element is not present on this object");
}
//#endregion
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldGet2.js
function _classPrivateFieldGet2(s, a) {
return s.get(_assertClassBrand(s, a));
}
//#endregion
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldSet2.js
function _classPrivateFieldSet2(s, a, r) {
return s.set(_assertClassBrand(s, a), r), r;
}
//#endregion
Object.defineProperty(exports, "_assertClassBrand", {
enumerable: true,
get: function() {
return _assertClassBrand;
}
});
Object.defineProperty(exports, "_checkPrivateRedeclaration", {
enumerable: true,
get: function() {
return _checkPrivateRedeclaration;
}
});
Object.defineProperty(exports, "_classPrivateFieldGet2", {
enumerable: true,
get: function() {
return _classPrivateFieldGet2;
}
});
Object.defineProperty(exports, "_classPrivateFieldInitSpec", {
enumerable: true,
get: function() {
return _classPrivateFieldInitSpec;
}
});
Object.defineProperty(exports, "_classPrivateFieldSet2", {
enumerable: true,
get: function() {
return _classPrivateFieldSet2;
}
});
@@ -0,0 +1,27 @@
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/checkPrivateRedeclaration.js
function _checkPrivateRedeclaration(e, t) {
if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
}
//#endregion
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldInitSpec.js
function _classPrivateFieldInitSpec(e, t, a) {
_checkPrivateRedeclaration(e, t), t.set(e, a);
}
//#endregion
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/assertClassBrand.js
function _assertClassBrand(e, t, n) {
if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
throw new TypeError("Private element is not present on this object");
}
//#endregion
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldGet2.js
function _classPrivateFieldGet2(s, a) {
return s.get(_assertClassBrand(s, a));
}
//#endregion
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateFieldSet2.js
function _classPrivateFieldSet2(s, a, r) {
return s.set(_assertClassBrand(s, a), r), r;
}
//#endregion
export { _checkPrivateRedeclaration as a, _classPrivateFieldInitSpec as i, _classPrivateFieldGet2 as n, _assertClassBrand as r, _classPrivateFieldSet2 as t };
@@ -0,0 +1,7 @@
import { a as _checkPrivateRedeclaration } from "./classPrivateFieldSet2-CV7wyte-.js";
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateMethodInitSpec.js
function _classPrivateMethodInitSpec(e, a) {
_checkPrivateRedeclaration(e, a), a.add(e);
}
//#endregion
export { _classPrivateMethodInitSpec as t };
@@ -0,0 +1,12 @@
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
//#region \0@oxc-project+runtime@0.144.0/helpers/esm/classPrivateMethodInitSpec.js
function _classPrivateMethodInitSpec(e, a) {
require_classPrivateFieldSet2._checkPrivateRedeclaration(e, a), a.add(e);
}
//#endregion
Object.defineProperty(exports, "_classPrivateMethodInitSpec", {
enumerable: true,
get: function() {
return _classPrivateMethodInitSpec;
}
});
@@ -0,0 +1,39 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_utils = require("./utils.cjs");
//#region src/environmentManager.ts
let isServerFn = () => require_utils.isServer;
/**
* Returns whether the current runtime should be treated as a server environment.
*/
const isServer = () => isServerFn();
/**
* Manages how TanStack Query detects whether the current runtime should be treated as
* server-side, which disables scheduling refetch timers and changes the default `retry` count
* and `gcTime`. By default, the detection treats a missing `window` (or the presence of a
* `Deno` global) as server.
*
* Override this for runtimes where that default detection would give the wrong answer — for
* example, a Service Worker, where `window` is undefined even though the environment should
* behave like a client.
*
* @example
* ```ts
* import { environmentManager } from '@tanstack/query-core'
*
* environmentManager.setIsServer(() => false)
* ```
*/
const environmentManager = {
isServer,
/**
* Overrides the server check globally.
*/
setIsServer(isServerValue) {
isServerFn = isServerValue;
}
};
//#endregion
exports.environmentManager = environmentManager;
exports.isServer = isServer;
//# sourceMappingURL=environmentManager.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"environmentManager.cjs","names":["defaultIsServer"],"sources":["../../src/environmentManager.ts"],"sourcesContent":["import { isServer as defaultIsServer } from './utils'\n\nexport type IsServerValue = () => boolean\n\nlet isServerFn: IsServerValue = () => defaultIsServer\n\n/**\n * Returns whether the current runtime should be treated as a server environment.\n */\nexport const isServer = (): boolean => isServerFn()\n\n/**\n * Manages how TanStack Query detects whether the current runtime should be treated as\n * server-side, which disables scheduling refetch timers and changes the default `retry` count\n * and `gcTime`. By default, the detection treats a missing `window` (or the presence of a\n * `Deno` global) as server.\n *\n * Override this for runtimes where that default detection would give the wrong answer — for\n * example, a Service Worker, where `window` is undefined even though the environment should\n * behave like a client.\n *\n * @example\n * ```ts\n * import { environmentManager } from '@tanstack/query-core'\n *\n * environmentManager.setIsServer(() => false)\n * ```\n */\nexport const environmentManager = {\n isServer,\n /**\n * Overrides the server check globally.\n */\n setIsServer(isServerValue: IsServerValue): void {\n isServerFn = isServerValue\n },\n}\n"],"mappings":";;;AAIA,IAAI,mBAAkCA,cAAAA;;;;AAKtC,MAAa,iBAA0B,WAAW;;;;;;;;;;;;;;;;;;AAmBlD,MAAa,qBAAqB;CAChC;;;;CAIA,YAAY,eAAoC;EAC9C,aAAa;CACf;AACF"}
@@ -0,0 +1,33 @@
//#region src/environmentManager.d.ts
type IsServerValue = () => boolean;
/**
* Returns whether the current runtime should be treated as a server environment.
*/
declare const isServer: () => boolean;
/**
* Manages how TanStack Query detects whether the current runtime should be treated as
* server-side, which disables scheduling refetch timers and changes the default `retry` count
* and `gcTime`. By default, the detection treats a missing `window` (or the presence of a
* `Deno` global) as server.
*
* Override this for runtimes where that default detection would give the wrong answer — for
* example, a Service Worker, where `window` is undefined even though the environment should
* behave like a client.
*
* @example
* ```ts
* import { environmentManager } from '@tanstack/query-core'
*
* environmentManager.setIsServer(() => false)
* ```
*/
declare const environmentManager: {
isServer: () => boolean;
/**
* Overrides the server check globally.
*/
setIsServer(isServerValue: IsServerValue): void;
};
//#endregion
export { IsServerValue, environmentManager, isServer };
//# sourceMappingURL=environmentManager.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"environmentManager.d.cts","names":[],"sources":["../../src/environmentManager.ts"],"mappings":";KAEY;;;;cAOC;;;;;;;;;;;;;;;;;;cAmBA;EAnBe;;;;EAwBC,YAAA,eAAA"}
@@ -0,0 +1,33 @@
//#region src/environmentManager.d.ts
type IsServerValue = () => boolean;
/**
* Returns whether the current runtime should be treated as a server environment.
*/
declare const isServer: () => boolean;
/**
* Manages how TanStack Query detects whether the current runtime should be treated as
* server-side, which disables scheduling refetch timers and changes the default `retry` count
* and `gcTime`. By default, the detection treats a missing `window` (or the presence of a
* `Deno` global) as server.
*
* Override this for runtimes where that default detection would give the wrong answer — for
* example, a Service Worker, where `window` is undefined even though the environment should
* behave like a client.
*
* @example
* ```ts
* import { environmentManager } from '@tanstack/query-core'
*
* environmentManager.setIsServer(() => false)
* ```
*/
declare const environmentManager: {
isServer: () => boolean;
/**
* Overrides the server check globally.
*/
setIsServer(isServerValue: IsServerValue): void;
};
//#endregion
export { IsServerValue, environmentManager, isServer };
//# sourceMappingURL=environmentManager.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"environmentManager.d.ts","names":[],"sources":["../../src/environmentManager.ts"],"mappings":";KAEY;;;;cAOC;;;;;;;;;;;;;;;;;;cAmBA;EAnBe;;;;EAwBC,YAAA,eAAA"}
@@ -0,0 +1,37 @@
import { isServer as isServer$1 } from "./utils.js";
//#region src/environmentManager.ts
let isServerFn = () => isServer$1;
/**
* Returns whether the current runtime should be treated as a server environment.
*/
const isServer = () => isServerFn();
/**
* Manages how TanStack Query detects whether the current runtime should be treated as
* server-side, which disables scheduling refetch timers and changes the default `retry` count
* and `gcTime`. By default, the detection treats a missing `window` (or the presence of a
* `Deno` global) as server.
*
* Override this for runtimes where that default detection would give the wrong answer — for
* example, a Service Worker, where `window` is undefined even though the environment should
* behave like a client.
*
* @example
* ```ts
* import { environmentManager } from '@tanstack/query-core'
*
* environmentManager.setIsServer(() => false)
* ```
*/
const environmentManager = {
isServer,
/**
* Overrides the server check globally.
*/
setIsServer(isServerValue) {
isServerFn = isServerValue;
}
};
//#endregion
export { environmentManager, isServer };
//# sourceMappingURL=environmentManager.js.map
@@ -0,0 +1 @@
{"version":3,"file":"environmentManager.js","names":["defaultIsServer"],"sources":["../../src/environmentManager.ts"],"sourcesContent":["import { isServer as defaultIsServer } from './utils'\n\nexport type IsServerValue = () => boolean\n\nlet isServerFn: IsServerValue = () => defaultIsServer\n\n/**\n * Returns whether the current runtime should be treated as a server environment.\n */\nexport const isServer = (): boolean => isServerFn()\n\n/**\n * Manages how TanStack Query detects whether the current runtime should be treated as\n * server-side, which disables scheduling refetch timers and changes the default `retry` count\n * and `gcTime`. By default, the detection treats a missing `window` (or the presence of a\n * `Deno` global) as server.\n *\n * Override this for runtimes where that default detection would give the wrong answer — for\n * example, a Service Worker, where `window` is undefined even though the environment should\n * behave like a client.\n *\n * @example\n * ```ts\n * import { environmentManager } from '@tanstack/query-core'\n *\n * environmentManager.setIsServer(() => false)\n * ```\n */\nexport const environmentManager = {\n isServer,\n /**\n * Overrides the server check globally.\n */\n setIsServer(isServerValue: IsServerValue): void {\n isServerFn = isServerValue\n },\n}\n"],"mappings":";;AAIA,IAAI,mBAAkCA;;;;AAKtC,MAAa,iBAA0B,WAAW;;;;;;;;;;;;;;;;;;AAmBlD,MAAa,qBAAqB;CAChC;;;;CAIA,YAAY,eAAoC;EAC9C,aAAa;CACf;AACF"}
+123
View File
@@ -0,0 +1,123 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
const require_subscribable = require("./subscribable.cjs");
//#region src/focusManager.ts
var _focused = /* @__PURE__ */ new WeakMap();
var _cleanup = /* @__PURE__ */ new WeakMap();
var _setup = /* @__PURE__ */ new WeakMap();
/**
* The `FocusManager` manages the focus state within TanStack Query.
*
* It can be used to change the default event listeners or to manually change the focus state.
*/
var FocusManager = class extends require_subscribable.Subscribable {
constructor() {
super();
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _focused, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _cleanup, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _setup, void 0);
require_classPrivateFieldSet2._classPrivateFieldSet2(_setup, this, (onFocus) => {
if (typeof window !== "undefined" && window.addEventListener) {
const listener = () => onFocus();
window.addEventListener("visibilitychange", listener, false);
return () => {
window.removeEventListener("visibilitychange", listener);
};
}
});
}
onSubscribe() {
if (!require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) this.setEventListener(require_classPrivateFieldSet2._classPrivateFieldGet2(_setup, this));
}
onUnsubscribe() {
if (!this.hasListeners()) {
var _classPrivateFieldGet2$1;
(_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet2$1 === void 0 || _classPrivateFieldGet2$1.call(this);
require_classPrivateFieldSet2._classPrivateFieldSet2(_cleanup, this, 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 _classPrivateFieldGet3;
require_classPrivateFieldSet2._classPrivateFieldSet2(_setup, this, setup);
(_classPrivateFieldGet3 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.call(this);
require_classPrivateFieldSet2._classPrivateFieldSet2(_cleanup, this, 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 (require_classPrivateFieldSet2._classPrivateFieldGet2(_focused, this) !== focused) {
require_classPrivateFieldSet2._classPrivateFieldSet2(_focused, this, 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 _globalThis$document;
if (typeof require_classPrivateFieldSet2._classPrivateFieldGet2(_focused, this) === "boolean") return require_classPrivateFieldSet2._classPrivateFieldGet2(_focused, this);
return ((_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.visibilityState) !== "hidden";
}
};
/**
* Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.
*/
const focusManager = new FocusManager();
//#endregion
exports.FocusManager = FocusManager;
exports.focusManager = focusManager;
//# sourceMappingURL=focusManager.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"focusManager.cjs","names":["Subscribable"],"sources":["../../src/focusManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (focused: boolean) => void\n\ntype SetupFn = (\n setFocused: (focused?: boolean) => void,\n) => (() => void) | undefined\n\n/**\n * The `FocusManager` manages the focus state within TanStack Query.\n *\n * It can be used to change the default event listeners or to manually change the focus state.\n */\nexport class FocusManager extends Subscribable<Listener> {\n #focused?: boolean\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onFocus) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const listener = () => onFocus()\n // Listen to visibilitychange\n window.addEventListener('visibilitychange', listener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('visibilitychange', listener)\n }\n }\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n /**\n * `setEventListener` can be used to set a custom event listener that will\n * be used to determine the focus state. The provided `setup` function\n * receives a `setFocused` callback: call it with a `boolean` to manually\n * set the focus state, or with no arguments to re-evaluate the current\n * focus state and notify subscribers.\n *\n * @example\n * ```ts\n * import { focusManager } from '@tanstack/query-core'\n *\n * focusManager.setEventListener((handleFocus) => {\n * const listener = () => handleFocus()\n * // Listen to visibilitychange\n * if (typeof window !== 'undefined' && window.addEventListener) {\n * window.addEventListener('visibilitychange', listener, false)\n * }\n *\n * return () => {\n * // Be sure to unsubscribe if a new handler is set\n * window.removeEventListener('visibilitychange', listener)\n * }\n * })\n * ```\n */\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup((focused) => {\n if (typeof focused === 'boolean') {\n this.setFocused(focused)\n } else {\n this.onFocus()\n }\n })\n }\n\n /**\n * `setFocused` can be used to manually set the focus state. Set `undefined`\n * to fall back to the default focus check.\n *\n * @example\n * ```ts\n * import { focusManager } from '@tanstack/query-core'\n *\n * // Set focused\n * focusManager.setFocused(true)\n *\n * // Set unfocused\n * focusManager.setFocused(false)\n *\n * // Fallback to the default focus check\n * focusManager.setFocused(undefined)\n * ```\n */\n setFocused(focused?: boolean): void {\n const changed = this.#focused !== focused\n if (changed) {\n this.#focused = focused\n this.onFocus()\n }\n }\n\n /**\n * `onFocus` notifies all subscribed listeners with the current focus state.\n */\n onFocus(): void {\n const isFocused = this.isFocused()\n this.listeners.forEach((listener) => {\n listener(isFocused)\n })\n }\n\n /**\n * `isFocused` can be used to get the current focus state.\n */\n isFocused(): boolean {\n if (typeof this.#focused === 'boolean') {\n return this.#focused\n }\n\n // document global can be unavailable in react native\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return globalThis.document?.visibilityState !== 'hidden'\n }\n}\n\n/**\n * Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.\n */\nexport const focusManager = new FocusManager()\n"],"mappings":";;;;;;;;;;;;AAaA,IAAa,eAAb,cAAkCA,qBAAAA,aAAuB;CAMvD,cAAc;EACZ,MAAM;;;;EACN,8BAAA,uBAAA,QAAA,OAAe,YAAY;GAGzB,IAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;IAC5D,MAAM,iBAAiB,QAAQ;IAE/B,OAAO,iBAAiB,oBAAoB,UAAU,KAAK;IAE3D,aAAa;KAEX,OAAO,oBAAoB,oBAAoB,QAAQ;IACzD;GACF;EAEF,CAAA;CACF;CAEA,cAA8B;EAC5B,IAAI,CAAA,8BAAA,uBAAA,UAAC,IAAA,GACH,KAAK,iBAAA,8BAAA,uBAAA,QAAiB,IAAA,CAAW;CAErC;CAEA,gBAA0B;EACxB,IAAI,CAAC,KAAK,aAAa,GAAG;;GACxB,CAAA,2BAAA,8BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,6BAAA,KAAA,KAAA,yBAAA,KAAA,IAAgB;GAChB,8BAAA,uBAAA,UAAA,MAAgB,KAAA,CAAA;EAClB;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,iBAAiB,OAAsB;;EACrC,8BAAA,uBAAA,QAAA,MAAc,KAAA;EACd,CAAA,yBAAA,8BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,2BAAA,KAAA,KAAA,uBAAA,KAAA,IAAgB;EAChB,8BAAA,uBAAA,UAAA,MAAgB,OAAO,YAAY;GACjC,IAAI,OAAO,YAAY,WACrB,KAAK,WAAW,OAAO;QAEvB,KAAK,QAAQ;EAEjB,CAAC,CALine truncated
+75
View File
@@ -0,0 +1,75 @@
import { t as Subscribable } from "./subscribable-CbifVTKz.cjs";
//#region src/focusManager.d.ts
type Listener = (focused: boolean) => void;
type SetupFn = (setFocused: (focused?: boolean) => void) => (() => void) | undefined;
/**
* The `FocusManager` manages the focus state within TanStack Query.
*
* It can be used to change the default event listeners or to manually change the focus state.
*/
declare class FocusManager extends Subscribable<Listener> {
#private;
constructor();
protected onSubscribe(): void;
protected onUnsubscribe(): void;
/**
* `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: SetupFn): void;
/**
* `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?: boolean): void;
/**
* `onFocus` notifies all subscribed listeners with the current focus state.
*/
onFocus(): void;
/**
* `isFocused` can be used to get the current focus state.
*/
isFocused(): boolean;
}
/**
* Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.
*/
declare const focusManager: FocusManager;
//#endregion
export { FocusManager, focusManager };
//# sourceMappingURL=focusManager.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"focusManager.d.cts","names":[],"sources":["../../src/focusManager.ts"],"mappings":";;KAEK,YAAY;KAEZ,WACH,aAAa;;;;;;cAQF,qBAAqB,aAAa;;;YAyBnC;YAMA;;;;;;;;;;;;;;;;;;;;;;;;;;EAgCV,iBAAiB,OAAO;;;;;;;;;;;;;;;;;;;EA8BxB,WAAW;;;;EAWX;;;;EAUA;;;;;cAcW,cAAY"}
+75
View File
@@ -0,0 +1,75 @@
import { t as Subscribable } from "./subscribable-CbifVTKz.js";
//#region src/focusManager.d.ts
type Listener = (focused: boolean) => void;
type SetupFn = (setFocused: (focused?: boolean) => void) => (() => void) | undefined;
/**
* The `FocusManager` manages the focus state within TanStack Query.
*
* It can be used to change the default event listeners or to manually change the focus state.
*/
declare class FocusManager extends Subscribable<Listener> {
#private;
constructor();
protected onSubscribe(): void;
protected onUnsubscribe(): void;
/**
* `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: SetupFn): void;
/**
* `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?: boolean): void;
/**
* `onFocus` notifies all subscribed listeners with the current focus state.
*/
onFocus(): void;
/**
* `isFocused` can be used to get the current focus state.
*/
isFocused(): boolean;
}
/**
* Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.
*/
declare const focusManager: FocusManager;
//#endregion
export { FocusManager, focusManager };
//# sourceMappingURL=focusManager.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"focusManager.d.ts","names":[],"sources":["../../src/focusManager.ts"],"mappings":";;KAEK,YAAY;KAEZ,WACH,aAAa;;;;;;cAQF,qBAAqB,aAAa;;;YAyBnC;YAMA;;;;;;;;;;;;;;;;;;;;;;;;;;EAgCV,iBAAiB,OAAO;;;;;;;;;;;;;;;;;;;EA8BxB,WAAW;;;;EAWX;;;;EAUA;;;;;cAcW,cAAY"}
+121
View File
@@ -0,0 +1,121 @@
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
import { Subscribable } from "./subscribable.js";
//#region src/focusManager.ts
var _focused = /* @__PURE__ */ new WeakMap();
var _cleanup = /* @__PURE__ */ new WeakMap();
var _setup = /* @__PURE__ */ new WeakMap();
/**
* The `FocusManager` manages the focus state within TanStack Query.
*
* It can be used to change the default event listeners or to manually change the focus state.
*/
var FocusManager = class extends Subscribable {
constructor() {
super();
_classPrivateFieldInitSpec(this, _focused, void 0);
_classPrivateFieldInitSpec(this, _cleanup, void 0);
_classPrivateFieldInitSpec(this, _setup, void 0);
_classPrivateFieldSet2(_setup, this, (onFocus) => {
if (typeof window !== "undefined" && window.addEventListener) {
const listener = () => onFocus();
window.addEventListener("visibilitychange", listener, false);
return () => {
window.removeEventListener("visibilitychange", listener);
};
}
});
}
onSubscribe() {
if (!_classPrivateFieldGet2(_cleanup, this)) this.setEventListener(_classPrivateFieldGet2(_setup, this));
}
onUnsubscribe() {
if (!this.hasListeners()) {
var _classPrivateFieldGet2$1;
(_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet2$1 === void 0 || _classPrivateFieldGet2$1.call(this);
_classPrivateFieldSet2(_cleanup, this, 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 _classPrivateFieldGet3;
_classPrivateFieldSet2(_setup, this, setup);
(_classPrivateFieldGet3 = _classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.call(this);
_classPrivateFieldSet2(_cleanup, this, 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 (_classPrivateFieldGet2(_focused, this) !== focused) {
_classPrivateFieldSet2(_focused, this, 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 _globalThis$document;
if (typeof _classPrivateFieldGet2(_focused, this) === "boolean") return _classPrivateFieldGet2(_focused, this);
return ((_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.visibilityState) !== "hidden";
}
};
/**
* Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.
*/
const focusManager = new FocusManager();
//#endregion
export { FocusManager, focusManager };
//# sourceMappingURL=focusManager.js.map
@@ -0,0 +1 @@
{"version":3,"file":"focusManager.js","names":[],"sources":["../../src/focusManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (focused: boolean) => void\n\ntype SetupFn = (\n setFocused: (focused?: boolean) => void,\n) => (() => void) | undefined\n\n/**\n * The `FocusManager` manages the focus state within TanStack Query.\n *\n * It can be used to change the default event listeners or to manually change the focus state.\n */\nexport class FocusManager extends Subscribable<Listener> {\n #focused?: boolean\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onFocus) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const listener = () => onFocus()\n // Listen to visibilitychange\n window.addEventListener('visibilitychange', listener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('visibilitychange', listener)\n }\n }\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n /**\n * `setEventListener` can be used to set a custom event listener that will\n * be used to determine the focus state. The provided `setup` function\n * receives a `setFocused` callback: call it with a `boolean` to manually\n * set the focus state, or with no arguments to re-evaluate the current\n * focus state and notify subscribers.\n *\n * @example\n * ```ts\n * import { focusManager } from '@tanstack/query-core'\n *\n * focusManager.setEventListener((handleFocus) => {\n * const listener = () => handleFocus()\n * // Listen to visibilitychange\n * if (typeof window !== 'undefined' && window.addEventListener) {\n * window.addEventListener('visibilitychange', listener, false)\n * }\n *\n * return () => {\n * // Be sure to unsubscribe if a new handler is set\n * window.removeEventListener('visibilitychange', listener)\n * }\n * })\n * ```\n */\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup((focused) => {\n if (typeof focused === 'boolean') {\n this.setFocused(focused)\n } else {\n this.onFocus()\n }\n })\n }\n\n /**\n * `setFocused` can be used to manually set the focus state. Set `undefined`\n * to fall back to the default focus check.\n *\n * @example\n * ```ts\n * import { focusManager } from '@tanstack/query-core'\n *\n * // Set focused\n * focusManager.setFocused(true)\n *\n * // Set unfocused\n * focusManager.setFocused(false)\n *\n * // Fallback to the default focus check\n * focusManager.setFocused(undefined)\n * ```\n */\n setFocused(focused?: boolean): void {\n const changed = this.#focused !== focused\n if (changed) {\n this.#focused = focused\n this.onFocus()\n }\n }\n\n /**\n * `onFocus` notifies all subscribed listeners with the current focus state.\n */\n onFocus(): void {\n const isFocused = this.isFocused()\n this.listeners.forEach((listener) => {\n listener(isFocused)\n })\n }\n\n /**\n * `isFocused` can be used to get the current focus state.\n */\n isFocused(): boolean {\n if (typeof this.#focused === 'boolean') {\n return this.#focused\n }\n\n // document global can be unavailable in react native\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return globalThis.document?.visibilityState !== 'hidden'\n }\n}\n\n/**\n * Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.\n */\nexport const focusManager = new FocusManager()\n"],"mappings":";;;;;;;;;;;AAaA,IAAa,eAAb,cAAkC,aAAuB;CAMvD,cAAc;EACZ,MAAM;;;;EACN,uBAAA,QAAA,OAAe,YAAY;GAGzB,IAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;IAC5D,MAAM,iBAAiB,QAAQ;IAE/B,OAAO,iBAAiB,oBAAoB,UAAU,KAAK;IAE3D,aAAa;KAEX,OAAO,oBAAoB,oBAAoB,QAAQ;IACzD;GACF;EAEF,CAAA;CACF;CAEA,cAA8B;EAC5B,IAAI,CAAA,uBAAA,UAAC,IAAA,GACH,KAAK,iBAAA,uBAAA,QAAiB,IAAA,CAAW;CAErC;CAEA,gBAA0B;EACxB,IAAI,CAAC,KAAK,aAAa,GAAG;;GACxB,CAAA,2BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,6BAAA,KAAA,KAAA,yBAAA,KAAA,IAAgB;GAChB,uBAAA,UAAA,MAAgB,KAAA,CAAA;EAClB;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,iBAAiB,OAAsB;;EACrC,uBAAA,QAAA,MAAc,KAAA;EACd,CAAA,yBAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,2BAAA,KAAA,KAAA,uBAAA,KAAA,IAAgB;EAChB,uBAAA,UAAA,MAAgB,OAAO,YAAY;GACjC,IAAI,OAAO,YAAY,WACrB,KAAK,WAAW,OAAO;QAEvB,KAAK,QAAQ;EAEjB,CAAC,CAAA;CACH;;;;;;;;;;;;;;;;;;;CAoBA,WAAW,SAAyB;EAElC,IAAA,uBAAA,UADgB,IAAA,MLine truncated
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
{"version":3,"file":"hydration-Cq7QYAzB.d.ts","names":[],"sources":["../../src/queryObserver.ts","../../src/query.ts","../../src/mutationObserver.ts","../../src/mutationCache.ts","../../src/mutation.ts","../../src/utils.ts","../../src/queryCache.ts","../../src/queryClient.ts","../../src/retryer.ts","../../src/types.ts","../../src/hydration.ts"],"mappings":";;;KA4BK,sBAAsB,OAAO,WAChC,QAAQ,oBAAoB,OAAO;UAG3B,6BAA6B;EACrC;;;;;;;;;;;;;;;;;;;;;;cAuBW,cACX,wBACA,SAAS,cACT,QAAQ,cACR,aAAa,cACb,kBAAkB,WAAW,kBACrB,aAAa,sBAAsB,OAAO;;EA0BzC,SAAS,qBACd,cACA,QACA,OACA,YACA;EANF,YAAA,QAAQ,aACD,SAAS,qBACd,cACA,QACA,OACA,YACA;YAYM;YAIA;YAcA;;;;;;EAWV;;;;;;EAaA;;;;;;EAaA;;;;;;;;;;;;;;;EAqBA,WACE,SAAS,qBACP,cACA,QACA,OACA,YACA;;;;;;;EAoFJ,oBACE,SAAS,8BACP,cACA,QACA,OACA,YACA,aAED,oBAAoB,OAAO;;;;;;;;;;;;;EAyC9B,oBAAoB,oBAAoB,OAAO;;;;;;;EAU/C,YACE,QAAQ,oBAAoB,OAAO,SACnC,iBAAiB,WAAW,+BAC3B,oBAAoB,OAAO;;;;;;;EAgB9B,UAAU,WAAW;;;;EAOrB,mBAAmB,MAAM,cAAc,QAAQ,YAAY;;;;;;;;;;;EAc3D,aAAa,YAAW,iBAAsB,QAC5C,oBAAoB,OAAO;;;;;;;;;;;;;;;;;EAuB7B,gBACE,SAAS,qBACP,cACA,QACA,OACA,YACA,aAED,QAAQ,oBAAoB,OAAO;YA6C5B,MACR,cAAc,uBACb,QAAQ,oBAAoB,OAAO;YA6G5B,aACR,OAAO,MAAM,cAAc,QAAQ,YAAY,YAC/C,SAAS,qBACP,cACA,QACA,OACA,YACA,aAED,oBAAoB,OAAO;;;;;;EAuK9B;;EA6FA;;;;UC1xBQ,YACR,cACA,QACA,OACA,kBAAkB,WAAW;EAE7B,QAAQ;EACR,UAAU;EACV;EACA,UAAU,aAAa,cAAc,QAAQ,OAAO;EACpD,iBAAiB,aAAa,cAAc,QAAQ,OAAO;EAC3D,QAAQ,WAAW,OAAO;;;;;;UAOX,WAAW,iBAAiB,SAAS;;;;EAIpD,MAAM;;;;EAIN;;;;EAIA;;;;;EAKA,OAAO;;;;EAIP;;;;EAIA;;;;;;EAMA;;;;;EAKA,oBAAoB;;;;;EAKpB,WAAW;;;;;EAKX;;;;;;;EAOA,QAAQ;;;;;;;EAOR,aAAa;;UAGE,aACf,cACA,QACA,OACA,kBAAkB,WAAW;EAE7B,yBAAyB;EACzB,eAAe;EACf,QAAQ;EACR,SAAS,aAAa,cAAc,QAAQ;EAC5C,QAAQ;EACR,UAAU;EACV,OAAO,WAAW,OAAO;;UAGV,cACf,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW;EAE7B,UACE,SAAS,aAAa,cAAc,QAAQ,OAAO,YACnD,OAAO;;KAIC;UAEK;EACf;IAAc,WAAW;;;UAGV,aAAa;EAC5B;EACA,OAAO;EACP,iBAAiB,QAAQ;;UAGjB,eAAa;EACrB;EACA;EACA,OAAO;;UAGC;EACR;EACA,OAAO;;UAGC,gBAAc;EACtB,MAAM;EACN;EACA;EACA;;UAGQ,cAAY;EACpB;EACA,OAAO;;UAGC;EACR;;UAGQ;EACR;;UAGQ;EACR;;UAGQ,eAAe,OAAO;EAC9B;EACA,OAAO,QAAQ,WAAW,OAAO;;KAGvB,SAAO,OAAO,UACtB,mBACA,cAAY,UACZ,eAAa,UACb,cACA,mBACA,gBACA,eAAe,OAAO,UACtB,gBAAc;;;;;;;;;;;;;;;;;;;;cAuBL,MACX,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,kBACrB;;EACR,UAAU;EACV;EACA,SAAU,aAAa,cAAc,QAAQ,OAAO;EACpD,OAAO,WAAW,OAAO;EAQzB,WAAW,MAAM;EAIL,YAAA,QAAQ,YAAY,cAAc,QAAQ,OAAO;;;;MAkBzD,QAAQ;;MAKR;;;;;MAQA,WAAW,QAAQ;;EAKvB,WACE,UAAU,aAAa,cAAc,QAAQ,OAAO;YAsB5C;;EAOV,QACE,SAAS,OACT,UAAU;IAAmB;MAC5B;;;;;;EAmBH,SAAS,OAAO,QAAQ,WAAW,OAAO;;;;;;;;;;;EAc1C,OAAO,UAAU,gBAAgB;;;;;;;;EAajC;;MAOI,cAAc,WAAW,OAAO;;;;;;EASpC;;;;;EASA;;;;;;;;;EAcA;;;;;EAYA;;;;;EAQA;;;;;;;;;;;;;;;;;EA2BA;;;;;;;;;;;;;;;EA0BA,cAAc,YAAW;;EAkBzB;;EAUA;;EAUA,YAAY,UAAU;;EAYtB,eAAe,UAAU;;;;;;;;;;;EAqCzB;;;;;;;;;;;EAcA;;;;;;;;;;;EAgBM,MACJ,UAAU,aAAa,cAAc,QAAQ,OAAO,YACpD,eAAe,aAAa,gBAC3B,QAAQ;;iBA0TG,WACd,cACA,QACA,OACA,kBAAkB,UAElB,MAAM,mBACN,SAAS,aAAa,cAAc,QAAQ,OAAO;;;;;;;;;KCj4BhD,yBAAyB,OAAO,QAAQ,YAAY,oBACvD,QAAQ,uBAAuB,OAAO,QAAQ,YAAY;;;;;;;;;;;;;;;;cAoB/C,iBACX,iBACA,SAAS,cACT,mBACA,mCACQ,aACR,yBAAyB,OAAO,QAAQ,YAAY;;EAEpD,SAAU,wBAAwB,OAAO,QAAQ,YAAY;EAa3D,YAAA,QAAQ,aACR,SAAS,wBACP,OACA,QACA,YACA;YAWM;;;;;;;;;;;;;;;;;EAqBV,WACE,SAAS,wBACP,OACA,QACA,YACA;YA0BM;YAQA;;EAOV,iBACE,QAAQ,OAAO,OAAO,QAAQ,YAAY;;;;;;EAY5C,oBAAoB,uBAClB,OACA,QACA,YACA;;;;;;;;;;;;;;;;;EAqBF;;;;;;;;;;;;;;;;;;;EA2BA,OACE,WAAW,YACX,UAAU,cAAc,OAAO,QAAQ,YAAY,mBAClD,QAAQ;;;;;;;;;;;;UCxLI;;EAEf,WACE,OAAO,cACP,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,aACE,eACA,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,YACE,oBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,aACE,2BACA,OAAO,qBACP,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;UAGG,iCAAiC;EACzC;EACA,UAAU;;UAEF,mCAAmC;EAC3C;EACA,UAAU;;UAGF,yCAAyC;EACjD;EACA,UAAU;EACV,UAAU;;UAGF,2CAA2C;EACnD;EACA,UAAU;EACV,UAAU;;UAGF,kDAAkD;EAC1D;EACA,WAAW;EACX,UAAU;;UAGF,mCAAmC;EAC3C;EACA,UAAU;EACV,QAAQ;;;;;;;KAQE,2BACR,2BACA,6BACA,mCACA,qCACA,4CACA;KAEC,yBAAyB,OAAO;;;;;;;;;;;;;;;cAkBxB,sBAAsB,aAAa;;EAK3B,QAAQ;EAAR,YAAA,SAAQ;;EAQ3B,MAAM,OAAO,QAAQ,YAAY,iBAC/B,QAAQ,aACR,SAAS,gBAAgB,OAAO,QAAQ,YAAY,kBACpD,QAAQ,cAAc,OAAO,QAAQ,YAAY,mBAChD,SAAS,OAAO,QAAQ,YAAY;;EAevC,IAAI,UAAU;;EAed,OAAO,UAAU;;EAwBjB,OAAO,UAAU;;EAkBjB,QAAQ,UAAU,+BAA+B;;;;;;;;;;;EAuBjD;;;;;;;;;;;;;;EAuBA,UAAU,MAAM;;;;;;;;;;;;;;;;EAmBhB,KACE,iBACA,SAAS,cACT,kBACA,2BAEA,SAAS,kBACR,SAAS,OAAO,QAAQ,YAAY;;;;;;;;;;;;;;;;EAuBvC,QAAQ,UAAS,kBAAuB,MAAM;;EAK9C,OAAO,OAAO;;EASd,yBAAyB;;;;UChTjB,eAAe,OAAO,QAAQ,YAAY;EAClD,QAAQ;EACR;EACA,eAAe;EACf,SAAS,gBAAgB,OAAO,QAAQ,YAAY;EACpD,QAAQ,cAAc,OAAO,QAAQ,YAAY;;;;;;UAOlC,cACf,iBACA,SAAS,cACT,sBACA;;;;;EAMA,SAAS;;;;EAIT,MAAM;;;;;EAKN,OAAO;;;;EAIP;;;;EAIA,eAAe;;;;;EAKf;;;;EAIA,QAAQ;;;;EAIR,WAAW;;;;EAIX;;UAGQ,aAAa;EACrB;EACA;EACA,OAAO;;UAGC,cAAc,YAAY;EAClC;EACA;EACA,YAAY;EACZ,UAAU;;UAGF,cAAc;EACtB;EACA,MAAM;;UAGE,YAAY;EACpB;EACA,OAAO;;UAGC;EACR;;UAGQ;EACR;;KAGU,OAAO,OAAO,QAAQ,YAAY,mBAC1C,iBACA,YAAY,UACZ,aAAa,UACb,cAAc,YAAY,mBAC1B,cACA,cAAc;;;;;;;;;;;;;;;;;;cAqBL,SACX,iBACA,SAAS,cACT,sBACA,mCACQ;;EACR,OAAO,cAAc,OAAO,QAAQ,YAAY;EAChD,SAAU,gBAAgB,OAAO,QAAQ,YAAY;WAC5C;EAUP,YAAA,QAAQ,eAAeLine truncated
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
{"version":3,"file":"hydration-DwR10Hi-.d.cts","names":[],"sources":["../../src/queryObserver.ts","../../src/query.ts","../../src/mutationObserver.ts","../../src/mutationCache.ts","../../src/mutation.ts","../../src/utils.ts","../../src/queryCache.ts","../../src/queryClient.ts","../../src/retryer.ts","../../src/types.ts","../../src/hydration.ts"],"mappings":";;;KA4BK,sBAAsB,OAAO,WAChC,QAAQ,oBAAoB,OAAO;UAG3B,6BAA6B;EACrC;;;;;;;;;;;;;;;;;;;;;;cAuBW,cACX,wBACA,SAAS,cACT,QAAQ,cACR,aAAa,cACb,kBAAkB,WAAW,kBACrB,aAAa,sBAAsB,OAAO;;EA0BzC,SAAS,qBACd,cACA,QACA,OACA,YACA;EANF,YAAA,QAAQ,aACD,SAAS,qBACd,cACA,QACA,OACA,YACA;YAYM;YAIA;YAcA;;;;;;EAWV;;;;;;EAaA;;;;;;EAaA;;;;;;;;;;;;;;;EAqBA,WACE,SAAS,qBACP,cACA,QACA,OACA,YACA;;;;;;;EAoFJ,oBACE,SAAS,8BACP,cACA,QACA,OACA,YACA,aAED,oBAAoB,OAAO;;;;;;;;;;;;;EAyC9B,oBAAoB,oBAAoB,OAAO;;;;;;;EAU/C,YACE,QAAQ,oBAAoB,OAAO,SACnC,iBAAiB,WAAW,+BAC3B,oBAAoB,OAAO;;;;;;;EAgB9B,UAAU,WAAW;;;;EAOrB,mBAAmB,MAAM,cAAc,QAAQ,YAAY;;;;;;;;;;;EAc3D,aAAa,YAAW,iBAAsB,QAC5C,oBAAoB,OAAO;;;;;;;;;;;;;;;;;EAuB7B,gBACE,SAAS,qBACP,cACA,QACA,OACA,YACA,aAED,QAAQ,oBAAoB,OAAO;YA6C5B,MACR,cAAc,uBACb,QAAQ,oBAAoB,OAAO;YA6G5B,aACR,OAAO,MAAM,cAAc,QAAQ,YAAY,YAC/C,SAAS,qBACP,cACA,QACA,OACA,YACA,aAED,oBAAoB,OAAO;;;;;;EAuK9B;;EA6FA;;;;UC1xBQ,YACR,cACA,QACA,OACA,kBAAkB,WAAW;EAE7B,QAAQ;EACR,UAAU;EACV;EACA,UAAU,aAAa,cAAc,QAAQ,OAAO;EACpD,iBAAiB,aAAa,cAAc,QAAQ,OAAO;EAC3D,QAAQ,WAAW,OAAO;;;;;;UAOX,WAAW,iBAAiB,SAAS;;;;EAIpD,MAAM;;;;EAIN;;;;EAIA;;;;;EAKA,OAAO;;;;EAIP;;;;EAIA;;;;;;EAMA;;;;;EAKA,oBAAoB;;;;;EAKpB,WAAW;;;;;EAKX;;;;;;;EAOA,QAAQ;;;;;;;EAOR,aAAa;;UAGE,aACf,cACA,QACA,OACA,kBAAkB,WAAW;EAE7B,yBAAyB;EACzB,eAAe;EACf,QAAQ;EACR,SAAS,aAAa,cAAc,QAAQ;EAC5C,QAAQ;EACR,UAAU;EACV,OAAO,WAAW,OAAO;;UAGV,cACf,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW;EAE7B,UACE,SAAS,aAAa,cAAc,QAAQ,OAAO,YACnD,OAAO;;KAIC;UAEK;EACf;IAAc,WAAW;;;UAGV,aAAa;EAC5B;EACA,OAAO;EACP,iBAAiB,QAAQ;;UAGjB,eAAa;EACrB;EACA;EACA,OAAO;;UAGC;EACR;EACA,OAAO;;UAGC,gBAAc;EACtB,MAAM;EACN;EACA;EACA;;UAGQ,cAAY;EACpB;EACA,OAAO;;UAGC;EACR;;UAGQ;EACR;;UAGQ;EACR;;UAGQ,eAAe,OAAO;EAC9B;EACA,OAAO,QAAQ,WAAW,OAAO;;KAGvB,SAAO,OAAO,UACtB,mBACA,cAAY,UACZ,eAAa,UACb,cACA,mBACA,gBACA,eAAe,OAAO,UACtB,gBAAc;;;;;;;;;;;;;;;;;;;;cAuBL,MACX,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,kBACrB;;EACR,UAAU;EACV;EACA,SAAU,aAAa,cAAc,QAAQ,OAAO;EACpD,OAAO,WAAW,OAAO;EAQzB,WAAW,MAAM;EAIL,YAAA,QAAQ,YAAY,cAAc,QAAQ,OAAO;;;;MAkBzD,QAAQ;;MAKR;;;;;MAQA,WAAW,QAAQ;;EAKvB,WACE,UAAU,aAAa,cAAc,QAAQ,OAAO;YAsB5C;;EAOV,QACE,SAAS,OACT,UAAU;IAAmB;MAC5B;;;;;;EAmBH,SAAS,OAAO,QAAQ,WAAW,OAAO;;;;;;;;;;;EAc1C,OAAO,UAAU,gBAAgB;;;;;;;;EAajC;;MAOI,cAAc,WAAW,OAAO;;;;;;EASpC;;;;;EASA;;;;;;;;;EAcA;;;;;EAYA;;;;;EAQA;;;;;;;;;;;;;;;;;EA2BA;;;;;;;;;;;;;;;EA0BA,cAAc,YAAW;;EAkBzB;;EAUA;;EAUA,YAAY,UAAU;;EAYtB,eAAe,UAAU;;;;;;;;;;;EAqCzB;;;;;;;;;;;EAcA;;;;;;;;;;;EAgBM,MACJ,UAAU,aAAa,cAAc,QAAQ,OAAO,YACpD,eAAe,aAAa,gBAC3B,QAAQ;;iBA0TG,WACd,cACA,QACA,OACA,kBAAkB,UAElB,MAAM,mBACN,SAAS,aAAa,cAAc,QAAQ,OAAO;;;;;;;;;KCj4BhD,yBAAyB,OAAO,QAAQ,YAAY,oBACvD,QAAQ,uBAAuB,OAAO,QAAQ,YAAY;;;;;;;;;;;;;;;;cAoB/C,iBACX,iBACA,SAAS,cACT,mBACA,mCACQ,aACR,yBAAyB,OAAO,QAAQ,YAAY;;EAEpD,SAAU,wBAAwB,OAAO,QAAQ,YAAY;EAa3D,YAAA,QAAQ,aACR,SAAS,wBACP,OACA,QACA,YACA;YAWM;;;;;;;;;;;;;;;;;EAqBV,WACE,SAAS,wBACP,OACA,QACA,YACA;YA0BM;YAQA;;EAOV,iBACE,QAAQ,OAAO,OAAO,QAAQ,YAAY;;;;;;EAY5C,oBAAoB,uBAClB,OACA,QACA,YACA;;;;;;;;;;;;;;;;;EAqBF;;;;;;;;;;;;;;;;;;;EA2BA,OACE,WAAW,YACX,UAAU,cAAc,OAAO,QAAQ,YAAY,mBAClD,QAAQ;;;;;;;;;;;;UCxLI;;EAEf,WACE,OAAO,cACP,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,aACE,eACA,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,YACE,oBACA,UAAU,qCACV,SAAS,4BACN;;EAEL,aACE,2BACA,OAAO,qBACP,oBACA,yBACA,UAAU,qCACV,SAAS,4BACN;;UAGG,iCAAiC;EACzC;EACA,UAAU;;UAEF,mCAAmC;EAC3C;EACA,UAAU;;UAGF,yCAAyC;EACjD;EACA,UAAU;EACV,UAAU;;UAGF,2CAA2C;EACnD;EACA,UAAU;EACV,UAAU;;UAGF,kDAAkD;EAC1D;EACA,WAAW;EACX,UAAU;;UAGF,mCAAmC;EAC3C;EACA,UAAU;EACV,QAAQ;;;;;;;KAQE,2BACR,2BACA,6BACA,mCACA,qCACA,4CACA;KAEC,yBAAyB,OAAO;;;;;;;;;;;;;;;cAkBxB,sBAAsB,aAAa;;EAK3B,QAAQ;EAAR,YAAA,SAAQ;;EAQ3B,MAAM,OAAO,QAAQ,YAAY,iBAC/B,QAAQ,aACR,SAAS,gBAAgB,OAAO,QAAQ,YAAY,kBACpD,QAAQ,cAAc,OAAO,QAAQ,YAAY,mBAChD,SAAS,OAAO,QAAQ,YAAY;;EAevC,IAAI,UAAU;;EAed,OAAO,UAAU;;EAwBjB,OAAO,UAAU;;EAkBjB,QAAQ,UAAU,+BAA+B;;;;;;;;;;;EAuBjD;;;;;;;;;;;;;;EAuBA,UAAU,MAAM;;;;;;;;;;;;;;;;EAmBhB,KACE,iBACA,SAAS,cACT,kBACA,2BAEA,SAAS,kBACR,SAAS,OAAO,QAAQ,YAAY;;;;;;;;;;;;;;;;EAuBvC,QAAQ,UAAS,kBAAuB,MAAM;;EAK9C,OAAO,OAAO;;EASd,yBAAyB;;;;UChTjB,eAAe,OAAO,QAAQ,YAAY;EAClD,QAAQ;EACR;EACA,eAAe;EACf,SAAS,gBAAgB,OAAO,QAAQ,YAAY;EACpD,QAAQ,cAAc,OAAO,QAAQ,YAAY;;;;;;UAOlC,cACf,iBACA,SAAS,cACT,sBACA;;;;;EAMA,SAAS;;;;EAIT,MAAM;;;;;EAKN,OAAO;;;;EAIP;;;;EAIA,eAAe;;;;;EAKf;;;;EAIA,QAAQ;;;;EAIR,WAAW;;;;EAIX;;UAGQ,aAAa;EACrB;EACA;EACA,OAAO;;UAGC,cAAc,YAAY;EAClC;EACA;EACA,YAAY;EACZ,UAAU;;UAGF,cAAc;EACtB;EACA,MAAM;;UAGE,YAAY;EACpB;EACA,OAAO;;UAGC;EACR;;UAGQ;EACR;;KAGU,OAAO,OAAO,QAAQ,YAAY,mBAC1C,iBACA,YAAY,UACZ,aAAa,UACb,cAAc,YAAY,mBAC1B,cACA,cAAc;;;;;;;;;;;;;;;;;;cAqBL,SACX,iBACA,SAAS,cACT,sBACA,mCACQ;;EACR,OAAO,cAAc,OAAO,QAAQ,YAAY;EAChD,SAAU,gBAAgB,OAAO,QAAQ,YAAY;WAC5C;EAUP,YAAA,QAAQ,eAALine truncated
+178
View File
@@ -0,0 +1,178 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_utils = require("./utils.cjs");
//#region src/hydration.ts
function tryResolveSync(promise) {
var _thenResult$catch;
let data;
const thenResult = promise.then((result) => {
data = result;
return result;
}, require_utils.noop);
thenResult === null || thenResult === void 0 || (_thenResult$catch = thenResult.catch) === null || _thenResult$catch === void 0 || _thenResult$catch.call(thenResult, require_utils.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 _query$promise;
const promise = (_query$promise = query.promise) === null || _query$promise === void 0 ? void 0 : _query$promise.then(serializeData).catch((error) => {
if ((shouldRedactErrors === null || shouldRedactErrors === void 0 ? void 0 : shouldRedactErrors(error)) === false) return Promise.reject(error);
if (process.env.NODE_ENV !== "production") console.error(`A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`);
return Promise.reject(/* @__PURE__ */ new Error("redacted"));
});
promise === null || promise === void 0 || promise.catch(require_utils.noop);
return promise;
}
/**
* Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot. Note that most query config (e.g.
* `queryFn`, `staleTime`) is not dehydrated but instead meant to be configured again when consuming the
* de/rehydrated data, typically with `useQuery` on the client. If the query is still `pending`, its in-flight
* promise is dehydrated too so it can be resumed on the other side instead of re-fetched.
* @param query - The query to dehydrate.
* @param serializeData - Optional transform applied to `query.state.data` before it is included in the snapshot.
* @param shouldRedactErrors - Optional predicate; if it returns `false` for the promise's rejection error, that
* error is kept as-is instead of being redacted.
*/
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 }
};
}
/**
* The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only dehydrates mutations that are
* currently paused (e.g. paused by `networkMode` while offline).
*/
function defaultShouldDehydrateMutation(mutation) {
return mutation.state.isPaused;
}
/**
* The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only dehydrates queries whose status is
* `'success'`.
*/
function defaultShouldDehydrateQuery(query) {
return query.state.status === "success";
}
/**
* Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain, serializable `DehydratedState`,
* typically to embed in server-rendered markup and later restore into a client-side `QueryClient` via `hydrate`.
* Which queries/mutations are included, and how their data/errors are transformed, is controlled by `options`,
* falling back to the client's `dehydrate` default options, and finally to `defaultShouldDehydrateQuery` /
* `defaultShouldDehydrateMutation`.
* @example
* ```ts
* const queryClient = new QueryClient()
*
* await queryClient.prefetchQuery({
* queryKey: ['posts'],
* queryFn: getPosts,
* })
*
* const dehydratedState = dehydrate(queryClient)
* ```
*/
function dehydrate(client, options = {}) {
var _client$getDefaultOpt, _client$getDefaultOpt2, _client$getDefaultOpt3, _client$getDefaultOpt4;
const filterMutation = options.shouldDehydrateMutation ?? ((_client$getDefaultOpt = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt === void 0 ? void 0 : _client$getDefaultOpt.shouldDehydrateMutation) ?? defaultShouldDehydrateMutation;
const mutations = client.getMutationCache().getAll().flatMap((mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []);
const filterQuery = options.shouldDehydrateQuery ?? ((_client$getDefaultOpt2 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt2 === void 0 ? void 0 : _client$getDefaultOpt2.shouldDehydrateQuery) ?? defaultShouldDehydrateQuery;
const shouldRedactErrors = options.shouldRedactErrors ?? ((_client$getDefaultOpt3 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt3 === void 0 ? void 0 : _client$getDefaultOpt3.shouldRedactErrors);
const serializeData = options.serializeData ?? ((_client$getDefaultOpt4 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt4 === void 0 ? void 0 : _client$getDefaultOpt4.serializeData);
return {
mutations,
queries: client.getQueryCache().getAll().flatMap((query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : [])
};
}
/**
* Restores a `DehydratedState` (as produced by `dehydrate`) into a `QueryClient`'s cache, typically to seed the
* client with data already fetched on the server. `mutations` and `queries` are each optional on `dehydratedState`.
* Queries not yet in the cache are built from the dehydrated snapshot; queries that already exist are only updated
* when the dehydrated data is newer than what's already cached. Newly built queries have their `fetchStatus` reset
* to `'idle'` so they don't hydrate stuck in a fetching state. If a dehydrated query still had an in-flight
* promise, it is resumed via `query.fetch()` (reusing that promise as `initialPromise`) rather than re-invoking
* `queryFn`.
* @example
* ```ts
* // dehydratedState was produced by `dehydrate` on the server
* // and sent to the client, e.g. embedded in server-rendered markup.
* const queryClient = new QueryClient()
*
* hydrate(queryClient, dehydratedState)
* ```
*/
function hydrate(client, dehydratedState, options) {
var _options$defaultOptio, _client$getDefaultOpt5, _dehydratedState$muta, _dehydratedState$quer;
const mutationCache = client.getMutationCache();
const queryCache = client.getQueryCache();
const deserializeData = (options === null || options === void 0 || (_options$defaultOptio = options.defaultOptions) === null || _options$defaultOptio === void 0 ? void 0 : _options$defaultOptio.deserializeData) ?? ((_client$getDefaultOpt5 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt5 === void 0 ? void 0 : _client$getDefaultOpt5.deserializeData);
(_dehydratedState$muta = dehydratedState.mutations) === null || _dehydratedState$muta === void 0 || _dehydratedState$muta.forEach(({ state, ...mutationOptions }) => {
var _client$getDefaultOpt6, _options$defaultOptio2;
mutationCache.build(client, {
...(_client$getDefaultOpt6 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt6 === void 0 ? void 0 : _client$getDefaultOpt6.mutations,
...options === null || options === void 0 || (_options$defaultOptio2 = options.defaultOptions) === null || _options$defaultOptio2 === void 0 ? void 0 : _options$defaultOptio2.mutations,
...mutationOptions
}, state);
});
(_dehydratedState$quer = dehydratedState.queries) === null || _dehydratedState$quer === void 0 || _dehydratedState$quer.forEach(({ queryKey, state, queryHash, meta, promise, dehydratedAt, queryType }) => {
const syncData = promise ? tryResolveSync(promise) : void 0;
const rawData = state.data === void 0 ? syncData === null || syncData === void 0 ? 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 || query === void 0 ? void 0 : query.state.status) === "pending";
const existingQueryIsFetching = (query === null || query === void 0 ? 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 {
var _client$getDefaultOpt7, _options$defaultOptio3;
query = queryCache.build(client, {
...(_client$getDefaultOpt7 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt7 === void 0 ? void 0 : _client$getDefaultOpt7.queries,
...options === null || options === void 0 || (_options$defaultOptio3 = options.defaultOptions) === null || _options$defaultOptio3 === void 0 ? void 0 : _options$defaultOptio3.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(require_utils.noop);
});
}
//#endregion
exports.defaultShouldDehydrateMutation = defaultShouldDehydrateMutation;
exports.defaultShouldDehydrateQuery = defaultShouldDehydrateQuery;
exports.dehydrate = dehydrate;
exports.dehydrateQuery = dehydrateQuery;
exports.hydrate = hydrate;
//# sourceMappingURL=hydration.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"hydration.cjs","names":["noop"],"sources":["../../src/hydration.ts"],"sourcesContent":["import { noop } from './utils'\nimport type {\n DefaultError,\n MutationKey,\n MutationMeta,\n MutationOptions,\n MutationScope,\n QueryKey,\n QueryMeta,\n QueryOptions,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Query, QueryState } from './query'\nimport type { Mutation, MutationState } from './mutation'\n\n// TYPES\ntype TransformerFn = (data: any) => any\n\nfunction tryResolveSync(promise: PromiseLike<unknown>) {\n let data: unknown\n\n const thenResult = promise.then((result) => {\n data = result\n return result\n }, noop) as Promise<unknown> | undefined\n\n // .catch can be unavailable on certain kinds of thenable's\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n thenResult?.catch?.(noop)\n\n if (data !== undefined) {\n return { data }\n }\n\n return undefined\n}\n\n/**\n * Options for `dehydrate`, controlling which queries/mutations are included in the resulting `DehydratedState` and\n * how their data/errors are transformed before being serialized (e.g. for embedding in server-rendered markup).\n */\nexport interface DehydrateOptions {\n /** Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. */\n serializeData?: TransformerFn\n /** Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. */\n shouldDehydrateMutation?: (mutation: Mutation) => boolean\n /** Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. */\n shouldDehydrateQuery?: (query: Query) => boolean\n /**\n * Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted\n * (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the\n * given error, in which case the original error is kept.\n */\n shouldRedactErrors?: (error: unknown) => boolean\n}\n\n/**\n * Options for `hydrate`, controlling the default options applied to queries/mutations restored from a\n * `DehydratedState`, and how to reverse any transformation applied by `DehydrateOptions.serializeData`.\n */\nexport interface HydrateOptions {\n defaultOptions?: {\n /** Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. */\n deserializeData?: TransformerFn\n /** Default options merged into every query restored from the dehydrated state. */\n queries?: QueryOptions\n /** Default options merged into every mutation restored from the dehydrated state. */\n mutations?: MutationOptions<unknown, DefaultError, unknown, unknown>\n }\n}\n\ninterface DehydratedMutation {\n mutationKey?: MutationKey\n state: MutationState\n meta?: MutationMeta\n scope?: MutationScope\n}\n\ninterface DehydratedQuery {\n queryHash: string\n queryKey: QueryKey\n state: QueryState\n dehydratedAt: number\n promise?: Promise<unknown>\n meta?: QueryMeta\n queryType?: 'infinite'\n}\n\n/**\n * A serializable snapshot of a `QueryClient`'s cache, as produced by `dehydrate` and consumed by `hydrate`. Typically\n * transported from server to client (e.g. embedded in server-rendered markup) to seed the client's cache with data\n * that has already been fetched, avoiding a redundant fetch on the client.\n */\nexport interface DehydratedState {\n mutations: Array<DehydratedMutation>\n queries: Array<DehydratedQuery>\n}\n\n// FUNCTIONS\n\nfunction dehydrateMutation(mutation: Mutation): DehydratedMutation {\n return {\n mutationKey: mutation.options.mutationKey,\n state: mutation.state,\n ...(mutation.options.scope && { scope: mutation.options.scope }),\n ...(mutation.meta && { meta: mutation.meta }),\n }\n}\n\nfunction dehydratePromise(\n query: Query,\n serializeData?: TransformerFn,\n shouldRedactErrors?: (error: unknown) => boolean,\n): Promise<unknown> | undefined {\n const promise = query.promise?.then(serializeData).catch((error) => {\n if (shouldRedactErrors?.(error) === false) {\n // Reject original error if it should not be redacted\n return Promise.reject(error)\n }\n // If not in production, log original error before rejecting redacted error\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,\n )\n }\n return Promise.reject(new Error('redacted'))\n })\n\n // Avoid unhandled promise rejections\n // We need the promise we dehydrate to reject to get the correct result into\n // the query cache, but we also want to avoid unhandled promise rejections\n // in whatever environment the prefetches are happening in.\n promise?.catch(noop)\n\n return promise\n}\n\n/**\n * Line truncated
+2
View File
@@ -0,0 +1,2 @@
import { a as defaultShouldDehydrateQuery, c as hydrate, i as defaultShouldDehydrateMutation, n as DehydratedState, o as dehydrate, r as HydrateOptions, s as dehydrateQuery, t as DehydrateOptions } from "./hydration-DwR10Hi-.cjs";
export { DehydrateOptions, DehydratedState, HydrateOptions, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, hydrate };
+2
View File
@@ -0,0 +1,2 @@
import { a as defaultShouldDehydrateQuery, c as hydrate, i as defaultShouldDehydrateMutation, n as DehydratedState, o as dehydrate, r as HydrateOptions, s as dehydrateQuery, t as DehydrateOptions } from "./hydration-Cq7QYAzB.js";
export { DehydrateOptions, DehydratedState, HydrateOptions, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, hydrate };
+173
View File
@@ -0,0 +1,173 @@
import { noop } from "./utils.js";
//#region src/hydration.ts
function tryResolveSync(promise) {
var _thenResult$catch;
let data;
const thenResult = promise.then((result) => {
data = result;
return result;
}, noop);
thenResult === null || thenResult === void 0 || (_thenResult$catch = thenResult.catch) === null || _thenResult$catch === void 0 || _thenResult$catch.call(thenResult, 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 _query$promise;
const promise = (_query$promise = query.promise) === null || _query$promise === void 0 ? void 0 : _query$promise.then(serializeData).catch((error) => {
if ((shouldRedactErrors === null || shouldRedactErrors === void 0 ? void 0 : shouldRedactErrors(error)) === false) return Promise.reject(error);
if (process.env.NODE_ENV !== "production") console.error(`A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`);
return Promise.reject(/* @__PURE__ */ new Error("redacted"));
});
promise === null || promise === void 0 || promise.catch(noop);
return promise;
}
/**
* Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot. Note that most query config (e.g.
* `queryFn`, `staleTime`) is not dehydrated but instead meant to be configured again when consuming the
* de/rehydrated data, typically with `useQuery` on the client. If the query is still `pending`, its in-flight
* promise is dehydrated too so it can be resumed on the other side instead of re-fetched.
* @param query - The query to dehydrate.
* @param serializeData - Optional transform applied to `query.state.data` before it is included in the snapshot.
* @param shouldRedactErrors - Optional predicate; if it returns `false` for the promise's rejection error, that
* error is kept as-is instead of being redacted.
*/
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 }
};
}
/**
* The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only dehydrates mutations that are
* currently paused (e.g. paused by `networkMode` while offline).
*/
function defaultShouldDehydrateMutation(mutation) {
return mutation.state.isPaused;
}
/**
* The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only dehydrates queries whose status is
* `'success'`.
*/
function defaultShouldDehydrateQuery(query) {
return query.state.status === "success";
}
/**
* Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain, serializable `DehydratedState`,
* typically to embed in server-rendered markup and later restore into a client-side `QueryClient` via `hydrate`.
* Which queries/mutations are included, and how their data/errors are transformed, is controlled by `options`,
* falling back to the client's `dehydrate` default options, and finally to `defaultShouldDehydrateQuery` /
* `defaultShouldDehydrateMutation`.
* @example
* ```ts
* const queryClient = new QueryClient()
*
* await queryClient.prefetchQuery({
* queryKey: ['posts'],
* queryFn: getPosts,
* })
*
* const dehydratedState = dehydrate(queryClient)
* ```
*/
function dehydrate(client, options = {}) {
var _client$getDefaultOpt, _client$getDefaultOpt2, _client$getDefaultOpt3, _client$getDefaultOpt4;
const filterMutation = options.shouldDehydrateMutation ?? ((_client$getDefaultOpt = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt === void 0 ? void 0 : _client$getDefaultOpt.shouldDehydrateMutation) ?? defaultShouldDehydrateMutation;
const mutations = client.getMutationCache().getAll().flatMap((mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []);
const filterQuery = options.shouldDehydrateQuery ?? ((_client$getDefaultOpt2 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt2 === void 0 ? void 0 : _client$getDefaultOpt2.shouldDehydrateQuery) ?? defaultShouldDehydrateQuery;
const shouldRedactErrors = options.shouldRedactErrors ?? ((_client$getDefaultOpt3 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt3 === void 0 ? void 0 : _client$getDefaultOpt3.shouldRedactErrors);
const serializeData = options.serializeData ?? ((_client$getDefaultOpt4 = client.getDefaultOptions().dehydrate) === null || _client$getDefaultOpt4 === void 0 ? void 0 : _client$getDefaultOpt4.serializeData);
return {
mutations,
queries: client.getQueryCache().getAll().flatMap((query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : [])
};
}
/**
* Restores a `DehydratedState` (as produced by `dehydrate`) into a `QueryClient`'s cache, typically to seed the
* client with data already fetched on the server. `mutations` and `queries` are each optional on `dehydratedState`.
* Queries not yet in the cache are built from the dehydrated snapshot; queries that already exist are only updated
* when the dehydrated data is newer than what's already cached. Newly built queries have their `fetchStatus` reset
* to `'idle'` so they don't hydrate stuck in a fetching state. If a dehydrated query still had an in-flight
* promise, it is resumed via `query.fetch()` (reusing that promise as `initialPromise`) rather than re-invoking
* `queryFn`.
* @example
* ```ts
* // dehydratedState was produced by `dehydrate` on the server
* // and sent to the client, e.g. embedded in server-rendered markup.
* const queryClient = new QueryClient()
*
* hydrate(queryClient, dehydratedState)
* ```
*/
function hydrate(client, dehydratedState, options) {
var _options$defaultOptio, _client$getDefaultOpt5, _dehydratedState$muta, _dehydratedState$quer;
const mutationCache = client.getMutationCache();
const queryCache = client.getQueryCache();
const deserializeData = (options === null || options === void 0 || (_options$defaultOptio = options.defaultOptions) === null || _options$defaultOptio === void 0 ? void 0 : _options$defaultOptio.deserializeData) ?? ((_client$getDefaultOpt5 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt5 === void 0 ? void 0 : _client$getDefaultOpt5.deserializeData);
(_dehydratedState$muta = dehydratedState.mutations) === null || _dehydratedState$muta === void 0 || _dehydratedState$muta.forEach(({ state, ...mutationOptions }) => {
var _client$getDefaultOpt6, _options$defaultOptio2;
mutationCache.build(client, {
...(_client$getDefaultOpt6 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt6 === void 0 ? void 0 : _client$getDefaultOpt6.mutations,
...options === null || options === void 0 || (_options$defaultOptio2 = options.defaultOptions) === null || _options$defaultOptio2 === void 0 ? void 0 : _options$defaultOptio2.mutations,
...mutationOptions
}, state);
});
(_dehydratedState$quer = dehydratedState.queries) === null || _dehydratedState$quer === void 0 || _dehydratedState$quer.forEach(({ queryKey, state, queryHash, meta, promise, dehydratedAt, queryType }) => {
const syncData = promise ? tryResolveSync(promise) : void 0;
const rawData = state.data === void 0 ? syncData === null || syncData === void 0 ? 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 || query === void 0 ? void 0 : query.state.status) === "pending";
const existingQueryIsFetching = (query === null || query === void 0 ? 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 {
var _client$getDefaultOpt7, _options$defaultOptio3;
query = queryCache.build(client, {
...(_client$getDefaultOpt7 = client.getDefaultOptions().hydrate) === null || _client$getDefaultOpt7 === void 0 ? void 0 : _client$getDefaultOpt7.queries,
...options === null || options === void 0 || (_options$defaultOptio3 = options.defaultOptions) === null || _options$defaultOptio3 === void 0 ? void 0 : _options$defaultOptio3.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);
});
}
//#endregion
export { defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, hydrate };
//# sourceMappingURL=hydration.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"hydration.js","names":[],"sources":["../../src/hydration.ts"],"sourcesContent":["import { noop } from './utils'\nimport type {\n DefaultError,\n MutationKey,\n MutationMeta,\n MutationOptions,\n MutationScope,\n QueryKey,\n QueryMeta,\n QueryOptions,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Query, QueryState } from './query'\nimport type { Mutation, MutationState } from './mutation'\n\n// TYPES\ntype TransformerFn = (data: any) => any\n\nfunction tryResolveSync(promise: PromiseLike<unknown>) {\n let data: unknown\n\n const thenResult = promise.then((result) => {\n data = result\n return result\n }, noop) as Promise<unknown> | undefined\n\n // .catch can be unavailable on certain kinds of thenable's\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n thenResult?.catch?.(noop)\n\n if (data !== undefined) {\n return { data }\n }\n\n return undefined\n}\n\n/**\n * Options for `dehydrate`, controlling which queries/mutations are included in the resulting `DehydratedState` and\n * how their data/errors are transformed before being serialized (e.g. for embedding in server-rendered markup).\n */\nexport interface DehydrateOptions {\n /** Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. */\n serializeData?: TransformerFn\n /** Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. */\n shouldDehydrateMutation?: (mutation: Mutation) => boolean\n /** Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. */\n shouldDehydrateQuery?: (query: Query) => boolean\n /**\n * Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted\n * (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the\n * given error, in which case the original error is kept.\n */\n shouldRedactErrors?: (error: unknown) => boolean\n}\n\n/**\n * Options for `hydrate`, controlling the default options applied to queries/mutations restored from a\n * `DehydratedState`, and how to reverse any transformation applied by `DehydrateOptions.serializeData`.\n */\nexport interface HydrateOptions {\n defaultOptions?: {\n /** Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. */\n deserializeData?: TransformerFn\n /** Default options merged into every query restored from the dehydrated state. */\n queries?: QueryOptions\n /** Default options merged into every mutation restored from the dehydrated state. */\n mutations?: MutationOptions<unknown, DefaultError, unknown, unknown>\n }\n}\n\ninterface DehydratedMutation {\n mutationKey?: MutationKey\n state: MutationState\n meta?: MutationMeta\n scope?: MutationScope\n}\n\ninterface DehydratedQuery {\n queryHash: string\n queryKey: QueryKey\n state: QueryState\n dehydratedAt: number\n promise?: Promise<unknown>\n meta?: QueryMeta\n queryType?: 'infinite'\n}\n\n/**\n * A serializable snapshot of a `QueryClient`'s cache, as produced by `dehydrate` and consumed by `hydrate`. Typically\n * transported from server to client (e.g. embedded in server-rendered markup) to seed the client's cache with data\n * that has already been fetched, avoiding a redundant fetch on the client.\n */\nexport interface DehydratedState {\n mutations: Array<DehydratedMutation>\n queries: Array<DehydratedQuery>\n}\n\n// FUNCTIONS\n\nfunction dehydrateMutation(mutation: Mutation): DehydratedMutation {\n return {\n mutationKey: mutation.options.mutationKey,\n state: mutation.state,\n ...(mutation.options.scope && { scope: mutation.options.scope }),\n ...(mutation.meta && { meta: mutation.meta }),\n }\n}\n\nfunction dehydratePromise(\n query: Query,\n serializeData?: TransformerFn,\n shouldRedactErrors?: (error: unknown) => boolean,\n): Promise<unknown> | undefined {\n const promise = query.promise?.then(serializeData).catch((error) => {\n if (shouldRedactErrors?.(error) === false) {\n // Reject original error if it should not be redacted\n return Promise.reject(error)\n }\n // If not in production, log original error before rejecting redacted error\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,\n )\n }\n return Promise.reject(new Error('redacted'))\n })\n\n // Avoid unhandled promise rejections\n // We need the promise we dehydrate to reject to get the correct result into\n // the query cache, but we also want to avoid unhandled promise rejections\n // in whatever environment the prefetches are happening in.\n promise?.catch(noop)\n\n return promise\n}\n\n/**\n * DehydraLine truncated
+61
View File
@@ -0,0 +1,61 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_timeoutManager = require("./timeoutManager.cjs");
const require_utils = require("./utils.cjs");
const require_environmentManager = require("./environmentManager.cjs");
const require_focusManager = require("./focusManager.cjs");
const require_hydration = require("./hydration.cjs");
const require_notifyManager = require("./notifyManager.cjs");
const require_onlineManager = require("./onlineManager.cjs");
const require_retryer = require("./retryer.cjs");
const require_query = require("./query.cjs");
const require_queryObserver = require("./queryObserver.cjs");
const require_infiniteQueryObserver = require("./infiniteQueryObserver.cjs");
const require_mutation = require("./mutation.cjs");
const require_mutationCache = require("./mutationCache.cjs");
const require_mutationObserver = require("./mutationObserver.cjs");
const require_queriesObserver = require("./queriesObserver.cjs");
const require_queryCache = require("./queryCache.cjs");
const require_queryClient = require("./queryClient.cjs");
const require_streamedQuery = require("./streamedQuery.cjs");
const require_types = require("./types.cjs");
//#region src/index.ts
/* istanbul ignore file */
//#endregion
exports.CancelledError = require_retryer.CancelledError;
exports.InfiniteQueryObserver = require_infiniteQueryObserver.InfiniteQueryObserver;
exports.Mutation = require_mutation.Mutation;
exports.MutationCache = require_mutationCache.MutationCache;
exports.MutationObserver = require_mutationObserver.MutationObserver;
exports.QueriesObserver = require_queriesObserver.QueriesObserver;
exports.Query = require_query.Query;
exports.QueryCache = require_queryCache.QueryCache;
exports.QueryClient = require_queryClient.QueryClient;
exports.QueryObserver = require_queryObserver.QueryObserver;
exports.dataTagErrorSymbol = require_types.dataTagErrorSymbol;
exports.dataTagSymbol = require_types.dataTagSymbol;
exports.defaultScheduler = require_notifyManager.defaultScheduler;
exports.defaultShouldDehydrateMutation = require_hydration.defaultShouldDehydrateMutation;
exports.defaultShouldDehydrateQuery = require_hydration.defaultShouldDehydrateQuery;
exports.dehydrate = require_hydration.dehydrate;
exports.dehydrateQuery = require_hydration.dehydrateQuery;
exports.environmentManager = require_environmentManager.environmentManager;
exports.experimental_streamedQuery = require_streamedQuery.streamedQuery;
exports.focusManager = require_focusManager.focusManager;
exports.hashKey = require_utils.hashKey;
exports.hydrate = require_hydration.hydrate;
exports.isCancelledError = require_retryer.isCancelledError;
exports.isServer = require_utils.isServer;
exports.keepPreviousData = require_utils.keepPreviousData;
exports.matchMutation = require_utils.matchMutation;
exports.matchQuery = require_utils.matchQuery;
exports.noop = require_utils.noop;
exports.notifyManager = require_notifyManager.notifyManager;
exports.onlineManager = require_onlineManager.onlineManager;
exports.partialMatchKey = require_utils.partialMatchKey;
exports.replaceEqualDeep = require_utils.replaceEqualDeep;
exports.shouldThrowError = require_utils.shouldThrowError;
exports.skipToken = require_utils.skipToken;
exports.timeoutManager = require_timeoutManager.timeoutManager;
exports.unsetMarker = require_types.unsetMarker;
//# sourceMappingURL=index.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport { focusManager } from './focusManager'\nexport type { FocusManager } from './focusManager'\nexport { environmentManager } from './environmentManager'\nexport {\n defaultShouldDehydrateMutation,\n defaultShouldDehydrateQuery,\n dehydrate,\n dehydrateQuery,\n hydrate,\n} from './hydration'\nexport { InfiniteQueryObserver } from './infiniteQueryObserver'\nexport { MutationCache } from './mutationCache'\nexport type { MutationCacheNotifyEvent } from './mutationCache'\nexport { MutationObserver } from './mutationObserver'\nexport { defaultScheduler, notifyManager } from './notifyManager'\nexport { onlineManager } from './onlineManager'\nexport type { OnlineManager } from './onlineManager'\nexport { QueriesObserver } from './queriesObserver'\nexport { QueryCache } from './queryCache'\nexport type { QueryCacheNotifyEvent } from './queryCache'\nexport { QueryClient } from './queryClient'\nexport { QueryObserver } from './queryObserver'\nexport { CancelledError, isCancelledError } from './retryer'\nexport {\n timeoutManager,\n type ManagedTimerId,\n type TimeoutCallback,\n type TimeoutManager,\n type TimeoutProvider,\n} from './timeoutManager'\nexport {\n hashKey,\n isServer,\n keepPreviousData,\n matchMutation,\n matchQuery,\n noop,\n partialMatchKey,\n replaceEqualDeep,\n shouldThrowError,\n skipToken,\n} from './utils'\nexport type { MutationFilters, QueryFilters, SkipToken, Updater } from './utils'\n\nexport { streamedQuery as experimental_streamedQuery } from './streamedQuery'\n\n// Types\nexport type {\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from './hydration'\nexport { Mutation } from './mutation'\nexport type { MutationState } from './mutation'\nexport type { MutationCacheConfig } from './mutationCache'\nexport type { QueriesObserverOptions } from './queriesObserver'\nexport { Query } from './query'\nexport type { QueryState } from './query'\nexport type { QueryCacheConfig } from './queryCache'\nexport * from './types'\n"],"mappings":""}
+10
View File
@@ -0,0 +1,10 @@
import { environmentManager } from "./environmentManager.cjs";
import { FocusManager, focusManager } from "./focusManager.cjs";
import { $ as MutationObserverBaseResult, $n as Query, $t as CancelledError, A as InfiniteData, An as noop, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dn as keepPreviousData, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gn as MutationCacheConfig, Gt as StaleTime, H as InitialDataFunction, Hn as MutationState, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, In as shouldThrowError, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kn as MutationCacheNotifyEvent, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Ln as skipToken, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nn as replaceEqualDeep, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, On as matchMutation, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tn as isServer, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vn as Mutation, Vt as Register, W as InvalidateOptions, Wn as MutationCache, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, a as defaultShouldDehydrateQuery, an as isCancelledError, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, c as hydrate, cn as QueryCacheConfig, ct as MutationStatus, d as DataTag, dn as MutationFilters, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, fn as QueryFilters, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, hn as Updater, ht as Override, i as defaultShouldDehydrateMutation, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jn as partialMatchKey, jt as QueryObserverPendingResult, k as InferErrorFromTag, kn as matchQuery, kt as QueryObserverLoadingResult, l as AnyDataTag, ln as QueryCacheNotifyEvent, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mn as SkipToken, mt as OmitKeyof, n as DehydratedState, nt as MutationObserverLoadingResult, o as dehydrate, on as QueryClient, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qn as MutationObserver, qt as ThrowOnError, r as HydrateOptions, rr as QueryObserver, rt as MutationObserverOptions, s as dehydrateQuery, sn as QueryCache, st as MutationScope, t as DehydrateOptions, tr as QueryState, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xn as hashKey, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-DwR10Hi-.cjs";
import { InfiniteQueryObserver } from "./infiniteQueryObserver.cjs";
import { defaultScheduler, notifyManager } from "./notifyManager.cjs";
import { OnlineManager, onlineManager } from "./onlineManager.cjs";
import { QueriesObserver, QueriesObserverOptions } from "./queriesObserver.cjs";
import { ManagedTimerId, TimeoutCallback, TimeoutManager, TimeoutProvider, timeoutManager } from "./timeoutManager.cjs";
import { streamedQuery } from "./streamedQuery.cjs";
export { AnyDataTag, CancelOptions, CancelledError, DataTag, DefaultError, DefaultOptions, DefaultedInfiniteQueryObserverOptions, DefaultedQueryObserverOptions, DefinedInfiniteQueryObserverResult, DefinedQueryObserverResult, type DehydrateOptions, type DehydratedState, DistributiveOmit, EnsureInfiniteQueryDataOptions, EnsureQueryDataOptions, FetchInfiniteQueryOptions, FetchNextPageOptions, FetchPreviousPageOptions, FetchQueryOptions, FetchStatus, type FocusManager, GetNextPageParamFunction, GetPreviousPageParamFunction, type HydrateOptions, InferDataFromTag, InferErrorFromTag, InfiniteData, InfiniteQueryExecuteOptions, InfiniteQueryObserver, InfiniteQueryObserverBaseResult, InfiniteQueryObserverLoadingErrorResult, InfiniteQueryObserverLoadingResult, InfiniteQueryObserverOptions, InfiniteQueryObserverPendingResult, InfiniteQueryObserverPlaceholderResult, InfiniteQueryObserverRefetchErrorResult, InfiniteQueryObserverResult, InfiniteQueryObserverSuccessResult, InfiniteQueryPageParamsOptions, InitialDataFunction, InitialPageParam, InvalidateOptions, InvalidateQueryFilters, type ManagedTimerId, MutateFunction, MutateFunctionRest, MutateOptions, Mutation, MutationCache, type MutationCacheConfig, type MutationCacheNotifyEvent, type MutationFilters, MutationFunction, MutationFunctionContext, MutationKey, MutationMeta, MutationObserver, MutationObserverBaseResult, MutationObserverErrorResult, MutationObserverIdleResult, MutationObserverLoadingResult, MutationObserverOptions, MutationObserverResult, MutationObserverSuccessResult, MutationOptions, MutationScope, type MutationState, MutationStatus, NetworkMode, NonUndefinedGuard, NotifyEvent, NotifyEventType, NotifyOnChangeProps, OmitKeyof, type OnlineManager, Override, PlaceholderDataFunction, QueriesObserver, type QueriesObserverOptions, QueriesPlaceholderDataFunction, Query, QueryBooleanOption, QueryCache, type QueryCacheConfig, type QueryCacheNotifyEvent, QueryClient, QueryClientConfig, QueryExecuteOptions, type QueryFilters, QueryFunction, QueryFunctionContext, QueryKey, QueryKeyHashFunction, QueryKeyWithDataTag, QueryMeta, QueryObserver, QueryObserverBaseResult, QueryObserverLoadingErrorResult, QueryObserverLoadingResult, QueryObserverOptions, QueryObserverPendingResult, QueryObserverPlaceholderResult, QueryObserverRefetchErrorResult, QueryObserverResult, QueryObserverSuccessResult, QueryOptions, QueryPersister, type QueryState, QueryStatus, RefetchOptions, RefetchQueryFilters, Register, ResetOptions, ResultOptions, SetDataOptions, type SkipToken, StaleTime, StaleTimeFunction, ThrowOnError, type TimeoutCallback, type TimeoutManager, type TimeoutProvider, UnsetMarker, type Updater, WithRequired, dataTagErrorSymbol, dataTagSymbol, defaultScheduler, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, environmentManager, streamedQuery as experimental_streamedQuery, focusManager, hashKey, hydrate, isCancelledError, isServer, keepPreviousData, matchMutation, matchQuery, noop, notifyManager, onlineManager, partialMatchKey, replaceEqualDeep, shouldThrowError, skipToken, timeoutManager, unsetMarker };
+10
View File
@@ -0,0 +1,10 @@
import { environmentManager } from "./environmentManager.js";
import { FocusManager, focusManager } from "./focusManager.js";
import { $ as MutationObserverBaseResult, $n as Query, $t as CancelledError, A as InfiniteData, An as noop, At as QueryObserverOptions, B as InfiniteQueryObserverSuccessResult, Bt as RefetchQueryFilters, C as FetchPreviousPageOptions, Ct as QueryKey, D as GetPreviousPageParamFunction, Dn as keepPreviousData, Dt as QueryObserverBaseResult, E as GetNextPageParamFunction, Et as QueryMeta, F as InfiniteQueryObserverOptions, Ft as QueryObserverSuccessResult, G as InvalidateQueryFilters, Gn as MutationCacheConfig, Gt as StaleTime, H as InitialDataFunction, Hn as MutationState, Ht as ResetOptions, I as InfiniteQueryObserverPendingResult, In as shouldThrowError, It as QueryOptions, J as MutateOptions, Jt as UnsetMarker, K as MutateFunction, Kn as MutationCacheNotifyEvent, Kt as StaleTimeFunction, L as InfiniteQueryObserverPlaceholderResult, Ln as skipToken, Lt as QueryPersister, M as InfiniteQueryObserverBaseResult, Mt as QueryObserverPlaceholderResult, N as InfiniteQueryObserverLoadingErrorResult, Nn as replaceEqualDeep, Nt as QueryObserverRefetchErrorResult, O as InferDataFromTag, On as matchMutation, Ot as QueryObserverLoadingErrorResult, P as InfiniteQueryObserverLoadingResult, Pt as QueryObserverResult, Q as MutationMeta, Qt as unsetMarker, R as InfiniteQueryObserverRefetchErrorResult, Rt as QueryStatus, S as FetchNextPageOptions, St as QueryFunctionContext, T as FetchStatus, Tn as isServer, Tt as QueryKeyWithDataTag, U as InitialPageParam, Ut as ResultOptions, V as InfiniteQueryPageParamsOptions, Vn as Mutation, Vt as Register, W as InvalidateOptions, Wn as MutationCache, Wt as SetDataOptions, X as MutationFunctionContext, Xt as dataTagErrorSymbol, Y as MutationFunction, Yt as WithRequired, Z as MutationKey, Zt as dataTagSymbol, _ as DefinedQueryObserverResult, _t as QueriesPlaceholderDataFunction, a as defaultShouldDehydrateQuery, an as isCancelledError, at as MutationObserverSuccessResult, b as EnsureQueryDataOptions, bt as QueryExecuteOptions, c as hydrate, cn as QueryCacheConfig, ct as MutationStatus, d as DataTag, dn as MutationFilters, dt as NotifyEvent, et as MutationObserverErrorResult, f as DefaultError, fn as QueryFilters, ft as NotifyEventType, g as DefinedInfiniteQueryObserverResult, gt as PlaceholderDataFunction, h as DefaultedQueryObserverOptions, hn as Updater, ht as Override, i as defaultShouldDehydrateMutation, it as MutationObserverResult, j as InfiniteQueryExecuteOptions, jn as partialMatchKey, jt as QueryObserverPendingResult, k as InferErrorFromTag, kn as matchQuery, kt as QueryObserverLoadingResult, l as AnyDataTag, ln as QueryCacheNotifyEvent, lt as NetworkMode, m as DefaultedInfiniteQueryObserverOptions, mn as SkipToken, mt as OmitKeyof, n as DehydratedState, nt as MutationObserverLoadingResult, o as dehydrate, on as QueryClient, ot as MutationOptions, p as DefaultOptions, pt as NotifyOnChangeProps, q as MutateFunctionRest, qn as MutationObserver, qt as ThrowOnError, r as HydrateOptions, rr as QueryObserver, rt as MutationObserverOptions, s as dehydrateQuery, sn as QueryCache, st as MutationScope, t as DehydrateOptions, tr as QueryState, tt as MutationObserverIdleResult, u as CancelOptions, ut as NonUndefinedGuard, v as DistributiveOmit, vt as QueryBooleanOption, w as FetchQueryOptions, wt as QueryKeyHashFunction, x as FetchInfiniteQueryOptions, xn as hashKey, xt as QueryFunction, y as EnsureInfiniteQueryDataOptions, yt as QueryClientConfig, z as InfiniteQueryObserverResult, zt as RefetchOptions } from "./hydration-Cq7QYAzB.js";
import { InfiniteQueryObserver } from "./infiniteQueryObserver.js";
import { defaultScheduler, notifyManager } from "./notifyManager.js";
import { OnlineManager, onlineManager } from "./onlineManager.js";
import { QueriesObserver, QueriesObserverOptions } from "./queriesObserver.js";
import { ManagedTimerId, TimeoutCallback, TimeoutManager, TimeoutProvider, timeoutManager } from "./timeoutManager.js";
import { streamedQuery } from "./streamedQuery.js";
export { AnyDataTag, CancelOptions, CancelledError, DataTag, DefaultError, DefaultOptions, DefaultedInfiniteQueryObserverOptions, DefaultedQueryObserverOptions, DefinedInfiniteQueryObserverResult, DefinedQueryObserverResult, type DehydrateOptions, type DehydratedState, DistributiveOmit, EnsureInfiniteQueryDataOptions, EnsureQueryDataOptions, FetchInfiniteQueryOptions, FetchNextPageOptions, FetchPreviousPageOptions, FetchQueryOptions, FetchStatus, type FocusManager, GetNextPageParamFunction, GetPreviousPageParamFunction, type HydrateOptions, InferDataFromTag, InferErrorFromTag, InfiniteData, InfiniteQueryExecuteOptions, InfiniteQueryObserver, InfiniteQueryObserverBaseResult, InfiniteQueryObserverLoadingErrorResult, InfiniteQueryObserverLoadingResult, InfiniteQueryObserverOptions, InfiniteQueryObserverPendingResult, InfiniteQueryObserverPlaceholderResult, InfiniteQueryObserverRefetchErrorResult, InfiniteQueryObserverResult, InfiniteQueryObserverSuccessResult, InfiniteQueryPageParamsOptions, InitialDataFunction, InitialPageParam, InvalidateOptions, InvalidateQueryFilters, type ManagedTimerId, MutateFunction, MutateFunctionRest, MutateOptions, Mutation, MutationCache, type MutationCacheConfig, type MutationCacheNotifyEvent, type MutationFilters, MutationFunction, MutationFunctionContext, MutationKey, MutationMeta, MutationObserver, MutationObserverBaseResult, MutationObserverErrorResult, MutationObserverIdleResult, MutationObserverLoadingResult, MutationObserverOptions, MutationObserverResult, MutationObserverSuccessResult, MutationOptions, MutationScope, type MutationState, MutationStatus, NetworkMode, NonUndefinedGuard, NotifyEvent, NotifyEventType, NotifyOnChangeProps, OmitKeyof, type OnlineManager, Override, PlaceholderDataFunction, QueriesObserver, type QueriesObserverOptions, QueriesPlaceholderDataFunction, Query, QueryBooleanOption, QueryCache, type QueryCacheConfig, type QueryCacheNotifyEvent, QueryClient, QueryClientConfig, QueryExecuteOptions, type QueryFilters, QueryFunction, QueryFunctionContext, QueryKey, QueryKeyHashFunction, QueryKeyWithDataTag, QueryMeta, QueryObserver, QueryObserverBaseResult, QueryObserverLoadingErrorResult, QueryObserverLoadingResult, QueryObserverOptions, QueryObserverPendingResult, QueryObserverPlaceholderResult, QueryObserverRefetchErrorResult, QueryObserverResult, QueryObserverSuccessResult, QueryOptions, QueryPersister, type QueryState, QueryStatus, RefetchOptions, RefetchQueryFilters, Register, ResetOptions, ResultOptions, SetDataOptions, type SkipToken, StaleTime, StaleTimeFunction, ThrowOnError, type TimeoutCallback, type TimeoutManager, type TimeoutProvider, UnsetMarker, type Updater, WithRequired, dataTagErrorSymbol, dataTagSymbol, defaultScheduler, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, environmentManager, streamedQuery as experimental_streamedQuery, focusManager, hashKey, hydrate, isCancelledError, isServer, keepPreviousData, matchMutation, matchQuery, noop, notifyManager, onlineManager, partialMatchKey, replaceEqualDeep, shouldThrowError, skipToken, timeoutManager, unsetMarker };
+25
View File
@@ -0,0 +1,25 @@
import { timeoutManager } from "./timeoutManager.js";
import { hashKey, isServer, keepPreviousData, matchMutation, matchQuery, noop, partialMatchKey, replaceEqualDeep, shouldThrowError, skipToken } from "./utils.js";
import { environmentManager } from "./environmentManager.js";
import { focusManager } from "./focusManager.js";
import { defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, hydrate } from "./hydration.js";
import { defaultScheduler, notifyManager } from "./notifyManager.js";
import { onlineManager } from "./onlineManager.js";
import { CancelledError, isCancelledError } from "./retryer.js";
import { Query } from "./query.js";
import { QueryObserver } from "./queryObserver.js";
import { InfiniteQueryObserver } from "./infiniteQueryObserver.js";
import { Mutation } from "./mutation.js";
import { MutationCache } from "./mutationCache.js";
import { MutationObserver } from "./mutationObserver.js";
import { QueriesObserver } from "./queriesObserver.js";
import { QueryCache } from "./queryCache.js";
import { QueryClient } from "./queryClient.js";
import { streamedQuery } from "./streamedQuery.js";
import { dataTagErrorSymbol, dataTagSymbol, unsetMarker } from "./types.js";
//#region src/index.ts
/* istanbul ignore file */
//#endregion
export { CancelledError, InfiniteQueryObserver, Mutation, MutationCache, MutationObserver, QueriesObserver, Query, QueryCache, QueryClient, QueryObserver, dataTagErrorSymbol, dataTagSymbol, defaultScheduler, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, dehydrateQuery, environmentManager, streamedQuery as experimental_streamedQuery, focusManager, hashKey, hydrate, isCancelledError, isServer, keepPreviousData, matchMutation, matchQuery, noop, notifyManager, onlineManager, partialMatchKey, replaceEqualDeep, shouldThrowError, skipToken, timeoutManager, unsetMarker };
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport { focusManager } from './focusManager'\nexport type { FocusManager } from './focusManager'\nexport { environmentManager } from './environmentManager'\nexport {\n defaultShouldDehydrateMutation,\n defaultShouldDehydrateQuery,\n dehydrate,\n dehydrateQuery,\n hydrate,\n} from './hydration'\nexport { InfiniteQueryObserver } from './infiniteQueryObserver'\nexport { MutationCache } from './mutationCache'\nexport type { MutationCacheNotifyEvent } from './mutationCache'\nexport { MutationObserver } from './mutationObserver'\nexport { defaultScheduler, notifyManager } from './notifyManager'\nexport { onlineManager } from './onlineManager'\nexport type { OnlineManager } from './onlineManager'\nexport { QueriesObserver } from './queriesObserver'\nexport { QueryCache } from './queryCache'\nexport type { QueryCacheNotifyEvent } from './queryCache'\nexport { QueryClient } from './queryClient'\nexport { QueryObserver } from './queryObserver'\nexport { CancelledError, isCancelledError } from './retryer'\nexport {\n timeoutManager,\n type ManagedTimerId,\n type TimeoutCallback,\n type TimeoutManager,\n type TimeoutProvider,\n} from './timeoutManager'\nexport {\n hashKey,\n isServer,\n keepPreviousData,\n matchMutation,\n matchQuery,\n noop,\n partialMatchKey,\n replaceEqualDeep,\n shouldThrowError,\n skipToken,\n} from './utils'\nexport type { MutationFilters, QueryFilters, SkipToken, Updater } from './utils'\n\nexport { streamedQuery as experimental_streamedQuery } from './streamedQuery'\n\n// Types\nexport type {\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from './hydration'\nexport { Mutation } from './mutation'\nexport type { MutationState } from './mutation'\nexport type { MutationCacheConfig } from './mutationCache'\nexport type { QueriesObserverOptions } from './queriesObserver'\nexport { Query } from './query'\nexport type { QueryState } from './query'\nexport type { QueryCacheConfig } from './queryCache'\nexport * from './types'\n"],"mappings":""}
@@ -0,0 +1,103 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_utils = require("./utils.cjs");
//#region src/infiniteQueryBehavior.ts
function infiniteQueryBehavior(pages) {
return { onFetch: (context, query) => {
var _context$fetchOptions, _context$state$data, _context$state$data2;
const options = context.options;
const direction = (_context$fetchOptions = context.fetchOptions) === null || _context$fetchOptions === void 0 || (_context$fetchOptions = _context$fetchOptions.meta) === null || _context$fetchOptions === void 0 || (_context$fetchOptions = _context$fetchOptions.fetchMore) === null || _context$fetchOptions === void 0 ? void 0 : _context$fetchOptions.direction;
const oldPages = ((_context$state$data = context.state.data) === null || _context$state$data === void 0 ? void 0 : _context$state$data.pages) || [];
const oldPageParams = ((_context$state$data2 = context.state.data) === null || _context$state$data2 === void 0 ? void 0 : _context$state$data2.pageParams) || [];
let result = {
pages: [],
pageParams: []
};
let currentPage = 0;
const fetchFn = async () => {
let cancelled = false;
const addSignalProperty = (object) => {
require_utils.addConsumeAwareSignal(object, () => context.signal, () => cancelled = true);
};
const queryFn = require_utils.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 queryFnContext = {
client: context.client,
queryKey: context.queryKey,
pageParam: param,
direction: previous ? "backward" : "forward",
meta: context.options.meta
};
addSignalProperty(queryFnContext);
return queryFnContext;
};
const queryFnContext = createQueryFnContext();
const page = await queryFn(queryFnContext);
const { maxPages } = context.options;
const addTo = previous ? require_utils.addToStart : require_utils.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 _context$options$pers, _context$options;
return (_context$options$pers = (_context$options = context.options).persister) === null || _context$options$pers === void 0 ? void 0 : _context$options$pers.call(_context$options, 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 _options$getPreviousP;
return pages.length > 0 ? (_options$getPreviousP = options.getPreviousPageParam) === null || _options$getPreviousP === void 0 ? void 0 : _options$getPreviousP.call(options, pages[0], pages, pageParams[0], pageParams) : void 0;
}
/**
* Checks if there is a next page.
*/
function hasNextPage(options, data) {
if (!data) return false;
return getNextPageParam(options, data) != null;
}
/**
* Checks if there is a previous page.
*/
function hasPreviousPage(options, data) {
if (!data || !options.getPreviousPageParam) return false;
return getPreviousPageParam(options, data) != null;
}
//#endregion
exports.hasNextPage = hasNextPage;
exports.hasPreviousPage = hasPreviousPage;
exports.infiniteQueryBehavior = infiniteQueryBehavior;
//# sourceMappingURL=infiniteQueryBehavior.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryBehavior.cjs","names":["ensureQueryFn","addToStart","addToEnd"],"sources":["../../src/infiniteQueryBehavior.ts"],"sourcesContent":["import {\n addConsumeAwareSignal,\n addToEnd,\n addToStart,\n ensureQueryFn,\n} from './utils'\nimport type { QueryBehavior } from './query'\nimport type {\n InfiniteData,\n InfiniteQueryPageParamsOptions,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\nexport function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(\n pages?: number,\n): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>> {\n return {\n onFetch: (context, query) => {\n const options = context.options as InfiniteQueryPageParamsOptions<TData>\n const direction = context.fetchOptions?.meta?.fetchMore?.direction\n const oldPages = context.state.data?.pages || []\n const oldPageParams = context.state.data?.pageParams || []\n let result: InfiniteData<unknown> = { pages: [], pageParams: [] }\n let currentPage = 0\n\n const fetchFn = async () => {\n let cancelled = false\n const addSignalProperty = (object: unknown) => {\n addConsumeAwareSignal(\n object,\n () => context.signal,\n () => (cancelled = true),\n )\n }\n\n const queryFn = ensureQueryFn(context.options, context.fetchOptions)\n\n // Create function to fetch a page\n const fetchPage = async (\n data: InfiniteData<unknown>,\n param: unknown,\n previous?: boolean,\n ): Promise<InfiniteData<unknown>> => {\n if (cancelled) {\n return Promise.reject(context.signal.reason)\n }\n\n if (param == null && data.pages.length) {\n return Promise.resolve(data)\n }\n\n const createQueryFnContext = () => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<QueryKey, unknown>,\n 'signal'\n > = {\n client: context.client,\n queryKey: context.queryKey,\n pageParam: param,\n direction: previous ? 'backward' : 'forward',\n meta: context.options.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext<QueryKey, unknown>\n }\n\n const queryFnContext = createQueryFnContext()\n\n const page = await queryFn(queryFnContext)\n\n const { maxPages } = context.options\n const addTo = previous ? addToStart : addToEnd\n\n return {\n pages: addTo(data.pages, page, maxPages),\n pageParams: addTo(data.pageParams, param, maxPages),\n }\n }\n\n // fetch next / previous page?\n if (direction && oldPages.length) {\n const previous = direction === 'backward'\n const pageParamFn = previous ? getPreviousPageParam : getNextPageParam\n const oldData = {\n pages: oldPages,\n pageParams: oldPageParams,\n }\n const param = pageParamFn(options, oldData)\n\n result = await fetchPage(oldData, param, previous)\n } else {\n const remainingPages = pages ?? oldPages.length\n\n // Fetch all pages\n do {\n const param =\n currentPage === 0\n ? (oldPageParams[0] ?? options.initialPageParam)\n : getNextPageParam(options, result)\n if (currentPage > 0 && param == null) {\n break\n }\n result = await fetchPage(result, param)\n currentPage++\n } while (currentPage < remainingPages)\n }\n\n return result\n }\n if (context.options.persister) {\n context.fetchFn = () => {\n return context.options.persister?.(\n fetchFn as any,\n {\n client: context.client,\n queryKey: context.queryKey,\n meta: context.options.meta,\n signal: context.signal,\n },\n query,\n )\n }\n } else {\n context.fetchFn = fetchFn\n }\n },\n }\n}\n\nfunction getNextPageParam(\n options: InfiniteQueryPageParamsOptions<any>,\n { pages, pageParams }: InfiniteData<unknown>,\n): unknown | undefined {\n const lastIndex = pages.length - 1\n return pages.length > 0\n ? options.getNextPageParam(\n pages[lastIndex],\n pages,\n pageParams[lastIndex],\n pageParams,\n )\n : undefined\n}\n\nfunction getPreviousPageParam(\n options: InfiniteQueryPageParamsOptions<any>,\n { pages, pageParams }: InfiniteData<unknown>,\n): unknown | undefined {\n return pages.length > 0\n ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)\n : undefined\n}\n\n/**\n * Checks if there is a next page.\n Line truncated
@@ -0,0 +1,14 @@
import { A as InfiniteData, V as InfiniteQueryPageParamsOptions, er as QueryBehavior } from "./hydration-DwR10Hi-.cjs";
//#region src/infiniteQueryBehavior.d.ts
declare function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(pages?: number): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>>;
/**
* Checks if there is a next page.
*/
declare function hasNextPage(options: InfiniteQueryPageParamsOptions<any, any>, data?: InfiniteData<unknown>): boolean;
/**
* Checks if there is a previous page.
*/
declare function hasPreviousPage(options: InfiniteQueryPageParamsOptions<any, any>, data?: InfiniteData<unknown>): boolean;
//#endregion
export { hasNextPage, hasPreviousPage, infiniteQueryBehavior };
//# sourceMappingURL=infiniteQueryBehavior.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryBehavior.d.cts","names":[],"sources":["../../src/infiniteQueryBehavior.ts"],"mappings":";;iBAegB,sBAAsB,cAAc,QAAQ,OAAO,YACjE,iBACC,cAAc,cAAc,QAAQ,aAAa,OAAO;;;;iBA6I3C,YACd,SAAS,0CACT,OAAO;;;;iBASO,gBACd,SAAS,0CACT,OAAO"}
@@ -0,0 +1,14 @@
import { A as InfiniteData, V as InfiniteQueryPageParamsOptions, er as QueryBehavior } from "./hydration-Cq7QYAzB.js";
//#region src/infiniteQueryBehavior.d.ts
declare function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(pages?: number): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>>;
/**
* Checks if there is a next page.
*/
declare function hasNextPage(options: InfiniteQueryPageParamsOptions<any, any>, data?: InfiniteData<unknown>): boolean;
/**
* Checks if there is a previous page.
*/
declare function hasPreviousPage(options: InfiniteQueryPageParamsOptions<any, any>, data?: InfiniteData<unknown>): boolean;
//#endregion
export { hasNextPage, hasPreviousPage, infiniteQueryBehavior };
//# sourceMappingURL=infiniteQueryBehavior.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryBehavior.d.ts","names":[],"sources":["../../src/infiniteQueryBehavior.ts"],"mappings":";;iBAegB,sBAAsB,cAAc,QAAQ,OAAO,YACjE,iBACC,cAAc,cAAc,QAAQ,aAAa,OAAO;;;;iBA6I3C,YACd,SAAS,0CACT,OAAO;;;;iBASO,gBACd,SAAS,0CACT,OAAO"}
@@ -0,0 +1,100 @@
import { addConsumeAwareSignal, addToEnd, addToStart, ensureQueryFn } from "./utils.js";
//#region src/infiniteQueryBehavior.ts
function infiniteQueryBehavior(pages) {
return { onFetch: (context, query) => {
var _context$fetchOptions, _context$state$data, _context$state$data2;
const options = context.options;
const direction = (_context$fetchOptions = context.fetchOptions) === null || _context$fetchOptions === void 0 || (_context$fetchOptions = _context$fetchOptions.meta) === null || _context$fetchOptions === void 0 || (_context$fetchOptions = _context$fetchOptions.fetchMore) === null || _context$fetchOptions === void 0 ? void 0 : _context$fetchOptions.direction;
const oldPages = ((_context$state$data = context.state.data) === null || _context$state$data === void 0 ? void 0 : _context$state$data.pages) || [];
const oldPageParams = ((_context$state$data2 = context.state.data) === null || _context$state$data2 === void 0 ? void 0 : _context$state$data2.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 queryFnContext = {
client: context.client,
queryKey: context.queryKey,
pageParam: param,
direction: previous ? "backward" : "forward",
meta: context.options.meta
};
addSignalProperty(queryFnContext);
return queryFnContext;
};
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 _context$options$pers, _context$options;
return (_context$options$pers = (_context$options = context.options).persister) === null || _context$options$pers === void 0 ? void 0 : _context$options$pers.call(_context$options, 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 _options$getPreviousP;
return pages.length > 0 ? (_options$getPreviousP = options.getPreviousPageParam) === null || _options$getPreviousP === void 0 ? void 0 : _options$getPreviousP.call(options, pages[0], pages, pageParams[0], pageParams) : void 0;
}
/**
* Checks if there is a next page.
*/
function hasNextPage(options, data) {
if (!data) return false;
return getNextPageParam(options, data) != null;
}
/**
* Checks if there is a previous page.
*/
function hasPreviousPage(options, data) {
if (!data || !options.getPreviousPageParam) return false;
return getPreviousPageParam(options, data) != null;
}
//#endregion
export { hasNextPage, hasPreviousPage, infiniteQueryBehavior };
//# sourceMappingURL=infiniteQueryBehavior.js.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryBehavior.js","names":[],"sources":["../../src/infiniteQueryBehavior.ts"],"sourcesContent":["import {\n addConsumeAwareSignal,\n addToEnd,\n addToStart,\n ensureQueryFn,\n} from './utils'\nimport type { QueryBehavior } from './query'\nimport type {\n InfiniteData,\n InfiniteQueryPageParamsOptions,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\nexport function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(\n pages?: number,\n): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>> {\n return {\n onFetch: (context, query) => {\n const options = context.options as InfiniteQueryPageParamsOptions<TData>\n const direction = context.fetchOptions?.meta?.fetchMore?.direction\n const oldPages = context.state.data?.pages || []\n const oldPageParams = context.state.data?.pageParams || []\n let result: InfiniteData<unknown> = { pages: [], pageParams: [] }\n let currentPage = 0\n\n const fetchFn = async () => {\n let cancelled = false\n const addSignalProperty = (object: unknown) => {\n addConsumeAwareSignal(\n object,\n () => context.signal,\n () => (cancelled = true),\n )\n }\n\n const queryFn = ensureQueryFn(context.options, context.fetchOptions)\n\n // Create function to fetch a page\n const fetchPage = async (\n data: InfiniteData<unknown>,\n param: unknown,\n previous?: boolean,\n ): Promise<InfiniteData<unknown>> => {\n if (cancelled) {\n return Promise.reject(context.signal.reason)\n }\n\n if (param == null && data.pages.length) {\n return Promise.resolve(data)\n }\n\n const createQueryFnContext = () => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<QueryKey, unknown>,\n 'signal'\n > = {\n client: context.client,\n queryKey: context.queryKey,\n pageParam: param,\n direction: previous ? 'backward' : 'forward',\n meta: context.options.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext<QueryKey, unknown>\n }\n\n const queryFnContext = createQueryFnContext()\n\n const page = await queryFn(queryFnContext)\n\n const { maxPages } = context.options\n const addTo = previous ? addToStart : addToEnd\n\n return {\n pages: addTo(data.pages, page, maxPages),\n pageParams: addTo(data.pageParams, param, maxPages),\n }\n }\n\n // fetch next / previous page?\n if (direction && oldPages.length) {\n const previous = direction === 'backward'\n const pageParamFn = previous ? getPreviousPageParam : getNextPageParam\n const oldData = {\n pages: oldPages,\n pageParams: oldPageParams,\n }\n const param = pageParamFn(options, oldData)\n\n result = await fetchPage(oldData, param, previous)\n } else {\n const remainingPages = pages ?? oldPages.length\n\n // Fetch all pages\n do {\n const param =\n currentPage === 0\n ? (oldPageParams[0] ?? options.initialPageParam)\n : getNextPageParam(options, result)\n if (currentPage > 0 && param == null) {\n break\n }\n result = await fetchPage(result, param)\n currentPage++\n } while (currentPage < remainingPages)\n }\n\n return result\n }\n if (context.options.persister) {\n context.fetchFn = () => {\n return context.options.persister?.(\n fetchFn as any,\n {\n client: context.client,\n queryKey: context.queryKey,\n meta: context.options.meta,\n signal: context.signal,\n },\n query,\n )\n }\n } else {\n context.fetchFn = fetchFn\n }\n },\n }\n}\n\nfunction getNextPageParam(\n options: InfiniteQueryPageParamsOptions<any>,\n { pages, pageParams }: InfiniteData<unknown>,\n): unknown | undefined {\n const lastIndex = pages.length - 1\n return pages.length > 0\n ? options.getNextPageParam(\n pages[lastIndex],\n pages,\n pageParams[lastIndex],\n pageParams,\n )\n : undefined\n}\n\nfunction getPreviousPageParam(\n options: InfiniteQueryPageParamsOptions<any>,\n { pages, pageParams }: InfiniteData<unknown>,\n): unknown | undefined {\n return pages.length > 0\n ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)\n : undefined\n}\n\n/**\n * Checks if there is a next page.\n */\nexport function hasNextPage(\n optiLine truncated
@@ -0,0 +1,129 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs");
const require_queryObserver = require("./queryObserver.cjs");
//#region src/infiniteQueryObserver.ts
/**
* An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
* between infinite queries. It augments the base `QueryObserverResult` with
* infinite-query-specific fields and methods, such as `hasNextPage` and
* `fetchNextPage`, and is the primitive that framework adapters (e.g.
* `useInfiniteQuery`) build their hooks on top of.
*
* @example
* ```ts
* const observer = new InfiniteQueryObserver(queryClient, {
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextCursor,
* })
*
* const unsubscribe = observer.subscribe((result) => console.log(result))
* ```
*/
var InfiniteQueryObserver = class extends require_queryObserver.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 _state$fetchMeta;
const { state } = query;
const parentResult = super.createResult(query, options);
const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
const fetchDirection = (_state$fetchMeta = state.fetchMeta) === null || _state$fetchMeta === void 0 || (_state$fetchMeta = _state$fetchMeta.fetchMore) === null || _state$fetchMeta === void 0 ? void 0 : _state$fetchMeta.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: require_infiniteQueryBehavior.hasNextPage(options, state.data),
hasPreviousPage: require_infiniteQueryBehavior.hasPreviousPage(options, state.data),
isFetchNextPageError,
isFetchingNextPage,
isFetchPreviousPageError,
isFetchingPreviousPage,
isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
};
}
};
//#endregion
exports.InfiniteQueryObserver = InfiniteQueryObserver;
//# sourceMappingURL=infiniteQueryObserver.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryObserver.cjs","names":["QueryObserver","hasNextPage","hasPreviousPage"],"sources":["../../src/infiniteQueryObserver.ts"],"sourcesContent":["import { QueryObserver } from './queryObserver'\nimport { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior'\nimport type { Subscribable } from './subscribable'\nimport type {\n DefaultError,\n DefaultedInfiniteQueryObserverOptions,\n FetchNextPageOptions,\n FetchPreviousPageOptions,\n InfiniteData,\n InfiniteQueryObserverBaseResult,\n InfiniteQueryObserverOptions,\n InfiniteQueryObserverResult,\n QueryKey,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Query } from './query'\n\ntype InfiniteQueryObserverListener<TData, TError> = (\n result: InfiniteQueryObserverResult<TData, TError>,\n) => void\n\n/**\n * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch\n * between infinite queries. It augments the base `QueryObserverResult` with\n * infinite-query-specific fields and methods, such as `hasNextPage` and\n * `fetchNextPage`, and is the primitive that framework adapters (e.g.\n * `useInfiniteQuery`) build their hooks on top of.\n *\n * @example\n * ```ts\n * const observer = new InfiniteQueryObserver(queryClient, {\n * queryKey: ['projects'],\n * queryFn: ({ pageParam }) => fetchProjects(pageParam),\n * initialPageParam: 0,\n * getNextPageParam: (lastPage) => lastPage.nextCursor,\n * })\n *\n * const unsubscribe = observer.subscribe((result) => console.log(result))\n * ```\n */\nexport class InfiniteQueryObserver<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> extends QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n> {\n // Type override\n subscribe!: Subscribable<\n InfiniteQueryObserverListener<TData, TError>\n >['subscribe']\n\n // Type override\n getCurrentResult!: ReplaceReturnType<\n QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n >['getCurrentResult'],\n InfiniteQueryObserverResult<TData, TError>\n >\n\n // Type override\n protected fetch!: ReplaceReturnType<\n QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n >['fetch'],\n Promise<InfiniteQueryObserverResult<TData, TError>>\n >\n\n constructor(\n client: QueryClient,\n options: InfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ) {\n super(client, options)\n }\n\n protected bindMethods(): void {\n super.bindMethods()\n this.fetchNextPage = this.fetchNextPage.bind(this)\n this.fetchPreviousPage = this.fetchPreviousPage.bind(this)\n }\n\n /**\n * Updates the observer's options. Behaves the same as\n * `QueryObserver.setOptions`, additionally marking the options as\n * belonging to an infinite query before delegating to the base\n * implementation.\n */\n setOptions(\n options: InfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): void {\n options._type = 'infinite'\n super.setOptions(options)\n }\n\n /**\n * The infinite-query counterpart of {@link QueryObserver#getOptimisticResult}, marking the\n * options as an infinite query before delegating to it. Called by framework adapters (e.g.\n * `useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`\n * synchronously.\n */\n getOptimisticResult(\n options: DefaultedInfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): InfiniteQueryObserverResult<TData, TError> {\n options._type = 'infinite'\n return super.getOptimisticResult(options) as InfiniteQueryObserverResult<\n TData,\n TError\n >\n }\n\n /**\n * Fetches the next page of the infinite query and returns a promise that\n * resolves with the resulting `InfiniteQueryObserverResult`. The page\n * param used for the fetch is determined by `getNextPageParam`, which\n * receives the current pages/page params and whose result also determines\n * `hasNextPage`.\n *\n * @example\n * ```ts\n * const { hasNextPage } = observer.getCurrentResult()\n *\n * if (hasNextPage) {\n * await observer.fetchNextPage()\n * }\n * ```\n *\n * @see {@link InfiniteQueryObserver#fetchPreviousPage}\n */\n fetchNextPage(\n options?: FetchNextPageOptions,\n ): Promise<InfiniteQueryObserverResult<TData, TError>> {\n return this.fetch({\n ...options,\n meta: {\n fetchMore: { direction: 'forward' },\n },\n })\n }\n\n /**\n * Fetches the previous page of Line truncated
@@ -0,0 +1,87 @@
import { t as Subscribable } from "./subscribable-CbifVTKz.cjs";
import { $n as Query, A as InfiniteData, C as FetchPreviousPageOptions, Ct as QueryKey, F as InfiniteQueryObserverOptions, S as FetchNextPageOptions, f as DefaultError, m as DefaultedInfiniteQueryObserverOptions, on as QueryClient, rr as QueryObserver, z as InfiniteQueryObserverResult } from "./hydration-DwR10Hi-.cjs";
//#region src/infiniteQueryObserver.d.ts
type InfiniteQueryObserverListener<TData, TError> = (result: InfiniteQueryObserverResult<TData, TError>) => void;
/**
* An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
* between infinite queries. It augments the base `QueryObserverResult` with
* infinite-query-specific fields and methods, such as `hasNextPage` and
* `fetchNextPage`, and is the primitive that framework adapters (e.g.
* `useInfiniteQuery`) build their hooks on top of.
*
* @example
* ```ts
* const observer = new InfiniteQueryObserver(queryClient, {
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextCursor,
* })
*
* const unsubscribe = observer.subscribe((result) => console.log(result))
* ```
*/
declare class InfiniteQueryObserver<TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> extends QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey> {
subscribe: Subscribable<InfiniteQueryObserverListener<TData, TError>>['subscribe'];
getCurrentResult: ReplaceReturnType<QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>['getCurrentResult'], InfiniteQueryObserverResult<TData, TError>>;
protected fetch: ReplaceReturnType<QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>['fetch'], Promise<InfiniteQueryObserverResult<TData, TError>>>;
constructor(client: QueryClient, options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>);
protected bindMethods(): void;
/**
* 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: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): void;
/**
* 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: DefaultedInfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserverResult<TData, TError>;
/**
* 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?: FetchNextPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
/**
* 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?: FetchPreviousPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
protected createResult(query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>, options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserverResult<TData, TError>;
}
type ReplaceReturnType<TFunction extends (...args: Array<any>) => unknown, TReturn> = (...args: Parameters<TFunction>) => TReturn;
//#endregion
export { InfiniteQueryObserver };
//# sourceMappingURL=infiniteQueryObserver.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryObserver.d.cts","names":[],"sources":["../../src/infiniteQueryObserver.ts"],"mappings":";;;KAiBK,8BAA8B,OAAO,WACxC,QAAQ,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;;cAsBhC,sBACX,wBACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,8BACQ,cACR,cACA,QACA,OACA,aAAa,cAAc,aAC3B;EAGA,WAAY,aACV,8BAA8B,OAAO;EAIvC,kBAAmB,kBACjB,cACE,cACA,QACA,OACA,aAAa,cAAc,aAC3B,gCAEF,4BAA4B,OAAO;YAI3B,OAAQ,kBAChB,cACE,cACA,QACA,OACA,aAAa,cAAc,aAC3B,qBAEF,QAAQ,4BAA4B,OAAO;EAI3C,YAAA,QAAQ,aACR,SAAS,6BACP,cACA,QACA,OACA,WACA;YAMM;;;;;;;EAYV,WACE,SAAS,6BACP,cACA,QACA,OACA,WACA;;;;;;;EAaJ,oBACE,SAAS,sCACP,cACA,QACA,OACA,WACA,cAED,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;EA0BtC,cACE,UAAU,uBACT,QAAQ,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;EA2B9C,kBACE,UAAU,2BACT,QAAQ,4BAA4B,OAAO;YASpC,aACR,OAAO,MACL,cACA,QACA,aAAa,cAAc,aAC3B,YAEF,SAAS,6BACP,cACA,QACA,OACA,WACA,cAED,4BAA4B,OAAO;;KAiCnC,kBACH,sBAAsB,MAAM,wBAC5B,eACM,MAAM,WAAW,eAAe"}
@@ -0,0 +1,87 @@
import { t as Subscribable } from "./subscribable-CbifVTKz.js";
import { $n as Query, A as InfiniteData, C as FetchPreviousPageOptions, Ct as QueryKey, F as InfiniteQueryObserverOptions, S as FetchNextPageOptions, f as DefaultError, m as DefaultedInfiniteQueryObserverOptions, on as QueryClient, rr as QueryObserver, z as InfiniteQueryObserverResult } from "./hydration-Cq7QYAzB.js";
//#region src/infiniteQueryObserver.d.ts
type InfiniteQueryObserverListener<TData, TError> = (result: InfiniteQueryObserverResult<TData, TError>) => void;
/**
* An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
* between infinite queries. It augments the base `QueryObserverResult` with
* infinite-query-specific fields and methods, such as `hasNextPage` and
* `fetchNextPage`, and is the primitive that framework adapters (e.g.
* `useInfiniteQuery`) build their hooks on top of.
*
* @example
* ```ts
* const observer = new InfiniteQueryObserver(queryClient, {
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextCursor,
* })
*
* const unsubscribe = observer.subscribe((result) => console.log(result))
* ```
*/
declare class InfiniteQueryObserver<TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> extends QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey> {
subscribe: Subscribable<InfiniteQueryObserverListener<TData, TError>>['subscribe'];
getCurrentResult: ReplaceReturnType<QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>['getCurrentResult'], InfiniteQueryObserverResult<TData, TError>>;
protected fetch: ReplaceReturnType<QueryObserver<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>['fetch'], Promise<InfiniteQueryObserverResult<TData, TError>>>;
constructor(client: QueryClient, options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>);
protected bindMethods(): void;
/**
* 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: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): void;
/**
* 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: DefaultedInfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserverResult<TData, TError>;
/**
* 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?: FetchNextPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
/**
* 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?: FetchPreviousPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
protected createResult(query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>, options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserverResult<TData, TError>;
}
type ReplaceReturnType<TFunction extends (...args: Array<any>) => unknown, TReturn> = (...args: Parameters<TFunction>) => TReturn;
//#endregion
export { InfiniteQueryObserver };
//# sourceMappingURL=infiniteQueryObserver.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryObserver.d.ts","names":[],"sources":["../../src/infiniteQueryObserver.ts"],"mappings":";;;KAiBK,8BAA8B,OAAO,WACxC,QAAQ,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;;cAsBhC,sBACX,wBACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,8BACQ,cACR,cACA,QACA,OACA,aAAa,cAAc,aAC3B;EAGA,WAAY,aACV,8BAA8B,OAAO;EAIvC,kBAAmB,kBACjB,cACE,cACA,QACA,OACA,aAAa,cAAc,aAC3B,gCAEF,4BAA4B,OAAO;YAI3B,OAAQ,kBAChB,cACE,cACA,QACA,OACA,aAAa,cAAc,aAC3B,qBAEF,QAAQ,4BAA4B,OAAO;EAI3C,YAAA,QAAQ,aACR,SAAS,6BACP,cACA,QACA,OACA,WACA;YAMM;;;;;;;EAYV,WACE,SAAS,6BACP,cACA,QACA,OACA,WACA;;;;;;;EAaJ,oBACE,SAAS,sCACP,cACA,QACA,OACA,WACA,cAED,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;EA0BtC,cACE,UAAU,uBACT,QAAQ,4BAA4B,OAAO;;;;;;;;;;;;;;;;;;;EA2B9C,kBACE,UAAU,2BACT,QAAQ,4BAA4B,OAAO;YASpC,aACR,OAAO,MACL,cACA,QACA,aAAa,cAAc,aAC3B,YAEF,SAAS,6BACP,cACA,QACA,OACA,WACA,cAED,4BAA4B,OAAO;;KAiCnC,kBACH,sBAAsB,MAAM,wBAC5B,eACM,MAAM,WAAW,eAAe"}
@@ -0,0 +1,128 @@
import { hasNextPage, hasPreviousPage } from "./infiniteQueryBehavior.js";
import { QueryObserver } from "./queryObserver.js";
//#region src/infiniteQueryObserver.ts
/**
* An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
* between infinite queries. It augments the base `QueryObserverResult` with
* infinite-query-specific fields and methods, such as `hasNextPage` and
* `fetchNextPage`, and is the primitive that framework adapters (e.g.
* `useInfiniteQuery`) build their hooks on top of.
*
* @example
* ```ts
* const observer = new InfiniteQueryObserver(queryClient, {
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextCursor,
* })
*
* const unsubscribe = observer.subscribe((result) => console.log(result))
* ```
*/
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 _state$fetchMeta;
const { state } = query;
const parentResult = super.createResult(query, options);
const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
const fetchDirection = (_state$fetchMeta = state.fetchMeta) === null || _state$fetchMeta === void 0 || (_state$fetchMeta = _state$fetchMeta.fetchMore) === null || _state$fetchMeta === void 0 ? void 0 : _state$fetchMeta.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
};
}
};
//#endregion
export { InfiniteQueryObserver };
//# sourceMappingURL=infiniteQueryObserver.js.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryObserver.js","names":[],"sources":["../../src/infiniteQueryObserver.ts"],"sourcesContent":["import { QueryObserver } from './queryObserver'\nimport { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior'\nimport type { Subscribable } from './subscribable'\nimport type {\n DefaultError,\n DefaultedInfiniteQueryObserverOptions,\n FetchNextPageOptions,\n FetchPreviousPageOptions,\n InfiniteData,\n InfiniteQueryObserverBaseResult,\n InfiniteQueryObserverOptions,\n InfiniteQueryObserverResult,\n QueryKey,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Query } from './query'\n\ntype InfiniteQueryObserverListener<TData, TError> = (\n result: InfiniteQueryObserverResult<TData, TError>,\n) => void\n\n/**\n * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch\n * between infinite queries. It augments the base `QueryObserverResult` with\n * infinite-query-specific fields and methods, such as `hasNextPage` and\n * `fetchNextPage`, and is the primitive that framework adapters (e.g.\n * `useInfiniteQuery`) build their hooks on top of.\n *\n * @example\n * ```ts\n * const observer = new InfiniteQueryObserver(queryClient, {\n * queryKey: ['projects'],\n * queryFn: ({ pageParam }) => fetchProjects(pageParam),\n * initialPageParam: 0,\n * getNextPageParam: (lastPage) => lastPage.nextCursor,\n * })\n *\n * const unsubscribe = observer.subscribe((result) => console.log(result))\n * ```\n */\nexport class InfiniteQueryObserver<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> extends QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n> {\n // Type override\n subscribe!: Subscribable<\n InfiniteQueryObserverListener<TData, TError>\n >['subscribe']\n\n // Type override\n getCurrentResult!: ReplaceReturnType<\n QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n >['getCurrentResult'],\n InfiniteQueryObserverResult<TData, TError>\n >\n\n // Type override\n protected fetch!: ReplaceReturnType<\n QueryObserver<\n TQueryFnData,\n TError,\n TData,\n InfiniteData<TQueryFnData, TPageParam>,\n TQueryKey\n >['fetch'],\n Promise<InfiniteQueryObserverResult<TData, TError>>\n >\n\n constructor(\n client: QueryClient,\n options: InfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ) {\n super(client, options)\n }\n\n protected bindMethods(): void {\n super.bindMethods()\n this.fetchNextPage = this.fetchNextPage.bind(this)\n this.fetchPreviousPage = this.fetchPreviousPage.bind(this)\n }\n\n /**\n * Updates the observer's options. Behaves the same as\n * `QueryObserver.setOptions`, additionally marking the options as\n * belonging to an infinite query before delegating to the base\n * implementation.\n */\n setOptions(\n options: InfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): void {\n options._type = 'infinite'\n super.setOptions(options)\n }\n\n /**\n * The infinite-query counterpart of {@link QueryObserver#getOptimisticResult}, marking the\n * options as an infinite query before delegating to it. Called by framework adapters (e.g.\n * `useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`\n * synchronously.\n */\n getOptimisticResult(\n options: DefaultedInfiniteQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): InfiniteQueryObserverResult<TData, TError> {\n options._type = 'infinite'\n return super.getOptimisticResult(options) as InfiniteQueryObserverResult<\n TData,\n TError\n >\n }\n\n /**\n * Fetches the next page of the infinite query and returns a promise that\n * resolves with the resulting `InfiniteQueryObserverResult`. The page\n * param used for the fetch is determined by `getNextPageParam`, which\n * receives the current pages/page params and whose result also determines\n * `hasNextPage`.\n *\n * @example\n * ```ts\n * const { hasNextPage } = observer.getCurrentResult()\n *\n * if (hasNextPage) {\n * await observer.fetchNextPage()\n * }\n * ```\n *\n * @see {@link InfiniteQueryObserver#fetchPreviousPage}\n */\n fetchNextPage(\n options?: FetchNextPageOptions,\n ): Promise<InfiniteQueryObserverResult<TData, TError>> {\n return this.fetch({\n ...options,\n meta: {\n fetchMore: { direction: 'forward' },\n },\n })\n }\n\n /**\n * Fetches the previous page of the infinite query and returns a promise\n * tLine truncated
+314
View File
@@ -0,0 +1,314 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
const require_notifyManager = require("./notifyManager.cjs");
const require_retryer = require("./retryer.cjs");
const require_removable = require("./removable.cjs");
const require_classPrivateMethodInitSpec = require("./classPrivateMethodInitSpec-DVhcLejn.cjs");
//#region src/mutation.ts
var _client = /* @__PURE__ */ new WeakMap();
var _observers = /* @__PURE__ */ new WeakMap();
var _mutationCache = /* @__PURE__ */ new WeakMap();
var _retryer = /* @__PURE__ */ new WeakMap();
var _Mutation_brand = /* @__PURE__ */ new WeakSet();
/**
* Represents a single mutation attempt. A `Mutation` holds the mutation's
* options, state (data/error/status), and the `MutationObserver`s currently
* subscribed to it.
*
* Instances are created and managed internally by `MutationCache`; application
* code typically interacts with mutations indirectly through `QueryClient` or
* a framework hook like `useMutation`. Direct access to a `Mutation` instance
* is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.
*
* @example
* ```ts
* const mutationCache = queryClient.getMutationCache()
*
* const mutation = mutationCache.find({ mutationKey: ['addPost'] })
* ```
*/
var Mutation = class extends require_removable.Removable {
constructor(config) {
super();
require_classPrivateMethodInitSpec._classPrivateMethodInitSpec(this, _Mutation_brand);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _client, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _observers, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _mutationCache, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _retryer, void 0);
require_classPrivateFieldSet2._classPrivateFieldSet2(_client, this, config.client);
this.mutationId = config.mutationId;
require_classPrivateFieldSet2._classPrivateFieldSet2(_mutationCache, this, config.mutationCache);
require_classPrivateFieldSet2._classPrivateFieldSet2(_observers, this, []);
this.state = config.state || getDefaultState();
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 (!require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).includes(observer)) {
require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).push(observer);
this.clearGcTimeout();
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).notify({
type: "observerAdded",
mutation: this,
observer
});
}
}
/** @internal */
removeObserver(observer) {
require_classPrivateFieldSet2._classPrivateFieldSet2(_observers, this, require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).filter((x) => x !== observer));
this.scheduleGc();
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).notify({
type: "observerRemoved",
mutation: this,
observer
});
}
optionalRemove() {
if (!require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).length) {
if (this.state.status === "pending") this.scheduleGc();
else require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).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 _classPrivateFieldGet2$1;
return ((_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.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) {
const onContinue = () => {
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, { type: "continue" });
};
const mutationFnContext = {
client: require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this),
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
const retryer = require_classPrivateFieldSet2._classPrivateFieldSet2(_retryer, this, require_retryer.createRetryer({
fn: () => {
if (!this.options.mutationFn) return Promise.reject(/* @__PURE__ */ new Error("No mutationFn found"));
return this.options.mutationFn(variables, mutationFnContext);
},
onFail: (failureCount, error) => {
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
type: "failed",
failureCount,
error
});
},
onPause: () => {
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, { type: "pause" });
},
onContinue,
retry: this.options.retry ?? 0,
retryDelay: this.options.retryDelay,
networkMode: this.options.networkMode,
canRun: () => require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).canRun(this)
}));
const restored = this.state.status === "pending";
const isPaused = !retryer.canStart();
try {
var _classPrivateFieldGet3, _classPrivateFieldGet4, _this$options$onSucce, _this$options2, _classPrivateFieldGet5, _classPrivateFieldGet6, _this$options$onSettl, _this$options3;
if (restored) onContinue();
else {
var _this$options$onMutat, _this$options;
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
type: "pending",
variables,
isPaused
});
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config.onMutate) await require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config.onMutate(variables, this, mutationFnContext);
const context = await ((_this$options$onMutat = (_this$options = this.options).onMutate) === null || _this$options$onMutat === void 0 ? void 0 : _this$options$onMutat.call(_this$options, variables, mutationFnContext));
if (context !== this.state.context) require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
type: "pending",
context,
variables,
isPaused
});
}
const data = await retryer.start();
await ((_classPrivateFieldGet3 = (_classPrivateFieldGet4 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config).onSuccess) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.call(_classPrivateFieldGet4, data, variables, this.state.context, this, mutationFnContext));
await ((_this$options$onSucce = (_this$options2 = this.options).onSuccess) === null || _this$options$onSucce === void 0 ? void 0 : _this$options$onSucce.call(_this$options2, data, variables, this.state.context, mutationFnContext));
await ((_classPrivateFieldGet5 = (_classPrivateFieldGet6 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config).onSettled) === null || _classPrivateFieldGet5 === void 0 ? void 0 : _classPrivateFieldGet5.call(_classPrivateFieldGet6, data, null, this.state.variables, this.state.context, this, mutationFnContext));
await ((_this$options$onSettl = (_this$options3 = this.options).onSettled) === null || _this$options$onSettl === void 0 ? void 0 : _this$options$onSettl.call(_this$options3, data, null, variables, this.state.context, mutationFnContext));
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
type: "success",
data
});
return data;
} catch (error) {
try {
var _classPrivateFieldGet7, _classPrivateFieldGet8;
await ((_classPrivateFieldGet7 = (_classPrivateFieldGet8 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config).onError) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.call(_classPrivateFieldGet8, error, variables, this.state.context, this, mutationFnContext));
} catch (e) {
Promise.reject(e);
}
try {
var _this$options$onError, _this$options4;
await ((_this$options$onError = (_this$options4 = this.options).onError) === null || _this$options$onError === void 0 ? void 0 : _this$options$onError.call(_this$options4, error, variables, this.state.context, mutationFnContext));
} catch (e) {
Promise.reject(e);
}
try {
var _classPrivateFieldGet9, _classPrivateFieldGet10;
await ((_classPrivateFieldGet9 = (_classPrivateFieldGet10 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).config).onSettled) === null || _classPrivateFieldGet9 === void 0 ? void 0 : _classPrivateFieldGet9.call(_classPrivateFieldGet10, void 0, error, this.state.variables, this.state.context, this, mutationFnContext));
} catch (e) {
Promise.reject(e);
}
try {
var _this$options$onSettl2, _this$options5;
await ((_this$options$onSettl2 = (_this$options5 = this.options).onSettled) === null || _this$options$onSettl2 === void 0 ? void 0 : _this$options$onSettl2.call(_this$options5, void 0, error, variables, this.state.context, mutationFnContext));
} catch (e) {
Promise.reject(e);
}
require_classPrivateFieldSet2._assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
type: "error",
error
});
throw error;
} finally {
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_retryer, this) === retryer) require_classPrivateFieldSet2._classPrivateFieldSet2(_retryer, this, void 0);
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).runNext(this);
}
}
};
function _dispatch(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);
require_notifyManager.notifyManager.batch(() => {
require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).forEach((observer) => {
observer.onMutationUpdate(action);
});
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationCache, this).notify({
mutation: this,
type: "updated",
action
});
});
}
function getDefaultState() {
return {
context: void 0,
data: void 0,
error: null,
failureCount: 0,
failureReason: null,
isPaused: false,
status: "idle",
variables: void 0,
submittedAt: 0
};
}
//#endregion
exports.Mutation = Mutation;
exports.getDefaultState = getDefaultState;
//# sourceMappingURL=mutation.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"mutation.cjs","names":["Removable","createRetryer"],"sources":["../../src/mutation.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Removable } from './removable'\nimport { createRetryer } from './retryer'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationMeta,\n MutationOptions,\n MutationStatus,\n} from './types'\nimport type { MutationCache } from './mutationCache'\nimport type { MutationObserver } from './mutationObserver'\nimport type { Retryer } from './retryer'\nimport type { QueryClient } from './queryClient'\n\n// TYPES\n\ninterface MutationConfig<TData, TError, TVariables, TOnMutateResult> {\n client: QueryClient\n mutationId: number\n mutationCache: MutationCache\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>\n}\n\n/**\n * The raw state stored on a `Mutation` instance. This is the underlying state\n * that observer results (e.g. `MutationObserverResult`) are derived from.\n */\nexport interface MutationState<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * The value returned by `onMutate`, if defined. Passed to `onSuccess`,\n * `onError` and `onSettled` as the mutation's context.\n */\n context: TOnMutateResult | undefined\n /**\n * The last successfully resolved data for the mutation.\n */\n data: TData | undefined\n /**\n * The error object for the mutation, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The number of times the mutation function has failed for the current attempt.\n */\n failureCount: number\n /**\n * The reason the current attempt failed, as reported by the retryer.\n */\n failureReason: TError | null\n /**\n * Whether the mutation is currently paused (see network mode), or is\n * waiting for another mutation with the same `scope` to finish.\n */\n isPaused: boolean\n /**\n * The status of the mutation.\n */\n status: MutationStatus\n /**\n * The variables the mutation was last called with.\n */\n variables: TVariables | undefined\n /**\n * The timestamp for when the mutation was submitted.\n */\n submittedAt: number\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError | null\n}\n\ninterface PendingAction<TVariables, TOnMutateResult> {\n type: 'pending'\n isPaused: boolean\n variables?: TVariables\n context?: TOnMutateResult\n}\n\ninterface SuccessAction<TData> {\n type: 'success'\n data: TData\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\nexport type Action<TData, TError, TVariables, TOnMutateResult> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | PendingAction<TVariables, TOnMutateResult>\n | PauseAction\n | SuccessAction<TData>\n\n// CLASS\n\n/**\n * Represents a single mutation attempt. A `Mutation` holds the mutation's\n * options, state (data/error/status), and the `MutationObserver`s currently\n * subscribed to it.\n *\n * Instances are created and managed internally by `MutationCache`; application\n * code typically interacts with mutations indirectly through `QueryClient` or\n * a framework hook like `useMutation`. Direct access to a `Mutation` instance\n * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * ```\n */\nexport class Mutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> extends Removable {\n state: MutationState<TData, TError, TVariables, TOnMutateResult>\n options!: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n readonly mutationId: number\n\n #client: QueryClient\n #observers: Array<\n MutationObserver<TData, TError, TVariables, TOnMutateResult>\n >\n #mutationCache: MutationCache\n #retryer?: Retryer<TData>\n\n constructor(\n config: MutationConfig<TData, TError, TVariables, TOnMutateResult>,\n ) {\n super()\n\n this.#client = config.client\n this.mutationId = config.mutationId\n this.#mutationCache = config.mutationCache\n this.#observers = []\n this.state = config.state || getDefaultState()\n\n this.setOptions(config.options)\n this.scheduleGc()\n }\n\n /** @internal */\n setOptions(\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.options = options\n\n this.updateGcTime(this.options.gcTime)\n }\n\n /**\n * The `meta` object passed in the mutation's options, if any.\n */\n get meta(): MutationMeta | undefined {\n return thLine truncated
+2
View File
@@ -0,0 +1,2 @@
import { Bn as Action, Hn as MutationState, Un as getDefaultState, Vn as Mutation } from "./hydration-DwR10Hi-.cjs";
export { Action, Mutation, MutationState, getDefaultState };
+2
View File
@@ -0,0 +1,2 @@
import { Bn as Action, Hn as MutationState, Un as getDefaultState, Vn as Mutation } from "./hydration-Cq7QYAzB.js";
export { Action, Mutation, MutationState, getDefaultState };
+312
View File
@@ -0,0 +1,312 @@
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
import { notifyManager } from "./notifyManager.js";
import { createRetryer } from "./retryer.js";
import { Removable } from "./removable.js";
import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-CBwa_Y7C.js";
//#region src/mutation.ts
var _client = /* @__PURE__ */ new WeakMap();
var _observers = /* @__PURE__ */ new WeakMap();
var _mutationCache = /* @__PURE__ */ new WeakMap();
var _retryer = /* @__PURE__ */ new WeakMap();
var _Mutation_brand = /* @__PURE__ */ new WeakSet();
/**
* Represents a single mutation attempt. A `Mutation` holds the mutation's
* options, state (data/error/status), and the `MutationObserver`s currently
* subscribed to it.
*
* Instances are created and managed internally by `MutationCache`; application
* code typically interacts with mutations indirectly through `QueryClient` or
* a framework hook like `useMutation`. Direct access to a `Mutation` instance
* is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.
*
* @example
* ```ts
* const mutationCache = queryClient.getMutationCache()
*
* const mutation = mutationCache.find({ mutationKey: ['addPost'] })
* ```
*/
var Mutation = class extends Removable {
constructor(config) {
super();
_classPrivateMethodInitSpec(this, _Mutation_brand);
_classPrivateFieldInitSpec(this, _client, void 0);
_classPrivateFieldInitSpec(this, _observers, void 0);
_classPrivateFieldInitSpec(this, _mutationCache, void 0);
_classPrivateFieldInitSpec(this, _retryer, void 0);
_classPrivateFieldSet2(_client, this, config.client);
this.mutationId = config.mutationId;
_classPrivateFieldSet2(_mutationCache, this, config.mutationCache);
_classPrivateFieldSet2(_observers, this, []);
this.state = config.state || getDefaultState();
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 (!_classPrivateFieldGet2(_observers, this).includes(observer)) {
_classPrivateFieldGet2(_observers, this).push(observer);
this.clearGcTimeout();
_classPrivateFieldGet2(_mutationCache, this).notify({
type: "observerAdded",
mutation: this,
observer
});
}
}
/** @internal */
removeObserver(observer) {
_classPrivateFieldSet2(_observers, this, _classPrivateFieldGet2(_observers, this).filter((x) => x !== observer));
this.scheduleGc();
_classPrivateFieldGet2(_mutationCache, this).notify({
type: "observerRemoved",
mutation: this,
observer
});
}
optionalRemove() {
if (!_classPrivateFieldGet2(_observers, this).length) {
if (this.state.status === "pending") this.scheduleGc();
else _classPrivateFieldGet2(_mutationCache, this).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 _classPrivateFieldGet2$1;
return ((_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.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) {
const onContinue = () => {
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, { type: "continue" });
};
const mutationFnContext = {
client: _classPrivateFieldGet2(_client, this),
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
const retryer = _classPrivateFieldSet2(_retryer, this, createRetryer({
fn: () => {
if (!this.options.mutationFn) return Promise.reject(/* @__PURE__ */ new Error("No mutationFn found"));
return this.options.mutationFn(variables, mutationFnContext);
},
onFail: (failureCount, error) => {
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
type: "failed",
failureCount,
error
});
},
onPause: () => {
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, { type: "pause" });
},
onContinue,
retry: this.options.retry ?? 0,
retryDelay: this.options.retryDelay,
networkMode: this.options.networkMode,
canRun: () => _classPrivateFieldGet2(_mutationCache, this).canRun(this)
}));
const restored = this.state.status === "pending";
const isPaused = !retryer.canStart();
try {
var _classPrivateFieldGet3, _classPrivateFieldGet4, _this$options$onSucce, _this$options2, _classPrivateFieldGet5, _classPrivateFieldGet6, _this$options$onSettl, _this$options3;
if (restored) onContinue();
else {
var _this$options$onMutat, _this$options;
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
type: "pending",
variables,
isPaused
});
if (_classPrivateFieldGet2(_mutationCache, this).config.onMutate) await _classPrivateFieldGet2(_mutationCache, this).config.onMutate(variables, this, mutationFnContext);
const context = await ((_this$options$onMutat = (_this$options = this.options).onMutate) === null || _this$options$onMutat === void 0 ? void 0 : _this$options$onMutat.call(_this$options, variables, mutationFnContext));
if (context !== this.state.context) _assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
type: "pending",
context,
variables,
isPaused
});
}
const data = await retryer.start();
await ((_classPrivateFieldGet3 = (_classPrivateFieldGet4 = _classPrivateFieldGet2(_mutationCache, this).config).onSuccess) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.call(_classPrivateFieldGet4, data, variables, this.state.context, this, mutationFnContext));
await ((_this$options$onSucce = (_this$options2 = this.options).onSuccess) === null || _this$options$onSucce === void 0 ? void 0 : _this$options$onSucce.call(_this$options2, data, variables, this.state.context, mutationFnContext));
await ((_classPrivateFieldGet5 = (_classPrivateFieldGet6 = _classPrivateFieldGet2(_mutationCache, this).config).onSettled) === null || _classPrivateFieldGet5 === void 0 ? void 0 : _classPrivateFieldGet5.call(_classPrivateFieldGet6, data, null, this.state.variables, this.state.context, this, mutationFnContext));
await ((_this$options$onSettl = (_this$options3 = this.options).onSettled) === null || _this$options$onSettl === void 0 ? void 0 : _this$options$onSettl.call(_this$options3, data, null, variables, this.state.context, mutationFnContext));
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
type: "success",
data
});
return data;
} catch (error) {
try {
var _classPrivateFieldGet7, _classPrivateFieldGet8;
await ((_classPrivateFieldGet7 = (_classPrivateFieldGet8 = _classPrivateFieldGet2(_mutationCache, this).config).onError) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.call(_classPrivateFieldGet8, error, variables, this.state.context, this, mutationFnContext));
} catch (e) {
Promise.reject(e);
}
try {
var _this$options$onError, _this$options4;
await ((_this$options$onError = (_this$options4 = this.options).onError) === null || _this$options$onError === void 0 ? void 0 : _this$options$onError.call(_this$options4, error, variables, this.state.context, mutationFnContext));
} catch (e) {
Promise.reject(e);
}
try {
var _classPrivateFieldGet9, _classPrivateFieldGet10;
await ((_classPrivateFieldGet9 = (_classPrivateFieldGet10 = _classPrivateFieldGet2(_mutationCache, this).config).onSettled) === null || _classPrivateFieldGet9 === void 0 ? void 0 : _classPrivateFieldGet9.call(_classPrivateFieldGet10, void 0, error, this.state.variables, this.state.context, this, mutationFnContext));
} catch (e) {
Promise.reject(e);
}
try {
var _this$options$onSettl2, _this$options5;
await ((_this$options$onSettl2 = (_this$options5 = this.options).onSettled) === null || _this$options$onSettl2 === void 0 ? void 0 : _this$options$onSettl2.call(_this$options5, void 0, error, variables, this.state.context, mutationFnContext));
} catch (e) {
Promise.reject(e);
}
_assertClassBrand(_Mutation_brand, this, _dispatch).call(this, {
type: "error",
error
});
throw error;
} finally {
if (_classPrivateFieldGet2(_retryer, this) === retryer) _classPrivateFieldSet2(_retryer, this, void 0);
_classPrivateFieldGet2(_mutationCache, this).runNext(this);
}
}
};
function _dispatch(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(() => {
_classPrivateFieldGet2(_observers, this).forEach((observer) => {
observer.onMutationUpdate(action);
});
_classPrivateFieldGet2(_mutationCache, this).notify({
mutation: this,
type: "updated",
action
});
});
}
function getDefaultState() {
return {
context: void 0,
data: void 0,
error: null,
failureCount: 0,
failureReason: null,
isPaused: false,
status: "idle",
variables: void 0,
submittedAt: 0
};
}
//#endregion
export { Mutation, getDefaultState };
//# sourceMappingURL=mutation.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"mutation.js","names":[],"sources":["../../src/mutation.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Removable } from './removable'\nimport { createRetryer } from './retryer'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationMeta,\n MutationOptions,\n MutationStatus,\n} from './types'\nimport type { MutationCache } from './mutationCache'\nimport type { MutationObserver } from './mutationObserver'\nimport type { Retryer } from './retryer'\nimport type { QueryClient } from './queryClient'\n\n// TYPES\n\ninterface MutationConfig<TData, TError, TVariables, TOnMutateResult> {\n client: QueryClient\n mutationId: number\n mutationCache: MutationCache\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>\n}\n\n/**\n * The raw state stored on a `Mutation` instance. This is the underlying state\n * that observer results (e.g. `MutationObserverResult`) are derived from.\n */\nexport interface MutationState<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * The value returned by `onMutate`, if defined. Passed to `onSuccess`,\n * `onError` and `onSettled` as the mutation's context.\n */\n context: TOnMutateResult | undefined\n /**\n * The last successfully resolved data for the mutation.\n */\n data: TData | undefined\n /**\n * The error object for the mutation, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The number of times the mutation function has failed for the current attempt.\n */\n failureCount: number\n /**\n * The reason the current attempt failed, as reported by the retryer.\n */\n failureReason: TError | null\n /**\n * Whether the mutation is currently paused (see network mode), or is\n * waiting for another mutation with the same `scope` to finish.\n */\n isPaused: boolean\n /**\n * The status of the mutation.\n */\n status: MutationStatus\n /**\n * The variables the mutation was last called with.\n */\n variables: TVariables | undefined\n /**\n * The timestamp for when the mutation was submitted.\n */\n submittedAt: number\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError | null\n}\n\ninterface PendingAction<TVariables, TOnMutateResult> {\n type: 'pending'\n isPaused: boolean\n variables?: TVariables\n context?: TOnMutateResult\n}\n\ninterface SuccessAction<TData> {\n type: 'success'\n data: TData\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\nexport type Action<TData, TError, TVariables, TOnMutateResult> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | PendingAction<TVariables, TOnMutateResult>\n | PauseAction\n | SuccessAction<TData>\n\n// CLASS\n\n/**\n * Represents a single mutation attempt. A `Mutation` holds the mutation's\n * options, state (data/error/status), and the `MutationObserver`s currently\n * subscribed to it.\n *\n * Instances are created and managed internally by `MutationCache`; application\n * code typically interacts with mutations indirectly through `QueryClient` or\n * a framework hook like `useMutation`. Direct access to a `Mutation` instance\n * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * ```\n */\nexport class Mutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> extends Removable {\n state: MutationState<TData, TError, TVariables, TOnMutateResult>\n options!: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n readonly mutationId: number\n\n #client: QueryClient\n #observers: Array<\n MutationObserver<TData, TError, TVariables, TOnMutateResult>\n >\n #mutationCache: MutationCache\n #retryer?: Retryer<TData>\n\n constructor(\n config: MutationConfig<TData, TError, TVariables, TOnMutateResult>,\n ) {\n super()\n\n this.#client = config.client\n this.mutationId = config.mutationId\n this.#mutationCache = config.mutationCache\n this.#observers = []\n this.state = config.state || getDefaultState()\n\n this.setOptions(config.options)\n this.scheduleGc()\n }\n\n /** @internal */\n setOptions(\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.options = options\n\n this.updateGcTime(this.options.gcTime)\n }\n\n /**\n * The `meta` object passed in the mutation's options, if any.\n */\n get meta(): MutationMeta | undefined {\n return this.options.meta\n }\n\n /*Line truncated
+199
View File
@@ -0,0 +1,199 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
const require_utils = require("./utils.cjs");
const require_subscribable = require("./subscribable.cjs");
const require_notifyManager = require("./notifyManager.cjs");
const require_mutation = require("./mutation.cjs");
//#region src/mutationCache.ts
var _mutations = /* @__PURE__ */ new WeakMap();
var _scopes = /* @__PURE__ */ new WeakMap();
var _mutationId = /* @__PURE__ */ new WeakMap();
/**
* The `MutationCache` is the storage for mutations.
*
* Normally, you will not interact with the `MutationCache` directly and instead use a
* `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of
* safe/known updates to the cache, such as mutations being added, removed, or updated.
*
* @example
* ```ts
* const unsubscribe = mutationCache.subscribe((event) => {
* console.log(event.type, event.mutation)
* })
* ```
*/
var MutationCache = class extends require_subscribable.Subscribable {
constructor(config = {}) {
super();
this.config = config;
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _mutations, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _scopes, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _mutationId, void 0);
require_classPrivateFieldSet2._classPrivateFieldSet2(_mutations, this, /* @__PURE__ */ new Set());
require_classPrivateFieldSet2._classPrivateFieldSet2(_scopes, this, /* @__PURE__ */ new Map());
require_classPrivateFieldSet2._classPrivateFieldSet2(_mutationId, this, 0);
}
/** @internal */
build(client, options, state) {
var _this$mutationId;
const mutation = new require_mutation.Mutation({
client,
mutationCache: this,
mutationId: require_classPrivateFieldSet2._classPrivateFieldSet2(_mutationId, this, (_this$mutationId = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutationId, this), ++_this$mutationId)),
options: client.defaultMutationOptions(options),
state
});
this.add(mutation);
return mutation;
}
/** @internal */
add(mutation) {
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutations, this).add(mutation);
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).get(scope);
if (scopedMutations) scopedMutations.push(mutation);
else require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).set(scope, [mutation]);
}
this.notify({
type: "added",
mutation
});
}
/** @internal */
remove(mutation) {
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_mutations, this).delete(mutation)) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).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) require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).delete(scope);
}
}
}
this.notify({
type: "removed",
mutation
});
}
/** @internal */
canRun(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const mutationsWithSameScope = require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).get(scope);
const firstPendingMutation = mutationsWithSameScope === null || mutationsWithSameScope === void 0 ? void 0 : mutationsWithSameScope.find((m) => m.state.status === "pending");
return !firstPendingMutation || firstPendingMutation === mutation;
} else return true;
}
/** @internal */
runNext(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
var _classPrivateFieldGet2$1;
const foundMutation = (_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).get(scope)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.find((m) => m !== mutation && m.state.isPaused);
return (foundMutation === null || foundMutation === void 0 ? void 0 : foundMutation.continue()) ?? Promise.resolve();
} else return Promise.resolve();
}
/**
* Removes all mutations from the cache.
*
* @example
* ```ts
* const mutationCache = queryClient.getMutationCache()
*
* mutationCache.clear()
* ```
*/
clear() {
require_notifyManager.notifyManager.batch(() => {
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutations, this).forEach((mutation) => {
this.notify({
type: "removed",
mutation
});
});
require_classPrivateFieldSet2._classPrivateFieldGet2(_mutations, this).clear();
require_classPrivateFieldSet2._classPrivateFieldGet2(_scopes, this).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(require_classPrivateFieldSet2._classPrivateFieldGet2(_mutations, this));
}
/**
* 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) => require_utils.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) => require_utils.matchMutation(filters, mutation));
}
/** @internal */
notify(event) {
require_notifyManager.notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(event);
});
});
}
/** @internal */
resumePausedMutations() {
const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
return require_notifyManager.notifyManager.batch(() => Promise.all(pausedMutations.map((mutation) => mutation.continue().catch(require_utils.noop))));
}
};
function scopeFor(mutation) {
var _mutation$options$sco;
return (_mutation$options$sco = mutation.options.scope) === null || _mutation$options$sco === void 0 ? void 0 : _mutation$options$sco.id;
}
//#endregion
exports.MutationCache = MutationCache;
//# sourceMappingURL=mutationCache.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"mutationCache.cjs","names":["Subscribable","Mutation","matchMutation","notifyManager","noop"],"sources":["../../src/mutationCache.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Mutation } from './mutation'\nimport { matchMutation, noop } from './utils'\nimport { Subscribable } from './subscribable'\nimport type { MutationObserver } from './mutationObserver'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationOptions,\n NotifyEvent,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Action, MutationState } from './mutation'\nimport type { MutationFilters } from './utils'\n\n// TYPES\n\n/**\n * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which\n * component or observer triggered it. They differ from the `defaultOptions` provided to a\n * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these\n * callbacks are always called, and `onMutate` here does not allow returning a result.\n *\n * If a callback returns a promise, it will be awaited before the mutation continues.\n */\nexport interface MutationCacheConfig {\n /** Called when any mutation in the cache encounters an error. */\n onError?: (\n error: DefaultError,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is successful. */\n onSuccess?: (\n data: unknown,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called before any mutation in the cache executes. */\n onMutate?: (\n variables: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is settled, either successfully or with an error. */\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n}\n\ninterface NotifyEventMutationAdded extends NotifyEvent {\n type: 'added'\n mutation: Mutation<any, any, any, any>\n}\ninterface NotifyEventMutationRemoved extends NotifyEvent {\n type: 'removed'\n mutation: Mutation<any, any, any, any>\n}\n\ninterface NotifyEventMutationObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n mutation?: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any, any>\n}\n\ninterface NotifyEventMutationUpdated extends NotifyEvent {\n type: 'updated'\n mutation: Mutation<any, any, any, any>\n action: Action<any, any, any, any>\n}\n\n/**\n * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed\n * from the cache, its state is updated, or one of its observers is added, removed, or has its\n * options updated.\n */\nexport type MutationCacheNotifyEvent =\n | NotifyEventMutationAdded\n | NotifyEventMutationRemoved\n | NotifyEventMutationObserverAdded\n | NotifyEventMutationObserverRemoved\n | NotifyEventMutationObserverOptionsUpdated\n | NotifyEventMutationUpdated\n\ntype MutationCacheListener = (event: MutationCacheNotifyEvent) => void\n\n// CLASS\n\n/**\n * The `MutationCache` is the storage for mutations.\n *\n * Normally, you will not interact with the `MutationCache` directly and instead use a\n * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of\n * safe/known updates to the cache, such as mutations being added, removed, or updated.\n *\n * @example\n * ```ts\n * const unsubscribe = mutationCache.subscribe((event) => {\n * console.log(event.type, event.mutation)\n * })\n * ```\n */\nexport class MutationCache extends Subscribable<MutationCacheListener> {\n #mutations: Set<Mutation<any, any, any, any>>\n #scopes: Map<string, Array<Mutation<any, any, any, any>>>\n #mutationId: number\n\n constructor(public config: MutationCacheConfig = {}) {\n super()\n this.#mutations = new Set()\n this.#scopes = new Map()\n this.#mutationId = 0\n }\n\n /** @internal */\n build<TData, TError, TVariables, TOnMutateResult>(\n client: QueryClient,\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n state?: MutatiLine truncated
@@ -0,0 +1,2 @@
import { Gn as MutationCacheConfig, Kn as MutationCacheNotifyEvent, Wn as MutationCache } from "./hydration-DwR10Hi-.cjs";
export { MutationCache, MutationCacheConfig, MutationCacheNotifyEvent };
@@ -0,0 +1,2 @@
import { Gn as MutationCacheConfig, Kn as MutationCacheNotifyEvent, Wn as MutationCache } from "./hydration-Cq7QYAzB.js";
export { MutationCache, MutationCacheConfig, MutationCacheNotifyEvent };
+198
View File
@@ -0,0 +1,198 @@
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
import { matchMutation, noop } from "./utils.js";
import { Subscribable } from "./subscribable.js";
import { notifyManager } from "./notifyManager.js";
import { Mutation } from "./mutation.js";
//#region src/mutationCache.ts
var _mutations = /* @__PURE__ */ new WeakMap();
var _scopes = /* @__PURE__ */ new WeakMap();
var _mutationId = /* @__PURE__ */ new WeakMap();
/**
* The `MutationCache` is the storage for mutations.
*
* Normally, you will not interact with the `MutationCache` directly and instead use a
* `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of
* safe/known updates to the cache, such as mutations being added, removed, or updated.
*
* @example
* ```ts
* const unsubscribe = mutationCache.subscribe((event) => {
* console.log(event.type, event.mutation)
* })
* ```
*/
var MutationCache = class extends Subscribable {
constructor(config = {}) {
super();
this.config = config;
_classPrivateFieldInitSpec(this, _mutations, void 0);
_classPrivateFieldInitSpec(this, _scopes, void 0);
_classPrivateFieldInitSpec(this, _mutationId, void 0);
_classPrivateFieldSet2(_mutations, this, /* @__PURE__ */ new Set());
_classPrivateFieldSet2(_scopes, this, /* @__PURE__ */ new Map());
_classPrivateFieldSet2(_mutationId, this, 0);
}
/** @internal */
build(client, options, state) {
var _this$mutationId;
const mutation = new Mutation({
client,
mutationCache: this,
mutationId: _classPrivateFieldSet2(_mutationId, this, (_this$mutationId = _classPrivateFieldGet2(_mutationId, this), ++_this$mutationId)),
options: client.defaultMutationOptions(options),
state
});
this.add(mutation);
return mutation;
}
/** @internal */
add(mutation) {
_classPrivateFieldGet2(_mutations, this).add(mutation);
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = _classPrivateFieldGet2(_scopes, this).get(scope);
if (scopedMutations) scopedMutations.push(mutation);
else _classPrivateFieldGet2(_scopes, this).set(scope, [mutation]);
}
this.notify({
type: "added",
mutation
});
}
/** @internal */
remove(mutation) {
if (_classPrivateFieldGet2(_mutations, this).delete(mutation)) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = _classPrivateFieldGet2(_scopes, this).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) _classPrivateFieldGet2(_scopes, this).delete(scope);
}
}
}
this.notify({
type: "removed",
mutation
});
}
/** @internal */
canRun(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const mutationsWithSameScope = _classPrivateFieldGet2(_scopes, this).get(scope);
const firstPendingMutation = mutationsWithSameScope === null || mutationsWithSameScope === void 0 ? void 0 : mutationsWithSameScope.find((m) => m.state.status === "pending");
return !firstPendingMutation || firstPendingMutation === mutation;
} else return true;
}
/** @internal */
runNext(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
var _classPrivateFieldGet2$1;
const foundMutation = (_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_scopes, this).get(scope)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.find((m) => m !== mutation && m.state.isPaused);
return (foundMutation === null || foundMutation === void 0 ? void 0 : foundMutation.continue()) ?? Promise.resolve();
} else return Promise.resolve();
}
/**
* Removes all mutations from the cache.
*
* @example
* ```ts
* const mutationCache = queryClient.getMutationCache()
*
* mutationCache.clear()
* ```
*/
clear() {
notifyManager.batch(() => {
_classPrivateFieldGet2(_mutations, this).forEach((mutation) => {
this.notify({
type: "removed",
mutation
});
});
_classPrivateFieldGet2(_mutations, this).clear();
_classPrivateFieldGet2(_scopes, this).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(_classPrivateFieldGet2(_mutations, this));
}
/**
* 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))));
}
};
function scopeFor(mutation) {
var _mutation$options$sco;
return (_mutation$options$sco = mutation.options.scope) === null || _mutation$options$sco === void 0 ? void 0 : _mutation$options$sco.id;
}
//#endregion
export { MutationCache };
//# sourceMappingURL=mutationCache.js.map
@@ -0,0 +1 @@
{"version":3,"file":"mutationCache.js","names":[],"sources":["../../src/mutationCache.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Mutation } from './mutation'\nimport { matchMutation, noop } from './utils'\nimport { Subscribable } from './subscribable'\nimport type { MutationObserver } from './mutationObserver'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationOptions,\n NotifyEvent,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Action, MutationState } from './mutation'\nimport type { MutationFilters } from './utils'\n\n// TYPES\n\n/**\n * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which\n * component or observer triggered it. They differ from the `defaultOptions` provided to a\n * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these\n * callbacks are always called, and `onMutate` here does not allow returning a result.\n *\n * If a callback returns a promise, it will be awaited before the mutation continues.\n */\nexport interface MutationCacheConfig {\n /** Called when any mutation in the cache encounters an error. */\n onError?: (\n error: DefaultError,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is successful. */\n onSuccess?: (\n data: unknown,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called before any mutation in the cache executes. */\n onMutate?: (\n variables: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is settled, either successfully or with an error. */\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n}\n\ninterface NotifyEventMutationAdded extends NotifyEvent {\n type: 'added'\n mutation: Mutation<any, any, any, any>\n}\ninterface NotifyEventMutationRemoved extends NotifyEvent {\n type: 'removed'\n mutation: Mutation<any, any, any, any>\n}\n\ninterface NotifyEventMutationObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n mutation?: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any, any>\n}\n\ninterface NotifyEventMutationUpdated extends NotifyEvent {\n type: 'updated'\n mutation: Mutation<any, any, any, any>\n action: Action<any, any, any, any>\n}\n\n/**\n * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed\n * from the cache, its state is updated, or one of its observers is added, removed, or has its\n * options updated.\n */\nexport type MutationCacheNotifyEvent =\n | NotifyEventMutationAdded\n | NotifyEventMutationRemoved\n | NotifyEventMutationObserverAdded\n | NotifyEventMutationObserverRemoved\n | NotifyEventMutationObserverOptionsUpdated\n | NotifyEventMutationUpdated\n\ntype MutationCacheListener = (event: MutationCacheNotifyEvent) => void\n\n// CLASS\n\n/**\n * The `MutationCache` is the storage for mutations.\n *\n * Normally, you will not interact with the `MutationCache` directly and instead use a\n * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of\n * safe/known updates to the cache, such as mutations being added, removed, or updated.\n *\n * @example\n * ```ts\n * const unsubscribe = mutationCache.subscribe((event) => {\n * console.log(event.type, event.mutation)\n * })\n * ```\n */\nexport class MutationCache extends Subscribable<MutationCacheListener> {\n #mutations: Set<Mutation<any, any, any, any>>\n #scopes: Map<string, Array<Mutation<any, any, any, any>>>\n #mutationId: number\n\n constructor(public config: MutationCacheConfig = {}) {\n super()\n this.#mutations = new Set()\n this.#scopes = new Map()\n this.#mutationId = 0\n }\n\n /** @internal */\n build<TData, TError, TVariables, TOnMutateResult>(\n client: QueryClient,\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>,\n ): MutatiLine truncated
+208
View File
@@ -0,0 +1,208 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
const require_utils = require("./utils.cjs");
const require_subscribable = require("./subscribable.cjs");
const require_notifyManager = require("./notifyManager.cjs");
const require_classPrivateMethodInitSpec = require("./classPrivateMethodInitSpec-DVhcLejn.cjs");
const require_mutation = require("./mutation.cjs");
//#region src/mutationObserver.ts
var _client = /* @__PURE__ */ new WeakMap();
var _currentResult = /* @__PURE__ */ new WeakMap();
var _currentMutation = /* @__PURE__ */ new WeakMap();
var _mutateOptions = /* @__PURE__ */ new WeakMap();
var _MutationObserver_brand = /* @__PURE__ */ new WeakSet();
/**
* Observes a single mutation and derives a `MutationObserverResult` from it.
* A framework hook like `useMutation` creates one `MutationObserver` per hook
* call, keeps it stable across re-renders, calls `setOptions` when the options
* passed to the hook change, subscribes to it to re-render on updates, and
* reads `getCurrentResult()` for the value to return. Calling `mutate()`
* builds a new underlying `Mutation` in the `MutationCache` and executes it.
*
* @example
* ```ts
* const observer = new MutationObserver(queryClient, {
* mutationFn: (variables: { title: string }) => addPost(variables),
* })
* ```
*/
var MutationObserver = class extends require_subscribable.Subscribable {
constructor(client, options) {
super();
require_classPrivateMethodInitSpec._classPrivateMethodInitSpec(this, _MutationObserver_brand);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _client, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _currentResult, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _currentMutation, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _mutateOptions, void 0);
require_classPrivateFieldSet2._classPrivateFieldSet2(_client, this, client);
this.setOptions(options);
this.bindMethods();
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _updateResult).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 _classPrivateFieldGet2$1;
const prevOptions = this.options;
this.options = require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this).defaultMutationOptions(options);
if (!require_utils.shallowEqualObjects(this.options, prevOptions)) require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this).getMutationCache().notify({
type: "observerOptionsUpdated",
mutation: require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this),
observer: this
});
if ((prevOptions === null || prevOptions === void 0 ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && require_utils.hashKey(prevOptions.mutationKey) !== require_utils.hashKey(this.options.mutationKey)) this.reset();
else if (((_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.state.status) === "pending") require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this).setOptions(this.options);
}
onSubscribe() {
if (this.listeners.size === 1 && require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) {
require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this).addObserver(this);
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
var _classPrivateFieldGet3;
(_classPrivateFieldGet3 = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.removeObserver(this);
}
}
/** @internal */
onMutationUpdate(action) {
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _notify).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 require_classPrivateFieldSet2._classPrivateFieldGet2(_currentResult, this);
}
/**
* 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 _classPrivateFieldGet4;
(_classPrivateFieldGet4 = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet4 === void 0 || _classPrivateFieldGet4.removeObserver(this);
require_classPrivateFieldSet2._classPrivateFieldSet2(_currentMutation, this, void 0);
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
require_classPrivateFieldSet2._assertClassBrand(_MutationObserver_brand, this, _notify).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 _classPrivateFieldGet5;
require_classPrivateFieldSet2._classPrivateFieldSet2(_mutateOptions, this, options);
(_classPrivateFieldGet5 = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet5 === void 0 || _classPrivateFieldGet5.removeObserver(this);
require_classPrivateFieldSet2._classPrivateFieldSet2(_currentMutation, this, require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this).getMutationCache().build(require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this), this.options));
require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this).addObserver(this);
return require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this).execute(variables);
}
};
function _updateResult() {
var _classPrivateFieldGet6;
const state = ((_classPrivateFieldGet6 = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet6 === void 0 ? void 0 : _classPrivateFieldGet6.state) ?? require_mutation.getDefaultState();
require_classPrivateFieldSet2._classPrivateFieldSet2(_currentResult, this, {
...state,
isPending: state.status === "pending",
isSuccess: state.status === "success",
isError: state.status === "error",
isIdle: state.status === "idle",
mutate: this.mutate,
reset: this.reset
});
}
function _notify(action) {
require_notifyManager.notifyManager.batch(() => {
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_mutateOptions, this) && this.hasListeners()) {
const variables = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentResult, this).variables;
const onMutateResult = require_classPrivateFieldSet2._classPrivateFieldGet2(_currentResult, this).context;
const context = {
client: require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this),
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
if ((action === null || action === void 0 ? void 0 : action.type) === "success") {
try {
var _classPrivateFieldGet7, _classPrivateFieldGet8;
(_classPrivateFieldGet7 = (_classPrivateFieldGet8 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutateOptions, this)).onSuccess) === null || _classPrivateFieldGet7 === void 0 || _classPrivateFieldGet7.call(_classPrivateFieldGet8, action.data, variables, onMutateResult, context);
} catch (e) {
Promise.reject(e);
}
try {
var _classPrivateFieldGet9, _classPrivateFieldGet10;
(_classPrivateFieldGet9 = (_classPrivateFieldGet10 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutateOptions, this)).onSettled) === null || _classPrivateFieldGet9 === void 0 || _classPrivateFieldGet9.call(_classPrivateFieldGet10, action.data, null, variables, onMutateResult, context);
} catch (e) {
Promise.reject(e);
}
} else if ((action === null || action === void 0 ? void 0 : action.type) === "error") {
try {
var _classPrivateFieldGet11, _classPrivateFieldGet12;
(_classPrivateFieldGet11 = (_classPrivateFieldGet12 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutateOptions, this)).onError) === null || _classPrivateFieldGet11 === void 0 || _classPrivateFieldGet11.call(_classPrivateFieldGet12, action.error, variables, onMutateResult, context);
} catch (e) {
Promise.reject(e);
}
try {
var _classPrivateFieldGet13, _classPrivateFieldGet14;
(_classPrivateFieldGet13 = (_classPrivateFieldGet14 = require_classPrivateFieldSet2._classPrivateFieldGet2(_mutateOptions, this)).onSettled) === null || _classPrivateFieldGet13 === void 0 || _classPrivateFieldGet13.call(_classPrivateFieldGet14, void 0, action.error, variables, onMutateResult, context);
} catch (e) {
Promise.reject(e);
}
}
}
this.listeners.forEach((listener) => {
listener(require_classPrivateFieldSet2._classPrivateFieldGet2(_currentResult, this));
});
});
}
//#endregion
exports.MutationObserver = MutationObserver;
//# sourceMappingURL=mutationObserver.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"mutationObserver.cjs","names":["Subscribable","shallowEqualObjects","hashKey","getDefaultState"],"sources":["../../src/mutationObserver.ts"],"sourcesContent":["import { getDefaultState } from './mutation'\nimport { notifyManager } from './notifyManager'\nimport { Subscribable } from './subscribable'\nimport { hashKey, shallowEqualObjects } from './utils'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultError,\n MutateOptions,\n MutationFunctionContext,\n MutationObserverOptions,\n MutationObserverResult,\n} from './types'\nimport type { Action, Mutation } from './mutation'\n\n// TYPES\n\ntype MutationObserverListener<TData, TError, TVariables, TOnMutateResult> = (\n result: MutationObserverResult<TData, TError, TVariables, TOnMutateResult>,\n) => void\n\n// CLASS\n\n/**\n * Observes a single mutation and derives a `MutationObserverResult` from it.\n * A framework hook like `useMutation` creates one `MutationObserver` per hook\n * call, keeps it stable across re-renders, calls `setOptions` when the options\n * passed to the hook change, subscribes to it to re-render on updates, and\n * reads `getCurrentResult()` for the value to return. Calling `mutate()`\n * builds a new underlying `Mutation` in the `MutationCache` and executes it.\n *\n * @example\n * ```ts\n * const observer = new MutationObserver(queryClient, {\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * })\n * ```\n */\nexport class MutationObserver<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n> extends Subscribable<\n MutationObserverListener<TData, TError, TVariables, TOnMutateResult>\n> {\n options!: MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n\n #client: QueryClient\n #currentResult: MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = undefined!\n #currentMutation?: Mutation<TData, TError, TVariables, TOnMutateResult>\n #mutateOptions?: MutateOptions<TData, TError, TVariables, TOnMutateResult>\n\n constructor(\n client: QueryClient,\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n super()\n\n this.#client = client\n this.setOptions(options)\n this.bindMethods()\n this.#updateResult()\n }\n\n protected bindMethods(): void {\n this.mutate = this.mutate.bind(this)\n this.reset = this.reset.bind(this)\n }\n\n /**\n * Updates the observer's options.\n *\n * If the new `mutationKey` differs from the previous one (and both were\n * defined), the observer is reset, detaching it from the mutation it was\n * observing. Otherwise, if the currently observed mutation is still\n * `pending`, its options are updated in place as well.\n *\n * @example\n * ```ts\n * observer.setOptions({\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * onSuccess: (data) => console.log(data),\n * })\n * ```\n */\n setOptions(\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n const prevOptions = this.options as\n | MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n | undefined\n this.options = this.#client.defaultMutationOptions(options)\n if (!shallowEqualObjects(this.options, prevOptions)) {\n this.#client.getMutationCache().notify({\n type: 'observerOptionsUpdated',\n mutation: this.#currentMutation,\n observer: this,\n })\n }\n\n if (\n prevOptions?.mutationKey &&\n this.options.mutationKey &&\n hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)\n ) {\n this.reset()\n } else if (this.#currentMutation?.state.status === 'pending') {\n this.#currentMutation.setOptions(this.options)\n }\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1 && this.#currentMutation) {\n this.#currentMutation.addObserver(this)\n\n this.#updateResult()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.#currentMutation?.removeObserver(this)\n }\n }\n\n /** @internal */\n onMutationUpdate(\n action: Action<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.#updateResult()\n\n this.#notify(action)\n }\n\n /**\n * Returns the observer's current result, derived from the observed\n * mutation's state (or the default, `idle` state if no mutation has been\n * built yet, e.g. before the first `mutate()` call or after `reset()`).\n */\n getCurrentResult(): MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > {\n return this.#currentResult\n }\n\n /**\n * Detaches the observer from the mutation it is currently observing (if\n * any) and resets the observed result back to its dLine truncated
@@ -0,0 +1,2 @@
import { qn as MutationObserver } from "./hydration-DwR10Hi-.cjs";
export { MutationObserver };
@@ -0,0 +1,2 @@
import { qn as MutationObserver } from "./hydration-Cq7QYAzB.js";
export { MutationObserver };
+207
View File
@@ -0,0 +1,207 @@
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
import { hashKey, shallowEqualObjects } from "./utils.js";
import { Subscribable } from "./subscribable.js";
import { notifyManager } from "./notifyManager.js";
import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-CBwa_Y7C.js";
import { getDefaultState } from "./mutation.js";
//#region src/mutationObserver.ts
var _client = /* @__PURE__ */ new WeakMap();
var _currentResult = /* @__PURE__ */ new WeakMap();
var _currentMutation = /* @__PURE__ */ new WeakMap();
var _mutateOptions = /* @__PURE__ */ new WeakMap();
var _MutationObserver_brand = /* @__PURE__ */ new WeakSet();
/**
* Observes a single mutation and derives a `MutationObserverResult` from it.
* A framework hook like `useMutation` creates one `MutationObserver` per hook
* call, keeps it stable across re-renders, calls `setOptions` when the options
* passed to the hook change, subscribes to it to re-render on updates, and
* reads `getCurrentResult()` for the value to return. Calling `mutate()`
* builds a new underlying `Mutation` in the `MutationCache` and executes it.
*
* @example
* ```ts
* const observer = new MutationObserver(queryClient, {
* mutationFn: (variables: { title: string }) => addPost(variables),
* })
* ```
*/
var MutationObserver = class extends Subscribable {
constructor(client, options) {
super();
_classPrivateMethodInitSpec(this, _MutationObserver_brand);
_classPrivateFieldInitSpec(this, _client, void 0);
_classPrivateFieldInitSpec(this, _currentResult, void 0);
_classPrivateFieldInitSpec(this, _currentMutation, void 0);
_classPrivateFieldInitSpec(this, _mutateOptions, void 0);
_classPrivateFieldSet2(_client, this, client);
this.setOptions(options);
this.bindMethods();
_assertClassBrand(_MutationObserver_brand, this, _updateResult).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 _classPrivateFieldGet2$1;
const prevOptions = this.options;
this.options = _classPrivateFieldGet2(_client, this).defaultMutationOptions(options);
if (!shallowEqualObjects(this.options, prevOptions)) _classPrivateFieldGet2(_client, this).getMutationCache().notify({
type: "observerOptionsUpdated",
mutation: _classPrivateFieldGet2(_currentMutation, this),
observer: this
});
if ((prevOptions === null || prevOptions === void 0 ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) this.reset();
else if (((_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.state.status) === "pending") _classPrivateFieldGet2(_currentMutation, this).setOptions(this.options);
}
onSubscribe() {
if (this.listeners.size === 1 && _classPrivateFieldGet2(_currentMutation, this)) {
_classPrivateFieldGet2(_currentMutation, this).addObserver(this);
_assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
var _classPrivateFieldGet3;
(_classPrivateFieldGet3 = _classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.removeObserver(this);
}
}
/** @internal */
onMutationUpdate(action) {
_assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
_assertClassBrand(_MutationObserver_brand, this, _notify).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 _classPrivateFieldGet2(_currentResult, this);
}
/**
* 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 _classPrivateFieldGet4;
(_classPrivateFieldGet4 = _classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet4 === void 0 || _classPrivateFieldGet4.removeObserver(this);
_classPrivateFieldSet2(_currentMutation, this, void 0);
_assertClassBrand(_MutationObserver_brand, this, _updateResult).call(this);
_assertClassBrand(_MutationObserver_brand, this, _notify).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 _classPrivateFieldGet5;
_classPrivateFieldSet2(_mutateOptions, this, options);
(_classPrivateFieldGet5 = _classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet5 === void 0 || _classPrivateFieldGet5.removeObserver(this);
_classPrivateFieldSet2(_currentMutation, this, _classPrivateFieldGet2(_client, this).getMutationCache().build(_classPrivateFieldGet2(_client, this), this.options));
_classPrivateFieldGet2(_currentMutation, this).addObserver(this);
return _classPrivateFieldGet2(_currentMutation, this).execute(variables);
}
};
function _updateResult() {
var _classPrivateFieldGet6;
const state = ((_classPrivateFieldGet6 = _classPrivateFieldGet2(_currentMutation, this)) === null || _classPrivateFieldGet6 === void 0 ? void 0 : _classPrivateFieldGet6.state) ?? getDefaultState();
_classPrivateFieldSet2(_currentResult, this, {
...state,
isPending: state.status === "pending",
isSuccess: state.status === "success",
isError: state.status === "error",
isIdle: state.status === "idle",
mutate: this.mutate,
reset: this.reset
});
}
function _notify(action) {
notifyManager.batch(() => {
if (_classPrivateFieldGet2(_mutateOptions, this) && this.hasListeners()) {
const variables = _classPrivateFieldGet2(_currentResult, this).variables;
const onMutateResult = _classPrivateFieldGet2(_currentResult, this).context;
const context = {
client: _classPrivateFieldGet2(_client, this),
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
if ((action === null || action === void 0 ? void 0 : action.type) === "success") {
try {
var _classPrivateFieldGet7, _classPrivateFieldGet8;
(_classPrivateFieldGet7 = (_classPrivateFieldGet8 = _classPrivateFieldGet2(_mutateOptions, this)).onSuccess) === null || _classPrivateFieldGet7 === void 0 || _classPrivateFieldGet7.call(_classPrivateFieldGet8, action.data, variables, onMutateResult, context);
} catch (e) {
Promise.reject(e);
}
try {
var _classPrivateFieldGet9, _classPrivateFieldGet10;
(_classPrivateFieldGet9 = (_classPrivateFieldGet10 = _classPrivateFieldGet2(_mutateOptions, this)).onSettled) === null || _classPrivateFieldGet9 === void 0 || _classPrivateFieldGet9.call(_classPrivateFieldGet10, action.data, null, variables, onMutateResult, context);
} catch (e) {
Promise.reject(e);
}
} else if ((action === null || action === void 0 ? void 0 : action.type) === "error") {
try {
var _classPrivateFieldGet11, _classPrivateFieldGet12;
(_classPrivateFieldGet11 = (_classPrivateFieldGet12 = _classPrivateFieldGet2(_mutateOptions, this)).onError) === null || _classPrivateFieldGet11 === void 0 || _classPrivateFieldGet11.call(_classPrivateFieldGet12, action.error, variables, onMutateResult, context);
} catch (e) {
Promise.reject(e);
}
try {
var _classPrivateFieldGet13, _classPrivateFieldGet14;
(_classPrivateFieldGet13 = (_classPrivateFieldGet14 = _classPrivateFieldGet2(_mutateOptions, this)).onSettled) === null || _classPrivateFieldGet13 === void 0 || _classPrivateFieldGet13.call(_classPrivateFieldGet14, void 0, action.error, variables, onMutateResult, context);
} catch (e) {
Promise.reject(e);
}
}
}
this.listeners.forEach((listener) => {
listener(_classPrivateFieldGet2(_currentResult, this));
});
});
}
//#endregion
export { MutationObserver };
//# sourceMappingURL=mutationObserver.js.map
@@ -0,0 +1 @@
{"version":3,"file":"mutationObserver.js","names":[],"sources":["../../src/mutationObserver.ts"],"sourcesContent":["import { getDefaultState } from './mutation'\nimport { notifyManager } from './notifyManager'\nimport { Subscribable } from './subscribable'\nimport { hashKey, shallowEqualObjects } from './utils'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultError,\n MutateOptions,\n MutationFunctionContext,\n MutationObserverOptions,\n MutationObserverResult,\n} from './types'\nimport type { Action, Mutation } from './mutation'\n\n// TYPES\n\ntype MutationObserverListener<TData, TError, TVariables, TOnMutateResult> = (\n result: MutationObserverResult<TData, TError, TVariables, TOnMutateResult>,\n) => void\n\n// CLASS\n\n/**\n * Observes a single mutation and derives a `MutationObserverResult` from it.\n * A framework hook like `useMutation` creates one `MutationObserver` per hook\n * call, keeps it stable across re-renders, calls `setOptions` when the options\n * passed to the hook change, subscribes to it to re-render on updates, and\n * reads `getCurrentResult()` for the value to return. Calling `mutate()`\n * builds a new underlying `Mutation` in the `MutationCache` and executes it.\n *\n * @example\n * ```ts\n * const observer = new MutationObserver(queryClient, {\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * })\n * ```\n */\nexport class MutationObserver<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n> extends Subscribable<\n MutationObserverListener<TData, TError, TVariables, TOnMutateResult>\n> {\n options!: MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n\n #client: QueryClient\n #currentResult: MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = undefined!\n #currentMutation?: Mutation<TData, TError, TVariables, TOnMutateResult>\n #mutateOptions?: MutateOptions<TData, TError, TVariables, TOnMutateResult>\n\n constructor(\n client: QueryClient,\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n super()\n\n this.#client = client\n this.setOptions(options)\n this.bindMethods()\n this.#updateResult()\n }\n\n protected bindMethods(): void {\n this.mutate = this.mutate.bind(this)\n this.reset = this.reset.bind(this)\n }\n\n /**\n * Updates the observer's options.\n *\n * If the new `mutationKey` differs from the previous one (and both were\n * defined), the observer is reset, detaching it from the mutation it was\n * observing. Otherwise, if the currently observed mutation is still\n * `pending`, its options are updated in place as well.\n *\n * @example\n * ```ts\n * observer.setOptions({\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * onSuccess: (data) => console.log(data),\n * })\n * ```\n */\n setOptions(\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n const prevOptions = this.options as\n | MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n | undefined\n this.options = this.#client.defaultMutationOptions(options)\n if (!shallowEqualObjects(this.options, prevOptions)) {\n this.#client.getMutationCache().notify({\n type: 'observerOptionsUpdated',\n mutation: this.#currentMutation,\n observer: this,\n })\n }\n\n if (\n prevOptions?.mutationKey &&\n this.options.mutationKey &&\n hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)\n ) {\n this.reset()\n } else if (this.#currentMutation?.state.status === 'pending') {\n this.#currentMutation.setOptions(this.options)\n }\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1 && this.#currentMutation) {\n this.#currentMutation.addObserver(this)\n\n this.#updateResult()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.#currentMutation?.removeObserver(this)\n }\n }\n\n /** @internal */\n onMutationUpdate(\n action: Action<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.#updateResult()\n\n this.#notify(action)\n }\n\n /**\n * Returns the observer's current result, derived from the observed\n * mutation's state (or the default, `idle` state if no mutation has been\n * built yet, e.g. before the first `mutate()` call or after `reset()`).\n */\n getCurrentResult(): MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > {\n return this.#currentResult\n }\n\n /**\n * Detaches the observer from the mutation it is currently observing (if\n * any) and resets the observed result back to its default, `idle` state.\n *\n * This does not cancel an in-fligLine truncated
+123
View File
@@ -0,0 +1,123 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/notifyManager.ts
/**
* Default scheduling function used by the notify manager.
* Schedules the callback with the system's `setTimeout(callback, 0)`.
*/
const defaultScheduler = require("./timeoutManager.cjs").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;
}
};
}
/**
* Handles scheduling and batching callbacks in TanStack Query.
*/
const notifyManager = createNotifyManager();
//#endregion
exports.createNotifyManager = createNotifyManager;
exports.defaultScheduler = defaultScheduler;
exports.notifyManager = notifyManager;
//# sourceMappingURL=notifyManager.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"notifyManager.cjs","names":["systemSetTimeoutZero"],"sources":["../../src/notifyManager.ts"],"sourcesContent":["// TYPES\n\nimport { systemSetTimeoutZero } from './timeoutManager'\n\ntype NotifyCallback = () => void\n\ntype NotifyFunction = (callback: () => void) => void\n\ntype BatchNotifyFunction = (callback: () => void) => void\n\ntype BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void\n\ntype ScheduleFunction = (callback: () => void) => void\n\n/**\n * Default scheduling function used by the notify manager.\n * Schedules the callback with the system's `setTimeout(callback, 0)`.\n */\nexport const defaultScheduler: ScheduleFunction = systemSetTimeoutZero\n\nexport function createNotifyManager() {\n let queue: Array<NotifyCallback> = []\n let transactions = 0\n let notifyFn: NotifyFunction = (callback) => {\n callback()\n }\n let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => {\n callback()\n }\n let scheduleFn = defaultScheduler\n\n const schedule = (callback: NotifyCallback): void => {\n if (transactions) {\n queue.push(callback)\n } else {\n scheduleFn(() => {\n notifyFn(callback)\n })\n }\n }\n const flush = (): void => {\n const originalQueue = queue\n queue = []\n if (originalQueue.length) {\n scheduleFn(() => {\n batchNotifyFn(() => {\n originalQueue.forEach((callback) => {\n notifyFn(callback)\n })\n })\n })\n }\n }\n\n return {\n /**\n * Batches all updates scheduled inside the passed callback.\n * This is mainly used internally to optimize query client updating.\n * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.\n * The return value of `callback` is passed through.\n */\n batch: <T>(callback: () => T): T => {\n let result\n transactions++\n try {\n result = callback()\n } finally {\n transactions--\n if (!transactions) {\n flush()\n }\n }\n return result\n },\n /**\n * All calls to the wrapped function will be batched.\n */\n batchCalls: <T extends Array<unknown>>(\n callback: BatchCallsCallback<T>,\n ): BatchCallsCallback<T> => {\n return (...args) => {\n schedule(() => {\n callback(...args)\n })\n }\n },\n /**\n * Schedules a function to be run on the next batch.\n * By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.\n */\n schedule,\n /**\n * Use this method to set a custom notify function.\n * This can be used to for example wrap notifications with `React.act` while running tests.\n */\n setNotifyFunction: (fn: NotifyFunction) => {\n notifyFn = fn\n },\n /**\n * Use this method to set a custom function to batch notifications together into a single tick.\n * Framework adapters use this to plug in their own batching primitive, so that a single query\n * update only triggers one re-render instead of one per subscriber.\n *\n * @example\n * ```ts\n * import { notifyManager } from '@tanstack/query-core'\n * import { batch } from 'solid-js'\n *\n * notifyManager.setBatchNotifyFunction(batch)\n * ```\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n /**\n * Configures a custom callback that schedules when the next batch runs.\n * The default behavior is `setTimeout(callback, 0)`.\n *\n * @example\n * ```ts\n * import { notifyManager } from '@tanstack/query-core'\n *\n * // Schedule batches in the next microtask\n * notifyManager.setScheduler(queueMicrotask)\n *\n * // Schedule batches before the next frame is rendered\n * notifyManager.setScheduler(requestAnimationFrame)\n *\n * // Schedule batches some time in the future\n * notifyManager.setScheduler((cb) => setTimeout(cb, 10))\n * ```\n */\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\n\n/**\n * Handles scheduling and batching callbacks in TanStack Query.\n */\nexport const notifyManager = createNotifyManager()\n"],"mappings":";;;;;;AAkBA,MAAa,iDAAqCA,CAAAA,CAAAA;AAElD,SAAgB,sBAAsB;CACpC,IAAI,QAA+B,CAAC;CACpC,IAAI,eAAe;CACnB,IAAI,YAA4B,aAAa;EAC3C,SAAS;CACX;CACA,IAAI,iBAAsC,aAAyB;EACjE,SAAS;CACX;CACA,IAAI,aAAa;CAEjB,MAAM,YAAY,aAAmC;EACnD,IAAI,cACF,MAAM,KAAK,QAAQ;OAEnB,iBAAiB;GACf,SAAS,QAAQ;EACnB,CAAC;CAEL;CACA,MAAM,cAAoB;EACxB,MAAM,gBAAgB;EACtB,QAAQ,CAAC;EACT,IAAI,cAAc,QAChB,iBAAiB;GACf,oBAAoB;IAClB,cAAc,SAAS,aAAa;KAClC,SAAS,QAAQ;IACnB,CAAC;GACH,CAAC;EACH,CAAC;CAEL;CAEA,OAAO;;;;;;;EAOL,QAAW,aAAyB;GAClC,IAAI;GACJ;GACA,IAAI;IACF,SAAS,SAAS;GACpB,UAAU;IACR;IACA,IAAI,CAAC,cACH,MAAM;GAEV;GACA,OAAO;EACT;;;;EAIA,aACE,aAC0B;GAC1B,QAAQ,GAAG,SAAS;IAClB,eAAe;KACb,SAAS,GAAG,IAALine truncated
+129
View File
@@ -0,0 +1,129 @@
//#region src/notifyManager.d.ts
type NotifyCallback = () => void;
type NotifyFunction = (callback: () => void) => void;
type BatchNotifyFunction = (callback: () => void) => void;
type BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void;
type ScheduleFunction = (callback: () => void) => void;
/**
* Default scheduling function used by the notify manager.
* Schedules the callback with the system's `setTimeout(callback, 0)`.
*/
declare const defaultScheduler: ScheduleFunction;
declare function createNotifyManager(): {
/**
* 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.
*/
readonly batch: <T>(callback: () => T) => T;
/**
* All calls to the wrapped function will be batched.
*/
readonly batchCalls: <T extends Array<unknown>>(callback: BatchCallsCallback<T>) => BatchCallsCallback<T>;
/**
* 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`.
*/
readonly schedule: (callback: NotifyCallback) => void;
/**
* Use this method to set a custom notify function.
* This can be used to for example wrap notifications with `React.act` while running tests.
*/
readonly setNotifyFunction: (fn: NotifyFunction) => void;
/**
* 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)
* ```
*/
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
/**
* 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))
* ```
*/
readonly setScheduler: (fn: ScheduleFunction) => void;
};
/**
* Handles scheduling and batching callbacks in TanStack Query.
*/
declare const notifyManager: {
/**
* 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.
*/
readonly batch: <T>(callback: () => T) => T;
/**
* All calls to the wrapped function will be batched.
*/
readonly batchCalls: <T extends Array<unknown>>(callback: BatchCallsCallback<T>) => BatchCallsCallback<T>;
/**
* 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`.
*/
readonly schedule: (callback: NotifyCallback) => void;
/**
* Use this method to set a custom notify function.
* This can be used to for example wrap notifications with `React.act` while running tests.
*/
readonly setNotifyFunction: (fn: NotifyFunction) => void;
/**
* 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)
* ```
*/
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
/**
* 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))
* ```
*/
readonly setScheduler: (fn: ScheduleFunction) => void;
};
//#endregion
export { createNotifyManager, defaultScheduler, notifyManager };
//# sourceMappingURL=notifyManager.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"notifyManager.d.cts","names":[],"sources":["../../src/notifyManager.ts"],"mappings":";KAIK;KAEA,kBAAkB;KAElB,uBAAuB;KAEvB,mBAAmB,UAAU,sBAAsB,MAAM;KAEzD,oBAAoB;;;;;cAMZ,kBAAkB;iBAEf;;;;;;;WAyCJ,QAAA,GAAC,gBAAkB,MAAI;;;;WAgBlB,aAAA,UAAU,gBAAc,UACzB,mBAAmB,OAC5B,mBAAmB;;;;;WAhDI,WAAA,UAAA;;;;;WAgEF,oBAAA,IAAA;;;;;;;;;;;;;;WAgBK,yBAAA,IAAA;;;;;;;;;;;;;;;;;;;WAqBV,eAAA,IAAA;;;;;cAWV;;;;;;;WAlFD,QAAA,GAAC,gBAAkB,MAAI;;;;WAgBlB,aAAA,UAAU,gBAAc,UACzB,mBAAmB,OAC5B,mBAAmB;;;;;WAhDI,WAAA,UAAA;;;;;WAgEF,oBAAA,IAAA;;;;;;;;;;;;;;WAgBK,yBAAA,IAAA;;;;;;;;;;;;;;;;;;;WAqBV,eAAA,IAAA"}
+129
View File
@@ -0,0 +1,129 @@
//#region src/notifyManager.d.ts
type NotifyCallback = () => void;
type NotifyFunction = (callback: () => void) => void;
type BatchNotifyFunction = (callback: () => void) => void;
type BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void;
type ScheduleFunction = (callback: () => void) => void;
/**
* Default scheduling function used by the notify manager.
* Schedules the callback with the system's `setTimeout(callback, 0)`.
*/
declare const defaultScheduler: ScheduleFunction;
declare function createNotifyManager(): {
/**
* 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.
*/
readonly batch: <T>(callback: () => T) => T;
/**
* All calls to the wrapped function will be batched.
*/
readonly batchCalls: <T extends Array<unknown>>(callback: BatchCallsCallback<T>) => BatchCallsCallback<T>;
/**
* 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`.
*/
readonly schedule: (callback: NotifyCallback) => void;
/**
* Use this method to set a custom notify function.
* This can be used to for example wrap notifications with `React.act` while running tests.
*/
readonly setNotifyFunction: (fn: NotifyFunction) => void;
/**
* 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)
* ```
*/
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
/**
* 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))
* ```
*/
readonly setScheduler: (fn: ScheduleFunction) => void;
};
/**
* Handles scheduling and batching callbacks in TanStack Query.
*/
declare const notifyManager: {
/**
* 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.
*/
readonly batch: <T>(callback: () => T) => T;
/**
* All calls to the wrapped function will be batched.
*/
readonly batchCalls: <T extends Array<unknown>>(callback: BatchCallsCallback<T>) => BatchCallsCallback<T>;
/**
* 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`.
*/
readonly schedule: (callback: NotifyCallback) => void;
/**
* Use this method to set a custom notify function.
* This can be used to for example wrap notifications with `React.act` while running tests.
*/
readonly setNotifyFunction: (fn: NotifyFunction) => void;
/**
* 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)
* ```
*/
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
/**
* 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))
* ```
*/
readonly setScheduler: (fn: ScheduleFunction) => void;
};
//#endregion
export { createNotifyManager, defaultScheduler, notifyManager };
//# sourceMappingURL=notifyManager.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"notifyManager.d.ts","names":[],"sources":["../../src/notifyManager.ts"],"mappings":";KAIK;KAEA,kBAAkB;KAElB,uBAAuB;KAEvB,mBAAmB,UAAU,sBAAsB,MAAM;KAEzD,oBAAoB;;;;;cAMZ,kBAAkB;iBAEf;;;;;;;WAyCJ,QAAA,GAAC,gBAAkB,MAAI;;;;WAgBlB,aAAA,UAAU,gBAAc,UACzB,mBAAmB,OAC5B,mBAAmB;;;;;WAhDI,WAAA,UAAA;;;;;WAgEF,oBAAA,IAAA;;;;;;;;;;;;;;WAgBK,yBAAA,IAAA;;;;;;;;;;;;;;;;;;;WAqBV,eAAA,IAAA;;;;;cAWV;;;;;;;WAlFD,QAAA,GAAC,gBAAkB,MAAI;;;;WAgBlB,aAAA,UAAU,gBAAc,UACzB,mBAAmB,OAC5B,mBAAmB;;;;;WAhDI,WAAA,UAAA;;;;;WAgEF,oBAAA,IAAA;;;;;;;;;;;;;;WAgBK,yBAAA,IAAA;;;;;;;;;;;;;;;;;;;WAqBV,eAAA,IAAA"}
+121
View File
@@ -0,0 +1,121 @@
import { systemSetTimeoutZero } from "./timeoutManager.js";
//#region src/notifyManager.ts
/**
* Default scheduling function used by the notify manager.
* Schedules the callback with the system's `setTimeout(callback, 0)`.
*/
const 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;
}
};
}
/**
* Handles scheduling and batching callbacks in TanStack Query.
*/
const notifyManager = createNotifyManager();
//#endregion
export { createNotifyManager, defaultScheduler, notifyManager };
//# sourceMappingURL=notifyManager.js.map
@@ -0,0 +1 @@
{"version":3,"file":"notifyManager.js","names":[],"sources":["../../src/notifyManager.ts"],"sourcesContent":["// TYPES\n\nimport { systemSetTimeoutZero } from './timeoutManager'\n\ntype NotifyCallback = () => void\n\ntype NotifyFunction = (callback: () => void) => void\n\ntype BatchNotifyFunction = (callback: () => void) => void\n\ntype BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void\n\ntype ScheduleFunction = (callback: () => void) => void\n\n/**\n * Default scheduling function used by the notify manager.\n * Schedules the callback with the system's `setTimeout(callback, 0)`.\n */\nexport const defaultScheduler: ScheduleFunction = systemSetTimeoutZero\n\nexport function createNotifyManager() {\n let queue: Array<NotifyCallback> = []\n let transactions = 0\n let notifyFn: NotifyFunction = (callback) => {\n callback()\n }\n let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => {\n callback()\n }\n let scheduleFn = defaultScheduler\n\n const schedule = (callback: NotifyCallback): void => {\n if (transactions) {\n queue.push(callback)\n } else {\n scheduleFn(() => {\n notifyFn(callback)\n })\n }\n }\n const flush = (): void => {\n const originalQueue = queue\n queue = []\n if (originalQueue.length) {\n scheduleFn(() => {\n batchNotifyFn(() => {\n originalQueue.forEach((callback) => {\n notifyFn(callback)\n })\n })\n })\n }\n }\n\n return {\n /**\n * Batches all updates scheduled inside the passed callback.\n * This is mainly used internally to optimize query client updating.\n * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.\n * The return value of `callback` is passed through.\n */\n batch: <T>(callback: () => T): T => {\n let result\n transactions++\n try {\n result = callback()\n } finally {\n transactions--\n if (!transactions) {\n flush()\n }\n }\n return result\n },\n /**\n * All calls to the wrapped function will be batched.\n */\n batchCalls: <T extends Array<unknown>>(\n callback: BatchCallsCallback<T>,\n ): BatchCallsCallback<T> => {\n return (...args) => {\n schedule(() => {\n callback(...args)\n })\n }\n },\n /**\n * Schedules a function to be run on the next batch.\n * By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.\n */\n schedule,\n /**\n * Use this method to set a custom notify function.\n * This can be used to for example wrap notifications with `React.act` while running tests.\n */\n setNotifyFunction: (fn: NotifyFunction) => {\n notifyFn = fn\n },\n /**\n * Use this method to set a custom function to batch notifications together into a single tick.\n * Framework adapters use this to plug in their own batching primitive, so that a single query\n * update only triggers one re-render instead of one per subscriber.\n *\n * @example\n * ```ts\n * import { notifyManager } from '@tanstack/query-core'\n * import { batch } from 'solid-js'\n *\n * notifyManager.setBatchNotifyFunction(batch)\n * ```\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n /**\n * Configures a custom callback that schedules when the next batch runs.\n * The default behavior is `setTimeout(callback, 0)`.\n *\n * @example\n * ```ts\n * import { notifyManager } from '@tanstack/query-core'\n *\n * // Schedule batches in the next microtask\n * notifyManager.setScheduler(queueMicrotask)\n *\n * // Schedule batches before the next frame is rendered\n * notifyManager.setScheduler(requestAnimationFrame)\n *\n * // Schedule batches some time in the future\n * notifyManager.setScheduler((cb) => setTimeout(cb, 10))\n * ```\n */\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\n\n/**\n * Handles scheduling and batching callbacks in TanStack Query.\n */\nexport const notifyManager = createNotifyManager()\n"],"mappings":";;;;;;AAkBA,MAAa,mBAAqC;AAElD,SAAgB,sBAAsB;CACpC,IAAI,QAA+B,CAAC;CACpC,IAAI,eAAe;CACnB,IAAI,YAA4B,aAAa;EAC3C,SAAS;CACX;CACA,IAAI,iBAAsC,aAAyB;EACjE,SAAS;CACX;CACA,IAAI,aAAa;CAEjB,MAAM,YAAY,aAAmC;EACnD,IAAI,cACF,MAAM,KAAK,QAAQ;OAEnB,iBAAiB;GACf,SAAS,QAAQ;EACnB,CAAC;CAEL;CACA,MAAM,cAAoB;EACxB,MAAM,gBAAgB;EACtB,QAAQ,CAAC;EACT,IAAI,cAAc,QAChB,iBAAiB;GACf,oBAAoB;IAClB,cAAc,SAAS,aAAa;KAClC,SAAS,QAAQ;IACnB,CAAC;GACH,CAAC;EACH,CAAC;CAEL;CAEA,OAAO;;;;;;;EAOL,QAAW,aAAyB;GAClC,IAAI;GACJ;GACA,IAAI;IACF,SAAS,SAAS;GACpB,UAAU;IACR;IACA,IAAI,CAAC,cACH,MAAM;GAEV;GACA,OAAO;EACT;;;;EAIA,aACE,aAC0B;GAC1B,QAAQ,GAAG,SAAS;IAClB,eAAe;KACb,SAAS,GAAG,IAAI;IAClB,CAAC;GACH;EACF;;;;;EAKA;;;;;Line truncated
+107
View File
@@ -0,0 +1,107 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
const require_subscribable = require("./subscribable.cjs");
//#region src/onlineManager.ts
var _online = /* @__PURE__ */ new WeakMap();
var _cleanup = /* @__PURE__ */ new WeakMap();
var _setup = /* @__PURE__ */ new WeakMap();
/**
* The `OnlineManager` manages the online state within TanStack Query. It can
* be used to change the default event listeners or to manually change the
* online state.
*
* By default, the `onlineManager` assumes an active network connection, and
* listens to the `online` and `offline` events on the `window` object to
* detect changes.
*/
var OnlineManager = class extends require_subscribable.Subscribable {
constructor() {
super();
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _online, true);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _cleanup, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _setup, void 0);
require_classPrivateFieldSet2._classPrivateFieldSet2(_setup, this, (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 (!require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) this.setEventListener(require_classPrivateFieldSet2._classPrivateFieldGet2(_setup, this));
}
onUnsubscribe() {
if (!this.hasListeners()) {
var _classPrivateFieldGet2$1;
(_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet2$1 === void 0 || _classPrivateFieldGet2$1.call(this);
require_classPrivateFieldSet2._classPrivateFieldSet2(_cleanup, this, 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 _classPrivateFieldGet3;
require_classPrivateFieldSet2._classPrivateFieldSet2(_setup, this, setup);
(_classPrivateFieldGet3 = require_classPrivateFieldSet2._classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.call(this);
require_classPrivateFieldSet2._classPrivateFieldSet2(_cleanup, this, 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 (require_classPrivateFieldSet2._classPrivateFieldGet2(_online, this) !== online) {
require_classPrivateFieldSet2._classPrivateFieldSet2(_online, this, online);
this.listeners.forEach((listener) => {
listener(online);
});
}
}
/**
* `isOnline` can be used to get the current online state.
*/
isOnline() {
return require_classPrivateFieldSet2._classPrivateFieldGet2(_online, this);
}
};
/**
* Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.
*/
const onlineManager = new OnlineManager();
//#endregion
exports.OnlineManager = OnlineManager;
exports.onlineManager = onlineManager;
//# sourceMappingURL=onlineManager.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"onlineManager.cjs","names":["Subscribable"],"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\n\n/**\n * The `OnlineManager` manages the online state within TanStack Query. It can\n * be used to change the default event listeners or to manually change the\n * online state.\n *\n * By default, the `onlineManager` assumes an active network connection, and\n * listens to the `online` and `offline` events on the `window` object to\n * detect changes.\n */\nexport class OnlineManager extends Subscribable<Listener> {\n #online = true\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onOnline) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const onlineListener = () => onOnline(true)\n const offlineListener = () => onOnline(false)\n // Listen to online\n window.addEventListener('online', onlineListener, false)\n window.addEventListener('offline', offlineListener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('online', onlineListener)\n window.removeEventListener('offline', offlineListener)\n }\n }\n\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n /**\n * `setEventListener` can be used to set a custom event listener that will\n * be used to determine the online state. The provided `setup` function\n * receives a `setOnline` callback that should be called with a `boolean`\n * whenever the online state changes.\n *\n * @example\n * ```ts\n * import NetInfo from '@react-native-community/netinfo'\n * import { onlineManager } from '@tanstack/query-core'\n *\n * onlineManager.setEventListener((setOnline) => {\n * return NetInfo.addEventListener((state) => {\n * setOnline(!!state.isConnected)\n * })\n * })\n * ```\n */\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\n }\n\n /**\n * `setOnline` can be used to manually set the online state.\n *\n * @example\n * ```ts\n * import { onlineManager } from '@tanstack/query-core'\n *\n * // Set to online\n * onlineManager.setOnline(true)\n *\n * // Set to offline\n * onlineManager.setOnline(false)\n * ```\n */\n setOnline(online: boolean): void {\n const changed = this.#online !== online\n\n if (changed) {\n this.#online = online\n this.listeners.forEach((listener) => {\n listener(online)\n })\n }\n }\n\n /**\n * `isOnline` can be used to get the current online state.\n */\n isOnline(): boolean {\n return this.#online\n }\n}\n\n/**\n * Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.\n */\nexport const onlineManager = new OnlineManager()\n"],"mappings":";;;;;;;;;;;;;;;;AAcA,IAAa,gBAAb,cAAmCA,qBAAAA,aAAuB;CAMxD,cAAc;EACZ,MAAM;EANE,8BAAA,2BAAA,MAAA,SAAA,IAAA;;;EAOR,8BAAA,uBAAA,QAAA,OAAe,aAAa;GAG1B,IAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;IAC5D,MAAM,uBAAuB,SAAS,IAAI;IAC1C,MAAM,wBAAwB,SAAS,KAAK;IAE5C,OAAO,iBAAiB,UAAU,gBAAgB,KAAK;IACvD,OAAO,iBAAiB,WAAW,iBAAiB,KAAK;IAEzD,aAAa;KAEX,OAAO,oBAAoB,UAAU,cAAc;KACnD,OAAO,oBAAoB,WAAW,eAAe;IACvD;GACF;EAGF,CAAA;CACF;CAEA,cAA8B;EAC5B,IAAI,CAAA,8BAAA,uBAAA,UAAC,IAAA,GACH,KAAK,iBAAA,8BAAA,uBAAA,QAAiB,IAAA,CAAW;CAErC;CAEA,gBAA0B;EACxB,IAAI,CAAC,KAAK,aAAa,GAAG;;GACxB,CAAA,2BAAA,8BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,6BAAA,KAAA,KAAA,yBAAA,KAAA,IAAgB;GAChB,8BAAA,uBAAA,UAAA,MAAgB,KAAA,CAAA;EAClB;CACF;;;;;;;;;;;;;;;;;;;CAoBA,iBAAiB,OAAsB;;EACrC,8BAAA,uBAAA,QAAA,MAAc,KAAA;EACd,CAAA,yBAAA,8BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,2BAAA,KAAA,KAAA,uBAAA,KAAA,IAAgB;EAChB,8BAAA,uBAAA,UAAA,MAAgB,MAAM,KAAK,UAAU,KAAK,IAAI,CAAC,CAAA;CACjD;;;;;;;;;;;;;;;CAgBA,UAAU,QAAuB;EAG/B,IAAA,8BAAA,uBAAA,SAFgB,IAAA,MAAiB,QAEpB;GACX,8BAAA,uBAAA,SAAA,MAAe,MAAA;GACf,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,MAAM;GACjB,CAAC;EACH;CACF;;;;CAKA,WAAoB;EAClB,OAAA,8BAAA,uBAAA,SAAO,IAAA;CACT;AACF;;;;AAKA,MAAa,gBAAgB,IAAI,cAAc"}
+64
View File
@@ -0,0 +1,64 @@
import { t as Subscribable } from "./subscribable-CbifVTKz.cjs";
//#region src/onlineManager.d.ts
type Listener = (online: boolean) => void;
type SetupFn = (setOnline: Listener) => (() => void) | undefined;
/**
* The `OnlineManager` manages the online state within TanStack Query. It can
* be used to change the default event listeners or to manually change the
* online state.
*
* By default, the `onlineManager` assumes an active network connection, and
* listens to the `online` and `offline` events on the `window` object to
* detect changes.
*/
declare class OnlineManager extends Subscribable<Listener> {
#private;
constructor();
protected onSubscribe(): void;
protected onUnsubscribe(): void;
/**
* `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: SetupFn): void;
/**
* `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: boolean): void;
/**
* `isOnline` can be used to get the current online state.
*/
isOnline(): boolean;
}
/**
* Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.
*/
declare const onlineManager: OnlineManager;
//#endregion
export { OnlineManager, onlineManager };
//# sourceMappingURL=onlineManager.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"onlineManager.d.cts","names":[],"sources":["../../src/onlineManager.ts"],"mappings":";;KAEK,YAAY;KACZ,WAAW,WAAW;;;;;;;;;;cAWd,sBAAsB,aAAa;;;YA6BpC;YAMA;;;;;;;;;;;;;;;;;;;EAyBV,iBAAiB,OAAO;;;;;;;;;;;;;;;EAoBxB,UAAU;;;;EAcV;;;;;cAQW,eAAa"}
+64
View File
@@ -0,0 +1,64 @@
import { t as Subscribable } from "./subscribable-CbifVTKz.js";
//#region src/onlineManager.d.ts
type Listener = (online: boolean) => void;
type SetupFn = (setOnline: Listener) => (() => void) | undefined;
/**
* The `OnlineManager` manages the online state within TanStack Query. It can
* be used to change the default event listeners or to manually change the
* online state.
*
* By default, the `onlineManager` assumes an active network connection, and
* listens to the `online` and `offline` events on the `window` object to
* detect changes.
*/
declare class OnlineManager extends Subscribable<Listener> {
#private;
constructor();
protected onSubscribe(): void;
protected onUnsubscribe(): void;
/**
* `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: SetupFn): void;
/**
* `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: boolean): void;
/**
* `isOnline` can be used to get the current online state.
*/
isOnline(): boolean;
}
/**
* Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.
*/
declare const onlineManager: OnlineManager;
//#endregion
export { OnlineManager, onlineManager };
//# sourceMappingURL=onlineManager.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"onlineManager.d.ts","names":[],"sources":["../../src/onlineManager.ts"],"mappings":";;KAEK,YAAY;KACZ,WAAW,WAAW;;;;;;;;;;cAWd,sBAAsB,aAAa;;;YA6BpC;YAMA;;;;;;;;;;;;;;;;;;;EAyBV,iBAAiB,OAAO;;;;;;;;;;;;;;;EAoBxB,UAAU;;;;EAcV;;;;;cAQW,eAAa"}
+105
View File
@@ -0,0 +1,105 @@
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CV7wyte-.js";
import { Subscribable } from "./subscribable.js";
//#region src/onlineManager.ts
var _online = /* @__PURE__ */ new WeakMap();
var _cleanup = /* @__PURE__ */ new WeakMap();
var _setup = /* @__PURE__ */ new WeakMap();
/**
* The `OnlineManager` manages the online state within TanStack Query. It can
* be used to change the default event listeners or to manually change the
* online state.
*
* By default, the `onlineManager` assumes an active network connection, and
* listens to the `online` and `offline` events on the `window` object to
* detect changes.
*/
var OnlineManager = class extends Subscribable {
constructor() {
super();
_classPrivateFieldInitSpec(this, _online, true);
_classPrivateFieldInitSpec(this, _cleanup, void 0);
_classPrivateFieldInitSpec(this, _setup, void 0);
_classPrivateFieldSet2(_setup, this, (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 (!_classPrivateFieldGet2(_cleanup, this)) this.setEventListener(_classPrivateFieldGet2(_setup, this));
}
onUnsubscribe() {
if (!this.hasListeners()) {
var _classPrivateFieldGet2$1;
(_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet2$1 === void 0 || _classPrivateFieldGet2$1.call(this);
_classPrivateFieldSet2(_cleanup, this, 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 _classPrivateFieldGet3;
_classPrivateFieldSet2(_setup, this, setup);
(_classPrivateFieldGet3 = _classPrivateFieldGet2(_cleanup, this)) === null || _classPrivateFieldGet3 === void 0 || _classPrivateFieldGet3.call(this);
_classPrivateFieldSet2(_cleanup, this, 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 (_classPrivateFieldGet2(_online, this) !== online) {
_classPrivateFieldSet2(_online, this, online);
this.listeners.forEach((listener) => {
listener(online);
});
}
}
/**
* `isOnline` can be used to get the current online state.
*/
isOnline() {
return _classPrivateFieldGet2(_online, this);
}
};
/**
* Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.
*/
const onlineManager = new OnlineManager();
//#endregion
export { OnlineManager, onlineManager };
//# sourceMappingURL=onlineManager.js.map
@@ -0,0 +1 @@
{"version":3,"file":"onlineManager.js","names":[],"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\n\n/**\n * The `OnlineManager` manages the online state within TanStack Query. It can\n * be used to change the default event listeners or to manually change the\n * online state.\n *\n * By default, the `onlineManager` assumes an active network connection, and\n * listens to the `online` and `offline` events on the `window` object to\n * detect changes.\n */\nexport class OnlineManager extends Subscribable<Listener> {\n #online = true\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onOnline) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const onlineListener = () => onOnline(true)\n const offlineListener = () => onOnline(false)\n // Listen to online\n window.addEventListener('online', onlineListener, false)\n window.addEventListener('offline', offlineListener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('online', onlineListener)\n window.removeEventListener('offline', offlineListener)\n }\n }\n\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n /**\n * `setEventListener` can be used to set a custom event listener that will\n * be used to determine the online state. The provided `setup` function\n * receives a `setOnline` callback that should be called with a `boolean`\n * whenever the online state changes.\n *\n * @example\n * ```ts\n * import NetInfo from '@react-native-community/netinfo'\n * import { onlineManager } from '@tanstack/query-core'\n *\n * onlineManager.setEventListener((setOnline) => {\n * return NetInfo.addEventListener((state) => {\n * setOnline(!!state.isConnected)\n * })\n * })\n * ```\n */\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\n }\n\n /**\n * `setOnline` can be used to manually set the online state.\n *\n * @example\n * ```ts\n * import { onlineManager } from '@tanstack/query-core'\n *\n * // Set to online\n * onlineManager.setOnline(true)\n *\n * // Set to offline\n * onlineManager.setOnline(false)\n * ```\n */\n setOnline(online: boolean): void {\n const changed = this.#online !== online\n\n if (changed) {\n this.#online = online\n this.listeners.forEach((listener) => {\n listener(online)\n })\n }\n }\n\n /**\n * `isOnline` can be used to get the current online state.\n */\n isOnline(): boolean {\n return this.#online\n }\n}\n\n/**\n * Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.\n */\nexport const onlineManager = new OnlineManager()\n"],"mappings":";;;;;;;;;;;;;;;AAcA,IAAa,gBAAb,cAAmC,aAAuB;CAMxD,cAAc;EACZ,MAAM;EANE,2BAAA,MAAA,SAAA,IAAA;;;EAOR,uBAAA,QAAA,OAAe,aAAa;GAG1B,IAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;IAC5D,MAAM,uBAAuB,SAAS,IAAI;IAC1C,MAAM,wBAAwB,SAAS,KAAK;IAE5C,OAAO,iBAAiB,UAAU,gBAAgB,KAAK;IACvD,OAAO,iBAAiB,WAAW,iBAAiB,KAAK;IAEzD,aAAa;KAEX,OAAO,oBAAoB,UAAU,cAAc;KACnD,OAAO,oBAAoB,WAAW,eAAe;IACvD;GACF;EAGF,CAAA;CACF;CAEA,cAA8B;EAC5B,IAAI,CAAA,uBAAA,UAAC,IAAA,GACH,KAAK,iBAAA,uBAAA,QAAiB,IAAA,CAAW;CAErC;CAEA,gBAA0B;EACxB,IAAI,CAAC,KAAK,aAAa,GAAG;;GACxB,CAAA,2BAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,6BAAA,KAAA,KAAA,yBAAA,KAAA,IAAgB;GAChB,uBAAA,UAAA,MAAgB,KAAA,CAAA;EAClB;CACF;;;;;;;;;;;;;;;;;;;CAoBA,iBAAiB,OAAsB;;EACrC,uBAAA,QAAA,MAAc,KAAA;EACd,CAAA,yBAAA,uBAAA,UAAA,IAAA,OAAA,QAAA,2BAAA,KAAA,KAAA,uBAAA,KAAA,IAAgB;EAChB,uBAAA,UAAA,MAAgB,MAAM,KAAK,UAAU,KAAK,IAAI,CAAC,CAAA;CACjD;;;;;;;;;;;;;;;CAgBA,UAAU,QAAuB;EAG/B,IAAA,uBAAA,SAFgB,IAAA,MAAiB,QAEpB;GACX,uBAAA,SAAA,MAAe,MAAA;GACf,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,MAAM;GACjB,CAAC;EACH;CACF;;;;CAKA,WAAoB;EAClB,OAAA,uBAAA,SAAO,IAAA;CACT;AACF;;;;AAKA,MAAa,gBAAgB,IAAI,cAAc"}
+269
View File
@@ -0,0 +1,269 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_classPrivateFieldSet2 = require("./classPrivateFieldSet2-Bo0ZyOIv.cjs");
const require_utils = require("./utils.cjs");
const require_subscribable = require("./subscribable.cjs");
const require_notifyManager = require("./notifyManager.cjs");
const require_classPrivateMethodInitSpec = require("./classPrivateMethodInitSpec-DVhcLejn.cjs");
const require_queryObserver = require("./queryObserver.cjs");
//#region src/queriesObserver.ts
function difference(array1, array2) {
const excludeSet = new Set(array2);
return array1.filter((x) => !excludeSet.has(x));
}
var _client = /* @__PURE__ */ new WeakMap();
var _result = /* @__PURE__ */ new WeakMap();
var _queries = /* @__PURE__ */ new WeakMap();
var _options = /* @__PURE__ */ new WeakMap();
var _observers = /* @__PURE__ */ new WeakMap();
var _combinedResult = /* @__PURE__ */ new WeakMap();
var _lastCombine = /* @__PURE__ */ new WeakMap();
var _lastResult = /* @__PURE__ */ new WeakMap();
var _lastQueryHashes = /* @__PURE__ */ new WeakMap();
var _observerMatches = /* @__PURE__ */ new WeakMap();
var _QueriesObserver_brand = /* @__PURE__ */ new WeakSet();
/**
* A `QueriesObserver` watches an array of queries at once, exposing them as
* a single array of `QueryObserverResult`s (or, when a `combine` option is
* given, as a combined value derived from that array). It manages one
* internal `QueryObserver` per query, and is the primitive that framework
* adapters (e.g. `useQueries`) build their hooks on top of.
*
* @example
* ```ts
* const observer = new QueriesObserver(queryClient, [
* { queryKey: ['post', 1], queryFn: fetchPost },
* { queryKey: ['post', 2], queryFn: fetchPost },
* ])
*
* const unsubscribe = observer.subscribe((result) => {
* console.log(result)
* })
* ```
*/
var QueriesObserver = class extends require_subscribable.Subscribable {
constructor(client, queries, options) {
super();
require_classPrivateMethodInitSpec._classPrivateMethodInitSpec(this, _QueriesObserver_brand);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _client, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _result, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _queries, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _options, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _observers, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _combinedResult, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _lastCombine, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _lastResult, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _lastQueryHashes, void 0);
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _observerMatches, []);
require_classPrivateFieldSet2._classPrivateFieldSet2(_client, this, client);
require_classPrivateFieldSet2._classPrivateFieldSet2(_options, this, options);
require_classPrivateFieldSet2._classPrivateFieldSet2(_queries, this, []);
require_classPrivateFieldSet2._classPrivateFieldSet2(_observers, this, []);
require_classPrivateFieldSet2._classPrivateFieldSet2(_result, this, []);
this.setQueries(queries);
}
onSubscribe() {
if (this.listeners.size === 1) require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).forEach((observer) => {
observer.subscribe((result) => {
require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _onUpdate).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();
require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).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) {
require_classPrivateFieldSet2._classPrivateFieldSet2(_queries, this, queries);
require_classPrivateFieldSet2._classPrivateFieldSet2(_options, this, options);
if (process.env.NODE_ENV !== "production") {
const queryHashes = queries.map((query) => require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this).defaultQueryOptions(query).queryHash);
if (new Set(queryHashes).size !== queryHashes.length) console.warn("[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.");
}
require_notifyManager.notifyManager.batch(() => {
const prevObservers = require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this);
const newObserverMatches = require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _findMatchingObservers).call(this, require_classPrivateFieldSet2._classPrivateFieldGet2(_queries, this));
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 = require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this)[index];
return !prev || !require_utils.shallowEqualObjects(result, prev);
});
if (!hasStructuralChange && !hasResultChange) return;
if (hasStructuralChange) {
require_classPrivateFieldSet2._classPrivateFieldSet2(_observerMatches, this, newObserverMatches);
require_classPrivateFieldSet2._classPrivateFieldSet2(_observers, this, newObservers);
}
require_classPrivateFieldSet2._classPrivateFieldSet2(_result, this, newResult);
if (!this.hasListeners()) return;
if (hasStructuralChange) {
difference(prevObservers, newObservers).forEach((observer) => {
observer.destroy();
});
difference(newObservers, prevObservers).forEach((observer) => {
observer.subscribe((result) => {
require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _onUpdate).call(this, observer, result);
});
});
}
require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _notify).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 require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this);
}
/**
* Returns the underlying `Query` instances currently being observed, in
* the same order as the queries passed to the constructor or `setQueries`.
*/
getQueries() {
return require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).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 require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this);
}
/**
* 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 = require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _findMatchingObservers).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 require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _combineResult).call(this, r ?? result, combine, queryHashes);
},
() => {
return require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _trackResult).call(this, result, matches);
}
];
}
};
function _trackResult(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;
});
}
function _combineResult(input, combine, queryHashes) {
if (combine) {
const lastHashes = require_classPrivateFieldSet2._classPrivateFieldGet2(_lastQueryHashes, this);
const queryHashesChanged = queryHashes !== void 0 && lastHashes !== void 0 && (lastHashes.length !== queryHashes.length || queryHashes.some((hash, i) => hash !== lastHashes[i]));
if (require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this) !== require_classPrivateFieldSet2._classPrivateFieldGet2(_lastResult, this) || queryHashesChanged || combine !== require_classPrivateFieldSet2._classPrivateFieldGet2(_lastCombine, this)) {
require_classPrivateFieldSet2._classPrivateFieldSet2(_lastCombine, this, combine);
require_classPrivateFieldSet2._classPrivateFieldSet2(_lastResult, this, require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this));
if (queryHashes !== void 0) require_classPrivateFieldSet2._classPrivateFieldSet2(_lastQueryHashes, this, queryHashes);
require_classPrivateFieldSet2._classPrivateFieldSet2(_combinedResult, this, require_utils.replaceEqualDeep(require_classPrivateFieldSet2._classPrivateFieldGet2(_combinedResult, this), combine(input)));
}
return require_classPrivateFieldSet2._classPrivateFieldGet2(_combinedResult, this);
}
return input;
}
function _shouldSkipCombine() {
var _classPrivateFieldGet2$1;
return !((_classPrivateFieldGet2$1 = require_classPrivateFieldSet2._classPrivateFieldGet2(_options, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.combine) || require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).some((observer, index) => {
var _classPrivateFieldGet3;
return observer.options.suspense && ((_classPrivateFieldGet3 = require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this)[index]) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.data) === void 0;
});
}
function _findMatchingObservers(queries) {
const prevObserversMap = /* @__PURE__ */ new Map();
require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).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 _prevObserversMap$get;
const defaultedOptions = require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this).defaultQueryOptions(options);
const observer = ((_prevObserversMap$get = prevObserversMap.get(defaultedOptions.queryHash)) === null || _prevObserversMap$get === void 0 ? void 0 : _prevObserversMap$get.shift()) ?? new require_queryObserver.QueryObserver(require_classPrivateFieldSet2._classPrivateFieldGet2(_client, this), defaultedOptions);
observers.push({
defaultedQueryOptions: defaultedOptions,
observer
});
});
return observers;
}
function _onUpdate(observer, result) {
const index = require_classPrivateFieldSet2._classPrivateFieldGet2(_observers, this).indexOf(observer);
if (index !== -1) {
require_classPrivateFieldSet2._classPrivateFieldSet2(_result, this, require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this).slice());
require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this)[index] = result;
require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _notify).call(this);
}
}
function _notify() {
if (this.hasListeners()) {
var _classPrivateFieldGet4;
const shouldSkipCombine = require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _shouldSkipCombine).call(this);
const previousResult = require_classPrivateFieldSet2._classPrivateFieldGet2(_combinedResult, this);
const newResult = shouldSkipCombine ? previousResult : require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _combineResult).call(this, require_classPrivateFieldSet2._assertClassBrand(_QueriesObserver_brand, this, _trackResult).call(this, require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this), require_classPrivateFieldSet2._classPrivateFieldGet2(_observerMatches, this)), (_classPrivateFieldGet4 = require_classPrivateFieldSet2._classPrivateFieldGet2(_options, this)) === null || _classPrivateFieldGet4 === void 0 ? void 0 : _classPrivateFieldGet4.combine);
if (shouldSkipCombine || previousResult !== newResult) require_notifyManager.notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(require_classPrivateFieldSet2._classPrivateFieldGet2(_result, this));
});
});
}
}
//#endregion
exports.QueriesObserver = QueriesObserver;
//# sourceMappingURL=queriesObserver.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"queriesObserver.cjs","names":["Subscribable","shallowEqualObjects","replaceEqualDeep","QueryObserver"],"sources":["../../src/queriesObserver.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { QueryObserver } from './queryObserver'\nimport { Subscribable } from './subscribable'\nimport { replaceEqualDeep, shallowEqualObjects } from './utils'\nimport type {\n DefaultedQueryObserverOptions,\n QueryObserverOptions,\n QueryObserverResult,\n} from './types'\nimport type { QueryClient } from './queryClient'\n\nfunction difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {\n const excludeSet = new Set(array2)\n return array1.filter((x) => !excludeSet.has(x))\n}\n\ntype QueriesObserverListener = (result: Array<QueryObserverResult>) => void\n\ntype CombineFn<TCombinedResult> = (\n result: Array<QueryObserverResult>,\n) => TCombinedResult\n\nexport interface QueriesObserverOptions<\n TCombinedResult = Array<QueryObserverResult>,\n> {\n /**\n * A function that combines the array of `QueryObserverResult`s (one per\n * observed query) into a single value. The combined value is memoized and\n * only recomputed when one of the underlying results, the query hashes, or\n * the `combine` function itself changes.\n *\n * Defaults to returning the array of `QueryObserverResult`s unchanged.\n */\n combine?: CombineFn<TCombinedResult>\n}\n\n/**\n * A `QueriesObserver` watches an array of queries at once, exposing them as\n * a single array of `QueryObserverResult`s (or, when a `combine` option is\n * given, as a combined value derived from that array). It manages one\n * internal `QueryObserver` per query, and is the primitive that framework\n * adapters (e.g. `useQueries`) build their hooks on top of.\n *\n * @example\n * ```ts\n * const observer = new QueriesObserver(queryClient, [\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 2], queryFn: fetchPost },\n * ])\n *\n * const unsubscribe = observer.subscribe((result) => {\n * console.log(result)\n * })\n * ```\n */\nexport class QueriesObserver<\n TCombinedResult = Array<QueryObserverResult>,\n> extends Subscribable<QueriesObserverListener> {\n #client: QueryClient\n #result!: Array<QueryObserverResult>\n #queries: Array<QueryObserverOptions>\n #options?: QueriesObserverOptions<TCombinedResult>\n #observers: Array<QueryObserver>\n #combinedResult!: TCombinedResult\n #lastCombine?: CombineFn<TCombinedResult>\n #lastResult?: Array<QueryObserverResult>\n #lastQueryHashes?: Array<string>\n #observerMatches: Array<QueryObserverMatch> = []\n\n constructor(\n client: QueryClient,\n queries: Array<QueryObserverOptions<any, any, any, any, any>>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ) {\n super()\n\n this.#client = client\n this.#options = options\n this.#queries = []\n this.#observers = []\n this.#result = []\n\n this.setQueries(queries)\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#observers.forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.listeners.size) {\n this.destroy()\n }\n }\n\n /**\n * Stops observing all queries: clears all listeners and destroys every\n * underlying `QueryObserver` this observer manages.\n */\n destroy(): void {\n this.listeners = new Set()\n this.#observers.forEach((observer) => {\n observer.destroy()\n })\n }\n\n /**\n * Replaces the set of queries being observed. Existing `QueryObserver`s\n * are reused for queries that match an already-observed query hash;\n * observers for queries that are no longer present are destroyed, and new\n * observers are created and subscribed to for newly added queries.\n *\n * @example\n * ```ts\n * observer.setQueries([\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 3], queryFn: fetchPost },\n * ])\n * ```\n */\n setQueries(\n queries: Array<QueryObserverOptions>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ): void {\n this.#queries = queries\n this.#options = options\n\n if (process.env.NODE_ENV !== 'production') {\n const queryHashes = queries.map(\n (query) => this.#client.defaultQueryOptions(query).queryHash,\n )\n if (new Set(queryHashes).size !== queryHashes.length) {\n console.warn(\n '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',\n )\n }\n }\n\n notifyManager.batch(() => {\n const prevObservers = this.#observers\n\n const newObserverMatches = this.#findMatchingObservers(this.#queries)\n\n // set options for the new observers to notify of changes\n newObserverMatches.forEach((match) =>\n match.observer.setOptioLine truncated
@@ -0,0 +1,95 @@
import { t as Subscribable } from "./subscribable-CbifVTKz.cjs";
import { $n as Query, At as QueryObserverOptions, Pt as QueryObserverResult, on as QueryClient, rr as QueryObserver } from "./hydration-DwR10Hi-.cjs";
//#region src/queriesObserver.d.ts
type QueriesObserverListener = (result: Array<QueryObserverResult>) => void;
type CombineFn<TCombinedResult> = (result: Array<QueryObserverResult>) => TCombinedResult;
interface QueriesObserverOptions<TCombinedResult = Array<QueryObserverResult>> {
/**
* A function that combines the array of `QueryObserverResult`s (one per
* observed query) into a single value. The combined value is memoized and
* only recomputed when one of the underlying results, the query hashes, or
* the `combine` function itself changes.
*
* Defaults to returning the array of `QueryObserverResult`s unchanged.
*/
combine?: CombineFn<TCombinedResult>;
}
/**
* A `QueriesObserver` watches an array of queries at once, exposing them as
* a single array of `QueryObserverResult`s (or, when a `combine` option is
* given, as a combined value derived from that array). It manages one
* internal `QueryObserver` per query, and is the primitive that framework
* adapters (e.g. `useQueries`) build their hooks on top of.
*
* @example
* ```ts
* const observer = new QueriesObserver(queryClient, [
* { queryKey: ['post', 1], queryFn: fetchPost },
* { queryKey: ['post', 2], queryFn: fetchPost },
* ])
*
* const unsubscribe = observer.subscribe((result) => {
* console.log(result)
* })
* ```
*/
declare class QueriesObserver<TCombinedResult = Array<QueryObserverResult>> extends Subscribable<QueriesObserverListener> {
#private;
constructor(client: QueryClient, queries: Array<QueryObserverOptions<any, any, any, any, any>>, options?: QueriesObserverOptions<TCombinedResult>);
protected onSubscribe(): void;
protected onUnsubscribe(): void;
/**
* Stops observing all queries: clears all listeners and destroys every
* underlying `QueryObserver` this observer manages.
*/
destroy(): void;
/**
* 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: Array<QueryObserverOptions>, options?: QueriesObserverOptions<TCombinedResult>): void;
/**
* 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(): Array<QueryObserverResult>;
/**
* Returns the underlying `Query` instances currently being observed, in
* the same order as the queries passed to the constructor or `setQueries`.
*/
getQueries(): Query<unknown, Error, unknown, readonly unknown[]>[];
/**
* Returns the underlying `QueryObserver` instances this observer manages,
* in the same order as the queries passed to the constructor or
* `setQueries`.
*/
getObservers(): QueryObserver<unknown, Error, unknown, unknown, readonly unknown[]>[];
/**
* 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: Array<QueryObserverOptions>, combine: CombineFn<TCombinedResult> | undefined): [rawResult: Array<QueryObserverResult>, combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult, trackResult: () => Array<QueryObserverResult>];
}
//#endregion
export { QueriesObserver, QueriesObserverOptions };
//# sourceMappingURL=queriesObserver.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"queriesObserver.d.cts","names":[],"sources":["../../src/queriesObserver.ts"],"mappings":";;;KAgBK,2BAA2B,QAAQ,MAAM;KAEzC,UAAU,oBACb,QAAQ,MAAM,yBACX;UAEY,uBACf,kBAAkB,MAAM;;;;;;;;;EAUxB,UAAU,UAAU;;;;;;;;;;;;;;;;;;;;;cAsBT,gBACX,kBAAkB,MAAM,8BAChB,aAAa;;EAanB,YAAA,QAAQ,aACR,SAAS,MAAM,gDACf,UAAU,uBAAuB;YAazB;YAUA;;;;;EAUV;;;;;;;;;;;;;;;EAqBA,WACE,SAAS,MAAM,uBACf,UAAU,uBAAuB;;;;;;;;;;;;EAiFnC,oBAAoB,MAAM;;;;;EAQ1B,cAAU,eAAA;;;;;;EASV,gBAAY,uBAAA;;;;;;;;EAWZ,oBACE,SAAS,MAAM,uBACf,SAAS,UAAU,gCAEnB,WAAW,MAAM,sBACjB,gBAAgB,IAAI,MAAM,yBAAyB,iBACnD,mBAAmB,MAAM"}
Loaded 100 of 4271 files, more files were not shown because too many files have changed in this diff. Show more