Add comprehensive frontend UI and distributed infrastructure

Frontend Enhancements:
- Complete React TypeScript frontend with modern UI components
- Distributed workflows management interface with real-time updates
- Socket.IO integration for live agent status monitoring
- Agent management dashboard with cluster visualization
- Project management interface with metrics and task tracking
- Responsive design with proper error handling and loading states

Backend Infrastructure:
- Distributed coordinator for multi-agent workflow orchestration
- Cluster management API with comprehensive agent operations
- Enhanced database models for agents and projects
- Project service for filesystem-based project discovery
- Performance monitoring and metrics collection
- Comprehensive API documentation and error handling

Documentation:
- Complete distributed development guide (README_DISTRIBUTED.md)
- Comprehensive development report with architecture insights
- System configuration templates and deployment guides

The platform now provides a complete web interface for managing the distributed AI cluster
with real-time monitoring, workflow orchestration, and agent coordination capabilities.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
anthonyrawlins
2025-07-10 08:41:59 +10:00
parent fc0eec91ef
commit 85bf1341f3
28348 changed files with 2646896 additions and 69 deletions

View File

@@ -0,0 +1,25 @@
var __typeError = (msg) => {
throw TypeError(msg);
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
var __privateWrapper = (obj, member, setter, getter) => ({
set _(value) {
__privateSet(obj, member, value, setter);
},
get _() {
return __privateGet(obj, member, getter);
}
});
export {
__privateGet,
__privateAdd,
__privateSet,
__privateMethod,
__privateWrapper
};
//# sourceMappingURL=chunk-PXG64RU4.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}

View File

@@ -0,0 +1,108 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
// src/focusManager.ts
var focusManager_exports = {};
__export(focusManager_exports, {
FocusManager: () => FocusManager,
focusManager: () => focusManager
});
module.exports = __toCommonJS(focusManager_exports);
var import_subscribable = require("./subscribable.cjs");
var import_utils = require("./utils.cjs");
var _focused, _cleanup, _setup;
var FocusManager = class extends import_subscribable.Subscribable {
constructor() {
super();
__privateAdd(this, _focused);
__privateAdd(this, _cleanup);
__privateAdd(this, _setup);
__privateSet(this, _setup, (onFocus) => {
if (!import_utils.isServer && window.addEventListener) {
const listener = () => onFocus();
window.addEventListener("visibilitychange", listener, false);
return () => {
window.removeEventListener("visibilitychange", listener);
};
}
return;
});
}
onSubscribe() {
if (!__privateGet(this, _cleanup)) {
this.setEventListener(__privateGet(this, _setup));
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, void 0);
}
}
setEventListener(setup) {
var _a;
__privateSet(this, _setup, setup);
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, setup((focused) => {
if (typeof focused === "boolean") {
this.setFocused(focused);
} else {
this.onFocus();
}
}));
}
setFocused(focused) {
const changed = __privateGet(this, _focused) !== focused;
if (changed) {
__privateSet(this, _focused, focused);
this.onFocus();
}
}
onFocus() {
const isFocused = this.isFocused();
this.listeners.forEach((listener) => {
listener(isFocused);
});
}
isFocused() {
var _a;
if (typeof __privateGet(this, _focused) === "boolean") {
return __privateGet(this, _focused);
}
return ((_a = globalThis.document) == null ? void 0 : _a.visibilityState) !== "hidden";
}
};
_focused = new WeakMap();
_cleanup = new WeakMap();
_setup = new WeakMap();
var focusManager = new FocusManager();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
FocusManager,
focusManager
});
//# sourceMappingURL=focusManager.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/focusManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\nimport { isServer } from './utils'\n\ntype Listener = (focused: boolean) => void\n\ntype SetupFn = (\n setFocused: (focused?: boolean) => void,\n) => (() => void) | undefined\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 (!isServer && 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 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 setFocused(focused?: boolean): void {\n const changed = this.#focused !== focused\n if (changed) {\n this.#focused = focused\n this.onFocus()\n }\n }\n\n onFocus(): void {\n const isFocused = this.isFocused()\n this.listeners.forEach((listener) => {\n listener(isFocused)\n })\n }\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\nexport const focusManager = new FocusManager()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAA6B;AAC7B,mBAAyB;AADzB;AASO,IAAM,eAAN,cAA2B,iCAAuB;AAAA,EAMvD,cAAc;AACZ,UAAM;AANR;AACA;AAEA;AAIE,uBAAK,QAAS,CAAC,YAAY;AAGzB,UAAI,CAAC,yBAAY,OAAO,kBAAkB;AACxC,cAAM,WAAW,MAAM,QAAQ;AAE/B,eAAO,iBAAiB,oBAAoB,UAAU,KAAK;AAE3D,eAAO,MAAM;AAEX,iBAAO,oBAAoB,oBAAoB,QAAQ;AAAA,QACzD;AAAA,MACF;AACA;AAAA,IACF;AAAA,EACF;AAAA,EAEU,cAAoB;AAC5B,QAAI,CAAC,mBAAK,WAAU;AAClB,WAAK,iBAAiB,mBAAK,OAAM;AAAA,IACnC;AAAA,EACF;AAAA,EAEU,gBAAgB;AAxC5B;AAyCI,QAAI,CAAC,KAAK,aAAa,GAAG;AACxB,+BAAK,cAAL;AACA,yBAAK,UAAW;AAAA,IAClB;AAAA,EACF;AAAA,EAEA,iBAAiB,OAAsB;AA/CzC;AAgDI,uBAAK,QAAS;AACd,6BAAK,cAAL;AACA,uBAAK,UAAW,MAAM,CAAC,YAAY;AACjC,UAAI,OAAO,YAAY,WAAW;AAChC,aAAK,WAAW,OAAO;AAAA,MACzB,OAAO;AACL,aAAK,QAAQ;AAAA,MACf;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,WAAW,SAAyB;AAClC,UAAM,UAAU,mBAAK,cAAa;AAClC,QAAI,SAAS;AACX,yBAAK,UAAW;AAChB,WAAK,QAAQ;AAAA,IACf;AAAA,EACF;AAAA,EAEA,UAAgB;AACd,UAAM,YAAY,KAAK,UAAU;AACjC,SAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,eAAS,SAAS;AAAA,IACpB,CAAC;AAAA,EACH;AAAA,EAEA,YAAqB;AA1EvB;AA2EI,QAAI,OAAO,mBAAK,cAAa,WAAW;AACtC,aAAO,mBAAK;AAAA,IACd;AAIA,aAAO,gBAAW,aAAX,mBAAqB,qBAAoB;AAAA,EAClD;AACF;AAzEE;AACA;AAEA;AAwEK,IAAM,eAAe,IAAI,aAAa;","names":[]}

View File

@@ -0,0 +1,17 @@
import { Subscribable } from './subscribable.cjs';
type Listener = (focused: boolean) => void;
type SetupFn = (setFocused: (focused?: boolean) => void) => (() => void) | undefined;
declare class FocusManager extends Subscribable<Listener> {
#private;
constructor();
protected onSubscribe(): void;
protected onUnsubscribe(): void;
setEventListener(setup: SetupFn): void;
setFocused(focused?: boolean): void;
onFocus(): void;
isFocused(): boolean;
}
declare const focusManager: FocusManager;
export { FocusManager, focusManager };

View File

@@ -0,0 +1,17 @@
import { Subscribable } from './subscribable.js';
type Listener = (focused: boolean) => void;
type SetupFn = (setFocused: (focused?: boolean) => void) => (() => void) | undefined;
declare class FocusManager extends Subscribable<Listener> {
#private;
constructor();
protected onSubscribe(): void;
protected onUnsubscribe(): void;
setEventListener(setup: SetupFn): void;
setFocused(focused?: boolean): void;
onFocus(): void;
isFocused(): boolean;
}
declare const focusManager: FocusManager;
export { FocusManager, focusManager };

View File

