ui5-lib-guard-router 1.6.2 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/{dist/.ui5 → .ui5}/build-manifest.json +56 -8
  2. package/CHANGELOG.md +197 -0
  3. package/README.md +695 -327
  4. package/dist/index.d.ts +9 -5
  5. package/dist/resources/ui5/guard/router/.library +1 -1
  6. package/dist/resources/ui5/guard/router/GuardConfig-dbg.js +222 -0
  7. package/dist/resources/ui5/guard/router/GuardConfig-dbg.js.map +1 -0
  8. package/dist/resources/ui5/guard/router/GuardConfig.d.ts +89 -0
  9. package/dist/resources/ui5/guard/router/GuardConfig.d.ts.map +1 -0
  10. package/dist/resources/ui5/guard/router/GuardConfig.js +2 -0
  11. package/dist/resources/ui5/guard/router/GuardConfig.js.map +1 -0
  12. package/dist/resources/ui5/guard/router/GuardModules-dbg.js +253 -0
  13. package/dist/resources/ui5/guard/router/GuardModules-dbg.js.map +1 -0
  14. package/dist/resources/ui5/guard/router/GuardModules.d.ts +72 -0
  15. package/dist/resources/ui5/guard/router/GuardModules.d.ts.map +1 -0
  16. package/dist/resources/ui5/guard/router/GuardModules.js +2 -0
  17. package/dist/resources/ui5/guard/router/GuardModules.js.map +1 -0
  18. package/dist/resources/ui5/guard/router/GuardPipeline-dbg.js +125 -122
  19. package/dist/resources/ui5/guard/router/GuardPipeline-dbg.js.map +1 -1
  20. package/dist/resources/ui5/guard/router/GuardPipeline.d.ts +45 -26
  21. package/dist/resources/ui5/guard/router/GuardPipeline.d.ts.map +1 -1
  22. package/dist/resources/ui5/guard/router/GuardPipeline.js +1 -1
  23. package/dist/resources/ui5/guard/router/GuardPipeline.js.map +1 -1
  24. package/dist/resources/ui5/guard/router/NavigationOutcome-dbg.js +3 -3
  25. package/dist/resources/ui5/guard/router/NavigationOutcome-dbg.js.map +1 -1
  26. package/dist/resources/ui5/guard/router/NavigationOutcome.d.ts +3 -3
  27. package/dist/resources/ui5/guard/router/NavigationOutcome.d.ts.map +1 -1
  28. package/dist/resources/ui5/guard/router/NavigationOutcome.js.map +1 -1
  29. package/dist/resources/ui5/guard/router/PatternTree-dbg.js +156 -0
  30. package/dist/resources/ui5/guard/router/PatternTree-dbg.js.map +1 -0
  31. package/dist/resources/ui5/guard/router/PatternTree.d.ts +71 -0
  32. package/dist/resources/ui5/guard/router/PatternTree.d.ts.map +1 -0
  33. package/dist/resources/ui5/guard/router/PatternTree.js +2 -0
  34. package/dist/resources/ui5/guard/router/PatternTree.js.map +1 -0
  35. package/dist/resources/ui5/guard/router/RouteMeta-dbg.js +84 -0
  36. package/dist/resources/ui5/guard/router/RouteMeta-dbg.js.map +1 -0
  37. package/dist/resources/ui5/guard/router/RouteMeta.d.ts +33 -0
  38. package/dist/resources/ui5/guard/router/RouteMeta.d.ts.map +1 -0
  39. package/dist/resources/ui5/guard/router/RouteMeta.js +2 -0
  40. package/dist/resources/ui5/guard/router/RouteMeta.js.map +1 -0
  41. package/dist/resources/ui5/guard/router/Router-dbg.js +900 -1033
  42. package/dist/resources/ui5/guard/router/Router-dbg.js.map +1 -1
  43. package/dist/resources/ui5/guard/router/Router.d.ts +362 -212
  44. package/dist/resources/ui5/guard/router/Router.d.ts.map +1 -1
  45. package/dist/resources/ui5/guard/router/Router.js +1 -1
  46. package/dist/resources/ui5/guard/router/Router.js.map +1 -1
  47. package/dist/resources/ui5/guard/router/library-dbg.js +1 -1
  48. package/dist/resources/ui5/guard/router/library-dbg.js.map +1 -1
  49. package/dist/resources/ui5/guard/router/library-preload.js +8 -4
  50. package/dist/resources/ui5/guard/router/library-preload.js.map +1 -1
  51. package/dist/resources/ui5/guard/router/library.js +1 -1
  52. package/dist/resources/ui5/guard/router/library.js.map +1 -1
  53. package/dist/resources/ui5/guard/router/manifest.json +5 -2
  54. package/dist/resources/ui5/guard/router/types-dbg.js.map +1 -1
  55. package/dist/resources/ui5/guard/router/types.d.ts +94 -39
  56. package/dist/resources/ui5/guard/router/types.d.ts.map +1 -1
  57. package/package.json +10 -6
  58. package/src/GuardConfig.ts +272 -0
  59. package/src/GuardModules.ts +249 -0
  60. package/src/GuardPipeline.ts +158 -129
  61. package/src/NavigationOutcome.ts +3 -3
  62. package/src/PatternTree.ts +145 -0
  63. package/src/RouteMeta.ts +82 -0
  64. package/src/Router.ts +1110 -1150
  65. package/src/manifest.json +5 -2
  66. package/src/types.ts +79 -22
  67. package/tsconfig.json +0 -11
@@ -1,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);
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;
405
159
  }
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
- }
420
- }
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,32 +439,25 @@ 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
- }
599
- let hasHandler = false;
600
- if (guard.beforeEnter !== undefined) {
601
- hasHandler = true;
602
- if (this._isFn(guard.beforeEnter, "addRouteGuard", routeName)) {
603
- this._pipeline.addEnterGuard(routeName, guard.beforeEnter);
604
- }
605
- }
606
- if (guard.beforeLeave !== undefined) {
607
- hasHandler = true;
608
- if (this._isFn(guard.beforeLeave, "addRouteGuard", routeName)) {
609
- this._pipeline.addLeaveGuard(routeName, guard.beforeLeave);
610
- }
611
- }
612
- if (!hasHandler) {
442
+ const {
443
+ beforeEnter,
444
+ beforeLeave
445
+ } = guard;
446
+ if (beforeEnter === undefined && beforeLeave === undefined) {
613
447
  Log.info("addRouteGuard: config has no beforeEnter or beforeLeave", routeName, LOG_COMPONENT);
614
448
  return this;
615
449
  }
450
+ // As for a guard function: the route is checked only when something is registered.
451
+ const enter = beforeEnter !== undefined && this._isFn(beforeEnter, "addRouteGuard", routeName);
452
+ const leave = beforeLeave !== undefined && this._isFn(beforeLeave, "addRouteGuard", routeName);
453
+ if (!enter && !leave) return this;
454
+ this._handleUnknownRouteRegistration(routeName, "addRouteGuard");
455
+ if (enter) this._pipeline.addEnterGuard(routeName, beforeEnter);
456
+ if (leave) this._pipeline.addLeaveGuard(routeName, beforeLeave);
616
457
  return this;
617
458
  }
618
459
  if (!this._isFn(guard, "addRouteGuard", routeName)) return this;
619
- if (!this._handleUnknownRouteRegistration(routeName, "addRouteGuard")) {
620
- return this;
621
- }
460
+ this._handleUnknownRouteRegistration(routeName, "addRouteGuard");
622
461
  this._pipeline.addEnterGuard(routeName, guard);
623
462
  return this;
624
463
  },
@@ -662,9 +501,7 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
662
501
  */
