clear-react-router 2.4.9 → 2.5.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 CHANGED
@@ -33,8 +33,8 @@ It provides first-class support for:
33
33
  - **Programmatic Redirects** - Redirect from beforeLoad hook
34
34
  - **Cache invalidation** - Manual route invalidation
35
35
  - **Bounded Cache** - Automatically evicts least recently used entries once `maxCacheSize` is reached, keeping memory usage predictable in long sessions
36
- - **Cache inspection** - Opt into a live, read-only snapshot of cached loader entries with `logged` and `useCacheSnapshot()`
37
- - **Prefetching** - Preload data on hover for instant navigation
36
+ - **Cache inspection** - Opt into a live, read-only snapshot of cached loader entries with `enableCacheSnapshot` and `useCacheSnapshot()`
37
+ - **Prefetching** - Preload data on hover; prefetched entries stay fresh for 30 seconds before the first navigation
38
38
  - **Lazy Loading** - Code-split your routes with dynamic imports for optimal performance
39
39
  - **Scroll Restoration** — Automatically saves and restores scroll position when navigating back to a page (preserves user's scroll position)
40
40
  - **Optimistic navigation** — Instantly renders stale cached data while fresh data is loaded in the background.
@@ -66,7 +66,6 @@ Netlify (`public/_redirects`):
66
66
  |------|------|---------|-------------|
67
67
  | `routes` | `RouteItem[]` | required | Array of route configurations |
68
68
  | `maxCacheSize` | `number \| undefined` | 60 for mobile, 150 for desktop | Maximum number of cached loader entries. Once the limit is reached, the least recently used entries are evicted |
69
- | `logged` | `boolean` | `false` | Enables cache snapshot tracking for [`useCacheSnapshot()`](#usecachesnapshot). Off by default: no snapshot is built and the hook returns an empty list |
70
69
  | `isAnimated` | `boolean \| undefined` | `false` | Enable smooth page fade transitions |
71
70
  | `animationDuration` | `number \| undefined` | `optional` | Animation duration in milliseconds (browser default is used if not set) |
72
71
  | `context` | `object` | `{}` | Initial context (user, theme, etc.) |
@@ -75,7 +74,7 @@ Netlify (`public/_redirects`):
75
74
  | `defaultLoaderFallback` | `ReactElement \| () => ReactElement` | `optional` | Default loading fallback for every route loader |
76
75
  | `defaultErrorElement` | `ReactElement \| () => ReactElement` | `optional` | Default error fallback for every route |
77
76
  | `defaultRetry` | `number \| { count: number; delay: number }` | `optional` | Default cache revalidation retry policy for all routes |
78
- | `defaultStaleTime` | `number` | `optional` | Default time in milliseconds before cached loader data is considered stale |
77
+ | `defaultStaleTime` | `number` | `0` | Default time in milliseconds before cached loader data is considered stale. When unset (or `0`), data is stale immediately and navigation revalidates it |
79
78
  | `defaultBeforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
80
79
  | `defaultAfterLoad` | `({ params, context, searchParams }) => Promise<void>` | `undefined` | Runs after every successful navigation. Useful for analytics, page tracking, or other global side effects. |
81
80
  | `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
@@ -83,6 +82,7 @@ Netlify (`public/_redirects`):
83
82
  | `defaultScrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | `auto` | Default scroll restoration behavior |
84
83
  | `revalidateOnFocus` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser tab regains focus |
85
84
  | `revalidateOnReconnect` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser regains an internet connection |
85
+ | `enableCacheSnapshot` | `boolean` | `false` | Enables cache snapshot tracking for [`useCacheSnapshot()`](#usecachesnapshot). Off by default: no snapshot is built and the hook returns an empty list |
86
86
 
87
87
  > **Note:** Global lifecycle hooks wrap every route navigation. The global `defaultBeforeLoad` runs **before** the route-specific beforeLoad, while the global `defaultAfterLoad` runs **after** the route-specific afterLoad.
88
88
 
@@ -106,7 +106,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
106
106
  | `retry` | `number \| { count: number; delay: number }` | Overrides the global cache revalidation retry policy for this route |
107
107
  | `optimistic` | `boolean \| undefined` | Instant navigation using stale data while fresh data is loaded in the background |
108
108
  | `errorElement` | `ReactElement \| () => ReactElement \| LazyComponent` | Error fallback for the route. Overrides the global `Router.defaultErrorElement` |
109
- | `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, cached data never expires |
109
+ | `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, data is stale immediately and navigation revalidates it. Use `Infinity` to never consider it stale |
110
110
  | `gcTime` | `number \| undefined` | How long, in milliseconds, an unused cache entry is kept in memory after you navigate away, before it's garbage-collected |
111
111
  | `actions` | `({ params, context, searchParams, setContext, location }) => Record<string, (data: Record<string, unknown>) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. |
112
112
  | `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active. Each tick refetches unconditionally, ignoring `staleTime` |
@@ -250,6 +250,8 @@ When using a custom element via `as`, these attributes arrive in `props` togethe
250
250
  | `'viewport'` | Prefetches when the link enters the viewport (using Intersection Observer) |
251
251
  | `'none'` | No prefetching |
252
252
 
253
+ > A prefetched entry is considered fresh for 30 seconds. The first navigation within that window reuses it without running the loader; after that, the route's normal `staleTime` applies (by default `0`, so the next revisit revalidates). A longer route `staleTime` is never shortened by prefetching.
254
+
253
255
  ### Custom elements via `as`
254
256
 
255
257
  When using `as` to render a custom component instead of the default `<a>`, your component **must spread all received props onto the underlying host element** — including `ref`. If any prop is dropped, the corresponding feature silently stops working (no error is thrown):
@@ -540,7 +542,7 @@ const routes = createRouter([
540
542
 
541
543
  Defines route-specific actions for handling data mutations such as creating, updating, or deleting resources.
542
544
 
543
- Actions are available through the `useSubmitAction` and `useAction` hooks. After a successful action, the current route is automatically invalidated, causing `loader` to run again in the background.
545
+ Actions are available through the `useSubmitAction` and `useAction` hooks. After a successful action, the route where the action was triggered is automatically invalidated, causing `loader` to run again in the background.
544
546
 
545
547
  ```tsx
546
548
  actions?: ({ params, context, searchParams, setContext, location }) => ({
@@ -644,7 +646,7 @@ const handleClick = async () => await save({ data: 'Hello world!' });
644
646
  <button onClick={handleClick}>Save</button>
645
647
  ```
646
648
 
647
- `useAction` automatically invalidates the current route after a successful action, causing `loader` to run again in the background.
649
+ `useAction` automatically invalidates the route where the action was triggered after a successful action, causing `loader` to run again in the background. This remains the same route even if the user navigates away while the action is in flight.
648
650
 
649
651
  This hook is useful when the mutation is triggered programmatically, such as from dialogs, context menus, drag-and-drop interactions, keyboard shortcuts, or custom UI components.
650
652
 
@@ -825,7 +827,7 @@ beforeLoad: async ({ location, redirect }) => {
825
827
 
826
828
  ### `useLoaderState<T>()`
827
829
 
828
- Returns the cached data loaded by the current route's `loader`, along with any errors from `loader` or `beforeLoad`. Data is automatically cached and reused when navigating back to the same route.
830
+ Returns the cached data loaded by the current route's `loader`, along with any errors from `loader` or `beforeLoad`. Data is cached, but whether a revisit reuses it depends on `staleTime`: by default cached data is stale immediately and the loader runs again.
829
831
 
830
832
  **Returns:**
831
833
 
@@ -842,8 +844,7 @@ const UserProfile = () => {
842
844
 
843
845
  ### Caching behavior:
844
846
 
845
- - The loader result is cached and reused when navigating back to the same route (e.g., from /user/123 back to /user/456 it will be a new request because different params, but from /user/456 to /user/456 — cache hit).
846
- - Use `staleTime` in route config to control how long cache is considered fresh:
847
+ - The loader result is cached. Without `staleTime` (and without `defaultStaleTime`), the entry is stale immediately, so navigating back to the same route runs the loader again. Set `staleTime` to reuse data within a time window:
847
848
 
848
849
  ```tsx
849
850
  {
@@ -853,6 +854,8 @@ const UserProfile = () => {
853
854
  }
854
855
  ```
855
856
 
857
+ - Use `staleTime: Infinity` when data should stay fresh until it is explicitly invalidated, garbage-collected or evicted.
858
+
856
859
  - The cache is bounded by `maxCacheSize` — once the limit is reached, the least recently used entry is evicted to make room for a new one, regardless of whether it's still fresh. This caps memory usage for apps with many high-cardinality dynamic routes (e.g. `/product/:id` across a large catalog). It defaults to a device-aware value (lower on mobile) and can be overridden on the `Router`:
857
860
 
858
861
  ```tsx
@@ -863,7 +866,7 @@ const UserProfile = () => {
863
866
  ### `useCacheSnapshot()`
864
867
 
865
868
  Returns a read-only snapshot of the loader cache — intended for devtools panels, debugging, and cache
866
- monitoring. Requires `<Router logged>`; while the flag is off the snapshot is empty and nothing is built.
869
+ monitoring. Requires `<Router enableCacheSnapshot>`; while the flag is off the snapshot is empty and nothing is built.
867
870
 
868
871
  ```tsx
869
872
  import { useCacheSnapshot } from 'clear-react-router';
@@ -882,7 +885,7 @@ const CachePanel = () => {
882
885
  );
883
886
  };
884
887
 
885
- <Router routes={routes} logged />
888
+ <Router routes={routes} enableCacheSnapshot />
886
889
  ```
887
890
 
888
891
  ```ts
@@ -892,11 +895,11 @@ type CacheSnapshotEntry = {
892
895
  path: string; // pathname + search
893
896
  data: unknown; // loader result; undefined while the first load is in flight
894
897
  timestamp: number; // when the entry was written (ms since epoch)
895
- staleTime: number | undefined; // copy of the route's staleTime
898
+ staleTime: number | undefined; // effective staleTime: route value, default, or 0 when neither is set
896
899
  reason?: CacheReason; // what wrote the entry last
897
900
  gcExpiresAt: number | undefined; // GC deadline, if a GC timer is pending
898
901
  gcDuration: number | undefined; // the route's gcTime, for progress display
899
- isLoading: boolean; // a loader for this path is currently running
902
+ isLoading: boolean; // a loader for this path is currently running
900
903
  };
901
904
 
902
905
  type CacheSnapshot = CacheSnapshotEntry[];
@@ -907,7 +910,7 @@ Notes:
907
910
  - The snapshot is a projection, not a second cache — changing it does nothing.
908
911
  - Entries appear for in-flight first loads too (`data: undefined`, `isLoading: true`), so a devtool never misses a request.
909
912
  - Mounting the hook refreshes the snapshot, so a panel opened after navigation still sees existing entries.
910
- - `logged` is process-wide (the router is a singleton): if several `<Router>`s render with different values, the last rendered one wins. Enable it only when a consumer is actually mounted.
913
+ - `enableCacheSnapshot` is process-wide (the router is a singleton): if several `<Router>`s render with different values, the last rendered one wins. Enable it only when a consumer is actually mounted.
911
914
 
912
915
  ### `useInvalidate()`
913
916
 
@@ -1,3 +1,3 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import { RouterProps } from '../types';
3
- export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, logged, }: RouterProps) => string | number | bigint | boolean | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null | undefined;
3
+ export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, enableCacheSnapshot, }: RouterProps) => string | number | bigint | boolean | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null | undefined;
@@ -13,7 +13,7 @@ declare class RouterConfig {
13
13
  defaultStaleTime?: RouterProps['defaultStaleTime'];
14
14
  defaultMinLoaderDuration?: RouterProps['defaultMinLoaderDuration'];
15
15
  defaultScrollRestorationBehavior: RouterProps['defaultScrollRestorationBehavior'];
16
- logged: boolean;
16
+ enableCacheSnapshot: boolean;
17
17
  configure(config: Partial<RouterConfig>): void;
18
18
  }
19
19
  export declare const routerConfig: RouterConfig;
@@ -1,3 +1,2 @@
1
1
  import type { CacheSnapshot } from '../types';
2
- /** Requires `<Router logged>` — otherwise the snapshot stays empty. */
3
2
  export declare const useCacheSnapshot: () => CacheSnapshot;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Suspense, lazy as lazy$1, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
2
  import { jsx } from "react/jsx-runtime";
3
- // create.ts
3
+ //#region create.ts
4
4
  var create = (initialState) => {
5
5
  let state = initialState;
6
6
  const subscribers = /* @__PURE__ */ new Set();
@@ -26,7 +26,8 @@ var create = (initialState) => {
26
26
  var useGlobalState = ({ subscribe, getState, setState }, synchronizer) => {
27
27
  return [synchronizer(subscribe, getState), setState];
28
28
  };
29
- // utils/commitState.ts
29
+ //#endregion
30
+ //#region utils/commitState.ts
30
31
  var createCommitState = ({ routeDataState, blockerState }) => ({ routeItem, loaderStateValue, location }) => {
31
32
  const isError = loaderStateValue.loaderError || loaderStateValue.beforeLoadError;
32
33
  routeDataState.setState({
@@ -39,11 +40,13 @@ var createCommitState = ({ routeDataState, blockerState }) => ({ routeItem, load
39
40
  if ((location.search ? `${location.pathname}${location.search}` : location.pathname) === window.location.pathname + window.location.search) return;
40
41
  history.pushState(location.state ?? null, "", `${location.pathname}${location.search}`);
41
42
  };
42
- // constants.ts
43
+ //#endregion
44
+ //#region constants.ts
43
45
  var EMPTY_LOADER_STATE = {};
44
46
  var WINDOW_TOP = "__window_top__";
45
47
  var WINDOW_LEFT = "__window_left__";
46
- // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
48
+ //#endregion
49
+ //#region \0@oxc-project+runtime@0.132.0/helpers/typeof.js
47
50
  function _typeof(o) {
48
51
  "@babel/helpers - typeof";
49
52
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -52,7 +55,8 @@ function _typeof(o) {
52
55
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
53
56
  }, _typeof(o);
54
57
  }
55
- // \0@oxc-project+runtime@0.155.0/helpers/esm/toPrimitive.js
58
+ //#endregion
59
+ //#region \0@oxc-project+runtime@0.132.0/helpers/toPrimitive.js
56
60
  function toPrimitive(t, r) {
57
61
  if ("object" != _typeof(t) || !t) return t;
58
62
  var e = t[Symbol.toPrimitive];
@@ -63,12 +67,14 @@ function toPrimitive(t, r) {
63
67
  }
64
68
  return ("string" === r ? String : Number)(t);
65
69
  }
66
- // \0@oxc-project+runtime@0.155.0/helpers/esm/toPropertyKey.js
70
+ //#endregion
71
+ //#region \0@oxc-project+runtime@0.132.0/helpers/toPropertyKey.js
67
72
  function toPropertyKey(t) {
68
73
  var i = toPrimitive(t, "string");
69
74
  return "symbol" == _typeof(i) ? i : i + "";
70
75
  }
71
- // \0@oxc-project+runtime@0.155.0/helpers/esm/defineProperty.js
76
+ //#endregion
77
+ //#region \0@oxc-project+runtime@0.132.0/helpers/defineProperty.js
72
78
  function _defineProperty(e, r, t) {
73
79
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
74
80
  value: t,
@@ -77,7 +83,8 @@ function _defineProperty(e, r, t) {
77
83
  writable: !0
78
84
  }) : e[r] = t, e;
79
85
  }
80
- // config/routerConfig.ts
86
+ //#endregion
87
+ //#region config/routerConfig.ts
81
88
  var RouterConfig = class {
82
89
  constructor() {
83
90
  _defineProperty(this, "routes", []);
@@ -93,14 +100,15 @@ var RouterConfig = class {
93
100
  _defineProperty(this, "defaultStaleTime", void 0);
94
101
  _defineProperty(this, "defaultMinLoaderDuration", void 0);
95
102
  _defineProperty(this, "defaultScrollRestorationBehavior", void 0);
96
- _defineProperty(this, "logged", false);
103
+ _defineProperty(this, "enableCacheSnapshot", false);
97
104
  }
98
105
  configure(config) {
99
106
  Object.assign(this, config);
100
107
  }
101
108
  };
102
109
  var routerConfig = new RouterConfig();
103
- // utils/commitNavigation.ts
110
+ //#endregion
111
+ //#region utils/commitNavigation.ts
104
112
  var commitNavigation = (callback, isCommited) => {
105
113
  if (!routerConfig.isAnimated || isCommited) return callback();
106
114
  try {
@@ -111,15 +119,17 @@ var commitNavigation = (callback, isCommited) => {
111
119
  callback();
112
120
  }
113
121
  };
114
- // utils/isCacheItemFresh.ts
122
+ //#endregion
123
+ //#region utils/isCacheItemFresh.ts
115
124
  var createIsCacheItemFresh = (loaderMap) => (path) => {
116
125
  const item = loaderMap.get(path);
117
126
  if (item === void 0) return false;
118
- const resolvedStaleTime = item.staleTime ?? routerConfig.defaultStaleTime;
119
- if (resolvedStaleTime === void 0) return true;
127
+ const resolvedStaleTime = item.staleTime ?? routerConfig.defaultStaleTime ?? 0;
128
+ if (resolvedStaleTime <= 0) return false;
120
129
  return Date.now() - item.timestamp <= resolvedStaleTime;
121
130
  };
122
- // utils/utils.ts
131
+ //#endregion
132
+ //#region utils/utils.ts
123
133
  var getParams = (location, routeItem) => {
124
134
  if (!routeItem) return {};
125
135
  const pathnameSegments = location.pathname.split("/");
@@ -196,7 +206,8 @@ var findRoute = (pathname, includeAll) => {
196
206
  if (includeAll) return routerConfig.routes.find((el) => el.path === "*" || comparePaths(el, pathname));
197
207
  return routerConfig.routes.find((el) => comparePaths(el, pathname));
198
208
  };
199
- // runtime/navigate.ts
209
+ //#endregion
210
+ //#region runtime/navigate.ts
200
211
  var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
201
212
  let navigationSeq = 0;
202
213
  let interval = 0;
@@ -359,12 +370,13 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
359
370
  if (defaultAfterLoad) await defaultAfterLoad(args);
360
371
  };
361
372
  const checkBlocked = (nextLocation) => {
362
- if (blockerState.getState() === "charged") {
373
+ const currentState = blockerState.getState();
374
+ if (currentState === "charged") {
363
375
  blockerState.setState("blocked");
364
376
  blockedTargetState.setState(nextLocation);
365
377
  return true;
366
378
  }
367
- return false;
379
+ return currentState === "blocked";
368
380
  };
369
381
  const clearCurrentGcTimeout = (routeItem, location) => {
370
382
  const path = `${location.pathname}${location.search}`;
@@ -413,14 +425,16 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
413
425
  };
414
426
  return navigate;
415
427
  };
416
- // runtime/invalidate.ts
428
+ //#endregion
429
+ //#region runtime/invalidate.ts
417
430
  var separatePathname = (text) => text.split("?")[0];
418
- var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache, syncCacheSnapshot) => {
431
+ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalidateCache, syncCacheSnapshot) => {
419
432
  const invalidatePath = async (routeItem, pathname, options) => {
420
433
  const routePathname = routeDataState.getState().location.pathname;
421
434
  if (!options?.staleOnly) {
422
435
  loaderMap.delete(pathname);
423
436
  syncCacheSnapshot();
437
+ await loadingPromises.get(pathname);
424
438
  }
425
439
  const [path, search = ""] = pathname.split("?");
426
440
  const result = await revalidateCache({
@@ -429,7 +443,8 @@ var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache, syncCach
429
443
  pathname: path,
430
444
  search
431
445
  },
432
- reason: "invalidate"
446
+ reason: "invalidate",
447
+ force: !options?.staleOnly
433
448
  });
434
449
  if (result && path === routePathname) routeDataState.setState((prevState) => ({
435
450
  ...prevState,
@@ -466,7 +481,8 @@ var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache, syncCach
466
481
  return (await Promise.all(pathnameList.map((pathname) => invalidateItem(pathname, options)))).flat();
467
482
  };
468
483
  };
469
- // runtime/prefetch.ts
484
+ //#endregion
485
+ //#region runtime/prefetch.ts
470
486
  var MOBILE_PREFETCH_CONCURRENCY = 2;
471
487
  var DESKTOP_PREFETCH_CONCURRENCY = 4;
472
488
  var createPrefetch = ({ routeDataState }, revalidateCache) => {
@@ -504,7 +520,9 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => {
504
520
  drain();
505
521
  });
506
522
  };
507
- // runtime/revalidateCache.ts
523
+ //#endregion
524
+ //#region runtime/revalidateCache.ts
525
+ var PRELOAD_STALE_TIME = 3e4;
508
526
  var isObjectRetry = (arg) => typeof arg === "object";
509
527
  var createRetry = (arg) => {
510
528
  if (arg === void 0) return null;
@@ -560,7 +578,12 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
560
578
  }
561
579
  }
562
580
  if (!force && isCacheItemFresh(path)) {
563
- const item = moveItemToLastPosition(path);
581
+ const item = loaderMap.get(path);
582
+ if (reason === "navigation" && item?.reason === "prefetch") {
583
+ item.reason = "navigation";
584
+ item.staleTime = routeItem.staleTime;
585
+ }
586
+ moveItemToLastPosition(path);
564
587
  if (!item?.state) return void 0;
565
588
  return item.state.loaderError ? {
566
589
  data: null,
@@ -583,6 +606,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
583
606
  signal: effectiveSignal,
584
607
  attempt: retried + 1
585
608
  });
609
+ const resolvedStaleTime = routeItem.staleTime ?? routerConfig.defaultStaleTime ?? 0;
586
610
  loaderMap.set(path, {
587
611
  state: {
588
612
  data: result,
@@ -590,7 +614,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
590
614
  loaderError: null
591
615
  },
592
616
  timestamp: Date.now(),
593
- staleTime: routeItem.staleTime,
617
+ staleTime: reason === "prefetch" ? Math.max(resolvedStaleTime, PRELOAD_STALE_TIME) : routeItem.staleTime,
594
618
  reason
595
619
  });
596
620
  evict();
@@ -636,14 +660,15 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
636
660
  };
637
661
  return revalidateCache;
638
662
  };
639
- // runtime/syncCacheSnapshot.ts
663
+ //#endregion
664
+ //#region runtime/syncCacheSnapshot.ts
640
665
  var createCacheSnapshot = (loaderMap, loadingPromises) => {
641
666
  const entries = [];
642
667
  for (const [path, item] of loaderMap) entries.push({
643
668
  path,
644
669
  data: item.state?.data,
645
670
  timestamp: item.timestamp,
646
- staleTime: item.staleTime,
671
+ staleTime: item.staleTime ?? routerConfig.defaultStaleTime ?? 0,
647
672
  reason: item.reason,
648
673
  gcExpiresAt: item.gcExpiresAt,
649
674
  gcDuration: item.gcDuration,
@@ -655,7 +680,7 @@ var createCacheSnapshot = (loaderMap, loadingPromises) => {
655
680
  path,
656
681
  data: void 0,
657
682
  timestamp: Date.now(),
658
- staleTime: void 0,
683
+ staleTime: routerConfig.defaultStaleTime ?? 0,
659
684
  gcExpiresAt: void 0,
660
685
  gcDuration: void 0,
661
686
  isLoading: true
@@ -663,7 +688,8 @@ var createCacheSnapshot = (loaderMap, loadingPromises) => {
663
688
  }
664
689
  return entries;
665
690
  };
666
- // creators/createRouterInstance.ts
691
+ //#endregion
692
+ //#region creators/createRouterInstance.ts
667
693
  var createRouterInstance = (synchronizer) => {
668
694
  const loaderMap = /* @__PURE__ */ new Map();
669
695
  const loadingPromises = /* @__PURE__ */ new Map();
@@ -684,7 +710,7 @@ var createRouterInstance = (synchronizer) => {
684
710
  loadingPromises
685
711
  };
686
712
  const syncCacheSnapshot = () => {
687
- if (routerConfig.logged) cacheSnapshotState.setState(createCacheSnapshot(loaderMap, loadingPromises));
713
+ if (routerConfig.enableCacheSnapshot) cacheSnapshotState.setState(createCacheSnapshot(loaderMap, loadingPromises));
688
714
  };
689
715
  const revalidateCache = createRevalidateCache(routerState, syncCacheSnapshot);
690
716
  const navigate = createNavigate(routerState, revalidateCache, syncCacheSnapshot);
@@ -763,8 +789,11 @@ var createRouterInstance = (synchronizer) => {
763
789
  useAction: (action, options = {}) => {
764
790
  return async (input) => {
765
791
  try {
766
- const data = await getCurrentAction(action)(input);
767
- await invalidate();
792
+ const currentAction = getCurrentAction(action);
793
+ const { location } = routerState.routeDataState.getState();
794
+ const path = `${location.pathname}${location.search ?? ""}`;
795
+ const data = await currentAction(input);
796
+ await invalidate(path);
768
797
  options.onSuccess?.(data);
769
798
  return {
770
799
  data,
@@ -817,13 +846,16 @@ var createRouterInstance = (synchronizer) => {
817
846
  }
818
847
  };
819
848
  };
820
- // instance.ts
849
+ //#endregion
850
+ //#region instance.ts
821
851
  var router = createRouterInstance(useSyncExternalStore);
822
- // hooks/useNavigation.ts
852
+ //#endregion
853
+ //#region hooks/useNavigation.ts
823
854
  var useNavigation = () => {
824
855
  const { navigate } = router.runtime;
825
856
  const { useRouteDataSelector, useBlockerState } = router.hooks;
826
857
  const location = useRouteDataSelector((state) => state.location);
858
+ const skipForwardPop = useRef(false);
827
859
  const [blockerState] = useBlockerState();
828
860
  useEffect(() => {
829
861
  const handler = async (event) => {
@@ -832,7 +864,19 @@ var useNavigation = () => {
832
864
  pathname: location.pathname,
833
865
  search: location.search
834
866
  };
835
- if (blockerState === "charged") history.pushState(location.state ?? null, "", `${location.pathname}${location.search}`);
867
+ if (skipForwardPop.current) {
868
+ skipForwardPop.current = false;
869
+ if (newLocation.pathname === location.pathname && (newLocation.search ?? "") === (location.search ?? "")) return;
870
+ }
871
+ if (blockerState === "charged" || blockerState === "blocked") {
872
+ skipForwardPop.current = true;
873
+ if (blockerState === "charged") await navigate({
874
+ ...newLocation,
875
+ prevLocation
876
+ });
877
+ history.forward();
878
+ return;
879
+ }
836
880
  await navigate({
837
881
  ...newLocation,
838
882
  prevLocation
@@ -851,7 +895,8 @@ var useNavigation = () => {
851
895
  navigate(parseWindowLocation(window.location));
852
896
  }, [navigate]);
853
897
  };
854
- // hooks/useApplyCustomAnimation.ts
898
+ //#endregion
899
+ //#region hooks/useApplyCustomAnimation.ts
855
900
  var useApplyCustomAnimation = (animationDuration) => {
856
901
  useEffect(() => {
857
902
  if (!animationDuration) return;
@@ -862,29 +907,34 @@ var useApplyCustomAnimation = (animationDuration) => {
862
907
  return () => style.remove();
863
908
  }, [animationDuration]);
864
909
  };
865
- // hooks/useRestoreScroll.ts
910
+ //#endregion
911
+ //#region hooks/useRestoreScroll.ts
866
912
  var useRestoreScroll = (behavior) => {
867
913
  const { useScrollRestoration } = router.hooks;
868
914
  const { defaultScrollRestorationBehavior = "auto" } = routerConfig;
869
915
  return useScrollRestoration(behavior ?? defaultScrollRestorationBehavior);
870
916
  };
871
- // hooks/useRestoreRouteScroll.ts
917
+ //#endregion
918
+ //#region hooks/useRestoreRouteScroll.ts
872
919
  var useRestoreRouteScroll = (behavior) => {
873
920
  const restoreScroll = useRestoreScroll(behavior);
874
921
  useEffect(restoreScroll, [restoreScroll]);
875
922
  };
876
- // hooks/useSetRouterConfig.ts
923
+ //#endregion
924
+ //#region hooks/useSetRouterConfig.ts
877
925
  var useSetRouterConfig = (routerProps) => {
878
926
  useLayoutEffect(() => routerConfig.configure(routerProps), [routerProps]);
879
927
  };
880
- // hooks/useSetInitialContext.ts
928
+ //#endregion
929
+ //#region hooks/useSetInitialContext.ts
881
930
  var useSetInitialContext = (initialContext) => {
882
931
  const [, setContext] = router.hooks.useContextState();
883
932
  useEffect(() => {
884
933
  if (initialContext) setContext(initialContext);
885
934
  }, [initialContext, setContext]);
886
935
  };
887
- // hooks/useReload.ts
936
+ //#endregion
937
+ //#region hooks/useReload.ts
888
938
  var useReload = () => {
889
939
  const { invalidate } = router.runtime;
890
940
  useEffect(() => {
@@ -902,18 +952,20 @@ var useReload = () => {
902
952
  return () => window.removeEventListener("online", handler);
903
953
  }, [invalidate]);
904
954
  };
905
- // utils/renderElement.tsx
955
+ //#endregion
956
+ //#region utils/renderElement.tsx
906
957
  var renderElement = (Component) => {
907
958
  if (!Component) return null;
908
959
  if (typeof Component !== "function") return Component;
909
960
  return /* @__PURE__ */ jsx(Component, {});
910
961
  };
911
- // components/Router.tsx
962
+ //#endregion
963
+ //#region components/Router.tsx
912
964
  var EmptyBoundary = ({ children }) => children;
913
965
  var IS_MOBILE = isMobile();
914
966
  var MOBILE_CACHE_SIZE = 60;
915
967
  var DESKTOP_CACHE_SIZE = 150;
916
- var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary, logged = false }) => {
968
+ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary, enableCacheSnapshot = false }) => {
917
969
  const { useRouteDataSelector } = router.hooks;
918
970
  const routeItem = useRouteDataSelector((state) => state.routeItem);
919
971
  const location = useRouteDataSelector((state) => state.location);
@@ -935,7 +987,7 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
935
987
  revalidateOnFocus,
936
988
  revalidateOnReconnect,
937
989
  defaultScrollRestorationBehavior,
938
- logged
990
+ enableCacheSnapshot
939
991
  });
940
992
  useApplyCustomAnimation(animationDuration);
941
993
  useSetInitialContext(initialContext);
@@ -951,23 +1003,25 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
951
1003
  children: content
952
1004
  }));
953
1005
  };
954
- // hooks/useNavigate.ts
1006
+ //#endregion
1007
+ //#region hooks/useNavigate.ts
955
1008
  var useNavigate = router.hooks.useNavigate;
956
- // components/Link.tsx
1009
+ //#endregion
1010
+ //#region components/Link.tsx
957
1011
  var VIEWPORT_DWELL_MS = 250;
958
1012
  var defaultAs = (props) => /* @__PURE__ */ jsx("a", { ...props });
959
1013
  var comparator = (to, pathname, exact) => to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
960
1014
  var Link = ({ children, to, path, params, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
961
1015
  const pathname = path !== void 0 ? interpolatePath(path, params ?? {}) : to ?? "";
1016
+ const searchString = typeof search === "object" ? formatSearchObject(search) : search;
962
1017
  const { useRouteDataSelector } = router.hooks;
963
- const isPending = useRouteDataSelector(({ location: { pathname: currentPathname }, status }) => currentPathname === pathname && status === "pending");
1018
+ const isPending = useRouteDataSelector(({ location: { pathname: currentPathname, search: currentSearch = "" }, status }) => currentPathname === pathname && currentSearch === searchString && status === "pending");
964
1019
  const navigate = useNavigate();
965
1020
  const isActive = useRouteDataSelector(({ location: { pathname: currentPathname } }) => comparator(pathname, currentPathname, exact));
966
1021
  const timeout = useRef(0);
967
1022
  const elementRef = useRef(null);
968
1023
  const getPrefetchStrategy = useCallback(() => linkPrefetch || routerConfig.defaultPrefetch, [linkPrefetch]);
969
1024
  const getPrefetchDelay = useCallback(() => hoverPrefetchDelay ?? routerConfig.defaultHoverPrefetchDelay, [hoverPrefetchDelay]);
970
- const searchString = typeof search === "object" ? formatSearchObject(search) : search;
971
1025
  const location = useMemo(() => ({
972
1026
  pathname,
973
1027
  search: searchString,
@@ -1080,7 +1134,8 @@ var Link = ({ children, to, path, params, search = "", state, as = defaultAs, pr
1080
1134
  isPending
1081
1135
  });
1082
1136
  };
1083
- // hooks/useParams.ts
1137
+ //#endregion
1138
+ //#region hooks/useParams.ts
1084
1139
  /**
1085
1140
  * Route params of the current location.
1086
1141
  *
@@ -1089,16 +1144,20 @@ var Link = ({ children, to, path, params, search = "", state, as = defaultAs, pr
1089
1144
  * - `useParams<{ ... }>()` — legacy manual shape, kept for compatibility.
1090
1145
  */
1091
1146
  var useParams = () => router.hooks.useParams();
1092
- // hooks/useLocation.ts
1147
+ //#endregion
1148
+ //#region hooks/useLocation.ts
1093
1149
  var useLocation = () => router.hooks.useRouteDataSelector((state) => state.location);
1094
- // hooks/useLoaderState.ts
1150
+ //#endregion
1151
+ //#region hooks/useLoaderState.ts
1095
1152
  var useLoaderState = () => {
1096
1153
  const { useRouteDataSelector } = router.hooks;
1097
1154
  return useRouteDataSelector((state) => state.loaderState);
1098
1155
  };
1099
- // hooks/useInvalidate.ts
1156
+ //#endregion
1157
+ //#region hooks/useInvalidate.ts
1100
1158
  var useInvalidate = () => router.runtime.invalidate;
1101
- // hooks/useBlocker.ts
1159
+ //#endregion
1160
+ //#region hooks/useBlocker.ts
1102
1161
  var useBlocker = (blockerFn) => {
1103
1162
  const { hooks: { useBlockerState, useContextState, useBlockedTargetState }, runtime: { navigate } } = router;
1104
1163
  const [blockerState, setBlockerState] = useBlockerState();
@@ -1118,11 +1177,15 @@ var useBlocker = (blockerFn) => {
1118
1177
  return {
1119
1178
  state: blockerState,
1120
1179
  process: useCallback(async () => {
1121
- if (nextLocation) await navigate(nextLocation);
1180
+ if (!nextLocation) return;
1181
+ const target = nextLocation;
1182
+ setBlockerState("unblocked");
1183
+ await navigate(target);
1122
1184
  setNextLocation(null);
1123
1185
  }, [
1124
1186
  navigate,
1125
1187
  nextLocation,
1188
+ setBlockerState,
1126
1189
  setNextLocation
1127
1190
  ]),
1128
1191
  reset: useCallback(() => {
@@ -1131,14 +1194,17 @@ var useBlocker = (blockerFn) => {
1131
1194
  }, [setBlockerState, setNextLocation])
1132
1195
  };
1133
1196
  };
1134
- // hooks/useAction.ts
1197
+ //#endregion
1198
+ //#region hooks/useAction.ts
1135
1199
  var useAction = router.hooks.useAction;
1136
- // hooks/useRouteStatus.ts
1200
+ //#endregion
1201
+ //#region hooks/useRouteStatus.ts
1137
1202
  function useRouteStatus(predicate) {
1138
1203
  const { useRouteDataSelector } = router.hooks;
1139
1204
  return useRouteDataSelector(({ status }) => predicate ? predicate(status) : status);
1140
1205
  }
1141
- // hooks/useRouterContext.ts
1206
+ //#endregion
1207
+ //#region hooks/useRouterContext.ts
1142
1208
  var useRouterContext = () => {
1143
1209
  const [context, setContext] = router.hooks.useContextState();
1144
1210
  return {
@@ -1146,7 +1212,8 @@ var useRouterContext = () => {
1146
1212
  setContext
1147
1213
  };
1148
1214
  };
1149
- // hooks/useSearchParams.ts
1215
+ //#endregion
1216
+ //#region hooks/useSearchParams.ts
1150
1217
  var useLatest = (value) => {
1151
1218
  const ref = useRef(value);
1152
1219
  useEffect(() => {
@@ -1183,14 +1250,13 @@ var useSearchParams = () => {
1183
1250
  currentParams.delete(param);
1184
1251
  (Array.isArray(value) ? value : [value]).forEach((v) => currentParams.append(param, v));
1185
1252
  navigateWithSearchParams(currentParams);
1186
- } else if (typeof param === "function") {
1187
- const newParams = param(currentParams);
1188
- navigateWithSearchParams(newParams);
1189
- } else throw new Error("useSearchParams first argument must be either function or string");
1253
+ } else if (typeof param === "function") navigateWithSearchParams(param(currentParams));
1254
+ else throw new Error("useSearchParams first argument must be either function or string");
1190
1255
  }, [navigateWithSearchParams, searchRef])
1191
1256
  };
1192
1257
  };
1193
- // hooks/useSubmitAction.ts
1258
+ //#endregion
1259
+ //#region hooks/useSubmitAction.ts
1194
1260
  var useSubmitAction = (action, options) => {
1195
1261
  const currentAction = router.hooks.useAction(action, options);
1196
1262
  const [data, setData] = useState();
@@ -1217,14 +1283,15 @@ var useSubmitAction = (action, options) => {
1217
1283
  isSubmitting
1218
1284
  };
1219
1285
  };
1220
- // hooks/useCacheSnapshot.ts
1221
- /** Requires `<Router logged>` — otherwise the snapshot stays empty. */
1286
+ //#endregion
1287
+ //#region hooks/useCacheSnapshot.ts
1222
1288
  var useCacheSnapshot = () => {
1223
1289
  const snapshot = router.hooks.useCacheSnapshot();
1224
1290
  useEffect(() => router.runtime.syncCacheSnapshot(), []);
1225
1291
  return snapshot;
1226
1292
  };
1227
- // utils/createLazyComponent.tsx
1293
+ //#endregion
1294
+ //#region utils/createLazyComponent.tsx
1228
1295
  var createLazyComponent = (importFn, fallback) => {
1229
1296
  const load = () => importFn().then((module) => ({ default: module.default || module }));
1230
1297
  const LazyComp = lazy$1(load);
@@ -1237,9 +1304,11 @@ var createLazyComponent = (importFn, fallback) => {
1237
1304
  preloadElement: load
1238
1305
  };
1239
1306
  };
1240
- // types.ts
1307
+ //#endregion
1308
+ //#region types.ts
1241
1309
  var LAZY_MARKER = Symbol("clear-router-lazy");
1242
- // creators/createRouter.ts
1310
+ //#endregion
1311
+ //#region creators/createRouter.ts
1243
1312
  var isLazy = (component) => typeof component === "object" && component !== null && LAZY_MARKER in component;
1244
1313
  var resolve = (component, fallback) => isLazy(component) ? createLazyComponent(component.importFn, fallback).Component : component;
1245
1314
  var parseClientRouteItem = (el, parentPattern = "", inheritedLayouts = []) => {
@@ -1256,9 +1325,11 @@ var parseClientRouteItem = (el, parentPattern = "", inheritedLayouts = []) => {
1256
1325
  }, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern, layouts)) ?? []];
1257
1326
  };
1258
1327
  var createRouter = (clientList) => clientList.flatMap((el) => parseClientRouteItem(el));
1259
- // utils/lazy.ts
1328
+ //#endregion
1329
+ //#region utils/lazy.ts
1260
1330
  var lazy = (importFn) => ({
1261
1331
  [LAZY_MARKER]: true,
1262
1332
  importFn
1263
1333
  });
1334
+ //#endregion
1264
1335
  export { Link, Router, createRouter, lazy, useAction, useBlocker, useCacheSnapshot, useInvalidate, useLoaderState, useLocation, useNavigate, useParams, useRestoreScroll, useRouteStatus, useRouterContext, useSearchParams, useSubmitAction };
@@ -1,2 +1,2 @@
1
1
  import { type InvalidateOptions, InvalidateResult, RevalidateCache, RouterState } from '../types';
2
- export declare const createInvalidate: ({ routeDataState, loaderMap }: RouterState, revalidateCache: RevalidateCache, syncCacheSnapshot: () => void) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
2
+ export declare const createInvalidate: ({ routeDataState, loaderMap, loadingPromises }: RouterState, revalidateCache: RevalidateCache, syncCacheSnapshot: () => void) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
package/dist/types.d.ts CHANGED
@@ -108,7 +108,7 @@ export type RouterProps = {
108
108
  revalidateOnReconnect?: boolean;
109
109
  context?: Record<string, unknown>;
110
110
  /** Enables cache snapshot tracking for devtools. `useCacheSnapshot` returns an empty list without it. */
111
- logged?: boolean;
111
+ enableCacheSnapshot?: boolean;
112
112
  };
113
113
  export type LoaderStateItem = {
114
114
  state: LoaderState;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.4.9",
3
+ "version": "2.5.0",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {