ui5-lib-guard-router 1.6.2 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/{dist/.ui5 → .ui5}/build-manifest.json +56 -8
  2. package/CHANGELOG.md +190 -0
  3. package/README.md +695 -327
  4. package/dist/index.d.ts +9 -5
  5. package/dist/resources/ui5/guard/router/.library +1 -1
  6. package/dist/resources/ui5/guard/router/GuardConfig-dbg.js +222 -0
  7. package/dist/resources/ui5/guard/router/GuardConfig-dbg.js.map +1 -0
  8. package/dist/resources/ui5/guard/router/GuardConfig.d.ts +89 -0
  9. package/dist/resources/ui5/guard/router/GuardConfig.d.ts.map +1 -0
  10. package/dist/resources/ui5/guard/router/GuardConfig.js +2 -0
  11. package/dist/resources/ui5/guard/router/GuardConfig.js.map +1 -0
  12. package/dist/resources/ui5/guard/router/GuardModules-dbg.js +253 -0
  13. package/dist/resources/ui5/guard/router/GuardModules-dbg.js.map +1 -0
  14. package/dist/resources/ui5/guard/router/GuardModules.d.ts +72 -0
  15. package/dist/resources/ui5/guard/router/GuardModules.d.ts.map +1 -0
  16. package/dist/resources/ui5/guard/router/GuardModules.js +2 -0
  17. package/dist/resources/ui5/guard/router/GuardModules.js.map +1 -0
  18. package/dist/resources/ui5/guard/router/GuardPipeline-dbg.js +122 -121
  19. package/dist/resources/ui5/guard/router/GuardPipeline-dbg.js.map +1 -1
  20. package/dist/resources/ui5/guard/router/GuardPipeline.d.ts +45 -26
  21. package/dist/resources/ui5/guard/router/GuardPipeline.d.ts.map +1 -1
  22. package/dist/resources/ui5/guard/router/GuardPipeline.js +1 -1
  23. package/dist/resources/ui5/guard/router/GuardPipeline.js.map +1 -1
  24. package/dist/resources/ui5/guard/router/NavigationOutcome-dbg.js +3 -3
  25. package/dist/resources/ui5/guard/router/NavigationOutcome-dbg.js.map +1 -1
  26. package/dist/resources/ui5/guard/router/NavigationOutcome.d.ts +3 -3
  27. package/dist/resources/ui5/guard/router/NavigationOutcome.d.ts.map +1 -1
  28. package/dist/resources/ui5/guard/router/NavigationOutcome.js.map +1 -1
  29. package/dist/resources/ui5/guard/router/PatternTree-dbg.js +156 -0
  30. package/dist/resources/ui5/guard/router/PatternTree-dbg.js.map +1 -0
  31. package/dist/resources/ui5/guard/router/PatternTree.d.ts +71 -0
  32. package/dist/resources/ui5/guard/router/PatternTree.d.ts.map +1 -0
  33. package/dist/resources/ui5/guard/router/PatternTree.js +2 -0
  34. package/dist/resources/ui5/guard/router/PatternTree.js.map +1 -0
  35. package/dist/resources/ui5/guard/router/RouteMeta-dbg.js +84 -0
  36. package/dist/resources/ui5/guard/router/RouteMeta-dbg.js.map +1 -0
  37. package/dist/resources/ui5/guard/router/RouteMeta.d.ts +33 -0
  38. package/dist/resources/ui5/guard/router/RouteMeta.d.ts.map +1 -0
  39. package/dist/resources/ui5/guard/router/RouteMeta.js +2 -0
  40. package/dist/resources/ui5/guard/router/RouteMeta.js.map +1 -0
  41. package/dist/resources/ui5/guard/router/Router-dbg.js +882 -1020
  42. package/dist/resources/ui5/guard/router/Router-dbg.js.map +1 -1
  43. package/dist/resources/ui5/guard/router/Router.d.ts +360 -211
  44. package/dist/resources/ui5/guard/router/Router.d.ts.map +1 -1
  45. package/dist/resources/ui5/guard/router/Router.js +1 -1
  46. package/dist/resources/ui5/guard/router/Router.js.map +1 -1
  47. package/dist/resources/ui5/guard/router/library-dbg.js +1 -1
  48. package/dist/resources/ui5/guard/router/library-dbg.js.map +1 -1
  49. package/dist/resources/ui5/guard/router/library-preload.js +8 -4
  50. package/dist/resources/ui5/guard/router/library-preload.js.map +1 -1
  51. package/dist/resources/ui5/guard/router/library.js +1 -1
  52. package/dist/resources/ui5/guard/router/library.js.map +1 -1
  53. package/dist/resources/ui5/guard/router/manifest.json +5 -2
  54. package/dist/resources/ui5/guard/router/types-dbg.js.map +1 -1
  55. package/dist/resources/ui5/guard/router/types.d.ts +94 -39
  56. package/dist/resources/ui5/guard/router/types.d.ts.map +1 -1
  57. package/package.json +10 -6
  58. package/src/GuardConfig.ts +272 -0
  59. package/src/GuardModules.ts +249 -0
  60. package/src/GuardPipeline.ts +155 -128
  61. package/src/NavigationOutcome.ts +3 -3
  62. package/src/PatternTree.ts +145 -0
  63. package/src/RouteMeta.ts +82 -0
  64. package/src/Router.ts +1089 -1130
  65. package/src/manifest.json +5 -2
  66. package/src/types.ts +79 -22
  67. package/tsconfig.json +0 -11
