slicejs-web-framework 3.3.6 → 3.3.8

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.
@@ -1,752 +1,775 @@
1
- /**
2
- * @typedef {Object} RouteConfig
3
- * @property {string} path
4
- * @property {string} component
5
- * @property {RouteConfig[]} [children]
6
- * @property {Object} [metadata]
7
- * @property {string} [fullPath]
8
- * @property {string|null} [parentPath]
9
- * @property {RouteConfig|null} [parentRoute]
10
- */
11
-
12
- /**
13
- * @typedef {Object} RouteInfo
14
- * @property {string} path
15
- * @property {string} component
16
- * @property {Object} params
17
- * @property {Object} query
18
- * @property {Object} metadata
19
- */
20
-
21
- /**
22
- * @typedef {Object} GuardRedirect
23
- * @property {string} path
24
- * @property {boolean} [replace]
25
- */
26
-
27
- /**
28
- * @typedef {Object} RouteMatch
29
- * @property {RouteConfig|null} route
30
- * @property {Object} params
31
- * @property {RouteConfig} [childRoute]
32
- */
33
-
34
- /**
35
- * @callback RouterNext
36
- * @param {void|false|string|{ path: string, replace?: boolean }} [arg]
37
- * @returns {void}
38
- */
39
-
40
- export default class Router {
41
- /**
42
- * @param {RouteConfig[]} routes
43
- */
44
- constructor(routes) {
45
- this.routes = routes;
46
- this.activeRoute = null;
47
- this.pathToRouteMap = this.createPathToRouteMap(routes);
48
-
49
- // Navigation Guards
50
- this._beforeEachGuard = null;
51
- this._afterEachGuard = null;
52
-
53
- // Router state
54
- this._started = false;
55
- this._autoStartTimeout = null;
56
-
57
- // Sistema de caché optimizado
58
- this.routeContainersCache = new Map();
59
- this.lastCacheUpdate = 0;
60
- this.CACHE_DURATION = 100; // ms - caché muy corto pero efectivo
61
-
62
- // Observer para invalidar caché automáticamente
63
- this.setupMutationObserver();
64
- }
65
-
66
- /**
67
- * Inicializa el router
68
- * Si el usuario no llama start() manualmente, se auto-inicia despues de un delay
69
- * @returns {void}
70
- */
71
- init() {
72
- window.addEventListener('popstate', this.onRouteChange.bind(this));
73
-
74
- // Auto-start después de 50ms si el usuario no llama start() manualmente
75
- // Esto da tiempo para que el usuario configure guards si lo necesita
76
- this._autoStartTimeout = setTimeout(async () => {
77
- if (!this._started) {
78
- slice.logger.logInfo('Router', 'Auto-starting router (no manual start() called)');
79
- await this.start();
80
- }
81
- }, 50);
82
- }
83
-
84
- /**
85
- * Inicia el router y carga la ruta inicial
86
- * OPCIONAL: Solo necesario si usas guards (beforeEach/afterEach)
87
- * Si no lo llamas, el router se auto-inicia despues de 50ms
88
- * @returns {Promise<void>}
89
- */
90
- async start() {
91
- // Prevenir múltiples llamadas
92
- if (this._started) {
93
- slice.logger.logWarning('Router', 'start() already called');
94
- return;
95
- }
96
-
97
- // Cancelar auto-start si existe
98
- if (this._autoStartTimeout) {
99
- clearTimeout(this._autoStartTimeout);
100
- this._autoStartTimeout = null;
101
- }
102
-
103
- this._started = true;
104
- await this.loadInitialRoute();
105
- }
106
-
107
- // ============================================
108
- // NAVIGATION GUARDS API
109
- // ============================================
110
-
111
- /**
112
- * Registra un guard que se ejecuta ANTES de cada navegacion.
113
- * Puede bloquear o redirigir la navegacion mediante next().
114
- * @param {(to: RouteInfo, from: RouteInfo, next: RouterNext) => void|Promise<void>} guard
115
- * @returns {void}
116
- */
117
- beforeEach(guard) {
118
- if (typeof guard !== 'function') {
119
- slice.logger.logError('Router', 'beforeEach expects a function');
120
- return;
121
- }
122
- this._beforeEachGuard = guard;
123
- }
124
-
125
- /**
126
- * Registra un guard que se ejecuta DESPUES de cada navegacion.
127
- * No puede bloquear la navegacion.
128
- * @param {(to: RouteInfo, from: RouteInfo) => void} guard
129
- * @returns {void}
130
- */
131
- afterEach(guard) {
132
- if (typeof guard !== 'function') {
133
- slice.logger.logError('Router', 'afterEach expects a function');
134
- return;
135
- }
136
- this._afterEachGuard = guard;
137
- }
138
-
139
- /**
140
- * Crea un objeto con información de ruta para los guards
141
- * @param {Object} route - Objeto de ruta
142
- * @param {Object} params - Parámetros de la ruta
143
- * @param {String} requestedPath - Path original solicitado
144
- * @returns {Object} Objeto con path, component, params, query, metadata
145
- */
146
- /**
147
- * Build route info used by guards and events.
148
- * @param {RouteConfig|null} route
149
- * @param {Object} [params]
150
- * @param {string|null} [requestedPath]
151
- * @returns {RouteInfo}
152
- */
153
- _createRouteInfo(route, params = {}, requestedPath = null) {
154
- if (!route) {
155
- return {
156
- path: requestedPath || '/404',
157
- component: 'NotFound',
158
- params: {},
159
- query: this._parseQueryParams(),
160
- metadata: {},
161
- };
162
- }
163
-
164
- return {
165
- path: requestedPath || route.fullPath || route.path,
166
- component: route.parentRoute ? route.parentRoute.component : route.component,
167
- params: params,
168
- query: this._parseQueryParams(),
169
- metadata: route.metadata || {},
170
- };
171
- }
172
-
173
- /**
174
- * Parsea los query parameters de la URL actual
175
- * @returns {Object} Objeto con los query params
176
- */
177
- /**
178
- * Parse query params from current URL.
179
- * @returns {Object}
180
- */
181
- _parseQueryParams() {
182
- const queryString = window.location.search;
183
- if (!queryString) return {};
184
-
185
- const params = {};
186
- const urlParams = new URLSearchParams(queryString);
187
-
188
- for (const [key, value] of urlParams) {
189
- params[key] = value;
190
- }
191
-
192
- return params;
193
- }
194
-
195
- /**
196
- * Ejecuta el beforeEach guard si existe
197
- * @param {Object} to - Información de ruta destino
198
- * @param {Object} from - Información de ruta origen
199
- * @returns {Object|null} Objeto con redirectPath y options, o null si continúa
200
- */
201
- /**
202
- * Execute beforeEach guard if defined.
203
- * @param {RouteInfo} to
204
- * @param {RouteInfo} from
205
- * @returns {Promise<{ path: string|false, options: { replace?: boolean } }|null>}
206
- */
207
- async _executeBeforeEachGuard(to, from) {
208
- if (!this._beforeEachGuard) {
209
- return null;
210
- }
211
-
212
- let redirectPath = null;
213
- let redirectOptions = {};
214
- let nextCalled = false;
215
-
216
- const next = (arg) => {
217
- if (nextCalled) {
218
- slice.logger.logWarning('Router', 'next() called multiple times in guard');
219
- return;
220
- }
221
- nextCalled = true;
222
-
223
- // Caso 1: Sin argumentos - continuar navegación
224
- if (arg === undefined) {
225
- return;
226
- }
227
-
228
- // Caso 2: false - cancelar navegación
229
- if (arg === false) {
230
- redirectPath = false;
231
- return;
232
- }
233
-
234
- // Caso 3: String - redirección simple (backward compatibility)
235
- if (typeof arg === 'string') {
236
- redirectPath = arg;
237
- redirectOptions = { replace: false };
238
- return;
239
- }
240
-
241
- // Caso 4: Objeto - redirección con opciones
242
- if (typeof arg === 'object' && arg.path) {
243
- redirectPath = arg.path;
244
- redirectOptions = {
245
- replace: arg.replace || false,
246
- };
247
- return;
248
- }
249
-
250
- // Argumento inválido
251
- slice.logger.logError(
252
- 'Router',
253
- 'Invalid argument passed to next(). Expected string, object with path, false, or undefined.'
254
- );
255
- };
256
-
257
- try {
258
- await this._beforeEachGuard(to, from, next);
259
-
260
- // Si no se llamó next(), loguear advertencia pero continuar
261
- if (!nextCalled) {
262
- slice.logger.logWarning('Router', 'beforeEach guard did not call next(). Navigation will continue.');
263
- }
264
-
265
- // Retornar tanto el path como las opciones
266
- return redirectPath ? { path: redirectPath, options: redirectOptions } : null;
267
- } catch (error) {
268
- slice.logger.logError('Router', 'Error in beforeEach guard', error);
269
- return null; // En caso de error, continuar con la navegación
270
- }
271
- }
272
-
273
- /**
274
- * Ejecuta el afterEach guard si existe
275
- * @param {Object} to - Información de ruta destino
276
- * @param {Object} from - Información de ruta origen
277
- */
278
- /**
279
- * Execute afterEach guard if defined.
280
- * @param {RouteInfo} to
281
- * @param {RouteInfo} from
282
- * @returns {void}
283
- */
284
- _executeAfterEachGuard(to, from) {
285
- if (!this._afterEachGuard) {
286
- return;
287
- }
288
-
289
- try {
290
- this._afterEachGuard(to, from);
291
- } catch (error) {
292
- slice.logger.logError('Router', 'Error in afterEach guard', error);
293
- }
294
- }
295
-
296
- // ============================================
297
- // ROUTING CORE (MODIFICADO CON GUARDS)
298
- // ============================================
299
-
300
- /**
301
- * Navigate to a route path (guards run automatically).
302
- * @param {string} path
303
- * @param {{ replace?: boolean }} [options] - `{ replace: true }` replaces history instead of pushing.
304
- * @returns {Promise<void>}
305
- */
306
- async navigate(path, options = {}, legacyOptions) {
307
- // Backward compatibility with the previous signature navigate(path, _redirectChain, _options):
308
- // if the 2nd argument is the internal redirect chain (an array) or a 3rd argument is passed,
309
- // use the 3rd argument as the options object.
310
- if (Array.isArray(options)) {
311
- options = legacyOptions || {};
312
- } else if (legacyOptions !== undefined) {
313
- options = legacyOptions || options;
314
- }
315
- return this._navigateWithGuards(path, options || {}, []);
316
- }
317
-
318
- /**
319
- * Internal navigation that tracks the guard redirection chain (loop protection).
320
- * @param {string} path
321
- * @param {{ replace?: boolean }} options
322
- * @param {string[]} redirectChain
323
- * @returns {Promise<void>}
324
- */
325
- async _navigateWithGuards(path, options, redirectChain) {
326
- const currentPath = window.location.pathname;
327
-
328
- // Detectar loops infinitos: si ya visitamos esta ruta en la cadena de redirecciones
329
- if (redirectChain.includes(path)) {
330
- slice.logger.logError('Router', `Guard redirection loop detected: ${redirectChain.join(' → ')} → ${path}`);
331
- return;
332
- }
333
-
334
- // Límite de seguridad: máximo 10 redirecciones
335
- if (redirectChain.length >= 10) {
336
- slice.logger.logError('Router', `Too many redirections: ${redirectChain.join(' → ')} → ${path}`);
337
- return;
338
- }
339
-
340
- // Obtener información de ruta actual
341
- const { route: fromRoute, params: fromParams } = this.matchRoute(currentPath);
342
- const from = this._createRouteInfo(fromRoute, fromParams, currentPath);
343
-
344
- // Obtener información de ruta destino
345
- const { route: toRoute, params: toParams } = this.matchRoute(path);
346
- const to = this._createRouteInfo(toRoute, toParams, path);
347
-
348
- // EJECUTAR BEFORE EACH GUARD
349
- const guardResult = await this._executeBeforeEachGuard(to, from);
350
-
351
- // Si el guard redirige
352
- if (guardResult && guardResult.path) {
353
- return this._navigateWithGuards(guardResult.path, guardResult.options || {}, [...redirectChain, path]);
354
- }
355
-
356
- // Si el guard cancela la navegación (next(false))
357
- if (guardResult && guardResult.path === false) {
358
- slice.logger.logInfo('Router', 'Navigation cancelled by guard');
359
- return;
360
- }
361
-
362
- // No hay redirección - continuar con la navegación normal
363
- // Usar replace o push según las opciones
364
- if (options.replace) {
365
- window.history.replaceState({}, path, window.location.origin + path);
366
- } else {
367
- window.history.pushState({}, path, window.location.origin + path);
368
- }
369
-
370
- await this._performNavigation(to, from);
371
- }
372
-
373
- /**
374
- * Método interno para ejecutar la navegación después de pasar los guards
375
- * @param {Object} to - Información de ruta destino
376
- * @param {Object} from - Información de ruta origen
377
- */
378
- /**
379
- * Perform navigation after guards.
380
- * @param {RouteInfo} to
381
- * @param {RouteInfo} from
382
- * @returns {Promise<void>}
383
- */
384
- async _performNavigation(to, from) {
385
- // Renderizar la nueva ruta
386
- await this.onRouteChange();
387
-
388
- // EJECUTAR AFTER EACH GUARD
389
- this._executeAfterEachGuard(to, from);
390
-
391
- // Emitir evento de cambio de ruta
392
- this._emitRouteChange(to, from);
393
- }
394
-
395
- /**
396
- * React to URL changes and render routes.
397
- * @returns {Promise<void>}
398
- */
399
- async onRouteChange() {
400
- // Cancelar el timeout anterior si existe
401
- if (this.routeChangeTimeout) {
402
- clearTimeout(this.routeChangeTimeout);
403
- }
404
-
405
- // Debounce de 10ms para evitar múltiples llamadas seguidas
406
- this.routeChangeTimeout = setTimeout(async () => {
407
- const path = window.location.pathname;
408
- const routeContainersFlag = await this.renderRoutesComponentsInPage();
409
-
410
- if (routeContainersFlag) {
411
- return;
412
- }
413
-
414
- const { route, params } = this.matchRoute(path);
415
- if (route) {
416
- await this.handleRoute(route, params);
417
- }
418
- }, 10);
419
- }
420
-
421
- /**
422
- * Build or update the active route component.
423
- * @param {RouteConfig} route
424
- * @param {Object} params
425
- * @returns {Promise<void>}
426
- */
427
- async handleRoute(route, params) {
428
- const targetElement = document.querySelector('#app');
429
-
430
- const componentName = route.parentRoute ? route.parentRoute.component : route.component;
431
- const sliceId = `route-${componentName}`;
432
-
433
- const existingComponent = slice.controller.getComponent(sliceId);
434
-
435
- if (slice.loading) {
436
- slice.loading.start();
437
- }
438
-
439
- try {
440
- if (existingComponent) {
441
- targetElement.innerHTML = '';
442
- if (existingComponent.update) {
443
- existingComponent.props = { ...existingComponent.props, ...params };
444
- await existingComponent.update();
445
- }
446
- targetElement.appendChild(existingComponent);
447
- await this.renderRoutesInComponent(existingComponent);
448
- } else {
449
- const component = await slice.build(componentName, {
450
- params,
451
- sliceId: sliceId,
452
- });
453
-
454
- targetElement.innerHTML = '';
455
- targetElement.appendChild(component);
456
-
457
- await this.renderRoutesInComponent(component);
458
- }
459
-
460
- // Invalidar caché después de cambios importantes en el DOM
461
- this.invalidateCache();
462
- slice.router.activeRoute = route;
463
- } finally {
464
- if (slice.loading) {
465
- slice.loading.stop();
466
- }
467
- }
468
- }
469
-
470
- /**
471
- * Load initial route and run guards.
472
- * @returns {Promise<void>}
473
- */
474
- async loadInitialRoute() {
475
- const path = window.location.pathname;
476
- const { route, params } = this.matchRoute(path);
477
-
478
- // Para la carga inicial, también ejecutar guards
479
- const from = this._createRouteInfo(null, {}, null);
480
- const to = this._createRouteInfo(route, params, path);
481
-
482
- // EJECUTAR BEFORE EACH GUARD en carga inicial
483
- const guardResult = await this._executeBeforeEachGuard(to, from);
484
-
485
- if (guardResult && guardResult.path) {
486
- return this.navigate(guardResult.path, guardResult.options || {});
487
- }
488
-
489
- // Si el guard cancela la navegación inicial (caso raro pero posible)
490
- if (guardResult && guardResult.path === false) {
491
- slice.logger.logWarning('Router', 'Initial route navigation cancelled by guard');
492
- return;
493
- }
494
-
495
- await this.handleRoute(route, params);
496
-
497
- // EJECUTAR AFTER EACH GUARD en carga inicial
498
- this._executeAfterEachGuard(to, from);
499
-
500
- // Emitir evento de cambio de ruta
501
- this._emitRouteChange(to, from);
502
- }
503
-
504
- /**
505
- * Emitir evento de cambio de ruta
506
- * @param {Object} to
507
- * @param {Object} from
508
- */
509
- /**
510
- * Emit route change event.
511
- * @param {RouteInfo} to
512
- * @param {RouteInfo} from
513
- * @returns {void}
514
- */
515
- _emitRouteChange(to, from) {
516
- const payload = { to, from };
517
-
518
- if (slice.eventsConfig?.enabled && slice.events && typeof slice.events.emit === 'function') {
519
- slice.events.emit('router:change', payload);
520
- return;
521
- }
522
-
523
- window.dispatchEvent(new CustomEvent('router:change', { detail: payload }));
524
- }
525
-
526
- // ============================================
527
- // MÉTODOS EXISTENTES (SIN CAMBIOS)
528
- // ============================================
529
-
530
- setupMutationObserver() {
531
- if (typeof MutationObserver !== 'undefined') {
532
- this.observer = new MutationObserver((mutations) => {
533
- let shouldInvalidateCache = false;
534
-
535
- mutations.forEach((mutation) => {
536
- if (mutation.type === 'childList') {
537
- const addedNodes = Array.from(mutation.addedNodes);
538
- const removedNodes = Array.from(mutation.removedNodes);
539
-
540
- const hasRouteNodes = [...addedNodes, ...removedNodes].some(
541
- (node) =>
542
- node.nodeType === Node.ELEMENT_NODE &&
543
- (node.tagName === 'SLICE-ROUTE' ||
544
- node.tagName === 'SLICE-MULTI-ROUTE' ||
545
- node.querySelector?.('slice-route, slice-multi-route'))
546
- );
547
-
548
- if (hasRouteNodes) {
549
- shouldInvalidateCache = true;
550
- }
551
- }
552
- });
553
-
554
- if (shouldInvalidateCache) {
555
- this.invalidateCache();
556
- }
557
- });
558
-
559
- this.observer.observe(document.body, {
560
- childList: true,
561
- subtree: true,
562
- });
563
- }
564
- }
565
-
566
- invalidateCache() {
567
- this.routeContainersCache.clear();
568
- this.lastCacheUpdate = 0;
569
- }
570
-
571
- createPathToRouteMap(routes, basePath = '', parentRoute = null) {
572
- const pathToRouteMap = new Map();
573
-
574
- for (const route of routes) {
575
- const fullPath = `${basePath}${route.path}`.replace(/\/+/g, '/');
576
-
577
- const routeWithParent = {
578
- ...route,
579
- fullPath,
580
- parentPath: parentRoute ? parentRoute.fullPath : null,
581
- parentRoute: parentRoute,
582
- };
583
-
584
- pathToRouteMap.set(fullPath, routeWithParent);
585
-
586
- if (route.children) {
587
- const childPathToRouteMap = this.createPathToRouteMap(route.children, fullPath, routeWithParent);
588
-
589
- for (const [childPath, childRoute] of childPathToRouteMap.entries()) {
590
- pathToRouteMap.set(childPath, childRoute);
591
- }
592
- }
593
- }
594
-
595
- return pathToRouteMap;
596
- }
597
-
598
- /**
599
- * Render any Route/MultiRoute components in a container.
600
- * @param {Document|HTMLElement} [searchContainer]
601
- * @returns {Promise<boolean>}
602
- */
603
- async renderRoutesComponentsInPage(searchContainer = document) {
604
- let routerContainersFlag = false;
605
- const routeContainers = this.getCachedRouteContainers(searchContainer);
606
-
607
- for (const routeContainer of routeContainers) {
608
- try {
609
- if (!routeContainer.isConnected) {
610
- this.invalidateCache();
611
- continue;
612
- }
613
-
614
- let response = await routeContainer.renderIfCurrentRoute();
615
- if (response) {
616
- this.activeRoute = routeContainer.props;
617
- routerContainersFlag = true;
618
- }
619
- } catch (error) {
620
- slice.logger.logError('Router', `Error rendering route container`, error);
621
- }
622
- }
623
-
624
- return routerContainersFlag;
625
- }
626
-
627
- getCachedRouteContainers(container) {
628
- const containerKey = container === document ? 'document' : container.sliceId || 'anonymous';
629
- const now = Date.now();
630
-
631
- if (this.routeContainersCache.has(containerKey) && now - this.lastCacheUpdate < this.CACHE_DURATION) {
632
- return this.routeContainersCache.get(containerKey);
633
- }
634
-
635
- const routeContainers = this.findAllRouteContainersOptimized(container);
636
- this.routeContainersCache.set(containerKey, routeContainers);
637
- this.lastCacheUpdate = now;
638
-
639
- return routeContainers;
640
- }
641
-
642
- findAllRouteContainersOptimized(container) {
643
- const routeContainers = [];
644
-
645
- const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
646
- acceptNode: (node) => {
647
- if (node.tagName === 'SLICE-ROUTE' || node.tagName === 'SLICE-MULTI-ROUTE') {
648
- return NodeFilter.FILTER_ACCEPT;
649
- }
650
- return NodeFilter.FILTER_SKIP;
651
- },
652
- });
653
-
654
- let node;
655
- while ((node = walker.nextNode())) {
656
- routeContainers.push(node);
657
- }
658
-
659
- return routeContainers;
660
- }
661
-
662
- /**
663
- * Render route containers inside a component.
664
- * @param {HTMLElement} component
665
- * @returns {Promise<boolean>}
666
- */
667
- async renderRoutesInComponent(component) {
668
- if (!component) {
669
- slice.logger.logWarning('Router', 'No component provided for route rendering');
670
- return false;
671
- }
672
-
673
- return await this.renderRoutesComponentsInPage(component);
674
- }
675
-
676
- /**
677
- * Match a path to a configured route.
678
- * @param {string} path
679
- * @returns {RouteMatch}
680
- */
681
- matchRoute(path) {
682
- // Normalize a trailing slash ('/about/' -> '/about'); keep root '/' as-is.
683
- path = path.length > 1 ? path.replace(/\/+$/, '') : path;
684
- // Exact match first (fast path), then a case-insensitive match on static paths
685
- // so '/About' resolves to a route declared as '/about'.
686
- let exactMatch = this.pathToRouteMap.get(path);
687
- if (!exactMatch) {
688
- const lowerPath = path.toLowerCase();
689
- for (const [routePattern, route] of this.pathToRouteMap.entries()) {
690
- if (!routePattern.includes('${') && routePattern.toLowerCase() === lowerPath) {
691
- exactMatch = route;
692
- break;
693
- }
694
- }
695
- }
696
- if (exactMatch) {
697
- if (exactMatch.parentRoute) {
698
- return {
699
- route: exactMatch.parentRoute,
700
- params: {},
701
- childRoute: exactMatch,
702
- };
703
- }
704
- return { route: exactMatch, params: {} };
705
- }
706
-
707
- for (const [routePattern, route] of this.pathToRouteMap.entries()) {
708
- if (routePattern.includes('${')) {
709
- const { regex, paramNames } = this.compilePathPattern(routePattern);
710
- const match = path.match(regex);
711
- if (match) {
712
- const params = {};
713
- paramNames.forEach((name, i) => {
714
- params[name] = match[i + 1];
715
- });
716
-
717
- if (route.parentRoute) {
718
- return {
719
- route: route.parentRoute,
720
- params: params,
721
- childRoute: route,
722
- };
723
- }
724
-
725
- return { route, params };
726
- }
727
- }
728
- }
729
-
730
- const notFoundRoute = this.pathToRouteMap.get('/404');
731
- return { route: notFoundRoute, params: {} };
732
- }
733
-
734
- /**
735
- * Compile a path pattern with ${param} segments.
736
- * @param {string} pattern
737
- * @returns {{ regex: RegExp, paramNames: string[] }}
738
- */
739
- compilePathPattern(pattern) {
740
- const paramNames = [];
741
- const regexPattern =
742
- '^' +
743
- pattern.replace(/\$\{([^}]+)\}/g, (_, paramName) => {
744
- paramNames.push(paramName);
745
- return '([^/]+)';
746
- }) +
747
- '$';
748
-
749
- // 'i' flag: paths match case-insensitively. Captured param values keep their original case.
750
- return { regex: new RegExp(regexPattern, 'i'), paramNames };
751
- }
752
- }
1
+ /**
2
+ * @typedef {Object} RouteConfig
3
+ * @property {string} path
4
+ * @property {string} component
5
+ * @property {RouteConfig[]} [children]
6
+ * @property {Object} [metadata]
7
+ * @property {string} [fullPath]
8
+ * @property {string|null} [parentPath]
9
+ * @property {RouteConfig|null} [parentRoute]
10
+ */
11
+
12
+ /**
13
+ * @typedef {Object} RouteInfo
14
+ * @property {string} path
15
+ * @property {string} component
16
+ * @property {Object} params
17
+ * @property {Object} query
18
+ * @property {Object} metadata
19
+ */
20
+
21
+ /**
22
+ * @typedef {Object} GuardRedirect
23
+ * @property {string} path
24
+ * @property {boolean} [replace]
25
+ */
26
+
27
+ /**
28
+ * @typedef {Object} RouteMatch
29
+ * @property {RouteConfig|null} route
30
+ * @property {Object} params
31
+ * @property {RouteConfig} [childRoute]
32
+ */
33
+
34
+ /**
35
+ * @callback RouterNext
36
+ * @param {void|false|string|{ path: string, replace?: boolean }} [arg]
37
+ * @returns {void}
38
+ */
39
+
40
+ export default class Router {
41
+ /**
42
+ * @param {RouteConfig[]} routes
43
+ */
44
+ constructor(routes) {
45
+ this.routes = routes;
46
+ this.activeRoute = null;
47
+ this.pathToRouteMap = this.createPathToRouteMap(routes);
48
+
49
+ // O(1) case-insensitive lookup for static routes, so a miss on the exact map
50
+ // doesn't scan every route on each navigation. Param routes (which carry a
51
+ // precompiled `compiled` regex) are excluded — they go through the param loop.
52
+ this._staticLowerIndex = new Map();
53
+ for (const [pattern, route] of this.pathToRouteMap.entries()) {
54
+ if (!route.compiled) this._staticLowerIndex.set(pattern.toLowerCase(), route);
55
+ }
56
+
57
+ // Navigation Guards
58
+ this._beforeEachGuard = null;
59
+ this._afterEachGuard = null;
60
+
61
+ // Router state
62
+ this._started = false;
63
+ this._autoStartTimeout = null;
64
+
65
+ // Sistema de caché optimizado
66
+ this.routeContainersCache = new Map();
67
+ this.lastCacheUpdate = 0;
68
+ this.CACHE_DURATION = 100; // ms - caché muy corto pero efectivo
69
+
70
+ // Observer para invalidar caché automáticamente
71
+ this.setupMutationObserver();
72
+ }
73
+
74
+ /**
75
+ * Inicializa el router
76
+ * Si el usuario no llama start() manualmente, se auto-inicia despues de un delay
77
+ * @returns {void}
78
+ */
79
+ init() {
80
+ window.addEventListener('popstate', () => {
81
+ try {
82
+ this.onRouteChange();
83
+ } catch (error) {
84
+ slice.logger.error('Router', 'Error in popstate handler', error);
85
+ }
86
+ });
87
+
88
+ this._autoStartTimeout = setTimeout(async () => {
89
+ if (!this._started) {
90
+ try {
91
+ slice.logger.info('Router', 'Auto-starting router (no manual start() called)');
92
+ await this.start();
93
+ } catch (error) {
94
+ slice.logger.error('Router', 'Auto-start failed', error);
95
+ }
96
+ }
97
+ }, 50);
98
+ }
99
+
100
+ /**
101
+ * Inicia el router y carga la ruta inicial
102
+ * OPCIONAL: Solo necesario si usas guards (beforeEach/afterEach)
103
+ * Si no lo llamas, el router se auto-inicia despues de 50ms
104
+ * @returns {Promise<void>}
105
+ */
106
+ async start() {
107
+ // Prevenir múltiples llamadas
108
+ if (this._started) {
109
+ slice.logger.logWarning('Router', 'start() already called');
110
+ return;
111
+ }
112
+
113
+ // Cancelar auto-start si existe
114
+ if (this._autoStartTimeout) {
115
+ clearTimeout(this._autoStartTimeout);
116
+ this._autoStartTimeout = null;
117
+ }
118
+
119
+ this._started = true;
120
+ await this.loadInitialRoute();
121
+ }
122
+
123
+ // ============================================
124
+ // NAVIGATION GUARDS API
125
+ // ============================================
126
+
127
+ /**
128
+ * Registra un guard que se ejecuta ANTES de cada navegacion.
129
+ * Puede bloquear o redirigir la navegacion mediante next().
130
+ * @param {(to: RouteInfo, from: RouteInfo, next: RouterNext) => void|Promise<void>} guard
131
+ * @returns {void}
132
+ */
133
+ beforeEach(guard) {
134
+ if (typeof guard !== 'function') {
135
+ slice.logger.logError('Router', 'beforeEach expects a function');
136
+ return;
137
+ }
138
+ this._beforeEachGuard = guard;
139
+ }
140
+
141
+ /**
142
+ * Registra un guard que se ejecuta DESPUES de cada navegacion.
143
+ * No puede bloquear la navegacion.
144
+ * @param {(to: RouteInfo, from: RouteInfo) => void} guard
145
+ * @returns {void}
146
+ */
147
+ afterEach(guard) {
148
+ if (typeof guard !== 'function') {
149
+ slice.logger.logError('Router', 'afterEach expects a function');
150
+ return;
151
+ }
152
+ this._afterEachGuard = guard;
153
+ }
154
+
155
+ /**
156
+ * Crea un objeto con información de ruta para los guards
157
+ * @param {Object} route - Objeto de ruta
158
+ * @param {Object} params - Parámetros de la ruta
159
+ * @param {String} requestedPath - Path original solicitado
160
+ * @returns {Object} Objeto con path, component, params, query, metadata
161
+ */
162
+ /**
163
+ * Build route info used by guards and events.
164
+ * @param {RouteConfig|null} route
165
+ * @param {Object} [params]
166
+ * @param {string|null} [requestedPath]
167
+ * @returns {RouteInfo}
168
+ */
169
+ _createRouteInfo(route, params = {}, requestedPath = null) {
170
+ if (!route) {
171
+ return {
172
+ path: requestedPath || '/404',
173
+ component: 'NotFound',
174
+ params: {},
175
+ query: this._parseQueryParams(),
176
+ metadata: {},
177
+ };
178
+ }
179
+
180
+ return {
181
+ path: requestedPath || route.fullPath || route.path,
182
+ component: route.parentRoute ? route.parentRoute.component : route.component,
183
+ params: params,
184
+ query: this._parseQueryParams(),
185
+ metadata: route.metadata || {},
186
+ };
187
+ }
188
+
189
+ /**
190
+ * Parsea los query parameters de la URL actual
191
+ * @returns {Object} Objeto con los query params
192
+ */
193
+ /**
194
+ * Parse query params from current URL.
195
+ * @returns {Object}
196
+ */
197
+ _parseQueryParams() {
198
+ const queryString = window.location.search;
199
+ if (!queryString) return {};
200
+
201
+ const params = {};
202
+ const urlParams = new URLSearchParams(queryString);
203
+
204
+ for (const [key, value] of urlParams) {
205
+ params[key] = value;
206
+ }
207
+
208
+ return params;
209
+ }
210
+
211
+ /**
212
+ * Ejecuta el beforeEach guard si existe
213
+ * @param {Object} to - Información de ruta destino
214
+ * @param {Object} from - Información de ruta origen
215
+ * @returns {Object|null} Objeto con redirectPath y options, o null si continúa
216
+ */
217
+ /**
218
+ * Execute beforeEach guard if defined.
219
+ * @param {RouteInfo} to
220
+ * @param {RouteInfo} from
221
+ * @returns {Promise<{ path: string|false, options: { replace?: boolean } }|null>}
222
+ */
223
+ async _executeBeforeEachGuard(to, from) {
224
+ if (!this._beforeEachGuard) {
225
+ return null;
226
+ }
227
+
228
+ let redirectPath = null;
229
+ let redirectOptions = {};
230
+ let nextCalled = false;
231
+
232
+ const next = (arg) => {
233
+ if (nextCalled) {
234
+ slice.logger.logWarning('Router', 'next() called multiple times in guard');
235
+ return;
236
+ }
237
+ nextCalled = true;
238
+
239
+ // Caso 1: Sin argumentos - continuar navegación
240
+ if (arg === undefined) {
241
+ return;
242
+ }
243
+
244
+ // Caso 2: false - cancelar navegación
245
+ if (arg === false) {
246
+ redirectPath = false;
247
+ return;
248
+ }
249
+
250
+ // Caso 3: String - redirección simple (backward compatibility)
251
+ if (typeof arg === 'string') {
252
+ redirectPath = arg;
253
+ redirectOptions = { replace: false };
254
+ return;
255
+ }
256
+
257
+ // Caso 4: Objeto - redirección con opciones
258
+ if (typeof arg === 'object' && arg.path) {
259
+ redirectPath = arg.path;
260
+ redirectOptions = {
261
+ replace: arg.replace || false,
262
+ };
263
+ return;
264
+ }
265
+
266
+ // Argumento inválido
267
+ slice.logger.logError(
268
+ 'Router',
269
+ 'Invalid argument passed to next(). Expected string, object with path, false, or undefined.'
270
+ );
271
+ };
272
+
273
+ try {
274
+ await this._beforeEachGuard(to, from, next);
275
+
276
+ // Si no se llamó next(), loguear advertencia pero continuar
277
+ if (!nextCalled) {
278
+ slice.logger.logWarning('Router', 'beforeEach guard did not call next(). Navigation will continue.');
279
+ }
280
+
281
+ // Retornar tanto el path como las opciones
282
+ return redirectPath ? { path: redirectPath, options: redirectOptions } : null;
283
+ } catch (error) {
284
+ slice.logger.error('Router', `Error in beforeEach guard from "${from?.path}" to "${to?.path}"`, error);
285
+ return { path: false, options: {} };
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Ejecuta el afterEach guard si existe
291
+ * @param {Object} to - Información de ruta destino
292
+ * @param {Object} from - Información de ruta origen
293
+ */
294
+ /**
295
+ * Execute afterEach guard if defined.
296
+ * @param {RouteInfo} to
297
+ * @param {RouteInfo} from
298
+ * @returns {void}
299
+ */
300
+ _executeAfterEachGuard(to, from) {
301
+ if (!this._afterEachGuard) {
302
+ return;
303
+ }
304
+
305
+ try {
306
+ this._afterEachGuard(to, from);
307
+ } catch (error) {
308
+ slice.logger.logError('Router', 'Error in afterEach guard', error);
309
+ }
310
+ }
311
+
312
+ // ============================================
313
+ // ROUTING CORE (MODIFICADO CON GUARDS)
314
+ // ============================================
315
+
316
+ /**
317
+ * Navigate to a route path (guards run automatically).
318
+ * @param {string} path
319
+ * @param {{ replace?: boolean }} [options] - `{ replace: true }` replaces history instead of pushing.
320
+ * @returns {Promise<void>}
321
+ */
322
+ async navigate(path, options = {}, legacyOptions) {
323
+ // Backward compatibility with the previous signature navigate(path, _redirectChain, _options):
324
+ // if the 2nd argument is the internal redirect chain (an array) or a 3rd argument is passed,
325
+ // use the 3rd argument as the options object.
326
+ if (Array.isArray(options)) {
327
+ options = legacyOptions || {};
328
+ } else if (legacyOptions !== undefined) {
329
+ options = legacyOptions || options;
330
+ }
331
+ return this._navigateWithGuards(path, options || {}, []);
332
+ }
333
+
334
+ /**
335
+ * Internal navigation that tracks the guard redirection chain (loop protection).
336
+ * @param {string} path
337
+ * @param {{ replace?: boolean }} options
338
+ * @param {string[]} redirectChain
339
+ * @returns {Promise<void>}
340
+ */
341
+ async _navigateWithGuards(path, options, redirectChain) {
342
+ const currentPath = window.location.pathname;
343
+
344
+ // Detectar loops infinitos: si ya visitamos esta ruta en la cadena de redirecciones
345
+ if (redirectChain.includes(path)) {
346
+ slice.logger.logError('Router', `Guard redirection loop detected: ${redirectChain.join(' ')} → ${path}`);
347
+ return;
348
+ }
349
+
350
+ // Límite de seguridad: máximo 10 redirecciones
351
+ if (redirectChain.length >= 10) {
352
+ slice.logger.logError('Router', `Too many redirections: ${redirectChain.join(' ')} → ${path}`);
353
+ return;
354
+ }
355
+
356
+ // Obtener información de ruta actual
357
+ const { route: fromRoute, params: fromParams } = this.matchRoute(currentPath);
358
+ const from = this._createRouteInfo(fromRoute, fromParams, currentPath);
359
+
360
+ // Obtener información de ruta destino
361
+ const { route: toRoute, params: toParams } = this.matchRoute(path);
362
+ const to = this._createRouteInfo(toRoute, toParams, path);
363
+
364
+ // EJECUTAR BEFORE EACH GUARD
365
+ const guardResult = await this._executeBeforeEachGuard(to, from);
366
+
367
+ // Si el guard redirige
368
+ if (guardResult && guardResult.path) {
369
+ return this._navigateWithGuards(guardResult.path, guardResult.options || {}, [...redirectChain, path]);
370
+ }
371
+
372
+ // Si el guard cancela la navegación (next(false))
373
+ if (guardResult && guardResult.path === false) {
374
+ slice.logger.logInfo('Router', 'Navigation cancelled by guard');
375
+ return;
376
+ }
377
+
378
+ // No hay redirección - continuar con la navegación normal
379
+ // Usar replace o push según las opciones
380
+ if (options.replace) {
381
+ window.history.replaceState({}, path, window.location.origin + path);
382
+ } else {
383
+ window.history.pushState({}, path, window.location.origin + path);
384
+ }
385
+
386
+ await this._performNavigation(to, from);
387
+ }
388
+
389
+ /**
390
+ * Método interno para ejecutar la navegación después de pasar los guards
391
+ * @param {Object} to - Información de ruta destino
392
+ * @param {Object} from - Información de ruta origen
393
+ */
394
+ /**
395
+ * Perform navigation after guards.
396
+ * @param {RouteInfo} to
397
+ * @param {RouteInfo} from
398
+ * @returns {Promise<void>}
399
+ */
400
+ async _performNavigation(to, from) {
401
+ // Renderizar la nueva ruta
402
+ await this.onRouteChange();
403
+
404
+ // EJECUTAR AFTER EACH GUARD
405
+ this._executeAfterEachGuard(to, from);
406
+
407
+ // Emitir evento de cambio de ruta
408
+ this._emitRouteChange(to, from);
409
+ }
410
+
411
+ /**
412
+ * React to URL changes and render routes.
413
+ * @returns {Promise<void>}
414
+ */
415
+ async onRouteChange() {
416
+ if (this.routeChangeTimeout) {
417
+ clearTimeout(this.routeChangeTimeout);
418
+ }
419
+
420
+ this.routeChangeTimeout = setTimeout(async () => {
421
+ try {
422
+ const path = window.location.pathname;
423
+ const routeContainersFlag = await this.renderRoutesComponentsInPage();
424
+
425
+ if (routeContainersFlag) {
426
+ return;
427
+ }
428
+
429
+ const { route, params } = this.matchRoute(path);
430
+ if (route) {
431
+ await this.handleRoute(route, params);
432
+ }
433
+ } catch (error) {
434
+ slice.logger.error('Router', `Route change failed for ${window.location.pathname}`, error);
435
+ }
436
+ }, 10);
437
+ }
438
+
439
+ /**
440
+ * Build or update the active route component.
441
+ * @param {RouteConfig} route
442
+ * @param {Object} params
443
+ * @returns {Promise<void>}
444
+ */
445
+ async handleRoute(route, params) {
446
+ const targetElement = document.querySelector('#app');
447
+
448
+ const componentName = route.parentRoute ? route.parentRoute.component : route.component;
449
+ const sliceId = `route-${componentName}`;
450
+
451
+ const existingComponent = slice.controller.getComponent(sliceId);
452
+
453
+ if (slice.loading) {
454
+ slice.loading.start();
455
+ }
456
+
457
+ try {
458
+ if (existingComponent) {
459
+ targetElement.innerHTML = '';
460
+ if (existingComponent.update) {
461
+ existingComponent.props = { ...existingComponent.props, ...params };
462
+ await existingComponent.update();
463
+ }
464
+ targetElement.appendChild(existingComponent);
465
+ await this.renderRoutesInComponent(existingComponent);
466
+ } else {
467
+ const component = await slice.build(componentName, {
468
+ params,
469
+ sliceId: sliceId,
470
+ });
471
+
472
+ targetElement.innerHTML = '';
473
+ targetElement.appendChild(component);
474
+
475
+ await this.renderRoutesInComponent(component);
476
+ }
477
+
478
+ // Invalidar caché después de cambios importantes en el DOM
479
+ this.invalidateCache();
480
+ slice.router.activeRoute = route;
481
+ } finally {
482
+ if (slice.loading) {
483
+ slice.loading.stop();
484
+ }
485
+ }
486
+ }
487
+
488
+ /**
489
+ * Load initial route and run guards.
490
+ * @returns {Promise<void>}
491
+ */
492
+ async loadInitialRoute() {
493
+ const path = window.location.pathname;
494
+ const { route, params } = this.matchRoute(path);
495
+
496
+ // Para la carga inicial, también ejecutar guards
497
+ const from = this._createRouteInfo(null, {}, null);
498
+ const to = this._createRouteInfo(route, params, path);
499
+
500
+ // EJECUTAR BEFORE EACH GUARD en carga inicial
501
+ const guardResult = await this._executeBeforeEachGuard(to, from);
502
+
503
+ if (guardResult && guardResult.path) {
504
+ return this.navigate(guardResult.path, guardResult.options || {});
505
+ }
506
+
507
+ // Si el guard cancela la navegación inicial (caso raro pero posible)
508
+ if (guardResult && guardResult.path === false) {
509
+ slice.logger.logWarning('Router', 'Initial route navigation cancelled by guard');
510
+ return;
511
+ }
512
+
513
+ await this.handleRoute(route, params);
514
+
515
+ // EJECUTAR AFTER EACH GUARD en carga inicial
516
+ this._executeAfterEachGuard(to, from);
517
+
518
+ // Emitir evento de cambio de ruta
519
+ this._emitRouteChange(to, from);
520
+ }
521
+
522
+ /**
523
+ * Emitir evento de cambio de ruta
524
+ * @param {Object} to
525
+ * @param {Object} from
526
+ */
527
+ /**
528
+ * Emit route change event.
529
+ * @param {RouteInfo} to
530
+ * @param {RouteInfo} from
531
+ * @returns {void}
532
+ */
533
+ _emitRouteChange(to, from) {
534
+ const payload = { to, from };
535
+
536
+ if (slice.eventsConfig?.enabled && slice.events && typeof slice.events.emit === 'function') {
537
+ slice.events.emit('router:change', payload);
538
+ return;
539
+ }
540
+
541
+ window.dispatchEvent(new CustomEvent('router:change', { detail: payload }));
542
+ }
543
+
544
+ // ============================================
545
+ // MÉTODOS EXISTENTES (SIN CAMBIOS)
546
+ // ============================================
547
+
548
+ setupMutationObserver() {
549
+ if (typeof MutationObserver !== 'undefined') {
550
+ this.observer = new MutationObserver((mutations) => {
551
+ try {
552
+ let shouldInvalidateCache = false;
553
+
554
+ mutations.forEach((mutation) => {
555
+ if (mutation.type === 'childList') {
556
+ const addedNodes = Array.from(mutation.addedNodes || []);
557
+ const removedNodes = Array.from(mutation.removedNodes || []);
558
+
559
+ const hasRouteNodes = [...addedNodes, ...removedNodes].some(
560
+ (node) =>
561
+ node.nodeType === Node.ELEMENT_NODE &&
562
+ (node.tagName === 'SLICE-ROUTE' ||
563
+ node.tagName === 'SLICE-MULTI-ROUTE' ||
564
+ node.querySelector?.('slice-route, slice-multi-route'))
565
+ );
566
+
567
+ if (hasRouteNodes) {
568
+ shouldInvalidateCache = true;
569
+ }
570
+ }
571
+ });
572
+
573
+ if (shouldInvalidateCache) {
574
+ this.invalidateCache();
575
+ }
576
+ } catch (error) {
577
+ slice.logger.error('Router', 'Error in MutationObserver callback', error);
578
+ }
579
+ });
580
+
581
+ this.observer.observe(document.body, {
582
+ childList: true,
583
+ subtree: true,
584
+ });
585
+ }
586
+ }
587
+
588
+ invalidateCache() {
589
+ this.routeContainersCache.clear();
590
+ this.lastCacheUpdate = 0;
591
+ }
592
+
593
+ createPathToRouteMap(routes, basePath = '', parentRoute = null) {
594
+ const pathToRouteMap = new Map();
595
+
596
+ for (const route of routes) {
597
+ const fullPath = `${basePath}${route.path}`.replace(/\/+/g, '/');
598
+
599
+ const routeWithParent = {
600
+ ...route,
601
+ fullPath,
602
+ parentPath: parentRoute ? parentRoute.fullPath : null,
603
+ parentRoute: parentRoute,
604
+ };
605
+
606
+ // Compile parameterized patterns once at map-build time instead of on every
607
+ // navigation. Static routes leave `compiled` undefined.
608
+ if (fullPath.includes('${')) {
609
+ routeWithParent.compiled = this.compilePathPattern(fullPath);
610
+ }
611
+
612
+ pathToRouteMap.set(fullPath, routeWithParent);
613
+
614
+ if (route.children) {
615
+ const childPathToRouteMap = this.createPathToRouteMap(route.children, fullPath, routeWithParent);
616
+
617
+ for (const [childPath, childRoute] of childPathToRouteMap.entries()) {
618
+ pathToRouteMap.set(childPath, childRoute);
619
+ }
620
+ }
621
+ }
622
+
623
+ return pathToRouteMap;
624
+ }
625
+
626
+ /**
627
+ * Render any Route/MultiRoute components in a container.
628
+ * @param {Document|HTMLElement} [searchContainer]
629
+ * @returns {Promise<boolean>}
630
+ */
631
+ async renderRoutesComponentsInPage(searchContainer = document) {
632
+ let routerContainersFlag = false;
633
+ const routeContainers = this.getCachedRouteContainers(searchContainer);
634
+
635
+ for (const routeContainer of routeContainers) {
636
+ try {
637
+ if (!routeContainer.isConnected) {
638
+ this.invalidateCache();
639
+ continue;
640
+ }
641
+
642
+ let response = await routeContainer.renderIfCurrentRoute();
643
+ if (response) {
644
+ this.activeRoute = routeContainer.props;
645
+ routerContainersFlag = true;
646
+ }
647
+ } catch (error) {
648
+ const containerName = routeContainer?.tagName || routeContainer?.constructor?.name || 'unknown';
649
+ slice.logger.error('Router', `Error rendering route container "${containerName}"`, error);
650
+ }
651
+ }
652
+
653
+ return routerContainersFlag;
654
+ }
655
+
656
+ getCachedRouteContainers(container) {
657
+ const containerKey = container === document ? 'document' : container.sliceId || 'anonymous';
658
+ const now = Date.now();
659
+
660
+ if (this.routeContainersCache.has(containerKey) && now - this.lastCacheUpdate < this.CACHE_DURATION) {
661
+ return this.routeContainersCache.get(containerKey);
662
+ }
663
+
664
+ const routeContainers = this.findAllRouteContainersOptimized(container);
665
+ this.routeContainersCache.set(containerKey, routeContainers);
666
+ this.lastCacheUpdate = now;
667
+
668
+ return routeContainers;
669
+ }
670
+
671
+ findAllRouteContainersOptimized(container) {
672
+ const routeContainers = [];
673
+
674
+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
675
+ acceptNode: (node) => {
676
+ if (node.tagName === 'SLICE-ROUTE' || node.tagName === 'SLICE-MULTI-ROUTE') {
677
+ return NodeFilter.FILTER_ACCEPT;
678
+ }
679
+ return NodeFilter.FILTER_SKIP;
680
+ },
681
+ });
682
+
683
+ let node;
684
+ while ((node = walker.nextNode())) {
685
+ routeContainers.push(node);
686
+ }
687
+
688
+ return routeContainers;
689
+ }
690
+
691
+ /**
692
+ * Render route containers inside a component.
693
+ * @param {HTMLElement} component
694
+ * @returns {Promise<boolean>}
695
+ */
696
+ async renderRoutesInComponent(component) {
697
+ if (!component) {
698
+ slice.logger.logWarning('Router', 'No component provided for route rendering');
699
+ return false;
700
+ }
701
+
702
+ return await this.renderRoutesComponentsInPage(component);
703
+ }
704
+
705
+ /**
706
+ * Match a path to a configured route.
707
+ * @param {string} path
708
+ * @returns {RouteMatch}
709
+ */
710
+ matchRoute(path) {
711
+ // Normalize a trailing slash ('/about/' -> '/about'); keep root '/' as-is.
712
+ path = path.length > 1 ? path.replace(/\/+$/, '') : path;
713
+ // Exact match first (fast path), then a case-insensitive match on static paths
714
+ // so '/About' resolves to a route declared as '/about'.
715
+ let exactMatch = this.pathToRouteMap.get(path);
716
+ if (!exactMatch) {
717
+ exactMatch = this._staticLowerIndex.get(path.toLowerCase());
718
+ }
719
+ if (exactMatch) {
720
+ if (exactMatch.parentRoute) {
721
+ return {
722
+ route: exactMatch.parentRoute,
723
+ params: {},
724
+ childRoute: exactMatch,
725
+ };
726
+ }
727
+ return { route: exactMatch, params: {} };
728
+ }
729
+
730
+ for (const route of this.pathToRouteMap.values()) {
731
+ if (route.compiled) {
732
+ const { regex, paramNames } = route.compiled;
733
+ const match = path.match(regex);
734
+ if (match) {
735
+ const params = {};
736
+ paramNames.forEach((name, i) => {
737
+ params[name] = match[i + 1];
738
+ });
739
+
740
+ if (route.parentRoute) {
741
+ return {
742
+ route: route.parentRoute,
743
+ params: params,
744
+ childRoute: route,
745
+ };
746
+ }
747
+
748
+ return { route, params };
749
+ }
750
+ }
751
+ }
752
+
753
+ const notFoundRoute = this.pathToRouteMap.get('/404');
754
+ return { route: notFoundRoute, params: {} };
755
+ }
756
+
757
+ /**
758
+ * Compile a path pattern with ${param} segments.
759
+ * @param {string} pattern
760
+ * @returns {{ regex: RegExp, paramNames: string[] }}
761
+ */
762
+ compilePathPattern(pattern) {
763
+ const paramNames = [];
764
+ const regexPattern =
765
+ '^' +
766
+ pattern.replace(/\$\{([^}]+)\}/g, (_, paramName) => {
767
+ paramNames.push(paramName);
768
+ return '([^/]+)';
769
+ }) +
770
+ '$';
771
+
772
+ // 'i' flag: paths match case-insensitively. Captured param values keep their original case.
773
+ return { regex: new RegExp(regexPattern, 'i'), paramNames };
774
+ }
775
+ }