@askrjs/askr 0.0.42 → 0.0.43
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/dist/benchmark.js +2 -2
- package/dist/boot/index.d.ts.map +1 -1
- package/dist/boot/index.js +2 -0
- package/dist/boot/index.js.map +1 -1
- package/dist/common/route-activity.js +30 -0
- package/dist/common/route-activity.js.map +1 -0
- package/dist/common/router.d.ts +4 -2
- package/dist/common/router.d.ts.map +1 -1
- package/dist/data/index.d.ts +21 -2
- package/dist/data/index.d.ts.map +1 -1
- package/dist/data/index.js +56 -3
- package/dist/data/index.js.map +1 -1
- package/dist/data/invalidation-listeners.js +15 -0
- package/dist/data/invalidation-listeners.js.map +1 -0
- package/dist/renderer/dom.js +23 -15
- package/dist/renderer/dom.js.map +1 -1
- package/dist/renderer/evaluate.js +9 -13
- package/dist/renderer/evaluate.js.map +1 -1
- package/dist/renderer/for-commit.js +9 -0
- package/dist/renderer/for-commit.js.map +1 -1
- package/dist/resources/index.d.ts +2 -2
- package/dist/resources/index.js +2 -2
- package/dist/router/match.js +31 -6
- package/dist/router/match.js.map +1 -1
- package/dist/router/navigate.d.ts.map +1 -1
- package/dist/router/navigate.js +30 -4
- package/dist/router/navigate.js.map +1 -1
- package/dist/router/route.d.ts +6 -1
- package/dist/router/route.d.ts.map +1 -1
- package/dist/router/route.js +35 -8
- package/dist/router/route.js.map +1 -1
- package/dist/runtime/component.d.ts +7 -1
- package/dist/runtime/component.d.ts.map +1 -1
- package/dist/runtime/component.js +205 -44
- package/dist/runtime/component.js.map +1 -1
- package/dist/runtime/fastlane.js +6 -0
- package/dist/runtime/fastlane.js.map +1 -1
- package/dist/runtime/operations.d.ts +11 -3
- package/dist/runtime/operations.d.ts.map +1 -1
- package/dist/runtime/operations.js +161 -22
- package/dist/runtime/operations.js.map +1 -1
- package/dist/runtime/readable.d.ts +1 -0
- package/dist/runtime/readable.d.ts.map +1 -1
- package/dist/runtime/readable.js +7 -4
- package/dist/runtime/readable.js.map +1 -1
- package/dist/testing/index.d.ts +53 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +172 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +11 -3
package/dist/router/navigate.js
CHANGED
|
@@ -4,7 +4,7 @@ import { ELEMENT_TYPE, Fragment } from "../common/jsx.js";
|
|
|
4
4
|
import { isPromiseLike } from "../common/promise.js";
|
|
5
5
|
import { cleanupComponent, mountComponent } from "../runtime/component.js";
|
|
6
6
|
import { cleanupInstancesUnder } from "../renderer/cleanup.js";
|
|
7
|
-
import { lockRouteRegistration, resolveRouteFromRoutes, resolveRouteRequest, syncCurrentRouteSnapshot } from "./route.js";
|
|
7
|
+
import { computeRouteActivityMatches, lockRouteRegistration, resolveRouteFromRoutes, resolveRouteRequest, syncCurrentRouteSnapshot } from "./route.js";
|
|
8
8
|
import "../jsx/index.js";
|
|
9
9
|
import { DefaultPortal, clearDefaultPortalForInstance } from "../foundations/structures/portal.js";
|
|
10
10
|
//#region src/router/navigate.ts
|
|
@@ -19,6 +19,27 @@ let activeRouteRequestId = 0;
|
|
|
19
19
|
let activeRouteRequestController = null;
|
|
20
20
|
const MAX_NAVIGATION_REDIRECTS = 20;
|
|
21
21
|
const registeredApps = [];
|
|
22
|
+
function collectRouteActivityMatches(pathname, apps = registeredApps) {
|
|
23
|
+
const matches = [];
|
|
24
|
+
const seenPaths = /* @__PURE__ */ new Set();
|
|
25
|
+
for (const app of apps) {
|
|
26
|
+
const appMatches = computeRouteActivityMatches(pathname, {
|
|
27
|
+
manifest: app.manifest,
|
|
28
|
+
routes: app.routes
|
|
29
|
+
});
|
|
30
|
+
for (const match of appMatches) {
|
|
31
|
+
if (seenPaths.has(match.path)) continue;
|
|
32
|
+
seenPaths.add(match.path);
|
|
33
|
+
matches.push(match);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return matches;
|
|
37
|
+
}
|
|
38
|
+
function syncRegisteredRouteSnapshot() {
|
|
39
|
+
if (typeof window === "undefined") return;
|
|
40
|
+
const pathname = window.location.pathname || "/";
|
|
41
|
+
syncCurrentRouteSnapshot(pathname, window.location.search || "", window.location.hash || "", collectRouteActivityMatches(pathname));
|
|
42
|
+
}
|
|
22
43
|
function syncAppRegistrationLocation(app, pathname, href) {
|
|
23
44
|
app.pathname = pathname;
|
|
24
45
|
app.href = href;
|
|
@@ -199,6 +220,8 @@ function remountResolvedRoute(instance, resolved, pathname, href) {
|
|
|
199
220
|
instance.evaluationGeneration++;
|
|
200
221
|
instance.notifyUpdate = null;
|
|
201
222
|
instance.mountOperations = [];
|
|
223
|
+
instance.commitOperations = [];
|
|
224
|
+
instance.lifecycleSlots = [];
|
|
202
225
|
instance.cleanupFns = [];
|
|
203
226
|
instance._placeholder = void 0;
|
|
204
227
|
instance.hasPendingUpdate = false;
|
|
@@ -293,7 +316,7 @@ function applyNavigationTargets(path, options, redirectState, pathname, href, ta
|
|
|
293
316
|
saveScrollPosition(currentHref);
|
|
294
317
|
const historyMethod = getNavigationHistoryMode(options) === "replace" ? "replaceState" : "pushState";
|
|
295
318
|
window.history[historyMethod]({ path: href }, "", href);
|
|
296
|
-
|
|
319
|
+
syncRegisteredRouteSnapshot();
|
|
297
320
|
for (const target of matchedTargets) {
|
|
298
321
|
const resolved = target.resolved;
|
|
299
322
|
if (resolved.kind === "redirect") continue;
|
|
@@ -324,18 +347,20 @@ function registerAppInstance(instance, path, source = {}) {
|
|
|
324
347
|
currentInstance = instance;
|
|
325
348
|
currentPathname = path;
|
|
326
349
|
currentHref = getWindowHref();
|
|
327
|
-
|
|
350
|
+
syncRegisteredRouteSnapshot();
|
|
328
351
|
if (isProductionEnvironment()) lockRouteRegistration();
|
|
329
352
|
}
|
|
330
353
|
function unregisterAppInstance(instance) {
|
|
331
354
|
const existingIndex = registeredApps.findIndex((app) => app.instance === instance);
|
|
332
355
|
if (existingIndex >= 0) registeredApps.splice(existingIndex, 1);
|
|
356
|
+
syncRegisteredRouteSnapshot();
|
|
333
357
|
if (currentInstance !== instance) return;
|
|
334
358
|
const nextApp = registeredApps.length > 0 ? registeredApps[registeredApps.length - 1] : null;
|
|
335
359
|
currentInstance = nextApp?.instance ?? null;
|
|
336
360
|
if (nextApp) {
|
|
337
361
|
currentPathname = nextApp.pathname;
|
|
338
362
|
currentHref = nextApp.href;
|
|
363
|
+
syncRegisteredRouteSnapshot();
|
|
339
364
|
return;
|
|
340
365
|
}
|
|
341
366
|
activeRouteRequestId += 1;
|
|
@@ -343,6 +368,7 @@ function unregisterAppInstance(instance) {
|
|
|
343
368
|
activeRouteRequestController = null;
|
|
344
369
|
currentPathname = "/";
|
|
345
370
|
currentHref = "/";
|
|
371
|
+
if (typeof window === "undefined") syncCurrentRouteSnapshot("/", "", "", []);
|
|
346
372
|
}
|
|
347
373
|
/**
|
|
348
374
|
* Navigate to a new path
|
|
@@ -401,7 +427,7 @@ function handlePopState(_event) {
|
|
|
401
427
|
navigate(resolved.to, { history: getRedirectHistoryMode(resolved.replace) });
|
|
402
428
|
return;
|
|
403
429
|
}
|
|
404
|
-
|
|
430
|
+
syncRegisteredRouteSnapshot();
|
|
405
431
|
for (const target of matchedTargets) {
|
|
406
432
|
const resolved = target.resolved;
|
|
407
433
|
if (pathname === target.app.pathname && isRenderResult(resolved)) {
|
|
@@ -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 resolveRouteRequest,\n resolveRouteFromRoutes,\n lockRouteRegistration,\n syncCurrentRouteSnapshot,\n type ResolvedRoute,\n} from './route';\nimport {\n cleanupComponent,\n mountComponent,\n type ComponentInstance,\n} from '../runtime/component';\nimport {\n isDevelopmentEnvironment,\n isProductionEnvironment,\n} from '../common/env';\nimport { logger } from '../dev/logger';\nimport type {\n Route,\n RouteAuthOptions,\n RouteManifest,\n RouteRenderResult,\n RouteRequestResult,\n} from '../common/router';\nimport { Fragment, ELEMENT_TYPE } from '../jsx';\nimport {\n DefaultPortal,\n clearDefaultPortalForInstance,\n} from '../foundations/structures/portal';\nimport { isPromiseLike } from '../common/promise';\nimport { cleanupInstancesUnder } from '../renderer/cleanup';\n\n// Global app state for navigation\nlet currentInstance: ComponentInstance | null = null;\nlet currentPathname = '/';\nlet currentHref = '/';\nlet navigationInitialized = false;\nlet activeRouteRequestId = 0;\nlet activeRouteRequestController: AbortController | null = null;\nconst MAX_NAVIGATION_REDIRECTS = 20;\n\ntype AppNavigationSource = {\n manifest?: RouteManifest;\n routes?: readonly Route[];\n auth?: RouteAuthOptions;\n};\n\ntype AppRegistration = AppNavigationSource & {\n instance: ComponentInstance;\n pathname: string;\n href: string;\n};\n\nconst registeredApps: AppRegistration[] = [];\n\nfunction syncAppRegistrationLocation(\n app: AppRegistration,\n pathname: string,\n href: string\n): void {\n app.pathname = pathname;\n app.href = href;\n}\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 replace?: boolean;\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 getRedirectHistoryMode(\n replace: boolean | undefined\n): 'push' | 'replace' {\n return replace === false ? 'push' : 'replace';\n}\n\nfunction getNavigationHistoryMode(\n options: NavigateOptions\n): 'push' | 'replace' {\n if (options.history) {\n return options.history;\n }\n\n return options.replace ? 'replace' : 'push';\n}\n\nfunction beginRouteRequest(): { id: number; signal: AbortSignal } {\n activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = new AbortController();\n\n return {\n id: activeRouteRequestId,\n signal: activeRouteRequestController.signal,\n };\n}\n\nfunction isStaleRouteRequest(requestId: number): boolean {\n return requestId !== activeRouteRequestId;\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 if (isPromiseLike(out)) {\n throw new Error(\n 'Async components are not supported. Components must return synchronously.'\n );\n }\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 cleanupRouteOwnership(instance: ComponentInstance): void {\n const cleanupErrors: unknown[] = [];\n const children = instance.target\n ? Array.from(instance.target.childNodes)\n : [];\n\n for (const child of children) {\n try {\n cleanupInstancesUnder(child, { strict: instance.cleanupStrict });\n } catch (error) {\n cleanupErrors.push(error);\n }\n }\n\n try {\n cleanupComponent(instance);\n } catch (error) {\n cleanupErrors.push(error);\n }\n\n if (cleanupErrors.length > 0) {\n throw new AggregateError(cleanupErrors, 'Route cleanup failed');\n }\n}\n\nfunction remountResolvedRoute(\n instance: ComponentInstance,\n resolved: ResolvedRoute,\n pathname: string,\n href: string\n): boolean {\n // The route handler IS the component function\n // It takes params as props and renders the route\n clearDefaultPortalForInstance(instance);\n cleanupRouteOwnership(instance);\n\n instance.fn = wrapRootRouteHandler(bindResolvedRouteHandler(resolved));\n instance.props = {};\n\n // Reset state to prevent leakage from previous route\n // Each route navigation starts completely fresh\n instance.stateValues = [];\n instance.expectedStateIndices = [];\n instance.firstRenderComplete = false;\n instance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n instance.evaluationGeneration++;\n instance.notifyUpdate = null;\n instance.mountOperations = [];\n instance.cleanupFns = [];\n instance._placeholder = undefined;\n instance.hasPendingUpdate = false;\n instance._currentRenderToken = undefined;\n instance.lastRenderToken = 0;\n instance._pendingReadSources = undefined;\n instance._lastReadSources = undefined;\n\n // Route-local async work should create a fresh abort controller lazily.\n instance.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(instance);\n currentPathname = pathname;\n currentHref = href;\n return true;\n}\n\nfunction rerenderResolvedRoute(\n instance: ComponentInstance,\n pathname: string,\n href: string\n): boolean {\n currentPathname = pathname;\n currentHref = href;\n instance._enqueueRun?.();\n return true;\n}\n\nfunction resolveAppRouteRequest(\n app: AppRegistration,\n pathname: string,\n href: string,\n signal: AbortSignal\n): RouteRequestResult | Promise<RouteRequestResult> {\n if (app.routes) {\n const resolved = resolveRouteFromRoutes(pathname, app.routes);\n if (!resolved) {\n return null;\n }\n\n return {\n kind: 'render',\n handler: resolved.handler,\n params: resolved.params,\n };\n }\n\n return resolveRouteRequest(href, {\n manifest: app.manifest,\n auth: app.auth,\n signal,\n });\n}\n\ntype AppNavigationTarget = {\n app: AppRegistration;\n resolved: RouteRequestResult;\n};\n\nfunction resolveNavigationTargetsForApps(\n pathname: string,\n href: string,\n signal: AbortSignal\n): AppNavigationTarget[] | Promise<AppNavigationTarget[]> {\n const apps = [...registeredApps];\n\n if (apps.length === 1) {\n const app = apps[0]!;\n const resolved = resolveAppRouteRequest(app, pathname, href, signal);\n if (isPromiseLike<RouteRequestResult>(resolved)) {\n return Promise.resolve(resolved).then((next) => [\n {\n app,\n resolved: next,\n },\n ]);\n }\n\n return [\n {\n app,\n resolved,\n },\n ];\n }\n\n const syncTargets: AppNavigationTarget[] = [];\n const pendingTargets: Array<Promise<AppNavigationTarget>> = [];\n\n for (const app of apps) {\n const resolved = resolveAppRouteRequest(app, pathname, href, signal);\n if (isPromiseLike<RouteRequestResult>(resolved)) {\n pendingTargets.push(\n Promise.resolve(resolved).then((next) => ({ app, resolved: next }))\n );\n continue;\n }\n\n syncTargets.push({ app, resolved });\n }\n\n if (pendingTargets.length === 0) {\n return syncTargets;\n }\n\n return Promise.all([\n ...syncTargets.map((target) => Promise.resolve(target)),\n ...pendingTargets,\n ]);\n}\n\nfunction applyNavigationTargets(\n path: string,\n options: NavigateOptions,\n redirectState: NavigationRedirectState,\n pathname: string,\n href: string,\n targets: AppNavigationTarget[]\n): void {\n const previousPathname = currentPathname;\n\n for (const target of targets) {\n const resolved = target.resolved;\n if (!resolved || resolved.kind !== 'redirect') {\n continue;\n }\n\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 if (redirectState.visited.has(redirectHref)) {\n throw new Error(\n `[Askr] Navigation redirect cycle detected at ${redirectHref}.`\n );\n }\n if (redirectState.redirects >= MAX_NAVIGATION_REDIRECTS) {\n throw new Error(\n `[Askr] Navigation redirect limit exceeded (${MAX_NAVIGATION_REDIRECTS}).`\n );\n }\n\n redirectState.visited.add(redirectHref);\n redirectState.redirects++;\n navigateWithRedirectState(\n redirectHref,\n {\n history: getRedirectHistoryMode(resolved.replace),\n },\n redirectState\n );\n return;\n }\n\n const matchedTargets = targets.filter((target) => target.resolved !== null);\n if (matchedTargets.length === 0) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${path}`);\n }\n return;\n }\n\n saveScrollPosition(currentHref);\n\n const historyMethod =\n getNavigationHistoryMode(options) === 'replace'\n ? 'replaceState'\n : '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 for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (resolved.kind === 'redirect') {\n continue;\n }\n\n if (pathname === target.app.pathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(target.app.instance, pathname, href);\n syncAppRegistrationLocation(target.app, pathname, href);\n continue;\n }\n\n remountResolvedRoute(\n target.app.instance,\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n },\n pathname,\n href\n );\n syncAppRegistrationLocation(target.app, pathname, href);\n }\n\n if (pathname !== previousPathname) {\n applyNavigationScroll(\n options.scroll ?? scrollRestorationOptions.navigation\n );\n }\n}\n\n/** Register the current app instance (called by createSPA/hydrateSPA). */\nexport function registerAppInstance(\n instance: ComponentInstance,\n path: string,\n source: AppNavigationSource = {}\n): void {\n const existingIndex = registeredApps.findIndex(\n (app) => app.instance === instance\n );\n const registration: AppRegistration = {\n instance,\n pathname: path,\n href: getWindowHref(),\n ...source,\n };\n if (existingIndex >= 0) {\n registeredApps[existingIndex] = registration;\n } else {\n registeredApps.push(registration);\n }\n\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\nexport function unregisterAppInstance(instance: ComponentInstance): void {\n const existingIndex = registeredApps.findIndex(\n (app) => app.instance === instance\n );\n if (existingIndex >= 0) {\n registeredApps.splice(existingIndex, 1);\n }\n\n if (currentInstance !== instance) {\n return;\n }\n\n const nextApp =\n registeredApps.length > 0\n ? registeredApps[registeredApps.length - 1]!\n : null;\n currentInstance = nextApp?.instance ?? null;\n if (nextApp) {\n currentPathname = nextApp.pathname;\n currentHref = nextApp.href;\n return;\n }\n\n activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = null;\n currentPathname = '/';\n currentHref = '/';\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 return;\n }\n\n const initialTarget = parseTargetUrl(path);\n navigateWithRedirectState(path, options, {\n redirects: 0,\n visited: new Set([\n `${initialTarget.pathname}${initialTarget.search}${initialTarget.hash}`,\n ]),\n });\n}\n\ntype NavigationRedirectState = {\n redirects: number;\n visited: Set<string>;\n};\n\nfunction navigateWithRedirectState(\n path: string,\n options: NavigateOptions,\n redirectState: NavigationRedirectState\n): void {\n if (typeof window === 'undefined') {\n // SSR context\n return;\n }\n\n const request = beginRouteRequest();\n\n const target = parseTargetUrl(path);\n const pathname = target.pathname;\n const href = `${target.pathname}${target.search}${target.hash}`;\n const resolvedTargets = resolveNavigationTargetsForApps(\n pathname,\n href,\n request.signal\n );\n\n if (isPromiseLike(resolvedTargets)) {\n void Promise.resolve(resolvedTargets).then(\n (targets) => {\n if (isStaleRouteRequest(request.id)) {\n return;\n }\n\n try {\n applyNavigationTargets(\n path,\n options,\n redirectState,\n pathname,\n href,\n targets\n );\n } catch (error) {\n logger.error('[Askr] navigation failed:', error);\n }\n },\n (error) => {\n logger.error('[Askr] navigation failed:', error);\n }\n );\n return;\n }\n\n applyNavigationTargets(\n path,\n options,\n redirectState,\n pathname,\n href,\n resolvedTargets\n );\n}\n\n/**\n * Handle browser back/forward buttons\n */\nfunction handlePopState(_event: PopStateEvent): void {\n const request = beginRouteRequest();\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 (registeredApps.length === 0) {\n return;\n }\n\n const applyResolved = (targets: AppNavigationTarget[]) => {\n if (isStaleRouteRequest(request.id)) {\n return;\n }\n\n const matchedTargets = targets.filter((target) => target.resolved !== null);\n if (matchedTargets.length === 0) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${pathname}`);\n }\n return;\n }\n\n for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (resolved.kind !== 'redirect') {\n continue;\n }\n\n navigate(resolved.to, {\n history: getRedirectHistoryMode(resolved.replace),\n });\n return;\n }\n\n syncCurrentRouteSnapshot(\n window.location.pathname,\n window.location.search,\n window.location.hash\n );\n\n for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (pathname === target.app.pathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(target.app.instance, pathname, href);\n syncAppRegistrationLocation(target.app, pathname, href);\n continue;\n }\n\n if (resolved.kind === 'redirect') {\n continue;\n }\n\n remountResolvedRoute(\n target.app.instance,\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n },\n pathname,\n href\n );\n syncAppRegistrationLocation(target.app, pathname, href);\n }\n\n applyHistoryScroll(href, _event.state);\n };\n\n const resolvedTargets = resolveNavigationTargetsForApps(\n pathname,\n href,\n request.signal\n );\n\n if (isPromiseLike<AppNavigationTarget[]>(resolvedTargets)) {\n void Promise.resolve(resolvedTargets).then(\n (next) => {\n try {\n applyResolved(next);\n } catch (error) {\n logger.error('[Askr] popstate navigation failed:', error);\n }\n },\n (error) => {\n logger.error('[Askr] popstate navigation failed:', error);\n }\n );\n return;\n }\n\n applyResolved(resolvedTargets);\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 activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = null;\n\n if (typeof window === 'undefined' || !navigationInitialized) {\n return;\n }\n\n navigation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O,SAAS,IAClB;EAEA,KAAK,MAAM,UAAU,gBAAgB;GACnC,MAAM,WAAW,OAAO;GACxB,IAAI,aAAa,OAAO,IAAI,YAAY,eAAe,QAAQ,GAAG;IAChE,sBAAsB,OAAO,IAAI,UAAU,UAAU,IAAI;IACzD,4BAA4B,OAAO,KAAK,UAAU,IAAI;IACtD;GACF;GAEA,IAAI,SAAS,SAAS,YACpB;GAGF,qBACE,OAAO,IAAI,UACX,SAAS,SAAS,SACd,0BAA0B,SAAS,MAAM,IACzC;IACE,SAAS,SAAS;IAClB,QAAQ,SAAS;GACnB,GACJ,UACA,IACF;GACA,4BAA4B,OAAO,KAAK,UAAU,IAAI;EACxD;EAEA,mBAAmB,MAAM,OAAO,KAAK;CACvC;CAEA,MAAM,kBAAkB,gCACtB,UACA,MACA,QAAQ,MACV;CAEA,IAAI,cAAqC,eAAe,GAAG;EACzD,AAAK,QAAQ,QAAQ,eAAe,EAAE,MACnC,SAAS;GACR,IAAI;IACF,cAAc,IAAI;GACpB,SAAS,OAAO;IACd,OAAO,MAAM,sCAAsC,KAAK;GAC1D;EACF,IACC,UAAU;GACT,OAAO,MAAM,sCAAsC,KAAK;EAC1D,CACF;EACA;CACF;CAEA,cAAc,eAAe;AAC/B;;;;AAKA,SAAgB,uBAA6B;CAC3C,IAAI,OAAO,WAAW,eAAe,uBACnC;CAGF,wBAAwB;CACxB,OAAO,iBAAiB,YAAY,cAAc;AACpD"}
|
|
1
|
+
{"version":3,"file":"navigate.js","names":[],"sources":["../../src/router/navigate.ts"],"sourcesContent":["/**\n * Client-side navigation with History API\n */\n\nimport {\n computeRouteActivityMatches,\n resolveRouteRequest,\n resolveRouteFromRoutes,\n lockRouteRegistration,\n syncCurrentRouteSnapshot,\n type ResolvedRoute,\n} from './route';\nimport {\n cleanupComponent,\n mountComponent,\n type ComponentInstance,\n} from '../runtime/component';\nimport {\n isDevelopmentEnvironment,\n isProductionEnvironment,\n} from '../common/env';\nimport { logger } from '../dev/logger';\nimport type {\n Route,\n RouteAuthOptions,\n RouteManifest,\n RouteRenderResult,\n RouteRequestResult,\n} from '../common/router';\nimport { Fragment, ELEMENT_TYPE } from '../jsx';\nimport {\n DefaultPortal,\n clearDefaultPortalForInstance,\n} from '../foundations/structures/portal';\nimport { isPromiseLike } from '../common/promise';\nimport { cleanupInstancesUnder } from '../renderer/cleanup';\n\n// Global app state for navigation\nlet currentInstance: ComponentInstance | null = null;\nlet currentPathname = '/';\nlet currentHref = '/';\nlet navigationInitialized = false;\nlet activeRouteRequestId = 0;\nlet activeRouteRequestController: AbortController | null = null;\nconst MAX_NAVIGATION_REDIRECTS = 20;\n\ntype AppNavigationSource = {\n manifest?: RouteManifest;\n routes?: readonly Route[];\n auth?: RouteAuthOptions;\n};\n\ntype AppRegistration = AppNavigationSource & {\n instance: ComponentInstance;\n pathname: string;\n href: string;\n};\n\nconst registeredApps: AppRegistration[] = [];\n\nfunction collectRouteActivityMatches(\n pathname: string,\n apps: readonly AppRegistration[] = registeredApps\n) {\n const matches: ReturnType<typeof computeRouteActivityMatches> = [];\n const seenPaths = new Set<string>();\n\n for (const app of apps) {\n const appMatches = computeRouteActivityMatches(pathname, {\n manifest: app.manifest,\n routes: app.routes,\n });\n\n for (const match of appMatches) {\n if (seenPaths.has(match.path)) {\n continue;\n }\n seenPaths.add(match.path);\n matches.push(match);\n }\n }\n\n return matches;\n}\n\nfunction syncRegisteredRouteSnapshot(): void {\n if (typeof window === 'undefined') {\n return;\n }\n\n const pathname = window.location.pathname || '/';\n syncCurrentRouteSnapshot(\n pathname,\n window.location.search || '',\n window.location.hash || '',\n collectRouteActivityMatches(pathname)\n );\n}\n\nfunction syncAppRegistrationLocation(\n app: AppRegistration,\n pathname: string,\n href: string\n): void {\n app.pathname = pathname;\n app.href = href;\n}\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 replace?: boolean;\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 getRedirectHistoryMode(\n replace: boolean | undefined\n): 'push' | 'replace' {\n return replace === false ? 'push' : 'replace';\n}\n\nfunction getNavigationHistoryMode(\n options: NavigateOptions\n): 'push' | 'replace' {\n if (options.history) {\n return options.history;\n }\n\n return options.replace ? 'replace' : 'push';\n}\n\nfunction beginRouteRequest(): { id: number; signal: AbortSignal } {\n activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = new AbortController();\n\n return {\n id: activeRouteRequestId,\n signal: activeRouteRequestController.signal,\n };\n}\n\nfunction isStaleRouteRequest(requestId: number): boolean {\n return requestId !== activeRouteRequestId;\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 if (isPromiseLike(out)) {\n throw new Error(\n 'Async components are not supported. Components must return synchronously.'\n );\n }\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 cleanupRouteOwnership(instance: ComponentInstance): void {\n const cleanupErrors: unknown[] = [];\n const children = instance.target\n ? Array.from(instance.target.childNodes)\n : [];\n\n for (const child of children) {\n try {\n cleanupInstancesUnder(child, { strict: instance.cleanupStrict });\n } catch (error) {\n cleanupErrors.push(error);\n }\n }\n\n try {\n cleanupComponent(instance);\n } catch (error) {\n cleanupErrors.push(error);\n }\n\n if (cleanupErrors.length > 0) {\n throw new AggregateError(cleanupErrors, 'Route cleanup failed');\n }\n}\n\nfunction remountResolvedRoute(\n instance: ComponentInstance,\n resolved: ResolvedRoute,\n pathname: string,\n href: string\n): boolean {\n // The route handler IS the component function\n // It takes params as props and renders the route\n clearDefaultPortalForInstance(instance);\n cleanupRouteOwnership(instance);\n\n instance.fn = wrapRootRouteHandler(bindResolvedRouteHandler(resolved));\n instance.props = {};\n\n // Reset state to prevent leakage from previous route\n // Each route navigation starts completely fresh\n instance.stateValues = [];\n instance.expectedStateIndices = [];\n instance.firstRenderComplete = false;\n instance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n instance.evaluationGeneration++;\n instance.notifyUpdate = null;\n instance.mountOperations = [];\n instance.commitOperations = [];\n instance.lifecycleSlots = [];\n instance.cleanupFns = [];\n instance._placeholder = undefined;\n instance.hasPendingUpdate = false;\n instance._currentRenderToken = undefined;\n instance.lastRenderToken = 0;\n instance._pendingReadSources = undefined;\n instance._lastReadSources = undefined;\n\n // Route-local async work should create a fresh abort controller lazily.\n instance.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(instance);\n currentPathname = pathname;\n currentHref = href;\n return true;\n}\n\nfunction rerenderResolvedRoute(\n instance: ComponentInstance,\n pathname: string,\n href: string\n): boolean {\n currentPathname = pathname;\n currentHref = href;\n instance._enqueueRun?.();\n return true;\n}\n\nfunction resolveAppRouteRequest(\n app: AppRegistration,\n pathname: string,\n href: string,\n signal: AbortSignal\n): RouteRequestResult | Promise<RouteRequestResult> {\n if (app.routes) {\n const resolved = resolveRouteFromRoutes(pathname, app.routes);\n if (!resolved) {\n return null;\n }\n\n return {\n kind: 'render',\n handler: resolved.handler,\n params: resolved.params,\n };\n }\n\n return resolveRouteRequest(href, {\n manifest: app.manifest,\n auth: app.auth,\n signal,\n });\n}\n\ntype AppNavigationTarget = {\n app: AppRegistration;\n resolved: RouteRequestResult;\n};\n\nfunction resolveNavigationTargetsForApps(\n pathname: string,\n href: string,\n signal: AbortSignal\n): AppNavigationTarget[] | Promise<AppNavigationTarget[]> {\n const apps = [...registeredApps];\n\n if (apps.length === 1) {\n const app = apps[0]!;\n const resolved = resolveAppRouteRequest(app, pathname, href, signal);\n if (isPromiseLike<RouteRequestResult>(resolved)) {\n return Promise.resolve(resolved).then((next) => [\n {\n app,\n resolved: next,\n },\n ]);\n }\n\n return [\n {\n app,\n resolved,\n },\n ];\n }\n\n const syncTargets: AppNavigationTarget[] = [];\n const pendingTargets: Array<Promise<AppNavigationTarget>> = [];\n\n for (const app of apps) {\n const resolved = resolveAppRouteRequest(app, pathname, href, signal);\n if (isPromiseLike<RouteRequestResult>(resolved)) {\n pendingTargets.push(\n Promise.resolve(resolved).then((next) => ({ app, resolved: next }))\n );\n continue;\n }\n\n syncTargets.push({ app, resolved });\n }\n\n if (pendingTargets.length === 0) {\n return syncTargets;\n }\n\n return Promise.all([\n ...syncTargets.map((target) => Promise.resolve(target)),\n ...pendingTargets,\n ]);\n}\n\nfunction applyNavigationTargets(\n path: string,\n options: NavigateOptions,\n redirectState: NavigationRedirectState,\n pathname: string,\n href: string,\n targets: AppNavigationTarget[]\n): void {\n const previousPathname = currentPathname;\n\n for (const target of targets) {\n const resolved = target.resolved;\n if (!resolved || resolved.kind !== 'redirect') {\n continue;\n }\n\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 if (redirectState.visited.has(redirectHref)) {\n throw new Error(\n `[Askr] Navigation redirect cycle detected at ${redirectHref}.`\n );\n }\n if (redirectState.redirects >= MAX_NAVIGATION_REDIRECTS) {\n throw new Error(\n `[Askr] Navigation redirect limit exceeded (${MAX_NAVIGATION_REDIRECTS}).`\n );\n }\n\n redirectState.visited.add(redirectHref);\n redirectState.redirects++;\n navigateWithRedirectState(\n redirectHref,\n {\n history: getRedirectHistoryMode(resolved.replace),\n },\n redirectState\n );\n return;\n }\n\n const matchedTargets = targets.filter((target) => target.resolved !== null);\n if (matchedTargets.length === 0) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${path}`);\n }\n return;\n }\n\n saveScrollPosition(currentHref);\n\n const historyMethod =\n getNavigationHistoryMode(options) === 'replace'\n ? 'replaceState'\n : 'pushState';\n window.history[historyMethod]({ path: href }, '', href);\n syncRegisteredRouteSnapshot();\n\n for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (resolved.kind === 'redirect') {\n continue;\n }\n\n if (pathname === target.app.pathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(target.app.instance, pathname, href);\n syncAppRegistrationLocation(target.app, pathname, href);\n continue;\n }\n\n remountResolvedRoute(\n target.app.instance,\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n },\n pathname,\n href\n );\n syncAppRegistrationLocation(target.app, pathname, href);\n }\n\n if (pathname !== previousPathname) {\n applyNavigationScroll(\n options.scroll ?? scrollRestorationOptions.navigation\n );\n }\n}\n\n/** Register the current app instance (called by createSPA/hydrateSPA). */\nexport function registerAppInstance(\n instance: ComponentInstance,\n path: string,\n source: AppNavigationSource = {}\n): void {\n const existingIndex = registeredApps.findIndex(\n (app) => app.instance === instance\n );\n const registration: AppRegistration = {\n instance,\n pathname: path,\n href: getWindowHref(),\n ...source,\n };\n if (existingIndex >= 0) {\n registeredApps[existingIndex] = registration;\n } else {\n registeredApps.push(registration);\n }\n\n currentInstance = instance;\n currentPathname = path;\n currentHref = getWindowHref();\n syncRegisteredRouteSnapshot();\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\nexport function unregisterAppInstance(instance: ComponentInstance): void {\n const existingIndex = registeredApps.findIndex(\n (app) => app.instance === instance\n );\n if (existingIndex >= 0) {\n registeredApps.splice(existingIndex, 1);\n }\n syncRegisteredRouteSnapshot();\n\n if (currentInstance !== instance) {\n return;\n }\n\n const nextApp =\n registeredApps.length > 0\n ? registeredApps[registeredApps.length - 1]!\n : null;\n currentInstance = nextApp?.instance ?? null;\n if (nextApp) {\n currentPathname = nextApp.pathname;\n currentHref = nextApp.href;\n syncRegisteredRouteSnapshot();\n return;\n }\n\n activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = null;\n currentPathname = '/';\n currentHref = '/';\n if (typeof window === 'undefined') {\n syncCurrentRouteSnapshot('/', '', '', []);\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 return;\n }\n\n const initialTarget = parseTargetUrl(path);\n navigateWithRedirectState(path, options, {\n redirects: 0,\n visited: new Set([\n `${initialTarget.pathname}${initialTarget.search}${initialTarget.hash}`,\n ]),\n });\n}\n\ntype NavigationRedirectState = {\n redirects: number;\n visited: Set<string>;\n};\n\nfunction navigateWithRedirectState(\n path: string,\n options: NavigateOptions,\n redirectState: NavigationRedirectState\n): void {\n if (typeof window === 'undefined') {\n // SSR context\n return;\n }\n\n const request = beginRouteRequest();\n\n const target = parseTargetUrl(path);\n const pathname = target.pathname;\n const href = `${target.pathname}${target.search}${target.hash}`;\n const resolvedTargets = resolveNavigationTargetsForApps(\n pathname,\n href,\n request.signal\n );\n\n if (isPromiseLike(resolvedTargets)) {\n void Promise.resolve(resolvedTargets).then(\n (targets) => {\n if (isStaleRouteRequest(request.id)) {\n return;\n }\n\n try {\n applyNavigationTargets(\n path,\n options,\n redirectState,\n pathname,\n href,\n targets\n );\n } catch (error) {\n logger.error('[Askr] navigation failed:', error);\n }\n },\n (error) => {\n logger.error('[Askr] navigation failed:', error);\n }\n );\n return;\n }\n\n applyNavigationTargets(\n path,\n options,\n redirectState,\n pathname,\n href,\n resolvedTargets\n );\n}\n\n/**\n * Handle browser back/forward buttons\n */\nfunction handlePopState(_event: PopStateEvent): void {\n const request = beginRouteRequest();\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 (registeredApps.length === 0) {\n return;\n }\n\n const applyResolved = (targets: AppNavigationTarget[]) => {\n if (isStaleRouteRequest(request.id)) {\n return;\n }\n\n const matchedTargets = targets.filter((target) => target.resolved !== null);\n if (matchedTargets.length === 0) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${pathname}`);\n }\n return;\n }\n\n for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (resolved.kind !== 'redirect') {\n continue;\n }\n\n navigate(resolved.to, {\n history: getRedirectHistoryMode(resolved.replace),\n });\n return;\n }\n\n syncRegisteredRouteSnapshot();\n\n for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (pathname === target.app.pathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(target.app.instance, pathname, href);\n syncAppRegistrationLocation(target.app, pathname, href);\n continue;\n }\n\n if (resolved.kind === 'redirect') {\n continue;\n }\n\n remountResolvedRoute(\n target.app.instance,\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n },\n pathname,\n href\n );\n syncAppRegistrationLocation(target.app, pathname, href);\n }\n\n applyHistoryScroll(href, _event.state);\n };\n\n const resolvedTargets = resolveNavigationTargetsForApps(\n pathname,\n href,\n request.signal\n );\n\n if (isPromiseLike<AppNavigationTarget[]>(resolvedTargets)) {\n void Promise.resolve(resolvedTargets).then(\n (next) => {\n try {\n applyResolved(next);\n } catch (error) {\n logger.error('[Askr] popstate navigation failed:', error);\n }\n },\n (error) => {\n logger.error('[Askr] popstate navigation failed:', error);\n }\n );\n return;\n }\n\n applyResolved(resolvedTargets);\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 activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = null;\n\n if (typeof window === 'undefined' || !navigationInitialized) {\n return;\n }\n\n navigationInitialized = false;\n window.removeEventListener('popstate', handlePopState);\n}\n"],"mappings":";;;;;;;;;;;;;AAsCA,IAAI,kBAA4C;AAChD,IAAI,kBAAkB;AACtB,IAAI,cAAc;AAClB,IAAI,wBAAwB;AAC5B,IAAI,uBAAuB;AAC3B,IAAI,+BAAuD;AAC3D,MAAM,2BAA2B;AAcjC,MAAM,iBAAoC,CAAC;AAE3C,SAAS,4BACP,UACA,OAAmC,gBACnC;CACA,MAAM,UAA0D,CAAC;CACjE,MAAM,4BAAY,IAAI,IAAY;CAElC,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,aAAa,4BAA4B,UAAU;GACvD,UAAU,IAAI;GACd,QAAQ,IAAI;EACd,CAAC;EAED,KAAK,MAAM,SAAS,YAAY;GAC9B,IAAI,UAAU,IAAI,MAAM,IAAI,GAC1B;GAEF,UAAU,IAAI,MAAM,IAAI;GACxB,QAAQ,KAAK,KAAK;EACpB;CACF;CAEA,OAAO;AACT;AAEA,SAAS,8BAAoC;CAC3C,IAAI,OAAO,WAAW,aACpB;CAGF,MA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QAAQ,GAAG;IAChE,sBAAsB,OAAO,IAAI,UAAU,UAAU,IAAI;IACzD,4BAA4B,OAAO,KAAK,UAAU,IAAI;IACtD;GACF;GAEA,IAAI,SAAS,SAAS,YACpB;GAGF,qBACE,OAAO,IAAI,UACX,SAAS,SAAS,SACd,0BAA0B,SAAS,MAAM,IACzC;IACE,SAAS,SAAS;IAClB,QAAQ,SAAS;GACnB,GACJ,UACA,IACF;GACA,4BAA4B,OAAO,KAAK,UAAU,IAAI;EACxD;EAEA,mBAAmB,MAAM,OAAO,KAAK;CACvC;CAEA,MAAM,kBAAkB,gCACtB,UACA,MACA,QAAQ,MACV;CAEA,IAAI,cAAqC,eAAe,GAAG;EACzD,AAAK,QAAQ,QAAQ,eAAe,EAAE,MACnC,SAAS;GACR,IAAI;IACF,cAAc,IAAI;GACpB,SAAS,OAAO;IACd,OAAO,MAAM,sCAAsC,KAAK;GAC1D;EACF,IACC,UAAU;GACT,OAAO,MAAM,sCAAsC,KAAK;EAC1D,CACF;EACA;CACF;CAEA,cAAc,eAAe;AAC/B;;;;AAKA,SAAgB,uBAA6B;CAC3C,IAAI,OAAO,WAAW,eAAe,uBACnC;CAGF,wBAAwB;CACxB,OAAO,iBAAiB,YAAY,cAAc;AACpD"}
|
package/dist/router/route.d.ts
CHANGED
|
@@ -10,6 +10,11 @@ type CompatibleRelativeRouteComponent<Path extends string, TComponent extends An
|
|
|
10
10
|
type CompatibleRouteComponent<Path extends string, TComponent extends AnyRouteComponent> = Path extends `/${string}` ? CompatibleAbsoluteRouteComponent<Path, TComponent> : CompatibleRelativeRouteComponent<Path, TComponent>;
|
|
11
11
|
type RouteOptionsForComponent<Path extends string, TComponent extends AnyRouteComponent> = Parameters<TComponent> extends [] ? RouteOptions<RoutePathParams<Path>> : RouteComponentParam<TComponent> extends RouteParams ? RouteOptions<RouteComponentParam<TComponent>> : RouteOptions<RoutePathParams<Path>>;
|
|
12
12
|
declare function setServerLocation(url: string | null): void;
|
|
13
|
+
declare function isRoutePathActive(pathOrPaths: string | readonly string[]): boolean;
|
|
14
|
+
declare function computeRouteActivityMatches(pathname: string, options?: {
|
|
15
|
+
manifest?: RouteManifest;
|
|
16
|
+
routes?: readonly Route[];
|
|
17
|
+
}): RouteMatch[];
|
|
13
18
|
declare function _setActiveRouteAuthOptions(auth: RouteAuthOptions | undefined): void;
|
|
14
19
|
/**
|
|
15
20
|
* Prevent route registrations after the app has started.
|
|
@@ -63,7 +68,7 @@ declare function index(Component: RouteComponent, options?: RouteOptions): void;
|
|
|
63
68
|
declare function fallback(Component: RouteComponent): void;
|
|
64
69
|
declare function registerRoutes(definition: RouteDefinition, options?: RegisterRoutesOptions): void;
|
|
65
70
|
declare function currentRoute<TParams extends RouteParams = RouteParams>(): RouteSnapshot<TParams>;
|
|
66
|
-
declare function syncCurrentRouteSnapshot(pathname: string, search: string, hash: string): void;
|
|
71
|
+
declare function syncCurrentRouteSnapshot(pathname: string, search: string, hash: string, activityMatches?: readonly RouteMatch[]): void;
|
|
67
72
|
/**
|
|
68
73
|
* Register a route.
|
|
69
74
|
*
|
|
@@ -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":";;;;;KA6GK,iBAAA,OAAwB,IAAA,YAAgB,eAAe;AAAA,KAEvD,mBAAA,oBAAuC,iBAAA,IAC1C,UAAA,CAAW,UAAA,yBAAmC,UAAA,CAAW,UAAA;AAAA,KAEtD,gCAAA,yCAEgB,iBAAA,IAEnB,UAAA,CAAW,UAAA,eACP,UAAA,GACA,eAAA,CAAgB,IAAA,UAAc,mBAAA,CAAoB,UAAA,IAChD,UAAA;AAAA,KAGH,gCAAA,yCAEgB,iBAAA,IAEnB,UAAA,CAAW,UAAA,eACP,UAAA,GACA,mBAAA,CAAoB,UAAA,UAAoB,MAAA,OAC9B,eAAA,CAAgB,IAAA,aAGxB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a,QAAA,WAAmB,aAAa;AAAA,iBAwJ7C,mBAAA,CACd,MAAA,UACA,OAAA,GAAS,mBAAA,GACR,kBAAA,GAAqB,OAAA,CAAQ,kBAAA;;;;;;;;AAzrDS;AAsIzC;;;;AAAoD;AA6DpD;iBA0jDgB,sBAAA,CACd,QAAA,UACA,SAAA,WAAoB,KAAA,KACnB,aAAa"}
|
package/dist/router/route.js
CHANGED
|
@@ -4,11 +4,12 @@ import { markReactivePropsDirtySource, markReadableDerivedSubscribersDirty, noti
|
|
|
4
4
|
import { isPromiseLike } from "../common/promise.js";
|
|
5
5
|
import { getCurrentComponentInstance } from "../runtime/component.js";
|
|
6
6
|
import { ROUTE_ROOT_COMPONENT } from "../common/router-internal.js";
|
|
7
|
-
import { computeRank, matchSegments, parseSegments, splitPathSegments } from "./match.js";
|
|
7
|
+
import { computeRank, matchSegments, normalizeRouteSegmentName, parseSegments, splitPathSegments } from "./match.js";
|
|
8
8
|
import { requireAuth, requireGuest, requirePermission, requireRole } from "./policy.js";
|
|
9
9
|
import { buildRouteContext, buildRouteContextBase, deepFreeze, makeQuery, parseLocation } from "./route-context.js";
|
|
10
10
|
import { getExecutionModel } from "../runtime/execution-model.js";
|
|
11
11
|
import { getRenderContext } from "../ssr/context.js";
|
|
12
|
+
import { syncRouteActivitySnapshot } from "../common/route-activity.js";
|
|
12
13
|
//#region src/router/route.ts
|
|
13
14
|
/**
|
|
14
15
|
* Route definition, registration, and matching.
|
|
@@ -86,6 +87,12 @@ currentRouteSource._readers = /* @__PURE__ */ new Map();
|
|
|
86
87
|
let serverLocation = null;
|
|
87
88
|
function setServerLocation(url) {
|
|
88
89
|
serverLocation = url;
|
|
90
|
+
if (url) {
|
|
91
|
+
const parsed = parseLocation(url);
|
|
92
|
+
syncRouteActivitySnapshot(parsed.pathname, computeMatchesFromRoutes(parsed.pathname, getActiveRoutes()));
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
syncRouteActivitySnapshot(currentRouteSnapshot.path, currentRouteSnapshot.matches);
|
|
89
96
|
}
|
|
90
97
|
function buildRouteSnapshot(pathname, search, hash) {
|
|
91
98
|
const query = makeQuery(search);
|
|
@@ -98,8 +105,9 @@ function buildRouteSnapshot(pathname, search, hash) {
|
|
|
98
105
|
matches: Object.freeze(matches)
|
|
99
106
|
});
|
|
100
107
|
}
|
|
101
|
-
function setCurrentRouteSnapshot(pathname, search, hash) {
|
|
108
|
+
function setCurrentRouteSnapshot(pathname, search, hash, activityMatches) {
|
|
102
109
|
currentRouteSnapshot = buildRouteSnapshot(pathname, search, hash);
|
|
110
|
+
syncRouteActivitySnapshot(pathname, activityMatches ?? currentRouteSnapshot.matches);
|
|
103
111
|
const instance = getCurrentComponentInstance();
|
|
104
112
|
markReadableDerivedSubscribersDirty(currentRouteSource);
|
|
105
113
|
markReactivePropsDirtySource(currentRouteSource);
|
|
@@ -126,6 +134,20 @@ function computeMatchesFromRoutes(pathname, routesList) {
|
|
|
126
134
|
namespace: "route" in bestMatch ? bestMatch.route.namespace : bestMatch.record.options.namespace
|
|
127
135
|
}];
|
|
128
136
|
}
|
|
137
|
+
function computeMatchesFromRouteRecords(pathname, routeRecords) {
|
|
138
|
+
const bestMatch = getMatchingRecord(pathname, routeRecords);
|
|
139
|
+
if (!bestMatch) return [];
|
|
140
|
+
return [{
|
|
141
|
+
path: bestMatch.record.path,
|
|
142
|
+
params: deepFreeze({ ...bestMatch.params }),
|
|
143
|
+
namespace: bestMatch.record.options.namespace
|
|
144
|
+
}];
|
|
145
|
+
}
|
|
146
|
+
function computeRouteActivityMatches(pathname, options = {}) {
|
|
147
|
+
if (options.routes) return computeMatchesFromRoutes(pathname, options.routes);
|
|
148
|
+
if (options.manifest) return computeMatchesFromRouteRecords(pathname, options.manifest.records);
|
|
149
|
+
return computeMatchesFromRoutes(pathname, getActiveRoutes());
|
|
150
|
+
}
|
|
129
151
|
function findBestResolvedRouteFromRoutes(pathname, routeList) {
|
|
130
152
|
const normalized = pathname.endsWith("/") && pathname !== "/" ? pathname.slice(0, -1) : pathname;
|
|
131
153
|
const urlParts = splitPathSegments(normalized);
|
|
@@ -234,14 +256,19 @@ function validateRoutePath(path) {
|
|
|
234
256
|
}
|
|
235
257
|
const segments = path.split("/").filter(Boolean);
|
|
236
258
|
const seenParamNames = /* @__PURE__ */ new Set();
|
|
237
|
-
for (
|
|
259
|
+
for (let index = 0; index < segments.length; index++) {
|
|
260
|
+
const segment = segments[index];
|
|
238
261
|
if (segment === "*") continue;
|
|
239
262
|
const hasOpenBrace = segment.includes("{");
|
|
240
263
|
const hasCloseBrace = segment.includes("}");
|
|
241
264
|
if (!hasOpenBrace && !hasCloseBrace) continue;
|
|
242
265
|
if (!(segment.startsWith("{") && segment.endsWith("}"))) throw new Error("Route parameter segments must use complete {name} interpolation.");
|
|
243
|
-
const
|
|
244
|
-
|
|
266
|
+
const rawParamName = normalizeRouteSegmentName(segment.slice(1, -1));
|
|
267
|
+
const isSplat = rawParamName.startsWith("*");
|
|
268
|
+
const paramName = isSplat ? normalizeRouteSegmentName(rawParamName.slice(1)) : rawParamName;
|
|
269
|
+
if (!paramName) throw new Error(isSplat ? "Route splat parameter name cannot be empty." : "Route parameter name cannot be empty.");
|
|
270
|
+
if (isSplat && paramName === "*") throw new Error("Route named splat parameter name cannot be \"*\".");
|
|
271
|
+
if (isSplat && index !== segments.length - 1) throw new Error("Route named splat parameters must be the final segment.");
|
|
245
272
|
if (seenParamNames.has(paramName)) throw new Error(`Route path cannot reuse duplicate parameter name "${paramName}".`);
|
|
246
273
|
seenParamNames.add(paramName);
|
|
247
274
|
}
|
|
@@ -597,8 +624,8 @@ function currentRoute() {
|
|
|
597
624
|
recordReadableRead(currentRouteSource);
|
|
598
625
|
return readCurrentRouteSnapshot();
|
|
599
626
|
}
|
|
600
|
-
function syncCurrentRouteSnapshot(pathname, search, hash) {
|
|
601
|
-
setCurrentRouteSnapshot(pathname, search, hash);
|
|
627
|
+
function syncCurrentRouteSnapshot(pathname, search, hash, activityMatches) {
|
|
628
|
+
setCurrentRouteSnapshot(pathname, search, hash, activityMatches);
|
|
602
629
|
}
|
|
603
630
|
function route(path, Component, options) {
|
|
604
631
|
if (typeof path === "undefined") throw new Error("route() is only for route registration. Use currentRoute() inside components.");
|
|
@@ -819,6 +846,6 @@ function resolveRouteFromRoutes(pathname, routeList) {
|
|
|
819
846
|
} : null;
|
|
820
847
|
}
|
|
821
848
|
//#endregion
|
|
822
|
-
export { Outlet, _applyManifest, _drainLazy, _setActiveRouteAuthOptions, _snapshotLazy, clearRoutes, currentRoute, fallback, getManifest, getRoutes, group, index, lazy, lockRouteRegistration, page, registerRoutes, resolveRouteFromRoutes, resolveRouteRequest, route, setServerLocation, syncCurrentRouteSnapshot };
|
|
849
|
+
export { Outlet, _applyManifest, _drainLazy, _setActiveRouteAuthOptions, _snapshotLazy, clearRoutes, computeRouteActivityMatches, currentRoute, fallback, getManifest, getRoutes, group, index, lazy, lockRouteRegistration, page, registerRoutes, resolveRouteFromRoutes, resolveRouteRequest, route, setServerLocation, syncCurrentRouteSnapshot };
|
|
823
850
|
|
|
824
851
|
//# sourceMappingURL=route.js.map
|