@@ -1,15 +1,15 @@
1
1
  import Log from "sap/base/Log";
2
2
  import type { GuardFn, GuardContext, GuardResult, GuardRedirect } from "./types";
3
3
 
4
- const LOG_COMPONENT = "ui5.guard.router.Router";
4
+ /** The component under which the library logs. */
5
+ export const LOG_COMPONENT = "ui5.guard.router.Router";
5
6
 
6
7
  function isGuardRedirect(value: unknown): value is GuardRedirect {
7
8
  if (typeof value !== "object" || value === null) {
8
9
  return false;
9
10
  }
10
11
 
11
- const { route } = value as GuardRedirect;
12
- return typeof route === "string" && route.length > 0;
12
+ return "route" in value && typeof value.route === "string" && value.route.length > 0;
13
13
  }
14
14
 
15
15
  /**
@@ -23,7 +23,43 @@ export function isPromiseLike<T>(value: unknown): value is PromiseLike<T> {
23
23
  return false;
24
24
  }
25
25
 
26
- return typeof (value as PromiseLike<T>).then === "function";
26
+ return "then" in value && typeof value.then === "function";
27
+ }
28
+
29
+ /** How this engine prints the resolve function of a Promise: `function () { [native code] }` in V8. */
30
+ let resolverSource!: string;
31
+ void new Promise((resolve) => {
32
+ resolverSource = Function.prototype.toString.call(resolve);
33
+ });
34
+
35
+ /**
36
+ * Whether `value` looks exactly like the resolve function of a native Promise: a function with
37
+ * the name `""`, the length `1` and the source text that this engine prints for such a function.
38
+ * `Router#attachRouteMatched` needs this to recognize a UI5 component target that waits for the
39
+ * router. A function written in JavaScript never matches; other anonymous built-ins with one
40
+ * parameter do, above all the reject function of a Promise.
41
+ */
42
+ export function isPromiseResolver(value: unknown): value is () => void {
43
+ return (
44
+ typeof value === "function" &&
45
+ value.name === "" &&
46
+ value.length === 1 &&
47
+ Function.prototype.toString.call(value) === resolverSource
48
+ );
49
+ }
50
+
51
+ /** Names of manifest guards, derived from their module, for log output. */
52
+ const guardNames = new WeakMap<GuardFn, string>();
53
+
54
+ /** Give a guard a name that its log messages show. */
55
+ export function nameGuard(guard: GuardFn, name: string): void {
56
+ guardNames.set(guard, name);
57
+ }
58
+
59
+ /** Describe a guard for log output: `Enter guard [0]`, or `Enter guard [0] "checks#0"` when it has a name. */
60
+ function describeGuard(label: string, index: number, guard: GuardFn): string {
61
+ const name = guardNames.get(guard);
62
+ return name === undefined ? `${label} [${index}]` : `${label} [${index}] "${name}"`;
27
63
  }
28
64
 
29
65
  /**
@@ -35,15 +71,23 @@ export type GuardDecision =
35
71
  | { action: "redirect"; target: string | GuardRedirect }
36
72
  | { action: "error"; error: unknown };
37
73
 
74
+ function toDecision(result: GuardResult): GuardDecision {
75
+ if (result === true) return { action: "allow" };
76
+ if (result === false) return { action: "block" };
77
+ return { action: "redirect", target: result };
78
+ }
79
+
80
+ function toErrorDecision(error: unknown): GuardDecision {
81
+ return { action: "error", error };
82
+ }
83
+
38
84
  /**
39
85
  * Standalone guard evaluation pipeline.
40
86
  *
41
87
  * Owns guard storage (global, enter, leave) and runs the full
42
- * leave -> global-enter -> route-enter pipeline. Pure logic with
43
- * no dependency on Router state beyond the current route name
44
- * passed into evaluate().
45
- *
46
- * @namespace ui5.guard.router
88
+ * leave -> global-enter -> route-enter pipeline. It reads no Router
89
+ * state: evaluate() receives the context and the greedy routes left
90
+ * and entered with it.
47
91
  */