@@ -0,0 +1,81 @@
import {
__privateAdd,
__privateGet,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/focusManager.ts
import { Subscribable } from "./subscribable.js";
import { isServer } from "./utils.js";
var _focused, _cleanup, _setup;
var FocusManager = class extends Subscribable {
constructor() {
super();
__privateAdd(this, _focused);
__privateAdd(this, _cleanup);
__privateAdd(this, _setup);
__privateSet(this, _setup, (onFocus) => {
if (!isServer && window.addEventListener) {
const listener = () => onFocus();
window.addEventListener("visibilitychange", listener, false);
return () => {
window.removeEventListener("visibilitychange", listener);
};
}
return;
});
}
onSubscribe() {
if (!__privateGet(this, _cleanup)) {
this.setEventListener(__privateGet(this, _setup));
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, void 0);
}
}
setEventListener(setup) {
var _a;
__privateSet(this, _setup, setup);
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, setup((focused) => {
if (typeof focused === "boolean") {
this.setFocused(focused);
} else {
this.onFocus();
}
}));
}
setFocused(focused) {
const changed = __privateGet(this, _focused) !== focused;
if (changed) {
__privateSet(this, _focused, focused);
this.onFocus();
}
}
onFocus() {
const isFocused = this.isFocused();
this.listeners.forEach((listener) => {
listener(isFocused);
});
}
isFocused() {
var _a;
if (typeof __privateGet(this, _focused) === "boolean") {
return __privateGet(this, _focused);
}
return ((_a = globalThis.document) == null ? void 0 : _a.visibilityState) !== "hidden";
}
};
_focused = new WeakMap();
_cleanup = new WeakMap();
_setup = new WeakMap();
var focusManager = new FocusManager();
export {
FocusManager,
focusManager
};
//# sourceMappingURL=focusManager.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/focusManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\nimport { isServer } from './utils'\n\ntype Listener = (focused: boolean) => void\n\ntype SetupFn = (\n setFocused: (focused?: boolean) => void,\n) => (() => void) | undefined\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 (!isServer && 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 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 setFocused(focused?: boolean): void {\n const changed = this.#focused !== focused\n if (changed) {\n this.#focused = focused\n this.onFocus()\n }\n }\n\n onFocus(): void {\n const isFocused = this.isFocused()\n this.listeners.forEach((listener) => {\n listener(isFocused)\n })\n }\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\nexport const focusManager = new FocusManager()\n"],"mappings":";;;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AADzB;AASO,IAAM,eAAN,cAA2B,aAAuB;AAAA,EAMvD,cAAc;AACZ,UAAM;AANR;AACA;AAEA;AAIE,uBAAK,QAAS,CAAC,YAAY;AAGzB,UAAI,CAAC,YAAY,OAAO,kBAAkB;AACxC,cAAM,WAAW,MAAM,QAAQ;AAE/B,eAAO,iBAAiB,oBAAoB,UAAU,KAAK;AAE3D,eAAO,MAAM;AAEX,iBAAO,oBAAoB,oBAAoB,QAAQ;AAAA,QACzD;AAAA,MACF;AACA;AAAA,IACF;AAAA,EACF;AAAA,EAEU,cAAoB;AAC5B,QAAI,CAAC,mBAAK,WAAU;AAClB,WAAK,iBAAiB,mBAAK,OAAM;AAAA,IACnC;AAAA,EACF;AAAA,EAEU,gBAAgB;AAxC5B;AAyCI,QAAI,CAAC,KAAK,aAAa,GAAG;AACxB,+BAAK,cAAL;AACA,yBAAK,UAAW;AAAA,IAClB;AAAA,EACF;AAAA,EAEA,iBAAiB,OAAsB;AA/CzC;AAgDI,uBAAK,QAAS;AACd,6BAAK,cAAL;AACA,uBAAK,UAAW,MAAM,CAAC,YAAY;AACjC,UAAI,OAAO,YAAY,WAAW;AAChC,aAAK,WAAW,OAAO;AAAA,MACzB,OAAO;AACL,aAAK,QAAQ;AAAA,MACf;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,WAAW,SAAyB;AAClC,UAAM,UAAU,mBAAK,cAAa;AAClC,QAAI,SAAS;AACX,yBAAK,UAAW;AAChB,WAAK,QAAQ;AAAA,IACf;AAAA,EACF;AAAA,EAEA,UAAgB;AACd,UAAM,YAAY,KAAK,UAAU;AACjC,SAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,eAAS,SAAS;AAAA,IACpB,CAAC;AAAA,EACH;AAAA,EAEA,YAAqB;AA1EvB;AA2EI,QAAI,OAAO,mBAAK,cAAa,WAAW;AACtC,aAAO,mBAAK;AAAA,IACd;AAIA,aAAO,gBAAW,aAAX,mBAAqB,qBAAoB;AAAA,EAClD;AACF;AAzEE;AACA;AAEA;AAwEK,IAAM,eAAe,IAAI,aAAa;","names":[]}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,172 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/hydration.ts
var hydration_exports = {};
__export(hydration_exports, {
defaultShouldDehydrateMutation: () => defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery: () => defaultShouldDehydrateQuery,
dehydrate: () => dehydrate,
hydrate: () => hydrate
});
module.exports = __toCommonJS(hydration_exports);
var import_thenable = require("./thenable.cjs");
function defaultTransformerFn(data) {
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 dehydrateQuery(query, serializeData, shouldRedactErrors) {
var _a;
return {
dehydratedAt: Date.now(),
state: {
...query.state,
...query.state.data !== void 0 && {
data: serializeData(query.state.data)
}
},
queryKey: query.queryKey,
queryHash: query.queryHash,
...query.state.status === "pending" && {
promise: (_a = query.promise) == null ? void 0 : _a.then(serializeData).catch((error) => {
if (!shouldRedactErrors(error)) {
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(new Error("redacted"));
})
},
...query.meta && { meta: query.meta }
};
}
function defaultShouldDehydrateMutation(mutation) {
return mutation.state.isPaused;
}
function defaultShouldDehydrateQuery(query) {
return query.state.status === "success";
}
function defaultShouldRedactErrors(_) {
return true;
}
function dehydrate(client, options = {}) {
var _a, _b, _c, _d;
const filterMutation = options.shouldDehydrateMutation ?? ((_a = client.getDefaultOptions().dehydrate) == null ? void 0 : _a.shouldDehydrateMutation) ?? defaultShouldDehydrateMutation;
const mutations = client.getMutationCache().getAll().flatMap(
(mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []
);
const filterQuery = options.shouldDehydrateQuery ?? ((_b = client.getDefaultOptions().dehydrate) == null ? void 0 : _b.shouldDehydrateQuery) ?? defaultShouldDehydrateQuery;
const shouldRedactErrors = options.shouldRedactErrors ?? ((_c = client.getDefaultOptions().dehydrate) == null ? void 0 : _c.shouldRedactErrors) ?? defaultShouldRedactErrors;
const serializeData = options.serializeData ?? ((_d = client.getDefaultOptions().dehydrate) == null ? void 0 : _d.serializeData) ?? defaultTransformerFn;
const queries = client.getQueryCache().getAll().flatMap(
(query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : []
);
return { mutations, queries };
}
function hydrate(client, dehydratedState, options) {
var _a, _b;
if (typeof dehydratedState !== "object" || dehydratedState === null) {
return;
}
const mutationCache = client.getMutationCache();
const queryCache = client.getQueryCache();
const deserializeData = ((_a = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _a.deserializeData) ?? ((_b = client.getDefaultOptions().hydrate) == null ? void 0 : _b.deserializeData) ?? defaultTransformerFn;
const mutations = dehydratedState.mutations || [];
const queries = dehydratedState.queries || [];
mutations.forEach(({ state, ...mutationOptions }) => {
var _a2, _b2;
mutationCache.build(
client,
{
...(_a2 = client.getDefaultOptions().hydrate) == null ? void 0 : _a2.mutations,
...(_b2 = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _b2.mutations,
...mutationOptions
},
state
);
});
queries.forEach(
({ queryKey, state, queryHash, meta, promise, dehydratedAt }) => {
var _a2, _b2;
const syncData = promise ? (0, import_thenable.tryResolveSync)(promise) : void 0;
const rawData = state.data === void 0 ? syncData == null ? void 0 : syncData.data : state.data;
const data = rawData === void 0 ? rawData : deserializeData(rawData);
let query = queryCache.get(queryHash);
const existingQueryIsPending = (query == null ? void 0 : query.state.status) === "pending";
const existingQueryIsFetching = (query == null ? void 0 : query.state.fetchStatus) === "fetching";
if (query) {
const hasNewerSyncData = syncData && // We only need this undefined check to handle older dehydration
// payloads that might not have dehydratedAt
dehydratedAt !== void 0 && dehydratedAt > query.state.dataUpdatedAt;
if (state.dataUpdatedAt > query.state.dataUpdatedAt || hasNewerSyncData) {
const { fetchStatus: _ignored, ...serializedState } = state;
query.setState({
...serializedState,
data
});
}
} else {
query = queryCache.build(
client,
{
...(_a2 = client.getDefaultOptions().hydrate) == null ? void 0 : _a2.queries,
...(_b2 = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _b2.queries,
queryKey,
queryHash,
meta
},
// Reset fetch status to idle to avoid
// query being stuck in fetching state upon hydration
{
...state,
data,
fetchStatus: "idle",
status: data !== void 0 ? "success" : state.status
}
);
}
if (promise && !existingQueryIsPending && !existingQueryIsFetching && // Only hydrate if dehydration is newer than any existing data,
// this is always true for new queries
(dehydratedAt === void 0 || dehydratedAt > query.state.dataUpdatedAt)) {
void query.fetch(void 0, {
// RSC transformed promises are not thenable
initialPromise: Promise.resolve(promise).then(deserializeData)
});
}
}
);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
hydrate
});
//# sourceMappingURL=hydration.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export { D as DehydrateOptions, A as DehydratedState, H as HydrateOptions, v as defaultShouldDehydrateMutation, u as defaultShouldDehydrateQuery, q as dehydrate, t as hydrate } from './hydration-CdBkFt9i.cjs';
import './removable.cjs';
import './subscribable.cjs';

View File

@@ -0,0 +1,3 @@
export { D as DehydrateOptions, A as DehydratedState, H as HydrateOptions, v as defaultShouldDehydrateMutation, u as defaultShouldDehydrateQuery, q as dehydrate, t as hydrate } from './hydration-Cr-4Kky1.js';
import './removable.js';
import './subscribable.js';

View File

@@ -0,0 +1,146 @@
import "./chunk-PXG64RU4.js";
// src/hydration.ts
import { tryResolveSync } from "./thenable.js";
function defaultTransformerFn(data) {
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 dehydrateQuery(query, serializeData, shouldRedactErrors) {
var _a;
return {
dehydratedAt: Date.now(),
state: {
...query.state,
...query.state.data !== void 0 && {
data: serializeData(query.state.data)
}
},
queryKey: query.queryKey,
queryHash: query.queryHash,
...query.state.status === "pending" && {
promise: (_a = query.promise) == null ? void 0 : _a.then(serializeData).catch((error) => {
if (!shouldRedactErrors(error)) {
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(new Error("redacted"));
})
},
...query.meta && { meta: query.meta }
};
}
function defaultShouldDehydrateMutation(mutation) {
return mutation.state.isPaused;
}
function defaultShouldDehydrateQuery(query) {
return query.state.status === "success";
}
function defaultShouldRedactErrors(_) {
return true;
}
function dehydrate(client, options = {}) {
var _a, _b, _c, _d;
const filterMutation = options.shouldDehydrateMutation ?? ((_a = client.getDefaultOptions().dehydrate) == null ? void 0 : _a.shouldDehydrateMutation) ?? defaultShouldDehydrateMutation;
const mutations = client.getMutationCache().getAll().flatMap(
(mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []
);
const filterQuery = options.shouldDehydrateQuery ?? ((_b = client.getDefaultOptions().dehydrate) == null ? void 0 : _b.shouldDehydrateQuery) ?? defaultShouldDehydrateQuery;
const shouldRedactErrors = options.shouldRedactErrors ?? ((_c = client.getDefaultOptions().dehydrate) == null ? void 0 : _c.shouldRedactErrors) ?? defaultShouldRedactErrors;
const serializeData = options.serializeData ?? ((_d = client.getDefaultOptions().dehydrate) == null ? void 0 : _d.serializeData) ?? defaultTransformerFn;
const queries = client.getQueryCache().getAll().flatMap(
(query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : []
);
return { mutations, queries };
}
function hydrate(client, dehydratedState, options) {
var _a, _b;
if (typeof dehydratedState !== "object" || dehydratedState === null) {
return;
}
const mutationCache = client.getMutationCache();
const queryCache = client.getQueryCache();
const deserializeData = ((_a = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _a.deserializeData) ?? ((_b = client.getDefaultOptions().hydrate) == null ? void 0 : _b.deserializeData) ?? defaultTransformerFn;
const mutations = dehydratedState.mutations || [];
const queries = dehydratedState.queries || [];
mutations.forEach(({ state, ...mutationOptions }) => {
var _a2, _b2;
mutationCache.build(
client,
{
...(_a2 = client.getDefaultOptions().hydrate) == null ? void 0 : _a2.mutations,
...(_b2 = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _b2.mutations,
...mutationOptions
},
state
);
});
queries.forEach(
({ queryKey, state, queryHash, meta, promise, dehydratedAt }) => {
var _a2, _b2;
const syncData = promise ? tryResolveSync(promise) : void 0;
const rawData = state.data === void 0 ? syncData == null ? void 0 : syncData.data : state.data;
const data = rawData === void 0 ? rawData : deserializeData(rawData);
let query = queryCache.get(queryHash);
const existingQueryIsPending = (query == null ? void 0 : query.state.status) === "pending";
const existingQueryIsFetching = (query == null ? void 0 : query.state.fetchStatus) === "fetching";
if (query) {
const hasNewerSyncData = syncData && // We only need this undefined check to handle older dehydration
// payloads that might not have dehydratedAt
dehydratedAt !== void 0 && dehydratedAt > query.state.dataUpdatedAt;
if (state.dataUpdatedAt > query.state.dataUpdatedAt || hasNewerSyncData) {
const { fetchStatus: _ignored, ...serializedState } = state;
query.setState({
...serializedState,
data
});
}
} else {
query = queryCache.build(
client,
{
...(_a2 = client.getDefaultOptions().hydrate) == null ? void 0 : _a2.queries,
...(_b2 = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _b2.queries,
queryKey,
queryHash,
meta
},
// Reset fetch status to idle to avoid
// query being stuck in fetching state upon hydration
{
...state,
data,
fetchStatus: "idle",
status: data !== void 0 ? "success" : state.status
}
);
}
if (promise && !existingQueryIsPending && !existingQueryIsFetching && // Only hydrate if dehydration is newer than any existing data,
// this is always true for new queries
(dehydratedAt === void 0 || dehydratedAt > query.state.dataUpdatedAt)) {
void query.fetch(void 0, {
// RSC transformed promises are not thenable
initialPromise: Promise.resolve(promise).then(deserializeData)
});
}
}
);
}
export {
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
hydrate
};
//# sourceMappingURL=hydration.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,108 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
CancelledError: () => import_retryer.CancelledError,
InfiniteQueryObserver: () => import_infiniteQueryObserver.InfiniteQueryObserver,
Mutation: () => import_mutation.Mutation,
MutationCache: () => import_mutationCache.MutationCache,
MutationObserver: () => import_mutationObserver.MutationObserver,
QueriesObserver: () => import_queriesObserver.QueriesObserver,
Query: () => import_query.Query,
QueryCache: () => import_queryCache.QueryCache,
QueryClient: () => import_queryClient.QueryClient,
QueryObserver: () => import_queryObserver.QueryObserver,
defaultScheduler: () => import_notifyManager.defaultScheduler,
defaultShouldDehydrateMutation: () => import_hydration.defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery: () => import_hydration.defaultShouldDehydrateQuery,
dehydrate: () => import_hydration.dehydrate,
experimental_streamedQuery: () => import_streamedQuery.streamedQuery,
focusManager: () => import_focusManager.focusManager,
hashKey: () => import_utils.hashKey,
hydrate: () => import_hydration.hydrate,
isCancelledError: () => import_retryer2.isCancelledError,
isServer: () => import_utils.isServer,
keepPreviousData: () => import_utils.keepPreviousData,
matchMutation: () => import_utils.matchMutation,
matchQuery: () => import_utils.matchQuery,
noop: () => import_utils.noop,
notifyManager: () => import_notifyManager.notifyManager,
onlineManager: () => import_onlineManager.onlineManager,
partialMatchKey: () => import_utils.partialMatchKey,
replaceEqualDeep: () => import_utils.replaceEqualDeep,
shouldThrowError: () => import_utils.shouldThrowError,
skipToken: () => import_utils.skipToken
});
module.exports = __toCommonJS(index_exports);
var import_retryer = require("./retryer.cjs");
var import_queryCache = require("./queryCache.cjs");
var import_queryClient = require("./queryClient.cjs");
var import_queryObserver = require("./queryObserver.cjs");
var import_queriesObserver = require("./queriesObserver.cjs");
var import_infiniteQueryObserver = require("./infiniteQueryObserver.cjs");
var import_mutationCache = require("./mutationCache.cjs");
var import_mutationObserver = require("./mutationObserver.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_focusManager = require("./focusManager.cjs");
var import_onlineManager = require("./onlineManager.cjs");
var import_utils = require("./utils.cjs");
var import_retryer2 = require("./retryer.cjs");
var import_hydration = require("./hydration.cjs");
var import_streamedQuery = require("./streamedQuery.cjs");
__reExport(index_exports, require("./types.cjs"), module.exports);
var import_query = require("./query.cjs");
var import_mutation = require("./mutation.cjs");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
CancelledError,
InfiniteQueryObserver,
Mutation,
MutationCache,
MutationObserver,
QueriesObserver,
Query,
QueryCache,
QueryClient,
QueryObserver,
defaultScheduler,
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
experimental_streamedQuery,
focusManager,
hashKey,
hydrate,
isCancelledError,
isServer,
keepPreviousData,
matchMutation,
matchQuery,
noop,
notifyManager,
onlineManager,
partialMatchKey,
replaceEqualDeep,
shouldThrowError,
skipToken,
...require("./types.cjs")
});
//# sourceMappingURL=index.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport { CancelledError } from './retryer'\nexport { QueryCache } from './queryCache'\nexport type { QueryCacheNotifyEvent } from './queryCache'\nexport { QueryClient } from './queryClient'\nexport { QueryObserver } from './queryObserver'\nexport { QueriesObserver } from './queriesObserver'\nexport { InfiniteQueryObserver } from './infiniteQueryObserver'\nexport { MutationCache } from './mutationCache'\nexport type { MutationCacheNotifyEvent } from './mutationCache'\nexport { MutationObserver } from './mutationObserver'\nexport { notifyManager, defaultScheduler } from './notifyManager'\nexport { focusManager } from './focusManager'\nexport { onlineManager } from './onlineManager'\nexport {\n hashKey,\n partialMatchKey,\n replaceEqualDeep,\n isServer,\n matchQuery,\n matchMutation,\n keepPreviousData,\n skipToken,\n noop,\n shouldThrowError,\n} from './utils'\nexport type { MutationFilters, QueryFilters, Updater, SkipToken } from './utils'\nexport { isCancelledError } from './retryer'\nexport {\n dehydrate,\n hydrate,\n defaultShouldDehydrateQuery,\n defaultShouldDehydrateMutation,\n} from './hydration'\n\nexport { streamedQuery as experimental_streamedQuery } from './streamedQuery'\n\n// Types\nexport * from './types'\nexport type { QueryState } from './query'\nexport { Query } from './query'\nexport type { MutationState } from './mutation'\nexport { Mutation } from './mutation'\nexport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n} from './hydration'\nexport type { QueriesObserverOptions } from './queriesObserver'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,qBAA+B;AAC/B,wBAA2B;AAE3B,yBAA4B;AAC5B,2BAA8B;AAC9B,6BAAgC;AAChC,mCAAsC;AACtC,2BAA8B;AAE9B,8BAAiC;AACjC,2BAAgD;AAChD,0BAA6B;AAC7B,2BAA8B;AAC9B,mBAWO;AAEP,IAAAA,kBAAiC;AACjC,uBAKO;AAEP,2BAA4D;AAG5D,0BAAc,wBAvCd;AAyCA,mBAAsB;AAEtB,sBAAyB;","names":["import_retryer"]}

View File

@@ -0,0 +1,9 @@
export { T as AnyDataTag, b6 as CancelOptions, C as CancelledError, V as DataTag, G as DefaultError, b5 as DefaultOptions, ak as DefaultedInfiniteQueryObserverOptions, ai as DefaultedQueryObserverOptions, aP as DefinedInfiniteQueryObserverResult, aG as DefinedQueryObserverResult, D as DehydrateOptions, A as DehydratedState, B as DistributiveOmit, $ as Enabled, an as EnsureInfiniteQueryDataOptions, am as EnsureQueryDataOptions, ao as FetchInfiniteQueryOptions, av as FetchNextPageOptions, aw as FetchPreviousPageOptions, al as FetchQueryOptions, ay as FetchStatus, a7 as GetNextPageParamFunction, a6 as GetPreviousPageParamFunction, H as HydrateOptions, W as InferDataFromTag, X as InferErrorFromTag, a8 as InfiniteData, aI as InfiniteQueryObserverBaseResult, aL as InfiniteQueryObserverLoadingErrorResult, aK as InfiniteQueryObserverLoadingResult, aj as InfiniteQueryObserverOptions, aJ as InfiniteQueryObserverPendingResult, aO as InfiniteQueryObserverPlaceholderResult, aM as InfiniteQueryObserverRefetchErrorResult, aQ as InfiniteQueryObserverResult, aN as InfiniteQueryObserverSuccessResult, ae as InfiniteQueryPageParamsOptions, a2 as InitialDataFunction, ad as InitialPageParam, at as InvalidateOptions, ar as InvalidateQueryFilters, aZ as MutateFunction, aY as MutateOptions, z as Mutation, M as MutationCache, d as MutationCacheNotifyEvent, j as MutationFilters, aV as MutationFunction, aR as MutationKey, aU as MutationMeta, e as MutationObserver, a_ as MutationObserverBaseResult, b1 as MutationObserverErrorResult, a$ as MutationObserverIdleResult, b0 as MutationObserverLoadingResult, aX as MutationObserverOptions, b3 as MutationObserverResult, b2 as MutationObserverSuccessResult, aW as MutationOptions, aT as MutationScope, y as MutationState, aS as MutationStatus, aa as NetworkMode, F as NoInfer, N as NonUndefinedGuard, b9 as NotifyEvent, b8 as NotifyEventType, ab as NotifyOnChangeProps, O as OmitKeyof, E as Override, a3 as PlaceholderDataFunction, a4 as QueriesPlaceholderDataFunction, x as Query, Q as QueryCache, a as QueryCacheNotifyEvent, b as QueryClient, b4 as QueryClientConfig, l as QueryFilters, Y as QueryFunction, a1 as QueryFunctionContext, I as QueryKey, a5 as QueryKeyHashFunction, a9 as QueryMeta, c as QueryObserver, az as QueryObserverBaseResult, aC as QueryObserverLoadingErrorResult, aB as QueryObserverLoadingResult, ag as QueryObserverOptions, aA as QueryObserverPendingResult, aF as QueryObserverPlaceholderResult, aD as QueryObserverRefetchErrorResult, aH as QueryObserverResult, aE as QueryObserverSuccessResult, ac as QueryOptions, a0 as QueryPersister, w as QueryState, ax as QueryStatus, aq as RefetchOptions, as as RefetchQueryFilters, R as Register, au as ResetOptions, ap as ResultOptions, b7 as SetDataOptions, S as SkipToken, Z as StaleTime, _ as StaleTimeFunction, af as ThrowOnError, P as UnsetMarker, U as Updater, ah as WithRequired, K as dataTagErrorSymbol, J as dataTagSymbol, v as defaultShouldDehydrateMutation, u as defaultShouldDehydrateQuery, q as dehydrate, h as hashKey, t as hydrate, o as isCancelledError, i as isServer, k as keepPreviousData, f as matchMutation, m as matchQuery, n as noop, p as partialMatchKey, r as replaceEqualDeep, g as shouldThrowError, s as skipToken, L as unsetMarker } from './hydration-CdBkFt9i.cjs';
export { QueriesObserver, QueriesObserverOptions } from './queriesObserver.cjs';
export { InfiniteQueryObserver } from './infiniteQueryObserver.cjs';
export { defaultScheduler, notifyManager } from './notifyManager.cjs';
export { focusManager } from './focusManager.cjs';
export { onlineManager } from './onlineManager.cjs';
export { streamedQuery as experimental_streamedQuery } from './streamedQuery.cjs';
import './removable.cjs';
import './subscribable.cjs';

View File

@@ -0,0 +1,9 @@
export { T as AnyDataTag, b6 as CancelOptions, C as CancelledError, V as DataTag, G as DefaultError, b5 as DefaultOptions, ak as DefaultedInfiniteQueryObserverOptions, ai as DefaultedQueryObserverOptions, aP as DefinedInfiniteQueryObserverResult, aG as DefinedQueryObserverResult, D as DehydrateOptions, A as DehydratedState, B as DistributiveOmit, $ as Enabled, an as EnsureInfiniteQueryDataOptions, am as EnsureQueryDataOptions, ao as FetchInfiniteQueryOptions, av as FetchNextPageOptions, aw as FetchPreviousPageOptions, al as FetchQueryOptions, ay as FetchStatus, a7 as GetNextPageParamFunction, a6 as GetPreviousPageParamFunction, H as HydrateOptions, W as InferDataFromTag, X as InferErrorFromTag, a8 as InfiniteData, aI as InfiniteQueryObserverBaseResult, aL as InfiniteQueryObserverLoadingErrorResult, aK as InfiniteQueryObserverLoadingResult, aj as InfiniteQueryObserverOptions, aJ as InfiniteQueryObserverPendingResult, aO as InfiniteQueryObserverPlaceholderResult, aM as InfiniteQueryObserverRefetchErrorResult, aQ as InfiniteQueryObserverResult, aN as InfiniteQueryObserverSuccessResult, ae as InfiniteQueryPageParamsOptions, a2 as InitialDataFunction, ad as InitialPageParam, at as InvalidateOptions, ar as InvalidateQueryFilters, aZ as MutateFunction, aY as MutateOptions, z as Mutation, M as MutationCache, d as MutationCacheNotifyEvent, j as MutationFilters, aV as MutationFunction, aR as MutationKey, aU as MutationMeta, e as MutationObserver, a_ as MutationObserverBaseResult, b1 as MutationObserverErrorResult, a$ as MutationObserverIdleResult, b0 as MutationObserverLoadingResult, aX as MutationObserverOptions, b3 as MutationObserverResult, b2 as MutationObserverSuccessResult, aW as MutationOptions, aT as MutationScope, y as MutationState, aS as MutationStatus, aa as NetworkMode, F as NoInfer, N as NonUndefinedGuard, b9 as NotifyEvent, b8 as NotifyEventType, ab as NotifyOnChangeProps, O as OmitKeyof, E as Override, a3 as PlaceholderDataFunction, a4 as QueriesPlaceholderDataFunction, x as Query, Q as QueryCache, a as QueryCacheNotifyEvent, b as QueryClient, b4 as QueryClientConfig, l as QueryFilters, Y as QueryFunction, a1 as QueryFunctionContext, I as QueryKey, a5 as QueryKeyHashFunction, a9 as QueryMeta, c as QueryObserver, az as QueryObserverBaseResult, aC as QueryObserverLoadingErrorResult, aB as QueryObserverLoadingResult, ag as QueryObserverOptions, aA as QueryObserverPendingResult, aF as QueryObserverPlaceholderResult, aD as QueryObserverRefetchErrorResult, aH as QueryObserverResult, aE as QueryObserverSuccessResult, ac as QueryOptions, a0 as QueryPersister, w as QueryState, ax as QueryStatus, aq as RefetchOptions, as as RefetchQueryFilters, R as Register, au as ResetOptions, ap as ResultOptions, b7 as SetDataOptions, S as SkipToken, Z as StaleTime, _ as StaleTimeFunction, af as ThrowOnError, P as UnsetMarker, U as Updater, ah as WithRequired, K as dataTagErrorSymbol, J as dataTagSymbol, v as defaultShouldDehydrateMutation, u as defaultShouldDehydrateQuery, q as dehydrate, h as hashKey, t as hydrate, o as isCancelledError, i as isServer, k as keepPreviousData, f as matchMutation, m as matchQuery, n as noop, p as partialMatchKey, r as replaceEqualDeep, g as shouldThrowError, s as skipToken, L as unsetMarker } from './hydration-Cr-4Kky1.js';
export { QueriesObserver, QueriesObserverOptions } from './queriesObserver.js';
export { InfiniteQueryObserver } from './infiniteQueryObserver.js';
export { defaultScheduler, notifyManager } from './notifyManager.js';
export { focusManager } from './focusManager.js';
export { onlineManager } from './onlineManager.js';
export { streamedQuery as experimental_streamedQuery } from './streamedQuery.js';
import './removable.js';
import './subscribable.js';

View File

@@ -0,0 +1,70 @@
import "./chunk-PXG64RU4.js";
// src/index.ts
import { CancelledError } from "./retryer.js";
import { QueryCache } from "./queryCache.js";
import { QueryClient } from "./queryClient.js";
import { QueryObserver } from "./queryObserver.js";
import { QueriesObserver } from "./queriesObserver.js";
import { InfiniteQueryObserver } from "./infiniteQueryObserver.js";
import { MutationCache } from "./mutationCache.js";
import { MutationObserver } from "./mutationObserver.js";
import { notifyManager, defaultScheduler } from "./notifyManager.js";
import { focusManager } from "./focusManager.js";
import { onlineManager } from "./onlineManager.js";
import {
hashKey,
partialMatchKey,
replaceEqualDeep,
isServer,
matchQuery,
matchMutation,
keepPreviousData,
skipToken,
noop,
shouldThrowError
} from "./utils.js";
import { isCancelledError } from "./retryer.js";
import {
dehydrate,
hydrate,
defaultShouldDehydrateQuery,
defaultShouldDehydrateMutation
} from "./hydration.js";
import { streamedQuery } from "./streamedQuery.js";
export * from "./types.js";
import { Query } from "./query.js";
import { Mutation } from "./mutation.js";
export {
CancelledError,
InfiniteQueryObserver,
Mutation,
MutationCache,
MutationObserver,
QueriesObserver,
Query,
QueryCache,
QueryClient,
QueryObserver,
defaultScheduler,
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
streamedQuery as experimental_streamedQuery,
focusManager,
hashKey,
hydrate,
isCancelledError,
isServer,
keepPreviousData,
matchMutation,
matchQuery,
noop,
notifyManager,
onlineManager,
partialMatchKey,
replaceEqualDeep,
shouldThrowError,
skipToken
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport { CancelledError } from './retryer'\nexport { QueryCache } from './queryCache'\nexport type { QueryCacheNotifyEvent } from './queryCache'\nexport { QueryClient } from './queryClient'\nexport { QueryObserver } from './queryObserver'\nexport { QueriesObserver } from './queriesObserver'\nexport { InfiniteQueryObserver } from './infiniteQueryObserver'\nexport { MutationCache } from './mutationCache'\nexport type { MutationCacheNotifyEvent } from './mutationCache'\nexport { MutationObserver } from './mutationObserver'\nexport { notifyManager, defaultScheduler } from './notifyManager'\nexport { focusManager } from './focusManager'\nexport { onlineManager } from './onlineManager'\nexport {\n hashKey,\n partialMatchKey,\n replaceEqualDeep,\n isServer,\n matchQuery,\n matchMutation,\n keepPreviousData,\n skipToken,\n noop,\n shouldThrowError,\n} from './utils'\nexport type { MutationFilters, QueryFilters, Updater, SkipToken } from './utils'\nexport { isCancelledError } from './retryer'\nexport {\n dehydrate,\n hydrate,\n defaultShouldDehydrateQuery,\n defaultShouldDehydrateMutation,\n} from './hydration'\n\nexport { streamedQuery as experimental_streamedQuery } from './streamedQuery'\n\n// Types\nexport * from './types'\nexport type { QueryState } from './query'\nexport { Query } from './query'\nexport type { MutationState } from './mutation'\nexport { Mutation } from './mutation'\nexport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n} from './hydration'\nexport type { QueriesObserverOptions } from './queriesObserver'\n"],"mappings":";;;AAEA,SAAS,sBAAsB;AAC/B,SAAS,kBAAkB;AAE3B,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,qBAAqB;AAE9B,SAAS,wBAAwB;AACjC,SAAS,eAAe,wBAAwB;AAChD,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAA0B,qBAAkC;AAG5D,cAAc;AAEd,SAAS,aAAa;AAEtB,SAAS,gBAAgB;","names":[]}

View File

@@ -0,0 +1,154 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/infiniteQueryBehavior.ts
var infiniteQueryBehavior_exports = {};
__export(infiniteQueryBehavior_exports, {
hasNextPage: () => hasNextPage,
hasPreviousPage: () => hasPreviousPage,
infiniteQueryBehavior: () => infiniteQueryBehavior
});
module.exports = __toCommonJS(infiniteQueryBehavior_exports);
var import_utils = require("./utils.cjs");
function infiniteQueryBehavior(pages) {
return {
onFetch: (context, query) => {
var _a, _b, _c, _d, _e;
const options = context.options;
const direction = (_c = (_b = (_a = context.fetchOptions) == null ? void 0 : _a.meta) == null ? void 0 : _b.fetchMore) == null ? void 0 : _c.direction;
const oldPages = ((_d = context.state.data) == null ? void 0 : _d.pages) || [];
const oldPageParams = ((_e = context.state.data) == null ? void 0 : _e.pageParams) || [];
let result = { pages: [], pageParams: [] };
let currentPage = 0;
const fetchFn = async () => {
let cancelled = false;
const addSignalProperty = (object) => {
Object.defineProperty(object, "signal", {
enumerable: true,
get: () => {
if (context.signal.aborted) {
cancelled = true;
} else {
context.signal.addEventListener("abort", () => {
cancelled = true;
});
}
return context.signal;
}
});
};
const queryFn = (0, import_utils.ensureQueryFn)(context.options, context.fetchOptions);
const fetchPage = async (data, param, previous) => {
if (cancelled) {
return Promise.reject();
}
if (param == null && data.pages.length) {
return Promise.resolve(data);
}
const createQueryFnContext = () => {
const queryFnContext2 = {
client: context.client,
queryKey: context.queryKey,
pageParam: param,
direction: previous ? "backward" : "forward",
meta: context.options.meta
};
addSignalProperty(queryFnContext2);
return queryFnContext2;
};
const queryFnContext = createQueryFnContext();
const page = await queryFn(queryFnContext);
const { maxPages } = context.options;
const addTo = previous ? import_utils.addToStart : import_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
};
const param = pageParamFn(options, oldData);
result = await fetchPage(oldData, param, 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 _a2, _b2;
return (_b2 = (_a2 = context.options).persister) == null ? void 0 : _b2.call(
_a2,
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 _a;
return pages.length > 0 ? (_a = options.getPreviousPageParam) == null ? void 0 : _a.call(options, pages[0], pages, pageParams[0], pageParams) : void 0;
}
function hasNextPage(options, data) {
if (!data) return false;
return getNextPageParam(options, data) != null;
}
function hasPreviousPage(options, data) {
if (!data || !options.getPreviousPageParam) return false;
return getPreviousPageParam(options, data) != null;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
hasNextPage,
hasPreviousPage,
infiniteQueryBehavior
});
//# sourceMappingURL=infiniteQueryBehavior.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
import { ba as QueryBehavior, a8 as InfiniteData, ae as InfiniteQueryPageParamsOptions } from './hydration-CdBkFt9i.cjs';
import './removable.cjs';
import './subscribable.cjs';
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;
export { hasNextPage, hasPreviousPage, infiniteQueryBehavior };

View File

@@ -0,0 +1,15 @@
import { ba as QueryBehavior, a8 as InfiniteData, ae as InfiniteQueryPageParamsOptions } from './hydration-Cr-4Kky1.js';
import './removable.js';
import './subscribable.js';
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;
export { hasNextPage, hasPreviousPage, infiniteQueryBehavior };

View File

@@ -0,0 +1,129 @@
import "./chunk-PXG64RU4.js";
// src/infiniteQueryBehavior.ts
import { addToEnd, addToStart, ensureQueryFn } from "./utils.js";
function infiniteQueryBehavior(pages) {
return {
onFetch: (context, query) => {
var _a, _b, _c, _d, _e;
const options = context.options;
const direction = (_c = (_b = (_a = context.fetchOptions) == null ? void 0 : _a.meta) == null ? void 0 : _b.fetchMore) == null ? void 0 : _c.direction;
const oldPages = ((_d = context.state.data) == null ? void 0 : _d.pages) || [];
const oldPageParams = ((_e = context.state.data) == null ? void 0 : _e.pageParams) || [];
let result = { pages: [], pageParams: [] };
let currentPage = 0;
const fetchFn = async () => {
let cancelled = false;
const addSignalProperty = (object) => {
Object.defineProperty(object, "signal", {
enumerable: true,
get: () => {
if (context.signal.aborted) {
cancelled = true;
} else {
context.signal.addEventListener("abort", () => {
cancelled = true;
});
}
return context.signal;
}
});
};
const queryFn = ensureQueryFn(context.options, context.fetchOptions);
const fetchPage = async (data, param, previous) => {
if (cancelled) {
return Promise.reject();
}
if (param == null && data.pages.length) {
return Promise.resolve(data);
}
const createQueryFnContext = () => {
const queryFnContext2 = {
client: context.client,
queryKey: context.queryKey,
pageParam: param,
direction: previous ? "backward" : "forward",
meta: context.options.meta
};
addSignalProperty(queryFnContext2);
return queryFnContext2;
};
const queryFnContext = createQueryFnContext();
const page = await queryFn(queryFnContext);
const { maxPages } = context.options;
const addTo = previous ? addToStart : addToEnd;
return {
pages: addTo(data.pages, page, maxPages),
pageParams: addTo(data.pageParams, param, maxPages)
};
};
if (direction && oldPages.length) {
const previous = direction === "backward";
const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
const oldData = {
pages: oldPages,
pageParams: oldPageParams
};
const param = pageParamFn(options, oldData);
result = await fetchPage(oldData, param, 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 _a2, _b2;
return (_b2 = (_a2 = context.options).persister) == null ? void 0 : _b2.call(
_a2,
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 _a;
return pages.length > 0 ? (_a = options.getPreviousPageParam) == null ? void 0 : _a.call(options, pages[0], pages, pageParams[0], pageParams) : void 0;
}
function hasNextPage(options, data) {
if (!data) return false;
return getNextPageParam(options, data) != null;
}
function hasPreviousPage(options, data) {
if (!data || !options.getPreviousPageParam) return false;
return getPreviousPageParam(options, data) != null;
}
export {
hasNextPage,
hasPreviousPage,
infiniteQueryBehavior
};
//# sourceMappingURL=infiniteQueryBehavior.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,93 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/infiniteQueryObserver.ts
var infiniteQueryObserver_exports = {};
__export(infiniteQueryObserver_exports, {
InfiniteQueryObserver: () => InfiniteQueryObserver
});
module.exports = __toCommonJS(infiniteQueryObserver_exports);
var import_queryObserver = require("./queryObserver.cjs");
var import_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs");
var InfiniteQueryObserver = class extends import_queryObserver.QueryObserver {
constructor(client, options) {
super(client, options);
}
bindMethods() {
super.bindMethods();
this.fetchNextPage = this.fetchNextPage.bind(this);
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
}
setOptions(options) {
super.setOptions({
...options,
behavior: (0, import_infiniteQueryBehavior.infiniteQueryBehavior)()
});
}
getOptimisticResult(options) {
options.behavior = (0, import_infiniteQueryBehavior.infiniteQueryBehavior)();
return super.getOptimisticResult(options);
}
fetchNextPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "forward" }
}
});
}
fetchPreviousPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "backward" }
}
});
}
createResult(query, options) {
var _a, _b;
const { state } = query;
const parentResult = super.createResult(query, options);
const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
const fetchDirection = (_b = (_a = state.fetchMeta) == null ? void 0 : _a.fetchMore) == null ? void 0 : _b.direction;
const isFetchNextPageError = isError && fetchDirection === "forward";
const isFetchingNextPage = isFetching && fetchDirection === "forward";
const isFetchPreviousPageError = isError && fetchDirection === "backward";
const isFetchingPreviousPage = isFetching && fetchDirection === "backward";
const result = {
...parentResult,
fetchNextPage: this.fetchNextPage,
fetchPreviousPage: this.fetchPreviousPage,
hasNextPage: (0, import_infiniteQueryBehavior.hasNextPage)(options, state.data),
hasPreviousPage: (0, import_infiniteQueryBehavior.hasPreviousPage)(options, state.data),
isFetchNextPageError,
isFetchingNextPage,
isFetchPreviousPageError,
isFetchingPreviousPage,
isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
};
return result;
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
InfiniteQueryObserver
});
//# sourceMappingURL=infiniteQueryObserver.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,20 @@
import { G as DefaultError, a8 as InfiniteData, I as QueryKey, c as QueryObserver, aQ as InfiniteQueryObserverResult, b as QueryClient, aj as InfiniteQueryObserverOptions, ak as DefaultedInfiniteQueryObserverOptions, av as FetchNextPageOptions, aw as FetchPreviousPageOptions, x as Query } from './hydration-CdBkFt9i.cjs';
import { Subscribable } from './subscribable.cjs';
import './removable.cjs';
type InfiniteQueryObserverListener<TData, TError> = (result: InfiniteQueryObserverResult<TData, TError>) => void;
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;
setOptions(options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): void;
getOptimisticResult(options: DefaultedInfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserverResult<TData, TError>;
fetchNextPage(options?: FetchNextPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
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;
export { InfiniteQueryObserver };

View File

@@ -0,0 +1,20 @@
import { G as DefaultError, a8 as InfiniteData, I as QueryKey, c as QueryObserver, aQ as InfiniteQueryObserverResult, b as QueryClient, aj as InfiniteQueryObserverOptions, ak as DefaultedInfiniteQueryObserverOptions, av as FetchNextPageOptions, aw as FetchPreviousPageOptions, x as Query } from './hydration-Cr-4Kky1.js';
import { Subscribable } from './subscribable.js';
import './removable.js';
type InfiniteQueryObserverListener<TData, TError> = (result: InfiniteQueryObserverResult<TData, TError>) => void;
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;
setOptions(options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): void;
getOptimisticResult(options: DefaultedInfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): InfiniteQueryObserverResult<TData, TError>;
fetchNextPage(options?: FetchNextPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
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;
export { InfiniteQueryObserver };

View File

@@ -0,0 +1,74 @@
import "./chunk-PXG64RU4.js";
// src/infiniteQueryObserver.ts
import { QueryObserver } from "./queryObserver.js";
import {
hasNextPage,
hasPreviousPage,
infiniteQueryBehavior
} from "./infiniteQueryBehavior.js";
var InfiniteQueryObserver = class extends QueryObserver {
constructor(client, options) {
super(client, options);
}
bindMethods() {
super.bindMethods();
this.fetchNextPage = this.fetchNextPage.bind(this);
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
}
setOptions(options) {
super.setOptions({
...options,
behavior: infiniteQueryBehavior()
});
}
getOptimisticResult(options) {
options.behavior = infiniteQueryBehavior();
return super.getOptimisticResult(options);
}
fetchNextPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "forward" }
}
});
}
fetchPreviousPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "backward" }
}
});
}
createResult(query, options) {
var _a, _b;
const { state } = query;
const parentResult = super.createResult(query, options);
const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
const fetchDirection = (_b = (_a = state.fetchMeta) == null ? void 0 : _a.fetchMore) == null ? void 0 : _b.direction;
const isFetchNextPageError = isError && fetchDirection === "forward";
const isFetchingNextPage = isFetching && fetchDirection === "forward";
const isFetchPreviousPageError = isError && fetchDirection === "backward";
const isFetchingPreviousPage = isFetching && fetchDirection === "backward";
const result = {
...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
};
return result;
}
};
export {
InfiniteQueryObserver
};
//# sourceMappingURL=infiniteQueryObserver.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,287 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// src/mutation.ts
var mutation_exports = {};
__export(mutation_exports, {
Mutation: () => Mutation,
getDefaultState: () => getDefaultState
});
module.exports = __toCommonJS(mutation_exports);
var import_notifyManager = require("./notifyManager.cjs");
var import_removable = require("./removable.cjs");
var import_retryer = require("./retryer.cjs");
var _observers, _mutationCache, _retryer, _Mutation_instances, dispatch_fn;
var Mutation = class extends import_removable.Removable {
constructor(config) {
super();
__privateAdd(this, _Mutation_instances);
__privateAdd(this, _observers);
__privateAdd(this, _mutationCache);
__privateAdd(this, _retryer);
this.mutationId = config.mutationId;
__privateSet(this, _mutationCache, config.mutationCache);
__privateSet(this, _observers, []);
this.state = config.state || getDefaultState();
this.setOptions(config.options);
this.scheduleGc();
}
setOptions(options) {
this.options = options;
this.updateGcTime(this.options.gcTime);
}
get meta() {
return this.options.meta;
}
addObserver(observer) {
if (!__privateGet(this, _observers).includes(observer)) {
__privateGet(this, _observers).push(observer);
this.clearGcTimeout();
__privateGet(this, _mutationCache).notify({
type: "observerAdded",
mutation: this,
observer
});
}
}
removeObserver(observer) {
__privateSet(this, _observers, __privateGet(this, _observers).filter((x) => x !== observer));
this.scheduleGc();
__privateGet(this, _mutationCache).notify({
type: "observerRemoved",
mutation: this,
observer
});
}
optionalRemove() {
if (!__privateGet(this, _observers).length) {
if (this.state.status === "pending") {
this.scheduleGc();
} else {
__privateGet(this, _mutationCache).remove(this);
}
}
}
continue() {
var _a;
return ((_a = __privateGet(this, _retryer)) == null ? void 0 : _a.continue()) ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
this.execute(this.state.variables);
}
async execute(variables) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
const onContinue = () => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "continue" });
};
__privateSet(this, _retryer, (0, import_retryer.createRetryer)({
fn: () => {
if (!this.options.mutationFn) {
return Promise.reject(new Error("No mutationFn found"));
}
return this.options.mutationFn(variables);
},
onFail: (failureCount, error) => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "failed", failureCount, error });
},
onPause: () => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "pause" });
},
onContinue,
retry: this.options.retry ?? 0,
retryDelay: this.options.retryDelay,
networkMode: this.options.networkMode,
canRun: () => __privateGet(this, _mutationCache).canRun(this)
}));
const restored = this.state.status === "pending";
const isPaused = !__privateGet(this, _retryer).canStart();
try {
if (restored) {
onContinue();
} else {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "pending", variables, isPaused });
await ((_b = (_a = __privateGet(this, _mutationCache).config).onMutate) == null ? void 0 : _b.call(
_a,
variables,
this
));
const context = await ((_d = (_c = this.options).onMutate) == null ? void 0 : _d.call(_c, variables));
if (context !== this.state.context) {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, {
type: "pending",
context,
variables,
isPaused
});
}
}
const data = await __privateGet(this, _retryer).start();
await ((_f = (_e = __privateGet(this, _mutationCache).config).onSuccess) == null ? void 0 : _f.call(
_e,
data,
variables,
this.state.context,
this
));
await ((_h = (_g = this.options).onSuccess) == null ? void 0 : _h.call(_g, data, variables, this.state.context));
await ((_j = (_i = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _j.call(
_i,
data,
null,
this.state.variables,
this.state.context,
this
));
await ((_l = (_k = this.options).onSettled) == null ? void 0 : _l.call(_k, data, null, variables, this.state.context));
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "success", data });
return data;
} catch (error) {
try {
await ((_n = (_m = __privateGet(this, _mutationCache).config).onError) == null ? void 0 : _n.call(
_m,
error,
variables,
this.state.context,
this
));
await ((_p = (_o = this.options).onError) == null ? void 0 : _p.call(
_o,
error,
variables,
this.state.context
));
await ((_r = (_q = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _r.call(
_q,
void 0,
error,
this.state.variables,
this.state.context,
this
));
await ((_t = (_s = this.options).onSettled) == null ? void 0 : _t.call(
_s,
void 0,
error,
variables,
this.state.context
));
throw error;
} finally {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "error", error });
}
} finally {
__privateGet(this, _mutationCache).runNext(this);
}
}
};
_observers = new WeakMap();
_mutationCache = new WeakMap();
_retryer = new WeakMap();
_Mutation_instances = new WeakSet();
dispatch_fn = function(action) {
const reducer = (state) => {
switch (action.type) {
case "failed":
return {
...state,
failureCount: action.failureCount,
failureReason: action.error
};
case "pause":
return {
...state,
isPaused: true
};
case "continue":
return {
...state,
isPaused: false
};
case "pending":
return {
...state,
context: action.context,
data: void 0,
failureCount: 0,
failureReason: null,
error: null,
isPaused: action.isPaused,
status: "pending",
variables: action.variables,
submittedAt: Date.now()
};
case "success":
return {
...state,
data: action.data,
failureCount: 0,
failureReason: null,
error: null,
status: "success",
isPaused: false
};
case "error":
return {
...state,
data: void 0,
error: action.error,
failureCount: state.failureCount + 1,
failureReason: action.error,
isPaused: false,
status: "error"
};
}
};
this.state = reducer(this.state);
import_notifyManager.notifyManager.batch(() => {
__privateGet(this, _observers).forEach((observer) => {
observer.onMutationUpdate(action);
});
__privateGet(this, _mutationCache).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
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Mutation,
getDefaultState
});
//# sourceMappingURL=mutation.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
import './removable.cjs';
export { bi as Action, z as Mutation, y as MutationState, bj as getDefaultState } from './hydration-CdBkFt9i.cjs';
import './subscribable.cjs';

View File

@@ -0,0 +1,3 @@
import './removable.js';
export { bi as Action, z as Mutation, y as MutationState, bj as getDefaultState } from './hydration-Cr-4Kky1.js';
import './subscribable.js';

View File

@@ -0,0 +1,260 @@
import {
__privateAdd,
__privateGet,
__privateMethod,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/mutation.ts
import { notifyManager } from "./notifyManager.js";
import { Removable } from "./removable.js";
import { createRetryer } from "./retryer.js";
var _observers, _mutationCache, _retryer, _Mutation_instances, dispatch_fn;
var Mutation = class extends Removable {
constructor(config) {
super();
__privateAdd(this, _Mutation_instances);
__privateAdd(this, _observers);
__privateAdd(this, _mutationCache);
__privateAdd(this, _retryer);
this.mutationId = config.mutationId;
__privateSet(this, _mutationCache, config.mutationCache);
__privateSet(this, _observers, []);
this.state = config.state || getDefaultState();
this.setOptions(config.options);
this.scheduleGc();
}
setOptions(options) {
this.options = options;
this.updateGcTime(this.options.gcTime);
}
get meta() {
return this.options.meta;
}
addObserver(observer) {
if (!__privateGet(this, _observers).includes(observer)) {
__privateGet(this, _observers).push(observer);
this.clearGcTimeout();
__privateGet(this, _mutationCache).notify({
type: "observerAdded",
mutation: this,
observer
});
}
}
removeObserver(observer) {
__privateSet(this, _observers, __privateGet(this, _observers).filter((x) => x !== observer));
this.scheduleGc();
__privateGet(this, _mutationCache).notify({
type: "observerRemoved",
mutation: this,
observer
});
}
optionalRemove() {
if (!__privateGet(this, _observers).length) {
if (this.state.status === "pending") {
this.scheduleGc();
} else {
__privateGet(this, _mutationCache).remove(this);
}
}
}
continue() {
var _a;
return ((_a = __privateGet(this, _retryer)) == null ? void 0 : _a.continue()) ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
this.execute(this.state.variables);
}
async execute(variables) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
const onContinue = () => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "continue" });
};
__privateSet(this, _retryer, createRetryer({
fn: () => {
if (!this.options.mutationFn) {
return Promise.reject(new Error("No mutationFn found"));
}
return this.options.mutationFn(variables);
},
onFail: (failureCount, error) => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "failed", failureCount, error });
},
onPause: () => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "pause" });
},
onContinue,
retry: this.options.retry ?? 0,
retryDelay: this.options.retryDelay,
networkMode: this.options.networkMode,
canRun: () => __privateGet(this, _mutationCache).canRun(this)
}));
const restored = this.state.status === "pending";
const isPaused = !__privateGet(this, _retryer).canStart();
try {
if (restored) {
onContinue();
} else {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "pending", variables, isPaused });
await ((_b = (_a = __privateGet(this, _mutationCache).config).onMutate) == null ? void 0 : _b.call(
_a,
variables,
this
));
const context = await ((_d = (_c = this.options).onMutate) == null ? void 0 : _d.call(_c, variables));
if (context !== this.state.context) {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, {
type: "pending",
context,
variables,
isPaused
});
}
}
const data = await __privateGet(this, _retryer).start();
await ((_f = (_e = __privateGet(this, _mutationCache).config).onSuccess) == null ? void 0 : _f.call(
_e,
data,
variables,
this.state.context,
this
));
await ((_h = (_g = this.options).onSuccess) == null ? void 0 : _h.call(_g, data, variables, this.state.context));
await ((_j = (_i = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _j.call(
_i,
data,
null,
this.state.variables,
this.state.context,
this
));
await ((_l = (_k = this.options).onSettled) == null ? void 0 : _l.call(_k, data, null, variables, this.state.context));
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "success", data });
return data;
} catch (error) {
try {
await ((_n = (_m = __privateGet(this, _mutationCache).config).onError) == null ? void 0 : _n.call(
_m,
error,
variables,
this.state.context,
this
));
await ((_p = (_o = this.options).onError) == null ? void 0 : _p.call(
_o,
error,
variables,
this.state.context
));
await ((_r = (_q = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _r.call(
_q,
void 0,
error,
this.state.variables,
this.state.context,
this
));
await ((_t = (_s = this.options).onSettled) == null ? void 0 : _t.call(
_s,
void 0,
error,
variables,
this.state.context
));
throw error;
} finally {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "error", error });
}
} finally {
__privateGet(this, _mutationCache).runNext(this);
}
}
};
_observers = new WeakMap();
_mutationCache = new WeakMap();
_retryer = new WeakMap();
_Mutation_instances = new WeakSet();
dispatch_fn = function(action) {
const reducer = (state) => {
switch (action.type) {
case "failed":
return {
...state,
failureCount: action.failureCount,
failureReason: action.error
};
case "pause":
return {
...state,
isPaused: true
};
case "continue":
return {
...state,
isPaused: false
};
case "pending":
return {
...state,
context: action.context,
data: void 0,
failureCount: 0,
failureReason: null,
error: null,
isPaused: action.isPaused,
status: "pending",
variables: action.variables,
submittedAt: Date.now()
};
case "success":
return {
...state,
data: action.data,
failureCount: 0,
failureReason: null,
error: null,
status: "success",
isPaused: false
};
case "error":
return {
...state,
data: void 0,
error: action.error,
failureCount: state.failureCount + 1,
failureReason: action.error,
isPaused: false,
status: "error"
};
}
};
this.state = reducer(this.state);
notifyManager.batch(() => {
__privateGet(this, _observers).forEach((observer) => {
observer.onMutationUpdate(action);
});
__privateGet(this, _mutationCache).notify({
mutation: this,
type: "updated",
action
});
});
};
function getDefaultState() {
return {
context: void 0,
data: void 0,
error: null,
failureCount: 0,
failureReason: null,
isPaused: false,
status: "idle",
variables: void 0,
submittedAt: 0
};
}
export {
Mutation,
getDefaultState
};
//# sourceMappingURL=mutation.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,169 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateWrapper = (obj, member, setter, getter) => ({
set _(value) {
__privateSet(obj, member, value, setter);
},
get _() {
return __privateGet(obj, member, getter);
}
});
// src/mutationCache.ts
var mutationCache_exports = {};
__export(mutationCache_exports, {
MutationCache: () => MutationCache
});
module.exports = __toCommonJS(mutationCache_exports);
var import_notifyManager = require("./notifyManager.cjs");
var import_mutation = require("./mutation.cjs");
var import_utils = require("./utils.cjs");
var import_subscribable = require("./subscribable.cjs");
var _mutations, _scopes, _mutationId;
var MutationCache = class extends import_subscribable.Subscribable {
constructor(config = {}) {
super();
this.config = config;
__privateAdd(this, _mutations);
__privateAdd(this, _scopes);
__privateAdd(this, _mutationId);
__privateSet(this, _mutations, /* @__PURE__ */ new Set());
__privateSet(this, _scopes, /* @__PURE__ */ new Map());
__privateSet(this, _mutationId, 0);
}
build(client, options, state) {
const mutation = new import_mutation.Mutation({
mutationCache: this,
mutationId: ++__privateWrapper(this, _mutationId)._,
options: client.defaultMutationOptions(options),
state
});
this.add(mutation);
return mutation;
}
add(mutation) {
__privateGet(this, _mutations).add(mutation);
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = __privateGet(this, _scopes).get(scope);
if (scopedMutations) {
scopedMutations.push(mutation);
} else {
__privateGet(this, _scopes).set(scope, [mutation]);
}
}
this.notify({ type: "added", mutation });
}
remove(mutation) {
if (__privateGet(this, _mutations).delete(mutation)) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = __privateGet(this, _scopes).get(scope);
if (scopedMutations) {
if (scopedMutations.length > 1) {
const index = scopedMutations.indexOf(mutation);
if (index !== -1) {
scopedMutations.splice(index, 1);
}
} else if (scopedMutations[0] === mutation) {
__privateGet(this, _scopes).delete(scope);
}
}
}
}
this.notify({ type: "removed", mutation });
}
canRun(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const mutationsWithSameScope = __privateGet(this, _scopes).get(scope);
const firstPendingMutation = mutationsWithSameScope == null ? void 0 : mutationsWithSameScope.find(
(m) => m.state.status === "pending"
);
return !firstPendingMutation || firstPendingMutation === mutation;
} else {
return true;
}
}
runNext(mutation) {
var _a;
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const foundMutation = (_a = __privateGet(this, _scopes).get(scope)) == null ? void 0 : _a.find((m) => m !== mutation && m.state.isPaused);
return (foundMutation == null ? void 0 : foundMutation.continue()) ?? Promise.resolve();
} else {
return Promise.resolve();
}
}
clear() {
import_notifyManager.notifyManager.batch(() => {
__privateGet(this, _mutations).forEach((mutation) => {
this.notify({ type: "removed", mutation });
});
__privateGet(this, _mutations).clear();
__privateGet(this, _scopes).clear();
});
}
getAll() {
return Array.from(__privateGet(this, _mutations));
}
find(filters) {
const defaultedFilters = { exact: true, ...filters };
return this.getAll().find(
(mutation) => (0, import_utils.matchMutation)(defaultedFilters, mutation)
);
}
findAll(filters = {}) {
return this.getAll().filter((mutation) => (0, import_utils.matchMutation)(filters, mutation));
}
notify(event) {
import_notifyManager.notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(event);
});
});
}
resumePausedMutations() {
const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
return import_notifyManager.notifyManager.batch(
() => Promise.all(
pausedMutations.map((mutation) => mutation.continue().catch(import_utils.noop))
)
);
}
};
_mutations = new WeakMap();
_scopes = new WeakMap();
_mutationId = new WeakMap();
function scopeFor(mutation) {
var _a;
return (_a = mutation.options.scope) == null ? void 0 : _a.id;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MutationCache
});
//# sourceMappingURL=mutationCache.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export { M as MutationCache, d as MutationCacheNotifyEvent } from './hydration-CdBkFt9i.cjs';
import './subscribable.cjs';
import './removable.cjs';

