@real-router/persistent-params-plugin 0.1.4 → 0.1.6

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