48
92
  export default class GuardPipeline {
49
93
  private _globalGuards: GuardFn[] = [];
@@ -68,16 +112,14 @@ export default class GuardPipeline {
68
112
  *
69
113
  * @param route - Route name as defined in `manifest.json`.
70
114
  * @param guard - Guard function to register.
115
+ * @param before - A guard of the route to register `guard` in front of; at the end without it.
71
116
  */
72
- addEnterGuard(route: string, guard: GuardFn): void {
73
- this._addToGuardMap(this._enterGuards, route, guard);
117
+ addEnterGuard(route: string, guard: GuardFn, before?: GuardFn): void {
118
+ this._addToGuardMap(this._enterGuards, route, guard, before);
74
119
  }
75
120
 
76
121
  /**
77
122
  * Remove a previously registered enter guard by reference.
78
- *
79
- * @param route - Route name.
80
- * @param guard - Guard function to remove.
81
123
  */
82
124
  removeEnterGuard(route: string, guard: GuardFn): void {
83
125
  this._removeFromGuardMap(this._enterGuards, route, guard);
@@ -92,16 +134,14 @@ export default class GuardPipeline {
92
134
  *
93
135
  * @param route - Route name as defined in `manifest.json`.
94
136
  * @param guard - Guard function to register as a leave guard.
137
+ * @param before - A leave guard of the route to register `guard` in front of; at the end without it.
95
138
  */
96
- addLeaveGuard(route: string, guard: GuardFn): void {
97
- this._addToGuardMap(this._leaveGuards, route, guard);
139
+ addLeaveGuard(route: string, guard: GuardFn, before?: GuardFn): void {
140
+ this._addToGuardMap(this._leaveGuards, route, guard, before);
98
141
  }
99
142
 
100
143
  /**
101
144
  * Remove a previously registered leave guard by reference.
102
- *
103
- * @param route - Route name.
104
- * @param guard - Guard function to remove.
105
145
  */
106
146
  removeLeaveGuard(route: string, guard: GuardFn): void {
107
147
  this._removeFromGuardMap(this._leaveGuards, route, guard);
@@ -127,74 +167,68 @@ export default class GuardPipeline {
127
167
  * @param options.skipLeaveGuards - When true, leave guards are skipped even if
128
168
  * `context.fromRoute` is set. Used by redirect chain hops to avoid re-running
129
169
  * leave guards while still preserving `fromRoute` in the context.
170
+ * @param options.alsoLeaving - Greedy routes that are left as well: their leave guards run
171
+ * after those of `context.fromRoute`, with the same context.
172
+ * @param options.alsoEntering - Greedy routes that match as well: their enter guards run
173
+ * after those of `context.toRoute`, with the same context.
130
174
  * @returns A synchronous {@link GuardDecision} when all guards return plain values,
131
175
  * or a `Promise<GuardDecision>` when at least one guard returns a thenable.
132
176
  */
133
- evaluate(context: GuardContext, options?: { skipLeaveGuards?: boolean }): GuardDecision | Promise<GuardDecision> {
134
- const hasLeaveGuards =
135
- !options?.skipLeaveGuards && context.fromRoute !== "" && this._leaveGuards.has(context.fromRoute);
136
- const hasEnterGuards =
137
- this._globalGuards.length > 0 || (context.toRoute !== "" && this._enterGuards.has(context.toRoute));
138
-
139
- if (!hasLeaveGuards && !hasEnterGuards) {
140
- return { action: "allow" };
141
- }
142
-
143
- const processEnterResult = (
144
- enterResult: GuardResult | Promise<GuardResult>,
145
- ): GuardDecision | Promise<GuardDecision> => {
146
- if (isPromiseLike(enterResult)) {
147
- return enterResult
148
- .then((r: GuardResult): GuardDecision => {
149
- if (r === true) return { action: "allow" };
150
- if (r === false) return { action: "block" };
151
- return { action: "redirect", target: r };
152
- })
153
- .catch((error: unknown): GuardDecision => {
154
- return { action: "error", error };
155
- });
156
- }
157
- if (enterResult === true) return { action: "allow" };
158
- if (enterResult === false) return { action: "block" };
159
- return { action: "redirect", target: enterResult };
160
- };
177
+ evaluate(
178
+ context: GuardContext,
179
+ options?: { skipLeaveGuards?: boolean; alsoLeaving?: string[]; alsoEntering?: string[] },
180
+ ): GuardDecision | Promise<GuardDecision> {
181
+ // No route is left on the first navigation, or after a hash that matched none.
182
+ const leaving =
183
+ options?.skipLeaveGuards || context.fromRoute === ""
184
+ ? []
185
+ : [context.fromRoute, ...(options?.alsoLeaving ?? [])];
186
+ const entering = [context.toRoute, ...(options?.alsoEntering ?? [])];
161
187
 
162
188
  const runEnterPhase = (): GuardDecision | Promise<GuardDecision> => {
163
- const enterResult = this._runEnterGuards(context.toRoute, context);
164
- return processEnterResult(enterResult);
189
+ const enterResult = this._runEnterGuards(entering, context);
190
+ return isPromiseLike(enterResult)
191
+ ? enterResult.then(toDecision).catch(toErrorDecision)
192
+ : toDecision(enterResult);
165
193
  };
166
194
 
167
195
  try {
168
- if (hasLeaveGuards) {
169
- const leaveResult = this._runLeaveGuards(context);
170
-
171
- if (isPromiseLike(leaveResult)) {
172
- return leaveResult
173
- .then((allowed: boolean): GuardDecision | Promise<GuardDecision> => {
174
- if (allowed !== true) return { action: "block" };
175
- if (context.signal.aborted) return { action: "block" };
176
- return runEnterPhase();
177
- })
178
- .catch((error: unknown): GuardDecision => {
179
- return { action: "error", error };
180
- });
181
- }
182
- if (leaveResult !== true) return { action: "block" };
196
+ const leaveResult = this._runForEach(leaving, context, (route) =>
197
+ this._runGuards(
198
+ this._leaveGuards.get(route) ?? [],
199
+ context,
200
+ route,
201
+ (result) => this._validateLeaveGuardResult(result),
202
+ "Leave guard",
203
+ ),
204
+ );
205
+
206
+ if (isPromiseLike(leaveResult)) {
207
+ return leaveResult
208
+ .then((allowed: GuardResult): GuardDecision | Promise<GuardDecision> => {
209
+ if (allowed !== true) return { action: "block" };
210
+ if (context.signal.aborted) return { action: "block" };
211
+ return runEnterPhase();
212
+ })
213
+ .catch(toErrorDecision);
183
214
  }
215
+ if (leaveResult !== true) return { action: "block" };
184
216
 
185
217
  return runEnterPhase();
186
218
  } catch (error) {
187
- return { action: "error", error };
219
+ return toErrorDecision(error);
188
220
  }
189
221
  }
190
222
 
191
- private _addToGuardMap<T>(map: Map<string, T[]>, key: string, guard: T): void {
223
+ private _addToGuardMap<T>(map: Map<string, T[]>, key: string, guard: T, before?: T): void {
192
224
  let guards = map.get(key);
193
225
  if (!guards) {
194
226
  guards = [];
195
227
  map.set(key, guards);
196
228
  }
197
- guards.push(guard);
229
+ const index = before === undefined ? -1 : guards.indexOf(before);
230
+ if (index === -1) guards.push(guard);
231
+ else guards.splice(index, 0, guard);
198
232
  }
199
233
 
200
234
  private _removeFromGuardMap<T>(map: Map<string, T[]>, key: string, guard: T): void {
@@ -206,97 +240,91 @@ export default class GuardPipeline {
206
240
  }
207
241
 
208
242
  /**
209
- * Run leave guards for the current route. Returns boolean (no redirects).
210
- *
211
- * The guard array is snapshot-copied before iteration so that guards
212
- * may safely add/remove themselves (e.g. one-shot guards) without
213
- * affecting the current pipeline run.
243
+ * Run `run` for each route in order until one does not return `true`. Stays sync as long
244
+ * as the runs do; after an async run the next one starts unless the navigation was aborted.
214
245
  */
215
- private _runLeaveGuards(context: GuardContext): boolean | Promise<boolean> {
216
- const registered = this._leaveGuards.get(context.fromRoute);
217
- if (!registered || registered.length === 0) return true;
218
-
219
- const guards = registered.slice();
220
- for (let i = 0; i < guards.length; i++) {
221
- try {
222
- const result = guards[i](context);
223
- if (isPromiseLike(result)) {
224
- return this._continueGuardsAsync(
225
- result,
226
- guards,
227
- i,
228
- context,
229
- (candidate) => this._validateLeaveGuardResult(candidate),
230
- "Leave guard",
231
- true,
232
- ) as Promise<boolean>;
233
- }
234
- if (result !== true) return this._validateLeaveGuardResult(result);
235
- } catch (error) {
236
- Log.error(
237
- `Leave guard [${i}] on route "${context.fromRoute}" threw, navigation failed`,
238
- error instanceof Error ? error : String(error),
239
- LOG_COMPONENT,
240
- );
241
- if (context.signal.aborted) return false;
242
- throw error;
246
+ private _runForEach(
247
+ routes: string[],
248
+ context: GuardContext,
249
+ run: (route: string) => GuardResult | Promise<GuardResult>,
250
+ start = 0,
251
+ ): GuardResult | Promise<GuardResult> {
252
+ for (let i = start; i < routes.length; i++) {
253
+ const result = run(routes[i]);
254
+ if (isPromiseLike(result)) {
255
+ return result.then((settled: GuardResult) => {
256
+ if (settled !== true) return settled;
257
+ if (context.signal.aborted) return false;
258
+ return this._runForEach(routes, context, run, i + 1);
259
+ });
243
260
  }
261
+ if (result !== true) return result;
244
262
  }
245
263
  return true;
246
264
  }
247
265
 
248
- /** Run global guards, then route-specific guards. Stays sync when possible. */
249
- private _runEnterGuards(toRoute: string, context: GuardContext): GuardResult | Promise<GuardResult> {
250
- const globalResult = this._runGuards(this._globalGuards, context);
266
+ /** Run global guards, then the route-specific guards of each route in `entering`. Stays sync when possible. */
267
+ private _runEnterGuards(entering: string[], context: GuardContext): GuardResult | Promise<GuardResult> {
268
+ const runRouteGuards = (): GuardResult | Promise<GuardResult> =>
269
+ this._runForEach(entering, context, (route) => this._runRouteGuards(route, context));
270
+ const globalResult = this._runGuards(
271
+ this._globalGuards,
272
+ context,
273
+ context.toRoute,
274
+ (result) => this._validateGuardResult(result),
275
+ "Enter guard",
276
+ );
251
277
 
252
278
  if (isPromiseLike(globalResult)) {
253
279
  return globalResult.then((result: GuardResult) => {
254
280
  if (result !== true) return result;
255
281
  if (context.signal.aborted) return false;
256
- return this._runRouteGuards(toRoute, context);
282
+ return runRouteGuards();
257
283
  });
258
284
  }
259
285
  if (globalResult !== true) return globalResult;
260
- return this._runRouteGuards(toRoute, context);
286
+ return runRouteGuards();
261
287
  }
262
288
 
263
289
  /** Run route-specific guards if any are registered. */
264
290
  private _runRouteGuards(toRoute: string, context: GuardContext): GuardResult | Promise<GuardResult> {
265
- if (!toRoute || !this._enterGuards.has(toRoute)) return true;
266
- return this._runGuards(this._enterGuards.get(toRoute)!, context);
291
+ const guards = toRoute ? this._enterGuards.get(toRoute) : undefined;
292
+ if (!guards) return true;
293
+ return this._runGuards(guards, context, toRoute, (result) => this._validateGuardResult(result), "Enter guard");
267
294
  }
268
295
 
269
296
  /**
270
- * Run guards sync; switch to async path if a Promise is returned.
297
+ * Run guards sync; switch to async path if a Promise is returned. A result that is not
298
+ * `true` ends the run with what `onBlock` makes of it.
271
299
  *
272
300
  * The guard array is snapshot-copied before iteration so that guards
273
301
  * may safely add/remove themselves (e.g. one-shot guards) without
274
302
  * affecting the current pipeline run.
303
+ *
304
+ * @param route - The route the guards are registered for, named in error logs.
275
305
  */
276
- private _runGuards(guards: GuardFn[], context: GuardContext): GuardResult | Promise<GuardResult> {
306
+ private _runGuards<R extends GuardResult>(
307
+ guards: GuardFn[],
308
+ context: GuardContext,
309
+ route: string,
310
+ onBlock: (result: unknown) => R,
311
+ label: string,
312
+ ): R | boolean | Promise<R | boolean> {
277
313
  guards = guards.slice();
278
314
  for (let i = 0; i < guards.length; i++) {
279
315
  try {
280
316
  const result = guards[i](context);
281
317
  if (isPromiseLike(result)) {
282
- return this._continueGuardsAsync(
283
- result,
284
- guards,
285
- i,
286
- context,
287
- (candidate) => this._validateGuardResult(candidate),
288
- "Enter guard",
289
- false,
290
- );
318
+ return this._continueGuardsAsync(result, guards, i, context, onBlock, label, route);
291
319
  }
292
- if (result !== true) return this._validateGuardResult(result);
320
+ if (result !== true) return onBlock(result);
293
321
  } catch (error) {
322
+ if (context.signal.aborted) return false;
294
323
  Log.error(
295
- `Enter guard [${i}] on route "${context.toRoute}" threw, navigation failed`,
324
+ `${describeGuard(label, i, guards[i])} on route "${route}" threw, navigation failed`,
296
325
  error instanceof Error ? error : String(error),
297
326
  LOG_COMPONENT,
298
327
  );
299
- if (context.signal.aborted) return false;
300
328
  throw error;
301
329
  }
302
330
  }
@@ -310,17 +338,17 @@ export default class GuardPipeline {
310
338
  * determines what to return for non-true results: leave guards always
311
339
  * return `false`, enter guards validate and may return redirects.
312
340
  *
313
- * @param isLeaveGuard - When true, error logs reference `fromRoute`; otherwise `toRoute`.
341
+ * @param route - The route the guards are registered for, named in error logs.
314
342
  */
315
- private async _continueGuardsAsync(
343
+ private async _continueGuardsAsync<R extends GuardResult>(
316
344
  pendingResult: PromiseLike<GuardResult>,
317
345
  guards: GuardFn[],
318
346
  currentIndex: number,
319
347
  context: GuardContext,
320
- onBlock: (result: unknown) => GuardResult,
348
+ onBlock: (result: unknown) => R,
321
349
  label: string,
322
- isLeaveGuard: boolean,
323
- ): Promise<GuardResult> {
350
+ route: string,
351
+ ): Promise<R | boolean> {
324
352
  let guardIndex = currentIndex;
325
353
  try {
326
354
  const result = await pendingResult;
@@ -335,9 +363,8 @@ export default class GuardPipeline {
335
363
  return true;
336
364
  } catch (error) {
337
365
  if (!context.signal.aborted) {
338
- const route = isLeaveGuard ? context.fromRoute : context.toRoute;
339
366
  Log.error(
340
- `${label} [${guardIndex}] on route "${route}" threw, navigation failed`,
367
+ `${describeGuard(label, guardIndex, guards[guardIndex])} on route "${route}" threw, navigation failed`,
341
368
  error instanceof Error ? error : String(error),
342
369
  LOG_COMPONENT,
343
370
  );
@@ -14,13 +14,13 @@ const NavigationOutcome = Object.freeze({
14
14
  Committed: "committed",
15
15
  /** Navigation was allowed, but no route matched; UI5 continued with bypassed handling. @since 1.3.0 */
16
16
  Bypassed: "bypassed",
17
- /** A guard blocked navigation; the previous route remains active. @since 1.2.0 */
17
+ /** A guard blocked navigation, or the hash changer refused the hash change; the previous route remains active. @since 1.2.0 */
18
18
  Blocked: "blocked",
19
- /** A guard redirected navigation to a different route. @since 1.2.0 */
19
+ /** A guard redirected navigation to a different route, or to the route that is displayed, which then does not match again. @since 1.2.0 */
20
20
  Redirected: "redirected",
21
21
  /** Navigation was cancelled before settling (superseded, stopped, or destroyed). @since 1.2.0 */
22
22
  Cancelled: "cancelled",
23
- /** A guard threw or rejected; the previous route remains active. @since 1.4.0 */
23
+ /** A guard threw or rejected, a redirect target had no valid hash, or applying the decision failed; the previous route remains active. @since 1.4.0 */
24
24
  Error: "error",
25
25
  });
26
26
 
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Pattern-tree helpers: compare UI5 route patterns by their mandatory path segments.
3
+ */
4
+
5
+ /** Matches a standalone optional (`:param:`) or rest (`:param*:`) segment. */
6
+ const OPTIONAL_OR_REST_SEGMENT = /^:[^:]*:$/;
7
+
8
+ /**
9
+ * Strips inline query and optional-query suffixes from a segment.
10
+ *
11
+ * UI5 (crossroads.js) allows query parameters to attach directly to a
12
+ * path segment without a `/` separator:
13
+ * - `product{?query}` → mandatory query on `product`
14
+ * - `product:?query:` → optional query on `product`
15
+ * - `{id}{?query}` → mandatory param + mandatory query
16
+ *
17
+ * For pattern-tree ancestry we only care about the path portion,
18
+ * so these suffixes are stripped.
19
+ */
20
+ function stripInlineQuery(seg: string): string {
21
+ const mqIdx = seg.indexOf("{?");
22
+ if (mqIdx !== -1) return seg.slice(0, mqIdx);
23
+ const oqIdx = seg.indexOf(":?");
24
+ if (oqIdx !== -1) return seg.slice(0, oqIdx);
25
+ return seg;
26
+ }
27
+
28
+ /**
29
+ * Extract mandatory path segments from a UI5 route pattern.
30
+ *
31
+ * Splits on `/`, strips inline query suffixes, then drops empty segments,
32
+ * standalone optional (`:param:`), and rest (`:param*:`) segments.
33
+ */
34
+ export function patternSegments(pattern: string): string[] {
35
+ return pattern
36
+ .split("/")
37
+ .map(stripInlineQuery)
38
+ .filter((seg) => seg !== "" && !OPTIONAL_OR_REST_SEGMENT.test(seg));
39
+ }
40
+
41
+ /**
42
+ * Check if `ancestorPattern` is a URL-tree ancestor of `candidatePattern`.
43
+ *
44
+ * Both patterns are reduced to their mandatory path segments and compared
45
+ * positionally. Mandatory parameter segments (`{paramA}`, `{paramB}`) are
46
+ * treated as equivalent regardless of name, so `employees/{empId}` is
47
+ * recognized as an ancestor of `employees/{id}/resume`.
48
+ */
49
+ export function isPatternAncestor(ancestorPattern: string, candidatePattern: string): boolean {
50
+ if (ancestorPattern === "") return true;
51
+ const ancestorSegments = patternSegments(ancestorPattern);
52
+ if (ancestorSegments.length === 0) return false;
53
+ const candidateSegments = patternSegments(candidatePattern);
54
+ if (candidateSegments.length <= ancestorSegments.length) return false;
55
+ return ancestorSegments.every((seg, i) => {
56
+ const candidateSeg = candidateSegments[i];
57
+ if (seg === candidateSeg) return true;
58
+ return seg.startsWith("{") && candidateSeg.startsWith("{");
59
+ });
60
+ }
61
+
62
+ /** A route name with its pattern. */
63
+ export interface RoutePattern {
64
+ readonly name: string;
65
+ readonly pattern: string;
66
+ }
67
+
68
+ /** Number of mandatory segments in the pattern of `route` (0 when unknown). */
69
+ function depthOf(route: string, patternByName: ReadonlyMap<string, string>): number {
70
+ return patternSegments(patternByName.get(route) ?? "").length;
71
+ }
72
+
73
+ /**
74
+ * Entries ordered by the pattern depth of their own route, declaration order within one depth.
75
+ * Expanding them in this order puts an ancestor's entries before a descendant's on every route.
76
+ */
77
+ export function byRouteDepth<T extends { readonly route: string }>(
78
+ entries: T[],
79
+ patternByName: ReadonlyMap<string, string>,
80
+ ): T[] {
81
+ return entries.toSorted((a, b) => depthOf(a.route, patternByName) - depthOf(b.route, patternByName));
82
+ }
83
+
84
+ /**
85
+ * Copy each route-specific entry to every descendant route (`inheritance: "pattern-tree"`).
86
+ * Global (`"*"`) entries and entries for routes without a known pattern are kept as-is.
87
+ * Ordered by the pattern depth of the route an entry was declared for, so on every route
88
+ * ancestor guards run before descendant guards, whatever the declaration order. Where global
89
+ * entries end up does not matter: the pipeline runs global guards separately.
90
+ * A route named `"*"` does not pass its entries on, because a `"*"` entry is a global one.
91
+ */
92
+ export function expandToDescendants<T extends { readonly route: string }>(entries: T[], routes: RoutePattern[]): T[] {
93
+ if (routes.length === 0) return entries;
94
+ const patternByName = new Map(routes.map((r) => [r.name, r.pattern]));
95
+
96
+ const expanded: T[] = [];
97
+ for (const entry of byRouteDepth(entries, patternByName)) {
98
+ expanded.push(entry);
99
+ if (entry.route === "*") continue;
100
+ const ancestorPattern = patternByName.get(entry.route);
101
+ if (ancestorPattern === undefined) continue;
102
+ for (const { name, pattern } of routes) {
103
+ if (name !== entry.route && isPatternAncestor(ancestorPattern, pattern)) {
104
+ expanded.push({ ...entry, route: name });
105
+ }
106
+ }
107
+ }
108
+
109
+ return expanded;
110
+ }
111
+
112
+ /**
113
+ * Entries a newly added route inherits (`inheritance: "pattern-tree"`): copies of its
114
+ * ancestors' entries for the new route, and copies of its own entries for its existing
115
+ * descendants. `routes` must include the new route. Ordered like {@link expandToDescendants};
116
+ * where the entries go among those a route has already is up to the caller.
117
+ */
118
+ export function expandForNewRoute<T extends { readonly route: string }>(
119
+ entries: T[],
120
+ newName: string,
121
+ routes: RoutePattern[],
122
+ ): T[] {
123
+ const patternByName = new Map(routes.map((r) => [r.name, r.pattern]));
124
+ const newPattern = patternByName.get(newName);
125
+ if (newPattern === undefined) return [];
126
+
127
+ const result: T[] = [];
128
+ for (const entry of byRouteDepth(entries, patternByName)) {
129
+ if (entry.route === "*") continue;
130
+ if (entry.route === newName) {
131
+ for (const { name, pattern } of routes) {
132
+ if (name !== newName && isPatternAncestor(newPattern, pattern)) {
133
+ result.push({ ...entry, route: name });
134
+ }
135
+ }
136
+ } else {
137
+ const ancestorPattern = patternByName.get(entry.route);
138
+ if (ancestorPattern !== undefined && isPatternAncestor(ancestorPattern, newPattern)) {
139
+ result.push({ ...entry, route: newName });
140
+ }
141
+ }
142
+ }
143
+
144
+ return result;
145
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Route metadata: manifest and runtime values per route, resolved with
3
+ * optional pattern-tree inheritance and cached until something changes.
4
+ */
5
+ import { isPatternAncestor, patternSegments, type RoutePattern } from "./PatternTree";
6
+
7
+ type Meta = Readonly<Record<string, unknown>>;
8
+
9
+ export const EMPTY_META: Meta = Object.freeze({});
10
+
11
+ export default class RouteMetaStore {
12
+ private readonly _manifest: Map<string, Meta>;
13
+ private readonly _runtime = new Map<string, Meta>();
14
+ private readonly _resolved = new Map<string, Meta>();
15
+ private readonly _routes: (() => RoutePattern[]) | null;
16
+
17
+ /**
18
+ * @param manifest - Frozen metadata per route from the manifest `routeMeta` block.
19
+ * @param routes - Route patterns for pattern-tree inheritance, or `null` for none.
20
+ */
21
+ constructor(manifest: Map<string, Meta>, routes: (() => RoutePattern[]) | null) {
22
+ this._manifest = manifest;
23
+ this._routes = routes;
24
+ }
25
+
26
+ /** Resolved metadata for a route: frozen, and the same object until something changes. */
27
+ get(routeName: string): Meta {
28
+ let result = this._resolved.get(routeName);
29
+ if (result === undefined) {
30
+ result = this._routes ? this._resolveInherited(routeName, this._routes()) : this._resolveOwn(routeName);
31
+ if (Object.keys(result).length === 0) result = EMPTY_META;
32
+ this._resolved.set(routeName, result);
33
+ }
34
+ return result;
35
+ }
36
+
37
+ /** Set runtime metadata for a route, merged over its manifest metadata. */
38
+ set(routeName: string, meta: Record<string, unknown>): void {
39
+ this._runtime.set(routeName, Object.freeze({ ...meta }));
40
+ this._resolved.clear();
41
+ }
42
+
43
+ /** Drop resolved values, e.g. after a route was added that changes inheritance. */
44
+ invalidate(): void {
45
+ this._resolved.clear();
46
+ }
47
+
48
+ /** Drop all metadata, manifest and runtime. */
49
+ clear(): void {
50
+ this._manifest.clear();
51
+ this._runtime.clear();
52
+ this._resolved.clear();
53
+ }
54
+
55
+ /** Manifest metadata with runtime metadata on top, without inheritance. */
56
+ private _resolveOwn(routeName: string): Meta {
57
+ const manifest = this._manifest.get(routeName);
58
+ const runtime = this._runtime.get(routeName);
59
+ if (!runtime) return manifest ?? EMPTY_META;
60
+ if (!manifest) return runtime;
61
+ return Object.freeze({ ...manifest, ...runtime });
62
+ }
63
+
64
+ /** Ancestors' metadata shallowest-first, then the route's own; each level manifest then runtime. */
65
+ private _resolveInherited(routeName: string, routes: RoutePattern[]): Meta {
66
+ const own = routes.find((r) => r.name === routeName);
67
+ if (!own) return this._resolveOwn(routeName);
68
+
69
+ const levels = routes
70
+ // Only the empty pattern counts as its own ancestor; merging a level twice changes nothing.
71
+ .filter((r) => isPatternAncestor(r.pattern, own.pattern))
72
+ .toSorted((a, b) => patternSegments(a.pattern).length - patternSegments(b.pattern).length)
73
+ .map((r) => r.name);
74
+ levels.push(routeName);
75
+
76
+ const merged: Record<string, unknown> = {};
77
+ for (const name of levels) {
78
+ Object.assign(merged, this._manifest.get(name), this._runtime.get(name));
79
+ }
80
+ return Object.freeze(merged);
81
+ }
82
+ }