@real-router/react 0.24.0 → 0.25.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.
Files changed (123) hide show
  1. package/README.md +127 -7
  2. package/dist/cjs/Await-whr-pcvo.d.ts +41 -0
  3. package/dist/cjs/Await-whr-pcvo.d.ts.map +1 -0
  4. package/dist/cjs/HttpStatusProvider-Dh6cMr95.d.ts +143 -0
  5. package/dist/cjs/HttpStatusProvider-Dh6cMr95.d.ts.map +1 -0
  6. package/dist/cjs/Link-BspioC76.js +2 -0
  7. package/dist/cjs/Link-BspioC76.js.map +1 -0
  8. package/dist/cjs/RouterErrorBoundary-BlJmaoyr.d.ts +47 -0
  9. package/dist/cjs/RouterErrorBoundary-BlJmaoyr.d.ts.map +1 -0
  10. package/dist/cjs/{RouterProvider-Bj1_NbpA.d.ts → RouterProvider-DvC9mViF.d.ts} +2 -2
  11. package/dist/cjs/RouterProvider-DvC9mViF.d.ts.map +1 -0
  12. package/dist/cjs/RouterProvider-fJvMO5Tc.js +2 -0
  13. package/dist/cjs/RouterProvider-fJvMO5Tc.js.map +1 -0
  14. package/dist/cjs/createHttpStatusSink-D_6IiR5E.js +2 -0
  15. package/dist/cjs/createHttpStatusSink-D_6IiR5E.js.map +1 -0
  16. package/dist/cjs/index.d.ts +6 -281
  17. package/dist/cjs/index.js +1 -1
  18. package/dist/cjs/index.js.map +1 -1
  19. package/dist/cjs/index.react-server.d.ts +5 -0
  20. package/dist/cjs/index.react-server.js +0 -0
  21. package/dist/cjs/ink.d.ts +2 -1
  22. package/dist/cjs/ink.d.ts.map +1 -1
  23. package/dist/cjs/ink.js +1 -1
  24. package/dist/cjs/ink.js.map +1 -1
  25. package/dist/cjs/legacy.d.ts +3 -2
  26. package/dist/cjs/legacy.js +1 -1
  27. package/dist/cjs/legacy.ssr.d.ts +3 -0
  28. package/dist/cjs/legacy.ssr.js +1 -0
  29. package/dist/cjs/ssr.d.ts +4 -0
  30. package/dist/cjs/ssr.js +2 -0
  31. package/dist/cjs/ssr.js.map +1 -0
  32. package/dist/cjs/ssr.react-server.d.ts +3 -0
  33. package/dist/cjs/ssr.react-server.js +0 -0
  34. package/dist/cjs/useDeferred-DE5YUsfa.d.ts +24 -0
  35. package/dist/cjs/useDeferred-DE5YUsfa.d.ts.map +1 -0
  36. package/dist/cjs/useRoute-Dudo2K_0.js +2 -0
  37. package/dist/cjs/useRoute-Dudo2K_0.js.map +1 -0
  38. package/dist/cjs/useRouteEnter-gfy65W0D.d.ts +279 -0
  39. package/dist/cjs/useRouteEnter-gfy65W0D.d.ts.map +1 -0
  40. package/dist/cjs/useRouterTransition-BfayPs0h.d.ts +56 -0
  41. package/dist/cjs/useRouterTransition-BfayPs0h.d.ts.map +1 -0
  42. package/dist/esm/Await-qSmJ-ZuN.d.mts +41 -0
  43. package/dist/esm/Await-qSmJ-ZuN.d.mts.map +1 -0
  44. package/dist/esm/HttpStatusProvider-Cy9GSANm.d.mts +143 -0
  45. package/dist/esm/HttpStatusProvider-Cy9GSANm.d.mts.map +1 -0
  46. package/dist/esm/Link-BQol2GYb.mjs +2 -0
  47. package/dist/esm/Link-BQol2GYb.mjs.map +1 -0
  48. package/dist/esm/RouterErrorBoundary-C-MH_yrP.d.mts +47 -0
  49. package/dist/esm/RouterErrorBoundary-C-MH_yrP.d.mts.map +1 -0
  50. package/dist/esm/{RouterProvider-Dr3X_vbc.d.mts → RouterProvider-D_ZlPVAC.d.mts} +2 -2
  51. package/dist/esm/RouterProvider-D_ZlPVAC.d.mts.map +1 -0
  52. package/dist/esm/RouterProvider-a9y9bqji.mjs +2 -0
  53. package/dist/esm/RouterProvider-a9y9bqji.mjs.map +1 -0
  54. package/dist/esm/createHttpStatusSink-BXWVamHE.mjs +2 -0
  55. package/dist/esm/createHttpStatusSink-BXWVamHE.mjs.map +1 -0
  56. package/dist/esm/index.d.mts +6 -281
  57. package/dist/esm/index.mjs +1 -1
  58. package/dist/esm/index.mjs.map +1 -1
  59. package/dist/esm/index.react-server.d.mts +5 -0
  60. package/dist/esm/index.react-server.mjs +0 -0
  61. package/dist/esm/ink.d.mts +2 -1
  62. package/dist/esm/ink.d.mts.map +1 -1
  63. package/dist/esm/ink.mjs +1 -1
  64. package/dist/esm/ink.mjs.map +1 -1
  65. package/dist/esm/legacy.d.mts +3 -2
  66. package/dist/esm/legacy.mjs +1 -1
  67. package/dist/esm/legacy.ssr.d.mts +3 -0
  68. package/dist/esm/legacy.ssr.mjs +1 -0
  69. package/dist/esm/ssr.d.mts +4 -0
  70. package/dist/esm/ssr.mjs +2 -0
  71. package/dist/esm/ssr.mjs.map +1 -0
  72. package/dist/esm/ssr.react-server.d.mts +3 -0
  73. package/dist/esm/ssr.react-server.mjs +0 -0
  74. package/dist/esm/useDeferred-B5Qy7ttQ.d.mts +24 -0
  75. package/dist/esm/useDeferred-B5Qy7ttQ.d.mts.map +1 -0
  76. package/dist/esm/useRoute-Bta1jyl2.mjs +2 -0
  77. package/dist/esm/useRoute-Bta1jyl2.mjs.map +1 -0
  78. package/dist/esm/useRouteEnter-CxjYofFa.d.mts +279 -0
  79. package/dist/esm/useRouteEnter-CxjYofFa.d.mts.map +1 -0
  80. package/dist/esm/useRouterTransition-CI1P95ZQ.d.mts +56 -0
  81. package/dist/esm/useRouterTransition-CI1P95ZQ.d.mts.map +1 -0
  82. package/package.json +46 -4
  83. package/src/components/Await.tsx +46 -0
  84. package/src/components/ClientOnly.tsx +25 -0
  85. package/src/components/HttpStatusCode.tsx +66 -0
  86. package/src/components/HttpStatusProvider.tsx +26 -0
  87. package/src/components/InkLink.tsx +44 -22
  88. package/src/components/Link.tsx +32 -36
  89. package/src/components/RouterErrorBoundary.tsx +21 -6
  90. package/src/components/ServerOnly.tsx +26 -0
  91. package/src/components/Streamed.tsx +30 -0
  92. package/src/components/modern/RouteView/RouteView.tsx +9 -3
  93. package/src/components/modern/RouteView/helpers.tsx +26 -16
  94. package/src/constants.ts +7 -8
  95. package/src/context.ts +4 -2
  96. package/src/hooks/useDeferred.tsx +34 -0
  97. package/src/hooks/useIsActiveRoute.tsx +17 -9
  98. package/src/hooks/useNavigator.tsx +0 -2
  99. package/src/hooks/useRoute.tsx +10 -7
  100. package/src/hooks/useRouter.tsx +0 -2
  101. package/src/index.react-server.ts +33 -0
  102. package/src/index.ts +5 -0
  103. package/src/legacy.ssr.ts +35 -0
  104. package/src/legacy.ts +4 -0
  105. package/src/ssr.react-server.ts +21 -0
  106. package/src/ssr.ts +43 -0
  107. package/src/utils/createHttpStatusSink.ts +27 -0
  108. package/dist/cjs/Link-DYvAnJlk.js +0 -2
  109. package/dist/cjs/Link-DYvAnJlk.js.map +0 -1
  110. package/dist/cjs/RouterProvider-Bj1_NbpA.d.ts.map +0 -1
  111. package/dist/cjs/RouterProvider-CfBNR-k7.js +0 -2
  112. package/dist/cjs/RouterProvider-CfBNR-k7.js.map +0 -1
  113. package/dist/cjs/index.d.ts.map +0 -1
  114. package/dist/cjs/useRouterTransition-BYit_9Mt.d.ts +0 -92
  115. package/dist/cjs/useRouterTransition-BYit_9Mt.d.ts.map +0 -1
  116. package/dist/esm/Link-C7upxMc8.mjs +0 -2
  117. package/dist/esm/Link-C7upxMc8.mjs.map +0 -1
  118. package/dist/esm/RouterProvider-CS2ZoONm.mjs +0 -2
  119. package/dist/esm/RouterProvider-CS2ZoONm.mjs.map +0 -1
  120. package/dist/esm/RouterProvider-Dr3X_vbc.d.mts.map +0 -1
  121. package/dist/esm/index.d.mts.map +0 -1
  122. package/dist/esm/useRouterTransition-B65Wvngj.d.mts +0 -92
  123. package/dist/esm/useRouterTransition-B65Wvngj.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RouterProvider-fJvMO5Tc.js","names":["RouterContext","NOOP_INSTANCE","NOOP_INSTANCE","NavigatorContext","RouterContext","NavigatorContext","RouteContext"],"sources":["../../src/hooks/useRouter.tsx","../../src/hooks/useRouteNode.tsx","../../../../shared/dom-utils/route-announcer.ts","../../../../shared/dom-utils/scroll-restore.ts","../../../../shared/dom-utils/view-transitions.ts","../../../../shared/dom-utils/link-utils.ts","../../src/hooks/useIsActiveRoute.tsx","../../src/components/RouterErrorBoundary.tsx","../../src/hooks/useNavigator.tsx","../../src/hooks/useRouteUtils.tsx","../../src/hooks/useRouterTransition.tsx","../../src/RouterProvider.tsx"],"sourcesContent":["import { useContext } from \"react\";\n\nimport { RouterContext } from \"../context\";\n\nimport type { Router } from \"@real-router/core\";\n\nexport const useRouter = (): Router => {\n const router = useContext(RouterContext);\n\n if (!router) {\n throw new Error(\"useRouter must be used within a RouterProvider\");\n }\n\n return router;\n};\n","import { getNavigator } from \"@real-router/core\";\nimport { createRouteNodeSource } from \"@real-router/sources\";\nimport { useMemo, useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouteContext } from \"../types\";\n\nexport function useRouteNode(nodeName: string): RouteContext {\n const router = useRouter();\n\n const store = useMemo(\n () => createRouteNodeSource(router, nodeName),\n [router, nodeName],\n );\n\n // Use snapshot reference directly. createRouteNodeSource via stabilizeState\n // returns the SAME snapshot when the node-relevant state did not change,\n // so memoization on `[navigator, snapshot]` preserves identity for consumers.\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot, // SSR: router returns same state on server and client\n );\n\n // getNavigator is WeakMap-cached in core; additional useMemo is redundant.\n const navigator = getNavigator(router);\n\n return useMemo(\n (): RouteContext => ({\n navigator,\n route: snapshot.route,\n previousRoute: snapshot.previousRoute,\n }),\n [navigator, snapshot],\n );\n}\n","import type { Router, State } from \"@real-router/core\";\n\nconst CLEAR_DELAY = 7000;\nconst SAFARI_READY_DELAY = 100;\nconst ANNOUNCER_ATTR = \"data-real-router-announcer\";\nconst INTERNAL_ROUTE_PREFIX = \"@@\";\nconst VISUALLY_HIDDEN =\n \"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);clip-path:inset(50%);white-space:nowrap;border:0\";\n\nexport interface RouteAnnouncerOptions {\n prefix?: string;\n getAnnouncementText?: (route: State) => string;\n}\n\nconst NOOP_INSTANCE: { destroy: () => void } = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport function createRouteAnnouncer(\n router: Router,\n options?: RouteAnnouncerOptions,\n): { destroy: () => void } {\n // Defensive SSR / non-browser guard: in SSR (Node.js) or non-DOM\n // environments, `document` is undefined and the announcer cannot\n // attach its aria-live region. Return a frozen NOOP_INSTANCE — same\n // pattern as `createDirectionTracker`, `createScrollRestoration`, and\n // `createViewTransitions`. Without this guard, `NavigationAnnouncer`\n // component construction would throw `ReferenceError: document is not\n // defined` under `@angular/ssr` rendering, tearing down the whole SSR\n // bootstrap. Closes review-2026-05-10 §5.10 ⛔ \"NavigationAnnouncer\n // SSR mode\" MED.\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const prefix = options?.prefix ?? \"Navigated to \";\n const getCustomText = options?.getAnnouncementText;\n\n let isInitialNavigation = true;\n let isReady = false;\n let isDestroyed = false;\n let lastAnnouncedText = \"\";\n let pendingText: string | null = null;\n let clearTimeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const announcer = getOrCreateAnnouncer();\n\n const doAnnounce = (text: string, h1: HTMLElement | null): void => {\n lastAnnouncedText = text;\n clearTimeout(clearTimeoutId);\n announcer.textContent = text;\n clearTimeoutId = setTimeout(() => {\n announcer.textContent = \"\";\n lastAnnouncedText = \"\";\n }, CLEAR_DELAY);\n\n manageFocus(h1);\n };\n\n // Safari-ready delay: announcing before VoiceOver wires up the aria-live region\n // causes the first announcement to be silently dropped. Wait SAFARI_READY_DELAY ms\n // before marking the announcer \"ready\" — any navigation during that window is\n // buffered in pendingText and flushed once the delay expires.\n const safariTimeoutId = setTimeout(() => {\n isReady = true;\n\n if (pendingText !== null && !isDestroyed) {\n const text = pendingText;\n\n pendingText = null;\n doAnnounce(text, document.querySelector<HTMLElement>(\"h1\"));\n }\n }, SAFARI_READY_DELAY);\n\n const unsubscribe = router.subscribe(({ route }) => {\n if (isInitialNavigation) {\n isInitialNavigation = false;\n\n return;\n }\n\n // Double rAF: waits for two paint frames so the incoming route's DOM\n // (including the new <h1>) is fully rendered before resolveText reads it.\n // Single rAF fires before the new route's template has been attached,\n // which would cause resolveText to pick up the OLD h1 or fall back to\n // document.title / route.name prematurely.\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n if (isDestroyed) {\n return;\n }\n\n const h1 = document.querySelector<HTMLElement>(\"h1\");\n const text = resolveText(route, prefix, getCustomText, h1);\n\n if (!text || text === lastAnnouncedText) {\n return;\n }\n\n if (!isReady) {\n // Defer announcement until Safari-ready window elapses (see safariTimeoutId).\n pendingText = text;\n\n return;\n }\n\n doAnnounce(text, h1);\n });\n });\n });\n\n return {\n destroy() {\n isDestroyed = true;\n unsubscribe();\n clearTimeout(clearTimeoutId);\n clearTimeout(safariTimeoutId);\n removeAnnouncer();\n },\n };\n}\n\nfunction getOrCreateAnnouncer(): HTMLElement {\n const existing = document.querySelector<HTMLElement>(`[${ANNOUNCER_ATTR}]`);\n\n if (existing) {\n return existing;\n }\n\n const element = document.createElement(\"div\");\n\n element.setAttribute(\"style\", VISUALLY_HIDDEN);\n element.setAttribute(\"aria-live\", \"assertive\");\n element.setAttribute(\"aria-atomic\", \"true\");\n element.setAttribute(ANNOUNCER_ATTR, \"\");\n\n // Defensive SSR / pre-`<body>` guard: in some environments (early\n // injection, deferred-body documents, certain SSR rehydration paths)\n // `document.body` can be null when the announcer is constructed.\n // `document.body.prepend(...)` would throw `TypeError: Cannot read\n // properties of null`, tearing down the consumer's RouterProvider /\n // NavigationAnnouncer mount. Fallback to `documentElement` keeps the\n // announcer working for SR users; visual-hidden styling means there is\n // no visible artifact regardless of mount point.\n //\n // TS dom lib types `document.body` as `HTMLElement` (non-null), but\n // runtime can return null per spec. The `as` cast narrows the type to\n // include null so the `??` short-circuit is type-safe.\n ((document.body as HTMLElement | null) ?? document.documentElement).prepend(\n element,\n );\n\n return element;\n}\n\nfunction removeAnnouncer(): void {\n document.querySelector(`[${ANNOUNCER_ATTR}]`)?.remove();\n}\n\nfunction resolveText(\n route: State,\n prefix: string,\n getCustomText: ((route: State) => string) | undefined,\n h1: HTMLElement | null,\n): string {\n if (getCustomText) {\n try {\n const customText = getCustomText(route);\n\n // Mini-sprint E.4 (audit-5 §4.2 #4) — empty-string fallback.\n // A consumer pattern like\n // getAnnouncementText: (route) => myMap[route.name] ?? \"\"\n // returns `\"\"` for routes outside the map. The subscribe loop\n // then sees an empty text and silently no-announces — screen\n // readers stay quiet without any signal to the developer. Treat\n // a falsy custom result (`\"\"` / `null` / `undefined`) as\n // \"consumer doesn't have a name for this route\" and fall through\n // to the default resolution chain (h1 → title → route name).\n if (customText) {\n return customText;\n }\n } catch (error) {\n // A throwing consumer callback inside the router's subscribe loop\n // would tear down sibling listeners — log and fall through to the\n // built-in resolution chain so the announcer keeps working.\n console.error(\n \"[real-router] getAnnouncementText threw; falling back to default resolution.\",\n error,\n );\n }\n }\n\n const h1Text = (h1?.textContent ?? \"\").trim();\n const routeName = route.name.startsWith(INTERNAL_ROUTE_PREFIX)\n ? \"\"\n : route.name;\n const rawText =\n h1Text || document.title || routeName || globalThis.location.pathname;\n\n return `${prefix}${rawText}`;\n}\n\nfunction manageFocus(h1: HTMLElement | null): void {\n if (!h1) {\n return;\n }\n\n if (!h1.hasAttribute(\"tabindex\")) {\n h1.setAttribute(\"tabindex\", \"-1\");\n }\n\n h1.focus({ preventScroll: true });\n}\n","import type { Router, State } from \"@real-router/core\";\n\nconst DEFAULT_STORAGE_KEY = \"real-router:scroll\";\n\nconst NOOP_INSTANCE: { destroy: () => void } = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport type ScrollRestorationMode = \"restore\" | \"top\" | \"native\";\n\nexport interface ScrollRestorationOptions {\n mode?: ScrollRestorationMode | undefined;\n anchorScrolling?: boolean | undefined;\n scrollContainer?: (() => HTMLElement | null) | undefined;\n /**\n * Scroll behavior passed to `scrollTo({ behavior })` and\n * `scrollIntoView({ behavior })`.\n *\n * - `\"auto\"` (default) — browser-defined, usually instant.\n * - `\"instant\"` — explicit instant jump (no animation).\n * - `\"smooth\"` — animated transition. Note: smooth restore on back/traverse\n * can feel disorienting if the user expects to land at the saved position\n * immediately. Recommended for `mode: \"top\"` or anchor scroll only.\n *\n * See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions/behavior).\n */\n behavior?: ScrollBehavior | undefined;\n /**\n * sessionStorage key used to persist saved scroll positions. Default:\n * `\"real-router:scroll\"`. Override only when multiple independent\n * `RouterProvider` instances share the same document and you need to\n * isolate their scroll stores (e.g. micro-frontends, embedded widgets,\n * or testing). For a single app with one provider the default is fine.\n */\n storageKey?: string | undefined;\n}\n\ninterface NavigationContext {\n direction?: \"forward\" | \"back\" | \"unknown\";\n navigationType?: \"push\" | \"replace\" | \"traverse\" | \"reload\";\n}\n\nexport function createScrollRestoration(\n router: Router,\n options?: ScrollRestorationOptions,\n): { destroy: () => void } {\n if (typeof globalThis.window === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const mode = options?.mode ?? \"restore\";\n\n // mode \"native\" = utility does nothing. Don't flip history.scrollRestoration,\n // don't subscribe, don't register pagehide — `history.scrollRestoration`\n // stays at the browser default (\"auto\") so the browser handles scroll\n // restore natively. (Note: this is the OPPOSITE of `history.scrollRestoration\n // === \"manual\"` — utility's \"native\" leaves the DOM property at \"auto\" so\n // the browser is in charge.)\n if (mode === \"native\") {\n return NOOP_INSTANCE;\n }\n\n const anchorEnabled = options?.anchorScrolling ?? true;\n const getContainer = options?.scrollContainer;\n const behavior: ScrollBehavior = options?.behavior ?? \"auto\";\n const storageKey = options?.storageKey ?? DEFAULT_STORAGE_KEY;\n\n // Write-through in-memory cache: parse sessionStorage once per provider\n // mount, then mutate in-memory. Avoids a JSON.parse + JSON.stringify pair\n // on every subscribeLeave / pagehide event.\n let store: Record<string, number> | undefined;\n\n const loadStore = (): Record<string, number> => {\n if (store !== undefined) {\n return store;\n }\n\n try {\n const raw = sessionStorage.getItem(storageKey);\n\n store = raw ? (JSON.parse(raw) as Record<string, number>) : {};\n } catch {\n store = {};\n }\n\n return store;\n };\n\n const putPos = (key: string, pos: number): void => {\n try {\n const cached = loadStore();\n\n // Skip-same-value: when a route is left at the same scroll position it\n // already holds in the cache (e.g. tab-switching without scrolling),\n // both the in-memory write and the JSON.stringify + setItem pair are\n // no-ops. Eliminates redundant serialization on the navigation hot\n // path for the common \"click tabs without scrolling\" case.\n if (cached[key] === pos) {\n return;\n }\n\n cached[key] = pos;\n sessionStorage.setItem(storageKey, JSON.stringify(cached));\n } catch {\n // Ignore quota / security errors.\n }\n };\n\n const prevScrollRestoration = history.scrollRestoration;\n\n try {\n history.scrollRestoration = \"manual\";\n } catch {\n // Ignore — some embedded contexts may reject the assignment.\n }\n\n // Resolve the container lazily on every event so containers mounted AFTER\n // the provider still get correct scroll handling. Falls back to window when\n // the getter is absent or returns null (pre-mount).\n const readPos = (): number => {\n const element = getContainer?.();\n\n return element ? element.scrollTop : globalThis.scrollY;\n };\n\n const writePos = (top: number): void => {\n const element = getContainer?.();\n\n if (element) {\n element.scrollTo({ top, left: 0, behavior });\n } else {\n globalThis.scrollTo({ top, left: 0, behavior });\n }\n };\n\n const scrollToHashOrTop = (route: State): void => {\n // URL plugin path (#532): `state.context.url.hash` is the source of truth\n // when one of the URL plugins (browser-plugin / navigation-plugin) is\n // installed. The value is already DECODED — feeding it through\n // `decodeURIComponent` again would throw on a bare `%`.\n const ctxHash = (route.context as { url?: { hash?: string } } | undefined)\n ?.url?.hash;\n\n if (ctxHash !== undefined) {\n if (anchorEnabled && ctxHash.length > 0) {\n // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars\n const element = document.getElementById(ctxHash);\n\n if (element) {\n element.scrollIntoView({ behavior });\n\n return;\n }\n }\n\n writePos(0);\n\n return;\n }\n\n // Fallback path: no URL plugin, read the DOM. `location.hash` is\n // percent-encoded; ids in the DOM are the raw string, so decode for the\n // match. Fall back to the raw slice if the hash contains a malformed\n // escape sequence (decodeURIComponent throws on those).\n const hash = globalThis.location.hash;\n\n if (anchorEnabled && hash.length > 1) {\n let id: string;\n\n try {\n id = decodeURIComponent(hash.slice(1));\n } catch {\n id = hash.slice(1);\n }\n\n // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars\n const element = document.getElementById(id);\n\n if (element) {\n element.scrollIntoView({ behavior });\n\n return;\n }\n }\n\n writePos(0);\n };\n\n let destroyed = false;\n let unserializableWarned = false;\n\n // `keyOf` defers to `canonicalJson` which calls `JSON.stringify`. Two\n // realistic inputs blow up the serializer and would otherwise crash the\n // subscribe callback (taking scroll-restore offline for the whole session):\n // - `BigInt` params → `TypeError: Do not know how to serialize a BigInt`\n // - cyclic params (reactive proxies, DOM-ref back-pointers) → stack\n // overflow.\n // The defensive wrapper drops capture/restore for that specific navigation\n // and warns once per provider — the rest of the cache stays usable.\n const safeKeyOf = (state: State): string | null => {\n try {\n return keyOf(state);\n } catch {\n if (!unserializableWarned) {\n unserializableWarned = true;\n console.error(\n `[real-router] scroll-restore: route \"${state.name}\" has params that cannot be canonicalized (e.g. BigInt or cyclic structure). Scroll position will not be captured or restored for this route.`,\n );\n }\n\n return null;\n }\n };\n\n const unsubscribe = router.subscribe(({ route, previousRoute }) => {\n const nav = (route.context as { navigation?: NavigationContext })\n .navigation;\n\n // Browsers dispatch reload as the initial navigation after refresh, so\n // previousRoute is undefined and capture is naturally skipped. The\n // pre-refresh position was already persisted via pagehide.\n if (previousRoute) {\n const prevKey = safeKeyOf(previousRoute);\n\n if (prevKey !== null) {\n putPos(prevKey, readPos());\n }\n }\n\n // Single rAF so DOM is committed before we read anchors / write scroll.\n // Guard against destroy() racing with the callback.\n requestAnimationFrame(() => {\n if (destroyed) {\n return;\n }\n\n if (mode === \"top\" || !nav) {\n scrollToHashOrTop(route);\n\n return;\n }\n\n if (nav.navigationType === \"replace\") {\n return;\n }\n\n if (\n nav.direction === \"back\" ||\n nav.navigationType === \"traverse\" ||\n nav.navigationType === \"reload\"\n ) {\n const key = safeKeyOf(route);\n\n writePos(key === null ? 0 : (loadStore()[key] ?? 0));\n\n return;\n }\n\n scrollToHashOrTop(route);\n });\n });\n\n const onPageHide = (): void => {\n const current = router.getState();\n\n if (current) {\n const key = safeKeyOf(current);\n\n if (key !== null) {\n putPos(key, readPos());\n }\n }\n };\n\n globalThis.addEventListener(\"pagehide\", onPageHide);\n\n return {\n destroy: () => {\n if (destroyed) {\n return;\n }\n\n destroyed = true;\n unsubscribe();\n globalThis.removeEventListener(\"pagehide\", onPageHide);\n\n try {\n history.scrollRestoration = prevScrollRestoration;\n } catch {\n // Ignore.\n }\n },\n };\n}\n\n/**\n * Internal cache-key builder for scroll-position storage.\n *\n * **Exported for testing only — not part of the public API** (intentionally\n * excluded from `index.ts` barrel). Adapter property tests import it via\n * the direct path to lock the `(name, canonicalJson(params))` key shape\n * as a regression guard (§8b H20 / audit-2026-05-16 #S3). A change to\n * key format would silently lose scroll positions across an upgrade —\n * the test set is the contract.\n *\n * ## Identity-based memoization (audit-2026-05-17 §8b #2)\n *\n * `State` objects emitted by core are frozen per-navigation: their\n * `name` / `params` are immutable for the lifetime of the snapshot, and\n * any change produces a new `State` reference. A `WeakMap<State, string>`\n * therefore safely caches the canonicalised key by identity — repeat\n * `keyOf(state)` calls on the same snapshot (typical on\n * back/forward/traverse where the same prior `State` is re-emitted)\n * skip the recursive `canonicalJson` pass entirely.\n *\n * The cache key is the `State` reference, so entries auto-release when\n * the snapshot is GC'd — no eviction needed.\n */\nconst KEY_CACHE = new WeakMap<State, string>();\n\nexport function keyOf(state: State): string {\n const cached = KEY_CACHE.get(state);\n\n if (cached !== undefined) {\n return cached;\n }\n\n const key = `${state.name}:${canonicalJson(state.params)}`;\n\n KEY_CACHE.set(state, key);\n\n return key;\n}\n\n/**\n * Stable JSON serializer with sorted object keys.\n *\n * **Exported for testing only — not part of the public API** (intentionally\n * excluded from `index.ts` barrel). Adapter property tests import it via\n * the direct path to lock the key-order-insensitive property\n * (`canonicalJson({a:1,b:2}) === canonicalJson({b:2,a:1})`).\n *\n * ## Divergence from `@real-router/sources/canonicalJson` — by design\n *\n * Two independent implementations live in the monorepo:\n *\n * - **`shared/dom-utils/scroll-restore.canonicalJson`** (this file) — scroll\n * cache key builder. Uses `localeCompare` and a plain-object accumulator;\n * tolerates `__proto__`-keyed inputs only insofar as `JSON.stringify`'s\n * replacer happens to sort them; relies on `JSON.stringify`'s native cycle\n * detector. Designed to be cheap on the navigation hot path. The\n * surrounding [[safeKeyOf]] wrapper catches the two crash inputs (`BigInt`,\n * cyclic) and skips the offending capture/restore.\n *\n * - **`@real-router/sources/canonicalJson`** — sources cache key builder.\n * Uses byte-order compare (`< / >`) for locale-independence, a\n * `Object.create(null)` accumulator to prevent prototype pollution, and a\n * bespoke path-based cycle detector (the native one cannot see the cloned\n * graph). Throws eagerly on `Map`/`Set`/`RegExp`/cycles — the caller falls\n * back to a non-cached source.\n *\n * **They are intentionally NOT interchangeable.** Aligning them would either\n * regress scroll-restore performance (byte-order + recursive clone is heavier\n * per call) or weaken the sources cache (locale dependence breaks\n * deterministic cache keys across machines). No cross-package equivalence\n * test exists or should be added; the relationship is \"different invariants,\n * different costs, different consumers.\" Audit-2 / audit-2026-05-17 §2\n * documents the choice.\n */\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(value, canonicalReplacer);\n}\n\nfunction canonicalReplacer(_key: string, val: unknown): unknown {\n // audit-2026-05-17 §5 MEDIUM (Sprint A.3) — function/Symbol marker.\n // `JSON.stringify` silently drops function and symbol values from\n // object output. Two routes that differ ONLY in a function/Symbol\n // value would canonicalize to the same string → silent scroll-cache\n // key collision (positions clobber each other). Replacing the value\n // with a sentinel string breaks the collision while keeping the\n // canonical form deterministic. The sentinels are intentionally\n // ASCII-only and lexically distinct from valid JSON-stringified\n // values; consumers will see `\"<fn>\"` / `\"<sym>\"` if they ever\n // round-trip the cache key, signalling the substitution clearly.\n if (typeof val === \"function\") {\n return \"<fn>\";\n }\n if (typeof val === \"symbol\") {\n return \"<sym>\";\n }\n\n if (val !== null && typeof val === \"object\" && !Array.isArray(val)) {\n // Null-prototype accumulator: a plain `{}` would interpret\n // `sorted[\"__proto__\"] = x` as a prototype assignment (silently dropped\n // from JSON.stringify output AND a prototype-pollution vector). Mirrors\n // the same guard in `@real-router/sources/canonicalJson`. The two\n // implementations are still intentionally divergent (see the doc-block\n // on [[canonicalJson]] above), but prototype-safety is non-negotiable\n // on both. Lock-test: scrollRestoreKey.properties.ts Invariant 11.\n const sorted = Object.create(null) as Record<string, unknown>;\n // eslint-disable-next-line unicorn/no-array-sort -- ng-packagr uses pre-ES2023 lib; toSorted unavailable\n const keys = Object.keys(val as Record<string, unknown>).sort(\n (left: string, right: string) => left.localeCompare(right),\n );\n\n for (const key of keys) {\n sorted[key] = (val as Record<string, unknown>)[key];\n }\n\n return sorted;\n }\n\n return val;\n}\n","import type { Router } from \"@real-router/core\";\n\nexport interface ViewTransitions {\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: ViewTransitions = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport function createViewTransitions(router: Router): ViewTransitions {\n if (\n typeof document === \"undefined\" ||\n typeof document.startViewTransition !== \"function\"\n ) {\n return NOOP_INSTANCE;\n }\n\n let closeVT: (() => void) | null = null;\n let currentVT: { skipTransition?: () => void } | null = null;\n // Tracks whether TRANSITION_SUCCESS fired for the current leave. Used to\n // distinguish \"benign cleanup abort\" (router's async path aborts its own\n // controller in a finally block after successful navigation) from \"real\n // cancellation\" (concurrent navigate, guard rejection, dispose).\n let successFired = false;\n\n const resolveAndClear = (): void => {\n closeVT?.();\n closeVT = null;\n };\n\n const offLeave = router.subscribeLeave(({ signal }) => {\n // Reentrant abort: signal already aborted when we're called. Open no VT\n // — router will fall through to TRANSITION_CANCELLED via isCurrentNav()\n // after leave resolves. addEventListener(\"abort\", ...) does not re-fire\n // for past events, so skipping startViewTransition is the safe path.\n if (signal.aborted) {\n return;\n }\n\n successFired = false;\n resolveAndClear();\n\n // Return a Promise so the router awaits until the browser invokes\n // updateCallback. This ensures old DOM snapshot is captured BEFORE the\n // router commits the new state — giving correct exit→state→entry\n // ordering (vs fire-and-forget, where URL changes before VT captures).\n return new Promise<void>((resolveLeave) => {\n // Capture the resolver synchronously BEFORE startViewTransition() is\n // called. The browser invokes updateCallback in a later task, but\n // router.subscribe (TRANSITION_SUCCESS) can fire before that. If we\n // captured `resolve` inside the callback, subscribe would see closeVT\n // still null and skip resolving — the deferred would hang for 4s\n // until the VT API aborts with TimeoutError.\n const deferred = new Promise<void>((resolve) => {\n closeVT = resolve;\n });\n\n signal.addEventListener(\n \"abort\",\n () => {\n if (successFired) {\n // Router's async path (#finishAsyncNavigation) aborts its own\n // controller in a finally block AFTER completeTransition (and\n // thus AFTER subscribe fired). This is cleanup, not\n // cancellation — VT is progressing normally, do nothing.\n return;\n }\n\n // Real cancellation (concurrent navigate, dispose). Resolve the\n // deferred so updateCallback can complete, skip the VT so no\n // stale animation leaks, and unblock the router if the abort\n // fires before updateCallback was invoked.\n resolveAndClear();\n currentVT?.skipTransition?.();\n resolveLeave();\n },\n { once: true },\n );\n\n try {\n currentVT = document.startViewTransition(() => {\n // Resolving here unblocks the router at the moment the browser\n // enters updateCallback — by spec, old DOM snapshot is captured\n // before this callback runs. Router now proceeds through\n // activation guards and setState; the VT animation waits on\n // `deferred`, which is resolved from router.subscribe after a\n // task-queue tick (see NOTE on setTimeout below).\n resolveLeave();\n\n return deferred;\n });\n } catch {\n // Defensive: spec says startViewTransition doesn't throw under\n // normal conditions, but Chromium has had edge cases (detached\n // document, extension interference). Clean up and unblock router.\n resolveAndClear();\n resolveLeave();\n }\n });\n });\n\n const offSuccess = router.subscribe(() => {\n const resolver = closeVT;\n\n successFired = true;\n closeVT = null;\n\n if (resolver === null) {\n currentVT = null;\n } else {\n // CRITICAL: CANNOT use requestAnimationFrame here. When the router\n // takes the async path (leave returned a Promise), subscribe fires\n // AFTER the browser has already transitioned VT into the\n // \"update-callback-called\" phase. In that phase Chromium sets\n // rendering suppression to true, which ALSO blocks rAF callbacks.\n // rAF would never fire → deferred never resolves → browser aborts\n // vt.ready with TimeoutError after 4s (observed in Chromium).\n //\n // setTimeout runs on the task queue independent of the rendering\n // pipeline, so it fires regardless of suppression. React's scheduler\n // uses MessageChannel tasks, which are queued before our setTimeout,\n // so the new DOM is committed by the time our callback runs.\n setTimeout(() => {\n resolver();\n currentVT = null;\n }, 0);\n }\n });\n\n return {\n destroy: () => {\n offLeave();\n offSuccess();\n currentVT?.skipTransition?.();\n currentVT = null;\n resolveAndClear();\n },\n };\n}\n","import type {\n NavigationOptions,\n Params,\n Router,\n State,\n} from \"@real-router/core\";\n\nexport function shouldNavigate(evt: MouseEvent): boolean {\n return (\n evt.button === 0 &&\n !evt.metaKey &&\n !evt.altKey &&\n !evt.ctrlKey &&\n !evt.shiftKey\n );\n}\n\n// Matches a single percent-escape triple (`%` + two hex digits). Used as\n// the \"already-encoded\" probe in `encodeFragmentInline` below — see the\n// idempotency rationale there.\nconst PERCENT_ESCAPE_PROBE = /%[\\dA-Fa-f]{2}/;\n\n/**\n * RFC 3986 fragment encoding: preserve sub-delims (`&`, `=`, `?`, `:`),\n * encode space, `%`, control chars, non-ASCII via encodeURI; defensively\n * escape `#` (encodeURI does not). Mirrors `encodeHashFragment` in\n * `shared/browser-env/url-context.ts` — duplicated here because the\n * shared/dom-utils symlink graph does not reach shared/browser-env.\n *\n * **Idempotency for pre-encoded input (audit-2026-05-17 §5 MEDIUM E.1).**\n * The doc-comment on `<Link hash>` says the value is a \"decoded fragment\n * without leading #\". But realistic consumers copy hashes out of\n * `location.hash` (which is percent-encoded) and pass them back, so the\n * naive `encodeURI(\"%20\")` would double-encode into `\"%2520\"` and break\n * anchor lookup. We detect a percent-escape triple in the input and, if\n * present, decode + re-encode for idempotency. Malformed `%XX` (e.g.\n * `\"%2\"` or `\"%ZZ\"`) makes `decodeURIComponent` throw — in that case we\n * fall through to plain `encodeURI`, which never throws.\n */\nfunction encodeFragmentInline(decoded: string): string {\n if (PERCENT_ESCAPE_PROBE.test(decoded)) {\n try {\n const roundtrip = decodeURIComponent(decoded);\n\n return encodeURI(roundtrip).replaceAll(\"#\", \"%23\");\n } catch {\n // Malformed `%XX` — fall through to the plain encoding path.\n // encodeURI does not throw on malformed escapes; it treats the\n // `%` as a literal and percent-encodes it (`%2` → `%252`).\n }\n }\n\n return encodeURI(decoded).replaceAll(\"#\", \"%23\");\n}\n\ntype BuildUrlFn = (\n name: string,\n params: Params,\n options?: { hash?: string },\n) => string | undefined;\n\n/**\n * Builds an href for a `<Link>` element.\n *\n * - Prefers the URL plugin's `buildUrl` (browser-plugin, navigation-plugin,\n * hash-plugin) when present.\n * - Falls back to `router.buildPath` for runtimes without a URL plugin\n * (memory-plugin, console UIs, NativeScript). In that fallback the hash\n * is appended manually so the rendered href is still correct.\n * - The optional 4th argument is an options object so the contract stays\n * extensible. The `hash` option is a decoded fragment without leading \"#\";\n * `<Link hash=\"#section\">` is accepted defensively (leading \"#\" stripped).\n * Frozen API: previous 3-arg call sites continue to work unchanged.\n */\nexport function buildHref(\n router: Router,\n routeName: string,\n routeParams: Params,\n options?: { hash?: string },\n): string | undefined {\n try {\n const rawHash = options?.hash;\n let normHash: string | undefined;\n\n if (rawHash !== undefined) {\n normHash = rawHash.startsWith(\"#\") ? rawHash.slice(1) : rawHash;\n }\n\n const buildUrl = router.buildUrl as BuildUrlFn | undefined;\n\n if (buildUrl) {\n const url = buildUrl(\n routeName,\n routeParams,\n normHash === undefined ? undefined : { hash: normHash },\n );\n\n // Accept only non-empty strings. The BuildUrlFn type contract is\n // `string | undefined`, but defensive against:\n // - `\"\"` (empty string) → would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - `null` (type-contract violation) → would render `<a href={null}>`,\n // stringified to `\"null\"` in some renderers.\n // Either case falls through to the `router.buildPath` fallback below.\n if (typeof url === \"string\" && url.length > 0) {\n return url;\n }\n }\n\n const path = router.buildPath(routeName, routeParams);\n\n // Symmetric to the buildUrl guard above (#S1 audit, Invariant 12).\n // `router.buildPath` is typed `string`, but defends against:\n // - `\"\"` (empty string) — would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - non-string type-contract violations from custom path-matchers.\n // Both yield `undefined` (renderer drops the attribute) with a warning.\n if (typeof path !== \"string\" || path.length === 0) {\n console.error(\n `[real-router] Route \"${routeName}\" yielded an empty path. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n\n return normHash ? `${path}#${encodeFragmentInline(normHash)}` : path;\n } catch {\n console.error(\n `[real-router] Route \"${routeName}\" is not defined. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n}\n\n/**\n * `<Link>` click-handler navigation helper (#532).\n *\n * Wraps `router.navigate(name, params, opts)` with same-route different-hash\n * detection: when the consumer clicks a hash-bearing Link that targets the\n * current route with the same params but a different fragment, core's\n * SAME_STATES check would otherwise reject the navigation. The helper adds\n * `force: true` and `hashChange: true` automatically — subscribers can then\n * disambiguate via `state.context.url.hashChanged`.\n *\n * For pure programmatic same-route hash-only navigation, callers are\n * documented to pass `{ force: true }` themselves; the auto-bypass here is\n * a UX convenience for `<Link hash>` that all 6 framework adapters share.\n */\n/**\n * Local extended-options type. Adapters that depend only on `@real-router/core`\n * (without a URL plugin) do not see the `NavigationOptions` augmentation that\n * declares `hash` / `hashChange`. Casting to this widened type inside the\n * helper keeps shared/dom-utils self-contained — adapters do not need to\n * augment NavigationOptions themselves to consume `<Link hash>`.\n */\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\nexport function navigateWithHash(\n router: Router,\n routeName: string,\n routeParams: Params,\n hash: string | undefined,\n extraOptions?: NavigationOptions,\n): Promise<State> {\n const opts: HashAwareNavigationOptions = { ...extraOptions };\n\n if (hash !== undefined) {\n opts.hash = hash;\n }\n\n const current = router.getState();\n\n if (\n current?.name === routeName &&\n shallowEqual(current.params, routeParams)\n ) {\n const currentHash =\n (current.context as { url?: { hash?: string } } | undefined)?.url?.hash ??\n \"\";\n const newHash = hash ?? currentHash;\n\n if (currentHash !== newHash) {\n opts.force = true;\n opts.hashChange = true;\n }\n }\n\n return router.navigate(routeName, routeParams, opts);\n}\n\n// Match-any-whitespace regex shared across calls. RegExp literals at\n// call-site recompile in some engines; lifting it avoids that microcost\n// for the slow-path branch.\nconst WHITESPACE_PROBE = /\\s/;\nconst WHITESPACE_SPLIT = /\\S+/g;\n\nfunction parseTokens(value: string | undefined): string[] {\n if (!value) {\n return [];\n }\n\n // Hot-path fast-path (audit-2026-05-17 §8b #1): >99% of active-class\n // inputs at `<Link>` emit are single-token strings like `\"active\"` or\n // `\"is-current\"` — no whitespace, no leading/trailing pad. Skip the\n // regex match and Array result allocation: a literal `[value]` works\n // because the slow-path `match(/\\S+/g)` would return exactly `[value]`\n // for the same input. PBT lock: linkUtils.properties.ts Invariant 13.\n if (!WHITESPACE_PROBE.test(value)) {\n return [value];\n }\n\n return value.match(WHITESPACE_SPLIT) ?? [];\n}\n\nexport function buildActiveClassName(\n isActive: boolean,\n activeClassName: string | undefined,\n baseClassName: string | undefined,\n): string | undefined {\n if (isActive && activeClassName) {\n const activeTokens = parseTokens(activeClassName);\n\n if (activeTokens.length === 0) {\n return baseClassName ?? undefined;\n }\n if (!baseClassName) {\n return activeTokens.join(\" \");\n }\n\n const baseTokens = parseTokens(baseClassName);\n const seen = new Set(baseTokens);\n\n for (const token of activeTokens) {\n if (!seen.has(token)) {\n seen.add(token);\n baseTokens.push(token);\n }\n }\n\n return baseTokens.join(\" \");\n }\n\n return baseClassName ?? undefined;\n}\n\n/**\n * One-level structural equality using `Object.is` per key.\n *\n * **String-keyed properties only (Mini-sprint E.3 — audit-5 §4.2 #3).**\n * Implementation walks `Object.keys()` which by spec returns only\n * enumerable own STRING keys. Symbol-keyed properties — created via\n * `obj[Symbol(\"brand\")] = value` or `{ [Symbol(...)]: value }` — are\n * NOT compared. Two records that differ only in a Symbol-keyed value\n * will compare as equal.\n *\n * This is intentional: route params and Link options are documented as\n * string-keyed primitives (string | number | boolean) — Symbol-keyed\n * metadata (e.g. brand markers, private state) doesn't belong in a\n * cache-key comparison. Switching to `Reflect.ownKeys()` would extend\n * the contract to symbols at the cost of one extra allocation per call\n * (Reflect.ownKeys composes string-keys + symbol-keys arrays). If a\n * consumer relies on symbol-keyed metadata for navigation\n * disambiguation, they should encode it into a string key instead.\n *\n * Mirrors React's `shallowEqual` (packages/shared/shallowEqual.js) in\n * both the string-keys-only semantics and the `hasOwnProperty` guard\n * below.\n */\nexport function shallowEqual(\n prev: object | undefined,\n next: object | undefined,\n): boolean {\n if (Object.is(prev, next)) {\n return true;\n }\n if (!prev || !next) {\n return false;\n }\n\n const prevKeys = Object.keys(prev);\n\n if (prevKeys.length !== Object.keys(next).length) {\n return false;\n }\n\n const prevRecord = prev as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n\n for (const key of prevKeys) {\n // hasOwnProperty guard: without it, a key missing in `next` reads as\n // `undefined` and falsely matches `prev[key] === undefined`. Same shape\n // as React's shallowEqual (packages/shared/shallowEqual.js).\n if (\n !Object.prototype.hasOwnProperty.call(next, key) ||\n !Object.is(prevRecord[key], nextRecord[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function applyLinkA11y(element: HTMLElement | null | undefined): void {\n if (!element) {\n return;\n }\n\n // Cross-realm safety (audit-2026-05-17 §5 HIGH #4):\n // `instanceof HTMLAnchorElement` compares against the constructor from\n // the CURRENT realm. An element created in a different window (iframe\n // contentDocument, micro-frontend, embedded widget) fails the check\n // even when it IS a real anchor — the helper would then inject\n // role=\"link\" + tabindex=\"0\" on top of native anchor semantics,\n // breaking screen reader output (\"link link\") and focus order.\n //\n // tagName is realm-agnostic and is uppercase for HTML-namespaced\n // elements in any document. SVG `<a>` has lowercase tagName plus a\n // different prototype (SVGAElement) — skipping it here is wrong by\n // accident: SVG anchors don't have keyboard activation semantics the\n // helper would add. But they also don't reach this helper in\n // practice (router Link components emit HTML anchors). Lock the\n // uppercase compare to keep the contract narrow.\n const tag = element.tagName;\n\n if (tag === \"A\" || tag === \"BUTTON\") {\n return;\n }\n if (!element.hasAttribute(\"role\")) {\n element.setAttribute(\"role\", \"link\");\n }\n if (!element.hasAttribute(\"tabindex\")) {\n element.setAttribute(\"tabindex\", \"0\");\n }\n}\n","import { createActiveRouteSource } from \"@real-router/sources\";\nimport { useMemo, useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { Params } from \"@real-router/core\";\n\nexport function useIsActiveRoute(\n routeName: string,\n params?: Params,\n strict = false,\n ignoreQueryParams = true,\n hash?: string,\n): boolean {\n const router = useRouter();\n\n // createActiveRouteSource is per-router + canonical-args cached in\n // @real-router/sources, so passing params by reference is safe — equivalent\n // param shapes hit the same cache entry regardless of key order. The\n // `hash` argument (#532) is part of the cache key when defined: a Link\n // pointing to `/settings#account` shares its source only with other\n // consumers using the same routeName + params + hash.\n //\n // The useMemo wrap skips `canonicalJson(params)` + cache lookup on every\n // render when all primitive deps and the `params` reference are stable —\n // the common case once memo()+shallowEqual has bailed out further up\n // (or when the parent re-renders for a non-Link reason). For inline\n // `params={{id:1}}` the dep changes per render and the lookup still\n // runs, but that path was already the slow path before this memo.\n // exactOptionalPropertyTypes forbids `{ hash: undefined }` literally, so\n // we conditionally spread the key only when the caller passed a value.\n const store = useMemo(\n () =>\n createActiveRouteSource(router, routeName, params, {\n strict,\n ignoreQueryParams,\n ...(hash !== undefined && { hash }),\n }),\n [router, routeName, params, strict, ignoreQueryParams, hash],\n );\n\n return useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n}\n","import { createDismissableError } from \"@real-router/sources\";\nimport {\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\n\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { RouterError, State } from \"@real-router/core\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nexport interface RouterErrorBoundaryProps {\n readonly children: ReactNode;\n readonly fallback: (error: RouterError, resetError: () => void) => ReactNode;\n readonly onError?: (\n error: RouterError,\n toRoute: State | null,\n fromRoute: State | null,\n ) => void;\n}\n\nexport function RouterErrorBoundary({\n children,\n fallback,\n onError,\n}: RouterErrorBoundaryProps): ReactElement {\n const router = useRouter();\n // Per-router cached in @real-router/sources — the WeakMap lookup is cheap,\n // but useMemo avoids it entirely on stable-router re-renders (the common\n // case for boundaries mounted in app shells).\n const store = useMemo(() => createDismissableError(router), [router]);\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n\n const onErrorRef = useRef(onError);\n\n // \"Latest ref\" pattern shared with useRouteEnter/useRouteExit: sync the\n // callback to the ref via useLayoutEffect (synchronous, post-render,\n // pre-paint) so the snapshot effect below reads the freshest callback\n // without listing `onError` as a dep — and StrictMode's double-effect\n // pass writes the same value twice harmlessly.\n useLayoutEffect(() => {\n onErrorRef.current = onError;\n });\n\n useEffect(() => {\n if (snapshot.error) {\n onErrorRef.current?.(\n snapshot.error,\n snapshot.toRoute,\n snapshot.fromRoute,\n );\n }\n // eslint-disable-next-line @eslint-react/exhaustive-deps -- onError tracked via ref, snapshot fields accessed inside callback\n }, [snapshot.version]);\n\n return (\n <>\n {children}\n {snapshot.error ? fallback(snapshot.error, snapshot.resetError) : null}\n </>\n );\n}\n","import { useContext } from \"react\";\n\nimport { NavigatorContext } from \"../context\";\n\nimport type { Navigator } from \"@real-router/core\";\n\nexport const useNavigator = (): Navigator => {\n const navigator = useContext(NavigatorContext);\n\n if (!navigator) {\n throw new Error(\"useNavigator must be used within a RouterProvider\");\n }\n\n return navigator;\n};\n","import { getPluginApi } from \"@real-router/core/api\";\nimport { getRouteUtils } from \"@real-router/route-utils\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouteUtils } from \"@real-router/route-utils\";\n\n/**\n * Returns a pre-computed {@link RouteUtils} instance for the current router.\n *\n * `getRouteUtils` is WeakMap-cached per `RouteTreeNode` inside\n * `@real-router/route-utils`, so the same router always returns the same\n * `RouteUtils` instance across renders — no local cache needed in the adapter.\n *\n * @returns RouteUtils instance with pre-computed chains and siblings\n *\n * @example\n * ```tsx\n * const utils = useRouteUtils();\n *\n * utils.getChain(\"users.profile\");\n * // → [\"users\", \"users.profile\"]\n *\n * utils.getSiblings(\"users\");\n * // → [\"admin\"]\n *\n * utils.isDescendantOf(\"users.profile\", \"users\");\n * // → true\n * ```\n */\nexport const useRouteUtils = (): RouteUtils => {\n const router = useRouter();\n\n return getRouteUtils(getPluginApi(router).getTree());\n};\n","import { getTransitionSource } from \"@real-router/sources\";\nimport { useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouterTransitionSnapshot } from \"@real-router/sources\";\n\nexport function useRouterTransition(): RouterTransitionSnapshot {\n const router = useRouter();\n const store = getTransitionSource(router);\n\n return useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n}\n","import { getNavigator } from \"@real-router/core\";\nimport { createRouteSource } from \"@real-router/sources\";\nimport { useEffect, useMemo, useSyncExternalStore } from \"react\";\n\nimport { NavigatorContext, RouteContext, RouterContext } from \"./context\";\nimport {\n createRouteAnnouncer,\n createScrollRestoration,\n createViewTransitions,\n} from \"./dom-utils\";\n\nimport type { ScrollRestorationOptions } from \"./dom-utils\";\nimport type { Router } from \"@real-router/core\";\nimport type { FC, ReactNode } from \"react\";\n\nexport interface RouteProviderProps {\n router: Router;\n children: ReactNode;\n announceNavigation?: boolean;\n scrollRestoration?: ScrollRestorationOptions;\n viewTransitions?: boolean;\n}\n\nexport const RouterProvider: FC<RouteProviderProps> = ({\n router,\n children,\n announceNavigation,\n scrollRestoration,\n viewTransitions,\n}) => {\n useEffect(() => {\n if (!announceNavigation) {\n return;\n }\n\n const announcer = createRouteAnnouncer(router);\n\n return () => {\n announcer.destroy();\n };\n }, [announceNavigation, router]);\n\n // Primitive deps so inline `{ mode: \"restore\" }` doesn't thrash on every\n // render. scrollContainer is a getter invoked lazily on every event inside\n // the utility — swapping its reference doesn't change the resolved element,\n // so we intentionally omit it from deps to keep inline getters stable.\n const srMode = scrollRestoration?.mode;\n const srAnchor = scrollRestoration?.anchorScrolling;\n const srBehavior = scrollRestoration?.behavior;\n const srStorageKey = scrollRestoration?.storageKey;\n const srEnabled = scrollRestoration !== undefined;\n\n useEffect(() => {\n if (!srEnabled) {\n return;\n }\n\n const sr = createScrollRestoration(router, {\n mode: srMode,\n anchorScrolling: srAnchor,\n behavior: srBehavior,\n storageKey: srStorageKey,\n // srEnabled check above guarantees scrollRestoration is defined.\n scrollContainer: scrollRestoration.scrollContainer,\n });\n\n return () => {\n sr.destroy();\n };\n // scrollRestoration (for scrollContainer) omitted — see comment above.\n // eslint-disable-next-line @eslint-react/exhaustive-deps\n }, [router, srEnabled, srMode, srAnchor, srBehavior, srStorageKey]);\n\n useEffect(() => {\n if (!viewTransitions) {\n return;\n }\n\n const vt = createViewTransitions(router);\n\n return () => {\n vt.destroy();\n };\n }, [router, viewTransitions]);\n\n const navigator = useMemo(() => getNavigator(router), [router]);\n\n // useSyncExternalStore manages the router subscription lifecycle:\n // subscribe connects to router on first listener, unsubscribes on last.\n // This is Strict Mode safe — no useEffect cleanup needed.\n const store = useMemo(() => createRouteSource(router), [router]);\n // Use snapshot reference directly. createRouteSource via stabilizeState\n // returns the SAME snapshot reference when route.path is unchanged, so\n // useMemo below sees stable deps for idempotent navigations and\n // RouteContext consumers do not re-render.\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot, // SSR: router returns same state on server and client\n );\n\n const routeContextValue = useMemo(\n () => ({\n navigator,\n route: snapshot.route,\n previousRoute: snapshot.previousRoute,\n }),\n [navigator, snapshot],\n );\n\n return (\n <RouterContext.Provider value={router}>\n <NavigatorContext.Provider value={navigator}>\n <RouteContext.Provider value={routeContextValue}>\n {children}\n </RouteContext.Provider>\n </NavigatorContext.Provider>\n </RouterContext.Provider>\n );\n};\n"],"mappings":"0OAMA,MAAa,MAA0B,CACrC,IAAM,GAAA,EAAA,EAAA,YAAoBA,EAAAA,EAAc,CAExC,GAAI,CAAC,EACH,MAAU,MAAM,iDAAiD,CAGnE,OAAO,GCLT,SAAgB,EAAa,EAAgC,CAC3D,IAAM,EAAS,GAAW,CAEpB,GAAA,EAAA,EAAA,cAAA,EAAA,EAAA,uBACwB,EAAQ,EAAS,CAC7C,CAAC,EAAQ,EAAS,CACnB,CAKK,GAAA,EAAA,EAAA,sBACJ,EAAM,UACN,EAAM,YACN,EAAM,YACP,CAGK,GAAA,EAAA,EAAA,cAAyB,EAAO,CAEtC,OAAA,EAAA,EAAA,cACuB,CACnB,YACA,MAAO,EAAS,MAChB,cAAe,EAAS,cACzB,EACD,CAAC,EAAW,EAAS,CACtB,CCjCH,MAEM,EAAiB,6BAUjBC,EAAyC,OAAO,OAAO,CAC3D,YAAe,GAGhB,CAAC,CAEF,SAAgB,EACd,EACA,EACyB,CAUzB,GAAI,OAAO,SAAa,IACtB,OAAOA,EAGT,IAAM,EAAS,GAAS,QAAU,gBAC5B,EAAgB,GAAS,oBAE3B,EAAsB,GACtB,EAAU,GACV,EAAc,GACd,EAAoB,GACpB,EAA6B,KAC7B,EAEE,EAAY,GAAsB,CAElC,GAAc,EAAc,IAAiC,CACjE,EAAoB,EACpB,aAAa,EAAe,CAC5B,EAAU,YAAc,EACxB,EAAiB,eAAiB,CAChC,EAAU,YAAc,GACxB,EAAoB,IACnB,IAAY,CAEf,EAAY,EAAG,EAOX,EAAkB,eAAiB,CAGvC,GAFA,EAAU,GAEN,IAAgB,MAAQ,CAAC,EAAa,CACxC,IAAM,EAAO,EAEb,EAAc,KACd,EAAW,EAAM,SAAS,cAA2B,KAAK,CAAC,GAE5D,IAAmB,CAEhB,EAAc,EAAO,WAAW,CAAE,WA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,MAAO,EAC3B,WACqB,CAAA,CACE,CAAA,CACL,CAAA"}
@@ -0,0 +1,2 @@
1
+ const e=require(`./useRoute-Dudo2K_0.js`);let t=require(`react`),n=require(`react/jsx-runtime`);function r({children:e,fallback:n=null}){let[r,i]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{i(!0)},[]),r?e:n}function i({children:e,fallback:n=null}){let[r,i]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{i(!0)},[]),r?n:e}function a(t){let{route:n}=e.t();return n.context.ssrDataDeferred?.[t]??e.i}function o({fallback:e,children:r}){return(0,n.jsx)(t.Suspense,{fallback:e,children:r})}const s=(0,t.createContext)(null);function c({sink:e,children:t}){return(0,n.jsx)(s.Provider,{value:e,children:t})}function l({code:e}){let n=(0,t.useContext)(s);return n&&(n.code=e),null}function u(){return{code:void 0}}Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return u}});
2
+ //# sourceMappingURL=createHttpStatusSink-D_6IiR5E.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createHttpStatusSink-D_6IiR5E.js","names":["useRoute","NEVER_PROMISE","Suspense"],"sources":["../../src/components/ClientOnly.tsx","../../src/components/ServerOnly.tsx","../../src/hooks/useDeferred.tsx","../../src/components/Streamed.tsx","../../src/components/HttpStatusProvider.tsx","../../src/components/HttpStatusCode.tsx","../../src/utils/createHttpStatusSink.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ClientOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ClientOnly({\n children,\n fallback = null,\n}: ClientOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the fallback branch, client matches\n // it on first paint, then this effect flips state to swap in the children.\n // The intentional re-render is what makes the markup match across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? children : fallback;\n}\n","import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ServerOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ServerOnly({\n children,\n fallback = null,\n}: ServerOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the children branch, client matches\n // it on first paint, then this effect flips state to swap in the fallback\n // (or hide entirely). The intentional re-render keeps markup consistent\n // across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? fallback : children;\n}\n","import { NEVER_PROMISE } from \"../constants\";\nimport { useRoute } from \"./useRoute\";\n\ninterface DeferredContext {\n ssrDataDeferred?: Record<string, Promise<unknown>>;\n}\n\n/**\n * Read a deferred promise published by `defer({ deferred: { <key>: Promise } })`\n * inside an SSR data loader.\n *\n * - **Server render**: returns the actual loader-returned promise. Combine\n * with `<Suspense>` + `use(promise)` for native streaming via React 19's\n * `renderToReadableStream`.\n * - **Post-hydration**: returns a registry-backed promise; the inline\n * `<script>__rrDefer__(\"key\", json)</script>` tags emitted by the server\n * stream resolve it. `use()` returns synchronously once the registry\n * settles.\n * - **Unknown key**: returns a never-resolving promise — Suspense boundary\n * stays in fallback. This surfaces consumer/loader key drift as a visible\n * loading state instead of a silent runtime error.\n *\n * The hook subscribes to `RouteContext`, so it re-runs on every navigation.\n * Promise reference identity is stable across renders within the same\n * navigation — `use()` will not re-suspend on rerenders.\n */\nexport function useDeferred<T = unknown>(key: string): Promise<T> {\n const { route } = useRoute();\n const context = route.context as DeferredContext;\n const deferred = context.ssrDataDeferred;\n const promise = deferred?.[key];\n\n return (promise ?? NEVER_PROMISE) as Promise<T>;\n}\n","import { Suspense } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface StreamedProps {\n /** Shown while any descendant `use(promise)` / `<Await>` is pending. */\n readonly fallback: ReactNode;\n readonly children: ReactNode;\n}\n\n/**\n * Cross-adapter alias for `<Suspense fallback={…}>`. Pairs with `<Await>`\n * for symmetry with `<Streamed>` boundaries in the SvelteKit / Solid\n * deferred-data conventions.\n *\n * ```tsx\n * <Streamed fallback={<Spinner />}>\n * <Await<Review[]> name=\"reviews\">\n * {(reviews) => <ReviewList items={reviews} />}\n * </Await>\n * </Streamed>\n * ```\n *\n * The component is a thin wrapper around React's native `<Suspense>` — no\n * additional behaviour. Use plain `<Suspense>` directly if you don't need\n * the cross-framework naming alignment.\n */\nexport function Streamed({ fallback, children }: StreamedProps): ReactNode {\n return <Suspense fallback={fallback}>{children}</Suspense>;\n}\n","import { createContext } from \"react\";\n\nimport type { HttpStatusSink } from \"../utils/createHttpStatusSink\";\nimport type { ReactNode } from \"react\";\n\nexport const HttpStatusContext = createContext<HttpStatusSink | null>(null);\n\nexport interface HttpStatusProviderProps {\n readonly sink: HttpStatusSink;\n readonly children: ReactNode;\n}\n\nexport function HttpStatusProvider({\n sink,\n children,\n}: HttpStatusProviderProps): ReactNode {\n // `<HttpStatusContext.Provider value>` (not the React 19 `<HttpStatusContext value>`\n // shorthand) — same component file is exported via `/legacy/ssr` for React 18\n // consumers, where the shorthand throws \"Element type is invalid: expected\n // a string but got: object\".\n return (\n <HttpStatusContext.Provider value={sink}>\n {children}\n </HttpStatusContext.Provider>\n );\n}\n","import { useContext } from \"react\";\n\nimport { HttpStatusContext } from \"./HttpStatusProvider\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface HttpStatusCodeProps {\n /** HTTP status to apply to the response. Common values: 404, 410, 451, 503. */\n readonly code: number;\n}\n\n/**\n * Render-time HTTP status declaration. Mount inside a route component (typical\n * use case: a glob `*` route's NotFound page) when the status is decided by\n * the rendered tree rather than a loader.\n *\n * Writes `code` to the nearest `<HttpStatusProvider>`'s sink during render and\n * returns `null`. With no provider mounted (the standard client-side case)\n * the component is a silent no-op — same component tree hydrates without\n * touching the DOM or warning about mismatches.\n *\n * Loader-driven errors (`LoaderNotFound` → 404, `LoaderRedirect` → 30x) keep\n * working as before; this component covers render-time decisions only.\n *\n * Last write wins when several `<HttpStatusCode />` instances mount in the\n * same render pass — sink reflects the last component that ran.\n *\n * ```tsx\n * // entry-server.tsx\n * import { renderToString } from \"react-dom/server\";\n * import { createHttpStatusSink, HttpStatusProvider } from \"@real-router/react/ssr\";\n *\n * const sink = createHttpStatusSink();\n * const html = renderToString(\n * <HttpStatusProvider sink={sink}>\n * <RouterProvider router={router}>\n * <App />\n * </RouterProvider>\n * </HttpStatusProvider>,\n * );\n * response.status(sink.code ?? 200).send(html);\n * ```\n *\n * **Streaming SSR (`renderToReadableStream`):** the response status MUST be\n * sent before the first body byte flushes. If `<HttpStatusCode />` is mounted\n * inside a late-resolving `<Suspense>` boundary, the sink write may happen\n * AFTER the headers are already on the wire — the override is then lost.\n * Either mount the component in the shell (above every `<Suspense>` that\n * could delay it) or `await stream.allReady` before reading `sink.code`\n * (which forfeits streaming benefits). For non-streaming SSR\n * (`renderToString`) there is no such ordering concern.\n *\n * **Valid `code` range:** Node's `res.end()` throws `Invalid status code` on\n * `NaN`, `0`, negative values, or values `> 999` — this surfaces as a 5xx /\n * dropped connection, not silent corruption. Pass a real HTTP status integer\n * (commonly 4xx/5xx; 100-999 is what Node accepts).\n */\nexport function HttpStatusCode({ code }: HttpStatusCodeProps): ReactNode {\n const sink = useContext(HttpStatusContext);\n\n if (sink) {\n sink.code = code;\n }\n\n return null;\n}\n","/**\n * Render-scoped HTTP status sink. Created per request on the server, passed to\n * `<HttpStatusProvider sink={...}>`, and read after `renderToString` /\n * `renderToReadableStream` to apply the value to the HTTP response.\n *\n * Last write wins: if the rendered tree mounts more than one\n * `<HttpStatusCode />`, the value reflects the last component that ran during\n * the render pass.\n *\n * No-op on the client — `<HttpStatusCode />` reads the optional context and\n * skips the write when no provider is mounted, so the same component tree can\n * be hydrated without changing behaviour.\n *\n * Constraints:\n * - **Per-request only.** Don't share a sink across requests; the rendered\n * tree mutates `code` in place. Module-level singletons leak status\n * between concurrent requests.\n * - **Don't `Object.freeze` the sink.** The component writes to `.code`;\n * freezing makes the assignment throw under ESM strict mode.\n */\nexport interface HttpStatusSink {\n code: number | undefined;\n}\n\nexport function createHttpStatusSink(): HttpStatusSink {\n return { code: undefined };\n}\n"],"mappings":"gGASA,SAAgB,EAAW,CACzB,WACA,WAAW,MACkB,CAC7B,GAAM,CAAC,EAAS,IAAA,EAAA,EAAA,UAAuB,GAAM,CAU7C,OARA,EAAA,EAAA,eAAgB,CAKd,EAAW,GAAK,EACf,EAAE,CAAC,CAEC,EAAU,EAAW,ECd9B,SAAgB,EAAW,CACzB,WACA,WAAW,MACkB,CAC7B,GAAM,CAAC,EAAS,IAAA,EAAA,EAAA,UAAuB,GAAM,CAW7C,OATA,EAAA,EAAA,eAAgB,CAMd,EAAW,GAAK,EACf,EAAE,CAAC,CAEC,EAAU,EAAW,ECE9B,SAAgB,EAAyB,EAAyB,CAChE,GAAM,CAAE,SAAUA,EAAAA,GAAU,CAK5B,OAJgB,EAAM,QACG,kBACE,IAERC,EAAAA,ECLrB,SAAgB,EAAS,CAAE,WAAU,YAAsC,CACzE,OAAO,EAAA,EAAA,KAACC,EAAAA,SAAD,CAAoB,WAAW,WAAoB,CAAA,CCvB5D,MAAa,GAAA,EAAA,EAAA,eAAyD,KAAK,CAO3E,SAAgB,EAAmB,CACjC,OACA,YACqC,CAKrC,OACE,EAAA,EAAA,KAAC,EAAkB,SAAnB,CAA4B,MAAO,EAChC,WAC0B,CAAA,CCkCjC,SAAgB,EAAe,CAAE,QAAwC,CACvE,IAAM,GAAA,EAAA,EAAA,YAAkB,EAAkB,CAM1C,OAJI,IACF,EAAK,KAAO,GAGP,KCxCT,SAAgB,GAAuC,CACrD,MAAO,CAAE,KAAM,IAAA,GAAW"}
@@ -1,282 +1,7 @@
1
- import { a as useNavigator, c as RouterErrorBoundaryProps, i as useRouteUtils, l as LinkProps, n as useRouteNode, o as useRouter, r as useRoute, s as RouterErrorBoundary, t as useRouterTransition } from "./useRouterTransition-BYit_9Mt.js";
2
- import { n as Link, t as RouterProvider } from "./RouterProvider-Bj1_NbpA.js";
3
- import { ReactElement, ReactNode } from "react";
4
- import { Navigator, State } from "@real-router/core";
1
+ import { a as RouteExitContext, c as useRouteExit, d as NotFoundProps, f as RouteViewProps, i as useRouteEnter, l as RouteView, n as RouteEnterHandler, o as RouteExitHandler, p as SelfProps, r as UseRouteEnterOptions, s as UseRouteExitOptions, t as RouteEnterContext, u as MatchProps } from "./useRouteEnter-gfy65W0D.js";
2
+ import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-BlJmaoyr.js";
3
+ import { n as Link, t as RouterProvider } from "./RouterProvider-DvC9mViF.js";
4
+ import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-BfayPs0h.js";
5
+ import { Navigator } from "@real-router/core";
5
6
  import { RouterTransitionSnapshot } from "@real-router/sources";
