@real-router/logger-plugin 0.2.1 → 0.2.3

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,67 +1,1604 @@
1
- import { PluginFactory } from '@real-router/core';
1
+ // Generated by dts-bundle-generator v9.5.1
2
2
 
3
3
  /**
4
4
  * Logging level for router events.
5
5
  * Controls which events are logged to the console.
6
6
  */
7
- type LogLevel = "all" | "transitions" | "errors" | "none";
7
+ export type LogLevel = "all" | "transitions" | "errors" | "none";
8
8
  /**
9
9
  * Configuration options for the logger-plugin.
10
10
  */
11
- interface LoggerPluginConfig {
12
- /**
13
- * Use Performance API to create marks and measures.
14
- * Enables integration with browser DevTools Performance tab.
15
- *
16
- * Creates marks:
17
- * - `router:transition-start:{from}→{to}`
18
- * - `router:transition-end:{from}→{to}` (success)
19
- * - `router:transition-cancel:{from}→{to}` (cancelled)
20
- * - `router:transition-error:{from}→{to}` (error)
21
- *
22
- * Creates measures:
23
- * - `router:transition:{from}→{to}` (success)
24
- * - `router:transition-cancelled:{from}→{to}` (cancelled)
25
- * - `router:transition-failed:{from}→{to}` (error)
26
- *
27
- * @default false
28
- */
29
- usePerformanceMarks?: boolean;
30
- /**
31
- * Logging level - controls what router events to log.
32
- *
33
- * - 'all': Log all router events (default)
34
- * - 'transitions': Log only transition-related events
35
- * - 'errors': Log only transition errors
36
- * - 'none': Disable all logging
37
- *
38
- * @default 'all'
39
- */
40
- level?: LogLevel;
41
- /**
42
- * Show execution time in milliseconds for transitions.
43
- * Helps identify slow route changes.
44
- *
45
- * @default true
46
- */
47
- showTiming?: boolean;
48
- /**
49
- * Show diff of changed route parameters between transitions.
50
- * Only applies when navigating within the same route.
51
- * Helps identify which parameters changed during navigation.
52
- *
53
- * @default false
54
- */
55
- showParamsDiff?: boolean;
56
- /**
57
- * Custom context name for console.
58
- * Useful when running multiple routers.
59
- *
60
- * @default 'logger-plugin'
61
- */
62
- context?: string;
11
+ export interface LoggerPluginConfig {
12
+ /**
13
+ * Use Performance API to create marks and measures.
14
+ * Enables integration with browser DevTools Performance tab.
15
+ *
16
+ * Creates marks:
17
+ * - `router:transition-start:{from}→{to}`
18
+ * - `router:transition-end:{from}→{to}` (success)
19
+ * - `router:transition-cancel:{from}→{to}` (cancelled)
20
+ * - `router:transition-error:{from}→{to}` (error)
21
+ *
22
+ * Creates measures:
23
+ * - `router:transition:{from}→{to}` (success)
24
+ * - `router:transition-cancelled:{from}→{to}` (cancelled)
25
+ * - `router:transition-failed:{from}→{to}` (error)
26
+ *
27
+ * @default false
28
+ */
29
+ usePerformanceMarks?: boolean;
30
+ /**
31
+ * Logging level - controls what router events to log.
32
+ *
33
+ * - 'all': Log all router events (default)
34
+ * - 'transitions': Log only transition-related events
35
+ * - 'errors': Log only transition errors
36
+ * - 'none': Disable all logging
37
+ *
38
+ * @default 'all'
39
+ */
40
+ level?: LogLevel;
41
+ /**
42
+ * Show execution time in milliseconds for transitions.
43
+ * Helps identify slow route changes.
44
+ *
45
+ * @default true
46
+ */
47
+ showTiming?: boolean;
48
+ /**
49
+ * Show diff of changed route parameters between transitions.
50
+ * Only applies when navigating within the same route.
51
+ * Helps identify which parameters changed during navigation.
52
+ *
53
+ * @default false
54
+ */
55
+ showParamsDiff?: boolean;
56
+ /**
57
+ * Custom context name for console.
58
+ * Useful when running multiple routers.
59
+ *
60
+ * @default 'logger-plugin'
61
+ */
62
+ context?: string;
63
63
  }
64
-
64
+ /**
65
+ * Route Node Type Definitions — Minimal Public API.
66
+ *
67
+ * This module exports ONLY the essential types used by real-router:
68
+ * - QueryParamsMode, QueryParamsOptions
69
+ * - RouteTreeState
70
+ *
71
+ * These types are copied from route-node to avoid circular dependencies.
72
+ *
73
+ * @module route-node-types
74
+ */
75
+ export type ArrayFormat = "none" | "brackets" | "index" | "comma";
76
+ export type BooleanFormat = "none" | "string" | "empty-true";
77
+ export type NullFormat = "default" | "hidden";
78
+ /**
79
+ * Options for query parameter parsing and building.
80
+ */
81
+ export interface QueryParamsOptions {
82
+ arrayFormat?: ArrayFormat;
83
+ booleanFormat?: BooleanFormat;
84
+ nullFormat?: NullFormat;
85
+ }
86
+ /**
87
+ * Controls how query parameters are handled during matching.
88
+ */
89
+ export type QueryParamsMode = "default" | "strict" | "loose";
90
+ export type ParamSource = "url" | "query";
91
+ export type ParamTypeMap = Record<string, ParamSource>;
92
+ export type RouteTreeStateMeta = Record<string, ParamTypeMap>;
93
+ export interface RouteParams {
94
+ [key: string]: string | string[] | number | number[] | boolean | boolean[] | RouteParams | RouteParams[] | Record<string, string | number | boolean> | null | undefined;
95
+ }
96
+ /**
97
+ * Complete state representation of a matched route.
98
+ */
99
+ export interface RouteTreeState<P extends Record<string, unknown> = RouteParams> {
100
+ name: string;
101
+ params: P;
102
+ meta: RouteTreeStateMeta;
103
+ }
104
+ export type Unsubscribe = () => void;
105
+ export type CancelFn = () => void;
106
+ export interface SimpleState<P extends Params = Params> {
107
+ name: string;
108
+ params: P;
109
+ }
110
+ export interface State<P extends Params = Params, MP extends Params = Params> {
111
+ name: string;
112
+ params: P;
113
+ path: string;
114
+ meta?: StateMeta<MP> | undefined;
115
+ }
116
+ export interface StateMeta<P extends Params = Params> {
117
+ id: number;
118
+ params: P;
119
+ options: NavigationOptions;
120
+ redirected: boolean;
121
+ source?: string | undefined;
122
+ }
123
+ /**
124
+ * Input type for makeState meta parameter.
125
+ * Omits `id` since it's auto-generated by makeState.
126
+ */
127
+ export type StateMetaInput<P extends Params = Params> = Omit<StateMeta<P>, "id">;
128
+ /**
129
+ * RouterError interface describing the public API of the RouterError class.
130
+ * The actual class implementation is in the real-router package.
131
+ * This interface enables structural typing compatibility between
132
+ * core-types and real-router packages.
133
+ */
134
+ export interface RouterError extends Error {
135
+ [key: string]: unknown;
136
+ readonly code: string;
137
+ readonly segment: string | undefined;
138
+ readonly path: string | undefined;
139
+ readonly redirect: State | undefined;
140
+ setCode: (code: string) => void;
141
+ setErrorInstance: (err: Error) => void;
142
+ setAdditionalFields: (fields: Record<string, unknown>) => void;
143
+ hasField: (key: string) => boolean;
144
+ getField: (key: string) => unknown;
145
+ toJSON: () => Record<string, unknown>;
146
+ }
147
+ export type DoneFn = (error?: RouterError, state?: State) => void;
148
+ /**
149
+ * Configuration options that control navigation transition behavior.
150
+ *
151
+ * @description
152
+ * NavigationOptions provides fine-grained control over how the router performs navigation
153
+ * transitions. These options affect history management, transition lifecycle execution,
154
+ * guard enforcement, and state comparison logic.
155
+ *
156
+ * All options are optional and have sensible defaults. Options can be combined to achieve
157
+ * complex navigation behaviors. The options object is stored in state.meta.options and is
158
+ * available to middleware, guards, and event listeners.
159
+ *
160
+ * @see {@link Router.navigate} for navigation method that accepts these options
161
+ * @see {@link State.meta} for where options are stored after navigation
162
+ */
163
+ export interface NavigationOptions {
164
+ [key: string]: string | number | boolean | Record<string, unknown> | undefined;
165
+ /**
166
+ * Replace the current history entry instead of pushing a new one.
167
+ *
168
+ * @description
169
+ * When `true`, the navigation will replace the current entry in browser history instead
170
+ * of adding a new entry. This is typically used by history plugins (browser plugin) to
171
+ * control how navigation affects the browser's back/forward buttons.
172
+ *
173
+ * @default false
174
+ *
175
+ * @example
176
+ * // Redirect after login - prevent back button to login page
177
+ * router.navigate('dashboard', {}, { replace: true });
178
+ *
179
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState}
180
+ */
181
+ replace?: boolean | undefined;
182
+ /**
183
+ * Force reload of the current route even if states are equal.
184
+ *
185
+ * @description
186
+ * When `true`, bypasses the "same state" check that normally prevents navigation when
187
+ * the target state equals the current state. This forces a full transition lifecycle
188
+ * execution, allowing route components to reload with the same parameters.
189
+ *
190
+ * Without `reload`:
191
+ * - Navigation to current route throws SAME_STATES error
192
+ * - No lifecycle hooks or middleware execute
193
+ * - No events are fired
194
+ *
195
+ * With `reload`:
196
+ * - Full transition executes (deactivate → activate → middleware)
197
+ * - All lifecycle hooks run again
198
+ * - TRANSITION_SUCCESS event fires with same state
199
+ * - State object is recreated (new reference)
200
+ *
201
+ * @default false
202
+ *
203
+ * @example
204
+ * // Refresh current page data
205
+ * router.navigate(currentRoute.name, currentRoute.params, { reload: true });
206
+ *
207
+ * @example
208
+ * // Force re-fetch on same route with different query params
209
+ * // Note: query params are in path, not checked for equality
210
+ * router.navigate('search', { term: 'react' }, { reload: true });
211
+ *
212
+ * @see {@link force} for alternative that forces transition
213
+ * @see {@link Router.areStatesEqual} for state comparison logic
214
+ */
215
+ reload?: boolean | undefined;
216
+ /**
217
+ * Preview navigation without any side effects (dry-run mode).
218
+ *
219
+ * @description
220
+ * When `true`, returns the would-be target state via callback WITHOUT:
221
+ * - Executing canDeactivate/canActivate guards
222
+ * - Executing middleware
223
+ * - Updating router state (`router.getState()` remains unchanged)
224
+ * - Emitting any transition events (TRANSITION_START, TRANSITION_SUCCESS, etc.)
225
+ *
226
+ * The callback receives `(undefined, toState)` where `toState` is the computed
227
+ * target state that WOULD result from this navigation.
228
+ *
229
+ * @default false
230
+ *
231
+ * @remarks
232
+ * This option is useful for:
233
+ * - Validating that a route exists and params are correct
234
+ * - SSR: previewing state for pre-rendering without side effects
235
+ * - Dry-run before actual navigation
236
+ *
237
+ * @deprecated Consider using `router.buildState()` + `router.makeState()` instead
238
+ * for clearer intent. This option may be removed in a future major version.
239
+ *
240
+ * @example
241
+ * // Preview navigation - router.getState() is NOT changed
242
+ * router.navigate('users.view', { id: 123 }, { skipTransition: true }, (err, previewState) => {
243
+ * console.log(previewState); // { name: 'users.view', params: { id: 123 }, path: '/users/view/123', ... }
244
+ * console.log(router.getState()); // Still the previous state!
245
+ * });
246
+ *
247
+ * @example
248
+ * // Recommended alternative (clearer intent)
249
+ * const route = router.buildState('users.view', { id: 123 });
250
+ * if (route) {
251
+ * const path = router.buildPath(route.name, route.params);
252
+ * const previewState = router.makeState(route.name, route.params, path, { params: route.meta });
253
+ * }
254
+ *
255
+ * @see {@link forceDeactivate} for skipping only canDeactivate guards
256
+ * @see {@link force} for forcing navigation while preserving lifecycle
257
+ */
258
+ skipTransition?: boolean | undefined;
259
+ /**
260
+ * Force navigation even if target state equals current state.
261
+ *
262
+ * @description
263
+ * When `true`, bypasses the "same state" equality check but still executes the full
264
+ * transition lifecycle (unlike `skipTransition`). Similar to `reload` but can be used
265
+ * for any forced navigation scenario.
266
+ *
267
+ * Difference from `reload`:
268
+ * - `reload`: semantic meaning is "refresh current route"
269
+ * - `force`: general-purpose bypass of equality check
270
+ * - Both have identical implementation effect
271
+ *
272
+ * The equality check compares:
273
+ * - state.name (route name)
274
+ * - state.params (route parameters, shallow comparison)
275
+ *
276
+ * @default false
277
+ *
278
+ * @example
279
+ * // Force transition for tracking even if params didn't change
280
+ * router.navigate('analytics', { event: 'pageview' }, { force: true });
281
+ *
282
+ * @see {@link reload} for semantic equivalent (preferred for refresh scenarios)
283
+ * @see {@link skipTransition} for bypassing entire lifecycle
284
+ */
285
+ force?: boolean | undefined;
286
+ /**
287
+ * Skip canDeactivate guards during transition.
288
+ *
289
+ * @description
290
+ * When `true`, bypasses only the canDeactivate lifecycle hooks for segments being
291
+ * deactivated. canActivate guards and middleware still execute normally. This allows
292
+ * forcing navigation away from routes with confirmation dialogs or unsaved changes.
293
+ *
294
+ * Skipped vs executed:
295
+ * ```
296
+ * // Normal transition
297
+ * deactivate(fromSegments) → activate(toSegments) → middleware → success
298
+ *
299
+ * // With forceDeactivate: true
300
+ * [skip deactivate] → activate(toSegments) → middleware → success
301
+ * ```
302
+ *
303
+ * ⚠️ Data loss risk: Bypassing canDeactivate means unsaved changes will be lost
304
+ *
305
+ * @default false
306
+ *
307
+ * @example
308
+ * // Force logout even with unsaved changes
309
+ * function forceLogout() {
310
+ * router.navigate('login', {}, {
311
+ * forceDeactivate: true,
312
+ * replace: true
313
+ * });
314
+ * }
315
+ *
316
+ * @see {@link skipTransition} for bypassing all guards and middleware
317
+ * @see {@link Router.clearCanDeactivate} for programmatically clearing guards
318
+ */
319
+ forceDeactivate?: boolean | undefined;
320
+ /**
321
+ * Internal flag indicating navigation is result of a redirect.
322
+ *
323
+ * @internal
324
+ *
325
+ * @description
326
+ * Automatically set by the router when a navigation is triggered by a redirect from
327
+ * middleware or lifecycle hooks. This flag is used internally to track redirect chains
328
+ * and is stored in state.meta.redirected.
329
+ *
330
+ * @default false (auto-set by router during redirects)
331
+ *
332
+ * @example
333
+ * // Middleware triggers automatic redirect
334
+ * router.useMiddleware((toState, fromState, opts) => {
335
+ * if (!isAuthenticated && toState.name !== 'login') {
336
+ * // Router will automatically set redirected: true
337
+ * return { name: 'login', params: { next: toState.path } };
338
+ * }
339
+ * });
340
+ *
341
+ * @example
342
+ * // Accessing redirect flag in lifecycle
343
+ * router.canActivate('dashboard', (toState, fromState) => {
344
+ * if (toState.meta?.redirected) {
345
+ * console.log('This navigation is from a redirect');
346
+ * }
347
+ * return true;
348
+ * });
349
+ *
350
+ * @see {@link Router.navigate} for redirect handling implementation
351
+ * @see {@link State.meta.redirected} for redirect flag in state
352
+ */
353
+ redirected?: boolean | undefined;
354
+ }
355
+ export interface Params {
356
+ [key: string]: string | string[] | number | number[] | boolean | boolean[] | Params | Params[] | Record<string, string | number | boolean> | null | undefined;
357
+ }
358
+ /**
359
+ * Event type keys
360
+ */
361
+ export type EventsKeys = "ROUTER_START" | "ROUTER_STOP" | "TRANSITION_START" | "TRANSITION_CANCEL" | "TRANSITION_SUCCESS" | "TRANSITION_ERROR";
362
+ /**
363
+ * Mapping of event keys to event names
364
+ */
365
+ export interface EventToNameMap {
366
+ ROUTER_START: "$start";
367
+ ROUTER_STOP: "$stop";
368
+ TRANSITION_START: "$$start";
369
+ TRANSITION_CANCEL: "$$cancel";
370
+ TRANSITION_SUCCESS: "$$success";
371
+ TRANSITION_ERROR: "$$error";
372
+ }
373
+ type LogLevel$1 = "log" | "warn" | "error";
374
+ /**
375
+ * Logger threshold configuration level.
376
+ *
377
+ * Determines which messages are displayed based on severity:
378
+ * - `all`: Show all messages (log, warn, error)
379
+ * - `warn-error`: Show only warnings and errors (filter out log)
380
+ * - `error-only`: Show only errors (filter out log and warn)
381
+ * - `none`: Show no messages (completely silent, unless callback ignores level)
382
+ *
383
+ * Note: Higher threshold = fewer messages shown.
384
+ *
385
+ * @example
386
+ * ```ts
387
+ * // Production: only show errors
388
+ * logger.configure({ level: 'error-only' });
389
+ *
390
+ * // Development: show everything
391
+ * logger.configure({ level: 'all' });
392
+ * ```
393
+ */
394
+ export type LogLevelConfig = "all" | "warn-error" | "error-only" | "none";
395
+ /**
396
+ * Callback function type for custom log processing.
397
+ *
398
+ * Receives all log messages that pass the configured level threshold
399
+ * (unless `callbackIgnoresLevel` is true, then receives all messages).
400
+ *
401
+ * Common use cases:
402
+ * - Send logs to external analytics service
403
+ * - Store logs in memory for debugging
404
+ * - Filter and forward to remote logging system
405
+ * - Display logs in custom UI component
406
+ *
407
+ * @param level - Severity level of this message
408
+ * @param context - Context/module identifier (e.g., 'Router', 'Plugin')
409
+ * @param message - Main log message text
410
+ * @param args - Additional arguments (objects, errors, etc.)
411
+ *
412
+ * @example
413
+ * ```ts
414
+ * const analyticsCallback: LogCallback = (level, context, message, ...args) => {
415
+ * sendToAnalytics({
416
+ * severity: level,
417
+ * module: context,
418
+ * text: message,
419
+ * metadata: args
420
+ * });
421
+ * };
422
+ *
423
+ * logger.configure({ callback: analyticsCallback });
424
+ * ```
425
+ */
426
+ export type LogCallback = (level: LogLevel$1, context: string, message: string, ...args: unknown[]) => void;
427
+ /**
428
+ * Logger configuration interface.
429
+ *
430
+ * Controls both console output and callback behavior.
431
+ *
432
+ * @example
433
+ * ```ts
434
+ * // Minimal configuration
435
+ * const config: LoggerConfig = {
436
+ * level: 'warn-error'
437
+ * };
438
+ *
439
+ * // Full configuration with callback
440
+ * const config: LoggerConfig = {
441
+ * level: 'error-only',
442
+ * callback: (level, context, message) => {
443
+ * // Send all errors to monitoring service
444
+ * },
445
+ * callbackIgnoresLevel: false // Callback respects 'error-only' level
446
+ * };
447
+ * ```
448
+ */
449
+ export interface LoggerConfig {
450
+ /**
451
+ * Minimum severity level to display in console.
452
+ *
453
+ * Messages below this threshold are filtered out from console output.
454
+ * Does not affect callback unless `callbackIgnoresLevel` is false.
455
+ *
456
+ * @default 'all'
457
+ */
458
+ level: LogLevelConfig;
459
+ /**
460
+ * Optional callback function for custom log processing.
461
+ *
462
+ * Called for each log message (subject to `callbackIgnoresLevel` setting).
463
+ * Can be undefined to disable callback processing.
464
+ *
465
+ * @default undefined
466
+ */
467
+ callback?: LogCallback | undefined;
468
+ /**
469
+ * Whether callback should receive ALL messages regardless of level threshold.
470
+ *
471
+ * - `false` (default): Callback only receives messages that pass level threshold
472
+ * (same filtering as console output)
473
+ * - `true`: Callback receives ALL messages, even those filtered from console
474
+ * (useful for analytics where you want to track everything)
475
+ *
476
+ * @default false
477
+ *
478
+ * @example
479
+ * ```ts
480
+ * // Scenario: Show only errors in console, but track ALL logs in analytics
481
+ * logger.configure({
482
+ * level: 'error-only', // Console: only errors
483
+ * callback: sendToAnalytics,
484
+ * callbackIgnoresLevel: true // Callback: receives log/warn/error
485
+ * });
486
+ * ```
487
+ */
488
+ callbackIgnoresLevel?: boolean;
489
+ }
490
+ /**
491
+ * Extended build result that includes segments for path building.
492
+ * Used internally to avoid duplicate getSegmentsByName calls.
493
+ *
494
+ * @param segments - Route segments from getSegmentsByName (typed as unknown[] for cross-package compatibility)
495
+ * @internal
496
+ */
497
+ export interface BuildStateResultWithSegments<P extends Params = Params> {
498
+ readonly state: RouteTreeState<P>;
499
+ readonly segments: readonly unknown[];
500
+ }
501
+ /**
502
+ * Route configuration.
503
+ */
504
+ export interface Route<Dependencies extends DefaultDependencies = DefaultDependencies> {
505
+ [key: string]: unknown;
506
+ /** Route name (dot-separated for nested routes). */
507
+ name: string;
508
+ /** URL path pattern for this route. */
509
+ path: string;
510
+ /** Factory function that returns a guard for route activation. */
511
+ canActivate?: ActivationFnFactory<Dependencies>;
512
+ /**
513
+ * Redirects navigation to another route.
514
+ *
515
+ * IMPORTANT: forwardTo creates a URL alias, not a transition chain.
516
+ * Guards (canActivate) on the source route are NOT executed.
517
+ * Only guards on the final destination are executed.
518
+ *
519
+ * This matches Vue Router and Angular Router behavior.
520
+ *
521
+ * @example
522
+ * // Correct: guard on target
523
+ * { name: "old", path: "/old", forwardTo: "new" }
524
+ * { name: "new", path: "/new", canActivate: myGuard }
525
+ *
526
+ * // Wrong: guard on source (will be ignored with warning)
527
+ * { name: "old", path: "/old", forwardTo: "new", canActivate: myGuard }
528
+ */
529
+ forwardTo?: string;
530
+ /** Nested child routes. */
531
+ children?: Route<Dependencies>[];
532
+ /** Encodes state params to URL params. */
533
+ encodeParams?: (stateParams: Params) => Params;
534
+ /** Decodes URL params to state params. */
535
+ decodeParams?: (pathParams: Params) => Params;
536
+ /**
537
+ * Default parameters for this route.
538
+ *
539
+ * @remarks
540
+ * **Type Contract:**
541
+ * The type of defaultParams MUST match the expected params type P
542
+ * when using `router.makeState<P>()` or `router.navigate<P>()`.
543
+ *
544
+ * These values are merged into state.params when creating route states.
545
+ * Missing URL params are filled from defaultParams.
546
+ *
547
+ * @example
548
+ * ```typescript
549
+ * // Define route with pagination defaults
550
+ * {
551
+ * name: "users",
552
+ * path: "/users",
553
+ * defaultParams: { page: 1, limit: 10 }
554
+ * }
555
+ *
556
+ * // Navigate without specifying page/limit
557
+ * router.navigate("users", { filter: "active" });
558
+ * // Result: state.params = { page: 1, limit: 10, filter: "active" }
559
+ *
560
+ * // Correct typing — include defaultParams properties
561
+ * type UsersParams = { page: number; limit: number; filter?: string };
562
+ * ```
563
+ */
564
+ defaultParams?: Params;
565
+ }
566
+ /**
567
+ * Router configuration options.
568
+ *
569
+ * Note: For input, use `Partial<Options>` as all fields have defaults.
570
+ * After initialization, `getOptions()` returns resolved `Options` with all fields populated.
571
+ */
572
+ export interface Options {
573
+ /**
574
+ * Default route to navigate to on start.
575
+ * Empty string means no default route.
576
+ *
577
+ * @default ""
578
+ */
579
+ defaultRoute: string;
580
+ /**
581
+ * Default parameters for the default route.
582
+ *
583
+ * @default {}
584
+ */
585
+ defaultParams: Params;
586
+ /**
587
+ * How to handle trailing slashes in URLs.
588
+ * - "strict": Route must match exactly
589
+ * - "never": Always remove trailing slash
590
+ * - "always": Always add trailing slash
591
+ * - "preserve": Keep as provided
592
+ *
593
+ * @default "preserve"
594
+ */
595
+ trailingSlash: "strict" | "never" | "always" | "preserve";
596
+ /**
597
+ * Whether route names are case-sensitive.
598
+ *
599
+ * @default false
600
+ */
601
+ caseSensitive: boolean;
602
+ /**
603
+ * How to encode URL parameters.
604
+ * - "default": Standard encoding
605
+ * - "uri": URI encoding (encodeURI)
606
+ * - "uriComponent": Component encoding (encodeURIComponent)
607
+ * - "none": No encoding
608
+ *
609
+ * @default "default"
610
+ */
611
+ urlParamsEncoding: "default" | "uri" | "uriComponent" | "none";
612
+ /**
613
+ * How to handle query parameters.
614
+ *
615
+ * @default "loose"
616
+ */
617
+ queryParamsMode: QueryParamsMode;
618
+ /**
619
+ * Query parameter parsing options.
620
+ *
621
+ * @default undefined
622
+ */
623
+ queryParams?: QueryParamsOptions;
624
+ /**
625
+ * Allow matching routes that don't exist.
626
+ * When true, unknown routes navigate without error.
627
+ *
628
+ * @default true
629
+ */
630
+ allowNotFound: boolean;
631
+ /**
632
+ * Rewrite path on successful match.
633
+ *
634
+ * @default false
635
+ */
636
+ rewritePathOnMatch: boolean;
637
+ /**
638
+ * Logger configuration.
639
+ *
640
+ * @default undefined
641
+ */
642
+ logger?: Partial<LoggerConfig>;
643
+ }
644
+ export type ActivationFn = (toState: State, fromState: State | undefined, done: DoneFn) => boolean | Promise<boolean | object | void> | State | void;
645
+ export type ActivationFnFactory<Dependencies extends DefaultDependencies = DefaultDependencies> = (router: Router<Dependencies>, getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K]) => ActivationFn;
646
+ export type DefaultDependencies = object;
647
+ /**
648
+ * Configuration update options for updateRoute().
649
+ * All properties are optional. Set to null to remove the configuration.
650
+ */
651
+ export interface RouteConfigUpdate<Dependencies extends DefaultDependencies = DefaultDependencies> {
652
+ /** Set to null to remove forwardTo */
653
+ forwardTo?: string | null;
654
+ /** Set to null to remove defaultParams */
655
+ defaultParams?: Params | null;
656
+ /** Set to null to remove decoder */
657
+ decodeParams?: ((params: Params) => Params) | null;
658
+ /** Set to null to remove encoder */
659
+ encodeParams?: ((params: Params) => Params) | null;
660
+ /** Set to null to remove canActivate */
661
+ canActivate?: ActivationFnFactory<Dependencies> | null;
662
+ }
663
+ export interface Router<Dependencies extends DefaultDependencies = DefaultDependencies> {
664
+ [key: symbol]: unknown;
665
+ [key: string]: unknown;
666
+ addRoute: (routes: Route<Dependencies>[] | Route<Dependencies>) => Router<Dependencies>;
667
+ isActiveRoute: (name: string, params?: Params, strictEquality?: boolean, ignoreQueryParams?: boolean) => boolean;
668
+ buildPath: (route: string, params?: Params) => string;
669
+ /**
670
+ * Internal path builder that accepts pre-computed segments.
671
+ * Avoids duplicate getSegmentsByName call when segments are already available.
672
+ *
673
+ * @param segments - Route segments from getSegmentsByName (typed as unknown[] for cross-package compatibility)
674
+ * @internal
675
+ */
676
+ buildPathWithSegments: (route: string, params: Params, segments: readonly unknown[]) => string;
677
+ matchPath: <P extends Params = Params, MP extends Params = Params>(path: string, source?: string) => State<P, MP> | undefined;
678
+ /**
679
+ * Sets the root path for the router.
680
+ *
681
+ * @param rootPath - New root path
682
+ * @returns void
683
+ */
684
+ setRootPath: (rootPath: string) => void;
685
+ /**
686
+ * Gets the current root path for the router.
687
+ *
688
+ * @returns Current root path
689
+ */
690
+ getRootPath: () => string;
691
+ /**
692
+ * Removes route configurations (metadata only).
693
+ *
694
+ * @description
695
+ * Clears associated configurations for a route (decoders, encoders, defaultParams,
696
+ * forwardMap). Note: RouteNode doesn't provide API for actual route removal from tree.
697
+ * Consider recreating the router with filtered routes for full removal.
698
+ *
699
+ * @param name - Route name to remove configurations for
700
+ * @returns Router instance for chaining
701
+ * @throws {TypeError} If name is not a valid route name
702
+ */
703
+ removeRoute: (name: string) => Router<Dependencies>;
704
+ /**
705
+ * Clears all routes from the router.
706
+ *
707
+ * @description
708
+ * Removes all route definitions, configurations, and lifecycle handlers.
709
+ * Preserves: listeners, plugins, dependencies, options, state.
710
+ * After clearing, you can add new routes with addRoute().
711
+ *
712
+ * @returns Router instance for chaining
713
+ *
714
+ * @example
715
+ * // Clear all routes and add new ones
716
+ * router.clearRoutes().addRoute([
717
+ * { name: 'home', path: '/' },
718
+ * { name: 'about', path: '/about' }
719
+ * ]);
720
+ */
721
+ clearRoutes: () => Router<Dependencies>;
722
+ /**
723
+ * Retrieves the full configuration of a route by name.
724
+ *
725
+ * @description
726
+ * Reconstructs the Route object from internal storage, including:
727
+ * - name, path, children from route definitions
728
+ * - forwardTo from forwardMap
729
+ * - defaultParams, decodeParams, encodeParams from config
730
+ * - canActivate from lifecycle factories
731
+ *
732
+ * Note: Custom properties (meta, etc.) are NOT preserved and won't be returned.
733
+ *
734
+ * @param name - Route name (dot-notation for nested routes, e.g., 'users.profile')
735
+ * @returns Route configuration or undefined if not found
736
+ *
737
+ * @throws {TypeError} If name is not a valid route name
738
+ *
739
+ * @example
740
+ * const route = router.getRoute('users.profile');
741
+ * if (route) {
742
+ * console.log(route.path, route.defaultParams);
743
+ * }
744
+ */
745
+ getRoute: (name: string) => Route<Dependencies> | undefined;
746
+ /**
747
+ * Checks if a route exists in the router.
748
+ *
749
+ * @description
750
+ * Lightweight check for route existence without constructing the full Route object.
751
+ * More efficient than `!!router.getRoute(name)` when you only need to check existence.
752
+ *
753
+ * @param name - Route name to check (supports dot notation for nested routes)
754
+ * @returns true if route exists, false otherwise
755
+ *
756
+ * @throws {TypeError} If name is not a valid route name
757
+ *
758
+ * @example
759
+ * if (router.hasRoute('users.profile')) {
760
+ * router.navigate('users.profile', { id: 123 });
761
+ * }
762
+ */
763
+ hasRoute: (name: string) => boolean;
764
+ /**
765
+ * Updates configuration properties of an existing route.
766
+ *
767
+ * @description
768
+ * Only updates configuration (forwardTo, defaultParams, encoders, decoders, canActivate).
769
+ * Does NOT update path or children (requires tree rebuild - use removeRoute + addRoute).
770
+ *
771
+ * Set a property to null to remove it. For example:
772
+ * - `{ forwardTo: null }` removes the forwardTo redirect
773
+ * - `{ canActivate: null }` removes the canActivate guard
774
+ *
775
+ * @param name - Route name to update
776
+ * @param updates - Partial route configuration to apply
777
+ * @returns Router instance for chaining
778
+ *
779
+ * @throws {TypeError} If name is not a valid route name
780
+ * @throws {ReferenceError} If route does not exist
781
+ * @throws {Error} If updating forwardTo with invalid target or cycle
782
+ *
783
+ * @example
784
+ * // Add/update configuration
785
+ * router.updateRoute('users', {
786
+ * defaultParams: { page: 1 },
787
+ * canActivate: authGuard
788
+ * });
789
+ *
790
+ * @example
791
+ * // Remove configuration
792
+ * router.updateRoute('oldRoute', { forwardTo: null });
793
+ */
794
+ updateRoute: (name: string, updates: RouteConfigUpdate<Dependencies>) => Router<Dependencies>;
795
+ /**
796
+ * Returns a copy of the previous state before the last navigation.
797
+ *
798
+ * @returns Copy of the previous state or undefined if no previous state exists
799
+ */
800
+ getPreviousState: () => State | undefined;
801
+ shouldUpdateNode: (nodeName: string) => (toState: State, fromState?: State) => boolean;
802
+ /**
803
+ * Returns a copy of the router's current configuration options.
804
+ *
805
+ * @description
806
+ * Provides read-only access to the router's configuration by returning a shallow
807
+ * copy of all current options. This method is useful for inspecting settings,
808
+ * debugging, passing configuration to other components, or conditional logic
809
+ * based on router configuration.
810
+ *
811
+ * @returns A shallow copy of the current router options. Each call returns
812
+ * a new object with all configuration properties.
813
+ *
814
+ * @example
815
+ * // Basic usage - inspect configuration
816
+ * const options = router.getOptions();
817
+ * console.log('Case sensitive:', options.caseSensitive);
818
+ * console.log('Trailing slash mode:', options.trailingSlash);
819
+ *
820
+ * @see {@link setOption} for modifying individual options
821
+ */
822
+ getOptions: () => Options;
823
+ /**
824
+ * Sets a single configuration option value.
825
+ *
826
+ * @description
827
+ * Modifies an individual router configuration option with type-safe validation.
828
+ * This method can ONLY be used before calling router.start() - after the router
829
+ * starts, all options become immutable and any attempt to modify them will throw
830
+ * an error.
831
+ *
832
+ * @param option - The name of the option to set. Must be a valid option key.
833
+ * @param value - The new value for the option. Type must match the option's expected type.
834
+ *
835
+ * @returns The router instance for method chaining.
836
+ *
837
+ * @throws {Error} If router is already started (router.isStarted() === true)
838
+ * @throws {ReferenceError} If option name doesn't exist in Options interface
839
+ * @throws {TypeError} If value type doesn't match expected type for the option
840
+ * @throws {TypeError} If object option receives non-plain object (array, date, class, null)
841
+ *
842
+ * @see {@link getOptions} for retrieving current options
843
+ */
844
+ setOption: (option: keyof Options, value: Options[keyof Options]) => Router<Dependencies>;
845
+ makeState: <P extends Params = Params, MP extends Params = Params>(name: string, params?: P, path?: string, meta?: StateMetaInput<MP>, forceId?: number) => State<P, MP>;
846
+ makeNotFoundState: (path: string, options?: NavigationOptions) => State;
847
+ getState: <P extends Params = Params, MP extends Params = Params>() => State<P, MP> | undefined;
848
+ setState: <P extends Params = Params, MP extends Params = Params>(state?: State<P, MP>) => void;
849
+ areStatesEqual: (state1: State | undefined, state2: State | undefined, ignoreQueryParams?: boolean) => boolean;
850
+ areStatesDescendants: (parentState: State, childState: State) => boolean;
851
+ forwardState: <P extends Params = Params>(routeName: string, routeParams: P) => SimpleState<P>;
852
+ buildState: (routeName: string, routeParams: Params) => RouteTreeState | undefined;
853
+ /**
854
+ * Builds state with segments for internal use.
855
+ * Avoids duplicate getSegmentsByName call when path building is needed.
856
+ *
857
+ * @internal
858
+ */
859
+ buildStateWithSegments: <P extends Params = Params>(routeName: string, routeParams: P) => BuildStateResultWithSegments<P> | undefined;
860
+ /**
861
+ * Checks whether the router has been successfully started.
862
+ *
863
+ * @description
864
+ * Returns true if the router has been started via the `start()` method and has not
865
+ * been stopped. When the router is started, it means:
866
+ * - Initial navigation has been attempted
867
+ * - Event listeners can receive navigation events
868
+ * - The router is ready to handle navigation requests
869
+ *
870
+ * Note: A router being "started" doesn't guarantee that the initial navigation
871
+ * succeeded. Use `getState()` to verify if a valid state exists.
872
+ *
873
+ * @returns true if the router is started, false otherwise
874
+ *
875
+ * @example
876
+ * // Check if router is started before navigation
877
+ * if (!router.isStarted()) {
878
+ * router.start('/home');
879
+ * }
880
+ *
881
+ * @example
882
+ * // Conditional logic based on router state
883
+ * const isReady = router.isStarted() && router.getState() !== undefined;
884
+ */
885
+ isStarted: () => boolean;
886
+ /**
887
+ * Checks if the router is active (starting or started).
888
+ *
889
+ * @description
890
+ * Returns true if the router is in the process of starting or has already started.
891
+ * This is different from `isStarted()` which only returns true after successful
892
+ * initial transition.
893
+ *
894
+ * This method is primarily used internally by the transition module to determine
895
+ * if transitions should be cancelled. During the initial start transition,
896
+ * `isStarted()` is false but `isActive()` is true, allowing the transition to proceed.
897
+ *
898
+ * @returns true if router is active (starting or started), false if stopped
899
+ *
900
+ * @example
901
+ * // Check if router is active (even during initial start)
902
+ * if (router.isActive()) {
903
+ * console.log('Router is active');
904
+ * }
905
+ *
906
+ * @see {@link isStarted} to check if initial transition completed
907
+ * @see https://github.com/greydragon888/real-router/issues/50
908
+ */
909
+ isActive: () => boolean;
910
+ /**
911
+ * Checks if a navigation transition is currently in progress.
912
+ *
913
+ * @description
914
+ * Returns true when the router is actively processing a navigation request.
915
+ * This includes the time spent executing guards (canDeactivate, canActivate)
916
+ * and middleware functions.
917
+ *
918
+ * Useful for:
919
+ * - Preventing route modifications during navigation
920
+ * - Showing loading indicators
921
+ * - Debouncing navigation requests
922
+ *
923
+ * @returns true if navigation is in progress, false otherwise
924
+ *
925
+ * @example
926
+ * // Prevent route removal during navigation
927
+ * if (router.isNavigating()) {
928
+ * console.warn('Cannot modify routes during navigation');
929
+ * return;
930
+ * }
931
+ *
932
+ * @example
933
+ * // Show loading state
934
+ * const isLoading = router.isNavigating();
935
+ *
936
+ * @remarks
937
+ * After FSM migration (RFC-2), this will use RouterState.TRANSITIONING
938
+ * for more granular state tracking.
939
+ */
940
+ isNavigating: () => boolean;
941
+ /**
942
+ * Initializes the router and performs the initial navigation.
943
+ *
944
+ * @description
945
+ * Starts the router and navigates to the initial route. This method must be called
946
+ * before any navigation operations. The initial route can be specified as a path
947
+ * string, a state object, or determined by the default route option.
948
+ *
949
+ * @param startPathOrState - Optional. The initial route as a path string or state object.
950
+ * If omitted, uses the default route if configured.
951
+ * @param done - Optional. Callback function called when start completes or fails.
952
+ *
953
+ * @returns The router instance for method chaining
954
+ *
955
+ * @example
956
+ * router.start()
957
+ *
958
+ * @example
959
+ * router.start('/users/123', (err, state) => {
960
+ * if (!err) console.log('Started at:', state.name)
961
+ * })
962
+ */
963
+ start: (() => Router<Dependencies>) & ((done: DoneFn) => Router<Dependencies>) & ((startPathOrState: string | State) => Router<Dependencies>) & ((startPathOrState: string | State, done: DoneFn) => Router<Dependencies>);
964
+ /**
965
+ * Stops the router and cleans up its state.
966
+ *
967
+ * @description
968
+ * Stops the router, clearing the current state and preventing further navigation.
969
+ * This method should be called when the router is no longer needed, typically
970
+ * during application cleanup or before unmounting.
971
+ *
972
+ * If the router is not started, this method does nothing and returns silently.
973
+ *
974
+ * @returns The router instance for method chaining
975
+ *
976
+ * @example
977
+ * // Stop the router
978
+ * router.stop();
979
+ *
980
+ * @fires ROUTER_STOP - When the router is successfully stopped
981
+ *
982
+ * @see {@link start} to restart the router
983
+ * @see {@link isStarted} to check router status
984
+ */
985
+ stop: () => Router<Dependencies>;
986
+ canDeactivate: (name: string, canDeactivateHandler: ActivationFnFactory<Dependencies> | boolean) => Router<Dependencies>;
987
+ clearCanDeactivate: (name: string, silent?: boolean) => Router<Dependencies>;
988
+ canActivate: (name: string, canActivateHandler: ActivationFnFactory<Dependencies> | boolean) => Router<Dependencies>;
989
+ clearCanActivate: (name: string, silent?: boolean) => Router<Dependencies>;
990
+ getLifecycleFactories: () => [
991
+ Record<string, ActivationFnFactory<Dependencies>>,
992
+ Record<string, ActivationFnFactory<Dependencies>>
993
+ ];
994
+ getLifecycleFunctions: () => [
995
+ Map<string, ActivationFn>,
996
+ Map<string, ActivationFn>
997
+ ];
998
+ /**
999
+ * Registers plugin(s) to extend router functionality through lifecycle event subscriptions.
1000
+ *
1001
+ * @description
1002
+ * Provides the primary mechanism for adding cross-cutting functionality to the router
1003
+ * through a plugin-based architecture. Plugins can react to router lifecycle events
1004
+ * (start/stop, navigation transitions) without modifying the core router code.
1005
+ *
1006
+ * @param plugins - Variable number of plugin factory functions.
1007
+ * Each factory receives (router, getDependency) and must return
1008
+ * a Plugin object with optional event handler methods.
1009
+ *
1010
+ * @returns Unsubscribe function that removes only the plugins registered in this call.
1011
+ * Calls teardown() for each plugin and removes all event subscriptions.
1012
+ * Safe to call multiple times (subsequent calls are no-op with error logging).
1013
+ *
1014
+ * @throws {TypeError} If any plugin parameter is not a function
1015
+ * @throws {TypeError} If any factory returns a non-object value
1016
+ * @throws {TypeError} If returned plugin object contains unknown properties
1017
+ * @throws {Error} If any plugin factory is already registered (duplicate by reference)
1018
+ * @throws {Error} If total plugin count would exceed 50 after registration
1019
+ * @throws {*} Rethrows any exception thrown by factory functions (after rollback)
1020
+ *
1021
+ * @example
1022
+ * // Basic logging plugin
1023
+ * const loggingPlugin = (router) => ({
1024
+ * onTransitionStart: (toState, fromState) => {
1025
+ * console.log(`Navigating: ${fromState?.name} → ${toState.name}`);
1026
+ * },
1027
+ * onTransitionSuccess: (toState) => {
1028
+ * console.log(`Arrived at: ${toState.name}`);
1029
+ * },
1030
+ * });
1031
+ *
1032
+ * @example
1033
+ * // Remove plugin
1034
+ * const remove = router.usePlugin(loggerPlugin)
1035
+ * remove() // Stop logging
1036
+ *
1037
+ * const unsubscribe = router.usePlugin(loggingPlugin);
1038
+ *
1039
+ * @see {@link getPlugins} for retrieving registered plugin factories (internal use)
1040
+ * @see {@link useMiddleware} for navigation-specific middleware (different from plugins)
1041
+ * @see {@link addEventListener} for low-level event subscription
1042
+ */
1043
+ usePlugin: (...plugins: PluginFactory<Dependencies>[]) => Unsubscribe;
1044
+ getPlugins: () => PluginFactory<Dependencies>[];
1045
+ /**
1046
+ * Registers middleware functions to execute during navigation transitions.
1047
+ *
1048
+ * @description
1049
+ * Provides the primary mechanism for adding custom logic to the navigation pipeline
1050
+ * through middleware functions. Middleware execute after lifecycle hooks (canActivate/
1051
+ * canDeactivate) and can modify or validate state during route transitions.
1052
+ *
1053
+ * @param middlewares - Variable number of middleware factory functions.
1054
+ * Each factory receives (router, getDependency) and must return
1055
+ * a middleware function with signature:
1056
+ * (toState, fromState, done) => void | Promise<State | boolean | void>
1057
+ *
1058
+ * @returns Unsubscribe function that removes only the middleware registered in this call.
1059
+ * Safe to call multiple times (subsequent calls are no-op with warnings).
1060
+ *
1061
+ * @throws {TypeError} If any middleware parameter is not a function
1062
+ * @throws {TypeError} If any factory returns a non-function value
1063
+ * @throws {Error} If any middleware factory is already registered (duplicate)
1064
+ * @throws {Error} If total middleware count would exceed 50 after registration
1065
+ * @throws {*} Rethrows any exception thrown by factory functions during initialization
1066
+ *
1067
+ * @example
1068
+ *
1069
+ * router.useMiddleware((router) => (toState, fromState, done) => {
1070
+ * console.log('Navigating to:', toState.name)
1071
+ * done()
1072
+ * })
1073
+ *
1074
+ * @example
1075
+ * // Auth middleware
1076
+ * router.useMiddleware(() => (toState, fromState, done) => {
1077
+ * if (toState.meta.requiresAuth && !isAuthenticated()) {
1078
+ * done({ redirect: { name: 'login' } })
1079
+ * } else {
1080
+ * done()
1081
+ * }
1082
+ * })
1083
+ */
1084
+ useMiddleware: (...middlewares: MiddlewareFactory<Dependencies>[]) => Unsubscribe;
1085
+ clearMiddleware: () => Router<Dependencies>;
1086
+ getMiddlewareFactories: () => MiddlewareFactory<Dependencies>[];
1087
+ getMiddlewareFunctions: () => Middleware[];
1088
+ setDependency: <K extends keyof Dependencies & string>(dependencyName: K, dependency: Dependencies[K]) => Router<Dependencies>;
1089
+ /**
1090
+ * Sets multiple dependencies at once using a batch operation.
1091
+ *
1092
+ * @description
1093
+ * Provides an optimized way to register multiple dependencies in a single operation.
1094
+ * This method is the primary approach for initializing dependencies during router
1095
+ * setup and for bulk updates of the dependency container.
1096
+ *
1097
+ * @param deps - Object containing dependencies to set. Must be a plain object.
1098
+ * Properties with undefined values are ignored (not set).
1099
+ * All other values (including null, false, 0) are set.
1100
+ *
1101
+ * @returns The router instance for method chaining.
1102
+ *
1103
+ * @throws {TypeError} If deps is not a plain object (e.g., class instance, array, null)
1104
+ * @throws {TypeError} If any property in deps has a getter (accessor property)
1105
+ * @throws {Error} If total dependencies would exceed 100 after the operation
1106
+ *
1107
+ * @example
1108
+ * // Basic batch setup
1109
+ * router.setDependencies({
1110
+ * api: new ApiService(),
1111
+ * logger: console,
1112
+ * cache: cacheService,
1113
+ * });
1114
+ *
1115
+ * @see {@link setDependency} for setting individual dependencies
1116
+ * @see {@link getDependencies} for retrieving all dependencies
1117
+ * @see {@link resetDependencies} for clearing all dependencies
1118
+ * @see {@link removeDependency} for removing specific dependencies
1119
+ */
1120
+ setDependencies: (deps: Dependencies) => Router<Dependencies>;
1121
+ /**
1122
+ * Retrieves a dependency from the router's dependency container by name.
1123
+ *
1124
+ * @description
1125
+ * Provides type-safe access to dependencies registered in the router's dependency
1126
+ * injection container. This method is the primary way to access services and utilities
1127
+ * within middleware, plugins, and lifecycle hooks.
1128
+ *
1129
+ * @template K - The dependency name, must be a key of the Dependencies type
1130
+ *
1131
+ * @param key - The name of the dependency to retrieve. Must be a string and
1132
+ * must exist in the Dependencies type definition.
1133
+ *
1134
+ * @returns The dependency value with proper type inference based on Dependencies type.
1135
+ * Returns the same reference on repeated calls (not a copy).
1136
+ *
1137
+ * @throws {TypeError} If the key parameter is not a string type
1138
+ * (e.g., number, object, null, undefined)
1139
+ * @throws {ReferenceError} If no dependency exists with the given name.
1140
+ * Error message includes the dependency name for debugging.
1141
+ *
1142
+ * @example
1143
+ * // Basic usage - direct access
1144
+ * interface MyDependencies {
1145
+ * api: ApiService;
1146
+ * logger: Logger;
1147
+ * }
1148
+ *
1149
+ * router.setDependency('api', new ApiService());
1150
+ * const api = router.getDependency('api'); // Type: ApiService
1151
+ *
1152
+ * @see {@link getDependencies} for retrieving all dependencies at once
1153
+ * @see {@link setDependency} for registering dependencies
1154
+ * @see {@link hasDependency} for checking dependency existence
1155
+ * @see {@link removeDependency} for removing dependencies
1156
+ */
1157
+ getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K];
1158
+ /**
1159
+ * Returns a shallow copy of all registered dependencies.
1160
+ *
1161
+ * @description
1162
+ * Retrieves a snapshot of all dependencies currently stored in the router's
1163
+ * dependency container. The method creates a new object on each call, protecting
1164
+ * the internal container structure from external modifications.
1165
+ *
1166
+ * @returns A new object containing all dependencies as key-value pairs.
1167
+ * Returns {} if no dependencies are registered.
1168
+ *
1169
+ * @example
1170
+ * // Basic usage - get all dependencies
1171
+ * const deps = router.getDependencies();
1172
+ * console.log(deps); // { api: ApiService, logger: Logger }
1173
+ *
1174
+ * @see {@link getDependency} for accessing individual dependencies
1175
+ * @see {@link setDependency} for adding dependencies
1176
+ * @see {@link setDependencies} for batch setting
1177
+ * @see {@link removeDependency} for removing dependencies
1178
+ * @see {@link resetDependencies} for clearing all dependencies
1179
+ * @see {@link hasDependency} for checking dependency existence
1180
+ */
1181
+ getDependencies: () => Partial<Dependencies>;
1182
+ /**
1183
+ * Removes a dependency from the router's dependency container.
1184
+ *
1185
+ * @description
1186
+ * Safely removes a registered dependency by name. This method is idempotent,
1187
+ * meaning it can be called multiple times with the same dependency name without
1188
+ * causing errors. If the dependency doesn't exist, a warning is logged but
1189
+ * execution continues normally.
1190
+ *
1191
+ * @param dependencyName - The name of the dependency to remove.
1192
+ * Type-safe in TypeScript (must be a key of Dependencies).
1193
+ * Safe to call with non-existent dependencies (logs warning).
1194
+ *
1195
+ * @returns The router instance for method chaining.
1196
+ *
1197
+ * @example
1198
+ * // Basic removal
1199
+ * router.setDependency('tempLogger', logger);
1200
+ * router.removeDependency('tempLogger');
1201
+ *
1202
+ * console.log(router.hasDependency('tempLogger')); // false
1203
+ *
1204
+ * @see {@link setDependency} for adding dependencies
1205
+ * @see {@link getDependency} for retrieving dependencies (throws after removal)
1206
+ * @see {@link hasDependency} for checking dependency existence (returns false after removal)
1207
+ * @see {@link resetDependencies} for removing all dependencies at once
1208
+ */
1209
+ removeDependency: (dependencyName: keyof Dependencies) => Router<Dependencies>;
1210
+ /**
1211
+ * Checks whether a dependency with the specified name exists in the router.
1212
+ *
1213
+ * @description
1214
+ * Provides a safe way to check for dependency existence without throwing errors.
1215
+ * This method is essential for implementing conditional logic based on optional
1216
+ * dependencies and for validating dependency setup before accessing them.
1217
+ *
1218
+ * @param dependencyName - The name of the dependency to check.
1219
+ * Type-safe in TypeScript (must be a key of Dependencies).
1220
+ * In runtime, non-string primitives are coerced to strings.
1221
+ *
1222
+ * @returns true if the dependency exists (even with falsy values like null/false/0),
1223
+ * false if the dependency has never been set or was removed.
1224
+ *
1225
+ * @example
1226
+ * // Basic existence check
1227
+ * router.setDependency('api', apiService);
1228
+ * console.log(router.hasDependency('api')); // true
1229
+ * console.log(router.hasDependency('nonexistent')); // false
1230
+ *
1231
+ * const ready = hasAllDependencies(router, ['api', 'auth', 'logger']);
1232
+ *
1233
+ * @see {@link getDependency} for retrieving dependencies (throws if not found)
1234
+ * @see {@link getDependencies} for getting all dependencies at once
1235
+ * @see {@link setDependency} for registering dependencies
1236
+ * @see {@link removeDependency} for removing dependencies
1237
+ */
1238
+ hasDependency: (dependencyName: keyof Dependencies) => boolean;
1239
+ /**
1240
+ * Removes all dependencies from the router's dependency container.
1241
+ *
1242
+ * @description
1243
+ * Performs a complete reset of the dependency container by removing all registered
1244
+ * dependencies at once. This is a destructive operation that clears the entire
1245
+ * dependency state, effectively returning the container to its initial empty state.
1246
+ *
1247
+ * @returns The router instance for method chaining.
1248
+ *
1249
+ * @example
1250
+ * // Basic reset
1251
+ * router.setDependency('logger', logger);
1252
+ * router.setDependency('api', apiService);
1253
+ * router.setDependency('cache', cacheService);
1254
+ *
1255
+ * router.resetDependencies();
1256
+ *
1257
+ * console.log(router.getDependencies()); // {}
1258
+ * console.log(router.hasDependency('logger')); // false
1259
+ *
1260
+ * @see {@link setDependency} for adding individual dependencies
1261
+ * @see {@link setDependencies} for setting multiple dependencies at once
1262
+ * @see {@link removeDependency} for removing individual dependencies
1263
+ * @see {@link getDependencies} for getting all current dependencies
1264
+ * @see {@link hasDependency} for checking if specific dependency exists
1265
+ */
1266
+ resetDependencies: () => Router<Dependencies>;
1267
+ /**
1268
+ * Invokes all registered event listeners for a specific router lifecycle event.
1269
+ *
1270
+ * @internal
1271
+ * This is an internal method used by the router core. It should NOT be called
1272
+ * directly by application code. Events are automatically dispatched by router
1273
+ * methods like start(), stop(), navigate(), etc.
1274
+ *
1275
+ * @description
1276
+ * Synchronously invokes all registered event listeners for a given router lifecycle
1277
+ * event in their registration order (FIFO). The method provides critical guarantees:
1278
+ * fail-safe execution, state immutability, recursion protection, and iteration safety.
1279
+ *
1280
+ * @param eventName - The event type to invoke listeners for.
1281
+ * Must be one of: ROUTER_START, ROUTER_STOP, TRANSITION_START,
1282
+ * TRANSITION_SUCCESS, TRANSITION_ERROR, TRANSITION_CANCEL.
1283
+ *
1284
+ * @param toState - Target state for navigation events. Deep frozen before passing.
1285
+ * Optional for ROUTER_START/STOP, required for TRANSITION_*.
1286
+ *
1287
+ * @param fromState - Source state for navigation events. Deep frozen before passing.
1288
+ * Optional for all events (undefined for first navigation).
1289
+ *
1290
+ * @param arg - Additional event data:
1291
+ * - NavigationOptions for TRANSITION_SUCCESS
1292
+ * - RouterError for TRANSITION_ERROR
1293
+ * - undefined for other events
1294
+ *
1295
+ * @returns void - Method performs side effects (invokes listeners)
1296
+ *
1297
+ * @throws {Error} If recursion depth exceeds MAX_DEPTH (5) for the event type
1298
+ * @throws {TypeError} If state validation fails (invalid State object structure)
1299
+ *
1300
+ * @see {@link addEventListener} for subscribing to router events (public API)
1301
+ * @see {@link removeEventListener} for unsubscribing from events (public API)
1302
+ * @see {@link usePlugin} for plugin-based event handling (recommended)
1303
+ */
1304
+ invokeEventListeners: (eventName: EventToNameMap[EventsKeys], toState?: State, fromState?: State, arg?: RouterError | NavigationOptions) => void;
1305
+ /**
1306
+ * Checks if there are any listeners registered for a given event.
1307
+ *
1308
+ * @internal
1309
+ * Used for performance optimization to skip event emission when no listeners exist.
1310
+ * This avoids the overhead of argument validation and event dispatch when
1311
+ * there are no subscribers.
1312
+ *
1313
+ * @param eventName - The event type to check for listeners. Must be one of the
1314
+ * predefined event constants.
1315
+ *
1316
+ * @returns true if at least one listener is registered for the event, false otherwise.
1317
+ * Returns false for invalid event names instead of throwing.
1318
+ *
1319
+ * @example
1320
+ * ```typescript
1321
+ * // Skip expensive event emission if no listeners
1322
+ * if (router.hasListeners(events.TRANSITION_ERROR)) {
1323
+ * router.invokeEventListeners(events.TRANSITION_ERROR, toState, fromState, error);
1324
+ * }
1325
+ * ```
1326
+ *
1327
+ * @see {@link invokeEventListeners} for the internal event dispatch mechanism
1328
+ * @see {@link addEventListener} for registering event listeners
1329
+ */
1330
+ hasListeners: (eventName: EventToNameMap[EventsKeys]) => boolean;
1331
+ /**
1332
+ * Removes a previously registered event listener from the router's event system.
1333
+ *
1334
+ * @internal
1335
+ * This is a low-level internal API used primarily by the router core and plugin system.
1336
+ * For application code, use the unsubscribe function returned by addEventListener instead.
1337
+ *
1338
+ * @description
1339
+ * Removes a specific event listener callback from the router's event system, preventing it
1340
+ * from being invoked on future events. This method is a fundamental part of the subscription
1341
+ * lifecycle, ensuring proper cleanup and preventing memory leaks.
1342
+ *
1343
+ * @param eventName - The event type to remove the listener from. Must be one of the
1344
+ * predefined event constants (events.ROUTER_START, events.TRANSITION_SUCCESS, etc.).
1345
+ * TypeScript enforces valid event names at compile time.
1346
+ *
1347
+ * @param cb - The callback function to remove. Must be the **exact same reference** that was
1348
+ * passed to addEventListener. Using a different function (even with identical code)
1349
+ * will not match and will log a warning.
1350
+ *
1351
+ * @returns void - No return value (follows DOM API convention). Use the unsubscribe function
1352
+ * from addEventListener if you need guaranteed cleanup confirmation.
1353
+ *
1354
+ * @throws {Error} If eventName is not a valid event constant
1355
+ * @throws {TypeError} If cb is not a function (null, undefined, string, etc.)
1356
+ *
1357
+ * @see {@link addEventListener} for registering event listeners (returns unsubscribe function)
1358
+ * @see {@link usePlugin} for plugin-based event handling (handles cleanup automatically)
1359
+ * @see {@link invokeEventListeners} for the internal event dispatch mechanism
1360
+ */
1361
+ removeEventListener: (eventName: EventToNameMap[EventsKeys], cb: Plugin$1[keyof Plugin$1]) => void;
1362
+ /**
1363
+ * Registers an event listener for a specific router lifecycle event.
1364
+ *
1365
+ * @description
1366
+ * Provides type-safe subscription to router events with automatic memory leak protection
1367
+ * and state immutability guarantees. This is the low-level API for event handling - for
1368
+ * most use cases, consider using plugins (usePlugin) or the subscribe method instead.
1369
+ *
1370
+ * @param eventName - The event type to listen for. Must be one of the predefined
1371
+ * event constants (events.ROUTER_START, events.TRANSITION_SUCCESS, etc.).
1372
+ * TypeScript enforces valid event names at compile time.
1373
+ *
1374
+ * @param cb - The callback function to invoke when the event occurs. Signature must
1375
+ * match the event type. TypeScript enforces correct callback signature.
1376
+ * All State parameters will be deeply frozen before passing.
1377
+ *
1378
+ * @returns Unsubscribe function that removes the listener. Safe to call multiple times
1379
+ * (subsequent calls log warning but don't throw). Closure captures event and
1380
+ * callback for automatic cleanup.
1381
+ *
1382
+ * @throws {Error} If the same callback is already registered for this event
1383
+ * @throws {Error} If listener count reaches 10000 (hard limit, indicates memory leak)
1384
+ * @throws {Error} If eventName is not a valid event constant
1385
+ * @throws {TypeError} If callback is not a function
1386
+ *
1387
+ * @example
1388
+ * const unsub = router.addEventListener('TRANSITION_START', (toState, fromState) => {
1389
+ * console.log('Starting navigation:', toState.name)
1390
+ * })
1391
+ *
1392
+ * @example
1393
+ * router.addEventListener('TRANSITION_ERROR', (toState, fromState, err) => {
1394
+ * console.error('Navigation failed:', err)
1395
+ * })
1396
+ *
1397
+ * @see {@link usePlugin} for plugin-based event handling (recommended)
1398
+ * @see {@link subscribe} for simplified navigation event subscription
1399
+ * @see {@link removeEventListener} for manual listener removal (use unsubscribe instead)
1400
+ */
1401
+ addEventListener: (eventName: EventToNameMap[EventsKeys], cb: Plugin$1[keyof Plugin$1]) => Unsubscribe;
1402
+ forward: (fromRoute: string, toRoute: string) => Router<Dependencies>;
1403
+ /**
1404
+ * Navigates to the specified route.
1405
+ *
1406
+ * @description
1407
+ * Performs a navigation transition from the current route to the target route.
1408
+ * The method handles route activation/deactivation lifecycle, middleware execution,
1409
+ * and state management. Navigation can be customized with options and supports
1410
+ * both synchronous and asynchronous operations.
1411
+ *
1412
+ * @param routeName - The name of the route to navigate to. Must be a registered route.
1413
+ * @param routeParams - Optional parameters to pass to the route. These will be used
1414
+ * to build the route path and will be available in the route state.
1415
+ * @param options - Optional navigation options to control the transition behavior
1416
+ * @param done - Optional callback function called when navigation completes or fails.
1417
+ * Receives error as first argument and state as second.
1418
+ *
1419
+ * @returns A cancel function that can be called to abort the navigation.
1420
+ * Calling cancel will trigger the TRANSITION_CANCELLED event.
1421
+ *
1422
+ * @example
1423
+ * // Simple navigation
1424
+ * router.navigate('home');
1425
+ *
1426
+ * @example
1427
+ * // Navigation with parameters
1428
+ * router.navigate('user', { id: '123' });
1429
+ *
1430
+ * @example
1431
+ * // Cancellable navigation
1432
+ * const cancel = router.navigate('slow-route', {}, {}, (err) => {
1433
+ * if (err?.code === 'CANCELLED') console.log('Navigation was cancelled');
1434
+ * });
1435
+ * // Later...
1436
+ * cancel(); // Abort the navigation
1437
+ *
1438
+ * @throws {RouterError} With code 'NOT_STARTED' if router is not started
1439
+ * @throws {RouterError} With code 'ROUTE_NOT_FOUND' if route doesn't exist
1440
+ * @throws {RouterError} With code 'SAME_STATES' if navigating to current route without reload
1441
+ * @throws {RouterError} With code 'CANNOT_DEACTIVATE' if canDeactivate guard prevents navigation
1442
+ * @throws {RouterError} With code 'CANNOT_ACTIVATE' if canActivate guard prevents navigation
1443
+ * @throws {RouterError} With code 'TRANSITION_ERR' if middleware throws an error
1444
+ */
1445
+ navigate: ((routeName: string) => CancelFn) & ((routeName: string, routeParams: Params) => CancelFn) & ((routeName: string, done: DoneFn) => CancelFn) & ((routeName: string, routeParams: Params, options: NavigationOptions) => CancelFn) & ((routeName: string, routeParams: Params, done: DoneFn) => CancelFn) & ((routeName: string, routeParams: Params, options: NavigationOptions, done: DoneFn) => CancelFn);
1446
+ /**
1447
+ * Navigates to the default route if one is configured.
1448
+ *
1449
+ * Uses `defaultRoute` and `defaultParams` from router options.
1450
+ * Returns no-op if no default route configured.
1451
+ *
1452
+ * @description
1453
+ * Convenience method that navigates to the route specified in router options
1454
+ * as `defaultRoute` with `defaultParams`. If no default route is configured,
1455
+ * this method does nothing and returns a no-op cancel function.
1456
+ *
1457
+ * @param opts - Optional navigation options (same as navigate method)
1458
+ * @param done - Optional callback function called when navigation completes
1459
+ *
1460
+ * @returns A cancel function that can be called to abort the navigation.
1461
+ * Returns no-op function if no default route is configured.
1462
+ *
1463
+ * @see {@link navigate} for detailed behavior and error handling
1464
+ */
1465
+ navigateToDefault: (() => CancelFn) & ((done: DoneFn) => CancelFn) & ((opts: NavigationOptions) => CancelFn) & ((opts: NavigationOptions, done: DoneFn) => CancelFn);
1466
+ /**
1467
+ * Internal navigation method that accepts pre-built state.
1468
+ *
1469
+ * @internal
1470
+ * @description
1471
+ * This is an internal method used by the router and plugins to perform navigation
1472
+ * with a pre-built state object. It should not be used directly by application code.
1473
+ * Use `navigate()` instead for normal navigation operations.
1474
+ *
1475
+ * The method provides control over TRANSITION_SUCCESS event emission through the
1476
+ * `emitSuccess` parameter, allowing internal callers to manage event emission
1477
+ * themselves to avoid duplicate events.
1478
+ *
1479
+ * @param toState - The target state to navigate to (pre-built)
1480
+ * @param fromState - The current state to navigate from
1481
+ * @param opts - Navigation options
1482
+ * @param callback - Callback function called when navigation completes
1483
+ * @param emitSuccess - Whether to emit TRANSITION_SUCCESS event (false for internal use)
1484
+ *
1485
+ * @returns A cancel function that can be called to abort the navigation
1486
+ *
1487
+ * @private
1488
+ */
1489
+ navigateToState: (toState: State, fromState: State | undefined, opts: NavigationOptions, callback: DoneFn, emitSuccess: boolean) => CancelFn;
1490
+ /**
1491
+ * Subscribes to successful navigation transitions.
1492
+ *
1493
+ * @description
1494
+ * Registers a listener function that will be called whenever a navigation transition
1495
+ * completes successfully. This is the primary method for integrating UI frameworks
1496
+ * with the router to react to route changes.
1497
+ *
1498
+ * @param listener - Function called on each successful navigation transition.
1499
+ * Receives { route, previousRoute } where:
1500
+ * - route: The new state (frozen/immutable)
1501
+ * - previousRoute: The previous state (frozen/immutable, undefined on first navigation)
1502
+ *
1503
+ * @returns Unsubscribe function to remove the listener. Safe to call multiple times.
1504
+ *
1505
+ * @example
1506
+ * // Basic subscription
1507
+ * const unsubscribe = router.subscribe(({ route, previousRoute }) => {
1508
+ * console.log(`Navigation: ${previousRoute?.name || 'init'} → ${route.name}`);
1509
+ * });
1510
+ *
1511
+ * // Later, cleanup
1512
+ * unsubscribe();
1513
+ *
1514
+ * @example
1515
+ *
1516
+ * // Analytics
1517
+ * router.subscribe(({ route }) => {
1518
+ * analytics.track('page_view', { path: route.path })
1519
+ * })
1520
+ *
1521
+ * @throws {TypeError} If listener is not a function. Error message includes
1522
+ * hint about using Symbol.observable for Observable pattern.
1523
+ *
1524
+ * @see {@link addEventListener} for low-level event subscription
1525
+ * @see {@link usePlugin} for subscribing to all router events
1526
+ * @see {@link navigate} for triggering navigation
1527
+ */
1528
+ subscribe: (listener: SubscribeFn) => Unsubscribe;
1529
+ /**
1530
+ * Creates a clone of this router with the same configuration.
1531
+ *
1532
+ * @description
1533
+ * Creates a new router instance with the same routes, options, middleware,
1534
+ * plugins, and lifecycle handlers as the original. The cloned router is
1535
+ * independent of the original - changes to one do not affect the other.
1536
+ *
1537
+ * Use cases:
1538
+ * - Server-side rendering (SSR): Create a fresh router for each request
1539
+ * - Testing: Clone router to test different scenarios without side effects
1540
+ * - Feature flags: Create alternative router configurations
1541
+ *
1542
+ * What is cloned:
1543
+ * - Route tree structure (via rootNode)
1544
+ * - Router options (defaultRoute, trailingSlash, etc.)
1545
+ * - Middleware factories
1546
+ * - Plugin factories
1547
+ * - Lifecycle factories (canActivate, canDeactivate)
1548
+ * - Config (encoders, decoders, defaultParams, forwardMap)
1549
+ *
1550
+ * What is NOT cloned:
1551
+ * - Current state (cloned router starts fresh)
1552
+ * - Event listeners (subscribers must re-register)
1553
+ * - Started status (cloned router is not started)
1554
+ *
1555
+ * @param dependencies - Optional new dependencies for the cloned router.
1556
+ * If not provided, uses empty dependencies.
1557
+ *
1558
+ * @returns A new router instance with the same configuration.
1559
+ *
1560
+ * @example
1561
+ * // Basic cloning
1562
+ * const router = createRouter(routes, options);
1563
+ * const clonedRouter = router.clone();
1564
+ *
1565
+ * @example
1566
+ * // SSR: Clone with request-specific dependencies
1567
+ * app.get('*', (req, res) => {
1568
+ * const ssrRouter = router.clone({ request: req });
1569
+ * ssrRouter.start(req.url, (err, state) => {
1570
+ * // Render with state...
1571
+ * });
1572
+ * });
1573
+ *
1574
+ * @example
1575
+ * // Testing: Clone for isolated test
1576
+ * it('should navigate to user', () => {
1577
+ * const testRouter = router.clone();
1578
+ * testRouter.start();
1579
+ * testRouter.navigate('user', { id: '123' });
1580
+ * expect(testRouter.getState().name).toBe('user');
1581
+ * });
1582
+ */
1583
+ clone: (dependencies?: Dependencies) => Router<Dependencies>;
1584
+ }
1585
+ interface Plugin$1 {
1586
+ onStart?: () => void;
1587
+ onStop?: () => void;
1588
+ onTransitionStart?: (toState: State, fromState?: State) => void;
1589
+ onTransitionCancel?: (toState: State, fromState?: State) => void;
1590
+ onTransitionError?: (toState: State | undefined, fromState: State | undefined, err: RouterError) => void;
1591
+ onTransitionSuccess?: (toState: State, fromState: State | undefined, opts: NavigationOptions) => void;
1592
+ teardown?: () => void;
1593
+ }
1594
+ export type Middleware = ActivationFn;
1595
+ export type MiddlewareFactory<Dependencies extends DefaultDependencies = DefaultDependencies> = (router: Router<Dependencies>, getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K]) => Middleware;
1596
+ export type PluginFactory<Dependencies extends DefaultDependencies = DefaultDependencies> = (router: Router<Dependencies>, getDependency: <K extends keyof Dependencies>(key: K) => Dependencies[K]) => Plugin$1;
1597
+ export interface SubscribeState {
1598
+ route: State;
1599
+ previousRoute?: State | undefined;
1600
+ }
1601
+ export type SubscribeFn = (state: SubscribeState) => void;
65
1602
  /**
66
1603
  * Creates a logger-plugin for real-router.
67
1604
  *
@@ -85,7 +1622,7 @@ interface LoggerPluginConfig {
85
1622
  * }));
86
1623
  * ```
87
1624
  */
88
- declare function loggerPluginFactory(options?: Partial<LoggerPluginConfig>): PluginFactory;
1625
+ export declare function loggerPluginFactory(options?: Partial<LoggerPluginConfig>): PluginFactory;
89
1626
  /**
90
1627
  * Default logger-plugin instance with standard configuration.
91
1628
  * Provided for backward compatibility with existing code.
@@ -94,6 +1631,6 @@ declare function loggerPluginFactory(options?: Partial<LoggerPluginConfig>): Plu
94
1631
  * // Use default configuration
95
1632
  * router.usePlugin(loggerPlugin);
96
1633
  */
97
- declare const loggerPlugin: PluginFactory;
1634
+ export declare const loggerPlugin: PluginFactory;
98
1635
 
99
- export { type LogLevel, type LoggerPluginConfig, loggerPlugin, loggerPluginFactory };
1636
+ export {};