-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
apply_redirects.ts
459 lines (397 loc) Β· 18.1 KB
/
apply_redirects.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {EnvironmentInjector, Ι΅RuntimeError as RuntimeError} from '@angular/core';
import {from, Observable, of, throwError} from 'rxjs';
import {catchError, concatMap, first, last, map, mergeMap, scan, switchMap, tap} from 'rxjs/operators';
import {RuntimeErrorCode} from './errors';
import {NavigationCancellationCode} from './events';
import {LoadedRouterConfig, Route, Routes} from './models';
import {navigationCancelingError} from './navigation_canceling_error';
import {runCanLoadGuards} from './operators/check_guards';
import {RouterConfigLoader} from './router_config_loader';
import {Params, PRIMARY_OUTLET} from './shared';
import {createRoot, squashSegmentGroup, UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree} from './url_tree';
import {forEach} from './utils/collection';
import {getOrCreateRouteInjectorIfNeeded, getOutlet, sortByMatchingOutlets} from './utils/config';
import {isImmediateMatch, match, matchWithChecks, noLeftoversInUrl, split} from './utils/config_matching';
import {isEmptyError} from './utils/type_guards';
const NG_DEV_MODE = typeof ngDevMode === 'undefined' || ngDevMode;
class NoMatch {
public segmentGroup: UrlSegmentGroup|null;
constructor(segmentGroup?: UrlSegmentGroup) {
this.segmentGroup = segmentGroup || null;
}
}
class AbsoluteRedirect {
constructor(public urlTree: UrlTree) {}
}
function noMatch(segmentGroup: UrlSegmentGroup): Observable<UrlSegmentGroup> {
return throwError(new NoMatch(segmentGroup));
}
function absoluteRedirect(newTree: UrlTree): Observable<any> {
return throwError(new AbsoluteRedirect(newTree));
}
function namedOutletsRedirect(redirectTo: string): Observable<any> {
return throwError(new RuntimeError(
RuntimeErrorCode.NAMED_OUTLET_REDIRECT,
NG_DEV_MODE &&
`Only absolute redirects can have named outlets. redirectTo: '${redirectTo}'`));
}
function canLoadFails(route: Route): Observable<LoadedRouterConfig> {
return throwError(navigationCancelingError(
NG_DEV_MODE &&
`Cannot load children because the guard of the route "path: '${
route.path}'" returned false`,
NavigationCancellationCode.GuardRejected));
}
/**
* Returns the `UrlTree` with the redirection applied.
*
* Lazy modules are loaded along the way.
*/
export function applyRedirects(
injector: EnvironmentInjector, configLoader: RouterConfigLoader, urlSerializer: UrlSerializer,
urlTree: UrlTree, config: Routes): Observable<UrlTree> {
return new ApplyRedirects(injector, configLoader, urlSerializer, urlTree, config).apply();
}
class ApplyRedirects {
private allowRedirects: boolean = true;
constructor(
private injector: EnvironmentInjector, private configLoader: RouterConfigLoader,
private urlSerializer: UrlSerializer, private urlTree: UrlTree, private config: Routes) {}
apply(): Observable<UrlTree> {
const splitGroup = split(this.urlTree.root, [], [], this.config).segmentGroup;
// TODO(atscott): creating a new segment removes the _sourceSegment _segmentIndexShift, which is
// only necessary to prevent failures in tests which assert exact object matches. The `split` is
// now shared between `applyRedirects` and `recognize` but only the `recognize` step needs these
// properties. Before the implementations were merged, the `applyRedirects` would not assign
// them. We should be able to remove this logic as a "breaking change" but should do some more
// investigation into the failures first.
const rootSegmentGroup = new UrlSegmentGroup(splitGroup.segments, splitGroup.children);
const expanded$ =
this.expandSegmentGroup(this.injector, this.config, rootSegmentGroup, PRIMARY_OUTLET);
const urlTrees$ = expanded$.pipe(map((rootSegmentGroup: UrlSegmentGroup) => {
return this.createUrlTree(
squashSegmentGroup(rootSegmentGroup), this.urlTree.queryParams, this.urlTree.fragment);
}));
return urlTrees$.pipe(catchError((e: any) => {
if (e instanceof AbsoluteRedirect) {
// After an absolute redirect we do not apply any more redirects!
// If this implementation changes, update the documentation note in `redirectTo`.
this.allowRedirects = false;
// we need to run matching, so we can fetch all lazy-loaded modules
return this.match(e.urlTree);
}
if (e instanceof NoMatch) {
throw this.noMatchError(e);
}
throw e;
}));
}
private match(tree: UrlTree): Observable<UrlTree> {
const expanded$ =
this.expandSegmentGroup(this.injector, this.config, tree.root, PRIMARY_OUTLET);
const mapped$ = expanded$.pipe(map((rootSegmentGroup: UrlSegmentGroup) => {
return this.createUrlTree(
squashSegmentGroup(rootSegmentGroup), tree.queryParams, tree.fragment);
}));
return mapped$.pipe(catchError((e: any): Observable<UrlTree> => {
if (e instanceof NoMatch) {
throw this.noMatchError(e);
}
throw e;
}));
}
private noMatchError(e: NoMatch): any {
return new RuntimeError(
RuntimeErrorCode.NO_MATCH,
NG_DEV_MODE && `Cannot match any routes. URL Segment: '${e.segmentGroup}'`);
}
private createUrlTree(rootCandidate: UrlSegmentGroup, queryParams: Params, fragment: string|null):
UrlTree {
const root = createRoot(rootCandidate);
return new UrlTree(root, queryParams, fragment);
}
private expandSegmentGroup(
injector: EnvironmentInjector, routes: Route[], segmentGroup: UrlSegmentGroup,
outlet: string): Observable<UrlSegmentGroup> {
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return this.expandChildren(injector, routes, segmentGroup)
.pipe(map((children: any) => new UrlSegmentGroup([], children)));
}
return this.expandSegment(injector, segmentGroup, routes, segmentGroup.segments, outlet, true);
}
// Recursively expand segment groups for all the child outlets
private expandChildren(
injector: EnvironmentInjector, routes: Route[],
segmentGroup: UrlSegmentGroup): Observable<{[name: string]: UrlSegmentGroup}> {
// Expand outlets one at a time, starting with the primary outlet. We need to do it this way
// because an absolute redirect from the primary outlet takes precedence.
const childOutlets: string[] = [];
for (const child of Object.keys(segmentGroup.children)) {
if (child === 'primary') {
childOutlets.unshift(child);
} else {
childOutlets.push(child);
}
}
return from(childOutlets)
.pipe(
concatMap(childOutlet => {
const child = segmentGroup.children[childOutlet];
// Sort the routes so routes with outlets that match the segment appear
// first, followed by routes for other outlets, which might match if they have an
// empty path.
const sortedRoutes = sortByMatchingOutlets(routes, childOutlet);
return this.expandSegmentGroup(injector, sortedRoutes, child, childOutlet)
.pipe(map(s => ({segment: s, outlet: childOutlet})));
}),
scan(
(children, expandedChild) => {
children[expandedChild.outlet] = expandedChild.segment;
return children;
},
{} as {[outlet: string]: UrlSegmentGroup}),
last(),
);
}
private expandSegment(
injector: EnvironmentInjector, segmentGroup: UrlSegmentGroup, routes: Route[],
segments: UrlSegment[], outlet: string,
allowRedirects: boolean): Observable<UrlSegmentGroup> {
return from(routes).pipe(
concatMap(r => {
const expanded$ = this.expandSegmentAgainstRoute(
injector, segmentGroup, routes, r, segments, outlet, allowRedirects);
return expanded$.pipe(catchError((e: any) => {
if (e instanceof NoMatch) {
return of(null);
}
throw e;
}));
}),
first((s): s is UrlSegmentGroup => !!s), catchError((e: any, _: any) => {
if (isEmptyError(e)) {
if (noLeftoversInUrl(segmentGroup, segments, outlet)) {
return of(new UrlSegmentGroup([], {}));
}
return noMatch(segmentGroup);
}
throw e;
}));
}
private expandSegmentAgainstRoute(
injector: EnvironmentInjector, segmentGroup: UrlSegmentGroup, routes: Route[], route: Route,
paths: UrlSegment[], outlet: string, allowRedirects: boolean): Observable<UrlSegmentGroup> {
if (!isImmediateMatch(route, segmentGroup, paths, outlet)) {
return noMatch(segmentGroup);
}
if (route.redirectTo === undefined) {
return this.matchSegmentAgainstRoute(injector, segmentGroup, route, paths, outlet);
}
if (allowRedirects && this.allowRedirects) {
return this.expandSegmentAgainstRouteUsingRedirect(
injector, segmentGroup, routes, route, paths, outlet);
}
return noMatch(segmentGroup);
}
private expandSegmentAgainstRouteUsingRedirect(
injector: EnvironmentInjector, segmentGroup: UrlSegmentGroup, routes: Route[], route: Route,
segments: UrlSegment[], outlet: string): Observable<UrlSegmentGroup> {
if (route.path === '**') {
return this.expandWildCardWithParamsAgainstRouteUsingRedirect(
injector, routes, route, outlet);
}
return this.expandRegularSegmentAgainstRouteUsingRedirect(
injector, segmentGroup, routes, route, segments, outlet);
}
private expandWildCardWithParamsAgainstRouteUsingRedirect(
injector: EnvironmentInjector, routes: Route[], route: Route,
outlet: string): Observable<UrlSegmentGroup> {
const newTree = this.applyRedirectCommands([], route.redirectTo!, {});
if (route.redirectTo!.startsWith('/')) {
return absoluteRedirect(newTree);
}
return this.lineralizeSegments(route, newTree).pipe(mergeMap((newSegments: UrlSegment[]) => {
const group = new UrlSegmentGroup(newSegments, {});
return this.expandSegment(injector, group, routes, newSegments, outlet, false);
}));
}
private expandRegularSegmentAgainstRouteUsingRedirect(
injector: EnvironmentInjector, segmentGroup: UrlSegmentGroup, routes: Route[], route: Route,
segments: UrlSegment[], outlet: string): Observable<UrlSegmentGroup> {
const {matched, consumedSegments, remainingSegments, positionalParamSegments} =
match(segmentGroup, route, segments);
if (!matched) return noMatch(segmentGroup);
const newTree =
this.applyRedirectCommands(consumedSegments, route.redirectTo!, positionalParamSegments);
if (route.redirectTo!.startsWith('/')) {
return absoluteRedirect(newTree);
}
return this.lineralizeSegments(route, newTree).pipe(mergeMap((newSegments: UrlSegment[]) => {
return this.expandSegment(
injector, segmentGroup, routes, newSegments.concat(remainingSegments), outlet, false);
}));
}
private matchSegmentAgainstRoute(
injector: EnvironmentInjector, rawSegmentGroup: UrlSegmentGroup, route: Route,
segments: UrlSegment[], outlet: string): Observable<UrlSegmentGroup> {
if (route.path === '**') {
// Only create the Route's `EnvironmentInjector` if it matches the attempted navigation
injector = getOrCreateRouteInjectorIfNeeded(route, injector);
if (route.loadChildren) {
const loaded$ = route._loadedRoutes ?
of({routes: route._loadedRoutes, injector: route._loadedInjector}) :
this.configLoader.loadChildren(injector, route);
return loaded$.pipe(map((cfg: LoadedRouterConfig) => {
route._loadedRoutes = cfg.routes;
route._loadedInjector = cfg.injector;
return new UrlSegmentGroup(segments, {});
}));
}
return of(new UrlSegmentGroup(segments, {}));
}
return matchWithChecks(rawSegmentGroup, route, segments, injector, this.urlSerializer)
.pipe(
switchMap(({matched, consumedSegments, remainingSegments}) => {
if (!matched) return noMatch(rawSegmentGroup);
// If the route has an injector created from providers, we should start using that.
injector = route._injector ?? injector;
const childConfig$ = this.getChildConfig(injector, route, segments);
return childConfig$.pipe(mergeMap((routerConfig: LoadedRouterConfig) => {
const childInjector = routerConfig.injector ?? injector;
const childConfig = routerConfig.routes;
const {segmentGroup: splitSegmentGroup, slicedSegments} =
split(rawSegmentGroup, consumedSegments, remainingSegments, childConfig);
// See comment on the other call to `split` about why this is necessary.
const segmentGroup =
new UrlSegmentGroup(splitSegmentGroup.segments, splitSegmentGroup.children);
if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
const expanded$ = this.expandChildren(childInjector, childConfig, segmentGroup);
return expanded$.pipe(
map((children: any) => new UrlSegmentGroup(consumedSegments, children)));
}
if (childConfig.length === 0 && slicedSegments.length === 0) {
return of(new UrlSegmentGroup(consumedSegments, {}));
}
const matchedOnOutlet = getOutlet(route) === outlet;
const expanded$ = this.expandSegment(
childInjector, segmentGroup, childConfig, slicedSegments,
matchedOnOutlet ? PRIMARY_OUTLET : outlet, true);
return expanded$.pipe(
map((cs: UrlSegmentGroup) => new UrlSegmentGroup(
consumedSegments.concat(cs.segments), cs.children)));
}));
}),
);
}
private getChildConfig(injector: EnvironmentInjector, route: Route, segments: UrlSegment[]):
Observable<LoadedRouterConfig> {
if (route.children) {
// The children belong to the same module
return of({routes: route.children, injector});
}
if (route.loadChildren) {
// lazy children belong to the loaded module
if (route._loadedRoutes !== undefined) {
return of({routes: route._loadedRoutes, injector: route._loadedInjector});
}
return runCanLoadGuards(injector, route, segments, this.urlSerializer)
.pipe(mergeMap((shouldLoadResult: boolean) => {
if (shouldLoadResult) {
return this.configLoader.loadChildren(injector, route)
.pipe(tap((cfg: LoadedRouterConfig) => {
route._loadedRoutes = cfg.routes;
route._loadedInjector = cfg.injector;
}));
}
return canLoadFails(route);
}));
}
return of({routes: [], injector});
}
private lineralizeSegments(route: Route, urlTree: UrlTree): Observable<UrlSegment[]> {
let res: UrlSegment[] = [];
let c = urlTree.root;
while (true) {
res = res.concat(c.segments);
if (c.numberOfChildren === 0) {
return of(res);
}
if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) {
return namedOutletsRedirect(route.redirectTo!);
}
c = c.children[PRIMARY_OUTLET];
}
}
private applyRedirectCommands(
segments: UrlSegment[], redirectTo: string, posParams: {[k: string]: UrlSegment}): UrlTree {
return this.applyRedirectCreateUrlTree(
redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams);
}
private applyRedirectCreateUrlTree(
redirectTo: string, urlTree: UrlTree, segments: UrlSegment[],
posParams: {[k: string]: UrlSegment}): UrlTree {
const newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams);
return new UrlTree(
newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams),
urlTree.fragment);
}
private createQueryParams(redirectToParams: Params, actualParams: Params): Params {
const res: Params = {};
forEach(redirectToParams, (v: any, k: string) => {
const copySourceValue = typeof v === 'string' && v.startsWith(':');
if (copySourceValue) {
const sourceName = v.substring(1);
res[k] = actualParams[sourceName];
} else {
res[k] = v;
}
});
return res;
}
private createSegmentGroup(
redirectTo: string, group: UrlSegmentGroup, segments: UrlSegment[],
posParams: {[k: string]: UrlSegment}): UrlSegmentGroup {
const updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams);
let children: {[n: string]: UrlSegmentGroup} = {};
forEach(group.children, (child: UrlSegmentGroup, name: string) => {
children[name] = this.createSegmentGroup(redirectTo, child, segments, posParams);
});
return new UrlSegmentGroup(updatedSegments, children);
}
private createSegments(
redirectTo: string, redirectToSegments: UrlSegment[], actualSegments: UrlSegment[],
posParams: {[k: string]: UrlSegment}): UrlSegment[] {
return redirectToSegments.map(
s => s.path.startsWith(':') ? this.findPosParam(redirectTo, s, posParams) :
this.findOrReturn(s, actualSegments));
}
private findPosParam(
redirectTo: string, redirectToUrlSegment: UrlSegment,
posParams: {[k: string]: UrlSegment}): UrlSegment {
const pos = posParams[redirectToUrlSegment.path.substring(1)];
if (!pos)
throw new RuntimeError(
RuntimeErrorCode.MISSING_REDIRECT,
NG_DEV_MODE &&
`Cannot redirect to '${redirectTo}'. Cannot find '${redirectToUrlSegment.path}'.`);
return pos;
}
private findOrReturn(redirectToUrlSegment: UrlSegment, actualSegments: UrlSegment[]): UrlSegment {
let idx = 0;
for (const s of actualSegments) {
if (s.path === redirectToUrlSegment.path) {
actualSegments.splice(idx);
return s;
}
idx++;
}
return redirectToUrlSegment;
}
}