@askrjs/askr 0.0.35 → 0.0.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -9
- package/dist/bench/components/benchmark-row.js.map +1 -1
- package/dist/bench/components/benchmark-table.js +1 -1
- package/dist/bench/components/benchmark-table.js.map +1 -1
- package/dist/benchmark.js +3 -3
- package/dist/benchmark.js.map +1 -1
- package/dist/bin/askr-ssg.js.map +1 -1
- package/dist/boot/index.d.ts +1 -7
- package/dist/boot/index.d.ts.map +1 -1
- package/dist/boot/index.js +31 -42
- package/dist/boot/index.js.map +1 -1
- package/dist/common/control.js.map +1 -1
- package/dist/common/env.js.map +1 -1
- package/dist/common/ssr-errors.js.map +1 -1
- package/dist/common/vnode.js.map +1 -1
- package/dist/components/error-boundary.js.map +1 -1
- package/dist/components/index.d.ts +2 -0
- package/dist/components/index.js +2 -0
- package/dist/components/link.d.ts +4 -5
- package/dist/components/link.d.ts.map +1 -1
- package/dist/components/link.js +2 -1
- package/dist/components/link.js.map +1 -1
- package/dist/control/case.js.map +1 -1
- package/dist/control/for.js.map +1 -1
- package/dist/control/shared.js.map +1 -1
- package/dist/control/show.js.map +1 -1
- package/dist/data/index.d.ts.map +1 -1
- package/dist/data/index.js +165 -23
- package/dist/data/index.js.map +1 -1
- package/dist/dev/invariant.js.map +1 -1
- package/dist/dev/logger.js.map +1 -1
- package/dist/foundations/icon/icon.d.ts.map +1 -1
- package/dist/foundations/icon/icon.js.map +1 -1
- package/dist/foundations/icon/icon.types.d.ts +2 -1
- package/dist/foundations/icon/icon.types.d.ts.map +1 -1
- package/dist/foundations/icon/index.d.ts +3 -0
- package/dist/foundations/icon/index.js +2 -0
- package/dist/foundations/index.d.ts +1 -18
- package/dist/foundations/index.js +2 -18
- package/dist/foundations/interactions/dismissable.js.map +1 -1
- package/dist/foundations/interactions/focusable.js.map +1 -1
- package/dist/foundations/interactions/hoverable.js.map +1 -1
- package/dist/foundations/interactions/index.d.ts +7 -0
- package/dist/foundations/interactions/index.js +7 -0
- package/dist/foundations/interactions/interaction-policy.js +2 -2
- package/dist/foundations/interactions/interaction-policy.js.map +1 -1
- package/dist/foundations/interactions/pressable.js.map +1 -1
- package/dist/foundations/interactions/roving-focus.js.map +1 -1
- package/dist/foundations/state/controllable.js.map +1 -1
- package/dist/foundations/state/index.d.ts +2 -0
- package/dist/foundations/state/index.js +2 -0
- package/dist/foundations/structures/collection.js.map +1 -1
- package/dist/foundations/structures/index.d.ts +8 -0
- package/dist/foundations/structures/index.js +7 -0
- package/dist/foundations/structures/layer.js.map +1 -1
- package/dist/foundations/structures/layout.js.map +1 -1
- package/dist/foundations/structures/portal.js.map +1 -1
- package/dist/foundations/structures/presence.js.map +1 -1
- package/dist/foundations/structures/slot.js.map +1 -1
- package/dist/foundations/utilities/aria.js.map +1 -1
- package/dist/foundations/utilities/compose-handlers.js.map +1 -1
- package/dist/foundations/utilities/compose-ref.js.map +1 -1
- package/dist/foundations/utilities/index.d.ts +7 -0
- package/dist/foundations/utilities/index.js +6 -0
- package/dist/foundations/utilities/merge-props.js.map +1 -1
- package/dist/foundations/utilities/use-id.js.map +1 -1
- package/dist/fx/fx.js.map +1 -1
- package/dist/fx/timing.js.map +1 -1
- package/dist/index.d.ts +2 -16
- package/dist/index.js +1 -17
- package/dist/index.js.map +1 -1
- package/dist/jsx/utils.js.map +1 -1
- package/dist/jsx-dev-runtime.d.ts +1 -1
- package/dist/jsx-dev-runtime.js.map +1 -1
- package/dist/jsx-runtime.d.ts +1 -1
- package/dist/jsx-runtime.js.map +1 -1
- package/dist/renderer/children.js.map +1 -1
- package/dist/renderer/cleanup.js.map +1 -1
- package/dist/renderer/dom.js +92 -357
- package/dist/renderer/dom.js.map +1 -1
- package/dist/renderer/evaluate.js +7 -0
- package/dist/renderer/evaluate.js.map +1 -1
- package/dist/renderer/fastpath.js +20 -18
- package/dist/renderer/fastpath.js.map +1 -1
- package/dist/renderer/for-commit.js +486 -0
- package/dist/renderer/for-commit.js.map +1 -0
- package/dist/renderer/index.js.map +1 -1
- package/dist/renderer/keyed.js +84 -23
- package/dist/renderer/keyed.js.map +1 -1
- package/dist/renderer/reconcile.js +11 -18
- package/dist/renderer/reconcile.js.map +1 -1
- package/dist/renderer/utils.js +5 -1
- package/dist/renderer/utils.js.map +1 -1
- package/dist/resources/index.d.ts +1 -2
- package/dist/resources/index.js +1 -2
- package/dist/router/index.d.ts +2 -2
- package/dist/router/index.js +2 -2
- package/dist/router/match.js.map +1 -1
- package/dist/router/navigate.d.ts.map +1 -1
- package/dist/router/navigate.js +4 -2
- package/dist/router/navigate.js.map +1 -1
- package/dist/router/policy.js.map +1 -1
- package/dist/router/route-context.js.map +1 -1
- package/dist/router/route.d.ts +1 -1
- package/dist/router/route.d.ts.map +1 -1
- package/dist/router/route.js +2 -33
- package/dist/router/route.js.map +1 -1
- package/dist/runtime/child-scope.d.ts +1 -0
- package/dist/runtime/child-scope.d.ts.map +1 -1
- package/dist/runtime/child-scope.js +2 -0
- package/dist/runtime/child-scope.js.map +1 -1
- package/dist/runtime/component.js +1 -1
- package/dist/runtime/component.js.map +1 -1
- package/dist/runtime/context.js.map +1 -1
- package/dist/runtime/control.js.map +1 -1
- package/dist/runtime/derive.d.ts +2 -1
- package/dist/runtime/derive.d.ts.map +1 -1
- package/dist/runtime/derive.js +15 -10
- package/dist/runtime/derive.js.map +1 -1
- package/dist/runtime/dev-namespace.js.map +1 -1
- package/dist/runtime/effect.d.ts.map +1 -1
- package/dist/runtime/effect.js +34 -9
- package/dist/runtime/effect.js.map +1 -1
- package/dist/runtime/events.js.map +1 -1
- package/dist/runtime/execution-model.js.map +1 -1
- package/dist/runtime/fastlane.js.map +1 -1
- package/dist/runtime/for-bench.d.ts +1 -1
- package/dist/runtime/for-bench.d.ts.map +1 -1
- package/dist/runtime/for-bench.js +15 -14
- package/dist/runtime/for-bench.js.map +1 -1
- package/dist/runtime/for.d.ts +1 -0
- package/dist/runtime/for.d.ts.map +1 -1
- package/dist/runtime/for.js +90 -31
- package/dist/runtime/for.js.map +1 -1
- package/dist/runtime/operations.d.ts.map +1 -1
- package/dist/runtime/operations.js +10 -8
- package/dist/runtime/operations.js.map +1 -1
- package/dist/runtime/perf-metrics.js +8 -2
- package/dist/runtime/perf-metrics.js.map +1 -1
- package/dist/runtime/readable.js.map +1 -1
- package/dist/runtime/resource-cell.js +3 -2
- package/dist/runtime/resource-cell.js.map +1 -1
- package/dist/runtime/scheduler.d.ts +0 -1
- package/dist/runtime/scheduler.d.ts.map +1 -1
- package/dist/runtime/scheduler.js +6 -19
- package/dist/runtime/scheduler.js.map +1 -1
- package/dist/runtime/selector.d.ts.map +1 -1
- package/dist/runtime/selector.js +182 -103
- package/dist/runtime/selector.js.map +1 -1
- package/dist/runtime/snapshot-source.d.ts +10 -0
- package/dist/runtime/snapshot-source.d.ts.map +1 -0
- package/dist/runtime/snapshot-source.js +17 -0
- package/dist/runtime/snapshot-source.js.map +1 -0
- package/dist/runtime/ssr-bridge.js.map +1 -1
- package/dist/runtime/state.d.ts.map +1 -1
- package/dist/runtime/state.js +1 -5
- package/dist/runtime/state.js.map +1 -1
- package/dist/ssg/batch-render.js.map +1 -1
- package/dist/ssg/create-static-gen.js.map +1 -1
- package/dist/ssg/generate-metadata.js.map +1 -1
- package/dist/ssg/incremental-manifest.js.map +1 -1
- package/dist/ssg/index.d.ts +1 -6
- package/dist/ssg/index.js +1 -6
- package/dist/ssg/resolve-ssg-data.js.map +1 -1
- package/dist/ssg/route-utils.js.map +1 -1
- package/dist/ssg/write-static-files.js.map +1 -1
- package/dist/ssr/attrs.js.map +1 -1
- package/dist/ssr/context.d.ts +3 -1
- package/dist/ssr/context.d.ts.map +1 -1
- package/dist/ssr/context.js +31 -11
- package/dist/ssr/context.js.map +1 -1
- package/dist/ssr/escape.js +56 -16
- package/dist/ssr/escape.js.map +1 -1
- package/dist/ssr/index.d.ts +2 -31
- package/dist/ssr/index.d.ts.map +1 -1
- package/dist/ssr/index.js +19 -49
- package/dist/ssr/index.js.map +1 -1
- package/dist/ssr/render-keys.js +1 -12
- package/dist/ssr/render-keys.js.map +1 -1
- package/dist/ssr/sink.js.map +1 -1
- package/dist/ssr/verify-hydration.js +25 -0
- package/dist/ssr/verify-hydration.js.map +1 -0
- package/package.json +44 -19
- package/dist/_virtual/_rolldown/runtime.js +0 -7
- package/dist/foundations/core.d.ts +0 -15
- package/dist/foundations/core.js +0 -13
- package/dist/foundations/structures.d.ts +0 -7
- package/dist/foundations/structures.js +0 -6
- package/dist/ssg/batch-render.d.ts +0 -16
- package/dist/ssg/batch-render.d.ts.map +0 -1
- package/dist/ssg/generate-metadata.d.ts +0 -24
- package/dist/ssg/generate-metadata.d.ts.map +0 -1
- package/dist/ssg/resolve-ssg-data.d.ts +0 -23
- package/dist/ssg/resolve-ssg-data.d.ts.map +0 -1
- package/dist/ssg/route-utils.d.ts +0 -16
- package/dist/ssg/route-utils.d.ts.map +0 -1
- package/dist/ssg/write-static-files.d.ts +0 -15
- package/dist/ssg/write-static-files.d.ts.map +0 -1
- package/dist/ssr/render-keys.d.ts +0 -37
- package/dist/ssr/render-keys.d.ts.map +0 -1
- package/dist/ssr/stream-render.js +0 -76
- package/dist/ssr/stream-render.js.map +0 -1
package/dist/router/navigate.js
CHANGED
|
@@ -12,6 +12,7 @@ import { DefaultPortal } from "../foundations/structures/portal.js";
|
|
|
12
12
|
let currentInstance = null;
|
|
13
13
|
let currentPathname = "/";
|
|
14
14
|
let currentHref = "/";
|
|
15
|
+
let navigationInitialized = false;
|
|
15
16
|
const DEFAULT_SCROLL_RESTORATION = {
|
|
16
17
|
enabled: true,
|
|
17
18
|
navigation: "top",
|
|
@@ -227,7 +228,6 @@ function registerAppInstance(instance, path) {
|
|
|
227
228
|
currentPathname = path;
|
|
228
229
|
currentHref = getWindowHref();
|
|
229
230
|
syncCurrentRouteSnapshot(window.location.pathname, window.location.search, window.location.hash);
|
|
230
|
-
saveScrollPosition(currentHref);
|
|
231
231
|
if (isProductionEnvironment()) lockRouteRegistration();
|
|
232
232
|
}
|
|
233
233
|
/**
|
|
@@ -283,7 +283,9 @@ function handlePopState(_event) {
|
|
|
283
283
|
* Setup popstate listener for browser navigation
|
|
284
284
|
*/
|
|
285
285
|
function initializeNavigation() {
|
|
286
|
-
if (typeof window
|
|
286
|
+
if (typeof window === "undefined" || navigationInitialized) return;
|
|
287
|
+
navigationInitialized = true;
|
|
288
|
+
window.addEventListener("popstate", handlePopState);
|
|
287
289
|
}
|
|
288
290
|
//#endregion
|
|
289
291
|
export { configureScrollRestoration, initializeNavigation, navigate, registerAppInstance };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"navigate.js","names":[],"sources":["../../src/router/navigate.ts"],"sourcesContent":["/**\n * Client-side navigation with History API\n */\n\nimport {\n resolveRoute,\n resolveRouteRequest,\n lockRouteRegistration,\n syncCurrentRouteSnapshot,\n type ResolvedRoute,\n} from './route';\nimport { mountComponent, type ComponentInstance } from '../runtime/component';\nimport {\n isDevelopmentEnvironment,\n isProductionEnvironment,\n} from '../common/env';\nimport { logger } from '../dev/logger';\nimport type { RouteRenderResult, RouteRequestResult } from '../common/router';\nimport { Fragment, ELEMENT_TYPE } from '../jsx';\nimport { DefaultPortal } from '../foundations/structures/portal';\n\n// Global app state for navigation\nlet currentInstance: ComponentInstance | null = null;\nlet currentPathname = '/';\nlet currentHref = '/';\n\nexport type NavigationScrollBehavior = 'top' | 'preserve';\nexport type HistoryScrollBehavior = 'restore' | 'top' | 'preserve';\n\nexport type ScrollRestorationOptions = {\n navigation?: NavigationScrollBehavior;\n history?: HistoryScrollBehavior;\n};\n\ntype NormalizedScrollRestorationOptions = {\n enabled: boolean;\n navigation: NavigationScrollBehavior;\n history: HistoryScrollBehavior;\n};\n\nconst DEFAULT_SCROLL_RESTORATION: NormalizedScrollRestorationOptions = {\n enabled: true,\n navigation: 'top',\n history: 'restore',\n};\n\nlet scrollRestorationOptions: NormalizedScrollRestorationOptions = {\n ...DEFAULT_SCROLL_RESTORATION,\n};\n\nconst scrollPositions = new Map<string, { x: number; y: number }>();\n\nexport type NavigateOptions = {\n history?: 'push' | 'replace';\n scroll?: NavigationScrollBehavior;\n};\n\nfunction getWindowHref(): string {\n if (typeof window === 'undefined') {\n return currentHref;\n }\n\n return `${window.location.pathname}${window.location.search}${window.location.hash}`;\n}\n\nfunction normalizeScrollRestorationOptions(\n options?: boolean | ScrollRestorationOptions\n): NormalizedScrollRestorationOptions {\n if (options === false) {\n return {\n enabled: false,\n navigation: DEFAULT_SCROLL_RESTORATION.navigation,\n history: DEFAULT_SCROLL_RESTORATION.history,\n };\n }\n\n if (options === true || options === undefined) {\n return { ...DEFAULT_SCROLL_RESTORATION };\n }\n\n return {\n enabled: true,\n navigation: options.navigation ?? DEFAULT_SCROLL_RESTORATION.navigation,\n history: options.history ?? DEFAULT_SCROLL_RESTORATION.history,\n };\n}\n\nfunction readScrollPosition(): { x: number; y: number } {\n if (typeof window === 'undefined') {\n return { x: 0, y: 0 };\n }\n\n const x =\n typeof window.scrollX === 'number'\n ? window.scrollX\n : typeof window.pageXOffset === 'number'\n ? window.pageXOffset\n : 0;\n const y =\n typeof window.scrollY === 'number'\n ? window.scrollY\n : typeof window.pageYOffset === 'number'\n ? window.pageYOffset\n : 0;\n\n return { x, y };\n}\n\nfunction writeHistoryScrollPosition(\n href: string,\n position: { x: number; y: number }\n): void {\n if (typeof window === 'undefined' || getWindowHref() !== href) {\n return;\n }\n if (typeof window.history?.replaceState !== 'function') {\n return;\n }\n const state =\n window.history.state && typeof window.history.state === 'object'\n ? window.history.state\n : {};\n\n window.history.replaceState(\n {\n ...state,\n path: href,\n scroll: position,\n },\n '',\n href\n );\n}\n\nfunction saveScrollPosition(href: string): void {\n if (!scrollRestorationOptions.enabled || typeof window === 'undefined') {\n return;\n }\n\n const position = readScrollPosition();\n scrollPositions.set(href, position);\n writeHistoryScrollPosition(href, position);\n}\n\nfunction scrollToPosition(position: { x: number; y: number }): void {\n if (typeof window === 'undefined' || typeof window.scrollTo !== 'function') {\n return;\n }\n\n window.scrollTo(position.x, position.y);\n}\n\nfunction applyNavigationScroll(behavior: NavigationScrollBehavior): void {\n if (!scrollRestorationOptions.enabled || behavior === 'preserve') {\n return;\n }\n\n scrollToPosition({ x: 0, y: 0 });\n}\n\nfunction applyHistoryScroll(href: string, state: PopStateEvent['state']): void {\n if (!scrollRestorationOptions.enabled) {\n return;\n }\n\n if (scrollRestorationOptions.history === 'preserve') {\n return;\n }\n\n if (scrollRestorationOptions.history === 'top') {\n scrollToPosition({ x: 0, y: 0 });\n return;\n }\n\n const fromState =\n state && typeof state === 'object' && 'scroll' in state\n ? (state.scroll as { x?: unknown; y?: unknown })\n : undefined;\n const saved =\n fromState &&\n typeof fromState.x === 'number' &&\n typeof fromState.y === 'number'\n ? { x: fromState.x, y: fromState.y }\n : scrollPositions.get(href);\n\n scrollToPosition(saved ?? { x: 0, y: 0 });\n}\n\nexport function configureScrollRestoration(\n options?: boolean | ScrollRestorationOptions\n): void {\n scrollRestorationOptions = normalizeScrollRestorationOptions(options);\n\n if (typeof window === 'undefined') {\n return;\n }\n\n if ('scrollRestoration' in window.history) {\n try {\n window.history.scrollRestoration = scrollRestorationOptions.enabled\n ? 'manual'\n : 'auto';\n } catch {\n // Ignore environments that expose but do not allow setting scrollRestoration.\n }\n }\n}\n\nfunction parseTargetUrl(path: string): URL {\n const pathname = window.location.pathname || '/';\n const search = window.location.search || '';\n const hash = window.location.hash || '';\n const href =\n typeof window.location.href === 'string' ? window.location.href : '';\n const base =\n href &&\n href !== 'about:blank' &&\n !href.startsWith('about:') &&\n !href.startsWith('data:')\n ? href\n : `http://localhost${pathname}${search}${hash}`;\n\n return new URL(path, base);\n}\n\nfunction isRenderResult(\n result: RouteRequestResult\n): result is RouteRenderResult {\n return result !== null && result.kind === 'render';\n}\n\nfunction isPromise<T>(value: T | Promise<T>): value is Promise<T> {\n return value instanceof Promise;\n}\n\nfunction createDeniedResolvedRoute(status: number): ResolvedRoute {\n return {\n handler: () => ({\n type: 'div',\n props: {\n 'data-route-denied': String(status),\n },\n children: [String(status)],\n }),\n params: {},\n };\n}\n\nfunction bindResolvedRouteHandler(\n resolved: ResolvedRoute\n): ComponentInstance['fn'] {\n return () =>\n resolved.handler(resolved.params) as ReturnType<ComponentInstance['fn']>;\n}\n\nfunction wrapRootRouteHandler(\n componentFn: ComponentInstance['fn']\n): ComponentInstance['fn'] {\n const wrappedFn: ComponentInstance['fn'] = (props, ctx) => {\n const out = componentFn(props, ctx);\n const portalVNode = {\n $$typeof: ELEMENT_TYPE,\n type: DefaultPortal,\n props: {},\n key: '__default_portal',\n } as unknown;\n\n return {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: {\n children:\n out === undefined || out === null\n ? [portalVNode]\n : [out, portalVNode],\n },\n } as ReturnType<ComponentInstance['fn']>;\n };\n\n Object.defineProperty(wrappedFn, 'name', {\n value: componentFn.name || 'Component',\n });\n\n return wrappedFn;\n}\n\nfunction remountResolvedRoute(\n resolved: ResolvedRoute,\n pathname: string,\n href: string\n): boolean {\n if (!currentInstance) {\n return false;\n }\n\n // The route handler IS the component function\n // It takes params as props and renders the route\n currentInstance.fn = wrapRootRouteHandler(bindResolvedRouteHandler(resolved));\n currentInstance.props = {};\n\n // Reset state to prevent leakage from previous route\n // Each route navigation starts completely fresh\n currentInstance.stateValues = [];\n currentInstance.expectedStateIndices = [];\n currentInstance.firstRenderComplete = false;\n currentInstance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n currentInstance.evaluationGeneration++;\n currentInstance.notifyUpdate = null;\n currentInstance.mountOperations = [];\n currentInstance._placeholder = undefined;\n currentInstance.hasPendingUpdate = false;\n\n // Route-local async work should create a fresh abort controller lazily.\n currentInstance.abortController = null;\n\n // Re-execute component against the existing host so reconciliation can\n // preserve any shared layout DOM between sibling routes.\n mountComponent(currentInstance);\n currentPathname = pathname;\n currentHref = href;\n return true;\n}\n\nfunction rerenderResolvedRoute(pathname: string, href: string): boolean {\n if (!currentInstance) {\n return false;\n }\n\n const resolved = resolveRoute(pathname);\n if (!resolved) {\n return false;\n }\n\n currentPathname = pathname;\n currentHref = href;\n currentInstance._enqueueRun?.();\n return true;\n}\n\nfunction resolveNavigationTarget(path: string) {\n const target = parseTargetUrl(path);\n const pathname = target.pathname;\n const href = `${target.pathname}${target.search}${target.hash}`;\n const resolved = resolveRouteRequest(href);\n\n if (isPromise(resolved)) {\n return resolved.then((next) => ({\n href,\n pathname,\n resolved: next,\n }));\n }\n\n return {\n href,\n pathname,\n resolved,\n };\n}\n\nfunction applyNavigationTarget(\n path: string,\n options: NavigateOptions,\n target: {\n href: string;\n pathname: string;\n resolved: RouteRequestResult;\n }\n): void {\n const { href, pathname, resolved } = target;\n const previousPathname = currentPathname;\n\n saveScrollPosition(currentHref);\n\n if (!resolved) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${path}`);\n }\n return;\n }\n\n if (resolved.kind === 'redirect') {\n const redirectTarget = parseTargetUrl(resolved.to);\n const redirectHref = `${redirectTarget.pathname}${redirectTarget.search}${redirectTarget.hash}`;\n if (redirectHref === href) {\n if (isDevelopmentEnvironment()) {\n logger.warn(\n `Navigation guard redirected to the same path: ${redirectHref}`\n );\n }\n return;\n }\n\n navigate(redirectHref, { history: 'replace' });\n return;\n }\n\n const nextResolved =\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n };\n\n const historyMethod =\n options.history === 'replace' ? 'replaceState' : 'pushState';\n window.history[historyMethod]({ path: href }, '', href);\n syncCurrentRouteSnapshot(\n window.location.pathname,\n window.location.search,\n window.location.hash\n );\n\n if (currentInstance) {\n if (pathname === currentPathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(pathname, href);\n return;\n }\n\n remountResolvedRoute(nextResolved, pathname, href);\n if (pathname !== previousPathname) {\n applyNavigationScroll(\n options.scroll ?? scrollRestorationOptions.navigation\n );\n }\n }\n}\n\n/** Register the current app instance (called by createSPA/hydrateSPA). */\nexport function registerAppInstance(\n instance: ComponentInstance,\n path: string\n): void {\n currentInstance = instance;\n currentPathname = path;\n currentHref = getWindowHref();\n syncCurrentRouteSnapshot(\n window.location.pathname,\n window.location.search,\n window.location.hash\n );\n saveScrollPosition(currentHref);\n // Lock further route registrations after the app has started — but allow tests to register routes.\n // Enforce only in production to avoid breaking test infra which registers routes dynamically.\n if (isProductionEnvironment()) {\n lockRouteRegistration();\n }\n}\n\n/**\n * Navigate to a new path\n * Updates URL, resolves route, and re-mounts app with new handler\n */\nexport function navigate(path: string, options: NavigateOptions = {}): void {\n if (typeof window === 'undefined') {\n // SSR context\n return;\n }\n\n const target = resolveNavigationTarget(path);\n if (isPromise(target)) {\n void target.then((resolvedTarget) =>\n applyNavigationTarget(path, options, resolvedTarget)\n );\n return;\n }\n\n applyNavigationTarget(path, options, target);\n}\n\n/**\n * Handle browser back/forward buttons\n */\nfunction handlePopState(_event: PopStateEvent): void {\n const previousHref = currentHref;\n const pathname = window.location.pathname;\n const href = `${window.location.pathname}${window.location.search}${window.location.hash}`;\n\n saveScrollPosition(previousHref);\n\n if (!currentInstance) {\n return;\n }\n\n const resolved = resolveRouteRequest(href);\n\n const applyResolved = (resolved: RouteRequestResult) => {\n if (!resolved) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${pathname}`);\n }\n return;\n }\n\n if (resolved.kind === 'redirect') {\n navigate(resolved.to, { history: 'replace' });\n return;\n }\n\n syncCurrentRouteSnapshot(\n window.location.pathname,\n window.location.search,\n window.location.hash\n );\n\n if (pathname === currentPathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(pathname, href);\n return;\n }\n\n remountResolvedRoute(\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n },\n pathname,\n href\n );\n\n applyHistoryScroll(href, _event.state);\n };\n\n if (isPromise(resolved)) {\n void resolved.then((next) => applyResolved(next));\n return;\n }\n\n applyResolved(resolved);\n}\n\n/**\n * Setup popstate listener for browser navigation\n */\nexport function initializeNavigation(): void {\n if (typeof window !== 'undefined') {\n window.addEventListener('popstate', handlePopState);\n }\n}\n\n/**\n * Cleanup navigation listeners\n */\nexport function cleanupNavigation(): void {\n if (typeof window !== 'undefined') {\n window.removeEventListener('popstate', handlePopState);\n }\n}\n"],"mappings":";;;;;;;;;;;AAsBA,IAAI,kBAA4C;AAChD,IAAI,kBAAkB;AACtB,IAAI,cAAc;AAgBlB,MAAM,6BAAiE;CACrE,SAAS;CACT,YAAY;CACZ,SAAS;CACV;AAED,IAAI,2BAA+D,EACjE,GAAG,4BACJ;AAED,MAAM,kCAAkB,IAAI,KAAuC;AAOnE,SAAS,gBAAwB;AAC/B,KAAI,OAAO,WAAW,YACpB,QAAO;AAGT,QAAO,GAAG,OAAO,SAAS,WAAW,OAAO,SAAS,SAAS,OAAO,SAAS;;AAGhF,SAAS,kCACP,SACoC;AACpC,KAAI,YAAY,MACd,QAAO;EACL,SAAS;EACT,YAAY,2BAA2B;EACvC,SAAS,2BAA2B;EACrC;AAGH,KAAI,YAAY,QAAQ,YAAY,OAClC,QAAO,EAAE,GAAG,4BAA4B;AAG1C,QAAO;EACL,SAAS;EACT,YAAY,QAAQ,cAAc,2BAA2B;EAC7D,SAAS,QAAQ,WAAW,2BAA2B;EACxD;;AAGH,SAAS,qBAA+C;AACtD,KAAI,OAAO,WAAW,YACpB,QAAO;EAAE,GAAG;EAAG,GAAG;EAAG;AAgBvB,QAAO;EAAE,GAZP,OAAO,OAAO,YAAY,WACtB,OAAO,UACP,OAAO,OAAO,gBAAgB,WAC5B,OAAO,cACP;EAQI,GANV,OAAO,OAAO,YAAY,WACtB,OAAO,UACP,OAAO,OAAO,gBAAgB,WAC5B,OAAO,cACP;EAEO;;AAGjB,SAAS,2BACP,MACA,UACM;AACN,KAAI,OAAO,WAAW,eAAe,eAAe,KAAK,KACvD;AAEF,KAAI,OAAO,OAAO,S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AGF,MAAI,SAAS,SAAS,YAAY;AAChC,YAAS,SAAS,IAAI,EAAE,SAAS,WAAW,CAAC;AAC7C;;AAGF,2BACE,OAAO,SAAS,UAChB,OAAO,SAAS,QAChB,OAAO,SAAS,KACjB;AAED,MAAI,aAAa,mBAAmB,eAAe,SAAS,EAAE;AAC5D,yBAAsB,UAAU,KAAK;AACrC;;AAGF,uBACE,SAAS,SAAS,SACd,0BAA0B,SAAS,OAAO,GAC1C;GACE,SAAS,SAAS;GAClB,QAAQ,SAAS;GAClB,EACL,UACA,KACD;AAED,qBAAmB,MAAM,OAAO,MAAM;;AAGxC,KAAI,UAAU,SAAS,EAAE;AACvB,EAAK,SAAS,MAAM,SAAS,cAAc,KAAK,CAAC;AACjD;;AAGF,eAAc,SAAS;;;;;AAMzB,SAAgB,uBAA6B;AAC3C,KAAI,OAAO,WAAW,YACpB,QAAO,iBAAiB,YAAY,eAAe"}
|
|
1
|
+
{"version":3,"file":"navigate.js","names":[],"sources":["../../src/router/navigate.ts"],"sourcesContent":["/**\n * Client-side navigation with History API\n */\n\nimport {\n resolveRoute,\n resolveRouteRequest,\n lockRouteRegistration,\n syncCurrentRouteSnapshot,\n type ResolvedRoute,\n} from './route';\nimport { mountComponent, type ComponentInstance } from '../runtime/component';\nimport {\n isDevelopmentEnvironment,\n isProductionEnvironment,\n} from '../common/env';\nimport { logger } from '../dev/logger';\nimport type { RouteRenderResult, RouteRequestResult } from '../common/router';\nimport { Fragment, ELEMENT_TYPE } from '../jsx';\nimport { DefaultPortal } from '../foundations/structures/portal';\n\n// Global app state for navigation\nlet currentInstance: ComponentInstance | null = null;\nlet currentPathname = '/';\nlet currentHref = '/';\nlet navigationInitialized = false;\n\nexport type NavigationScrollBehavior = 'top' | 'preserve';\nexport type HistoryScrollBehavior = 'restore' | 'top' | 'preserve';\n\nexport type ScrollRestorationOptions = {\n navigation?: NavigationScrollBehavior;\n history?: HistoryScrollBehavior;\n};\n\ntype NormalizedScrollRestorationOptions = {\n enabled: boolean;\n navigation: NavigationScrollBehavior;\n history: HistoryScrollBehavior;\n};\n\nconst DEFAULT_SCROLL_RESTORATION: NormalizedScrollRestorationOptions = {\n enabled: true,\n navigation: 'top',\n history: 'restore',\n};\n\nlet scrollRestorationOptions: NormalizedScrollRestorationOptions = {\n ...DEFAULT_SCROLL_RESTORATION,\n};\n\nconst scrollPositions = new Map<string, { x: number; y: number }>();\n\nexport type NavigateOptions = {\n history?: 'push' | 'replace';\n scroll?: NavigationScrollBehavior;\n};\n\nfunction getWindowHref(): string {\n if (typeof window === 'undefined') {\n return currentHref;\n }\n\n return `${window.location.pathname}${window.location.search}${window.location.hash}`;\n}\n\nfunction normalizeScrollRestorationOptions(\n options?: boolean | ScrollRestorationOptions\n): NormalizedScrollRestorationOptions {\n if (options === false) {\n return {\n enabled: false,\n navigation: DEFAULT_SCROLL_RESTORATION.navigation,\n history: DEFAULT_SCROLL_RESTORATION.history,\n };\n }\n\n if (options === true || options === undefined) {\n return { ...DEFAULT_SCROLL_RESTORATION };\n }\n\n return {\n enabled: true,\n navigation: options.navigation ?? DEFAULT_SCROLL_RESTORATION.navigation,\n history: options.history ?? DEFAULT_SCROLL_RESTORATION.history,\n };\n}\n\nfunction readScrollPosition(): { x: number; y: number } {\n if (typeof window === 'undefined') {\n return { x: 0, y: 0 };\n }\n\n const x =\n typeof window.scrollX === 'number'\n ? window.scrollX\n : typeof window.pageXOffset === 'number'\n ? window.pageXOffset\n : 0;\n const y =\n typeof window.scrollY === 'number'\n ? window.scrollY\n : typeof window.pageYOffset === 'number'\n ? window.pageYOffset\n : 0;\n\n return { x, y };\n}\n\nfunction writeHistoryScrollPosition(\n href: string,\n position: { x: number; y: number }\n): void {\n if (typeof window === 'undefined' || getWindowHref() !== href) {\n return;\n }\n if (typeof window.history?.replaceState !== 'function') {\n return;\n }\n const state =\n window.history.state && typeof window.history.state === 'object'\n ? window.history.state\n : {};\n\n window.history.replaceState(\n {\n ...state,\n path: href,\n scroll: position,\n },\n '',\n href\n );\n}\n\nfunction saveScrollPosition(href: string): void {\n if (!scrollRestorationOptions.enabled || typeof window === 'undefined') {\n return;\n }\n\n const position = readScrollPosition();\n scrollPositions.set(href, position);\n writeHistoryScrollPosition(href, position);\n}\n\nfunction scrollToPosition(position: { x: number; y: number }): void {\n if (typeof window === 'undefined' || typeof window.scrollTo !== 'function') {\n return;\n }\n\n window.scrollTo(position.x, position.y);\n}\n\nfunction applyNavigationScroll(behavior: NavigationScrollBehavior): void {\n if (!scrollRestorationOptions.enabled || behavior === 'preserve') {\n return;\n }\n\n scrollToPosition({ x: 0, y: 0 });\n}\n\nfunction applyHistoryScroll(href: string, state: PopStateEvent['state']): void {\n if (!scrollRestorationOptions.enabled) {\n return;\n }\n\n if (scrollRestorationOptions.history === 'preserve') {\n return;\n }\n\n if (scrollRestorationOptions.history === 'top') {\n scrollToPosition({ x: 0, y: 0 });\n return;\n }\n\n const fromState =\n state && typeof state === 'object' && 'scroll' in state\n ? (state.scroll as { x?: unknown; y?: unknown })\n : undefined;\n const saved =\n fromState &&\n typeof fromState.x === 'number' &&\n typeof fromState.y === 'number'\n ? { x: fromState.x, y: fromState.y }\n : scrollPositions.get(href);\n\n scrollToPosition(saved ?? { x: 0, y: 0 });\n}\n\nexport function configureScrollRestoration(\n options?: boolean | ScrollRestorationOptions\n): void {\n scrollRestorationOptions = normalizeScrollRestorationOptions(options);\n\n if (typeof window === 'undefined') {\n return;\n }\n\n if ('scrollRestoration' in window.history) {\n try {\n window.history.scrollRestoration = scrollRestorationOptions.enabled\n ? 'manual'\n : 'auto';\n } catch {\n // Ignore environments that expose but do not allow setting scrollRestoration.\n }\n }\n}\n\nfunction parseTargetUrl(path: string): URL {\n const pathname = window.location.pathname || '/';\n const search = window.location.search || '';\n const hash = window.location.hash || '';\n const href =\n typeof window.location.href === 'string' ? window.location.href : '';\n const base =\n href &&\n href !== 'about:blank' &&\n !href.startsWith('about:') &&\n !href.startsWith('data:')\n ? href\n : `http://localhost${pathname}${search}${hash}`;\n\n return new URL(path, base);\n}\n\nfunction isRenderResult(\n result: RouteRequestResult\n): result is RouteRenderResult {\n return result !== null && result.kind === 'render';\n}\n\nfunction isPromise<T>(value: T | Promise<T>): value is Promise<T> {\n return value instanceof Promise;\n}\n\nfunction createDeniedResolvedRoute(status: number): ResolvedRoute {\n return {\n handler: () => ({\n type: 'div',\n props: {\n 'data-route-denied': String(status),\n },\n children: [String(status)],\n }),\n params: {},\n };\n}\n\nfunction bindResolvedRouteHandler(\n resolved: ResolvedRoute\n): ComponentInstance['fn'] {\n return () =>\n resolved.handler(resolved.params) as ReturnType<ComponentInstance['fn']>;\n}\n\nfunction wrapRootRouteHandler(\n componentFn: ComponentInstance['fn']\n): ComponentInstance['fn'] {\n const wrappedFn: ComponentInstance['fn'] = (props, ctx) => {\n const out = componentFn(props, ctx);\n const portalVNode = {\n $$typeof: ELEMENT_TYPE,\n type: DefaultPortal,\n props: {},\n key: '__default_portal',\n } as unknown;\n\n return {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: {\n children:\n out === undefined || out === null\n ? [portalVNode]\n : [out, portalVNode],\n },\n } as ReturnType<ComponentInstance['fn']>;\n };\n\n Object.defineProperty(wrappedFn, 'name', {\n value: componentFn.name || 'Component',\n });\n\n return wrappedFn;\n}\n\nfunction remountResolvedRoute(\n resolved: ResolvedRoute,\n pathname: string,\n href: string\n): boolean {\n if (!currentInstance) {\n return false;\n }\n\n // The route handler IS the component function\n // It takes params as props and renders the route\n currentInstance.fn = wrapRootRouteHandler(bindResolvedRouteHandler(resolved));\n currentInstance.props = {};\n\n // Reset state to prevent leakage from previous route\n // Each route navigation starts completely fresh\n currentInstance.stateValues = [];\n currentInstance.expectedStateIndices = [];\n currentInstance.firstRenderComplete = false;\n currentInstance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n currentInstance.evaluationGeneration++;\n currentInstance.notifyUpdate = null;\n currentInstance.mountOperations = [];\n currentInstance._placeholder = undefined;\n currentInstance.hasPendingUpdate = false;\n\n // Route-local async work should create a fresh abort controller lazily.\n currentInstance.abortController = null;\n\n // Re-execute component against the existing host so reconciliation can\n // preserve any shared layout DOM between sibling routes.\n mountComponent(currentInstance);\n currentPathname = pathname;\n currentHref = href;\n return true;\n}\n\nfunction rerenderResolvedRoute(pathname: string, href: string): boolean {\n if (!currentInstance) {\n return false;\n }\n\n const resolved = resolveRoute(pathname);\n if (!resolved) {\n return false;\n }\n\n currentPathname = pathname;\n currentHref = href;\n currentInstance._enqueueRun?.();\n return true;\n}\n\nfunction resolveNavigationTarget(path: string) {\n const target = parseTargetUrl(path);\n const pathname = target.pathname;\n const href = `${target.pathname}${target.search}${target.hash}`;\n const resolved = resolveRouteRequest(href);\n\n if (isPromise(resolved)) {\n return resolved.then((next) => ({\n href,\n pathname,\n resolved: next,\n }));\n }\n\n return {\n href,\n pathname,\n resolved,\n };\n}\n\nfunction applyNavigationTarget(\n path: string,\n options: NavigateOptions,\n target: {\n href: string;\n pathname: string;\n resolved: RouteRequestResult;\n }\n): void {\n const { href, pathname, resolved } = target;\n const previousPathname = currentPathname;\n\n saveScrollPosition(currentHref);\n\n if (!resolved) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${path}`);\n }\n return;\n }\n\n if (resolved.kind === 'redirect') {\n const redirectTarget = parseTargetUrl(resolved.to);\n const redirectHref = `${redirectTarget.pathname}${redirectTarget.search}${redirectTarget.hash}`;\n if (redirectHref === href) {\n if (isDevelopmentEnvironment()) {\n logger.warn(\n `Navigation guard redirected to the same path: ${redirectHref}`\n );\n }\n return;\n }\n\n navigate(redirectHref, { history: 'replace' });\n return;\n }\n\n const nextResolved =\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n };\n\n const historyMethod =\n options.history === 'replace' ? 'replaceState' : 'pushState';\n window.history[historyMethod]({ path: href }, '', href);\n syncCurrentRouteSnapshot(\n window.location.pathname,\n window.location.search,\n window.location.hash\n );\n\n if (currentInstance) {\n if (pathname === currentPathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(pathname, href);\n return;\n }\n\n remountResolvedRoute(nextResolved, pathname, href);\n if (pathname !== previousPathname) {\n applyNavigationScroll(\n options.scroll ?? scrollRestorationOptions.navigation\n );\n }\n }\n}\n\n/** Register the current app instance (called by createSPA/hydrateSPA). */\nexport function registerAppInstance(\n instance: ComponentInstance,\n path: string\n): void {\n currentInstance = instance;\n currentPathname = path;\n currentHref = getWindowHref();\n syncCurrentRouteSnapshot(\n window.location.pathname,\n window.location.search,\n window.location.hash\n );\n // Lock further route registrations after the app has started — but allow tests to register routes.\n // Enforce only in production to avoid breaking test infra which registers routes dynamically.\n if (isProductionEnvironment()) {\n lockRouteRegistration();\n }\n}\n\n/**\n * Navigate to a new path\n * Updates URL, resolves route, and re-mounts app with new handler\n */\nexport function navigate(path: string, options: NavigateOptions = {}): void {\n if (typeof window === 'undefined') {\n // SSR context\n return;\n }\n\n const target = resolveNavigationTarget(path);\n if (isPromise(target)) {\n void target.then((resolvedTarget) =>\n applyNavigationTarget(path, options, resolvedTarget)\n );\n return;\n }\n\n applyNavigationTarget(path, options, target);\n}\n\n/**\n * Handle browser back/forward buttons\n */\nfunction handlePopState(_event: PopStateEvent): void {\n const previousHref = currentHref;\n const pathname = window.location.pathname;\n const href = `${window.location.pathname}${window.location.search}${window.location.hash}`;\n\n saveScrollPosition(previousHref);\n\n if (!currentInstance) {\n return;\n }\n\n const resolved = resolveRouteRequest(href);\n\n const applyResolved = (resolved: RouteRequestResult) => {\n if (!resolved) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${pathname}`);\n }\n return;\n }\n\n if (resolved.kind === 'redirect') {\n navigate(resolved.to, { history: 'replace' });\n return;\n }\n\n syncCurrentRouteSnapshot(\n window.location.pathname,\n window.location.search,\n window.location.hash\n );\n\n if (pathname === currentPathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(pathname, href);\n return;\n }\n\n remountResolvedRoute(\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n },\n pathname,\n href\n );\n\n applyHistoryScroll(href, _event.state);\n };\n\n if (isPromise(resolved)) {\n void resolved.then((next) => applyResolved(next));\n return;\n }\n\n applyResolved(resolved);\n}\n\n/**\n * Setup popstate listener for browser navigation\n */\nexport function initializeNavigation(): void {\n if (typeof window === 'undefined' || navigationInitialized) {\n return;\n }\n\n navigationInitialized = true;\n window.addEventListener('popstate', handlePopState);\n}\n\n/**\n * Cleanup navigation listeners\n */\nexport function cleanupNavigation(): void {\n if (typeof window === 'undefined' || !navigationInitialized) {\n return;\n }\n\n navigationInitialized = false;\n window.removeEventListener('popstate', handlePopState);\n}\n"],"mappings":";;;;;;;;;;;AAsBA,IAAI,kBAA4C;AAChD,IAAI,kBAAkB;AACtB,IAAI,cAAc;AAClB,IAAI,wBAAwB;AAgB5B,MAAM,6BAAiE;CACrE,SAAS;CACT,YAAY;CACZ,SAAS;CACV;AAED,IAAI,2BAA+D,EACjE,GAAG,4BACJ;AAED,MAAM,kCAAkB,IAAI,KAAuC;AAOnE,SAAS,gBAAwB;CAC/B,IAAI,OAAO,WAAW,aACpB,OAAO;CAGT,OAAO,GAAG,OAAO,SAAS,WAAW,OAAO,SAAS,SAAS,OAAO,SAAS;;AAGhF,SAAS,kCACP,SACoC;CACpC,IAAI,YAAY,OACd,OAAO;EACL,SAAS;EACT,YAAY,2BAA2B;EACvC,SAAS,2BAA2B;EACrC;CAGH,IAAI,YAAY,QAAQ,YAAY,QAClC,OAAO,EAAE,GAAG,4BAA4B;CAG1C,OAAO;EACL,SAAS;EACT,YAAY,QAAQ,cAAc,2BAA2B;EAC7D,SAAS,QAAQ,WAAW,2BAA2B;EACxD;;AAGH,SAAS,qBAA+C;CACtD,IAAI,OAAO,WAAW,aACpB,OAAO;EAAE,GAAG;EAAG,GAAG;EAAG;CAgBvB,OAAO;EAAE,GAZP,OAAO,OAAO,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S,WAAW,OAAO,SAAS,SAAS,OAAO,SAAS;CAEpF,mBAAmB,aAAa;CAEhC,IAAI,CAAC,iBACH;CAGF,MAAM,WAAW,oBAAoB,KAAK;CAE1C,MAAM,iBAAiB,aAAiC;EACtD,IAAI,CAAC,UAAU;GACb,IAAI,0BAA0B,EAC5B,OAAO,KAAK,4BAA4B,WAAW;GAErD;;EAGF,IAAI,SAAS,SAAS,YAAY;GAChC,SAAS,SAAS,IAAI,EAAE,SAAS,WAAW,CAAC;GAC7C;;EAGF,yBACE,OAAO,SAAS,UAChB,OAAO,SAAS,QAChB,OAAO,SAAS,KACjB;EAED,IAAI,aAAa,mBAAmB,eAAe,SAAS,EAAE;GAC5D,sBAAsB,UAAU,KAAK;GACrC;;EAGF,qBACE,SAAS,SAAS,SACd,0BAA0B,SAAS,OAAO,GAC1C;GACE,SAAS,SAAS;GAClB,QAAQ,SAAS;GAClB,EACL,UACA,KACD;EAED,mBAAmB,MAAM,OAAO,MAAM;;CAGxC,IAAI,UAAU,SAAS,EAAE;EACvB,AAAK,SAAS,MAAM,SAAS,cAAc,KAAK,CAAC;EACjD;;CAGF,cAAc,SAAS;;;;;AAMzB,SAAgB,uBAA6B;CAC3C,IAAI,OAAO,WAAW,eAAe,uBACnC;CAGF,wBAAwB;CACxB,OAAO,iBAAiB,YAAY,eAAe"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policy.js","names":[],"sources":["../../src/router/policy.ts"],"sourcesContent":["import type {\n AccessDecision,\n AccessDenyStatus,\n AccessRedirectStatus,\n RouteAuthOptions,\n RouteContext,\n RoutePolicy,\n} from '../common/router';\n\nconst ROUTE_AUTH_OPTIONS = Symbol.for('__ASKR_ROUTE_AUTH_OPTIONS__');\n\ntype InternalRouteContext = RouteContext & {\n [ROUTE_AUTH_OPTIONS]?: RouteAuthOptions;\n};\n\ntype RoutePathResolver =\n | string\n | ((context: RouteContext) => string | Promise<string>);\n\nfunction isPromise<T>(value: T | Promise<T>): value is Promise<T> {\n return value instanceof Promise;\n}\n\nexport function allow(): AccessDecision {\n return { kind: 'allow' };\n}\n\nexport function redirect(\n to: string,\n init: {\n status?: AccessRedirectStatus;\n replace?: boolean;\n } = {}\n): AccessDecision {\n return {\n kind: 'redirect',\n to,\n ...(init.status ? { status: init.status } : {}),\n ...(init.replace !== undefined ? { replace: init.replace } : {}),\n };\n}\n\nexport function deny(status: AccessDenyStatus): AccessDecision {\n return { kind: 'deny', status };\n}\n\nexport function unauthorized(): AccessDecision {\n return deny(401);\n}\n\nexport function forbidden(): AccessDecision {\n return deny(403);\n}\n\nexport function notFound(): AccessDecision {\n return deny(404);\n}\n\nexport function normalizeAccessDecision(\n result: AccessDecision\n): AccessDecision {\n return result;\n}\n\nexport function withRouteAuthOptions(\n context: RouteContext,\n auth: RouteAuthOptions | undefined\n): RouteContext {\n const internal = context as InternalRouteContext;\n\n if (!auth) {\n delete internal[ROUTE_AUTH_OPTIONS];\n return context;\n }\n\n internal[ROUTE_AUTH_OPTIONS] = auth;\n return context;\n}\n\nfunction getRouteAuthOptions(\n context: RouteContext\n): RouteAuthOptions | undefined {\n return (context as InternalRouteContext)[ROUTE_AUTH_OPTIONS];\n}\n\nfunction assertRouteAuthOptions(context: RouteContext): RouteAuthOptions {\n const auth = getRouteAuthOptions(context);\n if (!auth?.resolve) {\n throw new Error(\n 'Built-in auth policies require router auth configuration. ' +\n 'Provide `auth` to registerRoutes(...), createSPA(...), hydrateSPA(...), or SSR route resolution.'\n );\n }\n\n return auth;\n}\n\nfunction resolvePathSetting(\n value: RoutePathResolver | undefined,\n fallback: string,\n context: RouteContext\n): string | Promise<string> {\n if (!value) {\n return fallback;\n }\n\n if (typeof value === 'function') {\n return value(context);\n }\n\n return value;\n}\n\nfunction appendNextTarget(path: string, href: string): string {\n const resolved = new URL(path, 'http://localhost');\n resolved.searchParams.set('next', href);\n return `${resolved.pathname}${resolved.search}${resolved.hash}`;\n}\n\nfunction collectStringValues(value: unknown): string[] {\n if (typeof value === 'string') {\n return [value];\n }\n\n if (Array.isArray(value)) {\n return value.filter((entry): entry is string => typeof entry === 'string');\n }\n\n if (value instanceof Set) {\n return Array.from(value).filter(\n (entry): entry is string => typeof entry === 'string'\n );\n }\n\n return [];\n}\n\nfunction defaultHasRole(user: unknown, role: string): boolean {\n if (!user || typeof user !== 'object') {\n return false;\n }\n\n return collectStringValues((user as { roles?: unknown }).roles).includes(\n role\n );\n}\n\nfunction defaultHasPermission(user: unknown, permission: string): boolean {\n if (!user || typeof user !== 'object') {\n return false;\n }\n\n return collectStringValues(\n (user as { permissions?: unknown }).permissions\n ).includes(permission);\n}\n\nfunction resolveUnauthenticatedRedirect(\n context: RouteContext\n): AccessDecision | Promise<AccessDecision> {\n const auth = assertRouteAuthOptions(context);\n const loginPath = resolvePathSetting(auth.loginPath, '/login', context);\n if (isPromise(loginPath)) {\n return loginPath.then((nextPath) =>\n redirect(appendNextTarget(nextPath, context.href), {\n replace: context.mode === 'spa',\n })\n );\n }\n\n return redirect(appendNextTarget(loginPath, context.href), {\n replace: context.mode === 'spa',\n });\n}\n\nfunction resolveAuthenticatedRedirect(\n context: RouteContext\n): AccessDecision | Promise<AccessDecision> {\n const auth = assertRouteAuthOptions(context);\n const target = resolvePathSetting(auth.guestRedirectTo, '/', context);\n if (isPromise(target)) {\n return target.then((nextTarget) =>\n redirect(nextTarget, {\n replace: true,\n })\n );\n }\n\n return redirect(target, {\n replace: true,\n });\n}\n\nexport function requireAuth(): RoutePolicy {\n return (context) => {\n if (context.session) {\n return allow();\n }\n\n return resolveUnauthenticatedRedirect(context);\n };\n}\n\nexport function requireGuest(): RoutePolicy {\n return (context) => {\n if (!context.session) {\n return allow();\n }\n\n return resolveAuthenticatedRedirect(context);\n };\n}\n\nexport function requireRole(role: string): RoutePolicy {\n return (context) => {\n if (!context.user) {\n return resolveUnauthenticatedRedirect(context);\n }\n\n const auth = assertRouteAuthOptions(context);\n const hasRole = auth.hasRole\n ? auth.hasRole(context.user, role, context)\n : defaultHasRole(context.user, role);\n\n if (isPromise(hasRole)) {\n return hasRole.then((next) => (next ? allow() : forbidden()));\n }\n\n return hasRole ? allow() : forbidden();\n };\n}\n\nexport function requirePermission(permission: string): RoutePolicy {\n return (context) => {\n if (!context.user) {\n return resolveUnauthenticatedRedirect(context);\n }\n\n const auth = assertRouteAuthOptions(context);\n const hasPermission = auth.hasPermission\n ? auth.hasPermission(context.user, permission, context)\n : defaultHasPermission(context.user, permission);\n\n if (isPromise(hasPermission)) {\n return hasPermission.then((next) => (next ? allow() : forbidden()));\n }\n\n return hasPermission ? allow() : forbidden();\n };\n}\n\nexport async function evaluateRoutePolicy(\n policy: RoutePolicy,\n context: RouteContext\n): Promise<AccessDecision> {\n const result = await policy(context);\n return result;\n}\n"],"mappings":";AASA,MAAM,qBAAqB,OAAO,IAAI,8BAA8B;AAUpE,SAAS,UAAa,OAA4C;
|
|
1
|
+
{"version":3,"file":"policy.js","names":[],"sources":["../../src/router/policy.ts"],"sourcesContent":["import type {\n AccessDecision,\n AccessDenyStatus,\n AccessRedirectStatus,\n RouteAuthOptions,\n RouteContext,\n RoutePolicy,\n} from '../common/router';\n\nconst ROUTE_AUTH_OPTIONS = Symbol.for('__ASKR_ROUTE_AUTH_OPTIONS__');\n\ntype InternalRouteContext = RouteContext & {\n [ROUTE_AUTH_OPTIONS]?: RouteAuthOptions;\n};\n\ntype RoutePathResolver =\n | string\n | ((context: RouteContext) => string | Promise<string>);\n\nfunction isPromise<T>(value: T | Promise<T>): value is Promise<T> {\n return value instanceof Promise;\n}\n\nexport function allow(): AccessDecision {\n return { kind: 'allow' };\n}\n\nexport function redirect(\n to: string,\n init: {\n status?: AccessRedirectStatus;\n replace?: boolean;\n } = {}\n): AccessDecision {\n return {\n kind: 'redirect',\n to,\n ...(init.status ? { status: init.status } : {}),\n ...(init.replace !== undefined ? { replace: init.replace } : {}),\n };\n}\n\nexport function deny(status: AccessDenyStatus): AccessDecision {\n return { kind: 'deny', status };\n}\n\nexport function unauthorized(): AccessDecision {\n return deny(401);\n}\n\nexport function forbidden(): AccessDecision {\n return deny(403);\n}\n\nexport function notFound(): AccessDecision {\n return deny(404);\n}\n\nexport function normalizeAccessDecision(\n result: AccessDecision\n): AccessDecision {\n return result;\n}\n\nexport function withRouteAuthOptions(\n context: RouteContext,\n auth: RouteAuthOptions | undefined\n): RouteContext {\n const internal = context as InternalRouteContext;\n\n if (!auth) {\n delete internal[ROUTE_AUTH_OPTIONS];\n return context;\n }\n\n internal[ROUTE_AUTH_OPTIONS] = auth;\n return context;\n}\n\nfunction getRouteAuthOptions(\n context: RouteContext\n): RouteAuthOptions | undefined {\n return (context as InternalRouteContext)[ROUTE_AUTH_OPTIONS];\n}\n\nfunction assertRouteAuthOptions(context: RouteContext): RouteAuthOptions {\n const auth = getRouteAuthOptions(context);\n if (!auth?.resolve) {\n throw new Error(\n 'Built-in auth policies require router auth configuration. ' +\n 'Provide `auth` to registerRoutes(...), createSPA(...), hydrateSPA(...), or SSR route resolution.'\n );\n }\n\n return auth;\n}\n\nfunction resolvePathSetting(\n value: RoutePathResolver | undefined,\n fallback: string,\n context: RouteContext\n): string | Promise<string> {\n if (!value) {\n return fallback;\n }\n\n if (typeof value === 'function') {\n return value(context);\n }\n\n return value;\n}\n\nfunction appendNextTarget(path: string, href: string): string {\n const resolved = new URL(path, 'http://localhost');\n resolved.searchParams.set('next', href);\n return `${resolved.pathname}${resolved.search}${resolved.hash}`;\n}\n\nfunction collectStringValues(value: unknown): string[] {\n if (typeof value === 'string') {\n return [value];\n }\n\n if (Array.isArray(value)) {\n return value.filter((entry): entry is string => typeof entry === 'string');\n }\n\n if (value instanceof Set) {\n return Array.from(value).filter(\n (entry): entry is string => typeof entry === 'string'\n );\n }\n\n return [];\n}\n\nfunction defaultHasRole(user: unknown, role: string): boolean {\n if (!user || typeof user !== 'object') {\n return false;\n }\n\n return collectStringValues((user as { roles?: unknown }).roles).includes(\n role\n );\n}\n\nfunction defaultHasPermission(user: unknown, permission: string): boolean {\n if (!user || typeof user !== 'object') {\n return false;\n }\n\n return collectStringValues(\n (user as { permissions?: unknown }).permissions\n ).includes(permission);\n}\n\nfunction resolveUnauthenticatedRedirect(\n context: RouteContext\n): AccessDecision | Promise<AccessDecision> {\n const auth = assertRouteAuthOptions(context);\n const loginPath = resolvePathSetting(auth.loginPath, '/login', context);\n if (isPromise(loginPath)) {\n return loginPath.then((nextPath) =>\n redirect(appendNextTarget(nextPath, context.href), {\n replace: context.mode === 'spa',\n })\n );\n }\n\n return redirect(appendNextTarget(loginPath, context.href), {\n replace: context.mode === 'spa',\n });\n}\n\nfunction resolveAuthenticatedRedirect(\n context: RouteContext\n): AccessDecision | Promise<AccessDecision> {\n const auth = assertRouteAuthOptions(context);\n const target = resolvePathSetting(auth.guestRedirectTo, '/', context);\n if (isPromise(target)) {\n return target.then((nextTarget) =>\n redirect(nextTarget, {\n replace: true,\n })\n );\n }\n\n return redirect(target, {\n replace: true,\n });\n}\n\nexport function requireAuth(): RoutePolicy {\n return (context) => {\n if (context.session) {\n return allow();\n }\n\n return resolveUnauthenticatedRedirect(context);\n };\n}\n\nexport function requireGuest(): RoutePolicy {\n return (context) => {\n if (!context.session) {\n return allow();\n }\n\n return resolveAuthenticatedRedirect(context);\n };\n}\n\nexport function requireRole(role: string): RoutePolicy {\n return (context) => {\n if (!context.user) {\n return resolveUnauthenticatedRedirect(context);\n }\n\n const auth = assertRouteAuthOptions(context);\n const hasRole = auth.hasRole\n ? auth.hasRole(context.user, role, context)\n : defaultHasRole(context.user, role);\n\n if (isPromise(hasRole)) {\n return hasRole.then((next) => (next ? allow() : forbidden()));\n }\n\n return hasRole ? allow() : forbidden();\n };\n}\n\nexport function requirePermission(permission: string): RoutePolicy {\n return (context) => {\n if (!context.user) {\n return resolveUnauthenticatedRedirect(context);\n }\n\n const auth = assertRouteAuthOptions(context);\n const hasPermission = auth.hasPermission\n ? auth.hasPermission(context.user, permission, context)\n : defaultHasPermission(context.user, permission);\n\n if (isPromise(hasPermission)) {\n return hasPermission.then((next) => (next ? allow() : forbidden()));\n }\n\n return hasPermission ? allow() : forbidden();\n };\n}\n\nexport async function evaluateRoutePolicy(\n policy: RoutePolicy,\n context: RouteContext\n): Promise<AccessDecision> {\n const result = await policy(context);\n return result;\n}\n"],"mappings":";AASA,MAAM,qBAAqB,OAAO,IAAI,8BAA8B;AAUpE,SAAS,UAAa,OAA4C;CAChE,OAAO,iBAAiB;;AAG1B,SAAgB,QAAwB;CACtC,OAAO,EAAE,MAAM,SAAS;;AAG1B,SAAgB,SACd,IACA,OAGI,EAAE,EACU;CAChB,OAAO;EACL,MAAM;EACN;EACA,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,QAAQ,GAAG,EAAE;EAC9C,GAAI,KAAK,YAAY,SAAY,EAAE,SAAS,KAAK,SAAS,GAAG,EAAE;EAChE;;AAGH,SAAgB,KAAK,QAA0C;CAC7D,OAAO;EAAE,MAAM;EAAQ;EAAQ;;AAGjC,SAAgB,eAA+B;CAC7C,OAAO,KAAK,IAAI;;AAGlB,SAAgB,YAA4B;CAC1C,OAAO,KAAK,IAAI;;AAGlB,SAAgB,WAA2B;CACzC,OAAO,KAAK,IAAI;;AASlB,SAAgB,qBACd,SACA,MACc;CACd,MAAM,WAAW;CAEjB,IAAI,CAAC,MAAM;EACT,OAAO,SAAS;EAChB,OAAO;;CAGT,SAAS,sBAAsB;CAC/B,OAAO;;AAGT,SAAS,oBACP,SAC8B;CAC9B,OAAQ,QAAiC;;AAG3C,SAAS,uBAAuB,SAAyC;CACvE,MAAM,OAAO,oBAAoB,QAAQ;CACzC,IAAI,CAAC,MAAM,SACT,MAAM,IAAI,MACR,6JAED;CAGH,OAAO;;AAGT,SAAS,mBACP,OACA,UACA,SAC0B;CAC1B,IAAI,CAAC,OACH,OAAO;CAGT,IAAI,OAAO,UAAU,YACnB,OAAO,MAAM,QAAQ;CAGvB,OAAO;;AAGT,SAAS,iBAAiB,MAAc,MAAsB;CAC5D,MAAM,WAAW,IAAI,IAAI,MA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AY;EAClB,IAAI,QAAQ,SACV,OAAO,OAAO;EAGhB,OAAO,+BAA+B,QAAQ;;;AAIlD,SAAgB,eAA4B;CAC1C,QAAQ,YAAY;EAClB,IAAI,CAAC,QAAQ,SACX,OAAO,OAAO;EAGhB,OAAO,6BAA6B,QAAQ;;;AAIhD,SAAgB,YAAY,MAA2B;CACrD,QAAQ,YAAY;EAClB,IAAI,CAAC,QAAQ,MACX,OAAO,+BAA+B,QAAQ;EAGhD,MAAM,OAAO,uBAAuB,QAAQ;EAC5C,MAAM,UAAU,KAAK,UACjB,KAAK,QAAQ,QAAQ,MAAM,MAAM,QAAQ,GACzC,eAAe,QAAQ,MAAM,KAAK;EAEtC,IAAI,UAAU,QAAQ,EACpB,OAAO,QAAQ,MAAM,SAAU,OAAO,OAAO,GAAG,WAAW,CAAE;EAG/D,OAAO,UAAU,OAAO,GAAG,WAAW;;;AAI1C,SAAgB,kBAAkB,YAAiC;CACjE,QAAQ,YAAY;EAClB,IAAI,CAAC,QAAQ,MACX,OAAO,+BAA+B,QAAQ;EAGhD,MAAM,OAAO,uBAAuB,QAAQ;EAC5C,MAAM,gBAAgB,KAAK,gBACvB,KAAK,cAAc,QAAQ,MAAM,YAAY,QAAQ,GACrD,qBAAqB,QAAQ,MAAM,WAAW;EAElD,IAAI,UAAU,cAAc,EAC1B,OAAO,cAAc,MAAM,SAAU,OAAO,OAAO,GAAG,WAAW,CAAE;EAGrE,OAAO,gBAAgB,OAAO,GAAG,WAAW"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-context.js","names":[],"sources":["../../src/router/route-context.ts"],"sourcesContent":["import { withRouteAuthOptions } from './policy';\n\nimport type {\n RouteAuthOptions,\n RouteContext,\n RouteQuery,\n} from '../common/router';\n\nexport function parseLocation(url: string): {\n pathname: string;\n search: string;\n hash: string;\n} {\n try {\n const parsedUrl = new URL(url, 'http://localhost');\n return {\n pathname: parsedUrl.pathname,\n search: parsedUrl.search,\n hash: parsedUrl.hash,\n };\n } catch {\n return { pathname: '/', search: '', hash: '' };\n }\n}\n\nexport function deepFreeze<T>(obj: T): T {\n if (obj && typeof obj === 'object' && !Object.isFrozen(obj)) {\n Object.freeze(obj as Record<string, unknown>);\n for (const key of Object.keys(obj as Record<string, unknown>)) {\n const value = (obj as Record<string, unknown>)[key];\n if (value && typeof value === 'object') {\n deepFreeze(value);\n }\n }\n }\n\n return obj;\n}\n\nexport function makeQuery(search: string): RouteQuery {\n const searchParams = new URLSearchParams(search || '');\n const mapping = new Map<string, string[]>();\n\n for (const [key, value] of searchParams.entries()) {\n const existing = mapping.get(key);\n if (existing) {\n existing.push(value);\n } else {\n mapping.set(key, [value]);\n }\n }\n\n const query: RouteQuery = {\n get(key: string) {\n const values = mapping.get(key);\n return values ? values[0] : null;\n },\n getAll(key: string) {\n const values = mapping.get(key);\n return values ? [...values] : [];\n },\n has(key: string) {\n return mapping.has(key);\n },\n toJSON() {\n const output: Record<string, string | string[]> = {};\n for (const [key, values] of mapping.entries()) {\n output[key] = values.length > 1 ? [...values] : values[0];\n }\n return output;\n },\n };\n\n return deepFreeze(query);\n}\n\nexport function buildRouteContextBase(\n target: string,\n params: Record<string, string>,\n options: {\n mode: RouteContext['mode'];\n signal: AbortSignal;\n }\n): Omit<RouteContext, 'session' | 'user'> {\n const parsed = parseLocation(target);\n const href = `${parsed.pathname}${parsed.search}${parsed.hash}`;\n\n return {\n mode: options.mode,\n params,\n pathname: parsed.pathname,\n search: parsed.search,\n hash: parsed.hash,\n href,\n signal: options.signal,\n };\n}\n\nexport function buildRouteContext(\n target: string,\n params: Record<string, string>,\n options: {\n mode: RouteContext['mode'];\n signal: AbortSignal;\n auth?: RouteAuthOptions;\n session?: unknown;\n user?: unknown;\n }\n): RouteContext {\n const context: RouteContext = {\n ...buildRouteContextBase(target, params, options),\n session: options.session ?? null,\n user: options.user ?? null,\n };\n\n return withRouteAuthOptions(context, options.auth);\n}\n"],"mappings":";;AAQA,SAAgB,cAAc,KAI5B;
|
|
1
|
+
{"version":3,"file":"route-context.js","names":[],"sources":["../../src/router/route-context.ts"],"sourcesContent":["import { withRouteAuthOptions } from './policy';\n\nimport type {\n RouteAuthOptions,\n RouteContext,\n RouteQuery,\n} from '../common/router';\n\nexport function parseLocation(url: string): {\n pathname: string;\n search: string;\n hash: string;\n} {\n try {\n const parsedUrl = new URL(url, 'http://localhost');\n return {\n pathname: parsedUrl.pathname,\n search: parsedUrl.search,\n hash: parsedUrl.hash,\n };\n } catch {\n return { pathname: '/', search: '', hash: '' };\n }\n}\n\nexport function deepFreeze<T>(obj: T): T {\n if (obj && typeof obj === 'object' && !Object.isFrozen(obj)) {\n Object.freeze(obj as Record<string, unknown>);\n for (const key of Object.keys(obj as Record<string, unknown>)) {\n const value = (obj as Record<string, unknown>)[key];\n if (value && typeof value === 'object') {\n deepFreeze(value);\n }\n }\n }\n\n return obj;\n}\n\nexport function makeQuery(search: string): RouteQuery {\n const searchParams = new URLSearchParams(search || '');\n const mapping = new Map<string, string[]>();\n\n for (const [key, value] of searchParams.entries()) {\n const existing = mapping.get(key);\n if (existing) {\n existing.push(value);\n } else {\n mapping.set(key, [value]);\n }\n }\n\n const query: RouteQuery = {\n get(key: string) {\n const values = mapping.get(key);\n return values ? values[0] : null;\n },\n getAll(key: string) {\n const values = mapping.get(key);\n return values ? [...values] : [];\n },\n has(key: string) {\n return mapping.has(key);\n },\n toJSON() {\n const output: Record<string, string | string[]> = {};\n for (const [key, values] of mapping.entries()) {\n output[key] = values.length > 1 ? [...values] : values[0];\n }\n return output;\n },\n };\n\n return deepFreeze(query);\n}\n\nexport function buildRouteContextBase(\n target: string,\n params: Record<string, string>,\n options: {\n mode: RouteContext['mode'];\n signal: AbortSignal;\n }\n): Omit<RouteContext, 'session' | 'user'> {\n const parsed = parseLocation(target);\n const href = `${parsed.pathname}${parsed.search}${parsed.hash}`;\n\n return {\n mode: options.mode,\n params,\n pathname: parsed.pathname,\n search: parsed.search,\n hash: parsed.hash,\n href,\n signal: options.signal,\n };\n}\n\nexport function buildRouteContext(\n target: string,\n params: Record<string, string>,\n options: {\n mode: RouteContext['mode'];\n signal: AbortSignal;\n auth?: RouteAuthOptions;\n session?: unknown;\n user?: unknown;\n }\n): RouteContext {\n const context: RouteContext = {\n ...buildRouteContextBase(target, params, options),\n session: options.session ?? null,\n user: options.user ?? null,\n };\n\n return withRouteAuthOptions(context, options.auth);\n}\n"],"mappings":";;AAQA,SAAgB,cAAc,KAI5B;CACA,IAAI;EACF,MAAM,YAAY,IAAI,IAAI,KAAK,mBAAmB;EAClD,OAAO;GACL,UAAU,UAAU;GACpB,QAAQ,UAAU;GAClB,MAAM,UAAU;GACjB;SACK;EACN,OAAO;GAAE,UAAU;GAAK,QAAQ;GAAI,MAAM;GAAI;;;AAIlD,SAAgB,WAAc,KAAW;CACvC,IAAI,OAAO,OAAO,QAAQ,YAAY,CAAC,OAAO,SAAS,IAAI,EAAE;EAC3D,OAAO,OAAO,IAA+B;EAC7C,KAAK,MAAM,OAAO,OAAO,KAAK,IAA+B,EAAE;GAC7D,MAAM,QAAS,IAAgC;GAC/C,IAAI,SAAS,OAAO,UAAU,UAC5B,WAAW,MAAM;;;CAKvB,OAAO;;AAGT,SAAgB,UAAU,QAA4B;CACpD,MAAM,eAAe,IAAI,gBAAgB,UAAU,GAAG;CACtD,MAAM,0BAAU,IAAI,KAAuB;CAE3C,KAAK,MAAM,CAAC,KAAK,UAAU,aAAa,SAAS,EAAE;EACjD,MAAM,WAAW,QAAQ,IAAI,IAAI;EACjC,IAAI,UACF,SAAS,KAAK,MAAM;OAEpB,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC;;CAyB7B,OAAO,WAAW;EApBhB,IAAI,KAAa;GACf,MAAM,SAAS,QAAQ,IAAI,IAAI;GAC/B,OAAO,SAAS,OAAO,KAAK;;EAE9B,OAAO,KAAa;GAClB,MAAM,SAAS,QAAQ,IAAI,IAAI;GAC/B,OAAO,SAAS,CAAC,GAAG,OAAO,GAAG,EAAE;;EAElC,IAAI,KAAa;GACf,OAAO,QAAQ,IAAI,IAAI;;EAEzB,SAAS;GACP,MAAM,SAA4C,EAAE;GACpD,KAAK,MAAM,CAAC,KAAK,WAAW,QAAQ,SAAS,EAC3C,OAAO,OAAO,OAAO,SAAS,IAAI,CAAC,GAAG,OAAO,GAAG,OAAO;GAEzD,OAAO;;EAIO,CAAM;;AAG1B,SAAgB,sBACd,QACA,QACA,SAIwC;CACxC,MAAM,SAAS,cAAc,OAAO;CACpC,MAAM,OAAO,GAAG,OAAO,WAAW,OAAO,SAAS,OAAO;CAEzD,OAAO;EACL,MAAM,QAAQ;EACd;EACA,UAAU,OAAO;EACjB,QAAQ,OAAO;EACf,MAAM,OAAO;EACb;EACA,QAAQ,QAAQ;EACjB;;AAGH,SAAgB,kBACd,QACA,QACA,SAOc;CAOd,OAAO,qBAAqB;EAL1B,GAAG,sBAAsB,QAAQ,QAAQ,QAAQ;EACjD,SAAS,QAAQ,WAAW;EAC5B,MAAM,QAAQ,QAAQ;EAGI,EAAS,QAAQ,KAAK"}
|
package/dist/router/route.d.ts
CHANGED
|
@@ -125,5 +125,5 @@ declare function resolveRouteRequest(target: string, options?: RouteRequestOptio
|
|
|
125
125
|
*/
|
|
126
126
|
declare function resolveRouteFromRoutes(pathname: string, routeList: readonly Route[]): ResolvedRoute | null;
|
|
127
127
|
//#endregion
|
|
128
|
-
export { Outlet,
|
|
128
|
+
export { Outlet, clearRoutes, currentRoute, fallback, getManifest, getRoutes, group, index, lazy, page, registerRoutes, route };
|
|
129
129
|
//# sourceMappingURL=route.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route.d.ts","names":[],"sources":["../../src/router/route.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"route.d.ts","names":[],"sources":["../../src/router/route.ts"],"mappings":";;;iBAgOgB,iBAAA,CAAkB,GAAA;AAAA,iBA8MlB,0BAAA,CACd,IAAA,EAAM,gBAAA;AAuFR;;;;AAAA,iBAJgB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;;;iBAynBgB,YAAA,CAAa,QAAA,WAAmB,aAAA;AAAA,iBAuHhC,mBAAA,CACd,MAAA,UACA,OAAA,GAAS,mBAAA,GACR,kBAAA,GAAqB,OAAA,CAAQ,kBAAA;;;;;;;;;AA3WhC;;;;;AAiBA;iBA8ZgB,sBAAA,CACd,QAAA,UACA,SAAA,WAAoB,KAAA,KACnB,aAAA"}
|
package/dist/router/route.js
CHANGED
|
@@ -547,10 +547,6 @@ function currentRoute() {
|
|
|
547
547
|
const instance = getCurrentComponentInstance();
|
|
548
548
|
if (!instance) throw new Error("currentRoute() can only be called during component render execution. Call currentRoute() from inside your component function.");
|
|
549
549
|
if (typeof window === "undefined" || instance.ssr) return readCurrentRouteSnapshot();
|
|
550
|
-
if (currentRouteSnapshot.path !== (window.location.pathname || "/")) {
|
|
551
|
-
recordReadableRead(currentRouteSource);
|
|
552
|
-
return readCurrentRouteSnapshot();
|
|
553
|
-
}
|
|
554
550
|
recordReadableRead(currentRouteSource);
|
|
555
551
|
return readCurrentRouteSnapshot();
|
|
556
552
|
}
|
|
@@ -558,8 +554,8 @@ function syncCurrentRouteSnapshot(pathname, search, hash) {
|
|
|
558
554
|
setCurrentRouteSnapshot(pathname, search, hash);
|
|
559
555
|
}
|
|
560
556
|
function route(path, Component, options) {
|
|
561
|
-
if (getExecutionModel() === "islands") throw new Error("Routes are not supported with islands. Use createSPA (client) or createSSR (server) instead.");
|
|
562
557
|
if (typeof path === "undefined") throw new Error("route() is only for route registration. Use currentRoute() inside components.");
|
|
558
|
+
if (getExecutionModel() === "islands") throw new Error("Routes are not supported with islands. Use createSPA (client) or createSSR (server) instead.");
|
|
563
559
|
const currentInst = getCurrentComponentInstance();
|
|
564
560
|
if (currentInst && currentInst.ssr) throw new Error("route() cannot be called during SSR rendering. Register routes at module load time instead.");
|
|
565
561
|
if (registrationLocked) throw new Error("Route registration is locked after app startup. Register routes at module load time before calling createSPA or createSSR.");
|
|
@@ -606,27 +602,6 @@ function _applyManifest(manifest) {
|
|
|
606
602
|
function getRoutes() {
|
|
607
603
|
return [...routes];
|
|
608
604
|
}
|
|
609
|
-
/** Get routes for a specific namespace. */
|
|
610
|
-
function getNamespaceRoutes(namespace) {
|
|
611
|
-
return routes.filter((r) => r.namespace === namespace);
|
|
612
|
-
}
|
|
613
|
-
/** Unload all routes from a namespace (for MFE unmounting). */
|
|
614
|
-
function unloadNamespace(namespace) {
|
|
615
|
-
const before = routes.length;
|
|
616
|
-
for (let i = routes.length - 1; i >= 0; i--) if (routes[i].namespace === namespace) {
|
|
617
|
-
const removed = routes[i];
|
|
618
|
-
routes.splice(i, 1);
|
|
619
|
-
const depth = getDepth(removed.path);
|
|
620
|
-
const depthRoutes = routesByDepth.get(depth);
|
|
621
|
-
if (depthRoutes) {
|
|
622
|
-
const idx = depthRoutes.indexOf(removed);
|
|
623
|
-
if (idx >= 0) depthRoutes.splice(idx, 1);
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
for (let i = records.length - 1; i >= 0; i--) if (records[i].options.namespace === namespace) records.splice(i, 1);
|
|
627
|
-
namespaces.delete(namespace);
|
|
628
|
-
return before - routes.length;
|
|
629
|
-
}
|
|
630
605
|
/** Clear all registered routes and records (testing / boot reset). */
|
|
631
606
|
function clearRoutes() {
|
|
632
607
|
routes.length = 0;
|
|
@@ -641,12 +616,6 @@ function clearRoutes() {
|
|
|
641
616
|
setHasRoutes(false);
|
|
642
617
|
pendingLazy.clear();
|
|
643
618
|
}
|
|
644
|
-
/**
|
|
645
|
-
* Get all loaded namespaces (MFE identifiers)
|
|
646
|
-
*/
|
|
647
|
-
function getLoadedNamespaces() {
|
|
648
|
-
return Array.from(namespaces);
|
|
649
|
-
}
|
|
650
619
|
function findBestScopedFallbackRecord(pathname, routeRecords) {
|
|
651
620
|
let bestRecord = null;
|
|
652
621
|
let bestParams = null;
|
|
@@ -784,6 +753,6 @@ function resolveRouteFromRoutes(pathname, routeList) {
|
|
|
784
753
|
} : null;
|
|
785
754
|
}
|
|
786
755
|
//#endregion
|
|
787
|
-
export { Outlet, _applyManifest, _drainLazy, _setActiveRouteAuthOptions, _snapshotLazy, clearRoutes, currentRoute, fallback,
|
|
756
|
+
export { Outlet, _applyManifest, _drainLazy, _setActiveRouteAuthOptions, _snapshotLazy, clearRoutes, currentRoute, fallback, getManifest, getRoutes, group, index, lazy, lockRouteRegistration, page, registerRoutes, resolveRoute, resolveRouteFromRoutes, resolveRouteRequest, route, setServerLocation, syncCurrentRouteSnapshot };
|
|
788
757
|
|
|
789
758
|
//# sourceMappingURL=route.js.map
|
package/dist/router/route.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route.js","names":[],"sources":["../../src/router/route.ts"],"sourcesContent":["/**\n * Route definition, registration, and matching.\n *\n * Primary public authoring:\n * - `registerRoutes(() => { ... }, options?)`\n * - `group(options, () => { ... })`\n * - `page(path, Component, () => { ... })`\n * - `index(Component, options?)`\n * - `route(path, Component, options?)`\n * - `fallback(Component)`\n * - `Outlet()` for page child rendering\n * - `currentRoute()` for render-time access\n *\n */\n\nimport { matchSegments, parseSegments, computeRank } from './match';\nimport {\n buildRouteContext,\n buildRouteContextBase,\n deepFreeze,\n makeQuery,\n parseLocation,\n} from './route-context';\nimport { defineContext, readContext } from '../runtime/context';\nimport { getCurrentComponentInstance } from '../runtime/component';\nimport { getExecutionModel } from '../runtime/execution-model';\nimport {\n markReadableDerivedSubscribersDirty,\n markReactivePropsDirtySource,\n notifyReadableReaders,\n recordReadableRead,\n type ReadableSource,\n} from '../runtime/readable';\nimport { getRenderContext } from '../ssr/context';\nimport {\n requireAuth,\n requireGuest,\n requirePermission,\n requireRole,\n} from './policy';\n\nexport type {\n AccessDecision,\n AccessDenyDecision,\n AccessRedirectDecision,\n GroupHelperOptions,\n PageHelperOptions,\n RegisterRoutesOptions,\n RouteDefinition,\n RouteAuthOptions,\n RouteHandler,\n Route,\n RouteContext,\n RoutePolicy,\n RouteRenderResult,\n RouteRequestOptions,\n RouteRequestResult,\n ResolvedRoute,\n RouteMatch,\n RouteQuery,\n RouteSnapshot,\n RouteComponent,\n RouteOptions,\n ParsedSegment,\n LayoutScopeRecord,\n PageScopeRecord,\n RouteRecord,\n RouteManifest,\n} from '../common/router';\n\nimport type {\n AccessDecision,\n AccessDenyDecision,\n AccessRedirectDecision,\n GroupHelperOptions,\n PageHelperOptions,\n RegisterRoutesOptions,\n RouteDefinition,\n RouteAuthOptions,\n RouteHandler,\n Route,\n RouteContext,\n RoutePolicy,\n RouteRenderResult,\n RouteRequestOptions,\n RouteRequestResult,\n ResolvedRoute,\n RouteMatch,\n RouteQuery,\n RouteSnapshot,\n RouteComponent,\n RouteOptions,\n LayoutScopeRecord,\n PageScopeRecord,\n RouteRecord,\n RouteManifest,\n} from '../common/router';\n\n// ---------------------------------------------------------------------------\n// Module-level stores\n// ---------------------------------------------------------------------------\n\n/** Legacy flat route array — kept for resolver and route() accessor backward compat. */\ntype InternalRoute = Route & {\n fallbackPrefix?: string;\n};\n\ntype InternalRouteRecord = RouteRecord & {\n fallbackPrefix?: string;\n};\n\nconst routes: InternalRoute[] = [];\n\n/** Normalized route records built by the declarative registration API. */\nconst records: InternalRouteRecord[] = [];\n\ntype RegistrationScope = {\n kind: 'group' | 'page';\n pathPrefix: string;\n layout?: LayoutScopeRecord['component'];\n page?: PageScopeRecord['component'];\n policies: readonly RoutePolicy[];\n state: AccessScopeState;\n};\n\ntype RegistrationSession = {\n authConfigured: boolean;\n};\n\n/** Active registration scope stack during module-load-time registration. */\nconst registrationScopeStack: RegistrationScope[] = [];\nconst registrationSessionStack: RegistrationSession[] = [];\n\nconst namespaces = new Set<string>();\nlet registrationLocked = false;\n\ntype AccessScopeState = {\n guestOnly: boolean;\n authenticated: boolean;\n};\n\nlet defaultRouteAuthOptions: RouteAuthOptions | undefined;\nlet activeClientRouteAuthOptions: RouteAuthOptions | undefined;\n\nconst HAS_ROUTES_KEY = Symbol.for('__ASKR_HAS_ROUTES__');\n\nfunction setHasRoutes(value: boolean): void {\n try {\n const g = globalThis as unknown as Record<string | symbol, unknown>;\n g[HAS_ROUTES_KEY] = value;\n } catch {\n // ignore\n }\n}\n\n// Initialize to false at module load.\nsetHasRoutes(false);\n\n// Route index by depth - maintains insertion order\nconst routesByDepth = new Map<number, Route[]>();\n\n/**\n * Parse route path depth\n */\nfunction getDepth(path: string): number {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n return normalized === '/' ? 0 : normalized.split('/').filter(Boolean).length;\n}\n\n// ---------------------------------------------------------------------------\n// WeakMap caches for external Route[] objects (e.g. SSR per-request tables)\n// Amortises parseSegments / computeRank across repeated resolveRouteFromRoutes\n// calls on the same route list (same object reference).\n// ---------------------------------------------------------------------------\n\n/** Pre-parsed segments for an externally supplied Route object. */\nconst routeSegsCache = new WeakMap<Route, ReturnType<typeof parseSegments>>();\n/** Pre-computed rank for an externally supplied Route object. */\nconst routeRankCache = new WeakMap<Route, number>();\n/** A rank-descending sorted copy of an external readonly Route array. */\nconst sortedListCache = new WeakMap<\n ReadonlyArray<Route>,\n ReadonlyArray<Route>\n>();\n\nfunction cachedSegs(r: Route): ReturnType<typeof parseSegments> {\n let s = routeSegsCache.get(r);\n if (!s) {\n s = parseSegments(r.path);\n routeSegsCache.set(r, s);\n }\n return s;\n}\n\nfunction cachedRank(r: Route): number {\n let n = routeRankCache.get(r);\n if (n === undefined) {\n n = computeRank(cachedSegs(r));\n routeRankCache.set(r, n);\n }\n return n;\n}\n\nfunction cachedSortedList(\n routeList: ReadonlyArray<Route>\n): ReadonlyArray<Route> {\n let sorted = sortedListCache.get(routeList);\n if (!sorted) {\n sorted = [...routeList].sort((a, b) => cachedRank(b) - cachedRank(a));\n sortedListCache.set(routeList, sorted);\n }\n return sorted;\n}\n\nlet currentRouteSnapshot = buildRouteSnapshot('/', '', '');\n\nconst currentRouteSource = (() =>\n currentRouteSnapshot) as ReadableSource<RouteSnapshot> &\n (() => RouteSnapshot);\n\ncurrentRouteSource._readers = new Map();\n\n// SSR helper: when rendering on the server, callers may set a location so that\n// render-time route() returns deterministic server values that match client\n// hydration. This is deliberately an opt-in escape for SSR and tests.\nlet serverLocation: string | null = null;\n\nexport function setServerLocation(url: string | null): void {\n serverLocation = url;\n}\n\nfunction isPromise<T>(value: T | Promise<T>): value is Promise<T> {\n return value instanceof Promise;\n}\n\nfunction buildRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): RouteSnapshot {\n const query = makeQuery(search);\n const matches = computeMatchesFromRoutes(pathname, getActiveRoutes());\n\n return Object.freeze({\n path: pathname,\n params: deepFreeze({ ...matches[0]?.params }),\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n}\n\nfunction setCurrentRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): void {\n currentRouteSnapshot = buildRouteSnapshot(pathname, search, hash);\n\n const instance = getCurrentComponentInstance();\n markReadableDerivedSubscribersDirty(currentRouteSource);\n markReactivePropsDirtySource(currentRouteSource);\n notifyReadableReaders(currentRouteSource, instance);\n}\n\n// Compute matches for a specific route list.\nfunction matchFallbackPrefix(\n pathname: string,\n fallbackPrefix: string\n): Record<string, string> | null {\n const normalizedPath =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const normalizedPrefix =\n fallbackPrefix.endsWith('/') && fallbackPrefix !== '/'\n ? fallbackPrefix.slice(0, -1)\n : fallbackPrefix;\n\n if (normalizedPrefix === '/') {\n const urlParts =\n normalizedPath === '/' ? [] : normalizedPath.split('/').filter(Boolean);\n return {\n '*':\n urlParts.length === 0\n ? '/'\n : urlParts.length === 1\n ? urlParts[0]\n : '/' + urlParts.join('/'),\n };\n }\n\n if (\n normalizedPath !== normalizedPrefix &&\n !normalizedPath.startsWith(`${normalizedPrefix}/`)\n ) {\n return null;\n }\n\n const remainder =\n normalizedPath === normalizedPrefix\n ? '/'\n : normalizedPath.slice(normalizedPrefix.length + 1);\n const remainderParts =\n remainder === '/' ? [] : remainder.split('/').filter(Boolean);\n\n return {\n '*':\n remainderParts.length === 0\n ? '/'\n : remainderParts.length === 1\n ? remainderParts[0]\n : '/' + remainderParts.join('/'),\n };\n}\n\nfunction computeMatchesFromRoutes(\n pathname: string,\n routesList: readonly Route[]\n): RouteMatch[] {\n const bestMatch =\n routesList === routes\n ? getMatchingRecord(pathname, records)\n : findBestResolvedRouteFromRoutes(pathname, routesList);\n\n if (!bestMatch) {\n return [];\n }\n\n return [\n {\n path: 'route' in bestMatch ? bestMatch.route.path : bestMatch.record.path,\n params: deepFreeze({ ...bestMatch.params }),\n name:\n 'route' in bestMatch\n ? (bestMatch.route as { name?: string }).name\n : undefined,\n namespace:\n 'route' in bestMatch\n ? bestMatch.route.namespace\n : bestMatch.record.options.namespace,\n },\n ];\n}\n\nfunction findBestResolvedRouteFromRoutes(\n pathname: string,\n routeList: readonly Route[]\n): { route: Route; params: Record<string, string> } | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n const sorted = cachedSortedList(routeList);\n let bestRoute: Route | null = null;\n let bestParams: Record<string, string> = {};\n let bestRank = -Infinity;\n\n for (const route of sorted) {\n const internalRoute = route as InternalRoute;\n if (internalRoute.fallbackPrefix) {\n continue;\n }\n\n const rank = cachedRank(route);\n if (rank < bestRank) break;\n if (bestRoute !== null && rank === bestRank) continue;\n\n const params = matchSegments(urlParts, cachedSegs(route));\n if (params !== null) {\n bestRoute = route;\n bestParams = params;\n bestRank = rank;\n }\n }\n\n if (bestRoute !== null) {\n return { route: bestRoute, params: bestParams };\n }\n\n let bestFallback: InternalRoute | null = null;\n let bestFallbackParams: Record<string, string> | null = null;\n let bestPrefixLength = -1;\n\n for (const route of routeList) {\n const internalRoute = route as InternalRoute;\n if (!internalRoute.fallbackPrefix) {\n continue;\n }\n\n const params = matchFallbackPrefix(\n normalized,\n internalRoute.fallbackPrefix\n );\n if (params === null) {\n continue;\n }\n\n if (internalRoute.fallbackPrefix.length > bestPrefixLength) {\n bestFallback = internalRoute;\n bestFallbackParams = params;\n bestPrefixLength = internalRoute.fallbackPrefix.length;\n }\n }\n\n return bestFallback && bestFallbackParams\n ? { route: bestFallback, params: bestFallbackParams }\n : null;\n}\n\nfunction getActiveRoutes(): readonly Route[] {\n const renderContext = getRenderContext();\n return renderContext?.routes ?? routes;\n}\n\nfunction getActiveRouteAuthOptions(\n override?: RouteAuthOptions\n): RouteAuthOptions | undefined {\n if (override) {\n return override;\n }\n\n const renderContext = getRenderContext();\n return (\n renderContext?.routeAuth ??\n activeClientRouteAuthOptions ??\n defaultRouteAuthOptions\n );\n}\n\nexport function _setActiveRouteAuthOptions(\n auth: RouteAuthOptions | undefined\n): void {\n activeClientRouteAuthOptions = auth;\n}\n\nfunction getCurrentRegistrationSession(): RegistrationSession {\n return (\n registrationSessionStack[registrationSessionStack.length - 1] ?? {\n authConfigured: !!defaultRouteAuthOptions?.resolve,\n }\n );\n}\n\nfunction getCurrentAccessScopeState(): AccessScopeState {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.state ?? {\n guestOnly: false,\n authenticated: false,\n }\n );\n}\n\nfunction getCurrentLayoutChain(): LayoutScopeRecord[] {\n const layoutChain: LayoutScopeRecord[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.layout) {\n layoutChain.push({ component: scope.layout });\n }\n }\n\n return layoutChain;\n}\n\nfunction getCurrentPageChain(): PageScopeRecord[] {\n const pageChain: PageScopeRecord[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.page) {\n pageChain.push({ component: scope.page });\n }\n }\n\n return pageChain;\n}\n\nfunction hasActivePageScope(): boolean {\n return registrationScopeStack.some((scope) => !!scope.page);\n}\n\nfunction getCurrentScopeKind(): RegistrationScope['kind'] | null {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.kind ?? null\n );\n}\n\nfunction getCurrentPathPrefix(): string {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.pathPrefix ?? ''\n );\n}\n\nfunction getCurrentInheritedPolicies(): RoutePolicy[] {\n const policies: RoutePolicy[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.policies.length > 0) {\n policies.push(...scope.policies);\n }\n }\n\n return policies;\n}\n\n// ---------------------------------------------------------------------------\n// Registration lock\n// ---------------------------------------------------------------------------\n\n/**\n * Prevent route registrations after the app has started.\n * Enforced in production; tests may unlock explicitly.\n */\n\nexport function lockRouteRegistration(): void {\n registrationLocked = true;\n}\n\nexport function _lockRouteRegistrationForTests(): void {\n registrationLocked = true;\n}\n\nexport function _unlockRouteRegistrationForTests(): void {\n registrationLocked = false;\n}\n\n// ---------------------------------------------------------------------------\n// Path validation\n// ---------------------------------------------------------------------------\n\nfunction validateRoutePath(path: string): void {\n if (!path.startsWith('/')) {\n throw new Error(`Route path must begin with \"/\". Got: \"${path}\"`);\n }\n // Reject Express-style :param syntax — Askr uses {param} interpolation\n if (/:([^/{}]+)/.test(path)) {\n const suggested = path.replace(/:([^/{}]+)/g, '{$1}');\n throw new Error(\n `Route parameter syntax uses {name} interpolation, not :name. ` +\n `Use \"${suggested}\" instead of \"${path}\".`\n );\n }\n}\n\nfunction normalizeAbsoluteRoutePath(path: string): string {\n if (!path || path === '/') {\n return '/';\n }\n\n const normalized = path.endsWith('/') ? path.slice(0, -1) : path;\n return normalized || '/';\n}\n\nfunction joinRoutePaths(prefix: string, path: string): string {\n const normalizedPrefix = normalizeAbsoluteRoutePath(prefix || '/');\n const normalizedPath = path.replace(/^\\/+|\\/+$/g, '');\n\n if (!normalizedPath) {\n return normalizedPrefix;\n }\n\n return normalizedPrefix === '/'\n ? `/${normalizedPath}`\n : `${normalizedPrefix}/${normalizedPath}`;\n}\n\nfunction resolvePageScopePath(path: string): string {\n if (!path) {\n throw new Error('page(path, Component, fn) requires a non-empty path.');\n }\n\n if (path.startsWith('/')) {\n validateRoutePath(path);\n return normalizeAbsoluteRoutePath(path);\n }\n\n return joinRoutePaths(getCurrentPathPrefix(), path);\n}\n\nfunction resolveIndexPath(): string {\n return normalizeAbsoluteRoutePath(getCurrentPathPrefix() || '/');\n}\n\nfunction resolveRouteRegistrationPath(path: string): string {\n if (path.startsWith('/')) {\n if (hasActivePageScope()) {\n throw new Error(\n 'Child route paths inside page() must be relative. ' +\n `Use \"${path.slice(1)}\" instead of \"${path}\".`\n );\n }\n\n validateRoutePath(path);\n return normalizeAbsoluteRoutePath(path);\n }\n\n const prefix = getCurrentPathPrefix();\n\n if (!prefix) {\n throw new Error(`Route path must begin with \"/\". Got: \"${path}\"`);\n }\n\n return joinRoutePaths(prefix, path);\n}\n\n// ---------------------------------------------------------------------------\n// Internal helper: insert a RouteRecord in rank-descending order\n// so that resolveRoute can use first-match-wins without sorting.\n// Ties preserve declaration order (stable binary-search insertion).\n// ---------------------------------------------------------------------------\n\nfunction insertRecordSorted(record: RouteRecord): void {\n let lo = 0;\n let hi = records.length;\n // Find the insertion point: after all existing records with rank >= this one\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (records[mid].rank >= record.rank) lo = mid + 1;\n else hi = mid;\n }\n records.splice(lo, 0, record);\n}\n\n// ---------------------------------------------------------------------------\n// Internal helper: add a single pre-built Route object to the runtime stores\n// ---------------------------------------------------------------------------\n\nfunction addRouteToStores(routeObj: Route): void {\n routes.push(routeObj);\n setHasRoutes(true);\n\n const depth = getDepth(routeObj.path);\n let depthRoutes = routesByDepth.get(depth);\n if (!depthRoutes) {\n depthRoutes = [];\n routesByDepth.set(depth, depthRoutes);\n }\n depthRoutes.push(routeObj);\n\n if (routeObj.namespace) {\n namespaces.add(routeObj.namespace);\n }\n}\n\n// ---------------------------------------------------------------------------\n// lazy() — eager-prefetch code-split component wrapper\n// ---------------------------------------------------------------------------\n\n/** Promises from in-flight lazy() imports, drained by createSPA / hydrateSPA. */\nconst pendingLazy = new Set<Promise<unknown>>();\n\nconst outletContext = defineContext<unknown>(null);\n\nexport function Outlet(): unknown {\n return readContext(outletContext);\n}\n\n/**\n * Snapshot the current in-flight lazy() imports.\n * Boot uses this before clearing route state so manifest-based startup can\n * still await chunks that were kicked off during route module evaluation.\n */\nexport function _snapshotLazy(): Promise<unknown>[] {\n return [...pendingLazy];\n}\n\n/**\n * Declare a code-split route component. The `import()` fires immediately at\n * module evaluation time (creating a bundler split point), and the resolved\n * chunk is guaranteed to be available before the app mounts — so the renderer\n * always receives a plain synchronous function.\n *\n * ```ts\n * registerRoutes(() => {\n * group({ layout: AppLayout }, () => {\n * route('/', lazy(() => import('./pages/landing')));\n * route('/dashboard', lazy(() => import('./pages/dashboard')));\n * });\n * });\n * ```\n *\n * The module must export the component as its **default** export:\n * ```ts\n * // pages/dashboard.tsx\n * export default function DashboardPage() { … }\n * ```\n */\nexport function lazy(\n factory: () => Promise<{ default: RouteComponent } | RouteComponent>\n): RouteComponent {\n let resolved: RouteComponent | null = null;\n let loadError: unknown = null;\n\n const promise = factory().then(\n (mod) => {\n resolved =\n typeof mod === 'function'\n ? mod\n : (mod as { default: RouteComponent }).default;\n pendingLazy.delete(promise);\n },\n (err: unknown) => {\n loadError = err;\n pendingLazy.delete(promise);\n }\n );\n pendingLazy.add(promise);\n\n return (params) => {\n if (loadError) throw loadError as Error;\n if (!resolved) {\n throw new Error(\n 'lazy() component used before it was resolved. ' +\n 'Await createSPA() / hydrateSPA() to ensure all chunks load first.'\n );\n }\n return resolved(params);\n };\n}\n\n/**\n * Wait for all pending `lazy()` imports to settle.\n * Called automatically by `createSPA` / `hydrateSPA` before mounting.\n */\nexport function _drainLazy(\n additionalPending: Iterable<Promise<unknown>> = []\n): Promise<void> {\n const combined = new Set<Promise<unknown>>([\n ...additionalPending,\n ...pendingLazy,\n ]);\n if (combined.size === 0) return Promise.resolve();\n return Promise.allSettled(combined).then(() => undefined);\n}\n\nexport function group(options: GroupHelperOptions, fn: RouteDefinition): void;\nexport function group(options: GroupHelperOptions, fn: RouteDefinition): void {\n pushGroupScope(options, fn);\n}\n\nexport function page(\n path: string,\n Component: RouteComponent,\n fn: RouteDefinition\n): void;\nexport function page(\n path: string,\n Component: RouteComponent,\n options: PageHelperOptions,\n fn: RouteDefinition\n): void;\nexport function page(\n path: string,\n Component: RouteComponent,\n optionsOrFn: PageHelperOptions | RouteDefinition,\n maybeFn?: RouteDefinition\n): void {\n const options =\n typeof optionsOrFn === 'function' ? ({} as PageHelperOptions) : optionsOrFn;\n const fn = typeof optionsOrFn === 'function' ? optionsOrFn : maybeFn;\n\n if (typeof Component !== 'function') {\n throw new Error(\n 'page(path, Component, fn) requires a component function as the second argument.'\n );\n }\n\n if (typeof fn !== 'function') {\n throw new Error(\n 'page(path, Component, fn) requires a route definition callback as the final argument.'\n );\n }\n\n pushPageScope(path, Component, options, fn);\n}\n\nexport function index(Component: RouteComponent, options?: RouteOptions): void {\n registerRouteAtResolvedPath(resolveIndexPath(), Component, options);\n}\n\nexport function fallback(Component: RouteComponent): void {\n if (hasActivePageScope()) {\n if (getCurrentScopeKind() !== 'page') {\n throw new Error(\n 'fallback() inside page() must be declared directly in the page scope, not inside nested group().'\n );\n }\n\n registerRouteAtResolvedPath(\n `${getCurrentPathPrefix()}/*`,\n Component,\n undefined,\n { isFallback: true, fallbackPrefix: getCurrentPathPrefix() }\n );\n return;\n }\n\n const allowsRootFallback = registrationScopeStack.every(\n (scope) =>\n scope.policies.length === 0 &&\n !scope.state.guestOnly &&\n !scope.state.authenticated\n );\n\n if (!allowsRootFallback) {\n throw new Error(\n 'fallback() can only be registered at the root scope. ' +\n 'Use route(\"/*\", Component) if you need compatibility behavior.'\n );\n }\n\n registerRouteAtResolvedPath('/*', Component, undefined, {\n isFallback: true,\n fallbackPrefix: '/',\n });\n}\n\nfunction pushRegistrationScope(\n scope: RegistrationScope,\n fn: RouteDefinition\n): void {\n registrationScopeStack.push(scope);\n try {\n fn();\n } finally {\n registrationScopeStack.pop();\n }\n}\n\nfunction pushGroupScope(\n options: GroupHelperOptions,\n fn: RouteDefinition\n): void {\n const session = getCurrentRegistrationSession();\n validateAccessMetadata(options, {\n authConfigured: session.authConfigured,\n state: getCurrentAccessScopeState(),\n });\n const policies = compileNodePolicies(options);\n\n pushRegistrationScope(\n {\n kind: 'group',\n pathPrefix: getCurrentPathPrefix(),\n layout: options.layout,\n policies,\n state: nextAccessScopeState(options, getCurrentAccessScopeState()),\n },\n fn\n );\n}\n\nfunction pushPageScope(\n path: string,\n Component: RouteComponent,\n options: PageHelperOptions,\n fn: RouteDefinition\n): void {\n if (hasActivePageScope()) {\n throw new Error(\n 'page() cannot be nested inside another page(). ' +\n 'Use route() for child leaves or group() for inherited behavior inside the existing page scope.'\n );\n }\n\n const session = getCurrentRegistrationSession();\n validateAccessMetadata(options, {\n authConfigured: session.authConfigured,\n state: getCurrentAccessScopeState(),\n });\n\n const policies = compileNodePolicies(options);\n\n pushRegistrationScope(\n {\n kind: 'page',\n pathPrefix: resolvePageScopePath(path),\n page: Component,\n policies,\n state: nextAccessScopeState(options, getCurrentAccessScopeState()),\n },\n fn\n );\n}\n\nfunction hasBuiltInAuthMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>\n): boolean {\n return node.auth !== undefined || !!node.role || !!node.permission;\n}\n\nfunction validateSameNodeAccessMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>\n): void {\n if (node.auth === 'guest' && (!!node.role || !!node.permission)) {\n throw new Error(\n 'Guest-only routes cannot be combined with role or permission requirements.'\n );\n }\n}\n\nfunction validateAccessMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>,\n context: {\n authConfigured: boolean;\n state: AccessScopeState;\n }\n): void {\n validateSameNodeAccessMetadata(node);\n\n const requiresAuthenticated =\n node.auth === true || !!node.role || !!node.permission;\n\n if (\n node.auth === 'guest' &&\n (context.state.authenticated || !!node.role || !!node.permission)\n ) {\n throw new Error(\n 'Guest-only routes cannot be combined with authenticated access requirements.'\n );\n }\n\n if (context.state.guestOnly && requiresAuthenticated) {\n throw new Error(\n 'Child routes cannot weaken a guest-only access scope with authenticated requirements.'\n );\n }\n\n if (hasBuiltInAuthMetadata(node) && !context.authConfigured) {\n throw new Error(\n 'Routes using `auth`, `role`, or `permission` require `auth.resolve` in registerRoutes(...).'\n );\n }\n}\n\nfunction nextAccessScopeState(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>,\n state: AccessScopeState\n): AccessScopeState {\n const requiresAuthenticated =\n node.auth === true || !!node.role || !!node.permission;\n\n return {\n guestOnly: state.guestOnly || node.auth === 'guest',\n authenticated: state.authenticated || requiresAuthenticated,\n };\n}\n\nfunction compileNodePolicies(\n node: Pick<\n RouteOptions | GroupHelperOptions,\n 'auth' | 'role' | 'permission' | 'policies'\n >\n): RoutePolicy[] {\n validateSameNodeAccessMetadata(node);\n\n const compiled: RoutePolicy[] = [];\n\n if (node.auth === true) {\n compiled.push(requireAuth());\n } else if (node.auth === 'guest') {\n compiled.push(requireGuest());\n }\n\n if (node.role) {\n compiled.push(requireRole(node.role));\n }\n\n if (node.permission) {\n compiled.push(requirePermission(node.permission));\n }\n\n if (node.policies?.length) {\n compiled.push(...node.policies);\n }\n\n return compiled;\n}\n\nfunction normalizeRouteOptions(\n options: RouteOptions | undefined\n): RouteOptions | undefined {\n if (!options) {\n return undefined;\n }\n\n const loader = options.loader;\n const policies = compileNodePolicies(options);\n\n if (\n !loader &&\n !options.entries &&\n policies.length === 0 &&\n !options.title &&\n !options.namespace &&\n options.auth === undefined &&\n !options.role &&\n !options.permission\n ) {\n return undefined;\n }\n\n return {\n ...(loader ? { loader } : {}),\n ...(options.entries ? { entries: options.entries } : {}),\n ...(options.auth !== undefined ? { auth: options.auth } : {}),\n ...(options.role ? { role: options.role } : {}),\n ...(options.permission ? { permission: options.permission } : {}),\n ...(policies.length > 0 ? { policies } : {}),\n ...(options.title ? { title: options.title } : {}),\n ...(options.namespace ? { namespace: options.namespace } : {}),\n };\n}\n\nfunction applyPageChain(\n pageChain: readonly PageScopeRecord[],\n params: Record<string, string>,\n content: unknown\n): unknown {\n let nextContent = content;\n\n for (let i = pageChain.length - 1; i >= 0; i--) {\n nextContent = outletContext.Scope({\n value: nextContent,\n children: pageChain[i].component(params),\n });\n }\n\n return nextContent;\n}\n\nfunction registerRouteAtResolvedPath(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions,\n metadata?: {\n isFallback?: boolean;\n fallbackPrefix?: string;\n }\n): void {\n validateAccessMetadata(options ?? {}, {\n authConfigured: getCurrentRegistrationSession().authConfigured,\n state: getCurrentAccessScopeState(),\n });\n\n const chain = getCurrentLayoutChain();\n const pageChain = getCurrentPageChain();\n const segments = parseSegments(path);\n const rank = computeRank(segments);\n const isFallback = metadata?.isFallback ?? path === '/*';\n const comp = Component;\n const normalizedOptions = normalizeRouteOptions(options);\n const policies = [\n ...getCurrentInheritedPolicies(),\n ...(normalizedOptions?.policies ?? []),\n ];\n\n const handler: RouteHandler = (params) => {\n let content = comp(params);\n\n content = applyPageChain(pageChain, params, content);\n\n for (let i = chain.length - 1; i >= 0; i--) {\n content = chain[i].component({ children: content });\n }\n\n return content;\n };\n\n const record: InternalRouteRecord = {\n path,\n component: comp,\n segments,\n rank,\n layoutChain: chain,\n pageChain,\n options: normalizedOptions\n ? {\n ...normalizedOptions,\n ...(policies.length > 0 ? { policies } : {}),\n }\n : policies.length > 0\n ? { policies }\n : {},\n isFallback,\n handler,\n ...(metadata?.fallbackPrefix\n ? { fallbackPrefix: metadata.fallbackPrefix }\n : {}),\n };\n\n insertRecordSorted(record);\n addRouteToStores({\n path,\n handler,\n namespace: normalizedOptions?.namespace ?? options?.namespace,\n ...(metadata?.fallbackPrefix\n ? { fallbackPrefix: metadata.fallbackPrefix }\n : {}),\n });\n}\n\nexport function registerRoutes(\n definition: RouteDefinition,\n options: RegisterRoutesOptions = {}\n): void {\n defaultRouteAuthOptions = options.auth;\n\n registrationSessionStack.push({\n authConfigured: !!options.auth?.resolve,\n });\n try {\n definition();\n } finally {\n registrationSessionStack.pop();\n }\n}\n\n// ---------------------------------------------------------------------------\n// route() — dual-purpose: registration (module load) + accessor (render time)\n// ---------------------------------------------------------------------------\n\nfunction readCurrentRouteSnapshot(): RouteSnapshot {\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'currentRoute() can only be called during component render execution. ' +\n 'Call currentRoute() from inside your component function.'\n );\n }\n\n let pathname = '/';\n let search = '';\n let hash = '';\n const renderContext = getRenderContext();\n\n if (instance.ssr && renderContext?.url) {\n const parsed = parseLocation(renderContext.url);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n } else if (typeof window !== 'undefined' && window.location) {\n pathname = window.location.pathname || '/';\n search = window.location.search || '';\n hash = window.location.hash || '';\n } else if (serverLocation) {\n const parsed = parseLocation(serverLocation);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n }\n\n const query = makeQuery(search);\n const matches = computeMatchesFromRoutes(pathname, getActiveRoutes());\n const instanceParams = instance.props as Record<string, string>;\n const routeParams =\n Object.keys(instanceParams).length > 0\n ? instanceParams\n : (matches[0]?.params ?? {});\n const params = deepFreeze({\n ...routeParams,\n });\n\n return Object.freeze({\n path: pathname,\n params,\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n}\n\nexport function currentRoute(): RouteSnapshot {\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'currentRoute() can only be called during component render execution. ' +\n 'Call currentRoute() from inside your component function.'\n );\n }\n\n if (typeof window === 'undefined' || instance.ssr) {\n return readCurrentRouteSnapshot();\n }\n\n if (currentRouteSnapshot.path !== (window.location.pathname || '/')) {\n recordReadableRead(currentRouteSource);\n return readCurrentRouteSnapshot();\n }\n\n recordReadableRead(currentRouteSource);\n return readCurrentRouteSnapshot();\n}\n\nexport function syncCurrentRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): void {\n setCurrentRouteSnapshot(pathname, search, hash);\n}\n\n/**\n * Register a route.\n *\n * ```ts\n * route('/posts/{slug}', PostPage, {\n * loader: ({ params }) => getPost(params.slug),\n * entries: async () => getPosts().map(p => ({ slug: p.slug })),\n * title: 'Post',\n * policies:[requireAuth()],\n * });\n * ```\n */\nexport function route(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions\n): void;\nexport function route(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions\n): void {\n if (getExecutionModel() === 'islands') {\n throw new Error(\n 'Routes are not supported with islands. Use createSPA (client) or createSSR (server) instead.'\n );\n }\n\n // ── Render-time accessor (no arguments) ─────────────────────────────────\n if (typeof path === 'undefined') {\n throw new Error(\n 'route() is only for route registration. Use currentRoute() inside components.'\n );\n }\n\n // ── Registration mode ────────────────────────────────────────────────────\n\n // Disallow registration during SSR render\n const currentInst = getCurrentComponentInstance();\n if (currentInst && currentInst.ssr) {\n throw new Error(\n 'route() cannot be called during SSR rendering. Register routes at module load time instead.'\n );\n }\n\n if (registrationLocked) {\n throw new Error(\n 'Route registration is locked after app startup. ' +\n 'Register routes at module load time before calling createSPA or createSSR.'\n );\n }\n\n if (typeof Component !== 'function') {\n throw new Error(\n 'route(path, Component) requires a component function as the second argument. ' +\n 'Passing JSX elements or VNodes directly is not supported.'\n );\n }\n\n registerRouteAtResolvedPath(\n resolveRouteRegistrationPath(path),\n Component,\n options\n );\n}\n\n// ---------------------------------------------------------------------------\n// Manifest access\n// ---------------------------------------------------------------------------\n\n/**\n * Return the normalized route manifest built from registered route definitions.\n *\n * Pass this to `createSPA`, `hydrateSPA`, or `renderToString` as the\n * authoritative routing input:\n *\n * ```ts\n * import { getManifest } from '@askrjs/askr/router';\n * await createSPA({ root: '#app', manifest: getManifest() });\n * ```\n */\nexport function getManifest(): RouteManifest {\n return {\n records: [...records],\n ...(defaultRouteAuthOptions ? { auth: defaultRouteAuthOptions } : {}),\n };\n}\n\n/**\n * Internal: apply a pre-built manifest to the runtime stores without running\n * route() again. Called by createSPA / hydrateSPA when a manifest is passed.\n */\nexport function _applyManifest(manifest: RouteManifest): void {\n defaultRouteAuthOptions = manifest.auth;\n for (const record of manifest.records) {\n insertRecordSorted(record as InternalRouteRecord);\n addRouteToStores({\n path: record.path,\n handler: record.handler,\n namespace: record.options.namespace,\n ...('fallbackPrefix' in record &&\n typeof (record as InternalRouteRecord).fallbackPrefix === 'string'\n ? {\n fallbackPrefix: (record as InternalRouteRecord).fallbackPrefix,\n }\n : {}),\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Route collection helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Get all registered routes (flat list, insertion order).\n * Prefer `getManifest()` when metadata (loader, policies, entries) is needed.\n */\nexport function getRoutes(): Route[] {\n return [...routes];\n}\n\n/** Get routes for a specific namespace. */\nexport function getNamespaceRoutes(namespace: string): Route[] {\n return routes.filter((r) => r.namespace === namespace);\n}\n\n/** Unload all routes from a namespace (for MFE unmounting). */\nexport function unloadNamespace(namespace: string): number {\n const before = routes.length;\n\n for (let i = routes.length - 1; i >= 0; i--) {\n if (routes[i].namespace === namespace) {\n const removed = routes[i];\n routes.splice(i, 1);\n\n const depth = getDepth(removed.path);\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n const idx = depthRoutes.indexOf(removed);\n if (idx >= 0) depthRoutes.splice(idx, 1);\n }\n }\n }\n\n // Remove matching records too\n for (let i = records.length - 1; i >= 0; i--) {\n if (records[i].options.namespace === namespace) {\n records.splice(i, 1);\n }\n }\n\n namespaces.delete(namespace);\n return before - routes.length;\n}\n\n/** Clear all registered routes and records (testing / boot reset). */\nexport function clearRoutes(): void {\n routes.length = 0;\n records.length = 0;\n namespaces.clear();\n routesByDepth.clear();\n registrationScopeStack.length = 0;\n registrationSessionStack.length = 0;\n registrationLocked = false;\n defaultRouteAuthOptions = undefined;\n activeClientRouteAuthOptions = undefined;\n setHasRoutes(false);\n pendingLazy.clear();\n}\n\n/**\n * Get all loaded namespaces (MFE identifiers)\n */\nexport function getLoadedNamespaces(): string[] {\n return Array.from(namespaces);\n}\n\nfunction findBestScopedFallbackRecord(\n pathname: string,\n routeRecords: readonly RouteRecord[]\n): { record: InternalRouteRecord; params: Record<string, string> } | null {\n let bestRecord: InternalRouteRecord | null = null;\n let bestParams: Record<string, string> | null = null;\n let bestPrefixLength = -1;\n\n for (const routeRecord of routeRecords) {\n const record = routeRecord as InternalRouteRecord;\n if (!record.fallbackPrefix) {\n continue;\n }\n\n const params = matchFallbackPrefix(pathname, record.fallbackPrefix);\n if (params === null) {\n continue;\n }\n\n if (record.fallbackPrefix.length > bestPrefixLength) {\n bestRecord = record;\n bestParams = params;\n bestPrefixLength = record.fallbackPrefix.length;\n }\n }\n\n return bestRecord && bestParams\n ? { record: bestRecord, params: bestParams }\n : null;\n}\n\n/**\n * Resolve a path to a route handler.\n *\n * Hot path: walks the module-level `records[]` array which is kept sorted by\n * rank descending at registration time — so the first `matchSegments` hit is\n * always the most specific match. No per-call allocations for the common\n * case of purely-static routes.\n */\nexport function resolveRoute(pathname: string): ResolvedRoute | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n for (const record of records) {\n if (record.fallbackPrefix) {\n continue;\n }\n\n const params = matchSegments(urlParts, record.segments);\n if (params !== null) {\n return { handler: record.handler, params };\n }\n }\n\n const fallbackMatch = findBestScopedFallbackRecord(normalized, records);\n return fallbackMatch\n ? { handler: fallbackMatch.record.handler, params: fallbackMatch.params }\n : null;\n}\n\nfunction getMatchingRecord(\n target: string,\n routeRecords: readonly RouteRecord[]\n): { record: RouteRecord; params: Record<string, string> } | null {\n const location = parseLocation(target);\n const normalized =\n location.pathname.endsWith('/') && location.pathname !== '/'\n ? location.pathname.slice(0, -1)\n : location.pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n for (const record of routeRecords) {\n const internalRecord = record as InternalRouteRecord;\n if (internalRecord.fallbackPrefix) {\n continue;\n }\n\n const params = matchSegments(urlParts, record.segments);\n if (params !== null) {\n return { record, params };\n }\n }\n\n return findBestScopedFallbackRecord(normalized, routeRecords);\n}\n\nfunction getRoutePolicies(\n options: RouteOptions | undefined\n): readonly RoutePolicy[] {\n if (!options) {\n return [];\n }\n\n if (options.policies?.length) {\n return options.policies;\n }\n\n return compileNodePolicies(options);\n}\n\nfunction getDefaultRouteMode(): RouteContext['mode'] {\n if (typeof window !== 'undefined') {\n return 'spa';\n }\n\n return 'ssr';\n}\n\nfunction buildRenderResult(\n record: RouteRecord,\n params: Record<string, string>\n): RouteRenderResult {\n return {\n kind: 'render',\n handler: record.handler,\n params,\n };\n}\n\nfunction continueRoutePolicies(\n policies: readonly RoutePolicy[],\n context: RouteContext,\n record: RouteRecord,\n params: Record<string, string>,\n startIndex = 0\n): RouteRequestResult | Promise<RouteRequestResult> {\n for (let index = startIndex; index < policies.length; index += 1) {\n const policyResult = policies[index](context);\n\n if (isPromise(policyResult)) {\n return policyResult.then((next) => {\n if (next.kind !== 'allow') {\n return next;\n }\n\n return continueRoutePolicies(\n policies,\n context,\n record,\n params,\n index + 1\n );\n });\n }\n\n if (policyResult.kind !== 'allow') {\n return policyResult;\n }\n }\n\n return buildRenderResult(record, params);\n}\n\nexport function resolveRouteRequest(\n target: string,\n options: RouteRequestOptions = {}\n): RouteRequestResult | Promise<RouteRequestResult> {\n const routeRecords = options.manifest?.records ?? records;\n const match = getMatchingRecord(target, routeRecords);\n\n if (!match) {\n return null;\n }\n\n const { record, params } = match;\n const policies = getRoutePolicies(record.options);\n\n if (policies.length === 0) {\n return buildRenderResult(record, params);\n }\n\n const signal =\n options.signal ??\n getRenderContext()?.signal ??\n new AbortController().signal;\n const mode = options.mode ?? getDefaultRouteMode();\n const auth = getActiveRouteAuthOptions(\n options.auth ?? options.manifest?.auth\n );\n const baseContext = buildRouteContextBase(target, params, {\n mode,\n signal,\n });\n\n const finalize = (authState: { session: unknown; user: unknown }) =>\n continueRoutePolicies(\n policies,\n buildRouteContext(target, params, {\n mode,\n signal,\n auth,\n session: authState.session,\n user: authState.user,\n }),\n record,\n params\n );\n\n if (!auth?.resolve) {\n return finalize({ session: null, user: null });\n }\n\n const authState = auth.resolve(baseContext);\n if (isPromise(authState)) {\n return authState.then((next) => finalize(next));\n }\n\n return finalize(authState);\n}\n\n/**\n * Resolve a path against an explicit route list (e.g. an SSR per-render\n * context). When called with the global `routes` array this delegates to\n * the faster `resolveRoute` which uses pre-sorted `records[]`.\n *\n * For externally supplied lists the function:\n * 1. Builds a rank-sorted copy of the list on first call and caches it\n * in a WeakMap so subsequent resolutions against the same list pay\n * zero sort cost.\n * 2. Uses pre-parsed `ParsedSegment[]` from a WeakMap cache so no string\n * splitting or segment parsing occurs on the hot path.\n * 3. Uses a running-best with an early-exit once the sorted list reaches\n * a rank that cannot beat the current best match.\n */\nexport function resolveRouteFromRoutes(\n pathname: string,\n routeList: readonly Route[]\n): ResolvedRoute | null {\n if (routeList === routes) return resolveRoute(pathname);\n\n const match = findBestResolvedRouteFromRoutes(pathname, routeList);\n return match ? { handler: match.route.handler, params: match.params } : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+GA,MAAM,SAA0B,EAAE;;AAGlC,MAAM,UAAiC,EAAE;;AAgBzC,MAAM,yBAA8C,EAAE;AACtD,MAAM,2BAAkD,EAAE;AAE1D,MAAM,6BAAa,IAAI,KAAa;AACpC,IAAI,qBAAqB;AAOzB,IAAI;AACJ,IAAI;AAEJ,MAAM,iBAAiB,OAAO,IAAI,sBAAsB;AAExD,SAAS,aAAa,OAAsB;AAC1C,KAAI;EACF,MAAM,IAAI;AACV,IAAE,kBAAkB;SACd;;AAMV,aAAa,MAAM;AAGnB,MAAM,gCAAgB,IAAI,KAAsB;;;;AAKhD,SAAS,SAAS,MAAsB;CACtC,MAAM,aACJ,KAAK,SAAS,IAAI,IAAI,SAAS,MAAM,KAAK,MAAM,GAAG,GAAG,GAAG;AAC3D,QAAO,eAAe,MAAM,IAAI,WAAW,MAAM,IAAI,CA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ACJ,QAAQ,UACR,kBAAkB,EAAE,UACpB,IAAI,iBAAiB,CAAC;CACxB,MAAM,OAAO,QAAQ,QAAQ,qBAAqB;CAClD,MAAM,OAAO,0BACX,QAAQ,QAAQ,QAAQ,UAAU,KACnC;CACD,MAAM,cAAc,sBAAsB,QAAQ,QAAQ;EACxD;EACA;EACD,CAAC;CAEF,MAAM,YAAY,cAChB,sBACE,UACA,kBAAkB,QAAQ,QAAQ;EAChC;EACA;EACA;EACA,SAAS,UAAU;EACnB,MAAM,UAAU;EACjB,CAAC,EACF,QACA,OACD;AAEH,KAAI,CAAC,MAAM,QACT,QAAO,SAAS;EAAE,SAAS;EAAM,MAAM;EAAM,CAAC;CAGhD,MAAM,YAAY,KAAK,QAAQ,YAAY;AAC3C,KAAI,UAAU,UAAU,CACtB,QAAO,UAAU,MAAM,SAAS,SAAS,KAAK,CAAC;AAGjD,QAAO,SAAS,UAAU;;;;;;;;;;;;;;;;AAiB5B,SAAgB,uBACd,UACA,WACsB;AACtB,KAAI,cAAc,OAAQ,QAAO,aAAa,SAAS;CAEvD,MAAM,QAAQ,gCAAgC,UAAU,UAAU;AAClE,QAAO,QAAQ;EAAE,SAAS,MAAM,MAAM;EAAS,QAAQ,MAAM;EAAQ,GAAG"}
|
|
1
|
+
{"version":3,"file":"route.js","names":[],"sources":["../../src/router/route.ts"],"sourcesContent":["/**\n * Route definition, registration, and matching.\n *\n * Primary public authoring:\n * - `registerRoutes(() => { ... }, options?)`\n * - `group(options, () => { ... })`\n * - `page(path, Component, () => { ... })`\n * - `index(Component, options?)`\n * - `route(path, Component, options?)`\n * - `fallback(Component)`\n * - `Outlet()` for page child rendering\n * - `currentRoute()` for render-time access\n *\n */\n\nimport { matchSegments, parseSegments, computeRank } from './match';\nimport {\n buildRouteContext,\n buildRouteContextBase,\n deepFreeze,\n makeQuery,\n parseLocation,\n} from './route-context';\nimport { defineContext, readContext } from '../runtime/context';\nimport { getCurrentComponentInstance } from '../runtime/component';\nimport { getExecutionModel } from '../runtime/execution-model';\nimport {\n markReadableDerivedSubscribersDirty,\n markReactivePropsDirtySource,\n notifyReadableReaders,\n recordReadableRead,\n type ReadableSource,\n} from '../runtime/readable';\nimport { getRenderContext } from '../ssr/context';\nimport {\n requireAuth,\n requireGuest,\n requirePermission,\n requireRole,\n} from './policy';\n\nexport type {\n AccessDecision,\n AccessDenyDecision,\n AccessRedirectDecision,\n GroupHelperOptions,\n PageHelperOptions,\n RegisterRoutesOptions,\n RouteDefinition,\n RouteAuthOptions,\n RouteHandler,\n Route,\n RouteContext,\n RoutePolicy,\n RouteRenderResult,\n RouteRequestOptions,\n RouteRequestResult,\n ResolvedRoute,\n RouteMatch,\n RouteQuery,\n RouteSnapshot,\n RouteComponent,\n RouteOptions,\n ParsedSegment,\n LayoutScopeRecord,\n PageScopeRecord,\n RouteRecord,\n RouteManifest,\n} from '../common/router';\n\nimport type {\n GroupHelperOptions,\n PageHelperOptions,\n RegisterRoutesOptions,\n RouteDefinition,\n RouteAuthOptions,\n RouteHandler,\n Route,\n RouteContext,\n RoutePolicy,\n RouteRenderResult,\n RouteRequestOptions,\n RouteRequestResult,\n ResolvedRoute,\n RouteMatch,\n RouteSnapshot,\n RouteComponent,\n RouteOptions,\n LayoutScopeRecord,\n PageScopeRecord,\n RouteRecord,\n RouteManifest,\n} from '../common/router';\n\n// ---------------------------------------------------------------------------\n// Module-level stores\n// ---------------------------------------------------------------------------\n\n/** Legacy flat route array — kept for resolver and route() accessor backward compat. */\ntype InternalRoute = Route & {\n fallbackPrefix?: string;\n};\n\ntype InternalRouteRecord = RouteRecord & {\n fallbackPrefix?: string;\n};\n\nconst routes: InternalRoute[] = [];\n\n/** Normalized route records built by the declarative registration API. */\nconst records: InternalRouteRecord[] = [];\n\ntype RegistrationScope = {\n kind: 'group' | 'page';\n pathPrefix: string;\n layout?: LayoutScopeRecord['component'];\n page?: PageScopeRecord['component'];\n policies: readonly RoutePolicy[];\n state: AccessScopeState;\n};\n\ntype RegistrationSession = {\n authConfigured: boolean;\n};\n\n/** Active registration scope stack during module-load-time registration. */\nconst registrationScopeStack: RegistrationScope[] = [];\nconst registrationSessionStack: RegistrationSession[] = [];\n\nconst namespaces = new Set<string>();\nlet registrationLocked = false;\n\ntype AccessScopeState = {\n guestOnly: boolean;\n authenticated: boolean;\n};\n\nlet defaultRouteAuthOptions: RouteAuthOptions | undefined;\nlet activeClientRouteAuthOptions: RouteAuthOptions | undefined;\n\nconst HAS_ROUTES_KEY = Symbol.for('__ASKR_HAS_ROUTES__');\n\nfunction setHasRoutes(value: boolean): void {\n try {\n const g = globalThis as unknown as Record<string | symbol, unknown>;\n g[HAS_ROUTES_KEY] = value;\n } catch {\n // ignore\n }\n}\n\n// Initialize to false at module load.\nsetHasRoutes(false);\n\n// Route index by depth - maintains insertion order\nconst routesByDepth = new Map<number, Route[]>();\n\n/**\n * Parse route path depth\n */\nfunction getDepth(path: string): number {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n return normalized === '/' ? 0 : normalized.split('/').filter(Boolean).length;\n}\n\n// ---------------------------------------------------------------------------\n// WeakMap caches for external Route[] objects (e.g. SSR per-request tables)\n// Amortises parseSegments / computeRank across repeated resolveRouteFromRoutes\n// calls on the same route list (same object reference).\n// ---------------------------------------------------------------------------\n\n/** Pre-parsed segments for an externally supplied Route object. */\nconst routeSegsCache = new WeakMap<Route, ReturnType<typeof parseSegments>>();\n/** Pre-computed rank for an externally supplied Route object. */\nconst routeRankCache = new WeakMap<Route, number>();\n/** A rank-descending sorted copy of an external readonly Route array. */\nconst sortedListCache = new WeakMap<\n ReadonlyArray<Route>,\n ReadonlyArray<Route>\n>();\n\nfunction cachedSegs(r: Route): ReturnType<typeof parseSegments> {\n let s = routeSegsCache.get(r);\n if (!s) {\n s = parseSegments(r.path);\n routeSegsCache.set(r, s);\n }\n return s;\n}\n\nfunction cachedRank(r: Route): number {\n let n = routeRankCache.get(r);\n if (n === undefined) {\n n = computeRank(cachedSegs(r));\n routeRankCache.set(r, n);\n }\n return n;\n}\n\nfunction cachedSortedList(\n routeList: ReadonlyArray<Route>\n): ReadonlyArray<Route> {\n let sorted = sortedListCache.get(routeList);\n if (!sorted) {\n sorted = [...routeList].sort((a, b) => cachedRank(b) - cachedRank(a));\n sortedListCache.set(routeList, sorted);\n }\n return sorted;\n}\n\nlet currentRouteSnapshot = buildRouteSnapshot('/', '', '');\n\nconst currentRouteSource = (() =>\n currentRouteSnapshot) as ReadableSource<RouteSnapshot> &\n (() => RouteSnapshot);\n\ncurrentRouteSource._readers = new Map();\n\n// SSR helper: when rendering on the server, callers may set a location so that\n// render-time route() returns deterministic server values that match client\n// hydration. This is deliberately an opt-in escape for SSR and tests.\nlet serverLocation: string | null = null;\n\nexport function setServerLocation(url: string | null): void {\n serverLocation = url;\n}\n\nfunction isPromise<T>(value: T | Promise<T>): value is Promise<T> {\n return value instanceof Promise;\n}\n\nfunction buildRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): RouteSnapshot {\n const query = makeQuery(search);\n const matches = computeMatchesFromRoutes(pathname, getActiveRoutes());\n\n return Object.freeze({\n path: pathname,\n params: deepFreeze({ ...matches[0]?.params }),\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n}\n\nfunction setCurrentRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): void {\n currentRouteSnapshot = buildRouteSnapshot(pathname, search, hash);\n\n const instance = getCurrentComponentInstance();\n markReadableDerivedSubscribersDirty(currentRouteSource);\n markReactivePropsDirtySource(currentRouteSource);\n notifyReadableReaders(currentRouteSource, instance);\n}\n\n// Compute matches for a specific route list.\nfunction matchFallbackPrefix(\n pathname: string,\n fallbackPrefix: string\n): Record<string, string> | null {\n const normalizedPath =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const normalizedPrefix =\n fallbackPrefix.endsWith('/') && fallbackPrefix !== '/'\n ? fallbackPrefix.slice(0, -1)\n : fallbackPrefix;\n\n if (normalizedPrefix === '/') {\n const urlParts =\n normalizedPath === '/' ? [] : normalizedPath.split('/').filter(Boolean);\n return {\n '*':\n urlParts.length === 0\n ? '/'\n : urlParts.length === 1\n ? urlParts[0]\n : '/' + urlParts.join('/'),\n };\n }\n\n if (\n normalizedPath !== normalizedPrefix &&\n !normalizedPath.startsWith(`${normalizedPrefix}/`)\n ) {\n return null;\n }\n\n const remainder =\n normalizedPath === normalizedPrefix\n ? '/'\n : normalizedPath.slice(normalizedPrefix.length + 1);\n const remainderParts =\n remainder === '/' ? [] : remainder.split('/').filter(Boolean);\n\n return {\n '*':\n remainderParts.length === 0\n ? '/'\n : remainderParts.length === 1\n ? remainderParts[0]\n : '/' + remainderParts.join('/'),\n };\n}\n\nfunction computeMatchesFromRoutes(\n pathname: string,\n routesList: readonly Route[]\n): RouteMatch[] {\n const bestMatch =\n routesList === routes\n ? getMatchingRecord(pathname, records)\n : findBestResolvedRouteFromRoutes(pathname, routesList);\n\n if (!bestMatch) {\n return [];\n }\n\n return [\n {\n path: 'route' in bestMatch ? bestMatch.route.path : bestMatch.record.path,\n params: deepFreeze({ ...bestMatch.params }),\n name:\n 'route' in bestMatch\n ? (bestMatch.route as { name?: string }).name\n : undefined,\n namespace:\n 'route' in bestMatch\n ? bestMatch.route.namespace\n : bestMatch.record.options.namespace,\n },\n ];\n}\n\nfunction findBestResolvedRouteFromRoutes(\n pathname: string,\n routeList: readonly Route[]\n): { route: Route; params: Record<string, string> } | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n const sorted = cachedSortedList(routeList);\n let bestRoute: Route | null = null;\n let bestParams: Record<string, string> = {};\n let bestRank = -Infinity;\n\n for (const route of sorted) {\n const internalRoute = route as InternalRoute;\n if (internalRoute.fallbackPrefix) {\n continue;\n }\n\n const rank = cachedRank(route);\n if (rank < bestRank) break;\n if (bestRoute !== null && rank === bestRank) continue;\n\n const params = matchSegments(urlParts, cachedSegs(route));\n if (params !== null) {\n bestRoute = route;\n bestParams = params;\n bestRank = rank;\n }\n }\n\n if (bestRoute !== null) {\n return { route: bestRoute, params: bestParams };\n }\n\n let bestFallback: InternalRoute | null = null;\n let bestFallbackParams: Record<string, string> | null = null;\n let bestPrefixLength = -1;\n\n for (const route of routeList) {\n const internalRoute = route as InternalRoute;\n if (!internalRoute.fallbackPrefix) {\n continue;\n }\n\n const params = matchFallbackPrefix(\n normalized,\n internalRoute.fallbackPrefix\n );\n if (params === null) {\n continue;\n }\n\n if (internalRoute.fallbackPrefix.length > bestPrefixLength) {\n bestFallback = internalRoute;\n bestFallbackParams = params;\n bestPrefixLength = internalRoute.fallbackPrefix.length;\n }\n }\n\n return bestFallback && bestFallbackParams\n ? { route: bestFallback, params: bestFallbackParams }\n : null;\n}\n\nfunction getActiveRoutes(): readonly Route[] {\n const renderContext = getRenderContext();\n return renderContext?.routes ?? routes;\n}\n\nfunction getActiveRouteAuthOptions(\n override?: RouteAuthOptions\n): RouteAuthOptions | undefined {\n if (override) {\n return override;\n }\n\n const renderContext = getRenderContext();\n return (\n renderContext?.routeAuth ??\n activeClientRouteAuthOptions ??\n defaultRouteAuthOptions\n );\n}\n\nexport function _setActiveRouteAuthOptions(\n auth: RouteAuthOptions | undefined\n): void {\n activeClientRouteAuthOptions = auth;\n}\n\nfunction getCurrentRegistrationSession(): RegistrationSession {\n return (\n registrationSessionStack[registrationSessionStack.length - 1] ?? {\n authConfigured: !!defaultRouteAuthOptions?.resolve,\n }\n );\n}\n\nfunction getCurrentAccessScopeState(): AccessScopeState {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.state ?? {\n guestOnly: false,\n authenticated: false,\n }\n );\n}\n\nfunction getCurrentLayoutChain(): LayoutScopeRecord[] {\n const layoutChain: LayoutScopeRecord[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.layout) {\n layoutChain.push({ component: scope.layout });\n }\n }\n\n return layoutChain;\n}\n\nfunction getCurrentPageChain(): PageScopeRecord[] {\n const pageChain: PageScopeRecord[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.page) {\n pageChain.push({ component: scope.page });\n }\n }\n\n return pageChain;\n}\n\nfunction hasActivePageScope(): boolean {\n return registrationScopeStack.some((scope) => !!scope.page);\n}\n\nfunction getCurrentScopeKind(): RegistrationScope['kind'] | null {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.kind ?? null\n );\n}\n\nfunction getCurrentPathPrefix(): string {\n return (\n registrationScopeStack[registrationScopeStack.length - 1]?.pathPrefix ?? ''\n );\n}\n\nfunction getCurrentInheritedPolicies(): RoutePolicy[] {\n const policies: RoutePolicy[] = [];\n\n for (const scope of registrationScopeStack) {\n if (scope.policies.length > 0) {\n policies.push(...scope.policies);\n }\n }\n\n return policies;\n}\n\n// ---------------------------------------------------------------------------\n// Registration lock\n// ---------------------------------------------------------------------------\n\n/**\n * Prevent route registrations after the app has started.\n * Enforced in production; tests may unlock explicitly.\n */\n\nexport function lockRouteRegistration(): void {\n registrationLocked = true;\n}\n\nexport function _lockRouteRegistrationForTests(): void {\n registrationLocked = true;\n}\n\nexport function _unlockRouteRegistrationForTests(): void {\n registrationLocked = false;\n}\n\n// ---------------------------------------------------------------------------\n// Path validation\n// ---------------------------------------------------------------------------\n\nfunction validateRoutePath(path: string): void {\n if (!path.startsWith('/')) {\n throw new Error(`Route path must begin with \"/\". Got: \"${path}\"`);\n }\n // Reject Express-style :param syntax — Askr uses {param} interpolation\n if (/:([^/{}]+)/.test(path)) {\n const suggested = path.replace(/:([^/{}]+)/g, '{$1}');\n throw new Error(\n `Route parameter syntax uses {name} interpolation, not :name. ` +\n `Use \"${suggested}\" instead of \"${path}\".`\n );\n }\n}\n\nfunction normalizeAbsoluteRoutePath(path: string): string {\n if (!path || path === '/') {\n return '/';\n }\n\n const normalized = path.endsWith('/') ? path.slice(0, -1) : path;\n return normalized || '/';\n}\n\nfunction joinRoutePaths(prefix: string, path: string): string {\n const normalizedPrefix = normalizeAbsoluteRoutePath(prefix || '/');\n const normalizedPath = path.replace(/^\\/+|\\/+$/g, '');\n\n if (!normalizedPath) {\n return normalizedPrefix;\n }\n\n return normalizedPrefix === '/'\n ? `/${normalizedPath}`\n : `${normalizedPrefix}/${normalizedPath}`;\n}\n\nfunction resolvePageScopePath(path: string): string {\n if (!path) {\n throw new Error('page(path, Component, fn) requires a non-empty path.');\n }\n\n if (path.startsWith('/')) {\n validateRoutePath(path);\n return normalizeAbsoluteRoutePath(path);\n }\n\n return joinRoutePaths(getCurrentPathPrefix(), path);\n}\n\nfunction resolveIndexPath(): string {\n return normalizeAbsoluteRoutePath(getCurrentPathPrefix() || '/');\n}\n\nfunction resolveRouteRegistrationPath(path: string): string {\n if (path.startsWith('/')) {\n if (hasActivePageScope()) {\n throw new Error(\n 'Child route paths inside page() must be relative. ' +\n `Use \"${path.slice(1)}\" instead of \"${path}\".`\n );\n }\n\n validateRoutePath(path);\n return normalizeAbsoluteRoutePath(path);\n }\n\n const prefix = getCurrentPathPrefix();\n\n if (!prefix) {\n throw new Error(`Route path must begin with \"/\". Got: \"${path}\"`);\n }\n\n return joinRoutePaths(prefix, path);\n}\n\n// ---------------------------------------------------------------------------\n// Internal helper: insert a RouteRecord in rank-descending order\n// so that resolveRoute can use first-match-wins without sorting.\n// Ties preserve declaration order (stable binary-search insertion).\n// ---------------------------------------------------------------------------\n\nfunction insertRecordSorted(record: RouteRecord): void {\n let lo = 0;\n let hi = records.length;\n // Find the insertion point: after all existing records with rank >= this one\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (records[mid].rank >= record.rank) lo = mid + 1;\n else hi = mid;\n }\n records.splice(lo, 0, record);\n}\n\n// ---------------------------------------------------------------------------\n// Internal helper: add a single pre-built Route object to the runtime stores\n// ---------------------------------------------------------------------------\n\nfunction addRouteToStores(routeObj: Route): void {\n routes.push(routeObj);\n setHasRoutes(true);\n\n const depth = getDepth(routeObj.path);\n let depthRoutes = routesByDepth.get(depth);\n if (!depthRoutes) {\n depthRoutes = [];\n routesByDepth.set(depth, depthRoutes);\n }\n depthRoutes.push(routeObj);\n\n if (routeObj.namespace) {\n namespaces.add(routeObj.namespace);\n }\n}\n\n// ---------------------------------------------------------------------------\n// lazy() — eager-prefetch code-split component wrapper\n// ---------------------------------------------------------------------------\n\n/** Promises from in-flight lazy() imports, drained by createSPA / hydrateSPA. */\nconst pendingLazy = new Set<Promise<unknown>>();\n\nconst outletContext = defineContext<unknown>(null);\n\nexport function Outlet(): unknown {\n return readContext(outletContext);\n}\n\n/**\n * Snapshot the current in-flight lazy() imports.\n * Boot uses this before clearing route state so manifest-based startup can\n * still await chunks that were kicked off during route module evaluation.\n */\nexport function _snapshotLazy(): Promise<unknown>[] {\n return [...pendingLazy];\n}\n\n/**\n * Declare a code-split route component. The `import()` fires immediately at\n * module evaluation time (creating a bundler split point), and the resolved\n * chunk is guaranteed to be available before the app mounts — so the renderer\n * always receives a plain synchronous function.\n *\n * ```ts\n * registerRoutes(() => {\n * group({ layout: AppLayout }, () => {\n * route('/', lazy(() => import('./pages/landing')));\n * route('/dashboard', lazy(() => import('./pages/dashboard')));\n * });\n * });\n * ```\n *\n * The module must export the component as its **default** export:\n * ```ts\n * // pages/dashboard.tsx\n * export default function DashboardPage() { … }\n * ```\n */\nexport function lazy(\n factory: () => Promise<{ default: RouteComponent } | RouteComponent>\n): RouteComponent {\n let resolved: RouteComponent | null = null;\n let loadError: unknown = null;\n\n const promise = factory().then(\n (mod) => {\n resolved =\n typeof mod === 'function'\n ? mod\n : (mod as { default: RouteComponent }).default;\n pendingLazy.delete(promise);\n },\n (err: unknown) => {\n loadError = err;\n pendingLazy.delete(promise);\n }\n );\n pendingLazy.add(promise);\n\n return (params) => {\n if (loadError) throw loadError as Error;\n if (!resolved) {\n throw new Error(\n 'lazy() component used before it was resolved. ' +\n 'Await createSPA() / hydrateSPA() to ensure all chunks load first.'\n );\n }\n return resolved(params);\n };\n}\n\n/**\n * Wait for all pending `lazy()` imports to settle.\n * Called automatically by `createSPA` / `hydrateSPA` before mounting.\n */\nexport function _drainLazy(\n additionalPending: Iterable<Promise<unknown>> = []\n): Promise<void> {\n const combined = new Set<Promise<unknown>>([\n ...additionalPending,\n ...pendingLazy,\n ]);\n if (combined.size === 0) return Promise.resolve();\n return Promise.allSettled(combined).then(() => undefined);\n}\n\nexport function group(options: GroupHelperOptions, fn: RouteDefinition): void;\nexport function group(options: GroupHelperOptions, fn: RouteDefinition): void {\n pushGroupScope(options, fn);\n}\n\nexport function page(\n path: string,\n Component: RouteComponent,\n fn: RouteDefinition\n): void;\nexport function page(\n path: string,\n Component: RouteComponent,\n options: PageHelperOptions,\n fn: RouteDefinition\n): void;\nexport function page(\n path: string,\n Component: RouteComponent,\n optionsOrFn: PageHelperOptions | RouteDefinition,\n maybeFn?: RouteDefinition\n): void {\n const options =\n typeof optionsOrFn === 'function' ? ({} as PageHelperOptions) : optionsOrFn;\n const fn = typeof optionsOrFn === 'function' ? optionsOrFn : maybeFn;\n\n if (typeof Component !== 'function') {\n throw new Error(\n 'page(path, Component, fn) requires a component function as the second argument.'\n );\n }\n\n if (typeof fn !== 'function') {\n throw new Error(\n 'page(path, Component, fn) requires a route definition callback as the final argument.'\n );\n }\n\n pushPageScope(path, Component, options, fn);\n}\n\nexport function index(Component: RouteComponent, options?: RouteOptions): void {\n registerRouteAtResolvedPath(resolveIndexPath(), Component, options);\n}\n\nexport function fallback(Component: RouteComponent): void {\n if (hasActivePageScope()) {\n if (getCurrentScopeKind() !== 'page') {\n throw new Error(\n 'fallback() inside page() must be declared directly in the page scope, not inside nested group().'\n );\n }\n\n registerRouteAtResolvedPath(\n `${getCurrentPathPrefix()}/*`,\n Component,\n undefined,\n { isFallback: true, fallbackPrefix: getCurrentPathPrefix() }\n );\n return;\n }\n\n const allowsRootFallback = registrationScopeStack.every(\n (scope) =>\n scope.policies.length === 0 &&\n !scope.state.guestOnly &&\n !scope.state.authenticated\n );\n\n if (!allowsRootFallback) {\n throw new Error(\n 'fallback() can only be registered at the root scope. ' +\n 'Use route(\"/*\", Component) if you need compatibility behavior.'\n );\n }\n\n registerRouteAtResolvedPath('/*', Component, undefined, {\n isFallback: true,\n fallbackPrefix: '/',\n });\n}\n\nfunction pushRegistrationScope(\n scope: RegistrationScope,\n fn: RouteDefinition\n): void {\n registrationScopeStack.push(scope);\n try {\n fn();\n } finally {\n registrationScopeStack.pop();\n }\n}\n\nfunction pushGroupScope(\n options: GroupHelperOptions,\n fn: RouteDefinition\n): void {\n const session = getCurrentRegistrationSession();\n validateAccessMetadata(options, {\n authConfigured: session.authConfigured,\n state: getCurrentAccessScopeState(),\n });\n const policies = compileNodePolicies(options);\n\n pushRegistrationScope(\n {\n kind: 'group',\n pathPrefix: getCurrentPathPrefix(),\n layout: options.layout,\n policies,\n state: nextAccessScopeState(options, getCurrentAccessScopeState()),\n },\n fn\n );\n}\n\nfunction pushPageScope(\n path: string,\n Component: RouteComponent,\n options: PageHelperOptions,\n fn: RouteDefinition\n): void {\n if (hasActivePageScope()) {\n throw new Error(\n 'page() cannot be nested inside another page(). ' +\n 'Use route() for child leaves or group() for inherited behavior inside the existing page scope.'\n );\n }\n\n const session = getCurrentRegistrationSession();\n validateAccessMetadata(options, {\n authConfigured: session.authConfigured,\n state: getCurrentAccessScopeState(),\n });\n\n const policies = compileNodePolicies(options);\n\n pushRegistrationScope(\n {\n kind: 'page',\n pathPrefix: resolvePageScopePath(path),\n page: Component,\n policies,\n state: nextAccessScopeState(options, getCurrentAccessScopeState()),\n },\n fn\n );\n}\n\nfunction hasBuiltInAuthMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>\n): boolean {\n return node.auth !== undefined || !!node.role || !!node.permission;\n}\n\nfunction validateSameNodeAccessMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>\n): void {\n if (node.auth === 'guest' && (!!node.role || !!node.permission)) {\n throw new Error(\n 'Guest-only routes cannot be combined with role or permission requirements.'\n );\n }\n}\n\nfunction validateAccessMetadata(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>,\n context: {\n authConfigured: boolean;\n state: AccessScopeState;\n }\n): void {\n validateSameNodeAccessMetadata(node);\n\n const requiresAuthenticated =\n node.auth === true || !!node.role || !!node.permission;\n\n if (\n node.auth === 'guest' &&\n (context.state.authenticated || !!node.role || !!node.permission)\n ) {\n throw new Error(\n 'Guest-only routes cannot be combined with authenticated access requirements.'\n );\n }\n\n if (context.state.guestOnly && requiresAuthenticated) {\n throw new Error(\n 'Child routes cannot weaken a guest-only access scope with authenticated requirements.'\n );\n }\n\n if (hasBuiltInAuthMetadata(node) && !context.authConfigured) {\n throw new Error(\n 'Routes using `auth`, `role`, or `permission` require `auth.resolve` in registerRoutes(...).'\n );\n }\n}\n\nfunction nextAccessScopeState(\n node: Pick<GroupHelperOptions | RouteOptions, 'auth' | 'role' | 'permission'>,\n state: AccessScopeState\n): AccessScopeState {\n const requiresAuthenticated =\n node.auth === true || !!node.role || !!node.permission;\n\n return {\n guestOnly: state.guestOnly || node.auth === 'guest',\n authenticated: state.authenticated || requiresAuthenticated,\n };\n}\n\nfunction compileNodePolicies(\n node: Pick<\n RouteOptions | GroupHelperOptions,\n 'auth' | 'role' | 'permission' | 'policies'\n >\n): RoutePolicy[] {\n validateSameNodeAccessMetadata(node);\n\n const compiled: RoutePolicy[] = [];\n\n if (node.auth === true) {\n compiled.push(requireAuth());\n } else if (node.auth === 'guest') {\n compiled.push(requireGuest());\n }\n\n if (node.role) {\n compiled.push(requireRole(node.role));\n }\n\n if (node.permission) {\n compiled.push(requirePermission(node.permission));\n }\n\n if (node.policies?.length) {\n compiled.push(...node.policies);\n }\n\n return compiled;\n}\n\nfunction normalizeRouteOptions(\n options: RouteOptions | undefined\n): RouteOptions | undefined {\n if (!options) {\n return undefined;\n }\n\n const loader = options.loader;\n const policies = compileNodePolicies(options);\n\n if (\n !loader &&\n !options.entries &&\n policies.length === 0 &&\n !options.title &&\n !options.namespace &&\n options.auth === undefined &&\n !options.role &&\n !options.permission\n ) {\n return undefined;\n }\n\n return {\n ...(loader ? { loader } : {}),\n ...(options.entries ? { entries: options.entries } : {}),\n ...(options.auth !== undefined ? { auth: options.auth } : {}),\n ...(options.role ? { role: options.role } : {}),\n ...(options.permission ? { permission: options.permission } : {}),\n ...(policies.length > 0 ? { policies } : {}),\n ...(options.title ? { title: options.title } : {}),\n ...(options.namespace ? { namespace: options.namespace } : {}),\n };\n}\n\nfunction applyPageChain(\n pageChain: readonly PageScopeRecord[],\n params: Record<string, string>,\n content: unknown\n): unknown {\n let nextContent = content;\n\n for (let i = pageChain.length - 1; i >= 0; i--) {\n nextContent = outletContext.Scope({\n value: nextContent,\n children: pageChain[i].component(params),\n });\n }\n\n return nextContent;\n}\n\nfunction registerRouteAtResolvedPath(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions,\n metadata?: {\n isFallback?: boolean;\n fallbackPrefix?: string;\n }\n): void {\n validateAccessMetadata(options ?? {}, {\n authConfigured: getCurrentRegistrationSession().authConfigured,\n state: getCurrentAccessScopeState(),\n });\n\n const chain = getCurrentLayoutChain();\n const pageChain = getCurrentPageChain();\n const segments = parseSegments(path);\n const rank = computeRank(segments);\n const isFallback = metadata?.isFallback ?? path === '/*';\n const comp = Component;\n const normalizedOptions = normalizeRouteOptions(options);\n const policies = [\n ...getCurrentInheritedPolicies(),\n ...(normalizedOptions?.policies ?? []),\n ];\n\n const handler: RouteHandler = (params) => {\n let content = comp(params);\n\n content = applyPageChain(pageChain, params, content);\n\n for (let i = chain.length - 1; i >= 0; i--) {\n content = chain[i].component({ children: content });\n }\n\n return content;\n };\n\n const record: InternalRouteRecord = {\n path,\n component: comp,\n segments,\n rank,\n layoutChain: chain,\n pageChain,\n options: normalizedOptions\n ? {\n ...normalizedOptions,\n ...(policies.length > 0 ? { policies } : {}),\n }\n : policies.length > 0\n ? { policies }\n : {},\n isFallback,\n handler,\n ...(metadata?.fallbackPrefix\n ? { fallbackPrefix: metadata.fallbackPrefix }\n : {}),\n };\n\n insertRecordSorted(record);\n addRouteToStores({\n path,\n handler,\n namespace: normalizedOptions?.namespace ?? options?.namespace,\n ...(metadata?.fallbackPrefix\n ? { fallbackPrefix: metadata.fallbackPrefix }\n : {}),\n });\n}\n\nexport function registerRoutes(\n definition: RouteDefinition,\n options: RegisterRoutesOptions = {}\n): void {\n defaultRouteAuthOptions = options.auth;\n\n registrationSessionStack.push({\n authConfigured: !!options.auth?.resolve,\n });\n try {\n definition();\n } finally {\n registrationSessionStack.pop();\n }\n}\n\n// ---------------------------------------------------------------------------\n// route() — dual-purpose: registration (module load) + accessor (render time)\n// ---------------------------------------------------------------------------\n\nfunction readCurrentRouteSnapshot(): RouteSnapshot {\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'currentRoute() can only be called during component render execution. ' +\n 'Call currentRoute() from inside your component function.'\n );\n }\n\n let pathname = '/';\n let search = '';\n let hash = '';\n const renderContext = getRenderContext();\n\n if (instance.ssr && renderContext?.url) {\n const parsed = parseLocation(renderContext.url);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n } else if (typeof window !== 'undefined' && window.location) {\n pathname = window.location.pathname || '/';\n search = window.location.search || '';\n hash = window.location.hash || '';\n } else if (serverLocation) {\n const parsed = parseLocation(serverLocation);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n }\n\n const query = makeQuery(search);\n const matches = computeMatchesFromRoutes(pathname, getActiveRoutes());\n const instanceParams = instance.props as Record<string, string>;\n const routeParams =\n Object.keys(instanceParams).length > 0\n ? instanceParams\n : (matches[0]?.params ?? {});\n const params = deepFreeze({\n ...routeParams,\n });\n\n return Object.freeze({\n path: pathname,\n params,\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n}\n\nexport function currentRoute(): RouteSnapshot {\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'currentRoute() can only be called during component render execution. ' +\n 'Call currentRoute() from inside your component function.'\n );\n }\n\n if (typeof window === 'undefined' || instance.ssr) {\n return readCurrentRouteSnapshot();\n }\n\n recordReadableRead(currentRouteSource);\n return readCurrentRouteSnapshot();\n}\n\nexport function syncCurrentRouteSnapshot(\n pathname: string,\n search: string,\n hash: string\n): void {\n setCurrentRouteSnapshot(pathname, search, hash);\n}\n\n/**\n * Register a route.\n *\n * ```ts\n * route('/posts/{slug}', PostPage, {\n * loader: ({ params }) => getPost(params.slug),\n * entries: async () => getPosts().map(p => ({ slug: p.slug })),\n * title: 'Post',\n * policies:[requireAuth()],\n * });\n * ```\n */\nexport function route(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions\n): void;\nexport function route(\n path: string,\n Component: RouteComponent,\n options?: RouteOptions\n): void {\n if (typeof path === 'undefined') {\n throw new Error(\n 'route() is only for route registration. Use currentRoute() inside components.'\n );\n }\n\n if (getExecutionModel() === 'islands') {\n throw new Error(\n 'Routes are not supported with islands. Use createSPA (client) or createSSR (server) instead.'\n );\n }\n\n // ── Registration mode ────────────────────────────────────────────────────\n\n // Disallow registration during SSR render\n const currentInst = getCurrentComponentInstance();\n if (currentInst && currentInst.ssr) {\n throw new Error(\n 'route() cannot be called during SSR rendering. Register routes at module load time instead.'\n );\n }\n\n if (registrationLocked) {\n throw new Error(\n 'Route registration is locked after app startup. ' +\n 'Register routes at module load time before calling createSPA or createSSR.'\n );\n }\n\n if (typeof Component !== 'function') {\n throw new Error(\n 'route(path, Component) requires a component function as the second argument. ' +\n 'Passing JSX elements or VNodes directly is not supported.'\n );\n }\n\n registerRouteAtResolvedPath(\n resolveRouteRegistrationPath(path),\n Component,\n options\n );\n}\n\n// ---------------------------------------------------------------------------\n// Manifest access\n// ---------------------------------------------------------------------------\n\n/**\n * Return the normalized route manifest built from registered route definitions.\n *\n * Pass this to `createSPA`, `hydrateSPA`, or `renderToString` as the\n * authoritative routing input:\n *\n * ```ts\n * import { getManifest } from '@askrjs/askr/router';\n * await createSPA({ root: '#app', manifest: getManifest() });\n * ```\n */\nexport function getManifest(): RouteManifest {\n return {\n records: [...records],\n ...(defaultRouteAuthOptions ? { auth: defaultRouteAuthOptions } : {}),\n };\n}\n\n/**\n * Internal: apply a pre-built manifest to the runtime stores without running\n * route() again. Called by createSPA / hydrateSPA when a manifest is passed.\n */\nexport function _applyManifest(manifest: RouteManifest): void {\n defaultRouteAuthOptions = manifest.auth;\n for (const record of manifest.records) {\n insertRecordSorted(record as InternalRouteRecord);\n addRouteToStores({\n path: record.path,\n handler: record.handler,\n namespace: record.options.namespace,\n ...('fallbackPrefix' in record &&\n typeof (record as InternalRouteRecord).fallbackPrefix === 'string'\n ? {\n fallbackPrefix: (record as InternalRouteRecord).fallbackPrefix,\n }\n : {}),\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Route collection helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Get all registered routes (flat list, insertion order).\n * Prefer `getManifest()` when metadata (loader, policies, entries) is needed.\n */\nexport function getRoutes(): Route[] {\n return [...routes];\n}\n\n/** Get routes for a specific namespace. */\nexport function getNamespaceRoutes(namespace: string): Route[] {\n return routes.filter((r) => r.namespace === namespace);\n}\n\n/** Unload all routes from a namespace (for MFE unmounting). */\nexport function unloadNamespace(namespace: string): number {\n const before = routes.length;\n\n for (let i = routes.length - 1; i >= 0; i--) {\n if (routes[i].namespace === namespace) {\n const removed = routes[i];\n routes.splice(i, 1);\n\n const depth = getDepth(removed.path);\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n const idx = depthRoutes.indexOf(removed);\n if (idx >= 0) depthRoutes.splice(idx, 1);\n }\n }\n }\n\n // Remove matching records too\n for (let i = records.length - 1; i >= 0; i--) {\n if (records[i].options.namespace === namespace) {\n records.splice(i, 1);\n }\n }\n\n namespaces.delete(namespace);\n return before - routes.length;\n}\n\n/** Clear all registered routes and records (testing / boot reset). */\nexport function clearRoutes(): void {\n routes.length = 0;\n records.length = 0;\n namespaces.clear();\n routesByDepth.clear();\n registrationScopeStack.length = 0;\n registrationSessionStack.length = 0;\n registrationLocked = false;\n defaultRouteAuthOptions = undefined;\n activeClientRouteAuthOptions = undefined;\n setHasRoutes(false);\n pendingLazy.clear();\n}\n\n/**\n * Get all loaded namespaces (MFE identifiers)\n */\nexport function getLoadedNamespaces(): string[] {\n return Array.from(namespaces);\n}\n\nfunction findBestScopedFallbackRecord(\n pathname: string,\n routeRecords: readonly RouteRecord[]\n): { record: InternalRouteRecord; params: Record<string, string> } | null {\n let bestRecord: InternalRouteRecord | null = null;\n let bestParams: Record<string, string> | null = null;\n let bestPrefixLength = -1;\n\n for (const routeRecord of routeRecords) {\n const record = routeRecord as InternalRouteRecord;\n if (!record.fallbackPrefix) {\n continue;\n }\n\n const params = matchFallbackPrefix(pathname, record.fallbackPrefix);\n if (params === null) {\n continue;\n }\n\n if (record.fallbackPrefix.length > bestPrefixLength) {\n bestRecord = record;\n bestParams = params;\n bestPrefixLength = record.fallbackPrefix.length;\n }\n }\n\n return bestRecord && bestParams\n ? { record: bestRecord, params: bestParams }\n : null;\n}\n\n/**\n * Resolve a path to a route handler.\n *\n * Hot path: walks the module-level `records[]` array which is kept sorted by\n * rank descending at registration time — so the first `matchSegments` hit is\n * always the most specific match. No per-call allocations for the common\n * case of purely-static routes.\n */\nexport function resolveRoute(pathname: string): ResolvedRoute | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n for (const record of records) {\n if (record.fallbackPrefix) {\n continue;\n }\n\n const params = matchSegments(urlParts, record.segments);\n if (params !== null) {\n return { handler: record.handler, params };\n }\n }\n\n const fallbackMatch = findBestScopedFallbackRecord(normalized, records);\n return fallbackMatch\n ? { handler: fallbackMatch.record.handler, params: fallbackMatch.params }\n : null;\n}\n\nfunction getMatchingRecord(\n target: string,\n routeRecords: readonly RouteRecord[]\n): { record: RouteRecord; params: Record<string, string> } | null {\n const location = parseLocation(target);\n const normalized =\n location.pathname.endsWith('/') && location.pathname !== '/'\n ? location.pathname.slice(0, -1)\n : location.pathname;\n const urlParts =\n normalized === '/' ? [] : normalized.split('/').filter(Boolean);\n\n for (const record of routeRecords) {\n const internalRecord = record as InternalRouteRecord;\n if (internalRecord.fallbackPrefix) {\n continue;\n }\n\n const params = matchSegments(urlParts, record.segments);\n if (params !== null) {\n return { record, params };\n }\n }\n\n return findBestScopedFallbackRecord(normalized, routeRecords);\n}\n\nfunction getRoutePolicies(\n options: RouteOptions | undefined\n): readonly RoutePolicy[] {\n if (!options) {\n return [];\n }\n\n if (options.policies?.length) {\n return options.policies;\n }\n\n return compileNodePolicies(options);\n}\n\nfunction getDefaultRouteMode(): RouteContext['mode'] {\n if (typeof window !== 'undefined') {\n return 'spa';\n }\n\n return 'ssr';\n}\n\nfunction buildRenderResult(\n record: RouteRecord,\n params: Record<string, string>\n): RouteRenderResult {\n return {\n kind: 'render',\n handler: record.handler,\n params,\n };\n}\n\nfunction continueRoutePolicies(\n policies: readonly RoutePolicy[],\n context: RouteContext,\n record: RouteRecord,\n params: Record<string, string>,\n startIndex = 0\n): RouteRequestResult | Promise<RouteRequestResult> {\n for (let index = startIndex; index < policies.length; index += 1) {\n const policyResult = policies[index](context);\n\n if (isPromise(policyResult)) {\n return policyResult.then((next) => {\n if (next.kind !== 'allow') {\n return next;\n }\n\n return continueRoutePolicies(\n policies,\n context,\n record,\n params,\n index + 1\n );\n });\n }\n\n if (policyResult.kind !== 'allow') {\n return policyResult;\n }\n }\n\n return buildRenderResult(record, params);\n}\n\nexport function resolveRouteRequest(\n target: string,\n options: RouteRequestOptions = {}\n): RouteRequestResult | Promise<RouteRequestResult> {\n const routeRecords = options.manifest?.records ?? records;\n const match = getMatchingRecord(target, routeRecords);\n\n if (!match) {\n return null;\n }\n\n const { record, params } = match;\n const policies = getRoutePolicies(record.options);\n\n if (policies.length === 0) {\n return buildRenderResult(record, params);\n }\n\n const signal =\n options.signal ??\n getRenderContext()?.signal ??\n new AbortController().signal;\n const mode = options.mode ?? getDefaultRouteMode();\n const auth = getActiveRouteAuthOptions(\n options.auth ?? options.manifest?.auth\n );\n const baseContext = buildRouteContextBase(target, params, {\n mode,\n signal,\n });\n\n const finalize = (authState: { session: unknown; user: unknown }) =>\n continueRoutePolicies(\n policies,\n buildRouteContext(target, params, {\n mode,\n signal,\n auth,\n session: authState.session,\n user: authState.user,\n }),\n record,\n params\n );\n\n if (!auth?.resolve) {\n return finalize({ session: null, user: null });\n }\n\n const authState = auth.resolve(baseContext);\n if (isPromise(authState)) {\n return authState.then((next) => finalize(next));\n }\n\n return finalize(authState);\n}\n\n/**\n * Resolve a path against an explicit route list (e.g. an SSR per-render\n * context). When called with the global `routes` array this delegates to\n * the faster `resolveRoute` which uses pre-sorted `records[]`.\n *\n * For externally supplied lists the function:\n * 1. Builds a rank-sorted copy of the list on first call and caches it\n * in a WeakMap so subsequent resolutions against the same list pay\n * zero sort cost.\n * 2. Uses pre-parsed `ParsedSegment[]` from a WeakMap cache so no string\n * splitting or segment parsing occurs on the hot path.\n * 3. Uses a running-best with an early-exit once the sorted list reaches\n * a rank that cannot beat the current best match.\n */\nexport function resolveRouteFromRoutes(\n pathname: string,\n routeList: readonly Route[]\n): ResolvedRoute | null {\n if (routeList === routes) return resolveRoute(pathname);\n\n const match = findBestResolvedRouteFromRoutes(pathname, routeList);\n return match ? { handler: match.route.handler, params: match.params } : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2GA,MAAM,SAA0B,EAAE;;AAGlC,MAAM,UAAiC,EAAE;;AAgBzC,MAAM,yBAA8C,EAAE;AACtD,MAAM,2BAAkD,EAAE;AAE1D,MAAM,6BAAa,IAAI,KAAa;AACpC,IAAI,qBAAqB;AAOzB,IAAI;AACJ,IAAI;AAEJ,MAAM,iBAAiB,OAAO,IAAI,sBAAsB;AAExD,SAAS,aAAa,OAAsB;CAC1C,IAAI;EACF,MAAM,IAAI;EACV,EAAE,kBAAkB;SACd;;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