6
-
7
- //#region src/components/modern/RouteView/types.d.ts
8
- interface RouteViewProps {
9
- /** Route tree node name to subscribe to. "" for root. */
10
- readonly nodeName: string;
11
- /** <RouteView.Match>, <RouteView.Self>, and <RouteView.NotFound> elements. */
12
- readonly children: ReactNode;
13
- }
14
- interface MatchProps {
15
- /** Route segment to match against. */
16
- readonly segment: string;
17
- /** Exact match only (no descendants). Defaults to false. */
18
- readonly exact?: boolean;
19
- /** Preserve component state when deactivated (React Activity). Defaults to false. */
20
- readonly keepAlive?: boolean;
21
- /** Fallback content to show while children are suspended. */
22
- readonly fallback?: ReactNode;
23
- /** Content to render when matched. */
24
- readonly children: ReactNode;
25
- }
26
- interface SelfProps {
27
- /**
28
- * Fallback content to show while children are suspended.
29
- *
30
- * Symmetric with `<RouteView.Match fallback>` — wraps children in
31
- * `<Suspense>` when defined.
32
- */
33
- readonly fallback?: ReactNode;
34
- /** Content to render when the active route name equals the parent RouteView's nodeName. */
35
- readonly children: ReactNode;
36
- }
37
- interface NotFoundProps {
38
- /** Content to render on UNKNOWN_ROUTE. */
39
- readonly children: ReactNode;
40
- }
41
- //#endregion
42
- //#region src/components/modern/RouteView/components.d.ts
43
- declare function Match(_props: MatchProps): null;
44
- declare namespace Match {
45
- var displayName: string;
46
- }
47
- declare function Self(_props: SelfProps): null;
48
- declare namespace Self {
49
- var displayName: string;
50
- }
51
- declare function NotFound(_props: NotFoundProps): null;
52
- declare namespace NotFound {
53
- var displayName: string;
54
- }
55
- //#endregion
56
- //#region src/components/modern/RouteView/RouteView.d.ts
57
- declare function RouteViewRoot({
58
- nodeName,
59
- children
60
- }: Readonly<RouteViewProps>): ReactElement | null;
61
- declare namespace RouteViewRoot {
62
- var displayName: string;
63
- }
64
- declare const RouteView: typeof RouteViewRoot & {
65
- Match: typeof Match;
66
- Self: typeof Self;
67
- NotFound: typeof NotFound;
68
- };
69
- //#endregion
70
- //#region src/hooks/useRouteExit.d.ts
71
- interface RouteExitContext {
72
- /** The route being left. */
73
- route: State;
74
- /** The route being navigated to. */
75
- nextRoute: State;
76
- /**
77
- * AbortSignal that fires when this navigation is superseded by a later
78
- * one (rapid clicks). Already filtered: when the handler runs,
79
- * `signal.aborted` is guaranteed to be `false`. Use
80
- * `signal.addEventListener("abort", cleanup, { once: true })` for
81
- * cleanup that must run on cancellation.
82
- */
83
- signal: AbortSignal;
84
- }
85
- interface UseRouteExitOptions {
86
- /**
87
- * Skip the handler when `route.name === nextRoute.name`
88
- * (sort/filter/query-only navigations on the same route). Default:
89
- * `true`.
90
- */
91
- skipSameRoute?: boolean;
92
- }
93
- type RouteExitHandler = (context: RouteExitContext) => void | Promise<void>;
94
- /**
95
- * Subscribe to the router's leave-window with the universal guards baked
96
- * in. Wraps `router.subscribeLeave` so consumers don't repeat the same
97
- * boilerplate every time:
98
- *
99
- * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`
100
- * when the handler would run (rapid navigation superseded a slower
101
- * one), the handler is skipped entirely. `signal.addEventListener(
102
- * "abort", ...)` does not fire retroactively, so without this guard
103
- * downstream cleanup would never trigger.
104
- * - **Same-route skip**: by default, `route.name === nextRoute.name`
105
- * short-circuits the handler — query-only navigations (sort, filter,
106
- * pagination) skip the work. Opt out with `skipSameRoute: false`.
107
- * - **Stable handler reference**: the handler can change identity on
108
- * every render without causing resubscription — internal ref keeps
109
- * the latest handler accessible to the long-lived subscription.
110
- *
111
- * Returns nothing — the subscription's lifecycle is bound to the
112
- * component's mount.
113
- *
114
- * If the handler returns a Promise, the router blocks on it. If the
115
- * Promise resolves, navigation proceeds. If it rejects, the router emits
116
- * `TRANSITION_CANCELLED` (existing core behavior, no change here).
117
- *
118
- * @example Animation
119
- * ```tsx
120
- * const ref = useRef<HTMLDivElement>(null);
121
- *
122
- * useRouteExit(async ({ signal }) => {
123
- * const el = ref.current;
124
- * if (!el) return;
125
- * el.classList.add("fade-out");
126
- * const cleanup = () => el.classList.remove("fade-out");
127
- * signal.addEventListener("abort", cleanup, { once: true });
128
- * try {
129
- * el.getBoundingClientRect(); // style flush
130
- * await Promise.allSettled(el.getAnimations().map((a) => a.finished));
131
- * } finally {
132
- * cleanup();
133
- * }
134
- * });
135
- * ```
136
- *
137
- * @example Auto-save form draft
138
- * ```tsx
139
- * useRouteExit(async ({ signal }) => {
140
- * if (formState.dirty) await api.saveDraft(formState, { signal });
141
- * });
142
- * ```
143
- *
144
- * @example Cancel inflight requests
145
- * ```tsx
146
- * useRouteExit(() => {
147
- * inflightController.abort();
148
- * });
149
- * ```
150
- *
151
- * @example Library-coordinated exit (motion / framer-motion)
152
- * ```tsx
153
- * const exitResolverRef = useRef<(() => void) | null>(null);
154
- *
155
- * useRouteExit(({ signal }) => {
156
- * return new Promise<void>((resolve) => {
157
- * exitResolverRef.current = resolve;
158
- * signal.addEventListener("abort", () => resolve(), { once: true });
159
- * });
160
- * });
161
- *
162
- * const onExitComplete = () => exitResolverRef.current?.();
163
- * // pass onExitComplete to <AnimatePresence>
164
- * ```
165
- *
166
- * @example Reading rich transition metadata via `nextRoute.transition`
167
- * ```tsx
168
- * useRouteExit(({ route, nextRoute }) => {
169
- * // nextRoute.transition: TransitionMeta — preview of the upcoming nav
170
- * if (nextRoute.transition.segments.deactivated.includes("products")) {
171
- * // leaving the products subtree entirely — flush product-related caches
172
- * productCache.clear();
173
- * }
174
- * if (nextRoute.transition.redirected) {
175
- * // skip animation when navigation arrived via redirect
176
- * return;
177
- * }
178
- * });
179
- * ```
180
- */
181
- declare function useRouteExit(handler: RouteExitHandler, options?: UseRouteExitOptions): void;
182
- //#endregion
183
- //#region src/hooks/useRouteEnter.d.ts
184
- interface RouteEnterContext {
185
- /** The route that was just activated. */
186
- route: State;
187
- /** The route that was active immediately before this navigation. */
188
- previousRoute: State;
189
- }
190
- type RouteEnterHandler = (context: RouteEnterContext) => void;
191
- interface UseRouteEnterOptions {
192
- /**
193
- * Skip the handler when `route.name === previousRoute.name`
194
- * (sort/filter/query-only navigations on the same route). Default:
195
- * `true`. Symmetric with `useRouteExit`'s same-name option.
196
- */
197
- skipSameRoute?: boolean;
198
- }
199
- /**
200
- * Fire `handler` once when the component mounts as a result of a
201
- * navigation. Mirror of `useRouteExit` for the entry side.
202
- *
203
- * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:
204
- *
205
- * - **Skip-initial**: handler is skipped when there is no
206
- * `previousRoute` (i.e. first-load mount). Most consumers want to
207
- * fire side effects only on real navigations, not on hydration.
208
- * - **Same-route skip** (default): handler is skipped when
209
- * `route.name === previousRoute.name`. Sort/filter/query-only
210
- * navigations re-run the effect (because `route` reference changes
211
- * in `useRoute`'s snapshot), but they are not "entries" in the
212
- * animation / analytics sense — the component instance has stayed
213
- * mounted throughout. Opt out with `skipSameRoute: false` when
214
- * the handler legitimately needs to fire on every navigation
215
- * (e.g. analytics tracking each query-param flip).
216
- * - **StrictMode double-mount immunity**: in dev, React's StrictMode
217
- * runs every effect twice to surface bugs. Without a guard,
218
- * analytics fire twice, animations restart, focus jumps. The hook
219
- * tracks the last-handled `route` reference and short-circuits the
220
- * second pass.
221
- * - **Latest-handler ref**: the handler can change identity on every
222
- * render without re-running the effect — the registered wrapper
223
- * dispatches to whatever `handlerRef.current` points to.
224
- * - **Mount-time `route` / `previousRoute` snapshot**: the handler
225
- * receives the values that were live at the moment of mount, not
226
- * the latest ones (which may have moved on if the user navigated
227
- * again before the effect drained).
228
- *
229
- * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from
230
- * `@real-router/sources`, so by the time the new component's effect
231
- * runs, the snapshot is the post-commit one. This is the reason we can
232
- * read mount-time context from `useRoute()` instead of subscribing to
233
- * `router.subscribe` directly (which fires before React schedules a
234
- * re-render — the well-known race in distributed components).
235
- *
236
- * @example Direction-aware entry animation
237
- * ```tsx
238
- * useRouteEnter(({ route }) => {
239
- * const direction = route.context.browser?.direction;
240
- * ref.current?.classList.add(
241
- * direction === "back" ? "slide-from-left" : "slide-from-right",
242
- * );
243
- * });
244
- * ```
245
- *
246
- * @example Source-aware focus management
247
- * ```tsx
248
- * useRouteEnter(({ route }) => {
249
- * if (route.context.browser?.source === "navigate") {
250
- * headingRef.current?.focus();
251
- * }
252
- * });
253
- * ```
254
- *
255
- * @example Analytics page-enter event (skip-initial built-in)
256
- * ```tsx
257
- * useRouteEnter(({ route, previousRoute }) => {
258
- * analytics.track("page_enter", {
259
- * route: route.name,
260
- * from: previousRoute.name,
261
- * });
262
- * });
263
- * ```
264
- *
265
- * @example Reading rich transition metadata via `route.transition`
266
- * ```tsx
267
- * useRouteEnter(({ route }) => {
268
- * // route.transition: TransitionMeta — populated by core for every state
269
- * if (route.transition.redirected) {
270
- * showToast(`Redirected from ${route.transition.from}`);
271
- * }
272
- * if (route.transition.segments.activated.includes("products")) {
273
- * // products subtree just became active (could be products or
274
- * // products.detail). Useful for subtree-scoped side effects.
275
- * }
276
- * });
277
- * ```
278
- */
279
- declare function useRouteEnter(handler: RouteEnterHandler, options?: UseRouteEnterOptions): void;
280
- //#endregion
281
- export { Link, type LinkProps, type Navigator, type RouteEnterContext, type RouteEnterHandler, type RouteExitContext, type RouteExitHandler, RouteView, type MatchProps as RouteViewMatchProps, type NotFoundProps as RouteViewNotFoundProps, type RouteViewProps, type SelfProps as RouteViewSelfProps, RouterErrorBoundary, type RouterErrorBoundaryProps, RouterProvider, type RouterTransitionSnapshot, type UseRouteEnterOptions, type UseRouteExitOptions, useNavigator, useRoute, useRouteEnter, useRouteExit, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
282
- //# sourceMappingURL=index.d.ts.map
7
+ export { Link, type LinkProps, type Navigator, type RouteEnterContext, type RouteEnterHandler, type RouteExitContext, type RouteExitHandler, RouteView, type MatchProps as RouteViewMatchProps, type NotFoundProps as RouteViewNotFoundProps, type RouteViewProps, type SelfProps as RouteViewSelfProps, RouterErrorBoundary, type RouterErrorBoundaryProps, RouterProvider, type RouterTransitionSnapshot, type UseRouteEnterOptions, type UseRouteExitOptions, useNavigator, useRoute, useRouteEnter, useRouteExit, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
package/dist/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./RouterProvider-CfBNR-k7.js`),t=require(`./Link-DYvAnJlk.js`);let n=require(`react`),r=require(`@real-router/core`),i=require(`@real-router/route-utils`),a=require(`react/jsx-runtime`);function o(e){return null}o.displayName=`RouteView.Match`;function s(e){return null}s.displayName=`RouteView.Self`;function c(e){return null}c.displayName=`RouteView.NotFound`;function l(e,t,n){return t===``?!1:n?e===t:(0,i.startsWithSegment)(e,t)}function u(e,t){for(let r of n.Children.toArray(e))(0,n.isValidElement)(r)&&(r.type===o||r.type===s||r.type===c?t.push(r):u(r.props.children,t))}function d(e,t,r,i,o){let s=o===void 0?e:(0,a.jsx)(n.Suspense,{fallback:o,children:e});return r?(0,a.jsx)(n.Activity,{mode:i,children:s},t):(0,a.jsx)(n.Fragment,{children:s},t)}function f(e,t){return e.type===c?(t.notFoundChildren=e.props.children,!0):e.type===s?(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0):!1}function p(e,t,n,r,i){let{segment:a,exact:o=!1,keepAlive:s=!1,fallback:c}=e.props,u=n?`${n}.${a}`:a;return!i&&l(t,u,o)?(r.add(u),{rendered:d(e.props.children,u,s,`visible`,c),matched:!0}):s&&r.has(u)?{rendered:d(e.props.children,u,s,`hidden`,c),matched:!1}:{rendered:null,matched:!1}}function m(e,t,i,o){if(o.selfFound&&t===i){e.push(d(o.selfChildren,`__route-view-self__`,!1,`visible`,o.selfFallback));return}t===r.UNKNOWN_ROUTE&&o.notFoundChildren!==null&&e.push((0,a.jsx)(n.Fragment,{children:o.notFoundChildren},`__route-view-not-found__`))}function h(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null},a=!1,o=[];for(let s of e){if(f(s,i))continue;let e=p(s,t,n,r,a);e.matched&&(a=!0),e.rendered!==null&&o.push(e.rendered)}return a||m(o,t,n,i),{rendered:o,activeMatchFound:a}}function g({nodeName:t,children:r}){let{route:i}=e.h(t),o=(0,n.useRef)(null);o.current??=new Set;let s=(0,n.useMemo)(()=>{let e=[];return u(r,e),e},[r]);if(!i)return null;let{rendered:c}=h(s,i.name,t,o.current);return c.length>0?(0,a.jsx)(a.Fragment,{children:c}):null}g.displayName=`RouteView`;const _=Object.assign(g,{Match:o,Self:s,NotFound:c});function v(t,r){let i=e.g(),a=(0,n.useRef)(t),o=r?.skipSameRoute??!0;(0,n.useLayoutEffect)(()=>{a.current=t}),(0,n.useEffect)(()=>i.subscribeLeave(({route:e,nextRoute:t,signal:n})=>{if(!(o&&e.name===t.name)&&!n.aborted)return a.current({route:e,nextRoute:t,signal:n})}),[i,o])}function y(t,r){let{route:i,previousRoute:a}=e.r(),o=(0,n.useRef)(t),s=(0,n.useRef)(null),c=r?.skipSameRoute??!0;(0,n.useLayoutEffect)(()=>{o.current=t}),(0,n.useEffect)(()=>{i.transition.from&&(c&&i.transition.from===i.name||s.current===i||!a||(s.current=i,o.current({route:i,previousRoute:a})))},[i,a,c])}exports.Link=t.t,exports.RouteView=_,exports.RouterErrorBoundary=e.o,exports.RouterProvider=e.t,exports.useNavigator=e.a,exports.useRoute=e.r,exports.useRouteEnter=y,exports.useRouteExit=v,exports.useRouteNode=e.h,exports.useRouteUtils=e.i,exports.useRouter=e.g,exports.useRouterTransition=e.n;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./useRoute-Dudo2K_0.js`),t=require(`./RouterProvider-fJvMO5Tc.js`),n=require(`./Link-BspioC76.js`);let r=require(`react`),i=require(`@real-router/core`),a=require(`@real-router/route-utils`),o=require(`react/jsx-runtime`);function s(e){return null}s.displayName=`RouteView.Match`;function c(e){return null}c.displayName=`RouteView.Self`;function l(e){return null}l.displayName=`RouteView.NotFound`;function u(e,t,n){return t===``?!1:n?e===t:(0,a.startsWithSegment)(e,t)}function d(e,t){r.Children.forEach(e,e=>{(0,r.isValidElement)(e)&&(e.type===s||e.type===c||e.type===l?t.push(e):d(e.props.children,t))})}function f(e,t,n,i,a){let s=a===void 0?e:(0,o.jsx)(r.Suspense,{fallback:a,children:e});return n?(0,o.jsx)(r.Activity,{mode:i,children:s},t):(0,o.jsx)(r.Fragment,{children:s},t)}function p(e,t){return e.type===l?(t.notFoundChildren=e.props.children,!0):e.type===c?(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0):!1}function m(e,t,n,r,i){let a=e.props,{segment:o,exact:s=!1,keepAlive:c=!1,fallback:l}=a,d=n?`${n}.${o}`:o;return!i&&u(t,d,s)?(r.add(d),{rendered:f(a.children,d,c,`visible`,l),matched:!0}):c&&r.has(d)?{rendered:f(a.children,d,c,`hidden`,l),matched:!1}:{rendered:null,matched:!1}}function h(e,t,n,a){if(a.selfFound&&t===n){e.push(f(a.selfChildren,`__route-view-self__`,!1,`visible`,a.selfFallback));return}t===i.UNKNOWN_ROUTE&&a.notFoundChildren!==null&&e.push((0,o.jsx)(r.Fragment,{children:a.notFoundChildren},`__route-view-not-found__`))}function g(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null},a=!1,o=[];for(let s of e){if(p(s,i))continue;let e=m(s,t,n,r,a);e.matched&&(a=!0),e.rendered!==null&&o.push(e.rendered)}return a||h(o,t,n,i),{rendered:o,activeMatchFound:a}}function _({nodeName:e,children:n}){let{route:i}=t.f(e),a=(0,r.useRef)(null);a.current??=new Set;let s=(0,r.useMemo)(()=>{let e=[];return d(n,e),e},[n]);if(!i)return null;let{rendered:c}=g(s,i.name,e,a.current);return c.length>0?(0,o.jsx)(o.Fragment,{children:c}):null}_.displayName=`RouteView`;const v=Object.assign(_,{Match:s,Self:c,NotFound:l});function y(e,n){let i=t.p(),a=(0,r.useRef)(e),o=n?.skipSameRoute??!0;(0,r.useLayoutEffect)(()=>{a.current=e}),(0,r.useEffect)(()=>i.subscribeLeave(({route:e,nextRoute:t,signal:n})=>{if(!(o&&e.name===t.name)&&!n.aborted)return a.current({route:e,nextRoute:t,signal:n})}),[i,o])}function b(t,n){let{route:i,previousRoute:a}=e.t(),o=(0,r.useRef)(t),s=(0,r.useRef)(null),c=n?.skipSameRoute??!0;(0,r.useLayoutEffect)(()=>{o.current=t}),(0,r.useEffect)(()=>{i.transition.from&&(c&&i.transition.from===i.name||s.current===i||!a||(s.current=i,o.current({route:i,previousRoute:a})))},[i,a,c])}exports.Link=n.t,exports.RouteView=v,exports.RouterErrorBoundary=t.a,exports.RouterProvider=t.t,exports.useNavigator=t.i,exports.useRoute=e.t,exports.useRouteEnter=b,exports.useRouteExit=y,exports.useRouteNode=t.f,exports.useRouteUtils=t.r,exports.useRouter=t.p,exports.useRouterTransition=t.n;
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Children","Suspense","Activity","Fragment","UNKNOWN_ROUTE","useRouteNode","useRouter","useRoute"],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../src/hooks/useRouteExit.tsx","../../src/hooks/useRouteEnter.tsx"],"sourcesContent":["import type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\n\nexport function Match(_props: MatchProps): null {\n return null;\n}\n\nMatch.displayName = \"RouteView.Match\";\n\nexport function Self(_props: SelfProps): null {\n return null;\n}\n\nSelf.displayName = \"RouteView.Self\";\n\nexport function NotFound(_props: NotFoundProps): null {\n return null;\n}\n\nNotFound.displayName = \"RouteView.NotFound\";\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Activity, Children, Fragment, Suspense, isValidElement } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\nimport type { ReactElement, ReactNode } from \"react\";\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n}\n\nfunction isSegmentMatch(\n routeName: string,\n fullSegmentName: string,\n exact: boolean,\n): boolean {\n if (fullSegmentName === \"\") {\n return false;\n }\n\n if (exact) {\n return routeName === fullSegmentName;\n }\n\n return startsWithSegment(routeName, fullSegmentName);\n}\n\nexport function collectElements(\n children: ReactNode,\n result: ReactElement[],\n): void {\n // eslint-disable-next-line @eslint-react/no-children-to-array\n for (const child of Children.toArray(children)) {\n if (!isValidElement(child)) {\n continue;\n }\n\n if (\n child.type === Match ||\n child.type === Self ||\n child.type === NotFound\n ) {\n result.push(child);\n } else {\n collectElements(\n (child.props as { readonly children: ReactNode }).children,\n result,\n );\n }\n }\n}\n\nfunction renderSlotElement(\n slotChildren: ReactNode,\n key: string,\n keepAlive: boolean,\n mode: \"visible\" | \"hidden\",\n fallback?: ReactNode,\n): ReactElement {\n const content =\n fallback === undefined ? (\n slotChildren\n ) : (\n <Suspense fallback={fallback}>{slotChildren}</Suspense>\n );\n\n if (keepAlive) {\n return (\n <Activity mode={mode} key={key}>\n {content}\n </Activity>\n );\n }\n\n return <Fragment key={key}>{content}</Fragment>;\n}\n\nfunction recordFallback(child: ReactElement, slots: FallbackSlots): boolean {\n if (child.type === NotFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n\n return true;\n }\n\n if (child.type === Self) {\n // First-wins: subsequent <Self> elements are ignored, mirroring NotFound.\n if (!slots.selfFound) {\n slots.selfChildren = (child.props as SelfProps).children;\n slots.selfFallback = (child.props as SelfProps).fallback;\n slots.selfFound = true;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction processMatch(\n child: ReactElement,\n routeName: string,\n nodeName: string,\n hasBeenActivated: Set<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; matched: boolean } {\n const {\n segment,\n exact = false,\n keepAlive = false,\n fallback,\n } = child.props as MatchProps;\n const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;\n const isActive =\n !alreadyActive && isSegmentMatch(routeName, fullSegmentName, exact);\n\n if (isActive) {\n hasBeenActivated.add(fullSegmentName);\n\n return {\n rendered: renderSlotElement(\n (child.props as MatchProps).children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n matched: true,\n };\n }\n\n if (keepAlive && hasBeenActivated.has(fullSegmentName)) {\n return {\n rendered: renderSlotElement(\n (child.props as MatchProps).children,\n fullSegmentName,\n keepAlive,\n \"hidden\",\n fallback,\n ),\n matched: false,\n };\n }\n\n return { rendered: null, matched: false };\n}\n\nfunction appendFallback(\n rendered: ReactElement[],\n routeName: string,\n nodeName: string,\n slots: FallbackSlots,\n): void {\n if (slots.selfFound && routeName === nodeName) {\n rendered.push(\n renderSlotElement(\n slots.selfChildren,\n \"__route-view-self__\",\n false,\n \"visible\",\n slots.selfFallback,\n ),\n );\n\n return;\n }\n\n if (routeName === UNKNOWN_ROUTE && slots.notFoundChildren !== null) {\n rendered.push(\n <Fragment key=\"__route-view-not-found__\">\n {slots.notFoundChildren}\n </Fragment>,\n );\n }\n}\n\nexport function buildRenderList(\n elements: ReactElement[],\n routeName: string,\n nodeName: string,\n hasBeenActivated: Set<string>,\n): { rendered: ReactElement[]; activeMatchFound: boolean } {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n };\n let activeMatchFound = false;\n const rendered: ReactElement[] = [];\n\n for (const child of elements) {\n if (recordFallback(child, slots)) {\n continue;\n }\n\n const result = processMatch(\n child,\n routeName,\n nodeName,\n hasBeenActivated,\n activeMatchFound,\n );\n\n if (result.matched) {\n activeMatchFound = true;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (!activeMatchFound) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound };\n}\n","import { useMemo, useRef } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\nimport { buildRenderList, collectElements } from \"./helpers\";\nimport { useRouteNode } from \"../../../hooks/useRouteNode\";\n\nimport type { RouteViewProps } from \"./types\";\nimport type { ReactElement } from \"react\";\n\nfunction RouteViewRoot({\n nodeName,\n children,\n}: Readonly<RouteViewProps>): ReactElement | null {\n const { route } = useRouteNode(nodeName);\n const hasBeenActivatedRef = useRef<Set<string> | null>(null);\n\n // eslint-disable-next-line @eslint-react/refs -- lazy init: assign once when null to avoid `new Set()` allocation on every render\n hasBeenActivatedRef.current ??= new Set();\n\n // Skip the Children.toArray + collectElements traversal when children\n // reference is unchanged. children only changes when the parent re-renders\n // with a new ReactNode, so this caches the steady-state.\n const elements = useMemo(() => {\n const collected: ReactElement[] = [];\n\n collectElements(children, collected);\n\n return collected;\n }, [children]);\n\n if (!route) {\n return null;\n }\n\n const { rendered } = buildRenderList(\n elements,\n route.name,\n nodeName,\n // eslint-disable-next-line @eslint-react/refs -- stable Set ref read for keepAlive tracking (never reassigned)\n hasBeenActivatedRef.current,\n );\n\n if (rendered.length > 0) {\n return <>{rendered}</>;\n }\n\n return null;\n}\n\nRouteViewRoot.displayName = \"RouteView\";\n\nexport const RouteView = Object.assign(RouteViewRoot, {\n Match,\n Self,\n NotFound,\n});\n\nexport type {\n RouteViewProps,\n MatchProps as RouteViewMatchProps,\n SelfProps as RouteViewSelfProps,\n NotFoundProps as RouteViewNotFoundProps,\n} from \"./types\";\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteExitContext {\n /** The route being left. */\n route: State;\n /** The route being navigated to. */\n nextRoute: State;\n /**\n * AbortSignal that fires when this navigation is superseded by a later\n * one (rapid clicks). Already filtered: when the handler runs,\n * `signal.aborted` is guaranteed to be `false`. Use\n * `signal.addEventListener(\"abort\", cleanup, { once: true })` for\n * cleanup that must run on cancellation.\n */\n signal: AbortSignal;\n}\n\nexport interface UseRouteExitOptions {\n /**\n * Skip the handler when `route.name === nextRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`.\n */\n skipSameRoute?: boolean;\n}\n\nexport type RouteExitHandler = (\n context: RouteExitContext,\n) => void | Promise<void>;\n\n/**\n * Subscribe to the router's leave-window with the universal guards baked\n * in. Wraps `router.subscribeLeave` so consumers don't repeat the same\n * boilerplate every time:\n *\n * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`\n * when the handler would run (rapid navigation superseded a slower\n * one), the handler is skipped entirely. `signal.addEventListener(\n * \"abort\", ...)` does not fire retroactively, so without this guard\n * downstream cleanup would never trigger.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations (sort, filter,\n * pagination) skip the work. Opt out with `skipSameRoute: false`.\n * - **Stable handler reference**: the handler can change identity on\n * every render without causing resubscription — internal ref keeps\n * the latest handler accessible to the long-lived subscription.\n *\n * Returns nothing — the subscription's lifecycle is bound to the\n * component's mount.\n *\n * If the handler returns a Promise, the router blocks on it. If the\n * Promise resolves, navigation proceeds. If it rejects, the router emits\n * `TRANSITION_CANCELLED` (existing core behavior, no change here).\n *\n * @example Animation\n * ```tsx\n * const ref = useRef<HTMLDivElement>(null);\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.current;\n * if (!el) return;\n * el.classList.add(\"fade-out\");\n * const cleanup = () => el.classList.remove(\"fade-out\");\n * signal.addEventListener(\"abort\", cleanup, { once: true });\n * try {\n * el.getBoundingClientRect(); // style flush\n * await Promise.allSettled(el.getAnimations().map((a) => a.finished));\n * } finally {\n * cleanup();\n * }\n * });\n * ```\n *\n * @example Auto-save form draft\n * ```tsx\n * useRouteExit(async ({ signal }) => {\n * if (formState.dirty) await api.saveDraft(formState, { signal });\n * });\n * ```\n *\n * @example Cancel inflight requests\n * ```tsx\n * useRouteExit(() => {\n * inflightController.abort();\n * });\n * ```\n *\n * @example Library-coordinated exit (motion / framer-motion)\n * ```tsx\n * const exitResolverRef = useRef<(() => void) | null>(null);\n *\n * useRouteExit(({ signal }) => {\n * return new Promise<void>((resolve) => {\n * exitResolverRef.current = resolve;\n * signal.addEventListener(\"abort\", () => resolve(), { once: true });\n * });\n * });\n *\n * const onExitComplete = () => exitResolverRef.current?.();\n * // pass onExitComplete to <AnimatePresence>\n * ```\n *\n * @example Reading rich transition metadata via `nextRoute.transition`\n * ```tsx\n * useRouteExit(({ route, nextRoute }) => {\n * // nextRoute.transition: TransitionMeta — preview of the upcoming nav\n * if (nextRoute.transition.segments.deactivated.includes(\"products\")) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * if (nextRoute.transition.redirected) {\n * // skip animation when navigation arrived via redirect\n * return;\n * }\n * });\n * ```\n */\nexport function useRouteExit(\n handler: RouteExitHandler,\n options?: UseRouteExitOptions,\n): void {\n const router = useRouter();\n const handlerRef = useRef(handler);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler accessible to the subscription without\n // resubscribing on every render — the subscription registers the\n // wrapper once and dispatches to whatever ref points to.\n // useLayoutEffect (synchronous, post-render, pre-paint) updates the\n // ref before the browser can dispatch any router events that could\n // observe a stale closure.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n return router.subscribeLeave(({ route, nextRoute, signal }) => {\n if (skipSameRoute && route.name === nextRoute.name) {\n return;\n }\n\n // Reentrant abort: signal is already aborted when listener fires\n // (e.g. a newer navigate superseded this one before subscribeLeave\n // even ran). addEventListener(\"abort\", ...) does not fire\n // retroactively, so we skip the handler entirely — any cleanup the\n // handler would have wired via abort listener must not run because\n // the corresponding `add` work never happened.\n if (signal.aborted) {\n return;\n }\n\n return handlerRef.current({ route, nextRoute, signal });\n });\n }, [router, skipSameRoute]);\n}\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRoute } from \"./useRoute\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteEnterContext {\n /** The route that was just activated. */\n route: State;\n /** The route that was active immediately before this navigation. */\n previousRoute: State;\n}\n\nexport type RouteEnterHandler = (context: RouteEnterContext) => void;\n\nexport interface UseRouteEnterOptions {\n /**\n * Skip the handler when `route.name === previousRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`. Symmetric with `useRouteExit`'s same-name option.\n */\n skipSameRoute?: boolean;\n}\n\n/**\n * Fire `handler` once when the component mounts as a result of a\n * navigation. Mirror of `useRouteExit` for the entry side.\n *\n * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:\n *\n * - **Skip-initial**: handler is skipped when there is no\n * `previousRoute` (i.e. first-load mount). Most consumers want to\n * fire side effects only on real navigations, not on hydration.\n * - **Same-route skip** (default): handler is skipped when\n * `route.name === previousRoute.name`. Sort/filter/query-only\n * navigations re-run the effect (because `route` reference changes\n * in `useRoute`'s snapshot), but they are not \"entries\" in the\n * animation / analytics sense — the component instance has stayed\n * mounted throughout. Opt out with `skipSameRoute: false` when\n * the handler legitimately needs to fire on every navigation\n * (e.g. analytics tracking each query-param flip).\n * - **StrictMode double-mount immunity**: in dev, React's StrictMode\n * runs every effect twice to surface bugs. Without a guard,\n * analytics fire twice, animations restart, focus jumps. The hook\n * tracks the last-handled `route` reference and short-circuits the\n * second pass.\n * - **Latest-handler ref**: the handler can change identity on every\n * render without re-running the effect — the registered wrapper\n * dispatches to whatever `handlerRef.current` points to.\n * - **Mount-time `route` / `previousRoute` snapshot**: the handler\n * receives the values that were live at the moment of mount, not\n * the latest ones (which may have moved on if the user navigated\n * again before the effect drained).\n *\n * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from\n * `@real-router/sources`, so by the time the new component's effect\n * runs, the snapshot is the post-commit one. This is the reason we can\n * read mount-time context from `useRoute()` instead of subscribing to\n * `router.subscribe` directly (which fires before React schedules a\n * re-render — the well-known race in distributed components).\n *\n * @example Direction-aware entry animation\n * ```tsx\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.current?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Source-aware focus management\n * ```tsx\n * useRouteEnter(({ route }) => {\n * if (route.context.browser?.source === \"navigate\") {\n * headingRef.current?.focus();\n * }\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```tsx\n * useRouteEnter(({ route, previousRoute }) => {\n * analytics.track(\"page_enter\", {\n * route: route.name,\n * from: previousRoute.name,\n * });\n * });\n * ```\n *\n * @example Reading rich transition metadata via `route.transition`\n * ```tsx\n * useRouteEnter(({ route }) => {\n * // route.transition: TransitionMeta — populated by core for every state\n * if (route.transition.redirected) {\n * showToast(`Redirected from ${route.transition.from}`);\n * }\n * if (route.transition.segments.activated.includes(\"products\")) {\n * // products subtree just became active (could be products or\n * // products.detail). Useful for subtree-scoped side effects.\n * }\n * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const handlerRef = useRef(handler);\n const lastHandledRouteRef = useRef<State | null>(null);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler reference accessible without re-running\n // the effect. useLayoutEffect (synchronous, post-render, pre-paint)\n // updates the ref before the effect can read it.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n // Early-exit guards, top-down:\n //\n // - **Skip-initial**: `state.transition.from` is undefined only\n // for the very first state committed by `router.start()`.\n // - **Skip-same-route**: query-only navigations have\n // `transition.from === route.name`. Opt-out via\n // `skipSameRoute: false`.\n // - **StrictMode dedupe**: same `route` ref between effect\n // cleanup + re-run in dev's strict pass. Not testable from\n // vitest (`NODE_ENV === \"test\"` disables React's strict-mode\n // double-run), so v8-ignored.\n if (!route.transition.from) {\n return;\n }\n if (skipSameRoute && route.transition.from === route.name) {\n return;\n }\n /* v8 ignore start */\n if (lastHandledRouteRef.current === route || !previousRoute) {\n return;\n }\n /* v8 ignore stop */\n\n lastHandledRouteRef.current = route;\n handlerRef.current({ route, previousRoute });\n }, [route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"8QAEA,SAAgB,EAAM,EAA0B,CAC9C,OAAO,KAGT,EAAM,YAAc,kBAEpB,SAAgB,EAAK,EAAyB,CAC5C,OAAO,KAGT,EAAK,YAAc,iBAEnB,SAAgB,EAAS,EAA6B,CACpD,OAAO,KAGT,EAAS,YAAc,qBCFvB,SAAS,EACP,EACA,EACA,EACS,CAST,OARI,IAAoB,GACf,GAGL,EACK,IAAc,GAGvB,EAAA,EAAA,mBAAyB,EAAW,EAAgB,CAGtD,SAAgB,EACd,EACA,EACM,CAEN,IAAK,IAAM,KAASA,EAAAA,SAAS,QAAQ,EAA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AAiB,IAQhD,EAAA,EAAA,qBAAsB,CACpB,EAAW,QAAU,GACrB,EAEF,EAAA,EAAA,eACS,EAAO,gBAAgB,CAAE,QAAO,YAAW,YAAa,CACzD,QAAiB,EAAM,OAAS,EAAU,OAU1C,GAAO,QAIX,OAAO,EAAW,QAAQ,CAAE,QAAO,YAAW,SAAQ,CAAC,EACvD,CACD,CAAC,EAAQ,EAAc,CAAC,CCrD7B,SAAgB,EACd,EACA,EACM,CACN,GAAM,CAAE,QAAO,iBAAkBC,EAAAA,GAAU,CACrC,GAAA,EAAA,EAAA,QAAoB,EAAQ,CAC5B,GAAA,EAAA,EAAA,QAA2C,KAAK,CAChD,EAAgB,GAAS,eAAiB,IAKhD,EAAA,EAAA,qBAAsB,CACpB,EAAW,QAAU,GACrB,EAEF,EAAA,EAAA,eAAgB,CAYT,EAAM,WAAW,OAGlB,GAAiB,EAAM,WAAW,OAAS,EAAM,MAIjD,EAAoB,UAAY,GAAS,CAAC,IAK9C,EAAoB,QAAU,EAC9B,EAAW,QAAQ,CAAE,QAAO,gBAAe,CAAC,IAC3C,CAAC,EAAO,EAAe,EAAc,CAAC"}
1
+ {"version":3,"file":"index.js","names":["Suspense","Activity","Fragment","UNKNOWN_ROUTE","useRouteNode","useRouter","useRoute"],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../src/hooks/useRouteExit.tsx","../../src/hooks/useRouteEnter.tsx"],"sourcesContent":["import type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\n\nexport function Match(_props: MatchProps): null {\n return null;\n}\n\nMatch.displayName = \"RouteView.Match\";\n\nexport function Self(_props: SelfProps): null {\n return null;\n}\n\nSelf.displayName = \"RouteView.Self\";\n\nexport function NotFound(_props: NotFoundProps): null {\n return null;\n}\n\nNotFound.displayName = \"RouteView.NotFound\";\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Activity, Children, Fragment, Suspense, isValidElement } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\nimport type { ReactElement, ReactNode } from \"react\";\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n}\n\n// Fixed keys used by appendFallback to distinguish the Self / NotFound\n// render slots from user-supplied <Match> children. Match render slots key\n// off `fullSegmentName` instead — these two are the only synthetic keys.\nconst SELF_KEY = \"__route-view-self__\";\nconst NOT_FOUND_KEY = \"__route-view-not-found__\";\n\nfunction isSegmentMatch(\n routeName: string,\n fullSegmentName: string,\n exact: boolean,\n): boolean {\n if (fullSegmentName === \"\") {\n return false;\n }\n\n if (exact) {\n return routeName === fullSegmentName;\n }\n\n return startsWithSegment(routeName, fullSegmentName);\n}\n\nexport function collectElements(\n children: ReactNode,\n result: ReactElement[],\n): void {\n // Recurses into Fragment-like wrappers (anything that isn't Match / Self /\n // NotFound) to flatten the slot tree. No explicit depth guard: typical\n // RouteView shape is `<RouteView><Match/>...<NotFound/></RouteView>` —\n // depth ≤ 3 in real apps. A pathological hand-written tree of N Fragments\n // recurses N times; the call stack, not this function, is the bound.\n //\n // `Children.forEach` iterates without `Children.toArray`'s array allocation\n // and per-child clone-with-synthetic-key step. We don't read child.key here\n // (Match/Self/NotFound carry their own segment-derived keys further down),\n // so the cheaper iterator is functionally equivalent.\n // eslint-disable-next-line @eslint-react/no-children-for-each -- intentional: collectElements is a render-hot pipeline; toArray's array+key clone is wasteful here\n Children.forEach(children, (child) => {\n if (!isValidElement(child)) {\n return;\n }\n\n if (\n child.type === Match ||\n child.type === Self ||\n child.type === NotFound\n ) {\n result.push(child);\n } else {\n collectElements(\n (child.props as { readonly children: ReactNode }).children,\n result,\n );\n }\n });\n}\n\nfunction renderSlotElement(\n slotChildren: ReactNode,\n key: string,\n keepAlive: boolean,\n mode: \"visible\" | \"hidden\",\n fallback?: ReactNode,\n): ReactElement {\n const content =\n fallback === undefined ? (\n slotChildren\n ) : (\n <Suspense fallback={fallback}>{slotChildren}</Suspense>\n );\n\n if (keepAlive) {\n return (\n <Activity mode={mode} key={key}>\n {content}\n </Activity>\n );\n }\n\n return <Fragment key={key}>{content}</Fragment>;\n}\n\nfunction recordFallback(child: ReactElement, slots: FallbackSlots): boolean {\n if (child.type === NotFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n\n return true;\n }\n\n if (child.type === Self) {\n // First-wins: subsequent <Self> elements are ignored, mirroring NotFound.\n if (!slots.selfFound) {\n slots.selfChildren = (child.props as SelfProps).children;\n slots.selfFallback = (child.props as SelfProps).fallback;\n slots.selfFound = true;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction processMatch(\n child: ReactElement,\n routeName: string,\n nodeName: string,\n hasBeenActivated: Set<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; matched: boolean } {\n const matchProps = child.props as MatchProps;\n const { segment, exact = false, keepAlive = false, fallback } = matchProps;\n const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;\n const isActive =\n !alreadyActive && isSegmentMatch(routeName, fullSegmentName, exact);\n\n if (isActive) {\n hasBeenActivated.add(fullSegmentName);\n\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n matched: true,\n };\n }\n\n if (keepAlive && hasBeenActivated.has(fullSegmentName)) {\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"hidden\",\n fallback,\n ),\n matched: false,\n };\n }\n\n return { rendered: null, matched: false };\n}\n\nfunction appendFallback(\n rendered: ReactElement[],\n routeName: string,\n nodeName: string,\n slots: FallbackSlots,\n): void {\n if (slots.selfFound && routeName === nodeName) {\n rendered.push(\n renderSlotElement(\n slots.selfChildren,\n SELF_KEY,\n false,\n \"visible\",\n slots.selfFallback,\n ),\n );\n\n return;\n }\n\n if (routeName === UNKNOWN_ROUTE && slots.notFoundChildren !== null) {\n rendered.push(\n <Fragment key={NOT_FOUND_KEY}>{slots.notFoundChildren}</Fragment>,\n );\n }\n}\n\nexport function buildRenderList(\n elements: ReactElement[],\n routeName: string,\n nodeName: string,\n hasBeenActivated: Set<string>,\n): { rendered: ReactElement[]; activeMatchFound: boolean } {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n };\n let activeMatchFound = false;\n const rendered: ReactElement[] = [];\n\n for (const child of elements) {\n if (recordFallback(child, slots)) {\n continue;\n }\n\n const result = processMatch(\n child,\n routeName,\n nodeName,\n hasBeenActivated,\n activeMatchFound,\n );\n\n if (result.matched) {\n activeMatchFound = true;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (!activeMatchFound) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound };\n}\n","import { useMemo, useRef } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\nimport { buildRenderList, collectElements } from \"./helpers\";\nimport { useRouteNode } from \"../../../hooks/useRouteNode\";\n\nimport type { RouteViewProps } from \"./types\";\nimport type { ReactElement } from \"react\";\n\nfunction RouteViewRoot({\n nodeName,\n children,\n}: Readonly<RouteViewProps>): ReactElement | null {\n const { route } = useRouteNode(nodeName);\n const hasBeenActivatedRef = useRef<Set<string> | null>(null);\n\n // eslint-disable-next-line @eslint-react/refs -- lazy init: assign once when null to avoid `new Set()` allocation on every render\n hasBeenActivatedRef.current ??= new Set();\n\n // Skip the Children.forEach + collectElements traversal when the children\n // reference is unchanged. The common SPA case is a stable JSX tree across\n // re-renders, so the cache hits on every render except the first.\n //\n // Streaming SSR caveat: with `renderToReadableStream`, React may invoke\n // RouteView multiple times across chunks with a fresh `children` reference\n // each time. The useMemo misses on each new render and the traversal runs\n // again — this is the expected SSR cost; the alternative would be build-\n // time codegen of the static route tree, which is out of scope here.\n const elements = useMemo(() => {\n const collected: ReactElement[] = [];\n\n collectElements(children, collected);\n\n return collected;\n }, [children]);\n\n if (!route) {\n return null;\n }\n\n const { rendered } = buildRenderList(\n elements,\n route.name,\n nodeName,\n // eslint-disable-next-line @eslint-react/refs -- stable Set ref read for keepAlive tracking (never reassigned)\n hasBeenActivatedRef.current,\n );\n\n if (rendered.length > 0) {\n return <>{rendered}</>;\n }\n\n return null;\n}\n\nRouteViewRoot.displayName = \"RouteView\";\n\nexport const RouteView = Object.assign(RouteViewRoot, {\n Match,\n Self,\n NotFound,\n});\n\nexport type {\n RouteViewProps,\n MatchProps as RouteViewMatchProps,\n SelfProps as RouteViewSelfProps,\n NotFoundProps as RouteViewNotFoundProps,\n} from \"./types\";\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteExitContext {\n /** The route being left. */\n route: State;\n /** The route being navigated to. */\n nextRoute: State;\n /**\n * AbortSignal that fires when this navigation is superseded by a later\n * one (rapid clicks). Already filtered: when the handler runs,\n * `signal.aborted` is guaranteed to be `false`. Use\n * `signal.addEventListener(\"abort\", cleanup, { once: true })` for\n * cleanup that must run on cancellation.\n */\n signal: AbortSignal;\n}\n\nexport interface UseRouteExitOptions {\n /**\n * Skip the handler when `route.name === nextRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`.\n */\n skipSameRoute?: boolean;\n}\n\nexport type RouteExitHandler = (\n context: RouteExitContext,\n) => void | Promise<void>;\n\n/**\n * Subscribe to the router's leave-window with the universal guards baked\n * in. Wraps `router.subscribeLeave` so consumers don't repeat the same\n * boilerplate every time:\n *\n * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`\n * when the handler would run (rapid navigation superseded a slower\n * one), the handler is skipped entirely. `signal.addEventListener(\n * \"abort\", ...)` does not fire retroactively, so without this guard\n * downstream cleanup would never trigger.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations (sort, filter,\n * pagination) skip the work. Opt out with `skipSameRoute: false`.\n * - **Stable handler reference**: the handler can change identity on\n * every render without causing resubscription — internal ref keeps\n * the latest handler accessible to the long-lived subscription.\n *\n * Returns nothing — the subscription's lifecycle is bound to the\n * component's mount.\n *\n * If the handler returns a Promise, the router blocks on it. If the\n * Promise resolves, navigation proceeds. If it rejects, the router emits\n * `TRANSITION_CANCELLED` (existing core behavior, no change here).\n *\n * @example Animation\n * ```tsx\n * const ref = useRef<HTMLDivElement>(null);\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.current;\n * if (!el) return;\n * el.classList.add(\"fade-out\");\n * const cleanup = () => el.classList.remove(\"fade-out\");\n * signal.addEventListener(\"abort\", cleanup, { once: true });\n * try {\n * el.getBoundingClientRect(); // style flush\n * await Promise.allSettled(el.getAnimations().map((a) => a.finished));\n * } finally {\n * cleanup();\n * }\n * });\n * ```\n *\n * @example Auto-save form draft\n * ```tsx\n * useRouteExit(async ({ signal }) => {\n * if (formState.dirty) await api.saveDraft(formState, { signal });\n * });\n * ```\n *\n * @example Cancel inflight requests\n * ```tsx\n * useRouteExit(() => {\n * inflightController.abort();\n * });\n * ```\n *\n * @example Library-coordinated exit (motion / framer-motion)\n * ```tsx\n * const exitResolverRef = useRef<(() => void) | null>(null);\n *\n * useRouteExit(({ signal }) => {\n * return new Promise<void>((resolve) => {\n * exitResolverRef.current = resolve;\n * signal.addEventListener(\"abort\", () => resolve(), { once: true });\n * });\n * });\n *\n * const onExitComplete = () => exitResolverRef.current?.();\n * // pass onExitComplete to <AnimatePresence>\n * ```\n *\n * @example Reading rich transition metadata via `nextRoute.transition`\n * ```tsx\n * useRouteExit(({ route, nextRoute }) => {\n * // nextRoute.transition: TransitionMeta — preview of the upcoming nav\n * if (nextRoute.transition.segments.deactivated.includes(\"products\")) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * if (nextRoute.transition.redirected) {\n * // skip animation when navigation arrived via redirect\n * return;\n * }\n * });\n * ```\n */\nexport function useRouteExit(\n handler: RouteExitHandler,\n options?: UseRouteExitOptions,\n): void {\n const router = useRouter();\n const handlerRef = useRef(handler);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler accessible to the subscription without\n // resubscribing on every render — the subscription registers the\n // wrapper once and dispatches to whatever ref points to.\n // useLayoutEffect (synchronous, post-render, pre-paint) updates the\n // ref before the browser can dispatch any router events that could\n // observe a stale closure.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n return router.subscribeLeave(({ route, nextRoute, signal }) => {\n if (skipSameRoute && route.name === nextRoute.name) {\n return;\n }\n\n // Reentrant abort: signal is already aborted when listener fires\n // (e.g. a newer navigate superseded this one before subscribeLeave\n // even ran). addEventListener(\"abort\", ...) does not fire\n // retroactively, so we skip the handler entirely — any cleanup the\n // handler would have wired via abort listener must not run because\n // the corresponding `add` work never happened.\n if (signal.aborted) {\n return;\n }\n\n return handlerRef.current({ route, nextRoute, signal });\n });\n }, [router, skipSameRoute]);\n}\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRoute } from \"./useRoute\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteEnterContext {\n /** The route that was just activated. */\n route: State;\n /** The route that was active immediately before this navigation. */\n previousRoute: State;\n}\n\nexport type RouteEnterHandler = (context: RouteEnterContext) => void;\n\nexport interface UseRouteEnterOptions {\n /**\n * Skip the handler when `route.name === previousRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`. Symmetric with `useRouteExit`'s same-name option.\n */\n skipSameRoute?: boolean;\n}\n\n/**\n * Fire `handler` once when the component mounts as a result of a\n * navigation. Mirror of `useRouteExit` for the entry side.\n *\n * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:\n *\n * - **Skip-initial**: handler is skipped when there is no\n * `previousRoute` (i.e. first-load mount). Most consumers want to\n * fire side effects only on real navigations, not on hydration.\n * - **Same-route skip** (default): handler is skipped when\n * `route.name === previousRoute.name`. Sort/filter/query-only\n * navigations re-run the effect (because `route` reference changes\n * in `useRoute`'s snapshot), but they are not \"entries\" in the\n * animation / analytics sense — the component instance has stayed\n * mounted throughout. Opt out with `skipSameRoute: false` when\n * the handler legitimately needs to fire on every navigation\n * (e.g. analytics tracking each query-param flip).\n * - **StrictMode double-mount immunity**: in dev, React's StrictMode\n * runs every effect twice to surface bugs. Without a guard,\n * analytics fire twice, animations restart, focus jumps. The hook\n * tracks the last-handled `route` reference and short-circuits the\n * second pass.\n * - **Latest-handler ref**: the handler can change identity on every\n * render without re-running the effect — the registered wrapper\n * dispatches to whatever `handlerRef.current` points to.\n * - **Mount-time `route` / `previousRoute` snapshot**: the handler\n * receives the values that were live at the moment of mount, not\n * the latest ones (which may have moved on if the user navigated\n * again before the effect drained).\n *\n * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from\n * `@real-router/sources`, so by the time the new component's effect\n * runs, the snapshot is the post-commit one. This is the reason we can\n * read mount-time context from `useRoute()` instead of subscribing to\n * `router.subscribe` directly (which fires before React schedules a\n * re-render — the well-known race in distributed components).\n *\n * @example Direction-aware entry animation\n * ```tsx\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.current?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Source-aware focus management\n * ```tsx\n * useRouteEnter(({ route }) => {\n * if (route.context.browser?.source === \"navigate\") {\n * headingRef.current?.focus();\n * }\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```tsx\n * useRouteEnter(({ route, previousRoute }) => {\n * analytics.track(\"page_enter\", {\n * route: route.name,\n * from: previousRoute.name,\n * });\n * });\n * ```\n *\n * @example Reading rich transition metadata via `route.transition`\n * ```tsx\n * useRouteEnter(({ route }) => {\n * // route.transition: TransitionMeta — populated by core for every state\n * if (route.transition.redirected) {\n * showToast(`Redirected from ${route.transition.from}`);\n * }\n * if (route.transition.segments.activated.includes(\"products\")) {\n * // products subtree just became active (could be products or\n * // products.detail). Useful for subtree-scoped side effects.\n * }\n * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const handlerRef = useRef(handler);\n const lastHandledRouteRef = useRef<State | null>(null);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler reference accessible without re-running\n // the effect. useLayoutEffect (synchronous, post-render, pre-paint)\n // updates the ref before the effect can read it.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n // Early-exit guards, top-down:\n //\n // - **Skip-initial**: `state.transition.from` is undefined only\n // for the very first state committed by `router.start()`.\n // - **Skip-same-route**: query-only navigations have\n // `transition.from === route.name`. Opt-out via\n // `skipSameRoute: false`.\n // - **StrictMode dedupe**: same `route` ref between effect\n // cleanup + re-run in dev's strict pass. Not testable from\n // vitest (`NODE_ENV === \"test\"` disables React's strict-mode\n // double-run), so v8-ignored.\n if (!route.transition.from) {\n return;\n }\n if (skipSameRoute && route.transition.from === route.name) {\n return;\n }\n /* v8 ignore start */\n if (lastHandledRouteRef.current === route || !previousRoute) {\n return;\n }\n /* v8 ignore stop */\n\n lastHandledRouteRef.current = route;\n handlerRef.current({ route, previousRoute });\n }, [route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"kTAEA,SAAgB,EAAM,EAA0B,CAC9C,OAAO,KAGT,EAAM,YAAc,kBAEpB,SAAgB,EAAK,EAAyB,CAC5C,OAAO,KAGT,EAAK,YAAc,iBAEnB,SAAgB,EAAS,EAA6B,CACpD,OAAO,KAGT,EAAS,YAAc,qBCIvB,SAAS,EACP,EACA,EACA,EACS,CAST,OARI,IAAoB,GACf,GAGL,EACK,IAAc,GAGvB,EAAA,EAAA,mBAAyB,EAAW,EAAgB,CAGtD,SAAgB,EACd,EACA,EACM,CAYN,EAAA,SAAS,QAAQ,EAAW,GAAU,EAChC,EAAA,EAAA,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QhD,EAAA,EAAA,qBAAsB,CACpB,EAAW,QAAU,GACrB,EAEF,EAAA,EAAA,eACS,EAAO,gBAAgB,CAAE,QAAO,YAAW,YAAa,CACzD,QAAiB,EAAM,OAAS,EAAU,OAU1C,GAAO,QAIX,OAAO,EAAW,QAAQ,CAAE,QAAO,YAAW,SAAQ,CAAC,EACvD,CACD,CAAC,EAAQ,EAAc,CAAC,CCrD7B,SAAgB,EACd,EACA,EACM,CACN,GAAM,CAAE,QAAO,iBAAkBC,EAAAA,GAAU,CACrC,GAAA,EAAA,EAAA,QAAoB,EAAQ,CAC5B,GAAA,EAAA,EAAA,QAA2C,KAAK,CAChD,EAAgB,GAAS,eAAiB,IAKhD,EAAA,EAAA,qBAAsB,CACpB,EAAW,QAAU,GACrB,EAEF,EAAA,EAAA,eAAgB,CAYT,EAAM,WAAW,OAGlB,GAAiB,EAAM,WAAW,OAAS,EAAM,MAIjD,EAAoB,UAAY,GAAS,CAAC,IAK9C,EAAoB,QAAU,EAC9B,EAAW,QAAQ,CAAE,QAAO,gBAAe,CAAC,IAC3C,CAAC,EAAO,EAAe,EAAc,CAAC"}
@@ -0,0 +1,5 @@
1
+ import { a as RouteExitContext, d as NotFoundProps, f as RouteViewProps, n as RouteEnterHandler, o as RouteExitHandler, p as SelfProps, r as UseRouteEnterOptions, s as UseRouteExitOptions, t as RouteEnterContext, u as MatchProps } from "./useRouteEnter-gfy65W0D.js";
2
+ import { n as RouterErrorBoundaryProps, r as LinkProps } from "./RouterErrorBoundary-BlJmaoyr.js";
3
+ import { Navigator } from "@real-router/core";
4
+ import { RouterTransitionSnapshot } from "@real-router/sources";
5
+ export { type LinkProps, type Navigator, type RouteEnterContext, type RouteEnterHandler, type RouteExitContext, type RouteExitHandler, type MatchProps as RouteViewMatchProps, type NotFoundProps as RouteViewNotFoundProps, type RouteViewProps, type SelfProps as RouteViewSelfProps, type RouterErrorBoundaryProps, type RouterTransitionSnapshot, type UseRouteEnterOptions, type UseRouteExitOptions };