663
502
  addLeaveGuard: function _addLeaveGuard(routeName, guard) {
664
503
  if (!this._isFn(guard, "addLeaveGuard", routeName)) return this;
665
- if (!this._handleUnknownRouteRegistration(routeName, "addLeaveGuard")) {
666
- return this;
667
- }
504
+ this._handleUnknownRouteRegistration(routeName, "addLeaveGuard");
668
505
  this._pipeline.addLeaveGuard(routeName, guard);
669
506
  return this;
670
507
  },
@@ -674,20 +511,21 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
674
511
  * UI5's native `navTo` has two signatures where the third parameter is either
675
512
  * `componentTargetInfo` (object) or `bReplace` (boolean). This method normalizes
676
513
  * both forms so the rest of `navTo` can work with a single set of variables.
514
+ * The options follow `bReplace`, or take its place when it is left out.
677
515
  */
678
516
  _resolveNavToArgs: function _resolveNavToArgs(componentTargetInfoOrReplace, replaceOrOptions, options) {
679
517
  if (typeof componentTargetInfoOrReplace === "boolean") {
680
518
  // Short form: navTo(name, params, replace, options?)
681
519
  return {
682
520
  replace: componentTargetInfoOrReplace,
683
- guardOptions: typeof replaceOrOptions === "object" && replaceOrOptions !== null ? replaceOrOptions : undefined
521
+ guardOptions: typeof replaceOrOptions === "object" ? replaceOrOptions : undefined
684
522
  };
685
523
  }
686
524
  // Long form: navTo(name, params, componentTargetInfo, replace, options?)
687
525
  return {
688
526
  componentTargetInfo: componentTargetInfoOrReplace,
689
527
  replace: typeof replaceOrOptions === "boolean" ? replaceOrOptions : undefined,
690
- guardOptions: options
528
+ guardOptions: typeof replaceOrOptions === "object" ? replaceOrOptions : options
691
529
  };
692
530
  },
693
531
  /** Return `true` when the value is a function; otherwise log a warning. */_isFn: function _isFn(value, method, detail) {
@@ -695,21 +533,15 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
695
533
  Log.warning(`${method}: not a function, ignoring`, detail, LOG_COMPONENT);
696
534
  return false;
697
535
  },
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;
536
+ /** Apply the `unknownRouteRegistration` policy: warn or throw when the route is unknown. */_handleUnknownRouteRegistration: function _handleUnknownRouteRegistration(routeName, methodName, kept = "guard registered") {
537
+ if (this.getRoute(routeName)) return;
704
538
  switch (this._options.unknownRouteRegistration) {
705
539
  case "ignore":
706
- return true;
540
+ return;
707
541
  case "throw":
708
542
  throw new Error(`${methodName} called for unknown route "${routeName}". ` + `Set guardRouter.unknownRouteRegistration to "warn" or "ignore" to allow this.`);
709
543
  case "warn":
710
- default:
711
- Log.warning(`${methodName}: unknown route, guard registered anyway`, routeName, LOG_COMPONENT);
712
- return true;
544
+ Log.warning(`${methodName}: unknown route, ${kept} anyway`, routeName, LOG_COMPONENT);
713
545
  }
714
546
  },
715
547
  /**
@@ -744,24 +576,9 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
744
576
  // Empty string is a valid root route name (initial state before first navigation)
745
577
  if (routeName !== "" && !this.getRoute(routeName)) {
746
578
  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);
579
+ return EMPTY_META;
758
580
  }
759
- if (Object.keys(result).length === 0) {
760
- this._resolvedMetaCache.set(routeName, Router._EMPTY_META);
761
- return Router._EMPTY_META;
762
- }
763
- this._resolvedMetaCache.set(routeName, result);
764
- return result;
581
+ return this._meta.get(routeName);
765
582
  },
766
583
  /**
767
584
  * Set runtime metadata for a route.
@@ -782,13 +599,8 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
782
599
  Log.warning("setRouteMeta: expected object, ignoring", routeName, LOG_COMPONENT);
783
600
  return this;
784
601
  }
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();
602
+ if (routeName !== "") this._handleUnknownRouteRegistration(routeName, "setRouteMeta", "metadata stored");
603
+ this._meta.set(routeName, meta);
792
604
  return this;
793
605
  },
794
606
  /**
@@ -799,13 +611,13 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
799
611
  * settlement result. Before any navigation has settled, it falls back to a
800
612
  * synthetic `Committed` result derived from the router's current route/hash
801
613
  * state. After `stop()`, that idle fallback reports empty route/hash values
802
- * until a new navigation settles.
614
+ * until a new navigation settles, or `initialize(true)` resumes the route.
803
615
  *
804
616
  * @returns Promise that resolves with a {@link NavigationResult} once the pipeline settles.
805
617
  * @since 1.2.0
806
618
  */
