Files
gibbz/frontend/node_modules/.vite/deps/swr.js
T
2026-09-22 08:41:20 +02:00

924 lines
33 KiB
JavaScript

import { r as __toESM } from "./rolldown-runtime-DC62tzP2.js";
import { t as require_react } from "./react.js";
import { t as require_shim } from "./shim-BX6a9SD7.js";
//#region node_modules/dequal/lite/index.mjs
var import_react = /* @__PURE__ */ __toESM(require_react(), 1);
var import_shim = require_shim();
var has = Object.prototype.hasOwnProperty;
function dequal(foo, bar) {
var ctor, len;
if (foo === bar) return true;
if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
if (ctor === Date) return foo.getTime() === bar.getTime();
if (ctor === RegExp) return foo.toString() === bar.toString();
if (ctor === Array) {
if ((len = foo.length) === bar.length) while (len-- && dequal(foo[len], bar[len]));
return len === -1;
}
if (!ctor || typeof foo === "object") {
len = 0;
for (ctor in foo) {
if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;
if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;
}
return Object.keys(bar).length === len;
}
}
return foo !== foo && bar !== bar;
}
var SWRGlobalState = /* @__PURE__ */ new WeakMap();
var noop = () => {};
var OBJECT = Object;
var isUndefined = (v) => v === void 0;
var isFunction = (v) => typeof v == "function";
var mergeObjects = (a, b) => ({
...a,
...b
});
var isPromiseLike = (x) => isFunction(x.then);
var EMPTY_CACHE = {};
var INITIAL_CACHE = {};
var STR_UNDEFINED = "undefined";
var isWindowDefined = typeof window != STR_UNDEFINED;
var isDocumentDefined = typeof document != STR_UNDEFINED;
var isLegacyDeno = isWindowDefined && "Deno" in window;
var hasRequestAnimationFrame = () => isWindowDefined && typeof window["requestAnimationFrame"] != STR_UNDEFINED;
var createCacheHelper = (cache, key) => {
const state = SWRGlobalState.get(cache);
return [
() => !isUndefined(key) && cache.get(key) || EMPTY_CACHE,
(info) => {
if (!isUndefined(key)) {
const prev = cache.get(key);
if (!(key in INITIAL_CACHE)) INITIAL_CACHE[key] = prev;
state[5](key, mergeObjects(prev, info), prev || EMPTY_CACHE);
}
},
state[6],
() => {
if (!isUndefined(key)) {
if (key in INITIAL_CACHE) return INITIAL_CACHE[key];
}
return !isUndefined(key) && cache.get(key) || EMPTY_CACHE;
}
];
};
/**
* Due to the bug https://bugs.chromium.org/p/chromium/issues/detail?id=678075,
* it's not reliable to detect if the browser is currently online or offline
* based on `navigator.onLine`.
* As a workaround, we always assume it's online on the first load, and change
* the status upon `online` or `offline` events.
*/ var online = true;
var isOnline = () => online;
var [onWindowEvent, offWindowEvent] = isWindowDefined && window.addEventListener ? [window.addEventListener.bind(window), window.removeEventListener.bind(window)] : [noop, noop];
var isVisible = () => {
const visibilityState = isDocumentDefined && document.visibilityState;
return isUndefined(visibilityState) || visibilityState !== "hidden";
};
var initFocus = (callback) => {
if (isDocumentDefined) document.addEventListener("visibilitychange", callback);
onWindowEvent("focus", callback);
return () => {
if (isDocumentDefined) document.removeEventListener("visibilitychange", callback);
offWindowEvent("focus", callback);
};
};
var initReconnect = (callback) => {
const onOnline = () => {
online = true;
callback();
};
const onOffline = () => {
online = false;
};
onWindowEvent("online", onOnline);
onWindowEvent("offline", onOffline);
return () => {
offWindowEvent("online", onOnline);
offWindowEvent("offline", onOffline);
};
};
var preset = {
isOnline,
isVisible
};
var defaultConfigOptions = {
initFocus,
initReconnect
};
var IS_REACT_LEGACY = !import_react.useId;
var IS_SERVER = !isWindowDefined || isLegacyDeno;
var rAF = (f) => hasRequestAnimationFrame() ? window["requestAnimationFrame"](f) : setTimeout(f, 1);
var useIsomorphicLayoutEffect = IS_SERVER ? import_react.useEffect : import_react.useLayoutEffect;
var navigatorConnection = typeof navigator !== "undefined" && navigator.connection;
var slowConnection = !IS_SERVER && navigatorConnection && (["slow-2g", "2g"].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData);
var table = /* @__PURE__ */ new WeakMap();
var getTypeName = (value) => OBJECT.prototype.toString.call(value);
var isObjectTypeName = (typeName, type) => typeName === `[object ${type}]`;
var counter = 0;
var stableHash = (arg) => {
const type = typeof arg;
const typeName = getTypeName(arg);
const isDate = isObjectTypeName(typeName, "Date");
const isRegex = isObjectTypeName(typeName, "RegExp");
const isPlainObject = isObjectTypeName(typeName, "Object");
let result;
let index;
if (OBJECT(arg) === arg && !isDate && !isRegex) {
result = table.get(arg);
if (result) return result;
result = ++counter + "~";
table.set(arg, result);
if (Array.isArray(arg)) {
result = "@";
for (index = 0; index < arg.length; index++) result += stableHash(arg[index]) + ",";
table.set(arg, result);
}
if (isPlainObject) {
result = "#";
const keys = OBJECT.keys(arg).sort();
while (!isUndefined(index = keys.pop())) if (!isUndefined(arg[index])) result += index + ":" + stableHash(arg[index]) + ",";
table.set(arg, result);
}
} else result = isDate ? arg.toJSON() : type == "symbol" ? arg.toString() : type == "string" ? JSON.stringify(arg) : "" + arg;
return result;
};
var serialize = (key) => {
if (isFunction(key)) try {
key = key();
} catch (err) {
key = "";
}
const args = key;
key = typeof key == "string" ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : "";
return [key, args];
};
var __timestamp = 0;
var getTimestamp = () => ++__timestamp;
async function internalMutate(...args) {
const [cache, _key, _data, _opts] = args;
const options = mergeObjects({
populateCache: true,
throwOnError: true
}, typeof _opts === "boolean" ? { revalidate: _opts } : _opts || {});
let populateCache = options.populateCache;
const rollbackOnErrorOption = options.rollbackOnError;
let optimisticData = options.optimisticData;
const rollbackOnError = (error) => {
return typeof rollbackOnErrorOption === "function" ? rollbackOnErrorOption(error) : rollbackOnErrorOption !== false;
};
const throwOnError = options.throwOnError;
if (isFunction(_key)) {
const keyFilter = _key;
const matchedKeys = [];
const it = cache.keys();
for (const key of it) if (!/^\$(inf|sub)\$/.test(key) && keyFilter(cache.get(key)._k)) matchedKeys.push(key);
return Promise.all(matchedKeys.map(mutateByKey));
}
return mutateByKey(_key);
async function mutateByKey(_k) {
const [key] = serialize(_k);
if (!key) return;
const [get, set] = createCacheHelper(cache, key);
const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache);
const startRevalidate = () => {
const revalidators = EVENT_REVALIDATORS[key];
if (isFunction(options.revalidate) ? options.revalidate(get().data, _k) : options.revalidate !== false) {
delete FETCH[key];
delete PRELOAD[key];
if (revalidators && revalidators[0]) return revalidators[0](2).then(() => get().data);
}
return get().data;
};
if (args.length < 3) return startRevalidate();
let data = _data;
let error;
let isError = false;
const beforeMutationTs = getTimestamp();
MUTATION[key] = [beforeMutationTs, 0];
const hasOptimisticData = !isUndefined(optimisticData);
const state = get();
const displayedData = state.data;
const currentData = state._c;
const committedData = isUndefined(currentData) ? displayedData : currentData;
if (hasOptimisticData) {
optimisticData = isFunction(optimisticData) ? optimisticData(committedData, displayedData) : optimisticData;
set({
data: optimisticData,
_c: committedData
});
}
if (isFunction(data)) try {
data = data(committedData);
} catch (err) {
error = err;
isError = true;
}
if (data && isPromiseLike(data)) {
data = await data.catch((err) => {
error = err;
isError = true;
});
if (beforeMutationTs !== MUTATION[key][0]) {
if (isError) throw error;
return data;
} else if (isError && hasOptimisticData && rollbackOnError(error)) {
populateCache = true;
set({
data: committedData,
_c: void 0
});
}
}
if (populateCache) {
if (!isError) {
if (isFunction(populateCache)) set({
data: populateCache(data, committedData),
error: void 0,
_c: void 0
});
else set({
data,
error: void 0,
_c: void 0
});
}
}
MUTATION[key][1] = getTimestamp();
Promise.resolve(startRevalidate()).then(() => {
set({ _c: void 0 });
});
if (isError) {
if (throwOnError) throw error;
return;
}
return data;
}
}
var revalidateAllKeys = (revalidators, type) => {
for (const key in revalidators) if (revalidators[key][0]) revalidators[key][0](type);
};
var initCache = (provider, options) => {
if (!SWRGlobalState.has(provider)) {
const opts = mergeObjects(defaultConfigOptions, options);
const EVENT_REVALIDATORS = Object.create(null);
const mutate = internalMutate.bind(void 0, provider);
let unmount = noop;
const subscriptions = Object.create(null);
const subscribe = (key, callback) => {
const subs = subscriptions[key] || [];
subscriptions[key] = subs;
subs.push(callback);
return () => {
const index = subs.indexOf(callback);
if (index >= 0) {
subs[index] = subs[subs.length - 1];
subs.pop();
}
};
};
const setter = (key, value, prev) => {
provider.set(key, value);
const subs = subscriptions[key];
if (subs) for (const fn of subs) fn(value, prev);
};
const unload = (unloadOptions) => {
const state = SWRGlobalState.get(provider);
const [, MUTATION, FETCH, PRELOAD] = state;
const ts = getTimestamp();
state[8]++;
for (const key in FETCH) delete FETCH[key];
for (const key in PRELOAD) delete PRELOAD[key];
for (const key in MUTATION) MUTATION[key] = [ts, ts];
const emptyState = {};
for (const key of [...provider.keys()]) {
const prev = provider.get(key);
provider.delete(key);
const subs = subscriptions[key];
if (subs) for (const fn of subs) fn(emptyState, prev);
}
const revalidate = !unloadOptions || unloadOptions.revalidate !== false;
for (const key in EVENT_REVALIDATORS) {
const revalidators = EVENT_REVALIDATORS[key];
for (let i = 0; i < revalidators.length; i++) revalidators[i](4, { revalidate: revalidate && !i });
}
};
const initProvider = () => {
if (!SWRGlobalState.has(provider)) {
SWRGlobalState.set(provider, [
EVENT_REVALIDATORS,
Object.create(null),
Object.create(null),
Object.create(null),
mutate,
setter,
subscribe,
unload,
0
]);
if (!IS_SERVER) {
const releaseFocus = opts.initFocus(setTimeout.bind(void 0, revalidateAllKeys.bind(void 0, EVENT_REVALIDATORS, 0)));
const releaseReconnect = opts.initReconnect(setTimeout.bind(void 0, revalidateAllKeys.bind(void 0, EVENT_REVALIDATORS, 1)));
unmount = () => {
releaseFocus && releaseFocus();
releaseReconnect && releaseReconnect();
SWRGlobalState.delete(provider);
};
}
}
};
initProvider();
return [
provider,
mutate,
initProvider,
unmount,
unload
];
}
const state = SWRGlobalState.get(provider);
return [
provider,
state[4],
void 0,
void 0,
state[7]
];
};
var onErrorRetry = (_, __, config, revalidate, opts) => {
const maxRetryCount = config.errorRetryCount;
const currentRetryCount = opts.retryCount;
const timeout = ~~((Math.random() + .5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;
if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) return;
setTimeout(revalidate, timeout, opts);
};
var compare = dequal;
var [cache, mutate, , , unload] = initCache(/* @__PURE__ */ new Map());
var defaultConfig = mergeObjects({
onLoadingSlow: noop,
onSuccess: noop,
onError: noop,
onErrorRetry,
onDiscarded: noop,
revalidateOnFocus: true,
revalidateOnReconnect: true,
revalidateIfStale: true,
shouldRetryOnError: true,
errorRetryInterval: slowConnection ? 1e4 : 5e3,
focusThrottleInterval: 5e3,
dedupingInterval: 2e3,
loadingTimeout: slowConnection ? 5e3 : 3e3,
compare,
isPaused: () => false,
cache,
mutate,
unload,
fallback: {}
}, preset);
var mergeConfigs = (a, b) => {
const v = mergeObjects(a, b);
if (b) {
const { use: u1, fallback: f1, cacheData: c1 } = a;
const { use: u2, fallback: f2, cacheData: c2 } = b;
if (u1 && u2) v.use = u1.concat(u2);
if (f1 && f2) v.fallback = mergeObjects(f1, f2);
if (c1 && c2) v.cacheData = mergeObjects(c1, c2);
}
return v;
};
var SWRConfigContext = (0, import_react.createContext)({});
var SWRConfig$1 = (props) => {
const { value } = props;
const parentConfig = (0, import_react.useContext)(SWRConfigContext);
const isFunctionalConfig = isFunction(value);
const config = (0, import_react.useMemo)(() => isFunctionalConfig ? value(parentConfig) : value, [
isFunctionalConfig,
parentConfig,
value
]);
const extendedConfig = (0, import_react.useMemo)(() => isFunctionalConfig ? config : mergeConfigs(parentConfig, config), [
isFunctionalConfig,
parentConfig,
config
]);
const provider = config && config.provider;
const cacheContextRef = (0, import_react.useRef)(void 0);
if (provider && !cacheContextRef.current) cacheContextRef.current = initCache(provider(extendedConfig.cache || cache), config);
const cacheContext = cacheContextRef.current;
if (cacheContext) {
extendedConfig.cache = cacheContext[0];
extendedConfig.mutate = cacheContext[1];
extendedConfig.unload = cacheContext[4];
}
useIsomorphicLayoutEffect(() => {
if (cacheContext) {
cacheContext[2] && cacheContext[2]();
return cacheContext[3];
}
}, []);
return (0, import_react.createElement)(SWRConfigContext.Provider, mergeObjects(props, { value: extendedConfig }));
};
//#endregion
//#region node_modules/swr/dist/_internal/index.mjs
var enableDevtools = isWindowDefined && window.__SWR_DEVTOOLS_USE__;
var use$1 = enableDevtools ? window.__SWR_DEVTOOLS_USE__ : [];
var setupDevTools = () => {
if (enableDevtools) window.__SWR_DEVTOOLS_REACT__ = import_react.default;
};
var normalize = (args) => {
return isFunction(args[1]) ? [
args[0],
args[1],
args[2] || {}
] : [
args[0],
null,
(args[1] === null ? args[2] : args[1]) || {}
];
};
var useSWRConfig = () => {
const parentConfig = (0, import_react.useContext)(SWRConfigContext);
return (0, import_react.useMemo)(() => mergeObjects(defaultConfig, parentConfig), [parentConfig]);
};
var preload = (key_, fetcher) => {
if (IS_SERVER) return;
const [key, fnArg] = serialize(key_);
const [, , , PRELOAD] = SWRGlobalState.get(cache);
if (PRELOAD[key]) return PRELOAD[key];
const req = fetcher(fnArg);
PRELOAD[key] = req;
return req;
};
var middleware = (useSWRNext) => (key_, fetcher_, config) => {
return useSWRNext(key_, fetcher_ && ((...args) => {
const [key] = serialize(key_);
const [, , , PRELOAD] = SWRGlobalState.get(cache);
if (key.startsWith("$inf$")) return fetcher_(...args);
const req = PRELOAD[key];
if (isUndefined(req)) return fetcher_(...args);
delete PRELOAD[key];
return req;
}), config);
};
var BUILT_IN_MIDDLEWARE = use$1.concat(middleware);
var withArgs = (hook) => {
return function useSWRArgs(...args) {
const fallbackConfig = useSWRConfig();
const [key, fn, _config] = normalize(args);
const config = mergeConfigs(fallbackConfig, _config);
let next = hook;
const { use } = config;
const middleware = (use || []).concat(BUILT_IN_MIDDLEWARE);
for (let i = middleware.length; i--;) next = middleware[i](next);
return next(key, fn || config.fetcher || null, config);
};
};
var subscribeCallback = (key, callbacks, callback) => {
const keyedRevalidators = callbacks[key] || (callbacks[key] = []);
keyedRevalidators.push(callback);
return () => {
const index = keyedRevalidators.indexOf(callback);
if (index >= 0) {
keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1];
keyedRevalidators.pop();
}
};
};
setupDevTools();
//#endregion
//#region node_modules/swr/dist/use-swr-emll9s78.mjs
var use = import_react.use || ((thenable) => {
switch (thenable.status) {
case "pending": throw thenable;
case "fulfilled": return thenable.value;
case "rejected": throw thenable.reason;
default:
thenable.status = "pending";
thenable.then((v) => {
thenable.status = "fulfilled";
thenable.value = v;
}, (e) => {
thenable.status = "rejected";
thenable.reason = e;
});
throw thenable;
}
});
var WITH_DEDUPE = { dedupe: true };
var isCacheDataConsumed = (consumedCacheData, cacheData, key) => {
var _consumedCacheData_get;
return cacheData ? ((_consumedCacheData_get = consumedCacheData.get(cacheData)) == null ? void 0 : _consumedCacheData_get.has(key)) === true : false;
};
var markCacheDataConsumed = (consumedCacheData, cacheData, key) => {
if (!cacheData) return;
let consumedKeys = consumedCacheData.get(cacheData);
if (!consumedKeys) {
consumedKeys = /* @__PURE__ */ new Set();
consumedCacheData.set(cacheData, consumedKeys);
}
consumedKeys.add(key);
};
var commitCacheData = ({ value, getCacheData, canCommit, setCache }) => {
const commit = (state) => {
if (canCommit() && isUndefined(getCacheData())) setCache(state);
};
Promise.resolve(value).then((data) => {
commit({
data,
error: void 0
});
}, (error) => {
commit({ error });
});
};
var resolvedUndef = Promise.resolve(void 0);
resolvedUndef.status = "fulfilled";
resolvedUndef.value = void 0;
var sub = () => noop;
/**
* The core implementation of the useSWR hook.
*
* This is the main handler function that implements all SWR functionality including
* data fetching, caching, revalidation, error handling, and state management.
* It manages the complete lifecycle of SWR requests from initialization through
* cleanup.
*
* Key responsibilities:
* - Key serialization and normalization
* - Cache state management and synchronization
* - Automatic and manual revalidation
* - Error handling and retry logic
* - Suspense integration
* - Loading state management
* - Effect cleanup and memory management
*
* @template Data - The type of data returned by the fetcher
* @template Error - The type of error that can be thrown
*
* @param _key - The SWR key (string, array, object, function, or falsy)
* @param fetcher - The fetcher function to retrieve data, or null to disable fetching
* @param config - Complete SWR configuration object with both public and internal options
*
* @returns SWRResponse object containing data, error, mutate function, and loading states
*
* @internal This is the internal implementation. Use `useSWR` instead.
*/ var useSWRHandler = (_key, fetcher, config) => {
const { cache, compare, suspense, fallbackData, revalidateOnMount, revalidateIfStale, refreshInterval, refreshWhenHidden, refreshWhenOffline, keepPreviousData, strictServerPrefetchWarning } = config;
const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache);
const [key, fnArg] = serialize(_key);
const initialMountedRef = (0, import_react.useRef)(false);
const unmountedRef = (0, import_react.useRef)(false);
const keyRef = (0, import_react.useRef)(key);
const fetcherRef = (0, import_react.useRef)(fetcher);
const configRef = (0, import_react.useRef)(config);
const getConfig = () => configRef.current;
const isActive = () => getConfig().isVisible() && getConfig().isOnline();
const [getCache, setCache, subscribeCache, getInitialCache] = createCacheHelper(cache, key);
const stateDependencies = (0, import_react.useRef)({}).current;
const fallback = isUndefined(fallbackData) ? isUndefined(config.fallback) ? void 0 : config.fallback[key] : fallbackData;
const serverCacheData = config.cacheData;
const configCacheData = !key ? void 0 : serverCacheData == null ? void 0 : serverCacheData[key];
const req = key ? PRELOAD[key] : void 0;
const hasCacheData = isUndefined(req) && !isUndefined(configCacheData);
const preloadedData = hasCacheData ? configCacheData : req;
const isEqual = (prev, current) => {
for (const _ in stateDependencies) {
const t = _;
if (t === "data") {
if (!compare(prev[t], current[t])) {
if (!isUndefined(prev[t])) return false;
if (!compare(returnedData, current[t])) return false;
}
} else if (current[t] !== prev[t]) return false;
}
return true;
};
const isInitialMount = !initialMountedRef.current;
const getSnapshot = (0, import_react.useMemo)(() => {
const cachedData = getCache();
const initialData = getInitialCache();
const getSelectedCache = (state) => {
const snapshot = mergeObjects(state);
delete snapshot._k;
if (!(() => {
if (!key) return false;
if (!fetcher) return false;
if (getConfig().isPaused()) return false;
if (isInitialMount && !isUndefined(revalidateOnMount)) return revalidateOnMount;
const data = !isUndefined(fallback) ? fallback : snapshot.data;
if (suspense && hasCacheData && isUndefined(data)) return false;
if (suspense) return isUndefined(data) || revalidateIfStale;
return isUndefined(data) || revalidateIfStale;
})()) return snapshot;
return {
isValidating: true,
isLoading: true,
...snapshot
};
};
const clientSnapshot = getSelectedCache(cachedData);
const serverSnapshot = cachedData === initialData ? clientSnapshot : getSelectedCache(initialData);
let memorizedSnapshot = clientSnapshot;
return [() => {
const newSnapshot = getSelectedCache(getCache());
if (isEqual(newSnapshot, memorizedSnapshot)) {
memorizedSnapshot.data = newSnapshot.data;
memorizedSnapshot.isLoading = newSnapshot.isLoading;
memorizedSnapshot.isValidating = newSnapshot.isValidating;
memorizedSnapshot.error = newSnapshot.error;
return memorizedSnapshot;
} else {
memorizedSnapshot = newSnapshot;
return newSnapshot;
}
}, () => serverSnapshot];
}, [cache, key]);
const cached = (0, import_shim.useSyncExternalStore)((0, import_react.useCallback)((callback) => subscribeCache(key, (current, prev) => {
if (!isEqual(prev, current)) callback();
}), [cache, key]), getSnapshot[0], getSnapshot[1]);
const hasRevalidator = EVENT_REVALIDATORS[key] && EVENT_REVALIDATORS[key].length > 0;
const cachedData = cached.data;
let data = isUndefined(cachedData) ? fallback && isPromiseLike(fallback) ? use(fallback) : fallback : cachedData;
const error = cached.error;
const laggyDataRef = (0, import_react.useRef)(data);
const consumedCacheDataRef = (0, import_react.useRef)(void 0);
let consumedCacheData = consumedCacheDataRef.current;
if (!consumedCacheData) {
consumedCacheData = /* @__PURE__ */ new WeakMap();
consumedCacheDataRef.current = consumedCacheData;
}
const preloadCacheRef = (0, import_react.useRef)(null);
let returnedData = keepPreviousData ? isUndefined(cachedData) ? isUndefined(laggyDataRef.current) ? data : laggyDataRef.current : cachedData : data;
const hasKeyButNoData = key && isUndefined(data);
const hydrationRef = (0, import_react.useRef)(null);
!IS_SERVER && (0, import_shim.useSyncExternalStore)(sub, () => {
hydrationRef.current = false;
return hydrationRef;
}, () => {
hydrationRef.current = true;
return hydrationRef;
});
const isHydration = hydrationRef.current;
if (strictServerPrefetchWarning && isHydration && !suspense && hasKeyButNoData) console.warn(`Missing pre-initiated data for serialized key "${key}" during server-side rendering. Data fetching should be initiated on the server and provided to SWR via fallback data. You can set "strictServerPrefetchWarning: false" to disable this warning.`);
const shouldDoInitialRevalidation = (() => {
if (!key || !fetcher) return false;
if (getConfig().isPaused()) return false;
if (hasRevalidator && !isUndefined(error)) return false;
if (isInitialMount && !isUndefined(revalidateOnMount)) return revalidateOnMount;
if (suspense && hasCacheData && hasKeyButNoData) return false;
if (suspense) return isUndefined(data) ? false : revalidateIfStale;
return isUndefined(data) || revalidateIfStale;
})();
const defaultValidatingState = isInitialMount && shouldDoInitialRevalidation;
const isValidating = isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating;
const isLoading = isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading;
const revalidate = (0, import_react.useCallback)(async (revalidateOpts) => {
const currentFetcher = fetcherRef.current;
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) return false;
let newData;
let startAt;
let loading = true;
const opts = revalidateOpts || {};
const shouldStartNewRequest = !FETCH[key] || !opts.dedupe;
const shouldUseRSCPreload = hasCacheData && !isCacheDataConsumed(consumedCacheData, serverCacheData, key) && !isUndefined(preloadedData) && isUndefined(getCache().data);
const callbackSafeguard = () => {
if (IS_REACT_LEGACY) return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;
return key === keyRef.current;
};
const finalState = {
isValidating: false,
isLoading: false
};
const finishRequestAndUpdateState = () => {
setCache(finalState);
};
const cleanupState = () => {
const requestInfo = FETCH[key];
if (requestInfo && requestInfo[1] === startAt) delete FETCH[key];
};
const initialState = { isValidating: true };
if (isUndefined(getCache().data)) initialState.isLoading = true;
try {
if (shouldStartNewRequest) {
setCache(initialState);
if (config.loadingTimeout && isUndefined(getCache().data)) setTimeout(() => {
if (loading && callbackSafeguard()) getConfig().onLoadingSlow(key, config);
}, config.loadingTimeout);
if (shouldUseRSCPreload) markCacheDataConsumed(consumedCacheData, serverCacheData, key);
FETCH[key] = [shouldUseRSCPreload ? preloadedData : currentFetcher(fnArg), getTimestamp()];
if (shouldUseRSCPreload && PRELOAD[key]) delete PRELOAD[key];
}
[newData, startAt] = FETCH[key];
newData = await newData;
if (shouldStartNewRequest) setTimeout(cleanupState, config.dedupingInterval);
if (!FETCH[key] || FETCH[key][1] !== startAt) {
if (shouldStartNewRequest) {
if (callbackSafeguard()) getConfig().onDiscarded(key);
}
return false;
}
finalState.error = void 0;
const mutationInfo = MUTATION[key];
if (!isUndefined(mutationInfo) && (startAt <= mutationInfo[0] || startAt <= mutationInfo[1] || mutationInfo[1] === 0)) {
finishRequestAndUpdateState();
if (shouldStartNewRequest) {
if (callbackSafeguard()) getConfig().onDiscarded(key);
}
return false;
}
const cacheData = getCache().data;
finalState.data = compare(cacheData, newData) ? cacheData : newData;
if (shouldStartNewRequest) {
if (callbackSafeguard()) getConfig().onSuccess(newData, key, config);
}
} catch (err) {
cleanupState();
const currentConfig = getConfig();
const { shouldRetryOnError } = currentConfig;
if (!currentConfig.isPaused()) {
finalState.error = err;
if (shouldStartNewRequest && callbackSafeguard()) {
currentConfig.onError(err, key, currentConfig);
if (shouldRetryOnError === true || isFunction(shouldRetryOnError) && shouldRetryOnError(err)) {
if (!getConfig().revalidateOnFocus || !getConfig().revalidateOnReconnect || isActive()) currentConfig.onErrorRetry(err, key, currentConfig, (_opts) => {
const revalidators = EVENT_REVALIDATORS[key];
if (revalidators && revalidators[0]) revalidators[0](3, _opts);
}, {
retryCount: (opts.retryCount || 0) + 1,
dedupe: true
});
}
}
}
}
loading = false;
finishRequestAndUpdateState();
return true;
}, [key, cache]);
const boundMutate = (0, import_react.useCallback)((...args) => {
return internalMutate(cache, keyRef.current, ...args);
}, []);
useIsomorphicLayoutEffect(() => {
const preloaded = preloadCacheRef.current;
if (!preloaded) return;
preloadCacheRef.current = null;
markCacheDataConsumed(consumedCacheData, preloaded.cacheData, preloaded.key);
if (isUndefined(getCache().data)) setCache({
data: preloaded.data,
error: void 0,
_k: preloaded._k
});
if (PRELOAD[preloaded.key]) delete PRELOAD[preloaded.key];
});
useIsomorphicLayoutEffect(() => {
fetcherRef.current = fetcher;
configRef.current = config;
if (!isUndefined(cachedData)) laggyDataRef.current = cachedData;
});
useIsomorphicLayoutEffect(() => {
if (fetcher || !hasCacheData || isUndefined(preloadedData) || isCacheDataConsumed(consumedCacheData, serverCacheData, key) || !isUndefined(getCache().data)) return;
markCacheDataConsumed(consumedCacheData, serverCacheData, key);
const mutation = MUTATION[key];
commitCacheData({
value: preloadedData,
getCacheData: () => getCache().data,
canCommit: () => !unmountedRef.current && key === keyRef.current && MUTATION[key] === mutation,
setCache: (state) => setCache({
...state,
_k: fnArg
})
});
});
useIsomorphicLayoutEffect(() => {
if (!key) return;
const softRevalidate = revalidate.bind(void 0, WITH_DEDUPE);
let nextFocusRevalidatedAt = 0;
if (getConfig().revalidateOnFocus) nextFocusRevalidatedAt = Date.now() + getConfig().focusThrottleInterval;
const onRevalidate = (type, opts = {}) => {
if (type == 0) {
const now = Date.now();
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) {
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;
softRevalidate();
}
} else if (type == 1) {
if (getConfig().revalidateOnReconnect && isActive()) softRevalidate();
} else if (type == 2) return revalidate();
else if (type == 3) return revalidate(opts);
else if (type == 4) {
laggyDataRef.current = void 0;
if (opts.revalidate) return revalidate();
}
};
const unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);
unmountedRef.current = false;
keyRef.current = key;
initialMountedRef.current = true;
setCache({ _k: fnArg });
if (shouldDoInitialRevalidation) {
if (!FETCH[key]) {
if (isUndefined(data) || IS_SERVER) softRevalidate();
else rAF(softRevalidate);
}
}
return () => {
unmountedRef.current = true;
unsubEvents();
};
}, [key]);
useIsomorphicLayoutEffect(() => {
let timer;
function next() {
const interval = isFunction(refreshInterval) ? refreshInterval(getCache().data) : refreshInterval;
if (interval && timer !== -1) timer = setTimeout(execute, interval);
}
function execute() {
if (!getCache().error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) revalidate(WITH_DEDUPE).then(next);
else next();
}
next();
return () => {
if (timer) {
clearTimeout(timer);
timer = -1;
}
};
}, [
refreshInterval,
refreshWhenHidden,
refreshWhenOffline,
key
]);
(0, import_react.useDebugValue)(returnedData);
if (suspense) {
if (!IS_REACT_LEGACY && IS_SERVER && hasKeyButNoData && isUndefined(preloadedData)) throw new Error("Fallback data is required when using Suspense in SSR.");
if (hasKeyButNoData) {
fetcherRef.current = fetcher;
configRef.current = config;
unmountedRef.current = false;
}
const shouldConsumePreload = !isUndefined(preloadedData) && hasKeyButNoData;
let preloadData = void 0;
if (shouldConsumePreload && hasCacheData) {
preloadData = preloadedData && isPromiseLike(preloadedData) ? use(preloadedData) : preloadedData;
data = preloadData;
returnedData = preloadData;
if (!IS_SERVER) preloadCacheRef.current = {
data: preloadData,
_k: fnArg,
key,
cacheData: serverCacheData
};
} else use(shouldConsumePreload ? boundMutate(preloadedData) : resolvedUndef);
if (!isUndefined(error) && hasKeyButNoData) throw error;
const revalidation = hasKeyButNoData && isUndefined(preloadData) ? revalidate(WITH_DEDUPE) : resolvedUndef;
if (!isUndefined(returnedData) && hasKeyButNoData) {
revalidation.status = "fulfilled";
revalidation.value = true;
}
use(revalidation);
}
return {
mutate: boundMutate,
get data() {
stateDependencies.data = true;
return returnedData;
},
get error() {
stateDependencies.error = true;
return error;
},
get isValidating() {
stateDependencies.isValidating = true;
return isValidating;
},
get isLoading() {
stateDependencies.isLoading = true;
return isLoading;
}
};
};
var SWRConfig = OBJECT.defineProperty(SWRConfig$1, "defaultValue", { value: defaultConfig });
/**
* A hook to fetch data.
*
* @see {@link https://swr.vercel.app}
*
* @example
* ```jsx
* import useSWR from 'swr'
* function Profile() {
* const { data, error, isLoading } = useSWR('/api/user', fetcher)
* if (error) return <div>failed to load</div>
* if (isLoading) return <div>loading...</div>
* return <div>hello {data.name}!</div>
* }
* ```
*/ var useSWR = withArgs(useSWRHandler);
//#endregion
//#region node_modules/swr/dist/index/index.mjs
var unstable_serialize = (key) => serialize(key)[0];
//#endregion
export { SWRConfig, useSWR as default, mutate, preload, unload, unstable_serialize, useSWRConfig };