ui5-lib-guard-router 1.6.2 → 1.7.0

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 +190 -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 +122 -121
  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 +882 -1020
  42. package/dist/resources/ui5/guard/router/Router-dbg.js.map +1 -1
  43. package/dist/resources/ui5/guard/router/Router.d.ts +360 -211
  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 +155 -128
  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 +1089 -1130
  65. package/src/manifest.json +5 -2
  66. package/src/types.ts +79 -22
  67. package/tsconfig.json +0 -11
@@ -1,4 +1,4 @@
1
- sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", "./NavigationOutcome", "./GuardPipeline"], function (MobileRouter, Log, coreLibrary, __NavigationOutcome, __GuardPipeline) {
1
+ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", "sap/ui/core/routing/HashChanger", "sap/ui/core/routing/History", "./NavigationOutcome", "./GuardPipeline", "./GuardConfig", "./GuardModules", "./PatternTree", "./RouteMeta"], function (MobileRouter, Log, coreLibrary, HashChanger, History, __NavigationOutcome, __GuardPipeline, ___GuardConfig, ___GuardModules, ___PatternTree, __RouteMetaStore) {
2
2
  "use strict";
3
3
 
4
4
  function _interopRequireDefault(obj) {
@@ -7,339 +7,77 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
7
7
  const NavigationOutcome = _interopRequireDefault(__NavigationOutcome);
8
8
  const GuardPipeline = _interopRequireDefault(__GuardPipeline);
9
9
  const isPromiseLike = __GuardPipeline["isPromiseLike"];
10
+ const isPromiseResolver = __GuardPipeline["isPromiseResolver"];
11
+ const LOG_COMPONENT = __GuardPipeline["LOG_COMPONENT"];
12
+ const isRecord = ___GuardConfig["isRecord"];
13
+ const parseGuardRouterConfig = ___GuardConfig["parseGuardRouterConfig"];
14
+ const createLazyGuards = ___GuardModules["createLazyGuards"];
15
+ const loadGuardModules = ___GuardModules["loadGuardModules"];
16
+ const byRouteDepth = ___PatternTree["byRouteDepth"];
17
+ const expandForNewRoute = ___PatternTree["expandForNewRoute"];
18
+ const expandToDescendants = ___PatternTree["expandToDescendants"];
19
+ const RouteMetaStore = _interopRequireDefault(__RouteMetaStore);
20
+ const EMPTY_META = __RouteMetaStore["EMPTY_META"];
10
21
  const HistoryDirection = coreLibrary.routing.HistoryDirection;
11
- const LOG_COMPONENT = "ui5.guard.router.Router";
12
- function isRouteGuardConfig(guard) {
13
- return typeof guard === "object" && guard !== null;
14
- }
15
-
16
- /** Snapshot of an in-flight navigation being evaluated by the guard pipeline. */
17
-
18
- const IDLE = {
19
- kind: "idle"
20
- };
21
-
22
- /** Type guard for plain objects. */
23
- function isRecord(value) {
24
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
25
- const proto = Object.getPrototypeOf(value);
26
- return proto === Object.prototype || proto === null;
27
- }
28
-
29
- /** Create a type-narrowing validator for a finite set of string literal values. */
30
- function isOneOf(...values) {
31
- const set = new Set(values);
32
- return v => typeof v === "string" && set.has(v);
33
- }
34
- const isUnknownRouteRegistrationPolicy = isOneOf("ignore", "warn", "throw");
35
- const isNavToPreflightMode = isOneOf("guard", "bypass", "off");
36
- const isGuardLoading = isOneOf("block", "lazy");
37
- const isInheritance = isOneOf("none", "pattern-tree");
38
-
39
- /** Matches a standalone optional (`:param:`) or rest (`:param*:`) segment. */
40
- const OPTIONAL_OR_REST_SEGMENT = /^:[^:]*\*?:$/;
41
-
42
22
  /**
43
- * Strips inline query and optional-query suffixes from a segment.
44
- *
45
- * UI5 (crossroads.js) allows query parameters to attach directly to a
46
- * path segment without a `/` separator:
47
- * - `product{?query}` → mandatory query on `product`
48
- * - `product:?query:` → optional query on `product`
49
- * - `{id}{?query}` → mandatory param + mandatory query
50
- *
51
- * For pattern-tree ancestry we only care about the path portion,
52
- * so these suffixes are stripped.
23
+ * The router config as UI5 gets it: the caller's object without `guardRouter`. It is a view and
24
+ * not a copy, because UIComponent adds `targetParent` (the ID of the root view) to its config
25
+ * object after it has constructed the router, and the native router reads it from that object.
53
26
  */
54
- function stripInlineQuery(seg) {
55
- // Strip mandatory query `{?...}` suffix
56
- const mqIdx = seg.indexOf("{?");
57
- if (mqIdx !== -1) return seg.slice(0, mqIdx);
58
- // Strip optional query `:?...:` suffix
59
- const oqIdx = seg.indexOf(":?");
60
- if (oqIdx !== -1) return seg.slice(0, oqIdx);
61
- return seg;
27
+ function withoutGuardRouter(config) {
28
+ const hidden = key => key === "guardRouter";
29
+ return new Proxy(config, {
30
+ get: (target, key, receiver) => hidden(key) ? undefined : Reflect.get(target, key, receiver),
31
+ has: (target, key) => !hidden(key) && Reflect.has(target, key),
32
+ ownKeys: target => Reflect.ownKeys(target).filter(key => !hidden(key)),
33
+ getOwnPropertyDescriptor: (target, key) => hidden(key) ? undefined : Reflect.getOwnPropertyDescriptor(target, key)
34
+ });
62
35
  }
63
-
64
- /**
65
- * Extract mandatory path segments from a UI5 route pattern.
66
- *
67
- * Splits on `/`, strips inline query suffixes, then drops empty segments,
68
- * standalone optional (`:param:`), and rest (`:param*:`) segments.
69
- */
70
- function patternSegments(pattern) {
71
- return pattern.split("/").map(stripInlineQuery).filter(seg => seg !== "" && !OPTIONAL_OR_REST_SEGMENT.test(seg));
36
+ function isRouteGuardConfig(guard) {
37
+ return typeof guard === "object" && guard !== null;
72
38
  }
73
39
 
74
- /**
75
- * Check if `ancestorPattern` is a URL-tree ancestor of `candidatePattern`.
76
- *
77
- * Both patterns are reduced to their mandatory path segments and compared
78
- * positionally. Mandatory parameter segments (`{paramA}`, `{paramB}`) are
79
- * treated as equivalent regardless of name, so `employees/{empId}` is
80
- * recognized as an ancestor of `employees/{id}/resume`.
81
- */
82
- function isPatternAncestor(ancestorPattern, candidatePattern) {
83
- if (ancestorPattern === "") return true;
84
- const ancestorSegments = patternSegments(ancestorPattern);
85
- if (ancestorSegments.length === 0) return false;
86
- const candidateSegments = patternSegments(candidatePattern);
87
- if (candidateSegments.length <= ancestorSegments.length) return false;
88
- return ancestorSegments.every((seg, i) => {
89
- const candidateSeg = candidateSegments[i];
90
- if (seg === candidateSeg) return true;
91
- // Treat any two mandatory parameter segments as equivalent
92
- return seg.startsWith("{") && candidateSeg.startsWith("{");
93
- });
94
- }
40
+ /** A step through the browser history (back, forward): how far it went, and the URL it arrived at. */
95
41
 
96
- /** Parsed guard declaration from the manifest `guards` block. */
42
+ /** The step through the browser history that brought the browser to the URL it shows, if a step did. */
43
+ let lastStep = null;
44
+ /** The URL of a step that a router is taking back, until the browser reports the next URL change. */
45
+ let undoneHref = null;
97
46
 
98
- /**
99
- * Resolve a guard module path to a slash-separated AMD module path.
100
- *
101
- * Inspired by `sap.ui.core.routing.Target._getEffectiveObjectName()`,
102
- * which skips namespace prepending for `"module:"`-prefixed paths. This
103
- * function goes further: it also converts dots to slashes in a single
104
- * step, so both dot notation (`module:some.lib.guard`) and slash
105
- * notation (`module:some/lib/guard`) are accepted.
106
- *
107
- * - Paths prefixed with `"module:"` are treated as absolute (the prefix
108
- * is stripped, dots become slashes).
109
- * - All other paths are prefixed with the component namespace, then dots
110
- * become slashes.
111
- */
112
- function resolveGuardModulePath(dotPath, componentNamespace) {
113
- if (dotPath.startsWith("module:")) {
114
- return dotPath.slice("module:".length).replace(/\./g, "/");
47
+ // The Navigation API tells how far a step through the history went, before UI5 learns of the
48
+ // hash change. UI5's History only infers it, and wrongly once an entry lacks its state. Without
49
+ // the API (Firefox before 147, Safari before 26.2) no step is known and the entry is replaced.
50
+ window.navigation?.addEventListener("currententrychange", event => {
51
+ const href = window.location.href;
52
+ if (undoneHref !== href) undoneHref = null;
53
+ const entry = window.navigation.currentEntry;
54
+ if (entry && event.navigationType === "traverse") {
55
+ lastStep = {
56
+ offset: entry.index - event.from.index,
57
+ href
58
+ };
59
+ } else if (lastStep?.href !== href) {
60
+ // Not an entry whose state alone is replaced, as UI5's History does after a step.
61
+ lastStep = null;
115
62
  }
116
- const fullDotPath = componentNamespace ? componentNamespace + "." + dotPath : dotPath;
117
- return fullDotPath.replace(/\./g, "/");
118
- }
63
+ });
119
64
 
120
- /**
121
- * Split a manifest guard entry on the first `#` to separate the module path
122
- * from an optional export key, then derive a human-readable guard name.
123
- */
124
- function parseGuardEntry(entry, componentNamespace) {
125
- const hashIndex = entry.indexOf("#");
126
- const rawPath = hashIndex === -1 ? entry : entry.slice(0, hashIndex);
127
- const exportKey = hashIndex === -1 ? undefined : entry.slice(hashIndex + 1);
128
- const modulePath = resolveGuardModulePath(rawPath, componentNamespace);
65
+ /** What it takes to undo the hash change that an uncommitted navigation arrived with. */
129
66
 
130
- // Name: export key if present, otherwise last segment of the dot path
131
- const lastSegment = rawPath.split(".").pop() ?? rawPath;
132
- const name = exportKey ?? lastSegment;
133
- return {
134
- modulePath,
135
- name,
136
- exportKey
137
- };
138
- }
139
- /** Log a warning about a guard module entry in the manifest. */
140
- function guardWarning(modulePath, detail) {
141
- Log.warning(`guardRouter.guards: "${modulePath}" ${detail}`, undefined, LOG_COMPONENT);
142
- }
67
+ /** A manifest guard entry of a route, with the declared entry it stems from: itself, or the entry of an ancestor route. */
68
+
69
+ /** Snapshot of an in-flight navigation being evaluated by the guard pipeline. */
143
70
 
144
71
  /**
145
- * Detect the export shape of a loaded guard module and extract guard functions.
146
- *
147
- * Shapes:
148
- * - function → single guard
149
- * - Array → ordered guards (non-functions warned and skipped)
150
- * - plain object → named guards in key order (non-functions warned and skipped)
151
- *
152
- * When `exportKey` is set, only the matching export is returned.
153
- * When `exportKey` is set on a function export, the key is ignored with a debug warning.
72
+ * An allowed navigation waits for UI5 to write its hash. With component targets UI5 does that
73
+ * once the nested components are loaded, and never if one of them fails to load.
154
74
  */
155
- function resolveModuleExports(moduleExport, modulePath, descriptorName, exportKey) {
156
- const moduleName = modulePath.split("/").pop() ?? modulePath;
157
75
 
158
- // Shape 1: function
159
- if (typeof moduleExport === "function") {
160
- if (exportKey !== undefined) {
161
- Log.debug(`guardRouter.guards: "${modulePath}#${exportKey}" is a single function, ignoring export key`, undefined, LOG_COMPONENT);
162
- }
163
- return [{
164
- name: descriptorName,
165
- fn: moduleExport
166
- }];
167
- }
76
+ /** A navigation that did not commit waits for the URL to be back before it settles. */
168
77
 
169
- // Shape 2: array
170
- if (Array.isArray(moduleExport)) {
171
- if (moduleExport.length === 0) {
172
- guardWarning(modulePath, "exported an empty array, skipping");
173
- return [];
174
- }
175
- if (exportKey !== undefined) {
176
- const index = parseInt(exportKey, 10);
177
- if (Number.isNaN(index) || index < 0 || index >= moduleExport.length) {
178
- guardWarning(modulePath, `#${exportKey} - index out of range, skipping`);
179
- return [];
180
- }
181
- const entry = moduleExport[index];
182
- if (typeof entry !== "function") {
183
- guardWarning(modulePath, `#${exportKey} is not a function, skipping`);
184
- return [];
185
- }
186
- return [{
187
- name: `${moduleName}#${exportKey}`,
188
- fn: entry
189
- }];
190
- }
191
- const results = [];
192
- for (let i = 0; i < moduleExport.length; i++) {
193
- const entry = moduleExport[i];
194
- if (typeof entry !== "function") {
195
- guardWarning(modulePath, `[${i}] is not a function, skipping`);
196
- continue;
197
- }
198
- results.push({
199
- name: `${moduleName}#${i}`,
200
- fn: entry
201
- });
202
- }
203
- return results;
204
- }
205
-
206
- // Shape 3: plain object
207
- if (isRecord(moduleExport)) {
208
- const entries = Object.entries(moduleExport);
209
- if (entries.length === 0) {
210
- guardWarning(modulePath, "exported an empty object, skipping");
211
- return [];
212
- }
213
- if (exportKey !== undefined) {
214
- let value = moduleExport[exportKey];
215
- let resolvedName = exportKey;
216
- if (value === undefined) {
217
- const index = parseInt(exportKey, 10);
218
- if (!Number.isNaN(index) && index >= 0 && index < entries.length) {
219
- const [key, val] = entries[index];
220
- value = val;
221
- resolvedName = key;
222
- }
223
- }
224
- if (value === undefined) {
225
- guardWarning(modulePath, `#${exportKey} - key not found, skipping`);
226
- return [];
227
- }
228
- if (typeof value !== "function") {
229
- guardWarning(modulePath, `#${exportKey} is not a function, skipping`);
230
- return [];
231
- }
232
- return [{
233
- name: resolvedName,
234
- fn: value
235
- }];
236
- }
237
- const results = [];
238
- for (const [key, value] of entries) {
239
- if (typeof value !== "function") {
240
- guardWarning(modulePath, `.${key} is not a function, skipping`);
241
- continue;
242
- }
243
- results.push({
244
- name: key,
245
- fn: value
246
- });
247
- }
248
- return results;
249
- }
250
- guardWarning(modulePath, "did not export a function, array, or plain object, skipping");
251
- return [];
252
- }
253
-
254
- /**
255
- * Parse the `guards` block from the guardRouter config into an array of
256
- * {@link GuardDescriptor} objects.
257
- *
258
- * Handles:
259
- * - `"*"` key with `string[]` -> global enter guards
260
- * - Route name with `string[]` (shorthand) -> enter guards
261
- * - Route name with `{ enter: [...], leave: [...] }` -> enter + leave guards
262
- * - `"*"` with object form -> warn, treat enter as global
263
- * - `"*"` leave -> warn, skip (global leave guards not supported)
264
- * - Invalid entries -> warn, skip
265
- */
266
- function parseGuardDescriptors(guards, componentNamespace) {
267
- if (!isRecord(guards)) {
268
- Log.warning("guardRouter.guards is not a plain object, skipping", JSON.stringify(guards), LOG_COMPONENT);
269
- return [];
270
- }
271
- const descriptors = [];
272
- function pushEntries(entries, route, type, label) {
273
- for (const entry of entries) {
274
- if (typeof entry !== "string" || entry.length === 0) {
275
- Log.warning(`guardRouter.guards${label}: invalid entry, skipping`, JSON.stringify(entry), LOG_COMPONENT);
276
- continue;
277
- }
278
- const parsed = parseGuardEntry(entry, componentNamespace);
279
- descriptors.push({
280
- route,
281
- type,
282
- ...parsed
283
- });
284
- }
285
- }
286
- for (const [key, value] of Object.entries(guards)) {
287
- if (Array.isArray(value)) {
288
- pushEntries(value, key, "enter", `["${key}"]`);
289
- } else if (isRecord(value)) {
290
- const config = value;
291
- if (key === "*" && config.leave !== undefined) {
292
- Log.warning('guardRouter.guards["*"].leave: global leave guards are not supported, skipping', undefined, LOG_COMPONENT);
293
- }
294
- if (key === "*" && config.enter === undefined && config.leave !== undefined) {
295
- continue;
296
- }
297
- if (key === "*" && config.enter !== undefined) {
298
- Log.info('guardRouter.guards["*"]: object form; treating enter as global', undefined, LOG_COMPONENT);
299
- }
300
- if (Array.isArray(config.enter)) {
301
- pushEntries(config.enter, key, "enter", `["${key}"].enter`);
302
- }
303
- if (key !== "*" && Array.isArray(config.leave)) {
304
- pushEntries(config.leave, key, "leave", `["${key}"].leave`);
305
- }
306
- } else {
307
- Log.warning(`guardRouter.guards["${key}"]: expected string[] or { enter?, leave? }, skipping`, JSON.stringify(value), LOG_COMPONENT);
308
- }
309
- }
310
- return descriptors;
311
- }
312
- const DEFAULT_OPTIONS = {
313
- unknownRouteRegistration: "warn",
314
- navToPreflight: "guard",
315
- guardLoading: "lazy",
316
- inheritance: "none"
78
+ const IDLE = {
79
+ kind: "idle"
317
80
  };
318
- function applyOption(raw, key, guard, target) {
319
- if (raw[key] !== undefined) {
320
- if (guard(raw[key])) {
321
- target[key] = raw[key];
322
- } else {
323
- Log.warning(`guardRouter.${key} has invalid value, using default`, JSON.stringify(raw[key]), LOG_COMPONENT);
324
- }
325
- }
326
- }
327
- function normalizeGuardRouterOptions(raw) {
328
- if (!isRecord(raw)) {
329
- if (raw !== undefined) {
330
- Log.warning("guardRouter config is not a plain object, using defaults", JSON.stringify(raw), LOG_COMPONENT);
331
- }
332
- return DEFAULT_OPTIONS;
333
- }
334
- const result = {
335
- ...DEFAULT_OPTIONS
336
- };
337
- applyOption(raw, "unknownRouteRegistration", isUnknownRouteRegistrationPolicy, result);
338
- applyOption(raw, "navToPreflight", isNavToPreflightMode, result);
339
- applyOption(raw, "guardLoading", isGuardLoading, result);
340
- applyOption(raw, "inheritance", isInheritance, result);
341
- return result;
342
- }
343
81
 
344
82
  /** Maximum number of hops in a redirect chain before it is treated as a loop. */
345
83
  const MAX_REDIRECT_DEPTH = 10;
@@ -353,8 +91,8 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
353
91
  * loading, or event firing occurs.
354
92
  *
355
93
  * Two entry points feed the same pipeline:
356
- * - `navTo()` runs guards as a preflight check. Blocked or redirected
357
- * navigations never change the hash or push history entries.
94
+ * - `navTo()` runs guards as a preflight check. A blocked navigation
95
+ * never changes the hash; a redirected one only writes its final target.
358
96
  * - `parse()` runs guards as a fallback for browser back/forward, URL
359
97
  * bar entry, and direct hash changes where the hash has already changed
360
98
  * before guards can intercept.
@@ -370,72 +108,119 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
370
108
  * @extends sap.m.routing.Router
371
109
  */
372
110
  const Router = MobileRouter.extend("ui5.guard.router.Router", {
373
- constructor: function _constructor(...args) {
374
- const [routes, config, owner, ...rest] = args;
375
- const rawConfig = config;
376
- const isRecordConfig = isRecord(rawConfig);
377
- const {
378
- guardRouter,
379
- ...cleanConfig
380
- } = isRecordConfig ? rawConfig : {};
381
- MobileRouter.prototype.constructor.apply(this, [routes, isRecordConfig ? cleanConfig : config, owner, ...rest]);
382
- this._options = DEFAULT_OPTIONS;
111
+ constructor: function _constructor(routes, config, owner, ...rest) {
112
+ const isRecordConfig = isRecord(config);
113
+ const guardRouter = isRecordConfig ? config.guardRouter : undefined;
114
+ // UI5 passes more than its types declare: after the targets config comes the
115
+ // hash changer of a component that is loaded as a routing target.
116
+ MobileRouter.prototype.constructor.apply(this, [routes, isRecordConfig ? withoutGuardRouter(config) : config, owner, ...rest]);
383
117
  this._pipeline = new GuardPipeline();
384
118
  this._currentRoute = "";
385
119
  this._currentHash = null;
386
120
  this._phase = IDLE;
387
121
  this._parseGeneration = 0;
388
122
  this._suppressedHash = null;
123
+ /** How to undo the hash change of the pending navigation (see {@link _undoHashChange}). */
124
+ this._undo = null;
125
+ /** The hash that the hash changer of this router is reporting, until `parse()` receives it. */
126
+ this._reportedHash = null;
127
+ /** The hash that the hash changer of this router reported last, reports that are out of date aside. */
128
+ this._lastReport = null;
129
+ /** Whether the hash changer shows a later hash than the one it is reporting (see {@link _onHashReported}). */
130
+ this._reportOutdated = false;
131
+ /** The global hash changer that {@link _onRootHashChanged} is attached to, behind the listener of UI5 that informs the routers. */
132
+ this._rootHashChanger = null;
133
+ /** The route that was current when the router stopped: `initialize(true)` resumes it, as UI5 does. */
134
+ this._stoppedRoute = "";
389
135
  this._settlementResolvers = [];
390
136
  this._lastSettlement = null;
391
- this._pendingGuardDescriptors = [];
392
137
  this._sourceDescriptors = [];
138
+ /** The manifest guards registered for a route, by which `addRoute()` places the guards a route inherits then. */
139
+ this._manifestGuards = [];
393
140
  this._destroyed = false;
394
- this._manifestMeta = new Map();
395
- this._runtimeMeta = new Map();
396
- this._resolvedMetaCache = new Map();
397
- this._routeNames = [];
398
- this._options = normalizeGuardRouterOptions(guardRouter);
399
-
400
- // Collect route names from the constructor's routes parameter for pattern-tree traversal.
401
- if (Array.isArray(routes)) {
402
- this._routeNames = routes.filter(r => isRecord(r) && typeof r.name === "string").map(r => r.name);
403
- } else if (isRecord(routes)) {
404
- this._routeNames = Object.keys(routes);
405
- }
406
- if (isRecord(guardRouter) && guardRouter.routeMeta !== undefined) {
407
- if (isRecord(guardRouter.routeMeta)) {
408
- for (const [routeName, meta] of Object.entries(guardRouter.routeMeta)) {
409
- if (isRecord(meta)) {
410
- this._manifestMeta.set(routeName, Object.freeze({
411
- ...meta
412
- }));
413
- } else {
414
- Log.warning(`guardRouter.routeMeta["${routeName}"]: expected object, skipping`, JSON.stringify(meta), LOG_COMPONENT);
415
- }
416
- }
417
- } else {
418
- Log.warning("guardRouter.routeMeta: expected object, skipping", JSON.stringify(guardRouter.routeMeta), LOG_COMPONENT);
419
- }
141
+ /** What UI5 itself wrote to `_bMatchingProcessStarted` (see {@link _mirrorMatchingProcess}). */
142
+ this._nativeMatching = false;
143
+ /** Promises that wait for the `routeMatched` of a match that has not started (see {@link attachRouteMatched}). */
144
+ this._matchWaiters = [];
145
+ /**
146
+ * Set while block-mode guard modules load; `start` says whether to initialize once they have,
147
+ * `ignoreInitialHash` is the argument of the `initialize()` call that asked for it.
148
+ */
149
+ this._blockLoad = null;
150
+ this._ownerComponent = owner;
151
+ // A config without routes has made no addRoute() call.
152
+ this._routeNames ??= [];
153
+ this._greedyRouteNames ??= [];
154
+ this._mirrorMatchingProcess();
155
+ let componentNamespace = "";
156
+ const appConfig = owner?.getManifestEntry("sap.app");
157
+ if (isRecord(appConfig) && typeof appConfig.id === "string") {
158
+ componentNamespace = appConfig.id;
420
159
  }
421
- if (isRecord(guardRouter) && guardRouter.guards !== undefined) {
422
- let componentNamespace = "";
423
- if (owner) {
424
- const appConfig = owner.getManifestEntry("sap.app");
425
- if (isRecord(appConfig) && typeof appConfig.id === "string") {
426
- componentNamespace = appConfig.id;
427
- }
428
- }
429
- this._pendingGuardDescriptors = parseGuardDescriptors(guardRouter.guards, componentNamespace);
160
+ const parsed = parseGuardRouterConfig(guardRouter, componentNamespace);
161
+ this._options = parsed.options;
162
+ this._meta = new RouteMetaStore(parsed.routeMeta, this._options.inheritance === "pattern-tree" ? () => this._collectRoutePatterns() : null);
163
+ this._pendingGuardDescriptors = parsed.guards;
430
164
 
431
- // Fire-and-forget preload hint: warm the module cache so lazy
432
- // wrappers resolve synchronously on first navigation.
433
- // Block mode loads modules itself in initialize().
434
- if (this._pendingGuardDescriptors.length > 0 && this._options.guardLoading === "lazy") {
435
- const uniquePaths = [...new Set(this._pendingGuardDescriptors.map(d => d.modulePath))];
436
- sap.ui.require(uniquePaths);
165
+ // Fire-and-forget preload hint: a module cached by initialize()
166
+ // needs no async load on navigation (see _registerLazyGuards).
167
+ // Block mode loads modules itself in initialize().
168
+ if (this._options.guardLoading === "lazy") {
169
+ const uniquePaths = [...new Set(this._pendingGuardDescriptors.map(d => d.modulePath))];
170
+ // A failed preload is reported when the guard runs: its lazy load warns
171
+ // and the navigation settles as Error.
172
+ sap.ui.require(uniquePaths, undefined, () => {});
173
+ }
174
+ },
175
+ /**
176
+ * Report a navigation that waits for async guards as a route match in progress, through the
177
+ * UI5-private member `_bMatchingProcessStarted` of `sap.ui.core.routing.Router`. UI5 reads it
178
+ * to tell whether the router of a nested component is still matching; without this, a parent
179
+ * route would count the component as displayed before its first route matched. The router does
180
+ * not write the member: it replaces it with an accessor that keeps what UI5 writes in
181
+ * {@link _nativeMatching} and also reads `true` while a navigation is postponed.
182
+ *
183
+ * See docs/reference/architecture.md ("UI5 Internals the Router Relies On") for the UI5 code this
184
+ * relies on, and docs/reference/upstream-parity.md for the tests that pin it.
185
+ */
186
+ _mirrorMatchingProcess: function _mirrorMatchingProcess() {
187
+ Object.defineProperty(this, "_bMatchingProcessStarted", {
188
+ get: () => this._isMatching(),
189
+ set: matching => {
190
+ this._nativeMatching = matching;
437
191
  }
192
+ });
193
+ },
194
+ /** Whether a route match is in progress: in UI5, or postponed until async guards have decided. */_isMatching: function _isMatching() {
195
+ return this._nativeMatching || this._phase.kind === "evaluating" && this._phase.postponed === true;
196
+ },
197
+ attachRouteMatched: function _attachRouteMatched(oData, fnFunction, oListener) {
198
+ if (isPromiseResolver(oData) && (!this.isInitialized() || this._isMatching())) {
199
+ this._matchWaiters.push(oData);
438
200
  }
201
+ // The arguments go on as received: EventProvider#attachEvent tells the two call forms apart.
202
+ return MobileRouter.prototype.attachRouteMatched.call(this, oData, fnFunction, oListener);
203
+ },
204
+ /**
205
+ * Decide what becomes of the Promises that wait for a `routeMatched`
206
+ * (see {@link attachRouteMatched}). Runs in a microtask after a settlement, so that a commit
207
+ * has reached `super.parse()` and a navigation that supersedes the settled one has started:
208
+ * - A navigation waits for async guards: the Promises keep waiting, for its settlement.
209
+ * - UI5 is matching a route: the Promises are forgotten, the `routeMatched` of that match
210
+ * resolves them. If UI5 never fires it, because the display of a target fails, they wait
211
+ * forever, as with the native router.
212
+ * - Otherwise no match is coming, and the Promises are resolved.
213
+ *
214
+ * A navigation that starts after this microtask is not waited for. A Promise that is resolved
215
+ * here stays subscribed, and UI5 calls it again with the next `routeMatched`, which has no
216
+ * effect on a Promise.
217
+ */
218
+ _settleMatchWaiters: function _settleMatchWaiters() {
219
+ if (this._phase.kind === "evaluating" && this._phase.postponed) return;
220
+ const waiters = this._matchWaiters;
221
+ this._matchWaiters = [];
222
+ if (this._nativeMatching) return;
223
+ for (const resolve of waiters) resolve();
439
224
  },
440
225
  /**
441
226
  * Initialize the router. When manifest guards are declared and
@@ -444,117 +229,178 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
444
229
  * In `"lazy"` mode, lazy wrappers are registered synchronously
445
230
  * and `super.initialize()` is called immediately.
446
231
  *
232
+ * While block-mode modules load, the router is not initialized yet:
233
+ * calling `initialize()` again changes nothing, and `stop()` cancels
234
+ * the pending start until `initialize()` is called again.
235
+ *
236
+ * @param bIgnoreInitialHash - Whether the current hash is left unparsed, as in the native router (since 1.7.0).
447
237
  * @override sap.ui.core.routing.Router#initialize
448
238
  * @since 1.0.1
449
239
  */
450
- initialize: function _initialize() {
240
+ initialize: function _initialize(bIgnoreInitialHash) {
241
+ if (this._blockLoad) {
242
+ if (!this._blockLoad.start) {
243
+ this._blockLoad.start = true;
244
+ this._blockLoad.ignoreInitialHash = bIgnoreInitialHash;
245
+ }
246
+ return this;
247
+ }
451
248
  if (this._pendingGuardDescriptors.length === 0) {
452
- return MobileRouter.prototype.initialize.call(this);
249
+ return this._start(bIgnoreInitialHash);
453
250
  }
454
- const descriptors = this._pendingGuardDescriptors;
251
+ const descriptors = this._pendingGuardDescriptors.map(source => ({
252
+ ...source,
253
+ source
254
+ }));
455
255
  this._pendingGuardDescriptors = [];
456
256
  this._sourceDescriptors = descriptors;
457
- const expandedDescriptors = this._options.inheritance === "pattern-tree" ? this._expandGuardDescriptors(descriptors) : descriptors;
257
+ const expandedDescriptors = this._options.inheritance === "pattern-tree" ? expandToDescendants(descriptors, this._collectRoutePatterns()) : descriptors;
458
258
  if (this._options.guardLoading === "lazy") {
459
259
  this._registerLazyGuards(expandedDescriptors);
460
- return MobileRouter.prototype.initialize.call(this);
260
+ return this._start(bIgnoreInitialHash);
461
261
  }
462
262
 
463
- // "block" mode: load all modules, then initialize.
464
- // Guard against destroy() being called while modules are still loading.
465
- this._loadAndRegisterGuards(expandedDescriptors).then(() => {
466
- if (!this._destroyed) MobileRouter.prototype.initialize.call(this);
467
- }).catch(err => {
263
+ // "block" mode: load all modules, then register their guards in declaration order
264
+ // and initialize. Load and registration failures are logged per module and never
265
+ // reject. A router destroyed while modules load stays destroyed.
266
+ const blockLoad = {
267
+ start: true,
268
+ ignoreInitialHash: bIgnoreInitialHash
269
+ };
270
+ this._blockLoad = blockLoad;
271
+ void loadGuardModules(expandedDescriptors).then(results => {
272
+ this._blockLoad = null;
468
273
  if (this._destroyed) return;
469
- Log.error("guardRouter.guards: module loading failed, initializing without manifest guards", String(err), LOG_COMPONENT);
470
- MobileRouter.prototype.initialize.call(this);
274
+ for (const {
275
+ descriptor,
276
+ guards
277
+ } of results) {
278
+ for (const fn of guards) this._registerManifestGuard(descriptor, fn);
279
+ }
280
+ if (blockLoad.start) this._start(blockLoad.ignoreInitialHash);
471
281
  });
472
282
  return this;
473
283
  },
284
+ /**
285
+ * Start the native router. With `ignoreInitialHash` it parses nothing and resumes the route
286
+ * that was displayed when the router stopped. That route is the current one again, on the hash
287
+ * that the URL shows now, so that its leave guards run and a blocked hash change returns to it.
288
+ */
289
+ _start: function _start(ignoreInitialHash) {
290
+ // UI5 only warns about a router that is initialized already.
291
+ const starting = !this.isInitialized();
292
+ if (starting) {
293
+ // Before the listener of UI5 that calls parse(), which initialize() attaches.
294
+ this.getHashChanger().attachEvent("hashChanged", this._onHashReported, this);
295
+ // After the listener of UI5 that informs the routers, which is attached with the hash
296
+ // changer of the first router: UI5 has reported a hash change to every router when
297
+ // this one runs.
298
+ this._rootHashChanger = HashChanger.getInstance();
299
+ this._rootHashChanger.attachEvent("hashChanged", this._onRootHashChanged, this);
300
+ }
301
+ MobileRouter.prototype.initialize.call(this, ignoreInitialHash);
302
+ if (starting && ignoreInitialHash) {
303
+ // UI5 has reset the hash of the hash changer if a target was displayed without a route.
304
+ const shownHash = this.getHashChanger().getHash();
305
+ this._currentRoute = this._stoppedRoute;
306
+ this._currentHash = shownHash ?? null;
307
+ }
308
+ return this;
309
+ },
310
+ /**
311
+ * The hash changer of this router reports a hash change: `parse()` is called with it next.
312
+ *
313
+ * The report is out of date if the hash changer shows a later hash by now, one that it has
314
+ * reported to this router already. That happens to a router that shares its hash changer, as
315
+ * the routers of all components that are not routing targets do: a router that is informed
316
+ * first redirects the hash, UI5 reports the target to every router, and only then the hash
317
+ * that was redirected to the routers that are informed later. A hash changer that reports
318
+ * while a parent router collects the hashes of a navigation shows no hash at all.
319
+ */
320
+ _onHashReported: function _onHashReported(event) {
321
+ // A string, which the UI5 types declare as an object.
322
+ const newHash = event.getParameter("newHash");
323
+ const shown = this.getHashChanger().getHash();
324
+ this._reportedHash = newHash;
325
+ this._reportOutdated = shown !== newHash && shown === this._lastReport;
326
+ if (!this._reportOutdated) this._lastReport = newHash;
327
+ },
328
+ /**
329
+ * UI5 has reported a hash change to every router. The event tells what the URL showed before
330
+ * the change, which is what undoes it. A snapshot of the URL taken at any other time would not
331
+ * do: the URL also changes without an event, as when the Fiori launchpad puts it back after
332
+ * a cross-app navigation that the user cancelled. A navigation that waited for this to put
333
+ * the URL back does so now (see {@link _undoHashChange}).
334
+ */
335
+ _onRootHashChanged: function _onRootHashChanged(event) {
336
+ // A string, which the UI5 types declare as an object.
337
+ const newHash = event.getParameter("newHash");
338
+ // Only the first hash change that the page reports has no previous hash.
339
+ const oldHash = event.getParameter("oldHash") ?? "";
340
+ const hashChanger = HashChanger.getInstance();
341
+ if (hashChanger === this._rootHashChanger) {
342
+ this._completeUndo(newHash, oldHash);
343
+ return;
344
+ }
345
+ // The global hash changer was replaced (HashChanger.replaceHashChanger(), as the shell of
346
+ // the Fiori launchpad does). UI5 has moved this listener to the new one, in front of its
347
+ // listener that informs the routers. From the next hash change on it runs behind again;
348
+ // for this one, the routers are informed once this listener has returned.
349
+ hashChanger.detachEvent("hashChanged", this._onRootHashChanged, this);
350
+ hashChanger.attachEvent("hashChanged", this._onRootHashChanged, this);
351
+ this._rootHashChanger = hashChanger;
352
+ queueMicrotask(() => this._completeUndo(newHash, oldHash));
353
+ },
354
+ /**
355
+ * Tell the undo of the pending navigation what the URL showed before the hash change
356
+ * `newHash`, and put the URL back if the navigation waited for that.
357
+ */
358
+ _completeUndo: function _completeUndo(newHash, oldHash) {
359
+ const undo = this._undo;
360
+ if (!undo || undo.first !== newHash) return;
361
+ undo.fullHash ??= oldHash;
362
+ if (this._phase.kind === "restoring" && this._phase.awaitsReport) this._replaceFullHash(undo.fullHash);
363
+ },
474
364
  /**
475
365
  * Add a route dynamically and integrate it into pattern-tree inheritance.
476
366
  *
477
367
  * Appends the route name to the internal route list so that
478
368
  * `_collectRoutePatterns()` includes it in subsequent inheritance
479
369
  * lookups, clears the metadata cache, and registers any inherited
480
- * manifest guards when `inheritance` is `"pattern-tree"`.
370
+ * manifest guards when `inheritance` is `"pattern-tree"`: on every
371
+ * route, ancestor guards still run before descendant guards.
481
372
  *
482
373
  * @param oConfig - Route configuration object as defined by `sap.ui.core.routing.Route`.
483
- * @param rest - Additional arguments forwarded to the parent `addRoute`.
374
+ * @param oParent - Optional parent route, forwarded to the parent `addRoute`.
484
375
  * @override sap.ui.core.routing.Router#addRoute
485
376
  * @since 1.6.0
486
377
  */
487
- addRoute: function _addRoute(oConfig, ...rest) {
488
- // @ts-expect-error -- oParent is required in the type declaration but optional at runtime
489
- MobileRouter.prototype.addRoute.apply(this, [oConfig, ...rest]);
490
-
491
- // Skip when called by the parent constructor before field initializers have run.
492
- // Routes from the constructor args are captured in _routeNames by the constructor body.
493
- if (!this._routeNames) return;
378
+ addRoute: function _addRoute(oConfig, oParent) {
379
+ MobileRouter.prototype.addRoute.call(this, oConfig, oParent);
494
380
  const name = oConfig.name;
495
- if (typeof name !== "string") return;
381
+ this._routeNames ??= [];
382
+ this._greedyRouteNames ??= [];
496
383
  if (this._routeNames.includes(name)) return;
497
384
  this._routeNames.push(name);
498
- this._resolvedMetaCache.clear();
385
+ if (oConfig.greedy) this._greedyRouteNames.push(name);
386
+ // The UI5 constructor adds the routes of the config before this constructor sets up the rest.
387
+ if (!this._meta) return;
388
+ this._meta.invalidate();
499
389
  if (this._options.inheritance !== "pattern-tree") return;
500
- if (this._sourceDescriptors.length === 0) return;
501
- const route = this.getRoute(name);
502
- if (!route) return;
503
- const newPattern = route.getPattern();
504
- if (newPattern === undefined) return;
505
- const newDescriptors = this._expandGuardDescriptorsForNewRoute(name, newPattern);
506
- if (newDescriptors.length === 0) return;
390
+ const patterns = this._collectRoutePatterns();
391
+ const declared = byRouteDepth(this._sourceDescriptors, new Map(patterns.map(r => [r.name, r.pattern])));
392
+ const rankOf = descriptor => declared.findIndex(entry => entry.source === descriptor.source);
507
393
 
508
394
  // Always use lazy registration: if the module was loaded during
509
395
  // initialize() (block mode), the sync cache probe succeeds immediately.
510
396
  // This avoids an async gap between addRoute() and the first navigation.
511
- this._registerLazyGuards(newDescriptors);
512
- },
513
- /**
514
- * Expand manifest guard descriptors for a single newly added route.
515
- *
516
- * For each source descriptor whose route is an ancestor of the new
517
- * route's pattern, emits a copy targeting the new route. Also emits
518
- * copies for existing routes that are descendants of the new route
519
- * (in case the new route has declared guards). Sorted by depth.
520
- */
521
- _expandGuardDescriptorsForNewRoute: function _expandGuardDescriptorsForNewRoute(newName, newPattern) {
522
- const result = [];
523
- for (const descriptor of this._sourceDescriptors) {
524
- if (descriptor.route === "*") continue;
525
- if (descriptor.route !== newName) {
526
- // Check if the source descriptor's route is an ancestor of the new route.
527
- const ancestorRoute = this.getRoute(descriptor.route);
528
- const ancestorPattern = ancestorRoute?.getPattern();
529
- if (ancestorPattern !== undefined && isPatternAncestor(ancestorPattern, newPattern)) {
530
- result.push({
531
- ...descriptor,
532
- route: newName
533
- });
534
- }
535
- } else {
536
- // The new route itself has a source descriptor: expand to existing descendants.
537
- for (const {
538
- name,
539
- pattern
540
- } of this._collectRoutePatterns()) {
541
- if (name === newName) continue;
542
- if (isPatternAncestor(newPattern, pattern)) {
543
- result.push({
544
- ...descriptor,
545
- route: name
546
- });
547
- }
548
- }
549
- }
397
+ for (const descriptor of expandForNewRoute(this._sourceDescriptors, name, patterns)) {
398
+ // Ancestor guards run first: the new guards go before the manifest guards of the route
399
+ // that stem from an entry of a deeper route, or from a later entry of the same depth.
400
+ const rank = rankOf(descriptor);
401
+ const next = this._manifestGuards.filter(guard => guard.descriptor.route === descriptor.route && guard.descriptor.type === descriptor.type && rankOf(guard.descriptor) > rank).toSorted((a, b) => rankOf(a.descriptor) - rankOf(b.descriptor))[0];
402
+ for (const fn of createLazyGuards(descriptor)) this._registerManifestGuard(descriptor, fn, next?.fn);
550
403
  }
551
-
552
- // Sort by pattern depth (ancestor guards run before descendant guards).
553
- return result.toSorted((a, b) => {
554
- const pa = this.getRoute(a.route)?.getPattern() ?? "";
555
- const pb = this.getRoute(b.route)?.getPattern() ?? "";
556
- return patternSegments(pa).length - patternSegments(pb).length;
557
- });
558
404
  },
559
405
  /**
560
406
  * Register a global guard that runs for every navigation.
@@ -593,9 +439,7 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
593
439
  */
594
440
  addRouteGuard: function _addRouteGuard(routeName, guard) {
595
441
  if (isRouteGuardConfig(guard)) {
596
- if (!this._handleUnknownRouteRegistration(routeName, "addRouteGuard")) {
597
- return this;
598
- }
442
+ this._handleUnknownRouteRegistration(routeName, "addRouteGuard");
599
443
  let hasHandler = false;
600
444
  if (guard.beforeEnter !== undefined) {
601
445
  hasHandler = true;
@@ -611,14 +455,11 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
611
455
  }
612
456
  if (!hasHandler) {
613
457
  Log.info("addRouteGuard: config has no beforeEnter or beforeLeave", routeName, LOG_COMPONENT);
614
- return this;
615
458
  }
616
459
  return this;
617
460
  }
618
461
  if (!this._isFn(guard, "addRouteGuard", routeName)) return this;
619
- if (!this._handleUnknownRouteRegistration(routeName, "addRouteGuard")) {
620
- return this;
621
- }
462
+ this._handleUnknownRouteRegistration(routeName, "addRouteGuard");
622
463
  this._pipeline.addEnterGuard(routeName, guard);
623
464
  return this;
624
465
  },
@@ -662,9 +503,7 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
662
503
  */
663
504
  addLeaveGuard: function _addLeaveGuard(routeName, guard) {
664
505
  if (!this._isFn(guard, "addLeaveGuard", routeName)) return this;
665
- if (!this._handleUnknownRouteRegistration(routeName, "addLeaveGuard")) {
666
- return this;
667
- }
506
+ this._handleUnknownRouteRegistration(routeName, "addLeaveGuard");
668
507
  this._pipeline.addLeaveGuard(routeName, guard);
669
508
  return this;
670
509
  },
@@ -674,20 +513,21 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
674
513
  * UI5's native `navTo` has two signatures where the third parameter is either
675
514
  * `componentTargetInfo` (object) or `bReplace` (boolean). This method normalizes
676
515
  * both forms so the rest of `navTo` can work with a single set of variables.
516
+ * The options follow `bReplace`, or take its place when it is left out.
677
517
  */
678
518
  _resolveNavToArgs: function _resolveNavToArgs(componentTargetInfoOrReplace, replaceOrOptions, options) {
679
519
  if (typeof componentTargetInfoOrReplace === "boolean") {
680
520
  // Short form: navTo(name, params, replace, options?)
681
521
  return {
682
522
  replace: componentTargetInfoOrReplace,
683
- guardOptions: typeof replaceOrOptions === "object" && replaceOrOptions !== null ? replaceOrOptions : undefined
523
+ guardOptions: typeof replaceOrOptions === "object" ? replaceOrOptions : undefined
684
524
  };
685
525
  }
686
526
  // Long form: navTo(name, params, componentTargetInfo, replace, options?)
687
527
  return {
688
528
  componentTargetInfo: componentTargetInfoOrReplace,
689
529
  replace: typeof replaceOrOptions === "boolean" ? replaceOrOptions : undefined,
690
- guardOptions: options
530
+ guardOptions: typeof replaceOrOptions === "object" ? replaceOrOptions : options
691
531
  };
692
532
  },
693
533
  /** Return `true` when the value is a function; otherwise log a warning. */_isFn: function _isFn(value, method, detail) {
@@ -695,21 +535,15 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
695
535
  Log.warning(`${method}: not a function, ignoring`, detail, LOG_COMPONENT);
696
536
  return false;
697
537
  },
698
- /**
699
- * Handle guard registration for a potentially unknown route.
700
- * Returns `true` if registration should proceed, `false` if not.
701
- */
702
- _handleUnknownRouteRegistration: function _handleUnknownRouteRegistration(routeName, methodName) {
703
- if (this.getRoute(routeName)) return true;
538
+ /** Apply the `unknownRouteRegistration` policy: warn or throw when the route is unknown. */_handleUnknownRouteRegistration: function _handleUnknownRouteRegistration(routeName, methodName, kept = "guard registered") {
539
+ if (this.getRoute(routeName)) return;
704
540
  switch (this._options.unknownRouteRegistration) {
705
541
  case "ignore":
706
- return true;
542
+ return;
707
543
  case "throw":
708
544
  throw new Error(`${methodName} called for unknown route "${routeName}". ` + `Set guardRouter.unknownRouteRegistration to "warn" or "ignore" to allow this.`);
709
545
  case "warn":
710
- default:
711
- Log.warning(`${methodName}: unknown route, guard registered anyway`, routeName, LOG_COMPONENT);
712
- return true;
546
+ Log.warning(`${methodName}: unknown route, ${kept} anyway`, routeName, LOG_COMPONENT);
713
547
  }
714
548
  },
715
549
  /**
@@ -744,24 +578,9 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
744
578
  // Empty string is a valid root route name (initial state before first navigation)
745
579
  if (routeName !== "" && !this.getRoute(routeName)) {
746
580
  Log.warning("getRouteMeta: unknown route, returning empty metadata", routeName, LOG_COMPONENT);
747
- return Router._EMPTY_META;
748
- }
749
-
750
- // Cache hit
751
- const cached = this._resolvedMetaCache.get(routeName);
752
- if (cached) return cached;
753
- let result;
754
- if (this._options.inheritance === "pattern-tree") {
755
- result = this._resolveInheritedMeta(routeName);
756
- } else {
757
- result = this._resolveFlatMeta(routeName);
758
- }
759
- if (Object.keys(result).length === 0) {
760
- this._resolvedMetaCache.set(routeName, Router._EMPTY_META);
761
- return Router._EMPTY_META;
581
+ return EMPTY_META;
762
582
  }
763
- this._resolvedMetaCache.set(routeName, result);
764
- return result;
583
+ return this._meta.get(routeName);
765
584
  },
766
585
  /**
767
586
  * Set runtime metadata for a route.
@@ -782,13 +601,8 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
782
601
  Log.warning("setRouteMeta: expected object, ignoring", routeName, LOG_COMPONENT);
783
602
  return this;
784
603
  }
785
- if (routeName !== "" && !this._handleUnknownRouteRegistration(routeName, "setRouteMeta")) {
786
- return this;
787
- }
788
- this._runtimeMeta.set(routeName, Object.freeze({
789
- ...meta
790
- }));
791
- this._resolvedMetaCache.clear();
604
+ if (routeName !== "") this._handleUnknownRouteRegistration(routeName, "setRouteMeta", "metadata stored");
605
+ this._meta.set(routeName, meta);
792
606
  return this;
793
607
  },
794
608
  /**
@@ -799,13 +613,13 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
799
613
  * settlement result. Before any navigation has settled, it falls back to a
800
614
  * synthetic `Committed` result derived from the router's current route/hash
801
615
  * state. After `stop()`, that idle fallback reports empty route/hash values
802
- * until a new navigation settles.
616
+ * until a new navigation settles, or `initialize(true)` resumes the route.
803
617
  *
804
618
  * @returns Promise that resolves with a {@link NavigationResult} once the pipeline settles.
805
619
  * @since 1.2.0
806
620
  */
807
621
  navigationSettled: function _navigationSettled() {
808
- if (this._phase.kind !== "evaluating") {
622
+ if (this._phase.kind === "idle" || this._phase.kind === "committing") {
809
623
  return Promise.resolve(this._lastSettlement ?? {
810
624
  status: NavigationOutcome.Committed,
811
625
  route: this._currentRoute,
@@ -817,8 +631,8 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
817
631
  });
818
632
  },
819
633
  attachNavigationSettled: function _attachNavigationSettled(oData, fnFunction, oListener) {
820
- this.attachEvent("navigationSettled", oData, fnFunction, oListener);
821
- return this;
634
+ // The arguments go on as received: EventProvider#attachEvent tells the two call forms apart.
635
+ return this.attachEvent("navigationSettled", oData, fnFunction, oListener);
822
636
  },
823
637
  /**
824
638
  * Detach a previously attached `navigationSettled` event handler.
@@ -840,12 +654,21 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
840
654
  */
841
655
  _flushSettlement: function _flushSettlement(result) {
842
656
  this._lastSettlement = result;
657
+ Log.debug(`Navigation settled: ${result.status}`, result.hash, LOG_COMPONENT);
658
+ // After the call that settled: by then a commit has reached super.parse(), and a navigation
659
+ // that supersedes this one has started.
660
+ queueMicrotask(() => this._settleMatchWaiters());
843
661
  const resolvers = this._settlementResolvers;
844
662
  this._settlementResolvers = [];
845
663
  for (const resolve of resolvers) {
846
664
  resolve(result);
847
665
  }
848
- this.fireEvent("navigationSettled", result);
666
+ try {
667
+ this.fireEvent("navigationSettled", result);
668
+ } catch (error) {
669
+ // A handler must not keep the router from finishing the navigation it reports.
670
+ Log.error("A navigationSettled handler threw", String(error), LOG_COMPONENT);
671
+ }
849
672
  },
850
673
  navTo: function _navTo(routeName, parameters, componentTargetInfoOrReplace, replaceOrOptions, options) {
851
674
  const {
@@ -861,135 +684,130 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
861
684
  return this;
862
685
  }
863
686
 
864
- // Resolve the target hash so we can build a guard context.
865
- // getURL() returns the hash pattern with parameters substituted.
687
+ // A router that does not listen to hash changes (not initialized, loading block-mode
688
+ // guards, or stopped) navigates like the native one: the guards run once it parses the hash.
689
+ if (!this.isInitialized()) {
690
+ MobileRouter.prototype.navTo.call(this, routeName, parameters, componentTargetInfo, replace);
691
+ return this;
692
+ }
866
693
  const route = this.getRoute(routeName);
867
694
  if (!route) {
868
- // Unknown route -- let parent handle it (may fire bypassed event).
695
+ // Unknown route -- let the parent handle it (it logs a warning).
869
696
  // Cancel any pending async navigation so settlement resolvers drain
870
697
  // and the stale pipeline does not commit a superseded navigation.
871
- this._cancelPendingNavigation();
698
+ this._cancelPendingNavigation(true);
872
699
  MobileRouter.prototype.navTo.call(this, routeName, parameters, componentTargetInfo, replace);
873
700
  return this;
874
701
  }
875
702
  const targetHash = route.getURL(parameters ?? {});
876
- const routeInfo = this.getRouteInfoByHash(targetHash);
877
- const toRoute = routeInfo?.name ?? "";
703
+ const routeInfo = this._matchRoute(targetHash);
704
+ const toRoute = routeInfo.name;
878
705
 
879
- // Same-hash dedup: cancel any pending navigation and return without navigating.
880
- if (this._currentHash !== null && targetHash === this._currentHash) {
881
- this._cancelPendingNavigation();
706
+ // Same hash: no route of this router changes, so there is nothing to guard. Cancel any
707
+ // pending navigation and navigate natively: UI5 still sets the hashes of nested
708
+ // components (componentTargetInfo), or resets them when none are given.
709
+ if (targetHash === this._currentHash) {
710
+ this._cancelPendingNavigation(true);
711
+ // A navigationSettled handler of the cancelled navigation may have navigated on.
712
+ const shownHash = this.getHashChanger().getHash();
713
+ if (shownHash === undefined || shownHash === targetHash) {
714
+ // If UI5 has reset the hash of the hash changer, after a target was displayed without
715
+ // a route, it reports the hash again, and parse() lets the route match again.
716
+ MobileRouter.prototype.navTo.call(this, routeName, parameters, componentTargetInfo, replace);
717
+ }
882
718
  return this;
883
719
  }
720
+ const skipGuards = guardOptions?.skipGuards === true || this._options.navToPreflight === "bypass";
884
721
 
885
722
  // Pending-hash dedup: if an async preflight for this exact hash is
886
- // already running, don't cancel and restart it.
887
- if (this._phase.kind === "evaluating" && targetHash === this._phase.attempt.hash) {
723
+ // already running, don't cancel and restart it. A navigation that skips
724
+ // the guards does not wait for them.
725
+ if (!skipGuards && this._phase.kind === "evaluating" && targetHash === this._phase.attempt.hash) {
888
726
  return this;
889
727
  }
890
728
 
891
- // Cancel any pending navigation (including previous async preflight).
892
- this._cancelPendingNavigation();
893
- const skipGuards = guardOptions?.skipGuards === true;
894
-
895
- // Bypass mode: skip guards for programmatic navTo() -- commit directly.
896
- if (skipGuards || this._options.navToPreflight === "bypass") {
897
- this._phase = {
898
- kind: "committing",
899
- hash: targetHash,
900
- route: toRoute,
901
- origin: "preflight"
902
- };
729
+ // parse() evaluates the guards once the hash has changed. It supersedes a pending
730
+ // navigation then, and undoes the hash change of that navigation with its own.
731
+ if (!skipGuards && this._options.navToPreflight === "off") {
903
732
  MobileRouter.prototype.navTo.call(this, routeName, parameters, componentTargetInfo, replace);
904
- // Safety: if super.navTo didn't trigger parse (e.g. hash didn't change),
905
- // clear the marker to avoid stale state.
906
- if (this._phase.kind === "committing" && this._phase.hash === targetHash) {
907
- this._commitNavigation(targetHash, toRoute);
908
- }
909
733
  return this;
910
734
  }
911
735
 
912
- // Off mode: defer guard evaluation to parse() fallback.
913
- if (this._options.navToPreflight === "off") {
914
- MobileRouter.prototype.navTo.call(this, routeName, parameters, componentTargetInfo, replace);
736
+ // Cancel any pending navigation (including previous async preflight).
737
+ // A superseded hash-change navigation leaves its hash in the URL: restore it
738
+ // unless this navigation moves the URL.
739
+ const restoreHash = this._pendingRestoresHash();
740
+ this._cancelPendingNavigation();
741
+ if (skipGuards) {
742
+ this._navigateAllowed(routeName, parameters, componentTargetInfo, replace, targetHash, toRoute, restoreHash);
915
743
  return this;
916
744
  }
917
-
918
- // Default "guard" mode: evaluate guards before hash change.
919
- const controller = new AbortController();
920
- const generation = this._parseGeneration;
921
- this._phase = {
922
- kind: "evaluating",
923
- attempt: {
924
- hash: targetHash,
925
- route: toRoute,
926
- controller,
927
- generation
928
- }
929
- };
930
- const context = this._createGuardContext(toRoute, targetHash, routeInfo, controller.signal);
931
- const decision = this._pipeline.evaluate(context);
745
+ const attempt = this._startAttempt(targetHash, restoreHash);
746
+ const {
747
+ generation
748
+ } = attempt;
749
+ const context = this._createGuardContext(routeInfo, targetHash, attempt.controller.signal);
750
+ const decision = this._evaluateGuards(context);
932
751
  if (isPromiseLike(decision)) {
933
- decision.then(d => {
934
- if (generation !== this._parseGeneration || this._phase.kind !== "evaluating") {
752
+ this._applyWhenDecided(decision, d => {
753
+ if (generation !== this._parseGeneration) {
935
754
  Log.debug("Async preflight result discarded (superseded by newer navigation)", targetHash, LOG_COMPONENT);
936
755
  return;
937
756
  }
938
- this._applyPreflightDecision(d, routeName, parameters, componentTargetInfo, replace, targetHash, toRoute, context.bag);
939
- }).catch(error => {
940
- // Only check generation here, not phase. If _redirect threw and its
941
- // finally already reset phase to idle, we still need to drain
942
- // settlement resolvers via _errorNavigation.
943
- if (generation !== this._parseGeneration) return;
944
- Log.error(`Async preflight guard failed for route "${routeName}", navigation failed`, String(error), LOG_COMPONENT);
945
- this._errorNavigation(error, targetHash, false);
946
- });
757
+ this._applyPreflightDecision(d, routeName, parameters, componentTargetInfo, replace, targetHash, toRoute, context.bag, attempt);
758
+ }, targetHash, restoreHash);
947
759
  return this;
948
760
  }
949
-
950
- // Sync path: apply the decision immediately.
951
- this._applyPreflightDecision(decision, routeName, parameters, componentTargetInfo, replace, targetHash, toRoute, context.bag);
761
+ this._applyPreflightDecision(decision, routeName, parameters, componentTargetInfo, replace, targetHash, toRoute, context.bag, attempt);
952
762
  return this;
953
763
  },
764
+ /**
765
+ * Navigate to a `navTo()` target that needs no guards (allowed or bypassed) and commit it,
766
+ * or block it if the hash change was refused (see {@link _commitAfterNavTo}).
767
+ */
768
+ _navigateAllowed: function _navigateAllowed(routeName, parameters, componentTargetInfo, bReplace, targetHash, toRoute, restoreHash) {
769
+ this._phase = {
770
+ kind: "committing",
771
+ route: toRoute,
772
+ hash: targetHash,
773
+ origin: "preflight",
774
+ restoreHash,
775
+ writtenOver: HashChanger.getInstance().getHash()
776
+ };
777
+ try {
778
+ MobileRouter.prototype.navTo.call(this, routeName, parameters, componentTargetInfo, bReplace);
779
+ if (!this._commitAfterNavTo(componentTargetInfo)) {
780
+ this._blockNavigation(targetHash, restoreHash);
781
+ }
782
+ } finally {
783
+ // A failed hash change must not leave the next one to be committed without guards.
784
+ if (this._phase.kind === "committing") {
785
+ this._phase = IDLE;
786
+ }
787
+ }
788
+ },
954
789
  /**
955
790
  * Apply a preflight guard decision. For "allow", enter the committing
956
- * phase and call super.navTo(). For "block", flush settlement without
957
- * touching the hash. For "redirect", start a redirect chain.
791
+ * phase and call super.navTo(). For "block", flush settlement; the hash is
792
+ * only touched to restore it after a superseded hash-change navigation.
793
+ * For "redirect", start a redirect chain.
958
794
  * For "error", flush Error settlement with the guard's error.
959
- *
960
- * @param decision - Normalized guard pipeline result.
961
- * @param routeName - Original route name passed to navTo().
962
- * @param parameters - Original route parameters.
963
- * @param componentTargetInfo - Optional component target info from the navTo() overload.
964
- * @param bReplace - Whether to replace the current history entry.
965
- * @param targetHash - Resolved hash for the target route.
966
- * @param toRoute - Resolved route name (may differ from routeName for nested routes).
967
795
  */
968
- _applyPreflightDecision: function _applyPreflightDecision(decision, routeName, parameters, componentTargetInfo, bReplace, targetHash, toRoute, bag) {
796
+ _applyPreflightDecision: function _applyPreflightDecision(decision, routeName, parameters, componentTargetInfo, bReplace, targetHash, toRoute, bag, attempt) {
797
+ // A guard that navigated itself has superseded the navigation it was guarding.
798
+ if (attempt.generation !== this._parseGeneration) return;
969
799
  switch (decision.action) {
970
800
  case "allow":
971
- this._phase = {
972
- kind: "committing",
973
- hash: targetHash,
974
- route: toRoute,
975
- origin: "preflight"
976
- };
977
- MobileRouter.prototype.navTo.call(this, routeName, parameters, componentTargetInfo, bReplace);
978
- // Safety: if super.navTo didn't trigger parse (e.g. hash didn't change),
979
- // clear the marker to avoid stale state.
980
- if (this._phase.kind === "committing" && this._phase.hash === targetHash) {
981
- // Hash didn't change, so parse() wasn't called. Commit manually.
982
- this._commitNavigation(targetHash, toRoute);
983
- }
801
+ this._navigateAllowed(routeName, parameters, componentTargetInfo, bReplace, targetHash, toRoute, attempt.restoreHash);
984
802
  break;
985
803
  case "block":
986
- this._blockNavigation(targetHash, false);
804
+ this._blockNavigation(targetHash, attempt.restoreHash);
987
805
  break;
988
806
  case "redirect":
989
- this._startRedirectChain(decision.target, targetHash, false, bag);
807
+ this._startRedirectChain(decision.target, targetHash, bag, attempt, bReplace);
990
808
  break;
991
809
  case "error":
992
- this._errorNavigation(decision.error, targetHash, false);
810
+ this._errorNavigation(decision.error, targetHash, attempt.restoreHash);
993
811
  break;
994
812
  }
995
813
  },
@@ -1007,105 +825,211 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1007
825
  * @since 1.0.1
1008
826
  */
1009
827
  parse: function _parse(newHash) {
1010
- if (this._suppressedHash !== null) {
1011
- if (newHash === this._suppressedHash) {
1012
- this._suppressedHash = null;
1013
- return;
1014
- }
1015
- this._suppressedHash = null;
828
+ if (this._destroyed) {
829
+ // The base router only warns about a hash change that reaches a destroyed router.
830
+ MobileRouter.prototype.parse.call(this, newHash);
831
+ return;
1016
832
  }
1017
- if (this._phase.kind === "committing") {
1018
- this._commitNavigation(newHash, this._phase.route !== "" ? this._phase.route : this.getRouteInfoByHash(newHash)?.name ?? "");
833
+ const reported = this._reportedHash === newHash;
834
+ this._reportedHash = null;
835
+ // The URL shows a later hash, which this router has parsed.
836
+ if (reported && this._reportOutdated) return;
837
+ // The hash that _restoreHash() is writing.
838
+ if (newHash === this._suppressedHash) return;
839
+ const undo = this._undo;
840
+ if (undo?.started && undo.fullHash === HashChanger.getInstance().getHash()) {
841
+ // The URL is back where the router has put it (see _undoHashChange), so nothing is
842
+ // evaluated. What the hash changer reports now is the hash of the route that is shown.
843
+ this._undo = null;
844
+ this._currentHash = newHash;
845
+ this._finishRestore(newHash);
1019
846
  return;
1020
847
  }
1021
- if (this._currentHash !== null && newHash === this._currentHash) {
1022
- this._cancelPendingNavigation();
848
+ const phase = this._phase;
849
+ const commit = phase.kind === "awaitingHash" ? phase.commit : phase.kind === "committing" ? phase : null;
850
+ if (commit?.hash === newHash) {
851
+ this._phase = commit;
852
+ this._commitNavigation(newHash, commit.route);
1023
853
  return;
1024
854
  }
1025
- const routeInfo = this.getRouteInfoByHash(newHash);
1026
- const toRoute = routeInfo?.name ?? "";
1027
- this._cancelPendingNavigation();
1028
- const controller = new AbortController();
1029
- const generation = this._parseGeneration;
1030
- this._phase = {
1031
- kind: "evaluating",
1032
- attempt: {
1033
- hash: newHash,
1034
- route: toRoute,
1035
- controller,
1036
- generation
855
+ const currentHash = this._currentHash;
856
+ if (newHash === currentHash) {
857
+ if (this._pendingRestoresHash()) {
858
+ // The URL is back on the committed hash, whose route was never left. That ends the
859
+ // navigation that had moved it away; one that waits for UI5 to write its hash goes on.
860
+ if (this._phase.kind === "evaluating") this._cancelPendingNavigation();else this._undo = null;
861
+ } else {
862
+ // The committed hash is reported again, and its route matches again as it does
863
+ // natively: UI5 has written the hash of a navigation with component targets, or has
864
+ // reset the hash of the hash changer after a target was displayed without a route,
865
+ // or parse() was called directly.
866
+ MobileRouter.prototype.parse.call(this, newHash);
1037
867
  }
1038
- };
1039
- const context = this._createGuardContext(toRoute, newHash, routeInfo, controller.signal);
1040
- const decision = this._pipeline.evaluate(context);
868
+ return;
869
+ }
870
+ const routeInfo = this._matchRoute(newHash);
871
+ const toRoute = routeInfo.name;
872
+
873
+ // A pending navigation that has moved the URL as well leaves this one to undo both changes.
874
+ const pendingUndo = this._pendingRestoresHash() ? undo : null;
875
+ // The router is putting the URL back and gets another hash: that one is not undone as a
876
+ // whole, so that an undo cannot cause the next one.
877
+ const undoing = this._phase.kind === "restoring";
878
+ this._cancelPendingNavigation();
879
+ // A navigationSettled handler that navigated on the cancellation has moved the URL on.
880
+ if (this._currentHash !== currentHash) return;
881
+ this._undo = undoing ? null : this._describeUndo(pendingUndo, reported);
882
+ // Another listener of the hash change that navTo() caused has replaced the hash, before
883
+ // this router received it: undoing this hash change undoes the one of navTo() as well.
884
+ if (this._undo && commit === phase && !commit.restoreHash) this._undo.fullHash = commit.writtenOver;
885
+ const direction = reported ? History.getInstance().getDirection() : undefined;
886
+ const attempt = this._startAttempt(newHash, true, direction);
887
+ const {
888
+ generation
889
+ } = attempt;
890
+ const context = this._createGuardContext(routeInfo, newHash, attempt.controller.signal);
891
+ const decision = this._evaluateGuards(context);
1041
892
  if (isPromiseLike(decision)) {
1042
- decision.then(d => {
1043
- if (generation !== this._parseGeneration || this._phase.kind !== "evaluating") {
893
+ this._applyWhenDecided(decision, d => {
894
+ if (generation !== this._parseGeneration) {
1044
895
  Log.debug("Async guard result discarded (superseded by newer navigation)", newHash, LOG_COMPONENT);
1045
896
  return;
1046
897
  }
1047
- this._applyDecision(d, newHash, toRoute, context.bag);
1048
- }).catch(error => {
1049
- // Only check generation here, not phase. If _redirect threw and its
1050
- // finally already reset phase to idle, we still need to drain
1051
- // settlement resolvers via _errorNavigation.
1052
- if (generation !== this._parseGeneration) return;
1053
- Log.error(`Guard pipeline failed for "${newHash}", navigation failed`, String(error), LOG_COMPONENT);
1054
- this._errorNavigation(error, newHash);
1055
- });
898
+ this._applyDecision(d, newHash, toRoute, context.bag, attempt);
899
+ }, newHash, true);
1056
900
  return;
1057
901
  }
1058
- this._applyDecision(decision, newHash, toRoute, context.bag);
902
+ this._applyDecision(decision, newHash, toRoute, context.bag, attempt);
1059
903
  },
1060
904
  /**
1061
905
  * Stop listening to hash changes and reset guard state.
1062
906
  *
1063
907
  * Resets `_currentRoute` and `_currentHash` so that a subsequent
1064
908
  * `initialize()` re-parses the current hash and fires `routeMatched`,
1065
- * matching the native `sap.m.routing.Router` behavior.
909
+ * matching the native `sap.m.routing.Router` behavior. The route is
910
+ * kept for `initialize(true)`, which resumes it instead.
1066
911
  *
1067
912
  * @override sap.ui.core.routing.Router#stop
1068
913
  * @since 1.0.1
1069
914
  */
1070
915
  stop: function _stop() {
916
+ if (this._blockLoad) this._blockLoad.start = false;
1071
917
  // Cancel first so in-flight navigationSettled() resolvers receive the
1072
918
  // Cancelled result before _lastSettlement is cleared below.
1073
919
  this._cancelPendingNavigation();
1074
- this._suppressedHash = null;
920
+ // A hash change that was to put the URL back does not reach a stopped router.
921
+ this._undo = null;
922
+ // Nothing is committed on a router that is stopped already, or stops before its first navigation settles.
923
+ if (this._currentHash !== null) this._stoppedRoute = this._currentRoute;
1075
924
  this._currentRoute = "";
1076
925
  this._currentHash = null;
1077
926
  this._lastSettlement = null;
927
+ this._detachHashListeners();
1078
928
  MobileRouter.prototype.stop.call(this);
1079
929
  return this;
1080
930
  },
931
+ /** Detach what {@link _start} has attached. */_detachHashListeners: function _detachHashListeners() {
932
+ this.getHashChanger().detachEvent("hashChanged", this._onHashReported, this);
933
+ // UI5 moves the listener along when the global hash changer is replaced.
934
+ HashChanger.getInstance().detachEvent("hashChanged", this._onRootHashChanged, this);
935
+ this._rootHashChanger = null;
936
+ },
1081
937
  /**
1082
938
  * Invalidate any in-flight async guard work. Bumps the generation counter
1083
939
  * so pending `.then()` callbacks see they are stale, aborts the signal,
1084
- * and transitions to idle.
940
+ * and transitions to idle. A navigation that waits for its guards or for
941
+ * its hash settles as `Cancelled`. With `restoreHash`, a cancelled hash-change
942
+ * navigation also gets its hash restored: `navTo()` passes it when the
943
+ * call itself will not move the URL.
1085
944
  */
1086
- _cancelPendingNavigation: function _cancelPendingNavigation() {
945
+ _cancelPendingNavigation: function _cancelPendingNavigation(restoreHash = false) {
1087
946
  ++this._parseGeneration;
1088
- if (this._phase.kind === "evaluating") {
1089
- this._phase.attempt.controller.abort();
1090
- this._flushSettlement({
1091
- status: NavigationOutcome.Cancelled,
1092
- route: this._currentRoute,
1093
- hash: this._currentHash ?? ""
1094
- });
1095
- }
947
+ const phase = this._phase;
948
+ const pendingRestoresHash = this._pendingRestoresHash();
949
+ // Idle before the settlement fires, so that a handler can navigate.
1096
950
  this._phase = IDLE;
951
+ // A navigation that is committing ends with the navigation that supersedes it.
952
+ if (phase.kind === "idle" || phase.kind === "committing") return;
953
+ if (phase.kind === "restoring") {
954
+ // A navigation that waits for the URL to be back has ended already: it settles as it ended.
955
+ this._flushSettlement(phase.result);
956
+ return;
957
+ }
958
+ if (phase.kind === "evaluating") phase.attempt.controller.abort();
959
+ this._settleUncommitted({
960
+ status: NavigationOutcome.Cancelled,
961
+ route: this._currentRoute,
962
+ hash: this._currentHash ?? ""
963
+ }, phase.kind === "evaluating" ? phase.attempt.hash : phase.commit.hash, restoreHash && pendingRestoresHash);
964
+ },
965
+ /**
966
+ * Whether the pending navigation leaves a hash in the URL that never committed, the one of a
967
+ * hash-change navigation: it must be restored unless a navigation moves the URL.
968
+ */
969
+ _pendingRestoresHash: function _pendingRestoresHash() {
970
+ const phase = this._phase;
971
+ if (phase.kind === "evaluating") return phase.attempt.restoreHash;
972
+ if (phase.kind === "committing") return phase.restoreHash;
973
+ return phase.kind === "awaitingHash" && phase.commit.restoreHash;
974
+ },
975
+ /**
976
+ * Start evaluating a navigation. Its generation is its own, so the result of any earlier
977
+ * attempt is stale: also one that a navigationSettled handler started while this
978
+ * navigation cancelled its predecessor, which is aborted here without a settlement.
979
+ */
980
+ _startAttempt: function _startAttempt(hash, restoreHash, direction) {
981
+ if (this._phase.kind === "evaluating") this._phase.attempt.controller.abort();
982
+ const attempt = {
983
+ hash,
984
+ controller: new AbortController(),
985
+ generation: ++this._parseGeneration,
986
+ restoreHash,
987
+ direction
988
+ };
989
+ this._phase = {
990
+ kind: "evaluating",
991
+ attempt
992
+ };
993
+ return attempt;
994
+ },
995
+ /**
996
+ * Apply the decision of async guards once it is there. Until then the navigation is postponed,
997
+ * which UI5 sees as a route match in progress (see {@link _mirrorMatchingProcess}). The pipeline
998
+ * turns a failing guard into an error decision, so an error thrown here comes from applying the
999
+ * decision, which has no caller to throw to: it is logged, and fails the navigation unless that
1000
+ * has settled.
1001
+ */
1002
+ _applyWhenDecided: function _applyWhenDecided(decision, apply, attemptedHash, restoreHash) {
1003
+ if (this._phase.kind === "evaluating") this._phase = {
1004
+ ...this._phase,
1005
+ postponed: true
1006
+ };
1007
+ decision.then(d => {
1008
+ const lastSettlement = this._lastSettlement;
1009
+ try {
1010
+ apply(d);
1011
+ } catch (error) {
1012
+ Log.error("Navigation failed after its guards had settled", error instanceof Error ? error : String(error), LOG_COMPONENT);
1013
+ if (this._lastSettlement === lastSettlement) {
1014
+ this._errorNavigation(error, attemptedHash, restoreHash);
1015
+ }
1016
+ }
1017
+ });
1097
1018
  },
1098
1019
  /**
1099
1020
  * Apply a guard decision for the parse() fallback path.
1100
1021
  */
1101
- _applyDecision: function _applyDecision(decision, hash, route, bag) {
1022
+ _applyDecision: function _applyDecision(decision, hash, route, bag, attempt) {
1023
+ // A guard that navigated itself has superseded the navigation it was guarding.
1024
+ if (attempt.generation !== this._parseGeneration) return;
1102
1025
  switch (decision.action) {
1103
1026
  case "allow":
1104
1027
  this._phase = {
1105
1028
  kind: "committing",
1106
- hash,
1107
1029
  route,
1108
- origin: "parse"
1030
+ hash,
1031
+ origin: "parse",
1032
+ restoreHash: false
1109
1033
  };
1110
1034
  this._commitNavigation(hash, route);
1111
1035
  break;
@@ -1113,24 +1037,52 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1113
1037
  this._blockNavigation(hash);
1114
1038
  break;
1115
1039
  case "redirect":
1116
- this._startRedirectChain(decision.target, hash, true, bag);
1040
+ // The hash that redirects has reached the browser: the target takes its history entry.
1041
+ this._startRedirectChain(decision.target, hash, bag, attempt, true);
1117
1042
  break;
1118
1043
  case "error":
1119
1044
  this._errorNavigation(decision.error, hash);
1120
1045
  break;
1121
1046
  }
1122
1047
  },
1048
+ /**
1049
+ * Leave the title history of UI5 (`getTitleHistory()`) as after the native equivalent of a
1050
+ * redirected hash change: the hash change, then `navTo(target, ..., true)`. The route of the
1051
+ * hash change never matched, so UI5 has not handled its title:
1052
+ * - A new entry or a step forward would have added a title, which the title of the target
1053
+ * replaces: UI5 must not remove the title of the route before it.
1054
+ * - A step back would have removed the title of the route that was left, so that the target
1055
+ * replaces the title of the entry the step arrived at: UI5 removes the first for the
1056
+ * replaced hash, the router removes the second, under the condition of UI5 for a step back.
1057
+ */
1058
+ _alignTitleHistory: function _alignTitleHistory(direction) {
1059
+ if (direction === HistoryDirection.NewEntry || direction === HistoryDirection.Forwards) {
1060
+ Reflect.set(this, "_bLastHashReplaced", false);
1061
+ } else if (direction === HistoryDirection.Backwards) {
1062
+ const titles = this.getTitleHistory();
1063
+ const left = titles.at(-1);
1064
+ const replaced = titles.at(-2);
1065
+ if (isRecord(left) && isRecord(replaced) && !left.isHome && left.title !== replaced.title) {
1066
+ titles.splice(-2, 1);
1067
+ }
1068
+ }
1069
+ },
1123
1070
  /**
1124
1071
  * Delegate to the parent router and update internal state.
1125
1072
  *
1126
1073
  * State is updated BEFORE calling parse to ensure that if event handlers
1127
1074
  * (e.g., routeMatched) trigger nested navigation, the leave guards will
1128
- * run for the correct (new) route rather than the old one.
1075
+ * run for the correct (new) route rather than the old one. The settlement
1076
+ * fires before parse as well, so the settlements of such nested navigations
1077
+ * follow it.
1129
1078
  */
1130
1079
  _commitNavigation: function _commitNavigation(hash, route) {
1131
1080
  const wasRedirect = this._phase.kind === "committing" && this._phase.origin === "redirect";
1081
+ if (this._phase.kind === "committing") this._alignTitleHistory(this._phase.direction);
1082
+ // The URL has moved on: a hash change that was to put it back is not awaited any more.
1083
+ this._undo = null;
1132
1084
  this._currentHash = hash;
1133
- this._currentRoute = route ?? this.getRouteInfoByHash(hash)?.name ?? "";
1085
+ this._currentRoute = route;
1134
1086
  // Transition to idle before super.parse so that routeMatched/patternMatched
1135
1087
  // handlers that call navTo() go through the full guard pipeline.
1136
1088
  this._phase = IDLE;
@@ -1139,13 +1091,40 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1139
1091
  route: this._currentRoute,
1140
1092
  hash
1141
1093
  });
1094
+ // A navigationSettled handler that navigated on has committed its own hash.
1095
+ if (this._currentHash !== hash) return;
1142
1096
  MobileRouter.prototype.parse.call(this, hash);
1143
1097
  },
1098
+ /**
1099
+ * Commit the navigation of the committing phase after `super.navTo()` unless `parse()` has
1100
+ * committed it. Returns whether the navigation takes place:
1101
+ * - The hash changer shows the target hash: the route matches here.
1102
+ * - UI5 writes the hash later, which it does with component targets, once the nested
1103
+ * components are loaded. The navigation waits for it: it commits, and the route matches,
1104
+ * when `parse()` gets that hash, as the route does natively. Committed here, the router
1105
+ * would be on a route that UI5 does not display if the hash is never written.
1106
+ * - Otherwise the hash changer has refused the hash change, as the Fiori launchpad does while
1107
+ * it asks the user about unsaved data. Nothing changed, so nothing is committed.
1108
+ */
1109
+ _commitAfterNavTo: function _commitAfterNavTo(componentTargetInfo) {
1110
+ const phase = this._phase;
1111
+ if (phase.kind !== "committing") return true;
1112
+ if (this.getHashChanger().getHash() === phase.hash) {
1113
+ this._commitNavigation(phase.hash, phase.route);
1114
+ return true;
1115
+ }
1116
+ if (!componentTargetInfo || Object.keys(componentTargetInfo).length === 0) return false;
1117
+ this._phase = {
1118
+ kind: "awaitingHash",
1119
+ commit: phase
1120
+ };
1121
+ return true;
1122
+ },
1144
1123
  /**
1145
1124
  * Evaluate guards on a redirect target and apply the resulting decision.
1146
1125
  *
1147
- * Handles loop detection (visited-hash set + depth cap), unknown-route
1148
- * fallback, sync/async guard evaluation, and recursive chaining when
1126
+ * Handles the unknown-route block, loop detection (visited-hash set +
1127
+ * depth cap), sync/async guard evaluation, and recursive chaining when
1149
1128
  * the target's guard itself returns a redirect. All hops in a chain
1150
1129
  * share the same AbortSignal and generation counter from the original
1151
1130
  * navigation so that a superseding navigation correctly discards
@@ -1156,19 +1135,21 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1156
1135
  */
1157
1136
  _redirect: function _redirect(target, chain) {
1158
1137
  const targetName = typeof target === "string" ? target : target.route;
1159
- let targetHash = null;
1160
- const targetParameters = typeof target === "string" ? {} : target.parameters ?? {};
1161
1138
  const targetRoute = this.getRoute(targetName);
1162
- if (targetRoute) {
1163
- try {
1164
- targetHash = targetRoute.getURL(targetParameters);
1165
- } catch {
1166
- targetHash = null;
1167
- }
1139
+ if (!targetRoute) {
1140
+ Log.warning(`Guard redirect target "${targetName}" is not a known route, treating as blocked`, undefined, LOG_COMPONENT);
1141
+ this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1142
+ return;
1168
1143
  }
1169
-
1170
- // Loop detection: visited set (exact hash match) + depth cap.
1171
- if (targetHash !== null && chain.visited.has(targetHash)) {
1144
+ let targetHash;
1145
+ try {
1146
+ targetHash = targetRoute.getURL(typeof target === "string" ? {} : target.parameters ?? {});
1147
+ } catch (error) {
1148
+ Log.error(`Guard redirect target "${targetName}" has no valid hash, navigation failed`, String(error), LOG_COMPONENT);
1149
+ this._errorNavigation(error, chain.attemptedHash, chain.restoreHash);
1150
+ return;
1151
+ }
1152
+ if (chain.visited.has(targetHash)) {
1172
1153
  Log.error(`Guard redirect loop detected: ${[...chain.visited, targetHash].join(" -> ")}`, undefined, LOG_COMPONENT);
1173
1154
  this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1174
1155
  return;
@@ -1178,120 +1159,78 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1178
1159
  this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1179
1160
  return;
1180
1161
  }
1181
- if (targetHash !== null) {
1182
- chain.visited.add(targetHash);
1183
- }
1184
-
1185
- // If the target route doesn't exist or the hash couldn't be resolved,
1186
- // attempt navTo (parent may fire bypassed) and fall back to blocked.
1187
- if (targetHash === null) {
1188
- const settlementBefore = this._lastSettlement;
1189
- this._phase = {
1190
- kind: "committing",
1191
- hash: "",
1192
- route: targetName,
1193
- origin: "redirect"
1194
- };
1195
- try {
1196
- if (typeof target === "string") {
1197
- this.navTo(target, {}, {}, true);
1198
- } else {
1199
- this.navTo(target.route, target.parameters ?? {}, target.componentTargetInfo, true);
1200
- }
1201
- } finally {
1202
- if (this._phase.kind === "committing") {
1203
- this._phase = IDLE;
1204
- }
1205
- }
1206
- if (this._lastSettlement === settlementBefore) {
1207
- Log.warning(`Guard redirect target "${targetName}" did not produce a navigation, treating as blocked`, undefined, LOG_COMPONENT);
1208
- this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1209
- }
1210
- return;
1211
- }
1212
-
1213
- // Narrowed after the null-branch early return; const carries it into the async closure.
1214
- const resolvedHash = targetHash;
1215
-
1216
- // Build guard context for the redirect target.
1217
- const routeInfo = this.getRouteInfoByHash(resolvedHash);
1218
- const context = {
1219
- toRoute: routeInfo?.name ?? "",
1220
- toHash: resolvedHash,
1221
- toArguments: routeInfo?.arguments ?? {},
1222
- fromRoute: chain.fromRoute,
1223
- fromHash: chain.fromHash,
1224
- signal: chain.signal,
1225
- bag: chain.bag,
1226
- toMeta: this.getRouteMeta(routeInfo?.name ?? ""),
1227
- fromMeta: this.getRouteMeta(chain.fromRoute)
1228
- };
1229
- const decision = this._pipeline.evaluate(context, {
1230
- skipLeaveGuards: true
1231
- });
1162
+ chain.visited.add(targetHash);
1163
+ const routeInfo = this._matchRoute(targetHash);
1164
+ const toRoute = routeInfo.name;
1165
+ const context = this._createGuardContext(routeInfo, targetHash, chain.signal, chain);
1166
+ const decision = this._evaluateGuards(context, true);
1232
1167
  if (isPromiseLike(decision)) {
1233
- decision.then(d => {
1234
- if (chain.generation !== this._parseGeneration) return;
1235
- this._applyRedirectDecision(d, target, resolvedHash, chain);
1236
- }).catch(error => {
1237
- if (chain.generation !== this._parseGeneration) return;
1238
- Log.error(`Guard pipeline failed during redirect chain for "${targetName}", navigation failed`, String(error), LOG_COMPONENT);
1239
- this._errorNavigation(error, chain.attemptedHash, chain.restoreHash);
1240
- });
1168
+ this._applyWhenDecided(decision, d => this._applyRedirectDecision(d, target, targetHash, toRoute, chain), chain.attemptedHash, chain.restoreHash);
1241
1169
  return;
1242
1170
  }
1243
- this._applyRedirectDecision(decision, target, resolvedHash, chain);
1171
+ this._applyRedirectDecision(decision, target, targetHash, toRoute, chain);
1244
1172
  },
1245
1173
  /**
1246
1174
  * Apply a guard decision within a redirect chain. For "allow", enter
1247
- * committing phase and delegate to navTo (which hits the existing bypass).
1175
+ * committing phase and delegate to navTo (which hits the existing bypass);
1176
+ * if that does not reach parse(), commit the target directly. A target that
1177
+ * is displayed already settles the navigation without a commit.
1248
1178
  * For "block", block the entire chain. For "redirect", recurse.
1249
1179
  *
1250
1180
  * @param decision - Normalized guard pipeline result for this hop.
1251
1181
  * @param target - The redirect target (route name or {@link GuardRedirect}).
1252
- * @param targetHash - Resolved hash for the redirect target (guaranteed non-null).
1182
+ * @param targetHash - Resolved hash for the redirect target.
1183
+ * @param toRoute - Route that matches the hash, as in the hop's guard context: the route UI5 displays.
1253
1184
  * @param chain - Shared redirect chain context with visited set, signals, etc.
1254
1185
  */
1255
- _applyRedirectDecision: function _applyRedirectDecision(decision, target, targetHash, chain) {
1186
+ _applyRedirectDecision: function _applyRedirectDecision(decision, target, targetHash, toRoute, chain) {
1187
+ // Superseded while the hop's guards ran: by a newer navigation, or by a guard that navigated.
1188
+ if (chain.generation !== this._parseGeneration) return;
1256
1189
  switch (decision.action) {
1257
1190
  case "allow":
1258
1191
  {
1259
- const targetName = typeof target === "string" ? target : target.route;
1260
- const settlementBefore = this._lastSettlement;
1192
+ const componentTargetInfo = typeof target === "string" ? undefined : target.componentTargetInfo;
1193
+ if (targetHash === this._currentHash) {
1194
+ // The target is displayed already, so no route matches again, as for a navTo() to
1195
+ // the committed hash: the URL is put back and UI5 sets the hashes of nested components.
1196
+ this._phase = IDLE;
1197
+ this._settleUncommitted({
1198
+ status: NavigationOutcome.Redirected,
1199
+ route: this._currentRoute,
1200
+ hash: targetHash
1201
+ }, chain.attemptedHash, chain.restoreHash, typeof target !== "string" && componentTargetInfo ? () => {
1202
+ // Unless a settlement handler has moved the URL on.
1203
+ if (this.getHashChanger().getHash() !== targetHash) return;
1204
+ MobileRouter.prototype.navTo.call(this, target.route, target.parameters ?? {}, componentTargetInfo, chain.replace);
1205
+ } : undefined);
1206
+ break;
1207
+ }
1261
1208
  this._phase = {
1262
1209
  kind: "committing",
1210
+ route: toRoute,
1263
1211
  hash: targetHash,
1264
- route: targetName,
1265
- origin: "redirect"
1212
+ origin: "redirect",
1213
+ direction: chain.direction,
1214
+ restoreHash: chain.restoreHash,
1215
+ writtenOver: HashChanger.getInstance().getHash()
1266
1216
  };
1267
1217
  try {
1218
+ // Writing the hash the URL already shows changes nothing, except that a nested
1219
+ // router would add its prefix for an empty hash (see _restoreHash).
1220
+ const hashShown = this.getHashChanger().getHash() === targetHash;
1268
1221
  if (typeof target === "string") {
1269
- this.navTo(target, {}, {}, true);
1270
- } else {
1271
- this.navTo(target.route, target.parameters ?? {}, target.componentTargetInfo, true);
1222
+ if (!hashShown) this.navTo(target, {}, {}, chain.replace);
1223
+ } else if (!hashShown || componentTargetInfo) {
1224
+ this.navTo(target.route, target.parameters ?? {}, componentTargetInfo, chain.replace);
1225
+ }
1226
+ if (!this._commitAfterNavTo(componentTargetInfo)) {
1227
+ this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1272
1228
  }
1273
1229
  } finally {
1274
1230
  if (this._phase.kind === "committing") {
1275
1231
  this._phase = IDLE;
1276
1232
  }
1277
1233
  }
1278
- // Safety net: if navTo didn't produce a settlement (e.g. unknown route
1279
- // or redirect to current hash where HashChanger doesn't fire), handle it.
1280
- if (this._lastSettlement === settlementBefore) {
1281
- const redirectsToCurrentHash = targetHash === (this._currentHash ?? "");
1282
- if (redirectsToCurrentHash) {
1283
- this._phase = {
1284
- kind: "committing",
1285
- hash: this._currentHash ?? "",
1286
- route: this._currentRoute,
1287
- origin: "redirect"
1288
- };
1289
- this._commitNavigation(this._currentHash ?? "", this._currentRoute);
1290
- return;
1291
- }
1292
- Log.warning(`Guard redirect target "${targetName}" did not produce a navigation, treating as blocked`, undefined, LOG_COMPONENT);
1293
- this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1294
- }
1295
1234
  break;
1296
1235
  }
1297
1236
  case "block":
@@ -1305,39 +1244,65 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1305
1244
  break;
1306
1245
  }
1307
1246
  },
1247
+ /** The route that matches a hash, and its arguments. For a hash that no route matches: no route (`""`), no arguments. */_matchRoute: function _matchRoute(hash) {
1248
+ const info = this.getRouteInfoByHash(hash);
1249
+ return {
1250
+ name: info?.name ?? "",
1251
+ arguments: info?.arguments ?? {}
1252
+ };
1253
+ },
1254
+ /**
1255
+ * The greedy routes that match `hash` in addition to `firstMatch`, the first route that
1256
+ * matches it. UI5 matches them as well and fires their events.
1257
+ */
1258
+ _greedyMatches: function _greedyMatches(hash, firstMatch) {
1259
+ return this._greedyRouteNames.filter(name => name !== firstMatch && this.getRoute(name)?.match(hash));
1260
+ },
1308
1261
  /**
1309
- * Build a guard context for a new navigation.
1310
- * Called by {@link navTo} (preflight path) and {@link parse} (browser-initiated path).
1262
+ * Evaluate the guards of a navigation: of the routes in its context, and of the greedy routes
1263
+ * that are left and entered with them. A hop of a redirect chain leaves no route.
1311
1264
  */
1312
- _createGuardContext: function _createGuardContext(toRoute, toHash, routeInfo, signal) {
1265
+ _evaluateGuards: function _evaluateGuards(context, redirectHop = false) {
1266
+ return this._pipeline.evaluate(context, {
1267
+ skipLeaveGuards: redirectHop,
1268
+ alsoLeaving: this._greedyMatches(context.fromHash, context.fromRoute),
1269
+ alsoEntering: this._greedyMatches(context.toHash, context.toRoute)
1270
+ });
1271
+ },
1272
+ /**
1273
+ * Build the guard context of a navigation to `routeInfo`. A hop of a redirect chain passes the
1274
+ * chain, whose source route, source hash and bag are those of the original navigation.
1275
+ */
1276
+ _createGuardContext: function _createGuardContext(routeInfo, toHash, signal, chain) {
1277
+ const fromRoute = chain ? chain.fromRoute : this._currentRoute;
1313
1278
  return {
1314
- toRoute,
1279
+ toRoute: routeInfo.name,
1315
1280
  toHash,
1316
- toArguments: routeInfo?.arguments ?? {},
1317
- fromRoute: this._currentRoute,
1318
- fromHash: this._currentHash ?? "",
1281
+ toArguments: routeInfo.arguments,
1282
+ fromRoute,
1283
+ fromHash: chain ? chain.fromHash : this._currentHash ?? "",
1319
1284
  signal,
1320
- bag: new Map(),
1321
- toMeta: this.getRouteMeta(toRoute),
1322
- fromMeta: this.getRouteMeta(this._currentRoute)
1285
+ bag: chain ? chain.bag : new Map(),
1286
+ toMeta: this.getRouteMeta(routeInfo.name),
1287
+ fromMeta: this.getRouteMeta(fromRoute),
1288
+ ownerComponent: this._ownerComponent
1323
1289
  };
1324
1290
  },
1325
1291
  /**
1326
- * Start a new redirect chain from the current evaluating phase.
1292
+ * Start a new redirect chain for the given evaluating attempt.
1327
1293
  * Called by {@link _applyPreflightDecision} and {@link _applyDecision}
1328
1294
  * when a guard returns a redirect. Delegates to {@link _redirect} with
1329
1295
  * a fresh {@link RedirectChainContext}.
1330
1296
  */
1331
- _startRedirectChain: function _startRedirectChain(target, hash, restoreHash, bag) {
1332
- const {
1333
- attempt
1334
- } = this._phase;
1297
+ _startRedirectChain: function _startRedirectChain(target, hash, bag, attempt, replace) {
1335
1298
  const visited = new Set();
1336
1299
  visited.add(hash);
1337
1300
  this._redirect(target, {
1338
1301
  visited,
1339
1302
  attemptedHash: hash,
1340
- restoreHash,
1303
+ restoreHash: attempt.restoreHash,
1304
+ replace,
1305
+ direction: attempt.direction,
1341
1306
  fromRoute: this._currentRoute,
1342
1307
  fromHash: this._currentHash ?? "",
1343
1308
  signal: attempt.controller.signal,
@@ -1346,19 +1311,17 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1346
1311
  });
1347
1312
  },
1348
1313
  /**
1349
- * Clear pending state and flush a Blocked settlement.
1350
- * When `restoreHash` is true (default), also restores the browser hash
1351
- * to `_currentHash`. Preflight callers pass false because the hash was
1352
- * never changed.
1314
+ * Settle as Blocked. With `restoreHash` (default), the hash change of the navigation is
1315
+ * undone first (see {@link _settleUncommitted}). Preflight callers pass false unless they
1316
+ * superseded a hash-change navigation: otherwise the hash was never changed.
1353
1317
  */
1354
1318
  _blockNavigation: function _blockNavigation(attemptedHash, restoreHash = true) {
1355
1319
  this._phase = IDLE;
1356
- this._flushSettlement({
1320
+ this._settleUncommitted({
1357
1321
  status: NavigationOutcome.Blocked,
1358
1322
  route: this._currentRoute,
1359
1323
  hash: this._currentHash ?? ""
1360
- });
1361
- this._restoreHashIfNeeded(attemptedHash, restoreHash);
1324
+ }, attemptedHash, restoreHash);
1362
1325
  },
1363
1326
  /**
1364
1327
  * Clear pending state and flush an Error settlement.
@@ -1367,314 +1330,213 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1367
1330
  */
1368
1331
  _errorNavigation: function _errorNavigation(error, attemptedHash, restoreHash = true) {
1369
1332
  this._phase = IDLE;
1370
- this._flushSettlement({
1333
+ this._settleUncommitted({
1371
1334
  status: NavigationOutcome.Error,
1372
1335
  route: this._currentRoute,
1373
1336
  hash: this._currentHash ?? "",
1374
1337
  error
1375
- });
1376
- this._restoreHashIfNeeded(attemptedHash, restoreHash);
1377
- },
1378
- /** Conditionally restore the browser hash after a blocked or errored navigation. */_restoreHashIfNeeded: function _restoreHashIfNeeded(attemptedHash, restoreHash) {
1379
- if (!restoreHash) return;
1380
- if (this._currentHash === null && attemptedHash && attemptedHash !== "") {
1381
- this._restoreHash("", false);
1382
- return;
1383
- }
1384
- this._restoreHash(this._currentHash ?? "");
1338
+ }, attemptedHash, restoreHash);
1385
1339
  },
1386
1340
  /**
1387
- * Restore the previous hash without creating a history entry.
1388
- * Assumes replaceHash fires hashChanged synchronously (validated by test).
1389
- * `_currentRoute` stays unchanged because the navigation never
1390
- * committed. The user remains on the same logical route.
1341
+ * Settle a navigation that did not commit. With `restoreHash`, the hash it left in the URL
1342
+ * is restored first, so that settlement handlers run on the final URL and a hash they set
1343
+ * is not overwritten. The exception is a first navigation: nothing is committed yet, so the
1344
+ * empty hash is restored after the settlement and parsed as a navigation of its own.
1345
+ * `whenBack` runs after the settlement.
1391
1346
  */
1392
- _restoreHash: function _restoreHash(hash, suppressParse = true) {
1393
- const hashChanger = this.getHashChanger();
1394
- if (hashChanger) {
1395
- this._suppressedHash = suppressParse ? hash : null;
1396
- hashChanger.replaceHash(hash, HistoryDirection.Unknown);
1397
- if (this._suppressedHash === hash) {
1398
- this._suppressedHash = null;
1399
- }
1400
- }
1347
+ _settleUncommitted: function _settleUncommitted(result, attemptedHash, restoreHash, whenBack) {
1348
+ const loadDefaultRoute = restoreHash && this._currentHash === null && !!attemptedHash;
1349
+ // It settles once the URL is back.
1350
+ if (restoreHash && !loadDefaultRoute && !this._undoHashChange(result, whenBack)) return;
1351
+ this._flushSettlement(result);
1352
+ whenBack?.();
1353
+ // Unless a handler navigated and committed in the meantime.
1354
+ if (loadDefaultRoute && this._currentHash === null) this._restoreHash("", false);
1401
1355
  },
1402
1356
  /**
1403
- * Collect all route names and their patterns from the router.
1404
- * Skips routes whose pattern is undefined (no pattern configured).
1357
+ * Describe how to undo the hash change that the navigation starts with. After `pending`, the
1358
+ * undo of a navigation that this one supersedes, it takes back both changes. A `parse()` that
1359
+ * is not `reported` by the hash changer comes with no hash change.
1405
1360
  */
1406
- _collectRoutePatterns: function _collectRoutePatterns() {
1407
- const result = [];
1408
- for (const name of this._routeNames) {
1409
- const route = this.getRoute(name);
1410
- if (route) {
1411
- const pattern = route.getPattern();
1412
- if (pattern !== undefined) {
1413
- result.push({
1414
- name,
1415
- pattern
1416
- });
1417
- }
1418
- }
1419
- }
1420
- return result;
1361
+ _describeUndo: function _describeUndo(pending, reported) {
1362
+ if (!reported) return pending;
1363
+ const shown = HashChanger.getInstance().getHash();
1364
+ const step = lastStep;
1365
+ if (!pending) return {
1366
+ first: shown,
1367
+ fullHash: undefined,
1368
+ shown,
1369
+ step,
1370
+ started: false
1371
+ };
1372
+ const offset = pending.step && step ? pending.step.offset + step.offset : 0;
1373
+ return {
1374
+ first: pending.first,
1375
+ fullHash: pending.fullHash,
1376
+ shown,
1377
+ step: step && offset ? {
1378
+ offset,
1379
+ href: step.href
1380
+ } : null,
1381
+ started: false
1382
+ };
1421
1383
  },
1422
1384
  /**
1423
- * Expand guard descriptors to descendant routes when guard inheritance
1424
- * is set to `"pattern-tree"`. Global (`"*"`) descriptors are kept as-is.
1425
- * Descriptors are sorted by pattern depth (ancestor guards run before
1426
- * descendant guards).
1385
+ * Put the URL back after a navigation that did not commit. Returns whether it is back;
1386
+ * otherwise `result` settles when it is.
1387
+ *
1388
+ * While the URL still shows the hash change that started the navigation, that change is undone
1389
+ * as a whole, so that the hashes of nested routers are back as well:
1390
+ * - A step through the browser history is taken back, which leaves the history as it was.
1391
+ * The browser does that asynchronously.
1392
+ * - Any other change (a new entry, or a step the browser does not report) has its entry replaced with
1393
+ * the full previous hash, once UI5 has reported the change to every router. Nested routers
1394
+ * have received their part of the refused hash by then; they receive the previous one next.
1395
+ *
1396
+ * `parse()` ends the wait when the hash change arrives that shows the full previous hash.
1397
+ *
1398
+ * If the URL has moved on since, only the hash of this router is restored. So it is while
1399
+ * no navigation has committed: the URL before the change showed no route of this router either.
1427
1400
  */
1428
- _expandGuardDescriptors: function _expandGuardDescriptors(descriptors) {
1429
- const allRoutes = this._collectRoutePatterns();
1430
- if (allRoutes.length === 0) return descriptors;
1431
-
1432
- // Build a name -> pattern map for quick lookup
1433
- const patternByName = new Map(allRoutes.map(r => [r.name, r.pattern]));
1434
- const expanded = [];
1435
- for (const descriptor of descriptors) {
1436
- expanded.push(descriptor);
1437
-
1438
- // Global guards and routes without a known pattern are not expanded
1439
- if (descriptor.route === "*") continue;
1440
- const ancestorPattern = patternByName.get(descriptor.route);
1441
- if (ancestorPattern === undefined) continue;
1442
-
1443
- // Find descendant routes whose pattern extends the ancestor's pattern
1444
- for (const {
1445
- name,
1446
- pattern
1447
- } of allRoutes) {
1448
- if (name === descriptor.route) continue;
1449
- if (isPatternAncestor(ancestorPattern, pattern)) {
1450
- expanded.push({
1451
- ...descriptor,
1452
- route: name
1453
- });
1454
- }
1455
- }
1401
+ _undoHashChange: function _undoHashChange(result, whenBack) {
1402
+ const undo = this._undo;
1403
+ const hash = this._currentHash;
1404
+ const rootHash = HashChanger.getInstance().getHash();
1405
+ if (undo === null || hash === null || undo.shown !== rootHash || undo.fullHash === rootHash) {
1406
+ this._restoreHash(hash ?? "");
1407
+ return true;
1456
1408
  }
1457
-
1458
- // Sort by pattern depth (segment count) so ancestor guards run first.
1459
- // Global ("*") descriptors return 0 here -- their relative position is irrelevant
1460
- // because GuardPipeline evaluates globals separately from route-specific guards.
1461
- return expanded.toSorted((a, b) => {
1462
- if (a.route === "*" || b.route === "*") return 0;
1463
- const pa = patternByName.get(a.route) ?? "";
1464
- const pb = patternByName.get(b.route) ?? "";
1465
- return patternSegments(pa).length - patternSegments(pb).length;
1466
- });
1409
+ const href = window.location.href;
1410
+ undo.started = true;
1411
+ this._phase = {
1412
+ kind: "restoring",
1413
+ result,
1414
+ whenBack
1415
+ };
1416
+ if (undoneHref === href) {
1417
+ // Another router is taking the step back.
1418
+ } else if (undo.step) {
1419
+ undoneHref = href;
1420
+ window.history.go(-undo.step.offset);
1421
+ } else if (undo.fullHash === undefined) {
1422
+ // UI5 is still reporting the change to the nested routers.
1423
+ this._phase = {
1424
+ ...this._phase,
1425
+ awaitsReport: true
1426
+ };
1427
+ } else {
1428
+ this._replaceFullHash(undo.fullHash);
1429
+ }
1430
+ return false;
1467
1431
  },
1468
1432
  /**
1469
- * Resolve metadata for a route without inheritance (flat merge of
1470
- * manifest and runtime metadata).
1433
+ * Replace the hash of the root hash changer with the full previous hash, and settle the
1434
+ * navigation that waits for it unless `parse()` has done so.
1471
1435
  */
1472
- _resolveFlatMeta: function _resolveFlatMeta(routeName) {
1473
- const manifest = this._manifestMeta.get(routeName);
1474
- const runtime = this._runtimeMeta.get(routeName);
1475
- if (!manifest && !runtime) return Router._EMPTY_META;
1476
- if (!runtime) return manifest;
1477
- if (!manifest) return runtime;
1478
- return Object.freeze({
1479
- ...manifest,
1480
- ...runtime
1481
- });
1436
+ _replaceFullHash: function _replaceFullHash(fullHash) {
1437
+ HashChanger.getInstance().replaceHash(fullHash, HistoryDirection.Unknown);
1438
+ this._finishRestore();
1482
1439
  },
1483
1440
  /**
1484
- * Resolve metadata for a route with pattern-tree inheritance.
1485
- * Walks ancestor patterns shallowest-first, merging manifest and
1486
- * runtime metadata at each level, then overlays the route's own.
1441
+ * Settle the navigation that waited for the URL to be back: on `hash`, if the hash changer
1442
+ * has reported one with the URL.
1487
1443
  */
1488
- _resolveInheritedMeta: function _resolveInheritedMeta(routeName) {
1489
- const allRoutes = this._collectRoutePatterns();
1490
- const routeEntry = allRoutes.find(r => r.name === routeName);
1491
- if (!routeEntry) return this._resolveFlatMeta(routeName);
1492
-
1493
- // Find ancestors that have declared metadata (manifest or runtime)
1494
- const ancestors = allRoutes.filter(r => r.name !== routeName && (this._manifestMeta.has(r.name) || this._runtimeMeta.has(r.name)) && isPatternAncestor(r.pattern, routeEntry.pattern));
1495
- // oxlint-disable-next-line unicorn/no-array-sort -- ancestors is a fresh array from filter()
1496
- ancestors.sort((a, b) => patternSegments(a.pattern).length - patternSegments(b.pattern).length);
1497
-
1498
- // Merge shallowest-first: root ancestor -> deeper ancestors -> own manifest -> own runtime
1499
- const merged = {};
1500
- for (const ancestor of ancestors) {
1501
- const ancestorManifest = this._manifestMeta.get(ancestor.name);
1502
- if (ancestorManifest) Object.assign(merged, ancestorManifest);
1503
- const ancestorRuntime = this._runtimeMeta.get(ancestor.name);
1504
- if (ancestorRuntime) Object.assign(merged, ancestorRuntime);
1505
- }
1506
- const ownManifest = this._manifestMeta.get(routeName);
1507
- if (ownManifest) Object.assign(merged, ownManifest);
1508
- const ownRuntime = this._runtimeMeta.get(routeName);
1509
- if (ownRuntime) Object.assign(merged, ownRuntime);
1510
- if (Object.keys(merged).length === 0) return Router._EMPTY_META;
1511
- return Object.freeze(merged);
1444
+ _finishRestore: function _finishRestore(hash) {
1445
+ const phase = this._phase;
1446
+ if (phase.kind !== "restoring") return;
1447
+ this._phase = IDLE;
1448
+ this._flushSettlement(hash === undefined ? phase.result : {
1449
+ ...phase.result,
1450
+ hash
1451
+ });
1452
+ phase.whenBack?.();
1512
1453
  },
1513
1454
  /**
1514
- * Load guard modules individually via `sap.ui.require` and register
1515
- * each resolved function with the appropriate guard API.
1455
+ * Restore the previous hash of this router without creating a history entry
1456
+ * (see {@link _undoHashChange} for the hash change of a navigation).
1457
+ * Assumes replaceHash fires hashChanged synchronously (validated by test).
1458
+ * `_currentRoute` stays unchanged because the navigation never
1459
+ * committed. The user remains on the same logical route.
1516
1460
  *
1517
- * Each module is loaded in its own `sap.ui.require` call so that a
1518
- * single invalid path only skips that guard (with a warning) rather
1519
- * than failing the entire batch. Once all loads settle, guards
1520
- * register in declaration order. Registration errors (e.g. from
1521
- * `unknownRouteRegistration: "throw"`) are caught per-module.
1461
+ * A hash that the hash changer already shows is not written again: the navigation never
1462
+ * moved it. For a nested router, writing its empty hash would add its prefix to the browser
1463
+ * hash (`shell` becomes `shell&/child/`).
1522
1464
  */
1523
- _loadAndRegisterGuards: function _loadAndRegisterGuards(descriptors) {
1524
- const promises = descriptors.map(descriptor => {
1525
- return new Promise(resolve => {
1526
- sap.ui.require([descriptor.modulePath], moduleExport => {
1527
- resolve({
1528
- descriptor,
1529
- moduleExport
1530
- });
1531
- }, err => {
1532
- Log.warning(`guardRouter.guards: failed to load module "${descriptor.modulePath}", skipping`, String(err), LOG_COMPONENT);
1533
- resolve({
1534
- descriptor,
1535
- moduleExport: null
1536
- });
1537
- });
1538
- });
1539
- });
1540
- return Promise.all(promises).then(results => {
1541
- for (const {
1542
- descriptor,
1543
- moduleExport
1544
- } of results) {
1545
- if (moduleExport === null) continue;
1546
- const exports = resolveModuleExports(moduleExport, descriptor.modulePath, descriptor.name, descriptor.exportKey);
1547
- for (const {
1548
- fn
1549
- } of exports) {
1550
- try {
1551
- this._registerGuardFromDescriptor(descriptor, fn);
1552
- } catch (err) {
1553
- Log.error(`guardRouter.guards: failed to register "${descriptor.modulePath}"`, String(err), LOG_COMPONENT);
1554
- }
1555
- }
1556
- }
1557
- });
1465
+ _restoreHash: function _restoreHash(hash, suppressParse = true) {
1466
+ const hashChanger = this.getHashChanger();
1467
+ if (hashChanger.getHash() === hash) return;
1468
+ this._suppressedHash = suppressParse ? hash : null;
1469
+ void hashChanger.replaceHash(hash, HistoryDirection.Unknown);
1470
+ this._suppressedHash = null;
1558
1471
  },
1559
1472
  /**
1560
- * Route a parsed guard descriptor to the correct registration method.
1473
+ * Collect all route names and their patterns from the router.
1474
+ * Skips routes whose pattern is undefined (no pattern configured).
1561
1475
  */
1562
- _registerGuardFromDescriptor: function _registerGuardFromDescriptor(descriptor, guardFn) {
1563
- if (descriptor.route === "*") {
1564
- this.addGuard(guardFn);
1565
- } else if (descriptor.type === "leave") {
1566
- if (!this._handleUnknownRouteRegistration(descriptor.route, "addLeaveGuard")) return;
1567
- this._pipeline.addLeaveGuard(descriptor.route, guardFn);
1568
- } else {
1569
- this.addRouteGuard(descriptor.route, guardFn);
1476
+ _collectRoutePatterns: function _collectRoutePatterns() {
1477
+ const result = [];
1478
+ for (const name of this._routeNames) {
1479
+ const pattern = this.getRoute(name)?.getPattern();
1480
+ if (pattern !== undefined) result.push({
1481
+ name,
1482
+ pattern
1483
+ });
1570
1484
  }
1485
+ return result;
1571
1486
  },
1572
1487
  /**
1573
- * Register lazy wrapper functions that load guard modules on first use.
1574
- *
1575
- * Cherry-picked descriptors (with exportKey) get one lazy wrapper each.
1576
- * Bare-path descriptors try a sync cache probe first; if the module is
1577
- * cached (preload likely finished), all guards are expanded immediately.
1578
- * On cache miss, a single "expander" wrapper loads the module on first
1579
- * navigation, registers remaining guards, and executes the first.
1488
+ * Register one manifest guard: as the last guard of its route, or in front of the guard
1489
+ * `before`. A registration error (`unknownRouteRegistration: "throw"` for an unknown route)
1490
+ * is logged and skips the guard: no caller of the manifest config could catch it, and it
1491
+ * must not keep the router from starting.
1580
1492
  */
1581
- _registerLazyGuards: function _registerLazyGuards(descriptors) {
1582
- for (const descriptor of descriptors) {
1583
- const {
1584
- modulePath,
1585
- exportKey,
1586
- name
1587
- } = descriptor;
1588
- if (exportKey !== undefined) {
1589
- // Cherry-picked: one lazy wrapper, resolves to exactly one guard
1590
- const lazyGuard = context => {
1591
- const cached = sap.ui.require(modulePath);
1592
- if (cached !== undefined) {
1593
- const exports = resolveModuleExports(cached, modulePath, name, exportKey);
1594
- if (exports.length === 0) return true;
1595
- return exports[0].fn(context);
1596
- }
1597
- return new Promise((resolve, reject) => {
1598
- sap.ui.require([modulePath], mod => {
1599
- const exports = resolveModuleExports(mod, modulePath, name, exportKey);
1600
- if (exports.length === 0) {
1601
- resolve(true);
1602
- return;
1603
- }
1604
- resolve(exports[0].fn(context));
1605
- }, err => {
1606
- Log.warning(`guardRouter.guards: lazy load of "${modulePath}" failed`, String(err), LOG_COMPONENT);
1607
- reject(err);
1608
- });
1609
- });
1610
- };
1611
- this._registerGuardFromDescriptor(descriptor, lazyGuard);
1612
- continue;
1493
+ _registerManifestGuard: function _registerManifestGuard(descriptor, guardFn, before) {
1494
+ try {
1495
+ if (descriptor.route === "*") {
1496
+ this.addGuard(guardFn);
1497
+ return;
1613
1498
  }
1614
-
1615
- // Bare-path: try sync expansion from cache (preload likely finished)
1616
- const cached = sap.ui.require(modulePath);
1617
- if (cached !== undefined) {
1618
- const exports = resolveModuleExports(cached, modulePath, name);
1619
- for (const exp of exports) {
1620
- this._registerGuardFromDescriptor(descriptor, exp.fn);
1621
- }
1622
- continue;
1499
+ if (descriptor.type === "leave") {
1500
+ this._handleUnknownRouteRegistration(descriptor.route, "addLeaveGuard");
1501
+ this._pipeline.addLeaveGuard(descriptor.route, guardFn, before);
1502
+ } else {
1503
+ this._handleUnknownRouteRegistration(descriptor.route, "addRouteGuard");
1504
+ this._pipeline.addEnterGuard(descriptor.route, guardFn, before);
1623
1505
  }
1624
-
1625
- // Cache miss: register an expander that loads, expands once, and runs guard[0].
1626
- // NOTE: Guards 1..N are appended to the guard array on first invocation,
1627
- // which means they execute AFTER any imperative guards registered between
1628
- // initialize() and first navigation. This differs from block mode where
1629
- // all guards occupy contiguous positions. In practice this is rare because
1630
- // the preload hint fires in the constructor and modules are typically cached
1631
- // by the time initialize() runs.
1632
- let expanded = false;
1633
- const lazyExpander = context => {
1634
- return new Promise((resolve, reject) => {
1635
- sap.ui.require([modulePath], mod => {
1636
- const exports = resolveModuleExports(mod, modulePath, name);
1637
- if (exports.length === 0) {
1638
- resolve(true);
1639
- return;
1640
- }
1641
- if (!expanded) {
1642
- expanded = true;
1643
- for (let i = 1; i < exports.length; i++) {
1644
- this._registerGuardFromDescriptor(descriptor, exports[i].fn);
1645
- }
1646
- }
1647
- resolve(exports[0].fn(context));
1648
- }, err => {
1649
- Log.warning(`guardRouter.guards: lazy load of "${modulePath}" failed`, String(err), LOG_COMPONENT);
1650
- reject(err);
1651
- });
1652
- });
1653
- };
1654
- this._registerGuardFromDescriptor(descriptor, lazyExpander);
1506
+ this._manifestGuards.push({
1507
+ descriptor,
1508
+ fn: guardFn
1509
+ });
1510
+ } catch (err) {
1511
+ Log.error(`guardRouter.guards: failed to register "${descriptor.modulePath}"`, String(err), LOG_COMPONENT);
1512
+ }
1513
+ },
1514
+ /** Register the guards of each descriptor, loading their modules on first use (see `createLazyGuards`). */_registerLazyGuards: function _registerLazyGuards(descriptors) {
1515
+ for (const descriptor of descriptors) {
1516
+ for (const fn of createLazyGuards(descriptor)) this._registerManifestGuard(descriptor, fn);
1655
1517
  }
1656
1518
  },
1657
1519
  /**
1658
1520
  * Clean up guards on destroy. Bumps generation to discard pending async results.
1521
+ * A second call does nothing, like `sap.ui.core.routing.Router#destroy`.
1659
1522
  *
1660
1523
  * @since 1.0.1
1661
1524
  */
1662
1525
  destroy: function _destroy() {
1526
+ if (this._destroyed) return this;
1663
1527
  this._destroyed = true;
1664
1528
  this._pipeline.clear();
1665
1529
  this._pendingGuardDescriptors = [];
1666
1530
  this._sourceDescriptors = [];
1531
+ this._manifestGuards = [];
1667
1532
  this._cancelPendingNavigation();
1668
- this._suppressedHash = null;
1669
1533
  this._lastSettlement = null;
1670
- this._manifestMeta.clear();
1671
- this._runtimeMeta.clear();
1672
- this._resolvedMetaCache.clear();
1534
+ this._detachHashListeners();
1535
+ this._meta.clear();
1673
1536
  MobileRouter.prototype.destroy.call(this);
1674
1537
  return this;
1675
1538
  }
1676
1539
  });
1677
- Router._EMPTY_META = Object.freeze({});
1678
1540
  return Router;
1679
1541
  });
1680
1542
  //# sourceMappingURL=Router-dbg.js.map