Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 438x 2x 2x 438x 1x 1x 438x 1x 1x 438x 1x 1x 438x 6250x 6250x 64x 64x 64x 64x 64x 64x 64x 64x 6250x 6250x 438x 438x 438x 438x 3367x 3367x 438x 691x 691x 438x 355x 355x 438x 33x 33x 438x 353x 353x 438x 739x 739x 438x 359x 359x 438x 353x 353x 438x 438x 438x 438x 438x 438x 261x 261x 261x 261x 261x 3x 3x 258x 261x 253x 261x 3x 3x 2x 2x 258x 261x 438x 3367x 3007x 3007x 3367x 3367x 438x 350x 349x 349x 350x 348x 348x 348x 346x 350x 350x 350x 350x 350x 350x 350x 304x 304x 346x 346x 346x 346x 346x 350x 350x 3x 3x 350x 383x 383x 383x 383x 350x 383x 383x 350x 438x 7x 12x 12x 7x 7x 7x 7x 438x 10x 9x 9x 10x 10x 9x 9x 9x 9x 9x 9x 10x 14x 14x 10x 438x 1x 145x 145x | import { anchor, mutable } from '@anchorlib/core';
import { URLCache } from './cache.js';
import { DYNAMIC_ROUTE_KEY, inheritConfig, WILDCARD_ROUTE_KEY } from './constant.js';
import { RENDER_MODE, ROUTE_TYPE } from './enum.js';
import { Redirect } from './redirect.js';
import { RouteRegistry } from './registry.js';
import { Route } from './route.js';
import { getStore } from './store.js';
import type {
ExtractParams,
ExtractQueryParams,
GuardBlocker,
MatchResult,
None,
ProviderContext,
RouteOptions,
RoutePath,
RouterOptions,
RouterStorage,
TRec,
UnknownRoute,
} from './types.js';
/**
* A type-safe router for managing routes and navigation.
*
* Supports nested routes, guards, data providers, and caching.
* Routes can be activated, deactivated, and preloaded.
*
* @example
* ```ts
* const router = new Router({ baseUrl: 'https://example.com' });
*
* const usersRoute = router.route('/users');
* const userRoute = usersRoute.route('/:id');
*
* await router.activate('/users/123');
* ```
*/
// biome-ignore lint/suspicious/noExplicitAny: Expect any.
export class Router<Output = any> {
public get path() {
return this.activeRoute?.path;
}
public get data() {
return this.activeContext.data;
}
public get query() {
return this.activeContext.query;
}
public get params() {
return this.activeContext.params;
}
private get storage(): RouterStorage {
const store = getStore();
if (!store.has(this)) {
store.set(this, {
cache: new URLCache(this.rootRegistry, this.options.cacheSize),
activeUrl: undefined,
activeRoute: undefined,
activeContext: mutable({ data: {}, query: {}, params: {} }),
activeSegments: undefined,
});
}
return store.get(this) as RouterStorage;
}
public readonly options: RouterOptions;
public readonly rootRoute: UnknownRoute;
public readonly rootRegistry: RouteRegistry;
private get cache() {
return this.storage.cache;
}
private get activeUrl() {
return this.storage.activeUrl;
}
private set activeUrl(activeUrl) {
this.storage.activeUrl = activeUrl;
}
/** The currently active route */
public get activeRoute() {
return this.storage.activeRoute;
}
private set activeRoute(activeRoute) {
this.storage.activeRoute = activeRoute;
}
/** The active context shared across all routes */
public get activeContext() {
return this.storage.activeContext;
}
/** The currently active route segments */
public get activeSegments() {
return this.storage.activeSegments;
}
private set activeSegments(activeSegments) {
this.storage.activeSegments = activeSegments;
}
/**
* Creates a new Router instance.
*
* @param options - Optional router configuration
*
* @example
* ```ts
* const router = new Router({
* baseUrl: 'https://example.com',
* cacheSize: 100,
* maxAge: 60000
* });
* ```
*/
constructor(options?: RouterOptions) {
this.options = inheritConfig(options);
this.rootRoute = new Route(this, '/', this.options);
this.rootRegistry = new RouteRegistry(this.rootRoute);
}
/**
* Creates a new route.
*
* If path is '/', creates an index route and returns the root route.
* Otherwise, creates a new child route and returns it.
*
* @template TPath - The route path type
* @template TParams - The route parameters type
* @template TQueryParams - The query parameters type
* @template TOptions - The route options type
* @template TData - The route data type
* @param path - The route path
* @param options - Optional route options
* @returns The created route
*
* @example
* ```ts
* const usersRoute = router.route('/users');
* const userRoute = usersRoute.route('/:id');
* const indexRoute = router.route('/');
* ```
*/
public route<
TPath extends RoutePath,
TParams extends ExtractParams<TPath>,
TQueryParams extends ExtractQueryParams<TPath>,
TOptions extends RouteOptions,
TData,
>(
path: TPath,
options?: TOptions
): Route<TPath, TParams, TQueryParams, RouteOptions & TOptions, TData, never, Output> {
const route = new Route(this, path, options);
if (path === ('/' as TPath)) {
return this.rootRoute as never;
}
const routeMap = new RouteRegistry(route as never as UnknownRoute);
if (route.type === ROUTE_TYPE.STATIC) {
this.rootRegistry.set(route.name, routeMap);
} else if (route.type === ROUTE_TYPE.DYNAMIC) {
this.rootRegistry.set(DYNAMIC_ROUTE_KEY, routeMap);
} else if (route.type === ROUTE_TYPE.WILDCARD) {
this.rootRegistry.set(WILDCARD_ROUTE_KEY, routeMap);
}
return route as Route<TPath, TParams, TQueryParams, TOptions, TData>;
}
/**
* Finds a route matching the given URL.
*
* Uses the URL cache for performance.
*
* @param url - The URL to match (string or URL object)
* @returns The match result, or undefined if no match
*
* @example
* ```ts
* const match = router.find('/users/123');
* if (match) {
* console.log(match.route, match.params);
* }
* ```
*/
public find(url: string | URL): MatchResult | void {
if (typeof url === 'string') {
url = new URL(url, this.options.baseUrl);
}
return this.cache.get(url);
}
/**
* Activates a route by URL.
*
* Preloads all route segments, deactivates old segments,
* and activates new segments. Handles race conditions by
* checking if the URL is still active after preloading.
*
* @param url - The URL to activate (string or URL object)
* @returns A GuardBlocker if navigation was blocked, otherwise void
*
* @example
* ```ts
* const blocker = await router.activate('/users/123');
* if (blocker) {
* console.log('Navigation blocked:', blocker);
* }
* ```
*/
public async activate(url: string | URL): Promise<void | GuardBlocker> {
if (typeof url === 'string') {
url = new URL(url, url.startsWith('http') ? undefined : this.options.baseUrl);
}
if (this.activeUrl === url.href) return;
// Set active URL synchronously - prevents race condition
this.activeUrl = url.href;
const match = this.find(url);
if (!match) return;
const { segments, context } = match;
const currentSegments = this.activeSegments || [];
const targetSegments = segments;
// Update the active context reference to point to this URL's context
anchor.assign(this.activeContext, context);
// Update router state
this.activeRoute = match.route;
this.activeSegments = targetSegments;
// Deactivate segments not in target (leaf to root)
const toDeactivate = currentSegments.filter((r) => !targetSegments.includes(r));
for (const route of toDeactivate.reverse()) {
route.deactivate();
}
// Activate new segments (root to leaf) without preloading
const toActivate = targetSegments.filter((r) => !currentSegments.includes(r));
// Authenticate target segments.
const blockers = await Promise.all(
toActivate.map((r) => r.authenticate(context as ProviderContext<None, None, TRec>))
);
const blocker = blockers.find((b) => b instanceof Error || b instanceof Redirect);
if (blocker) return blocker;
// Check if still active after authentication (guards).
if (this.activeUrl !== url.href) {
return; // Newer navigation started, abort
}
// Activate immediate segments.
for (const route of toActivate) {
if (route.options.renderMode === RENDER_MODE.IMMEDIATE) {
route.active = true;
}
}
// Activate target segments.
for (const route of toActivate) {
await route.activate(this.activeContext as ProviderContext<None, None, TRec>);
}
}
/**
* Deactivates all currently active routes.
*
* Clears all active segments and resets router state.
*
* @example
* ```ts
* router.deactivate();
* ```
*/
public deactivate(): void {
for (const route of [...(this.activeSegments || [])].reverse()) {
route.deactivate();
}
this.activeUrl = undefined;
this.activeRoute = undefined;
this.activeSegments = undefined;
}
/**
* Preloads a route without activating it.
*
* Useful for prefetching routes before navigation.
*
* @param url - The URL to preload (string or URL object)
*
* @example
* ```ts
* await router.preload('/users/123');
* // Route data is now cached
* ```
*/
public async preload(url: string | URL): Promise<void> {
if (typeof url === 'string') {
url = new URL(url, this.options.baseUrl);
}
const match = this.find(url);
if (!match) return;
const { segments, context } = match;
const blockers = await Promise.all(
segments.map((r) => r.authenticate(context as ProviderContext<None, None, TRec>))
);
const blocker = blockers.find((b) => b instanceof Error || b instanceof Redirect);
if (blocker) return;
// Preload all segments without activating them
for (const route of segments) {
await route.preload(context as ProviderContext<None, None, TRec>);
}
}
}
/**
* Creates a new Router instance.
*
* Convenience function for creating a router with optional options.
*
* @param options - Optional router configuration
* @returns A new Router instance
*
* @example
* ```ts
* const router = createRouter({ baseUrl: 'https://example.com' });
* ```
*/
export function createRouter<Output>(options?: RouterOptions): Router<Output> {
return new Router(options);
}
|