View File

@@ -0,0 +1,3 @@
export { M as MutationCache, d as MutationCacheNotifyEvent } from './hydration-Cr-4Kky1.js';
import './subscribable.js';
import './removable.js';

View File

@@ -0,0 +1,136 @@
import {
__privateAdd,
__privateGet,
__privateSet,
__privateWrapper
} from "./chunk-PXG64RU4.js";
// src/mutationCache.ts
import { notifyManager } from "./notifyManager.js";
import { Mutation } from "./mutation.js";
import { matchMutation, noop } from "./utils.js";
import { Subscribable } from "./subscribable.js";
var _mutations, _scopes, _mutationId;
var MutationCache = class extends Subscribable {
constructor(config = {}) {
super();
this.config = config;
__privateAdd(this, _mutations);
__privateAdd(this, _scopes);
__privateAdd(this, _mutationId);
__privateSet(this, _mutations, /* @__PURE__ */ new Set());
__privateSet(this, _scopes, /* @__PURE__ */ new Map());
__privateSet(this, _mutationId, 0);
}
build(client, options, state) {
const mutation = new Mutation({
mutationCache: this,
mutationId: ++__privateWrapper(this, _mutationId)._,
options: client.defaultMutationOptions(options),
state
});
this.add(mutation);
return mutation;
}
add(mutation) {
__privateGet(this, _mutations).add(mutation);
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = __privateGet(this, _scopes).get(scope);
if (scopedMutations) {
scopedMutations.push(mutation);
} else {
__privateGet(this, _scopes).set(scope, [mutation]);
}
}
this.notify({ type: "added", mutation });
}
remove(mutation) {
if (__privateGet(this, _mutations).delete(mutation)) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = __privateGet(this, _scopes).get(scope);
if (scopedMutations) {
if (scopedMutations.length > 1) {
const index = scopedMutations.indexOf(mutation);
if (index !== -1) {
scopedMutations.splice(index, 1);
}
} else if (scopedMutations[0] === mutation) {
__privateGet(this, _scopes).delete(scope);
}
}
}
}
this.notify({ type: "removed", mutation });
}
canRun(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const mutationsWithSameScope = __privateGet(this, _scopes).get(scope);
const firstPendingMutation = mutationsWithSameScope == null ? void 0 : mutationsWithSameScope.find(
(m) => m.state.status === "pending"
);
return !firstPendingMutation || firstPendingMutation === mutation;
} else {
return true;
}
}
runNext(mutation) {
var _a;
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const foundMutation = (_a = __privateGet(this, _scopes).get(scope)) == null ? void 0 : _a.find((m) => m !== mutation && m.state.isPaused);
return (foundMutation == null ? void 0 : foundMutation.continue()) ?? Promise.resolve();
} else {
return Promise.resolve();
}
}
clear() {
notifyManager.batch(() => {
__privateGet(this, _mutations).forEach((mutation) => {
this.notify({ type: "removed", mutation });
});
__privateGet(this, _mutations).clear();
__privateGet(this, _scopes).clear();
});
}
getAll() {
return Array.from(__privateGet(this, _mutations));
}
find(filters) {
const defaultedFilters = { exact: true, ...filters };
return this.getAll().find(
(mutation) => matchMutation(defaultedFilters, mutation)
);
}
findAll(filters = {}) {
return this.getAll().filter((mutation) => matchMutation(filters, mutation));
}
notify(event) {
notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(event);
});
});
}
resumePausedMutations() {
const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
return notifyManager.batch(
() => Promise.all(
pausedMutations.map((mutation) => mutation.continue().catch(noop))
)
);
}
};
_mutations = new WeakMap();
_scopes = new WeakMap();
_mutationId = new WeakMap();
function scopeFor(mutation) {
var _a;
return (_a = mutation.options.scope) == null ? void 0 : _a.id;
}
export {
MutationCache
};
//# sourceMappingURL=mutationCache.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,149 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// src/mutationObserver.ts
var mutationObserver_exports = {};
__export(mutationObserver_exports, {
MutationObserver: () => MutationObserver
});
module.exports = __toCommonJS(mutationObserver_exports);
var import_mutation = require("./mutation.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_subscribable = require("./subscribable.cjs");
var import_utils = require("./utils.cjs");
var _client, _currentResult, _currentMutation, _mutateOptions, _MutationObserver_instances, updateResult_fn, notify_fn;
var MutationObserver = class extends import_subscribable.Subscribable {
constructor(client, options) {
super();
__privateAdd(this, _MutationObserver_instances);
__privateAdd(this, _client);
__privateAdd(this, _currentResult);
__privateAdd(this, _currentMutation);
__privateAdd(this, _mutateOptions);
__privateSet(this, _client, client);
this.setOptions(options);
this.bindMethods();
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
}
bindMethods() {
this.mutate = this.mutate.bind(this);
this.reset = this.reset.bind(this);
}
setOptions(options) {
var _a;
const prevOptions = this.options;
this.options = __privateGet(this, _client).defaultMutationOptions(options);
if (!(0, import_utils.shallowEqualObjects)(this.options, prevOptions)) {
__privateGet(this, _client).getMutationCache().notify({
type: "observerOptionsUpdated",
mutation: __privateGet(this, _currentMutation),
observer: this
});
}
if ((prevOptions == null ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && (0, import_utils.hashKey)(prevOptions.mutationKey) !== (0, import_utils.hashKey)(this.options.mutationKey)) {
this.reset();
} else if (((_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.state.status) === "pending") {
__privateGet(this, _currentMutation).setOptions(this.options);
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
}
}
onMutationUpdate(action) {
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
__privateMethod(this, _MutationObserver_instances, notify_fn).call(this, action);
}
getCurrentResult() {
return __privateGet(this, _currentResult);
}
reset() {
var _a;
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
__privateSet(this, _currentMutation, void 0);
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
__privateMethod(this, _MutationObserver_instances, notify_fn).call(this);
}
mutate(variables, options) {
var _a;
__privateSet(this, _mutateOptions, options);
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
__privateSet(this, _currentMutation, __privateGet(this, _client).getMutationCache().build(__privateGet(this, _client), this.options));
__privateGet(this, _currentMutation).addObserver(this);
return __privateGet(this, _currentMutation).execute(variables);
}
};
_client = new WeakMap();
_currentResult = new WeakMap();
_currentMutation = new WeakMap();
_mutateOptions = new WeakMap();
_MutationObserver_instances = new WeakSet();
updateResult_fn = function() {
var _a;
const state = ((_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.state) ?? (0, import_mutation.getDefaultState)();
__privateSet(this, _currentResult, {
...state,
isPending: state.status === "pending",
isSuccess: state.status === "success",
isError: state.status === "error",
isIdle: state.status === "idle",
mutate: this.mutate,
reset: this.reset
});
};
notify_fn = function(action) {
import_notifyManager.notifyManager.batch(() => {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (__privateGet(this, _mutateOptions) && this.hasListeners()) {
const variables = __privateGet(this, _currentResult).variables;
const context = __privateGet(this, _currentResult).context;
if ((action == null ? void 0 : action.type) === "success") {
(_b = (_a = __privateGet(this, _mutateOptions)).onSuccess) == null ? void 0 : _b.call(_a, action.data, variables, context);
(_d = (_c = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _d.call(_c, action.data, null, variables, context);
} else if ((action == null ? void 0 : action.type) === "error") {
(_f = (_e = __privateGet(this, _mutateOptions)).onError) == null ? void 0 : _f.call(_e, action.error, variables, context);
(_h = (_g = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _h.call(
_g,
void 0,
action.error,
variables,
context
);
}
}
this.listeners.forEach((listener) => {
listener(__privateGet(this, _currentResult));
});
});
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MutationObserver
});
//# sourceMappingURL=mutationObserver.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
import './subscribable.cjs';
export { e as MutationObserver } from './hydration-CdBkFt9i.cjs';
import './removable.cjs';

View File

@@ -0,0 +1,3 @@
import './subscribable.js';
export { e as MutationObserver } from './hydration-Cr-4Kky1.js';
import './removable.js';

View File

@@ -0,0 +1,123 @@
import {
__privateAdd,
__privateGet,
__privateMethod,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/mutationObserver.ts
import { getDefaultState } from "./mutation.js";
import { notifyManager } from "./notifyManager.js";
import { Subscribable } from "./subscribable.js";
import { hashKey, shallowEqualObjects } from "./utils.js";
var _client, _currentResult, _currentMutation, _mutateOptions, _MutationObserver_instances, updateResult_fn, notify_fn;
var MutationObserver = class extends Subscribable {
constructor(client, options) {
super();
__privateAdd(this, _MutationObserver_instances);
__privateAdd(this, _client);
__privateAdd(this, _currentResult);
__privateAdd(this, _currentMutation);
__privateAdd(this, _mutateOptions);
__privateSet(this, _client, client);
this.setOptions(options);
this.bindMethods();
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
}
bindMethods() {
this.mutate = this.mutate.bind(this);
this.reset = this.reset.bind(this);
}
setOptions(options) {
var _a;
const prevOptions = this.options;
this.options = __privateGet(this, _client).defaultMutationOptions(options);
if (!shallowEqualObjects(this.options, prevOptions)) {
__privateGet(this, _client).getMutationCache().notify({
type: "observerOptionsUpdated",
mutation: __privateGet(this, _currentMutation),
observer: this
});
}
if ((prevOptions == null ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
this.reset();
} else if (((_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.state.status) === "pending") {
__privateGet(this, _currentMutation).setOptions(this.options);
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
}
}
onMutationUpdate(action) {
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
__privateMethod(this, _MutationObserver_instances, notify_fn).call(this, action);
}
getCurrentResult() {
return __privateGet(this, _currentResult);
}
reset() {
var _a;
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
__privateSet(this, _currentMutation, void 0);
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
__privateMethod(this, _MutationObserver_instances, notify_fn).call(this);
}
mutate(variables, options) {
var _a;
__privateSet(this, _mutateOptions, options);
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
__privateSet(this, _currentMutation, __privateGet(this, _client).getMutationCache().build(__privateGet(this, _client), this.options));
__privateGet(this, _currentMutation).addObserver(this);
return __privateGet(this, _currentMutation).execute(variables);
}
};
_client = new WeakMap();
_currentResult = new WeakMap();
_currentMutation = new WeakMap();
_mutateOptions = new WeakMap();
_MutationObserver_instances = new WeakSet();
updateResult_fn = function() {
var _a;
const state = ((_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.state) ?? getDefaultState();
__privateSet(this, _currentResult, {
...state,
isPending: state.status === "pending",
isSuccess: state.status === "success",
isError: state.status === "error",
isIdle: state.status === "idle",
mutate: this.mutate,
reset: this.reset
});
};
notify_fn = function(action) {
notifyManager.batch(() => {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (__privateGet(this, _mutateOptions) && this.hasListeners()) {
const variables = __privateGet(this, _currentResult).variables;
const context = __privateGet(this, _currentResult).context;
if ((action == null ? void 0 : action.type) === "success") {
(_b = (_a = __privateGet(this, _mutateOptions)).onSuccess) == null ? void 0 : _b.call(_a, action.data, variables, context);
(_d = (_c = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _d.call(_c, action.data, null, variables, context);
} else if ((action == null ? void 0 : action.type) === "error") {
(_f = (_e = __privateGet(this, _mutateOptions)).onError) == null ? void 0 : _f.call(_e, action.error, variables, context);
(_h = (_g = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _h.call(
_g,
void 0,
action.error,
variables,
context
);
}
}
this.listeners.forEach((listener) => {
listener(__privateGet(this, _currentResult));
});
});
};
export {
MutationObserver
};
//# sourceMappingURL=mutationObserver.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,112 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/notifyManager.ts
var notifyManager_exports = {};
__export(notifyManager_exports, {
createNotifyManager: () => createNotifyManager,
defaultScheduler: () => defaultScheduler,
notifyManager: () => notifyManager
});
module.exports = __toCommonJS(notifyManager_exports);
var defaultScheduler = (cb) => setTimeout(cb, 0);
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 {
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);
});
};
},
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.
* By default React Query will use the batch function provided by ReactDOM or React Native.
*/
setBatchNotifyFunction: (fn) => {
batchNotifyFn = fn;
},
setScheduler: (fn) => {
scheduleFn = fn;
}
};
}
var notifyManager = createNotifyManager();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createNotifyManager,
defaultScheduler,
notifyManager
});
//# sourceMappingURL=notifyManager.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/notifyManager.ts"],"sourcesContent":["// TYPES\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\nexport const defaultScheduler: ScheduleFunction = (cb) => setTimeout(cb, 0)\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 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 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 * By default React Query will use the batch function provided by ReactDOM or React Native.\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\nexport const notifyManager = createNotifyManager()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYO,IAAM,mBAAqC,CAAC,OAAO,WAAW,IAAI,CAAC;AAEnE,SAAS,sBAAsB;AACpC,MAAI,QAA+B,CAAC;AACpC,MAAI,eAAe;AACnB,MAAI,WAA2B,CAAC,aAAa;AAC3C,aAAS;AAAA,EACX;AACA,MAAI,gBAAqC,CAAC,aAAyB;AACjE,aAAS;AAAA,EACX;AACA,MAAI,aAAa;AAEjB,QAAM,WAAW,CAAC,aAAmC;AACnD,QAAI,cAAc;AAChB,YAAM,KAAK,QAAQ;AAAA,IACrB,OAAO;AACL,iBAAW,MAAM;AACf,iBAAS,QAAQ;AAAA,MACnB,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,QAAQ,MAAY;AACxB,UAAM,gBAAgB;AACtB,YAAQ,CAAC;AACT,QAAI,cAAc,QAAQ;AACxB,iBAAW,MAAM;AACf,sBAAc,MAAM;AAClB,wBAAc,QAAQ,CAAC,aAAa;AAClC,qBAAS,QAAQ;AAAA,UACnB,CAAC;AAAA,QACH,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,CAAI,aAAyB;AAClC,UAAI;AACJ;AACA,UAAI;AACF,iBAAS,SAAS;AAAA,MACpB,UAAE;AACA;AACA,YAAI,CAAC,cAAc;AACjB,gBAAM;AAAA,QACR;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA,IAIA,YAAY,CACV,aAC0B;AAC1B,aAAO,IAAI,SAAS;AAClB,iBAAS,MAAM;AACb,mBAAS,GAAG,IAAI;AAAA,QAClB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,mBAAmB,CAAC,OAAuB;AACzC,iBAAW;AAAA,IACb;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,wBAAwB,CAAC,OAA4B;AACnD,sBAAgB;AAAA,IAClB;AAAA,IACA,cAAc,CAAC,OAAyB;AACtC,mBAAa;AAAA,IACf;AAAA,EACF;AACF;AAGO,IAAM,gBAAgB,oBAAoB;","names":[]}

View File

@@ -0,0 +1,46 @@
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;
declare const defaultScheduler: ScheduleFunction;
declare function createNotifyManager(): {
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>;
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.
* By default React Query will use the batch function provided by ReactDOM or React Native.
*/
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
readonly setScheduler: (fn: ScheduleFunction) => void;
};
declare const notifyManager: {
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>;
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.
* By default React Query will use the batch function provided by ReactDOM or React Native.
*/
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
readonly setScheduler: (fn: ScheduleFunction) => void;
};
export { createNotifyManager, defaultScheduler, notifyManager };

View File

@@ -0,0 +1,46 @@
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;
declare const defaultScheduler: ScheduleFunction;
declare function createNotifyManager(): {
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>;
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.
* By default React Query will use the batch function provided by ReactDOM or React Native.
*/
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
readonly setScheduler: (fn: ScheduleFunction) => void;
};
declare const notifyManager: {
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>;
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.
* By default React Query will use the batch function provided by ReactDOM or React Native.
*/
readonly setBatchNotifyFunction: (fn: BatchNotifyFunction) => void;
readonly setScheduler: (fn: ScheduleFunction) => void;
};
export { createNotifyManager, defaultScheduler, notifyManager };

View File

@@ -0,0 +1,87 @@
import "./chunk-PXG64RU4.js";
// src/notifyManager.ts
var defaultScheduler = (cb) => setTimeout(cb, 0);
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 {
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);
});
};
},
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.
* By default React Query will use the batch function provided by ReactDOM or React Native.
*/
setBatchNotifyFunction: (fn) => {
batchNotifyFn = fn;
},
setScheduler: (fn) => {
scheduleFn = fn;
}
};
}
var notifyManager = createNotifyManager();
export {
createNotifyManager,
defaultScheduler,
notifyManager
};
//# sourceMappingURL=notifyManager.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/notifyManager.ts"],"sourcesContent":["// TYPES\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\nexport const defaultScheduler: ScheduleFunction = (cb) => setTimeout(cb, 0)\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 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 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 * By default React Query will use the batch function provided by ReactDOM or React Native.\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\nexport const notifyManager = createNotifyManager()\n"],"mappings":";;;AAYO,IAAM,mBAAqC,CAAC,OAAO,WAAW,IAAI,CAAC;AAEnE,SAAS,sBAAsB;AACpC,MAAI,QAA+B,CAAC;AACpC,MAAI,eAAe;AACnB,MAAI,WAA2B,CAAC,aAAa;AAC3C,aAAS;AAAA,EACX;AACA,MAAI,gBAAqC,CAAC,aAAyB;AACjE,aAAS;AAAA,EACX;AACA,MAAI,aAAa;AAEjB,QAAM,WAAW,CAAC,aAAmC;AACnD,QAAI,cAAc;AAChB,YAAM,KAAK,QAAQ;AAAA,IACrB,OAAO;AACL,iBAAW,MAAM;AACf,iBAAS,QAAQ;AAAA,MACnB,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,QAAQ,MAAY;AACxB,UAAM,gBAAgB;AACtB,YAAQ,CAAC;AACT,QAAI,cAAc,QAAQ;AACxB,iBAAW,MAAM;AACf,sBAAc,MAAM;AAClB,wBAAc,QAAQ,CAAC,aAAa;AAClC,qBAAS,QAAQ;AAAA,UACnB,CAAC;AAAA,QACH,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,CAAI,aAAyB;AAClC,UAAI;AACJ;AACA,UAAI;AACF,iBAAS,SAAS;AAAA,MACpB,UAAE;AACA;AACA,YAAI,CAAC,cAAc;AACjB,gBAAM;AAAA,QACR;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA,IAIA,YAAY,CACV,aAC0B;AAC1B,aAAO,IAAI,SAAS;AAClB,iBAAS,MAAM;AACb,mBAAS,GAAG,IAAI;AAAA,QAClB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,mBAAmB,CAAC,OAAuB;AACzC,iBAAW;AAAA,IACb;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,wBAAwB,CAAC,OAA4B;AACnD,sBAAgB;AAAA,IAClB;AAAA,IACA,cAAc,CAAC,OAAyB;AACtC,mBAAa;AAAA,IACf;AAAA,EACF;AACF;AAGO,IAAM,gBAAgB,oBAAoB;","names":[]}

View File

@@ -0,0 +1,97 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
// src/onlineManager.ts
var onlineManager_exports = {};
__export(onlineManager_exports, {
OnlineManager: () => OnlineManager,
onlineManager: () => onlineManager
});
module.exports = __toCommonJS(onlineManager_exports);
var import_subscribable = require("./subscribable.cjs");
var import_utils = require("./utils.cjs");
var _online, _cleanup, _setup;
var OnlineManager = class extends import_subscribable.Subscribable {
constructor() {
super();
__privateAdd(this, _online, true);
__privateAdd(this, _cleanup);
__privateAdd(this, _setup);
__privateSet(this, _setup, (onOnline) => {
if (!import_utils.isServer && 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);
};
}
return;
});
}
onSubscribe() {
if (!__privateGet(this, _cleanup)) {
this.setEventListener(__privateGet(this, _setup));
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, void 0);
}
}
setEventListener(setup) {
var _a;
__privateSet(this, _setup, setup);
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, setup(this.setOnline.bind(this)));
}
setOnline(online) {
const changed = __privateGet(this, _online) !== online;
if (changed) {
__privateSet(this, _online, online);
this.listeners.forEach((listener) => {
listener(online);
});
}
}
isOnline() {
return __privateGet(this, _online);
}
};
_online = new WeakMap();
_cleanup = new WeakMap();
_setup = new WeakMap();
var onlineManager = new OnlineManager();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
OnlineManager,
onlineManager
});
//# sourceMappingURL=onlineManager.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\nimport { isServer } from './utils'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\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 (!isServer && 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 setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\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 isOnline(): boolean {\n return this.#online\n }\n}\n\nexport const onlineManager = new OnlineManager()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAA6B;AAC7B,mBAAyB;AADzB;AAMO,IAAM,gBAAN,cAA4B,iCAAuB;AAAA,EAMxD,cAAc;AACZ,UAAM;AANR,gCAAU;AACV;AAEA;AAIE,uBAAK,QAAS,CAAC,aAAa;AAG1B,UAAI,CAAC,yBAAY,OAAO,kBAAkB;AACxC,cAAM,iBAAiB,MAAM,SAAS,IAAI;AAC1C,cAAM,kBAAkB,MAAM,SAAS,KAAK;AAE5C,eAAO,iBAAiB,UAAU,gBAAgB,KAAK;AACvD,eAAO,iBAAiB,WAAW,iBAAiB,KAAK;AAEzD,eAAO,MAAM;AAEX,iBAAO,oBAAoB,UAAU,cAAc;AACnD,iBAAO,oBAAoB,WAAW,eAAe;AAAA,QACvD;AAAA,MACF;AAEA;AAAA,IACF;AAAA,EACF;AAAA,EAEU,cAAoB;AAC5B,QAAI,CAAC,mBAAK,WAAU;AAClB,WAAK,iBAAiB,mBAAK,OAAM;AAAA,IACnC;AAAA,EACF;AAAA,EAEU,gBAAgB;AAzC5B;AA0CI,QAAI,CAAC,KAAK,aAAa,GAAG;AACxB,+BAAK,cAAL;AACA,yBAAK,UAAW;AAAA,IAClB;AAAA,EACF;AAAA,EAEA,iBAAiB,OAAsB;AAhDzC;AAiDI,uBAAK,QAAS;AACd,6BAAK,cAAL;AACA,uBAAK,UAAW,MAAM,KAAK,UAAU,KAAK,IAAI,CAAC;AAAA,EACjD;AAAA,EAEA,UAAU,QAAuB;AAC/B,UAAM,UAAU,mBAAK,aAAY;AAEjC,QAAI,SAAS;AACX,yBAAK,SAAU;AACf,WAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,iBAAS,MAAM;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,WAAoB;AAClB,WAAO,mBAAK;AAAA,EACd;AACF;AA7DE;AACA;AAEA;AA4DK,IAAM,gBAAgB,IAAI,cAAc;","names":[]}

