@hyper-fetch/react 9.8.1 → 10.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -26
- package/__tests__/features/use-listener/use-listener.payload.spec.tsx +196 -0
- package/__tests__/features/use-listener/use-listener.ssr.spec.tsx +22 -1
- package/__tests__/features/use-listener/use-listener.status.spec.tsx +288 -0
- package/dist/helpers/use-socket-state/use-socket-state.hooks.d.ts +10 -3
- package/dist/helpers/use-socket-state/use-socket-state.hooks.d.ts.map +1 -1
- package/dist/hooks/use-listener/use-listener.hooks.d.ts +20 -4
- package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
- package/dist/hooks/use-listener/use-listener.types.d.ts +11 -0
- package/dist/hooks/use-listener/use-listener.types.d.ts.map +1 -1
- package/dist/index.mjs +66 -10
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/helpers/use-socket-state/use-socket-state.hooks.ts +36 -11
- package/src/hooks/use-listener/use-listener.hooks.ts +66 -13
- package/src/hooks/use-listener/use-listener.types.ts +12 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["r","f","t","u","a","n","v","y","d","n","o","t","r","e","u","l","c"],"sources":["../../../node_modules/.pnpm/@better-hooks+lifecycle@2.0.0_react@19.2.5/node_modules/@better-hooks/lifecycle/dist/index.esm.js","../../../node_modules/.pnpm/@better-hooks+performance@2.1.0_react@19.2.5/node_modules/@better-hooks/performance/dist/index.esm.js","../src/utils/scope.utils.ts","../src/helpers/use-request-events/use-request-events.hooks.ts","../src/helpers/use-tracked-state/use-tracked-state.constants.ts","../src/hydrate/hydrate.utils.ts","../src/hydrate/hydrate.tsx","../src/utils/deep-equal.utils.ts","../src/utils/bounce.utils.ts","../src/utils/tracked-proxy.utils.ts","../src/helpers/use-tracked-state/use-tracked-state.utils.ts","../src/helpers/use-tracked-state/use-tracked-state.hooks.ts","../src/helpers/use-socket-state/use-socket-state.hooks.ts","../src/helpers/use-socket-state/use-socket-state.constants.ts","../src/provider/provider.tsx","../src/utils/key.utils.ts","../src/hooks/use-fetch/use-fetch.hooks.ts","../src/hooks/use-fetch/use-fetch.utils.ts","../src/hooks/use-fetch/use-fetch.constants.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.constants.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.requests.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts","../src/hooks/use-submit/use-submit.hooks.ts","../src/hooks/use-submit/use-submit.constants.ts","../src/hooks/use-queue/use-queue.hooks.ts","../src/hooks/use-queue/use-queue.constants.ts","../src/hooks/use-cache/use-cache.hooks.ts","../src/hooks/use-cache/use-cache.constants.ts","../src/hooks/use-stream/use-stream.hooks.ts","../src/hooks/use-listener/use-listener.hooks.ts","../src/hooks/use-emitter/use-emitter.hooks.ts","../src/hooks/use-app-manager/use-app-manager.hooks.ts","../src/hooks/use-is-fetching/use-is-fetching.hooks.ts"],"sourcesContent":["import{useRef as r,useEffect as n,useState as t,useCallback as u,useLayoutEffect as c}from\"react\";var e=function(t,u,c){void 0===c&&(c=!1);var e=r(null),o=r(c);n((function(){if(o.current)return function(){t(e.current),e.current=u};o.current=!0}),u)},o=function(t){var u=r(!1);n((function(){if(!u.current)return u.current=!0,t()}),[])},i=function(t,u,c){void 0===c&&(c=!1);var e=r(c);n((function(){if(e.current)return t();e.current=!0}),u)};var f=function(){var r=function(r,n){var t=\"function\"==typeof Symbol&&r[Symbol.iterator];if(!t)return r;var u,c,e=t.call(r),o=[];try{for(;(void 0===n||n-- >0)&&!(u=e.next()).done;)o.push(u.value)}catch(r){c={error:r}}finally{try{u&&!u.done&&(t=e.return)&&t.call(e)}finally{if(c)throw c.error}}return o}(t(0),2)[1];return u((function(){r((function(r){return r+1}))}),[])},a=function(){var t=r(!0);return n((function(){return t.current=!0,function(){t.current=!1}}),[]),t},v=function(n){var t=r(!1);c((function(){if(!t.current)return t.current=!0,n()}),[])},l=function(n,t,u){void 0===u&&(u=!1);var e=r(u);c((function(){if(e.current)return n();e.current=!0}),t)},y=function(n){var t=r(!0);t.current&&n(),t.current=!1},d=function(r){n((function(){return r}),[])};export{e as useDepsChange,o as useDidMount,i as useDidUpdate,f as useForceUpdate,a as useIsMounted,v as useLayoutMount,l as useLayoutUpdate,y as useWillMount,d as useWillUnmount};\n//# sourceMappingURL=index.esm.js.map\n","import{useRef as n,useCallback as t,useEffect as r,useState as e,useMemo as u,useLayoutEffect as c}from\"react\";import{useForceUpdate as o,useDidUpdate as i,useDidMount as l}from\"@better-hooks/lifecycle\";var f=function(e){var u=(e||{}).delay,c=void 0===u?400:u,i=n(!1),l=n(null),f=o(),a=t((function(){i.current&&f()}),[f]),v=function(){null!==l.current&&clearTimeout(l.current),l.current=null},d=t((function(n,t){var r=null!=t?t:c;v(),l.current=setTimeout((function(){l.current=null,n(),a()}),r),a()}),[c,a]);return r((function(){return v}),[]),{get active(){return i.current=!0,!!l.current},debounce:d,reset:v}},a=function(n,t,e){var u=f(t).debounce;r((function(){u(n)}),e)};function v(n,t){var r=\"function\"==typeof Symbol&&n[Symbol.iterator];if(!r)return n;var e,u,c=r.call(n),o=[];try{for(;(void 0===t||t-- >0)&&!(e=c.next()).done;)o.push(e.value)}catch(n){u={error:n}}finally{try{e&&!e.done&&(r=c.return)&&r.call(c)}finally{if(u)throw u.error}}return o}var d=function(n,t){var r=f(t).debounce,u=v(e(n),2),c=u[0],o=u[1];return[c,function(n){return r((function(){return o(n)}))}]},y=function(n){var t=Object.prototype.toString.call(n);return Array.isArray(n)?!n.length:\"object\"==typeof n&&null!==n&&\"[object Object]\"===t&&!Object.keys(n).length},m=function(n,t){var r,e=Object.prototype.toString.call(n),u=Object.prototype.toString.call(t),c=typeof n,o=typeof t,i=function(n){return c===n&&o===n};return e===u&&(null===n&&null===t||(!!(i(\"number\")&&Number.isNaN(n)&&Number.isNaN(t))||(!(!y(n)||!y(t))||(Array.isArray(n)&&Array.isArray(t)?n.length===t.length&&!n.some((function(n,r){return!m(n,t[r])})):i(\"object\")&&(e===(r=\"[object Object]\")&&u===r)?Object.keys(n).length===Object.keys(t).length&&!Object.entries(n).some((function(n){var r=v(n,2),e=r[0],u=r[1];return!m(u,t[e])})):n instanceof Date&&t instanceof Date?+n==+t:n===t))))},s=function(t,e){return r(t,(o=n(c=e),i=n(0),m(c,o.current)||(o.current=c,i.current+=1),u((function(){return o.current}),[i.current])));var c,o,i},b=function(t,r,u){var c=u||{},o=c.immediate,f=void 0===o||o,a=c.disabled,d=void 0!==a&&a,y=v(e(null),2),m=y[0],s=y[1],b=n(t),p=function(){m&&clearInterval(m),s(null)},h=function(){p(),!r&&0!==r||d||s(setInterval((function(){return b.current()}),r))};return i((function(){b.current=t}),[t]),l((function(){if(b.current=t,f)return h(),p})),i((function(){return b.current=t,h(),p}),[r]),{active:null!==m,start:h,stop:p}},p=function(t){var e=t||{},u=e.interval,c=void 0===u?200:u,i=e.timeout,l=void 0===i?200:i,f=n(0),a=n(!0),v=n(!1),d=n(null),y=o(),m=function(){a.current&&(a.current=!1),v.current&&y()},s=function(){null!==d.current&&clearTimeout(d.current),d.current=null};return r((function(){return s}),[]),{get active(){return v.current=!0,!!d.current},throttle:function(n,t){var r,e,u=function(){f.current=Date.now(),n(),m()},o=null!==(r=null==t?void 0:t.interval)&&void 0!==r?r:c,i=null!==(e=null==t?void 0:t.timeout)&&void 0!==e?e:l,v=Date.now()>=f.current+o;a.current&&m(),d.current&&s(),v?u():i&&(d.current=setTimeout((function(){d.current=null,a.current=!0,u()}),i))},reset:s}},h=function(n,t,e){var u=p(t).throttle;r((function(){u(n)}),e)},j=function(n,t){var r=p(t).throttle,u=v(e(n),2),c=u[0],o=u[1];return[c,function(n){return r((function(){return o(n)}))}]},g=function(t,e){var u=n(t);w((function(){u.current=t}),[t]),r((function(){if(e||0===e){var n=setTimeout((function(){return u.current()}),e);return function(){return clearTimeout(n)}}}),[e])},w=!(\"undefined\"==typeof window||void 0===window.document||void 0===window.document.createElement)?c:r;export{f as useDebounce,a as useDebounceEffect,d as useDebounceState,s as useDeepEffect,b as useInterval,w as useIsomorphicEffect,p as useThrottle,h as useThrottleEffect,j as useThrottleState,g as useTimeout};\n//# sourceMappingURL=index.esm.js.map\n","/**\n * Core emits request and cache events by the logical (unscoped) keys, while dispatcher queues and cache storage\n * use the scoped keys. Listeners subscribe by the logical key and use this check to skip events of other scopes.\n * @internal\n */\nexport const isSameScope = (scope: string | null | undefined, otherScope: string | null | undefined): boolean => {\n return (scope ?? null) === (otherScope ?? null);\n};\n","import { useIsMounted, useWillUnmount } from \"@better-hooks/lifecycle\";\nimport type {\n ExtractErrorType,\n ExtractResponseType,\n RequestInstance,\n RequestEventType,\n RequestLoadingEventType,\n RequestRemovedEventType,\n ExtractAdapterType,\n RequestProgressEventType,\n RequestResponseEventType,\n ResponseType,\n OptimisticCallbackResult,\n} from \"@hyper-fetch/core\";\nimport { getErrorMessage, runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport type {\n OnErrorCallbackType,\n OnStartCallbackType,\n OnSuccessCallbackType,\n OnProgressCallbackType,\n OnFinishedCallbackType,\n UseRequestEventsDataMap,\n UseRequestEventsReturnType,\n UseRequestEventsPropsType,\n UseRequestEventsLifecycleMap,\n} from \"helpers\";\nimport { useRef } from \"react\";\nimport { isSameScope } from \"utils/scope.utils\";\n\n/**\n * This is helper hook that handles main Hyper-Fetch event/data flow\n * @internal\n * @param options\n * @returns\n */\nexport const useRequestEvents = <R extends RequestInstance>({\n request,\n dispatcher,\n logger,\n actions,\n setCacheData,\n getIsDataProcessing,\n}: UseRequestEventsPropsType<R>): UseRequestEventsReturnType<R> => {\n const { cache, requestManager } = request.client;\n\n // Always points to the request from the latest render - handlers created once can use it safely\n const requestRef = useRef(request);\n requestRef.current = request;\n const dispatcherRef = useRef(dispatcher);\n dispatcherRef.current = dispatcher;\n\n // ******************\n // Callbacks\n // ******************\n\n const onSuccessCallback = useRef<null | OnSuccessCallbackType<R>>(null);\n const onErrorCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onAbortCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onOfflineErrorCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onFinishedCallback = useRef<null | OnFinishedCallbackType<R>>(null);\n const onRequestStartCallback = useRef<null | OnStartCallbackType<R>>(null);\n const onResponseStartCallback = useRef<null | OnStartCallbackType<R>>(null);\n const onDownloadProgressCallback = useRef<null | OnProgressCallbackType>(null);\n const onUploadProgressCallback = useRef<null | OnProgressCallbackType>(null);\n\n // ******************\n // Listeners unmounting\n // ******************\n\n const lifecycleEvents = useRef<UseRequestEventsLifecycleMap>(new Map());\n const dataEvents = useRef<UseRequestEventsDataMap | null>(null);\n // Sending can outlive the component - the unmount cleanup never sees listeners attached after it ran\n const isMounted = useIsMounted();\n\n const removeLifecycleListener = (requestId: string) => {\n const event = lifecycleEvents.current.get(requestId);\n event?.unmount();\n lifecycleEvents.current.delete(requestId);\n };\n\n const clearLifecycleListeners = () => {\n const events = lifecycleEvents.current;\n const listeners = [...events.values()];\n listeners.forEach((value) => {\n value.unmount();\n });\n events.clear();\n pendingRequests.current.clear();\n };\n\n // ******************\n // Optimistic state\n // ******************\n\n // Rollback and invalidation are settled by the core - here we only deliver the context to the callbacks\n const optimisticResultsRef = useRef<Map<string, OptimisticCallbackResult<any>>>(new Map());\n // Requests which already got their last response - their removal from the queue is only a cleanup\n const settledRequests = useRef(new Set<string>());\n // Requests sent with their ids (useSubmit) which are submitted or in flight. The hook is loading as long as there\n // are any - also between two queued requests and when the requests have different keys.\n const pendingRequests = useRef(new Set<string>());\n // Queue which the loading and data listeners follow - the one of the latest request\n const listenedQueryKey = useRef<string | null>(null);\n\n // ******************\n // Response handlers\n // ******************\n\n const handleResponseCallbacks = (values: RequestResponseEventType<R>) => {\n const { success } = values.response;\n const { isOffline, isCanceled, willRetry } = values.details;\n const opt = optimisticResultsRef.current.get(values.requestId);\n const paramsWithContext = { ...values, mutationContext: opt?.context } as any;\n const isOfflineError = request.offline && isOffline && !success;\n\n if (isOfflineError) {\n logger.debug({ title: \"Performing offline error callback\", type: \"system\", extra: values });\n onOfflineErrorCallback.current?.(paramsWithContext);\n } else if (isCanceled) {\n logger.debug({ title: \"Performing abort callback\", type: \"system\", extra: values });\n onAbortCallback.current?.(paramsWithContext);\n } else if (success) {\n logger.debug({ title: \"Performing success callback\", type: \"system\", extra: values });\n onSuccessCallback.current?.(paramsWithContext);\n } else {\n logger.debug({ title: \"Performing error callback\", type: \"system\", extra: values });\n onErrorCallback.current?.(paramsWithContext);\n }\n onFinishedCallback.current?.(paramsWithContext);\n // Retried and offline requests respond again, their callbacks still need the context\n if (!willRetry && (!isOfflineError || isCanceled)) {\n optimisticResultsRef.current.delete(values.requestId);\n }\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n const handleGetLoadingEvent = (req: R) => {\n return ({ loading, request: eventRequest }: RequestLoadingEventType<RequestInstance>) => {\n // Loading events are emitted by the logical queryKey - skip requests of other scopes\n if (!isSameScope(eventRequest.scope, req.scope)) {\n return;\n }\n\n const isProcessing = getIsDataProcessing(req.cacheKey);\n\n // When we process the cache data, we don't want to change the loading state during it\n // This prevents the UI from flickering with { data: null, loading: false }\n if (isProcessing) {\n return;\n }\n\n const canDisableLoading =\n !loading &&\n !dispatcher.hasRunningRequests(scopeKey(req.queryKey, req.scope)) &&\n pendingRequests.current.size === 0;\n if (loading || canDisableLoading) {\n actions.setLoading(loading);\n }\n };\n };\n\n const handleDownloadProgress = (req: R) => {\n return (data: RequestProgressEventType<RequestInstance>) => {\n if (!isSameScope(data.request?.scope, req.scope)) {\n return;\n }\n onDownloadProgressCallback.current?.(data);\n };\n };\n\n const handleUploadProgress = (req: R) => {\n return (data: RequestProgressEventType<RequestInstance>) => {\n if (!isSameScope(data.request?.scope, req.scope)) {\n return;\n }\n onUploadProgressCallback.current?.(data);\n };\n };\n\n const handleRequestStart = (req: R) => {\n return (details: RequestEventType<R>) => {\n if (!isSameScope(details.request?.scope, req.scope)) {\n return;\n }\n onRequestStartCallback.current?.(details);\n };\n };\n const handleResponseStart = (req: R) => {\n return (details: RequestEventType<R>) => {\n if (!isSameScope(details.request?.scope, req.scope)) {\n return;\n }\n onResponseStartCallback.current?.(details);\n };\n };\n\n const handleResponse = (req: R) => {\n return (values: RequestResponseEventType<R>) => {\n if (!isSameScope(values.request?.scope, req.scope)) {\n return;\n }\n\n // This attempt is over - a retried request becomes pending again when its next attempt starts\n pendingRequests.current.delete(values.requestId);\n\n // Marked before the mapper runs - an async mapper answers after the dispatcher removed the request.\n // Failed attempts which are retried or kept for the connection to return respond once again.\n const { success } = values.response;\n const { isCanceled, isOffline, willRetry } = values.details;\n const willRespondAgain = !success && !isCanceled && (willRetry || (!!req.offline && isOffline));\n if (!willRespondAgain) {\n settledRequests.current.add(values.requestId);\n }\n\n // The loading listeners follow the queue of the latest request. A request sent earlier to another queue\n // (other params) is not heard by them, so when it is the last one, it ends the loading state here.\n const queryKey = scopeKey(req.queryKey, req.scope);\n const isLastRequest = pendingRequests.current.size === 0 && !dispatcher.hasRunningRequests(queryKey);\n if (isLastRequest && listenedQueryKey.current !== null && listenedQueryKey.current !== queryKey) {\n actions.setLoading(dispatcher.hasRunningRequests(listenedQueryKey.current));\n }\n\n // The mapper of the listened request - it can differ from the request of the current render\n const data = runResponseMapper(req, values.response);\n\n if (data instanceof Promise) {\n return (async () => {\n const response = (await data) as ResponseType<any, any, ExtractAdapterType<R>>;\n // The mapper can outlive the component - the unmount cleanup can't stop a response already being mapped\n if (!isMounted.current) {\n return;\n }\n handleResponseCallbacks({ ...values, response });\n })();\n }\n // Callbacks receive the same (mapped) response as the hook state\n return handleResponseCallbacks({\n ...values,\n response: (data || values.response) as ResponseType<any, any, ExtractAdapterType<R>>,\n });\n };\n };\n\n const handleRemove = ({ requestId, request: removedRequest }: RequestRemovedEventType<R>) => {\n // Removed before its last response - aborted with the hook, deleted or cleared from the queue. No response is\n // going to reach the listeners anymore, so the removal is what ends the request: the abort callback runs with\n // the same \"deleted\" response that `submit()` resolves with.\n if (!settledRequests.current.has(requestId) && lifecycleEvents.current.has(requestId)) {\n const timestamp = Date.now();\n handleResponseCallbacks({\n request: removedRequest,\n requestId,\n response: {\n data: null,\n error: getErrorMessage(\"deleted\") as ExtractErrorType<R>,\n status: null,\n success: false,\n extra: removedRequest.client.adapter.defaultExtra,\n requestTimestamp: timestamp,\n responseTimestamp: timestamp,\n },\n details: {\n retries: 0,\n isCanceled: true,\n isOffline: false,\n willRetry: false,\n addedTimestamp: timestamp,\n triggerTimestamp: timestamp,\n requestTimestamp: timestamp,\n responseTimestamp: timestamp,\n },\n });\n }\n settledRequests.current.delete(requestId);\n pendingRequests.current.delete(requestId);\n optimisticResultsRef.current.delete(requestId);\n removeLifecycleListener(requestId);\n };\n\n // ******************\n // Data Listeners\n // ******************\n\n const clearCacheDataListener = () => {\n dataEvents.current?.unmount();\n dataEvents.current = null;\n };\n\n const addCacheDataListener = (req: R) => {\n if (!isMounted.current) {\n return () => undefined;\n }\n\n // Data handlers\n // Core emits these events by the logical keys; the handlers skip events of other scopes\n const loadingUnmount = requestManager.events.onLoadingByQueue(req.queryKey, handleGetLoadingEvent(req));\n const getResponseUnmount = cache.events.onDataByKey<\n ExtractResponseType<R>,\n ExtractErrorType<R>,\n ExtractAdapterType<R>\n >(req.cacheKey, (cacheData) => {\n if (!isSameScope(cacheData.scope, req.scope)) {\n return;\n }\n setCacheData(cacheData);\n // Cache data brings the loading state of its own queue only - other requests of the hook can still be pending\n if (pendingRequests.current.size > 0) {\n actions.setLoading(true);\n }\n });\n\n const unmount = () => {\n loadingUnmount();\n getResponseUnmount();\n };\n\n clearCacheDataListener();\n dataEvents.current = { unmount };\n listenedQueryKey.current = scopeKey(req.queryKey, req.scope);\n\n return unmount;\n };\n\n // ******************\n // Lifecycle Listeners\n // ******************\n\n const addLifecycleListeners = (req: R, requestId?: string, optimisticResult?: OptimisticCallbackResult<any>) => {\n if (!isMounted.current) {\n return () => undefined;\n }\n\n /**\n * useFetch handles requesting by general keys\n * This makes it possible to deduplicate requests from different places and share data\n */\n if (!requestId) {\n // It's important to clear previously attached listeners to not cause some additional response/request\n // events to be triggered during lifecycle\n clearLifecycleListeners();\n const { queryKey, cacheKey } = req;\n const requestStartUnmount = requestManager.events.onRequestStartByQueue(queryKey, handleRequestStart(req));\n const responseStartUnmount = requestManager.events.onResponseStartByQueue(queryKey, handleResponseStart(req));\n const uploadUnmount = requestManager.events.onUploadProgressByQueue(queryKey, handleUploadProgress(req));\n const downloadUnmount = requestManager.events.onDownloadProgressByQueue(queryKey, handleDownloadProgress(req));\n const responseUnmount = requestManager.events.onResponseByCache(cacheKey, handleResponse(req));\n\n const unmount = () => {\n downloadUnmount();\n uploadUnmount();\n requestStartUnmount();\n responseStartUnmount();\n responseUnmount();\n };\n\n lifecycleEvents.current.set(queryKey, { unmount });\n\n return unmount;\n }\n /**\n * useSubmit handles requesting by requestIds, this makes it possible to track single requests\n */\n if (optimisticResult) {\n optimisticResultsRef.current.set(requestId, optimisticResult);\n }\n pendingRequests.current.add(requestId);\n const onRequestStart = handleRequestStart(req);\n const requestRemove = requestManager.events.onRemoveById(requestId, handleRemove);\n const requestStartUnmount = requestManager.events.onRequestStartById<R>(requestId, (details) => {\n // Every attempt, also a retry or one postponed until the connection returned\n pendingRequests.current.add(requestId);\n onRequestStart(details);\n });\n const responseStartUnmount = requestManager.events.onResponseStartById(requestId, handleResponseStart(req));\n const responseUnmount = requestManager.events.onResponseById(requestId, handleResponse(req));\n const uploadUnmount = requestManager.events.onUploadProgressById(requestId, handleUploadProgress(req));\n const downloadUnmount = requestManager.events.onDownloadProgressById(requestId, handleDownloadProgress(req));\n\n const unmount = () => {\n requestRemove();\n downloadUnmount();\n uploadUnmount();\n requestStartUnmount();\n responseStartUnmount();\n responseUnmount();\n };\n\n lifecycleEvents.current.set(requestId, { unmount });\n\n return unmount;\n };\n\n // ******************\n // Abort\n // ******************\n\n const abort = () => {\n const currentRequest = requestRef.current;\n const currentDispatcher = dispatcherRef.current;\n const ak = scopeKey(currentRequest.abortKey, currentRequest.scope);\n const requests = currentDispatcher.getAllRunningRequests();\n requests.forEach((requestData) => {\n const reqAk = scopeKey(requestData.request.abortKey, requestData.request.scope);\n if (reqAk === ak) {\n const qk = scopeKey(requestData.request.queryKey, requestData.request.scope);\n currentDispatcher.delete(qk, requestData.requestId, reqAk);\n }\n });\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n /**\n * On unmount we want to clear all the listeners to prevent memory leaks\n */\n useWillUnmount(() => {\n // Unmount listeners\n clearLifecycleListeners();\n clearCacheDataListener();\n });\n\n // Callbacks setters and abort work on refs only, so they are created once - their identity is stable between the renders\n const callbacksRef = useRef<UseRequestEventsReturnType<R>[0] | null>(null);\n if (!callbacksRef.current) {\n callbacksRef.current = {\n abort,\n onSuccess: (callback: OnSuccessCallbackType<R>) => {\n onSuccessCallback.current = callback;\n },\n onError: (callback: OnErrorCallbackType<R>) => {\n onErrorCallback.current = callback;\n },\n onAbort: (callback: OnErrorCallbackType<R>) => {\n onAbortCallback.current = callback;\n },\n onOfflineError: (callback: OnErrorCallbackType<R>) => {\n onOfflineErrorCallback.current = callback;\n },\n onFinished: (callback: OnFinishedCallbackType<R>) => {\n onFinishedCallback.current = callback;\n },\n onRequestStart: (callback: OnStartCallbackType<R>) => {\n onRequestStartCallback.current = callback;\n },\n onResponseStart: (callback: OnStartCallbackType<R>) => {\n onResponseStartCallback.current = callback;\n },\n onDownloadProgress: (callback: OnProgressCallbackType) => {\n onDownloadProgressCallback.current = callback;\n },\n onUploadProgress: (callback: OnProgressCallbackType) => {\n onUploadProgressCallback.current = callback;\n },\n };\n }\n\n return [\n callbacksRef.current,\n {\n addCacheDataListener,\n clearCacheDataListener,\n addLifecycleListeners,\n removeLifecycleListener,\n clearLifecycleListeners,\n },\n ];\n};\n","import type { UseTrackedStateType } from \"./use-tracked-state.types\";\n\nexport const initialState: UseTrackedStateType = {\n data: null,\n error: null,\n status: null,\n extra: {},\n success: false,\n loading: false,\n retries: 0,\n responseTimestamp: null,\n requestTimestamp: null,\n};\n","import type {\n CacheValueType,\n ClientInstance,\n EmptyTypes,\n HydrateDataType,\n HydrationOptions,\n NullableType,\n} from \"@hyper-fetch/core\";\nimport { parseResponse, scopeKey } from \"@hyper-fetch/core\";\n\nimport type { HydratedEntry, HydrateOptionsType } from \"./hydrate.types\";\n\n/**\n * Items already written to the cache (or skipped because the cache held newer data), per client.\n * Once an item is consumed the cache is the source of truth, so a hook mounted after `client.clear()`\n * does not get the old server snapshot back.\n */\nconst consumedItems = new WeakMap<ClientInstance, WeakSet<HydrateDataType>>();\n\nconst getConsumed = (client: ClientInstance) => {\n let consumed = consumedItems.get(client);\n if (!consumed) {\n consumed = new WeakSet();\n consumedItems.set(client, consumed);\n }\n return consumed;\n};\n\nexport const isConsumed = (client: ClientInstance, item: HydrateDataType) => {\n return getConsumed(client).has(item);\n};\n\nexport const markConsumed = (client: ClientInstance, item: HydrateDataType) => {\n getConsumed(client).add(item);\n};\n\n/**\n * Resolves the config of a single item exactly like `client.hydrate()` does\n */\nconst resolveConfig = (item: HydrateDataType, options?: HydrateOptionsType) => {\n const { cacheKey, scope, response: _response, ...fallbackOptions } = item;\n const defaults = { cache: true, override: true } satisfies Partial<HydrationOptions>;\n const config =\n typeof options === \"function\"\n ? { ...defaults, ...fallbackOptions, ...options(item) }\n : { ...defaults, ...fallbackOptions, ...options };\n\n return { ...config, cacheKey, scope };\n};\n\nconst getResponseTimestamp = (value: NullableType<{ responseTimestamp?: number | null }>, fallback = 0) => {\n const timestamp = Number(value?.responseTimestamp);\n return Number.isFinite(timestamp) ? timestamp : fallback;\n};\n\n/**\n * Turns dehydrated items into the values they will have in the cache, keyed by storage key.\n * The last item wins when the same key is passed twice.\n */\nexport const getHydratedEntries = (\n client: ClientInstance,\n data: NullableType<(HydrateDataType | EmptyTypes)[]>,\n options?: HydrateOptionsType,\n): Map<string, HydratedEntry> => {\n const entries = new Map<string, HydratedEntry>();\n\n data?.forEach((item) => {\n if (!item) {\n return;\n }\n\n const config = resolveConfig(item, options);\n const response = parseResponse(item.response);\n const storageKey = scopeKey(config.cacheKey, config.scope ?? null);\n\n // Mirrors the value created by `cache.set()`, so the first render matches the state after the write\n const value = {\n ...response,\n cacheKey: config.cacheKey,\n scope: config.scope ?? null,\n staleTime: config.staleTime,\n cacheTime: config.cacheTime,\n version: client.cache.version,\n cached: !!config.cache,\n } as CacheValueType;\n\n entries.set(storageKey, {\n item,\n storageKey,\n value,\n override: config.override !== false,\n timestamp: getResponseTimestamp(response, item.timestamp ?? 0),\n });\n });\n\n return entries;\n};\n\n/**\n * Decides whether the hydrated value should be used instead of the cached one.\n * Newer data always wins; with `override: false` existing cache data is kept.\n */\nexport const shouldUseHydratedValue = (cacheData: NullableType<CacheValueType>, entry: HydratedEntry): boolean => {\n if (!cacheData) {\n return true;\n }\n if (!entry.override) {\n return false;\n }\n return entry.timestamp > getResponseTimestamp(cacheData);\n};\n\n/**\n * Picks the data a hook should start with: cached data, unless the hydrated data is newer\n */\nexport const pickInitialCacheData = <T extends CacheValueType>(\n cacheData: NullableType<T>,\n entry: NullableType<HydratedEntry>,\n): NullableType<T> => {\n if (!entry || !shouldUseHydratedValue(cacheData, entry)) {\n return cacheData;\n }\n return entry.value as T;\n};\n","import React, { useContext, useEffect, useLayoutEffect, useMemo, useRef } from \"react\";\n\nimport type { HydrateProps, HydrationContextType } from \"./hydrate.types\";\nimport { getHydratedEntries, isConsumed, markConsumed, shouldUseHydratedValue } from \"./hydrate.utils\";\n\nconst HydrationContext = React.createContext<HydrationContextType | null>(null);\n\n// Layout effects do not run on the server; on the client they run before any passive effect of the tree\nconst useIsomorphicLayoutEffect = typeof window !== \"undefined\" ? useLayoutEffect : useEffect;\n\n/**\n * Hydrates the client cache with data fetched on the server.\n *\n * - Hooks below it render with the hydrated data on the first render, also during server rendering.\n * - On the client the data is written to the cache before the hooks mount, so fresh data is not refetched.\n * - Newer cache data is never replaced by an older snapshot.\n * - It can be nested and rendered conditionally; every `Hydrate` serves only its own client.\n */\nexport const Hydrate = ({ client, data, options, children }: HydrateProps) => {\n const parent = useContext(HydrationContext);\n\n const entries = useMemo(() => getHydratedEntries(client, data, options), [client, data, options]);\n\n // Read through a ref, so the context value stays stable when only the entries change (e.g. inline options)\n // and memoized children do not re-render. Hooks read the context only on their first render.\n const entriesRef = useRef(entries);\n entriesRef.current = entries;\n\n useIsomorphicLayoutEffect(() => {\n // Server mode cache does not store unscoped data - the context keeps serving it instead\n if (client.mode === \"server\") {\n return;\n }\n\n entries.forEach((entry) => {\n if (isConsumed(client, entry.item)) {\n return;\n }\n markConsumed(client, entry.item);\n\n const cacheData = client.cache.get(entry.storageKey);\n if (!shouldUseHydratedValue(cacheData, entry)) {\n return;\n }\n\n client.hydrate([entry.item], options);\n });\n }, [client, entries, options]);\n\n const value = useMemo<HydrationContextType>(\n () => ({\n get: (targetClient, storageKey) => {\n if (targetClient === client) {\n const entry = entriesRef.current.get(storageKey);\n if (entry) {\n return isConsumed(client, entry.item) ? undefined : entry;\n }\n }\n return parent?.get(targetClient, storageKey);\n },\n }),\n [client, parent],\n );\n\n return <HydrationContext.Provider value={value}>{children}</HydrationContext.Provider>;\n};\n\n/**\n * Access to the closest hydration data\n * @internal\n */\nexport const useHydration = (): HydrationContextType | null => {\n return useContext(HydrationContext);\n};\n","/**\n * Check if value is empty\n * @param value any object or primitive\n * @returns true when value is empty\n */\nexport const isEmpty = (value?: unknown): boolean => {\n const valueType = Object.prototype.toString.call(value);\n if (Array.isArray(value)) {\n return value.length === 0;\n }\n if (typeof value === \"object\" && value !== null && valueType === \"[object Object]\") {\n return Object.keys(value).length === 0;\n }\n return false;\n};\n\n/**\n * Allow to deep compare any passed values\n * @param firstValue unknown\n * @param secondValue unknown\n * @returns true when elements are equal\n */\nexport const isEqual = (firstValue?: unknown, secondValue?: unknown): boolean => {\n // Nulls (objects), and other primitives\n if (firstValue === secondValue) {\n return true;\n }\n\n try {\n const firstValueType = Object.prototype.toString.call(firstValue);\n const secondValueType = Object.prototype.toString.call(secondValue);\n\n const firstType = typeof firstValue;\n const secondType = typeof secondValue;\n\n const isType = (type: unknown) => firstType === type && secondType === type;\n const isTypeValue = (type: unknown) => firstValueType === type && secondValueType === type;\n\n // Compared types are different\n if (firstValueType !== secondValueType) {\n return false;\n }\n\n // NaN\n if (isType(\"number\") && Number.isNaN(firstValue) && Number.isNaN(secondValue)) {\n return true;\n }\n\n // Empty Array or Object\n if (isEmpty(firstValue) && isEmpty(secondValue)) {\n return true;\n }\n\n // Array\n if (Array.isArray(firstValue) && Array.isArray(secondValue)) {\n if (firstValue.length !== secondValue.length) {\n return false;\n }\n\n return !firstValue.some((element, i) => !isEqual(element, secondValue[i]));\n }\n\n // Object\n if (isType(\"object\") && isTypeValue(\"[object Object]\")) {\n if (Object.keys(firstValue as object).length !== Object.keys(secondValue as object).length) {\n return false;\n }\n\n return !Object.entries(firstValue as object).some(\n ([key, value]) => !isEqual(value, (secondValue as Record<string, unknown>)[key]),\n );\n }\n\n // Date\n if (firstValue instanceof Date && secondValue instanceof Date) {\n return +firstValue === +secondValue;\n }\n\n // undefined, string, number, bool\n return firstValue === secondValue;\n } catch (error) {\n console.error(error);\n return false;\n }\n};\n","export const getBounceData = (bounceData: {\n reset: () => void;\n active: boolean;\n}): { reset: () => void; active: boolean } => {\n return {\n ...bounceData,\n // oxlint-disable-next-line unicorn/no-useless-spread\n ...{ throttle: undefined, debounce: undefined },\n };\n};\n","/**\n * Wraps a plain object in a Proxy that calls `setRenderKey` when tracked properties are accessed.\n * Unlike getter-based tracking, Proxy-wrapped objects display their actual values in console.log,\n * making debugging significantly easier while preserving field-level dependency tracking.\n */\nexport const createTrackedProxy = <T extends Record<string, unknown>, K extends string>(\n target: T,\n trackedKeys: readonly K[],\n setRenderKey: (key: K) => void,\n): T => {\n return new Proxy(target, {\n get(obj, prop, receiver) {\n if (typeof prop === \"string\" && trackedKeys.includes(prop as K)) {\n setRenderKey(prop as K);\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n};\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport type {\n CacheValueType,\n NullableType,\n RequestInstance,\n ExtractResponseType,\n ExtractErrorType,\n ExtractAdapterResolvedType,\n Dispatcher,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ResponseDetailsType,\n ExtractAdapterStatusType,\n ResponseType,\n} from \"@hyper-fetch/core\";\nimport { runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport type { UseTrackedStateType } from \"helpers\";\nimport { initialState } from \"helpers\";\nimport type { HydratedEntry } from \"hydrate/hydrate.types\";\nimport { pickInitialCacheData } from \"hydrate/hydrate.utils\";\n\n/**\n * Extracts the \"identity\" portion of a cache key (method + endpoint with resolved params),\n * stripping the query params part. Cache keys follow the format: `method_endpoint_queryParams`.\n */\nconst getCacheKeyIdentity = (cacheKey: string): string => {\n const lastUnderscoreIndex = cacheKey.lastIndexOf(\"_\");\n if (lastUnderscoreIndex === -1) {\n return cacheKey;\n }\n return cacheKey.substring(0, lastUnderscoreIndex);\n};\n\n/**\n * Identity of the requested resource - method and endpoint with resolved params, without the query params.\n * Two requests with the same identity ask for the same resource (e.g. another page or filter of one list).\n */\nexport const getRequestIdentity = (request: Pick<RequestInstance, \"method\" | \"endpoint\" | \"scope\">): string => {\n return `${request.scope ?? \"\"}_${String(request.method)}_${String(request.endpoint)}`;\n};\n\n/**\n * Determines whether state should be cleared when the cache key changes.\n *\n * - `\"clean\"` — always clear\n * - `\"preserve\"` — never clear\n * - `\"auto\"` — clear when the resource identity changed (URL params), preserve when only query params changed\n *\n * In the \"auto\" mode the identity is read from the cache keys, which is not reliable for custom cache keys\n * and for query params containing underscores - compare the requests with `getRequestIdentity` when they are available.\n */\nexport const getShouldClearState = (\n mode: \"auto\" | \"preserve\" | \"clean\",\n oldCacheKey: string,\n newCacheKey: string,\n): boolean => {\n if (oldCacheKey === newCacheKey) {\n return false;\n }\n\n if (mode === \"clean\") {\n return true;\n }\n if (mode === \"preserve\") {\n return false;\n }\n\n // \"auto\" — compare the identity part (method + endpoint with params)\n return getCacheKeyIdentity(oldCacheKey) !== getCacheKeyIdentity(newCacheKey);\n};\n\nexport const getDetailsState = (\n state?: UseTrackedStateType<RequestInstance>,\n details?: Partial<ResponseDetailsType>,\n): ResponseDetailsType => {\n return {\n retries: state?.retries || 0,\n isCanceled: false,\n isOffline: false,\n willRetry: false,\n addedTimestamp: Date.now(),\n triggerTimestamp: Date.now(),\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n ...details,\n };\n};\n\nexport const isStaleCacheData = (staleTime: number, staleTimestamp: NullableType<Date | number>) => {\n if (!staleTimestamp) {\n return true;\n }\n return Date.now() > +staleTimestamp + staleTime;\n};\n\nexport const getValidCacheData = <T extends RequestInstance>(\n request: T,\n initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>,\n cacheData: NullableType<CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>>,\n): CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>> | null => {\n if (cacheData) {\n return cacheData;\n }\n\n if (initialResponse) {\n return {\n data: null,\n error: null,\n status: null,\n success: true,\n extra: null,\n cached: !!request.cache,\n ...(initialResponse as Partial<ExtractAdapterResolvedType<T>>),\n ...getDetailsState(),\n staleTime: 1000,\n version: request.client.cache.version,\n cacheKey: request.cacheKey,\n scope: request.scope,\n cacheTime: request.cacheTime,\n requestTimestamp: initialResponse?.requestTimestamp ?? Date.now(),\n responseTimestamp: initialResponse?.responseTimestamp ?? Date.now(),\n };\n }\n\n return null;\n};\n\nexport const getTimestamp = (timestamp?: NullableType<number | Date>) => {\n return timestamp ? new Date(timestamp) : null;\n};\n\nexport const getIsInitiallyLoading = <T extends RequestInstance>({\n queryKey,\n dispatcher,\n hasState,\n revalidate,\n disabled,\n}: {\n queryKey: string;\n dispatcher: Dispatcher<ExtractAdapterType<T>>;\n hasState: boolean;\n revalidate?: boolean;\n disabled?: boolean;\n}) => {\n if (!revalidate && hasState) {\n return false;\n }\n\n const queue = dispatcher.getQueue(queryKey);\n const isInitiallyLoading = dispatcher.hasRunningRequests(queryKey) || (!queue.stopped && disabled === false);\n\n return isInitiallyLoading;\n};\n\nexport const getInitialState = <T extends RequestInstance>({\n initialResponse,\n dispatcher,\n request,\n disabled,\n revalidate,\n hydratedEntry,\n}: {\n initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>;\n dispatcher: Dispatcher<ExtractAdapterType<T>>;\n request: T;\n disabled?: boolean; // useFetch only\n revalidate?: boolean; // useFetch only\n /** Data from the closest `Hydrate` that was not written to the cache yet */\n hydratedEntry?: NullableType<HydratedEntry>;\n}): UseTrackedStateType<T> => {\n const { client, cacheKey } = request;\n const { cache } = client;\n\n const cacheData = pickInitialCacheData(\n cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopeKey(cacheKey, request.scope)),\n hydratedEntry,\n );\n const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);\n\n const initialLoading = getIsInitiallyLoading({\n queryKey: scopeKey(request.queryKey, request.scope),\n dispatcher,\n disabled,\n revalidate,\n hasState: !!cacheState,\n });\n\n if (cacheState) {\n const mappedData =\n runResponseMapper(request, cacheState as ResponseType<any, any, ExtractAdapterType<T>>) || cacheState;\n if (mappedData instanceof Promise) {\n // For the async mapper we cannot return async values\n // So we have return the initial state instead\n return initialState;\n }\n return {\n data: mappedData.data,\n error: mappedData.error,\n status: mappedData.status as ExtractAdapterStatusType<ExtractAdapterType<T>>,\n success: mappedData.success,\n extra: (mappedData.extra || client.adapter.defaultExtra) as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: cacheState.retries,\n requestTimestamp: getTimestamp(cacheState.requestTimestamp),\n responseTimestamp: getTimestamp(cacheState.responseTimestamp),\n loading: initialLoading,\n };\n }\n\n return {\n data: initialState.data,\n error: initialState.error,\n status: initialState.status as ExtractAdapterStatusType<ExtractAdapterType<T>>,\n success: initialState.success,\n extra: request.client.adapter.defaultExtra as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: initialState.retries,\n requestTimestamp: getTimestamp(initialState.requestTimestamp),\n responseTimestamp: getTimestamp(initialState.responseTimestamp),\n loading: initialLoading,\n };\n};\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type {\n ExtractErrorType,\n CacheValueType,\n ExtractResponseType,\n RequestInstance,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ResponseType,\n} from \"@hyper-fetch/core\";\nimport { replaceEqualDeep, runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport { useHydration } from \"hydrate/hydrate\";\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport { isEqual } from \"utils\";\n\nimport type {\n UseTrackedStateActions,\n UseTrackedStateType,\n UseTrackedStateProps,\n UseTrackedStateReturn,\n UseTrackedStateResponseDetails,\n} from \"./use-tracked-state.types\";\nimport {\n getInitialState,\n getIsInitiallyLoading,\n getRequestIdentity,\n getShouldClearState,\n getValidCacheData,\n isStaleCacheData,\n} from \"./use-tracked-state.utils\";\n\n/**\n *\n * @param request\n * @param initialResponse\n * @param dispatcher\n * @param dependencies\n * @internal\n */\nexport const useTrackedState = <T extends RequestInstance, TData = ExtractResponseType<T>>({\n request,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n keepPreviousData = \"auto\",\n disabled,\n revalidate,\n select,\n structuralSharing = true,\n}: UseTrackedStateProps<T, TData>): UseTrackedStateReturn<T, TData> => {\n const { client, cacheKey, queryKey, staleTime } = request;\n const { cache } = client;\n // Cache storage and dispatcher queues are keyed with the scope of the request\n const scopedCacheKey = scopeKey(cacheKey, request.scope);\n const scopedQueryKey = scopeKey(queryKey, request.scope);\n const identity = getRequestIdentity(request);\n const hydration = useHydration();\n\n const state = useRef<UseTrackedStateType<T, TData>>(null as unknown as UseTrackedStateType<T, TData>);\n const renderKeys = useRef<(keyof UseTrackedStateType<T, TData>)[]>([]);\n const isProcessingData = useRef(\"\");\n const previousCacheKey = useRef(scopedCacheKey);\n const previousIdentity = useRef(identity);\n // State created from scratch can be filled with the initialResponse, the preserved one (keepPreviousData) can not\n const isFreshState = useRef(true);\n\n // ******************\n // Data selection\n // ******************\n\n const selectRef = useRef(select);\n selectRef.current = select;\n const appliedSelect = useRef(select);\n // Response data before applying the selector - allows to re-run it when the selector changes\n const rawData = useRef<ExtractResponseType<T> | null>(null);\n // Data set with the setData action has the selected shape and should not get re-selected\n const isLocalData = useRef(false);\n const selectError = useRef<{ error: unknown } | null>(null);\n const responseDetails = useRef<UseTrackedStateResponseDetails | null>(null);\n\n const selectData = (data: ExtractResponseType<T> | null, previousData: TData | null = null): TData | null => {\n if (!selectRef.current || data === null || data === undefined) {\n return data as TData | null;\n }\n const selected = selectRef.current(data);\n return structuralSharing ? replaceEqualDeep(previousData, selected) : selected;\n };\n\n const getSelectedState = (newState: UseTrackedStateType<T>): UseTrackedStateType<T, TData> => {\n rawData.current = newState.data;\n isLocalData.current = false;\n responseDetails.current = null;\n appliedSelect.current = selectRef.current;\n return { ...newState, data: selectData(newState.data, state.current?.data) };\n };\n\n if (!state.current) {\n const hydratedEntry = hydration?.get(client, scopeKey(cacheKey, request.scope));\n state.current = getSelectedState(\n getInitialState({ initialResponse, dispatcher, request, disabled, hydratedEntry }),\n );\n }\n // Request key changed - the state is switched during the render, so the data of the previous key\n // is never returned for the new one (unless it is kept on purpose with keepPreviousData)\n else if (previousCacheKey.current !== scopedCacheKey) {\n // \"auto\" mode keeps the state of the same resource (only its query params changed).\n // Resources are compared by the requests, cache keys can't be parsed reliably.\n const shouldClear =\n keepPreviousData === \"auto\"\n ? previousIdentity.current !== identity\n : getShouldClearState(keepPreviousData, previousCacheKey.current, scopedCacheKey);\n previousCacheKey.current = scopedCacheKey;\n previousIdentity.current = identity;\n\n const hasCacheData = !!cache.get(scopedCacheKey);\n isFreshState.current = hasCacheData || shouldClear;\n\n if (isFreshState.current) {\n const hydratedEntry = hydration?.get(client, scopedCacheKey);\n state.current = getSelectedState(\n getInitialState({ initialResponse, dispatcher, request, disabled, revalidate, hydratedEntry }),\n );\n }\n // Otherwise the previous state stays until the response of the new key arrives (#126)\n }\n\n // Selector failed while processing incoming data - surface it to the closest error boundary\n if (selectError.current) {\n const { error } = selectError.current;\n selectError.current = null;\n throw error;\n }\n\n // Selector changed (e.g. it closes over a new prop) - re-run it against the latest response data\n if (appliedSelect.current !== select && !isLocalData.current) {\n appliedSelect.current = select;\n state.current.data = selectData(rawData.current, state.current.data);\n }\n\n // ******************\n // useSyncExternalStore\n // ******************\n\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n // ******************\n // Utils\n // ******************\n\n const getStaleStatus = (): boolean => {\n const cacheData = cache.get(scopedCacheKey);\n // Invalidation marks the cache entry with the stale time of 0 - it has to be fetched again,\n // also when no hook was mounted to refetch it at the moment of the invalidation\n const isInvalidated = cacheData?.staleTime === 0;\n return !cacheData || isInvalidated || isStaleCacheData(staleTime, cacheData?.responseTimestamp);\n };\n\n // ******************\n // Dependency Tracking\n // ******************\n\n const renderKeyTrigger = (keys: (keyof UseTrackedStateType<T, TData>)[]) => {\n const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));\n if (shouldRerender) {\n emitChange();\n }\n };\n\n const setRenderKey = (renderKey: keyof UseTrackedStateType<T, TData>) => {\n if (!renderKeys.current.includes(renderKey)) {\n renderKeys.current.push(renderKey);\n }\n };\n\n // ******************\n // Cache initialization\n // ******************\n\n useDidUpdate(\n () => {\n // The state of the key is already set during the render. Here we pick up the changes done to the cache\n // between the render and the effect and the data that requires asynchronous mapping.\n const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopedCacheKey);\n // Initial response is a placeholder for the empty state only - it never replaces the data kept from the previous key\n const cacheState =\n cacheData || (isFreshState.current ? getValidCacheData<T>(request, initialResponse, null) : null);\n\n if (cacheState) {\n state.current.loading = getIsInitiallyLoading({\n queryKey: scopedQueryKey,\n dispatcher,\n disabled,\n revalidate,\n hasState: true,\n });\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n setCacheData(cacheState);\n }\n // When state is preserved and no cache exists (e.g. query param change in \"auto\" mode),\n // don't update loading on the ref — let the dispatcher's loading event handle it (#126)\n },\n [scopedCacheKey, scopedQueryKey],\n true,\n );\n\n // ******************\n // Turn off dependency tracking\n // ******************\n\n useDidUpdate(\n () => {\n const handleDependencyTracking = () => {\n if (!dependencyTracking) {\n Object.keys(state.current).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0]));\n }\n };\n\n handleDependencyTracking();\n },\n [dependencyTracking],\n true,\n );\n\n // ******************\n // Cache data handler\n // ******************\n\n const handleCompare = (firstValue: unknown, secondValue: unknown) => {\n if (Object.is(firstValue, secondValue)) {\n return true;\n }\n if (typeof deepCompare === \"function\") {\n return deepCompare(firstValue, secondValue);\n }\n if (deepCompare) {\n return isEqual(firstValue, secondValue);\n }\n return false;\n };\n\n const handleCacheData = (\n cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>,\n ) => {\n rawData.current = cacheData.data;\n isLocalData.current = false;\n appliedSelect.current = selectRef.current;\n responseDetails.current = {\n willRetry: !!cacheData.willRetry,\n isCanceled: !!cacheData.isCanceled,\n isOffline: !!cacheData.isOffline,\n };\n\n let data: TData | null;\n try {\n data = selectData(cacheData.data, state.current.data);\n } catch (error) {\n // Never throw inside of the cache events - rethrow it on render instead\n selectError.current = { error };\n emitChange();\n return;\n }\n\n const newStateValues: UseTrackedStateType<T, TData> = {\n data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: cacheData.retries,\n responseTimestamp: new Date(cacheData.responseTimestamp),\n requestTimestamp: new Date(cacheData.requestTimestamp),\n loading: dispatcher.hasRunningRequests(scopedQueryKey),\n };\n\n const nextState: UseTrackedStateType<T, TData> = { ...state.current };\n const changedKeys = (Object.keys(newStateValues) as (keyof UseTrackedStateType<T, TData>)[]).filter((key) => {\n const isEqualValue = handleCompare(state.current[key], newStateValues[key]);\n // Equal values keep their previous reference, so they stay stable between renders\n if (!isEqualValue) {\n (nextState as Record<string, unknown>)[key] = newStateValues[key];\n }\n return !isEqualValue;\n });\n\n state.current = nextState;\n\n renderKeyTrigger(changedKeys);\n };\n\n const setIsDataProcessing = ({\n processingCacheKey,\n isProcessing,\n }: {\n processingCacheKey: string;\n isProcessing: boolean;\n }) => {\n if (isProcessing) {\n isProcessingData.current = processingCacheKey;\n }\n // Do not turn off other keys processing\n else if (isProcessingData.current === cacheKey) {\n isProcessingData.current = \"\";\n }\n };\n\n const getIsDataProcessing = (processingCacheKey: string) => {\n return isProcessingData.current === processingCacheKey;\n };\n\n const setCacheData = (\n cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>,\n ): Promise<void> | void => {\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: true });\n const data = runResponseMapper(request, cacheData as ResponseType<any, any, ExtractAdapterType<T>>) || cacheData;\n\n if (data instanceof Promise) {\n return (async () => {\n const promiseData = await data;\n handleCacheData({ ...cacheData, ...promiseData } as CacheValueType<\n ExtractResponseType<T>,\n ExtractErrorType<T>,\n ExtractAdapterType<T>\n >);\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: false });\n })();\n }\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: false });\n return handleCacheData({ ...cacheData, ...data } as CacheValueType<\n ExtractResponseType<T>,\n ExtractErrorType<T>,\n ExtractAdapterType<T>\n >);\n };\n\n // ******************\n // Actions\n // ******************\n\n // Actions work on refs only, so they are created once - their identity is stable between the renders\n const actionsRef = useRef<UseTrackedStateActions<T, TData> | null>(null);\n if (!actionsRef.current) {\n actionsRef.current = {\n setData: (data) => {\n isLocalData.current = true;\n state.current.data = data instanceof Function ? data(state.current.data ?? null) : data;\n renderKeyTrigger([\"data\"]);\n },\n setError: (error) => {\n state.current.error = error instanceof Function ? error(state.current.error ?? null) : error;\n renderKeyTrigger([\"error\"]);\n },\n setLoading: (loading) => {\n const value = loading instanceof Function ? loading(state.current.loading) : loading;\n if (value === state.current.loading) {\n return;\n }\n state.current.loading = value;\n renderKeyTrigger([\"loading\"]);\n },\n setStatus: (status) => {\n const value = status instanceof Function ? status(state.current.status ?? null) : status;\n if (value === state.current.status) {\n return;\n }\n state.current.status = value;\n renderKeyTrigger([\"status\"]);\n },\n setSuccess: (success) => {\n const value = success instanceof Function ? success(state.current.success || false) : success;\n if (value === state.current.success) {\n return;\n }\n state.current.success = value;\n renderKeyTrigger([\"success\"]);\n },\n setExtra: (extra) => {\n const value = extra instanceof Function ? extra(state.current.extra) : extra;\n if (value === state.current.extra) {\n return;\n }\n state.current.extra = value;\n renderKeyTrigger([\"extra\"]);\n },\n setRetries: (retries) => {\n const value = retries instanceof Function ? retries(state.current.retries || 0) : retries;\n if (value === state.current.retries) {\n return;\n }\n state.current.retries = value;\n renderKeyTrigger([\"retries\"]);\n },\n setResponseTimestamp: (timestamp) => {\n const value = timestamp instanceof Function ? timestamp(state.current.responseTimestamp) : timestamp;\n if (value === state.current.responseTimestamp) {\n return;\n }\n const getTimestamp = (prev: Date | null) => {\n return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;\n };\n\n state.current.responseTimestamp = getTimestamp(state.current.responseTimestamp);\n renderKeyTrigger([\"responseTimestamp\"]);\n },\n setRequestTimestamp: (timestamp) => {\n const value = timestamp instanceof Function ? timestamp(state.current.requestTimestamp) : timestamp;\n if (value === state.current.requestTimestamp) {\n return;\n }\n const getTimestamp = (prev: Date | null) => {\n return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;\n };\n\n state.current.requestTimestamp = getTimestamp(state.current.requestTimestamp);\n renderKeyTrigger([\"requestTimestamp\"]);\n },\n clearState: () => {\n rawData.current = null;\n isLocalData.current = false;\n responseDetails.current = null;\n state.current = {\n data: null,\n error: null,\n loading: false,\n status: null,\n success: false,\n extra: client.adapter.defaultExtra,\n retries: 0,\n responseTimestamp: null,\n requestTimestamp: null,\n } as UseTrackedStateType<T, TData>;\n renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T, TData>)[]);\n },\n };\n }\n const actions = actionsRef.current;\n\n return [\n state.current,\n actions,\n {\n setRenderKey,\n setCacheData,\n getStaleStatus,\n getIsDataProcessing,\n selectData: (data) => selectData(data, state.current.data),\n getResponseDetails: () => responseDetails.current,\n },\n ];\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { SocketInstance, ExtractSocketExtraType } from \"@hyper-fetch/sockets\";\nimport type { UseSocketStateType, UseSocketStateProps } from \"helpers\";\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\n\nexport const useSocketState = <DataType, Socket extends SocketInstance>(\n socket: Socket,\n { dependencyTracking }: UseSocketStateProps,\n) => {\n const onDisconnectCallback = useRef<null | VoidFunction>(null);\n const onErrorCallback = useRef<null | ((event: any) => void)>(null);\n const onConnectedCallback = useRef<null | VoidFunction>(null);\n const onConnectingCallback = useRef<null | VoidFunction>(null);\n const onReconnectingCallback = useRef<null | ((data: { attempts: number }) => void)>(null);\n const onReconnectingFailedCallback = useRef<null | ((data: { attempts: number }) => void)>(null);\n\n const state = useRef<UseSocketStateType<Socket, DataType>>({\n data: null,\n extra: null,\n connected: socket.adapter.connected,\n connecting: socket.adapter.connecting,\n timestamp: null,\n });\n const renderKeys = useRef<(keyof UseSocketStateType<Socket, DataType>)[]>([]);\n\n // ******************\n // useSyncExternalStore\n // ******************\n\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n // ******************\n // Dependency Tracking\n // ******************\n\n const renderKeyTrigger = (keys: (keyof UseSocketStateType<Socket, DataType>)[]) => {\n const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));\n if (shouldRerender) {emitChange();}\n };\n\n const setRenderKey = (renderKey: keyof UseSocketStateType<Socket, DataType>) => {\n if (!renderKeys.current.includes(renderKey)) {\n renderKeys.current.push(renderKey);\n }\n };\n\n // ******************\n // Turn off dependency tracking\n // ******************\n\n useDidUpdate(\n () => {\n const handleDependencyTracking = () => {\n if (!dependencyTracking) {\n Object.keys(state.current).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0]));\n }\n };\n\n handleDependencyTracking();\n },\n [dependencyTracking],\n true,\n );\n\n // ******************\n // Actions\n // ******************\n\n const actions = {\n setData: (data: DataType | null) => {\n state.current.data = data;\n renderKeyTrigger([\"data\"]);\n },\n setExtra: (extra: ExtractSocketExtraType<Socket> | null) => {\n state.current.extra = extra;\n renderKeyTrigger([\"extra\"]);\n },\n setConnected: (connected: boolean) => {\n state.current.connected = connected;\n renderKeyTrigger([\"connected\"]);\n },\n setConnecting: (connecting: boolean) => {\n state.current.connecting = connecting;\n renderKeyTrigger([\"connecting\"]);\n },\n setTimestamp: (timestamp: number | null) => {\n state.current.timestamp = timestamp;\n renderKeyTrigger([\"timestamp\"]);\n },\n clearState: () => {\n state.current = {\n data: null,\n extra: null,\n connected: false,\n connecting: false,\n timestamp: null,\n };\n renderKeyTrigger(Object.keys(state.current) as (keyof UseSocketStateType<Socket, DataType>)[]);\n },\n };\n\n const callbacks = {\n onConnected: (callback: VoidFunction) => {\n onConnectedCallback.current = callback;\n },\n onDisconnected: (callback: VoidFunction) => {\n onDisconnectCallback.current = callback;\n },\n onError: <ErrorType = Event>(callback: (event: ErrorType) => void) => {\n onErrorCallback.current = callback;\n },\n onConnecting: (callback: VoidFunction) => {\n onConnectingCallback.current = callback;\n },\n onReconnecting: (callback: (data: { attempts: number }) => void) => {\n onReconnectingCallback.current = callback;\n },\n onReconnectingFailed: (callback: (data: { attempts: number }) => void) => {\n onReconnectingFailedCallback.current = callback;\n },\n };\n\n // ******************\n // Hook to events\n // ******************\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without any subscriptions\n useEffect(() => {\n // Catch up with anything that happened between the render and the subscription\n if (state.current.connected !== socket.adapter.connected) {\n actions.setConnected(socket.adapter.connected);\n }\n if (state.current.connecting !== socket.adapter.connecting) {\n actions.setConnecting(socket.adapter.connecting);\n }\n\n const umountOnError = socket.events.onError((event) => {\n onErrorCallback.current?.(event);\n });\n const umountOnConnecting = socket.events.onConnecting(({ connecting }) => {\n actions.setConnecting(connecting);\n onConnectingCallback.current?.();\n });\n const umountOnOpen = socket.events.onConnected(() => {\n actions.setConnected(true);\n onConnectedCallback.current?.();\n });\n const umountOnClose = socket.events.onDisconnected(() => {\n actions.setConnected(false);\n onDisconnectCallback.current?.();\n });\n const umountOnReconnecting = socket.events.onReconnecting(({ attempts }) => {\n onReconnectingCallback.current?.({ attempts });\n });\n const umountOnReconnectingFailed = socket.events.onReconnectingFailed(({ attempts }) => {\n onReconnectingFailedCallback.current?.({ attempts });\n });\n\n return () => {\n umountOnError();\n umountOnConnecting();\n umountOnOpen();\n umountOnClose();\n umountOnReconnecting();\n umountOnReconnectingFailed();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [socket]);\n\n const getState = () => state.current;\n\n return [state.current, actions, callbacks, { setRenderKey, getState, rerender: emitChange }] as const;\n};\n","import type { SocketInstance } from \"@hyper-fetch/sockets\";\n\nimport type { UseSocketStateType } from \"./use-socket-state.types\";\n\nexport const initialSocketState: UseSocketStateType<SocketInstance> = {\n data: null,\n extra: null,\n connected: false,\n connecting: false,\n timestamp: null,\n};\n","import React, { useContext, useMemo, useRef, useState } from \"react\";\nimport { isEqual } from \"utils\";\n\nimport type { ProviderProps, ProviderValueType } from \"./provider.types\";\n\nconst ConfigContext = React.createContext<ProviderValueType>({\n config: {},\n setConfig: () => null,\n});\n\n/**\n * Provider with configuration for hooks\n * @param options\n * @returns\n */\nexport const Provider = ({ children, config }: ProviderProps) => {\n const [currentConfig, setConfig] = useState(config || {});\n\n // Follow the changes of the config prop - inline objects with the same values do not cause updates\n const previousConfig = useRef(config);\n if (!isEqual(previousConfig.current, config)) {\n previousConfig.current = config;\n setConfig(config || {});\n }\n\n const value = useMemo(() => {\n const contextValue: ProviderValueType = { config: currentConfig, setConfig };\n return contextValue;\n }, [currentConfig]);\n\n return <ConfigContext.Provider value={value}>{children}</ConfigContext.Provider>;\n};\n\n/**\n * Hook to allow reading current context config\n * @returns\n */\nexport const useProvider = (): ProviderValueType => {\n const config = useContext(ConfigContext);\n return config;\n};\n","/**\n * `JSON.stringify` replacer for the keys the hooks build from a request.\n * Adapters with their own serializers accept `BigInt` payloads, which plain JSON can't encode.\n * They are kept in the key and stay distinct from a string with the same digits.\n */\nexport const keyReplacer = (_key: string, value: unknown) => {\n return typeof value === \"bigint\" ? { \"~bigint\": value.toString() } : value;\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n CacheValueType,\n RequestInstance,\n ExtractAdapterStatusType,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ExtractErrorType,\n ExtractResponseType,\n} from \"@hyper-fetch/core\";\nimport { scopeKey } from \"@hyper-fetch/core\";\nimport { useRequestEvents, useTrackedState } from \"helpers\";\nimport type { UseFetchOptionsType, UseFetchReturnType } from \"hooks/use-fetch\";\nimport { useFetchDefaultOptions } from \"hooks/use-fetch\";\nimport { useProvider } from \"provider\";\nimport { useCallback, useRef } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\nimport { keyReplacer } from \"utils/key.utils\";\nimport { isSameScope } from \"utils/scope.utils\";\n\ntype SuspenseEntry = { promise: Promise<void>; resolve: () => void; cleanup: () => void };\ntype SuspenseResult = Pick<\n CacheValueType<any, any>,\n \"data\" | \"error\" | \"status\" | \"extra\" | \"success\" | \"retries\" | \"responseTimestamp\" | \"requestTimestamp\"\n> & { receivedTimestamp: number };\ntype SuspenseStore = { promises: Map<string, SuspenseEntry>; results: Map<string, SuspenseResult> };\n\n/**\n * Suspended components lose their state, so the pending promises and the responses that are not stored in the cache\n * have to live outside of them. They are kept per cache instance - every client (and every cleared client)\n * has its own store, so responses never leak between the clients.\n */\nconst suspenseStores = new WeakMap<object, SuspenseStore>();\nconst getSuspenseStore = (cache: object): SuspenseStore => {\n let store = suspenseStores.get(cache);\n if (!store) {\n store = { promises: new Map(), results: new Map() };\n suspenseStores.set(cache, store);\n }\n return store;\n};\n\n/**\n * Data received by the suspended component is not fetched again when it mounts right after.\n * Responses waiting for the suspended component are dropped after this time - the component is gone.\n */\nconst suspenseFreshTime = 1000;\n\n/**\n * Options passed as `undefined` (e.g. forwarded optional props) fall back to the defaults instead of overriding them\n */\nconst mergeOptions = <T extends object>(...sources: (object | undefined)[]): T => {\n const merged: Record<string, unknown> = {};\n sources.forEach((source) => {\n Object.entries(source || {}).forEach(([key, value]) => {\n if (value !== undefined) {\n merged[key] = value;\n }\n });\n });\n return merged as T;\n};\n\n/**\n * This hook aims to retrieve data from the server. It automatically fetches on mount and\n * refetches based on dependencies, with support for caching, polling, and suspense.\n * @param request Request instance\n * @param options Hook options\n * @returns\n */\nexport const useFetch = <R extends RequestInstance, TSelected = ExtractResponseType<R>>(\n request: R,\n options?: UseFetchOptionsType<R, TSelected>,\n): UseFetchReturnType<R, TSelected> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const {\n suspense,\n dependencies,\n disabled,\n dependencyTracking,\n revalidate,\n initialResponse,\n keepPreviousData,\n refresh,\n refreshTime,\n refetchBlurred,\n refetchOnBlur,\n refetchOnFocus,\n refetchOnReconnect,\n bounce,\n bounceType,\n bounceTime,\n bounceTimeout,\n deepCompare,\n structuralSharing,\n throwOnError,\n } = mergeOptions<typeof useFetchDefaultOptions & UseFetchOptionsType<R, TSelected>>(\n useFetchDefaultOptions,\n globalConfig.useFetchConfig,\n options,\n );\n\n const updateKey = JSON.stringify(request.toJSON(), keyReplacer);\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({ interval: bounceTime, timeout: bounceTimeout });\n const refreshDebounce = useDebounce({ delay: refreshTime });\n\n const { cacheKey, queryKey, client } = request;\n const { cache, fetchDispatcher: dispatcher, appManager, loggerManager } = client;\n // Cache storage and dispatcher queues are keyed with the scope of the request\n const scopedCacheKey = scopeKey(cacheKey, request.scope);\n const scopedQueryKey = scopeKey(queryKey, request.scope);\n\n const fetchDependencies = useRef<unknown[] | null>(null);\n const isSuspenseResolved = useRef(false);\n const logger = useRef(loggerManager.initialize(client, \"useFetch\")).current;\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n /**\n * State handler with optimization for re-rendering, that hooks into the cache state and dispatchers queues\n */\n const [\n state,\n actions,\n { setRenderKey, setCacheData, getStaleStatus, getIsDataProcessing, selectData, getResponseDetails },\n ] = useTrackedState<R, TSelected>({\n logger,\n request: request as unknown as R,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n keepPreviousData,\n disabled,\n revalidate,\n select: options?.select,\n structuralSharing,\n });\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [callbacks, listeners] = useRequestEvents<R>({\n logger,\n actions,\n request: request as unknown as R,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners, clearCacheDataListener } = listeners;\n\n // ******************\n // Fetching\n // ******************\n const handleFetch = (options?: { force?: boolean }) => {\n if (!disabled) {\n logger.debug({ title: `Fetching data`, type: \"system\", extra: { request } });\n // A forced fetch must not be deduplicated into an already running request: that request\n // started earlier, so its response can be older than the state that prompted the call.\n // Manual refetch() promises data at least as fresh as the moment it was called.\n const requestToAdd = options?.force ? request.setDeduplicate(false) : request;\n dispatcher.add(requestToAdd as unknown as R);\n } else {\n logger.debug({ title: `Cannot add to fetch queue`, type: \"system\", extra: { disabled } });\n }\n };\n\n // ******************\n // Refreshing\n // ******************\n\n function handleRefresh() {\n if (!refresh || disabled) {\n refreshDebounce.reset();\n return;\n }\n\n refreshDebounce.debounce(() => {\n // Timer outlives the render which started it - always use the latest options and request\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n latest.current.refresh();\n });\n }\n\n const performRefresh = () => {\n const isBlurred = !appManager.isFocused;\n\n // If window tab is not active should we refresh the cache\n const isFetching = dispatcher.hasRunningRequests(scopedQueryKey);\n const isQueued = dispatcher.getIsActiveQueue(scopedQueryKey);\n const isActive = isFetching || isQueued;\n const canRefreshBlurred = isBlurred && refetchBlurred && !isActive;\n const canRefreshFocused = !isBlurred && !isActive;\n\n if (canRefreshBlurred || canRefreshFocused) {\n handleFetch();\n logger.debug({ title: `Performing refresh request`, type: \"system\", extra: { request } });\n }\n\n // Start new refresh counter\n handleRefresh();\n };\n\n const handleRefetch = () => {\n handleFetch({ force: true });\n handleRefresh();\n };\n\n /**\n * Events and timers are registered once and live longer than a single render.\n * This ref gives them the handlers and options from the latest render.\n */\n const latest = useRef({\n disabled,\n refetchOnFocus,\n refetchOnBlur,\n refetchOnReconnect,\n fetch: handleFetch,\n refresh: performRefresh,\n restartRefresh: handleRefresh,\n refetch: handleRefetch,\n });\n latest.current = {\n disabled,\n refetchOnFocus,\n refetchOnBlur,\n refetchOnReconnect,\n fetch: handleFetch,\n refresh: performRefresh,\n restartRefresh: handleRefresh,\n refetch: handleRefetch,\n };\n\n // Stable identity - safe to use in the dependency arrays\n const refetch = useCallback(() => {\n latest.current.refetch();\n }, []);\n\n // ******************\n // Fetching lifecycle\n // ******************\n\n // This help us to check for currently running requests\n const getIsFetchingIdentity = () => {\n // We need to check if the queryKey have the same cacheKey elements ongoing\n return dispatcher.getRunningRequests(scopedQueryKey).some((running) => running.request.cacheKey === cacheKey);\n };\n\n const initialFetchData = () => {\n const hasStaleData = getStaleStatus();\n const isFetching = getIsFetchingIdentity();\n // Suspended component already waited for this response - do not ask for it again right after mounting\n const cacheTimestamp = cache.get(scopedCacheKey)?.responseTimestamp;\n const isFreshSuspenseData =\n suspense &&\n (isSuspenseResolved.current ||\n (typeof cacheTimestamp === \"number\" && Date.now() - cacheTimestamp < suspenseFreshTime));\n isSuspenseResolved.current = false;\n\n if ((revalidate || hasStaleData) && !isFetching && !isFreshSuspenseData) {\n handleFetch();\n }\n };\n\n const updateFetchData = () => {\n const hasStaleData = getStaleStatus();\n const shouldUpdate = !revalidate ? hasStaleData : true;\n\n if (shouldUpdate) {\n /**\n * Only the updates are bounced - the initial request is sent right away\n */\n if (bounce) {\n logger.debug({ title: `Bounce request with ${bounceType}`, type: \"system\", extra: { queryKey, request } });\n // Bounced callback can run after the next renders - it has to use the latest request and options\n bounceFunction(() => latest.current.fetch());\n } else {\n handleFetch();\n }\n }\n };\n\n /**\n * Effects can run again without any change - on StrictMode remount or when the hidden <Activity> is revealed.\n * We compare the dependencies with the ones already handled, to fetch once on mount and once per change.\n */\n const handleFetchLifecycle = () => {\n const currentDependencies = [updateKey, disabled, ...dependencies];\n const previousDependencies = fetchDependencies.current;\n fetchDependencies.current = currentDependencies;\n\n if (!previousDependencies) {\n initialFetchData();\n return;\n }\n\n const hasChanged =\n previousDependencies.length !== currentDependencies.length ||\n currentDependencies.some((dependency, index) => !Object.is(dependency, previousDependencies[index]));\n\n if (hasChanged) {\n updateFetchData();\n }\n };\n\n // ******************\n // Events\n // ******************\n\n const handleMountEvents = () => {\n addCacheDataListener(request as unknown as R);\n addLifecycleListeners(request as unknown as R);\n\n // Options can change without re-registering the listeners - they are read when the event happens\n const focusUnmount = appManager.events.onFocus(() => {\n if (latest.current.refetchOnFocus && !latest.current.disabled) {\n latest.current.fetch();\n latest.current.restartRefresh();\n }\n });\n const blurUnmount = appManager.events.onBlur(() => {\n if (latest.current.refetchOnBlur && !latest.current.disabled) {\n latest.current.fetch();\n latest.current.restartRefresh();\n }\n });\n const onlineUnmount = appManager.events.onOnline(() => {\n if (latest.current.refetchOnReconnect && !latest.current.disabled) {\n latest.current.fetch();\n latest.current.restartRefresh();\n }\n });\n\n // Invalidation and deletion are emitted by the request cache key, which is shared between the scopes.\n // The event carries the key of the changed element - only our own one has to be fetched again.\n const handleCacheChange = (changedKey: string) => {\n if (changedKey === scopedCacheKey) {\n latest.current.fetch();\n }\n };\n const invalidateUnmount = cache.events.onInvalidateByKey(cacheKey, handleCacheChange);\n const deletionUnmount = cache.events.onDeleteByKey(cacheKey, handleCacheChange);\n\n const unmount = () => {\n clearCacheDataListener();\n focusUnmount();\n blurUnmount();\n onlineUnmount();\n invalidateUnmount();\n deletionUnmount();\n };\n\n return unmount;\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n /**\n * Initialization of the events related to data exchange with cache and queue\n * This allows to share the state with other hooks and keep it related\n */\n useDidUpdate(handleMountEvents, [updateKey, disabled], true);\n\n /**\n * Initial fetch triggered once data is stale or we use the refetch strategy\n * and the fetching logic for updates handling\n */\n useDidUpdate(handleFetchLifecycle, [updateKey, disabled, ...dependencies], true);\n\n /**\n * Refresh lifecycle handler\n */\n useDidUpdate(handleRefresh, [updateKey, ...dependencies, disabled, refresh, refreshTime], true);\n\n // ******************\n // Suspense\n // ******************\n if (suspense && !disabled) {\n const store = getSuspenseStore(cache);\n\n // Apply any cached suspense result (covers error responses that aren't stored in cache)\n const storedResult = store.results.get(scopedCacheKey);\n // Nobody picked the response up in time (suspended component got unmounted) - it is outdated now\n const suspenseResult =\n storedResult && Date.now() - storedResult.receivedTimestamp <= suspenseFreshTime ? storedResult : null;\n if (storedResult && !suspenseResult) {\n store.results.delete(scopedCacheKey);\n }\n if (suspenseResult) {\n // Result stays available until the end of the current render pass. React can render the component more than\n // once before it mounts (StrictMode, retry after a thrown error) and other components can wait for the same response.\n queueMicrotask(() => {\n if (store.results.get(scopedCacheKey) === suspenseResult) {\n store.results.delete(scopedCacheKey);\n }\n });\n isSuspenseResolved.current = true;\n if (suspenseResult.data !== null) {\n state.data = selectData(suspenseResult.data);\n }\n if (suspenseResult.error !== null) {\n state.error = suspenseResult.error;\n }\n if (suspenseResult.status !== null) {\n state.status = suspenseResult.status;\n }\n if (suspenseResult.extra !== null) {\n state.extra = suspenseResult.extra;\n }\n state.success = suspenseResult.success;\n state.loading = dispatcher.hasRunningRequests(scopedQueryKey);\n state.retries = suspenseResult.retries ?? state.retries;\n // Timestamps tell that the response was received - also when it came without any data\n state.responseTimestamp = new Date(suspenseResult.responseTimestamp);\n state.requestTimestamp = new Date(suspenseResult.requestTimestamp);\n }\n\n // Response without data (like 204 No Content) is still a response - suspending on it would never end\n const hasData = state.data !== null || state.error !== null || state.responseTimestamp !== null;\n\n if (!hasData) {\n let entry = store.promises.get(scopedCacheKey);\n if (!entry) {\n let resolvePromise: () => void;\n const promise = new Promise<void>((r) => {\n resolvePromise = r;\n });\n\n const unsubscribe = cache.events.onDataByKey(cacheKey, (cacheData: CacheValueType<any, any>) => {\n // Events of the same cache key are shared between the scopes\n if (!isSameScope(cacheData.scope, request.scope)) {\n return;\n }\n\n store.results.set(scopedCacheKey, {\n data: cacheData.data ?? null,\n error: cacheData.error ?? null,\n status: cacheData.status ?? null,\n extra: cacheData.extra ?? null,\n success: cacheData.success ?? false,\n retries: cacheData.retries ?? 0,\n responseTimestamp: cacheData.responseTimestamp ?? Date.now(),\n requestTimestamp: cacheData.requestTimestamp ?? Date.now(),\n receivedTimestamp: Date.now(),\n });\n resolvePromise();\n unsubscribe();\n store.promises.delete(scopedCacheKey);\n });\n\n entry = { promise, resolve: resolvePromise!, cleanup: unsubscribe };\n store.promises.set(scopedCacheKey, entry);\n }\n\n // Ensure the request is dispatched before suspending —\n // effects never run when a component suspends.\n // React may render a suspended component again before the queued request starts running,\n // so a queued request counts as dispatched too.\n if (!dispatcher.hasRunningRequests(scopedQueryKey) && !dispatcher.getIsActiveQueue(scopedQueryKey)) {\n dispatcher.add(request as unknown as R);\n }\n\n throw entry.promise;\n }\n\n // Data has arrived — clean up any leftover entry\n const entry = store.promises.get(scopedCacheKey);\n if (entry) {\n entry.cleanup();\n store.promises.delete(scopedCacheKey);\n }\n }\n\n // ******************\n // Error boundary\n // ******************\n if (throwOnError) {\n // The error has to be observed to rerender (and throw) even if the component does not read it\n setRenderKey(\"error\");\n setRenderKey(\"loading\");\n setRenderKey(\"success\");\n\n const details = getResponseDetails();\n // Errors of retried, canceled or offline (re-queued) requests are not final\n const isSettled = !state.loading && !details?.willRetry && !details?.isCanceled && !details?.isOffline;\n const hasError = !state.success && state.error !== null && state.error !== undefined;\n\n if (isSettled && hasError) {\n const error = state.error as ExtractErrorType<R>;\n if (typeof throwOnError === \"function\" ? throwOnError(error) : throwOnError) {\n throw error;\n }\n }\n }\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"loading\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n error: state.error,\n loading: state.loading,\n status: state.status as ExtractAdapterStatusType<ExtractAdapterType<R>>,\n success: state.success,\n extra: state.extra as ExtractAdapterExtraType<ExtractAdapterType<R>>,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n bounce: getBounceData(bounceData),\n ...actions,\n ...(callbacks as any),\n refetch,\n },\n trackedKeys,\n setRenderKey,\n ) as UseFetchReturnType<R, TSelected>;\n};\n","export const getRefreshTime = (refreshTime: number, dataTimestamp?: Date) => {\n if (dataTimestamp) {\n const timeDiff = Date.now() - +dataTimestamp;\n return timeDiff < refreshTime ? refreshTime - timeDiff : refreshTime;\n }\n return refreshTime;\n};\n","import type { RequestInstance, RequiredKeys } from \"@hyper-fetch/core\";\nimport { Time } from \"@hyper-fetch/core\";\nimport type { UseFetchOptionsType } from \"hooks/use-fetch\";\n\ntype DefaultOptionsType = RequiredKeys<Omit<UseFetchOptionsType<RequestInstance>, \"initialResponse\" | \"select\">> & {\n initialResponse: null;\n};\n\nexport const useFetchDefaultOptions: DefaultOptionsType = {\n suspense: false,\n dependencies: [],\n disabled: false,\n dependencyTracking: true,\n revalidate: true,\n initialResponse: null,\n keepPreviousData: \"auto\",\n refresh: false,\n refreshTime: Time.HOUR,\n refetchBlurred: true,\n refetchOnBlur: false,\n refetchOnFocus: false,\n refetchOnReconnect: false,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n bounceTimeout: 400,\n deepCompare: true,\n structuralSharing: true,\n throwOnError: false,\n};\n","import { Time } from \"@hyper-fetch/core\";\n\nimport type { UseInfiniteFetchConfigType } from \"./use-infinite-fetch.types\";\n\nexport const useInfiniteFetchDefaultOptions = {\n suspense: false,\n throwOnError: false,\n dependencies: [],\n disabled: false,\n dependencyTracking: true,\n // Pages restored from the cache are refetched only once they are stale\n revalidate: false,\n keepPreviousData: \"auto\",\n refresh: false,\n refreshTime: Time.HOUR,\n refetchBlurred: true,\n refetchOnBlur: false,\n refetchOnFocus: false,\n refetchOnReconnect: false,\n structuralSharing: true,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n bounceTimeout: 400,\n} satisfies Required<UseInfiniteFetchConfigType>;\n","import type { RequestInstance } from \"@hyper-fetch/core\";\nimport { getErrorMessage, mapResponseForSend, scopeKey } from \"@hyper-fetch/core\";\n\ntype LoadPageOptions = {\n request: RequestInstance;\n /** Skips requests started before this fetch was asked for */\n force: boolean;\n /** Filled with the functions stopping this fetch */\n cancellers: Set<VoidFunction>;\n isCancelled: () => boolean;\n};\n\n/**\n * Cancelled pages are not failures: the list simply did not need them anymore\n */\nexport const isCancelledResponse = (response: any) => {\n const message = response?.error?.message;\n return (\n !response?.success &&\n (message === getErrorMessage(\"abort\").message || message === getErrorMessage(\"deleted\").message)\n );\n};\n\n/**\n * Joins a request started elsewhere. Cancelling only stops waiting, the request belongs to someone else.\n */\nconst waitForResponse = (request: RequestInstance, requestId: string, cancellers: Set<VoidFunction>) => {\n const { requestManager } = request.client;\n\n return new Promise<any>((resolve) => {\n const finish = (response: any) => {\n unmountResponse();\n unmountRemove();\n cancellers.delete(cancel);\n resolve(response);\n };\n const cancel = () => finish(null);\n const unmountResponse = requestManager.events.onResponseById(requestId, ({ response, details }) => {\n if (response.success || (!details.willRetry && !details.isOffline)) {\n finish(response);\n }\n });\n const unmountRemove = requestManager.events.onRemoveById(requestId, cancel);\n\n cancellers.add(cancel);\n });\n};\n\nconst sendPage = async ({ request, force, cancellers }: LoadPageOptions) => {\n const { fetchDispatcher } = request.client;\n const pageRequest = force ? request.setDeduplicate(false) : request;\n let sentRequestId = \"\";\n\n const cancel = () => {\n fetchDispatcher.delete(\n scopeKey(request.queryKey, request.scope),\n sentRequestId,\n scopeKey(request.abortKey, request.scope),\n );\n };\n cancellers.add(cancel);\n\n const response = await (pageRequest as RequestInstance).send({\n dispatcherType: \"fetch\",\n onBeforeSent: ({ requestId }: { requestId: string }) => {\n sentRequestId = requestId;\n },\n } as any);\n\n cancellers.delete(cancel);\n return response;\n};\n\n/**\n * Loads a page, reusing the request already running for it\n */\nexport const loadPage = async (options: LoadPageOptions) => {\n const { request, force, cancellers, isCancelled } = options;\n\n // A forced fetch must not reuse a request started before it was asked for\n if (!force) {\n const running = request.client.fetchDispatcher\n .getRunningRequests(scopeKey(request.queryKey, request.scope))\n .find((item) => item.request.cacheKey === request.cacheKey);\n\n if (running) {\n const response = await waitForResponse(request, running.requestId, cancellers);\n if (response) {\n return mapResponseForSend(request, response);\n }\n if (isCancelled()) {\n return null;\n }\n }\n }\n\n return sendPage(options);\n};\n","import type { ClientInstance, RequestInstance } from \"@hyper-fetch/core\";\nimport { keyReplacer } from \"utils/key.utils\";\n\nimport type { InfiniteStore } from \"./use-infinite-fetch.store\";\nimport type { InfiniteSnapshot } from \"./use-infinite-fetch.store.types\";\n\n/**\n * Identity of a list. Everything describing the request takes part in it, so a changed filter, sort, page size\n * or URL param starts a new list without anything having to be listed by hand.\n */\nexport const getInfiniteKey = (request: RequestInstance, pagination: unknown, maxPages?: number) => {\n return JSON.stringify([request.toJSON(), pagination, maxPages ?? null], (key, value) => {\n return typeof value === \"function\" ? value.toString() : keyReplacer(key, value);\n });\n};\n\n/**\n * Keeps the first occurrence of every item\n */\nexport const getUniqueItems = (items: unknown[], uniqueBy: unknown) => {\n if (uniqueBy === undefined) {\n return items;\n }\n\n const seen = new Set<unknown>();\n return items.filter((item: any) => {\n const identity = typeof uniqueBy === \"function\" ? uniqueBy({ item }) : item?.[uniqueBy as string];\n if (seen.has(identity)) {\n return false;\n }\n seen.add(identity);\n return true;\n });\n};\n\n/**\n * Decides if the previous list stays on screen while the new one loads its first page\n */\nexport const getShouldKeepPreviousList = (\n mode: \"auto\" | \"preserve\" | \"clean\",\n previous: RequestInstance,\n current: RequestInstance,\n) => {\n if (mode === \"auto\") {\n return previous.method === current.method && previous.endpoint === current.endpoint;\n }\n return mode === \"preserve\";\n};\n\n/**\n * Tells whether nothing changed between two states of a list, so nobody has to be notified\n */\nexport const isSameSnapshot = (a: InfiniteSnapshot, b: InfiniteSnapshot) => {\n return (Object.keys(a) as (keyof InfiniteSnapshot)[]).every((key) => a[key] === b[key]);\n};\n\nconst stores = new WeakMap<ClientInstance, Map<string, InfiniteStore>>();\n\n/**\n * Stores of the lists shown with the client, by the key of the list\n */\nexport const getStores = (client: ClientInstance) => {\n let clientStores = stores.get(client);\n if (!clientStores) {\n clientStores = new Map();\n stores.set(client, clientStores);\n }\n return clientStores;\n};\n","import type { CacheValueType, PaginationConfig, PaginationPageContext, RequestInstance } from \"@hyper-fetch/core\";\nimport {\n getCachedPages,\n getHasNextPage,\n getHasPreviousPage,\n getInitialPageParam,\n getNextPageParam,\n getPageItems,\n getPageRequest,\n getPageTotal,\n getPaginationMode,\n getPreviousPageParam,\n replaceEqualDeep,\n scopeKey,\n stringifyKey,\n} from \"@hyper-fetch/core\";\nimport { isStaleCacheData } from \"helpers/use-tracked-state/use-tracked-state.utils\";\nimport { pickInitialCacheData } from \"hydrate/hydrate.utils\";\n\nimport { isCancelledResponse, loadPage } from \"./use-infinite-fetch.requests\";\nimport type {\n FetchedPage,\n InfinitePage,\n InfiniteSnapshot,\n InfiniteStoreOptions,\n Operation,\n OperationKind,\n} from \"./use-infinite-fetch.store.types\";\nimport type { InfinitePageEvent } from \"./use-infinite-fetch.types\";\nimport { getStores, isSameSnapshot } from \"./use-infinite-fetch.utils\";\n\n// Render and commit are separate steps, a store waits this long for the component that created it\nconst unusedStoreTime = 1000;\n\n/**\n * State of a single list. Hooks showing the same list share one store, so they stay in sync and never request\n * the same page twice. Pages are ordinary requests under their own cache keys - nothing extra is stored.\n *\n * Fetches run one at a time: every page depends on the list as it was when its value was computed.\n */\nexport class InfiniteStore {\n private listeners = new Set<VoidFunction>();\n private pageListeners = new Set<(event: InfinitePageEvent<any>) => void>();\n private pages: InfinitePage[] = [];\n // Values of pages dropped by `maxPages`, a cursor list may have no other way of going back to them\n private droppedParams: unknown[] = [];\n private queue: Operation[] = [];\n private running: Operation | null = null;\n private cancellers = new Set<VoidFunction>();\n // Pages being refetched - their cache events wait for the whole list to be swapped at once\n private refetchedKeys = new Set<string>();\n private unmountCacheListeners: VoidFunction | null = null;\n private unusedTimer: ReturnType<typeof setTimeout> | null = null;\n private enabledHooks = 0;\n private started = false;\n private settled = false;\n private firstFetch: Promise<any> = Promise.resolve(null);\n private nextPageError = false;\n private previousPageError = false;\n private result: { error: any; status: any; extra: any; success: boolean } = {\n error: null,\n status: null,\n extra: null,\n success: false,\n };\n private snapshot: InfiniteSnapshot;\n\n constructor(\n readonly key: string,\n private options: InfiniteStoreOptions,\n ) {\n getPaginationMode(options.pagination);\n this.restorePages();\n this.snapshot = this.createSnapshot();\n }\n\n // ******************\n // State\n // ******************\n\n getSnapshot = () => this.snapshot;\n\n subscribe = (listener: VoidFunction) => {\n this.listeners.add(listener);\n if (this.listeners.size === 1) {\n this.attach();\n }\n\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) {\n this.detach();\n }\n };\n };\n\n onPage = (listener: (event: InfinitePageEvent<any>) => void) => {\n this.pageListeners.add(listener);\n return () => {\n this.pageListeners.delete(listener);\n };\n };\n\n /** Counts the hooks allowed to fetch - changes of the cache refetch the list only for them */\n enable = () => {\n this.enabledHooks += 1;\n return () => {\n this.enabledHooks -= 1;\n };\n };\n\n /** Callbacks can capture values of the latest render */\n setPagination = (pagination: PaginationConfig) => {\n this.options.pagination = pagination;\n };\n\n hasPages = () => this.pages.length > 0;\n\n // ******************\n // Actions\n // ******************\n\n /**\n * Loads the list when it is first needed. Safe to call many times.\n */\n start = ({ revalidate }: { revalidate?: boolean } = {}) => {\n if (this.started) {\n // A hook joining a list already on screen, or coming back to it, checks the loaded pages like a new mount\n const isIdle = !this.running && this.queue.length === 0;\n if (isIdle && this.pages.length > 0 && (revalidate || this.getHasStalePages())) {\n this.revalidate();\n }\n return this.firstFetch;\n }\n this.started = true;\n\n if (this.pages.length === 0) {\n this.firstFetch = this.schedule(\"initial\");\n } else if (revalidate || this.getHasStalePages()) {\n this.revalidate();\n } else {\n this.settled = true;\n }\n this.publish();\n return this.firstFetch;\n };\n\n fetchNextPage = () => this.fetchDirection(\"next\");\n\n fetchPreviousPage = () => this.fetchDirection(\"previous\");\n\n /**\n * Refetch asked for by the user: anything already refetching is older than this call and gets replaced.\n */\n refetch = () => {\n if (this.pages.length === 0) {\n return this.revalidate();\n }\n this.getOperations(\"refetch\").forEach(this.cancelOperation);\n return this.schedule(\"refetch\");\n };\n\n /**\n * Automatic refetch: joins the one in progress\n */\n revalidate = () => {\n const kind = this.pages.length > 0 ? \"refetch\" : \"initial\";\n return this.getOperations(kind)[0]?.promise ?? this.schedule(kind);\n };\n\n reset = () => {\n this.cancelOperations();\n const startParam = stringifyKey(getInitialPageParam(this.options.request, this.options.pagination));\n\n this.pages = this.pages.filter((page) => stringifyKey(page.param) === startParam);\n this.droppedParams = [];\n this.nextPageError = false;\n this.previousPageError = false;\n this.settled = false;\n this.started = true;\n\n return this.schedule(this.pages.length > 0 ? \"refetch\" : \"initial\");\n };\n\n abort = () => {\n this.cancelOperations();\n this.settled = true;\n this.publish();\n };\n\n /** The list is no longer on screen - stop fetching its pages */\n cancelIfUnused = () => {\n if (this.listeners.size === 0) {\n this.cancelOperations();\n }\n };\n\n /** A store that threw its error starts over when the Error Boundary renders the component again */\n evictSoon = () => {\n setTimeout(this.evict, 0);\n };\n\n /** Stores created while rendering are removed when the component never mounts */\n scheduleUnusedCheck = () => {\n this.unusedTimer = setTimeout(() => {\n this.unusedTimer = null;\n if (this.running || this.queue.length > 0) {\n this.scheduleUnusedCheck();\n } else {\n this.evict();\n }\n }, unusedStoreTime);\n };\n\n // ******************\n // Operations\n // ******************\n\n private fetchDirection = (kind: \"next\" | \"previous\") => {\n if (this.pages.length === 0) {\n return this.getOperations(\"initial\")[0]?.promise ?? Promise.resolve(null);\n }\n const scheduled = this.getOperations(kind)[0];\n if (scheduled) {\n return scheduled.promise;\n }\n if (kind === \"next\" ? this.getNextParam() === undefined : !this.getPreviousTarget()) {\n return Promise.resolve(null);\n }\n if (kind === \"next\") {\n this.nextPageError = false;\n } else {\n this.previousPageError = false;\n }\n return this.schedule(kind);\n };\n\n private getOperations = (kind: OperationKind) => {\n const operations = this.running ? [this.running, ...this.queue] : this.queue;\n return operations.filter((operation) => operation.kind === kind && !operation.cancelled);\n };\n\n private schedule = (kind: OperationKind) => {\n const operation = { kind, cancelled: false } as Operation;\n operation.promise = new Promise<any>((resolve) => {\n operation.resolve = resolve;\n });\n\n if (kind === \"initial\") {\n this.settled = false;\n }\n this.queue.push(operation);\n this.pump();\n this.publish();\n return operation.promise;\n };\n\n private pump = async () => {\n if (this.running) {\n return;\n }\n const operation = this.queue.shift();\n if (!operation) {\n return;\n }\n\n this.running = operation;\n const previousPages = this.pages;\n let response = null;\n try {\n response = await this.perform(operation);\n } catch (error) {\n this.setFailure(error);\n }\n this.keepValidPages(previousPages);\n this.running = null;\n this.refetchedKeys.clear();\n\n if ((operation.kind === \"initial\" || operation.kind === \"refetch\") && !operation.cancelled) {\n this.settled = true;\n }\n\n operation.resolve(operation.cancelled ? null : response);\n this.pump();\n this.publish();\n };\n\n private cancelOperation = (operation: Operation) => {\n operation.cancelled = true;\n if (operation === this.running) {\n this.cancellers.forEach((cancel) => cancel());\n this.cancellers.clear();\n this.refetchedKeys.clear();\n } else {\n this.queue = this.queue.filter((item) => item !== operation);\n operation.resolve(null);\n }\n };\n\n private cancelOperations = () => {\n [...this.queue, ...(this.running ? [this.running] : [])].forEach(this.cancelOperation);\n };\n\n private perform = (operation: Operation) => {\n switch (operation.kind) {\n case \"next\": {\n return this.performNext(operation);\n }\n case \"previous\": {\n return this.performPrevious(operation);\n }\n case \"refetch\": {\n return this.performRefetch(operation);\n }\n default: {\n return this.performInitial(operation);\n }\n }\n };\n\n private performInitial = async (operation: Operation) => {\n const { request, pagination } = this.options;\n const fetched = await this.fetchPage(operation, getInitialPageParam(request, pagination));\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n if (fetched.response.success) {\n this.pages = [this.createPage(fetched)];\n }\n return fetched.response;\n };\n\n private performNext = async (operation: Operation) => {\n const param = this.getNextParam();\n if (param === undefined) {\n return null;\n }\n\n const fetched = await this.fetchPage(operation, param);\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n this.nextPageError = !fetched.response.success;\n if (fetched.response.success) {\n this.pages = [...this.pages, this.createPage(fetched)];\n this.trimPages(\"start\");\n }\n return fetched.response;\n };\n\n private performPrevious = async (operation: Operation) => {\n const target = this.getPreviousTarget();\n if (!target) {\n return null;\n }\n\n const { param } = target;\n const fetched = await this.fetchPage(operation, param);\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n this.previousPageError = !fetched.response.success;\n if (fetched.response.success) {\n if (target.isDropped) {\n this.droppedParams = this.droppedParams.slice(0, -1);\n }\n this.pages = [this.createPage(fetched), ...this.pages];\n this.trimPages(\"end\");\n }\n return fetched.response;\n };\n\n private performRefetch = async (operation: Operation) => {\n const current = this.pages;\n current.forEach((page) => this.refetchedKeys.add(page.storageKey));\n\n return getPaginationMode(this.options.pagination) === \"cursor\"\n ? this.refetchInOrder(operation, current)\n : this.refetchAtOnce(operation, current);\n };\n\n /**\n * Page and offset values do not depend on other pages, so they can be requested together\n */\n private refetchAtOnce = async (operation: Operation, current: InfinitePage[]) => {\n const results = await Promise.all(current.map((page) => this.fetchPage(operation, page.param, true)));\n if (operation.cancelled) {\n return null;\n }\n\n const pages = current.map((page, index) => {\n const fetched = results[index];\n return fetched?.response.success ? this.createPage(fetched) : page;\n });\n // The list can be shorter than before. Pages after its new end are gone, whatever their requests returned.\n const end = pages.findIndex((page, index) => {\n return results[index]?.response.success && !getHasNextPage(this.getContext(page, pages.slice(0, index + 1)));\n });\n const length = end === -1 ? pages.length : end + 1;\n const kept = results.slice(0, length);\n const failed = kept.find((fetched) => fetched && !fetched.response.success);\n const last = failed ?? kept.findLast(Boolean);\n\n this.pages = pages.slice(0, length);\n if (last) {\n this.setResult(last.response);\n }\n return last?.response ?? null;\n };\n\n /**\n * Every cursor comes from the page before it, and the fresh data can hold different cursors than before.\n * The list is replaced only when the whole chain arrived, a failure leaves it as it was.\n */\n private refetchInOrder = async (operation: Operation, current: InfinitePage[]) => {\n const fresh: InfinitePage[] = [];\n let param = current[0].param;\n let response = null;\n\n while (fresh.length < current.length) {\n // Each request needs the response of the previous one\n // eslint-disable-next-line no-await-in-loop\n const fetched = await this.fetchPage(operation, param, true);\n if (!fetched) {\n return null;\n }\n\n response = fetched.response;\n this.setResult(response);\n if (!response.success) {\n return response;\n }\n\n const page = this.createPage(fetched);\n fresh.push(page);\n\n const context = this.getContext(page, fresh);\n if (!getHasNextPage(context)) {\n break;\n }\n param = getNextPageParam(context);\n }\n\n this.pages = fresh;\n return response;\n };\n\n private trimPages = (side: \"start\" | \"end\") => {\n const { maxPages } = this.options;\n if (!maxPages || this.pages.length <= maxPages) {\n return;\n }\n\n const overflow = this.pages.length - maxPages;\n if (side === \"start\") {\n this.droppedParams = [...this.droppedParams, ...this.pages.slice(0, overflow).map((page) => page.param)];\n this.pages = this.pages.slice(overflow);\n } else {\n this.pages = this.pages.slice(0, maxPages);\n }\n };\n\n // ******************\n // Requests\n // ******************\n\n private fetchPage = async (operation: Operation, param: unknown, force = false): Promise<FetchedPage | null> => {\n const request = getPageRequest(this.options.request, this.options.pagination, param);\n const response = await loadPage({\n request,\n force,\n cancellers: this.cancellers,\n isCancelled: () => operation.cancelled,\n });\n\n if (operation.cancelled || !response || isCancelledResponse(response)) {\n return null;\n }\n\n this.pageListeners.forEach((listener) => listener({ response, request, param }));\n return { param, request, response };\n };\n\n // ******************\n // Pages\n // ******************\n\n private getContext = (page: InfinitePage, pages: InfinitePage[] = this.pages): PaginationPageContext => ({\n request: this.options.request,\n pagination: this.options.pagination,\n data: page.data,\n param: page.param,\n pages: pages.map((item) => item.data),\n });\n\n private getNextParam = () => {\n const last = this.pages.at(-1);\n if (!last || !getHasNextPage(this.getContext(last))) {\n return;\n }\n return getNextPageParam(this.getContext(last));\n };\n\n // The first page of a cursor list has no cursor, so \"no value\" cannot mean \"no page\"\n private getPreviousTarget = (): { param: unknown; isDropped: boolean } | null => {\n const first = this.pages[0];\n if (!first) {\n return null;\n }\n if (this.droppedParams.length > 0) {\n return { param: this.droppedParams.at(-1), isDropped: true };\n }\n if (getHasPreviousPage(this.getContext(first))) {\n return { param: getPreviousPageParam(this.getContext(first)), isDropped: false };\n }\n return null;\n };\n\n private getHasStalePages = () => {\n return this.pages.some(({ request, responseTimestamp }) => {\n // Pages of requests without cache are kept only here\n const kept = request.cache ? null : { staleTime: request.staleTime, responseTimestamp };\n const value = this.readValue(request) ?? kept;\n return !value || isStaleCacheData(value.staleTime, value.responseTimestamp);\n });\n };\n\n private readValue = (request: RequestInstance) => {\n const { client } = request;\n const storageKey = scopeKey(request.cacheKey, request.scope);\n return pickInitialCacheData<CacheValueType>(\n client.cache.get(storageKey),\n this.options.hydration?.get(client, storageKey),\n );\n };\n\n /** Responses go through the response mapper of the request, an asynchronous one cannot be read synchronously */\n private mapValue = (request: RequestInstance, value: CacheValueType) => {\n const mapped: any = request.unstable_responseMapper ? request.unstable_responseMapper(value as any) : value;\n return mapped instanceof Promise ? undefined : mapped;\n };\n\n private createPage = ({ param, request, response }: FetchedPage): InfinitePage => {\n // Reading the cache keeps changes made after the response arrived, like optimistic updates\n const value = this.readValue(request);\n const cached =\n value && value.responseTimestamp >= response.responseTimestamp ? this.mapValue(request, value) : null;\n\n return {\n param,\n request,\n storageKey: scopeKey(request.cacheKey, request.scope),\n data: cached?.success ? cached.data : response.data,\n responseTimestamp: response.responseTimestamp,\n };\n };\n\n private restorePages = () => {\n const { request, pagination, maxPages } = this.options;\n\n this.pages = getCachedPages({\n request,\n pagination,\n maxPages,\n read: (pageRequest) => {\n const value = this.readValue(pageRequest);\n const mapped = value ? this.mapValue(pageRequest, value) : null;\n return mapped?.success ? { ...value, data: mapped.data } : null;\n },\n }).map(({ param, request: pageRequest, value }) => ({\n param,\n request: pageRequest,\n storageKey: scopeKey(pageRequest.cacheKey, pageRequest.scope),\n data: value.data,\n responseTimestamp: Number(value.responseTimestamp),\n }));\n };\n\n /** Picks up everything that happened between rendering and mounting */\n private syncPages = () => {\n if (this.running || this.queue.length > 0) {\n return;\n }\n if (this.pages.length === 0) {\n this.restorePages();\n return;\n }\n\n this.pages = this.pages.map((page) => {\n const value = this.readValue(page.request);\n const mapped = value ? this.mapValue(page.request, value) : null;\n return mapped?.success\n ? { ...page, data: mapped.data, responseTimestamp: Number(value?.responseTimestamp) }\n : page;\n });\n };\n\n private setFailure = (error: unknown) => {\n this.result = { error, status: null, extra: null, success: false };\n };\n\n /**\n * Pagination callbacks read the data of every page. When one of them throws, the page that caused it is not\n * used and the error is reported instead of breaking the list.\n */\n private keepValidPages = (previousPages: InfinitePage[]) => {\n try {\n this.createSnapshot();\n } catch (error) {\n this.pages = previousPages;\n this.setFailure(error);\n }\n };\n\n private setResult = (response: any) => {\n // Like the flags of TanStack Query, these describe the last fetch only - next and previous set theirs after this\n this.nextPageError = false;\n this.previousPageError = false;\n this.result = {\n error: response.success ? null : response.error,\n status: response.status,\n extra: response.extra,\n success: response.success,\n };\n };\n\n // ******************\n // Cache\n // ******************\n\n private attach = () => {\n if (this.unusedTimer) {\n clearTimeout(this.unusedTimer);\n this.unusedTimer = null;\n }\n\n const { client } = this.options.request;\n const clientStores = getStores(client);\n if (!clientStores.has(this.key) && client.mode !== \"server\") {\n clientStores.set(this.key, this);\n }\n\n const { cache } = client;\n const unmountData = cache.events.onData(this.handleCacheData);\n const unmountInvalidate = cache.events.onInvalidate(this.handleCacheChange);\n const unmountDelete = cache.events.onDelete(this.handleCacheChange);\n\n this.unmountCacheListeners = () => {\n unmountData();\n unmountInvalidate();\n unmountDelete();\n };\n\n this.syncPages();\n this.publish();\n };\n\n private detach = () => {\n this.unmountCacheListeners?.();\n this.unmountCacheListeners = null;\n this.evict();\n };\n\n private evict = () => {\n if (this.listeners.size > 0) {\n return;\n }\n const clientStores = getStores(this.options.request.client);\n if (clientStores.get(this.key) === this) {\n clientStores.delete(this.key);\n }\n };\n\n private handleCacheData = (value: CacheValueType) => {\n const storageKey = scopeKey(value.cacheKey, value.scope ?? null);\n if (!value.success || this.refetchedKeys.has(storageKey)) {\n return;\n }\n\n const index = this.pages.findIndex((page) => page.storageKey === storageKey);\n const page = this.pages[index];\n const mapped = page ? this.mapValue(page.request, value) : null;\n if (!page || !mapped?.success) {\n return;\n }\n\n const previousPages = this.pages;\n this.pages = this.pages.map((item, itemIndex) => {\n return itemIndex === index\n ? { ...item, data: mapped.data, responseTimestamp: Number(value.responseTimestamp) }\n : item;\n });\n this.keepValidPages(previousPages);\n this.publish();\n };\n\n private hasInvalidation = false;\n\n /**\n * Invalidated data may have changed after a running refetch started, so that refetch is replaced.\n * Invalidating by a pattern reports every key on its own, all of them are handled by one refetch.\n */\n private handleCacheChange = (key: string) => {\n const isLoaded = this.pages.some((page) => page.storageKey === key || page.request.cacheKey === key);\n if (!isLoaded || this.hasInvalidation) {\n return;\n }\n\n this.hasInvalidation = true;\n queueMicrotask(() => {\n this.hasInvalidation = false;\n if (this.enabledHooks > 0) {\n this.refetch();\n }\n });\n };\n\n // ******************\n // Snapshot\n // ******************\n\n private createSnapshot = (): InfiniteSnapshot => {\n const { structuralSharing = true } = this.options;\n const previous = this.snapshot as InfiniteSnapshot | undefined;\n const share = <T>(prev: T | undefined, next: T) =>\n structuralSharing && prev ? replaceEqualDeep(prev, next) : next;\n\n const contexts = this.pages.map((page) => this.getContext(page));\n const last = contexts.at(-1);\n const totals = contexts.map(getPageTotal).filter((total) => total !== null);\n const operations = [...this.queue, ...(this.running ? [this.running] : [])].filter((item) => !item.cancelled);\n const isRunning = (kind: OperationKind) => operations.some((item) => item.kind === kind);\n\n return {\n items: share(previous?.items, contexts.flatMap((context) => getPageItems(context))),\n data: share(previous?.data, this.pages.map((page) => page.data)),\n pageParams: share(previous?.pageParams, this.pages.map((page) => page.param)),\n total: totals.length > 0 ? (totals.at(-1) as number) : null,\n hasNextPage: !!last && this.getNextParam() !== undefined,\n hasPreviousPage: !!this.getPreviousTarget(),\n loading: this.pages.length === 0 && !this.settled,\n isFetching: operations.length > 0,\n isRefetching: isRunning(\"refetch\"),\n isFetchingNextPage: isRunning(\"next\"),\n isFetchingPreviousPage: isRunning(\"previous\"),\n isFetchNextPageError: this.nextPageError,\n isFetchPreviousPageError: this.previousPageError,\n ...this.result,\n };\n };\n\n private publish = () => {\n const snapshot = this.createSnapshot();\n if (isSameSnapshot(this.snapshot, snapshot)) {\n return;\n }\n this.snapshot = snapshot;\n this.listeners.forEach((listener) => listener());\n };\n}\n\n/**\n * Returns the store of the list, shared between all the mounted hooks showing it.\n * Server renders never share one: a client can serve many users at the same time.\n */\nexport const getInfiniteStore = (key: string, options: InfiniteStoreOptions) => {\n const { client } = options.request;\n if (client.mode === \"server\" || typeof window === \"undefined\") {\n return new InfiniteStore(key, options);\n }\n\n const clientStores = getStores(client);\n let store = clientStores.get(key);\n if (!store) {\n store = new InfiniteStore(key, options);\n clientStores.set(key, store);\n store.scheduleUnusedCheck();\n }\n return store;\n};\n","import { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n ExtractErrorType,\n Pagination,\n PaginationConfig,\n PaginationItem,\n RequestInstance,\n} from \"@hyper-fetch/core\";\nimport { replaceEqualDeep } from \"@hyper-fetch/core\";\nimport { useHydration } from \"hydrate/hydrate\";\nimport { useProvider } from \"provider\";\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\n\nimport { useInfiniteFetchDefaultOptions } from \"./use-infinite-fetch.constants\";\nimport type { InfiniteStore } from \"./use-infinite-fetch.store\";\nimport { getInfiniteStore } from \"./use-infinite-fetch.store\";\nimport type { InfiniteSnapshot } from \"./use-infinite-fetch.store.types\";\nimport type { UseInfiniteFetchOptionsType, UseInfiniteFetchReturnType } from \"./use-infinite-fetch.types\";\nimport { getInfiniteKey, getShouldKeepPreviousList, getUniqueItems } from \"./use-infinite-fetch.utils\";\n\n// What decides about a returned value - the list on screen also depends on the new list still loading\nconst trackedSources: Record<string, (keyof InfiniteSnapshot)[]> = {\n items: [\"items\", \"loading\"],\n pages: [\"data\", \"loading\"],\n pageParams: [\"pageParams\", \"loading\"],\n total: [\"total\", \"loading\"],\n isPreviousData: [\"data\", \"loading\"],\n loading: [\"data\", \"loading\"],\n};\n\nconst trackedKeys = [\n \"items\",\n \"pages\",\n \"pageParams\",\n \"total\",\n \"hasNextPage\",\n \"hasPreviousPage\",\n \"loading\",\n \"isFetching\",\n \"isRefetching\",\n \"isFetchingNextPage\",\n \"isFetchingPreviousPage\",\n \"isFetchNextPageError\",\n \"isFetchPreviousPageError\",\n \"isPreviousData\",\n \"error\",\n \"status\",\n \"extra\",\n \"success\",\n] as const;\n\n/**\n * Loads a list page by page. Say which fields page through the request, and the hook takes care of the rest:\n * every page is a normal request under its own cache key, and the hook glues them together.\n *\n * A changed filter, sort or URL param starts a new list on its own. When to load more is up to you - call\n * `fetchNextPage` from a button, an intersection observer, `onEndReached` or a virtualizer.\n *\n * @param request Request instance\n * @param options Hook options, `pagination` is required\n * @returns\n * @example\n * ```tsx\n * const { items, hasNextPage, fetchNextPage } = useInfiniteFetch(getFeed.setQueryParams({ topic }), {\n * pagination: { cursor: \"cursor\", next: \"nextCursor\", items: \"data\" },\n * });\n * ```\n */\nexport const useInfiniteFetch = <\n R extends RequestInstance,\n const P extends Pagination<R>,\n TSelected = PaginationItem<R, P>[],\n>(\n request: R,\n options: UseInfiniteFetchOptionsType<R, P, TSelected>,\n): UseInfiniteFetchReturnType<R, P, TSelected> => {\n const { config: globalConfig } = useProvider();\n const {\n pagination,\n uniqueBy,\n maxPages,\n select,\n suspense,\n throwOnError,\n dependencies,\n disabled,\n dependencyTracking,\n revalidate,\n keepPreviousData,\n refresh,\n refreshTime,\n refetchBlurred,\n refetchOnBlur,\n refetchOnFocus,\n refetchOnReconnect,\n structuralSharing,\n bounce,\n bounceType,\n bounceTime,\n bounceTimeout,\n } = {\n ...useInfiniteFetchDefaultOptions,\n ...globalConfig.useInfiniteFetchConfig,\n ...options,\n };\n\n const { client } = request;\n const hydration = useHydration();\n\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({ interval: bounceTime, timeout: bounceTimeout });\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n // ******************\n // Store\n // ******************\n\n const key = getInfiniteKey(request, pagination, maxPages);\n const storeRef = useRef<InfiniteStore | null>(null);\n const storeClientRef = useRef(client);\n\n if (!storeRef.current || storeRef.current.key !== key || storeClientRef.current !== client) {\n storeClientRef.current = client;\n storeRef.current = getInfiniteStore(key, {\n request,\n pagination: pagination as PaginationConfig,\n maxPages,\n structuralSharing,\n hydration,\n });\n }\n const store = storeRef.current;\n\n // Rerenders only when something the component reads has changed\n const usedKeys = useRef(new Set<string>()).current;\n const renderedRef = useRef<{ store: InfiniteStore; snapshot: InfiniteSnapshot } | null>(null);\n\n const getSnapshot = () => {\n const next = store.getSnapshot();\n const rendered = renderedRef.current;\n\n if (dependencyTracking && rendered?.store === store) {\n const hasChanged = [...usedKeys].some((usedKey) => {\n const sources = trackedSources[usedKey] ?? [usedKey as keyof InfiniteSnapshot];\n return sources.some((source) => rendered.snapshot[source] !== next[source]);\n });\n if (!hasChanged) {\n return rendered.snapshot;\n }\n }\n\n renderedRef.current = { store, snapshot: next };\n return next;\n };\n\n const snapshot = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);\n\n // ******************\n // Latest values\n // ******************\n\n const callbacks = useRef<{\n onSuccess?: (event: any) => void;\n onError?: (event: any) => void;\n onFinished?: (event: any) => void;\n onReset?: VoidFunction;\n }>({});\n\n const latest = useRef({ disabled, revalidate, refetchOnBlur, refetchOnFocus, refetchOnReconnect });\n latest.current = { disabled, revalidate, refetchOnBlur, refetchOnFocus, refetchOnReconnect };\n\n // ******************\n // Lifecycle\n // ******************\n\n useEffect(() => {\n store.setPagination(pagination as PaginationConfig);\n });\n\n useEffect(() => {\n return store.onPage((event) => {\n if (event.response.success) {\n callbacks.current.onSuccess?.(event);\n } else {\n callbacks.current.onError?.(event);\n }\n callbacks.current.onFinished?.(event);\n });\n }, [store]);\n\n /**\n * A new list stops the pages of the previous one, so a late response never gets in the way\n */\n const mountedStore = useRef<InfiniteStore | null>(null);\n\n useEffect(() => {\n const previous = mountedStore.current;\n mountedStore.current = store;\n\n if (previous && previous !== store) {\n previous.cancelIfUnused();\n callbacks.current.onReset?.();\n }\n if (disabled) {\n return;\n }\n\n if (bounce && previous && previous !== store && !store.hasPages()) {\n bounceFunction(() => {\n // The list could have been left for another one, or disabled, before the bounce settled\n if (mountedStore.current === store && !latest.current.disabled) {\n store.start({ revalidate: latest.current.revalidate });\n }\n });\n } else {\n store.start({ revalidate });\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [store, disabled]);\n\n useEffect(() => {\n if (disabled) {\n return;\n }\n return store.enable();\n }, [store, disabled]);\n\n // Effects run again in StrictMode and when a hidden list is shown - only changed values are a reason to refetch\n const usedDependencies = useRef(dependencies);\n\n useEffect(() => {\n const previous = usedDependencies.current;\n usedDependencies.current = dependencies;\n\n const hasChanged =\n previous.length !== dependencies.length ||\n previous.some((value, index) => !Object.is(value, dependencies[index]));\n if (hasChanged && !disabled) {\n store.refetch();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n\n useEffect(() => {\n const { appManager } = client;\n const handle = (option: \"refetchOnBlur\" | \"refetchOnFocus\" | \"refetchOnReconnect\") => () => {\n if (latest.current[option] && !latest.current.disabled) {\n store.revalidate();\n }\n };\n\n const unmountFocus = appManager.events.onFocus(handle(\"refetchOnFocus\"));\n const unmountBlur = appManager.events.onBlur(handle(\"refetchOnBlur\"));\n const unmountOnline = appManager.events.onOnline(handle(\"refetchOnReconnect\"));\n\n return () => {\n unmountFocus();\n unmountBlur();\n unmountOnline();\n };\n }, [client, store]);\n\n useEffect(() => {\n if (!refresh || disabled) {\n return;\n }\n\n const timer = setInterval(() => {\n if (client.appManager.isFocused || refetchBlurred) {\n store.revalidate();\n }\n }, refreshTime);\n\n return () => clearInterval(timer);\n }, [client, store, refresh, refreshTime, refetchBlurred, disabled]);\n\n // ******************\n // Previous list\n // ******************\n\n const previousList = useRef<{ store: InfiniteStore; request: RequestInstance; snapshot: InfiniteSnapshot } | null>(\n null,\n );\n\n useEffect(() => {\n if (snapshot.data.length > 0) {\n previousList.current = { store, request, snapshot };\n }\n });\n\n const previous = previousList.current;\n const isPreviousData =\n !disabled &&\n snapshot.loading &&\n snapshot.data.length === 0 &&\n !!previous &&\n previous.store !== store &&\n getShouldKeepPreviousList(keepPreviousData, previous.request, request);\n\n const list = isPreviousData ? previous.snapshot : snapshot;\n\n // ******************\n // Suspense\n // ******************\n\n const isServer = client.mode === \"server\" || typeof window === \"undefined\";\n\n if (suspense && !disabled && !isServer && snapshot.loading && !isPreviousData) {\n throw store.start({ revalidate });\n }\n\n // ******************\n // Items\n // ******************\n\n const uniqueByRef = useRef(uniqueBy);\n uniqueByRef.current = uniqueBy;\n const uniqueByKey = typeof uniqueBy === \"function\" ? uniqueBy.toString() : uniqueBy;\n\n const uniqueItems = useMemo(() => {\n return getUniqueItems(list.items, uniqueByRef.current);\n // Inline functions change on every render, the key changes only with their code\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [list.items, uniqueByKey]);\n\n const selectedRef = useRef<unknown>(null);\n let items: unknown = uniqueItems;\n let selectError: unknown = null;\n\n if (select) {\n try {\n const selected = select({ items: uniqueItems as PaginationItem<R, P>[], pages: list.data as any[] });\n items = structuralSharing ? replaceEqualDeep(selectedRef.current, selected) : selected;\n selectedRef.current = items;\n } catch (error) {\n // Like in TanStack Query, a failing select is the error of the list and the last selected value stays\n selectError = error;\n items = selectedRef.current;\n }\n }\n\n const error = (selectError ?? snapshot.error) as ExtractErrorType<R> | null;\n\n // ******************\n // Error boundary\n // ******************\n\n if (throwOnError) {\n usedKeys.add(\"error\");\n usedKeys.add(\"isFetching\");\n\n const shouldThrow = typeof throwOnError === \"function\" ? !!error && throwOnError(error) : !!error;\n\n if (shouldThrow && !snapshot.isFetching) {\n store.evictSoon();\n throw error;\n }\n }\n\n // ******************\n // Actions\n // ******************\n\n const actions = useMemo(\n () => ({\n fetchNextPage: () => store.fetchNextPage(),\n fetchPreviousPage: () => store.fetchPreviousPage(),\n refetch: () => store.refetch(),\n reset: () => {\n callbacks.current.onReset?.();\n return store.reset();\n },\n abort: () => store.abort(),\n onSuccess: (callback: (event: any) => void) => {\n callbacks.current.onSuccess = callback;\n },\n onError: (callback: (event: any) => void) => {\n callbacks.current.onError = callback;\n },\n onFinished: (callback: (event: any) => void) => {\n callbacks.current.onFinished = callback;\n },\n onReset: (callback: VoidFunction) => {\n callbacks.current.onReset = callback;\n },\n }),\n [store],\n );\n\n return createTrackedProxy(\n {\n items,\n pages: list.data,\n pageParams: list.pageParams,\n total: list.total,\n hasNextPage: snapshot.hasNextPage,\n hasPreviousPage: snapshot.hasPreviousPage,\n loading: !disabled && snapshot.loading && !isPreviousData,\n isFetching: snapshot.isFetching,\n isRefetching: snapshot.isRefetching,\n isFetchingNextPage: snapshot.isFetchingNextPage,\n isFetchingPreviousPage: snapshot.isFetchingPreviousPage,\n isFetchNextPageError: snapshot.isFetchNextPageError,\n isFetchPreviousPageError: snapshot.isFetchPreviousPageError,\n isPreviousData,\n error,\n status: snapshot.status,\n extra: snapshot.extra,\n success: !selectError && snapshot.success,\n bounce: getBounceData(bounceData),\n ...actions,\n },\n trackedKeys,\n (usedKey) => usedKeys.add(usedKey),\n ) as unknown as UseInfiniteFetchReturnType<R, P, TSelected>;\n};\n","import { useForceUpdate } from \"@better-hooks/lifecycle\";\nimport { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n ExtractAdapterResolvedType,\n RequestInstance,\n ResponseType,\n ExtractResponseType,\n ExtractErrorType,\n RequestSendOptionsType,\n RequestSendType,\n ExtractAdapterType,\n} from \"@hyper-fetch/core\";\nimport { runUserCode, sendRequest } from \"@hyper-fetch/core\";\nimport type { UseTrackedStateType } from \"helpers\";\nimport { useTrackedState, useRequestEvents } from \"helpers\";\nimport type { UseSubmitOptionsType, UseSubmitReturnType } from \"hooks/use-submit\";\nimport { useSubmitDefaultOptions } from \"hooks/use-submit\";\nimport { useProvider } from \"provider\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\n\n/**\n * This hook aims to mutate data on the server. Unlike useFetch, it does not fire automatically -\n * call the returned `submit` function to trigger the request (e.g., on button click).\n * @param request\n * @param options\n * @returns\n */\nexport const useSubmit = <RequestType extends RequestInstance, TSelected = ExtractResponseType<RequestType>>(\n request: RequestType,\n options?: UseSubmitOptionsType<RequestType, TSelected>,\n): UseSubmitReturnType<RequestType, TSelected> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const mergedOptions: UseSubmitOptionsType<RequestType, TSelected> = useMemo(\n () => ({\n ...useSubmitDefaultOptions,\n ...globalConfig.useSubmitConfig,\n ...options,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [globalConfig.useSubmitConfig, JSON.stringify(options), options?.deepCompare],\n );\n const {\n disabled,\n dependencyTracking,\n initialResponse,\n bounce,\n bounceType,\n bounceTime,\n deepCompare,\n structuralSharing,\n } = mergedOptions;\n\n /**\n * Because of the dynamic cacheKey / queryKey signing within the request we need to store it's latest instance\n * so the events got triggered properly and show the latest result without mixing it up\n */\n const { client } = request;\n const { cache, submitDispatcher: dispatcher, loggerManager } = client;\n\n const logger = useRef(loggerManager.initialize(client, \"useSubmit\")).current;\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({\n interval: bounceTime,\n timeout: \"bounceTimeout\" in mergedOptions ? mergedOptions.bounceTimeout : bounceTime,\n });\n const forceUpdate = useForceUpdate();\n // Resolvers of the submit calls waiting for the bounced request\n const bounceResolver = useRef<\n | null\n | ((\n value: ResponseType<\n ExtractResponseType<RequestType>,\n ExtractErrorType<RequestType>,\n ExtractAdapterType<RequestType>\n >,\n ) => void)\n >(null);\n\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n // Bounce state shown by this render\n const isBounceActive = bounceData.active;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n /**\n * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues\n */\n const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<RequestType, TSelected>(\n {\n logger,\n request,\n dispatcher,\n initialResponse,\n deepCompare: deepCompare as boolean,\n dependencyTracking: dependencyTracking as boolean,\n // Read directly from options - functions are not part of the memoized options key\n select: options?.select,\n structuralSharing,\n },\n );\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [callbacks, listeners] = useRequestEvents({\n logger,\n actions,\n request,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners, removeLifecycleListener } = listeners;\n\n // ******************\n // Submitting\n // ******************\n\n /**\n * Response for the submit calls which did not send any request. The submit promise never rejects,\n * so the reason is returned as an error response.\n */\n const getNotSentResponse = (message: string) => {\n const timestamp = Date.now();\n return {\n data: null,\n error: new Error(message),\n status: null,\n success: false,\n extra: request.client.adapter.defaultExtra,\n requestTimestamp: timestamp,\n responseTimestamp: timestamp,\n } as ResponseType<ExtractResponseType<RequestType>, ExtractErrorType<RequestType>, ExtractAdapterType<RequestType>>;\n };\n\n /**\n * Bounced submit calls wait for the request to be triggered. When it will not happen anymore (bounce got reset,\n * call got dropped or the hook unmounted) we have to resolve them - the submit promise can never stay pending.\n */\n const resolveBouncedCalls = (message: string) => {\n const resolvePending = bounceResolver.current;\n bounceResolver.current = null;\n resolvePending?.(getNotSentResponse(message));\n };\n\n const handleSubmit: RequestSendType<RequestType> = (submitOptions?: RequestSendOptionsType<RequestType>) => {\n if (disabled) {\n logger.warning({ title: `Cannot submit request`, type: \"system\", extra: { disabled, submitOptions } });\n return Promise.resolve(getNotSentResponse(\"Cannot submit request. Option 'disabled' is enabled\"));\n }\n\n const { optimistic: submitOptimistic, ...cloneOptions } = submitOptions || {};\n const requestClone = request.clone(cloneOptions as any) as unknown as RequestType;\n // Read directly from options - functions are not part of the memoized options key\n const optimistic = submitOptimistic ?? options?.optimistic;\n\n const triggerRequest = () => {\n addCacheDataListener(requestClone);\n\n const configuration: RequestSendOptionsType<RequestType> = {\n dispatcherType: \"submit\",\n ...(submitOptions as RequestSendOptionsType<RequestType>),\n optimistic,\n onBeforeSent: (data) => {\n // Deduplicated submit joins the request which is already in flight and shares its id.\n // We keep a single set of listeners for it, so the callbacks fire once per response.\n removeLifecycleListener(data.requestId);\n addLifecycleListeners(requestClone, data.requestId, data.mutationContext);\n submitOptions?.onBeforeSent?.(data);\n },\n onResponse: (data) => {\n // This is the final response (retries and waiting for the network are over) and our listeners already\n // handled it. Dispatcher does not announce the removal of every request (e.g. the canceled ones),\n // so we release the listeners here to not leak them.\n removeLifecycleListener(data.requestId);\n submitOptions?.onResponse?.(data);\n },\n };\n\n return sendRequest(requestClone, configuration);\n };\n\n return new Promise<ExtractAdapterResolvedType<RequestType>>((resolve) => {\n const performSubmit = async () => {\n logger.debug({ title: `Submitting request`, type: \"system\", extra: { disabled, submitOptions } });\n if (bounce) {\n const bouncedResolve = bounceResolver.current;\n // We need to keep the resolve of debounced requests to prevent memory leaks - we need to always resolve promise.\n // By default bounce method will prevent function to be triggered, but returned promise will still await to be resolved.\n // This way we can close previous promise, making sure our logic will not stuck in memory.\n bounceResolver.current = (\n value: ResponseType<\n ExtractResponseType<RequestType>,\n ExtractErrorType<RequestType>,\n ExtractAdapterType<RequestType>\n >,\n ) => {\n // Trigger previous awaiting calls to resolve together in bounced batches\n bouncedResolve?.(value);\n resolve(value);\n };\n\n let isTriggered = false;\n\n // Start bounce\n bounceFunction(async () => {\n isTriggered = true;\n // We will always resolve previous calls as we stack the callbacks together until bounce function trigger\n const callback = bounceResolver.current;\n // Clean bounce resolvers to start the new stack\n bounceResolver.current = null;\n\n const value = await triggerRequest();\n callback?.(value);\n });\n\n // Throttle without the trailing timeout drops the calls made during the interval - nothing will trigger them\n if (!isTriggered && !bounceData.active) {\n resolveBouncedCalls(\"Request was not sent. Submit call got dropped by the throttle\");\n }\n\n // Throttle does not notify about the call it holds, so the returned bounce state would stay outdated\n if (bounceData.active !== isBounceActive) {\n forceUpdate();\n }\n } else {\n const value = await triggerRequest();\n resolve(value);\n }\n };\n\n performSubmit();\n });\n };\n\n // ******************\n // Invalidation\n // ******************\n\n const handleRefetch = () => {\n cache.invalidate(request);\n };\n\n // ******************\n // Stable methods\n // ******************\n\n // The returned methods keep their identity between renders (safe to use in the dependency arrays)\n // and always work with the request and options from the latest render\n const latest = useRef({ handleSubmit, handleRefetch, resolveBouncedCalls });\n latest.current = { handleSubmit, handleRefetch, resolveBouncedCalls };\n\n const submit = useCallback(\n ((submitOptions?: RequestSendOptionsType<RequestType>) =>\n (latest.current.handleSubmit as (options?: RequestSendOptionsType<RequestType>) => unknown)(\n submitOptions,\n )) as unknown as RequestSendType<RequestType>,\n [],\n );\n\n const refetch = useCallback(() => latest.current.handleRefetch(), []);\n\n // ******************\n // Bounce\n // ******************\n\n const resetBounce = () => {\n const wasActive = bounceData.active;\n bounceData.reset();\n resolveBouncedCalls(\"Request was not sent. Bounce got reset before triggering the request\");\n // Reset does not notify about the change on its own\n if (wasActive) {\n forceUpdate();\n }\n };\n\n // ******************\n // Misc\n // ******************\n\n const handlers = useMemo(() => {\n /**\n * Callbacks run inside of the request lifecycle. Error thrown by one of them would break it - the request\n * would never finish and it would block the queue. Such error is thrown outside of the lifecycle instead,\n * the same way as the errors of every other callback, listener and plugin.\n */\n const protect = <Args extends unknown[]>(callback: (...args: Args) => void | Promise<void>) => {\n return (...args: Args): void => {\n runUserCode(() => {\n callback(...args);\n });\n };\n };\n\n return {\n onSubmitSuccess: (callback: Parameters<typeof callbacks.onSuccess>[0]) => callbacks.onSuccess(protect(callback)),\n onSubmitError: (callback: Parameters<typeof callbacks.onError>[0]) => callbacks.onError(protect(callback)),\n onSubmitFinished: (callback: Parameters<typeof callbacks.onFinished>[0]) =>\n callbacks.onFinished(protect(callback)),\n onSubmitRequestStart: (callback: Parameters<typeof callbacks.onRequestStart>[0]) =>\n callbacks.onRequestStart(protect(callback)),\n onSubmitResponseStart: (callback: Parameters<typeof callbacks.onResponseStart>[0]) =>\n callbacks.onResponseStart(protect(callback)),\n onSubmitDownloadProgress: (callback: Parameters<typeof callbacks.onDownloadProgress>[0]) =>\n callbacks.onDownloadProgress(protect(callback) as typeof callback),\n onSubmitUploadProgress: (callback: Parameters<typeof callbacks.onUploadProgress>[0]) =>\n callbacks.onUploadProgress(protect(callback) as typeof callback),\n onSubmitOfflineError: (callback: Parameters<typeof callbacks.onOfflineError>[0]) =>\n callbacks.onOfflineError(protect(callback)),\n onSubmitAbort: (callback: Parameters<typeof callbacks.onAbort>[0]) => callbacks.onAbort(protect(callback)),\n };\n }, [callbacks]);\n\n // ******************\n // Lifecycle\n // ******************\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without the cache subscription.\n // When the request changes, we follow the data of the new one.\n useEffect(() => {\n addCacheDataListener(request);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [request.cacheKey, request.queryKey, request.scope]);\n\n // Bounce timers get cleared on unmount, so the waiting submit calls would never get resolved\n useEffect(() => {\n return () => {\n latest.current.resolveBouncedCalls(\"Request was not sent. Hook got unmounted before triggering the request\");\n };\n }, []);\n\n const setSubmitRenderKey = (key: string) => {\n setRenderKey((key === \"submitting\" ? \"loading\" : key) as keyof UseTrackedStateType);\n };\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"submitting\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n submit,\n data: state.data,\n error: state.error,\n submitting: state.loading,\n status: state.status,\n success: state.success,\n extra: state.extra,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n abort: callbacks.abort,\n ...actions,\n ...handlers,\n bounce: { ...getBounceData(bounceData), reset: resetBounce },\n refetch,\n },\n trackedKeys,\n setSubmitRenderKey,\n ) as UseSubmitReturnType<RequestType, TSelected>;\n};\n","import type { RequestInstance, RequiredKeys } from \"@hyper-fetch/core\";\n\nimport type { UseSubmitOptionsType } from \"./use-submit.types\";\n\ntype DefaultOptionsType = RequiredKeys<\n Omit<UseSubmitOptionsType<RequestInstance>, \"initialResponse\" | \"select\" | \"optimistic\">\n> & {\n initialResponse: null;\n};\n\nexport const useSubmitDefaultOptions: DefaultOptionsType = {\n disabled: false,\n dependencyTracking: true,\n initialResponse: null,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n deepCompare: true,\n structuralSharing: true,\n};\n","import type {\n ProgressType,\n RequestInstance,\n ResolvedQueueItemType,\n QueueDataType,\n QueueItemType,\n} from \"@hyper-fetch/core\";\nimport { Request, getRequestDispatcher, scopeKey } from \"@hyper-fetch/core\";\nimport type { UseQueueOptionsType, QueueRequest, UseQueueReturnType } from \"hooks/use-queue\";\nimport { useQueueDefaultOptions } from \"hooks/use-queue\";\nimport { useProvider } from \"provider\";\nimport { useState, useEffect, useCallback } from \"react\";\n\nconst canUpdate = (\n item: Pick<QueueRequest<RequestInstance>, \"success\" | \"failed\" | \"canceled\" | \"removed\" | \"resolved\">,\n) => {\n if (item.success || item.failed) {\n return false;\n }\n return true;\n};\n\nconst getInitialProgress = (): ProgressType => ({\n progress: 0,\n timeLeft: 0,\n sizeLeft: 0,\n total: 0,\n loaded: 0,\n startTimestamp: 0,\n});\n\n/**\n * This hook allows you to monitor and control dispatcher request queues for a given request,\n * including starting, stopping, pausing, and inspecting pending/in-flight items.\n * @param request\n * @param options\n * @returns\n */\nexport const useQueue = <Request extends RequestInstance>(\n request: Request,\n options?: UseQueueOptionsType,\n): UseQueueReturnType<Request> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const { dispatcherType, keepFinishedRequests } = {\n ...useQueueDefaultOptions,\n ...globalConfig.useQueueConfig,\n ...options,\n };\n\n const { abortKey: rawAbortKey, queryKey: rawQueryKey, scope, client } = request;\n const abortKey = scopeKey(rawAbortKey, scope);\n const queryKey = scopeKey(rawQueryKey, scope);\n const { requestManager } = client;\n\n const [dispatcher] = getRequestDispatcher(request, dispatcherType);\n\n // ******************\n // Mapping\n // ******************\n\n const createRequestsArray = useCallback(\n (\n queueElements: ResolvedQueueItemType<Request>[],\n prevRequests: QueueRequest<Request>[] = [],\n ): QueueRequest<Request>[] => {\n const previous = new Map(prevRequests.map((el) => [el.requestId, el]));\n\n // The list mirrors the dispatcher queue - requests we already track keep their local state\n // (progress and result flags) and get the latest queue values (stopped, retries, resolved)\n const current = new Map(\n queueElements.map((req) => {\n const tracked = previous.get(req.requestId);\n const item: QueueRequest<Request> = tracked\n ? { ...tracked, ...req }\n : {\n failed: false,\n canceled: false,\n removed: false,\n success: false,\n ...req,\n downloading: getInitialProgress(),\n uploading: getInitialProgress(),\n stopRequest: () => dispatcher.stopRequest(queryKey, req.requestId),\n startRequest: () => dispatcher.startRequest(queryKey, req.requestId),\n deleteRequest: () => dispatcher.delete(queryKey, req.requestId, abortKey),\n };\n return [req.requestId, item];\n }),\n );\n\n if (!keepFinishedRequests) {\n return [...current.values()];\n }\n\n // Requests that left the queue keep their place, new ones are added at the end\n const kept = prevRequests.map((el) => current.get(el.requestId) || el);\n const added = [...current.values()].filter((el) => !previous.has(el.requestId));\n\n return [...kept, ...added];\n },\n [abortKey, dispatcher, queryKey, keepFinishedRequests],\n );\n\n // ******************\n // State\n // ******************\n\n // Read the queue right away, so the first render already shows its real state\n const [stopped, setStopped] = useState(() => dispatcher.getQueue<Request>(queryKey).stopped);\n const [requests, setRequests] = useState<QueueRequest<Request>[]>(() =>\n createRequestsArray(dispatcher.getQueue<Request>(queryKey).requests),\n );\n\n const mergePayloadType = useCallback((requestId: string, data: Partial<QueueRequest<Request>>) => {\n setRequests((prev) =>\n prev.map((el) => {\n if (el.requestId === requestId && canUpdate(el)) {\n return { ...el, ...data };\n }\n return el;\n }),\n );\n }, []);\n\n const getInitialState = () => {\n const requestQueue = dispatcher.getQueue<Request>(queryKey);\n\n setStopped(requestQueue.stopped);\n setRequests(createRequestsArray(requestQueue.requests));\n };\n\n const resolveQueueItems = useCallback(\n (items: QueueItemType<Request>[]): ResolvedQueueItemType<Request>[] => {\n return items.map((item) => {\n if (item.request instanceof Request) {\n return item as ResolvedQueueItemType<Request>;\n }\n return { ...item, request: client.fromJSON(item.request) as Request };\n });\n },\n [client],\n );\n\n const updateQueueState = useCallback(\n (values: QueueDataType<Request>) => {\n setStopped(values.stopped);\n setRequests((prev) => createRequestsArray(resolveQueueItems(values.requests), prev));\n },\n [createRequestsArray, resolveQueueItems],\n );\n\n // ******************\n // Events\n // ******************\n\n const mountEvents = () => {\n const unmountChange = dispatcher.events.onQueueChangeByKey<Request>(queryKey, updateQueueState);\n const unmountStatus = dispatcher.events.onQueueStatusChangeByKey<Request>(queryKey, updateQueueState);\n\n const unmountResponse = requestManager.events.onResponse(({ requestId, response, details }) => {\n setRequests((prev) =>\n prev.map((el) => {\n if (el.requestId !== requestId) {\n return el;\n }\n if (response.success) {\n return { ...el, success: true };\n }\n // The request is not done yet when it will be sent again - after the retry time,\n // once the queue gets started again or when the network connection is back\n const isRepeated =\n !!details?.willRetry || !!details?.isCanceled || (!!details?.isOffline && !!el.request.offline);\n return isRepeated ? el : { ...el, failed: true };\n }),\n );\n });\n const unmountCanceled = requestManager.events.onAbort(({ requestId }) => {\n setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, canceled: true } : el)));\n });\n // Canceled request can be sent again - for example after starting the stopped queue\n const unmountStarted = requestManager.events.onRequestStart(({ requestId }) => {\n setRequests((prev) =>\n prev.map((el) => (el.requestId === requestId && el.canceled ? { ...el, canceled: false } : el)),\n );\n });\n\n const unmountRemoved = requestManager.events.onRemove(({ requestId }) => {\n setRequests((prev) =>\n prev.map((el) => (el.requestId === requestId && canUpdate(el) ? { ...el, removed: true } : el)),\n );\n });\n\n const unmountDownload = requestManager.events.onDownloadProgress(\n ({ progress, timeLeft, sizeLeft, total, loaded, startTimestamp, requestId }) => {\n mergePayloadType(requestId, { downloading: { progress, timeLeft, sizeLeft, total, loaded, startTimestamp } });\n },\n );\n\n const unmountUpload = requestManager.events.onUploadProgress(\n ({ progress, timeLeft, sizeLeft, total, loaded, startTimestamp, requestId }) => {\n mergePayloadType(requestId, { uploading: { progress, timeLeft, sizeLeft, total, loaded, startTimestamp } });\n },\n );\n\n const unmount = () => {\n unmountStatus();\n unmountChange();\n unmountDownload();\n unmountUpload();\n unmountResponse();\n unmountCanceled();\n unmountStarted();\n unmountRemoved();\n };\n\n return unmount;\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n useEffect(getInitialState, [createRequestsArray, dispatcher, queryKey]);\n\n // The handlers only use state updaters, so there is no need to subscribe again when the state changes\n useEffect(mountEvents, [queryKey, dispatcher.events, requestManager.events, updateQueueState, mergePayloadType]);\n\n return {\n stopped,\n requests,\n dispatcher,\n stop: () => dispatcher.stop(queryKey),\n pause: () => dispatcher.pause(queryKey),\n start: () => dispatcher.start(queryKey),\n };\n};\n","import type { RequiredKeys } from \"@hyper-fetch/core\";\nimport type { UseQueueOptionsType } from \"hooks/use-queue\";\n\nexport const useQueueDefaultOptions: RequiredKeys<UseQueueOptionsType> = {\n dispatcherType: \"auto\",\n keepFinishedRequests: false,\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { ExtractResponseType, RequestInstance } from \"@hyper-fetch/core\";\nimport { getRequestDispatcher } from \"@hyper-fetch/core\";\nimport { useRequestEvents, useTrackedState } from \"helpers\";\nimport type { UseCacheOptionsType, UseCacheReturnType } from \"hooks/use-cache\";\nimport { useCacheDefaultOptions } from \"hooks/use-cache\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\nimport { keyReplacer } from \"utils/key.utils\";\n\n/**\n * Options passed as `undefined` (e.g. forwarded optional props) fall back to the defaults instead of overriding them\n */\nconst mergeOptions = <T extends object>(...sources: (object | undefined)[]): T => {\n const merged: Record<string, unknown> = {};\n sources.forEach((source) => {\n Object.entries(source || {}).forEach(([key, value]) => {\n if (value !== undefined) {\n merged[key] = value;\n }\n });\n });\n return merged as T;\n};\n\n/** Subscribe to cache updates for a given request without triggering network activity. */\nexport const useCache = <T extends RequestInstance, TSelected = ExtractResponseType<T>>(\n request: T,\n options?: UseCacheOptionsType<T, TSelected>,\n): UseCacheReturnType<T, TSelected> => {\n const { cacheKey, client } = request;\n\n const { cache, loggerManager } = client;\n const logger = useRef(loggerManager.initialize(client, \"useCache\")).current;\n const [dispatcher] = getRequestDispatcher(request);\n const updateKey = JSON.stringify(request.toJSON(), keyReplacer);\n\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const { dependencyTracking, initialResponse, deepCompare, structuralSharing } = mergeOptions<\n typeof useCacheDefaultOptions & UseCacheOptionsType<T, TSelected>\n >(useCacheDefaultOptions, globalConfig.useCacheConfig, options);\n\n /**\n * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues\n */\n const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<T, TSelected>({\n logger,\n request,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n // Cache observer shows the data of the given key only - nothing would replace the data kept from the previous key\n keepPreviousData: \"clean\",\n select: options?.select,\n structuralSharing,\n });\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [, listeners] = useRequestEvents({\n logger,\n actions,\n request,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners } = listeners;\n\n const handleMountEvents = () => {\n const unmountDataListener = addCacheDataListener(request);\n const unmountLifecycleListener = addLifecycleListeners(request);\n return () => {\n unmountDataListener();\n unmountLifecycleListener();\n };\n };\n\n useDidUpdate(\n () => {\n return handleMountEvents();\n },\n [updateKey],\n true,\n );\n\n const invalidate = (cacheKeys?: string | RegExp | RequestInstance | (string | RegExp | RequestInstance)[]) => {\n cache.invalidate(cacheKeys ?? cacheKey);\n };\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"loading\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n error: state.error,\n loading: state.loading,\n status: state.status,\n success: state.success,\n extra: state.extra,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n ...actions,\n invalidate,\n },\n trackedKeys,\n setRenderKey,\n ) as UseCacheReturnType<T, TSelected>;\n};\n","export const useCacheDefaultOptions = {\n dependencyTracking: true,\n initialResponse: null,\n deepCompare: true,\n structuralSharing: true,\n};\n","import type { RequestInstance, ExtractAdapterExtraType, ExtractAdapterType, ExtractErrorType } from \"@hyper-fetch/core\";\nimport { scopeKey } from \"@hyper-fetch/core\";\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\n\nimport type { UseStreamOptionsType, UseStreamReturnType } from \"./use-stream.types\";\n\ntype StreamState<T extends RequestInstance> = {\n text: string;\n chunks: Uint8Array[];\n streaming: boolean;\n done: boolean;\n error: ExtractErrorType<T> | null;\n extra: ExtractAdapterExtraType<ExtractAdapterType<T>> | null;\n status: number | null;\n};\n\nconst getInitialState = <T extends RequestInstance>(): StreamState<T> => ({\n text: \"\",\n chunks: [],\n streaming: false,\n done: false,\n error: null,\n extra: null,\n status: null,\n});\n\n/**\n * Hook for consuming streaming responses chunk-by-chunk.\n * Works with any request that uses the fetch adapter's `streaming: true` option.\n *\n * Provides both accumulated `text` (for LLM/SSE use cases) and raw `chunks`\n * (for binary streaming / file downloads).\n */\nexport const useStream = <T extends RequestInstance>(\n request: T,\n options?: UseStreamOptionsType,\n): UseStreamReturnType<T> => {\n const { autoStart = false } = options || {};\n\n const state = useRef<StreamState<T>>(getInitialState<T>());\n const abortRef = useRef<(() => void) | null>(null);\n const startedRef = useRef(false);\n\n // useSyncExternalStore for re-renders\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n const consumeStream = async (stream: ReadableStream<Uint8Array>) => {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {break;}\n\n state.current.chunks = [...state.current.chunks, value];\n state.current.text += decoder.decode(value, { stream: true });\n emitChange();\n }\n\n state.current.streaming = false;\n state.current.done = true;\n emitChange();\n } catch (error) {\n state.current.streaming = false;\n state.current.error = error as ExtractErrorType<T>;\n emitChange();\n }\n };\n\n const start = useCallback(() => {\n if (state.current.streaming) {return;}\n\n state.current = {\n ...getInitialState<T>(),\n streaming: true,\n };\n emitChange();\n\n const streamingRequest = request.setOptions({ streaming: true } as any);\n\n streamingRequest.send().then((response) => {\n const { data, error, status, extra } = response;\n\n state.current.status = status as number | null;\n state.current.extra = extra as ExtractAdapterExtraType<ExtractAdapterType<T>> | null;\n\n if (error) {\n state.current.streaming = false;\n state.current.error = error;\n emitChange();\n return;\n }\n\n if (data && typeof (data as any).getReader === \"function\") {\n consumeStream(data as unknown as ReadableStream<Uint8Array>);\n } else {\n state.current.streaming = false;\n state.current.text = typeof data === \"string\" ? data : JSON.stringify(data);\n state.current.done = true;\n emitChange();\n }\n });\n\n abortRef.current = () => {\n request.client.requestManager.abortByKey(scopeKey(request.abortKey, request.scope));\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [request]);\n\n const abort = useCallback(() => {\n abortRef.current?.();\n state.current.streaming = false;\n emitChange();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const reset = useCallback(() => {\n abortRef.current?.();\n state.current = getInitialState<T>();\n startedRef.current = false;\n emitChange();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (autoStart && !startedRef.current) {\n startedRef.current = true;\n start();\n }\n }, [autoStart, start]);\n\n return {\n text: state.current.text,\n chunks: state.current.chunks,\n streaming: state.current.streaming,\n done: state.current.done,\n error: state.current.error,\n extra: state.current.extra,\n status: state.current.status,\n start,\n abort,\n reset,\n };\n};\n","import { useDidUpdate, useWillUnmount } from \"@better-hooks/lifecycle\";\nimport { replaceEqualDeep } from \"@hyper-fetch/core\";\nimport type { ListenerInstance, ExtractListenerDeliveredType } from \"@hyper-fetch/sockets\";\nimport { getDeliveryKey } from \"@hyper-fetch/sockets\";\nimport { useSocketState } from \"helpers\";\nimport type { UseListenerOptionsType } from \"hooks/use-listener\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\n\n/** Subscribe to incoming socket messages on a given listener topic with tracked connection state and callbacks. */\nexport const useListener = <\n ListenerType extends ListenerInstance,\n TSelected = ExtractListenerDeliveredType<ListenerType>,\n>(\n listener: ListenerType,\n options?: UseListenerOptionsType<ExtractListenerDeliveredType<ListenerType>, TSelected>,\n) => {\n const { config: globalConfig } = useProvider();\n const { dependencyTracking = true, structuralSharing = true } = { ...globalConfig.useListener, ...options };\n const select = options?.select;\n const [state, actions, callbacks, { setRenderKey, getState, rerender }] = useSocketState<\n TSelected,\n ListenerType[\"socket\"]\n >(listener.socket, { dependencyTracking });\n const removeListenerRef = useRef<ReturnType<typeof listener.listen> | null>(null);\n\n /**\n * Selection\n */\n\n const selectRef = useRef(select);\n selectRef.current = select;\n const appliedSelect = useRef(select);\n // Last message data before applying the selector - allows to re-run it when the selector changes\n const rawData = useRef<{ data: ExtractListenerDeliveredType<ListenerType> } | null>(null);\n const selectError = useRef<{ error: unknown } | null>(null);\n\n const selectData = (data: ExtractListenerDeliveredType<ListenerType>): TSelected => {\n if (!selectRef.current) {\n return data as unknown as TSelected;\n }\n const selected = selectRef.current(data);\n return structuralSharing ? replaceEqualDeep(getState().data, selected) : selected;\n };\n\n // Selector failed while processing a message - surface it to the closest error boundary\n if (selectError.current) {\n const { error } = selectError.current;\n selectError.current = null;\n throw error;\n }\n\n // Selector changed (e.g. it closes over a new prop) - re-run it against the last message\n if (appliedSelect.current !== select) {\n appliedSelect.current = select;\n if (rawData.current) {\n state.data = selectData(rawData.current.data);\n }\n }\n\n /**\n * Callbacks\n */\n\n const onEventCallback = useRef<\n null | ((response: { data: ExtractListenerDeliveredType<ListenerType>; extra: Record<string, any> }) => void)\n >(null);\n\n /**\n * Actions\n */\n\n const stopListener = () => {\n removeListenerRef.current?.();\n };\n\n const listen = () => {\n stopListener();\n removeListenerRef.current = listener.listen(({ data, extra }) => {\n onEventCallback.current?.({ data, extra });\n rawData.current = { data };\n appliedSelect.current = selectRef.current;\n\n let selected: TSelected;\n try {\n selected = selectData(data);\n } catch (error) {\n // Never throw inside of the socket events - rethrow it on render instead\n selectError.current = { error };\n rerender();\n return;\n }\n\n // With a selector, data is updated only when the selected value changed\n if (!selectRef.current || !Object.is(selected, getState().data)) {\n actions.setData(selected);\n }\n actions.setExtra(extra);\n actions.setTimestamp(Date.now());\n });\n };\n\n const additionalCallbacks = {\n onEvent: (callback: NonNullable<typeof onEventCallback.current>) => {\n onEventCallback.current = callback;\n },\n };\n\n /**\n * Lifecycle\n */\n\n useDidUpdate(\n () => {\n listen();\n },\n // Topic already contains resolved params. Delivery presets compare by value, custom strategies by identity.\n // The socket is a dependency too - the same topic on another socket is a different subscription.\n [listener.socket, listener.topic, JSON.stringify(listener.options), getDeliveryKey(listener.delivery)],\n true,\n );\n\n useWillUnmount(() => {\n stopListener();\n });\n\n const trackedKeys = [\"data\", \"extra\", \"connected\", \"connecting\", \"timestamp\"] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n extra: state.extra,\n connected: state.connected,\n connecting: state.connecting,\n timestamp: state.timestamp,\n ...actions,\n ...callbacks,\n ...additionalCallbacks,\n listen,\n },\n trackedKeys,\n setRenderKey,\n );\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { EmitterInstance, EmitterCallbackErrorType, EmitType } from \"@hyper-fetch/sockets\";\nimport { useSocketState } from \"helpers\";\nimport type { UseEmitterOptionsType } from \"hooks/use-emitter\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\n\n/** Send messages through a socket emitter with tracked connection state and lifecycle callbacks. */\nexport const useEmitter = <EmitterType extends EmitterInstance>(\n emitter: EmitterType,\n options?: UseEmitterOptionsType,\n) => {\n const { config: globalConfig } = useProvider();\n const { dependencyTracking = true } = { ...globalConfig.useEmitter, ...options };\n\n const [state, actions, callbacks, { setRenderKey }] = useSocketState(emitter.socket, { dependencyTracking });\n\n /**\n * Callbacks\n */\n const onEventStartCallback = useRef<null | ((emitter: EmitterType) => void)>(null);\n const onEventErrorCallback = useRef<null | EmitterCallbackErrorType>(null);\n\n useDidUpdate(\n () => {\n const onEventStart = () => {\n return emitter.socket.events.onEmitterStartEventByTopic(emitter, () => {\n onEventStartCallback.current?.(emitter);\n });\n };\n\n const onEventError = () => {\n return emitter.socket.events.onEmitterErrorByTopic(emitter, ({ error }) => {\n onEventErrorCallback.current?.({ error });\n });\n };\n\n const unmountEventStart = onEventStart();\n const unmountEventError = onEventError();\n\n return () => {\n unmountEventStart();\n unmountEventError();\n };\n },\n [emitter.topic, onEventStartCallback.current, onEventErrorCallback.current],\n true,\n );\n\n /**\n * Emitter\n */\n\n const emit: EmitType<EmitterType> = (emitOptions: Parameters<EmitType<EmitterType>>[0]) => {\n return emitter.emit(emitOptions as any);\n };\n\n const onEmit = (callback: (emitter: EmitterType) => void) => {\n onEventStartCallback.current = callback;\n };\n\n const onEmitError = (callback: EmitterCallbackErrorType) => {\n onEventErrorCallback.current = callback;\n };\n\n const trackedKeys = [\"connected\", \"connecting\"] as const;\n\n return createTrackedProxy(\n {\n connected: state.connected,\n connecting: state.connecting,\n ...actions,\n ...callbacks,\n onEmit,\n onEmitError,\n emit,\n },\n trackedKeys,\n setRenderKey,\n );\n};\n","import type { ClientInstance } from \"@hyper-fetch/core\";\nimport type { UseAppManagerReturnType } from \"hooks/use-app-manager\";\nimport { useEffect, useState } from \"react\";\n\n/** Track the application's online/offline and focus/blur state through the client's AppManager. */\nexport const useAppManager = <Client extends ClientInstance>(client: Client): UseAppManagerReturnType => {\n const [online, setIsOnline] = useState(client.appManager.isOnline);\n const [focused, setIsFocused] = useState(client.appManager.isFocused);\n\n const mountEvents = () => {\n // Catch up with anything that happened between the render and the subscription\n setIsOnline(client.appManager.isOnline);\n setIsFocused(client.appManager.isFocused);\n\n const unmountIsOnline = client.appManager.events.onOnline(() => setIsOnline(true));\n const unmountIsOffline = client.appManager.events.onOffline(() => setIsOnline(false));\n const unmountIsFocus = client.appManager.events.onFocus(() => setIsFocused(true));\n const unmountIsBlur = client.appManager.events.onBlur(() => setIsFocused(false));\n\n return () => {\n unmountIsOnline();\n unmountIsOffline();\n unmountIsFocus();\n unmountIsBlur();\n };\n };\n\n const setOnline = (isOnline: boolean) => {\n client.appManager.setOnline(isOnline);\n };\n\n const setFocused = (isFocused: boolean) => {\n client.appManager.setFocused(isFocused);\n };\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without any subscriptions\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(mountEvents, [client]);\n\n return { isOnline: online, isFocused: focused, setOnline, setFocused };\n};\n","import type { AdapterInstance, ClientInstance, Dispatcher } from \"@hyper-fetch/core\";\nimport type { UseIsFetchingOptionsType } from \"hooks/use-is-fetching\";\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\n\nconst useRunningRequestsCount = (\n dispatcher: Dispatcher<AdapterInstance>,\n options?: UseIsFetchingOptionsType,\n): number => {\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const subscribe = useCallback(\n (listener: () => void) => dispatcher.events.onRunningRequestsChange(listener),\n [dispatcher],\n );\n\n const getCount = () => {\n const { queryKey, predicate } = optionsRef.current || {};\n return dispatcher.getAllRunningRequests().filter(({ request }) => {\n if (typeof queryKey === \"string\" && request.queryKey !== queryKey) {\n return false;\n }\n if (queryKey instanceof RegExp && !queryKey.test(request.queryKey)) {\n return false;\n }\n return !predicate || predicate(request);\n }).length;\n };\n\n return useSyncExternalStore(subscribe, getCount, getCount);\n};\n\n/**\n * Count of the currently running fetch requests (useFetch, useCache and fetch dispatcher). Useful for global loading indicators.\n * @param client Client instance\n * @param options Filters for the counted requests\n * @returns number of running requests\n */\nexport const useIsFetching = (client: ClientInstance, options?: UseIsFetchingOptionsType): number => {\n return useRunningRequestsCount(client.fetchDispatcher, options);\n};\n\n/**\n * Count of the currently running submit requests (useSubmit and submit dispatcher). Useful for global saving indicators.\n * @param client Client instance\n * @param options Filters for the counted requests\n * @returns number of running requests\n */\nexport const useIsSubmitting = (client: ClientInstance, options?: UseIsFetchingOptionsType): number => {\n return useRunningRequestsCount(client.submitDispatcher, options);\n};\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;AAAkG,IAA6O,IAAE,SAAS,GAAE,GAAE,GAAE;AAAC,MAAK,MAAI,MAAI,IAAE,CAAC;CAAG,IAAI,IAAEA,OAAE,EAAE;AAAC,YAAG,WAAU;AAAC,MAAG,EAAE,QAAQ,QAAO,GAAG;AAAC,IAAE,UAAQ,CAAC;KAAI,EAAE;GAAMC,MAAE,WAAU;CAAC,IAAI,IAAE,SAAS,GAAE,GAAE;EAAC,IAAI,IAAE,cAAY,OAAO,UAAQ,EAAE,OAAO;AAAU,MAAG,CAAC,EAAE,QAAO;EAAE,IAAI,GAAE,GAAE,IAAE,EAAE,KAAK,EAAE,EAAC,IAAE,EAAE;AAAC,MAAG;AAAC,WAAM,KAAK,MAAI,KAAG,MAAK,MAAI,EAAE,IAAE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AC;EACrF,MAAM,iBAAiB,OAAO,WAAW,OAAO,cAAc,aAAa,KAAK,CAAC;EACjF,MAAM,gBAAgB,OAAO,WAAW,OAAO,aAAa,aAAa,MAAM,CAAC;AAEhF,eAAa;AACX,oBAAiB;AACjB,qBAAkB;AAClB,mBAAgB;AAChB,kBAAe;;;CAInB,MAAM,aAAa,aAAsB;AACvC,SAAO,WAAW,UAAU,SAAS;;CAGvC,MAAM,cAAc,cAAuB;AACzC,SAAO,WAAW,WAAW,UAAU;;AAMzC,WAAU,aAAa,CAAC,OAAO,CAAC;AAEhC,QAAO;EAAE,UAAU;EAAQ,WAAW;EAAS;EAAW;EAAY;;;;ACpCxE,IAAM,2BACJ,YACA,YACW;CACX,MAAM,aAAa,OAAO,QAAQ;AAClC,YAAW,UAAU;CAErB,MAAM,YAAY,aACf,aAAyB,WAAW,OAAO,wBAAwB,SAAS,EAC7E,CAAC,WAAW,CACb;CAED,MAAM,iBAAiB;EACrB,MAAM,EAAE,UAAU,cAAc,WAAW,WAAW,EAAE;AACxD,SAAO,WAAW,uBAAuB,CAAC,QAAQ,EAAE,cAAc;AAChE,OAAI,OAAO,aAAa,YAAY,QAAQ,aAAa,SACvD,QAAO;AAET,OAAI,oBAAoB,UAAU,CAAC,SAAS,KAAK,QAAQ,SAAS,CAChE,QAAO;AAET,UAAO,CAAC,aAAa,UAAU,QAAQ;IACvC,CAAC;;AAGL,QAAO,qBAAqB,WAAW,UAAU,SAAS;;;;;;;;AAS5D,IAAa,iBAAiB,QAAwB,YAA+C;AACnG,QAAO,wBAAwB,OAAO,iBAAiB,QAAQ;;;;;;;;AASjE,IAAa,mBAAmB,QAAwB,YAA+C;AACrG,QAAO,wBAAwB,OAAO,kBAAkB,QAAQ"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["r","f","t","u","a","n","v","y","d","n","o","t","r","e","u","l","c"],"sources":["../../../node_modules/.pnpm/@better-hooks+lifecycle@2.0.0_react@19.2.5/node_modules/@better-hooks/lifecycle/dist/index.esm.js","../../../node_modules/.pnpm/@better-hooks+performance@2.1.0_react@19.2.5/node_modules/@better-hooks/performance/dist/index.esm.js","../src/utils/scope.utils.ts","../src/helpers/use-request-events/use-request-events.hooks.ts","../src/helpers/use-tracked-state/use-tracked-state.constants.ts","../src/hydrate/hydrate.utils.ts","../src/hydrate/hydrate.tsx","../src/utils/deep-equal.utils.ts","../src/utils/bounce.utils.ts","../src/utils/tracked-proxy.utils.ts","../src/helpers/use-tracked-state/use-tracked-state.utils.ts","../src/helpers/use-tracked-state/use-tracked-state.hooks.ts","../src/helpers/use-socket-state/use-socket-state.hooks.ts","../src/helpers/use-socket-state/use-socket-state.constants.ts","../src/provider/provider.tsx","../src/utils/key.utils.ts","../src/hooks/use-fetch/use-fetch.hooks.ts","../src/hooks/use-fetch/use-fetch.utils.ts","../src/hooks/use-fetch/use-fetch.constants.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.constants.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.requests.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts","../src/hooks/use-submit/use-submit.hooks.ts","../src/hooks/use-submit/use-submit.constants.ts","../src/hooks/use-queue/use-queue.hooks.ts","../src/hooks/use-queue/use-queue.constants.ts","../src/hooks/use-cache/use-cache.hooks.ts","../src/hooks/use-cache/use-cache.constants.ts","../src/hooks/use-stream/use-stream.hooks.ts","../src/hooks/use-listener/use-listener.hooks.ts","../src/hooks/use-emitter/use-emitter.hooks.ts","../src/hooks/use-app-manager/use-app-manager.hooks.ts","../src/hooks/use-is-fetching/use-is-fetching.hooks.ts"],"sourcesContent":["import{useRef as r,useEffect as n,useState as t,useCallback as u,useLayoutEffect as c}from\"react\";var e=function(t,u,c){void 0===c&&(c=!1);var e=r(null),o=r(c);n((function(){if(o.current)return function(){t(e.current),e.current=u};o.current=!0}),u)},o=function(t){var u=r(!1);n((function(){if(!u.current)return u.current=!0,t()}),[])},i=function(t,u,c){void 0===c&&(c=!1);var e=r(c);n((function(){if(e.current)return t();e.current=!0}),u)};var f=function(){var r=function(r,n){var t=\"function\"==typeof Symbol&&r[Symbol.iterator];if(!t)return r;var u,c,e=t.call(r),o=[];try{for(;(void 0===n||n-- >0)&&!(u=e.next()).done;)o.push(u.value)}catch(r){c={error:r}}finally{try{u&&!u.done&&(t=e.return)&&t.call(e)}finally{if(c)throw c.error}}return o}(t(0),2)[1];return u((function(){r((function(r){return r+1}))}),[])},a=function(){var t=r(!0);return n((function(){return t.current=!0,function(){t.current=!1}}),[]),t},v=function(n){var t=r(!1);c((function(){if(!t.current)return t.current=!0,n()}),[])},l=function(n,t,u){void 0===u&&(u=!1);var e=r(u);c((function(){if(e.current)return n();e.current=!0}),t)},y=function(n){var t=r(!0);t.current&&n(),t.current=!1},d=function(r){n((function(){return r}),[])};export{e as useDepsChange,o as useDidMount,i as useDidUpdate,f as useForceUpdate,a as useIsMounted,v as useLayoutMount,l as useLayoutUpdate,y as useWillMount,d as useWillUnmount};\n//# sourceMappingURL=index.esm.js.map\n","import{useRef as n,useCallback as t,useEffect as r,useState as e,useMemo as u,useLayoutEffect as c}from\"react\";import{useForceUpdate as o,useDidUpdate as i,useDidMount as l}from\"@better-hooks/lifecycle\";var f=function(e){var u=(e||{}).delay,c=void 0===u?400:u,i=n(!1),l=n(null),f=o(),a=t((function(){i.current&&f()}),[f]),v=function(){null!==l.current&&clearTimeout(l.current),l.current=null},d=t((function(n,t){var r=null!=t?t:c;v(),l.current=setTimeout((function(){l.current=null,n(),a()}),r),a()}),[c,a]);return r((function(){return v}),[]),{get active(){return i.current=!0,!!l.current},debounce:d,reset:v}},a=function(n,t,e){var u=f(t).debounce;r((function(){u(n)}),e)};function v(n,t){var r=\"function\"==typeof Symbol&&n[Symbol.iterator];if(!r)return n;var e,u,c=r.call(n),o=[];try{for(;(void 0===t||t-- >0)&&!(e=c.next()).done;)o.push(e.value)}catch(n){u={error:n}}finally{try{e&&!e.done&&(r=c.return)&&r.call(c)}finally{if(u)throw u.error}}return o}var d=function(n,t){var r=f(t).debounce,u=v(e(n),2),c=u[0],o=u[1];return[c,function(n){return r((function(){return o(n)}))}]},y=function(n){var t=Object.prototype.toString.call(n);return Array.isArray(n)?!n.length:\"object\"==typeof n&&null!==n&&\"[object Object]\"===t&&!Object.keys(n).length},m=function(n,t){var r,e=Object.prototype.toString.call(n),u=Object.prototype.toString.call(t),c=typeof n,o=typeof t,i=function(n){return c===n&&o===n};return e===u&&(null===n&&null===t||(!!(i(\"number\")&&Number.isNaN(n)&&Number.isNaN(t))||(!(!y(n)||!y(t))||(Array.isArray(n)&&Array.isArray(t)?n.length===t.length&&!n.some((function(n,r){return!m(n,t[r])})):i(\"object\")&&(e===(r=\"[object Object]\")&&u===r)?Object.keys(n).length===Object.keys(t).length&&!Object.entries(n).some((function(n){var r=v(n,2),e=r[0],u=r[1];return!m(u,t[e])})):n instanceof Date&&t instanceof Date?+n==+t:n===t))))},s=function(t,e){return r(t,(o=n(c=e),i=n(0),m(c,o.current)||(o.current=c,i.current+=1),u((function(){return o.current}),[i.current])));var c,o,i},b=function(t,r,u){var c=u||{},o=c.immediate,f=void 0===o||o,a=c.disabled,d=void 0!==a&&a,y=v(e(null),2),m=y[0],s=y[1],b=n(t),p=function(){m&&clearInterval(m),s(null)},h=function(){p(),!r&&0!==r||d||s(setInterval((function(){return b.current()}),r))};return i((function(){b.current=t}),[t]),l((function(){if(b.current=t,f)return h(),p})),i((function(){return b.current=t,h(),p}),[r]),{active:null!==m,start:h,stop:p}},p=function(t){var e=t||{},u=e.interval,c=void 0===u?200:u,i=e.timeout,l=void 0===i?200:i,f=n(0),a=n(!0),v=n(!1),d=n(null),y=o(),m=function(){a.current&&(a.current=!1),v.current&&y()},s=function(){null!==d.current&&clearTimeout(d.current),d.current=null};return r((function(){return s}),[]),{get active(){return v.current=!0,!!d.current},throttle:function(n,t){var r,e,u=function(){f.current=Date.now(),n(),m()},o=null!==(r=null==t?void 0:t.interval)&&void 0!==r?r:c,i=null!==(e=null==t?void 0:t.timeout)&&void 0!==e?e:l,v=Date.now()>=f.current+o;a.current&&m(),d.current&&s(),v?u():i&&(d.current=setTimeout((function(){d.current=null,a.current=!0,u()}),i))},reset:s}},h=function(n,t,e){var u=p(t).throttle;r((function(){u(n)}),e)},j=function(n,t){var r=p(t).throttle,u=v(e(n),2),c=u[0],o=u[1];return[c,function(n){return r((function(){return o(n)}))}]},g=function(t,e){var u=n(t);w((function(){u.current=t}),[t]),r((function(){if(e||0===e){var n=setTimeout((function(){return u.current()}),e);return function(){return clearTimeout(n)}}}),[e])},w=!(\"undefined\"==typeof window||void 0===window.document||void 0===window.document.createElement)?c:r;export{f as useDebounce,a as useDebounceEffect,d as useDebounceState,s as useDeepEffect,b as useInterval,w as useIsomorphicEffect,p as useThrottle,h as useThrottleEffect,j as useThrottleState,g as useTimeout};\n//# sourceMappingURL=index.esm.js.map\n","/**\n * Core emits request and cache events by the logical (unscoped) keys, while dispatcher queues and cache storage\n * use the scoped keys. Listeners subscribe by the logical key and use this check to skip events of other scopes.\n * @internal\n */\nexport const isSameScope = (scope: string | null | undefined, otherScope: string | null | undefined): boolean => {\n return (scope ?? null) === (otherScope ?? null);\n};\n","import { useIsMounted, useWillUnmount } from \"@better-hooks/lifecycle\";\nimport type {\n ExtractErrorType,\n ExtractResponseType,\n RequestInstance,\n RequestEventType,\n RequestLoadingEventType,\n RequestRemovedEventType,\n ExtractAdapterType,\n RequestProgressEventType,\n RequestResponseEventType,\n ResponseType,\n OptimisticCallbackResult,\n} from \"@hyper-fetch/core\";\nimport { getErrorMessage, runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport type {\n OnErrorCallbackType,\n OnStartCallbackType,\n OnSuccessCallbackType,\n OnProgressCallbackType,\n OnFinishedCallbackType,\n UseRequestEventsDataMap,\n UseRequestEventsReturnType,\n UseRequestEventsPropsType,\n UseRequestEventsLifecycleMap,\n} from \"helpers\";\nimport { useRef } from \"react\";\nimport { isSameScope } from \"utils/scope.utils\";\n\n/**\n * This is helper hook that handles main Hyper-Fetch event/data flow\n * @internal\n * @param options\n * @returns\n */\nexport const useRequestEvents = <R extends RequestInstance>({\n request,\n dispatcher,\n logger,\n actions,\n setCacheData,\n getIsDataProcessing,\n}: UseRequestEventsPropsType<R>): UseRequestEventsReturnType<R> => {\n const { cache, requestManager } = request.client;\n\n // Always points to the request from the latest render - handlers created once can use it safely\n const requestRef = useRef(request);\n requestRef.current = request;\n const dispatcherRef = useRef(dispatcher);\n dispatcherRef.current = dispatcher;\n\n // ******************\n // Callbacks\n // ******************\n\n const onSuccessCallback = useRef<null | OnSuccessCallbackType<R>>(null);\n const onErrorCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onAbortCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onOfflineErrorCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onFinishedCallback = useRef<null | OnFinishedCallbackType<R>>(null);\n const onRequestStartCallback = useRef<null | OnStartCallbackType<R>>(null);\n const onResponseStartCallback = useRef<null | OnStartCallbackType<R>>(null);\n const onDownloadProgressCallback = useRef<null | OnProgressCallbackType>(null);\n const onUploadProgressCallback = useRef<null | OnProgressCallbackType>(null);\n\n // ******************\n // Listeners unmounting\n // ******************\n\n const lifecycleEvents = useRef<UseRequestEventsLifecycleMap>(new Map());\n const dataEvents = useRef<UseRequestEventsDataMap | null>(null);\n // Sending can outlive the component - the unmount cleanup never sees listeners attached after it ran\n const isMounted = useIsMounted();\n\n const removeLifecycleListener = (requestId: string) => {\n const event = lifecycleEvents.current.get(requestId);\n event?.unmount();\n lifecycleEvents.current.delete(requestId);\n };\n\n const clearLifecycleListeners = () => {\n const events = lifecycleEvents.current;\n const listeners = [...events.values()];\n listeners.forEach((value) => {\n value.unmount();\n });\n events.clear();\n pendingRequests.current.clear();\n };\n\n // ******************\n // Optimistic state\n // ******************\n\n // Rollback and invalidation are settled by the core - here we only deliver the context to the callbacks\n const optimisticResultsRef = useRef<Map<string, OptimisticCallbackResult<any>>>(new Map());\n // Requests which already got their last response - their removal from the queue is only a cleanup\n const settledRequests = useRef(new Set<string>());\n // Requests sent with their ids (useSubmit) which are submitted or in flight. The hook is loading as long as there\n // are any - also between two queued requests and when the requests have different keys.\n const pendingRequests = useRef(new Set<string>());\n // Queue which the loading and data listeners follow - the one of the latest request\n const listenedQueryKey = useRef<string | null>(null);\n\n // ******************\n // Response handlers\n // ******************\n\n const handleResponseCallbacks = (values: RequestResponseEventType<R>) => {\n const { success } = values.response;\n const { isOffline, isCanceled, willRetry } = values.details;\n const opt = optimisticResultsRef.current.get(values.requestId);\n const paramsWithContext = { ...values, mutationContext: opt?.context } as any;\n const isOfflineError = request.offline && isOffline && !success;\n\n if (isOfflineError) {\n logger.debug({ title: \"Performing offline error callback\", type: \"system\", extra: values });\n onOfflineErrorCallback.current?.(paramsWithContext);\n } else if (isCanceled) {\n logger.debug({ title: \"Performing abort callback\", type: \"system\", extra: values });\n onAbortCallback.current?.(paramsWithContext);\n } else if (success) {\n logger.debug({ title: \"Performing success callback\", type: \"system\", extra: values });\n onSuccessCallback.current?.(paramsWithContext);\n } else {\n logger.debug({ title: \"Performing error callback\", type: \"system\", extra: values });\n onErrorCallback.current?.(paramsWithContext);\n }\n onFinishedCallback.current?.(paramsWithContext);\n // Retried and offline requests respond again, their callbacks still need the context\n if (!willRetry && (!isOfflineError || isCanceled)) {\n optimisticResultsRef.current.delete(values.requestId);\n }\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n const handleGetLoadingEvent = (req: R) => {\n return ({ loading, request: eventRequest }: RequestLoadingEventType<RequestInstance>) => {\n // Loading events are emitted by the logical queryKey - skip requests of other scopes\n if (!isSameScope(eventRequest.scope, req.scope)) {\n return;\n }\n\n const isProcessing = getIsDataProcessing(req.cacheKey);\n\n // When we process the cache data, we don't want to change the loading state during it\n // This prevents the UI from flickering with { data: null, loading: false }\n if (isProcessing) {\n return;\n }\n\n const canDisableLoading =\n !loading &&\n !dispatcher.hasRunningRequests(scopeKey(req.queryKey, req.scope)) &&\n pendingRequests.current.size === 0;\n if (loading || canDisableLoading) {\n actions.setLoading(loading);\n }\n };\n };\n\n const handleDownloadProgress = (req: R) => {\n return (data: RequestProgressEventType<RequestInstance>) => {\n if (!isSameScope(data.request?.scope, req.scope)) {\n return;\n }\n onDownloadProgressCallback.current?.(data);\n };\n };\n\n const handleUploadProgress = (req: R) => {\n return (data: RequestProgressEventType<RequestInstance>) => {\n if (!isSameScope(data.request?.scope, req.scope)) {\n return;\n }\n onUploadProgressCallback.current?.(data);\n };\n };\n\n const handleRequestStart = (req: R) => {\n return (details: RequestEventType<R>) => {\n if (!isSameScope(details.request?.scope, req.scope)) {\n return;\n }\n onRequestStartCallback.current?.(details);\n };\n };\n const handleResponseStart = (req: R) => {\n return (details: RequestEventType<R>) => {\n if (!isSameScope(details.request?.scope, req.scope)) {\n return;\n }\n onResponseStartCallback.current?.(details);\n };\n };\n\n const handleResponse = (req: R) => {\n return (values: RequestResponseEventType<R>) => {\n if (!isSameScope(values.request?.scope, req.scope)) {\n return;\n }\n\n // This attempt is over - a retried request becomes pending again when its next attempt starts\n pendingRequests.current.delete(values.requestId);\n\n // Marked before the mapper runs - an async mapper answers after the dispatcher removed the request.\n // Failed attempts which are retried or kept for the connection to return respond once again.\n const { success } = values.response;\n const { isCanceled, isOffline, willRetry } = values.details;\n const willRespondAgain = !success && !isCanceled && (willRetry || (!!req.offline && isOffline));\n if (!willRespondAgain) {\n settledRequests.current.add(values.requestId);\n }\n\n // The loading listeners follow the queue of the latest request. A request sent earlier to another queue\n // (other params) is not heard by them, so when it is the last one, it ends the loading state here.\n const queryKey = scopeKey(req.queryKey, req.scope);\n const isLastRequest = pendingRequests.current.size === 0 && !dispatcher.hasRunningRequests(queryKey);\n if (isLastRequest && listenedQueryKey.current !== null && listenedQueryKey.current !== queryKey) {\n actions.setLoading(dispatcher.hasRunningRequests(listenedQueryKey.current));\n }\n\n // The mapper of the listened request - it can differ from the request of the current render\n const data = runResponseMapper(req, values.response);\n\n if (data instanceof Promise) {\n return (async () => {\n const response = (await data) as ResponseType<any, any, ExtractAdapterType<R>>;\n // The mapper can outlive the component - the unmount cleanup can't stop a response already being mapped\n if (!isMounted.current) {\n return;\n }\n handleResponseCallbacks({ ...values, response });\n })();\n }\n // Callbacks receive the same (mapped) response as the hook state\n return handleResponseCallbacks({\n ...values,\n response: (data || values.response) as ResponseType<any, any, ExtractAdapterType<R>>,\n });\n };\n };\n\n const handleRemove = ({ requestId, request: removedRequest }: RequestRemovedEventType<R>) => {\n // Removed before its last response - aborted with the hook, deleted or cleared from the queue. No response is\n // going to reach the listeners anymore, so the removal is what ends the request: the abort callback runs with\n // the same \"deleted\" response that `submit()` resolves with.\n if (!settledRequests.current.has(requestId) && lifecycleEvents.current.has(requestId)) {\n const timestamp = Date.now();\n handleResponseCallbacks({\n request: removedRequest,\n requestId,\n response: {\n data: null,\n error: getErrorMessage(\"deleted\") as ExtractErrorType<R>,\n status: null,\n success: false,\n extra: removedRequest.client.adapter.defaultExtra,\n requestTimestamp: timestamp,\n responseTimestamp: timestamp,\n },\n details: {\n retries: 0,\n isCanceled: true,\n isOffline: false,\n willRetry: false,\n addedTimestamp: timestamp,\n triggerTimestamp: timestamp,\n requestTimestamp: timestamp,\n responseTimestamp: timestamp,\n },\n });\n }\n settledRequests.current.delete(requestId);\n pendingRequests.current.delete(requestId);\n optimisticResultsRef.current.delete(requestId);\n removeLifecycleListener(requestId);\n };\n\n // ******************\n // Data Listeners\n // ******************\n\n const clearCacheDataListener = () => {\n dataEvents.current?.unmount();\n dataEvents.current = null;\n };\n\n const addCacheDataListener = (req: R) => {\n if (!isMounted.current) {\n return () => undefined;\n }\n\n // Data handlers\n // Core emits these events by the logical keys; the handlers skip events of other scopes\n const loadingUnmount = requestManager.events.onLoadingByQueue(req.queryKey, handleGetLoadingEvent(req));\n const getResponseUnmount = cache.events.onDataByKey<\n ExtractResponseType<R>,\n ExtractErrorType<R>,\n ExtractAdapterType<R>\n >(req.cacheKey, (cacheData) => {\n if (!isSameScope(cacheData.scope, req.scope)) {\n return;\n }\n setCacheData(cacheData);\n // Cache data brings the loading state of its own queue only - other requests of the hook can still be pending\n if (pendingRequests.current.size > 0) {\n actions.setLoading(true);\n }\n });\n\n const unmount = () => {\n loadingUnmount();\n getResponseUnmount();\n };\n\n clearCacheDataListener();\n dataEvents.current = { unmount };\n listenedQueryKey.current = scopeKey(req.queryKey, req.scope);\n\n return unmount;\n };\n\n // ******************\n // Lifecycle Listeners\n // ******************\n\n const addLifecycleListeners = (req: R, requestId?: string, optimisticResult?: OptimisticCallbackResult<any>) => {\n if (!isMounted.current) {\n return () => undefined;\n }\n\n /**\n * useFetch handles requesting by general keys\n * This makes it possible to deduplicate requests from different places and share data\n */\n if (!requestId) {\n // It's important to clear previously attached listeners to not cause some additional response/request\n // events to be triggered during lifecycle\n clearLifecycleListeners();\n const { queryKey, cacheKey } = req;\n const requestStartUnmount = requestManager.events.onRequestStartByQueue(queryKey, handleRequestStart(req));\n const responseStartUnmount = requestManager.events.onResponseStartByQueue(queryKey, handleResponseStart(req));\n const uploadUnmount = requestManager.events.onUploadProgressByQueue(queryKey, handleUploadProgress(req));\n const downloadUnmount = requestManager.events.onDownloadProgressByQueue(queryKey, handleDownloadProgress(req));\n const responseUnmount = requestManager.events.onResponseByCache(cacheKey, handleResponse(req));\n\n const unmount = () => {\n downloadUnmount();\n uploadUnmount();\n requestStartUnmount();\n responseStartUnmount();\n responseUnmount();\n };\n\n lifecycleEvents.current.set(queryKey, { unmount });\n\n return unmount;\n }\n /**\n * useSubmit handles requesting by requestIds, this makes it possible to track single requests\n */\n if (optimisticResult) {\n optimisticResultsRef.current.set(requestId, optimisticResult);\n }\n pendingRequests.current.add(requestId);\n const onRequestStart = handleRequestStart(req);\n const requestRemove = requestManager.events.onRemoveById(requestId, handleRemove);\n const requestStartUnmount = requestManager.events.onRequestStartById<R>(requestId, (details) => {\n // Every attempt, also a retry or one postponed until the connection returned\n pendingRequests.current.add(requestId);\n onRequestStart(details);\n });\n const responseStartUnmount = requestManager.events.onResponseStartById(requestId, handleResponseStart(req));\n const responseUnmount = requestManager.events.onResponseById(requestId, handleResponse(req));\n const uploadUnmount = requestManager.events.onUploadProgressById(requestId, handleUploadProgress(req));\n const downloadUnmount = requestManager.events.onDownloadProgressById(requestId, handleDownloadProgress(req));\n\n const unmount = () => {\n requestRemove();\n downloadUnmount();\n uploadUnmount();\n requestStartUnmount();\n responseStartUnmount();\n responseUnmount();\n };\n\n lifecycleEvents.current.set(requestId, { unmount });\n\n return unmount;\n };\n\n // ******************\n // Abort\n // ******************\n\n const abort = () => {\n const currentRequest = requestRef.current;\n const currentDispatcher = dispatcherRef.current;\n const ak = scopeKey(currentRequest.abortKey, currentRequest.scope);\n const requests = currentDispatcher.getAllRunningRequests();\n requests.forEach((requestData) => {\n const reqAk = scopeKey(requestData.request.abortKey, requestData.request.scope);\n if (reqAk === ak) {\n const qk = scopeKey(requestData.request.queryKey, requestData.request.scope);\n currentDispatcher.delete(qk, requestData.requestId, reqAk);\n }\n });\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n /**\n * On unmount we want to clear all the listeners to prevent memory leaks\n */\n useWillUnmount(() => {\n // Unmount listeners\n clearLifecycleListeners();\n clearCacheDataListener();\n });\n\n // Callbacks setters and abort work on refs only, so they are created once - their identity is stable between the renders\n const callbacksRef = useRef<UseRequestEventsReturnType<R>[0] | null>(null);\n if (!callbacksRef.current) {\n callbacksRef.current = {\n abort,\n onSuccess: (callback: OnSuccessCallbackType<R>) => {\n onSuccessCallback.current = callback;\n },\n onError: (callback: OnErrorCallbackType<R>) => {\n onErrorCallback.current = callback;\n },\n onAbort: (callback: OnErrorCallbackType<R>) => {\n onAbortCallback.current = callback;\n },\n onOfflineError: (callback: OnErrorCallbackType<R>) => {\n onOfflineErrorCallback.current = callback;\n },\n onFinished: (callback: OnFinishedCallbackType<R>) => {\n onFinishedCallback.current = callback;\n },\n onRequestStart: (callback: OnStartCallbackType<R>) => {\n onRequestStartCallback.current = callback;\n },\n onResponseStart: (callback: OnStartCallbackType<R>) => {\n onResponseStartCallback.current = callback;\n },\n onDownloadProgress: (callback: OnProgressCallbackType) => {\n onDownloadProgressCallback.current = callback;\n },\n onUploadProgress: (callback: OnProgressCallbackType) => {\n onUploadProgressCallback.current = callback;\n },\n };\n }\n\n return [\n callbacksRef.current,\n {\n addCacheDataListener,\n clearCacheDataListener,\n addLifecycleListeners,\n removeLifecycleListener,\n clearLifecycleListeners,\n },\n ];\n};\n","import type { UseTrackedStateType } from \"./use-tracked-state.types\";\n\nexport const initialState: UseTrackedStateType = {\n data: null,\n error: null,\n status: null,\n extra: {},\n success: false,\n loading: false,\n retries: 0,\n responseTimestamp: null,\n requestTimestamp: null,\n};\n","import type {\n CacheValueType,\n ClientInstance,\n EmptyTypes,\n HydrateDataType,\n HydrationOptions,\n NullableType,\n} from \"@hyper-fetch/core\";\nimport { parseResponse, scopeKey } from \"@hyper-fetch/core\";\n\nimport type { HydratedEntry, HydrateOptionsType } from \"./hydrate.types\";\n\n/**\n * Items already written to the cache (or skipped because the cache held newer data), per client.\n * Once an item is consumed the cache is the source of truth, so a hook mounted after `client.clear()`\n * does not get the old server snapshot back.\n */\nconst consumedItems = new WeakMap<ClientInstance, WeakSet<HydrateDataType>>();\n\nconst getConsumed = (client: ClientInstance) => {\n let consumed = consumedItems.get(client);\n if (!consumed) {\n consumed = new WeakSet();\n consumedItems.set(client, consumed);\n }\n return consumed;\n};\n\nexport const isConsumed = (client: ClientInstance, item: HydrateDataType) => {\n return getConsumed(client).has(item);\n};\n\nexport const markConsumed = (client: ClientInstance, item: HydrateDataType) => {\n getConsumed(client).add(item);\n};\n\n/**\n * Resolves the config of a single item exactly like `client.hydrate()` does\n */\nconst resolveConfig = (item: HydrateDataType, options?: HydrateOptionsType) => {\n const { cacheKey, scope, response: _response, ...fallbackOptions } = item;\n const defaults = { cache: true, override: true } satisfies Partial<HydrationOptions>;\n const config =\n typeof options === \"function\"\n ? { ...defaults, ...fallbackOptions, ...options(item) }\n : { ...defaults, ...fallbackOptions, ...options };\n\n return { ...config, cacheKey, scope };\n};\n\nconst getResponseTimestamp = (value: NullableType<{ responseTimestamp?: number | null }>, fallback = 0) => {\n const timestamp = Number(value?.responseTimestamp);\n return Number.isFinite(timestamp) ? timestamp : fallback;\n};\n\n/**\n * Turns dehydrated items into the values they will have in the cache, keyed by storage key.\n * The last item wins when the same key is passed twice.\n */\nexport const getHydratedEntries = (\n client: ClientInstance,\n data: NullableType<(HydrateDataType | EmptyTypes)[]>,\n options?: HydrateOptionsType,\n): Map<string, HydratedEntry> => {\n const entries = new Map<string, HydratedEntry>();\n\n data?.forEach((item) => {\n if (!item) {\n return;\n }\n\n const config = resolveConfig(item, options);\n const response = parseResponse(item.response);\n const storageKey = scopeKey(config.cacheKey, config.scope ?? null);\n\n // Mirrors the value created by `cache.set()`, so the first render matches the state after the write\n const value = {\n ...response,\n cacheKey: config.cacheKey,\n scope: config.scope ?? null,\n staleTime: config.staleTime,\n cacheTime: config.cacheTime,\n version: client.cache.version,\n cached: !!config.cache,\n } as CacheValueType;\n\n entries.set(storageKey, {\n item,\n storageKey,\n value,\n override: config.override !== false,\n timestamp: getResponseTimestamp(response, item.timestamp ?? 0),\n });\n });\n\n return entries;\n};\n\n/**\n * Decides whether the hydrated value should be used instead of the cached one.\n * Newer data always wins; with `override: false` existing cache data is kept.\n */\nexport const shouldUseHydratedValue = (cacheData: NullableType<CacheValueType>, entry: HydratedEntry): boolean => {\n if (!cacheData) {\n return true;\n }\n if (!entry.override) {\n return false;\n }\n return entry.timestamp > getResponseTimestamp(cacheData);\n};\n\n/**\n * Picks the data a hook should start with: cached data, unless the hydrated data is newer\n */\nexport const pickInitialCacheData = <T extends CacheValueType>(\n cacheData: NullableType<T>,\n entry: NullableType<HydratedEntry>,\n): NullableType<T> => {\n if (!entry || !shouldUseHydratedValue(cacheData, entry)) {\n return cacheData;\n }\n return entry.value as T;\n};\n","import React, { useContext, useEffect, useLayoutEffect, useMemo, useRef } from \"react\";\n\nimport type { HydrateProps, HydrationContextType } from \"./hydrate.types\";\nimport { getHydratedEntries, isConsumed, markConsumed, shouldUseHydratedValue } from \"./hydrate.utils\";\n\nconst HydrationContext = React.createContext<HydrationContextType | null>(null);\n\n// Layout effects do not run on the server; on the client they run before any passive effect of the tree\nconst useIsomorphicLayoutEffect = typeof window !== \"undefined\" ? useLayoutEffect : useEffect;\n\n/**\n * Hydrates the client cache with data fetched on the server.\n *\n * - Hooks below it render with the hydrated data on the first render, also during server rendering.\n * - On the client the data is written to the cache before the hooks mount, so fresh data is not refetched.\n * - Newer cache data is never replaced by an older snapshot.\n * - It can be nested and rendered conditionally; every `Hydrate` serves only its own client.\n */\nexport const Hydrate = ({ client, data, options, children }: HydrateProps) => {\n const parent = useContext(HydrationContext);\n\n const entries = useMemo(() => getHydratedEntries(client, data, options), [client, data, options]);\n\n // Read through a ref, so the context value stays stable when only the entries change (e.g. inline options)\n // and memoized children do not re-render. Hooks read the context only on their first render.\n const entriesRef = useRef(entries);\n entriesRef.current = entries;\n\n useIsomorphicLayoutEffect(() => {\n // Server mode cache does not store unscoped data - the context keeps serving it instead\n if (client.mode === \"server\") {\n return;\n }\n\n entries.forEach((entry) => {\n if (isConsumed(client, entry.item)) {\n return;\n }\n markConsumed(client, entry.item);\n\n const cacheData = client.cache.get(entry.storageKey);\n if (!shouldUseHydratedValue(cacheData, entry)) {\n return;\n }\n\n client.hydrate([entry.item], options);\n });\n }, [client, entries, options]);\n\n const value = useMemo<HydrationContextType>(\n () => ({\n get: (targetClient, storageKey) => {\n if (targetClient === client) {\n const entry = entriesRef.current.get(storageKey);\n if (entry) {\n return isConsumed(client, entry.item) ? undefined : entry;\n }\n }\n return parent?.get(targetClient, storageKey);\n },\n }),\n [client, parent],\n );\n\n return <HydrationContext.Provider value={value}>{children}</HydrationContext.Provider>;\n};\n\n/**\n * Access to the closest hydration data\n * @internal\n */\nexport const useHydration = (): HydrationContextType | null => {\n return useContext(HydrationContext);\n};\n","/**\n * Check if value is empty\n * @param value any object or primitive\n * @returns true when value is empty\n */\nexport const isEmpty = (value?: unknown): boolean => {\n const valueType = Object.prototype.toString.call(value);\n if (Array.isArray(value)) {\n return value.length === 0;\n }\n if (typeof value === \"object\" && value !== null && valueType === \"[object Object]\") {\n return Object.keys(value).length === 0;\n }\n return false;\n};\n\n/**\n * Allow to deep compare any passed values\n * @param firstValue unknown\n * @param secondValue unknown\n * @returns true when elements are equal\n */\nexport const isEqual = (firstValue?: unknown, secondValue?: unknown): boolean => {\n // Nulls (objects), and other primitives\n if (firstValue === secondValue) {\n return true;\n }\n\n try {\n const firstValueType = Object.prototype.toString.call(firstValue);\n const secondValueType = Object.prototype.toString.call(secondValue);\n\n const firstType = typeof firstValue;\n const secondType = typeof secondValue;\n\n const isType = (type: unknown) => firstType === type && secondType === type;\n const isTypeValue = (type: unknown) => firstValueType === type && secondValueType === type;\n\n // Compared types are different\n if (firstValueType !== secondValueType) {\n return false;\n }\n\n // NaN\n if (isType(\"number\") && Number.isNaN(firstValue) && Number.isNaN(secondValue)) {\n return true;\n }\n\n // Empty Array or Object\n if (isEmpty(firstValue) && isEmpty(secondValue)) {\n return true;\n }\n\n // Array\n if (Array.isArray(firstValue) && Array.isArray(secondValue)) {\n if (firstValue.length !== secondValue.length) {\n return false;\n }\n\n return !firstValue.some((element, i) => !isEqual(element, secondValue[i]));\n }\n\n // Object\n if (isType(\"object\") && isTypeValue(\"[object Object]\")) {\n if (Object.keys(firstValue as object).length !== Object.keys(secondValue as object).length) {\n return false;\n }\n\n return !Object.entries(firstValue as object).some(\n ([key, value]) => !isEqual(value, (secondValue as Record<string, unknown>)[key]),\n );\n }\n\n // Date\n if (firstValue instanceof Date && secondValue instanceof Date) {\n return +firstValue === +secondValue;\n }\n\n // undefined, string, number, bool\n return firstValue === secondValue;\n } catch (error) {\n console.error(error);\n return false;\n }\n};\n","export const getBounceData = (bounceData: {\n reset: () => void;\n active: boolean;\n}): { reset: () => void; active: boolean } => {\n return {\n ...bounceData,\n // oxlint-disable-next-line unicorn/no-useless-spread\n ...{ throttle: undefined, debounce: undefined },\n };\n};\n","/**\n * Wraps a plain object in a Proxy that calls `setRenderKey` when tracked properties are accessed.\n * Unlike getter-based tracking, Proxy-wrapped objects display their actual values in console.log,\n * making debugging significantly easier while preserving field-level dependency tracking.\n */\nexport const createTrackedProxy = <T extends Record<string, unknown>, K extends string>(\n target: T,\n trackedKeys: readonly K[],\n setRenderKey: (key: K) => void,\n): T => {\n return new Proxy(target, {\n get(obj, prop, receiver) {\n if (typeof prop === \"string\" && trackedKeys.includes(prop as K)) {\n setRenderKey(prop as K);\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n};\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport type {\n CacheValueType,\n NullableType,\n RequestInstance,\n ExtractResponseType,\n ExtractErrorType,\n ExtractAdapterResolvedType,\n Dispatcher,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ResponseDetailsType,\n ExtractAdapterStatusType,\n ResponseType,\n} from \"@hyper-fetch/core\";\nimport { runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport type { UseTrackedStateType } from \"helpers\";\nimport { initialState } from \"helpers\";\nimport type { HydratedEntry } from \"hydrate/hydrate.types\";\nimport { pickInitialCacheData } from \"hydrate/hydrate.utils\";\n\n/**\n * Extracts the \"identity\" portion of a cache key (method + endpoint with resolved params),\n * stripping the query params part. Cache keys follow the format: `method_endpoint_queryParams`.\n */\nconst getCacheKeyIdentity = (cacheKey: string): string => {\n const lastUnderscoreIndex = cacheKey.lastIndexOf(\"_\");\n if (lastUnderscoreIndex === -1) {\n return cacheKey;\n }\n return cacheKey.substring(0, lastUnderscoreIndex);\n};\n\n/**\n * Identity of the requested resource - method and endpoint with resolved params, without the query params.\n * Two requests with the same identity ask for the same resource (e.g. another page or filter of one list).\n */\nexport const getRequestIdentity = (request: Pick<RequestInstance, \"method\" | \"endpoint\" | \"scope\">): string => {\n return `${request.scope ?? \"\"}_${String(request.method)}_${String(request.endpoint)}`;\n};\n\n/**\n * Determines whether state should be cleared when the cache key changes.\n *\n * - `\"clean\"` — always clear\n * - `\"preserve\"` — never clear\n * - `\"auto\"` — clear when the resource identity changed (URL params), preserve when only query params changed\n *\n * In the \"auto\" mode the identity is read from the cache keys, which is not reliable for custom cache keys\n * and for query params containing underscores - compare the requests with `getRequestIdentity` when they are available.\n */\nexport const getShouldClearState = (\n mode: \"auto\" | \"preserve\" | \"clean\",\n oldCacheKey: string,\n newCacheKey: string,\n): boolean => {\n if (oldCacheKey === newCacheKey) {\n return false;\n }\n\n if (mode === \"clean\") {\n return true;\n }\n if (mode === \"preserve\") {\n return false;\n }\n\n // \"auto\" — compare the identity part (method + endpoint with params)\n return getCacheKeyIdentity(oldCacheKey) !== getCacheKeyIdentity(newCacheKey);\n};\n\nexport const getDetailsState = (\n state?: UseTrackedStateType<RequestInstance>,\n details?: Partial<ResponseDetailsType>,\n): ResponseDetailsType => {\n return {\n retries: state?.retries || 0,\n isCanceled: false,\n isOffline: false,\n willRetry: false,\n addedTimestamp: Date.now(),\n triggerTimestamp: Date.now(),\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n ...details,\n };\n};\n\nexport const isStaleCacheData = (staleTime: number, staleTimestamp: NullableType<Date | number>) => {\n if (!staleTimestamp) {\n return true;\n }\n return Date.now() > +staleTimestamp + staleTime;\n};\n\nexport const getValidCacheData = <T extends RequestInstance>(\n request: T,\n initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>,\n cacheData: NullableType<CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>>,\n): CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>> | null => {\n if (cacheData) {\n return cacheData;\n }\n\n if (initialResponse) {\n return {\n data: null,\n error: null,\n status: null,\n success: true,\n extra: null,\n cached: !!request.cache,\n ...(initialResponse as Partial<ExtractAdapterResolvedType<T>>),\n ...getDetailsState(),\n staleTime: 1000,\n version: request.client.cache.version,\n cacheKey: request.cacheKey,\n scope: request.scope,\n cacheTime: request.cacheTime,\n requestTimestamp: initialResponse?.requestTimestamp ?? Date.now(),\n responseTimestamp: initialResponse?.responseTimestamp ?? Date.now(),\n };\n }\n\n return null;\n};\n\nexport const getTimestamp = (timestamp?: NullableType<number | Date>) => {\n return timestamp ? new Date(timestamp) : null;\n};\n\nexport const getIsInitiallyLoading = <T extends RequestInstance>({\n queryKey,\n dispatcher,\n hasState,\n revalidate,\n disabled,\n}: {\n queryKey: string;\n dispatcher: Dispatcher<ExtractAdapterType<T>>;\n hasState: boolean;\n revalidate?: boolean;\n disabled?: boolean;\n}) => {\n if (!revalidate && hasState) {\n return false;\n }\n\n const queue = dispatcher.getQueue(queryKey);\n const isInitiallyLoading = dispatcher.hasRunningRequests(queryKey) || (!queue.stopped && disabled === false);\n\n return isInitiallyLoading;\n};\n\nexport const getInitialState = <T extends RequestInstance>({\n initialResponse,\n dispatcher,\n request,\n disabled,\n revalidate,\n hydratedEntry,\n}: {\n initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>;\n dispatcher: Dispatcher<ExtractAdapterType<T>>;\n request: T;\n disabled?: boolean; // useFetch only\n revalidate?: boolean; // useFetch only\n /** Data from the closest `Hydrate` that was not written to the cache yet */\n hydratedEntry?: NullableType<HydratedEntry>;\n}): UseTrackedStateType<T> => {\n const { client, cacheKey } = request;\n const { cache } = client;\n\n const cacheData = pickInitialCacheData(\n cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopeKey(cacheKey, request.scope)),\n hydratedEntry,\n );\n const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);\n\n const initialLoading = getIsInitiallyLoading({\n queryKey: scopeKey(request.queryKey, request.scope),\n dispatcher,\n disabled,\n revalidate,\n hasState: !!cacheState,\n });\n\n if (cacheState) {\n const mappedData =\n runResponseMapper(request, cacheState as ResponseType<any, any, ExtractAdapterType<T>>) || cacheState;\n if (mappedData instanceof Promise) {\n // For the async mapper we cannot return async values\n // So we have return the initial state instead\n return initialState;\n }\n return {\n data: mappedData.data,\n error: mappedData.error,\n status: mappedData.status as ExtractAdapterStatusType<ExtractAdapterType<T>>,\n success: mappedData.success,\n extra: (mappedData.extra || client.adapter.defaultExtra) as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: cacheState.retries,\n requestTimestamp: getTimestamp(cacheState.requestTimestamp),\n responseTimestamp: getTimestamp(cacheState.responseTimestamp),\n loading: initialLoading,\n };\n }\n\n return {\n data: initialState.data,\n error: initialState.error,\n status: initialState.status as ExtractAdapterStatusType<ExtractAdapterType<T>>,\n success: initialState.success,\n extra: request.client.adapter.defaultExtra as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: initialState.retries,\n requestTimestamp: getTimestamp(initialState.requestTimestamp),\n responseTimestamp: getTimestamp(initialState.responseTimestamp),\n loading: initialLoading,\n };\n};\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type {\n ExtractErrorType,\n CacheValueType,\n ExtractResponseType,\n RequestInstance,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ResponseType,\n} from \"@hyper-fetch/core\";\nimport { replaceEqualDeep, runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport { useHydration } from \"hydrate/hydrate\";\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport { isEqual } from \"utils\";\n\nimport type {\n UseTrackedStateActions,\n UseTrackedStateType,\n UseTrackedStateProps,\n UseTrackedStateReturn,\n UseTrackedStateResponseDetails,\n} from \"./use-tracked-state.types\";\nimport {\n getInitialState,\n getIsInitiallyLoading,\n getRequestIdentity,\n getShouldClearState,\n getValidCacheData,\n isStaleCacheData,\n} from \"./use-tracked-state.utils\";\n\n/**\n *\n * @param request\n * @param initialResponse\n * @param dispatcher\n * @param dependencies\n * @internal\n */\nexport const useTrackedState = <T extends RequestInstance, TData = ExtractResponseType<T>>({\n request,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n keepPreviousData = \"auto\",\n disabled,\n revalidate,\n select,\n structuralSharing = true,\n}: UseTrackedStateProps<T, TData>): UseTrackedStateReturn<T, TData> => {\n const { client, cacheKey, queryKey, staleTime } = request;\n const { cache } = client;\n // Cache storage and dispatcher queues are keyed with the scope of the request\n const scopedCacheKey = scopeKey(cacheKey, request.scope);\n const scopedQueryKey = scopeKey(queryKey, request.scope);\n const identity = getRequestIdentity(request);\n const hydration = useHydration();\n\n const state = useRef<UseTrackedStateType<T, TData>>(null as unknown as UseTrackedStateType<T, TData>);\n const renderKeys = useRef<(keyof UseTrackedStateType<T, TData>)[]>([]);\n const isProcessingData = useRef(\"\");\n const previousCacheKey = useRef(scopedCacheKey);\n const previousIdentity = useRef(identity);\n // State created from scratch can be filled with the initialResponse, the preserved one (keepPreviousData) can not\n const isFreshState = useRef(true);\n\n // ******************\n // Data selection\n // ******************\n\n const selectRef = useRef(select);\n selectRef.current = select;\n const appliedSelect = useRef(select);\n // Response data before applying the selector - allows to re-run it when the selector changes\n const rawData = useRef<ExtractResponseType<T> | null>(null);\n // Data set with the setData action has the selected shape and should not get re-selected\n const isLocalData = useRef(false);\n const selectError = useRef<{ error: unknown } | null>(null);\n const responseDetails = useRef<UseTrackedStateResponseDetails | null>(null);\n\n const selectData = (data: ExtractResponseType<T> | null, previousData: TData | null = null): TData | null => {\n if (!selectRef.current || data === null || data === undefined) {\n return data as TData | null;\n }\n const selected = selectRef.current(data);\n return structuralSharing ? replaceEqualDeep(previousData, selected) : selected;\n };\n\n const getSelectedState = (newState: UseTrackedStateType<T>): UseTrackedStateType<T, TData> => {\n rawData.current = newState.data;\n isLocalData.current = false;\n responseDetails.current = null;\n appliedSelect.current = selectRef.current;\n return { ...newState, data: selectData(newState.data, state.current?.data) };\n };\n\n if (!state.current) {\n const hydratedEntry = hydration?.get(client, scopeKey(cacheKey, request.scope));\n state.current = getSelectedState(\n getInitialState({ initialResponse, dispatcher, request, disabled, hydratedEntry }),\n );\n }\n // Request key changed - the state is switched during the render, so the data of the previous key\n // is never returned for the new one (unless it is kept on purpose with keepPreviousData)\n else if (previousCacheKey.current !== scopedCacheKey) {\n // \"auto\" mode keeps the state of the same resource (only its query params changed).\n // Resources are compared by the requests, cache keys can't be parsed reliably.\n const shouldClear =\n keepPreviousData === \"auto\"\n ? previousIdentity.current !== identity\n : getShouldClearState(keepPreviousData, previousCacheKey.current, scopedCacheKey);\n previousCacheKey.current = scopedCacheKey;\n previousIdentity.current = identity;\n\n const hasCacheData = !!cache.get(scopedCacheKey);\n isFreshState.current = hasCacheData || shouldClear;\n\n if (isFreshState.current) {\n const hydratedEntry = hydration?.get(client, scopedCacheKey);\n state.current = getSelectedState(\n getInitialState({ initialResponse, dispatcher, request, disabled, revalidate, hydratedEntry }),\n );\n }\n // Otherwise the previous state stays until the response of the new key arrives (#126)\n }\n\n // Selector failed while processing incoming data - surface it to the closest error boundary\n if (selectError.current) {\n const { error } = selectError.current;\n selectError.current = null;\n throw error;\n }\n\n // Selector changed (e.g. it closes over a new prop) - re-run it against the latest response data\n if (appliedSelect.current !== select && !isLocalData.current) {\n appliedSelect.current = select;\n state.current.data = selectData(rawData.current, state.current.data);\n }\n\n // ******************\n // useSyncExternalStore\n // ******************\n\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n // ******************\n // Utils\n // ******************\n\n const getStaleStatus = (): boolean => {\n const cacheData = cache.get(scopedCacheKey);\n // Invalidation marks the cache entry with the stale time of 0 - it has to be fetched again,\n // also when no hook was mounted to refetch it at the moment of the invalidation\n const isInvalidated = cacheData?.staleTime === 0;\n return !cacheData || isInvalidated || isStaleCacheData(staleTime, cacheData?.responseTimestamp);\n };\n\n // ******************\n // Dependency Tracking\n // ******************\n\n const renderKeyTrigger = (keys: (keyof UseTrackedStateType<T, TData>)[]) => {\n const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));\n if (shouldRerender) {\n emitChange();\n }\n };\n\n const setRenderKey = (renderKey: keyof UseTrackedStateType<T, TData>) => {\n if (!renderKeys.current.includes(renderKey)) {\n renderKeys.current.push(renderKey);\n }\n };\n\n // ******************\n // Cache initialization\n // ******************\n\n useDidUpdate(\n () => {\n // The state of the key is already set during the render. Here we pick up the changes done to the cache\n // between the render and the effect and the data that requires asynchronous mapping.\n const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopedCacheKey);\n // Initial response is a placeholder for the empty state only - it never replaces the data kept from the previous key\n const cacheState =\n cacheData || (isFreshState.current ? getValidCacheData<T>(request, initialResponse, null) : null);\n\n if (cacheState) {\n state.current.loading = getIsInitiallyLoading({\n queryKey: scopedQueryKey,\n dispatcher,\n disabled,\n revalidate,\n hasState: true,\n });\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n setCacheData(cacheState);\n }\n // When state is preserved and no cache exists (e.g. query param change in \"auto\" mode),\n // don't update loading on the ref — let the dispatcher's loading event handle it (#126)\n },\n [scopedCacheKey, scopedQueryKey],\n true,\n );\n\n // ******************\n // Turn off dependency tracking\n // ******************\n\n useDidUpdate(\n () => {\n const handleDependencyTracking = () => {\n if (!dependencyTracking) {\n Object.keys(state.current).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0]));\n }\n };\n\n handleDependencyTracking();\n },\n [dependencyTracking],\n true,\n );\n\n // ******************\n // Cache data handler\n // ******************\n\n const handleCompare = (firstValue: unknown, secondValue: unknown) => {\n if (Object.is(firstValue, secondValue)) {\n return true;\n }\n if (typeof deepCompare === \"function\") {\n return deepCompare(firstValue, secondValue);\n }\n if (deepCompare) {\n return isEqual(firstValue, secondValue);\n }\n return false;\n };\n\n const handleCacheData = (\n cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>,\n ) => {\n rawData.current = cacheData.data;\n isLocalData.current = false;\n appliedSelect.current = selectRef.current;\n responseDetails.current = {\n willRetry: !!cacheData.willRetry,\n isCanceled: !!cacheData.isCanceled,\n isOffline: !!cacheData.isOffline,\n };\n\n let data: TData | null;\n try {\n data = selectData(cacheData.data, state.current.data);\n } catch (error) {\n // Never throw inside of the cache events - rethrow it on render instead\n selectError.current = { error };\n emitChange();\n return;\n }\n\n const newStateValues: UseTrackedStateType<T, TData> = {\n data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: cacheData.retries,\n responseTimestamp: new Date(cacheData.responseTimestamp),\n requestTimestamp: new Date(cacheData.requestTimestamp),\n loading: dispatcher.hasRunningRequests(scopedQueryKey),\n };\n\n const nextState: UseTrackedStateType<T, TData> = { ...state.current };\n const changedKeys = (Object.keys(newStateValues) as (keyof UseTrackedStateType<T, TData>)[]).filter((key) => {\n const isEqualValue = handleCompare(state.current[key], newStateValues[key]);\n // Equal values keep their previous reference, so they stay stable between renders\n if (!isEqualValue) {\n (nextState as Record<string, unknown>)[key] = newStateValues[key];\n }\n return !isEqualValue;\n });\n\n state.current = nextState;\n\n renderKeyTrigger(changedKeys);\n };\n\n const setIsDataProcessing = ({\n processingCacheKey,\n isProcessing,\n }: {\n processingCacheKey: string;\n isProcessing: boolean;\n }) => {\n if (isProcessing) {\n isProcessingData.current = processingCacheKey;\n }\n // Do not turn off other keys processing\n else if (isProcessingData.current === cacheKey) {\n isProcessingData.current = \"\";\n }\n };\n\n const getIsDataProcessing = (processingCacheKey: string) => {\n return isProcessingData.current === processingCacheKey;\n };\n\n const setCacheData = (\n cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>,\n ): Promise<void> | void => {\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: true });\n const data = runResponseMapper(request, cacheData as ResponseType<any, any, ExtractAdapterType<T>>) || cacheData;\n\n if (data instanceof Promise) {\n return (async () => {\n const promiseData = await data;\n handleCacheData({ ...cacheData, ...promiseData } as CacheValueType<\n ExtractResponseType<T>,\n ExtractErrorType<T>,\n ExtractAdapterType<T>\n >);\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: false });\n })();\n }\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: false });\n return handleCacheData({ ...cacheData, ...data } as CacheValueType<\n ExtractResponseType<T>,\n ExtractErrorType<T>,\n ExtractAdapterType<T>\n >);\n };\n\n // ******************\n // Actions\n // ******************\n\n // Actions work on refs only, so they are created once - their identity is stable between the renders\n const actionsRef = useRef<UseTrackedStateActions<T, TData> | null>(null);\n if (!actionsRef.current) {\n actionsRef.current = {\n setData: (data) => {\n isLocalData.current = true;\n state.current.data = data instanceof Function ? data(state.current.data ?? null) : data;\n renderKeyTrigger([\"data\"]);\n },\n setError: (error) => {\n state.current.error = error instanceof Function ? error(state.current.error ?? null) : error;\n renderKeyTrigger([\"error\"]);\n },\n setLoading: (loading) => {\n const value = loading instanceof Function ? loading(state.current.loading) : loading;\n if (value === state.current.loading) {\n return;\n }\n state.current.loading = value;\n renderKeyTrigger([\"loading\"]);\n },\n setStatus: (status) => {\n const value = status instanceof Function ? status(state.current.status ?? null) : status;\n if (value === state.current.status) {\n return;\n }\n state.current.status = value;\n renderKeyTrigger([\"status\"]);\n },\n setSuccess: (success) => {\n const value = success instanceof Function ? success(state.current.success || false) : success;\n if (value === state.current.success) {\n return;\n }\n state.current.success = value;\n renderKeyTrigger([\"success\"]);\n },\n setExtra: (extra) => {\n const value = extra instanceof Function ? extra(state.current.extra) : extra;\n if (value === state.current.extra) {\n return;\n }\n state.current.extra = value;\n renderKeyTrigger([\"extra\"]);\n },\n setRetries: (retries) => {\n const value = retries instanceof Function ? retries(state.current.retries || 0) : retries;\n if (value === state.current.retries) {\n return;\n }\n state.current.retries = value;\n renderKeyTrigger([\"retries\"]);\n },\n setResponseTimestamp: (timestamp) => {\n const value = timestamp instanceof Function ? timestamp(state.current.responseTimestamp) : timestamp;\n if (value === state.current.responseTimestamp) {\n return;\n }\n const getTimestamp = (prev: Date | null) => {\n return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;\n };\n\n state.current.responseTimestamp = getTimestamp(state.current.responseTimestamp);\n renderKeyTrigger([\"responseTimestamp\"]);\n },\n setRequestTimestamp: (timestamp) => {\n const value = timestamp instanceof Function ? timestamp(state.current.requestTimestamp) : timestamp;\n if (value === state.current.requestTimestamp) {\n return;\n }\n const getTimestamp = (prev: Date | null) => {\n return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;\n };\n\n state.current.requestTimestamp = getTimestamp(state.current.requestTimestamp);\n renderKeyTrigger([\"requestTimestamp\"]);\n },\n clearState: () => {\n rawData.current = null;\n isLocalData.current = false;\n responseDetails.current = null;\n state.current = {\n data: null,\n error: null,\n loading: false,\n status: null,\n success: false,\n extra: client.adapter.defaultExtra,\n retries: 0,\n responseTimestamp: null,\n requestTimestamp: null,\n } as UseTrackedStateType<T, TData>;\n renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T, TData>)[]);\n },\n };\n }\n const actions = actionsRef.current;\n\n return [\n state.current,\n actions,\n {\n setRenderKey,\n setCacheData,\n getStaleStatus,\n getIsDataProcessing,\n selectData: (data) => selectData(data, state.current.data),\n getResponseDetails: () => responseDetails.current,\n },\n ];\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { SocketInstance, ExtractSocketExtraType } from \"@hyper-fetch/sockets\";\nimport type { UseSocketStateType, UseSocketStateProps } from \"helpers\";\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\n\n/**\n * Tracked socket state shared by the socket hooks. `extendedState` adds hook-specific fields (e.g. the listener\n * status) that are tracked the same way and changed with `actions.setExtendedState`.\n */\nexport const useSocketState = <\n DataType,\n Socket extends SocketInstance,\n ExtendedState extends Record<string, unknown> = Record<never, never>,\n>(\n socket: Socket,\n { dependencyTracking, extendedState }: UseSocketStateProps & { extendedState?: ExtendedState },\n) => {\n type StateType = UseSocketStateType<Socket, DataType> & ExtendedState;\n const initialExtendedState = useRef(extendedState);\n const onDisconnectCallback = useRef<null | VoidFunction>(null);\n const onErrorCallback = useRef<null | ((event: any) => void)>(null);\n const onConnectedCallback = useRef<null | VoidFunction>(null);\n const onConnectingCallback = useRef<null | VoidFunction>(null);\n const onReconnectingCallback = useRef<null | ((data: { attempts: number }) => void)>(null);\n const onReconnectingFailedCallback = useRef<null | ((data: { attempts: number }) => void)>(null);\n\n const state = useRef<StateType>({\n ...initialExtendedState.current,\n data: null,\n extra: null,\n connected: socket.adapter.connected,\n connecting: socket.adapter.connecting,\n timestamp: null,\n } as StateType);\n const renderKeys = useRef<(keyof StateType)[]>([]);\n\n // ******************\n // useSyncExternalStore\n // ******************\n\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n // ******************\n // Dependency Tracking\n // ******************\n\n const renderKeyTrigger = (keys: (keyof StateType)[]) => {\n const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));\n if (shouldRerender) {\n emitChange();\n }\n };\n\n const setRenderKey = (renderKey: keyof StateType) => {\n if (!renderKeys.current.includes(renderKey)) {\n renderKeys.current.push(renderKey);\n }\n };\n\n // ******************\n // Turn off dependency tracking\n // ******************\n\n useDidUpdate(\n () => {\n const handleDependencyTracking = () => {\n if (!dependencyTracking) {\n Object.keys(state.current).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0]));\n }\n };\n\n handleDependencyTracking();\n },\n [dependencyTracking],\n true,\n );\n\n // ******************\n // Actions\n // ******************\n\n const actions = {\n setData: (data: DataType | null) => {\n state.current.data = data;\n renderKeyTrigger([\"data\"]);\n },\n setExtra: (extra: ExtractSocketExtraType<Socket> | null) => {\n state.current.extra = extra;\n renderKeyTrigger([\"extra\"]);\n },\n setConnected: (connected: boolean) => {\n state.current.connected = connected;\n renderKeyTrigger([\"connected\"]);\n },\n setConnecting: (connecting: boolean) => {\n state.current.connecting = connecting;\n renderKeyTrigger([\"connecting\"]);\n },\n setTimestamp: (timestamp: number | null) => {\n state.current.timestamp = timestamp;\n renderKeyTrigger([\"timestamp\"]);\n },\n clearState: () => {\n state.current = {\n ...initialExtendedState.current,\n data: null,\n extra: null,\n connected: false,\n connecting: false,\n timestamp: null,\n } as StateType;\n renderKeyTrigger(Object.keys(state.current) as (keyof StateType)[]);\n },\n };\n\n const callbacks = {\n onConnected: (callback: VoidFunction) => {\n onConnectedCallback.current = callback;\n },\n onDisconnected: (callback: VoidFunction) => {\n onDisconnectCallback.current = callback;\n },\n onError: <ErrorType = Event>(callback: (event: ErrorType) => void) => {\n onErrorCallback.current = callback;\n },\n onConnecting: (callback: VoidFunction) => {\n onConnectingCallback.current = callback;\n },\n onReconnecting: (callback: (data: { attempts: number }) => void) => {\n onReconnectingCallback.current = callback;\n },\n onReconnectingFailed: (callback: (data: { attempts: number }) => void) => {\n onReconnectingFailedCallback.current = callback;\n },\n };\n\n // ******************\n // Hook to events\n // ******************\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without any subscriptions\n useEffect(() => {\n // Catch up with anything that happened between the render and the subscription\n if (state.current.connected !== socket.adapter.connected) {\n actions.setConnected(socket.adapter.connected);\n }\n if (state.current.connecting !== socket.adapter.connecting) {\n actions.setConnecting(socket.adapter.connecting);\n }\n\n const umountOnError = socket.events.onError((event) => {\n onErrorCallback.current?.(event);\n });\n const umountOnConnecting = socket.events.onConnecting(({ connecting }) => {\n actions.setConnecting(connecting);\n onConnectingCallback.current?.();\n });\n const umountOnOpen = socket.events.onConnected(() => {\n actions.setConnected(true);\n onConnectedCallback.current?.();\n });\n const umountOnClose = socket.events.onDisconnected(() => {\n actions.setConnected(false);\n onDisconnectCallback.current?.();\n });\n const umountOnReconnecting = socket.events.onReconnecting(({ attempts }) => {\n onReconnectingCallback.current?.({ attempts });\n });\n const umountOnReconnectingFailed = socket.events.onReconnectingFailed(({ attempts }) => {\n onReconnectingFailedCallback.current?.({ attempts });\n });\n\n return () => {\n umountOnError();\n umountOnConnecting();\n umountOnOpen();\n umountOnClose();\n umountOnReconnecting();\n umountOnReconnectingFailed();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [socket]);\n\n const getState = () => state.current;\n\n /** Changes the hook-specific fields added with `extendedState` */\n const setExtendedState = (newState: Partial<ExtendedState>) => {\n Object.assign(state.current, newState);\n renderKeyTrigger(Object.keys(newState) as (keyof StateType)[]);\n };\n\n return [\n state.current,\n actions,\n callbacks,\n { setRenderKey, getState, rerender: emitChange, setExtendedState },\n ] as const;\n};\n","import type { SocketInstance } from \"@hyper-fetch/sockets\";\n\nimport type { UseSocketStateType } from \"./use-socket-state.types\";\n\nexport const initialSocketState: UseSocketStateType<SocketInstance> = {\n data: null,\n extra: null,\n connected: false,\n connecting: false,\n timestamp: null,\n};\n","import React, { useContext, useMemo, useRef, useState } from \"react\";\nimport { isEqual } from \"utils\";\n\nimport type { ProviderProps, ProviderValueType } from \"./provider.types\";\n\nconst ConfigContext = React.createContext<ProviderValueType>({\n config: {},\n setConfig: () => null,\n});\n\n/**\n * Provider with configuration for hooks\n * @param options\n * @returns\n */\nexport const Provider = ({ children, config }: ProviderProps) => {\n const [currentConfig, setConfig] = useState(config || {});\n\n // Follow the changes of the config prop - inline objects with the same values do not cause updates\n const previousConfig = useRef(config);\n if (!isEqual(previousConfig.current, config)) {\n previousConfig.current = config;\n setConfig(config || {});\n }\n\n const value = useMemo(() => {\n const contextValue: ProviderValueType = { config: currentConfig, setConfig };\n return contextValue;\n }, [currentConfig]);\n\n return <ConfigContext.Provider value={value}>{children}</ConfigContext.Provider>;\n};\n\n/**\n * Hook to allow reading current context config\n * @returns\n */\nexport const useProvider = (): ProviderValueType => {\n const config = useContext(ConfigContext);\n return config;\n};\n","/**\n * `JSON.stringify` replacer for the keys the hooks build from a request.\n * Adapters with their own serializers accept `BigInt` payloads, which plain JSON can't encode.\n * They are kept in the key and stay distinct from a string with the same digits.\n */\nexport const keyReplacer = (_key: string, value: unknown) => {\n return typeof value === \"bigint\" ? { \"~bigint\": value.toString() } : value;\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n CacheValueType,\n RequestInstance,\n ExtractAdapterStatusType,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ExtractErrorType,\n ExtractResponseType,\n} from \"@hyper-fetch/core\";\nimport { scopeKey } from \"@hyper-fetch/core\";\nimport { useRequestEvents, useTrackedState } from \"helpers\";\nimport type { UseFetchOptionsType, UseFetchReturnType } from \"hooks/use-fetch\";\nimport { useFetchDefaultOptions } from \"hooks/use-fetch\";\nimport { useProvider } from \"provider\";\nimport { useCallback, useRef } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\nimport { keyReplacer } from \"utils/key.utils\";\nimport { isSameScope } from \"utils/scope.utils\";\n\ntype SuspenseEntry = { promise: Promise<void>; resolve: () => void; cleanup: () => void };\ntype SuspenseResult = Pick<\n CacheValueType<any, any>,\n \"data\" | \"error\" | \"status\" | \"extra\" | \"success\" | \"retries\" | \"responseTimestamp\" | \"requestTimestamp\"\n> & { receivedTimestamp: number };\ntype SuspenseStore = { promises: Map<string, SuspenseEntry>; results: Map<string, SuspenseResult> };\n\n/**\n * Suspended components lose their state, so the pending promises and the responses that are not stored in the cache\n * have to live outside of them. They are kept per cache instance - every client (and every cleared client)\n * has its own store, so responses never leak between the clients.\n */\nconst suspenseStores = new WeakMap<object, SuspenseStore>();\nconst getSuspenseStore = (cache: object): SuspenseStore => {\n let store = suspenseStores.get(cache);\n if (!store) {\n store = { promises: new Map(), results: new Map() };\n suspenseStores.set(cache, store);\n }\n return store;\n};\n\n/**\n * Data received by the suspended component is not fetched again when it mounts right after.\n * Responses waiting for the suspended component are dropped after this time - the component is gone.\n */\nconst suspenseFreshTime = 1000;\n\n/**\n * Options passed as `undefined` (e.g. forwarded optional props) fall back to the defaults instead of overriding them\n */\nconst mergeOptions = <T extends object>(...sources: (object | undefined)[]): T => {\n const merged: Record<string, unknown> = {};\n sources.forEach((source) => {\n Object.entries(source || {}).forEach(([key, value]) => {\n if (value !== undefined) {\n merged[key] = value;\n }\n });\n });\n return merged as T;\n};\n\n/**\n * This hook aims to retrieve data from the server. It automatically fetches on mount and\n * refetches based on dependencies, with support for caching, polling, and suspense.\n * @param request Request instance\n * @param options Hook options\n * @returns\n */\nexport const useFetch = <R extends RequestInstance, TSelected = ExtractResponseType<R>>(\n request: R,\n options?: UseFetchOptionsType<R, TSelected>,\n): UseFetchReturnType<R, TSelected> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const {\n suspense,\n dependencies,\n disabled,\n dependencyTracking,\n revalidate,\n initialResponse,\n keepPreviousData,\n refresh,\n refreshTime,\n refetchBlurred,\n refetchOnBlur,\n refetchOnFocus,\n refetchOnReconnect,\n bounce,\n bounceType,\n bounceTime,\n bounceTimeout,\n deepCompare,\n structuralSharing,\n throwOnError,\n } = mergeOptions<typeof useFetchDefaultOptions & UseFetchOptionsType<R, TSelected>>(\n useFetchDefaultOptions,\n globalConfig.useFetchConfig,\n options,\n );\n\n const updateKey = JSON.stringify(request.toJSON(), keyReplacer);\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({ interval: bounceTime, timeout: bounceTimeout });\n const refreshDebounce = useDebounce({ delay: refreshTime });\n\n const { cacheKey, queryKey, client } = request;\n const { cache, fetchDispatcher: dispatcher, appManager, loggerManager } = client;\n // Cache storage and dispatcher queues are keyed with the scope of the request\n const scopedCacheKey = scopeKey(cacheKey, request.scope);\n const scopedQueryKey = scopeKey(queryKey, request.scope);\n\n const fetchDependencies = useRef<unknown[] | null>(null);\n const isSuspenseResolved = useRef(false);\n const logger = useRef(loggerManager.initialize(client, \"useFetch\")).current;\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n /**\n * State handler with optimization for re-rendering, that hooks into the cache state and dispatchers queues\n */\n const [\n state,\n actions,\n { setRenderKey, setCacheData, getStaleStatus, getIsDataProcessing, selectData, getResponseDetails },\n ] = useTrackedState<R, TSelected>({\n logger,\n request: request as unknown as R,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n keepPreviousData,\n disabled,\n revalidate,\n select: options?.select,\n structuralSharing,\n });\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [callbacks, listeners] = useRequestEvents<R>({\n logger,\n actions,\n request: request as unknown as R,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners, clearCacheDataListener } = listeners;\n\n // ******************\n // Fetching\n // ******************\n const handleFetch = (options?: { force?: boolean }) => {\n if (!disabled) {\n logger.debug({ title: `Fetching data`, type: \"system\", extra: { request } });\n // A forced fetch must not be deduplicated into an already running request: that request\n // started earlier, so its response can be older than the state that prompted the call.\n // Manual refetch() promises data at least as fresh as the moment it was called.\n const requestToAdd = options?.force ? request.setDeduplicate(false) : request;\n dispatcher.add(requestToAdd as unknown as R);\n } else {\n logger.debug({ title: `Cannot add to fetch queue`, type: \"system\", extra: { disabled } });\n }\n };\n\n // ******************\n // Refreshing\n // ******************\n\n function handleRefresh() {\n if (!refresh || disabled) {\n refreshDebounce.reset();\n return;\n }\n\n refreshDebounce.debounce(() => {\n // Timer outlives the render which started it - always use the latest options and request\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n latest.current.refresh();\n });\n }\n\n const performRefresh = () => {\n const isBlurred = !appManager.isFocused;\n\n // If window tab is not active should we refresh the cache\n const isFetching = dispatcher.hasRunningRequests(scopedQueryKey);\n const isQueued = dispatcher.getIsActiveQueue(scopedQueryKey);\n const isActive = isFetching || isQueued;\n const canRefreshBlurred = isBlurred && refetchBlurred && !isActive;\n const canRefreshFocused = !isBlurred && !isActive;\n\n if (canRefreshBlurred || canRefreshFocused) {\n handleFetch();\n logger.debug({ title: `Performing refresh request`, type: \"system\", extra: { request } });\n }\n\n // Start new refresh counter\n handleRefresh();\n };\n\n const handleRefetch = () => {\n handleFetch({ force: true });\n handleRefresh();\n };\n\n /**\n * Events and timers are registered once and live longer than a single render.\n * This ref gives them the handlers and options from the latest render.\n */\n const latest = useRef({\n disabled,\n refetchOnFocus,\n refetchOnBlur,\n refetchOnReconnect,\n fetch: handleFetch,\n refresh: performRefresh,\n restartRefresh: handleRefresh,\n refetch: handleRefetch,\n });\n latest.current = {\n disabled,\n refetchOnFocus,\n refetchOnBlur,\n refetchOnReconnect,\n fetch: handleFetch,\n refresh: performRefresh,\n restartRefresh: handleRefresh,\n refetch: handleRefetch,\n };\n\n // Stable identity - safe to use in the dependency arrays\n const refetch = useCallback(() => {\n latest.current.refetch();\n }, []);\n\n // ******************\n // Fetching lifecycle\n // ******************\n\n // This help us to check for currently running requests\n const getIsFetchingIdentity = () => {\n // We need to check if the queryKey have the same cacheKey elements ongoing\n return dispatcher.getRunningRequests(scopedQueryKey).some((running) => running.request.cacheKey === cacheKey);\n };\n\n const initialFetchData = () => {\n const hasStaleData = getStaleStatus();\n const isFetching = getIsFetchingIdentity();\n // Suspended component already waited for this response - do not ask for it again right after mounting\n const cacheTimestamp = cache.get(scopedCacheKey)?.responseTimestamp;\n const isFreshSuspenseData =\n suspense &&\n (isSuspenseResolved.current ||\n (typeof cacheTimestamp === \"number\" && Date.now() - cacheTimestamp < suspenseFreshTime));\n isSuspenseResolved.current = false;\n\n if ((revalidate || hasStaleData) && !isFetching && !isFreshSuspenseData) {\n handleFetch();\n }\n };\n\n const updateFetchData = () => {\n const hasStaleData = getStaleStatus();\n const shouldUpdate = !revalidate ? hasStaleData : true;\n\n if (shouldUpdate) {\n /**\n * Only the updates are bounced - the initial request is sent right away\n */\n if (bounce) {\n logger.debug({ title: `Bounce request with ${bounceType}`, type: \"system\", extra: { queryKey, request } });\n // Bounced callback can run after the next renders - it has to use the latest request and options\n bounceFunction(() => latest.current.fetch());\n } else {\n handleFetch();\n }\n }\n };\n\n /**\n * Effects can run again without any change - on StrictMode remount or when the hidden <Activity> is revealed.\n * We compare the dependencies with the ones already handled, to fetch once on mount and once per change.\n */\n const handleFetchLifecycle = () => {\n const currentDependencies = [updateKey, disabled, ...dependencies];\n const previousDependencies = fetchDependencies.current;\n fetchDependencies.current = currentDependencies;\n\n if (!previousDependencies) {\n initialFetchData();\n return;\n }\n\n const hasChanged =\n previousDependencies.length !== currentDependencies.length ||\n currentDependencies.some((dependency, index) => !Object.is(dependency, previousDependencies[index]));\n\n if (hasChanged) {\n updateFetchData();\n }\n };\n\n // ******************\n // Events\n // ******************\n\n const handleMountEvents = () => {\n addCacheDataListener(request as unknown as R);\n addLifecycleListeners(request as unknown as R);\n\n // Options can change without re-registering the listeners - they are read when the event happens\n const focusUnmount = appManager.events.onFocus(() => {\n if (latest.current.refetchOnFocus && !latest.current.disabled) {\n latest.current.fetch();\n latest.current.restartRefresh();\n }\n });\n const blurUnmount = appManager.events.onBlur(() => {\n if (latest.current.refetchOnBlur && !latest.current.disabled) {\n latest.current.fetch();\n latest.current.restartRefresh();\n }\n });\n const onlineUnmount = appManager.events.onOnline(() => {\n if (latest.current.refetchOnReconnect && !latest.current.disabled) {\n latest.current.fetch();\n latest.current.restartRefresh();\n }\n });\n\n // Invalidation and deletion are emitted by the request cache key, which is shared between the scopes.\n // The event carries the key of the changed element - only our own one has to be fetched again.\n const handleCacheChange = (changedKey: string) => {\n if (changedKey === scopedCacheKey) {\n latest.current.fetch();\n }\n };\n const invalidateUnmount = cache.events.onInvalidateByKey(cacheKey, handleCacheChange);\n const deletionUnmount = cache.events.onDeleteByKey(cacheKey, handleCacheChange);\n\n const unmount = () => {\n clearCacheDataListener();\n focusUnmount();\n blurUnmount();\n onlineUnmount();\n invalidateUnmount();\n deletionUnmount();\n };\n\n return unmount;\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n /**\n * Initialization of the events related to data exchange with cache and queue\n * This allows to share the state with other hooks and keep it related\n */\n useDidUpdate(handleMountEvents, [updateKey, disabled], true);\n\n /**\n * Initial fetch triggered once data is stale or we use the refetch strategy\n * and the fetching logic for updates handling\n */\n useDidUpdate(handleFetchLifecycle, [updateKey, disabled, ...dependencies], true);\n\n /**\n * Refresh lifecycle handler\n */\n useDidUpdate(handleRefresh, [updateKey, ...dependencies, disabled, refresh, refreshTime], true);\n\n // ******************\n // Suspense\n // ******************\n if (suspense && !disabled) {\n const store = getSuspenseStore(cache);\n\n // Apply any cached suspense result (covers error responses that aren't stored in cache)\n const storedResult = store.results.get(scopedCacheKey);\n // Nobody picked the response up in time (suspended component got unmounted) - it is outdated now\n const suspenseResult =\n storedResult && Date.now() - storedResult.receivedTimestamp <= suspenseFreshTime ? storedResult : null;\n if (storedResult && !suspenseResult) {\n store.results.delete(scopedCacheKey);\n }\n if (suspenseResult) {\n // Result stays available until the end of the current render pass. React can render the component more than\n // once before it mounts (StrictMode, retry after a thrown error) and other components can wait for the same response.\n queueMicrotask(() => {\n if (store.results.get(scopedCacheKey) === suspenseResult) {\n store.results.delete(scopedCacheKey);\n }\n });\n isSuspenseResolved.current = true;\n if (suspenseResult.data !== null) {\n state.data = selectData(suspenseResult.data);\n }\n if (suspenseResult.error !== null) {\n state.error = suspenseResult.error;\n }\n if (suspenseResult.status !== null) {\n state.status = suspenseResult.status;\n }\n if (suspenseResult.extra !== null) {\n state.extra = suspenseResult.extra;\n }\n state.success = suspenseResult.success;\n state.loading = dispatcher.hasRunningRequests(scopedQueryKey);\n state.retries = suspenseResult.retries ?? state.retries;\n // Timestamps tell that the response was received - also when it came without any data\n state.responseTimestamp = new Date(suspenseResult.responseTimestamp);\n state.requestTimestamp = new Date(suspenseResult.requestTimestamp);\n }\n\n // Response without data (like 204 No Content) is still a response - suspending on it would never end\n const hasData = state.data !== null || state.error !== null || state.responseTimestamp !== null;\n\n if (!hasData) {\n let entry = store.promises.get(scopedCacheKey);\n if (!entry) {\n let resolvePromise: () => void;\n const promise = new Promise<void>((r) => {\n resolvePromise = r;\n });\n\n const unsubscribe = cache.events.onDataByKey(cacheKey, (cacheData: CacheValueType<any, any>) => {\n // Events of the same cache key are shared between the scopes\n if (!isSameScope(cacheData.scope, request.scope)) {\n return;\n }\n\n store.results.set(scopedCacheKey, {\n data: cacheData.data ?? null,\n error: cacheData.error ?? null,\n status: cacheData.status ?? null,\n extra: cacheData.extra ?? null,\n success: cacheData.success ?? false,\n retries: cacheData.retries ?? 0,\n responseTimestamp: cacheData.responseTimestamp ?? Date.now(),\n requestTimestamp: cacheData.requestTimestamp ?? Date.now(),\n receivedTimestamp: Date.now(),\n });\n resolvePromise();\n unsubscribe();\n store.promises.delete(scopedCacheKey);\n });\n\n entry = { promise, resolve: resolvePromise!, cleanup: unsubscribe };\n store.promises.set(scopedCacheKey, entry);\n }\n\n // Ensure the request is dispatched before suspending —\n // effects never run when a component suspends.\n // React may render a suspended component again before the queued request starts running,\n // so a queued request counts as dispatched too.\n if (!dispatcher.hasRunningRequests(scopedQueryKey) && !dispatcher.getIsActiveQueue(scopedQueryKey)) {\n dispatcher.add(request as unknown as R);\n }\n\n throw entry.promise;\n }\n\n // Data has arrived — clean up any leftover entry\n const entry = store.promises.get(scopedCacheKey);\n if (entry) {\n entry.cleanup();\n store.promises.delete(scopedCacheKey);\n }\n }\n\n // ******************\n // Error boundary\n // ******************\n if (throwOnError) {\n // The error has to be observed to rerender (and throw) even if the component does not read it\n setRenderKey(\"error\");\n setRenderKey(\"loading\");\n setRenderKey(\"success\");\n\n const details = getResponseDetails();\n // Errors of retried, canceled or offline (re-queued) requests are not final\n const isSettled = !state.loading && !details?.willRetry && !details?.isCanceled && !details?.isOffline;\n const hasError = !state.success && state.error !== null && state.error !== undefined;\n\n if (isSettled && hasError) {\n const error = state.error as ExtractErrorType<R>;\n if (typeof throwOnError === \"function\" ? throwOnError(error) : throwOnError) {\n throw error;\n }\n }\n }\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"loading\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n error: state.error,\n loading: state.loading,\n status: state.status as ExtractAdapterStatusType<ExtractAdapterType<R>>,\n success: state.success,\n extra: state.extra as ExtractAdapterExtraType<ExtractAdapterType<R>>,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n bounce: getBounceData(bounceData),\n ...actions,\n ...(callbacks as any),\n refetch,\n },\n trackedKeys,\n setRenderKey,\n ) as UseFetchReturnType<R, TSelected>;\n};\n","export const getRefreshTime = (refreshTime: number, dataTimestamp?: Date) => {\n if (dataTimestamp) {\n const timeDiff = Date.now() - +dataTimestamp;\n return timeDiff < refreshTime ? refreshTime - timeDiff : refreshTime;\n }\n return refreshTime;\n};\n","import type { RequestInstance, RequiredKeys } from \"@hyper-fetch/core\";\nimport { Time } from \"@hyper-fetch/core\";\nimport type { UseFetchOptionsType } from \"hooks/use-fetch\";\n\ntype DefaultOptionsType = RequiredKeys<Omit<UseFetchOptionsType<RequestInstance>, \"initialResponse\" | \"select\">> & {\n initialResponse: null;\n};\n\nexport const useFetchDefaultOptions: DefaultOptionsType = {\n suspense: false,\n dependencies: [],\n disabled: false,\n dependencyTracking: true,\n revalidate: true,\n initialResponse: null,\n keepPreviousData: \"auto\",\n refresh: false,\n refreshTime: Time.HOUR,\n refetchBlurred: true,\n refetchOnBlur: false,\n refetchOnFocus: false,\n refetchOnReconnect: false,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n bounceTimeout: 400,\n deepCompare: true,\n structuralSharing: true,\n throwOnError: false,\n};\n","import { Time } from \"@hyper-fetch/core\";\n\nimport type { UseInfiniteFetchConfigType } from \"./use-infinite-fetch.types\";\n\nexport const useInfiniteFetchDefaultOptions = {\n suspense: false,\n throwOnError: false,\n dependencies: [],\n disabled: false,\n dependencyTracking: true,\n // Pages restored from the cache are refetched only once they are stale\n revalidate: false,\n keepPreviousData: \"auto\",\n refresh: false,\n refreshTime: Time.HOUR,\n refetchBlurred: true,\n refetchOnBlur: false,\n refetchOnFocus: false,\n refetchOnReconnect: false,\n structuralSharing: true,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n bounceTimeout: 400,\n} satisfies Required<UseInfiniteFetchConfigType>;\n","import type { RequestInstance } from \"@hyper-fetch/core\";\nimport { getErrorMessage, mapResponseForSend, scopeKey } from \"@hyper-fetch/core\";\n\ntype LoadPageOptions = {\n request: RequestInstance;\n /** Skips requests started before this fetch was asked for */\n force: boolean;\n /** Filled with the functions stopping this fetch */\n cancellers: Set<VoidFunction>;\n isCancelled: () => boolean;\n};\n\n/**\n * Cancelled pages are not failures: the list simply did not need them anymore\n */\nexport const isCancelledResponse = (response: any) => {\n const message = response?.error?.message;\n return (\n !response?.success &&\n (message === getErrorMessage(\"abort\").message || message === getErrorMessage(\"deleted\").message)\n );\n};\n\n/**\n * Joins a request started elsewhere. Cancelling only stops waiting, the request belongs to someone else.\n */\nconst waitForResponse = (request: RequestInstance, requestId: string, cancellers: Set<VoidFunction>) => {\n const { requestManager } = request.client;\n\n return new Promise<any>((resolve) => {\n const finish = (response: any) => {\n unmountResponse();\n unmountRemove();\n cancellers.delete(cancel);\n resolve(response);\n };\n const cancel = () => finish(null);\n const unmountResponse = requestManager.events.onResponseById(requestId, ({ response, details }) => {\n if (response.success || (!details.willRetry && !details.isOffline)) {\n finish(response);\n }\n });\n const unmountRemove = requestManager.events.onRemoveById(requestId, cancel);\n\n cancellers.add(cancel);\n });\n};\n\nconst sendPage = async ({ request, force, cancellers }: LoadPageOptions) => {\n const { fetchDispatcher } = request.client;\n const pageRequest = force ? request.setDeduplicate(false) : request;\n let sentRequestId = \"\";\n\n const cancel = () => {\n fetchDispatcher.delete(\n scopeKey(request.queryKey, request.scope),\n sentRequestId,\n scopeKey(request.abortKey, request.scope),\n );\n };\n cancellers.add(cancel);\n\n const response = await (pageRequest as RequestInstance).send({\n dispatcherType: \"fetch\",\n onBeforeSent: ({ requestId }: { requestId: string }) => {\n sentRequestId = requestId;\n },\n } as any);\n\n cancellers.delete(cancel);\n return response;\n};\n\n/**\n * Loads a page, reusing the request already running for it\n */\nexport const loadPage = async (options: LoadPageOptions) => {\n const { request, force, cancellers, isCancelled } = options;\n\n // A forced fetch must not reuse a request started before it was asked for\n if (!force) {\n const running = request.client.fetchDispatcher\n .getRunningRequests(scopeKey(request.queryKey, request.scope))\n .find((item) => item.request.cacheKey === request.cacheKey);\n\n if (running) {\n const response = await waitForResponse(request, running.requestId, cancellers);\n if (response) {\n return mapResponseForSend(request, response);\n }\n if (isCancelled()) {\n return null;\n }\n }\n }\n\n return sendPage(options);\n};\n","import type { ClientInstance, RequestInstance } from \"@hyper-fetch/core\";\nimport { keyReplacer } from \"utils/key.utils\";\n\nimport type { InfiniteStore } from \"./use-infinite-fetch.store\";\nimport type { InfiniteSnapshot } from \"./use-infinite-fetch.store.types\";\n\n/**\n * Identity of a list. Everything describing the request takes part in it, so a changed filter, sort, page size\n * or URL param starts a new list without anything having to be listed by hand.\n */\nexport const getInfiniteKey = (request: RequestInstance, pagination: unknown, maxPages?: number) => {\n return JSON.stringify([request.toJSON(), pagination, maxPages ?? null], (key, value) => {\n return typeof value === \"function\" ? value.toString() : keyReplacer(key, value);\n });\n};\n\n/**\n * Keeps the first occurrence of every item\n */\nexport const getUniqueItems = (items: unknown[], uniqueBy: unknown) => {\n if (uniqueBy === undefined) {\n return items;\n }\n\n const seen = new Set<unknown>();\n return items.filter((item: any) => {\n const identity = typeof uniqueBy === \"function\" ? uniqueBy({ item }) : item?.[uniqueBy as string];\n if (seen.has(identity)) {\n return false;\n }\n seen.add(identity);\n return true;\n });\n};\n\n/**\n * Decides if the previous list stays on screen while the new one loads its first page\n */\nexport const getShouldKeepPreviousList = (\n mode: \"auto\" | \"preserve\" | \"clean\",\n previous: RequestInstance,\n current: RequestInstance,\n) => {\n if (mode === \"auto\") {\n return previous.method === current.method && previous.endpoint === current.endpoint;\n }\n return mode === \"preserve\";\n};\n\n/**\n * Tells whether nothing changed between two states of a list, so nobody has to be notified\n */\nexport const isSameSnapshot = (a: InfiniteSnapshot, b: InfiniteSnapshot) => {\n return (Object.keys(a) as (keyof InfiniteSnapshot)[]).every((key) => a[key] === b[key]);\n};\n\nconst stores = new WeakMap<ClientInstance, Map<string, InfiniteStore>>();\n\n/**\n * Stores of the lists shown with the client, by the key of the list\n */\nexport const getStores = (client: ClientInstance) => {\n let clientStores = stores.get(client);\n if (!clientStores) {\n clientStores = new Map();\n stores.set(client, clientStores);\n }\n return clientStores;\n};\n","import type { CacheValueType, PaginationConfig, PaginationPageContext, RequestInstance } from \"@hyper-fetch/core\";\nimport {\n getCachedPages,\n getHasNextPage,\n getHasPreviousPage,\n getInitialPageParam,\n getNextPageParam,\n getPageItems,\n getPageRequest,\n getPageTotal,\n getPaginationMode,\n getPreviousPageParam,\n replaceEqualDeep,\n scopeKey,\n stringifyKey,\n} from \"@hyper-fetch/core\";\nimport { isStaleCacheData } from \"helpers/use-tracked-state/use-tracked-state.utils\";\nimport { pickInitialCacheData } from \"hydrate/hydrate.utils\";\n\nimport { isCancelledResponse, loadPage } from \"./use-infinite-fetch.requests\";\nimport type {\n FetchedPage,\n InfinitePage,\n InfiniteSnapshot,\n InfiniteStoreOptions,\n Operation,\n OperationKind,\n} from \"./use-infinite-fetch.store.types\";\nimport type { InfinitePageEvent } from \"./use-infinite-fetch.types\";\nimport { getStores, isSameSnapshot } from \"./use-infinite-fetch.utils\";\n\n// Render and commit are separate steps, a store waits this long for the component that created it\nconst unusedStoreTime = 1000;\n\n/**\n * State of a single list. Hooks showing the same list share one store, so they stay in sync and never request\n * the same page twice. Pages are ordinary requests under their own cache keys - nothing extra is stored.\n *\n * Fetches run one at a time: every page depends on the list as it was when its value was computed.\n */\nexport class InfiniteStore {\n private listeners = new Set<VoidFunction>();\n private pageListeners = new Set<(event: InfinitePageEvent<any>) => void>();\n private pages: InfinitePage[] = [];\n // Values of pages dropped by `maxPages`, a cursor list may have no other way of going back to them\n private droppedParams: unknown[] = [];\n private queue: Operation[] = [];\n private running: Operation | null = null;\n private cancellers = new Set<VoidFunction>();\n // Pages being refetched - their cache events wait for the whole list to be swapped at once\n private refetchedKeys = new Set<string>();\n private unmountCacheListeners: VoidFunction | null = null;\n private unusedTimer: ReturnType<typeof setTimeout> | null = null;\n private enabledHooks = 0;\n private started = false;\n private settled = false;\n private firstFetch: Promise<any> = Promise.resolve(null);\n private nextPageError = false;\n private previousPageError = false;\n private result: { error: any; status: any; extra: any; success: boolean } = {\n error: null,\n status: null,\n extra: null,\n success: false,\n };\n private snapshot: InfiniteSnapshot;\n\n constructor(\n readonly key: string,\n private options: InfiniteStoreOptions,\n ) {\n getPaginationMode(options.pagination);\n this.restorePages();\n this.snapshot = this.createSnapshot();\n }\n\n // ******************\n // State\n // ******************\n\n getSnapshot = () => this.snapshot;\n\n subscribe = (listener: VoidFunction) => {\n this.listeners.add(listener);\n if (this.listeners.size === 1) {\n this.attach();\n }\n\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) {\n this.detach();\n }\n };\n };\n\n onPage = (listener: (event: InfinitePageEvent<any>) => void) => {\n this.pageListeners.add(listener);\n return () => {\n this.pageListeners.delete(listener);\n };\n };\n\n /** Counts the hooks allowed to fetch - changes of the cache refetch the list only for them */\n enable = () => {\n this.enabledHooks += 1;\n return () => {\n this.enabledHooks -= 1;\n };\n };\n\n /** Callbacks can capture values of the latest render */\n setPagination = (pagination: PaginationConfig) => {\n this.options.pagination = pagination;\n };\n\n hasPages = () => this.pages.length > 0;\n\n // ******************\n // Actions\n // ******************\n\n /**\n * Loads the list when it is first needed. Safe to call many times.\n */\n start = ({ revalidate }: { revalidate?: boolean } = {}) => {\n if (this.started) {\n // A hook joining a list already on screen, or coming back to it, checks the loaded pages like a new mount\n const isIdle = !this.running && this.queue.length === 0;\n if (isIdle && this.pages.length > 0 && (revalidate || this.getHasStalePages())) {\n this.revalidate();\n }\n return this.firstFetch;\n }\n this.started = true;\n\n if (this.pages.length === 0) {\n this.firstFetch = this.schedule(\"initial\");\n } else if (revalidate || this.getHasStalePages()) {\n this.revalidate();\n } else {\n this.settled = true;\n }\n this.publish();\n return this.firstFetch;\n };\n\n fetchNextPage = () => this.fetchDirection(\"next\");\n\n fetchPreviousPage = () => this.fetchDirection(\"previous\");\n\n /**\n * Refetch asked for by the user: anything already refetching is older than this call and gets replaced.\n */\n refetch = () => {\n if (this.pages.length === 0) {\n return this.revalidate();\n }\n this.getOperations(\"refetch\").forEach(this.cancelOperation);\n return this.schedule(\"refetch\");\n };\n\n /**\n * Automatic refetch: joins the one in progress\n */\n revalidate = () => {\n const kind = this.pages.length > 0 ? \"refetch\" : \"initial\";\n return this.getOperations(kind)[0]?.promise ?? this.schedule(kind);\n };\n\n reset = () => {\n this.cancelOperations();\n const startParam = stringifyKey(getInitialPageParam(this.options.request, this.options.pagination));\n\n this.pages = this.pages.filter((page) => stringifyKey(page.param) === startParam);\n this.droppedParams = [];\n this.nextPageError = false;\n this.previousPageError = false;\n this.settled = false;\n this.started = true;\n\n return this.schedule(this.pages.length > 0 ? \"refetch\" : \"initial\");\n };\n\n abort = () => {\n this.cancelOperations();\n this.settled = true;\n this.publish();\n };\n\n /** The list is no longer on screen - stop fetching its pages */\n cancelIfUnused = () => {\n if (this.listeners.size === 0) {\n this.cancelOperations();\n }\n };\n\n /** A store that threw its error starts over when the Error Boundary renders the component again */\n evictSoon = () => {\n setTimeout(this.evict, 0);\n };\n\n /** Stores created while rendering are removed when the component never mounts */\n scheduleUnusedCheck = () => {\n this.unusedTimer = setTimeout(() => {\n this.unusedTimer = null;\n if (this.running || this.queue.length > 0) {\n this.scheduleUnusedCheck();\n } else {\n this.evict();\n }\n }, unusedStoreTime);\n };\n\n // ******************\n // Operations\n // ******************\n\n private fetchDirection = (kind: \"next\" | \"previous\") => {\n if (this.pages.length === 0) {\n return this.getOperations(\"initial\")[0]?.promise ?? Promise.resolve(null);\n }\n const scheduled = this.getOperations(kind)[0];\n if (scheduled) {\n return scheduled.promise;\n }\n if (kind === \"next\" ? this.getNextParam() === undefined : !this.getPreviousTarget()) {\n return Promise.resolve(null);\n }\n if (kind === \"next\") {\n this.nextPageError = false;\n } else {\n this.previousPageError = false;\n }\n return this.schedule(kind);\n };\n\n private getOperations = (kind: OperationKind) => {\n const operations = this.running ? [this.running, ...this.queue] : this.queue;\n return operations.filter((operation) => operation.kind === kind && !operation.cancelled);\n };\n\n private schedule = (kind: OperationKind) => {\n const operation = { kind, cancelled: false } as Operation;\n operation.promise = new Promise<any>((resolve) => {\n operation.resolve = resolve;\n });\n\n if (kind === \"initial\") {\n this.settled = false;\n }\n this.queue.push(operation);\n this.pump();\n this.publish();\n return operation.promise;\n };\n\n private pump = async () => {\n if (this.running) {\n return;\n }\n const operation = this.queue.shift();\n if (!operation) {\n return;\n }\n\n this.running = operation;\n const previousPages = this.pages;\n let response = null;\n try {\n response = await this.perform(operation);\n } catch (error) {\n this.setFailure(error);\n }\n this.keepValidPages(previousPages);\n this.running = null;\n this.refetchedKeys.clear();\n\n if ((operation.kind === \"initial\" || operation.kind === \"refetch\") && !operation.cancelled) {\n this.settled = true;\n }\n\n operation.resolve(operation.cancelled ? null : response);\n this.pump();\n this.publish();\n };\n\n private cancelOperation = (operation: Operation) => {\n operation.cancelled = true;\n if (operation === this.running) {\n this.cancellers.forEach((cancel) => cancel());\n this.cancellers.clear();\n this.refetchedKeys.clear();\n } else {\n this.queue = this.queue.filter((item) => item !== operation);\n operation.resolve(null);\n }\n };\n\n private cancelOperations = () => {\n [...this.queue, ...(this.running ? [this.running] : [])].forEach(this.cancelOperation);\n };\n\n private perform = (operation: Operation) => {\n switch (operation.kind) {\n case \"next\": {\n return this.performNext(operation);\n }\n case \"previous\": {\n return this.performPrevious(operation);\n }\n case \"refetch\": {\n return this.performRefetch(operation);\n }\n default: {\n return this.performInitial(operation);\n }\n }\n };\n\n private performInitial = async (operation: Operation) => {\n const { request, pagination } = this.options;\n const fetched = await this.fetchPage(operation, getInitialPageParam(request, pagination));\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n if (fetched.response.success) {\n this.pages = [this.createPage(fetched)];\n }\n return fetched.response;\n };\n\n private performNext = async (operation: Operation) => {\n const param = this.getNextParam();\n if (param === undefined) {\n return null;\n }\n\n const fetched = await this.fetchPage(operation, param);\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n this.nextPageError = !fetched.response.success;\n if (fetched.response.success) {\n this.pages = [...this.pages, this.createPage(fetched)];\n this.trimPages(\"start\");\n }\n return fetched.response;\n };\n\n private performPrevious = async (operation: Operation) => {\n const target = this.getPreviousTarget();\n if (!target) {\n return null;\n }\n\n const { param } = target;\n const fetched = await this.fetchPage(operation, param);\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n this.previousPageError = !fetched.response.success;\n if (fetched.response.success) {\n if (target.isDropped) {\n this.droppedParams = this.droppedParams.slice(0, -1);\n }\n this.pages = [this.createPage(fetched), ...this.pages];\n this.trimPages(\"end\");\n }\n return fetched.response;\n };\n\n private performRefetch = async (operation: Operation) => {\n const current = this.pages;\n current.forEach((page) => this.refetchedKeys.add(page.storageKey));\n\n return getPaginationMode(this.options.pagination) === \"cursor\"\n ? this.refetchInOrder(operation, current)\n : this.refetchAtOnce(operation, current);\n };\n\n /**\n * Page and offset values do not depend on other pages, so they can be requested together\n */\n private refetchAtOnce = async (operation: Operation, current: InfinitePage[]) => {\n const results = await Promise.all(current.map((page) => this.fetchPage(operation, page.param, true)));\n if (operation.cancelled) {\n return null;\n }\n\n const pages = current.map((page, index) => {\n const fetched = results[index];\n return fetched?.response.success ? this.createPage(fetched) : page;\n });\n // The list can be shorter than before. Pages after its new end are gone, whatever their requests returned.\n const end = pages.findIndex((page, index) => {\n return results[index]?.response.success && !getHasNextPage(this.getContext(page, pages.slice(0, index + 1)));\n });\n const length = end === -1 ? pages.length : end + 1;\n const kept = results.slice(0, length);\n const failed = kept.find((fetched) => fetched && !fetched.response.success);\n const last = failed ?? kept.findLast(Boolean);\n\n this.pages = pages.slice(0, length);\n if (last) {\n this.setResult(last.response);\n }\n return last?.response ?? null;\n };\n\n /**\n * Every cursor comes from the page before it, and the fresh data can hold different cursors than before.\n * The list is replaced only when the whole chain arrived, a failure leaves it as it was.\n */\n private refetchInOrder = async (operation: Operation, current: InfinitePage[]) => {\n const fresh: InfinitePage[] = [];\n let param = current[0].param;\n let response = null;\n\n while (fresh.length < current.length) {\n // Each request needs the response of the previous one\n // eslint-disable-next-line no-await-in-loop\n const fetched = await this.fetchPage(operation, param, true);\n if (!fetched) {\n return null;\n }\n\n response = fetched.response;\n this.setResult(response);\n if (!response.success) {\n return response;\n }\n\n const page = this.createPage(fetched);\n fresh.push(page);\n\n const context = this.getContext(page, fresh);\n if (!getHasNextPage(context)) {\n break;\n }\n param = getNextPageParam(context);\n }\n\n this.pages = fresh;\n return response;\n };\n\n private trimPages = (side: \"start\" | \"end\") => {\n const { maxPages } = this.options;\n if (!maxPages || this.pages.length <= maxPages) {\n return;\n }\n\n const overflow = this.pages.length - maxPages;\n if (side === \"start\") {\n this.droppedParams = [...this.droppedParams, ...this.pages.slice(0, overflow).map((page) => page.param)];\n this.pages = this.pages.slice(overflow);\n } else {\n this.pages = this.pages.slice(0, maxPages);\n }\n };\n\n // ******************\n // Requests\n // ******************\n\n private fetchPage = async (operation: Operation, param: unknown, force = false): Promise<FetchedPage | null> => {\n const request = getPageRequest(this.options.request, this.options.pagination, param);\n const response = await loadPage({\n request,\n force,\n cancellers: this.cancellers,\n isCancelled: () => operation.cancelled,\n });\n\n if (operation.cancelled || !response || isCancelledResponse(response)) {\n return null;\n }\n\n this.pageListeners.forEach((listener) => listener({ response, request, param }));\n return { param, request, response };\n };\n\n // ******************\n // Pages\n // ******************\n\n private getContext = (page: InfinitePage, pages: InfinitePage[] = this.pages): PaginationPageContext => ({\n request: this.options.request,\n pagination: this.options.pagination,\n data: page.data,\n param: page.param,\n pages: pages.map((item) => item.data),\n });\n\n private getNextParam = () => {\n const last = this.pages.at(-1);\n if (!last || !getHasNextPage(this.getContext(last))) {\n return;\n }\n return getNextPageParam(this.getContext(last));\n };\n\n // The first page of a cursor list has no cursor, so \"no value\" cannot mean \"no page\"\n private getPreviousTarget = (): { param: unknown; isDropped: boolean } | null => {\n const first = this.pages[0];\n if (!first) {\n return null;\n }\n if (this.droppedParams.length > 0) {\n return { param: this.droppedParams.at(-1), isDropped: true };\n }\n if (getHasPreviousPage(this.getContext(first))) {\n return { param: getPreviousPageParam(this.getContext(first)), isDropped: false };\n }\n return null;\n };\n\n private getHasStalePages = () => {\n return this.pages.some(({ request, responseTimestamp }) => {\n // Pages of requests without cache are kept only here\n const kept = request.cache ? null : { staleTime: request.staleTime, responseTimestamp };\n const value = this.readValue(request) ?? kept;\n return !value || isStaleCacheData(value.staleTime, value.responseTimestamp);\n });\n };\n\n private readValue = (request: RequestInstance) => {\n const { client } = request;\n const storageKey = scopeKey(request.cacheKey, request.scope);\n return pickInitialCacheData<CacheValueType>(\n client.cache.get(storageKey),\n this.options.hydration?.get(client, storageKey),\n );\n };\n\n /** Responses go through the response mapper of the request, an asynchronous one cannot be read synchronously */\n private mapValue = (request: RequestInstance, value: CacheValueType) => {\n const mapped: any = request.unstable_responseMapper ? request.unstable_responseMapper(value as any) : value;\n return mapped instanceof Promise ? undefined : mapped;\n };\n\n private createPage = ({ param, request, response }: FetchedPage): InfinitePage => {\n // Reading the cache keeps changes made after the response arrived, like optimistic updates\n const value = this.readValue(request);\n const cached =\n value && value.responseTimestamp >= response.responseTimestamp ? this.mapValue(request, value) : null;\n\n return {\n param,\n request,\n storageKey: scopeKey(request.cacheKey, request.scope),\n data: cached?.success ? cached.data : response.data,\n responseTimestamp: response.responseTimestamp,\n };\n };\n\n private restorePages = () => {\n const { request, pagination, maxPages } = this.options;\n\n this.pages = getCachedPages({\n request,\n pagination,\n maxPages,\n read: (pageRequest) => {\n const value = this.readValue(pageRequest);\n const mapped = value ? this.mapValue(pageRequest, value) : null;\n return mapped?.success ? { ...value, data: mapped.data } : null;\n },\n }).map(({ param, request: pageRequest, value }) => ({\n param,\n request: pageRequest,\n storageKey: scopeKey(pageRequest.cacheKey, pageRequest.scope),\n data: value.data,\n responseTimestamp: Number(value.responseTimestamp),\n }));\n };\n\n /** Picks up everything that happened between rendering and mounting */\n private syncPages = () => {\n if (this.running || this.queue.length > 0) {\n return;\n }\n if (this.pages.length === 0) {\n this.restorePages();\n return;\n }\n\n this.pages = this.pages.map((page) => {\n const value = this.readValue(page.request);\n const mapped = value ? this.mapValue(page.request, value) : null;\n return mapped?.success\n ? { ...page, data: mapped.data, responseTimestamp: Number(value?.responseTimestamp) }\n : page;\n });\n };\n\n private setFailure = (error: unknown) => {\n this.result = { error, status: null, extra: null, success: false };\n };\n\n /**\n * Pagination callbacks read the data of every page. When one of them throws, the page that caused it is not\n * used and the error is reported instead of breaking the list.\n */\n private keepValidPages = (previousPages: InfinitePage[]) => {\n try {\n this.createSnapshot();\n } catch (error) {\n this.pages = previousPages;\n this.setFailure(error);\n }\n };\n\n private setResult = (response: any) => {\n // Like the flags of TanStack Query, these describe the last fetch only - next and previous set theirs after this\n this.nextPageError = false;\n this.previousPageError = false;\n this.result = {\n error: response.success ? null : response.error,\n status: response.status,\n extra: response.extra,\n success: response.success,\n };\n };\n\n // ******************\n // Cache\n // ******************\n\n private attach = () => {\n if (this.unusedTimer) {\n clearTimeout(this.unusedTimer);\n this.unusedTimer = null;\n }\n\n const { client } = this.options.request;\n const clientStores = getStores(client);\n if (!clientStores.has(this.key) && client.mode !== \"server\") {\n clientStores.set(this.key, this);\n }\n\n const { cache } = client;\n const unmountData = cache.events.onData(this.handleCacheData);\n const unmountInvalidate = cache.events.onInvalidate(this.handleCacheChange);\n const unmountDelete = cache.events.onDelete(this.handleCacheChange);\n\n this.unmountCacheListeners = () => {\n unmountData();\n unmountInvalidate();\n unmountDelete();\n };\n\n this.syncPages();\n this.publish();\n };\n\n private detach = () => {\n this.unmountCacheListeners?.();\n this.unmountCacheListeners = null;\n this.evict();\n };\n\n private evict = () => {\n if (this.listeners.size > 0) {\n return;\n }\n const clientStores = getStores(this.options.request.client);\n if (clientStores.get(this.key) === this) {\n clientStores.delete(this.key);\n }\n };\n\n private handleCacheData = (value: CacheValueType) => {\n const storageKey = scopeKey(value.cacheKey, value.scope ?? null);\n if (!value.success || this.refetchedKeys.has(storageKey)) {\n return;\n }\n\n const index = this.pages.findIndex((page) => page.storageKey === storageKey);\n const page = this.pages[index];\n const mapped = page ? this.mapValue(page.request, value) : null;\n if (!page || !mapped?.success) {\n return;\n }\n\n const previousPages = this.pages;\n this.pages = this.pages.map((item, itemIndex) => {\n return itemIndex === index\n ? { ...item, data: mapped.data, responseTimestamp: Number(value.responseTimestamp) }\n : item;\n });\n this.keepValidPages(previousPages);\n this.publish();\n };\n\n private hasInvalidation = false;\n\n /**\n * Invalidated data may have changed after a running refetch started, so that refetch is replaced.\n * Invalidating by a pattern reports every key on its own, all of them are handled by one refetch.\n */\n private handleCacheChange = (key: string) => {\n const isLoaded = this.pages.some((page) => page.storageKey === key || page.request.cacheKey === key);\n if (!isLoaded || this.hasInvalidation) {\n return;\n }\n\n this.hasInvalidation = true;\n queueMicrotask(() => {\n this.hasInvalidation = false;\n if (this.enabledHooks > 0) {\n this.refetch();\n }\n });\n };\n\n // ******************\n // Snapshot\n // ******************\n\n private createSnapshot = (): InfiniteSnapshot => {\n const { structuralSharing = true } = this.options;\n const previous = this.snapshot as InfiniteSnapshot | undefined;\n const share = <T>(prev: T | undefined, next: T) =>\n structuralSharing && prev ? replaceEqualDeep(prev, next) : next;\n\n const contexts = this.pages.map((page) => this.getContext(page));\n const last = contexts.at(-1);\n const totals = contexts.map(getPageTotal).filter((total) => total !== null);\n const operations = [...this.queue, ...(this.running ? [this.running] : [])].filter((item) => !item.cancelled);\n const isRunning = (kind: OperationKind) => operations.some((item) => item.kind === kind);\n\n return {\n items: share(previous?.items, contexts.flatMap((context) => getPageItems(context))),\n data: share(previous?.data, this.pages.map((page) => page.data)),\n pageParams: share(previous?.pageParams, this.pages.map((page) => page.param)),\n total: totals.length > 0 ? (totals.at(-1) as number) : null,\n hasNextPage: !!last && this.getNextParam() !== undefined,\n hasPreviousPage: !!this.getPreviousTarget(),\n loading: this.pages.length === 0 && !this.settled,\n isFetching: operations.length > 0,\n isRefetching: isRunning(\"refetch\"),\n isFetchingNextPage: isRunning(\"next\"),\n isFetchingPreviousPage: isRunning(\"previous\"),\n isFetchNextPageError: this.nextPageError,\n isFetchPreviousPageError: this.previousPageError,\n ...this.result,\n };\n };\n\n private publish = () => {\n const snapshot = this.createSnapshot();\n if (isSameSnapshot(this.snapshot, snapshot)) {\n return;\n }\n this.snapshot = snapshot;\n this.listeners.forEach((listener) => listener());\n };\n}\n\n/**\n * Returns the store of the list, shared between all the mounted hooks showing it.\n * Server renders never share one: a client can serve many users at the same time.\n */\nexport const getInfiniteStore = (key: string, options: InfiniteStoreOptions) => {\n const { client } = options.request;\n if (client.mode === \"server\" || typeof window === \"undefined\") {\n return new InfiniteStore(key, options);\n }\n\n const clientStores = getStores(client);\n let store = clientStores.get(key);\n if (!store) {\n store = new InfiniteStore(key, options);\n clientStores.set(key, store);\n store.scheduleUnusedCheck();\n }\n return store;\n};\n","import { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n ExtractErrorType,\n Pagination,\n PaginationConfig,\n PaginationItem,\n RequestInstance,\n} from \"@hyper-fetch/core\";\nimport { replaceEqualDeep } from \"@hyper-fetch/core\";\nimport { useHydration } from \"hydrate/hydrate\";\nimport { useProvider } from \"provider\";\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\n\nimport { useInfiniteFetchDefaultOptions } from \"./use-infinite-fetch.constants\";\nimport type { InfiniteStore } from \"./use-infinite-fetch.store\";\nimport { getInfiniteStore } from \"./use-infinite-fetch.store\";\nimport type { InfiniteSnapshot } from \"./use-infinite-fetch.store.types\";\nimport type { UseInfiniteFetchOptionsType, UseInfiniteFetchReturnType } from \"./use-infinite-fetch.types\";\nimport { getInfiniteKey, getShouldKeepPreviousList, getUniqueItems } from \"./use-infinite-fetch.utils\";\n\n// What decides about a returned value - the list on screen also depends on the new list still loading\nconst trackedSources: Record<string, (keyof InfiniteSnapshot)[]> = {\n items: [\"items\", \"loading\"],\n pages: [\"data\", \"loading\"],\n pageParams: [\"pageParams\", \"loading\"],\n total: [\"total\", \"loading\"],\n isPreviousData: [\"data\", \"loading\"],\n loading: [\"data\", \"loading\"],\n};\n\nconst trackedKeys = [\n \"items\",\n \"pages\",\n \"pageParams\",\n \"total\",\n \"hasNextPage\",\n \"hasPreviousPage\",\n \"loading\",\n \"isFetching\",\n \"isRefetching\",\n \"isFetchingNextPage\",\n \"isFetchingPreviousPage\",\n \"isFetchNextPageError\",\n \"isFetchPreviousPageError\",\n \"isPreviousData\",\n \"error\",\n \"status\",\n \"extra\",\n \"success\",\n] as const;\n\n/**\n * Loads a list page by page. Say which fields page through the request, and the hook takes care of the rest:\n * every page is a normal request under its own cache key, and the hook glues them together.\n *\n * A changed filter, sort or URL param starts a new list on its own. When to load more is up to you - call\n * `fetchNextPage` from a button, an intersection observer, `onEndReached` or a virtualizer.\n *\n * @param request Request instance\n * @param options Hook options, `pagination` is required\n * @returns\n * @example\n * ```tsx\n * const { items, hasNextPage, fetchNextPage } = useInfiniteFetch(getFeed.setQueryParams({ topic }), {\n * pagination: { cursor: \"cursor\", next: \"nextCursor\", items: \"data\" },\n * });\n * ```\n */\nexport const useInfiniteFetch = <\n R extends RequestInstance,\n const P extends Pagination<R>,\n TSelected = PaginationItem<R, P>[],\n>(\n request: R,\n options: UseInfiniteFetchOptionsType<R, P, TSelected>,\n): UseInfiniteFetchReturnType<R, P, TSelected> => {\n const { config: globalConfig } = useProvider();\n const {\n pagination,\n uniqueBy,\n maxPages,\n select,\n suspense,\n throwOnError,\n dependencies,\n disabled,\n dependencyTracking,\n revalidate,\n keepPreviousData,\n refresh,\n refreshTime,\n refetchBlurred,\n refetchOnBlur,\n refetchOnFocus,\n refetchOnReconnect,\n structuralSharing,\n bounce,\n bounceType,\n bounceTime,\n bounceTimeout,\n } = {\n ...useInfiniteFetchDefaultOptions,\n ...globalConfig.useInfiniteFetchConfig,\n ...options,\n };\n\n const { client } = request;\n const hydration = useHydration();\n\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({ interval: bounceTime, timeout: bounceTimeout });\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n // ******************\n // Store\n // ******************\n\n const key = getInfiniteKey(request, pagination, maxPages);\n const storeRef = useRef<InfiniteStore | null>(null);\n const storeClientRef = useRef(client);\n\n if (!storeRef.current || storeRef.current.key !== key || storeClientRef.current !== client) {\n storeClientRef.current = client;\n storeRef.current = getInfiniteStore(key, {\n request,\n pagination: pagination as PaginationConfig,\n maxPages,\n structuralSharing,\n hydration,\n });\n }\n const store = storeRef.current;\n\n // Rerenders only when something the component reads has changed\n const usedKeys = useRef(new Set<string>()).current;\n const renderedRef = useRef<{ store: InfiniteStore; snapshot: InfiniteSnapshot } | null>(null);\n\n const getSnapshot = () => {\n const next = store.getSnapshot();\n const rendered = renderedRef.current;\n\n if (dependencyTracking && rendered?.store === store) {\n const hasChanged = [...usedKeys].some((usedKey) => {\n const sources = trackedSources[usedKey] ?? [usedKey as keyof InfiniteSnapshot];\n return sources.some((source) => rendered.snapshot[source] !== next[source]);\n });\n if (!hasChanged) {\n return rendered.snapshot;\n }\n }\n\n renderedRef.current = { store, snapshot: next };\n return next;\n };\n\n const snapshot = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);\n\n // ******************\n // Latest values\n // ******************\n\n const callbacks = useRef<{\n onSuccess?: (event: any) => void;\n onError?: (event: any) => void;\n onFinished?: (event: any) => void;\n onReset?: VoidFunction;\n }>({});\n\n const latest = useRef({ disabled, revalidate, refetchOnBlur, refetchOnFocus, refetchOnReconnect });\n latest.current = { disabled, revalidate, refetchOnBlur, refetchOnFocus, refetchOnReconnect };\n\n // ******************\n // Lifecycle\n // ******************\n\n useEffect(() => {\n store.setPagination(pagination as PaginationConfig);\n });\n\n useEffect(() => {\n return store.onPage((event) => {\n if (event.response.success) {\n callbacks.current.onSuccess?.(event);\n } else {\n callbacks.current.onError?.(event);\n }\n callbacks.current.onFinished?.(event);\n });\n }, [store]);\n\n /**\n * A new list stops the pages of the previous one, so a late response never gets in the way\n */\n const mountedStore = useRef<InfiniteStore | null>(null);\n\n useEffect(() => {\n const previous = mountedStore.current;\n mountedStore.current = store;\n\n if (previous && previous !== store) {\n previous.cancelIfUnused();\n callbacks.current.onReset?.();\n }\n if (disabled) {\n return;\n }\n\n if (bounce && previous && previous !== store && !store.hasPages()) {\n bounceFunction(() => {\n // The list could have been left for another one, or disabled, before the bounce settled\n if (mountedStore.current === store && !latest.current.disabled) {\n store.start({ revalidate: latest.current.revalidate });\n }\n });\n } else {\n store.start({ revalidate });\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [store, disabled]);\n\n useEffect(() => {\n if (disabled) {\n return;\n }\n return store.enable();\n }, [store, disabled]);\n\n // Effects run again in StrictMode and when a hidden list is shown - only changed values are a reason to refetch\n const usedDependencies = useRef(dependencies);\n\n useEffect(() => {\n const previous = usedDependencies.current;\n usedDependencies.current = dependencies;\n\n const hasChanged =\n previous.length !== dependencies.length ||\n previous.some((value, index) => !Object.is(value, dependencies[index]));\n if (hasChanged && !disabled) {\n store.refetch();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n\n useEffect(() => {\n const { appManager } = client;\n const handle = (option: \"refetchOnBlur\" | \"refetchOnFocus\" | \"refetchOnReconnect\") => () => {\n if (latest.current[option] && !latest.current.disabled) {\n store.revalidate();\n }\n };\n\n const unmountFocus = appManager.events.onFocus(handle(\"refetchOnFocus\"));\n const unmountBlur = appManager.events.onBlur(handle(\"refetchOnBlur\"));\n const unmountOnline = appManager.events.onOnline(handle(\"refetchOnReconnect\"));\n\n return () => {\n unmountFocus();\n unmountBlur();\n unmountOnline();\n };\n }, [client, store]);\n\n useEffect(() => {\n if (!refresh || disabled) {\n return;\n }\n\n const timer = setInterval(() => {\n if (client.appManager.isFocused || refetchBlurred) {\n store.revalidate();\n }\n }, refreshTime);\n\n return () => clearInterval(timer);\n }, [client, store, refresh, refreshTime, refetchBlurred, disabled]);\n\n // ******************\n // Previous list\n // ******************\n\n const previousList = useRef<{ store: InfiniteStore; request: RequestInstance; snapshot: InfiniteSnapshot } | null>(\n null,\n );\n\n useEffect(() => {\n if (snapshot.data.length > 0) {\n previousList.current = { store, request, snapshot };\n }\n });\n\n const previous = previousList.current;\n const isPreviousData =\n !disabled &&\n snapshot.loading &&\n snapshot.data.length === 0 &&\n !!previous &&\n previous.store !== store &&\n getShouldKeepPreviousList(keepPreviousData, previous.request, request);\n\n const list = isPreviousData ? previous.snapshot : snapshot;\n\n // ******************\n // Suspense\n // ******************\n\n const isServer = client.mode === \"server\" || typeof window === \"undefined\";\n\n if (suspense && !disabled && !isServer && snapshot.loading && !isPreviousData) {\n throw store.start({ revalidate });\n }\n\n // ******************\n // Items\n // ******************\n\n const uniqueByRef = useRef(uniqueBy);\n uniqueByRef.current = uniqueBy;\n const uniqueByKey = typeof uniqueBy === \"function\" ? uniqueBy.toString() : uniqueBy;\n\n const uniqueItems = useMemo(() => {\n return getUniqueItems(list.items, uniqueByRef.current);\n // Inline functions change on every render, the key changes only with their code\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [list.items, uniqueByKey]);\n\n const selectedRef = useRef<unknown>(null);\n let items: unknown = uniqueItems;\n let selectError: unknown = null;\n\n if (select) {\n try {\n const selected = select({ items: uniqueItems as PaginationItem<R, P>[], pages: list.data as any[] });\n items = structuralSharing ? replaceEqualDeep(selectedRef.current, selected) : selected;\n selectedRef.current = items;\n } catch (error) {\n // Like in TanStack Query, a failing select is the error of the list and the last selected value stays\n selectError = error;\n items = selectedRef.current;\n }\n }\n\n const error = (selectError ?? snapshot.error) as ExtractErrorType<R> | null;\n\n // ******************\n // Error boundary\n // ******************\n\n if (throwOnError) {\n usedKeys.add(\"error\");\n usedKeys.add(\"isFetching\");\n\n const shouldThrow = typeof throwOnError === \"function\" ? !!error && throwOnError(error) : !!error;\n\n if (shouldThrow && !snapshot.isFetching) {\n store.evictSoon();\n throw error;\n }\n }\n\n // ******************\n // Actions\n // ******************\n\n const actions = useMemo(\n () => ({\n fetchNextPage: () => store.fetchNextPage(),\n fetchPreviousPage: () => store.fetchPreviousPage(),\n refetch: () => store.refetch(),\n reset: () => {\n callbacks.current.onReset?.();\n return store.reset();\n },\n abort: () => store.abort(),\n onSuccess: (callback: (event: any) => void) => {\n callbacks.current.onSuccess = callback;\n },\n onError: (callback: (event: any) => void) => {\n callbacks.current.onError = callback;\n },\n onFinished: (callback: (event: any) => void) => {\n callbacks.current.onFinished = callback;\n },\n onReset: (callback: VoidFunction) => {\n callbacks.current.onReset = callback;\n },\n }),\n [store],\n );\n\n return createTrackedProxy(\n {\n items,\n pages: list.data,\n pageParams: list.pageParams,\n total: list.total,\n hasNextPage: snapshot.hasNextPage,\n hasPreviousPage: snapshot.hasPreviousPage,\n loading: !disabled && snapshot.loading && !isPreviousData,\n isFetching: snapshot.isFetching,\n isRefetching: snapshot.isRefetching,\n isFetchingNextPage: snapshot.isFetchingNextPage,\n isFetchingPreviousPage: snapshot.isFetchingPreviousPage,\n isFetchNextPageError: snapshot.isFetchNextPageError,\n isFetchPreviousPageError: snapshot.isFetchPreviousPageError,\n isPreviousData,\n error,\n status: snapshot.status,\n extra: snapshot.extra,\n success: !selectError && snapshot.success,\n bounce: getBounceData(bounceData),\n ...actions,\n },\n trackedKeys,\n (usedKey) => usedKeys.add(usedKey),\n ) as unknown as UseInfiniteFetchReturnType<R, P, TSelected>;\n};\n","import { useForceUpdate } from \"@better-hooks/lifecycle\";\nimport { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n ExtractAdapterResolvedType,\n RequestInstance,\n ResponseType,\n ExtractResponseType,\n ExtractErrorType,\n RequestSendOptionsType,\n RequestSendType,\n ExtractAdapterType,\n} from \"@hyper-fetch/core\";\nimport { runUserCode, sendRequest } from \"@hyper-fetch/core\";\nimport type { UseTrackedStateType } from \"helpers\";\nimport { useTrackedState, useRequestEvents } from \"helpers\";\nimport type { UseSubmitOptionsType, UseSubmitReturnType } from \"hooks/use-submit\";\nimport { useSubmitDefaultOptions } from \"hooks/use-submit\";\nimport { useProvider } from \"provider\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\n\n/**\n * This hook aims to mutate data on the server. Unlike useFetch, it does not fire automatically -\n * call the returned `submit` function to trigger the request (e.g., on button click).\n * @param request\n * @param options\n * @returns\n */\nexport const useSubmit = <RequestType extends RequestInstance, TSelected = ExtractResponseType<RequestType>>(\n request: RequestType,\n options?: UseSubmitOptionsType<RequestType, TSelected>,\n): UseSubmitReturnType<RequestType, TSelected> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const mergedOptions: UseSubmitOptionsType<RequestType, TSelected> = useMemo(\n () => ({\n ...useSubmitDefaultOptions,\n ...globalConfig.useSubmitConfig,\n ...options,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [globalConfig.useSubmitConfig, JSON.stringify(options), options?.deepCompare],\n );\n const {\n disabled,\n dependencyTracking,\n initialResponse,\n bounce,\n bounceType,\n bounceTime,\n deepCompare,\n structuralSharing,\n } = mergedOptions;\n\n /**\n * Because of the dynamic cacheKey / queryKey signing within the request we need to store it's latest instance\n * so the events got triggered properly and show the latest result without mixing it up\n */\n const { client } = request;\n const { cache, submitDispatcher: dispatcher, loggerManager } = client;\n\n const logger = useRef(loggerManager.initialize(client, \"useSubmit\")).current;\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({\n interval: bounceTime,\n timeout: \"bounceTimeout\" in mergedOptions ? mergedOptions.bounceTimeout : bounceTime,\n });\n const forceUpdate = useForceUpdate();\n // Resolvers of the submit calls waiting for the bounced request\n const bounceResolver = useRef<\n | null\n | ((\n value: ResponseType<\n ExtractResponseType<RequestType>,\n ExtractErrorType<RequestType>,\n ExtractAdapterType<RequestType>\n >,\n ) => void)\n >(null);\n\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n // Bounce state shown by this render\n const isBounceActive = bounceData.active;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n /**\n * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues\n */\n const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<RequestType, TSelected>(\n {\n logger,\n request,\n dispatcher,\n initialResponse,\n deepCompare: deepCompare as boolean,\n dependencyTracking: dependencyTracking as boolean,\n // Read directly from options - functions are not part of the memoized options key\n select: options?.select,\n structuralSharing,\n },\n );\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [callbacks, listeners] = useRequestEvents({\n logger,\n actions,\n request,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners, removeLifecycleListener } = listeners;\n\n // ******************\n // Submitting\n // ******************\n\n /**\n * Response for the submit calls which did not send any request. The submit promise never rejects,\n * so the reason is returned as an error response.\n */\n const getNotSentResponse = (message: string) => {\n const timestamp = Date.now();\n return {\n data: null,\n error: new Error(message),\n status: null,\n success: false,\n extra: request.client.adapter.defaultExtra,\n requestTimestamp: timestamp,\n responseTimestamp: timestamp,\n } as ResponseType<ExtractResponseType<RequestType>, ExtractErrorType<RequestType>, ExtractAdapterType<RequestType>>;\n };\n\n /**\n * Bounced submit calls wait for the request to be triggered. When it will not happen anymore (bounce got reset,\n * call got dropped or the hook unmounted) we have to resolve them - the submit promise can never stay pending.\n */\n const resolveBouncedCalls = (message: string) => {\n const resolvePending = bounceResolver.current;\n bounceResolver.current = null;\n resolvePending?.(getNotSentResponse(message));\n };\n\n const handleSubmit: RequestSendType<RequestType> = (submitOptions?: RequestSendOptionsType<RequestType>) => {\n if (disabled) {\n logger.warning({ title: `Cannot submit request`, type: \"system\", extra: { disabled, submitOptions } });\n return Promise.resolve(getNotSentResponse(\"Cannot submit request. Option 'disabled' is enabled\"));\n }\n\n const { optimistic: submitOptimistic, ...cloneOptions } = submitOptions || {};\n const requestClone = request.clone(cloneOptions as any) as unknown as RequestType;\n // Read directly from options - functions are not part of the memoized options key\n const optimistic = submitOptimistic ?? options?.optimistic;\n\n const triggerRequest = () => {\n addCacheDataListener(requestClone);\n\n const configuration: RequestSendOptionsType<RequestType> = {\n dispatcherType: \"submit\",\n ...(submitOptions as RequestSendOptionsType<RequestType>),\n optimistic,\n onBeforeSent: (data) => {\n // Deduplicated submit joins the request which is already in flight and shares its id.\n // We keep a single set of listeners for it, so the callbacks fire once per response.\n removeLifecycleListener(data.requestId);\n addLifecycleListeners(requestClone, data.requestId, data.mutationContext);\n submitOptions?.onBeforeSent?.(data);\n },\n onResponse: (data) => {\n // This is the final response (retries and waiting for the network are over) and our listeners already\n // handled it. Dispatcher does not announce the removal of every request (e.g. the canceled ones),\n // so we release the listeners here to not leak them.\n removeLifecycleListener(data.requestId);\n submitOptions?.onResponse?.(data);\n },\n };\n\n return sendRequest(requestClone, configuration);\n };\n\n return new Promise<ExtractAdapterResolvedType<RequestType>>((resolve) => {\n const performSubmit = async () => {\n logger.debug({ title: `Submitting request`, type: \"system\", extra: { disabled, submitOptions } });\n if (bounce) {\n const bouncedResolve = bounceResolver.current;\n // We need to keep the resolve of debounced requests to prevent memory leaks - we need to always resolve promise.\n // By default bounce method will prevent function to be triggered, but returned promise will still await to be resolved.\n // This way we can close previous promise, making sure our logic will not stuck in memory.\n bounceResolver.current = (\n value: ResponseType<\n ExtractResponseType<RequestType>,\n ExtractErrorType<RequestType>,\n ExtractAdapterType<RequestType>\n >,\n ) => {\n // Trigger previous awaiting calls to resolve together in bounced batches\n bouncedResolve?.(value);\n resolve(value);\n };\n\n let isTriggered = false;\n\n // Start bounce\n bounceFunction(async () => {\n isTriggered = true;\n // We will always resolve previous calls as we stack the callbacks together until bounce function trigger\n const callback = bounceResolver.current;\n // Clean bounce resolvers to start the new stack\n bounceResolver.current = null;\n\n const value = await triggerRequest();\n callback?.(value);\n });\n\n // Throttle without the trailing timeout drops the calls made during the interval - nothing will trigger them\n if (!isTriggered && !bounceData.active) {\n resolveBouncedCalls(\"Request was not sent. Submit call got dropped by the throttle\");\n }\n\n // Throttle does not notify about the call it holds, so the returned bounce state would stay outdated\n if (bounceData.active !== isBounceActive) {\n forceUpdate();\n }\n } else {\n const value = await triggerRequest();\n resolve(value);\n }\n };\n\n performSubmit();\n });\n };\n\n // ******************\n // Invalidation\n // ******************\n\n const handleRefetch = () => {\n cache.invalidate(request);\n };\n\n // ******************\n // Stable methods\n // ******************\n\n // The returned methods keep their identity between renders (safe to use in the dependency arrays)\n // and always work with the request and options from the latest render\n const latest = useRef({ handleSubmit, handleRefetch, resolveBouncedCalls });\n latest.current = { handleSubmit, handleRefetch, resolveBouncedCalls };\n\n const submit = useCallback(\n ((submitOptions?: RequestSendOptionsType<RequestType>) =>\n (latest.current.handleSubmit as (options?: RequestSendOptionsType<RequestType>) => unknown)(\n submitOptions,\n )) as unknown as RequestSendType<RequestType>,\n [],\n );\n\n const refetch = useCallback(() => latest.current.handleRefetch(), []);\n\n // ******************\n // Bounce\n // ******************\n\n const resetBounce = () => {\n const wasActive = bounceData.active;\n bounceData.reset();\n resolveBouncedCalls(\"Request was not sent. Bounce got reset before triggering the request\");\n // Reset does not notify about the change on its own\n if (wasActive) {\n forceUpdate();\n }\n };\n\n // ******************\n // Misc\n // ******************\n\n const handlers = useMemo(() => {\n /**\n * Callbacks run inside of the request lifecycle. Error thrown by one of them would break it - the request\n * would never finish and it would block the queue. Such error is thrown outside of the lifecycle instead,\n * the same way as the errors of every other callback, listener and plugin.\n */\n const protect = <Args extends unknown[]>(callback: (...args: Args) => void | Promise<void>) => {\n return (...args: Args): void => {\n runUserCode(() => {\n callback(...args);\n });\n };\n };\n\n return {\n onSubmitSuccess: (callback: Parameters<typeof callbacks.onSuccess>[0]) => callbacks.onSuccess(protect(callback)),\n onSubmitError: (callback: Parameters<typeof callbacks.onError>[0]) => callbacks.onError(protect(callback)),\n onSubmitFinished: (callback: Parameters<typeof callbacks.onFinished>[0]) =>\n callbacks.onFinished(protect(callback)),\n onSubmitRequestStart: (callback: Parameters<typeof callbacks.onRequestStart>[0]) =>\n callbacks.onRequestStart(protect(callback)),\n onSubmitResponseStart: (callback: Parameters<typeof callbacks.onResponseStart>[0]) =>\n callbacks.onResponseStart(protect(callback)),\n onSubmitDownloadProgress: (callback: Parameters<typeof callbacks.onDownloadProgress>[0]) =>\n callbacks.onDownloadProgress(protect(callback) as typeof callback),\n onSubmitUploadProgress: (callback: Parameters<typeof callbacks.onUploadProgress>[0]) =>\n callbacks.onUploadProgress(protect(callback) as typeof callback),\n onSubmitOfflineError: (callback: Parameters<typeof callbacks.onOfflineError>[0]) =>\n callbacks.onOfflineError(protect(callback)),\n onSubmitAbort: (callback: Parameters<typeof callbacks.onAbort>[0]) => callbacks.onAbort(protect(callback)),\n };\n }, [callbacks]);\n\n // ******************\n // Lifecycle\n // ******************\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without the cache subscription.\n // When the request changes, we follow the data of the new one.\n useEffect(() => {\n addCacheDataListener(request);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [request.cacheKey, request.queryKey, request.scope]);\n\n // Bounce timers get cleared on unmount, so the waiting submit calls would never get resolved\n useEffect(() => {\n return () => {\n latest.current.resolveBouncedCalls(\"Request was not sent. Hook got unmounted before triggering the request\");\n };\n }, []);\n\n const setSubmitRenderKey = (key: string) => {\n setRenderKey((key === \"submitting\" ? \"loading\" : key) as keyof UseTrackedStateType);\n };\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"submitting\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n submit,\n data: state.data,\n error: state.error,\n submitting: state.loading,\n status: state.status,\n success: state.success,\n extra: state.extra,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n abort: callbacks.abort,\n ...actions,\n ...handlers,\n bounce: { ...getBounceData(bounceData), reset: resetBounce },\n refetch,\n },\n trackedKeys,\n setSubmitRenderKey,\n ) as UseSubmitReturnType<RequestType, TSelected>;\n};\n","import type { RequestInstance, RequiredKeys } from \"@hyper-fetch/core\";\n\nimport type { UseSubmitOptionsType } from \"./use-submit.types\";\n\ntype DefaultOptionsType = RequiredKeys<\n Omit<UseSubmitOptionsType<RequestInstance>, \"initialResponse\" | \"select\" | \"optimistic\">\n> & {\n initialResponse: null;\n};\n\nexport const useSubmitDefaultOptions: DefaultOptionsType = {\n disabled: false,\n dependencyTracking: true,\n initialResponse: null,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n deepCompare: true,\n structuralSharing: true,\n};\n","import type {\n ProgressType,\n RequestInstance,\n ResolvedQueueItemType,\n QueueDataType,\n QueueItemType,\n} from \"@hyper-fetch/core\";\nimport { Request, getRequestDispatcher, scopeKey } from \"@hyper-fetch/core\";\nimport type { UseQueueOptionsType, QueueRequest, UseQueueReturnType } from \"hooks/use-queue\";\nimport { useQueueDefaultOptions } from \"hooks/use-queue\";\nimport { useProvider } from \"provider\";\nimport { useState, useEffect, useCallback } from \"react\";\n\nconst canUpdate = (\n item: Pick<QueueRequest<RequestInstance>, \"success\" | \"failed\" | \"canceled\" | \"removed\" | \"resolved\">,\n) => {\n if (item.success || item.failed) {\n return false;\n }\n return true;\n};\n\nconst getInitialProgress = (): ProgressType => ({\n progress: 0,\n timeLeft: 0,\n sizeLeft: 0,\n total: 0,\n loaded: 0,\n startTimestamp: 0,\n});\n\n/**\n * This hook allows you to monitor and control dispatcher request queues for a given request,\n * including starting, stopping, pausing, and inspecting pending/in-flight items.\n * @param request\n * @param options\n * @returns\n */\nexport const useQueue = <Request extends RequestInstance>(\n request: Request,\n options?: UseQueueOptionsType,\n): UseQueueReturnType<Request> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const { dispatcherType, keepFinishedRequests } = {\n ...useQueueDefaultOptions,\n ...globalConfig.useQueueConfig,\n ...options,\n };\n\n const { abortKey: rawAbortKey, queryKey: rawQueryKey, scope, client } = request;\n const abortKey = scopeKey(rawAbortKey, scope);\n const queryKey = scopeKey(rawQueryKey, scope);\n const { requestManager } = client;\n\n const [dispatcher] = getRequestDispatcher(request, dispatcherType);\n\n // ******************\n // Mapping\n // ******************\n\n const createRequestsArray = useCallback(\n (\n queueElements: ResolvedQueueItemType<Request>[],\n prevRequests: QueueRequest<Request>[] = [],\n ): QueueRequest<Request>[] => {\n const previous = new Map(prevRequests.map((el) => [el.requestId, el]));\n\n // The list mirrors the dispatcher queue - requests we already track keep their local state\n // (progress and result flags) and get the latest queue values (stopped, retries, resolved)\n const current = new Map(\n queueElements.map((req) => {\n const tracked = previous.get(req.requestId);\n const item: QueueRequest<Request> = tracked\n ? { ...tracked, ...req }\n : {\n failed: false,\n canceled: false,\n removed: false,\n success: false,\n ...req,\n downloading: getInitialProgress(),\n uploading: getInitialProgress(),\n stopRequest: () => dispatcher.stopRequest(queryKey, req.requestId),\n startRequest: () => dispatcher.startRequest(queryKey, req.requestId),\n deleteRequest: () => dispatcher.delete(queryKey, req.requestId, abortKey),\n };\n return [req.requestId, item];\n }),\n );\n\n if (!keepFinishedRequests) {\n return [...current.values()];\n }\n\n // Requests that left the queue keep their place, new ones are added at the end\n const kept = prevRequests.map((el) => current.get(el.requestId) || el);\n const added = [...current.values()].filter((el) => !previous.has(el.requestId));\n\n return [...kept, ...added];\n },\n [abortKey, dispatcher, queryKey, keepFinishedRequests],\n );\n\n // ******************\n // State\n // ******************\n\n // Read the queue right away, so the first render already shows its real state\n const [stopped, setStopped] = useState(() => dispatcher.getQueue<Request>(queryKey).stopped);\n const [requests, setRequests] = useState<QueueRequest<Request>[]>(() =>\n createRequestsArray(dispatcher.getQueue<Request>(queryKey).requests),\n );\n\n const mergePayloadType = useCallback((requestId: string, data: Partial<QueueRequest<Request>>) => {\n setRequests((prev) =>\n prev.map((el) => {\n if (el.requestId === requestId && canUpdate(el)) {\n return { ...el, ...data };\n }\n return el;\n }),\n );\n }, []);\n\n const getInitialState = () => {\n const requestQueue = dispatcher.getQueue<Request>(queryKey);\n\n setStopped(requestQueue.stopped);\n setRequests(createRequestsArray(requestQueue.requests));\n };\n\n const resolveQueueItems = useCallback(\n (items: QueueItemType<Request>[]): ResolvedQueueItemType<Request>[] => {\n return items.map((item) => {\n if (item.request instanceof Request) {\n return item as ResolvedQueueItemType<Request>;\n }\n return { ...item, request: client.fromJSON(item.request) as Request };\n });\n },\n [client],\n );\n\n const updateQueueState = useCallback(\n (values: QueueDataType<Request>) => {\n setStopped(values.stopped);\n setRequests((prev) => createRequestsArray(resolveQueueItems(values.requests), prev));\n },\n [createRequestsArray, resolveQueueItems],\n );\n\n // ******************\n // Events\n // ******************\n\n const mountEvents = () => {\n const unmountChange = dispatcher.events.onQueueChangeByKey<Request>(queryKey, updateQueueState);\n const unmountStatus = dispatcher.events.onQueueStatusChangeByKey<Request>(queryKey, updateQueueState);\n\n const unmountResponse = requestManager.events.onResponse(({ requestId, response, details }) => {\n setRequests((prev) =>\n prev.map((el) => {\n if (el.requestId !== requestId) {\n return el;\n }\n if (response.success) {\n return { ...el, success: true };\n }\n // The request is not done yet when it will be sent again - after the retry time,\n // once the queue gets started again or when the network connection is back\n const isRepeated =\n !!details?.willRetry || !!details?.isCanceled || (!!details?.isOffline && !!el.request.offline);\n return isRepeated ? el : { ...el, failed: true };\n }),\n );\n });\n const unmountCanceled = requestManager.events.onAbort(({ requestId }) => {\n setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, canceled: true } : el)));\n });\n // Canceled request can be sent again - for example after starting the stopped queue\n const unmountStarted = requestManager.events.onRequestStart(({ requestId }) => {\n setRequests((prev) =>\n prev.map((el) => (el.requestId === requestId && el.canceled ? { ...el, canceled: false } : el)),\n );\n });\n\n const unmountRemoved = requestManager.events.onRemove(({ requestId }) => {\n setRequests((prev) =>\n prev.map((el) => (el.requestId === requestId && canUpdate(el) ? { ...el, removed: true } : el)),\n );\n });\n\n const unmountDownload = requestManager.events.onDownloadProgress(\n ({ progress, timeLeft, sizeLeft, total, loaded, startTimestamp, requestId }) => {\n mergePayloadType(requestId, { downloading: { progress, timeLeft, sizeLeft, total, loaded, startTimestamp } });\n },\n );\n\n const unmountUpload = requestManager.events.onUploadProgress(\n ({ progress, timeLeft, sizeLeft, total, loaded, startTimestamp, requestId }) => {\n mergePayloadType(requestId, { uploading: { progress, timeLeft, sizeLeft, total, loaded, startTimestamp } });\n },\n );\n\n const unmount = () => {\n unmountStatus();\n unmountChange();\n unmountDownload();\n unmountUpload();\n unmountResponse();\n unmountCanceled();\n unmountStarted();\n unmountRemoved();\n };\n\n return unmount;\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n useEffect(getInitialState, [createRequestsArray, dispatcher, queryKey]);\n\n // The handlers only use state updaters, so there is no need to subscribe again when the state changes\n useEffect(mountEvents, [queryKey, dispatcher.events, requestManager.events, updateQueueState, mergePayloadType]);\n\n return {\n stopped,\n requests,\n dispatcher,\n stop: () => dispatcher.stop(queryKey),\n pause: () => dispatcher.pause(queryKey),\n start: () => dispatcher.start(queryKey),\n };\n};\n","import type { RequiredKeys } from \"@hyper-fetch/core\";\nimport type { UseQueueOptionsType } from \"hooks/use-queue\";\n\nexport const useQueueDefaultOptions: RequiredKeys<UseQueueOptionsType> = {\n dispatcherType: \"auto\",\n keepFinishedRequests: false,\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { ExtractResponseType, RequestInstance } from \"@hyper-fetch/core\";\nimport { getRequestDispatcher } from \"@hyper-fetch/core\";\nimport { useRequestEvents, useTrackedState } from \"helpers\";\nimport type { UseCacheOptionsType, UseCacheReturnType } from \"hooks/use-cache\";\nimport { useCacheDefaultOptions } from \"hooks/use-cache\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\nimport { keyReplacer } from \"utils/key.utils\";\n\n/**\n * Options passed as `undefined` (e.g. forwarded optional props) fall back to the defaults instead of overriding them\n */\nconst mergeOptions = <T extends object>(...sources: (object | undefined)[]): T => {\n const merged: Record<string, unknown> = {};\n sources.forEach((source) => {\n Object.entries(source || {}).forEach(([key, value]) => {\n if (value !== undefined) {\n merged[key] = value;\n }\n });\n });\n return merged as T;\n};\n\n/** Subscribe to cache updates for a given request without triggering network activity. */\nexport const useCache = <T extends RequestInstance, TSelected = ExtractResponseType<T>>(\n request: T,\n options?: UseCacheOptionsType<T, TSelected>,\n): UseCacheReturnType<T, TSelected> => {\n const { cacheKey, client } = request;\n\n const { cache, loggerManager } = client;\n const logger = useRef(loggerManager.initialize(client, \"useCache\")).current;\n const [dispatcher] = getRequestDispatcher(request);\n const updateKey = JSON.stringify(request.toJSON(), keyReplacer);\n\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const { dependencyTracking, initialResponse, deepCompare, structuralSharing } = mergeOptions<\n typeof useCacheDefaultOptions & UseCacheOptionsType<T, TSelected>\n >(useCacheDefaultOptions, globalConfig.useCacheConfig, options);\n\n /**\n * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues\n */\n const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<T, TSelected>({\n logger,\n request,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n // Cache observer shows the data of the given key only - nothing would replace the data kept from the previous key\n keepPreviousData: \"clean\",\n select: options?.select,\n structuralSharing,\n });\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [, listeners] = useRequestEvents({\n logger,\n actions,\n request,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners } = listeners;\n\n const handleMountEvents = () => {\n const unmountDataListener = addCacheDataListener(request);\n const unmountLifecycleListener = addLifecycleListeners(request);\n return () => {\n unmountDataListener();\n unmountLifecycleListener();\n };\n };\n\n useDidUpdate(\n () => {\n return handleMountEvents();\n },\n [updateKey],\n true,\n );\n\n const invalidate = (cacheKeys?: string | RegExp | RequestInstance | (string | RegExp | RequestInstance)[]) => {\n cache.invalidate(cacheKeys ?? cacheKey);\n };\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"loading\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n error: state.error,\n loading: state.loading,\n status: state.status,\n success: state.success,\n extra: state.extra,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n ...actions,\n invalidate,\n },\n trackedKeys,\n setRenderKey,\n ) as UseCacheReturnType<T, TSelected>;\n};\n","export const useCacheDefaultOptions = {\n dependencyTracking: true,\n initialResponse: null,\n deepCompare: true,\n structuralSharing: true,\n};\n","import type { RequestInstance, ExtractAdapterExtraType, ExtractAdapterType, ExtractErrorType } from \"@hyper-fetch/core\";\nimport { scopeKey } from \"@hyper-fetch/core\";\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\n\nimport type { UseStreamOptionsType, UseStreamReturnType } from \"./use-stream.types\";\n\ntype StreamState<T extends RequestInstance> = {\n text: string;\n chunks: Uint8Array[];\n streaming: boolean;\n done: boolean;\n error: ExtractErrorType<T> | null;\n extra: ExtractAdapterExtraType<ExtractAdapterType<T>> | null;\n status: number | null;\n};\n\nconst getInitialState = <T extends RequestInstance>(): StreamState<T> => ({\n text: \"\",\n chunks: [],\n streaming: false,\n done: false,\n error: null,\n extra: null,\n status: null,\n});\n\n/**\n * Hook for consuming streaming responses chunk-by-chunk.\n * Works with any request that uses the fetch adapter's `streaming: true` option.\n *\n * Provides both accumulated `text` (for LLM/SSE use cases) and raw `chunks`\n * (for binary streaming / file downloads).\n */\nexport const useStream = <T extends RequestInstance>(\n request: T,\n options?: UseStreamOptionsType,\n): UseStreamReturnType<T> => {\n const { autoStart = false } = options || {};\n\n const state = useRef<StreamState<T>>(getInitialState<T>());\n const abortRef = useRef<(() => void) | null>(null);\n const startedRef = useRef(false);\n\n // useSyncExternalStore for re-renders\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n const consumeStream = async (stream: ReadableStream<Uint8Array>) => {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {break;}\n\n state.current.chunks = [...state.current.chunks, value];\n state.current.text += decoder.decode(value, { stream: true });\n emitChange();\n }\n\n state.current.streaming = false;\n state.current.done = true;\n emitChange();\n } catch (error) {\n state.current.streaming = false;\n state.current.error = error as ExtractErrorType<T>;\n emitChange();\n }\n };\n\n const start = useCallback(() => {\n if (state.current.streaming) {return;}\n\n state.current = {\n ...getInitialState<T>(),\n streaming: true,\n };\n emitChange();\n\n const streamingRequest = request.setOptions({ streaming: true } as any);\n\n streamingRequest.send().then((response) => {\n const { data, error, status, extra } = response;\n\n state.current.status = status as number | null;\n state.current.extra = extra as ExtractAdapterExtraType<ExtractAdapterType<T>> | null;\n\n if (error) {\n state.current.streaming = false;\n state.current.error = error;\n emitChange();\n return;\n }\n\n if (data && typeof (data as any).getReader === \"function\") {\n consumeStream(data as unknown as ReadableStream<Uint8Array>);\n } else {\n state.current.streaming = false;\n state.current.text = typeof data === \"string\" ? data : JSON.stringify(data);\n state.current.done = true;\n emitChange();\n }\n });\n\n abortRef.current = () => {\n request.client.requestManager.abortByKey(scopeKey(request.abortKey, request.scope));\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [request]);\n\n const abort = useCallback(() => {\n abortRef.current?.();\n state.current.streaming = false;\n emitChange();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const reset = useCallback(() => {\n abortRef.current?.();\n state.current = getInitialState<T>();\n startedRef.current = false;\n emitChange();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (autoStart && !startedRef.current) {\n startedRef.current = true;\n start();\n }\n }, [autoStart, start]);\n\n return {\n text: state.current.text,\n chunks: state.current.chunks,\n streaming: state.current.streaming,\n done: state.current.done,\n error: state.current.error,\n extra: state.current.extra,\n status: state.current.status,\n start,\n abort,\n reset,\n };\n};\n","import { useDidUpdate, useWillUnmount } from \"@better-hooks/lifecycle\";\nimport { replaceEqualDeep, stringifyKey } from \"@hyper-fetch/core\";\nimport type {\n ExtractListenerDeliveredType,\n ListenerEndType,\n ListenerInstance,\n ListenerLifecycleOptionsType,\n ListenerRequiresPayload,\n} from \"@hyper-fetch/sockets\";\nimport { getDeliveryKey } from \"@hyper-fetch/sockets\";\nimport { useSocketState } from \"helpers\";\nimport type { ListenerStatusType, UseListenerOptionsType } from \"hooks/use-listener\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\n\n/** A listener whose subscription payload is required has to get it with `setPayload()` before it is passed */\ntype ListenerWithPayloadType<ListenerType extends ListenerInstance> =\n ListenerRequiresPayload<ListenerType> extends true\n ? ListenerType & { \"Set the payload with setPayload() before passing the listener\": never }\n : ListenerType;\n\n/**\n * Subscribe to incoming socket messages on a given listener topic with tracked connection state and callbacks.\n * Changing the topic params, payload, options, delivery or socket of the listener starts a new subscription.\n */\nexport const useListener = <\n ListenerType extends ListenerInstance,\n TSelected = ExtractListenerDeliveredType<ListenerType>,\n>(\n listener: ListenerWithPayloadType<ListenerType>,\n options?: UseListenerOptionsType<ExtractListenerDeliveredType<ListenerType>, TSelected>,\n) => {\n const { config: globalConfig } = useProvider();\n const { dependencyTracking = true, structuralSharing = true } = { ...globalConfig.useListener, ...options };\n const select = options?.select;\n const [state, actions, callbacks, { setRenderKey, getState, rerender, setExtendedState }] = useSocketState<\n TSelected,\n ListenerType[\"socket\"],\n { status: ListenerStatusType; error: Error | null }\n >(listener.socket, { dependencyTracking, extendedState: { status: \"idle\", error: null } });\n const removeListenerRef = useRef<ReturnType<typeof listener.listen> | null>(null);\n\n /**\n * Selection\n */\n\n const selectRef = useRef(select);\n selectRef.current = select;\n const appliedSelect = useRef(select);\n // Last message data before applying the selector - allows to re-run it when the selector changes\n const rawData = useRef<{ data: ExtractListenerDeliveredType<ListenerType> } | null>(null);\n const selectError = useRef<{ error: unknown } | null>(null);\n\n const selectData = (data: ExtractListenerDeliveredType<ListenerType>): TSelected => {\n if (!selectRef.current) {\n return data as unknown as TSelected;\n }\n const selected = selectRef.current(data);\n return structuralSharing ? replaceEqualDeep(getState().data, selected) : selected;\n };\n\n // Selector failed while processing a message - surface it to the closest error boundary\n if (selectError.current) {\n const { error } = selectError.current;\n selectError.current = null;\n throw error;\n }\n\n // Selector changed (e.g. it closes over a new prop) - re-run it against the last message\n if (appliedSelect.current !== select) {\n appliedSelect.current = select;\n if (rawData.current) {\n state.data = selectData(rawData.current.data);\n }\n }\n\n /**\n * Callbacks\n */\n\n const onEventCallback = useRef<\n null | ((response: { data: ExtractListenerDeliveredType<ListenerType>; extra: Record<string, any> }) => void)\n >(null);\n const onStartCallback = useRef<null | ((data: { topic: string }) => void)>(null);\n const onEndCallback = useRef<null | ((data: ListenerEndType) => void)>(null);\n\n /**\n * Actions\n */\n\n const stopListener = () => {\n removeListenerRef.current?.();\n };\n\n const listen = () => {\n stopListener();\n // Set before subscribing - adapters without confirmation start the subscription synchronously\n setExtendedState({ status: \"starting\", error: null });\n const lifecycle = {\n onStart: (data: { topic: string }) => {\n setExtendedState({ status: \"listening\" });\n onStartCallback.current?.(data);\n },\n onEnd: (data: ListenerEndType) => {\n removeListenerRef.current = null;\n setExtendedState({ status: data.error ? \"failed\" : \"ended\", error: data.error });\n onEndCallback.current?.(data);\n },\n };\n // The payload is set on the listener, so only the lifecycle callbacks are passed\n const listenWithLifecycle = listener.listen as (\n callback: Parameters<typeof listener.listen>[0],\n options: ListenerLifecycleOptionsType,\n ) => VoidFunction;\n removeListenerRef.current = listenWithLifecycle(({ data, extra }) => {\n onEventCallback.current?.({ data, extra });\n rawData.current = { data };\n appliedSelect.current = selectRef.current;\n\n let selected: TSelected;\n try {\n selected = selectData(data);\n } catch (error) {\n // Never throw inside of the socket events - rethrow it on render instead\n selectError.current = { error };\n rerender();\n return;\n }\n\n // With a selector, data is updated only when the selected value changed\n if (!selectRef.current || !Object.is(selected, getState().data)) {\n actions.setData(selected);\n }\n actions.setExtra(extra);\n actions.setTimestamp(Date.now());\n }, lifecycle);\n };\n\n const additionalCallbacks = {\n onEvent: (callback: NonNullable<typeof onEventCallback.current>) => {\n onEventCallback.current = callback;\n },\n /** The subscription started - with tRPC and oRPC when the server confirmed it, also after a reconnect */\n onStart: (callback: NonNullable<typeof onStartCallback.current>) => {\n onStartCallback.current = callback;\n },\n /** The server ended the subscription, with `error` when it failed */\n onEnd: (callback: NonNullable<typeof onEndCallback.current>) => {\n onEndCallback.current = callback;\n },\n };\n\n /**\n * Lifecycle\n */\n\n useDidUpdate(\n () => {\n listen();\n },\n // Topic already contains resolved params. Delivery presets compare by value, custom strategies by identity.\n // The socket is a dependency too - the same topic on another socket is a different subscription, the same\n // goes for the payload - the same procedure with another input is another subscription.\n [\n listener.socket,\n listener.topic,\n stringifyKey(listener.payload),\n JSON.stringify(listener.options),\n getDeliveryKey(listener.delivery),\n ],\n true,\n );\n\n useWillUnmount(() => {\n stopListener();\n });\n\n const trackedKeys = [\"data\", \"extra\", \"connected\", \"connecting\", \"timestamp\", \"status\", \"error\"] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n extra: state.extra,\n connected: state.connected,\n connecting: state.connecting,\n timestamp: state.timestamp,\n status: state.status,\n error: state.error,\n ...actions,\n ...callbacks,\n ...additionalCallbacks,\n listen,\n },\n trackedKeys,\n setRenderKey,\n );\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { EmitterInstance, EmitterCallbackErrorType, EmitType } from \"@hyper-fetch/sockets\";\nimport { useSocketState } from \"helpers\";\nimport type { UseEmitterOptionsType } from \"hooks/use-emitter\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\n\n/** Send messages through a socket emitter with tracked connection state and lifecycle callbacks. */\nexport const useEmitter = <EmitterType extends EmitterInstance>(\n emitter: EmitterType,\n options?: UseEmitterOptionsType,\n) => {\n const { config: globalConfig } = useProvider();\n const { dependencyTracking = true } = { ...globalConfig.useEmitter, ...options };\n\n const [state, actions, callbacks, { setRenderKey }] = useSocketState(emitter.socket, { dependencyTracking });\n\n /**\n * Callbacks\n */\n const onEventStartCallback = useRef<null | ((emitter: EmitterType) => void)>(null);\n const onEventErrorCallback = useRef<null | EmitterCallbackErrorType>(null);\n\n useDidUpdate(\n () => {\n const onEventStart = () => {\n return emitter.socket.events.onEmitterStartEventByTopic(emitter, () => {\n onEventStartCallback.current?.(emitter);\n });\n };\n\n const onEventError = () => {\n return emitter.socket.events.onEmitterErrorByTopic(emitter, ({ error }) => {\n onEventErrorCallback.current?.({ error });\n });\n };\n\n const unmountEventStart = onEventStart();\n const unmountEventError = onEventError();\n\n return () => {\n unmountEventStart();\n unmountEventError();\n };\n },\n [emitter.topic, onEventStartCallback.current, onEventErrorCallback.current],\n true,\n );\n\n /**\n * Emitter\n */\n\n const emit: EmitType<EmitterType> = (emitOptions: Parameters<EmitType<EmitterType>>[0]) => {\n return emitter.emit(emitOptions as any);\n };\n\n const onEmit = (callback: (emitter: EmitterType) => void) => {\n onEventStartCallback.current = callback;\n };\n\n const onEmitError = (callback: EmitterCallbackErrorType) => {\n onEventErrorCallback.current = callback;\n };\n\n const trackedKeys = [\"connected\", \"connecting\"] as const;\n\n return createTrackedProxy(\n {\n connected: state.connected,\n connecting: state.connecting,\n ...actions,\n ...callbacks,\n onEmit,\n onEmitError,\n emit,\n },\n trackedKeys,\n setRenderKey,\n );\n};\n","import type { ClientInstance } from \"@hyper-fetch/core\";\nimport type { UseAppManagerReturnType } from \"hooks/use-app-manager\";\nimport { useEffect, useState } from \"react\";\n\n/** Track the application's online/offline and focus/blur state through the client's AppManager. */\nexport const useAppManager = <Client extends ClientInstance>(client: Client): UseAppManagerReturnType => {\n const [online, setIsOnline] = useState(client.appManager.isOnline);\n const [focused, setIsFocused] = useState(client.appManager.isFocused);\n\n const mountEvents = () => {\n // Catch up with anything that happened between the render and the subscription\n setIsOnline(client.appManager.isOnline);\n setIsFocused(client.appManager.isFocused);\n\n const unmountIsOnline = client.appManager.events.onOnline(() => setIsOnline(true));\n const unmountIsOffline = client.appManager.events.onOffline(() => setIsOnline(false));\n const unmountIsFocus = client.appManager.events.onFocus(() => setIsFocused(true));\n const unmountIsBlur = client.appManager.events.onBlur(() => setIsFocused(false));\n\n return () => {\n unmountIsOnline();\n unmountIsOffline();\n unmountIsFocus();\n unmountIsBlur();\n };\n };\n\n const setOnline = (isOnline: boolean) => {\n client.appManager.setOnline(isOnline);\n };\n\n const setFocused = (isFocused: boolean) => {\n client.appManager.setFocused(isFocused);\n };\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without any subscriptions\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(mountEvents, [client]);\n\n return { isOnline: online, isFocused: focused, setOnline, setFocused };\n};\n","import type { AdapterInstance, ClientInstance, Dispatcher } from \"@hyper-fetch/core\";\nimport type { UseIsFetchingOptionsType } from \"hooks/use-is-fetching\";\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\n\nconst useRunningRequestsCount = (\n dispatcher: Dispatcher<AdapterInstance>,\n options?: UseIsFetchingOptionsType,\n): number => {\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const subscribe = useCallback(\n (listener: () => void) => dispatcher.events.onRunningRequestsChange(listener),\n [dispatcher],\n );\n\n const getCount = () => {\n const { queryKey, predicate } = optionsRef.current || {};\n return dispatcher.getAllRunningRequests().filter(({ request }) => {\n if (typeof queryKey === \"string\" && request.queryKey !== queryKey) {\n return false;\n }\n if (queryKey instanceof RegExp && !queryKey.test(request.queryKey)) {\n return false;\n }\n return !predicate || predicate(request);\n }).length;\n };\n\n return useSyncExternalStore(subscribe, getCount, getCount);\n};\n\n/**\n * Count of the currently running fetch requests (useFetch, useCache and fetch dispatcher). Useful for global loading indicators.\n * @param client Client instance\n * @param options Filters for the counted requests\n * @returns number of running requests\n */\nexport const useIsFetching = (client: ClientInstance, options?: UseIsFetchingOptionsType): number => {\n return useRunningRequestsCount(client.fetchDispatcher, options);\n};\n\n/**\n * Count of the currently running submit requests (useSubmit and submit dispatcher). Useful for global saving indicators.\n * @param client Client instance\n * @param options Filters for the counted requests\n * @returns number of running requests\n */\nexport const useIsSubmitting = (client: ClientInstance, options?: U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