807
619
  navigationSettled: function _navigationSettled() {
808
- if (this._phase.kind !== "evaluating") {
620
+ if (this._phase.kind === "idle" || this._phase.kind === "committing") {
809
621
  return Promise.resolve(this._lastSettlement ?? {
810
622
  status: NavigationOutcome.Committed,
811
623
  route: this._currentRoute,
@@ -817,8 +629,8 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
817
629
  });
818
630
  },
819
631
  attachNavigationSettled: function _attachNavigationSettled(oData, fnFunction, oListener) {
820
- this.attachEvent("navigationSettled", oData, fnFunction, oListener);
821
- return this;
632
+ // The arguments go on as received: EventProvider#attachEvent tells the two call forms apart.
633
+ return this.attachEvent("navigationSettled", oData, fnFunction, oListener);
822
634
  },
823
635
  /**
824
636
  * Detach a previously attached `navigationSettled` event handler.
@@ -840,14 +652,30 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
840
652
  */
841
653
  _flushSettlement: function _flushSettlement(result) {
842
654
  this._lastSettlement = result;
655
+ Log.debug(`Navigation settled: ${result.status}`, result.hash, LOG_COMPONENT);
656
+ // After the call that settled: by then a commit has reached super.parse(), and a navigation
657
+ // that supersedes this one has started.
658
+ queueMicrotask(() => this._settleMatchWaiters());
843
659
  const resolvers = this._settlementResolvers;
844
660
  this._settlementResolvers = [];
845
661
  for (const resolve of resolvers) {
846
662
  resolve(result);
847
663
  }
848
- this.fireEvent("navigationSettled", result);
664
+ // No handler runs while destroy() tears the router down; the native destroy() fires no event either.
665
+ if (this._destroyed) return;
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) {
674
+ // The guards are gone: code that awaited navigationSettled() may still call navTo().
675
+ if (this._destroyed) {
676
+ Log.warning("navTo: router is destroyed, ignoring", routeName, LOG_COMPONENT);
677
+ return this;
678
+ }
851
679
  const {
852
680
  componentTargetInfo,
853
681
  replace,
@@ -861,135 +689,130 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
861
689
  return this;
862
690
  }
863
691
 
864
- // Resolve the target hash so we can build a guard context.
865
- // getURL() returns the hash pattern with parameters substituted.
692
+ // A router that does not listen to hash changes (not initialized, loading block-mode
693
+ // guards, or stopped) navigates like the native one: the guards run once it parses the hash.
694
+ if (!this.isInitialized()) {
695
+ MobileRouter.prototype.navTo.call(this, routeName, parameters, componentTargetInfo, replace);
696
+ return this;
697
+ }
866
698
  const route = this.getRoute(routeName);
867
699
  if (!route) {
868
- // Unknown route -- let parent handle it (may fire bypassed event).
700
+ // Unknown route -- let the parent handle it (it logs a warning).
869
701
  // Cancel any pending async navigation so settlement resolvers drain
870
702
  // and the stale pipeline does not commit a superseded navigation.
871
- this._cancelPendingNavigation();
703
+ this._cancelPendingNavigation(true);
872
704
  MobileRouter.prototype.navTo.call(this, routeName, parameters, componentTargetInfo, replace);
873
705
  return this;
874
706
  }
875
707
  const targetHash = route.getURL(parameters ?? {});
876
- const routeInfo = this.getRouteInfoByHash(targetHash);
877
- const toRoute = routeInfo?.name ?? "";
708
+ const routeInfo = this._matchRoute(targetHash);
709
+ const toRoute = routeInfo.name;
878
710
 
879
- // Same-hash dedup: cancel any pending navigation and return without navigating.
880
- if (this._currentHash !== null && targetHash === this._currentHash) {
881
- this._cancelPendingNavigation();
711
+ // Same hash: no route of this router changes, so there is nothing to guard. Cancel any
712
+ // pending navigation and navigate natively: UI5 still sets the hashes of nested
713
+ // components (componentTargetInfo), or resets them when none are given.
714
+ if (targetHash === this._currentHash) {
715
+ this._cancelPendingNavigation(true);
716
+ // A navigationSettled handler of the cancelled navigation may have navigated on.
717
+ const shownHash = this.getHashChanger().getHash();
718
+ if (shownHash === undefined || shownHash === targetHash) {
719
+ // If UI5 has reset the hash of the hash changer, after a target was displayed without
720
+ // a route, it reports the hash again, and parse() lets the route match again.
721
+ MobileRouter.prototype.navTo.call(this, routeName, parameters, componentTargetInfo, replace);
722
+ }
882
723
  return this;
883
724
  }
725
+ const skipGuards = guardOptions?.skipGuards === true || this._options.navToPreflight === "bypass";
884
726
 
885
727
  // 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) {
728
+ // already running, don't cancel and restart it. A navigation that skips
729
+ // the guards does not wait for them.
730
+ if (!skipGuards && this._phase.kind === "evaluating" && targetHash === this._phase.attempt.hash) {
888
731
  return this;
889
732
  }
890
733
 
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
- };
734
+ // parse() evaluates the guards once the hash has changed. It supersedes a pending
735
+ // navigation then, and undoes the hash change of that navigation with its own.
736
+ if (!skipGuards && this._options.navToPreflight === "off") {
903
737
  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
738
  return this;
910
739
  }
911
740
 
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);
741
+ // Cancel any pending navigation (including previous async preflight).
742
+ // A superseded hash-change navigation leaves its hash in the URL: restore it
743
+ // unless this navigation moves the URL.
744
+ const restoreHash = this._pendingRestoresHash();
745
+ this._cancelPendingNavigation();
746
+ if (skipGuards) {
747
+ this._navigateAllowed(routeName, parameters, componentTargetInfo, replace, targetHash, toRoute, restoreHash);
915
748
  return this;
916
749
  }
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);
750
+ const attempt = this._startAttempt(targetHash, restoreHash);
751
+ const {
752
+ generation
753
+ } = attempt;
754
+ const context = this._createGuardContext(routeInfo, targetHash, attempt.controller.signal);
755
+ const decision = this._evaluateGuards(context);
932
756
  if (isPromiseLike(decision)) {
933
- decision.then(d => {
934
- if (generation !== this._parseGeneration || this._phase.kind !== "evaluating") {
757
+ this._applyWhenDecided(decision, d => {
758
+ if (generation !== this._parseGeneration) {
935
759
  Log.debug("Async preflight result discarded (superseded by newer navigation)", targetHash, LOG_COMPONENT);
936
760
  return;
937
761
  }
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
- });
762
+ this._applyPreflightDecision(d, routeName, parameters, componentTargetInfo, replace, targetHash, toRoute, context.bag, attempt);
763
+ }, targetHash, restoreHash);
947
764
  return this;
948
765
  }
949
-
950
- // Sync path: apply the decision immediately.
951
- this._applyPreflightDecision(decision, routeName, parameters, componentTargetInfo, replace, targetHash, toRoute, context.bag);
766
+ this._applyPreflightDecision(decision, routeName, parameters, componentTargetInfo, replace, targetHash, toRoute, context.bag, attempt);
952
767
  return this;
953
768
  },
769
+ /**
770
+ * Navigate to a `navTo()` target that needs no guards (allowed or bypassed) and commit it,
771
+ * or block it if the hash change was refused (see {@link _commitAfterNavTo}).
772
+ */
773
+ _navigateAllowed: function _navigateAllowed(routeName, parameters, componentTargetInfo, bReplace, targetHash, toRoute, restoreHash) {
774
+ this._phase = {
775
+ kind: "committing",
776
+ route: toRoute,
777
+ hash: targetHash,
778
+ origin: "preflight",
779
+ restoreHash,
780
+ writtenOver: HashChanger.getInstance().getHash()
781
+ };
782
+ try {
783
+ MobileRouter.prototype.navTo.call(this, routeName, parameters, componentTargetInfo, bReplace);
784
+ if (!this._commitAfterNavTo(componentTargetInfo)) {
785
+ this._blockNavigation(targetHash, restoreHash);
786
+ }
787
+ } finally {
788
+ // A failed hash change must not leave the next one to be committed without guards.
789
+ if (this._phase.kind === "committing") {
790
+ this._phase = IDLE;
791
+ }
792
+ }
793
+ },
954
794
  /**
955
795
  * 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.
796
+ * phase and call super.navTo(). For "block", flush settlement; the hash is
797
+ * only touched to restore it after a superseded hash-change navigation.
798
+ * For "redirect", start a redirect chain.
958
799
  * 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
800
  */
968
- _applyPreflightDecision: function _applyPreflightDecision(decision, routeName, parameters, componentTargetInfo, bReplace, targetHash, toRoute, bag) {
801
+ _applyPreflightDecision: function _applyPreflightDecision(decision, routeName, parameters, componentTargetInfo, bReplace, targetHash, toRoute, bag, attempt) {
802
+ // A guard that navigated itself has superseded the navigation it was guarding.
803
+ if (attempt.generation !== this._parseGeneration) return;
969
804
  switch (decision.action) {
970
805
  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
- }
806
+ this._navigateAllowed(routeName, parameters, componentTargetInfo, bReplace, targetHash, toRoute, attempt.restoreHash);
984
807
  break;
985
808
  case "block":
986
- this._blockNavigation(targetHash, false);
809
+ this._blockNavigation(targetHash, attempt.restoreHash);
987
810
  break;
988
811
  case "redirect":
989
- this._startRedirectChain(decision.target, targetHash, false, bag);
812
+ this._startRedirectChain(decision.target, targetHash, bag, attempt, bReplace);
990
813
  break;
991
814
  case "error":
992
- this._errorNavigation(decision.error, targetHash, false);
815
+ this._errorNavigation(decision.error, targetHash, attempt.restoreHash);
993
816
  break;
994
817
  }
995
818
  },
@@ -1007,105 +830,211 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1007
830
  * @since 1.0.1
1008
831
  */
1009
832
  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;
833
+ if (this._destroyed) {
834
+ // The base router only warns about a hash change that reaches a destroyed router.
835
+ MobileRouter.prototype.parse.call(this, newHash);
836
+ return;
1016
837
  }
1017
- if (this._phase.kind === "committing") {
1018
- this._commitNavigation(newHash, this._phase.route !== "" ? this._phase.route : this.getRouteInfoByHash(newHash)?.name ?? "");
838
+ const reported = this._reportedHash === newHash;
839
+ this._reportedHash = null;
840
+ // The URL shows a later hash, which this router has parsed.
841
+ if (reported && this._reportOutdated) return;
842
+ // The hash that _restoreHash() is writing.
843
+ if (newHash === this._suppressedHash) return;
844
+ const undo = this._undo;
845
+ if (undo?.started && undo.fullHash === HashChanger.getInstance().getHash()) {
846
+ // The URL is back where the router has put it (see _undoHashChange), so nothing is
847
+ // evaluated. What the hash changer reports now is the hash of the route that is shown.
848
+ this._undo = null;
849
+ this._currentHash = newHash;
850
+ this._finishRestore(newHash);
1019
851
  return;
1020
852
  }
1021
- if (this._currentHash !== null && newHash === this._currentHash) {
1022
- this._cancelPendingNavigation();
853
+ const phase = this._phase;
854
+ const commit = phase.kind === "awaitingHash" ? phase.commit : phase.kind === "committing" ? phase : null;
855
+ if (commit?.hash === newHash) {
856
+ this._phase = commit;
857
+ this._commitNavigation(newHash, commit.route);
1023
858
  return;
1024
859
  }
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
860
+ const currentHash = this._currentHash;
861
+ if (newHash === currentHash) {
862
+ if (this._pendingRestoresHash()) {
863
+ // The URL is back on the committed hash, whose route was never left. That ends the
864
+ // navigation that had moved it away; one that waits for UI5 to write its hash goes on.
865
+ if (this._phase.kind === "evaluating") this._cancelPendingNavigation();else this._undo = null;
866
+ } else {
867
+ // The committed hash is reported again, and its route matches again as it does
868
+ // natively: UI5 has written the hash of a navigation with component targets, or has
869
+ // reset the hash of the hash changer after a target was displayed without a route,
870
+ // or parse() was called directly.
871
+ MobileRouter.prototype.parse.call(this, newHash);
1037
872
  }
1038
- };
1039
- const context = this._createGuardContext(toRoute, newHash, routeInfo, controller.signal);
1040
- const decision = this._pipeline.evaluate(context);
873
+ return;
874
+ }
875
+ const routeInfo = this._matchRoute(newHash);
876
+ const toRoute = routeInfo.name;
877
+
878
+ // A pending navigation that has moved the URL as well leaves this one to undo both changes.
879
+ const pendingUndo = this._pendingRestoresHash() ? undo : null;
880
+ // The router is putting the URL back and gets another hash: that one is not undone as a
881
+ // whole, so that an undo cannot cause the next one.
882
+ const undoing = this._phase.kind === "restoring";
883
+ this._cancelPendingNavigation();
884
+ // A navigationSettled handler that navigated on the cancellation has moved the URL on.
885
+ if (this._currentHash !== currentHash) return;
886
+ this._undo = undoing ? null : this._describeUndo(pendingUndo, reported);
887
+ // Another listener of the hash change that navTo() caused has replaced the hash, before
888
+ // this router received it: undoing this hash change undoes the one of navTo() as well.
889
+ if (this._undo && commit === phase && !commit.restoreHash) this._undo.fullHash = commit.writtenOver;
890
+ const direction = reported ? History.getInstance().getDirection() : undefined;
891
+ const attempt = this._startAttempt(newHash, true, direction);
892
+ const {
893
+ generation
894
+ } = attempt;
895
+ const context = this._createGuardContext(routeInfo, newHash, attempt.controller.signal);
896
+ const decision = this._evaluateGuards(context);
1041
897
  if (isPromiseLike(decision)) {
1042
- decision.then(d => {
1043
- if (generation !== this._parseGeneration || this._phase.kind !== "evaluating") {
898
+ this._applyWhenDecided(decision, d => {
899
+ if (generation !== this._parseGeneration) {
1044
900
  Log.debug("Async guard result discarded (superseded by newer navigation)", newHash, LOG_COMPONENT);
1045
901
  return;
1046
902
  }
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
- });
903
+ this._applyDecision(d, newHash, toRoute, context.bag, attempt);
904
+ }, newHash, true);
1056
905
  return;
1057
906
  }
1058
- this._applyDecision(decision, newHash, toRoute, context.bag);
907
+ this._applyDecision(decision, newHash, toRoute, context.bag, attempt);
1059
908
  },
1060
909
  /**
1061
910
  * Stop listening to hash changes and reset guard state.
1062
911
  *
1063
912
  * Resets `_currentRoute` and `_currentHash` so that a subsequent
1064
913
  * `initialize()` re-parses the current hash and fires `routeMatched`,
1065
- * matching the native `sap.m.routing.Router` behavior.
914
+ * matching the native `sap.m.routing.Router` behavior. The route is
915
+ * kept for `initialize(true)`, which resumes it instead.
1066
916
  *
1067
917
  * @override sap.ui.core.routing.Router#stop
1068
918
  * @since 1.0.1
1069
919
  */
1070
920
  stop: function _stop() {
921
+ if (this._blockLoad) this._blockLoad.start = false;
1071
922
  // Cancel first so in-flight navigationSettled() resolvers receive the
1072
923
  // Cancelled result before _lastSettlement is cleared below.
1073
924
  this._cancelPendingNavigation();
1074
- this._suppressedHash = null;
925
+ // A hash change that was to put the URL back does not reach a stopped router.
926
+ this._undo = null;
927
+ // Nothing is committed on a router that is stopped already, or stops before its first navigation settles.
928
+ if (this._currentHash !== null) this._stoppedRoute = this._currentRoute;
1075
929
  this._currentRoute = "";
1076
930
  this._currentHash = null;
1077
931
  this._lastSettlement = null;
932
+ this._detachHashListeners();
1078
933
  MobileRouter.prototype.stop.call(this);
1079
934
  return this;
1080
935
  },
936
+ /** Detach what {@link _start} has attached. */_detachHashListeners: function _detachHashListeners() {
937
+ this.getHashChanger().detachEvent("hashChanged", this._onHashReported, this);
938
+ // UI5 moves the listener along when the global hash changer is replaced.
939
+ HashChanger.getInstance().detachEvent("hashChanged", this._onRootHashChanged, this);
940
+ this._rootHashChanger = null;
941
+ },
1081
942
  /**
1082
943
  * Invalidate any in-flight async guard work. Bumps the generation counter
1083
944
  * so pending `.then()` callbacks see they are stale, aborts the signal,
1084
- * and transitions to idle.
945
+ * and transitions to idle. A navigation that waits for its guards or for
946
+ * its hash settles as `Cancelled`. With `restoreHash`, a cancelled hash-change
947
+ * navigation also gets its hash restored: `navTo()` passes it when the
948
+ * call itself will not move the URL.
1085
949
  */
1086
- _cancelPendingNavigation: function _cancelPendingNavigation() {
950
+ _cancelPendingNavigation: function _cancelPendingNavigation(restoreHash = false) {
1087
951
  ++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
- }
952
+ const phase = this._phase;
953
+ const pendingRestoresHash = this._pendingRestoresHash();
954
+ // Idle before the settlement fires, so that a handler can navigate.
1096
955
  this._phase = IDLE;
956
+ // A navigation that is committing ends with the navigation that supersedes it.
957
+ if (phase.kind === "idle" || phase.kind === "committing") return;
958
+ if (phase.kind === "restoring") {
959
+ // A navigation that waits for the URL to be back has ended already: it settles as it ended.
960
+ this._flushSettlement(phase.result);
961
+ return;
962
+ }
963
+ if (phase.kind === "evaluating") phase.attempt.controller.abort();
964
+ this._settleUncommitted({
965
+ status: NavigationOutcome.Cancelled,
966
+ route: this._currentRoute,
967
+ hash: this._currentHash ?? ""
968
+ }, phase.kind === "evaluating" ? phase.attempt.hash : phase.commit.hash, restoreHash && pendingRestoresHash);
969
+ },
970
+ /**
971
+ * Whether the pending navigation leaves a hash in the URL that never committed, the one of a
972
+ * hash-change navigation: it must be restored unless a navigation moves the URL.
973
+ */
974
+ _pendingRestoresHash: function _pendingRestoresHash() {
975
+ const phase = this._phase;
976
+ if (phase.kind === "evaluating") return phase.attempt.restoreHash;
977
+ if (phase.kind === "committing") return phase.restoreHash;
978
+ return phase.kind === "awaitingHash" && phase.commit.restoreHash;
979
+ },
980
+ /**
981
+ * Start evaluating a navigation. Its generation is its own, so the result of any earlier
982
+ * attempt is stale: also one that a navigationSettled handler started while this
983
+ * navigation cancelled its predecessor, which is aborted here without a settlement.
984
+ */
985
+ _startAttempt: function _startAttempt(hash, restoreHash, direction) {
986
+ if (this._phase.kind === "evaluating") this._phase.attempt.controller.abort();
987
+ const attempt = {
988
+ hash,
989
+ controller: new AbortController(),
990
+ generation: ++this._parseGeneration,
991
+ restoreHash,
992
+ direction
993
+ };
994
+ this._phase = {
995
+ kind: "evaluating",
996
+ attempt
997
+ };
998
+ return attempt;
999
+ },
1000
+ /**
1001
+ * Apply the decision of async guards once it is there. Until then the navigation is postponed,
1002
+ * which UI5 sees as a route match in progress (see {@link _mirrorMatchingProcess}). The pipeline
1003
+ * turns a failing guard into an error decision, so an error thrown here comes from applying the
1004
+ * decision, which has no caller to throw to: it is logged, and fails the navigation unless that
1005
+ * has settled.
1006
+ */
1007
+ _applyWhenDecided: function _applyWhenDecided(decision, apply, attemptedHash, restoreHash) {
1008
+ if (this._phase.kind === "evaluating") this._phase = {
1009
+ ...this._phase,
1010
+ postponed: true
1011
+ };
1012
+ decision.then(d => {
1013
+ const lastSettlement = this._lastSettlement;
1014
+ try {
1015
+ apply(d);
1016
+ } catch (error) {
1017
+ Log.error("Navigation failed after its guards had settled", error instanceof Error ? error : String(error), LOG_COMPONENT);
1018
+ if (this._lastSettlement === lastSettlement) {
1019
+ this._errorNavigation(error, attemptedHash, restoreHash);
1020
+ }
1021
+ }
1022
+ });
1097
1023
  },
1098
1024
  /**
1099
1025
  * Apply a guard decision for the parse() fallback path.
1100
1026
  */
1101
- _applyDecision: function _applyDecision(decision, hash, route, bag) {
1027
+ _applyDecision: function _applyDecision(decision, hash, route, bag, attempt) {
1028
+ // A guard that navigated itself has superseded the navigation it was guarding.
1029
+ if (attempt.generation !== this._parseGeneration) return;
1102
1030
  switch (decision.action) {
1103
1031
  case "allow":
1104
1032
  this._phase = {
1105
1033
  kind: "committing",
1106
- hash,
1107
1034
  route,
1108
- origin: "parse"
1035
+ hash,
1036
+ origin: "parse",
1037
+ restoreHash: false
1109
1038
  };
1110
1039
  this._commitNavigation(hash, route);
1111
1040
  break;
@@ -1113,24 +1042,52 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1113
1042
  this._blockNavigation(hash);
1114
1043
  break;
1115
1044
  case "redirect":
1116
- this._startRedirectChain(decision.target, hash, true, bag);
1045
+ // The hash that redirects has reached the browser: the target takes its history entry.
1046
+ this._startRedirectChain(decision.target, hash, bag, attempt, true);
1117
1047
  break;
1118
1048
  case "error":
1119
1049
  this._errorNavigation(decision.error, hash);
1120
1050
  break;
1121
1051
  }
1122
1052
  },
1053
+ /**
1054
+ * Leave the title history of UI5 (`getTitleHistory()`) as after the native equivalent of a
1055
+ * redirected hash change: the hash change, then `navTo(target, ..., true)`. The route of the
1056
+ * hash change never matched, so UI5 has not handled its title:
1057
+ * - A new entry or a step forward would have added a title, which the title of the target
1058
+ * replaces: UI5 must not remove the title of the route before it.
1059
+ * - A step back would have removed the title of the route that was left, so that the target
1060
+ * replaces the title of the entry the step arrived at: UI5 removes the first for the
1061
+ * replaced hash, the router removes the second, under the condition of UI5 for a step back.
1062
+ */
1063
+ _alignTitleHistory: function _alignTitleHistory(direction) {
1064
+ if (direction === HistoryDirection.NewEntry || direction === HistoryDirection.Forwards) {
1065
+ Reflect.set(this, "_bLastHashReplaced", false);
1066
+ } else if (direction === HistoryDirection.Backwards) {
1067
+ const titles = this.getTitleHistory();
1068
+ const left = titles.at(-1);
1069
+ const replaced = titles.at(-2);
1070
+ if (isRecord(left) && isRecord(replaced) && !left.isHome && left.title !== replaced.title) {
1071
+ titles.splice(-2, 1);
1072
+ }
1073
+ }
1074
+ },
1123
1075
  /**
1124
1076
  * Delegate to the parent router and update internal state.
1125
1077
  *
1126
1078
  * State is updated BEFORE calling parse to ensure that if event handlers
1127
1079
  * (e.g., routeMatched) trigger nested navigation, the leave guards will
1128
- * run for the correct (new) route rather than the old one.
1080
+ * run for the correct (new) route rather than the old one. The settlement
1081
+ * fires before parse as well, so the settlements of such nested navigations
1082
+ * follow it.
1129
1083
  */
1130
1084
  _commitNavigation: function _commitNavigation(hash, route) {
1131
1085
  const wasRedirect = this._phase.kind === "committing" && this._phase.origin === "redirect";
1086
+ if (this._phase.kind === "committing") this._alignTitleHistory(this._phase.direction);
1087
+ // The URL has moved on: a hash change that was to put it back is not awaited any more.
1088
+ this._undo = null;
1132
1089
  this._currentHash = hash;
1133
- this._currentRoute = route ?? this.getRouteInfoByHash(hash)?.name ?? "";
1090
+ this._currentRoute = route;
1134
1091
  // Transition to idle before super.parse so that routeMatched/patternMatched
1135
1092
  // handlers that call navTo() go through the full guard pipeline.
1136
1093
  this._phase = IDLE;
@@ -1139,13 +1096,40 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1139
1096
  route: this._currentRoute,
1140
1097
  hash
1141
1098
  });
1099
+ // A navigationSettled handler that navigated on has committed its own hash.
1100
+ if (this._currentHash !== hash) return;
1142
1101
  MobileRouter.prototype.parse.call(this, hash);
1143
1102
  },
1103
+ /**
1104
+ * Commit the navigation of the committing phase after `super.navTo()` unless `parse()` has
1105
+ * committed it. Returns whether the navigation takes place:
1106
+ * - The hash changer shows the target hash: the route matches here.
1107
+ * - UI5 writes the hash later, which it does with component targets, once the nested
1108
+ * components are loaded. The navigation waits for it: it commits, and the route matches,
1109
+ * when `parse()` gets that hash, as the route does natively. Committed here, the router
1110
+ * would be on a route that UI5 does not display if the hash is never written.
1111
+ * - Otherwise the hash changer has refused the hash change, as the Fiori launchpad does while
1112
+ * it asks the user about unsaved data. Nothing changed, so nothing is committed.
1113
+ */
1114
+ _commitAfterNavTo: function _commitAfterNavTo(componentTargetInfo) {
1115
+ const phase = this._phase;
1116
+ if (phase.kind !== "committing") return true;
1117
+ if (this.getHashChanger().getHash() === phase.hash) {
1118
+ this._commitNavigation(phase.hash, phase.route);
1119
+ return true;
1120
+ }
1121
+ if (!componentTargetInfo || Object.keys(componentTargetInfo).length === 0) return false;
1122
+ this._phase = {
1123
+ kind: "awaitingHash",
1124
+ commit: phase
1125
+ };
1126
+ return true;
1127
+ },
1144
1128
  /**
1145
1129
  * Evaluate guards on a redirect target and apply the resulting decision.
1146
1130
  *
1147
- * Handles loop detection (visited-hash set + depth cap), unknown-route
1148
- * fallback, sync/async guard evaluation, and recursive chaining when
1131
+ * Handles the unknown-route block, loop detection (visited-hash set +
1132
+ * depth cap), sync/async guard evaluation, and recursive chaining when
1149
1133
  * the target's guard itself returns a redirect. All hops in a chain
1150
1134
  * share the same AbortSignal and generation counter from the original
1151
1135
  * navigation so that a superseding navigation correctly discards
@@ -1156,19 +1140,21 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1156
1140
  */
1157
1141
  _redirect: function _redirect(target, chain) {
1158
1142
  const targetName = typeof target === "string" ? target : target.route;
1159
- let targetHash = null;
1160
- const targetParameters = typeof target === "string" ? {} : target.parameters ?? {};
1161
1143
  const targetRoute = this.getRoute(targetName);
1162
- if (targetRoute) {
1163
- try {
1164
- targetHash = targetRoute.getURL(targetParameters);
1165
- } catch {
1166
- targetHash = null;
1167
- }
1144
+ if (!targetRoute) {
1145
+ Log.warning(`Guard redirect target "${targetName}" is not a known route, treating as blocked`, undefined, LOG_COMPONENT);
1146
+ this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1147
+ return;
1168
1148
  }
1169
-
1170
- // Loop detection: visited set (exact hash match) + depth cap.
1171
- if (targetHash !== null && chain.visited.has(targetHash)) {
1149
+ let targetHash;
1150
+ try {
1151
+ targetHash = targetRoute.getURL(typeof target === "string" ? {} : target.parameters ?? {});
1152
+ } catch (error) {
1153
+ Log.error(`Guard redirect target "${targetName}" has no valid hash, navigation failed`, String(error), LOG_COMPONENT);
1154
+ this._errorNavigation(error, chain.attemptedHash, chain.restoreHash);
1155
+ return;
1156
+ }
1157
+ if (chain.visited.has(targetHash)) {
1172
1158
  Log.error(`Guard redirect loop detected: ${[...chain.visited, targetHash].join(" -> ")}`, undefined, LOG_COMPONENT);
1173
1159
  this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1174
1160
  return;
@@ -1178,120 +1164,78 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1178
1164
  this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1179
1165
  return;
1180
1166
  }
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
- });
1167
+ chain.visited.add(targetHash);
1168
+ const routeInfo = this._matchRoute(targetHash);
1169
+ const toRoute = routeInfo.name;
1170
+ const context = this._createGuardContext(routeInfo, targetHash, chain.signal, chain);
1171
+ const decision = this._evaluateGuards(context, true);
1232
1172
  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
- });
1173
+ this._applyWhenDecided(decision, d => this._applyRedirectDecision(d, target, targetHash, toRoute, chain), chain.attemptedHash, chain.restoreHash);
1241
1174
  return;