View File

@@ -0,0 +1,16 @@
import { Subscribable } from './subscribable.cjs';
type Listener = (online: boolean) => void;
type SetupFn = (setOnline: Listener) => (() => void) | undefined;
declare class OnlineManager extends Subscribable<Listener> {
#private;
constructor();
protected onSubscribe(): void;
protected onUnsubscribe(): void;
setEventListener(setup: SetupFn): void;
setOnline(online: boolean): void;
isOnline(): boolean;
}
declare const onlineManager: OnlineManager;
export { OnlineManager, onlineManager };

View File

@@ -0,0 +1,16 @@
import { Subscribable } from './subscribable.js';
type Listener = (online: boolean) => void;
type SetupFn = (setOnline: Listener) => (() => void) | undefined;
declare class OnlineManager extends Subscribable<Listener> {
#private;
constructor();
protected onSubscribe(): void;
protected onUnsubscribe(): void;
setEventListener(setup: SetupFn): void;
setOnline(online: boolean): void;
isOnline(): boolean;
}
declare const onlineManager: OnlineManager;
export { OnlineManager, onlineManager };

View File

@@ -0,0 +1,70 @@
import {
__privateAdd,
__privateGet,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/onlineManager.ts
import { Subscribable } from "./subscribable.js";
import { isServer } from "./utils.js";
var _online, _cleanup, _setup;
var OnlineManager = class extends Subscribable {
constructor() {
super();
__privateAdd(this, _online, true);
__privateAdd(this, _cleanup);
__privateAdd(this, _setup);
__privateSet(this, _setup, (onOnline) => {
if (!isServer && 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);
};
}
return;
});
}
onSubscribe() {
if (!__privateGet(this, _cleanup)) {
this.setEventListener(__privateGet(this, _setup));
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, void 0);
}
}
setEventListener(setup) {
var _a;
__privateSet(this, _setup, setup);
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, setup(this.setOnline.bind(this)));
}
setOnline(online) {
const changed = __privateGet(this, _online) !== online;
if (changed) {
__privateSet(this, _online, online);
this.listeners.forEach((listener) => {
listener(online);
});
}
}
isOnline() {
return __privateGet(this, _online);
}
};
_online = new WeakMap();
_cleanup = new WeakMap();
_setup = new WeakMap();
var onlineManager = new OnlineManager();
export {
OnlineManager,
onlineManager
};
//# sourceMappingURL=onlineManager.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\nimport { isServer } from './utils'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\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 (!isServer && 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 setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\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 isOnline(): boolean {\n return this.#online\n }\n}\n\nexport const onlineManager = new OnlineManager()\n"],"mappings":";;;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AADzB;AAMO,IAAM,gBAAN,cAA4B,aAAuB;AAAA,EAMxD,cAAc;AACZ,UAAM;AANR,gCAAU;AACV;AAEA;AAIE,uBAAK,QAAS,CAAC,aAAa;AAG1B,UAAI,CAAC,YAAY,OAAO,kBAAkB;AACxC,cAAM,iBAAiB,MAAM,SAAS,IAAI;AAC1C,cAAM,kBAAkB,MAAM,SAAS,KAAK;AAE5C,eAAO,iBAAiB,UAAU,gBAAgB,KAAK;AACvD,eAAO,iBAAiB,WAAW,iBAAiB,KAAK;AAEzD,eAAO,MAAM;AAEX,iBAAO,oBAAoB,UAAU,cAAc;AACnD,iBAAO,oBAAoB,WAAW,eAAe;AAAA,QACvD;AAAA,MACF;AAEA;AAAA,IACF;AAAA,EACF;AAAA,EAEU,cAAoB;AAC5B,QAAI,CAAC,mBAAK,WAAU;AAClB,WAAK,iBAAiB,mBAAK,OAAM;AAAA,IACnC;AAAA,EACF;AAAA,EAEU,gBAAgB;AAzC5B;AA0CI,QAAI,CAAC,KAAK,aAAa,GAAG;AACxB,+BAAK,cAAL;AACA,yBAAK,UAAW;AAAA,IAClB;AAAA,EACF;AAAA,EAEA,iBAAiB,OAAsB;AAhDzC;AAiDI,uBAAK,QAAS;AACd,6BAAK,cAAL;AACA,uBAAK,UAAW,MAAM,KAAK,UAAU,KAAK,IAAI,CAAC;AAAA,EACjD;AAAA,EAEA,UAAU,QAAuB;AAC/B,UAAM,UAAU,mBAAK,aAAY;AAEjC,QAAI,SAAS;AACX,yBAAK,SAAU;AACf,WAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,iBAAS,MAAM;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,WAAoB;AAClB,WAAO,mBAAK;AAAA,EACd;AACF;AA7DE;AACA;AAEA;AA4DK,IAAM,gBAAgB,IAAI,cAAc;","names":[]}

View File

@@ -0,0 +1,241 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// src/queriesObserver.ts
var queriesObserver_exports = {};
__export(queriesObserver_exports, {
QueriesObserver: () => QueriesObserver
});
module.exports = __toCommonJS(queriesObserver_exports);
var import_notifyManager = require("./notifyManager.cjs");
var import_queryObserver = require("./queryObserver.cjs");
var import_subscribable = require("./subscribable.cjs");
var import_utils = require("./utils.cjs");
function difference(array1, array2) {
const excludeSet = new Set(array2);
return array1.filter((x) => !excludeSet.has(x));
}
function replaceAt(array, index, value) {
const copy = array.slice(0);
copy[index] = value;
return copy;
}
var _client, _result, _queries, _options, _observers, _combinedResult, _lastCombine, _lastResult, _observerMatches, _QueriesObserver_instances, trackResult_fn, combineResult_fn, findMatchingObservers_fn, onUpdate_fn, notify_fn;
var QueriesObserver = class extends import_subscribable.Subscribable {
constructor(client, queries, options) {
super();
__privateAdd(this, _QueriesObserver_instances);
__privateAdd(this, _client);
__privateAdd(this, _result);
__privateAdd(this, _queries);
__privateAdd(this, _options);
__privateAdd(this, _observers);
__privateAdd(this, _combinedResult);
__privateAdd(this, _lastCombine);
__privateAdd(this, _lastResult);
__privateAdd(this, _observerMatches, []);
__privateSet(this, _client, client);
__privateSet(this, _options, options);
__privateSet(this, _queries, []);
__privateSet(this, _observers, []);
__privateSet(this, _result, []);
this.setQueries(queries);
}
onSubscribe() {
if (this.listeners.size === 1) {
__privateGet(this, _observers).forEach((observer) => {
observer.subscribe((result) => {
__privateMethod(this, _QueriesObserver_instances, onUpdate_fn).call(this, observer, result);
});
});
}
}
onUnsubscribe() {
if (!this.listeners.size) {
this.destroy();
}
}
destroy() {
this.listeners = /* @__PURE__ */ new Set();
__privateGet(this, _observers).forEach((observer) => {
observer.destroy();
});
}
setQueries(queries, options) {
__privateSet(this, _queries, queries);
__privateSet(this, _options, options);
if (process.env.NODE_ENV !== "production") {
const queryHashes = queries.map(
(query) => __privateGet(this, _client).defaultQueryOptions(query).queryHash
);
if (new Set(queryHashes).size !== queryHashes.length) {
console.warn(
"[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior."
);
}
}
import_notifyManager.notifyManager.batch(() => {
const prevObservers = __privateGet(this, _observers);
const newObserverMatches = __privateMethod(this, _QueriesObserver_instances, findMatchingObservers_fn).call(this, __privateGet(this, _queries));
__privateSet(this, _observerMatches, newObserverMatches);
newObserverMatches.forEach(
(match) => match.observer.setOptions(match.defaultedQueryOptions)
);
const newObservers = newObserverMatches.map((match) => match.observer);
const newResult = newObservers.map(
(observer) => observer.getCurrentResult()
);
const hasIndexChange = newObservers.some(
(observer, index) => observer !== prevObservers[index]
);
if (prevObservers.length === newObservers.length && !hasIndexChange) {
return;
}
__privateSet(this, _observers, newObservers);
__privateSet(this, _result, newResult);
if (!this.hasListeners()) {
return;
}
difference(prevObservers, newObservers).forEach((observer) => {
observer.destroy();
});
difference(newObservers, prevObservers).forEach((observer) => {
observer.subscribe((result) => {
__privateMethod(this, _QueriesObserver_instances, onUpdate_fn).call(this, observer, result);
});
});
__privateMethod(this, _QueriesObserver_instances, notify_fn).call(this);
});
}
getCurrentResult() {
return __privateGet(this, _result);
}
getQueries() {
return __privateGet(this, _observers).map((observer) => observer.getCurrentQuery());
}
getObservers() {
return __privateGet(this, _observers);
}
getOptimisticResult(queries, combine) {
const matches = __privateMethod(this, _QueriesObserver_instances, findMatchingObservers_fn).call(this, queries);
const result = matches.map(
(match) => match.observer.getOptimisticResult(match.defaultedQueryOptions)
);
return [
result,
(r) => {
return __privateMethod(this, _QueriesObserver_instances, combineResult_fn).call(this, r ?? result, combine);
},
() => {
return __privateMethod(this, _QueriesObserver_instances, trackResult_fn).call(this, result, matches);
}
];
}
};
_client = new WeakMap();
_result = new WeakMap();
_queries = new WeakMap();
_options = new WeakMap();
_observers = new WeakMap();
_combinedResult = new WeakMap();
_lastCombine = new WeakMap();
_lastResult = new WeakMap();
_observerMatches = new WeakMap();
_QueriesObserver_instances = new WeakSet();
trackResult_fn = function(result, matches) {
return matches.map((match, index) => {
const observerResult = result[index];
return !match.defaultedQueryOptions.notifyOnChangeProps ? match.observer.trackResult(observerResult, (accessedProp) => {
matches.forEach((m) => {
m.observer.trackProp(accessedProp);
});
}) : observerResult;
});
};
combineResult_fn = function(input, combine) {
if (combine) {
if (!__privateGet(this, _combinedResult) || __privateGet(this, _result) !== __privateGet(this, _lastResult) || combine !== __privateGet(this, _lastCombine)) {
__privateSet(this, _lastCombine, combine);
__privateSet(this, _lastResult, __privateGet(this, _result));
__privateSet(this, _combinedResult, (0, import_utils.replaceEqualDeep)(
__privateGet(this, _combinedResult),
combine(input)
));
}
return __privateGet(this, _combinedResult);
}
return input;
};
findMatchingObservers_fn = function(queries) {
const prevObserversMap = new Map(
__privateGet(this, _observers).map((observer) => [observer.options.queryHash, observer])
);
const observers = [];
queries.forEach((options) => {
const defaultedOptions = __privateGet(this, _client).defaultQueryOptions(options);
const match = prevObserversMap.get(defaultedOptions.queryHash);
if (match) {
observers.push({
defaultedQueryOptions: defaultedOptions,
observer: match
});
} else {
observers.push({
defaultedQueryOptions: defaultedOptions,
observer: new import_queryObserver.QueryObserver(__privateGet(this, _client), defaultedOptions)
});
}
});
return observers;
};
onUpdate_fn = function(observer, result) {
const index = __privateGet(this, _observers).indexOf(observer);
if (index !== -1) {
__privateSet(this, _result, replaceAt(__privateGet(this, _result), index, result));
__privateMethod(this, _QueriesObserver_instances, notify_fn).call(this);
}
};
notify_fn = function() {
var _a;
if (this.hasListeners()) {
const previousResult = __privateGet(this, _combinedResult);
const newTracked = __privateMethod(this, _QueriesObserver_instances, trackResult_fn).call(this, __privateGet(this, _result), __privateGet(this, _observerMatches));
const newResult = __privateMethod(this, _QueriesObserver_instances, combineResult_fn).call(this, newTracked, (_a = __privateGet(this, _options)) == null ? void 0 : _a.combine);
if (previousResult !== newResult) {
import_notifyManager.notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(__privateGet(this, _result));
});
});
}
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QueriesObserver
});
//# sourceMappingURL=queriesObserver.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import { aH as QueryObserverResult, b as QueryClient, ag as QueryObserverOptions, x as Query, c as QueryObserver } from './hydration-CdBkFt9i.cjs';
import { Subscribable } from './subscribable.cjs';
import './removable.cjs';
type QueriesObserverListener = (result: Array<QueryObserverResult>) => void;
type CombineFn<TCombinedResult> = (result: Array<QueryObserverResult>) => TCombinedResult;
interface QueriesObserverOptions<TCombinedResult = Array<QueryObserverResult>> {
combine?: CombineFn<TCombinedResult>;
}
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;
destroy(): void;
setQueries(queries: Array<QueryObserverOptions>, options?: QueriesObserverOptions<TCombinedResult>): void;
getCurrentResult(): Array<QueryObserverResult>;
getQueries(): Query<unknown, Error, unknown, readonly unknown[]>[];
getObservers(): QueryObserver<unknown, Error, unknown, unknown, readonly unknown[]>[];
getOptimisticResult(queries: Array<QueryObserverOptions>, combine: CombineFn<TCombinedResult> | undefined): [
rawResult: Array<QueryObserverResult>,
combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,
trackResult: () => Array<QueryObserverResult>
];
}
export { QueriesObserver, type QueriesObserverOptions };

