ui5-lib-guard-router 1.6.2 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/{dist/.ui5 → .ui5}/build-manifest.json +56 -8
  2. package/CHANGELOG.md +197 -0
  3. package/README.md +695 -327
  4. package/dist/index.d.ts +9 -5
  5. package/dist/resources/ui5/guard/router/.library +1 -1
  6. package/dist/resources/ui5/guard/router/GuardConfig-dbg.js +222 -0
  7. package/dist/resources/ui5/guard/router/GuardConfig-dbg.js.map +1 -0
  8. package/dist/resources/ui5/guard/router/GuardConfig.d.ts +89 -0
  9. package/dist/resources/ui5/guard/router/GuardConfig.d.ts.map +1 -0
  10. package/dist/resources/ui5/guard/router/GuardConfig.js +2 -0
  11. package/dist/resources/ui5/guard/router/GuardConfig.js.map +1 -0
  12. package/dist/resources/ui5/guard/router/GuardModules-dbg.js +253 -0
  13. package/dist/resources/ui5/guard/router/GuardModules-dbg.js.map +1 -0
  14. package/dist/resources/ui5/guard/router/GuardModules.d.ts +72 -0
  15. package/dist/resources/ui5/guard/router/GuardModules.d.ts.map +1 -0
  16. package/dist/resources/ui5/guard/router/GuardModules.js +2 -0
  17. package/dist/resources/ui5/guard/router/GuardModules.js.map +1 -0
  18. package/dist/resources/ui5/guard/router/GuardPipeline-dbg.js +125 -122
  19. package/dist/resources/ui5/guard/router/GuardPipeline-dbg.js.map +1 -1
  20. package/dist/resources/ui5/guard/router/GuardPipeline.d.ts +45 -26
  21. package/dist/resources/ui5/guard/router/GuardPipeline.d.ts.map +1 -1
  22. package/dist/resources/ui5/guard/router/GuardPipeline.js +1 -1
  23. package/dist/resources/ui5/guard/router/GuardPipeline.js.map +1 -1
  24. package/dist/resources/ui5/guard/router/NavigationOutcome-dbg.js +3 -3
  25. package/dist/resources/ui5/guard/router/NavigationOutcome-dbg.js.map +1 -1
  26. package/dist/resources/ui5/guard/router/NavigationOutcome.d.ts +3 -3
  27. package/dist/resources/ui5/guard/router/NavigationOutcome.d.ts.map +1 -1
  28. package/dist/resources/ui5/guard/router/NavigationOutcome.js.map +1 -1
  29. package/dist/resources/ui5/guard/router/PatternTree-dbg.js +156 -0
  30. package/dist/resources/ui5/guard/router/PatternTree-dbg.js.map +1 -0
  31. package/dist/resources/ui5/guard/router/PatternTree.d.ts +71 -0
  32. package/dist/resources/ui5/guard/router/PatternTree.d.ts.map +1 -0
  33. package/dist/resources/ui5/guard/router/PatternTree.js +2 -0
  34. package/dist/resources/ui5/guard/router/PatternTree.js.map +1 -0
  35. package/dist/resources/ui5/guard/router/RouteMeta-dbg.js +84 -0
  36. package/dist/resources/ui5/guard/router/RouteMeta-dbg.js.map +1 -0
  37. package/dist/resources/ui5/guard/router/RouteMeta.d.ts +33 -0
  38. package/dist/resources/ui5/guard/router/RouteMeta.d.ts.map +1 -0
  39. package/dist/resources/ui5/guard/router/RouteMeta.js +2 -0
  40. package/dist/resources/ui5/guard/router/RouteMeta.js.map +1 -0
  41. package/dist/resources/ui5/guard/router/Router-dbg.js +900 -1033
  42. package/dist/resources/ui5/guard/router/Router-dbg.js.map +1 -1
  43. package/dist/resources/ui5/guard/router/Router.d.ts +362 -212
  44. package/dist/resources/ui5/guard/router/Router.d.ts.map +1 -1
  45. package/dist/resources/ui5/guard/router/Router.js +1 -1
  46. package/dist/resources/ui5/guard/router/Router.js.map +1 -1
  47. package/dist/resources/ui5/guard/router/library-dbg.js +1 -1
  48. package/dist/resources/ui5/guard/router/library-dbg.js.map +1 -1
  49. package/dist/resources/ui5/guard/router/library-preload.js +8 -4
  50. package/dist/resources/ui5/guard/router/library-preload.js.map +1 -1
  51. package/dist/resources/ui5/guard/router/library.js +1 -1
  52. package/dist/resources/ui5/guard/router/library.js.map +1 -1
  53. package/dist/resources/ui5/guard/router/manifest.json +5 -2
  54. package/dist/resources/ui5/guard/router/types-dbg.js.map +1 -1
  55. package/dist/resources/ui5/guard/router/types.d.ts +94 -39
  56. package/dist/resources/ui5/guard/router/types.d.ts.map +1 -1
  57. package/package.json +10 -6
  58. package/src/GuardConfig.ts +272 -0
  59. package/src/GuardModules.ts +249 -0
  60. package/src/GuardPipeline.ts +158 -129
  61. package/src/NavigationOutcome.ts +3 -3
  62. package/src/PatternTree.ts +145 -0
  63. package/src/RouteMeta.ts +82 -0
  64. package/src/Router.ts +1110 -1150
  65. package/src/manifest.json +5 -2
  66. package/src/types.ts +79 -22
  67. package/tsconfig.json +0 -11