1242
1175
  }
1243
- this._applyRedirectDecision(decision, target, resolvedHash, chain);
1176
+ this._applyRedirectDecision(decision, target, targetHash, toRoute, chain);
1244
1177
  },
1245
1178
  /**
1246
1179
  * Apply a guard decision within a redirect chain. For "allow", enter
1247
- * committing phase and delegate to navTo (which hits the existing bypass).
1180
+ * committing phase and delegate to navTo (which hits the existing bypass);
1181
+ * if that does not reach parse(), commit the target directly. A target that
1182
+ * is displayed already settles the navigation without a commit.
1248
1183
  * For "block", block the entire chain. For "redirect", recurse.
1249
1184
  *
1250
1185
  * @param decision - Normalized guard pipeline result for this hop.
1251
1186
  * @param target - The redirect target (route name or {@link GuardRedirect}).
1252
- * @param targetHash - Resolved hash for the redirect target (guaranteed non-null).
1187
+ * @param targetHash - Resolved hash for the redirect target.
1188
+ * @param toRoute - Route that matches the hash, as in the hop's guard context: the route UI5 displays.
1253
1189
  * @param chain - Shared redirect chain context with visited set, signals, etc.
1254
1190
  */
1255
- _applyRedirectDecision: function _applyRedirectDecision(decision, target, targetHash, chain) {
1191
+ _applyRedirectDecision: function _applyRedirectDecision(decision, target, targetHash, toRoute, chain) {
1192
+ // Superseded while the hop's guards ran: by a newer navigation, or by a guard that navigated.
1193
+ if (chain.generation !== this._parseGeneration) return;
1256
1194
  switch (decision.action) {
1257
1195
  case "allow":
1258
1196
  {
1259
- const targetName = typeof target === "string" ? target : target.route;
1260
- const settlementBefore = this._lastSettlement;
1197
+ const componentTargetInfo = typeof target === "string" ? undefined : target.componentTargetInfo;
1198
+ if (targetHash === this._currentHash) {
1199
+ // The target is displayed already, so no route matches again, as for a navTo() to
1200
+ // the committed hash: the URL is put back and UI5 sets the hashes of nested components.
1201
+ this._phase = IDLE;
1202
+ this._settleUncommitted({
1203
+ status: NavigationOutcome.Redirected,
1204
+ route: this._currentRoute,
1205
+ hash: targetHash
1206
+ }, chain.attemptedHash, chain.restoreHash, typeof target !== "string" && componentTargetInfo ? () => {
1207
+ // Unless a settlement handler has moved the URL on.
1208
+ if (this.getHashChanger().getHash() !== targetHash) return;
1209
+ MobileRouter.prototype.navTo.call(this, target.route, target.parameters ?? {}, componentTargetInfo, chain.replace);
1210
+ } : undefined);
1211
+ break;
1212
+ }
1261
1213
  this._phase = {
1262
1214
  kind: "committing",
1215
+ route: toRoute,
1263
1216
  hash: targetHash,
1264
- route: targetName,
1265
- origin: "redirect"
1217
+ origin: "redirect",
1218
+ direction: chain.direction,
1219
+ restoreHash: chain.restoreHash,
1220
+ writtenOver: HashChanger.getInstance().getHash()
1266
1221
  };
1267
1222
  try {
1223
+ // Writing the hash the URL already shows changes nothing, except that a nested
1224
+ // router would add its prefix for an empty hash (see _restoreHash).
1225
+ const hashShown = this.getHashChanger().getHash() === targetHash;
1268
1226
  if (typeof target === "string") {
1269
- this.navTo(target, {}, {}, true);
1270
- } else {
1271
- this.navTo(target.route, target.parameters ?? {}, target.componentTargetInfo, true);
1227
+ if (!hashShown) this.navTo(target, {}, {}, chain.replace);
1228
+ } else if (!hashShown || componentTargetInfo) {
1229
+ this.navTo(target.route, target.parameters ?? {}, componentTargetInfo, chain.replace);
1230
+ }
1231
+ if (!this._commitAfterNavTo(componentTargetInfo)) {
1232
+ this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1272
1233
  }
1273
1234
  } finally {
1274
1235
  if (this._phase.kind === "committing") {
1275
1236
  this._phase = IDLE;
1276
1237
  }
1277
1238
  }
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
1239
  break;
1296
1240
  }
1297
1241
  case "block":
@@ -1305,39 +1249,65 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1305
1249
  break;
1306
1250
  }
1307
1251
  },
1252
+ /** The route that matches a hash, and its arguments. For a hash that no route matches: no route (`""`), no arguments. */_matchRoute: function _matchRoute(hash) {
1253
+ const info = this.getRouteInfoByHash(hash);
1254
+ return {
1255
+ name: info?.name ?? "",
1256
+ arguments: info?.arguments ?? {}
1257
+ };
1258
+ },
1308
1259
  /**
1309
- * Build a guard context for a new navigation.
1310
- * Called by {@link navTo} (preflight path) and {@link parse} (browser-initiated path).
1260
+ * The greedy routes that match `hash` in addition to `firstMatch`, the first route that
1261
+ * matches it. UI5 matches them as well and fires their events.
1311
1262
  */
1312
- _createGuardContext: function _createGuardContext(toRoute, toHash, routeInfo, signal) {
1263
+ _greedyMatches: function _greedyMatches(hash, firstMatch) {
1264
+ return this._greedyRouteNames.filter(name => name !== firstMatch && this.getRoute(name)?.match(hash));
1265
+ },
1266
+ /**
1267
+ * Evaluate the guards of a navigation: of the routes in its context, and of the greedy routes
1268
+ * that are left and entered with them. A hop of a redirect chain leaves no route.
1269
+ */
1270
+ _evaluateGuards: function _evaluateGuards(context, redirectHop = false) {
1271
+ return this._pipeline.evaluate(context, {
1272
+ skipLeaveGuards: redirectHop,
1273
+ alsoLeaving: this._greedyMatches(context.fromHash, context.fromRoute),
1274
+ alsoEntering: this._greedyMatches(context.toHash, context.toRoute)
1275
+ });
1276
+ },
1277
+ /**
1278
+ * Build the guard context of a navigation to `routeInfo`. A hop of a redirect chain passes the
1279
+ * chain, whose source route, source hash and bag are those of the original navigation.
1280
+ */
1281
+ _createGuardContext: function _createGuardContext(routeInfo, toHash, signal, chain) {
1282
+ const fromRoute = chain ? chain.fromRoute : this._currentRoute;
1313
1283
  return {
1314
- toRoute,
1284
+ toRoute: routeInfo.name,
1315
1285
  toHash,
1316
- toArguments: routeInfo?.arguments ?? {},
1317
- fromRoute: this._currentRoute,
1318
- fromHash: this._currentHash ?? "",
1286
+ toArguments: routeInfo.arguments,
1287
+ fromRoute,
1288
+ fromHash: chain ? chain.fromHash : this._currentHash ?? "",
1319
1289
  signal,
1320
- bag: new Map(),
1321
- toMeta: this.getRouteMeta(toRoute),
1322
- fromMeta: this.getRouteMeta(this._currentRoute)
1290
+ bag: chain ? chain.bag : new Map(),
1291
+ toMeta: this.getRouteMeta(routeInfo.name),
1292
+ fromMeta: this.getRouteMeta(fromRoute),
1293
+ ownerComponent: this._ownerComponent
1323
1294
  };
1324
1295
  },
1325
1296
  /**
1326
- * Start a new redirect chain from the current evaluating phase.
1297
+ * Start a new redirect chain for the given evaluating attempt.
1327
1298
  * Called by {@link _applyPreflightDecision} and {@link _applyDecision}
1328
1299
  * when a guard returns a redirect. Delegates to {@link _redirect} with
1329
1300
  * a fresh {@link RedirectChainContext}.
1330
1301
  */
1331
- _startRedirectChain: function _startRedirectChain(target, hash, restoreHash, bag) {
1332
- const {
1333
- attempt
1334
- } = this._phase;
1302
+ _startRedirectChain: function _startRedirectChain(target, hash, bag, attempt, replace) {
1335
1303
  const visited = new Set();
1336
1304
  visited.add(hash);
1337
1305
  this._redirect(target, {
1338
1306
  visited,
1339
1307
  attemptedHash: hash,
1340
- restoreHash,
1308
+ restoreHash: attempt.restoreHash,
1309
+ replace,
1310
+ direction: attempt.direction,
1341
1311
  fromRoute: this._currentRoute,
1342
1312
  fromHash: this._currentHash ?? "",
1343
1313
  signal: attempt.controller.signal,
@@ -1346,19 +1316,17 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1346
1316
  });
1347
1317
  },
1348
1318
  /**
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.
1319
+ * Settle as Blocked. With `restoreHash` (default), the hash change of the navigation is
1320
+ * undone first (see {@link _settleUncommitted}). Preflight callers pass false unless they
1321
+ * superseded a hash-change navigation: otherwise the hash was never changed.
1353
1322
  */
1354
1323
  _blockNavigation: function _blockNavigation(attemptedHash, restoreHash = true) {
1355
1324
  this._phase = IDLE;
1356
- this._flushSettlement({
1325
+ this._settleUncommitted({
1357
1326
  status: NavigationOutcome.Blocked,
1358
1327
  route: this._currentRoute,
1359
1328
  hash: this._currentHash ?? ""
1360
- });
1361
- this._restoreHashIfNeeded(attemptedHash, restoreHash);
1329
+ }, attemptedHash, restoreHash);
1362
1330
  },
1363
1331
  /**
1364
1332
  * Clear pending state and flush an Error settlement.
@@ -1367,314 +1335,213 @@ sap.ui.define(["sap/m/routing/Router", "sap/base/Log", "sap/ui/core/library", ".
1367
1335
  */
1368
1336
  _errorNavigation: function _errorNavigation(error, attemptedHash, restoreHash = true) {
1369
1337
  this._phase = IDLE;
1370
- this._flushSettlement({
1338
+ this._settleUncommitted({
1371
1339
  status: NavigationOutcome.Error,
1372
1340
  route: this._currentRoute,
1373
1341
  hash: this._currentHash ?? "",
1374
1342
  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 ?? "");
1343
+ }, attemptedHash, restoreHash);
1385
1344
  },
1386
1345
  /**
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.
1346
+ * Settle a navigation that did not commit. With `restoreHash`, the hash it left in the URL
1347
+ * is restored first, so that settlement handlers run on the final URL and a hash they set
1348
+ * is not overwritten. The exception is a first navigation: nothing is committed yet, so the
1349
+ * empty hash is restored after the settlement and parsed as a navigation of its own.
1350
+ * `whenBack` runs after the settlement.
1391
1351
  */
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
- }
1352
+ _settleUncommitted: function _settleUncommitted(result, attemptedHash, restoreHash, whenBack) {
1353
+ const loadDefaultRoute = restoreHash && this._currentHash === null && !!attemptedHash;
1354
+ // It settles once the URL is back.
1355
+ if (restoreHash && !loadDefaultRoute && !this._undoHashChange(result, whenBack)) return;
1356
+ this._flushSettlement(result);
1357
+ whenBack?.();
1358
+ // Unless a handler navigated and committed in the meantime.
1359
+ if (loadDefaultRoute && this._currentHash === null) this._restoreHash("", false);
1401
1360
  },
1402
1361
  /**
1403
- * Collect all route names and their patterns from the router.
1404
- * Skips routes whose pattern is undefined (no pattern configured).
1362
+ * Describe how to undo the hash change that the navigation starts with. After `pending`, the
1363
+ * undo of a navigation that this one supersedes, it takes back both changes. A `parse()` that
1364
+ * is not `reported` by the hash changer comes with no hash change.
1405
1365
  */
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;
1366
+ _describeUndo: function _describeUndo(pending, reported) {
1367
+ if (!reported) return pending;
1368
+ const shown = HashChanger.getInstance().getHash();
1369
+ const step = lastStep;
1370
+ if (!pending) return {
1371
+ first: shown,
1372
+ fullHash: undefined,
1373
+ shown,
1374
+ step,
1375
+ started: false
1376
+ };
1377
+ const offset = pending.step && step ? pending.step.offset + step.offset : 0;
1378
+ return {
1379
+ first: pending.first,
1380
+ fullHash: pending.fullHash,
1381
+ shown,
1382
+ step: step && offset ? {
1383
+ offset,
1384
+ href: step.href
1385
+ } : null,
1386
+ started: false
1387
+ };
1421
1388
  },
1422
1389
  /**
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).
1390
+ * Put the URL back after a navigation that did not commit. Returns whether it is back;
1391
+ * otherwise `result` settles when it is.
1392
+ *
1393
+ * While the URL still shows the hash change that started the navigation, that change is undone
1394
+ * as a whole, so that the hashes of nested routers are back as well:
1395
+ * - A step through the browser history is taken back, which leaves the history as it was.
1396
+ * The browser does that asynchronously.
1397
+ * - Any other change (a new entry, or a step the browser does not report) has its entry replaced with
1398
+ * the full previous hash, once UI5 has reported the change to every router. Nested routers
1399
+ * have received their part of the refused hash by then; they receive the previous one next.
1400
+ *
1401
+ * `parse()` ends the wait when the hash change arrives that shows the full previous hash.
1402
+ *
1403
+ * If the URL has moved on since, only the hash of this router is restored. So it is while
1404
+ * no navigation has committed: the URL before the change showed no route of this router either.
1427
1405
  */
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
- }
1406
+ _undoHashChange: function _undoHashChange(result, whenBack) {
1407
+ const undo = this._undo;
1408
+ const hash = this._currentHash;
1409
+ const rootHash = HashChanger.getInstance().getHash();
1410
+ if (undo === null || hash === null || undo.shown !== rootHash || undo.fullHash === rootHash) {
1411
+ this._restoreHash(hash ?? "");
1412
+ return true;
1456
1413
  }
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
- });
1414
+ const href = window.location.href;
1415
+ undo.started = true;
1416
+ this._phase = {
1417
+ kind: "restoring",
1418
+ result,
1419
+ whenBack
1420
+ };
1421
+ if (undoneHref === href) {
1422
+ // Another router is taking the step back.
1423
+ } else if (undo.step) {
1424
+ undoneHref = href;
1425
+ window.history.go(-undo.step.offset);
1426
+ } else if (undo.fullHash === undefined) {
1427
+ // UI5 is still reporting the change to the nested routers.
1428
+ this._phase = {
1429
+ ...this._phase,
1430
+ awaitsReport: true
1431
+ };
1432
+ } else {
1433
+ this._replaceFullHash(undo.fullHash);
1434
+ }
1435
+ return false;
1467
1436
  },