View File

@@ -0,0 +1,27 @@
import { aH as QueryObserverResult, b as QueryClient, ag as QueryObserverOptions, x as Query, c as QueryObserver } from './hydration-Cr-4Kky1.js';
import { Subscribable } from './subscribable.js';
import './removable.js';
type QueriesObserverListener = (result: Array<QueryObserverResult>) => void;
type CombineFn<TCombinedResult> = (result: Array<QueryObserverResult>) => TCombinedResult;
interface QueriesObserverOptions<TCombinedResult = Array<QueryObserverResult>> {
combine?: CombineFn<TCombinedResult>;
}
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;
destroy(): void;
setQueries(queries: Array<QueryObserverOptions>, options?: QueriesObserverOptions<TCombinedResult>): void;
getCurrentResult(): Array<QueryObserverResult>;
getQueries(): Query<unknown, Error, unknown, readonly unknown[]>[];
getObservers(): QueryObserver<unknown, Error, unknown, unknown, readonly unknown[]>[];
getOptimisticResult(queries: Array<QueryObserverOptions>, combine: CombineFn<TCombinedResult> | undefined): [
rawResult: Array<QueryObserverResult>,
combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,
trackResult: () => Array<QueryObserverResult>
];
}
export { QueriesObserver, type QueriesObserverOptions };

View File

@@ -0,0 +1,215 @@
import {
__privateAdd,
__privateGet,
__privateMethod,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/queriesObserver.ts
import { notifyManager } from "./notifyManager.js";
import { QueryObserver } from "./queryObserver.js";
import { Subscribable } from "./subscribable.js";
import { replaceEqualDeep } from "./utils.js";
function difference(array1, array2) {
const excludeSet = new Set(array2);
return array1.filter((x) => !excludeSet.has(x));
}
function replaceAt(array, index, value) {
const copy = array.slice(0);
copy[index] = value;
return copy;
}
var _client, _result, _queries, _options, _observers, _combinedResult, _lastCombine, _lastResult, _observerMatches, _QueriesObserver_instances, trackResult_fn, combineResult_fn, findMatchingObservers_fn, onUpdate_fn, notify_fn;
var QueriesObserver = class extends Subscribable {
constructor(client, queries, options) {
super();
__privateAdd(this, _QueriesObserver_instances);
__privateAdd(this, _client);
__privateAdd(this, _result);
__privateAdd(this, _queries);
__privateAdd(this, _options);
__privateAdd(this, _observers);
__privateAdd(this, _combinedResult);
__privateAdd(this, _lastCombine);
__privateAdd(this, _lastResult);
__privateAdd(this, _observerMatches, []);
__privateSet(this, _client, client);
__privateSet(this, _options, options);
__privateSet(this, _queries, []);
__privateSet(this, _observers, []);
__privateSet(this, _result, []);
this.setQueries(queries);
}
onSubscribe() {
if (this.listeners.size === 1) {
__privateGet(this, _observers).forEach((observer) => {
observer.subscribe((result) => {
__privateMethod(this, _QueriesObserver_instances, onUpdate_fn).call(this, observer, result);
});
});
}
}
onUnsubscribe() {
if (!this.listeners.size) {
this.destroy();
}
}
destroy() {
this.listeners = /* @__PURE__ */ new Set();
__privateGet(this, _observers).forEach((observer) => {
observer.destroy();
});
}
setQueries(queries, options) {
__privateSet(this, _queries, queries);
__privateSet(this, _options, options);
if (process.env.NODE_ENV !== "production") {
const queryHashes = queries.map(
(query) => __privateGet(this, _client).defaultQueryOptions(query).queryHash
);
if (new Set(queryHashes).size !== queryHashes.length) {
console.warn(
"[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior."
);
}
}
notifyManager.batch(() => {
const prevObservers = __privateGet(this, _observers);
const newObserverMatches = __privateMethod(this, _QueriesObserver_instances, findMatchingObservers_fn).call(this, __privateGet(this, _queries));
__privateSet(this, _observerMatches, newObserverMatches);
newObserverMatches.forEach(
(match) => match.observer.setOptions(match.defaultedQueryOptions)
);
const newObservers = newObserverMatches.map((match) => match.observer);
const newResult = newObservers.map(
(observer) => observer.getCurrentResult()
);
const hasIndexChange = newObservers.some(
(observer, index) => observer !== prevObservers[index]
);
if (prevObservers.length === newObservers.length && !hasIndexChange) {
return;
}
__privateSet(this, _observers, newObservers);
__privateSet(this, _result, newResult);
if (!this.hasListeners()) {
return;
}
difference(prevObservers, newObservers).forEach((observer) => {
observer.destroy();
});
difference(newObservers, prevObservers).forEach((observer) => {
observer.subscribe((result) => {
__privateMethod(this, _QueriesObserver_instances, onUpdate_fn).call(this, observer, result);
});
});
__privateMethod(this, _QueriesObserver_instances, notify_fn).call(this);
});
}
getCurrentResult() {
return __privateGet(this, _result);
}
getQueries() {
return __privateGet(this, _observers).map((observer) => observer.getCurrentQuery());
}
getObservers() {
return __privateGet(this, _observers);
}
getOptimisticResult(queries, combine) {
const matches = __privateMethod(this, _QueriesObserver_instances, findMatchingObservers_fn).call(this, queries);
const result = matches.map(
(match) => match.observer.getOptimisticResult(match.defaultedQueryOptions)
);
return [
result,
(r) => {
return __privateMethod(this, _QueriesObserver_instances, combineResult_fn).call(this, r ?? result, combine);
},
() => {
return __privateMethod(this, _QueriesObserver_instances, trackResult_fn).call(this, result, matches);
}
];
}
};
_client = new WeakMap();
_result = new WeakMap();
_queries = new WeakMap();
_options = new WeakMap();
_observers = new WeakMap();
_combinedResult = new WeakMap();
_lastCombine = new WeakMap();
_lastResult = new WeakMap();
_observerMatches = new WeakMap();
_QueriesObserver_instances = new WeakSet();
trackResult_fn = function(result, matches) {
return matches.map((match, index) => {
const observerResult = result[index];
return !match.defaultedQueryOptions.notifyOnChangeProps ? match.observer.trackResult(observerResult, (accessedProp) => {
matches.forEach((m) => {
m.observer.trackProp(accessedProp);
});
}) : observerResult;
});
};
combineResult_fn = function(input, combine) {
if (combine) {
if (!__privateGet(this, _combinedResult) || __privateGet(this, _result) !== __privateGet(this, _lastResult) || combine !== __privateGet(this, _lastCombine)) {
__privateSet(this, _lastCombine, combine);
__privateSet(this, _lastResult, __privateGet(this, _result));
__privateSet(this, _combinedResult, replaceEqualDeep(
__privateGet(this, _combinedResult),
combine(input)
));
}
return __privateGet(this, _combinedResult);
}
return input;
};
findMatchingObservers_fn = function(queries) {
const prevObserversMap = new Map(
__privateGet(this, _observers).map((observer) => [observer.options.queryHash, observer])
);
const observers = [];
queries.forEach((options) => {
const defaultedOptions = __privateGet(this, _client).defaultQueryOptions(options);
const match = prevObserversMap.get(defaultedOptions.queryHash);
if (match) {
observers.push({
defaultedQueryOptions: defaultedOptions,
observer: match
});
} else {
observers.push({
defaultedQueryOptions: defaultedOptions,
observer: new QueryObserver(__privateGet(this, _client), defaultedOptions)
});
}
});
return observers;
};
onUpdate_fn = function(observer, result) {
const index = __privateGet(this, _observers).indexOf(observer);
if (index !== -1) {
__privateSet(this, _result, replaceAt(__privateGet(this, _result), index, result));
__privateMethod(this, _QueriesObserver_instances, notify_fn).call(this);
}
};
notify_fn = function() {
var _a;
if (this.hasListeners()) {
const previousResult = __privateGet(this, _combinedResult);
const newTracked = __privateMethod(this, _QueriesObserver_instances, trackResult_fn).call(this, __privateGet(this, _result), __privateGet(this, _observerMatches));
const newResult = __privateMethod(this, _QueriesObserver_instances, combineResult_fn).call(this, newTracked, (_a = __privateGet(this, _options)) == null ? void 0 : _a.combine);
if (previousResult !== newResult) {
notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(__privateGet(this, _result));
});
});
}
}
};
export {
QueriesObserver
};
//# sourceMappingURL=queriesObserver.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,454 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// src/query.ts
var query_exports = {};
__export(query_exports, {
Query: () => Query,
fetchState: () => fetchState
});
module.exports = __toCommonJS(query_exports);
var import_utils = require("./utils.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_retryer = require("./retryer.cjs");
var import_removable = require("./removable.cjs");
var _initialState, _revertState, _cache, _client, _retryer, _defaultOptions, _abortSignalConsumed, _Query_instances, dispatch_fn;
var Query = class extends import_removable.Removable {
constructor(config) {
super();
__privateAdd(this, _Query_instances);
__privateAdd(this, _initialState);
__privateAdd(this, _revertState);
__privateAdd(this, _cache);
__privateAdd(this, _client);
__privateAdd(this, _retryer);
__privateAdd(this, _defaultOptions);
__privateAdd(this, _abortSignalConsumed);
__privateSet(this, _abortSignalConsumed, false);
__privateSet(this, _defaultOptions, config.defaultOptions);
this.setOptions(config.options);
this.observers = [];
__privateSet(this, _client, config.client);
__privateSet(this, _cache, __privateGet(this, _client).getQueryCache());
this.queryKey = config.queryKey;
this.queryHash = config.queryHash;
__privateSet(this, _initialState, getDefaultState(this.options));
this.state = config.state ?? __privateGet(this, _initialState);
this.scheduleGc();
}
get meta() {
return this.options.meta;
}
get promise() {
var _a;
return (_a = __privateGet(this, _retryer)) == null ? void 0 : _a.promise;
}
setOptions(options) {
this.options = { ...__privateGet(this, _defaultOptions), ...options };
this.updateGcTime(this.options.gcTime);
}
optionalRemove() {
if (!this.observers.length && this.state.fetchStatus === "idle") {
__privateGet(this, _cache).remove(this);
}
}
setData(newData, options) {
const data = (0, import_utils.replaceData)(this.state.data, newData, this.options);
__privateMethod(this, _Query_instances, dispatch_fn).call(this, {
data,
type: "success",
dataUpdatedAt: options == null ? void 0 : options.updatedAt,
manual: options == null ? void 0 : options.manual
});
return data;
}
setState(state, setStateOptions) {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "setState", state, setStateOptions });
}
cancel(options) {
var _a, _b;
const promise = (_a = __privateGet(this, _retryer)) == null ? void 0 : _a.promise;
(_b = __privateGet(this, _retryer)) == null ? void 0 : _b.cancel(options);
return promise ? promise.then(import_utils.noop).catch(import_utils.noop) : Promise.resolve();
}
destroy() {
super.destroy();
this.cancel({ silent: true });
}
reset() {
this.destroy();
this.setState(__privateGet(this, _initialState));
}
isActive() {
return this.observers.some(
(observer) => (0, import_utils.resolveEnabled)(observer.options.enabled, this) !== false
);
}
isDisabled() {
if (this.getObserversCount() > 0) {
return !this.isActive();
}
return this.options.queryFn === import_utils.skipToken || this.state.dataUpdateCount + this.state.errorUpdateCount === 0;
}
isStatic() {
if (this.getObserversCount() > 0) {
return this.observers.some(
(observer) => (0, import_utils.resolveStaleTime)(observer.options.staleTime, this) === "static"
);
}
return false;
}
isStale() {
if (this.getObserversCount() > 0) {
return this.observers.some(
(observer) => observer.getCurrentResult().isStale
);
}
return this.state.data === void 0 || this.state.isInvalidated;
}
isStaleByTime(staleTime = 0) {
if (this.state.data === void 0) {
return true;
}
if (staleTime === "static") {
return false;
}
if (this.state.isInvalidated) {
return true;
}
return !(0, import_utils.timeUntilStale)(this.state.dataUpdatedAt, staleTime);
}
onFocus() {
var _a;
const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());
observer == null ? void 0 : observer.refetch({ cancelRefetch: false });
(_a = __privateGet(this, _retryer)) == null ? void 0 : _a.continue();
}
onOnline() {
var _a;
const observer = this.observers.find((x) => x.shouldFetchOnReconnect());
observer == null ? void 0 : observer.refetch({ cancelRefetch: false });
(_a = __privateGet(this, _retryer)) == null ? void 0 : _a.continue();
}
addObserver(observer) {
if (!this.observers.includes(observer)) {
this.observers.push(observer);
this.clearGcTimeout();
__privateGet(this, _cache).notify({ type: "observerAdded", query: this, observer });
}
}
removeObserver(observer) {
if (this.observers.includes(observer)) {
this.observers = this.observers.filter((x) => x !== observer);
if (!this.observers.length) {
if (__privateGet(this, _retryer)) {
if (__privateGet(this, _abortSignalConsumed)) {
__privateGet(this, _retryer).cancel({ revert: true });
} else {
__privateGet(this, _retryer).cancelRetry();
}
}
this.scheduleGc();
}
__privateGet(this, _cache).notify({ type: "observerRemoved", query: this, observer });
}
}
getObserversCount() {
return this.observers.length;
}
invalidate() {
if (!this.state.isInvalidated) {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "invalidate" });
}
}
fetch(options, fetchOptions) {
var _a, _b, _c;
if (this.state.fetchStatus !== "idle") {
if (this.state.data !== void 0 && (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch)) {
this.cancel({ silent: true });
} else if (__privateGet(this, _retryer)) {
__privateGet(this, _retryer).continueRetry();
return __privateGet(this, _retryer).promise;
}
}
if (options) {
this.setOptions(options);
}
if (!this.options.queryFn) {
const observer = this.observers.find((x) => x.options.queryFn);
if (observer) {
this.setOptions(observer.options);
}
}
if (process.env.NODE_ENV !== "production") {
if (!Array.isArray(this.options.queryKey)) {
console.error(
`As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`
);
}
}
const abortController = new AbortController();
const addSignalProperty = (object) => {
Object.defineProperty(object, "signal", {
enumerable: true,
get: () => {
__privateSet(this, _abortSignalConsumed, true);
return abortController.signal;
}
});
};
const fetchFn = () => {
const queryFn = (0, import_utils.ensureQueryFn)(this.options, fetchOptions);
const createQueryFnContext = () => {
const queryFnContext2 = {
client: __privateGet(this, _client),
queryKey: this.queryKey,
meta: this.meta
};
addSignalProperty(queryFnContext2);
return queryFnContext2;
};
const queryFnContext = createQueryFnContext();
__privateSet(this, _abortSignalConsumed, false);
if (this.options.persister) {
return this.options.persister(
queryFn,
queryFnContext,
this
);
}
return queryFn(queryFnContext);
};
const createFetchContext = () => {
const context2 = {
fetchOptions,
options: this.options,
queryKey: this.queryKey,
client: __privateGet(this, _client),
state: this.state,
fetchFn
};
addSignalProperty(context2);
return context2;
};
const context = createFetchContext();
(_a = this.options.behavior) == null ? void 0 : _a.onFetch(context, this);
__privateSet(this, _revertState, this.state);
if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== ((_b = context.fetchOptions) == null ? void 0 : _b.meta)) {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "fetch", meta: (_c = context.fetchOptions) == null ? void 0 : _c.meta });
}
const onError = (error) => {
var _a2, _b2, _c2, _d;
if (!((0, import_retryer.isCancelledError)(error) && error.silent)) {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, {
type: "error",
error
});
}
if (!(0, import_retryer.isCancelledError)(error)) {
(_b2 = (_a2 = __privateGet(this, _cache).config).onError) == null ? void 0 : _b2.call(
_a2,
error,
this
);
(_d = (_c2 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _d.call(
_c2,
this.state.data,
error,
this
);
}
this.scheduleGc();
};
__privateSet(this, _retryer, (0, import_retryer.createRetryer)({
initialPromise: fetchOptions == null ? void 0 : fetchOptions.initialPromise,
fn: context.fetchFn,
abort: abortController.abort.bind(abortController),
onSuccess: (data) => {
var _a2, _b2, _c2, _d;
if (data === void 0) {
if (process.env.NODE_ENV !== "production") {
console.error(
`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`
);
}
onError(new Error(`${this.queryHash} data is undefined`));
return;
}
try {
this.setData(data);
} catch (error) {
onError(error);
return;
}
(_b2 = (_a2 = __privateGet(this, _cache).config).onSuccess) == null ? void 0 : _b2.call(_a2, data, this);
(_d = (_c2 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _d.call(
_c2,
data,
this.state.error,
this
);
this.scheduleGc();
},
onError,
onFail: (failureCount, error) => {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "failed", failureCount, error });
},
onPause: () => {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "pause" });
},
onContinue: () => {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "continue" });
},
retry: context.options.retry,
retryDelay: context.options.retryDelay,
networkMode: context.options.networkMode,
canRun: () => true
}));
return __privateGet(this, _retryer).start();
}
};
_initialState = new WeakMap();
_revertState = new WeakMap();
_cache = new WeakMap();
_client = new WeakMap();
_retryer = new WeakMap();
_defaultOptions = new WeakMap();
_abortSignalConsumed = new WeakMap();
_Query_instances = new WeakSet();
dispatch_fn = function(action) {
const reducer = (state) => {
switch (action.type) {
case "failed":
return {
...state,
fetchFailureCount: action.failureCount,
fetchFailureReason: action.error
};
case "pause":
return {
...state,
fetchStatus: "paused"
};
case "continue":
return {
...state,
fetchStatus: "fetching"
};
case "fetch":
return {
...state,
...fetchState(state.data, this.options),
fetchMeta: action.meta ?? null
};
case "success":
__privateSet(this, _revertState, void 0);
return {
...state,
data: action.data,
dataUpdateCount: state.dataUpdateCount + 1,
dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
error: null,
isInvalidated: false,
status: "success",
...!action.manual && {
fetchStatus: "idle",
fetchFailureCount: 0,
fetchFailureReason: null
}
};
case "error":
const error = action.error;
if ((0, import_retryer.isCancelledError)(error) && error.revert && __privateGet(this, _revertState)) {
return { ...__privateGet(this, _revertState), fetchStatus: "idle" };
}
return {
...state,
error,
errorUpdateCount: state.errorUpdateCount + 1,
errorUpdatedAt: Date.now(),
fetchFailureCount: state.fetchFailureCount + 1,
fetchFailureReason: error,
fetchStatus: "idle",
status: "error"
};
case "invalidate":
return {
...state,
isInvalidated: true
};
case "setState":
return {
...state,
...action.state
};
}
};
this.state = reducer(this.state);
import_notifyManager.notifyManager.batch(() => {
this.observers.forEach((observer) => {
observer.onQueryUpdate();
});
__privateGet(this, _cache).notify({ query: this, type: "updated", action });
});
};
function fetchState(data, options) {
return {
fetchFailureCount: 0,
fetchFailureReason: null,
fetchStatus: (0, import_retryer.canFetch)(options.networkMode) ? "fetching" : "paused",
...data === void 0 && {
error: null,
status: "pending"
}
};
}
function getDefaultState(options) {
const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
const hasData = data !== void 0;
const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
return {
data,
dataUpdateCount: 0,
dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
error: null,
errorUpdateCount: 0,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: hasData ? "success" : "pending",
fetchStatus: "idle"
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Query,
fetchState
});
//# sourceMappingURL=query.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
import './removable.cjs';
export { bf as Action, bb as FetchContext, bc as FetchDirection, bd as FetchMeta, be as FetchOptions, x as Query, ba as QueryBehavior, w as QueryState, bg as SetStateOptions, bh as fetchState } from './hydration-CdBkFt9i.cjs';
import './subscribable.cjs';

View File

@@ -0,0 +1,3 @@
import './removable.js';
export { bf as Action, bb as FetchContext, bc as FetchDirection, bd as FetchMeta, be as FetchOptions, x as Query, ba as QueryBehavior, w as QueryState, bg as SetStateOptions, bh as fetchState } from './hydration-Cr-4Kky1.js';
import './subscribable.js';

View File