@@ -1,17 +1,59 @@
1
1
  declare module "ui5/guard/router/Router" {
2
2
  import MobileRouter from "sap/m/routing/Router";
3
- import type { ComponentTargetParameters } from "sap/ui/core/routing/Router";
3
+ import History from "sap/ui/core/routing/History";
4
+ import type { ComponentTargetParameters, Router$RouteMatchedEvent } from "sap/ui/core/routing/Router";
5
+ import type Route from "sap/ui/core/routing/Route";
4
6
  import type { $RouteSettings } from "sap/ui/core/routing/Route";
5
- import type { GuardFn, GuardNavToOptions, GuardRouter, GuardLoading, Inheritance, LeaveGuardFn, NavToPreflightMode, NavigationResult, Router$NavigationSettledEvent, RouteGuardConfig, UnknownRouteRegistrationPolicy } from "./types";
7
+ import type UIComponent from "sap/ui/core/UIComponent";
8
+ import type { GuardFn, GuardNavToOptions, GuardRouter, GuardRouterConfig, LeaveGuardFn, NavigationResult, Router$NavigationSettledEvent, RouteGuardConfig } from "ui5/guard/router/types";
9
+ import { type GuardDescriptor } from "ui5/guard/router/GuardConfig";
6
10
  const HistoryDirection: any;
7
- const LOG_COMPONENT = "ui5.guard.router.Router";
11
+ type Direction = ReturnType<History["getDirection"]>;
12
+ /**
13
+ * The router config as UI5 gets it: the caller's object without `guardRouter`. It is a view and
14
+ * not a copy, because UIComponent adds `targetParent` (the ID of the root view) to its config
15
+ * object after it has constructed the router, and the native router reads it from that object.
16
+ */
17
+ function withoutGuardRouter(config: object): object;
8
18
  function isRouteGuardConfig(guard: GuardFn | RouteGuardConfig): guard is RouteGuardConfig;
19
+ /** A step through the browser history (back, forward): how far it went, and the URL it arrived at. */
20
+ interface HistoryStep {
21
+ readonly offset: number;
22
+ readonly href: string;
23
+ }
24
+ /** The step through the browser history that brought the browser to the URL it shows, if a step did. */
25
+ let lastStep: HistoryStep | null;
26
+ /** The URL of a step that a router is taking back, until the browser reports the next URL change. */
27
+ let undoneHref: string | null;
28
+ /** What it takes to undo the hash change that an uncommitted navigation arrived with. */
29
+ interface HashChangeUndo {
30
+ /** The hash of the root hash changer after the first change that this takes back. */
31
+ readonly first: string;
32
+ /**
33
+ * The hash of the root hash changer before that change, with the hashes of nested routers.
34
+ * The root hash changer reports it with the change, after the routers have parsed their part.
35
+ */
36
+ fullHash: string | undefined;
37
+ /** The hash of the root hash changer after the change. */
38
+ readonly shown: string;
39
+ /** Whether the router has started to put the URL back, and the hash change that does it is still to come. */
40
+ started: boolean;
41
+ /** The step through the browser history that the change was, if it was one. */
42
+ readonly step: HistoryStep | null;
43
+ }
44
+ /** A manifest guard entry of a route, with the declared entry it stems from: itself, or the entry of an ancestor route. */
45
+ interface ManifestGuardDescriptor extends GuardDescriptor {
46
+ readonly source: GuardDescriptor;
47
+ }
9
48
  /** Snapshot of an in-flight navigation being evaluated by the guard pipeline. */
10
49
  interface NavigationAttempt {
11
50
  readonly hash: string;
12
- readonly route: string;
13
51
  readonly controller: AbortController;
14
52
  readonly generation: number;
53
+ /** Whether the URL shows a hash that never committed, so that it must be restored unless this attempt moves it. */
54
+ readonly restoreHash: boolean;
55
+ /** How the browser got to the hash that started the navigation; `undefined` after `navTo()` or `parse()`. */
56
+ readonly direction: Direction | undefined;
15
57
  }
16
58
  interface PhaseIdle {
17
59
  readonly kind: "idle";
@@ -19,128 +61,42 @@ declare module "ui5/guard/router/Router" {
19
61
  interface PhaseEvaluating {
20
62
  readonly kind: "evaluating";
21
63
  readonly attempt: NavigationAttempt;
64
+ /** Whether the navigation waits for async guards: the native router would be matching its route by now. */
65
+ readonly postponed?: true;
22
66
  }
23
67
  interface PhaseCommitting {
24
68
  readonly kind: "committing";
25
- readonly hash: string;
26
69
  readonly route: string;
70
+ /** The hash of the route: `parse()` commits the navigation when it receives this hash. */
71
+ readonly hash: string;
27
72
  readonly origin: "preflight" | "redirect" | "parse";
73
+ /** How the browser got to the history entry that the route replaces (see {@link RedirectChainContext.direction}). */
74
+ readonly direction?: Direction;
75
+ /** Whether the URL showed a hash that never committed when `navTo()` wrote the hash (see {@link NavigationAttempt.restoreHash}). */
76
+ readonly restoreHash: boolean;
77
+ /** What the root hash changer showed before `navTo()` wrote the hash: the write is undone with it. */
78
+ readonly writtenOver?: string;
28
79
  }
29
- type RouterPhase = PhaseIdle | PhaseEvaluating | PhaseCommitting;
30
- const IDLE: PhaseIdle;
31
- /** Type guard for plain objects. */
32
- function isRecord(value: unknown): value is Record<string, unknown>;
33
- /** Create a type-narrowing validator for a finite set of string literal values. */
34
- function isOneOf<T extends string>(...values: T[]): (v: unknown) => v is T;
35
- const isUnknownRouteRegistrationPolicy: (v: unknown) => v is UnknownRouteRegistrationPolicy;
36
- const isNavToPreflightMode: (v: unknown) => v is NavToPreflightMode;
37
- const isGuardLoading: (v: unknown) => v is GuardLoading;
38
- const isInheritance: (v: unknown) => v is Inheritance;
39
- /** Matches a standalone optional (`:param:`) or rest (`:param*:`) segment. */
40
- const OPTIONAL_OR_REST_SEGMENT: RegExp;
41
80
  /**
42
- * Strips inline query and optional-query suffixes from a segment.
43
- *
44
- * UI5 (crossroads.js) allows query parameters to attach directly to a
45
- * path segment without a `/` separator:
46
- * - `product{?query}` → mandatory query on `product`
47
- * - `product:?query:` → optional query on `product`
48
- * - `{id}{?query}` → mandatory param + mandatory query
49
- *
50
- * For pattern-tree ancestry we only care about the path portion,
51
- * so these suffixes are stripped.
52
- */
53
- function stripInlineQuery(seg: string): string;
54
- /**
55
- * Extract mandatory path segments from a UI5 route pattern.
56
- *
57
- * Splits on `/`, strips inline query suffixes, then drops empty segments,
58
- * standalone optional (`:param:`), and rest (`:param*:`) segments.
81
+ * An allowed navigation waits for UI5 to write its hash. With component targets UI5 does that
82
+ * once the nested components are loaded, and never if one of them fails to load.
59
83
  */
60
- function patternSegments(pattern: string): string[];
61
- /**
62
- * Check if `ancestorPattern` is a URL-tree ancestor of `candidatePattern`.
63
- *
64
- * Both patterns are reduced to their mandatory path segments and compared
65
- * positionally. Mandatory parameter segments (`{paramA}`, `{paramB}`) are
66
- * treated as equivalent regardless of name, so `employees/{empId}` is
67
- * recognized as an ancestor of `employees/{id}/resume`.
68
- */
69
- function isPatternAncestor(ancestorPattern: string, candidatePattern: string): boolean;
70
- /** Parsed guard declaration from the manifest `guards` block. */
71
- interface GuardDescriptor {
72
- readonly route: string;
73
- readonly type: "enter" | "leave";
74
- readonly modulePath: string;
75
- readonly name: string;
76
- readonly exportKey?: string;
84
+ interface PhaseAwaitingHash {
85
+ readonly kind: "awaitingHash";
86
+ /** The phase that commits the navigation when `parse()` receives its hash. */
87
+ readonly commit: PhaseCommitting;
77
88
  }
78
- /**
79
- * Resolve a guard module path to a slash-separated AMD module path.
80
- *
81
- * Inspired by `sap.ui.core.routing.Target._getEffectiveObjectName()`,
82
- * which skips namespace prepending for `"module:"`-prefixed paths. This
83
- * function goes further: it also converts dots to slashes in a single
84
- * step, so both dot notation (`module:some.lib.guard`) and slash
85
- * notation (`module:some/lib/guard`) are accepted.
86
- *
87
- * - Paths prefixed with `"module:"` are treated as absolute (the prefix
88
- * is stripped, dots become slashes).
89
- * - All other paths are prefixed with the component namespace, then dots
90
- * become slashes.
91
- */
92
- function resolveGuardModulePath(dotPath: string, componentNamespace: string): string;
93
- /**
94
- * Split a manifest guard entry on the first `#` to separate the module path
95
- * from an optional export key, then derive a human-readable guard name.
96
- */
97
- function parseGuardEntry(entry: string, componentNamespace: string): {
98
- modulePath: string;
99
- name: string;
100
- exportKey?: string;
101
- };
102
- interface ResolvedGuardExport {
103
- readonly name: string;
104
- readonly fn: GuardFn;
105
- }
106
- /** Log a warning about a guard module entry in the manifest. */
107
- function guardWarning(modulePath: string, detail: string): void;
108
- /**
109
- * Detect the export shape of a loaded guard module and extract guard functions.
110
- *
111
- * Shapes:
112
- * - function → single guard
113
- * - Array → ordered guards (non-functions warned and skipped)
114
- * - plain object → named guards in key order (non-functions warned and skipped)
115
- *
116
- * When `exportKey` is set, only the matching export is returned.
117
- * When `exportKey` is set on a function export, the key is ignored with a debug warning.
118
- */
119
- function resolveModuleExports(moduleExport: unknown, modulePath: string, descriptorName: string, exportKey?: string): ResolvedGuardExport[];
120
- /**
121
- * Parse the `guards` block from the guardRouter config into an array of
122
- * {@link GuardDescriptor} objects.
123
- *
124
- * Handles:
125
- * - `"*"` key with `string[]` -> global enter guards
126
- * - Route name with `string[]` (shorthand) -> enter guards
127
- * - Route name with `{ enter: [...], leave: [...] }` -> enter + leave guards
128
- * - `"*"` with object form -> warn, treat enter as global
129
- * - `"*"` leave -> warn, skip (global leave guards not supported)
130
- * - Invalid entries -> warn, skip
131
- */
132
- function parseGuardDescriptors(guards: unknown, componentNamespace: string): GuardDescriptor[];
133
- interface ResolvedGuardRouterOptions {
134
- readonly unknownRouteRegistration: UnknownRouteRegistrationPolicy;
135
- readonly navToPreflight: NavToPreflightMode;
136
- readonly guardLoading: GuardLoading;
137
- readonly inheritance: Inheritance;
89
+ /** A navigation that did not commit waits for the URL to be back before it settles. */
90
+ interface PhaseRestoring {
91
+ readonly kind: "restoring";
92
+ readonly result: NavigationResult;
93
+ /** Whether the previous hash is written once UI5 has reported the hash change to every router. */
94
+ readonly awaitsReport?: true;
95
+ /** What a redirect to the route that is shown still has to do once the navigation has settled. */
96
+ readonly whenBack?: () => void;
138
97
  }
139
- const DEFAULT_OPTIONS: ResolvedGuardRouterOptions;
140
- function applyOption<K extends keyof ResolvedGuardRouterOptions>(raw: Record<string, unknown>, key: K, guard: (v: unknown) => v is ResolvedGuardRouterOptions[K], target: {
141
- -readonly [P in keyof ResolvedGuardRouterOptions]: ResolvedGuardRouterOptions[P];
142
- }): void;
143
- function normalizeGuardRouterOptions(raw: unknown): ResolvedGuardRouterOptions;
98
+ type RouterPhase = PhaseIdle | PhaseEvaluating | PhaseCommitting | PhaseAwaitingHash | PhaseRestoring;
99
+ const IDLE: PhaseIdle;
144
100
  /** Maximum number of hops in a redirect chain before it is treated as a loop. */
145
101
  const MAX_REDIRECT_DEPTH = 10;
146
102
  /** State threaded through a redirect chain. */
@@ -149,12 +105,19 @@ declare module "ui5/guard/router/Router" {
149
105
  visited: Set<string>;
150
106
  /** Hash of the originally attempted navigation (for settlement / hash restore). */
151
107
  readonly attemptedHash: string | undefined;
152
- /** Whether to restore the hash on block (true for parse path, false for preflight). */
108
+ /** Whether to restore the hash on block (see {@link NavigationAttempt.restoreHash}). */
153
109
  readonly restoreHash: boolean;
154
110
  /** Original source route (the route the user occupies). */
155
111
  readonly fromRoute: string;
156
112
  /** Original source hash (the hash the user occupies). */
157
113
  readonly fromHash: string;
114
+ /** Whether the target replaces the current history entry: as the `navTo()` call asked, always after a hash change. */
115
+ readonly replace: boolean | undefined;
116
+ /**
117
+ * How the browser got to the history entry that the target replaces, for the title history
118
+ * of UI5 (see {@link Router._alignTitleHistory}); `undefined` after `navTo()` or `parse()`.
119
+ */
120
+ readonly direction: Direction | undefined;
158
121
  /** Shared AbortSignal from the original navigation. */
159
122
  readonly signal: AbortSignal;
160
123
  /** Shared generation counter from the original navigation. */
@@ -170,8 +133,8 @@ declare module "ui5/guard/router/Router" {
170
133
  * loading, or event firing occurs.
171
134
  *
172
135
  * Two entry points feed the same pipeline:
173
- * - `navTo()` runs guards as a preflight check. Blocked or redirected
174
- * navigations never change the hash or push history entries.
136
+ * - `navTo()` runs guards as a preflight check. A blocked navigation
137
+ * never changes the hash; a redirected one only writes its final target.
175
138
  * - `parse()` runs guards as a fallback for browser back/forward, URL
176
139
  * bar entry, and direct hash changes where the hash has already changed
177
140
  * before guards can intercept.
@@ -194,16 +157,87 @@ declare module "ui5/guard/router/Router" {
194
157
  private _phase;
195
158
  private _parseGeneration;
196
159
  private _suppressedHash;
160
+ /** How to undo the hash change of the pending navigation (see {@link _undoHashChange}). */
161
+ private _undo;
162
+ /** The hash that the hash changer of this router is reporting, until `parse()` receives it. */
163
+ private _reportedHash;
164
+ /** The hash that the hash changer of this router reported last, reports that are out of date aside. */
165
+ private _lastReport;
166
+ /** Whether the hash changer shows a later hash than the one it is reporting (see {@link _onHashReported}). */
167
+ private _reportOutdated;
168
+ /** The global hash changer that {@link _onRootHashChanged} is attached to, behind the listener of UI5 that informs the routers. */
169
+ private _rootHashChanger;
170
+ /** The route that was current when the router stopped: `initialize(true)` resumes it, as UI5 does. */
171
+ private _stoppedRoute;
197
172
  private _settlementResolvers;
198
173
  private _lastSettlement;
199
174
  private _pendingGuardDescriptors;
200
175
  private _sourceDescriptors;
176
+ /** The manifest guards registered for a route, by which `addRoute()` places the guards a route inherits then. */
177
+ private _manifestGuards;
201
178
  private _destroyed;
202
- private _manifestMeta;
203
- private _runtimeMeta;
204
- private _resolvedMetaCache;
179
+ /** What UI5 itself wrote to `_bMatchingProcessStarted` (see {@link _mirrorMatchingProcess}). */
180
+ private _nativeMatching;
181
+ /** Promises that wait for the `routeMatched` of a match that has not started (see {@link attachRouteMatched}). */
182
+ private _matchWaiters;
183
+ /**
184
+ * Set while block-mode guard modules load; `start` says whether to initialize once they have,
185
+ * `ignoreInitialHash` is the argument of the `initialize()` call that asked for it.
186
+ */
187
+ private _blockLoad;
188
+ private _meta;
189
+ /** Recorded by `addRoute()`, which the UI5 constructor calls before field setup; `declare` keeps field setup from resetting it. */
205
190
  private _routeNames;
206
- constructor(...args: ConstructorParameters<typeof MobileRouter>);
191
+ /** Routes that also match when an earlier route has matched the hash (`greedy: true`). */
192
+ private _greedyRouteNames;
193
+ private readonly _ownerComponent;
194
+ constructor(routes?: object | object[], config?: GuardRouterConfig, owner?: UIComponent, targetsConfig?: object);
195
+ /**
196
+ * Report a navigation that waits for async guards as a route match in progress, through the
197
+ * UI5-private member `_bMatchingProcessStarted` of `sap.ui.core.routing.Router`. UI5 reads it
198
+ * to tell whether the router of a nested component is still matching; without this, a parent
199
+ * route would count the component as displayed before its first route matched. The router does
200
+ * not write the member: it replaces it with an accessor that keeps what UI5 writes in
201
+ * {@link _nativeMatching} and also reads `true` while a navigation is postponed.
202
+ *
203
+ * See docs/reference/architecture.md ("UI5 Internals the Router Relies On") for the UI5 code this
204
+ * relies on, and docs/reference/upstream-parity.md for the tests that pin it.
205
+ */
206
+ private _mirrorMatchingProcess;
207
+ /** Whether a route match is in progress: in UI5, or postponed until async guards have decided. */
208
+ private _isMatching;
209
+ /**
210
+ * Attach an event handler for the `routeMatched` event, as the native router does. In addition,
211
+ * remember a Promise resolve function ({@link isPromiseResolver}) that is subscribed while the
212
+ * router is not initialized or a match is in progress: that is how a UI5 component target
213
+ * waits for this router. UI5 relies on a match always ending in `routeMatched`, which a
214
+ * navigation that guards block, fail or cancel never fires, so {@link _settleMatchWaiters}
215
+ * resolves the Promise then. Application code that subscribes a Promise resolve function under
216
+ * the same condition is treated alike.
217
+ *
218
+ * See docs/reference/architecture.md ("UI5 Internals the Router Relies On") for the UI5 code this
219
+ * relies on, and docs/reference/upstream-parity.md for the tests that pin it.
220
+ *
221
+ * @override sap.ui.core.routing.Router#attachRouteMatched
222
+ * @since 1.7.0
223
+ */
224
+ attachRouteMatched(oData: object, fnFunction: (evt: Router$RouteMatchedEvent) => void, oListener?: object): this;
225
+ attachRouteMatched(fnFunction: (evt: Router$RouteMatchedEvent) => void, oListener?: object): this;
226
+ /**
227
+ * Decide what becomes of the Promises that wait for a `routeMatched`
228
+ * (see {@link attachRouteMatched}). Runs in a microtask after a settlement, so that a commit
229
+ * has reached `super.parse()` and a navigation that supersedes the settled one has started:
230
+ * - A navigation waits for async guards: the Promises keep waiting, for its settlement.
231
+ * - UI5 is matching a route: the Promises are forgotten, the `routeMatched` of that match
232
+ * resolves them. If UI5 never fires it, because the display of a target fails, they wait
233
+ * forever, as with the native router.
234
+ * - Otherwise no match is coming, and the Promises are resolved.
235
+ *
236
+ * A navigation that starts after this microtask is not waited for. A Promise that is resolved
237
+ * here stays subscribed, and UI5 calls it again with the next `routeMatched`, which has no
238
+ * effect on a Promise.
239
+ */
240
+ private _settleMatchWaiters;
207
241
  /**
208
242
  * Initialize the router. When manifest guards are declared and
209
243
  * `guardLoading` is `"block"`, module loading starts and
@@ -211,33 +245,60 @@ declare module "ui5/guard/router/Router" {
211
245
  * In `"lazy"` mode, lazy wrappers are registered synchronously
212
246
  * and `super.initialize()` is called immediately.
213
247
  *
248
+ * While block-mode modules load, the router is not initialized yet:
249
+ * calling `initialize()` again changes nothing, and `stop()` cancels
250
+ * the pending start until `initialize()` is called again.
251
+ *
252
+ * @param bIgnoreInitialHash - Whether the current hash is left unparsed, as in the native router (since 1.7.0).
214
253
  * @override sap.ui.core.routing.Router#initialize
215
254
  * @since 1.0.1
216
255
  */
217
- initialize(): this;
256
+ initialize(bIgnoreInitialHash?: boolean): this;
257
+ /**
258
+ * Start the native router. With `ignoreInitialHash` it parses nothing and resumes the route
259
+ * that was displayed when the router stopped. That route is the current one again, on the hash
260
+ * that the URL shows now, so that its leave guards run and a blocked hash change returns to it.
261
+ */
262
+ private _start;
263
+ /**
264
+ * The hash changer of this router reports a hash change: `parse()` is called with it next.
265
+ *
266
+ * The report is out of date if the hash changer shows a later hash by now, one that it has
267
+ * reported to this router already. That happens to a router that shares its hash changer, as
268
+ * the routers of all components that are not routing targets do: a router that is informed
269
+ * first redirects the hash, UI5 reports the target to every router, and only then the hash
270
+ * that was redirected to the routers that are informed later. A hash changer that reports
271
+ * while a parent router collects the hashes of a navigation shows no hash at all.
272
+ */
273
+ private _onHashReported;
274
+ /**
275
+ * UI5 has reported a hash change to every router. The event tells what the URL showed before
276
+ * the change, which is what undoes it. A snapshot of the URL taken at any other time would not
277
+ * do: the URL also changes without an event, as when the Fiori launchpad puts it back after
278
+ * a cross-app navigation that the user cancelled. A navigation that waited for this to put
279
+ * the URL back does so now (see {@link _undoHashChange}).
280
+ */
281
+ private _onRootHashChanged;
282
+ /**
283
+ * Tell the undo of the pending navigation what the URL showed before the hash change
284
+ * `newHash`, and put the URL back if the navigation waited for that.
285
+ */
286
+ private _completeUndo;
218
287
  /**
219
288
  * Add a route dynamically and integrate it into pattern-tree inheritance.
220
289
  *
221
290
  * Appends the route name to the internal route list so that
222
291
  * `_collectRoutePatterns()` includes it in subsequent inheritance
223
292
  * lookups, clears the metadata cache, and registers any inherited
224
- * manifest guards when `inheritance` is `"pattern-tree"`.
293
+ * manifest guards when `inheritance` is `"pattern-tree"`: on every
294
+ * route, ancestor guards still run before descendant guards.
225
295
  *
226
296
  * @param oConfig - Route configuration object as defined by `sap.ui.core.routing.Route`.
227
- * @param rest - Additional arguments forwarded to the parent `addRoute`.
297
+ * @param oParent - Optional parent route, forwarded to the parent `addRoute`.
228
298
  * @override sap.ui.core.routing.Router#addRoute
229
299
  * @since 1.6.0
230
300
  */
231
- addRoute(oConfig: $RouteSettings, ...rest: unknown[]): void;
232
- /**
233
- * Expand manifest guard descriptors for a single newly added route.
234
- *
235
- * For each source descriptor whose route is an ancestor of the new
236
- * route's pattern, emits a copy targeting the new route. Also emits
237
- * copies for existing routes that are descendants of the new route
238
- * (in case the new route has declared guards). Sorted by depth.
239
- */
240
- private _expandGuardDescriptorsForNewRoute;
301
+ addRoute(oConfig: $RouteSettings, oParent?: Route): void;
241
302
  /**
242
303
  * Register a global guard that runs for every navigation.
243
304
  *
@@ -298,14 +359,12 @@ declare module "ui5/guard/router/Router" {
298
359
  * UI5's native `navTo` has two signatures where the third parameter is either
299
360
  * `componentTargetInfo` (object) or `bReplace` (boolean). This method normalizes
300
361
  * both forms so the rest of `navTo` can work with a single set of variables.
362
+ * The options follow `bReplace`, or take its place when it is left out.
301
363
  */
302
364
  private _resolveNavToArgs;
303
365
  /** Return `true` when the value is a function; otherwise log a warning. */
304
366
  private _isFn;
305
- /**
306
- * Handle guard registration for a potentially unknown route.
307
- * Returns `true` if registration should proceed, `false` if not.
308
- */
367
+ /** Apply the `unknownRouteRegistration` policy: warn or throw when the route is unknown. */
309
368
  private _handleUnknownRouteRegistration;
310
369
  /**
311
370
  * Remove a leave guard from a specific route.
@@ -316,7 +375,6 @@ declare module "ui5/guard/router/Router" {
316
375
  * @since 1.0.1
317
376
  */
318
377
  removeLeaveGuard(routeName: string, guard: LeaveGuardFn): this;
319
- private static readonly _EMPTY_META;
320
378
  /**
321
379
  * Return the resolved metadata for a route.
322
380
  *
@@ -356,7 +414,7 @@ declare module "ui5/guard/router/Router" {
356
414
  * settlement result. Before any navigation has settled, it falls back to a
357
415
  * synthetic `Committed` result derived from the router's current route/hash
358
416
  * state. After `stop()`, that idle fallback reports empty route/hash values
359
- * until a new navigation settles.
417
+ * until a new navigation settles, or `initialize(true)` resumes the route.
360
418
  *
361
419
  * @returns Promise that resolves with a {@link NavigationResult} once the pipeline settles.
362
420
  * @since 1.2.0
@@ -368,7 +426,8 @@ declare module "ui5/guard/router/Router" {
368
426
  * Fires synchronously after every guard pipeline settlement with
369
427
  * a {@link NavigationResult} payload. Unlike the one-shot
370
428
  * `navigationSettled()` Promise, this event fires for every
371
- * navigation outcome without re-registration.
429
+ * navigation outcome without re-registration. It does not fire for the
430
+ * navigation that `destroy()` cancels.
372
431
  *
373
432
  * @param oData - Application-specific payload passed to the handler as second argument.
374
433
  * @param fnFunction - The function to be called when the event occurs.
@@ -399,12 +458,13 @@ declare module "ui5/guard/router/Router" {
399
458
  * For programmatic navigation, guards run BEFORE the hash changes.
400
459
  * This prevents history pollution: blocked navigations never push a
401
460
  * history entry, and redirected navigations go directly to the final
402
- * target.
461
+ * target, which is written the way this call asked for (`bReplace`).
403
462
  *
404
- * Same-hash navigations are deduped: if the target hash matches
405
- * `_currentHash`, any pending navigation is cancelled and the call
406
- * returns without navigating. If it matches the in-flight attempt's
407
- * hash, the in-flight preflight continues undisturbed.
463
+ * A `navTo()` to the committed hash changes no route of this router, so
464
+ * no guard runs: any pending navigation is cancelled and the call goes
465
+ * to the native `navTo()`, which sets or resets the hashes of nested
466
+ * components (`componentTargetInfo`). If the target matches the
467
+ * in-flight attempt's hash, the in-flight preflight continues undisturbed.
408
468
  *
409
469
  * When all guards are synchronous, the decision and the resulting
410
470
  * hash change happen in the same tick. When any guard returns a
@@ -413,7 +473,23 @@ declare module "ui5/guard/router/Router" {
413
473
  *
414
474
  * Assumes `super.navTo()` calls `HashChanger.setHash()` which fires
415
475
  * `hashChanged` synchronously, causing `parse()` to re-enter in the
416
- * same call stack (validated by test).
476
+ * same call stack (validated by test). If the hash changer refuses the
477
+ * hash change, as the Fiori launchpad's navigation filter does when its
478
+ * dirty-state check stops it, nothing is committed and the navigation
479
+ * settles as `Blocked`.
480
+ *
481
+ * With component targets (`componentTargetInfo`) UI5 writes the hash
482
+ * later, once the nested components are loaded. The navigation commits
483
+ * and settles when `parse()` receives that hash. Until then it is
484
+ * pending: a navigation that supersedes it, `stop()` or `destroy()`
485
+ * settles it as `Cancelled`. That also ends a navigation whose hash UI5
486
+ * never writes, because a nested component failed to load or the router
487
+ * is not async.
488
+ *
489
+ * On a router that is not initialized (before `initialize()`, while
490
+ * block-mode guard modules load, after `stop()`) the call goes straight
491
+ * to the native `navTo()`, which only sets the hash or does nothing when
492
+ * stopped. The guards run when the router starts and parses the hash.
417
493
  *
418
494
  * @override sap.ui.core.routing.Router#navTo
419
495
  * @since 1.0.1
@@ -422,19 +498,17 @@ declare module "ui5/guard/router/Router" {
422
498
  navTo(routeName: string, parameters?: object, bReplace?: boolean): this;
423
499
  navTo(routeName: string, parameters?: object, bReplace?: boolean, options?: GuardNavToOptions): this;
424
500
  navTo(routeName: string, parameters?: object, componentTargetInfo?: Record<string, ComponentTargetParameters>, bReplace?: boolean, options?: GuardNavToOptions): this;
501
+ /**
502
+ * Navigate to a `navTo()` target that needs no guards (allowed or bypassed) and commit it,
503
+ * or block it if the hash change was refused (see {@link _commitAfterNavTo}).
504
+ */
505
+ private _navigateAllowed;
425
506
  /**
426
507
  * Apply a preflight guard decision. For "allow", enter the committing
427
- * phase and call super.navTo(). For "block", flush settlement without
428
- * touching the hash. For "redirect", start a redirect chain.
508
+ * phase and call super.navTo(). For "block", flush settlement; the hash is
509
+ * only touched to restore it after a superseded hash-change navigation.
510
+ * For "redirect", start a redirect chain.
429
511
  * For "error", flush Error settlement with the guard's error.
430
- *
431
- * @param decision - Normalized guard pipeline result.
432
- * @param routeName - Original route name passed to navTo().
433
- * @param parameters - Original route parameters.
434
- * @param componentTargetInfo - Optional component target info from the navTo() overload.
435
- * @param bReplace - Whether to replace the current history entry.
436
- * @param targetHash - Resolved hash for the target route.
437
- * @param toRoute - Resolved route name (may differ from routeName for nested routes).
438
512
  */
439
513
  private _applyPreflightDecision;
440
514
  /**
@@ -456,35 +530,85 @@ declare module "ui5/guard/router/Router" {
456
530
  *
457
531
  * Resets `_currentRoute` and `_currentHash` so that a subsequent
458
532
  * `initialize()` re-parses the current hash and fires `routeMatched`,
459
- * matching the native `sap.m.routing.Router` behavior.
533
+ * matching the native `sap.m.routing.Router` behavior. The route is
534
+ * kept for `initialize(true)`, which resumes it instead.
460
535
  *
461
536
  * @override sap.ui.core.routing.Router#stop
462
537
  * @since 1.0.1
463
538
  */
464
539
  stop(): this;
540
+ /** Detach what {@link _start} has attached. */
541
+ private _detachHashListeners;
465
542
  /**
466
543
  * Invalidate any in-flight async guard work. Bumps the generation counter
467
544
  * so pending `.then()` callbacks see they are stale, aborts the signal,
468
- * and transitions to idle.
545
+ * and transitions to idle. A navigation that waits for its guards or for
546
+ * its hash settles as `Cancelled`. With `restoreHash`, a cancelled hash-change
547
+ * navigation also gets its hash restored: `navTo()` passes it when the
548
+ * call itself will not move the URL.
469
549
  */
470
550
  private _cancelPendingNavigation;
551
+ /**
552
+ * Whether the pending navigation leaves a hash in the URL that never committed, the one of a
553
+ * hash-change navigation: it must be restored unless a navigation moves the URL.
554
+ */
555
+ private _pendingRestoresHash;
556
+ /**
557
+ * Start evaluating a navigation. Its generation is its own, so the result of any earlier
558
+ * attempt is stale: also one that a navigationSettled handler started while this
559
+ * navigation cancelled its predecessor, which is aborted here without a settlement.
560
+ */
561
+ private _startAttempt;
562
+ /**
563
+ * Apply the decision of async guards once it is there. Until then the navigation is postponed,
564
+ * which UI5 sees as a route match in progress (see {@link _mirrorMatchingProcess}). The pipeline
565
+ * turns a failing guard into an error decision, so an error thrown here comes from applying the
566
+ * decision, which has no caller to throw to: it is logged, and fails the navigation unless that
567
+ * has settled.
568
+ */
569
+ private _applyWhenDecided;
471
570
  /**
472
571
  * Apply a guard decision for the parse() fallback path.
473
572
  */
474
573
  private _applyDecision;
574
+ /**
575
+ * Leave the title history of UI5 (`getTitleHistory()`) as after the native equivalent of a
576
+ * redirected hash change: the hash change, then `navTo(target, ..., true)`. The route of the
577
+ * hash change never matched, so UI5 has not handled its title:
578
+ * - A new entry or a step forward would have added a title, which the title of the target
579
+ * replaces: UI5 must not remove the title of the route before it.
580
+ * - A step back would have removed the title of the route that was left, so that the target
581
+ * replaces the title of the entry the step arrived at: UI5 removes the first for the
582
+ * replaced hash, the router removes the second, under the condition of UI5 for a step back.
583
+ */
584
+ private _alignTitleHistory;
475
585
  /**
476
586
  * Delegate to the parent router and update internal state.
477
587
  *
478
588
  * State is updated BEFORE calling parse to ensure that if event handlers
479
589
  * (e.g., routeMatched) trigger nested navigation, the leave guards will
480
- * run for the correct (new) route rather than the old one.
590
+ * run for the correct (new) route rather than the old one. The settlement
591
+ * fires before parse as well, so the settlements of such nested navigations
592
+ * follow it.
481
593
  */
482
594
  private _commitNavigation;
595
+ /**
596
+ * Commit the navigation of the committing phase after `super.navTo()` unless `parse()` has
597
+ * committed it. Returns whether the navigation takes place:
598
+ * - The hash changer shows the target hash: the route matches here.
599
+ * - UI5 writes the hash later, which it does with component targets, once the nested
600
+ * components are loaded. The navigation waits for it: it commits, and the route matches,
601
+ * when `parse()` gets that hash, as the route does natively. Committed here, the router
602
+ * would be on a route that UI5 does not display if the hash is never written.
603
+ * - Otherwise the hash changer has refused the hash change, as the Fiori launchpad does while
604
+ * it asks the user about unsaved data. Nothing changed, so nothing is committed.
605
+ */
606
+ private _commitAfterNavTo;
483
607
  /**
484
608
  * Evaluate guards on a redirect target and apply the resulting decision.
485
609
  *
486
- * Handles loop detection (visited-hash set + depth cap), unknown-route
487
- * fallback, sync/async guard evaluation, and recursive chaining when
610
+ * Handles the unknown-route block, loop detection (visited-hash set +
611
+ * depth cap), sync/async guard evaluation, and recursive chaining when
488
612
  * the target's guard itself returns a redirect. All hops in a chain
489
613
  * share the same AbortSignal and generation counter from the original
490
614
  * navigation so that a superseding navigation correctly discards
@@ -496,32 +620,46 @@ declare module "ui5/guard/router/Router" {
496
620
  private _redirect;
497
621
  /**
498
622
  * Apply a guard decision within a redirect chain. For "allow", enter
499
- * committing phase and delegate to navTo (which hits the existing bypass).
623
+ * committing phase and delegate to navTo (which hits the existing bypass);
624
+ * if that does not reach parse(), commit the target directly. A target that
625
+ * is displayed already settles the navigation without a commit.
500
626
  * For "block", block the entire chain. For "redirect", recurse.
501
627
  *
502
628
  * @param decision - Normalized guard pipeline result for this hop.
503
629
  * @param target - The redirect target (route name or {@link GuardRedirect}).
504
- * @param targetHash - Resolved hash for the redirect target (guaranteed non-null).
630
+ * @param targetHash - Resolved hash for the redirect target.
631
+ * @param toRoute - Route that matches the hash, as in the hop's guard context: the route UI5 displays.
505
632
  * @param chain - Shared redirect chain context with visited set, signals, etc.
506
633
  */
507
634
  private _applyRedirectDecision;
635
+ /** The route that matches a hash, and its arguments. For a hash that no route matches: no route (`""`), no arguments. */
636
+ private _matchRoute;
508
637
  /**
509
- * Build a guard context for a new navigation.
510
- * Called by {@link navTo} (preflight path) and {@link parse} (browser-initiated path).
638
+ * The greedy routes that match `hash` in addition to `firstMatch`, the first route that
639
+ * matches it. UI5 matches them as well and fires their events.
640
+ */
641
+ private _greedyMatches;
642
+ /**
643
+ * Evaluate the guards of a navigation: of the routes in its context, and of the greedy routes
644
+ * that are left and entered with them. A hop of a redirect chain leaves no route.
645
+ */
646
+ private _evaluateGuards;
647
+ /**
648
+ * Build the guard context of a navigation to `routeInfo`. A hop of a redirect chain passes the
649
+ * chain, whose source route, source hash and bag are those of the original navigation.
511
650
  */
512
651
  private _createGuardContext;
513
652
  /**
514
- * Start a new redirect chain from the current evaluating phase.
653
+ * Start a new redirect chain for the given evaluating attempt.
515
654
  * Called by {@link _applyPreflightDecision} and {@link _applyDecision}
516
655
  * when a guard returns a redirect. Delegates to {@link _redirect} with
517
656
  * a fresh {@link RedirectChainContext}.
518
657
  */
519
658
  private _startRedirectChain;
520
659
  /**
521
- * Clear pending state and flush a Blocked settlement.
522
- * When `restoreHash` is true (default), also restores the browser hash
523
- * to `_currentHash`. Preflight callers pass false because the hash was
524
- * never changed.
660
+ * Settle as Blocked. With `restoreHash` (default), the hash change of the navigation is
661
+ * undone first (see {@link _settleUncommitted}). Preflight callers pass false unless they
662
+ * superseded a hash-change navigation: otherwise the hash was never changed.
525
663
  */
526
664
  private _blockNavigation;
527
665
  /**
@@ -530,65 +668,77 @@ declare module "ui5/guard/router/Router" {
530
668
  * and the error that caused the failure.
531
669
  */
532
670
  private _errorNavigation;
533
- /** Conditionally restore the browser hash after a blocked or errored navigation. */
534
- private _restoreHashIfNeeded;
535
671
  /**
536
- * Restore the previous hash without creating a history entry.
537
- * Assumes replaceHash fires hashChanged synchronously (validated by test).
538
- * `_currentRoute` stays unchanged because the navigation never
539
- * committed. The user remains on the same logical route.
672
+ * Settle a navigation that did not commit. With `restoreHash`, the hash it left in the URL
673
+ * is restored first, so that settlement handlers run on the final URL and a hash they set
674
+ * is not overwritten. The exception is a first navigation: nothing is committed yet, so the
675
+ * empty hash is restored after the settlement and parsed as a navigation of its own.
676
+ * `whenBack` runs after the settlement.
540
677
  */
541
- private _restoreHash;
678
+ private _settleUncommitted;
542
679
  /**
543
- * Collect all route names and their patterns from the router.
544
- * Skips routes whose pattern is undefined (no pattern configured).
680
+ * Describe how to undo the hash change that the navigation starts with. After `pending`, the
681
+ * undo of a navigation that this one supersedes, it takes back both changes. A `parse()` that
682
+ * is not `reported` by the hash changer comes with no hash change.
545
683
  */
546
- private _collectRoutePatterns;
684
+ private _describeUndo;
547
685
  /**
548
- * Expand guard descriptors to descendant routes when guard inheritance
549
- * is set to `"pattern-tree"`. Global (`"*"`) descriptors are kept as-is.
550
- * Descriptors are sorted by pattern depth (ancestor guards run before
551
- * descendant guards).
686
+ * Put the URL back after a navigation that did not commit. Returns whether it is back;
687
+ * otherwise `result` settles when it is.
688
+ *
689
+ * While the URL still shows the hash change that started the navigation, that change is undone
690
+ * as a whole, so that the hashes of nested routers are back as well:
691
+ * - A step through the browser history is taken back, which leaves the history as it was.
692
+ * The browser does that asynchronously.
693
+ * - Any other change (a new entry, or a step the browser does not report) has its entry replaced with
694
+ * the full previous hash, once UI5 has reported the change to every router. Nested routers
695
+ * have received their part of the refused hash by then; they receive the previous one next.
696
+ *
697
+ * `parse()` ends the wait when the hash change arrives that shows the full previous hash.
698
+ *
699
+ * If the URL has moved on since, only the hash of this router is restored. So it is while
700
+ * no navigation has committed: the URL before the change showed no route of this router either.
552
701
  */
553
- private _expandGuardDescriptors;
702
+ private _undoHashChange;
554
703
  /**
555
- * Resolve metadata for a route without inheritance (flat merge of
556
- * manifest and runtime metadata).
704
+ * Replace the hash of the root hash changer with the full previous hash, and settle the
705
+ * navigation that waits for it unless `parse()` has done so.
557
706
  */
558
- private _resolveFlatMeta;
707
+ private _replaceFullHash;
559
708
  /**
560
- * Resolve metadata for a route with pattern-tree inheritance.
561
- * Walks ancestor patterns shallowest-first, merging manifest and
562
- * runtime metadata at each level, then overlays the route's own.
709
+ * Settle the navigation that waited for the URL to be back: on `hash`, if the hash changer
710
+ * has reported one with the URL.
563
711
  */
564
- private _resolveInheritedMeta;
712
+ private _finishRestore;
565
713
  /**
566
- * Load guard modules individually via `sap.ui.require` and register
567
- * each resolved function with the appropriate guard API.
714
+ * Restore the previous hash of this router without creating a history entry
715
+ * (see {@link _undoHashChange} for the hash change of a navigation).
716
+ * Assumes replaceHash fires hashChanged synchronously (validated by test).
717
+ * `_currentRoute` stays unchanged because the navigation never
718
+ * committed. The user remains on the same logical route.
568
719
  *
569
- * Each module is loaded in its own `sap.ui.require` call so that a
570
- * single invalid path only skips that guard (with a warning) rather
571
- * than failing the entire batch. Once all loads settle, guards
572
- * register in declaration order. Registration errors (e.g. from
573
- * `unknownRouteRegistration: "throw"`) are caught per-module.
720
+ * A hash that the hash changer already shows is not written again: the navigation never
721
+ * moved it. For a nested router, writing its empty hash would add its prefix to the browser
722
+ * hash (`shell` becomes `shell&/child/`).
574
723
  */
575
- private _loadAndRegisterGuards;
724
+ private _restoreHash;
576
725
  /**
577
- * Route a parsed guard descriptor to the correct registration method.
726
+ * Collect all route names and their patterns from the router.
727
+ * Skips routes whose pattern is undefined (no pattern configured).
578
728
  */
579
- private _registerGuardFromDescriptor;
729
+ private _collectRoutePatterns;
580
730
  /**
581
- * Register lazy wrapper functions that load guard modules on first use.
582
- *
583
- * Cherry-picked descriptors (with exportKey) get one lazy wrapper each.
584
- * Bare-path descriptors try a sync cache probe first; if the module is
585
- * cached (preload likely finished), all guards are expanded immediately.
586
- * On cache miss, a single "expander" wrapper loads the module on first
587
- * navigation, registers remaining guards, and executes the first.
731
+ * Register one manifest guard: as the last guard of its route, or in front of the guard
732
+ * `before`. A registration error (`unknownRouteRegistration: "throw"` for an unknown route)
733
+ * is logged and skips the guard: no caller of the manifest config could catch it, and it
734
+ * must not keep the router from starting.
588
735
  */
736
+ private _registerManifestGuard;
737
+ /** Register the guards of each descriptor, loading their modules on first use (see `createLazyGuards`). */
589
738
  private _registerLazyGuards;
590
739
  /**
591
740
  * Clean up guards on destroy. Bumps generation to discard pending async results.
741
+ * A second call does nothing, like `sap.ui.core.routing.Router#destroy`.
592
742
  *
593
743
  * @since 1.0.1
594
744
  */