1468
1437
  /**
1469
- * Resolve metadata for a route without inheritance (flat merge of
1470
- * manifest and runtime metadata).
1438
+ * Replace the hash of the root hash changer with the full previous hash, and settle the
1439
+ * navigation that waits for it unless `parse()` has done so.
1471
1440
  */
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
- });
1441
+ _replaceFullHash: function _replaceFullHash(fullHash) {
1442
+ HashChanger.getInstance().replaceHash(fullHash, HistoryDirection.Unknown);
1443
+ this._finishRestore();
1482
1444
  },
1483
1445
  /**
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.
1446
+ * Settle the navigation that waited for the URL to be back: on `hash`, if the hash changer
1447
+ * has reported one with the URL.
1487
1448
  */
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);
1449
+ _finishRestore: function _finishRestore(hash) {
1450
+ const phase = this._phase;
1451
+ if (phase.kind !== "restoring") return;
1452
+ this._phase = IDLE;
1453
+ this._flushSettlement(hash === undefined ? phase.result : {
1454
+ ...phase.result,
1455
+ hash
1456
+ });
1457
+ phase.whenBack?.();
1512
1458
  },
1513
1459
  /**
1514
- * Load guard modules individually via `sap.ui.require` and register
1515
- * each resolved function with the appropriate guard API.
1460
+ * Restore the previous hash of this router without creating a history entry
1461
+ * (see {@link _undoHashChange} for the hash change of a navigation).
1462
+ * Assumes replaceHash fires hashChanged synchronously (validated by test).
1463
+ * `_currentRoute` stays unchanged because the navigation never
1464
+ * committed. The user remains on the same logical route.
1516
1465
  *
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.
1466
+ * A hash that the hash changer already shows is not written again: the navigation never
1467
+ * moved it. For a nested router, writing its empty hash would add its prefix to the browser
1468
+ * hash (`shell` becomes `shell&/child/`).
1522
1469
  */
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
- });
1470
+ _restoreHash: function _restoreHash(hash, suppressParse = true) {
1471
+ const hashChanger = this.getHashChanger();
1472
+ if (hashChanger.getHash() === hash) return;
1473
+ this._suppressedHash = suppressParse ? hash : null;
1474
+ void hashChanger.replaceHash(hash, HistoryDirection.Unknown);
1475
+ this._suppressedHash = null;
1558
1476
  },