@@ -0,0 +1,435 @@
import {
__privateAdd,
__privateGet,
__privateMethod,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/query.ts
import {
ensureQueryFn,
noop,
replaceData,
resolveEnabled,
resolveStaleTime,
skipToken,
timeUntilStale
} from "./utils.js";
import { notifyManager } from "./notifyManager.js";
import { canFetch, createRetryer, isCancelledError } from "./retryer.js";
import { Removable } from "./removable.js";
var _initialState, _revertState, _cache, _client, _retryer, _defaultOptions, _abortSignalConsumed, _Query_instances, dispatch_fn;
var Query = class extends Removable {
constructor(config) {
super();
__privateAdd(this, _Query_instances);
__privateAdd(this, _initialState);
__privateAdd(this, _revertState);
__privateAdd(this, _cache);
__privateAdd(this, _client);
__privateAdd(this, _retryer);
__privateAdd(this, _defaultOptions);
__privateAdd(this, _abortSignalConsumed);
__privateSet(this, _abortSignalConsumed, false);
__privateSet(this, _defaultOptions, config.defaultOptions);
this.setOptions(config.options);
this.observers = [];
__privateSet(this, _client, config.client);
__privateSet(this, _cache, __privateGet(this, _client).getQueryCache());
this.queryKey = config.queryKey;
this.queryHash = config.queryHash;
__privateSet(this, _initialState, getDefaultState(this.options));
this.state = config.state ?? __privateGet(this, _initialState);
this.scheduleGc();
}
get meta() {
return this.options.meta;
}
get promise() {
var _a;
return (_a = __privateGet(this, _retryer)) == null ? void 0 : _a.promise;
}
setOptions(options) {
this.options = { ...__privateGet(this, _defaultOptions), ...options };
this.updateGcTime(this.options.gcTime);
}
optionalRemove() {
if (!this.observers.length && this.state.fetchStatus === "idle") {
__privateGet(this, _cache).remove(this);
}
}
setData(newData, options) {
const data = replaceData(this.state.data, newData, this.options);
__privateMethod(this, _Query_instances, dispatch_fn).call(this, {
data,
type: "success",
dataUpdatedAt: options == null ? void 0 : options.updatedAt,
manual: options == null ? void 0 : options.manual
});
return data;
}
setState(state, setStateOptions) {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "setState", state, setStateOptions });
}
cancel(options) {
var _a, _b;
const promise = (_a = __privateGet(this, _retryer)) == null ? void 0 : _a.promise;
(_b = __privateGet(this, _retryer)) == null ? void 0 : _b.cancel(options);
return promise ? promise.then(noop).catch(noop) : Promise.resolve();
}
destroy() {
super.destroy();
this.cancel({ silent: true });
}
reset() {
this.destroy();
this.setState(__privateGet(this, _initialState));
}
isActive() {
return this.observers.some(
(observer) => resolveEnabled(observer.options.enabled, this) !== false
);
}
isDisabled() {
if (this.getObserversCount() > 0) {
return !this.isActive();
}
return this.options.queryFn === skipToken || this.state.dataUpdateCount + this.state.errorUpdateCount === 0;
}
isStatic() {
if (this.getObserversCount() > 0) {
return this.observers.some(
(observer) => resolveStaleTime(observer.options.staleTime, this) === "static"
);
}
return false;
}
isStale() {
if (this.getObserversCount() > 0) {
return this.observers.some(
(observer) => observer.getCurrentResult().isStale
);
}
return this.state.data === void 0 || this.state.isInvalidated;
}
isStaleByTime(staleTime = 0) {
if (this.state.data === void 0) {
return true;
}
if (staleTime === "static") {
return false;
}
if (this.state.isInvalidated) {
return true;
}
return !timeUntilStale(this.state.dataUpdatedAt, staleTime);
}
onFocus() {
var _a;
const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());
observer == null ? void 0 : observer.refetch({ cancelRefetch: false });
(_a = __privateGet(this, _retryer)) == null ? void 0 : _a.continue();
}
onOnline() {
var _a;
const observer = this.observers.find((x) => x.shouldFetchOnReconnect());
observer == null ? void 0 : observer.refetch({ cancelRefetch: false });
(_a = __privateGet(this, _retryer)) == null ? void 0 : _a.continue();
}
addObserver(observer) {
if (!this.observers.includes(observer)) {
this.observers.push(observer);
this.clearGcTimeout();
__privateGet(this, _cache).notify({ type: "observerAdded", query: this, observer });
}
}
removeObserver(observer) {
if (this.observers.includes(observer)) {
this.observers = this.observers.filter((x) => x !== observer);
if (!this.observers.length) {
if (__privateGet(this, _retryer)) {
if (__privateGet(this, _abortSignalConsumed)) {
__privateGet(this, _retryer).cancel({ revert: true });
} else {
__privateGet(this, _retryer).cancelRetry();
}
}
this.scheduleGc();
}
__privateGet(this, _cache).notify({ type: "observerRemoved", query: this, observer });
}
}
getObserversCount() {
return this.observers.length;
}
invalidate() {
if (!this.state.isInvalidated) {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "invalidate" });
}
}
fetch(options, fetchOptions) {
var _a, _b, _c;
if (this.state.fetchStatus !== "idle") {
if (this.state.data !== void 0 && (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch)) {
this.cancel({ silent: true });
} else if (__privateGet(this, _retryer)) {
__privateGet(this, _retryer).continueRetry();
return __privateGet(this, _retryer).promise;
}
}
if (options) {
this.setOptions(options);
}
if (!this.options.queryFn) {
const observer = this.observers.find((x) => x.options.queryFn);
if (observer) {
this.setOptions(observer.options);
}
}
if (process.env.NODE_ENV !== "production") {
if (!Array.isArray(this.options.queryKey)) {
console.error(
`As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`
);
}
}
const abortController = new AbortController();
const addSignalProperty = (object) => {
Object.defineProperty(object, "signal", {
enumerable: true,
get: () => {
__privateSet(this, _abortSignalConsumed, true);
return abortController.signal;
}
});
};
const fetchFn = () => {
const queryFn = ensureQueryFn(this.options, fetchOptions);
const createQueryFnContext = () => {
const queryFnContext2 = {
client: __privateGet(this, _client),
queryKey: this.queryKey,
meta: this.meta
};
addSignalProperty(queryFnContext2);
return queryFnContext2;
};
const queryFnContext = createQueryFnContext();
__privateSet(this, _abortSignalConsumed, false);
if (this.options.persister) {
return this.options.persister(
queryFn,
queryFnContext,
this
);
}
return queryFn(queryFnContext);
};
const createFetchContext = () => {
const context2 = {
fetchOptions,
options: this.options,
queryKey: this.queryKey,
client: __privateGet(this, _client),
state: this.state,
fetchFn
};
addSignalProperty(context2);
return context2;
};
const context = createFetchContext();
(_a = this.options.behavior) == null ? void 0 : _a.onFetch(context, this);
__privateSet(this, _revertState, this.state);
if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== ((_b = context.fetchOptions) == null ? void 0 : _b.meta)) {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "fetch", meta: (_c = context.fetchOptions) == null ? void 0 : _c.meta });
}
const onError = (error) => {
var _a2, _b2, _c2, _d;
if (!(isCancelledError(error) && error.silent)) {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, {
type: "error",
error
});
}
if (!isCancelledError(error)) {
(_b2 = (_a2 = __privateGet(this, _cache).config).onError) == null ? void 0 : _b2.call(
_a2,
error,
this
);
(_d = (_c2 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _d.call(
_c2,
this.state.data,
error,
this
);
}
this.scheduleGc();
};
__privateSet(this, _retryer, createRetryer({
initialPromise: fetchOptions == null ? void 0 : fetchOptions.initialPromise,
fn: context.fetchFn,
abort: abortController.abort.bind(abortController),
onSuccess: (data) => {
var _a2, _b2, _c2, _d;
if (data === void 0) {
if (process.env.NODE_ENV !== "production") {
console.error(
`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`
);
}
onError(new Error(`${this.queryHash} data is undefined`));
return;
}
try {
this.setData(data);
} catch (error) {
onError(error);
return;
}
(_b2 = (_a2 = __privateGet(this, _cache).config).onSuccess) == null ? void 0 : _b2.call(_a2, data, this);
(_d = (_c2 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _d.call(
_c2,
data,
this.state.error,
this
);
this.scheduleGc();
},
onError,
onFail: (failureCount, error) => {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "failed", failureCount, error });
},
onPause: () => {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "pause" });
},
onContinue: () => {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "continue" });
},
retry: context.options.retry,
retryDelay: context.options.retryDelay,
networkMode: context.options.networkMode,
canRun: () => true
}));
return __privateGet(this, _retryer).start();
}
};
_initialState = new WeakMap();
_revertState = new WeakMap();
_cache = new WeakMap();
_client = new WeakMap();
_retryer = new WeakMap();
_defaultOptions = new WeakMap();
_abortSignalConsumed = new WeakMap();
_Query_instances = new WeakSet();
dispatch_fn = function(action) {
const reducer = (state) => {
switch (action.type) {
case "failed":
return {
...state,
fetchFailureCount: action.failureCount,
fetchFailureReason: action.error
};
case "pause":
return {
...state,
fetchStatus: "paused"
};
case "continue":
return {
...state,
fetchStatus: "fetching"
};
case "fetch":
return {
...state,
...fetchState(state.data, this.options),
fetchMeta: action.meta ?? null
};
case "success":
__privateSet(this, _revertState, void 0);
return {
...state,
data: action.data,
dataUpdateCount: state.dataUpdateCount + 1,
dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
error: null,
isInvalidated: false,
status: "success",
...!action.manual && {
fetchStatus: "idle",
fetchFailureCount: 0,
fetchFailureReason: null
}
};
case "error":
const error = action.error;
if (isCancelledError(error) && error.revert && __privateGet(this, _revertState)) {
return { ...__privateGet(this, _revertState), fetchStatus: "idle" };
}
return {
...state,
error,
errorUpdateCount: state.errorUpdateCount + 1,
errorUpdatedAt: Date.now(),
fetchFailureCount: state.fetchFailureCount + 1,
fetchFailureReason: error,
fetchStatus: "idle",
status: "error"
};
case "invalidate":
return {
...state,
isInvalidated: true
};
case "setState":
return {
...state,
...action.state
};
}
};
this.state = reducer(this.state);
notifyManager.batch(() => {
this.observers.forEach((observer) => {
observer.onQueryUpdate();
});
__privateGet(this, _cache).notify({ query: this, type: "updated", action });
});
};
function fetchState(data, options) {
return {
fetchFailureCount: 0,
fetchFailureReason: null,
fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused",
...data === void 0 && {
error: null,
status: "pending"
}
};
}
function getDefaultState(options) {
const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
const hasData = data !== void 0;
const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
return {
data,
dataUpdateCount: 0,
dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
error: null,
errorUpdateCount: 0,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: hasData ? "success" : "pending",
fetchStatus: "idle"
};
}
export {
Query,
fetchState
};
//# sourceMappingURL=query.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,131 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
// src/queryCache.ts
var queryCache_exports = {};
__export(queryCache_exports, {
QueryCache: () => QueryCache
});
module.exports = __toCommonJS(queryCache_exports);
var import_utils = require("./utils.cjs");
var import_query = require("./query.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_subscribable = require("./subscribable.cjs");
var _queries;
var QueryCache = class extends import_subscribable.Subscribable {
constructor(config = {}) {
super();
this.config = config;
__privateAdd(this, _queries);
__privateSet(this, _queries, /* @__PURE__ */ new Map());
}
build(client, options, state) {
const queryKey = options.queryKey;
const queryHash = options.queryHash ?? (0, import_utils.hashQueryKeyByOptions)(queryKey, options);
let query = this.get(queryHash);
if (!query) {
query = new import_query.Query({
client,
queryKey,
queryHash,
options: client.defaultQueryOptions(options),
state,
defaultOptions: client.getQueryDefaults(queryKey)
});
this.add(query);
}
return query;
}
add(query) {
if (!__privateGet(this, _queries).has(query.queryHash)) {
__privateGet(this, _queries).set(query.queryHash, query);
this.notify({
type: "added",
query
});
}
}
remove(query) {
const queryInMap = __privateGet(this, _queries).get(query.queryHash);
if (queryInMap) {
query.destroy();
if (queryInMap === query) {
__privateGet(this, _queries).delete(query.queryHash);
}
this.notify({ type: "removed", query });
}
}
clear() {
import_notifyManager.notifyManager.batch(() => {
this.getAll().forEach((query) => {
this.remove(query);
});
});
}
get(queryHash) {
return __privateGet(this, _queries).get(queryHash);
}
getAll() {
return [...__privateGet(this, _queries).values()];
}
find(filters) {
const defaultedFilters = { exact: true, ...filters };
return this.getAll().find(
(query) => (0, import_utils.matchQuery)(defaultedFilters, query)
);
}
findAll(filters = {}) {
const queries = this.getAll();
return Object.keys(filters).length > 0 ? queries.filter((query) => (0, import_utils.matchQuery)(filters, query)) : queries;
}
notify(event) {
import_notifyManager.notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(event);
});
});
}
onFocus() {
import_notifyManager.notifyManager.batch(() => {
this.getAll().forEach((query) => {
query.onFocus();
});
});
}
onOnline() {
import_notifyManager.notifyManager.batch(() => {
this.getAll().forEach((query) => {
query.onOnline();
});
});
}
};
_queries = new WeakMap();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QueryCache
});
//# sourceMappingURL=queryCache.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export { Q as QueryCache, a as QueryCacheNotifyEvent, bz as QueryStore } from './hydration-CdBkFt9i.cjs';
import './subscribable.cjs';
import './removable.cjs';

View File

@@ -0,0 +1,3 @@
export { Q as QueryCache, a as QueryCacheNotifyEvent, bz as QueryStore } from './hydration-Cr-4Kky1.js';
import './subscribable.js';
import './removable.js';

View File

@@ -0,0 +1,105 @@
import {
__privateAdd,
__privateGet,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/queryCache.ts
import { hashQueryKeyByOptions, matchQuery } from "./utils.js";
import { Query } from "./query.js";
import { notifyManager } from "./notifyManager.js";
import { Subscribable } from "./subscribable.js";
var _queries;
var QueryCache = class extends Subscribable {
constructor(config = {}) {
super();
this.config = config;
__privateAdd(this, _queries);
__privateSet(this, _queries, /* @__PURE__ */ new Map());
}
build(client, options, state) {
const queryKey = options.queryKey;
const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
let query = this.get(queryHash);
if (!query) {
query = new Query({
client,
queryKey,
queryHash,
options: client.defaultQueryOptions(options),
state,
defaultOptions: client.getQueryDefaults(queryKey)
});
this.add(query);
}
return query;
}
add(query) {
if (!__privateGet(this, _queries).has(query.queryHash)) {
__privateGet(this, _queries).set(query.queryHash, query);
this.notify({
type: "added",
query
});
}
}
remove(query) {
const queryInMap = __privateGet(this, _queries).get(query.queryHash);
if (queryInMap) {
query.destroy();
if (queryInMap === query) {
__privateGet(this, _queries).delete(query.queryHash);
}
this.notify({ type: "removed", query });
}
}
clear() {
notifyManager.batch(() => {
this.getAll().forEach((query) => {
this.remove(query);
});
});
}
get(queryHash) {
return __privateGet(this, _queries).get(queryHash);
}
getAll() {
return [...__privateGet(this, _queries).values()];
}
find(filters) {
const defaultedFilters = { exact: true, ...filters };
return this.getAll().find(
(query) => matchQuery(defaultedFilters, query)
);
}
findAll(filters = {}) {
const queries = this.getAll();
return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
}
notify(event) {
notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(event);
});
});
}
onFocus() {
notifyManager.batch(() => {
this.getAll().forEach((query) => {
query.onFocus();
});
});
}
onOnline() {
notifyManager.batch(() => {
this.getAll().forEach((query) => {
query.onOnline();
});
});
}
};
_queries = new WeakMap();
export {
QueryCache
};
//# sourceMappingURL=queryCache.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,349 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateWrapper = (obj, member, setter, getter) => ({
set _(value) {
__privateSet(obj, member, value, setter);
},
get _() {
return __privateGet(obj, member, getter);
}
});
// src/queryClient.ts
var queryClient_exports = {};
__export(queryClient_exports, {
QueryClient: () => QueryClient
});
module.exports = __toCommonJS(queryClient_exports);
var import_utils = require("./utils.cjs");
var import_queryCache = require("./queryCache.cjs");
var import_mutationCache = require("./mutationCache.cjs");
var import_focusManager = require("./focusManager.cjs");
var import_onlineManager = require("./onlineManager.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs");
var _queryCache, _mutationCache, _defaultOptions, _queryDefaults, _mutationDefaults, _mountCount, _unsubscribeFocus, _unsubscribeOnline;
var QueryClient = class {
constructor(config = {}) {
__privateAdd(this, _queryCache);
__privateAdd(this, _mutationCache);
__privateAdd(this, _defaultOptions);
__privateAdd(this, _queryDefaults);
__privateAdd(this, _mutationDefaults);
__privateAdd(this, _mountCount);
__privateAdd(this, _unsubscribeFocus);
__privateAdd(this, _unsubscribeOnline);
__privateSet(this, _queryCache, config.queryCache || new import_queryCache.QueryCache());
__privateSet(this, _mutationCache, config.mutationCache || new import_mutationCache.MutationCache());
__privateSet(this, _defaultOptions, config.defaultOptions || {});
__privateSet(this, _queryDefaults, /* @__PURE__ */ new Map());
__privateSet(this, _mutationDefaults, /* @__PURE__ */ new Map());
__privateSet(this, _mountCount, 0);
}
mount() {
__privateWrapper(this, _mountCount)._++;
if (__privateGet(this, _mountCount) !== 1) return;
__privateSet(this, _unsubscribeFocus, import_focusManager.focusManager.subscribe(async (focused) => {
if (focused) {
await this.resumePausedMutations();
__privateGet(this, _queryCache).onFocus();
}
}));
__privateSet(this, _unsubscribeOnline, import_onlineManager.onlineManager.subscribe(async (online) => {
if (online) {
await this.resumePausedMutations();
__privateGet(this, _queryCache).onOnline();
}
}));
}
unmount() {
var _a, _b;
__privateWrapper(this, _mountCount)._--;
if (__privateGet(this, _mountCount) !== 0) return;
(_a = __privateGet(this, _unsubscribeFocus)) == null ? void 0 : _a.call(this);
__privateSet(this, _unsubscribeFocus, void 0);
(_b = __privateGet(this, _unsubscribeOnline)) == null ? void 0 : _b.call(this);
__privateSet(this, _unsubscribeOnline, void 0);
}
isFetching(filters) {
return __privateGet(this, _queryCache).findAll({ ...filters, fetchStatus: "fetching" }).length;
}
isMutating(filters) {
return __privateGet(this, _mutationCache).findAll({ ...filters, status: "pending" }).length;
}
/**
* Imperative (non-reactive) way to retrieve data for a QueryKey.
* Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.
*
* Hint: Do not use this function inside a component, because it won't receive updates.
* Use `useQuery` to create a `QueryObserver` that subscribes to changes.
*/
getQueryData(queryKey) {
var _a;
const options = this.defaultQueryOptions({ queryKey });
return (_a = __privateGet(this, _queryCache).get(options.queryHash)) == null ? void 0 : _a.state.data;
}
ensureQueryData(options) {
const defaultedOptions = this.defaultQueryOptions(options);
const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
const cachedData = query.state.data;
if (cachedData === void 0) {
return this.fetchQuery(options);
}
if (options.revalidateIfStale && query.isStaleByTime((0, import_utils.resolveStaleTime)(defaultedOptions.staleTime, query))) {
void this.prefetchQuery(defaultedOptions);
}
return Promise.resolve(cachedData);
}
getQueriesData(filters) {
return __privateGet(this, _queryCache).findAll(filters).map(({ queryKey, state }) => {
const data = state.data;
return [queryKey, data];
});
}
setQueryData(queryKey, updater, options) {
const defaultedOptions = this.defaultQueryOptions({ queryKey });
const query = __privateGet(this, _queryCache).get(
defaultedOptions.queryHash
);
const prevData = query == null ? void 0 : query.state.data;
const data = (0, import_utils.functionalUpdate)(updater, prevData);
if (data === void 0) {
return void 0;
}
return __privateGet(this, _queryCache).build(this, defaultedOptions).setData(data, { ...options, manual: true });
}
setQueriesData(filters, updater, options) {
return import_notifyManager.notifyManager.batch(
() => __privateGet(this, _queryCache).findAll(filters).map(({ queryKey }) => [
queryKey,
this.setQueryData(queryKey, updater, options)
])
);
}
getQueryState(queryKey) {
var _a;
const options = this.defaultQueryOptions({ queryKey });
return (_a = __privateGet(this, _queryCache).get(
options.queryHash
)) == null ? void 0 : _a.state;
}
removeQueries(filters) {
const queryCache = __privateGet(this, _queryCache);
import_notifyManager.notifyManager.batch(() => {
queryCache.findAll(filters).forEach((query) => {
queryCache.remove(query);
});
});
}
resetQueries(filters, options) {
const queryCache = __privateGet(this, _queryCache);
return import_notifyManager.notifyManager.batch(() => {
queryCache.findAll(filters).forEach((query) => {
query.reset();
});
return this.refetchQueries(
{
type: "active",
...filters
},
options
);
});
}
cancelQueries(filters, cancelOptions = {}) {
const defaultedCancelOptions = { revert: true, ...cancelOptions };
const promises = import_notifyManager.notifyManager.batch(
() => __privateGet(this, _queryCache).findAll(filters).map((query) => query.cancel(defaultedCancelOptions))
);
return Promise.all(promises).then(import_utils.noop).catch(import_utils.noop);
}
invalidateQueries(filters, options = {}) {
return import_notifyManager.notifyManager.batch(() => {
__privateGet(this, _queryCache).findAll(filters).forEach((query) => {
query.invalidate();
});
if ((filters == null ? void 0 : filters.refetchType) === "none") {
return Promise.resolve();
}
return this.refetchQueries(
{
...filters,
type: (filters == null ? void 0 : filters.refetchType) ?? (filters == null ? void 0 : filters.type) ?? "active"
},
options
);
});
}
refetchQueries(filters, options = {}) {
const fetchOptions = {
...options,
cancelRefetch: options.cancelRefetch ?? true
};
const promises = import_notifyManager.notifyManager.batch(
() => __privateGet(this, _queryCache).findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {
let promise = query.fetch(void 0, fetchOptions);
if (!fetchOptions.throwOnError) {
promise = promise.catch(import_utils.noop);
}
return query.state.fetchStatus === "paused" ? Promise.resolve() : promise;
})
);
return Promise.all(promises).then(import_utils.noop);
}
fetchQuery(options) {
const defaultedOptions = this.defaultQueryOptions(options);
if (defaultedOptions.retry === void 0) {
defaultedOptions.retry = false;
}
const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
return query.isStaleByTime(
(0, import_utils.resolveStaleTime)(defaultedOptions.staleTime, query)
) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
}
prefetchQuery(options) {
return this.fetchQuery(options).then(import_utils.noop).catch(import_utils.noop);
}
fetchInfiniteQuery(options) {
options.behavior = (0, import_infiniteQueryBehavior.infiniteQueryBehavior)(options.pages);
return this.fetchQuery(options);
}
prefetchInfiniteQuery(options) {
return this.fetchInfiniteQuery(options).then(import_utils.noop).catch(import_utils.noop);
}
ensureInfiniteQueryData(options) {
options.behavior = (0, import_infiniteQueryBehavior.infiniteQueryBehavior)(options.pages);
return this.ensureQueryData(options);
}
resumePausedMutations() {
if (import_onlineManager.onlineManager.isOnline()) {
return __privateGet(this, _mutationCache).resumePausedMutations();
}
return Promise.resolve();
}
getQueryCache() {
return __privateGet(this, _queryCache);
}
getMutationCache() {
return __privateGet(this, _mutationCache);
}
getDefaultOptions() {
return __privateGet(this, _defaultOptions);
}
setDefaultOptions(options) {
__privateSet(this, _defaultOptions, options);
}
setQueryDefaults(queryKey, options) {
__privateGet(this, _queryDefaults).set((0, import_utils.hashKey)(queryKey), {
queryKey,
defaultOptions: options
});
}
getQueryDefaults(queryKey) {
const defaults = [...__privateGet(this, _queryDefaults).values()];
const result = {};
defaults.forEach((queryDefault) => {
if ((0, import_utils.partialMatchKey)(queryKey, queryDefault.queryKey)) {
Object.assign(result, queryDefault.defaultOptions);
}
});
return result;
}
setMutationDefaults(mutationKey, options) {
__privateGet(this, _mutationDefaults).set((0, import_utils.hashKey)(mutationKey), {
mutationKey,
defaultOptions: options
});
}
getMutationDefaults(mutationKey) {
const defaults = [...__privateGet(this, _mutationDefaults).values()];
const result = {};
defaults.forEach((queryDefault) => {
if ((0, import_utils.partialMatchKey)(mutationKey, queryDefault.mutationKey)) {
Object.assign(result, queryDefault.defaultOptions);
}
});
return result;
}
defaultQueryOptions(options) {
if (options._defaulted) {
return options;
}
const defaultedOptions = {
...__privateGet(this, _defaultOptions).queries,
...this.getQueryDefaults(options.queryKey),
...options,
_defaulted: true
};
if (!defaultedOptions.queryHash) {
defaultedOptions.queryHash = (0, import_utils.hashQueryKeyByOptions)(
defaultedOptions.queryKey,
defaultedOptions
);
}
if (defaultedOptions.refetchOnReconnect === void 0) {
defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
}
if (defaultedOptions.throwOnError === void 0) {
defaultedOptions.throwOnError = !!defaultedOptions.suspense;
}
if (!defaultedOptions.networkMode && defaultedOptions.persister) {
defaultedOptions.networkMode = "offlineFirst";
}
if (defaultedOptions.queryFn === import_utils.skipToken) {
defaultedOptions.enabled = false;
}
return defaultedOptions;
}
defaultMutationOptions(options) {
if (options == null ? void 0 : options._defaulted) {
return options;
}
return {
...__privateGet(this, _defaultOptions).mutations,
...(options == null ? void 0 : options.mutationKey) && this.getMutationDefaults(options.mutationKey),
...options,
_defaulted: true
};
}
clear() {
__privateGet(this, _queryCache).clear();
__privateGet(this, _mutationCache).clear();
}
};
_queryCache = new WeakMap();
_mutationCache = new WeakMap();
_defaultOptions = new WeakMap();
_queryDefaults = new WeakMap();
_mutationDefaults = new WeakMap();
_mountCount = new WeakMap();
_unsubscribeFocus = new WeakMap();
_unsubscribeOnline = new WeakMap();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QueryClient
});
//# sourceMappingURL=queryClient.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export { b as QueryClient } from './hydration-CdBkFt9i.cjs';
import './removable.cjs';
import './subscribable.cjs';

