slicejs-web-framework 4.0.2 → 4.1.1

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