1559
1477
  /**
1560
- * Route a parsed guard descriptor to the correct registration method.
1478
+ * Collect all route names and their patterns from the router.
1479
+ * Skips routes whose pattern is undefined (no pattern configured).
1561
1480
  */
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);
1481
+ _collectRoutePatterns: function _collectRoutePatterns() {
1482
+ const result = [];
1483
+ for (const name of this._routeNames) {
1484
+ const pattern = this.getRoute(name)?.getPattern();
1485
+ if (pattern !== undefined) result.push({
1486
+ name,
1487
+ pattern
1488
+ });
1570
1489
  }
1490
+ return result;
1571
1491
  },
1572
1492
  /**
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.
1493
+ * Register one manifest guard: as the last guard of its route, or in front of the guard
1494
+ * `before`. A registration error (`unknownRouteRegistration: "throw"` for an unknown route)
1495
+ * is logged and skips the guard: no caller of the manifest config could catch it, and it
1496
+ * must not keep the router from starting.
1580
1497
  */
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;
1498
+ _registerManifestGuard: function _registerManifestGuard(descriptor, guardFn, before) {
1499
+ try {
1500
+ if (descriptor.route === "*") {
1501
+ this.addGuard(guardFn);
1502
+ return;
1613
1503
  }
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;
1504
+ if (descriptor.type === "leave") {
1505
+ this._handleUnknownRouteRegistration(descriptor.route, "addLeaveGuard");
1506
+ this._pipeline.addLeaveGuard(descriptor.route, guardFn, before);
1507
+ } else {
1508
+ this._handleUnknownRouteRegistration(descriptor.route, "addRouteGuard");
1509
+ this._pipeline.addEnterGuard(descriptor.route, guardFn, before);
1623
1510
  }
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);
1511
+ this._manifestGuards.push({
1512
+ descriptor,
1513
+ fn: guardFn
1514
+ });
1515
+ } catch (err) {
1516
+ Log.error(`guardRouter.guards: failed to register "${descriptor.modulePath}"`, String(err), LOG_COMPONENT);
1517
+ }
1518
+ },
1519
+ /** Register the guards of each descriptor, loading their modules on first use (see `createLazyGuards`). */_registerLazyGuards: function _registerLazyGuards(descriptors) {
1520
+ for (const descriptor of descriptors) {
1521
+ for (const fn of createLazyGuards(descriptor)) this._registerManifestGuard(descriptor, fn);
1655
1522
  }
1656
1523
  },