View File

@@ -0,0 +1,3 @@
export { b as QueryClient } from './hydration-Cr-4Kky1.js';
import './removable.js';
import './subscribable.js';

View File

@@ -0,0 +1,324 @@
import {
__privateAdd,
__privateGet,
__privateSet,
__privateWrapper
} from "./chunk-PXG64RU4.js";
// src/queryClient.ts
import {
functionalUpdate,
hashKey,
hashQueryKeyByOptions,
noop,
partialMatchKey,
resolveStaleTime,
skipToken
} from "./utils.js";
import { QueryCache } from "./queryCache.js";
import { MutationCache } from "./mutationCache.js";
import { focusManager } from "./focusManager.js";
import { onlineManager } from "./onlineManager.js";
import { notifyManager } from "./notifyManager.js";
import { infiniteQueryBehavior } from "./infiniteQueryBehavior.js";
var _queryCache, _mutationCache, _defaultOptions, _queryDefaults, _mutationDefaults, _mountCount, _unsubscribeFocus, _unsubscribeOnline;
var QueryClient = class {
constructor(config = {}) {
__privateAdd(this, _queryCache);
__privateAdd(this, _mutationCache);
__privateAdd(this, _defaultOptions);
__privateAdd(this, _queryDefaults);
__privateAdd(this, _mutationDefaults);
__privateAdd(this, _mountCount);
__privateAdd(this, _unsubscribeFocus);
__privateAdd(this, _unsubscribeOnline);
__privateSet(this, _queryCache, config.queryCache || new QueryCache());
__privateSet(this, _mutationCache, config.mutationCache || new MutationCache());
__privateSet(this, _defaultOptions, config.defaultOptions || {});
__privateSet(this, _queryDefaults, /* @__PURE__ */ new Map());
__privateSet(this, _mutationDefaults, /* @__PURE__ */ new Map());
__privateSet(this, _mountCount, 0);
}
mount() {
__privateWrapper(this, _mountCount)._++;
if (__privateGet(this, _mountCount) !== 1) return;
__privateSet(this, _unsubscribeFocus, focusManager.subscribe(async (focused) => {
if (focused) {
await this.resumePausedMutations();
__privateGet(this, _queryCache).onFocus();
}
}));
__privateSet(this, _unsubscribeOnline, onlineManager.subscribe(async (online) => {
if (online) {
await this.resumePausedMutations();
__privateGet(this, _queryCache).onOnline();
}
}));
}
unmount() {
var _a, _b;
__privateWrapper(this, _mountCount)._--;
if (__privateGet(this, _mountCount) !== 0) return;
(_a = __privateGet(this, _unsubscribeFocus)) == null ? void 0 : _a.call(this);
__privateSet(this, _unsubscribeFocus, void 0);
(_b = __privateGet(this, _unsubscribeOnline)) == null ? void 0 : _b.call(this);
__privateSet(this, _unsubscribeOnline, void 0);
}
isFetching(filters) {
return __privateGet(this, _queryCache).findAll({ ...filters, fetchStatus: "fetching" }).length;
}
isMutating(filters) {
return __privateGet(this, _mutationCache).findAll({ ...filters, status: "pending" }).length;
}
/**
* Imperative (non-reactive) way to retrieve data for a QueryKey.
* Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.
*
* Hint: Do not use this function inside a component, because it won't receive updates.
* Use `useQuery` to create a `QueryObserver` that subscribes to changes.
*/
getQueryData(queryKey) {
var _a;
const options = this.defaultQueryOptions({ queryKey });
return (_a = __privateGet(this, _queryCache).get(options.queryHash)) == null ? void 0 : _a.state.data;
}
ensureQueryData(options) {
const defaultedOptions = this.defaultQueryOptions(options);
const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
const cachedData = query.state.data;
if (cachedData === void 0) {
return this.fetchQuery(options);
}
if (options.revalidateIfStale && query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query))) {
void this.prefetchQuery(defaultedOptions);
}
return Promise.resolve(cachedData);
}
getQueriesData(filters) {
return __privateGet(this, _queryCache).findAll(filters).map(({ queryKey, state }) => {
const data = state.data;
return [queryKey, data];
});
}
setQueryData(queryKey, updater, options) {
const defaultedOptions = this.defaultQueryOptions({ queryKey });
const query = __privateGet(this, _queryCache).get(
defaultedOptions.queryHash
);
const prevData = query == null ? void 0 : query.state.data;
const data = functionalUpdate(updater, prevData);
if (data === void 0) {
return void 0;
}
return __privateGet(this, _queryCache).build(this, defaultedOptions).setData(data, { ...options, manual: true });
}
setQueriesData(filters, updater, options) {
return notifyManager.batch(
() => __privateGet(this, _queryCache).findAll(filters).map(({ queryKey }) => [
queryKey,
this.setQueryData(queryKey, updater, options)
])
);
}
getQueryState(queryKey) {
var _a;
const options = this.defaultQueryOptions({ queryKey });
return (_a = __privateGet(this, _queryCache).get(
options.queryHash
)) == null ? void 0 : _a.state;
}
removeQueries(filters) {
const queryCache = __privateGet(this, _queryCache);
notifyManager.batch(() => {
queryCache.findAll(filters).forEach((query) => {
queryCache.remove(query);
});
});
}
resetQueries(filters, options) {
const queryCache = __privateGet(this, _queryCache);
return notifyManager.batch(() => {
queryCache.findAll(filters).forEach((query) => {
query.reset();
});
return this.refetchQueries(
{
type: "active",
...filters
},
options
);
});
}
cancelQueries(filters, cancelOptions = {}) {
const defaultedCancelOptions = { revert: true, ...cancelOptions };
const promises = notifyManager.batch(
() => __privateGet(this, _queryCache).findAll(filters).map((query) => query.cancel(defaultedCancelOptions))
);
return Promise.all(promises).then(noop).catch(noop);
}
invalidateQueries(filters, options = {}) {
return notifyManager.batch(() => {
__privateGet(this, _queryCache).findAll(filters).forEach((query) => {
query.invalidate();
});
if ((filters == null ? void 0 : filters.refetchType) === "none") {
return Promise.resolve();
}
return this.refetchQueries(
{
...filters,
type: (filters == null ? void 0 : filters.refetchType) ?? (filters == null ? void 0 : filters.type) ?? "active"
},
options
);
});
}
refetchQueries(filters, options = {}) {
const fetchOptions = {
...options,
cancelRefetch: options.cancelRefetch ?? true
};
const promises = notifyManager.batch(
() => __privateGet(this, _queryCache).findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {
let promise = query.fetch(void 0, fetchOptions);
if (!fetchOptions.throwOnError) {
promise = promise.catch(noop);
}
return query.state.fetchStatus === "paused" ? Promise.resolve() : promise;
})
);
return Promise.all(promises).then(noop);
}
fetchQuery(options) {
const defaultedOptions = this.defaultQueryOptions(options);
if (defaultedOptions.retry === void 0) {
defaultedOptions.retry = false;
}
const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
return query.isStaleByTime(
resolveStaleTime(defaultedOptions.staleTime, query)
) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
}
prefetchQuery(options) {
return this.fetchQuery(options).then(noop).catch(noop);
}
fetchInfiniteQuery(options) {
options.behavior = infiniteQueryBehavior(options.pages);
return this.fetchQuery(options);
}
prefetchInfiniteQuery(options) {
return this.fetchInfiniteQuery(options).then(noop).catch(noop);
}
ensureInfiniteQueryData(options) {
options.behavior = infiniteQueryBehavior(options.pages);
return this.ensureQueryData(options);
}
resumePausedMutations() {
if (onlineManager.isOnline()) {
return __privateGet(this, _mutationCache).resumePausedMutations();
}
return Promise.resolve();
}
getQueryCache() {
return __privateGet(this, _queryCache);
}
getMutationCache() {
return __privateGet(this, _mutationCache);
}
getDefaultOptions() {
return __privateGet(this, _defaultOptions);
}
setDefaultOptions(options) {
__privateSet(this, _defaultOptions, options);
}
setQueryDefaults(queryKey, options) {
__privateGet(this, _queryDefaults).set(hashKey(queryKey), {
queryKey,
defaultOptions: options
});
}
getQueryDefaults(queryKey) {
const defaults = [...__privateGet(this, _queryDefaults).values()];
const result = {};
defaults.forEach((queryDefault) => {
if (partialMatchKey(queryKey, queryDefault.queryKey)) {
Object.assign(result, queryDefault.defaultOptions);
}
});
return result;
}
setMutationDefaults(mutationKey, options) {
__privateGet(this, _mutationDefaults).set(hashKey(mutationKey), {
mutationKey,
defaultOptions: options
});
}
getMutationDefaults(mutationKey) {
const defaults = [...__privateGet(this, _mutationDefaults).values()];
const result = {};
defaults.forEach((queryDefault) => {
if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {
Object.assign(result, queryDefault.defaultOptions);
}
});
return result;
}
defaultQueryOptions(options) {
if (options._defaulted) {
return options;
}
const defaultedOptions = {
...__privateGet(this, _defaultOptions).queries,
...this.getQueryDefaults(options.queryKey),
...options,
_defaulted: true
};
if (!defaultedOptions.queryHash) {
defaultedOptions.queryHash = hashQueryKeyByOptions(
defaultedOptions.queryKey,
defaultedOptions
);
}
if (defaultedOptions.refetchOnReconnect === void 0) {
defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
}
if (defaultedOptions.throwOnError === void 0) {
defaultedOptions.throwOnError = !!defaultedOptions.suspense;
}
if (!defaultedOptions.networkMode && defaultedOptions.persister) {
defaultedOptions.networkMode = "offlineFirst";
}
if (defaultedOptions.queryFn === skipToken) {
defaultedOptions.enabled = false;
}
return defaultedOptions;
}
defaultMutationOptions(options) {
if (options == null ? void 0 : options._defaulted) {
return options;
}
return {
...__privateGet(this, _defaultOptions).mutations,
...(options == null ? void 0 : options.mutationKey) && this.getMutationDefaults(options.mutationKey),
...options,
_defaulted: true
};
}
clear() {
__privateGet(this, _queryCache).clear();
__privateGet(this, _mutationCache).clear();
}
};
_queryCache = new WeakMap();
_mutationCache = new WeakMap();
_defaultOptions = new WeakMap();
_queryDefaults = new WeakMap();
_mutationDefaults = new WeakMap();
_mountCount = new WeakMap();
_unsubscribeFocus = new WeakMap();
_unsubscribeOnline = new WeakMap();
export {
QueryClient
};
//# sourceMappingURL=queryClient.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,506 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// src/queryObserver.ts
var queryObserver_exports = {};
__export(queryObserver_exports, {
QueryObserver: () => QueryObserver
});
module.exports = __toCommonJS(queryObserver_exports);
var import_focusManager = require("./focusManager.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_query = require("./query.cjs");
var import_subscribable = require("./subscribable.cjs");
var import_thenable = require("./thenable.cjs");
var import_utils = require("./utils.cjs");
var _client, _currentQuery, _currentQueryInitialState, _currentResult, _currentResultState, _currentResultOptions, _currentThenable, _selectError, _selectFn, _selectResult, _lastQueryWithDefinedData, _staleTimeoutId, _refetchIntervalId, _currentRefetchInterval, _trackedProps, _QueryObserver_instances, executeFetch_fn, updateStaleTimeout_fn, computeRefetchInterval_fn, updateRefetchInterval_fn, updateTimers_fn, clearStaleTimeout_fn, clearRefetchInterval_fn, updateQuery_fn, notify_fn;
var QueryObserver = class extends import_subscribable.Subscribable {
constructor(client, options) {
super();
this.options = options;
__privateAdd(this, _QueryObserver_instances);
__privateAdd(this, _client);
__privateAdd(this, _currentQuery);
__privateAdd(this, _currentQueryInitialState);
__privateAdd(this, _currentResult);
__privateAdd(this, _currentResultState);
__privateAdd(this, _currentResultOptions);
__privateAdd(this, _currentThenable);
__privateAdd(this, _selectError);
__privateAdd(this, _selectFn);
__privateAdd(this, _selectResult);
// This property keeps track of the last query with defined data.
// It will be used to pass the previous data and query to the placeholder function between renders.
__privateAdd(this, _lastQueryWithDefinedData);
__privateAdd(this, _staleTimeoutId);
__privateAdd(this, _refetchIntervalId);
__privateAdd(this, _currentRefetchInterval);
__privateAdd(this, _trackedProps, /* @__PURE__ */ new Set());
__privateSet(this, _client, client);
__privateSet(this, _selectError, null);
__privateSet(this, _currentThenable, (0, import_thenable.pendingThenable)());
if (!this.options.experimental_prefetchInRender) {
__privateGet(this, _currentThenable).reject(
new Error("experimental_prefetchInRender feature flag is not enabled")
);
}
this.bindMethods();
this.setOptions(options);
}
bindMethods() {
this.refetch = this.refetch.bind(this);
}
onSubscribe() {
if (this.listeners.size === 1) {
__privateGet(this, _currentQuery).addObserver(this);
if (shouldFetchOnMount(__privateGet(this, _currentQuery), this.options)) {
__privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
} else {
this.updateResult();
}
__privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this);
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
this.destroy();
}
}
shouldFetchOnReconnect() {
return shouldFetchOn(
__privateGet(this, _currentQuery),
this.options,
this.options.refetchOnReconnect
);
}
shouldFetchOnWindowFocus() {
return shouldFetchOn(
__privateGet(this, _currentQuery),
this.options,
this.options.refetchOnWindowFocus
);
}
destroy() {
this.listeners = /* @__PURE__ */ new Set();
__privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this);
__privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this);
__privateGet(this, _currentQuery).removeObserver(this);
}
setOptions(options) {
const prevOptions = this.options;
const prevQuery = __privateGet(this, _currentQuery);
this.options = __privateGet(this, _client).defaultQueryOptions(options);
if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof (0, import_utils.resolveEnabled)(this.options.enabled, __privateGet(this, _currentQuery)) !== "boolean") {
throw new Error(
"Expected enabled to be a boolean or a callback that returns a boolean"
);
}
__privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this);
__privateGet(this, _currentQuery).setOptions(this.options);
if (prevOptions._defaulted && !(0, import_utils.shallowEqualObjects)(this.options, prevOptions)) {
__privateGet(this, _client).getQueryCache().notify({
type: "observerOptionsUpdated",
query: __privateGet(this, _currentQuery),
observer: this
});
}
const mounted = this.hasListeners();
if (mounted && shouldFetchOptionally(
__privateGet(this, _currentQuery),
prevQuery,
this.options,
prevOptions
)) {
__privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
}
this.updateResult();
if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || (0, import_utils.resolveEnabled)(this.options.enabled, __privateGet(this, _currentQuery)) !== (0, import_utils.resolveEnabled)(prevOptions.enabled, __privateGet(this, _currentQuery)) || (0, import_utils.resolveStaleTime)(this.options.staleTime, __privateGet(this, _currentQuery)) !== (0, import_utils.resolveStaleTime)(prevOptions.staleTime, __privateGet(this, _currentQuery)))) {
__privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this);
}
const nextRefetchInterval = __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this);
if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || (0, import_utils.resolveEnabled)(this.options.enabled, __privateGet(this, _currentQuery)) !== (0, import_utils.resolveEnabled)(prevOptions.enabled, __privateGet(this, _currentQuery)) || nextRefetchInterval !== __privateGet(this, _currentRefetchInterval))) {
__privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, nextRefetchInterval);
}
}
getOptimisticResult(options) {
const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), options);
const result = this.createResult(query, options);
if (shouldAssignObserverCurrentProperties(this, result)) {
__privateSet(this, _currentResult, result);
__privateSet(this, _currentResultOptions, this.options);
__privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state);
}
return result;
}
getCurrentResult() {
return __privateGet(this, _currentResult);
}
trackResult(result, onPropTracked) {
return new Proxy(result, {
get: (target, key) => {
this.trackProp(key);
onPropTracked == null ? void 0 : onPropTracked(key);
return Reflect.get(target, key);
}
});
}
trackProp(key) {
__privateGet(this, _trackedProps).add(key);
}
getCurrentQuery() {
return __privateGet(this, _currentQuery);
}
refetch({ ...options } = {}) {
return this.fetch({
...options
});
}
fetchOptimistic(options) {
const defaultedOptions = __privateGet(this, _client).defaultQueryOptions(options);
const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), defaultedOptions);
return query.fetch().then(() => this.createResult(query, defaultedOptions));
}
fetch(fetchOptions) {
return __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this, {
...fetchOptions,
cancelRefetch: fetchOptions.cancelRefetch ?? true
}).then(() => {
this.updateResult();
return __privateGet(this, _currentResult);
});
}
createResult(query, options) {
var _a;
const prevQuery = __privateGet(this, _currentQuery);
const prevOptions = this.options;
const prevResult = __privateGet(this, _currentResult);
const prevResultState = __privateGet(this, _currentResultState);
const prevResultOptions = __privateGet(this, _currentResultOptions);
const queryChange = query !== prevQuery;
const queryInitialState = queryChange ? query.state : __privateGet(this, _currentQueryInitialState);
const { state } = query;
let newState = { ...state };
let isPlaceholderData = false;
let data;
if (options._optimisticResults) {
const mounted = this.hasListeners();
const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
if (fetchOnMount || fetchOptionally) {
newState = {
...newState,
...(0, import_query.fetchState)(state.data, query.options)
};
}
if (options._optimisticResults === "isRestoring") {
newState.fetchStatus = "idle";
}
}
let { error, errorUpdatedAt, status } = newState;
data = newState.data;
let skipSelect = false;
if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
let placeholderData;
if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
placeholderData = prevResult.data;
skipSelect = true;
} else {
placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
(_a = __privateGet(this, _lastQueryWithDefinedData)) == null ? void 0 : _a.state.data,
__privateGet(this, _lastQueryWithDefinedData)
) : options.placeholderData;
}
if (placeholderData !== void 0) {
status = "success";
data = (0, import_utils.replaceData)(
prevResult == null ? void 0 : prevResult.data,
placeholderData,
options
);
isPlaceholderData = true;
}
}
if (options.select && data !== void 0 && !skipSelect) {
if (prevResult && data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === __privateGet(this, _selectFn)) {
data = __privateGet(this, _selectResult);
} else {
try {
__privateSet(this, _selectFn, options.select);
data = options.select(data);
data = (0, import_utils.replaceData)(prevResult == null ? void 0 : prevResult.data, data, options);
__privateSet(this, _selectResult, data);
__privateSet(this, _selectError, null);
} catch (selectError) {
__privateSet(this, _selectError, selectError);
}
}
}
if (__privateGet(this, _selectError)) {
error = __privateGet(this, _selectError);
data = __privateGet(this, _selectResult);
errorUpdatedAt = Date.now();
status = "error";
}
const isFetching = newState.fetchStatus === "fetching";
const isPending = status === "pending";
const isError = status === "error";
const isLoading = isPending && isFetching;
const hasData = data !== void 0;
const result = {
status,
fetchStatus: newState.fetchStatus,
isPending,
isSuccess: status === "success",
isError,
isInitialLoading: isLoading,
isLoading,
data,
dataUpdatedAt: newState.dataUpdatedAt,
error,
errorUpdatedAt,
failureCount: newState.fetchFailureCount,
failureReason: newState.fetchFailureReason,
errorUpdateCount: newState.errorUpdateCount,
isFetched: newState.dataUpdateCount > 0 || newState.errorUpdateCount > 0,
isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,
isFetching,
isRefetching: isFetching && !isPending,
isLoadingError: isError && !hasData,
isPaused: newState.fetchStatus === "paused",
isPlaceholderData,
isRefetchError: isError && hasData,
isStale: isStale(query, options),
refetch: this.refetch,
promise: __privateGet(this, _currentThenable)
};
const nextResult = result;
if (this.options.experimental_prefetchInRender) {
const finalizeThenableIfPossible = (thenable) => {
if (nextResult.status === "error") {
thenable.reject(nextResult.error);
} else if (nextResult.data !== void 0) {
thenable.resolve(nextResult.data);
}
};
const recreateThenable = () => {
const pending = __privateSet(this, _currentThenable, nextResult.promise = (0, import_thenable.pendingThenable)());
finalizeThenableIfPossible(pending);
};
const prevThenable = __privateGet(this, _currentThenable);
switch (prevThenable.status) {
case "pending":
if (query.queryHash === prevQuery.queryHash) {
finalizeThenableIfPossible(prevThenable);
}
break;
case "fulfilled":
if (nextResult.status === "error" || nextResult.data !== prevThenable.value) {
recreateThenable();
}
break;
case "rejected":
if (nextResult.status !== "error" || nextResult.error !== prevThenable.reason) {
recreateThenable();
}
break;
}
}
return nextResult;
}
updateResult() {
const prevResult = __privateGet(this, _currentResult);
const nextResult = this.createResult(__privateGet(this, _currentQuery), this.options);
__privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state);
__privateSet(this, _currentResultOptions, this.options);
if (__privateGet(this, _currentResultState).data !== void 0) {
__privateSet(this, _lastQueryWithDefinedData, __privateGet(this, _currentQuery));
}
if ((0, import_utils.shallowEqualObjects)(nextResult, prevResult)) {
return;
}
__privateSet(this, _currentResult, nextResult);
const shouldNotifyListeners = () => {
if (!prevResult) {
return true;
}
const { notifyOnChangeProps } = this.options;
const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !__privateGet(this, _trackedProps).size) {
return true;
}
const includedProps = new Set(
notifyOnChangePropsValue ?? __privateGet(this, _trackedProps)
);
if (this.options.throwOnError) {
includedProps.add("error");
}
return Object.keys(__privateGet(this, _currentResult)).some((key) => {
const typedKey = key;
const changed = __privateGet(this, _currentResult)[typedKey] !== prevResult[typedKey];
return changed && includedProps.has(typedKey);
});
};
__privateMethod(this, _QueryObserver_instances, notify_fn).call(this, { listeners: shouldNotifyListeners() });
}
onQueryUpdate() {
this.updateResult();
if (this.hasListeners()) {
__privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this);
}
}
};
_client = new WeakMap();
_currentQuery = new WeakMap();
_currentQueryInitialState = new WeakMap();
_currentResult = new WeakMap();
_currentResultState = new WeakMap();
_currentResultOptions = new WeakMap();
_currentThenable = new WeakMap();
_selectError = new WeakMap();
_selectFn = new WeakMap();
_selectResult = new WeakMap();
_lastQueryWithDefinedData = new WeakMap();
_staleTimeoutId = new WeakMap();
_refetchIntervalId = new WeakMap();
_currentRefetchInterval = new WeakMap();
_trackedProps = new WeakMap();
_QueryObserver_instances = new WeakSet();
executeFetch_fn = function(fetchOptions) {
__privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this);
let promise = __privateGet(this, _currentQuery).fetch(
this.options,
fetchOptions
);
if (!(fetchOptions == null ? void 0 : fetchOptions.throwOnError)) {
promise = promise.catch(import_utils.noop);
}
return promise;
};
updateStaleTimeout_fn = function() {
__privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this);
const staleTime = (0, import_utils.resolveStaleTime)(
this.options.staleTime,
__privateGet(this, _currentQuery)
);
if (import_utils.isServer || __privateGet(this, _currentResult).isStale || !(0, import_utils.isValidTimeout)(staleTime)) {
return;
}
const time = (0, import_utils.timeUntilStale)(__privateGet(this, _currentResult).dataUpdatedAt, staleTime);
const timeout = time + 1;
__privateSet(this, _staleTimeoutId, setTimeout(() => {
if (!__privateGet(this, _currentResult).isStale) {
this.updateResult();
}
}, timeout));
};
computeRefetchInterval_fn = function() {
return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(__privateGet(this, _currentQuery)) : this.options.refetchInterval) ?? false;
};
updateRefetchInterval_fn = function(nextInterval) {
__privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this);
__privateSet(this, _currentRefetchInterval, nextInterval);
if (import_utils.isServer || (0, import_utils.resolveEnabled)(this.options.enabled, __privateGet(this, _currentQuery)) === false || !(0, import_utils.isValidTimeout)(__privateGet(this, _currentRefetchInterval)) || __privateGet(this, _currentRefetchInterval) === 0) {
return;
}
__privateSet(this, _refetchIntervalId, setInterval(() => {
if (this.options.refetchIntervalInBackground || import_focusManager.focusManager.isFocused()) {
__privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
}
}, __privateGet(this, _currentRefetchInterval)));
};
updateTimers_fn = function() {
__privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this);
__privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this));
};
clearStaleTimeout_fn = function() {
if (__privateGet(this, _staleTimeoutId)) {
clearTimeout(__privateGet(this, _staleTimeoutId));
__privateSet(this, _staleTimeoutId, void 0);
}
};
clearRefetchInterval_fn = function() {
if (__privateGet(this, _refetchIntervalId)) {
clearInterval(__privateGet(this, _refetchIntervalId));
__privateSet(this, _refetchIntervalId, void 0);
}
};
updateQuery_fn = function() {
const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), this.options);
if (query === __privateGet(this, _currentQuery)) {
return;
}
const prevQuery = __privateGet(this, _currentQuery);
__privateSet(this, _currentQuery, query);
__privateSet(this, _currentQueryInitialState, query.state);
if (this.hasListeners()) {
prevQuery == null ? void 0 : prevQuery.removeObserver(this);
query.addObserver(this);
}
};
notify_fn = function(notifyOptions) {
import_notifyManager.notifyManager.batch(() => {
if (notifyOptions.listeners) {
this.listeners.forEach((listener) => {
listener(__privateGet(this, _currentResult));
});
}
__privateGet(this, _client).getQueryCache().notify({
query: __privateGet(this, _currentQuery),
type: "observerResultsUpdated"
});
});
};
function shouldLoadOnMount(query, options) {
return (0, import_utils.resolveEnabled)(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && options.retryOnMount === false);
}
function shouldFetchOnMount(query, options) {
return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);
}
function shouldFetchOn(query, options, field) {
if ((0, import_utils.resolveEnabled)(options.enabled, query) !== false && (0, import_utils.resolveStaleTime)(options.staleTime, query) !== "static") {
const value = typeof field === "function" ? field(query) : field;
return value === "always" || value !== false && isStale(query, options);
}
return false;
}
function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
return (query !== prevQuery || (0, import_utils.resolveEnabled)(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
}
function isStale(query, options) {
return (0, import_utils.resolveEnabled)(options.enabled, query) !== false && query.isStaleByTime((0, import_utils.resolveStaleTime)(options.staleTime, query));
}
function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
if (!(0, import_utils.shallowEqualObjects)(observer.getCurrentResult(), optimisticResult)) {
return true;
}
return false;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QueryObserver
});
//# sourceMappingURL=queryObserver.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
import './subscribable.cjs';
export { c as QueryObserver } from './hydration-CdBkFt9i.cjs';
import './removable.cjs';

View File

@@ -0,0 +1,3 @@
import './subscribable.js';
export { c as QueryObserver } from './hydration-Cr-4Kky1.js';
import './removable.js';

View File

@@ -0,0 +1,489 @@
import {
__privateAdd,
__privateGet,
__privateMethod,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/queryObserver.ts
import { focusManager } from "./focusManager.js";
import { notifyManager } from "./notifyManager.js";
import { fetchState } from "./query.js";
import { Subscribable } from "./subscribable.js";
import { pendingThenable } from "./thenable.js";
import {
isServer,
isValidTimeout,
noop,
replaceData,
resolveEnabled,
resolveStaleTime,
shallowEqualObjects,
timeUntilStale
} from "./utils.js";
var _client, _currentQuery, _currentQueryInitialState, _currentResult, _currentResultState, _currentResultOptions, _currentThenable, _selectError, _selectFn, _selectResult, _lastQueryWithDefinedData, _staleTimeoutId, _refetchIntervalId, _currentRefetchInterval, _trackedProps, _QueryObserver_instances, executeFetch_fn, updateStaleTimeout_fn, computeRefetchInterval_fn, updateRefetchInterval_fn, updateTimers_fn, clearStaleTimeout_fn, clearRefetchInterval_fn, updateQuery_fn, notify_fn;
var QueryObserver = class extends Subscribable {
constructor(client, options) {
super();
this.options = options;
__privateAdd(this, _QueryObserver_instances);
__privateAdd(this, _client);
__privateAdd(this, _currentQuery);
__privateAdd(this, _currentQueryInitialState);
__privateAdd(this, _currentResult);
__privateAdd(this, _currentResultState);
__privateAdd(this, _currentResultOptions);
__privateAdd(this, _currentThenable);
__privateAdd(this, _selectError);
__privateAdd(this, _selectFn);
__privateAdd(this, _selectResult);
// This property keeps track of the last query with defined data.
// It will be used to pass the previous data and query to the placeholder function between renders.
__privateAdd(this, _lastQueryWithDefinedData);
__privateAdd(this, _staleTimeoutId);
__privateAdd(this, _refetchIntervalId);
__privateAdd(this, _currentRefetchInterval);
__privateAdd(this, _trackedProps, /* @__PURE__ */ new Set());
__privateSet(this, _client, client);
__privateSet(this, _selectError, null);
__privateSet(this, _currentThenable, pendingThenable());
if (!this.options.experimental_prefetchInRender) {
__privateGet(this, _currentThenable).reject(
new Error("experimental_prefetchInRender feature flag is not enabled")
);
}
this.bindMethods();
this.setOptions(options);
}
bindMethods() {
this.refetch = this.refetch.bind(this);
}
onSubscribe() {
if (this.listeners.size === 1) {
__privateGet(this, _currentQuery).addObserver(this);
if (shouldFetchOnMount(__privateGet(this, _currentQuery), this.options)) {
__privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
} else {
this.updateResult();
}
__privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this);
}
}
onUnsubscribe() {
if (!this.hasListeners()) {
this.destroy();
}
}
shouldFetchOnReconnect() {
return shouldFetchOn(
__privateGet(this, _currentQuery),
this.options,
this.options.refetchOnReconnect
);
}
shouldFetchOnWindowFocus() {
return shouldFetchOn(
__privateGet(this, _currentQuery),
this.options,
this.options.refetchOnWindowFocus
);
}
destroy() {
this.listeners = /* @__PURE__ */ new Set();
__privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this);
__privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this);
__privateGet(this, _currentQuery).removeObserver(this);
}
setOptions(options) {
const prevOptions = this.options;
const prevQuery = __privateGet(this, _currentQuery);
this.options = __privateGet(this, _client).defaultQueryOptions(options);
if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== "boolean") {
throw new Error(
"Expected enabled to be a boolean or a callback that returns a boolean"
);
}
__privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this);
__privateGet(this, _currentQuery).setOptions(this.options);
if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) {
__privateGet(this, _client).getQueryCache().notify({
type: "observerOptionsUpdated",
query: __privateGet(this, _currentQuery),
observer: this
});
}
const mounted = this.hasListeners();
if (mounted && shouldFetchOptionally(
__privateGet(this, _currentQuery),
prevQuery,
this.options,
prevOptions
)) {
__privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
}
this.updateResult();
if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || resolveStaleTime(this.options.staleTime, __privateGet(this, _currentQuery)) !== resolveStaleTime(prevOptions.staleTime, __privateGet(this, _currentQuery)))) {
__privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this);
}
const nextRefetchInterval = __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this);
if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || nextRefetchInterval !== __privateGet(this, _currentRefetchInterval))) {
__privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, nextRefetchInterval);
}
}
getOptimisticResult(options) {
const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), options);
const result = this.createResult(query, options);
if (shouldAssignObserverCurrentProperties(this, result)) {
__privateSet(this, _currentResult, result);
__privateSet(this, _currentResultOptions, this.options);
__privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state);
}
return result;
}
getCurrentResult() {
return __privateGet(this, _currentResult);
}
trackResult(result, onPropTracked) {
return new Proxy(result, {
get: (target, key) => {
this.trackProp(key);
onPropTracked == null ? void 0 : onPropTracked(key);
return Reflect.get(target, key);
}
});
}
trackProp(key) {
__privateGet(this, _trackedProps).add(key);
}
getCurrentQuery() {
return __privateGet(this, _currentQuery);
}
refetch({ ...options } = {}) {
return this.fetch({
...options
});
}
fetchOptimistic(options) {
const defaultedOptions = __privateGet(this, _client).defaultQueryOptions(options);
const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), defaultedOptions);
return query.fetch().then(() => this.createResult(query, defaultedOptions));
}
fetch(fetchOptions) {
return __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this, {
...fetchOptions,
cancelRefetch: fetchOptions.cancelRefetch ?? true
}).then(() => {
this.updateResult();
return __privateGet(this, _currentResult);
});
}
createResult(query, options) {
var _a;
const prevQuery = __privateGet(this, _currentQuery);
const prevOptions = this.options;
const prevResult = __privateGet(this, _currentResult);
const prevResultState = __privateGet(this, _currentResultState);
const prevResultOptions = __privateGet(this, _currentResultOptions);
const queryChange = query !== prevQuery;
const queryInitialState = queryChange ? query.state : __privateGet(this, _currentQueryInitialState);
const { state } = query;
let newState = { ...state };
let isPlaceholderData = false;
let data;
if (options._optimisticResults) {
const mounted = this.hasListeners();
const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
if (fetchOnMount || fetchOptionally) {
newState = {
...newState,
...fetchState(state.data, query.options)
};
}
if (options._optimisticResults === "isRestoring") {
newState.fetchStatus = "idle";
}
}
let { error, errorUpdatedAt, status } = newState;
data = newState.data;
let skipSelect = false;
if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
let placeholderData;
if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
placeholderData = prevResult.data;
skipSelect = true;
} else {
placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
(_a = __privateGet(this, _lastQueryWithDefinedData)) == null ? void 0 : _a.state.data,
__privateGet(this, _lastQueryWithDefinedData)
) : options.placeholderData;
}
if (placeholderData !== void 0) {
status = "success";
data = replaceData(
prevResult == null ? void 0 : prevResult.data,
placeholderData,
options
);
isPlaceholderData = true;
}
}
if (options.select && data !== void 0 && !skipSelect) {
if (prevResult && data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === __privateGet(this, _selectFn)) {
data = __privateGet(this, _selectResult);
} else {
try {
__privateSet(this, _selectFn, options.select);
data = options.select(data);
data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options);
__privateSet(this, _selectResult, data);
__privateSet(this, _selectError, null);
} catch (selectError) {
__privateSet(this, _selectError, selectError);
}
}
}
if (__privateGet(this, _selectError)) {
error = __privateGet(this, _selectError);
data = __privateGet(this, _selectResult);
errorUpdatedAt = Date.now();
status = "error";
}
const isFetching = newState.fetchStatus === "fetching";
const isPending = status === "pending";
const isError = status === "error";
const isLoading = isPending && isFetching;
const hasData = data !== void 0;
const result = {
status,
fetchStatus: newState.fetchStatus,
isPending,
isSuccess: status === "success",
isError,
isInitialLoading: isLoading,
isLoading,
data,
dataUpdatedAt: newState.dataUpdatedAt,
error,
errorUpdatedAt,
failureCount: newState.fetchFailureCount,
failureReason: newState.fetchFailureReason,
errorUpdateCount: newState.errorUpdateCount,
isFetched: newState.dataUpdateCount > 0 || newState.errorUpdateCount > 0,
isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,
isFetching,
isRefetching: isFetching && !isPending,
isLoadingError: isError && !hasData,
isPaused: newState.fetchStatus === "paused",
isPlaceholderData,
isRefetchError: isError && hasData,
isStale: isStale(query, options),
refetch: this.refetch,
promise: __privateGet(this, _currentThenable)
};
const nextResult = result;
if (this.options.experimental_prefetchInRender) {
const finalizeThenableIfPossible = (thenable) => {
if (nextResult.status === "error") {
thenable.reject(nextResult.error);
} else if (nextResult.data !== void 0) {
thenable.resolve(nextResult.data);
}
};
const recreateThenable = () => {
const pending = __privateSet(this, _currentThenable, nextResult.promise = pendingThenable());
finalizeThenableIfPossible(pending);
};
const prevThenable = __privateGet(this, _currentThenable);
switch (prevThenable.status) {
case "pending":
if (query.queryHash === prevQuery.queryHash) {
finalizeThenableIfPossible(prevThenable);
}
break;
case "fulfilled":
if (nextResult.status === "error" || nextResult.data !== prevThenable.value) {
recreateThenable();
}
break;
case "rejected":
if (nextResult.status !== "error" || nextResult.error !== prevThenable.reason) {
recreateThenable();
}
break;
}
}
return nextResult;
}
updateResult() {
const prevResult = __privateGet(this, _currentResult);
const nextResult = this.createResult(__privateGet(this, _currentQuery), this.options);
__privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state);
__privateSet(this, _currentResultOptions, this.options);
if (__privateGet(this, _currentResultState).data !== void 0) {
__privateSet(this, _lastQueryWithDefinedData, __privateGet(this, _currentQuery));
}
if (shallowEqualObjects(nextResult, prevResult)) {
return;
}
__privateSet(this, _currentResult, nextResult);
const shouldNotifyListeners = () => {
if (!prevResult) {
return true;
}
const { notifyOnChangeProps } = this.options;
const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !__privateGet(this, _trackedProps).size) {
return true;
}
const includedProps = new Set(
notifyOnChangePropsValue ?? __privateGet(this, _trackedProps)
);
if (this.options.throwOnError) {
includedProps.add("error");
}
return Object.keys(__privateGet(this, _currentResult)).some((key) => {
const typedKey = key;
const changed = __privateGet(this, _currentResult)[typedKey] !== prevResult[typedKey];
return changed && includedProps.has(typedKey);
});
};
__privateMethod(this, _QueryObserver_instances, notify_fn).call(this, { listeners: shouldNotifyListeners() });
}
onQueryUpdate() {
this.updateResult();
if (this.hasListeners()) {
__privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this);
}
}
};
_client = new WeakMap();
_currentQuery = new WeakMap();
_currentQueryInitialState = new WeakMap();
_currentResult = new WeakMap();
_currentResultState = new WeakMap();
_currentResultOptions = new WeakMap();
_currentThenable = new WeakMap();
_selectError = new WeakMap();
_selectFn = new WeakMap();
_selectResult = new WeakMap();
_lastQueryWithDefinedData = new WeakMap();
_staleTimeoutId = new WeakMap();
_refetchIntervalId = new WeakMap();
_currentRefetchInterval = new WeakMap();
_trackedProps = new WeakMap();
_QueryObserver_instances = new WeakSet();
executeFetch_fn = function(fetchOptions) {
__privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this);
let promise = __privateGet(this, _currentQuery).fetch(
this.options,
fetchOptions
);
if (!(fetchOptions == null ? void 0 : fetchOptions.throwOnError)) {
promise = promise.catch(noop);
}
return promise;
};
updateStaleTimeout_fn = function() {
__privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this);
const staleTime = resolveStaleTime(
this.options.staleTime,
__privateGet(this, _currentQuery)
);
if (isServer || __privateGet(this, _currentResult).isStale || !isValidTimeout(staleTime)) {
return;
}
const time = timeUntilStale(__privateGet(this, _currentResult).dataUpdatedAt, staleTime);
const timeout = time + 1;
__privateSet(this, _staleTimeoutId, setTimeout(() => {
if (!__privateGet(this, _currentResult).isStale) {
this.updateResult();
}
}, timeout));
};
computeRefetchInterval_fn = function() {
return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(__privateGet(this, _currentQuery)) : this.options.refetchInterval) ?? false;
};
updateRefetchInterval_fn = function(nextInterval) {
__privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this);
__privateSet(this, _currentRefetchInterval, nextInterval);
if (isServer || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) === false || !isValidTimeout(__privateGet(this, _currentRefetchInterval)) || __privateGet(this, _currentRefetchInterval) === 0) {
return;
}
__privateSet(this, _refetchIntervalId, setInterval(() => {
if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
__privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
}
}, __privateGet(this, _currentRefetchInterval)));
};
updateTimers_fn = function() {
__privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this);
__privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this));
};
clearStaleTimeout_fn = function() {
if (__privateGet(this, _staleTimeoutId)) {
clearTimeout(__privateGet(this, _staleTimeoutId));
__privateSet(this, _staleTimeoutId, void 0);
}
};
clearRefetchInterval_fn = function() {
if (__privateGet(this, _refetchIntervalId)) {
clearInterval(__privateGet(this, _refetchIntervalId));
__privateSet(this, _refetchIntervalId, void 0);
}
};
updateQuery_fn = function() {
const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), this.options);
if (query === __privateGet(this, _currentQuery)) {
return;
}
const prevQuery = __privateGet(this, _currentQuery);
__privateSet(this, _currentQuery, query);
__privateSet(this, _currentQueryInitialState, query.state);
if (this.hasListeners()) {
prevQuery == null ? void 0 : prevQuery.removeObserver(this);
query.addObserver(this);
}
};
notify_fn = function(notifyOptions) {
notifyManager.batch(() => {
if (notifyOptions.listeners) {
this.listeners.forEach((listener) => {
listener(__privateGet(this, _currentResult));
});
}
__privateGet(this, _client).getQueryCache().notify({
query: __privateGet(this, _currentQuery),
type: "observerResultsUpdated"
});
});
};
function shouldLoadOnMount(query, options) {
return resolveEnabled(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && options.retryOnMount === false);
}
function shouldFetchOnMount(query, options) {
return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);
}
function shouldFetchOn(query, options, field) {
if (resolveEnabled(options.enabled, query) !== false && resolveStaleTime(options.staleTime, query) !== "static") {
const value = typeof field === "function" ? field(query) : field;
return value === "always" || value !== false && isStale(query, options);
}
return false;
}
function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
return (query !== prevQuery || resolveEnabled(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
}
function isStale(query, options) {
return resolveEnabled(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query));
}
function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {
return true;
}
return false;
}
export {
QueryObserver
};
//# sourceMappingURL=queryObserver.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,68 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
// src/removable.ts
var removable_exports = {};
__export(removable_exports, {
Removable: () => Removable
});
module.exports = __toCommonJS(removable_exports);
var import_utils = require("./utils.cjs");
var _gcTimeout;
var Removable = class {
constructor() {
__privateAdd(this, _gcTimeout);
}
destroy() {
this.clearGcTimeout();
}
scheduleGc() {
this.clearGcTimeout();
if ((0, import_utils.isValidTimeout)(this.gcTime)) {
__privateSet(this, _gcTimeout, setTimeout(() => {
this.optionalRemove();
}, this.gcTime));
}
}
updateGcTime(newGcTime) {
this.gcTime = Math.max(
this.gcTime || 0,
newGcTime ?? (import_utils.isServer ? Infinity : 5 * 60 * 1e3)
);
}
clearGcTimeout() {
if (__privateGet(this, _gcTimeout)) {
clearTimeout(__privateGet(this, _gcTimeout));
__privateSet(this, _gcTimeout, void 0);
}
}
};
_gcTimeout = new WeakMap();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Removable
});
//# sourceMappingURL=removable.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/removable.ts"],"sourcesContent":["import { isServer, isValidTimeout } from './utils'\n\nexport abstract class Removable {\n gcTime!: number\n #gcTimeout?: ReturnType<typeof setTimeout>\n\n destroy(): void {\n this.clearGcTimeout()\n }\n\n protected scheduleGc(): void {\n this.clearGcTimeout()\n\n if (isValidTimeout(this.gcTime)) {\n this.#gcTimeout = setTimeout(() => {\n this.optionalRemove()\n }, this.gcTime)\n }\n }\n\n protected updateGcTime(newGcTime: number | undefined): void {\n // Default to 5 minutes (Infinity for server-side) if no gcTime is set\n this.gcTime = Math.max(\n this.gcTime || 0,\n newGcTime ?? (isServer ? Infinity : 5 * 60 * 1000),\n )\n }\n\n protected clearGcTimeout() {\n if (this.#gcTimeout) {\n clearTimeout(this.#gcTimeout)\n this.#gcTimeout = undefined\n }\n }\n\n protected abstract optionalRemove(): void\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAyC;AAAzC;AAEO,IAAe,YAAf,MAAyB;AAAA,EAAzB;AAEL;AAAA;AAAA,EAEA,UAAgB;AACd,SAAK,eAAe;AAAA,EACtB;AAAA,EAEU,aAAmB;AAC3B,SAAK,eAAe;AAEpB,YAAI,6BAAe,KAAK,MAAM,GAAG;AAC/B,yBAAK,YAAa,WAAW,MAAM;AACjC,aAAK,eAAe;AAAA,MACtB,GAAG,KAAK,MAAM;AAAA,IAChB;AAAA,EACF;AAAA,EAEU,aAAa,WAAqC;AAE1D,SAAK,SAAS,KAAK;AAAA,MACjB,KAAK,UAAU;AAAA,MACf,cAAc,wBAAW,WAAW,IAAI,KAAK;AAAA,IAC/C;AAAA,EACF;AAAA,EAEU,iBAAiB;AACzB,QAAI,mBAAK,aAAY;AACnB,mBAAa,mBAAK,WAAU;AAC5B,yBAAK,YAAa;AAAA,IACpB;AAAA,EACF;AAGF;AAhCE;","names":[]}

View File

@@ -0,0 +1,11 @@
declare abstract class Removable {
#private;
gcTime: number;
destroy(): void;
protected scheduleGc(): void;
protected updateGcTime(newGcTime: number | undefined): void;
protected clearGcTimeout(): void;
protected abstract optionalRemove(): void;
}
export { Removable };

View File

@@ -0,0 +1,11 @@
declare abstract class Removable {
#private;
gcTime: number;
destroy(): void;
protected scheduleGc(): void;
protected updateGcTime(newGcTime: number | undefined): void;
protected clearGcTimeout(): void;
protected abstract optionalRemove(): void;
}
export { Removable };

View File

@@ -0,0 +1,42 @@
import {
__privateAdd,
__privateGet,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/removable.ts
import { isServer, isValidTimeout } from "./utils.js";
var _gcTimeout;
var Removable = class {
constructor() {
__privateAdd(this, _gcTimeout);
}
destroy() {
this.clearGcTimeout();
}
scheduleGc() {
this.clearGcTimeout();
if (isValidTimeout(this.gcTime)) {
__privateSet(this, _gcTimeout, setTimeout(() => {
this.optionalRemove();
}, this.gcTime));
}
}
updateGcTime(newGcTime) {
this.gcTime = Math.max(
this.gcTime || 0,
newGcTime ?? (isServer ? Infinity : 5 * 60 * 1e3)
);
}
clearGcTimeout() {
if (__privateGet(this, _gcTimeout)) {
clearTimeout(__privateGet(this, _gcTimeout));
__privateSet(this, _gcTimeout, void 0);
}
}
};
_gcTimeout = new WeakMap();
export {
Removable
};
//# sourceMappingURL=removable.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/removable.ts"],"sourcesContent":["import { isServer, isValidTimeout } from './utils'\n\nexport abstract class Removable {\n gcTime!: number\n #gcTimeout?: ReturnType<typeof setTimeout>\n\n destroy(): void {\n this.clearGcTimeout()\n }\n\n protected scheduleGc(): void {\n this.clearGcTimeout()\n\n if (isValidTimeout(this.gcTime)) {\n this.#gcTimeout = setTimeout(() => {\n this.optionalRemove()\n }, this.gcTime)\n }\n }\n\n protected updateGcTime(newGcTime: number | undefined): void {\n // Default to 5 minutes (Infinity for server-side) if no gcTime is set\n this.gcTime = Math.max(\n this.gcTime || 0,\n newGcTime ?? (isServer ? Infinity : 5 * 60 * 1000),\n )\n }\n\n protected clearGcTimeout() {\n if (this.#gcTimeout) {\n clearTimeout(this.#gcTimeout)\n this.#gcTimeout = undefined\n }\n }\n\n protected abstract optionalRemove(): void\n}\n"],"mappings":";;;;;;;AAAA,SAAS,UAAU,sBAAsB;AAAzC;AAEO,IAAe,YAAf,MAAyB;AAAA,EAAzB;AAEL;AAAA;AAAA,EAEA,UAAgB;AACd,SAAK,eAAe;AAAA,EACtB;AAAA,EAEU,aAAmB;AAC3B,SAAK,eAAe;AAEpB,QAAI,eAAe,KAAK,MAAM,GAAG;AAC/B,yBAAK,YAAa,WAAW,MAAM;AACjC,aAAK,eAAe;AAAA,MACtB,GAAG,KAAK,MAAM;AAAA,IAChB;AAAA,EACF;AAAA,EAEU,aAAa,WAAqC;AAE1D,SAAK,SAAS,KAAK;AAAA,MACjB,KAAK,UAAU;AAAA,MACf,cAAc,WAAW,WAAW,IAAI,KAAK;AAAA,IAC/C;AAAA,EACF;AAAA,EAEU,iBAAiB;AACzB,QAAI,mBAAK,aAAY;AACnB,mBAAa,mBAAK,WAAU;AAC5B,yBAAK,YAAa;AAAA,IACpB;AAAA,EACF;AAGF;AAhCE;","names":[]}

Some files were not shown because too many files have changed in this diff Show More