1657
1524
  /**
1658
1525
  * Clean up guards on destroy. Bumps generation to discard pending async results.
1526
+ * A second call does nothing, like `sap.ui.core.routing.Router#destroy`.
1659
1527
  *
1660
1528
  * @since 1.0.1
1661
1529
  */
1662
1530
  destroy: function _destroy() {
1531
+ if (this._destroyed) return this;
1663
1532
  this._destroyed = true;
1664
1533
  this._pipeline.clear();
1665
1534
  this._pendingGuardDescriptors = [];
1666
1535
  this._sourceDescriptors = [];
1536
+ this._manifestGuards = [];
1667
1537
  this._cancelPendingNavigation();
1668
- this._suppressedHash = null;
1669
1538
  this._lastSettlement = null;
1670
- this._manifestMeta.clear();
1671
- this._runtimeMeta.clear();
1672
- this._resolvedMetaCache.clear();
1539
+ this._detachHashListeners();
1540
+ this._meta.clear();
1673
1541
  MobileRouter.prototype.destroy.call(this);
1674
1542
  return this;
1675
1543
  }
1676
1544
  });
1677
- Router._EMPTY_META = Object.freeze({});
1678
1545
  return Router;
1679
1546
  });
1680
1547
  //# sourceMappingURL=Router-dbg.js.map