UNPKG

260 kBJavaScriptView Raw
1/**
2 * @license Angular v8.2.0
3 * (c) 2010-2019 Google LLC. https://angular.io/
4 * License: MIT
5 */
6
7(function (global, factory) {
8 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common'), require('@angular/core'), require('rxjs'), require('rxjs/operators'), require('@angular/platform-browser')) :
9 typeof define === 'function' && define.amd ? define('@angular/router', ['exports', '@angular/common', '@angular/core', 'rxjs', 'rxjs/operators', '@angular/platform-browser'], factory) :
10 (global = global || self, factory((global.ng = global.ng || {}, global.ng.router = {}), global.ng.common, global.ng.core, global.rxjs, global.rxjs.operators, global.ng.platformBrowser));
11}(this, function (exports, common, core, rxjs, operators, platformBrowser) { 'use strict';
12
13 /*! *****************************************************************************
14 Copyright (c) Microsoft Corporation. All rights reserved.
15 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
16 this file except in compliance with the License. You may obtain a copy of the
17 License at http://www.apache.org/licenses/LICENSE-2.0
18
19 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
20 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
21 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
22 MERCHANTABLITY OR NON-INFRINGEMENT.
23
24 See the Apache Version 2.0 License for specific language governing permissions
25 and limitations under the License.
26 ***************************************************************************** */
27 /* global Reflect, Promise */
28
29 var extendStatics = function(d, b) {
30 extendStatics = Object.setPrototypeOf ||
31 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33 return extendStatics(d, b);
34 };
35
36 function __extends(d, b) {
37 extendStatics(d, b);
38 function __() { this.constructor = d; }
39 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40 }
41
42 var __assign = function() {
43 __assign = Object.assign || function __assign(t) {
44 for (var s, i = 1, n = arguments.length; i < n; i++) {
45 s = arguments[i];
46 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
47 }
48 return t;
49 };
50 return __assign.apply(this, arguments);
51 };
52
53 function __decorate(decorators, target, key, desc) {
54 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
55 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
56 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
57 return c > 3 && r && Object.defineProperty(target, key, r), r;
58 }
59
60 function __param(paramIndex, decorator) {
61 return function (target, key) { decorator(target, key, paramIndex); }
62 }
63
64 function __metadata(metadataKey, metadataValue) {
65 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
66 }
67
68 function __values(o) {
69 var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
70 if (m) return m.call(o);
71 return {
72 next: function () {
73 if (o && i >= o.length) o = void 0;
74 return { value: o && o[i++], done: !o };
75 }
76 };
77 }
78
79 function __read(o, n) {
80 var m = typeof Symbol === "function" && o[Symbol.iterator];
81 if (!m) return o;
82 var i = m.call(o), r, ar = [], e;
83 try {
84 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
85 }
86 catch (error) { e = { error: error }; }
87 finally {
88 try {
89 if (r && !r.done && (m = i["return"])) m.call(i);
90 }
91 finally { if (e) throw e.error; }
92 }
93 return ar;
94 }
95
96 function __spread() {
97 for (var ar = [], i = 0; i < arguments.length; i++)
98 ar = ar.concat(__read(arguments[i]));
99 return ar;
100 }
101
102 /**
103 * @license
104 * Copyright Google Inc. All Rights Reserved.
105 *
106 * Use of this source code is governed by an MIT-style license that can be
107 * found in the LICENSE file at https://angular.io/license
108 */
109 /**
110 * Base for events the router goes through, as opposed to events tied to a specific
111 * route. Fired one time for any given navigation.
112 *
113 * @usageNotes
114 *
115 * ```ts
116 * class MyService {
117 * constructor(public router: Router, logger: Logger) {
118 * router.events.pipe(
119 * filter(e => e instanceof RouterEvent)
120 * ).subscribe(e => {
121 * logger.log(e.id, e.url);
122 * });
123 * }
124 * }
125 * ```
126 *
127 * @see `Event`
128 * @publicApi
129 */
130 var RouterEvent = /** @class */ (function () {
131 function RouterEvent(
132 /** A unique ID that the router assigns to every router navigation. */
133 id,
134 /** The URL that is the destination for this navigation. */
135 url) {
136 this.id = id;
137 this.url = url;
138 }
139 return RouterEvent;
140 }());
141 /**
142 * An event triggered when a navigation starts.
143 *
144 * @publicApi
145 */
146 var NavigationStart = /** @class */ (function (_super) {
147 __extends(NavigationStart, _super);
148 function NavigationStart(
149 /** @docsNotRequired */
150 id,
151 /** @docsNotRequired */
152 url,
153 /** @docsNotRequired */
154 navigationTrigger,
155 /** @docsNotRequired */
156 restoredState) {
157 if (navigationTrigger === void 0) { navigationTrigger = 'imperative'; }
158 if (restoredState === void 0) { restoredState = null; }
159 var _this = _super.call(this, id, url) || this;
160 _this.navigationTrigger = navigationTrigger;
161 _this.restoredState = restoredState;
162 return _this;
163 }
164 /** @docsNotRequired */
165 NavigationStart.prototype.toString = function () { return "NavigationStart(id: " + this.id + ", url: '" + this.url + "')"; };
166 return NavigationStart;
167 }(RouterEvent));
168 /**
169 * An event triggered when a navigation ends successfully.
170 *
171 * @publicApi
172 */
173 var NavigationEnd = /** @class */ (function (_super) {
174 __extends(NavigationEnd, _super);
175 function NavigationEnd(
176 /** @docsNotRequired */
177 id,
178 /** @docsNotRequired */
179 url,
180 /** @docsNotRequired */
181 urlAfterRedirects) {
182 var _this = _super.call(this, id, url) || this;
183 _this.urlAfterRedirects = urlAfterRedirects;
184 return _this;
185 }
186 /** @docsNotRequired */
187 NavigationEnd.prototype.toString = function () {
188 return "NavigationEnd(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "')";
189 };
190 return NavigationEnd;
191 }(RouterEvent));
192 /**
193 * An event triggered when a navigation is canceled.
194 *
195 * @publicApi
196 */
197 var NavigationCancel = /** @class */ (function (_super) {
198 __extends(NavigationCancel, _super);
199 function NavigationCancel(
200 /** @docsNotRequired */
201 id,
202 /** @docsNotRequired */
203 url,
204 /** @docsNotRequired */
205 reason) {
206 var _this = _super.call(this, id, url) || this;
207 _this.reason = reason;
208 return _this;
209 }
210 /** @docsNotRequired */
211 NavigationCancel.prototype.toString = function () { return "NavigationCancel(id: " + this.id + ", url: '" + this.url + "')"; };
212 return NavigationCancel;
213 }(RouterEvent));
214 /**
215 * An event triggered when a navigation fails due to an unexpected error.
216 *
217 * @publicApi
218 */
219 var NavigationError = /** @class */ (function (_super) {
220 __extends(NavigationError, _super);
221 function NavigationError(
222 /** @docsNotRequired */
223 id,
224 /** @docsNotRequired */
225 url,
226 /** @docsNotRequired */
227 error) {
228 var _this = _super.call(this, id, url) || this;
229 _this.error = error;
230 return _this;
231 }
232 /** @docsNotRequired */
233 NavigationError.prototype.toString = function () {
234 return "NavigationError(id: " + this.id + ", url: '" + this.url + "', error: " + this.error + ")";
235 };
236 return NavigationError;
237 }(RouterEvent));
238 /**
239 *An event triggered when routes are recognized.
240 *
241 * @publicApi
242 */
243 var RoutesRecognized = /** @class */ (function (_super) {
244 __extends(RoutesRecognized, _super);
245 function RoutesRecognized(
246 /** @docsNotRequired */
247 id,
248 /** @docsNotRequired */
249 url,
250 /** @docsNotRequired */
251 urlAfterRedirects,
252 /** @docsNotRequired */
253 state) {
254 var _this = _super.call(this, id, url) || this;
255 _this.urlAfterRedirects = urlAfterRedirects;
256 _this.state = state;
257 return _this;
258 }
259 /** @docsNotRequired */
260 RoutesRecognized.prototype.toString = function () {
261 return "RoutesRecognized(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ")";
262 };
263 return RoutesRecognized;
264 }(RouterEvent));
265 /**
266 * An event triggered at the start of the Guard phase of routing.
267 *
268 * @publicApi
269 */
270 var GuardsCheckStart = /** @class */ (function (_super) {
271 __extends(GuardsCheckStart, _super);
272 function GuardsCheckStart(
273 /** @docsNotRequired */
274 id,
275 /** @docsNotRequired */
276 url,
277 /** @docsNotRequired */
278 urlAfterRedirects,
279 /** @docsNotRequired */
280 state) {
281 var _this = _super.call(this, id, url) || this;
282 _this.urlAfterRedirects = urlAfterRedirects;
283 _this.state = state;
284 return _this;
285 }
286 GuardsCheckStart.prototype.toString = function () {
287 return "GuardsCheckStart(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ")";
288 };
289 return GuardsCheckStart;
290 }(RouterEvent));
291 /**
292 * An event triggered at the end of the Guard phase of routing.
293 *
294 * @publicApi
295 */
296 var GuardsCheckEnd = /** @class */ (function (_super) {
297 __extends(GuardsCheckEnd, _super);
298 function GuardsCheckEnd(
299 /** @docsNotRequired */
300 id,
301 /** @docsNotRequired */
302 url,
303 /** @docsNotRequired */
304 urlAfterRedirects,
305 /** @docsNotRequired */
306 state,
307 /** @docsNotRequired */
308 shouldActivate) {
309 var _this = _super.call(this, id, url) || this;
310 _this.urlAfterRedirects = urlAfterRedirects;
311 _this.state = state;
312 _this.shouldActivate = shouldActivate;
313 return _this;
314 }
315 GuardsCheckEnd.prototype.toString = function () {
316 return "GuardsCheckEnd(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ", shouldActivate: " + this.shouldActivate + ")";
317 };
318 return GuardsCheckEnd;
319 }(RouterEvent));
320 /**
321 * An event triggered at the the start of the Resolve phase of routing.
322 *
323 * Runs in the "resolve" phase whether or not there is anything to resolve.
324 * In future, may change to only run when there are things to be resolved.
325 *
326 * @publicApi
327 */
328 var ResolveStart = /** @class */ (function (_super) {
329 __extends(ResolveStart, _super);
330 function ResolveStart(
331 /** @docsNotRequired */
332 id,
333 /** @docsNotRequired */
334 url,
335 /** @docsNotRequired */
336 urlAfterRedirects,
337 /** @docsNotRequired */
338 state) {
339 var _this = _super.call(this, id, url) || this;
340 _this.urlAfterRedirects = urlAfterRedirects;
341 _this.state = state;
342 return _this;
343 }
344 ResolveStart.prototype.toString = function () {
345 return "ResolveStart(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ")";
346 };
347 return ResolveStart;
348 }(RouterEvent));
349 /**
350 * An event triggered at the end of the Resolve phase of routing.
351 * @see `ResolveStart`.
352 *
353 * @publicApi
354 */
355 var ResolveEnd = /** @class */ (function (_super) {
356 __extends(ResolveEnd, _super);
357 function ResolveEnd(
358 /** @docsNotRequired */
359 id,
360 /** @docsNotRequired */
361 url,
362 /** @docsNotRequired */
363 urlAfterRedirects,
364 /** @docsNotRequired */
365 state) {
366 var _this = _super.call(this, id, url) || this;
367 _this.urlAfterRedirects = urlAfterRedirects;
368 _this.state = state;
369 return _this;
370 }
371 ResolveEnd.prototype.toString = function () {
372 return "ResolveEnd(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ")";
373 };
374 return ResolveEnd;
375 }(RouterEvent));
376 /**
377 * An event triggered before lazy loading a route configuration.
378 *
379 * @publicApi
380 */
381 var RouteConfigLoadStart = /** @class */ (function () {
382 function RouteConfigLoadStart(
383 /** @docsNotRequired */
384 route) {
385 this.route = route;
386 }
387 RouteConfigLoadStart.prototype.toString = function () { return "RouteConfigLoadStart(path: " + this.route.path + ")"; };
388 return RouteConfigLoadStart;
389 }());
390 /**
391 * An event triggered when a route has been lazy loaded.
392 *
393 * @publicApi
394 */
395 var RouteConfigLoadEnd = /** @class */ (function () {
396 function RouteConfigLoadEnd(
397 /** @docsNotRequired */
398 route) {
399 this.route = route;
400 }
401 RouteConfigLoadEnd.prototype.toString = function () { return "RouteConfigLoadEnd(path: " + this.route.path + ")"; };
402 return RouteConfigLoadEnd;
403 }());
404 /**
405 * An event triggered at the start of the child-activation
406 * part of the Resolve phase of routing.
407 * @see `ChildActivationEnd`
408 * @see `ResolveStart`
409 *
410 * @publicApi
411 */
412 var ChildActivationStart = /** @class */ (function () {
413 function ChildActivationStart(
414 /** @docsNotRequired */
415 snapshot) {
416 this.snapshot = snapshot;
417 }
418 ChildActivationStart.prototype.toString = function () {
419 var path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
420 return "ChildActivationStart(path: '" + path + "')";
421 };
422 return ChildActivationStart;
423 }());
424 /**
425 * An event triggered at the end of the child-activation part
426 * of the Resolve phase of routing.
427 * @see `ChildActivationStart`
428 * @see `ResolveStart` *
429 * @publicApi
430 */
431 var ChildActivationEnd = /** @class */ (function () {
432 function ChildActivationEnd(
433 /** @docsNotRequired */
434 snapshot) {
435 this.snapshot = snapshot;
436 }
437 ChildActivationEnd.prototype.toString = function () {
438 var path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
439 return "ChildActivationEnd(path: '" + path + "')";
440 };
441 return ChildActivationEnd;
442 }());
443 /**
444 * An event triggered at the start of the activation part
445 * of the Resolve phase of routing.
446 * @see ActivationEnd`
447 * @see `ResolveStart`
448 *
449 * @publicApi
450 */
451 var ActivationStart = /** @class */ (function () {
452 function ActivationStart(
453 /** @docsNotRequired */
454 snapshot) {
455 this.snapshot = snapshot;
456 }
457 ActivationStart.prototype.toString = function () {
458 var path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
459 return "ActivationStart(path: '" + path + "')";
460 };
461 return ActivationStart;
462 }());
463 /**
464 * An event triggered at the end of the activation part
465 * of the Resolve phase of routing.
466 * @see `ActivationStart`
467 * @see `ResolveStart`
468 *
469 * @publicApi
470 */
471 var ActivationEnd = /** @class */ (function () {
472 function ActivationEnd(
473 /** @docsNotRequired */
474 snapshot) {
475 this.snapshot = snapshot;
476 }
477 ActivationEnd.prototype.toString = function () {
478 var path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
479 return "ActivationEnd(path: '" + path + "')";
480 };
481 return ActivationEnd;
482 }());
483 /**
484 * An event triggered by scrolling.
485 *
486 * @publicApi
487 */
488 var Scroll = /** @class */ (function () {
489 function Scroll(
490 /** @docsNotRequired */
491 routerEvent,
492 /** @docsNotRequired */
493 position,
494 /** @docsNotRequired */
495 anchor) {
496 this.routerEvent = routerEvent;
497 this.position = position;
498 this.anchor = anchor;
499 }
500 Scroll.prototype.toString = function () {
501 var pos = this.position ? this.position[0] + ", " + this.position[1] : null;
502 return "Scroll(anchor: '" + this.anchor + "', position: '" + pos + "')";
503 };
504 return Scroll;
505 }());
506
507 /**
508 * @license
509 * Copyright Google Inc. All Rights Reserved.
510 *
511 * Use of this source code is governed by an MIT-style license that can be
512 * found in the LICENSE file at https://angular.io/license
513 */
514 /**
515 * This component is used internally within the router to be a placeholder when an empty
516 * router-outlet is needed. For example, with a config such as:
517 *
518 * `{path: 'parent', outlet: 'nav', children: [...]}`
519 *
520 * In order to render, there needs to be a component on this config, which will default
521 * to this `EmptyOutletComponent`.
522 */
523 var ɵEmptyOutletComponent = /** @class */ (function () {
524 function ɵEmptyOutletComponent() {
525 }
526 ɵEmptyOutletComponent = __decorate([
527 core.Component({ template: "<router-outlet></router-outlet>" })
528 ], ɵEmptyOutletComponent);
529 return ɵEmptyOutletComponent;
530 }());
531
532 /**
533 * @license
534 * Copyright Google Inc. All Rights Reserved.
535 *
536 * Use of this source code is governed by an MIT-style license that can be
537 * found in the LICENSE file at https://angular.io/license
538 */
539 /**
540 * The primary routing outlet.
541 *
542 * @publicApi
543 */
544 var PRIMARY_OUTLET = 'primary';
545 var ParamsAsMap = /** @class */ (function () {
546 function ParamsAsMap(params) {
547 this.params = params || {};
548 }
549 ParamsAsMap.prototype.has = function (name) { return this.params.hasOwnProperty(name); };
550 ParamsAsMap.prototype.get = function (name) {
551 if (this.has(name)) {
552 var v = this.params[name];
553 return Array.isArray(v) ? v[0] : v;
554 }
555 return null;
556 };
557 ParamsAsMap.prototype.getAll = function (name) {
558 if (this.has(name)) {
559 var v = this.params[name];
560 return Array.isArray(v) ? v : [v];
561 }
562 return [];
563 };
564 Object.defineProperty(ParamsAsMap.prototype, "keys", {
565 get: function () { return Object.keys(this.params); },
566 enumerable: true,
567 configurable: true
568 });
569 return ParamsAsMap;
570 }());
571 /**
572 * Converts a `Params` instance to a `ParamMap`.
573 * @param params The instance to convert.
574 * @returns The new map instance.
575 *
576 * @publicApi
577 */
578 function convertToParamMap(params) {
579 return new ParamsAsMap(params);
580 }
581 var NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError';
582 function navigationCancelingError(message) {
583 var error = Error('NavigationCancelingError: ' + message);
584 error[NAVIGATION_CANCELING_ERROR] = true;
585 return error;
586 }
587 function isNavigationCancelingError(error) {
588 return error && error[NAVIGATION_CANCELING_ERROR];
589 }
590 // Matches the route configuration (`route`) against the actual URL (`segments`).
591 function defaultUrlMatcher(segments, segmentGroup, route) {
592 var parts = route.path.split('/');
593 if (parts.length > segments.length) {
594 // The actual URL is shorter than the config, no match
595 return null;
596 }
597 if (route.pathMatch === 'full' &&
598 (segmentGroup.hasChildren() || parts.length < segments.length)) {
599 // The config is longer than the actual URL but we are looking for a full match, return null
600 return null;
601 }
602 var posParams = {};
603 // Check each config part against the actual URL
604 for (var index = 0; index < parts.length; index++) {
605 var part = parts[index];
606 var segment = segments[index];
607 var isParameter = part.startsWith(':');
608 if (isParameter) {
609 posParams[part.substring(1)] = segment;
610 }
611 else if (part !== segment.path) {
612 // The actual URL part does not match the config, no match
613 return null;
614 }
615 }
616 return { consumed: segments.slice(0, parts.length), posParams: posParams };
617 }
618
619 /**
620 * @license
621 * Copyright Google Inc. All Rights Reserved.
622 *
623 * Use of this source code is governed by an MIT-style license that can be
624 * found in the LICENSE file at https://angular.io/license
625 */
626 var LoadedRouterConfig = /** @class */ (function () {
627 function LoadedRouterConfig(routes, module) {
628 this.routes = routes;
629 this.module = module;
630 }
631 return LoadedRouterConfig;
632 }());
633 function validateConfig(config, parentPath) {
634 if (parentPath === void 0) { parentPath = ''; }
635 // forEach doesn't iterate undefined values
636 for (var i = 0; i < config.length; i++) {
637 var route = config[i];
638 var fullPath = getFullPath(parentPath, route);
639 validateNode(route, fullPath);
640 }
641 }
642 function validateNode(route, fullPath) {
643 if (!route) {
644 throw new Error("\n Invalid configuration of route '" + fullPath + "': Encountered undefined route.\n The reason might be an extra comma.\n\n Example:\n const routes: Routes = [\n { path: '', redirectTo: '/dashboard', pathMatch: 'full' },\n { path: 'dashboard', component: DashboardComponent },, << two commas\n { path: 'detail/:id', component: HeroDetailComponent }\n ];\n ");
645 }
646 if (Array.isArray(route)) {
647 throw new Error("Invalid configuration of route '" + fullPath + "': Array cannot be specified");
648 }
649 if (!route.component && !route.children && !route.loadChildren &&
650 (route.outlet && route.outlet !== PRIMARY_OUTLET)) {
651 throw new Error("Invalid configuration of route '" + fullPath + "': a componentless route without children or loadChildren cannot have a named outlet set");
652 }
653 if (route.redirectTo && route.children) {
654 throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and children cannot be used together");
655 }
656 if (route.redirectTo && route.loadChildren) {
657 throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and loadChildren cannot be used together");
658 }
659 if (route.children && route.loadChildren) {
660 throw new Error("Invalid configuration of route '" + fullPath + "': children and loadChildren cannot be used together");
661 }
662 if (route.redirectTo && route.component) {
663 throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and component cannot be used together");
664 }
665 if (route.path && route.matcher) {
666 throw new Error("Invalid configuration of route '" + fullPath + "': path and matcher cannot be used together");
667 }
668 if (route.redirectTo === void 0 && !route.component && !route.children && !route.loadChildren) {
669 throw new Error("Invalid configuration of route '" + fullPath + "'. One of the following must be provided: component, redirectTo, children or loadChildren");
670 }
671 if (route.path === void 0 && route.matcher === void 0) {
672 throw new Error("Invalid configuration of route '" + fullPath + "': routes must have either a path or a matcher specified");
673 }
674 if (typeof route.path === 'string' && route.path.charAt(0) === '/') {
675 throw new Error("Invalid configuration of route '" + fullPath + "': path cannot start with a slash");
676 }
677 if (route.path === '' && route.redirectTo !== void 0 && route.pathMatch === void 0) {
678 var exp = "The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.";
679 throw new Error("Invalid configuration of route '{path: \"" + fullPath + "\", redirectTo: \"" + route.redirectTo + "\"}': please provide 'pathMatch'. " + exp);
680 }
681 if (route.pathMatch !== void 0 && route.pathMatch !== 'full' && route.pathMatch !== 'prefix') {
682 throw new Error("Invalid configuration of route '" + fullPath + "': pathMatch can only be set to 'prefix' or 'full'");
683 }
684 if (route.children) {
685 validateConfig(route.children, fullPath);
686 }
687 }
688 function getFullPath(parentPath, currentRoute) {
689 if (!currentRoute) {
690 return parentPath;
691 }
692 if (!parentPath && !currentRoute.path) {
693 return '';
694 }
695 else if (parentPath && !currentRoute.path) {
696 return parentPath + "/";
697 }
698 else if (!parentPath && currentRoute.path) {
699 return currentRoute.path;
700 }
701 else {
702 return parentPath + "/" + currentRoute.path;
703 }
704 }
705 /**
706 * Makes a copy of the config and adds any default required properties.
707 */
708 function standardizeConfig(r) {
709 var children = r.children && r.children.map(standardizeConfig);
710 var c = children ? __assign({}, r, { children: children }) : __assign({}, r);
711 if (!c.component && (children || c.loadChildren) && (c.outlet && c.outlet !== PRIMARY_OUTLET)) {
712 c.component = ɵEmptyOutletComponent;
713 }
714 return c;
715 }
716
717 /**
718 * @license
719 * Copyright Google Inc. All Rights Reserved.
720 *
721 * Use of this source code is governed by an MIT-style license that can be
722 * found in the LICENSE file at https://angular.io/license
723 */
724 function shallowEqualArrays(a, b) {
725 if (a.length !== b.length)
726 return false;
727 for (var i = 0; i < a.length; ++i) {
728 if (!shallowEqual(a[i], b[i]))
729 return false;
730 }
731 return true;
732 }
733 function shallowEqual(a, b) {
734 // Casting Object.keys return values to include `undefined` as there are some cases
735 // in IE 11 where this can happen. Cannot provide a test because the behavior only
736 // exists in certain circumstances in IE 11, therefore doing this cast ensures the
737 // logic is correct for when this edge case is hit.
738 var k1 = Object.keys(a);
739 var k2 = Object.keys(b);
740 if (!k1 || !k2 || k1.length != k2.length) {
741 return false;
742 }
743 var key;
744 for (var i = 0; i < k1.length; i++) {
745 key = k1[i];
746 if (a[key] !== b[key]) {
747 return false;
748 }
749 }
750 return true;
751 }
752 /**
753 * Flattens single-level nested arrays.
754 */
755 function flatten(arr) {
756 return Array.prototype.concat.apply([], arr);
757 }
758 /**
759 * Return the last element of an array.
760 */
761 function last(a) {
762 return a.length > 0 ? a[a.length - 1] : null;
763 }
764 function forEach(map, callback) {
765 for (var prop in map) {
766 if (map.hasOwnProperty(prop)) {
767 callback(map[prop], prop);
768 }
769 }
770 }
771 function waitForMap(obj, fn) {
772 if (Object.keys(obj).length === 0) {
773 return rxjs.of({});
774 }
775 var waitHead = [];
776 var waitTail = [];
777 var res = {};
778 forEach(obj, function (a, k) {
779 var mapped = fn(k, a).pipe(operators.map(function (r) { return res[k] = r; }));
780 if (k === PRIMARY_OUTLET) {
781 waitHead.push(mapped);
782 }
783 else {
784 waitTail.push(mapped);
785 }
786 });
787 // Closure compiler has problem with using spread operator here. So we use "Array.concat".
788 // Note that we also need to cast the new promise because TypeScript cannot infer the type
789 // when calling the "of" function through "Function.apply"
790 return rxjs.of.apply(null, waitHead.concat(waitTail))
791 .pipe(operators.concatAll(), operators.last(), operators.map(function () { return res; }));
792 }
793 function wrapIntoObservable(value) {
794 if (core.ɵisObservable(value)) {
795 return value;
796 }
797 if (core.ɵisPromise(value)) {
798 // Use `Promise.resolve()` to wrap promise-like instances.
799 // Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the
800 // change detection.
801 return rxjs.from(Promise.resolve(value));
802 }
803 return rxjs.of(value);
804 }
805
806 /**
807 * @license
808 * Copyright Google Inc. All Rights Reserved.
809 *
810 * Use of this source code is governed by an MIT-style license that can be
811 * found in the LICENSE file at https://angular.io/license
812 */
813 function createEmptyUrlTree() {
814 return new UrlTree(new UrlSegmentGroup([], {}), {}, null);
815 }
816 function containsTree(container, containee, exact) {
817 if (exact) {
818 return equalQueryParams(container.queryParams, containee.queryParams) &&
819 equalSegmentGroups(container.root, containee.root);
820 }
821 return containsQueryParams(container.queryParams, containee.queryParams) &&
822 containsSegmentGroup(container.root, containee.root);
823 }
824 function equalQueryParams(container, containee) {
825 // TODO: This does not handle array params correctly.
826 return shallowEqual(container, containee);
827 }
828 function equalSegmentGroups(container, containee) {
829 if (!equalPath(container.segments, containee.segments))
830 return false;
831 if (container.numberOfChildren !== containee.numberOfChildren)
832 return false;
833 for (var c in containee.children) {
834 if (!container.children[c])
835 return false;
836 if (!equalSegmentGroups(container.children[c], containee.children[c]))
837 return false;
838 }
839 return true;
840 }
841 function containsQueryParams(container, containee) {
842 // TODO: This does not handle array params correctly.
843 return Object.keys(containee).length <= Object.keys(container).length &&
844 Object.keys(containee).every(function (key) { return containee[key] === container[key]; });
845 }
846 function containsSegmentGroup(container, containee) {
847 return containsSegmentGroupHelper(container, containee, containee.segments);
848 }
849 function containsSegmentGroupHelper(container, containee, containeePaths) {
850 if (container.segments.length > containeePaths.length) {
851 var current = container.segments.slice(0, containeePaths.length);
852 if (!equalPath(current, containeePaths))
853 return false;
854 if (containee.hasChildren())
855 return false;
856 return true;
857 }
858 else if (container.segments.length === containeePaths.length) {
859 if (!equalPath(container.segments, containeePaths))
860 return false;
861 for (var c in containee.children) {
862 if (!container.children[c])
863 return false;
864 if (!containsSegmentGroup(container.children[c], containee.children[c]))
865 return false;
866 }
867 return true;
868 }
869 else {
870 var current = containeePaths.slice(0, container.segments.length);
871 var next = containeePaths.slice(container.segments.length);
872 if (!equalPath(container.segments, current))
873 return false;
874 if (!container.children[PRIMARY_OUTLET])
875 return false;
876 return containsSegmentGroupHelper(container.children[PRIMARY_OUTLET], containee, next);
877 }
878 }
879 /**
880 * @description
881 *
882 * Represents the parsed URL.
883 *
884 * Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a
885 * serialized tree.
886 * UrlTree is a data structure that provides a lot of affordances in dealing with URLs
887 *
888 * @usageNotes
889 * ### Example
890 *
891 * ```
892 * @Component({templateUrl:'template.html'})
893 * class MyComponent {
894 * constructor(router: Router) {
895 * const tree: UrlTree =
896 * router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment');
897 * const f = tree.fragment; // return 'fragment'
898 * const q = tree.queryParams; // returns {debug: 'true'}
899 * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
900 * const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33'
901 * g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor'
902 * g.children['support'].segments; // return 1 segment 'help'
903 * }
904 * }
905 * ```
906 *
907 * @publicApi
908 */
909 var UrlTree = /** @class */ (function () {
910 /** @internal */
911 function UrlTree(
912 /** The root segment group of the URL tree */
913 root,
914 /** The query params of the URL */
915 queryParams,
916 /** The fragment of the URL */
917 fragment) {
918 this.root = root;
919 this.queryParams = queryParams;
920 this.fragment = fragment;
921 }
922 Object.defineProperty(UrlTree.prototype, "queryParamMap", {
923 get: function () {
924 if (!this._queryParamMap) {
925 this._queryParamMap = convertToParamMap(this.queryParams);
926 }
927 return this._queryParamMap;
928 },
929 enumerable: true,
930 configurable: true
931 });
932 /** @docsNotRequired */
933 UrlTree.prototype.toString = function () { return DEFAULT_SERIALIZER.serialize(this); };
934 return UrlTree;
935 }());
936 /**
937 * @description
938 *
939 * Represents the parsed URL segment group.
940 *
941 * See `UrlTree` for more information.
942 *
943 * @publicApi
944 */
945 var UrlSegmentGroup = /** @class */ (function () {
946 function UrlSegmentGroup(
947 /** The URL segments of this group. See `UrlSegment` for more information */
948 segments,
949 /** The list of children of this group */
950 children) {
951 var _this = this;
952 this.segments = segments;
953 this.children = children;
954 /** The parent node in the url tree */
955 this.parent = null;
956 forEach(children, function (v, k) { return v.parent = _this; });
957 }
958 /** Whether the segment has child segments */
959 UrlSegmentGroup.prototype.hasChildren = function () { return this.numberOfChildren > 0; };
960 Object.defineProperty(UrlSegmentGroup.prototype, "numberOfChildren", {
961 /** Number of child segments */
962 get: function () { return Object.keys(this.children).length; },
963 enumerable: true,
964 configurable: true
965 });
966 /** @docsNotRequired */
967 UrlSegmentGroup.prototype.toString = function () { return serializePaths(this); };
968 return UrlSegmentGroup;
969 }());
970 /**
971 * @description
972 *
973 * Represents a single URL segment.
974 *
975 * A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix
976 * parameters associated with the segment.
977 *
978 * @usageNotes
979 * ### Example
980 *
981 * ```
982 * @Component({templateUrl:'template.html'})
983 * class MyComponent {
984 * constructor(router: Router) {
985 * const tree: UrlTree = router.parseUrl('/team;id=33');
986 * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
987 * const s: UrlSegment[] = g.segments;
988 * s[0].path; // returns 'team'
989 * s[0].parameters; // returns {id: 33}
990 * }
991 * }
992 * ```
993 *
994 * @publicApi
995 */
996 var UrlSegment = /** @class */ (function () {
997 function UrlSegment(
998 /** The path part of a URL segment */
999 path,
1000 /** The matrix parameters associated with a segment */
1001 parameters) {
1002 this.path = path;
1003 this.parameters = parameters;
1004 }
1005 Object.defineProperty(UrlSegment.prototype, "parameterMap", {
1006 get: function () {
1007 if (!this._parameterMap) {
1008 this._parameterMap = convertToParamMap(this.parameters);
1009 }
1010 return this._parameterMap;
1011 },
1012 enumerable: true,
1013 configurable: true
1014 });
1015 /** @docsNotRequired */
1016 UrlSegment.prototype.toString = function () { return serializePath(this); };
1017 return UrlSegment;
1018 }());
1019 function equalSegments(as, bs) {
1020 return equalPath(as, bs) && as.every(function (a, i) { return shallowEqual(a.parameters, bs[i].parameters); });
1021 }
1022 function equalPath(as, bs) {
1023 if (as.length !== bs.length)
1024 return false;
1025 return as.every(function (a, i) { return a.path === bs[i].path; });
1026 }
1027 function mapChildrenIntoArray(segment, fn) {
1028 var res = [];
1029 forEach(segment.children, function (child, childOutlet) {
1030 if (childOutlet === PRIMARY_OUTLET) {
1031 res = res.concat(fn(child, childOutlet));
1032 }
1033 });
1034 forEach(segment.children, function (child, childOutlet) {
1035 if (childOutlet !== PRIMARY_OUTLET) {
1036 res = res.concat(fn(child, childOutlet));
1037 }
1038 });
1039 return res;
1040 }
1041 /**
1042 * @description
1043 *
1044 * Serializes and deserializes a URL string into a URL tree.
1045 *
1046 * The url serialization strategy is customizable. You can
1047 * make all URLs case insensitive by providing a custom UrlSerializer.
1048 *
1049 * See `DefaultUrlSerializer` for an example of a URL serializer.
1050 *
1051 * @publicApi
1052 */
1053 var UrlSerializer = /** @class */ (function () {
1054 function UrlSerializer() {
1055 }
1056 return UrlSerializer;
1057 }());
1058 /**
1059 * @description
1060 *
1061 * A default implementation of the `UrlSerializer`.
1062 *
1063 * Example URLs:
1064 *
1065 * ```
1066 * /inbox/33(popup:compose)
1067 * /inbox/33;open=true/messages/44
1068 * ```
1069 *
1070 * DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the
1071 * colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to
1072 * specify route specific parameters.
1073 *
1074 * @publicApi
1075 */
1076 var DefaultUrlSerializer = /** @class */ (function () {
1077 function DefaultUrlSerializer() {
1078 }
1079 /** Parses a url into a `UrlTree` */
1080 DefaultUrlSerializer.prototype.parse = function (url) {
1081 var p = new UrlParser(url);
1082 return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment());
1083 };
1084 /** Converts a `UrlTree` into a url */
1085 DefaultUrlSerializer.prototype.serialize = function (tree) {
1086 var segment = "/" + serializeSegment(tree.root, true);
1087 var query = serializeQueryParams(tree.queryParams);
1088 var fragment = typeof tree.fragment === "string" ? "#" + encodeUriFragment(tree.fragment) : '';
1089 return "" + segment + query + fragment;
1090 };
1091 return DefaultUrlSerializer;
1092 }());
1093 var DEFAULT_SERIALIZER = new DefaultUrlSerializer();
1094 function serializePaths(segment) {
1095 return segment.segments.map(function (p) { return serializePath(p); }).join('/');
1096 }
1097 function serializeSegment(segment, root) {
1098 if (!segment.hasChildren()) {
1099 return serializePaths(segment);
1100 }
1101 if (root) {
1102 var primary = segment.children[PRIMARY_OUTLET] ?
1103 serializeSegment(segment.children[PRIMARY_OUTLET], false) :
1104 '';
1105 var children_1 = [];
1106 forEach(segment.children, function (v, k) {
1107 if (k !== PRIMARY_OUTLET) {
1108 children_1.push(k + ":" + serializeSegment(v, false));
1109 }
1110 });
1111 return children_1.length > 0 ? primary + "(" + children_1.join('//') + ")" : primary;
1112 }
1113 else {
1114 var children = mapChildrenIntoArray(segment, function (v, k) {
1115 if (k === PRIMARY_OUTLET) {
1116 return [serializeSegment(segment.children[PRIMARY_OUTLET], false)];
1117 }
1118 return [k + ":" + serializeSegment(v, false)];
1119 });
1120 return serializePaths(segment) + "/(" + children.join('//') + ")";
1121 }
1122 }
1123 /**
1124 * Encodes a URI string with the default encoding. This function will only ever be called from
1125 * `encodeUriQuery` or `encodeUriSegment` as it's the base set of encodings to be used. We need
1126 * a custom encoding because encodeURIComponent is too aggressive and encodes stuff that doesn't
1127 * have to be encoded per https://url.spec.whatwg.org.
1128 */
1129 function encodeUriString(s) {
1130 return encodeURIComponent(s)
1131 .replace(/%40/g, '@')
1132 .replace(/%3A/gi, ':')
1133 .replace(/%24/g, '$')
1134 .replace(/%2C/gi, ',');
1135 }
1136 /**
1137 * This function should be used to encode both keys and values in a query string key/value. In
1138 * the following URL, you need to call encodeUriQuery on "k" and "v":
1139 *
1140 * http://www.site.org/html;mk=mv?k=v#f
1141 */
1142 function encodeUriQuery(s) {
1143 return encodeUriString(s).replace(/%3B/gi, ';');
1144 }
1145 /**
1146 * This function should be used to encode a URL fragment. In the following URL, you need to call
1147 * encodeUriFragment on "f":
1148 *
1149 * http://www.site.org/html;mk=mv?k=v#f
1150 */
1151 function encodeUriFragment(s) {
1152 return encodeURI(s);
1153 }
1154 /**
1155 * This function should be run on any URI segment as well as the key and value in a key/value
1156 * pair for matrix params. In the following URL, you need to call encodeUriSegment on "html",
1157 * "mk", and "mv":
1158 *
1159 * http://www.site.org/html;mk=mv?k=v#f
1160 */
1161 function encodeUriSegment(s) {
1162 return encodeUriString(s).replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%26/gi, '&');
1163 }
1164 function decode(s) {
1165 return decodeURIComponent(s);
1166 }
1167 // Query keys/values should have the "+" replaced first, as "+" in a query string is " ".
1168 // decodeURIComponent function will not decode "+" as a space.
1169 function decodeQuery(s) {
1170 return decode(s.replace(/\+/g, '%20'));
1171 }
1172 function serializePath(path) {
1173 return "" + encodeUriSegment(path.path) + serializeMatrixParams(path.parameters);
1174 }
1175 function serializeMatrixParams(params) {
1176 return Object.keys(params)
1177 .map(function (key) { return ";" + encodeUriSegment(key) + "=" + encodeUriSegment(params[key]); })
1178 .join('');
1179 }
1180 function serializeQueryParams(params) {
1181 var strParams = Object.keys(params).map(function (name) {
1182 var value = params[name];
1183 return Array.isArray(value) ?
1184 value.map(function (v) { return encodeUriQuery(name) + "=" + encodeUriQuery(v); }).join('&') :
1185 encodeUriQuery(name) + "=" + encodeUriQuery(value);
1186 });
1187 return strParams.length ? "?" + strParams.join("&") : '';
1188 }
1189 var SEGMENT_RE = /^[^\/()?;=#]+/;
1190 function matchSegments(str) {
1191 var match = str.match(SEGMENT_RE);
1192 return match ? match[0] : '';
1193 }
1194 var QUERY_PARAM_RE = /^[^=?&#]+/;
1195 // Return the name of the query param at the start of the string or an empty string
1196 function matchQueryParams(str) {
1197 var match = str.match(QUERY_PARAM_RE);
1198 return match ? match[0] : '';
1199 }
1200 var QUERY_PARAM_VALUE_RE = /^[^?&#]+/;
1201 // Return the value of the query param at the start of the string or an empty string
1202 function matchUrlQueryParamValue(str) {
1203 var match = str.match(QUERY_PARAM_VALUE_RE);
1204 return match ? match[0] : '';
1205 }
1206 var UrlParser = /** @class */ (function () {
1207 function UrlParser(url) {
1208 this.url = url;
1209 this.remaining = url;
1210 }
1211 UrlParser.prototype.parseRootSegment = function () {
1212 this.consumeOptional('/');
1213 if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) {
1214 return new UrlSegmentGroup([], {});
1215 }
1216 // The root segment group never has segments
1217 return new UrlSegmentGroup([], this.parseChildren());
1218 };
1219 UrlParser.prototype.parseQueryParams = function () {
1220 var params = {};
1221 if (this.consumeOptional('?')) {
1222 do {
1223 this.parseQueryParam(params);
1224 } while (this.consumeOptional('&'));
1225 }
1226 return params;
1227 };
1228 UrlParser.prototype.parseFragment = function () {
1229 return this.consumeOptional('#') ? decodeURIComponent(this.remaining) : null;
1230 };
1231 UrlParser.prototype.parseChildren = function () {
1232 if (this.remaining === '') {
1233 return {};
1234 }
1235 this.consumeOptional('/');
1236 var segments = [];
1237 if (!this.peekStartsWith('(')) {
1238 segments.push(this.parseSegment());
1239 }
1240 while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) {
1241 this.capture('/');
1242 segments.push(this.parseSegment());
1243 }
1244 var children = {};
1245 if (this.peekStartsWith('/(')) {
1246 this.capture('/');
1247 children = this.parseParens(true);
1248 }
1249 var res = {};
1250 if (this.peekStartsWith('(')) {
1251 res = this.parseParens(false);
1252 }
1253 if (segments.length > 0 || Object.keys(children).length > 0) {
1254 res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children);
1255 }
1256 return res;
1257 };
1258 // parse a segment with its matrix parameters
1259 // ie `name;k1=v1;k2`
1260 UrlParser.prototype.parseSegment = function () {
1261 var path = matchSegments(this.remaining);
1262 if (path === '' && this.peekStartsWith(';')) {
1263 throw new Error("Empty path url segment cannot have parameters: '" + this.remaining + "'.");
1264 }
1265 this.capture(path);
1266 return new UrlSegment(decode(path), this.parseMatrixParams());
1267 };
1268 UrlParser.prototype.parseMatrixParams = function () {
1269 var params = {};
1270 while (this.consumeOptional(';')) {
1271 this.parseParam(params);
1272 }
1273 return params;
1274 };
1275 UrlParser.prototype.parseParam = function (params) {
1276 var key = matchSegments(this.remaining);
1277 if (!key) {
1278 return;
1279 }
1280 this.capture(key);
1281 var value = '';
1282 if (this.consumeOptional('=')) {
1283 var valueMatch = matchSegments(this.remaining);
1284 if (valueMatch) {
1285 value = valueMatch;
1286 this.capture(value);
1287 }
1288 }
1289 params[decode(key)] = decode(value);
1290 };
1291 // Parse a single query parameter `name[=value]`
1292 UrlParser.prototype.parseQueryParam = function (params) {
1293 var key = matchQueryParams(this.remaining);
1294 if (!key) {
1295 return;
1296 }
1297 this.capture(key);
1298 var value = '';
1299 if (this.consumeOptional('=')) {
1300 var valueMatch = matchUrlQueryParamValue(this.remaining);
1301 if (valueMatch) {
1302 value = valueMatch;
1303 this.capture(value);
1304 }
1305 }
1306 var decodedKey = decodeQuery(key);
1307 var decodedVal = decodeQuery(value);
1308 if (params.hasOwnProperty(decodedKey)) {
1309 // Append to existing values
1310 var currentVal = params[decodedKey];
1311 if (!Array.isArray(currentVal)) {
1312 currentVal = [currentVal];
1313 params[decodedKey] = currentVal;
1314 }
1315 currentVal.push(decodedVal);
1316 }
1317 else {
1318 // Create a new value
1319 params[decodedKey] = decodedVal;
1320 }
1321 };
1322 // parse `(a/b//outlet_name:c/d)`
1323 UrlParser.prototype.parseParens = function (allowPrimary) {
1324 var segments = {};
1325 this.capture('(');
1326 while (!this.consumeOptional(')') && this.remaining.length > 0) {
1327 var path = matchSegments(this.remaining);
1328 var next = this.remaining[path.length];
1329 // if is is not one of these characters, then the segment was unescaped
1330 // or the group was not closed
1331 if (next !== '/' && next !== ')' && next !== ';') {
1332 throw new Error("Cannot parse url '" + this.url + "'");
1333 }
1334 var outletName = undefined;
1335 if (path.indexOf(':') > -1) {
1336 outletName = path.substr(0, path.indexOf(':'));
1337 this.capture(outletName);
1338 this.capture(':');
1339 }
1340 else if (allowPrimary) {
1341 outletName = PRIMARY_OUTLET;
1342 }
1343 var children = this.parseChildren();
1344 segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] :
1345 new UrlSegmentGroup([], children);
1346 this.consumeOptional('//');
1347 }
1348 return segments;
1349 };
1350 UrlParser.prototype.peekStartsWith = function (str) { return this.remaining.startsWith(str); };
1351 // Consumes the prefix when it is present and returns whether it has been consumed
1352 UrlParser.prototype.consumeOptional = function (str) {
1353 if (this.peekStartsWith(str)) {
1354 this.remaining = this.remaining.substring(str.length);
1355 return true;
1356 }
1357 return false;
1358 };
1359 UrlParser.prototype.capture = function (str) {
1360 if (!this.consumeOptional(str)) {
1361 throw new Error("Expected \"" + str + "\".");
1362 }
1363 };
1364 return UrlParser;
1365 }());
1366
1367 /**
1368 * @license
1369 * Copyright Google Inc. All Rights Reserved.
1370 *
1371 * Use of this source code is governed by an MIT-style license that can be
1372 * found in the LICENSE file at https://angular.io/license
1373 */
1374 var Tree = /** @class */ (function () {
1375 function Tree(root) {
1376 this._root = root;
1377 }
1378 Object.defineProperty(Tree.prototype, "root", {
1379 get: function () { return this._root.value; },
1380 enumerable: true,
1381 configurable: true
1382 });
1383 /**
1384 * @internal
1385 */
1386 Tree.prototype.parent = function (t) {
1387 var p = this.pathFromRoot(t);
1388 return p.length > 1 ? p[p.length - 2] : null;
1389 };
1390 /**
1391 * @internal
1392 */
1393 Tree.prototype.children = function (t) {
1394 var n = findNode(t, this._root);
1395 return n ? n.children.map(function (t) { return t.value; }) : [];
1396 };
1397 /**
1398 * @internal
1399 */
1400 Tree.prototype.firstChild = function (t) {
1401 var n = findNode(t, this._root);
1402 return n && n.children.length > 0 ? n.children[0].value : null;
1403 };
1404 /**
1405 * @internal
1406 */
1407 Tree.prototype.siblings = function (t) {
1408 var p = findPath(t, this._root);
1409 if (p.length < 2)
1410 return [];
1411 var c = p[p.length - 2].children.map(function (c) { return c.value; });
1412 return c.filter(function (cc) { return cc !== t; });
1413 };
1414 /**
1415 * @internal
1416 */
1417 Tree.prototype.pathFromRoot = function (t) { return findPath(t, this._root).map(function (s) { return s.value; }); };
1418 return Tree;
1419 }());
1420 // DFS for the node matching the value
1421 function findNode(value, node) {
1422 var e_1, _a;
1423 if (value === node.value)
1424 return node;
1425 try {
1426 for (var _b = __values(node.children), _c = _b.next(); !_c.done; _c = _b.next()) {
1427 var child = _c.value;
1428 var node_1 = findNode(value, child);
1429 if (node_1)
1430 return node_1;
1431 }
1432 }
1433 catch (e_1_1) { e_1 = { error: e_1_1 }; }
1434 finally {
1435 try {
1436 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1437 }
1438 finally { if (e_1) throw e_1.error; }
1439 }
1440 return null;
1441 }
1442 // Return the path to the node with the given value using DFS
1443 function findPath(value, node) {
1444 var e_2, _a;
1445 if (value === node.value)
1446 return [node];
1447 try {
1448 for (var _b = __values(node.children), _c = _b.next(); !_c.done; _c = _b.next()) {
1449 var child = _c.value;
1450 var path = findPath(value, child);
1451 if (path.length) {
1452 path.unshift(node);
1453 return path;
1454 }
1455 }
1456 }
1457 catch (e_2_1) { e_2 = { error: e_2_1 }; }
1458 finally {
1459 try {
1460 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1461 }
1462 finally { if (e_2) throw e_2.error; }
1463 }
1464 return [];
1465 }
1466 var TreeNode = /** @class */ (function () {
1467 function TreeNode(value, children) {
1468 this.value = value;
1469 this.children = children;
1470 }
1471 TreeNode.prototype.toString = function () { return "TreeNode(" + this.value + ")"; };
1472 return TreeNode;
1473 }());
1474 // Return the list of T indexed by outlet name
1475 function nodeChildrenAsMap(node) {
1476 var map = {};
1477 if (node) {
1478 node.children.forEach(function (child) { return map[child.value.outlet] = child; });
1479 }
1480 return map;
1481 }
1482
1483 /**
1484 * @license
1485 * Copyright Google Inc. All Rights Reserved.
1486 *
1487 * Use of this source code is governed by an MIT-style license that can be
1488 * found in the LICENSE file at https://angular.io/license
1489 */
1490 /**
1491 * Represents the state of the router as a tree of activated routes.
1492 *
1493 * @usageNotes
1494 *
1495 * Every node in the route tree is an `ActivatedRoute` instance
1496 * that knows about the "consumed" URL segments, the extracted parameters,
1497 * and the resolved data.
1498 * Use the `ActivatedRoute` properties to traverse the tree from any node.
1499 *
1500 * ### Example
1501 *
1502 * ```
1503 * @Component({templateUrl:'template.html'})
1504 * class MyComponent {
1505 * constructor(router: Router) {
1506 * const state: RouterState = router.routerState;
1507 * const root: ActivatedRoute = state.root;
1508 * const child = root.firstChild;
1509 * const id: Observable<string> = child.params.map(p => p.id);
1510 * //...
1511 * }
1512 * }
1513 * ```
1514 *
1515 * @see `ActivatedRoute`
1516 *
1517 * @publicApi
1518 */
1519 var RouterState = /** @class */ (function (_super) {
1520 __extends(RouterState, _super);
1521 /** @internal */
1522 function RouterState(root,
1523 /** The current snapshot of the router state */
1524 snapshot) {
1525 var _this = _super.call(this, root) || this;
1526 _this.snapshot = snapshot;
1527 setRouterState(_this, root);
1528 return _this;
1529 }
1530 RouterState.prototype.toString = function () { return this.snapshot.toString(); };
1531 return RouterState;
1532 }(Tree));
1533 function createEmptyState(urlTree, rootComponent) {
1534 var snapshot = createEmptyStateSnapshot(urlTree, rootComponent);
1535 var emptyUrl = new rxjs.BehaviorSubject([new UrlSegment('', {})]);
1536 var emptyParams = new rxjs.BehaviorSubject({});
1537 var emptyData = new rxjs.BehaviorSubject({});
1538 var emptyQueryParams = new rxjs.BehaviorSubject({});
1539 var fragment = new rxjs.BehaviorSubject('');
1540 var activated = new ActivatedRoute(emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root);
1541 activated.snapshot = snapshot.root;
1542 return new RouterState(new TreeNode(activated, []), snapshot);
1543 }
1544 function createEmptyStateSnapshot(urlTree, rootComponent) {
1545 var emptyParams = {};
1546 var emptyData = {};
1547 var emptyQueryParams = {};
1548 var fragment = '';
1549 var activated = new ActivatedRouteSnapshot([], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, urlTree.root, -1, {});
1550 return new RouterStateSnapshot('', new TreeNode(activated, []));
1551 }
1552 /**
1553 * Provides access to information about a route associated with a component
1554 * that is loaded in an outlet.
1555 * Use to traverse the `RouterState` tree and extract information from nodes.
1556 *
1557 * {@example router/activated-route/module.ts region="activated-route"
1558 * header="activated-route.component.ts"}
1559 *
1560 * @publicApi
1561 */
1562 var ActivatedRoute = /** @class */ (function () {
1563 /** @internal */
1564 function ActivatedRoute(
1565 /** An observable of the URL segments matched by this route. */
1566 url,
1567 /** An observable of the matrix parameters scoped to this route. */
1568 params,
1569 /** An observable of the query parameters shared by all the routes. */
1570 queryParams,
1571 /** An observable of the URL fragment shared by all the routes. */
1572 fragment,
1573 /** An observable of the static and resolved data of this route. */
1574 data,
1575 /** The outlet name of the route, a constant. */
1576 outlet,
1577 /** The component of the route, a constant. */
1578 // TODO(vsavkin): remove |string
1579 component, futureSnapshot) {
1580 this.url = url;
1581 this.params = params;
1582 this.queryParams = queryParams;
1583 this.fragment = fragment;
1584 this.data = data;
1585 this.outlet = outlet;
1586 this.component = component;
1587 this._futureSnapshot = futureSnapshot;
1588 }
1589 Object.defineProperty(ActivatedRoute.prototype, "routeConfig", {
1590 /** The configuration used to match this route. */
1591 get: function () { return this._futureSnapshot.routeConfig; },
1592 enumerable: true,
1593 configurable: true
1594 });
1595 Object.defineProperty(ActivatedRoute.prototype, "root", {
1596 /** The root of the router state. */
1597 get: function () { return this._routerState.root; },
1598 enumerable: true,
1599 configurable: true
1600 });
1601 Object.defineProperty(ActivatedRoute.prototype, "parent", {
1602 /** The parent of this route in the router state tree. */
1603 get: function () { return this._routerState.parent(this); },
1604 enumerable: true,
1605 configurable: true
1606 });
1607 Object.defineProperty(ActivatedRoute.prototype, "firstChild", {
1608 /** The first child of this route in the router state tree. */
1609 get: function () { return this._routerState.firstChild(this); },
1610 enumerable: true,
1611 configurable: true
1612 });
1613 Object.defineProperty(ActivatedRoute.prototype, "children", {
1614 /** The children of this route in the router state tree. */
1615 get: function () { return this._routerState.children(this); },
1616 enumerable: true,
1617 configurable: true
1618 });
1619 Object.defineProperty(ActivatedRoute.prototype, "pathFromRoot", {
1620 /** The path from the root of the router state tree to this route. */
1621 get: function () { return this._routerState.pathFromRoot(this); },
1622 enumerable: true,
1623 configurable: true
1624 });
1625 Object.defineProperty(ActivatedRoute.prototype, "paramMap", {
1626 /** An Observable that contains a map of the required and optional parameters
1627 * specific to the route.
1628 * The map supports retrieving single and multiple values from the same parameter. */
1629 get: function () {
1630 if (!this._paramMap) {
1631 this._paramMap = this.params.pipe(operators.map(function (p) { return convertToParamMap(p); }));
1632 }
1633 return this._paramMap;
1634 },
1635 enumerable: true,
1636 configurable: true
1637 });
1638 Object.defineProperty(ActivatedRoute.prototype, "queryParamMap", {
1639 /**
1640 * An Observable that contains a map of the query parameters available to all routes.
1641 * The map supports retrieving single and multiple values from the query parameter.
1642 */
1643 get: function () {
1644 if (!this._queryParamMap) {
1645 this._queryParamMap =
1646 this.queryParams.pipe(operators.map(function (p) { return convertToParamMap(p); }));
1647 }
1648 return this._queryParamMap;
1649 },
1650 enumerable: true,
1651 configurable: true
1652 });
1653 ActivatedRoute.prototype.toString = function () {
1654 return this.snapshot ? this.snapshot.toString() : "Future(" + this._futureSnapshot + ")";
1655 };
1656 return ActivatedRoute;
1657 }());
1658 /**
1659 * Returns the inherited params, data, and resolve for a given route.
1660 * By default, this only inherits values up to the nearest path-less or component-less route.
1661 * @internal
1662 */
1663 function inheritedParamsDataResolve(route, paramsInheritanceStrategy) {
1664 if (paramsInheritanceStrategy === void 0) { paramsInheritanceStrategy = 'emptyOnly'; }
1665 var pathFromRoot = route.pathFromRoot;
1666 var inheritingStartingFrom = 0;
1667 if (paramsInheritanceStrategy !== 'always') {
1668 inheritingStartingFrom = pathFromRoot.length - 1;
1669 while (inheritingStartingFrom >= 1) {
1670 var current = pathFromRoot[inheritingStartingFrom];
1671 var parent_1 = pathFromRoot[inheritingStartingFrom - 1];
1672 // current route is an empty path => inherits its parent's params and data
1673 if (current.routeConfig && current.routeConfig.path === '') {
1674 inheritingStartingFrom--;
1675 // parent is componentless => current route should inherit its params and data
1676 }
1677 else if (!parent_1.component) {
1678 inheritingStartingFrom--;
1679 }
1680 else {
1681 break;
1682 }
1683 }
1684 }
1685 return flattenInherited(pathFromRoot.slice(inheritingStartingFrom));
1686 }
1687 /** @internal */
1688 function flattenInherited(pathFromRoot) {
1689 return pathFromRoot.reduce(function (res, curr) {
1690 var params = __assign({}, res.params, curr.params);
1691 var data = __assign({}, res.data, curr.data);
1692 var resolve = __assign({}, res.resolve, curr._resolvedData);
1693 return { params: params, data: data, resolve: resolve };
1694 }, { params: {}, data: {}, resolve: {} });
1695 }
1696 /**
1697 * @description
1698 *
1699 * Contains the information about a route associated with a component loaded in an
1700 * outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to
1701 * traverse the router state tree.
1702 *
1703 * ```
1704 * @Component({templateUrl:'./my-component.html'})
1705 * class MyComponent {
1706 * constructor(route: ActivatedRoute) {
1707 * const id: string = route.snapshot.params.id;
1708 * const url: string = route.snapshot.url.join('');
1709 * const user = route.snapshot.data.user;
1710 * }
1711 * }
1712 * ```
1713 *
1714 * @publicApi
1715 */
1716 var ActivatedRouteSnapshot = /** @class */ (function () {
1717 /** @internal */
1718 function ActivatedRouteSnapshot(
1719 /** The URL segments matched by this route */
1720 url,
1721 /** The matrix parameters scoped to this route */
1722 params,
1723 /** The query parameters shared by all the routes */
1724 queryParams,
1725 /** The URL fragment shared by all the routes */
1726 fragment,
1727 /** The static and resolved data of this route */
1728 data,
1729 /** The outlet name of the route */
1730 outlet,
1731 /** The component of the route */
1732 component, routeConfig, urlSegment, lastPathIndex, resolve) {
1733 this.url = url;
1734 this.params = params;
1735 this.queryParams = queryParams;
1736 this.fragment = fragment;
1737 this.data = data;
1738 this.outlet = outlet;
1739 this.component = component;
1740 this.routeConfig = routeConfig;
1741 this._urlSegment = urlSegment;
1742 this._lastPathIndex = lastPathIndex;
1743 this._resolve = resolve;
1744 }
1745 Object.defineProperty(ActivatedRouteSnapshot.prototype, "root", {
1746 /** The root of the router state */
1747 get: function () { return this._routerState.root; },
1748 enumerable: true,
1749 configurable: true
1750 });
1751 Object.defineProperty(ActivatedRouteSnapshot.prototype, "parent", {
1752 /** The parent of this route in the router state tree */
1753 get: function () { return this._routerState.parent(this); },
1754 enumerable: true,
1755 configurable: true
1756 });
1757 Object.defineProperty(ActivatedRouteSnapshot.prototype, "firstChild", {
1758 /** The first child of this route in the router state tree */
1759 get: function () { return this._routerState.firstChild(this); },
1760 enumerable: true,
1761 configurable: true
1762 });
1763 Object.defineProperty(ActivatedRouteSnapshot.prototype, "children", {
1764 /** The children of this route in the router state tree */
1765 get: function () { return this._routerState.children(this); },
1766 enumerable: true,
1767 configurable: true
1768 });
1769 Object.defineProperty(ActivatedRouteSnapshot.prototype, "pathFromRoot", {
1770 /** The path from the root of the router state tree to this route */
1771 get: function () { return this._routerState.pathFromRoot(this); },
1772 enumerable: true,
1773 configurable: true
1774 });
1775 Object.defineProperty(ActivatedRouteSnapshot.prototype, "paramMap", {
1776 get: function () {
1777 if (!this._paramMap) {
1778 this._paramMap = convertToParamMap(this.params);
1779 }
1780 return this._paramMap;
1781 },
1782 enumerable: true,
1783 configurable: true
1784 });
1785 Object.defineProperty(ActivatedRouteSnapshot.prototype, "queryParamMap", {
1786 get: function () {
1787 if (!this._queryParamMap) {
1788 this._queryParamMap = convertToParamMap(this.queryParams);
1789 }
1790 return this._queryParamMap;
1791 },
1792 enumerable: true,
1793 configurable: true
1794 });
1795 ActivatedRouteSnapshot.prototype.toString = function () {
1796 var url = this.url.map(function (segment) { return segment.toString(); }).join('/');
1797 var matched = this.routeConfig ? this.routeConfig.path : '';
1798 return "Route(url:'" + url + "', path:'" + matched + "')";
1799 };
1800 return ActivatedRouteSnapshot;
1801 }());
1802 /**
1803 * @description
1804 *
1805 * Represents the state of the router at a moment in time.
1806 *
1807 * This is a tree of activated route snapshots. Every node in this tree knows about
1808 * the "consumed" URL segments, the extracted parameters, and the resolved data.
1809 *
1810 * @usageNotes
1811 * ### Example
1812 *
1813 * ```
1814 * @Component({templateUrl:'template.html'})
1815 * class MyComponent {
1816 * constructor(router: Router) {
1817 * const state: RouterState = router.routerState;
1818 * const snapshot: RouterStateSnapshot = state.snapshot;
1819 * const root: ActivatedRouteSnapshot = snapshot.root;
1820 * const child = root.firstChild;
1821 * const id: Observable<string> = child.params.map(p => p.id);
1822 * //...
1823 * }
1824 * }
1825 * ```
1826 *
1827 * @publicApi
1828 */
1829 var RouterStateSnapshot = /** @class */ (function (_super) {
1830 __extends(RouterStateSnapshot, _super);
1831 /** @internal */
1832 function RouterStateSnapshot(
1833 /** The url from which this snapshot was created */
1834 url, root) {
1835 var _this = _super.call(this, root) || this;
1836 _this.url = url;
1837 setRouterState(_this, root);
1838 return _this;
1839 }
1840 RouterStateSnapshot.prototype.toString = function () { return serializeNode(this._root); };
1841 return RouterStateSnapshot;
1842 }(Tree));
1843 function setRouterState(state, node) {
1844 node.value._routerState = state;
1845 node.children.forEach(function (c) { return setRouterState(state, c); });
1846 }
1847 function serializeNode(node) {
1848 var c = node.children.length > 0 ? " { " + node.children.map(serializeNode).join(', ') + " } " : '';
1849 return "" + node.value + c;
1850 }
1851 /**
1852 * The expectation is that the activate route is created with the right set of parameters.
1853 * So we push new values into the observables only when they are not the initial values.
1854 * And we detect that by checking if the snapshot field is set.
1855 */
1856 function advanceActivatedRoute(route) {
1857 if (route.snapshot) {
1858 var currentSnapshot = route.snapshot;
1859 var nextSnapshot = route._futureSnapshot;
1860 route.snapshot = nextSnapshot;
1861 if (!shallowEqual(currentSnapshot.queryParams, nextSnapshot.queryParams)) {
1862 route.queryParams.next(nextSnapshot.queryParams);
1863 }
1864 if (currentSnapshot.fragment !== nextSnapshot.fragment) {
1865 route.fragment.next(nextSnapshot.fragment);
1866 }
1867 if (!shallowEqual(currentSnapshot.params, nextSnapshot.params)) {
1868 route.params.next(nextSnapshot.params);
1869 }
1870 if (!shallowEqualArrays(currentSnapshot.url, nextSnapshot.url)) {
1871 route.url.next(nextSnapshot.url);
1872 }
1873 if (!shallowEqual(currentSnapshot.data, nextSnapshot.data)) {
1874 route.data.next(nextSnapshot.data);
1875 }
1876 }
1877 else {
1878 route.snapshot = route._futureSnapshot;
1879 // this is for resolved data
1880 route.data.next(route._futureSnapshot.data);
1881 }
1882 }
1883 function equalParamsAndUrlSegments(a, b) {
1884 var equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url);
1885 var parentsMismatch = !a.parent !== !b.parent;
1886 return equalUrlParams && !parentsMismatch &&
1887 (!a.parent || equalParamsAndUrlSegments(a.parent, b.parent));
1888 }
1889
1890 /**
1891 * @license
1892 * Copyright Google Inc. All Rights Reserved.
1893 *
1894 * Use of this source code is governed by an MIT-style license that can be
1895 * found in the LICENSE file at https://angular.io/license
1896 */
1897 function createRouterState(routeReuseStrategy, curr, prevState) {
1898 var root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined);
1899 return new RouterState(root, curr);
1900 }
1901 function createNode(routeReuseStrategy, curr, prevState) {
1902 // reuse an activated route that is currently displayed on the screen
1903 if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) {
1904 var value = prevState.value;
1905 value._futureSnapshot = curr.value;
1906 var children = createOrReuseChildren(routeReuseStrategy, curr, prevState);
1907 return new TreeNode(value, children);
1908 // retrieve an activated route that is used to be displayed, but is not currently displayed
1909 }
1910 else {
1911 var detachedRouteHandle = routeReuseStrategy.retrieve(curr.value);
1912 if (detachedRouteHandle) {
1913 var tree = detachedRouteHandle.route;
1914 setFutureSnapshotsOfActivatedRoutes(curr, tree);
1915 return tree;
1916 }
1917 else {
1918 var value = createActivatedRoute(curr.value);
1919 var children = curr.children.map(function (c) { return createNode(routeReuseStrategy, c); });
1920 return new TreeNode(value, children);
1921 }
1922 }
1923 }
1924 function setFutureSnapshotsOfActivatedRoutes(curr, result) {
1925 if (curr.value.routeConfig !== result.value.routeConfig) {
1926 throw new Error('Cannot reattach ActivatedRouteSnapshot created from a different route');
1927 }
1928 if (curr.children.length !== result.children.length) {
1929 throw new Error('Cannot reattach ActivatedRouteSnapshot with a different number of children');
1930 }
1931 result.value._futureSnapshot = curr.value;
1932 for (var i = 0; i < curr.children.length; ++i) {
1933 setFutureSnapshotsOfActivatedRoutes(curr.children[i], result.children[i]);
1934 }
1935 }
1936 function createOrReuseChildren(routeReuseStrategy, curr, prevState) {
1937 return curr.children.map(function (child) {
1938 var e_1, _a;
1939 try {
1940 for (var _b = __values(prevState.children), _c = _b.next(); !_c.done; _c = _b.next()) {
1941 var p = _c.value;
1942 if (routeReuseStrategy.shouldReuseRoute(p.value.snapshot, child.value)) {
1943 return createNode(routeReuseStrategy, child, p);
1944 }
1945 }
1946 }
1947 catch (e_1_1) { e_1 = { error: e_1_1 }; }
1948 finally {
1949 try {
1950 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1951 }
1952 finally { if (e_1) throw e_1.error; }
1953 }
1954 return createNode(routeReuseStrategy, child);
1955 });
1956 }
1957 function createActivatedRoute(c) {
1958 return new ActivatedRoute(new rxjs.BehaviorSubject(c.url), new rxjs.BehaviorSubject(c.params), new rxjs.BehaviorSubject(c.queryParams), new rxjs.BehaviorSubject(c.fragment), new rxjs.BehaviorSubject(c.data), c.outlet, c.component, c);
1959 }
1960
1961 /**
1962 * @license
1963 * Copyright Google Inc. All Rights Reserved.
1964 *
1965 * Use of this source code is governed by an MIT-style license that can be
1966 * found in the LICENSE file at https://angular.io/license
1967 */
1968 function createUrlTree(route, urlTree, commands, queryParams, fragment) {
1969 if (commands.length === 0) {
1970 return tree(urlTree.root, urlTree.root, urlTree, queryParams, fragment);
1971 }
1972 var nav = computeNavigation(commands);
1973 if (nav.toRoot()) {
1974 return tree(urlTree.root, new UrlSegmentGroup([], {}), urlTree, queryParams, fragment);
1975 }
1976 var startingPosition = findStartingPosition(nav, urlTree, route);
1977 var segmentGroup = startingPosition.processChildren ?
1978 updateSegmentGroupChildren(startingPosition.segmentGroup, startingPosition.index, nav.commands) :
1979 updateSegmentGroup(startingPosition.segmentGroup, startingPosition.index, nav.commands);
1980 return tree(startingPosition.segmentGroup, segmentGroup, urlTree, queryParams, fragment);
1981 }
1982 function isMatrixParams(command) {
1983 return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath;
1984 }
1985 function tree(oldSegmentGroup, newSegmentGroup, urlTree, queryParams, fragment) {
1986 var qp = {};
1987 if (queryParams) {
1988 forEach(queryParams, function (value, name) {
1989 qp[name] = Array.isArray(value) ? value.map(function (v) { return "" + v; }) : "" + value;
1990 });
1991 }
1992 if (urlTree.root === oldSegmentGroup) {
1993 return new UrlTree(newSegmentGroup, qp, fragment);
1994 }
1995 return new UrlTree(replaceSegment(urlTree.root, oldSegmentGroup, newSegmentGroup), qp, fragment);
1996 }
1997 function replaceSegment(current, oldSegment, newSegment) {
1998 var children = {};
1999 forEach(current.children, function (c, outletName) {
2000 if (c === oldSegment) {
2001 children[outletName] = newSegment;
2002 }
2003 else {
2004 children[outletName] = replaceSegment(c, oldSegment, newSegment);
2005 }
2006 });
2007 return new UrlSegmentGroup(current.segments, children);
2008 }
2009 var Navigation = /** @class */ (function () {
2010 function Navigation(isAbsolute, numberOfDoubleDots, commands) {
2011 this.isAbsolute = isAbsolute;
2012 this.numberOfDoubleDots = numberOfDoubleDots;
2013 this.commands = commands;
2014 if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) {
2015 throw new Error('Root segment cannot have matrix parameters');
2016 }
2017 var cmdWithOutlet = commands.find(function (c) { return typeof c === 'object' && c != null && c.outlets; });
2018 if (cmdWithOutlet && cmdWithOutlet !== last(commands)) {
2019 throw new Error('{outlets:{}} has to be the last command');
2020 }
2021 }
2022 Navigation.prototype.toRoot = function () {
2023 return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/';
2024 };
2025 return Navigation;
2026 }());
2027 /** Transforms commands to a normalized `Navigation` */
2028 function computeNavigation(commands) {
2029 if ((typeof commands[0] === 'string') && commands.length === 1 && commands[0] === '/') {
2030 return new Navigation(true, 0, commands);
2031 }
2032 var numberOfDoubleDots = 0;
2033 var isAbsolute = false;
2034 var res = commands.reduce(function (res, cmd, cmdIdx) {
2035 if (typeof cmd === 'object' && cmd != null) {
2036 if (cmd.outlets) {
2037 var outlets_1 = {};
2038 forEach(cmd.outlets, function (commands, name) {
2039 outlets_1[name] = typeof commands === 'string' ? commands.split('/') : commands;
2040 });
2041 return __spread(res, [{ outlets: outlets_1 }]);
2042 }
2043 if (cmd.segmentPath) {
2044 return __spread(res, [cmd.segmentPath]);
2045 }
2046 }
2047 if (!(typeof cmd === 'string')) {
2048 return __spread(res, [cmd]);
2049 }
2050 if (cmdIdx === 0) {
2051 cmd.split('/').forEach(function (urlPart, partIndex) {
2052 if (partIndex == 0 && urlPart === '.') ;
2053 else if (partIndex == 0 && urlPart === '') { // '/a'
2054 isAbsolute = true;
2055 }
2056 else if (urlPart === '..') { // '../a'
2057 numberOfDoubleDots++;
2058 }
2059 else if (urlPart != '') {
2060 res.push(urlPart);
2061 }
2062 });
2063 return res;
2064 }
2065 return __spread(res, [cmd]);
2066 }, []);
2067 return new Navigation(isAbsolute, numberOfDoubleDots, res);
2068 }
2069 var Position = /** @class */ (function () {
2070 function Position(segmentGroup, processChildren, index) {
2071 this.segmentGroup = segmentGroup;
2072 this.processChildren = processChildren;
2073 this.index = index;
2074 }
2075 return Position;
2076 }());
2077 function findStartingPosition(nav, tree, route) {
2078 if (nav.isAbsolute) {
2079 return new Position(tree.root, true, 0);
2080 }
2081 if (route.snapshot._lastPathIndex === -1) {
2082 return new Position(route.snapshot._urlSegment, true, 0);
2083 }
2084 var modifier = isMatrixParams(nav.commands[0]) ? 0 : 1;
2085 var index = route.snapshot._lastPathIndex + modifier;
2086 return createPositionApplyingDoubleDots(route.snapshot._urlSegment, index, nav.numberOfDoubleDots);
2087 }
2088 function createPositionApplyingDoubleDots(group, index, numberOfDoubleDots) {
2089 var g = group;
2090 var ci = index;
2091 var dd = numberOfDoubleDots;
2092 while (dd > ci) {
2093 dd -= ci;
2094 g = g.parent;
2095 if (!g) {
2096 throw new Error('Invalid number of \'../\'');
2097 }
2098 ci = g.segments.length;
2099 }
2100 return new Position(g, false, ci - dd);
2101 }
2102 function getPath(command) {
2103 if (typeof command === 'object' && command != null && command.outlets) {
2104 return command.outlets[PRIMARY_OUTLET];
2105 }
2106 return "" + command;
2107 }
2108 function getOutlets(commands) {
2109 var _a, _b;
2110 if (!(typeof commands[0] === 'object'))
2111 return _a = {}, _a[PRIMARY_OUTLET] = commands, _a;
2112 if (commands[0].outlets === undefined)
2113 return _b = {}, _b[PRIMARY_OUTLET] = commands, _b;
2114 return commands[0].outlets;
2115 }
2116 function updateSegmentGroup(segmentGroup, startIndex, commands) {
2117 if (!segmentGroup) {
2118 segmentGroup = new UrlSegmentGroup([], {});
2119 }
2120 if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
2121 return updateSegmentGroupChildren(segmentGroup, startIndex, commands);
2122 }
2123 var m = prefixedWith(segmentGroup, startIndex, commands);
2124 var slicedCommands = commands.slice(m.commandIndex);
2125 if (m.match && m.pathIndex < segmentGroup.segments.length) {
2126 var g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {});
2127 g.children[PRIMARY_OUTLET] =
2128 new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children);
2129 return updateSegmentGroupChildren(g, 0, slicedCommands);
2130 }
2131 else if (m.match && slicedCommands.length === 0) {
2132 return new UrlSegmentGroup(segmentGroup.segments, {});
2133 }
2134 else if (m.match && !segmentGroup.hasChildren()) {
2135 return createNewSegmentGroup(segmentGroup, startIndex, commands);
2136 }
2137 else if (m.match) {
2138 return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands);
2139 }
2140 else {
2141 return createNewSegmentGroup(segmentGroup, startIndex, commands);
2142 }
2143 }
2144 function updateSegmentGroupChildren(segmentGroup, startIndex, commands) {
2145 if (commands.length === 0) {
2146 return new UrlSegmentGroup(segmentGroup.segments, {});
2147 }
2148 else {
2149 var outlets_2 = getOutlets(commands);
2150 var children_1 = {};
2151 forEach(outlets_2, function (commands, outlet) {
2152 if (commands !== null) {
2153 children_1[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands);
2154 }
2155 });
2156 forEach(segmentGroup.children, function (child, childOutlet) {
2157 if (outlets_2[childOutlet] === undefined) {
2158 children_1[childOutlet] = child;
2159 }
2160 });
2161 return new UrlSegmentGroup(segmentGroup.segments, children_1);
2162 }
2163 }
2164 function prefixedWith(segmentGroup, startIndex, commands) {
2165 var currentCommandIndex = 0;
2166 var currentPathIndex = startIndex;
2167 var noMatch = { match: false, pathIndex: 0, commandIndex: 0 };
2168 while (currentPathIndex < segmentGroup.segments.length) {
2169 if (currentCommandIndex >= commands.length)
2170 return noMatch;
2171 var path = segmentGroup.segments[currentPathIndex];
2172 var curr = getPath(commands[currentCommandIndex]);
2173 var next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null;
2174 if (currentPathIndex > 0 && curr === undefined)
2175 break;
2176 if (curr && next && (typeof next === 'object') && next.outlets === undefined) {
2177 if (!compare(curr, next, path))
2178 return noMatch;
2179 currentCommandIndex += 2;
2180 }
2181 else {
2182 if (!compare(curr, {}, path))
2183 return noMatch;
2184 currentCommandIndex++;
2185 }
2186 currentPathIndex++;
2187 }
2188 return { match: true, pathIndex: currentPathIndex, commandIndex: currentCommandIndex };
2189 }
2190 function createNewSegmentGroup(segmentGroup, startIndex, commands) {
2191 var paths = segmentGroup.segments.slice(0, startIndex);
2192 var i = 0;
2193 while (i < commands.length) {
2194 if (typeof commands[i] === 'object' && commands[i].outlets !== undefined) {
2195 var children = createNewSegmentChildren(commands[i].outlets);
2196 return new UrlSegmentGroup(paths, children);
2197 }
2198 // if we start with an object literal, we need to reuse the path part from the segment
2199 if (i === 0 && isMatrixParams(commands[0])) {
2200 var p = segmentGroup.segments[startIndex];
2201 paths.push(new UrlSegment(p.path, commands[0]));
2202 i++;
2203 continue;
2204 }
2205 var curr = getPath(commands[i]);
2206 var next = (i < commands.length - 1) ? commands[i + 1] : null;
2207 if (curr && next && isMatrixParams(next)) {
2208 paths.push(new UrlSegment(curr, stringify(next)));
2209 i += 2;
2210 }
2211 else {
2212 paths.push(new UrlSegment(curr, {}));
2213 i++;
2214 }
2215 }
2216 return new UrlSegmentGroup(paths, {});
2217 }
2218 function createNewSegmentChildren(outlets) {
2219 var children = {};
2220 forEach(outlets, function (commands, outlet) {
2221 if (commands !== null) {
2222 children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands);
2223 }
2224 });
2225 return children;
2226 }
2227 function stringify(params) {
2228 var res = {};
2229 forEach(params, function (v, k) { return res[k] = "" + v; });
2230 return res;
2231 }
2232 function compare(path, params, segment) {
2233 return path == segment.path && shallowEqual(params, segment.parameters);
2234 }
2235
2236 /**
2237 * @license
2238 * Copyright Google Inc. All Rights Reserved.
2239 *
2240 * Use of this source code is governed by an MIT-style license that can be
2241 * found in the LICENSE file at https://angular.io/license
2242 */
2243 var activateRoutes = function (rootContexts, routeReuseStrategy, forwardEvent) {
2244 return operators.map(function (t) {
2245 new ActivateRoutes(routeReuseStrategy, t.targetRouterState, t.currentRouterState, forwardEvent)
2246 .activate(rootContexts);
2247 return t;
2248 });
2249 };
2250 var ActivateRoutes = /** @class */ (function () {
2251 function ActivateRoutes(routeReuseStrategy, futureState, currState, forwardEvent) {
2252 this.routeReuseStrategy = routeReuseStrategy;
2253 this.futureState = futureState;
2254 this.currState = currState;
2255 this.forwardEvent = forwardEvent;
2256 }
2257 ActivateRoutes.prototype.activate = function (parentContexts) {
2258 var futureRoot = this.futureState._root;
2259 var currRoot = this.currState ? this.currState._root : null;
2260 this.deactivateChildRoutes(futureRoot, currRoot, parentContexts);
2261 advanceActivatedRoute(this.futureState.root);
2262 this.activateChildRoutes(futureRoot, currRoot, parentContexts);
2263 };
2264 // De-activate the child route that are not re-used for the future state
2265 ActivateRoutes.prototype.deactivateChildRoutes = function (futureNode, currNode, contexts) {
2266 var _this = this;
2267 var children = nodeChildrenAsMap(currNode);
2268 // Recurse on the routes active in the future state to de-activate deeper children
2269 futureNode.children.forEach(function (futureChild) {
2270 var childOutletName = futureChild.value.outlet;
2271 _this.deactivateRoutes(futureChild, children[childOutletName], contexts);
2272 delete children[childOutletName];
2273 });
2274 // De-activate the routes that will not be re-used
2275 forEach(children, function (v, childName) {
2276 _this.deactivateRouteAndItsChildren(v, contexts);
2277 });
2278 };
2279 ActivateRoutes.prototype.deactivateRoutes = function (futureNode, currNode, parentContext) {
2280 var future = futureNode.value;
2281 var curr = currNode ? currNode.value : null;
2282 if (future === curr) {
2283 // Reusing the node, check to see if the children need to be de-activated
2284 if (future.component) {
2285 // If we have a normal route, we need to go through an outlet.
2286 var context = parentContext.getContext(future.outlet);
2287 if (context) {
2288 this.deactivateChildRoutes(futureNode, currNode, context.children);
2289 }
2290 }
2291 else {
2292 // if we have a componentless route, we recurse but keep the same outlet map.
2293 this.deactivateChildRoutes(futureNode, currNode, parentContext);
2294 }
2295 }
2296 else {
2297 if (curr) {
2298 // Deactivate the current route which will not be re-used
2299 this.deactivateRouteAndItsChildren(currNode, parentContext);
2300 }
2301 }
2302 };
2303 ActivateRoutes.prototype.deactivateRouteAndItsChildren = function (route, parentContexts) {
2304 if (this.routeReuseStrategy.shouldDetach(route.value.snapshot)) {
2305 this.detachAndStoreRouteSubtree(route, parentContexts);
2306 }
2307 else {
2308 this.deactivateRouteAndOutlet(route, parentContexts);
2309 }
2310 };
2311 ActivateRoutes.prototype.detachAndStoreRouteSubtree = function (route, parentContexts) {
2312 var context = parentContexts.getContext(route.value.outlet);
2313 if (context && context.outlet) {
2314 var componentRef = context.outlet.detach();
2315 var contexts = context.children.onOutletDeactivated();
2316 this.routeReuseStrategy.store(route.value.snapshot, { componentRef: componentRef, route: route, contexts: contexts });
2317 }
2318 };
2319 ActivateRoutes.prototype.deactivateRouteAndOutlet = function (route, parentContexts) {
2320 var _this = this;
2321 var context = parentContexts.getContext(route.value.outlet);
2322 if (context) {
2323 var children = nodeChildrenAsMap(route);
2324 var contexts_1 = route.value.component ? context.children : parentContexts;
2325 forEach(children, function (v, k) { return _this.deactivateRouteAndItsChildren(v, contexts_1); });
2326 if (context.outlet) {
2327 // Destroy the component
2328 context.outlet.deactivate();
2329 // Destroy the contexts for all the outlets that were in the component
2330 context.children.onOutletDeactivated();
2331 }
2332 }
2333 };
2334 ActivateRoutes.prototype.activateChildRoutes = function (futureNode, currNode, contexts) {
2335 var _this = this;
2336 var children = nodeChildrenAsMap(currNode);
2337 futureNode.children.forEach(function (c) {
2338 _this.activateRoutes(c, children[c.value.outlet], contexts);
2339 _this.forwardEvent(new ActivationEnd(c.value.snapshot));
2340 });
2341 if (futureNode.children.length) {
2342 this.forwardEvent(new ChildActivationEnd(futureNode.value.snapshot));
2343 }
2344 };
2345 ActivateRoutes.prototype.activateRoutes = function (futureNode, currNode, parentContexts) {
2346 var future = futureNode.value;
2347 var curr = currNode ? currNode.value : null;
2348 advanceActivatedRoute(future);
2349 // reusing the node
2350 if (future === curr) {
2351 if (future.component) {
2352 // If we have a normal route, we need to go through an outlet.
2353 var context = parentContexts.getOrCreateContext(future.outlet);
2354 this.activateChildRoutes(futureNode, currNode, context.children);
2355 }
2356 else {
2357 // if we have a componentless route, we recurse but keep the same outlet map.
2358 this.activateChildRoutes(futureNode, currNode, parentContexts);
2359 }
2360 }
2361 else {
2362 if (future.component) {
2363 // if we have a normal route, we need to place the component into the outlet and recurse.
2364 var context = parentContexts.getOrCreateContext(future.outlet);
2365 if (this.routeReuseStrategy.shouldAttach(future.snapshot)) {
2366 var stored = this.routeReuseStrategy.retrieve(future.snapshot);
2367 this.routeReuseStrategy.store(future.snapshot, null);
2368 context.children.onOutletReAttached(stored.contexts);
2369 context.attachRef = stored.componentRef;
2370 context.route = stored.route.value;
2371 if (context.outlet) {
2372 // Attach right away when the outlet has already been instantiated
2373 // Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated
2374 context.outlet.attach(stored.componentRef, stored.route.value);
2375 }
2376 advanceActivatedRouteNodeAndItsChildren(stored.route);
2377 }
2378 else {
2379 var config = parentLoadedConfig(future.snapshot);
2380 var cmpFactoryResolver = config ? config.module.componentFactoryResolver : null;
2381 context.attachRef = null;
2382 context.route = future;
2383 context.resolver = cmpFactoryResolver;
2384 if (context.outlet) {
2385 // Activate the outlet when it has already been instantiated
2386 // Otherwise it will get activated from its `ngOnInit` when instantiated
2387 context.outlet.activateWith(future, cmpFactoryResolver);
2388 }
2389 this.activateChildRoutes(futureNode, null, context.children);
2390 }
2391 }
2392 else {
2393 // if we have a componentless route, we recurse but keep the same outlet map.
2394 this.activateChildRoutes(futureNode, null, parentContexts);
2395 }
2396 }
2397 };
2398 return ActivateRoutes;
2399 }());
2400 function advanceActivatedRouteNodeAndItsChildren(node) {
2401 advanceActivatedRoute(node.value);
2402 node.children.forEach(advanceActivatedRouteNodeAndItsChildren);
2403 }
2404 function parentLoadedConfig(snapshot) {
2405 for (var s = snapshot.parent; s; s = s.parent) {
2406 var route = s.routeConfig;
2407 if (route && route._loadedConfig)
2408 return route._loadedConfig;
2409 if (route && route.component)
2410 return null;
2411 }
2412 return null;
2413 }
2414
2415 /**
2416 * @license
2417 * Copyright Google Inc. All Rights Reserved.
2418 *
2419 * Use of this source code is governed by an MIT-style license that can be
2420 * found in the LICENSE file at https://angular.io/license
2421 */
2422 /**
2423 * Simple function check, but generic so type inference will flow. Example:
2424 *
2425 * function product(a: number, b: number) {
2426 * return a * b;
2427 * }
2428 *
2429 * if (isFunction<product>(fn)) {
2430 * return fn(1, 2);
2431 * } else {
2432 * throw "Must provide the `product` function";
2433 * }
2434 */
2435 function isFunction(v) {
2436 return typeof v === 'function';
2437 }
2438 function isBoolean(v) {
2439 return typeof v === 'boolean';
2440 }
2441 function isUrlTree(v) {
2442 return v instanceof UrlTree;
2443 }
2444 function isCanLoad(guard) {
2445 return guard && isFunction(guard.canLoad);
2446 }
2447 function isCanActivate(guard) {
2448 return guard && isFunction(guard.canActivate);
2449 }
2450 function isCanActivateChild(guard) {
2451 return guard && isFunction(guard.canActivateChild);
2452 }
2453 function isCanDeactivate(guard) {
2454 return guard && isFunction(guard.canDeactivate);
2455 }
2456
2457 /**
2458 * @license
2459 * Copyright Google Inc. All Rights Reserved.
2460 *
2461 * Use of this source code is governed by an MIT-style license that can be
2462 * found in the LICENSE file at https://angular.io/license
2463 */
2464 var NoMatch = /** @class */ (function () {
2465 function NoMatch(segmentGroup) {
2466 this.segmentGroup = segmentGroup || null;
2467 }
2468 return NoMatch;
2469 }());
2470 var AbsoluteRedirect = /** @class */ (function () {
2471 function AbsoluteRedirect(urlTree) {
2472 this.urlTree = urlTree;
2473 }
2474 return AbsoluteRedirect;
2475 }());
2476 function noMatch(segmentGroup) {
2477 return new rxjs.Observable(function (obs) { return obs.error(new NoMatch(segmentGroup)); });
2478 }
2479 function absoluteRedirect(newTree) {
2480 return new rxjs.Observable(function (obs) { return obs.error(new AbsoluteRedirect(newTree)); });
2481 }
2482 function namedOutletsRedirect(redirectTo) {
2483 return new rxjs.Observable(function (obs) { return obs.error(new Error("Only absolute redirects can have named outlets. redirectTo: '" + redirectTo + "'")); });
2484 }
2485 function canLoadFails(route) {
2486 return new rxjs.Observable(function (obs) { return obs.error(navigationCancelingError("Cannot load children because the guard of the route \"path: '" + route.path + "'\" returned false")); });
2487 }
2488 /**
2489 * Returns the `UrlTree` with the redirection applied.
2490 *
2491 * Lazy modules are loaded along the way.
2492 */
2493 function applyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) {
2494 return new ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config).apply();
2495 }
2496 var ApplyRedirects = /** @class */ (function () {
2497 function ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) {
2498 this.configLoader = configLoader;
2499 this.urlSerializer = urlSerializer;
2500 this.urlTree = urlTree;
2501 this.config = config;
2502 this.allowRedirects = true;
2503 this.ngModule = moduleInjector.get(core.NgModuleRef);
2504 }
2505 ApplyRedirects.prototype.apply = function () {
2506 var _this = this;
2507 var expanded$ = this.expandSegmentGroup(this.ngModule, this.config, this.urlTree.root, PRIMARY_OUTLET);
2508 var urlTrees$ = expanded$.pipe(operators.map(function (rootSegmentGroup) { return _this.createUrlTree(rootSegmentGroup, _this.urlTree.queryParams, _this.urlTree.fragment); }));
2509 return urlTrees$.pipe(operators.catchError(function (e) {
2510 if (e instanceof AbsoluteRedirect) {
2511 // after an absolute redirect we do not apply any more redirects!
2512 _this.allowRedirects = false;
2513 // we need to run matching, so we can fetch all lazy-loaded modules
2514 return _this.match(e.urlTree);
2515 }
2516 if (e instanceof NoMatch) {
2517 throw _this.noMatchError(e);
2518 }
2519 throw e;
2520 }));
2521 };
2522 ApplyRedirects.prototype.match = function (tree) {
2523 var _this = this;
2524 var expanded$ = this.expandSegmentGroup(this.ngModule, this.config, tree.root, PRIMARY_OUTLET);
2525 var mapped$ = expanded$.pipe(operators.map(function (rootSegmentGroup) {
2526 return _this.createUrlTree(rootSegmentGroup, tree.queryParams, tree.fragment);
2527 }));
2528 return mapped$.pipe(operators.catchError(function (e) {
2529 if (e instanceof NoMatch) {
2530 throw _this.noMatchError(e);
2531 }
2532 throw e;
2533 }));
2534 };
2535 ApplyRedirects.prototype.noMatchError = function (e) {
2536 return new Error("Cannot match any routes. URL Segment: '" + e.segmentGroup + "'");
2537 };
2538 ApplyRedirects.prototype.createUrlTree = function (rootCandidate, queryParams, fragment) {
2539 var _a;
2540 var root = rootCandidate.segments.length > 0 ?
2541 new UrlSegmentGroup([], (_a = {}, _a[PRIMARY_OUTLET] = rootCandidate, _a)) :
2542 rootCandidate;
2543 return new UrlTree(root, queryParams, fragment);
2544 };
2545 ApplyRedirects.prototype.expandSegmentGroup = function (ngModule, routes, segmentGroup, outlet) {
2546 if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
2547 return this.expandChildren(ngModule, routes, segmentGroup)
2548 .pipe(operators.map(function (children) { return new UrlSegmentGroup([], children); }));
2549 }
2550 return this.expandSegment(ngModule, segmentGroup, routes, segmentGroup.segments, outlet, true);
2551 };
2552 // Recursively expand segment groups for all the child outlets
2553 ApplyRedirects.prototype.expandChildren = function (ngModule, routes, segmentGroup) {
2554 var _this = this;
2555 return waitForMap(segmentGroup.children, function (childOutlet, child) { return _this.expandSegmentGroup(ngModule, routes, child, childOutlet); });
2556 };
2557 ApplyRedirects.prototype.expandSegment = function (ngModule, segmentGroup, routes, segments, outlet, allowRedirects) {
2558 var _this = this;
2559 return rxjs.of.apply(void 0, __spread(routes)).pipe(operators.map(function (r) {
2560 var expanded$ = _this.expandSegmentAgainstRoute(ngModule, segmentGroup, routes, r, segments, outlet, allowRedirects);
2561 return expanded$.pipe(operators.catchError(function (e) {
2562 if (e instanceof NoMatch) {
2563 // TODO(i): this return type doesn't match the declared Observable<UrlSegmentGroup> -
2564 // talk to Jason
2565 return rxjs.of(null);
2566 }
2567 throw e;
2568 }));
2569 }), operators.concatAll(), operators.first(function (s) { return !!s; }), operators.catchError(function (e, _) {
2570 if (e instanceof rxjs.EmptyError || e.name === 'EmptyError') {
2571 if (_this.noLeftoversInUrl(segmentGroup, segments, outlet)) {
2572 return rxjs.of(new UrlSegmentGroup([], {}));
2573 }
2574 throw new NoMatch(segmentGroup);
2575 }
2576 throw e;
2577 }));
2578 };
2579 ApplyRedirects.prototype.noLeftoversInUrl = function (segmentGroup, segments, outlet) {
2580 return segments.length === 0 && !segmentGroup.children[outlet];
2581 };
2582 ApplyRedirects.prototype.expandSegmentAgainstRoute = function (ngModule, segmentGroup, routes, route, paths, outlet, allowRedirects) {
2583 if (getOutlet(route) !== outlet) {
2584 return noMatch(segmentGroup);
2585 }
2586 if (route.redirectTo === undefined) {
2587 return this.matchSegmentAgainstRoute(ngModule, segmentGroup, route, paths);
2588 }
2589 if (allowRedirects && this.allowRedirects) {
2590 return this.expandSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, paths, outlet);
2591 }
2592 return noMatch(segmentGroup);
2593 };
2594 ApplyRedirects.prototype.expandSegmentAgainstRouteUsingRedirect = function (ngModule, segmentGroup, routes, route, segments, outlet) {
2595 if (route.path === '**') {
2596 return this.expandWildCardWithParamsAgainstRouteUsingRedirect(ngModule, routes, route, outlet);
2597 }
2598 return this.expandRegularSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, segments, outlet);
2599 };
2600 ApplyRedirects.prototype.expandWildCardWithParamsAgainstRouteUsingRedirect = function (ngModule, routes, route, outlet) {
2601 var _this = this;
2602 var newTree = this.applyRedirectCommands([], route.redirectTo, {});
2603 if (route.redirectTo.startsWith('/')) {
2604 return absoluteRedirect(newTree);
2605 }
2606 return this.lineralizeSegments(route, newTree).pipe(operators.mergeMap(function (newSegments) {
2607 var group = new UrlSegmentGroup(newSegments, {});
2608 return _this.expandSegment(ngModule, group, routes, newSegments, outlet, false);
2609 }));
2610 };
2611 ApplyRedirects.prototype.expandRegularSegmentAgainstRouteUsingRedirect = function (ngModule, segmentGroup, routes, route, segments, outlet) {
2612 var _this = this;
2613 var _a = match(segmentGroup, route, segments), matched = _a.matched, consumedSegments = _a.consumedSegments, lastChild = _a.lastChild, positionalParamSegments = _a.positionalParamSegments;
2614 if (!matched)
2615 return noMatch(segmentGroup);
2616 var newTree = this.applyRedirectCommands(consumedSegments, route.redirectTo, positionalParamSegments);
2617 if (route.redirectTo.startsWith('/')) {
2618 return absoluteRedirect(newTree);
2619 }
2620 return this.lineralizeSegments(route, newTree).pipe(operators.mergeMap(function (newSegments) {
2621 return _this.expandSegment(ngModule, segmentGroup, routes, newSegments.concat(segments.slice(lastChild)), outlet, false);
2622 }));
2623 };
2624 ApplyRedirects.prototype.matchSegmentAgainstRoute = function (ngModule, rawSegmentGroup, route, segments) {
2625 var _this = this;
2626 if (route.path === '**') {
2627 if (route.loadChildren) {
2628 return this.configLoader.load(ngModule.injector, route)
2629 .pipe(operators.map(function (cfg) {
2630 route._loadedConfig = cfg;
2631 return new UrlSegmentGroup(segments, {});
2632 }));
2633 }
2634 return rxjs.of(new UrlSegmentGroup(segments, {}));
2635 }
2636 var _a = match(rawSegmentGroup, route, segments), matched = _a.matched, consumedSegments = _a.consumedSegments, lastChild = _a.lastChild;
2637 if (!matched)
2638 return noMatch(rawSegmentGroup);
2639 var rawSlicedSegments = segments.slice(lastChild);
2640 var childConfig$ = this.getChildConfig(ngModule, route, segments);
2641 return childConfig$.pipe(operators.mergeMap(function (routerConfig) {
2642 var childModule = routerConfig.module;
2643 var childConfig = routerConfig.routes;
2644 var _a = split(rawSegmentGroup, consumedSegments, rawSlicedSegments, childConfig), segmentGroup = _a.segmentGroup, slicedSegments = _a.slicedSegments;
2645 if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
2646 var expanded$_1 = _this.expandChildren(childModule, childConfig, segmentGroup);
2647 return expanded$_1.pipe(operators.map(function (children) { return new UrlSegmentGroup(consumedSegments, children); }));
2648 }
2649 if (childConfig.length === 0 && slicedSegments.length === 0) {
2650 return rxjs.of(new UrlSegmentGroup(consumedSegments, {}));
2651 }
2652 var expanded$ = _this.expandSegment(childModule, segmentGroup, childConfig, slicedSegments, PRIMARY_OUTLET, true);
2653 return expanded$.pipe(operators.map(function (cs) {
2654 return new UrlSegmentGroup(consumedSegments.concat(cs.segments), cs.children);
2655 }));
2656 }));
2657 };
2658 ApplyRedirects.prototype.getChildConfig = function (ngModule, route, segments) {
2659 var _this = this;
2660 if (route.children) {
2661 // The children belong to the same module
2662 return rxjs.of(new LoadedRouterConfig(route.children, ngModule));
2663 }
2664 if (route.loadChildren) {
2665 // lazy children belong to the loaded module
2666 if (route._loadedConfig !== undefined) {
2667 return rxjs.of(route._loadedConfig);
2668 }
2669 return runCanLoadGuard(ngModule.injector, route, segments)
2670 .pipe(operators.mergeMap(function (shouldLoad) {
2671 if (shouldLoad) {
2672 return _this.configLoader.load(ngModule.injector, route)
2673 .pipe(operators.map(function (cfg) {
2674 route._loadedConfig = cfg;
2675 return cfg;
2676 }));
2677 }
2678 return canLoadFails(route);
2679 }));
2680 }
2681 return rxjs.of(new LoadedRouterConfig([], ngModule));
2682 };
2683 ApplyRedirects.prototype.lineralizeSegments = function (route, urlTree) {
2684 var res = [];
2685 var c = urlTree.root;
2686 while (true) {
2687 res = res.concat(c.segments);
2688 if (c.numberOfChildren === 0) {
2689 return rxjs.of(res);
2690 }
2691 if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) {
2692 return namedOutletsRedirect(route.redirectTo);
2693 }
2694 c = c.children[PRIMARY_OUTLET];
2695 }
2696 };
2697 ApplyRedirects.prototype.applyRedirectCommands = function (segments, redirectTo, posParams) {
2698 return this.applyRedirectCreatreUrlTree(redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams);
2699 };
2700 ApplyRedirects.prototype.applyRedirectCreatreUrlTree = function (redirectTo, urlTree, segments, posParams) {
2701 var newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams);
2702 return new UrlTree(newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment);
2703 };
2704 ApplyRedirects.prototype.createQueryParams = function (redirectToParams, actualParams) {
2705 var res = {};
2706 forEach(redirectToParams, function (v, k) {
2707 var copySourceValue = typeof v === 'string' && v.startsWith(':');
2708 if (copySourceValue) {
2709 var sourceName = v.substring(1);
2710 res[k] = actualParams[sourceName];
2711 }
2712 else {
2713 res[k] = v;
2714 }
2715 });
2716 return res;
2717 };
2718 ApplyRedirects.prototype.createSegmentGroup = function (redirectTo, group, segments, posParams) {
2719 var _this = this;
2720 var updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams);
2721 var children = {};
2722 forEach(group.children, function (child, name) {
2723 children[name] = _this.createSegmentGroup(redirectTo, child, segments, posParams);
2724 });
2725 return new UrlSegmentGroup(updatedSegments, children);
2726 };
2727 ApplyRedirects.prototype.createSegments = function (redirectTo, redirectToSegments, actualSegments, posParams) {
2728 var _this = this;
2729 return redirectToSegments.map(function (s) { return s.path.startsWith(':') ? _this.findPosParam(redirectTo, s, posParams) :
2730 _this.findOrReturn(s, actualSegments); });
2731 };
2732 ApplyRedirects.prototype.findPosParam = function (redirectTo, redirectToUrlSegment, posParams) {
2733 var pos = posParams[redirectToUrlSegment.path.substring(1)];
2734 if (!pos)
2735 throw new Error("Cannot redirect to '" + redirectTo + "'. Cannot find '" + redirectToUrlSegment.path + "'.");
2736 return pos;
2737 };
2738 ApplyRedirects.prototype.findOrReturn = function (redirectToUrlSegment, actualSegments) {
2739 var e_1, _a;
2740 var idx = 0;
2741 try {
2742 for (var actualSegments_1 = __values(actualSegments), actualSegments_1_1 = actualSegments_1.next(); !actualSegments_1_1.done; actualSegments_1_1 = actualSegments_1.next()) {
2743 var s = actualSegments_1_1.value;
2744 if (s.path === redirectToUrlSegment.path) {
2745 actualSegments.splice(idx);
2746 return s;
2747 }
2748 idx++;
2749 }
2750 }
2751 catch (e_1_1) { e_1 = { error: e_1_1 }; }
2752 finally {
2753 try {
2754 if (actualSegments_1_1 && !actualSegments_1_1.done && (_a = actualSegments_1.return)) _a.call(actualSegments_1);
2755 }
2756 finally { if (e_1) throw e_1.error; }
2757 }
2758 return redirectToUrlSegment;
2759 };
2760 return ApplyRedirects;
2761 }());
2762 function runCanLoadGuard(moduleInjector, route, segments) {
2763 var canLoad = route.canLoad;
2764 if (!canLoad || canLoad.length === 0)
2765 return rxjs.of(true);
2766 var obs = rxjs.from(canLoad).pipe(operators.map(function (injectionToken) {
2767 var guard = moduleInjector.get(injectionToken);
2768 var guardVal;
2769 if (isCanLoad(guard)) {
2770 guardVal = guard.canLoad(route, segments);
2771 }
2772 else if (isFunction(guard)) {
2773 guardVal = guard(route, segments);
2774 }
2775 else {
2776 throw new Error('Invalid CanLoad guard');
2777 }
2778 return wrapIntoObservable(guardVal);
2779 }));
2780 return obs.pipe(operators.concatAll(), operators.every(function (result) { return result === true; }));
2781 }
2782 function match(segmentGroup, route, segments) {
2783 if (route.path === '') {
2784 if ((route.pathMatch === 'full') && (segmentGroup.hasChildren() || segments.length > 0)) {
2785 return { matched: false, consumedSegments: [], lastChild: 0, positionalParamSegments: {} };
2786 }
2787 return { matched: true, consumedSegments: [], lastChild: 0, positionalParamSegments: {} };
2788 }
2789 var matcher = route.matcher || defaultUrlMatcher;
2790 var res = matcher(segments, segmentGroup, route);
2791 if (!res) {
2792 return {
2793 matched: false,
2794 consumedSegments: [],
2795 lastChild: 0,
2796 positionalParamSegments: {},
2797 };
2798 }
2799 return {
2800 matched: true,
2801 consumedSegments: res.consumed,
2802 lastChild: res.consumed.length,
2803 positionalParamSegments: res.posParams,
2804 };
2805 }
2806 function split(segmentGroup, consumedSegments, slicedSegments, config) {
2807 if (slicedSegments.length > 0 &&
2808 containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, slicedSegments, config)) {
2809 var s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptySegments(config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
2810 return { segmentGroup: mergeTrivialChildren(s), slicedSegments: [] };
2811 }
2812 if (slicedSegments.length === 0 &&
2813 containsEmptyPathRedirects(segmentGroup, slicedSegments, config)) {
2814 var s = new UrlSegmentGroup(segmentGroup.segments, addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children));
2815 return { segmentGroup: mergeTrivialChildren(s), slicedSegments: slicedSegments };
2816 }
2817 return { segmentGroup: segmentGroup, slicedSegments: slicedSegments };
2818 }
2819 function mergeTrivialChildren(s) {
2820 if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {
2821 var c = s.children[PRIMARY_OUTLET];
2822 return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);
2823 }
2824 return s;
2825 }
2826 function addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) {
2827 var e_2, _a;
2828 var res = {};
2829 try {
2830 for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
2831 var r = routes_1_1.value;
2832 if (isEmptyPathRedirect(segmentGroup, slicedSegments, r) && !children[getOutlet(r)]) {
2833 res[getOutlet(r)] = new UrlSegmentGroup([], {});
2834 }
2835 }
2836 }
2837 catch (e_2_1) { e_2 = { error: e_2_1 }; }
2838 finally {
2839 try {
2840 if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
2841 }
2842 finally { if (e_2) throw e_2.error; }
2843 }
2844 return __assign({}, children, res);
2845 }
2846 function createChildrenForEmptySegments(routes, primarySegmentGroup) {
2847 var e_3, _a;
2848 var res = {};
2849 res[PRIMARY_OUTLET] = primarySegmentGroup;
2850 try {
2851 for (var routes_2 = __values(routes), routes_2_1 = routes_2.next(); !routes_2_1.done; routes_2_1 = routes_2.next()) {
2852 var r = routes_2_1.value;
2853 if (r.path === '' && getOutlet(r) !== PRIMARY_OUTLET) {
2854 res[getOutlet(r)] = new UrlSegmentGroup([], {});
2855 }
2856 }
2857 }
2858 catch (e_3_1) { e_3 = { error: e_3_1 }; }
2859 finally {
2860 try {
2861 if (routes_2_1 && !routes_2_1.done && (_a = routes_2.return)) _a.call(routes_2);
2862 }
2863 finally { if (e_3) throw e_3.error; }
2864 }
2865 return res;
2866 }
2867 function containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, segments, routes) {
2868 return routes.some(function (r) { return isEmptyPathRedirect(segmentGroup, segments, r) && getOutlet(r) !== PRIMARY_OUTLET; });
2869 }
2870 function containsEmptyPathRedirects(segmentGroup, segments, routes) {
2871 return routes.some(function (r) { return isEmptyPathRedirect(segmentGroup, segments, r); });
2872 }
2873 function isEmptyPathRedirect(segmentGroup, segments, r) {
2874 if ((segmentGroup.hasChildren() || segments.length > 0) && r.pathMatch === 'full') {
2875 return false;
2876 }
2877 return r.path === '' && r.redirectTo !== undefined;
2878 }
2879 function getOutlet(route) {
2880 return route.outlet || PRIMARY_OUTLET;
2881 }
2882
2883 /**
2884 * @license
2885 * Copyright Google Inc. All Rights Reserved.
2886 *
2887 * Use of this source code is governed by an MIT-style license that can be
2888 * found in the LICENSE file at https://angular.io/license
2889 */
2890 function applyRedirects$1(moduleInjector, configLoader, urlSerializer, config) {
2891 return function (source) {
2892 return source.pipe(operators.switchMap(function (t) { return applyRedirects(moduleInjector, configLoader, urlSerializer, t.extractedUrl, config)
2893 .pipe(operators.map(function (urlAfterRedirects) { return (__assign({}, t, { urlAfterRedirects: urlAfterRedirects })); })); }));
2894 };
2895 }
2896
2897 /**
2898 * @license
2899 * Copyright Google Inc. All Rights Reserved.
2900 *
2901 * Use of this source code is governed by an MIT-style license that can be
2902 * found in the LICENSE file at https://angular.io/license
2903 */
2904 var CanActivate = /** @class */ (function () {
2905 function CanActivate(path) {
2906 this.path = path;
2907 this.route = this.path[this.path.length - 1];
2908 }
2909 return CanActivate;
2910 }());
2911 var CanDeactivate = /** @class */ (function () {
2912 function CanDeactivate(component, route) {
2913 this.component = component;
2914 this.route = route;
2915 }
2916 return CanDeactivate;
2917 }());
2918 function getAllRouteGuards(future, curr, parentContexts) {
2919 var futureRoot = future._root;
2920 var currRoot = curr ? curr._root : null;
2921 return getChildRouteGuards(futureRoot, currRoot, parentContexts, [futureRoot.value]);
2922 }
2923 function getCanActivateChild(p) {
2924 var canActivateChild = p.routeConfig ? p.routeConfig.canActivateChild : null;
2925 if (!canActivateChild || canActivateChild.length === 0)
2926 return null;
2927 return { node: p, guards: canActivateChild };
2928 }
2929 function getToken(token, snapshot, moduleInjector) {
2930 var config = getClosestLoadedConfig(snapshot);
2931 var injector = config ? config.module.injector : moduleInjector;
2932 return injector.get(token);
2933 }
2934 function getClosestLoadedConfig(snapshot) {
2935 if (!snapshot)
2936 return null;
2937 for (var s = snapshot.parent; s; s = s.parent) {
2938 var route = s.routeConfig;
2939 if (route && route._loadedConfig)
2940 return route._loadedConfig;
2941 }
2942 return null;
2943 }
2944 function getChildRouteGuards(futureNode, currNode, contexts, futurePath, checks) {
2945 if (checks === void 0) { checks = {
2946 canDeactivateChecks: [],
2947 canActivateChecks: []
2948 }; }
2949 var prevChildren = nodeChildrenAsMap(currNode);
2950 // Process the children of the future route
2951 futureNode.children.forEach(function (c) {
2952 getRouteGuards(c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value]), checks);
2953 delete prevChildren[c.value.outlet];
2954 });
2955 // Process any children left from the current route (not active for the future route)
2956 forEach(prevChildren, function (v, k) {
2957 return deactivateRouteAndItsChildren(v, contexts.getContext(k), checks);
2958 });
2959 return checks;
2960 }
2961 function getRouteGuards(futureNode, currNode, parentContexts, futurePath, checks) {
2962 if (checks === void 0) { checks = {
2963 canDeactivateChecks: [],
2964 canActivateChecks: []
2965 }; }
2966 var future = futureNode.value;
2967 var curr = currNode ? currNode.value : null;
2968 var context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null;
2969 // reusing the node
2970 if (curr && future.routeConfig === curr.routeConfig) {
2971 var shouldRun = shouldRunGuardsAndResolvers(curr, future, future.routeConfig.runGuardsAndResolvers);
2972 if (shouldRun) {
2973 checks.canActivateChecks.push(new CanActivate(futurePath));
2974 }
2975 else {
2976 // we need to set the data
2977 future.data = curr.data;
2978 future._resolvedData = curr._resolvedData;
2979 }
2980 // If we have a component, we need to go through an outlet.
2981 if (future.component) {
2982 getChildRouteGuards(futureNode, currNode, context ? context.children : null, futurePath, checks);
2983 // if we have a componentless route, we recurse but keep the same outlet map.
2984 }
2985 else {
2986 getChildRouteGuards(futureNode, currNode, parentContexts, futurePath, checks);
2987 }
2988 if (shouldRun) {
2989 var component = context && context.outlet && context.outlet.component || null;
2990 checks.canDeactivateChecks.push(new CanDeactivate(component, curr));
2991 }
2992 }
2993 else {
2994 if (curr) {
2995 deactivateRouteAndItsChildren(currNode, context, checks);
2996 }
2997 checks.canActivateChecks.push(new CanActivate(futurePath));
2998 // If we have a component, we need to go through an outlet.
2999 if (future.component) {
3000 getChildRouteGuards(futureNode, null, context ? context.children : null, futurePath, checks);
3001 // if we have a componentless route, we recurse but keep the same outlet map.
3002 }
3003 else {
3004 getChildRouteGuards(futureNode, null, parentContexts, futurePath, checks);
3005 }
3006 }
3007 return checks;
3008 }
3009 function shouldRunGuardsAndResolvers(curr, future, mode) {
3010 if (typeof mode === 'function') {
3011 return mode(curr, future);
3012 }
3013 switch (mode) {
3014 case 'pathParamsChange':
3015 return !equalPath(curr.url, future.url);
3016 case 'pathParamsOrQueryParamsChange':
3017 return !equalPath(curr.url, future.url) ||
3018 !shallowEqual(curr.queryParams, future.queryParams);
3019 case 'always':
3020 return true;
3021 case 'paramsOrQueryParamsChange':
3022 return !equalParamsAndUrlSegments(curr, future) ||
3023 !shallowEqual(curr.queryParams, future.queryParams);
3024 case 'paramsChange':
3025 default:
3026 return !equalParamsAndUrlSegments(curr, future);
3027 }
3028 }
3029 function deactivateRouteAndItsChildren(route, context, checks) {
3030 var children = nodeChildrenAsMap(route);
3031 var r = route.value;
3032 forEach(children, function (node, childName) {
3033 if (!r.component) {
3034 deactivateRouteAndItsChildren(node, context, checks);
3035 }
3036 else if (context) {
3037 deactivateRouteAndItsChildren(node, context.children.getContext(childName), checks);
3038 }
3039 else {
3040 deactivateRouteAndItsChildren(node, null, checks);
3041 }
3042 });
3043 if (!r.component) {
3044 checks.canDeactivateChecks.push(new CanDeactivate(null, r));
3045 }
3046 else if (context && context.outlet && context.outlet.isActivated) {
3047 checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r));
3048 }
3049 else {
3050 checks.canDeactivateChecks.push(new CanDeactivate(null, r));
3051 }
3052 }
3053
3054 /**
3055 * @license
3056 * Copyright Google Inc. All Rights Reserved.
3057 *
3058 * Use of this source code is governed by an MIT-style license that can be
3059 * found in the LICENSE file at https://angular.io/license
3060 */
3061 var INITIAL_VALUE = Symbol('INITIAL_VALUE');
3062 function prioritizedGuardValue() {
3063 return operators.switchMap(function (obs) {
3064 return rxjs.combineLatest.apply(void 0, __spread(obs.map(function (o) { return o.pipe(operators.take(1), operators.startWith(INITIAL_VALUE)); }))).pipe(operators.scan(function (acc, list) {
3065 var isPending = false;
3066 return list.reduce(function (innerAcc, val, i) {
3067 if (innerAcc !== INITIAL_VALUE)
3068 return innerAcc;
3069 // Toggle pending flag if any values haven't been set yet
3070 if (val === INITIAL_VALUE)
3071 isPending = true;
3072 // Any other return values are only valid if we haven't yet hit a pending call.
3073 // This guarantees that in the case of a guard at the bottom of the tree that
3074 // returns a redirect, we will wait for the higher priority guard at the top to
3075 // finish before performing the redirect.
3076 if (!isPending) {
3077 // Early return when we hit a `false` value as that should always cancel
3078 // navigation
3079 if (val === false)
3080 return val;
3081 if (i === list.length - 1 || isUrlTree(val)) {
3082 return val;
3083 }
3084 }
3085 return innerAcc;
3086 }, acc);
3087 }, INITIAL_VALUE), operators.filter(function (item) { return item !== INITIAL_VALUE; }), operators.map(function (item) { return isUrlTree(item) ? item : item === true; }), //
3088 operators.take(1));
3089 });
3090 }
3091
3092 /**
3093 * @license
3094 * Copyright Google Inc. All Rights Reserved.
3095 *
3096 * Use of this source code is governed by an MIT-style license that can be
3097 * found in the LICENSE file at https://angular.io/license
3098 */
3099 function checkGuards(moduleInjector, forwardEvent) {
3100 return function (source) {
3101 return source.pipe(operators.mergeMap(function (t) {
3102 var targetSnapshot = t.targetSnapshot, currentSnapshot = t.currentSnapshot, _a = t.guards, canActivateChecks = _a.canActivateChecks, canDeactivateChecks = _a.canDeactivateChecks;
3103 if (canDeactivateChecks.length === 0 && canActivateChecks.length === 0) {
3104 return rxjs.of(__assign({}, t, { guardsResult: true }));
3105 }
3106 return runCanDeactivateChecks(canDeactivateChecks, targetSnapshot, currentSnapshot, moduleInjector)
3107 .pipe(operators.mergeMap(function (canDeactivate) {
3108 return canDeactivate && isBoolean(canDeactivate) ?
3109 runCanActivateChecks(targetSnapshot, canActivateChecks, moduleInjector, forwardEvent) :
3110 rxjs.of(canDeactivate);
3111 }), operators.map(function (guardsResult) { return (__assign({}, t, { guardsResult: guardsResult })); }));
3112 }));
3113 };
3114 }
3115 function runCanDeactivateChecks(checks, futureRSS, currRSS, moduleInjector) {
3116 return rxjs.from(checks).pipe(operators.mergeMap(function (check) {
3117 return runCanDeactivate(check.component, check.route, currRSS, futureRSS, moduleInjector);
3118 }), operators.first(function (result) { return result !== true; }, true));
3119 }
3120 function runCanActivateChecks(futureSnapshot, checks, moduleInjector, forwardEvent) {
3121 return rxjs.from(checks).pipe(operators.concatMap(function (check) {
3122 return rxjs.from([
3123 fireChildActivationStart(check.route.parent, forwardEvent),
3124 fireActivationStart(check.route, forwardEvent),
3125 runCanActivateChild(futureSnapshot, check.path, moduleInjector),
3126 runCanActivate(futureSnapshot, check.route, moduleInjector)
3127 ])
3128 .pipe(operators.concatAll(), operators.first(function (result) {
3129 return result !== true;
3130 }, true));
3131 }), operators.first(function (result) { return result !== true; }, true));
3132 }
3133 /**
3134 * This should fire off `ActivationStart` events for each route being activated at this
3135 * level.
3136 * In other words, if you're activating `a` and `b` below, `path` will contain the
3137 * `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always
3138 * return
3139 * `true` so checks continue to run.
3140 */
3141 function fireActivationStart(snapshot, forwardEvent) {
3142 if (snapshot !== null && forwardEvent) {
3143 forwardEvent(new ActivationStart(snapshot));
3144 }
3145 return rxjs.of(true);
3146 }
3147 /**
3148 * This should fire off `ChildActivationStart` events for each route being activated at this
3149 * level.
3150 * In other words, if you're activating `a` and `b` below, `path` will contain the
3151 * `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always
3152 * return
3153 * `true` so checks continue to run.
3154 */
3155 function fireChildActivationStart(snapshot, forwardEvent) {
3156 if (snapshot !== null && forwardEvent) {
3157 forwardEvent(new ChildActivationStart(snapshot));
3158 }
3159 return rxjs.of(true);
3160 }
3161 function runCanActivate(futureRSS, futureARS, moduleInjector) {
3162 var canActivate = futureARS.routeConfig ? futureARS.routeConfig.canActivate : null;
3163 if (!canActivate || canActivate.length === 0)
3164 return rxjs.of(true);
3165 var canActivateObservables = canActivate.map(function (c) {
3166 return rxjs.defer(function () {
3167 var guard = getToken(c, futureARS, moduleInjector);
3168 var observable;
3169 if (isCanActivate(guard)) {
3170 observable = wrapIntoObservable(guard.canActivate(futureARS, futureRSS));
3171 }
3172 else if (isFunction(guard)) {
3173 observable = wrapIntoObservable(guard(futureARS, futureRSS));
3174 }
3175 else {
3176 throw new Error('Invalid CanActivate guard');
3177 }
3178 return observable.pipe(operators.first());
3179 });
3180 });
3181 return rxjs.of(canActivateObservables).pipe(prioritizedGuardValue());
3182 }
3183 function runCanActivateChild(futureRSS, path, moduleInjector) {
3184 var futureARS = path[path.length - 1];
3185 var canActivateChildGuards = path.slice(0, path.length - 1)
3186 .reverse()
3187 .map(function (p) { return getCanActivateChild(p); })
3188 .filter(function (_) { return _ !== null; });
3189 var canActivateChildGuardsMapped = canActivateChildGuards.map(function (d) {
3190 return rxjs.defer(function () {
3191 var guardsMapped = d.guards.map(function (c) {
3192 var guard = getToken(c, d.node, moduleInjector);
3193 var observable;
3194 if (isCanActivateChild(guard)) {
3195 observable = wrapIntoObservable(guard.canActivateChild(futureARS, futureRSS));
3196 }
3197 else if (isFunction(guard)) {
3198 observable = wrapIntoObservable(guard(futureARS, futureRSS));
3199 }
3200 else {
3201 throw new Error('Invalid CanActivateChild guard');
3202 }
3203 return observable.pipe(operators.first());
3204 });
3205 return rxjs.of(guardsMapped).pipe(prioritizedGuardValue());
3206 });
3207 });
3208 return rxjs.of(canActivateChildGuardsMapped).pipe(prioritizedGuardValue());
3209 }
3210 function runCanDeactivate(component, currARS, currRSS, futureRSS, moduleInjector) {
3211 var canDeactivate = currARS && currARS.routeConfig ? currARS.routeConfig.canDeactivate : null;
3212 if (!canDeactivate || canDeactivate.length === 0)
3213 return rxjs.of(true);
3214 var canDeactivateObservables = canDeactivate.map(function (c) {
3215 var guard = getToken(c, currARS, moduleInjector);
3216 var observable;
3217 if (isCanDeactivate(guard)) {
3218 observable =
3219 wrapIntoObservable(guard.canDeactivate(component, currARS, currRSS, futureRSS));
3220 }
3221 else if (isFunction(guard)) {
3222 observable = wrapIntoObservable(guard(component, currARS, currRSS, futureRSS));
3223 }
3224 else {
3225 throw new Error('Invalid CanDeactivate guard');
3226 }
3227 return observable.pipe(operators.first());
3228 });
3229 return rxjs.of(canDeactivateObservables).pipe(prioritizedGuardValue());
3230 }
3231
3232 /**
3233 * @license
3234 * Copyright Google Inc. All Rights Reserved.
3235 *
3236 * Use of this source code is governed by an MIT-style license that can be
3237 * found in the LICENSE file at https://angular.io/license
3238 */
3239 var NoMatch$1 = /** @class */ (function () {
3240 function NoMatch() {
3241 }
3242 return NoMatch;
3243 }());
3244 function recognize(rootComponentType, config, urlTree, url, paramsInheritanceStrategy, relativeLinkResolution) {
3245 if (paramsInheritanceStrategy === void 0) { paramsInheritanceStrategy = 'emptyOnly'; }
3246 if (relativeLinkResolution === void 0) { relativeLinkResolution = 'legacy'; }
3247 return new Recognizer(rootComponentType, config, urlTree, url, paramsInheritanceStrategy, relativeLinkResolution)
3248 .recognize();
3249 }
3250 var Recognizer = /** @class */ (function () {
3251 function Recognizer(rootComponentType, config, urlTree, url, paramsInheritanceStrategy, relativeLinkResolution) {
3252 this.rootComponentType = rootComponentType;
3253 this.config = config;
3254 this.urlTree = urlTree;
3255 this.url = url;
3256 this.paramsInheritanceStrategy = paramsInheritanceStrategy;
3257 this.relativeLinkResolution = relativeLinkResolution;
3258 }
3259 Recognizer.prototype.recognize = function () {
3260 try {
3261 var rootSegmentGroup = split$1(this.urlTree.root, [], [], this.config, this.relativeLinkResolution).segmentGroup;
3262 var children = this.processSegmentGroup(this.config, rootSegmentGroup, PRIMARY_OUTLET);
3263 var root = new ActivatedRouteSnapshot([], Object.freeze({}), Object.freeze(__assign({}, this.urlTree.queryParams)), this.urlTree.fragment, {}, PRIMARY_OUTLET, this.rootComponentType, null, this.urlTree.root, -1, {});
3264 var rootNode = new TreeNode(root, children);
3265 var routeState = new RouterStateSnapshot(this.url, rootNode);
3266 this.inheritParamsAndData(routeState._root);
3267 return rxjs.of(routeState);
3268 }
3269 catch (e) {
3270 return new rxjs.Observable(function (obs) { return obs.error(e); });
3271 }
3272 };
3273 Recognizer.prototype.inheritParamsAndData = function (routeNode) {
3274 var _this = this;
3275 var route = routeNode.value;
3276 var i = inheritedParamsDataResolve(route, this.paramsInheritanceStrategy);
3277 route.params = Object.freeze(i.params);
3278 route.data = Object.freeze(i.data);
3279 routeNode.children.forEach(function (n) { return _this.inheritParamsAndData(n); });
3280 };
3281 Recognizer.prototype.processSegmentGroup = function (config, segmentGroup, outlet) {
3282 if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
3283 return this.processChildren(config, segmentGroup);
3284 }
3285 return this.processSegment(config, segmentGroup, segmentGroup.segments, outlet);
3286 };
3287 Recognizer.prototype.processChildren = function (config, segmentGroup) {
3288 var _this = this;
3289 var children = mapChildrenIntoArray(segmentGroup, function (child, childOutlet) { return _this.processSegmentGroup(config, child, childOutlet); });
3290 checkOutletNameUniqueness(children);
3291 sortActivatedRouteSnapshots(children);
3292 return children;
3293 };
3294 Recognizer.prototype.processSegment = function (config, segmentGroup, segments, outlet) {
3295 var e_1, _a;
3296 try {
3297 for (var config_1 = __values(config), config_1_1 = config_1.next(); !config_1_1.done; config_1_1 = config_1.next()) {
3298 var r = config_1_1.value;
3299 try {
3300 return this.processSegmentAgainstRoute(r, segmentGroup, segments, outlet);
3301 }
3302 catch (e) {
3303 if (!(e instanceof NoMatch$1))
3304 throw e;
3305 }
3306 }
3307 }
3308 catch (e_1_1) { e_1 = { error: e_1_1 }; }
3309 finally {
3310 try {
3311 if (config_1_1 && !config_1_1.done && (_a = config_1.return)) _a.call(config_1);
3312 }
3313 finally { if (e_1) throw e_1.error; }
3314 }
3315 if (this.noLeftoversInUrl(segmentGroup, segments, outlet)) {
3316 return [];
3317 }
3318 throw new NoMatch$1();
3319 };
3320 Recognizer.prototype.noLeftoversInUrl = function (segmentGroup, segments, outlet) {
3321 return segments.length === 0 && !segmentGroup.children[outlet];
3322 };
3323 Recognizer.prototype.processSegmentAgainstRoute = function (route, rawSegment, segments, outlet) {
3324 if (route.redirectTo)
3325 throw new NoMatch$1();
3326 if ((route.outlet || PRIMARY_OUTLET) !== outlet)
3327 throw new NoMatch$1();
3328 var snapshot;
3329 var consumedSegments = [];
3330 var rawSlicedSegments = [];
3331 if (route.path === '**') {
3332 var params = segments.length > 0 ? last(segments).parameters : {};
3333 snapshot = new ActivatedRouteSnapshot(segments, params, Object.freeze(__assign({}, this.urlTree.queryParams)), this.urlTree.fragment, getData(route), outlet, route.component, route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + segments.length, getResolve(route));
3334 }
3335 else {
3336 var result = match$1(rawSegment, route, segments);
3337 consumedSegments = result.consumedSegments;
3338 rawSlicedSegments = segments.slice(result.lastChild);
3339 snapshot = new ActivatedRouteSnapshot(consumedSegments, result.parameters, Object.freeze(__assign({}, this.urlTree.queryParams)), this.urlTree.fragment, getData(route), outlet, route.component, route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + consumedSegments.length, getResolve(route));
3340 }
3341 var childConfig = getChildConfig(route);
3342 var _a = split$1(rawSegment, consumedSegments, rawSlicedSegments, childConfig, this.relativeLinkResolution), segmentGroup = _a.segmentGroup, slicedSegments = _a.slicedSegments;
3343 if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
3344 var children_1 = this.processChildren(childConfig, segmentGroup);
3345 return [new TreeNode(snapshot, children_1)];
3346 }
3347 if (childConfig.length === 0 && slicedSegments.length === 0) {
3348 return [new TreeNode(snapshot, [])];
3349 }
3350 var children = this.processSegment(childConfig, segmentGroup, slicedSegments, PRIMARY_OUTLET);
3351 return [new TreeNode(snapshot, children)];
3352 };
3353 return Recognizer;
3354 }());
3355 function sortActivatedRouteSnapshots(nodes) {
3356 nodes.sort(function (a, b) {
3357 if (a.value.outlet === PRIMARY_OUTLET)
3358 return -1;
3359 if (b.value.outlet === PRIMARY_OUTLET)
3360 return 1;
3361 return a.value.outlet.localeCompare(b.value.outlet);
3362 });
3363 }
3364 function getChildConfig(route) {
3365 if (route.children) {
3366 return route.children;
3367 }
3368 if (route.loadChildren) {
3369 return route._loadedConfig.routes;
3370 }
3371 return [];
3372 }
3373 function match$1(segmentGroup, route, segments) {
3374 if (route.path === '') {
3375 if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) {
3376 throw new NoMatch$1();
3377 }
3378 return { consumedSegments: [], lastChild: 0, parameters: {} };
3379 }
3380 var matcher = route.matcher || defaultUrlMatcher;
3381 var res = matcher(segments, segmentGroup, route);
3382 if (!res)
3383 throw new NoMatch$1();
3384 var posParams = {};
3385 forEach(res.posParams, function (v, k) { posParams[k] = v.path; });
3386 var parameters = res.consumed.length > 0 ? __assign({}, posParams, res.consumed[res.consumed.length - 1].parameters) :
3387 posParams;
3388 return { consumedSegments: res.consumed, lastChild: res.consumed.length, parameters: parameters };
3389 }
3390 function checkOutletNameUniqueness(nodes) {
3391 var names = {};
3392 nodes.forEach(function (n) {
3393 var routeWithSameOutletName = names[n.value.outlet];
3394 if (routeWithSameOutletName) {
3395 var p = routeWithSameOutletName.url.map(function (s) { return s.toString(); }).join('/');
3396 var c = n.value.url.map(function (s) { return s.toString(); }).join('/');
3397 throw new Error("Two segments cannot have the same outlet name: '" + p + "' and '" + c + "'.");
3398 }
3399 names[n.value.outlet] = n.value;
3400 });
3401 }
3402 function getSourceSegmentGroup(segmentGroup) {
3403 var s = segmentGroup;
3404 while (s._sourceSegment) {
3405 s = s._sourceSegment;
3406 }
3407 return s;
3408 }
3409 function getPathIndexShift(segmentGroup) {
3410 var s = segmentGroup;
3411 var res = (s._segmentIndexShift ? s._segmentIndexShift : 0);
3412 while (s._sourceSegment) {
3413 s = s._sourceSegment;
3414 res += (s._segmentIndexShift ? s._segmentIndexShift : 0);
3415 }
3416 return res - 1;
3417 }
3418 function split$1(segmentGroup, consumedSegments, slicedSegments, config, relativeLinkResolution) {
3419 if (slicedSegments.length > 0 &&
3420 containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, config)) {
3421 var s_1 = new UrlSegmentGroup(consumedSegments, createChildrenForEmptyPaths(segmentGroup, consumedSegments, config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
3422 s_1._sourceSegment = segmentGroup;
3423 s_1._segmentIndexShift = consumedSegments.length;
3424 return { segmentGroup: s_1, slicedSegments: [] };
3425 }
3426 if (slicedSegments.length === 0 &&
3427 containsEmptyPathMatches(segmentGroup, slicedSegments, config)) {
3428 var s_2 = new UrlSegmentGroup(segmentGroup.segments, addEmptyPathsToChildrenIfNeeded(segmentGroup, consumedSegments, slicedSegments, config, segmentGroup.children, relativeLinkResolution));
3429 s_2._sourceSegment = segmentGroup;
3430 s_2._segmentIndexShift = consumedSegments.length;
3431 return { segmentGroup: s_2, slicedSegments: slicedSegments };
3432 }
3433 var s = new UrlSegmentGroup(segmentGroup.segments, segmentGroup.children);
3434 s._sourceSegment = segmentGroup;
3435 s._segmentIndexShift = consumedSegments.length;
3436 return { segmentGroup: s, slicedSegments: slicedSegments };
3437 }
3438 function addEmptyPathsToChildrenIfNeeded(segmentGroup, consumedSegments, slicedSegments, routes, children, relativeLinkResolution) {
3439 var e_2, _a;
3440 var res = {};
3441 try {
3442 for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
3443 var r = routes_1_1.value;
3444 if (emptyPathMatch(segmentGroup, slicedSegments, r) && !children[getOutlet$1(r)]) {
3445 var s = new UrlSegmentGroup([], {});
3446 s._sourceSegment = segmentGroup;
3447 if (relativeLinkResolution === 'legacy') {
3448 s._segmentIndexShift = segmentGroup.segments.length;
3449 }
3450 else {
3451 s._segmentIndexShift = consumedSegments.length;
3452 }
3453 res[getOutlet$1(r)] = s;
3454 }
3455 }
3456 }
3457 catch (e_2_1) { e_2 = { error: e_2_1 }; }
3458 finally {
3459 try {
3460 if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
3461 }
3462 finally { if (e_2) throw e_2.error; }
3463 }
3464 return __assign({}, children, res);
3465 }
3466 function createChildrenForEmptyPaths(segmentGroup, consumedSegments, routes, primarySegment) {
3467 var e_3, _a;
3468 var res = {};
3469 res[PRIMARY_OUTLET] = primarySegment;
3470 primarySegment._sourceSegment = segmentGroup;
3471 primarySegment._segmentIndexShift = consumedSegments.length;
3472 try {
3473 for (var routes_2 = __values(routes), routes_2_1 = routes_2.next(); !routes_2_1.done; routes_2_1 = routes_2.next()) {
3474 var r = routes_2_1.value;
3475 if (r.path === '' && getOutlet$1(r) !== PRIMARY_OUTLET) {
3476 var s = new UrlSegmentGroup([], {});
3477 s._sourceSegment = segmentGroup;
3478 s._segmentIndexShift = consumedSegments.length;
3479 res[getOutlet$1(r)] = s;
3480 }
3481 }
3482 }
3483 catch (e_3_1) { e_3 = { error: e_3_1 }; }
3484 finally {
3485 try {
3486 if (routes_2_1 && !routes_2_1.done && (_a = routes_2.return)) _a.call(routes_2);
3487 }
3488 finally { if (e_3) throw e_3.error; }
3489 }
3490 return res;
3491 }
3492 function containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, routes) {
3493 return routes.some(function (r) { return emptyPathMatch(segmentGroup, slicedSegments, r) && getOutlet$1(r) !== PRIMARY_OUTLET; });
3494 }
3495 function containsEmptyPathMatches(segmentGroup, slicedSegments, routes) {
3496 return routes.some(function (r) { return emptyPathMatch(segmentGroup, slicedSegments, r); });
3497 }
3498 function emptyPathMatch(segmentGroup, slicedSegments, r) {
3499 if ((segmentGroup.hasChildren() || slicedSegments.length > 0) && r.pathMatch === 'full') {
3500 return false;
3501 }
3502 return r.path === '' && r.redirectTo === undefined;
3503 }
3504 function getOutlet$1(route) {
3505 return route.outlet || PRIMARY_OUTLET;
3506 }
3507 function getData(route) {
3508 return route.data || {};
3509 }
3510 function getResolve(route) {
3511 return route.resolve || {};
3512 }
3513
3514 /**
3515 * @license
3516 * Copyright Google Inc. All Rights Reserved.
3517 *
3518 * Use of this source code is governed by an MIT-style license that can be
3519 * found in the LICENSE file at https://angular.io/license
3520 */
3521 function recognize$1(rootComponentType, config, serializer, paramsInheritanceStrategy, relativeLinkResolution) {
3522 return function (source) {
3523 return source.pipe(operators.mergeMap(function (t) { return recognize(rootComponentType, config, t.urlAfterRedirects, serializer(t.urlAfterRedirects), paramsInheritanceStrategy, relativeLinkResolution)
3524 .pipe(operators.map(function (targetSnapshot) { return (__assign({}, t, { targetSnapshot: targetSnapshot })); })); }));
3525 };
3526 }
3527
3528 /**
3529 * @license
3530 * Copyright Google Inc. All Rights Reserved.
3531 *
3532 * Use of this source code is governed by an MIT-style license that can be
3533 * found in the LICENSE file at https://angular.io/license
3534 */
3535 function resolveData(paramsInheritanceStrategy, moduleInjector) {
3536 return function (source) {
3537 return source.pipe(operators.mergeMap(function (t) {
3538 var targetSnapshot = t.targetSnapshot, canActivateChecks = t.guards.canActivateChecks;
3539 if (!canActivateChecks.length) {
3540 return rxjs.of(t);
3541 }
3542 return rxjs.from(canActivateChecks)
3543 .pipe(operators.concatMap(function (check) { return runResolve(check.route, targetSnapshot, paramsInheritanceStrategy, moduleInjector); }), operators.reduce(function (_, __) { return _; }), operators.map(function (_) { return t; }));
3544 }));
3545 };
3546 }
3547 function runResolve(futureARS, futureRSS, paramsInheritanceStrategy, moduleInjector) {
3548 var resolve = futureARS._resolve;
3549 return resolveNode(resolve, futureARS, futureRSS, moduleInjector)
3550 .pipe(operators.map(function (resolvedData) {
3551 futureARS._resolvedData = resolvedData;
3552 futureARS.data = __assign({}, futureARS.data, inheritedParamsDataResolve(futureARS, paramsInheritanceStrategy).resolve);
3553 return null;
3554 }));
3555 }
3556 function resolveNode(resolve, futureARS, futureRSS, moduleInjector) {
3557 var keys = Object.keys(resolve);
3558 if (keys.length === 0) {
3559 return rxjs.of({});
3560 }
3561 if (keys.length === 1) {
3562 var key_1 = keys[0];
3563 return getResolver(resolve[key_1], futureARS, futureRSS, moduleInjector)
3564 .pipe(operators.map(function (value) {
3565 var _a;
3566 return _a = {}, _a[key_1] = value, _a;
3567 }));
3568 }
3569 var data = {};
3570 var runningResolvers$ = rxjs.from(keys).pipe(operators.mergeMap(function (key) {
3571 return getResolver(resolve[key], futureARS, futureRSS, moduleInjector)
3572 .pipe(operators.map(function (value) {
3573 data[key] = value;
3574 return value;
3575 }));
3576 }));
3577 return runningResolvers$.pipe(operators.last(), operators.map(function () { return data; }));
3578 }
3579 function getResolver(injectionToken, futureARS, futureRSS, moduleInjector) {
3580 var resolver = getToken(injectionToken, futureARS, moduleInjector);
3581 return resolver.resolve ? wrapIntoObservable(resolver.resolve(futureARS, futureRSS)) :
3582 wrapIntoObservable(resolver(futureARS, futureRSS));
3583 }
3584
3585 /**
3586 * @license
3587 * Copyright Google Inc. All Rights Reserved.
3588 *
3589 * Use of this source code is governed by an MIT-style license that can be
3590 * found in the LICENSE file at https://angular.io/license
3591 */
3592 /**
3593 * Perform a side effect through a switchMap for every emission on the source Observable,
3594 * but return an Observable that is identical to the source. It's essentially the same as
3595 * the `tap` operator, but if the side effectful `next` function returns an ObservableInput,
3596 * it will wait before continuing with the original value.
3597 */
3598 function switchTap(next) {
3599 return function (source) {
3600 return source.pipe(operators.switchMap(function (v) {
3601 var nextResult = next(v);
3602 if (nextResult) {
3603 return rxjs.from(nextResult).pipe(operators.map(function () { return v; }));
3604 }
3605 return rxjs.from([v]);
3606 }));
3607 };
3608 }
3609
3610 /**
3611 * @license
3612 * Copyright Google Inc. All Rights Reserved.
3613 *
3614 * Use of this source code is governed by an MIT-style license that can be
3615 * found in the LICENSE file at https://angular.io/license
3616 */
3617 /**
3618 * @description
3619 *
3620 * Provides a way to customize when activated routes get reused.
3621 *
3622 * @publicApi
3623 */
3624 var RouteReuseStrategy = /** @class */ (function () {
3625 function RouteReuseStrategy() {
3626 }
3627 return RouteReuseStrategy;
3628 }());
3629 /**
3630 * Does not detach any subtrees. Reuses routes as long as their route config is the same.
3631 */
3632 var DefaultRouteReuseStrategy = /** @class */ (function () {
3633 function DefaultRouteReuseStrategy() {
3634 }
3635 DefaultRouteReuseStrategy.prototype.shouldDetach = function (route) { return false; };
3636 DefaultRouteReuseStrategy.prototype.store = function (route, detachedTree) { };
3637 DefaultRouteReuseStrategy.prototype.shouldAttach = function (route) { return false; };
3638 DefaultRouteReuseStrategy.prototype.retrieve = function (route) { return null; };
3639 DefaultRouteReuseStrategy.prototype.shouldReuseRoute = function (future, curr) {
3640 return future.routeConfig === curr.routeConfig;
3641 };
3642 return DefaultRouteReuseStrategy;
3643 }());
3644
3645 /**
3646 * @license
3647 * Copyright Google Inc. All Rights Reserved.
3648 *
3649 * Use of this source code is governed by an MIT-style license that can be
3650 * found in the LICENSE file at https://angular.io/license
3651 */
3652 /**
3653 * The [DI token](guide/glossary/#di-token) for a router configuration.
3654 * @see `ROUTES`
3655 * @publicApi
3656 */
3657 var ROUTES = new core.InjectionToken('ROUTES');
3658 var RouterConfigLoader = /** @class */ (function () {
3659 function RouterConfigLoader(loader, compiler, onLoadStartListener, onLoadEndListener) {
3660 this.loader = loader;
3661 this.compiler = compiler;
3662 this.onLoadStartListener = onLoadStartListener;
3663 this.onLoadEndListener = onLoadEndListener;
3664 }
3665 RouterConfigLoader.prototype.load = function (parentInjector, route) {
3666 var _this = this;
3667 if (this.onLoadStartListener) {
3668 this.onLoadStartListener(route);
3669 }
3670 var moduleFactory$ = this.loadModuleFactory(route.loadChildren);
3671 return moduleFactory$.pipe(operators.map(function (factory) {
3672 if (_this.onLoadEndListener) {
3673 _this.onLoadEndListener(route);
3674 }
3675 var module = factory.create(parentInjector);
3676 return new LoadedRouterConfig(flatten(module.injector.get(ROUTES)).map(standardizeConfig), module);
3677 }));
3678 };
3679 RouterConfigLoader.prototype.loadModuleFactory = function (loadChildren) {
3680 var _this = this;
3681 if (typeof loadChildren === 'string') {
3682 return rxjs.from(this.loader.load(loadChildren));
3683 }
3684 else {
3685 return wrapIntoObservable(loadChildren()).pipe(operators.mergeMap(function (t) {
3686 if (t instanceof core.NgModuleFactory) {
3687 return rxjs.of(t);
3688 }
3689 else {
3690 return rxjs.from(_this.compiler.compileModuleAsync(t));
3691 }
3692 }));
3693 }
3694 };
3695 return RouterConfigLoader;
3696 }());
3697
3698 /**
3699 * @license
3700 * Copyright Google Inc. All Rights Reserved.
3701 *
3702 * Use of this source code is governed by an MIT-style license that can be
3703 * found in the LICENSE file at https://angular.io/license
3704 */
3705 /**
3706 * @description
3707 *
3708 * Provides a way to migrate AngularJS applications to Angular.
3709 *
3710 * @publicApi
3711 */
3712 var UrlHandlingStrategy = /** @class */ (function () {
3713 function UrlHandlingStrategy() {
3714 }
3715 return UrlHandlingStrategy;
3716 }());
3717 /**
3718 * @publicApi
3719 */
3720 var DefaultUrlHandlingStrategy = /** @class */ (function () {
3721 function DefaultUrlHandlingStrategy() {
3722 }
3723 DefaultUrlHandlingStrategy.prototype.shouldProcessUrl = function (url) { return true; };
3724 DefaultUrlHandlingStrategy.prototype.extract = function (url) { return url; };
3725 DefaultUrlHandlingStrategy.prototype.merge = function (newUrlPart, wholeUrl) { return newUrlPart; };
3726 return DefaultUrlHandlingStrategy;
3727 }());
3728
3729 /**
3730 * @license
3731 * Copyright Google Inc. All Rights Reserved.
3732 *
3733 * Use of this source code is governed by an MIT-style license that can be
3734 * found in the LICENSE file at https://angular.io/license
3735 */
3736 function defaultErrorHandler(error) {
3737 throw error;
3738 }
3739 function defaultMalformedUriErrorHandler(error, urlSerializer, url) {
3740 return urlSerializer.parse('/');
3741 }
3742 /**
3743 * @internal
3744 */
3745 function defaultRouterHook(snapshot, runExtras) {
3746 return rxjs.of(null);
3747 }
3748 /**
3749 * @description
3750 *
3751 * An NgModule that provides navigation and URL manipulation capabilities.
3752 *
3753 * @see `Route`.
3754 * @see [Routing and Navigation Guide](guide/router).
3755 *
3756 * @ngModule RouterModule
3757 *
3758 * @publicApi
3759 */
3760 var Router = /** @class */ (function () {
3761 /**
3762 * Creates the router service.
3763 */
3764 // TODO: vsavkin make internal after the final is out.
3765 function Router(rootComponentType, urlSerializer, rootContexts, location, injector, loader, compiler, config) {
3766 var _this = this;
3767 this.rootComponentType = rootComponentType;
3768 this.urlSerializer = urlSerializer;
3769 this.rootContexts = rootContexts;
3770 this.location = location;
3771 this.config = config;
3772 this.lastSuccessfulNavigation = null;
3773 this.currentNavigation = null;
3774 this.navigationId = 0;
3775 this.isNgZoneEnabled = false;
3776 /**
3777 * An event stream for routing events in this NgModule.
3778 */
3779 this.events = new rxjs.Subject();
3780 /**
3781 * A handler for navigation errors in this NgModule.
3782 */
3783 this.errorHandler = defaultErrorHandler;
3784 /**
3785 * A handler for errors thrown by `Router.parseUrl(url)`
3786 * when `url` contains an invalid character.
3787 * The most common case is a `%` sign
3788 * that's not encoded and is not part of a percent encoded sequence.
3789 */
3790 this.malformedUriErrorHandler = defaultMalformedUriErrorHandler;
3791 /**
3792 * True if at least one navigation event has occurred,
3793 * false otherwise.
3794 */
3795 this.navigated = false;
3796 this.lastSuccessfulId = -1;
3797 /**
3798 * Hooks that enable you to pause navigation,
3799 * either before or after the preactivation phase.
3800 * Used by `RouterModule`.
3801 *
3802 * @internal
3803 */
3804 this.hooks = {
3805 beforePreactivation: defaultRouterHook,
3806 afterPreactivation: defaultRouterHook
3807 };
3808 /**
3809 * A strategy for extracting and merging URLs.
3810 * Used for AngularJS to Angular migrations.
3811 */
3812 this.urlHandlingStrategy = new DefaultUrlHandlingStrategy();
3813 /**
3814 * A strategy for re-using routes.
3815 */
3816 this.routeReuseStrategy = new DefaultRouteReuseStrategy();
3817 /**
3818 * How to handle a navigation request to the current URL. One of:
3819 * - `'ignore'` : The router ignores the request.
3820 * - `'reload'` : The router reloads the URL. Use to implement a "refresh" feature.
3821 */
3822 this.onSameUrlNavigation = 'ignore';
3823 /**
3824 * How to merge parameters, data, and resolved data from parent to child
3825 * routes. One of:
3826 *
3827 * - `'emptyOnly'` : Inherit parent parameters, data, and resolved data
3828 * for path-less or component-less routes.
3829 * - `'always'` : Inherit parent parameters, data, and resolved data
3830 * for all child routes.
3831 */
3832 this.paramsInheritanceStrategy = 'emptyOnly';
3833 /**
3834 * Determines when the router updates the browser URL.
3835 * By default (`"deferred"`), udates the browser URL after navigation has finished.
3836 * Set to `'eager'` to update the browser URL at the beginning of navigation.
3837 * You can choose to update early so that, if navigation fails,
3838 * you can show an error message with the URL that failed.
3839 */
3840 this.urlUpdateStrategy = 'deferred';
3841 /**
3842 * Enables a bug fix that corrects relative link resolution in components with empty paths.
3843 * @see `RouterModule`
3844 */
3845 this.relativeLinkResolution = 'legacy';
3846 var onLoadStart = function (r) { return _this.triggerEvent(new RouteConfigLoadStart(r)); };
3847 var onLoadEnd = function (r) { return _this.triggerEvent(new RouteConfigLoadEnd(r)); };
3848 this.ngModule = injector.get(core.NgModuleRef);
3849 this.console = injector.get(core.ɵConsole);
3850 var ngZone = injector.get(core.NgZone);
3851 this.isNgZoneEnabled = ngZone instanceof core.NgZone;
3852 this.resetConfig(config);
3853 this.currentUrlTree = createEmptyUrlTree();
3854 this.rawUrlTree = this.currentUrlTree;
3855 this.browserUrlTree = this.currentUrlTree;
3856 this.configLoader = new RouterConfigLoader(loader, compiler, onLoadStart, onLoadEnd);
3857 this.routerState = createEmptyState(this.currentUrlTree, this.rootComponentType);
3858 this.transitions = new rxjs.BehaviorSubject({
3859 id: 0,
3860 currentUrlTree: this.currentUrlTree,
3861 currentRawUrl: this.currentUrlTree,
3862 extractedUrl: this.urlHandlingStrategy.extract(this.currentUrlTree),
3863 urlAfterRedirects: this.urlHandlingStrategy.extract(this.currentUrlTree),
3864 rawUrl: this.currentUrlTree,
3865 extras: {},
3866 resolve: null,
3867 reject: null,
3868 promise: Promise.resolve(true),
3869 source: 'imperative',
3870 restoredState: null,
3871 currentSnapshot: this.routerState.snapshot,
3872 targetSnapshot: null,
3873 currentRouterState: this.routerState,
3874 targetRouterState: null,
3875 guards: { canActivateChecks: [], canDeactivateChecks: [] },
3876 guardsResult: null,
3877 });
3878 this.navigations = this.setupNavigations(this.transitions);
3879 this.processNavigations();
3880 }
3881 Router.prototype.setupNavigations = function (transitions) {
3882 var _this = this;
3883 var eventsSubject = this.events;
3884 return transitions.pipe(operators.filter(function (t) { return t.id !== 0; }),
3885 // Extract URL
3886 operators.map(function (t) { return (__assign({}, t, { extractedUrl: _this.urlHandlingStrategy.extract(t.rawUrl) })); }),
3887 // Using switchMap so we cancel executing navigations when a new one comes in
3888 operators.switchMap(function (t) {
3889 var completed = false;
3890 var errored = false;
3891 return rxjs.of(t).pipe(
3892 // Store the Navigation object
3893 operators.tap(function (t) {
3894 _this.currentNavigation = {
3895 id: t.id,
3896 initialUrl: t.currentRawUrl,
3897 extractedUrl: t.extractedUrl,
3898 trigger: t.source,
3899 extras: t.extras,
3900 previousNavigation: _this.lastSuccessfulNavigation ? __assign({}, _this.lastSuccessfulNavigation, { previousNavigation: null }) :
3901 null
3902 };
3903 }), operators.switchMap(function (t) {
3904 var urlTransition = !_this.navigated || t.extractedUrl.toString() !== _this.browserUrlTree.toString();
3905 var processCurrentUrl = (_this.onSameUrlNavigation === 'reload' ? true : urlTransition) &&
3906 _this.urlHandlingStrategy.shouldProcessUrl(t.rawUrl);
3907 if (processCurrentUrl) {
3908 return rxjs.of(t).pipe(
3909 // Fire NavigationStart event
3910 operators.switchMap(function (t) {
3911 var transition = _this.transitions.getValue();
3912 eventsSubject.next(new NavigationStart(t.id, _this.serializeUrl(t.extractedUrl), t.source, t.restoredState));
3913 if (transition !== _this.transitions.getValue()) {
3914 return rxjs.EMPTY;
3915 }
3916 return [t];
3917 }),
3918 // This delay is required to match old behavior that forced navigation to
3919 // always be async
3920 operators.switchMap(function (t) { return Promise.resolve(t); }),
3921 // ApplyRedirects
3922 applyRedirects$1(_this.ngModule.injector, _this.configLoader, _this.urlSerializer, _this.config),
3923 // Update the currentNavigation
3924 operators.tap(function (t) {
3925 _this.currentNavigation = __assign({}, _this.currentNavigation, { finalUrl: t.urlAfterRedirects });
3926 }),
3927 // Recognize
3928 recognize$1(_this.rootComponentType, _this.config, function (url) { return _this.serializeUrl(url); }, _this.paramsInheritanceStrategy, _this.relativeLinkResolution),
3929 // Update URL if in `eager` update mode
3930 operators.tap(function (t) {
3931 if (_this.urlUpdateStrategy === 'eager') {
3932 if (!t.extras.skipLocationChange) {
3933 _this.setBrowserUrl(t.urlAfterRedirects, !!t.extras.replaceUrl, t.id, t.extras.state);
3934 }
3935 _this.browserUrlTree = t.urlAfterRedirects;
3936 }
3937 }),
3938 // Fire RoutesRecognized
3939 operators.tap(function (t) {
3940 var routesRecognized = new RoutesRecognized(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot);
3941 eventsSubject.next(routesRecognized);
3942 }));
3943 }
3944 else {
3945 var processPreviousUrl = urlTransition && _this.rawUrlTree &&
3946 _this.urlHandlingStrategy.shouldProcessUrl(_this.rawUrlTree);
3947 /* When the current URL shouldn't be processed, but the previous one was, we
3948 * handle this "error condition" by navigating to the previously successful URL,
3949 * but leaving the URL intact.*/
3950 if (processPreviousUrl) {
3951 var id = t.id, extractedUrl = t.extractedUrl, source = t.source, restoredState = t.restoredState, extras = t.extras;
3952 var navStart = new NavigationStart(id, _this.serializeUrl(extractedUrl), source, restoredState);
3953 eventsSubject.next(navStart);
3954 var targetSnapshot = createEmptyState(extractedUrl, _this.rootComponentType).snapshot;
3955 return rxjs.of(__assign({}, t, { targetSnapshot: targetSnapshot, urlAfterRedirects: extractedUrl, extras: __assign({}, extras, { skipLocationChange: false, replaceUrl: false }) }));
3956 }
3957 else {
3958 /* When neither the current or previous URL can be processed, do nothing other
3959 * than update router's internal reference to the current "settled" URL. This
3960 * way the next navigation will be coming from the current URL in the browser.
3961 */
3962 _this.rawUrlTree = t.rawUrl;
3963 _this.browserUrlTree = t.urlAfterRedirects;
3964 t.resolve(null);
3965 return rxjs.EMPTY;
3966 }
3967 }
3968 }),
3969 // Before Preactivation
3970 switchTap(function (t) {
3971 var targetSnapshot = t.targetSnapshot, navigationId = t.id, appliedUrlTree = t.extractedUrl, rawUrlTree = t.rawUrl, _a = t.extras, skipLocationChange = _a.skipLocationChange, replaceUrl = _a.replaceUrl;
3972 return _this.hooks.beforePreactivation(targetSnapshot, {
3973 navigationId: navigationId,
3974 appliedUrlTree: appliedUrlTree,
3975 rawUrlTree: rawUrlTree,
3976 skipLocationChange: !!skipLocationChange,
3977 replaceUrl: !!replaceUrl,
3978 });
3979 }),
3980 // --- GUARDS ---
3981 operators.tap(function (t) {
3982 var guardsStart = new GuardsCheckStart(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot);
3983 _this.triggerEvent(guardsStart);
3984 }), operators.map(function (t) { return (__assign({}, t, { guards: getAllRouteGuards(t.targetSnapshot, t.currentSnapshot, _this.rootContexts) })); }), checkGuards(_this.ngModule.injector, function (evt) { return _this.triggerEvent(evt); }), operators.tap(function (t) {
3985 if (isUrlTree(t.guardsResult)) {
3986 var error = navigationCancelingError("Redirecting to \"" + _this.serializeUrl(t.guardsResult) + "\"");
3987 error.url = t.guardsResult;
3988 throw error;
3989 }
3990 }), operators.tap(function (t) {
3991 var guardsEnd = new GuardsCheckEnd(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot, !!t.guardsResult);
3992 _this.triggerEvent(guardsEnd);
3993 }), operators.filter(function (t) {
3994 if (!t.guardsResult) {
3995 _this.resetUrlToCurrentUrlTree();
3996 var navCancel = new NavigationCancel(t.id, _this.serializeUrl(t.extractedUrl), '');
3997 eventsSubject.next(navCancel);
3998 t.resolve(false);
3999 return false;
4000 }
4001 return true;
4002 }),
4003 // --- RESOLVE ---
4004 switchTap(function (t) {
4005 if (t.guards.canActivateChecks.length) {
4006 return rxjs.of(t).pipe(operators.tap(function (t) {
4007 var resolveStart = new ResolveStart(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot);
4008 _this.triggerEvent(resolveStart);
4009 }), resolveData(_this.paramsInheritanceStrategy, _this.ngModule.injector), //
4010 operators.tap(function (t) {
4011 var resolveEnd = new ResolveEnd(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot);
4012 _this.triggerEvent(resolveEnd);
4013 }));
4014 }
4015 return undefined;
4016 }),
4017 // --- AFTER PREACTIVATION ---
4018 switchTap(function (t) {
4019 var targetSnapshot = t.targetSnapshot, navigationId = t.id, appliedUrlTree = t.extractedUrl, rawUrlTree = t.rawUrl, _a = t.extras, skipLocationChange = _a.skipLocationChange, replaceUrl = _a.replaceUrl;
4020 return _this.hooks.afterPreactivation(targetSnapshot, {
4021 navigationId: navigationId,
4022 appliedUrlTree: appliedUrlTree,
4023 rawUrlTree: rawUrlTree,
4024 skipLocationChange: !!skipLocationChange,
4025 replaceUrl: !!replaceUrl,
4026 });
4027 }), operators.map(function (t) {
4028 var targetRouterState = createRouterState(_this.routeReuseStrategy, t.targetSnapshot, t.currentRouterState);
4029 return (__assign({}, t, { targetRouterState: targetRouterState }));
4030 }),
4031 /* Once here, we are about to activate syncronously. The assumption is this will
4032 succeed, and user code may read from the Router service. Therefore before
4033 activation, we need to update router properties storing the current URL and the
4034 RouterState, as well as updated the browser URL. All this should happen *before*
4035 activating. */
4036 operators.tap(function (t) {
4037 _this.currentUrlTree = t.urlAfterRedirects;
4038 _this.rawUrlTree = _this.urlHandlingStrategy.merge(_this.currentUrlTree, t.rawUrl);
4039 _this.routerState = t.targetRouterState;
4040 if (_this.urlUpdateStrategy === 'deferred') {
4041 if (!t.extras.skipLocationChange) {
4042 _this.setBrowserUrl(_this.rawUrlTree, !!t.extras.replaceUrl, t.id, t.extras.state);
4043 }
4044 _this.browserUrlTree = t.urlAfterRedirects;
4045 }
4046 }), activateRoutes(_this.rootContexts, _this.routeReuseStrategy, function (evt) { return _this.triggerEvent(evt); }), operators.tap({ next: function () { completed = true; }, complete: function () { completed = true; } }), operators.finalize(function () {
4047 /* When the navigation stream finishes either through error or success, we set the
4048 * `completed` or `errored` flag. However, there are some situations where we could
4049 * get here without either of those being set. For instance, a redirect during
4050 * NavigationStart. Therefore, this is a catch-all to make sure the NavigationCancel
4051 * event is fired when a navigation gets cancelled but not caught by other means. */
4052 if (!completed && !errored) {
4053 // Must reset to current URL tree here to ensure history.state is set. On a fresh
4054 // page load, if a new navigation comes in before a successful navigation
4055 // completes, there will be nothing in history.state.navigationId. This can cause
4056 // sync problems with AngularJS sync code which looks for a value here in order
4057 // to determine whether or not to handle a given popstate event or to leave it
4058 // to the Angualr router.
4059 _this.resetUrlToCurrentUrlTree();
4060 var navCancel = new NavigationCancel(t.id, _this.serializeUrl(t.extractedUrl), "Navigation ID " + t.id + " is not equal to the current navigation id " + _this.navigationId);
4061 eventsSubject.next(navCancel);
4062 t.resolve(false);
4063 }
4064 // currentNavigation should always be reset to null here. If navigation was
4065 // successful, lastSuccessfulTransition will have already been set. Therefore we
4066 // can safely set currentNavigation to null here.
4067 _this.currentNavigation = null;
4068 }), operators.catchError(function (e) {
4069 errored = true;
4070 /* This error type is issued during Redirect, and is handled as a cancellation
4071 * rather than an error. */
4072 if (isNavigationCancelingError(e)) {
4073 var redirecting = isUrlTree(e.url);
4074 if (!redirecting) {
4075 // Set property only if we're not redirecting. If we landed on a page and
4076 // redirect to `/` route, the new navigation is going to see the `/` isn't
4077 // a change from the default currentUrlTree and won't navigate. This is
4078 // only applicable with initial navigation, so setting `navigated` only when
4079 // not redirecting resolves this scenario.
4080 _this.navigated = true;
4081 _this.resetStateAndUrl(t.currentRouterState, t.currentUrlTree, t.rawUrl);
4082 }
4083 var navCancel = new NavigationCancel(t.id, _this.serializeUrl(t.extractedUrl), e.message);
4084 eventsSubject.next(navCancel);
4085 t.resolve(false);
4086 if (redirecting) {
4087 _this.navigateByUrl(e.url);
4088 }
4089 /* All other errors should reset to the router's internal URL reference to the
4090 * pre-error state. */
4091 }
4092 else {
4093 _this.resetStateAndUrl(t.currentRouterState, t.currentUrlTree, t.rawUrl);
4094 var navError = new NavigationError(t.id, _this.serializeUrl(t.extractedUrl), e);
4095 eventsSubject.next(navError);
4096 try {
4097 t.resolve(_this.errorHandler(e));
4098 }
4099 catch (ee) {
4100 t.reject(ee);
4101 }
4102 }
4103 return rxjs.EMPTY;
4104 }));
4105 // TODO(jasonaden): remove cast once g3 is on updated TypeScript
4106 }));
4107 };
4108 /**
4109 * @internal
4110 * TODO: this should be removed once the constructor of the router made internal
4111 */
4112 Router.prototype.resetRootComponentType = function (rootComponentType) {
4113 this.rootComponentType = rootComponentType;
4114 // TODO: vsavkin router 4.0 should make the root component set to null
4115 // this will simplify the lifecycle of the router.
4116 this.routerState.root.component = this.rootComponentType;
4117 };
4118 Router.prototype.getTransition = function () {
4119 var transition = this.transitions.value;
4120 // This value needs to be set. Other values such as extractedUrl are set on initial navigation
4121 // but the urlAfterRedirects may not get set if we aren't processing the new URL *and* not
4122 // processing the previous URL.
4123 transition.urlAfterRedirects = this.browserUrlTree;
4124 return transition;
4125 };
4126 Router.prototype.setTransition = function (t) {
4127 this.transitions.next(__assign({}, this.getTransition(), t));
4128 };
4129 /**
4130 * Sets up the location change listener and performs the initial navigation.
4131 */
4132 Router.prototype.initialNavigation = function () {
4133 this.setUpLocationChangeListener();
4134 if (this.navigationId === 0) {
4135 this.navigateByUrl(this.location.path(true), { replaceUrl: true });
4136 }
4137 };
4138 /**
4139 * Sets up the location change listener.
4140 */
4141 Router.prototype.setUpLocationChangeListener = function () {
4142 var _this = this;
4143 // Don't need to use Zone.wrap any more, because zone.js
4144 // already patch onPopState, so location change callback will
4145 // run into ngZone
4146 if (!this.locationSubscription) {
4147 this.locationSubscription = this.location.subscribe(function (change) {
4148 var rawUrlTree = _this.parseUrl(change['url']);
4149 var source = change['type'] === 'popstate' ? 'popstate' : 'hashchange';
4150 // Navigations coming from Angular router have a navigationId state property. When this
4151 // exists, restore the state.
4152 var state = change.state && change.state.navigationId ? change.state : null;
4153 setTimeout(function () { _this.scheduleNavigation(rawUrlTree, source, state, { replaceUrl: true }); }, 0);
4154 });
4155 }
4156 };
4157 Object.defineProperty(Router.prototype, "url", {
4158 /** The current URL. */
4159 get: function () { return this.serializeUrl(this.currentUrlTree); },
4160 enumerable: true,
4161 configurable: true
4162 });
4163 /** The current Navigation object if one exists */
4164 Router.prototype.getCurrentNavigation = function () { return this.currentNavigation; };
4165 /** @internal */
4166 Router.prototype.triggerEvent = function (event) { this.events.next(event); };
4167 /**
4168 * Resets the configuration used for navigation and generating links.
4169 *
4170 * @param config The route array for the new configuration.
4171 *
4172 * @usageNotes
4173 *
4174 * ```
4175 * router.resetConfig([
4176 * { path: 'team/:id', component: TeamCmp, children: [
4177 * { path: 'simple', component: SimpleCmp },
4178 * { path: 'user/:name', component: UserCmp }
4179 * ]}
4180 * ]);
4181 * ```
4182 */
4183 Router.prototype.resetConfig = function (config) {
4184 validateConfig(config);
4185 this.config = config.map(standardizeConfig);
4186 this.navigated = false;
4187 this.lastSuccessfulId = -1;
4188 };
4189 /** @docsNotRequired */
4190 Router.prototype.ngOnDestroy = function () { this.dispose(); };
4191 /** Disposes of the router. */
4192 Router.prototype.dispose = function () {
4193 if (this.locationSubscription) {
4194 this.locationSubscription.unsubscribe();
4195 this.locationSubscription = null;
4196 }
4197 };
4198 /**
4199 * Applies an array of commands to the current URL tree and creates a new URL tree.
4200 *
4201 * When given an activate route, applies the given commands starting from the route.
4202 * Otherwise, applies the given command starting from the root.
4203 *
4204 * @param commands An array of commands to apply.
4205 * @param navigationExtras Options that control the navigation strategy.
4206 * @returns The new URL tree.
4207 *
4208 * @usageNotes
4209 *
4210 * ```
4211 * // create /team/33/user/11
4212 * router.createUrlTree(['/team', 33, 'user', 11]);
4213 *
4214 * // create /team/33;expand=true/user/11
4215 * router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);
4216 *
4217 * // you can collapse static segments like this (this works only with the first passed-in value):
4218 * router.createUrlTree(['/team/33/user', userId]);
4219 *
4220 * // If the first segment can contain slashes, and you do not want the router to split it,
4221 * // you can do the following:
4222 * router.createUrlTree([{segmentPath: '/one/two'}]);
4223 *
4224 * // create /team/33/(user/11//right:chat)
4225 * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);
4226 *
4227 * // remove the right secondary node
4228 * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
4229 *
4230 * // assuming the current url is `/team/33/user/11` and the route points to `user/11`
4231 *
4232 * // navigate to /team/33/user/11/details
4233 * router.createUrlTree(['details'], {relativeTo: route});
4234 *
4235 * // navigate to /team/33/user/22
4236 * router.createUrlTree(['../22'], {relativeTo: route});
4237 *
4238 * // navigate to /team/44/user/22
4239 * router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});
4240 * ```
4241 */
4242 Router.prototype.createUrlTree = function (commands, navigationExtras) {
4243 if (navigationExtras === void 0) { navigationExtras = {}; }
4244 var relativeTo = navigationExtras.relativeTo, queryParams = navigationExtras.queryParams, fragment = navigationExtras.fragment, preserveQueryParams = navigationExtras.preserveQueryParams, queryParamsHandling = navigationExtras.queryParamsHandling, preserveFragment = navigationExtras.preserveFragment;
4245 if (core.isDevMode() && preserveQueryParams && console && console.warn) {
4246 console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.');
4247 }
4248 var a = relativeTo || this.routerState.root;
4249 var f = preserveFragment ? this.currentUrlTree.fragment : fragment;
4250 var q = null;
4251 if (queryParamsHandling) {
4252 switch (queryParamsHandling) {
4253 case 'merge':
4254 q = __assign({}, this.currentUrlTree.queryParams, queryParams);
4255 break;
4256 case 'preserve':
4257 q = this.currentUrlTree.queryParams;
4258 break;
4259 default:
4260 q = queryParams || null;
4261 }
4262 }
4263 else {
4264 q = preserveQueryParams ? this.currentUrlTree.queryParams : queryParams || null;
4265 }
4266 if (q !== null) {
4267 q = this.removeEmptyProps(q);
4268 }
4269 return createUrlTree(a, this.currentUrlTree, commands, q, f);
4270 };
4271 /**
4272 * Navigate based on the provided URL, which must be absolute.
4273 *
4274 * @param url An absolute URL. The function does not apply any delta to the current URL.
4275 * @param extras An object containing properties that modify the navigation strategy.
4276 * The function ignores any properties in the `NavigationExtras` that would change the
4277 * provided URL.
4278 *
4279 * @returns A Promise that resolves to 'true' when navigation succeeds,
4280 * to 'false' when navigation fails, or is rejected on error.
4281 *
4282 * @usageNotes
4283 *
4284 * ```
4285 * router.navigateByUrl("/team/33/user/11");
4286 *
4287 * // Navigate without updating the URL
4288 * router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
4289 * ```
4290 *
4291 */
4292 Router.prototype.navigateByUrl = function (url, extras) {
4293 if (extras === void 0) { extras = { skipLocationChange: false }; }
4294 if (core.isDevMode() && this.isNgZoneEnabled && !core.NgZone.isInAngularZone()) {
4295 this.console.warn("Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?");
4296 }
4297 var urlTree = isUrlTree(url) ? url : this.parseUrl(url);
4298 var mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree);
4299 return this.scheduleNavigation(mergedTree, 'imperative', null, extras);
4300 };
4301 /**
4302 * Navigate based on the provided array of commands and a starting point.
4303 * If no starting route is provided, the navigation is absolute.
4304 *
4305 * Returns a promise that:
4306 * - resolves to 'true' when navigation succeeds,
4307 * - resolves to 'false' when navigation fails,
4308 * - is rejected when an error happens.
4309 *
4310 * @usageNotes
4311 *
4312 * ```
4313 * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
4314 *
4315 * // Navigate without updating the URL
4316 * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
4317 * ```
4318 *
4319 * The first parameter of `navigate()` is a delta to be applied to the current URL
4320 * or the one provided in the `relativeTo` property of the second parameter (the
4321 * `NavigationExtras`).
4322 *
4323 * In order to affect this browser's `history.state` entry, the `state`
4324 * parameter can be passed. This must be an object because the router
4325 * will add the `navigationId` property to this object before creating
4326 * the new history item.
4327 */
4328 Router.prototype.navigate = function (commands, extras) {
4329 if (extras === void 0) { extras = { skipLocationChange: false }; }
4330 validateCommands(commands);
4331 return this.navigateByUrl(this.createUrlTree(commands, extras), extras);
4332 };
4333 /** Serializes a `UrlTree` into a string */
4334 Router.prototype.serializeUrl = function (url) { return this.urlSerializer.serialize(url); };
4335 /** Parses a string into a `UrlTree` */
4336 Router.prototype.parseUrl = function (url) {
4337 var urlTree;
4338 try {
4339 urlTree = this.urlSerializer.parse(url);
4340 }
4341 catch (e) {
4342 urlTree = this.malformedUriErrorHandler(e, this.urlSerializer, url);
4343 }
4344 return urlTree;
4345 };
4346 /** Returns whether the url is activated */
4347 Router.prototype.isActive = function (url, exact) {
4348 if (isUrlTree(url)) {
4349 return containsTree(this.currentUrlTree, url, exact);
4350 }
4351 var urlTree = this.parseUrl(url);
4352 return containsTree(this.currentUrlTree, urlTree, exact);
4353 };
4354 Router.prototype.removeEmptyProps = function (params) {
4355 return Object.keys(params).reduce(function (result, key) {
4356 var value = params[key];
4357 if (value !== null && value !== undefined) {
4358 result[key] = value;
4359 }
4360 return result;
4361 }, {});
4362 };
4363 Router.prototype.processNavigations = function () {
4364 var _this = this;
4365 this.navigations.subscribe(function (t) {
4366 _this.navigated = true;
4367 _this.lastSuccessfulId = t.id;
4368 _this.events
4369 .next(new NavigationEnd(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(_this.currentUrlTree)));
4370 _this.lastSuccessfulNavigation = _this.currentNavigation;
4371 _this.currentNavigation = null;
4372 t.resolve(true);
4373 }, function (e) { _this.console.warn("Unhandled Navigation Error: "); });
4374 };
4375 Router.prototype.scheduleNavigation = function (rawUrl, source, restoredState, extras) {
4376 var lastNavigation = this.getTransition();
4377 // If the user triggers a navigation imperatively (e.g., by using navigateByUrl),
4378 // and that navigation results in 'replaceState' that leads to the same URL,
4379 // we should skip those.
4380 if (lastNavigation && source !== 'imperative' && lastNavigation.source === 'imperative' &&
4381 lastNavigation.rawUrl.toString() === rawUrl.toString()) {
4382 return Promise.resolve(true); // return value is not used
4383 }
4384 // Because of a bug in IE and Edge, the location class fires two events (popstate and
4385 // hashchange) every single time. The second one should be ignored. Otherwise, the URL will
4386 // flicker. Handles the case when a popstate was emitted first.
4387 if (lastNavigation && source == 'hashchange' && lastNavigation.source === 'popstate' &&
4388 lastNavigation.rawUrl.toString() === rawUrl.toString()) {
4389 return Promise.resolve(true); // return value is not used
4390 }
4391 // Because of a bug in IE and Edge, the location class fires two events (popstate and
4392 // hashchange) every single time. The second one should be ignored. Otherwise, the URL will
4393 // flicker. Handles the case when a hashchange was emitted first.
4394 if (lastNavigation && source == 'popstate' && lastNavigation.source === 'hashchange' &&
4395 lastNavigation.rawUrl.toString() === rawUrl.toString()) {
4396 return Promise.resolve(true); // return value is not used
4397 }
4398 var resolve = null;
4399 var reject = null;
4400 var promise = new Promise(function (res, rej) {
4401 resolve = res;
4402 reject = rej;
4403 });
4404 var id = ++this.navigationId;
4405 this.setTransition({
4406 id: id,
4407 source: source,
4408 restoredState: restoredState,
4409 currentUrlTree: this.currentUrlTree,
4410 currentRawUrl: this.rawUrlTree, rawUrl: rawUrl, extras: extras, resolve: resolve, reject: reject, promise: promise,
4411 currentSnapshot: this.routerState.snapshot,
4412 currentRouterState: this.routerState
4413 });
4414 // Make sure that the error is propagated even though `processNavigations` catch
4415 // handler does not rethrow
4416 return promise.catch(function (e) { return Promise.reject(e); });
4417 };
4418 Router.prototype.setBrowserUrl = function (url, replaceUrl, id, state) {
4419 var path = this.urlSerializer.serialize(url);
4420 state = state || {};
4421 if (this.location.isCurrentPathEqualTo(path) || replaceUrl) {
4422 // TODO(jasonaden): Remove first `navigationId` and rely on `ng` namespace.
4423 this.location.replaceState(path, '', __assign({}, state, { navigationId: id }));
4424 }
4425 else {
4426 this.location.go(path, '', __assign({}, state, { navigationId: id }));
4427 }
4428 };
4429 Router.prototype.resetStateAndUrl = function (storedState, storedUrl, rawUrl) {
4430 this.routerState = storedState;
4431 this.currentUrlTree = storedUrl;
4432 this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, rawUrl);
4433 this.resetUrlToCurrentUrlTree();
4434 };
4435 Router.prototype.resetUrlToCurrentUrlTree = function () {
4436 this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree), '', { navigationId: this.lastSuccessfulId });
4437 };
4438 return Router;
4439 }());
4440 function validateCommands(commands) {
4441 for (var i = 0; i < commands.length; i++) {
4442 var cmd = commands[i];
4443 if (cmd == null) {
4444 throw new Error("The requested path contains " + cmd + " segment at index " + i);
4445 }
4446 }
4447 }
4448
4449 /**
4450 * @license
4451 * Copyright Google Inc. All Rights Reserved.
4452 *
4453 * Use of this source code is governed by an MIT-style license that can be
4454 * found in the LICENSE file at https://angular.io/license
4455 */
4456 /**
4457 * @description
4458 *
4459 * Lets you link to specific routes in your app.
4460 *
4461 * Consider the following route configuration:
4462 * `[{ path: 'user/:name', component: UserCmp }]`.
4463 * When linking to this `user/:name` route, you use the `RouterLink` directive.
4464 *
4465 * If the link is static, you can use the directive as follows:
4466 * `<a routerLink="/user/bob">link to user component</a>`
4467 *
4468 * If you use dynamic values to generate the link, you can pass an array of path
4469 * segments, followed by the params for each segment.
4470 *
4471 * For instance `['/team', teamId, 'user', userName, {details: true}]`
4472 * means that we want to generate a link to `/team/11/user/bob;details=true`.
4473 *
4474 * Multiple static segments can be merged into one
4475 * (e.g., `['/team/11/user', userName, {details: true}]`).
4476 *
4477 * The first segment name can be prepended with `/`, `./`, or `../`:
4478 * * If the first segment begins with `/`, the router will look up the route from the root of the
4479 * app.
4480 * * If the first segment begins with `./`, or doesn't begin with a slash, the router will
4481 * instead look in the children of the current activated route.
4482 * * And if the first segment begins with `../`, the router will go up one level.
4483 *
4484 * You can set query params and fragment as follows:
4485 *
4486 * ```
4487 * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">
4488 * link to user component
4489 * </a>
4490 * ```
4491 * RouterLink will use these to generate this link: `/user/bob#education?debug=true`.
4492 *
4493 * (Deprecated in v4.0.0 use `queryParamsHandling` instead) You can also tell the
4494 * directive to preserve the current query params and fragment:
4495 *
4496 * ```
4497 * <a [routerLink]="['/user/bob']" preserveQueryParams preserveFragment>
4498 * link to user component
4499 * </a>
4500 * ```
4501 *
4502 * You can tell the directive how to handle queryParams. Available options are:
4503 * - `'merge'`: merge the queryParams into the current queryParams
4504 * - `'preserve'`: preserve the current queryParams
4505 * - default/`''`: use the queryParams only
4506 *
4507 * Same options for {@link NavigationExtras#queryParamsHandling
4508 * NavigationExtras#queryParamsHandling}.
4509 *
4510 * ```
4511 * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge">
4512 * link to user component
4513 * </a>
4514 * ```
4515 *
4516 * You can provide a `state` value to be persisted to the browser's History.state
4517 * property (See https://developer.mozilla.org/en-US/docs/Web/API/History#Properties). It's
4518 * used as follows:
4519 *
4520 * ```
4521 * <a [routerLink]="['/user/bob']" [state]="{tracingId: 123}">
4522 * link to user component
4523 * </a>
4524 * ```
4525 *
4526 * And later the value can be read from the router through `router.getCurrentNavigation`.
4527 * For example, to capture the `tracingId` above during the `NavigationStart` event:
4528 *
4529 * ```
4530 * // Get NavigationStart events
4531 * router.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => {
4532 * const navigation = router.getCurrentNavigation();
4533 * tracingService.trace({id: navigation.extras.state.tracingId});
4534 * });
4535 * ```
4536 *
4537 * The router link directive always treats the provided input as a delta to the current url.
4538 *
4539 * For instance, if the current url is `/user/(box//aux:team)`.
4540 *
4541 * Then the following link `<a [routerLink]="['/user/jim']">Jim</a>` will generate the link
4542 * `/user/(jim//aux:team)`.
4543 *
4544 * See {@link Router#createUrlTree createUrlTree} for more information.
4545 *
4546 * @ngModule RouterModule
4547 *
4548 * @publicApi
4549 */
4550 var RouterLink = /** @class */ (function () {
4551 function RouterLink(router, route, tabIndex, renderer, el) {
4552 this.router = router;
4553 this.route = route;
4554 this.commands = [];
4555 if (tabIndex == null) {
4556 renderer.setAttribute(el.nativeElement, 'tabindex', '0');
4557 }
4558 }
4559 Object.defineProperty(RouterLink.prototype, "routerLink", {
4560 set: function (commands) {
4561 if (commands != null) {
4562 this.commands = Array.isArray(commands) ? commands : [commands];
4563 }
4564 else {
4565 this.commands = [];
4566 }
4567 },
4568 enumerable: true,
4569 configurable: true
4570 });
4571 Object.defineProperty(RouterLink.prototype, "preserveQueryParams", {
4572 /**
4573 * @deprecated 4.0.0 use `queryParamsHandling` instead.
4574 */
4575 set: function (value) {
4576 if (core.isDevMode() && console && console.warn) {
4577 console.warn('preserveQueryParams is deprecated!, use queryParamsHandling instead.');
4578 }
4579 this.preserve = value;
4580 },
4581 enumerable: true,
4582 configurable: true
4583 });
4584 RouterLink.prototype.onClick = function () {
4585 var extras = {
4586 skipLocationChange: attrBoolValue(this.skipLocationChange),
4587 replaceUrl: attrBoolValue(this.replaceUrl),
4588 };
4589 this.router.navigateByUrl(this.urlTree, extras);
4590 return true;
4591 };
4592 Object.defineProperty(RouterLink.prototype, "urlTree", {
4593 get: function () {
4594 return this.router.createUrlTree(this.commands, {
4595 relativeTo: this.route,
4596 queryParams: this.queryParams,
4597 fragment: this.fragment,
4598 preserveQueryParams: attrBoolValue(this.preserve),
4599 queryParamsHandling: this.queryParamsHandling,
4600 preserveFragment: attrBoolValue(this.preserveFragment),
4601 });
4602 },
4603 enumerable: true,
4604 configurable: true
4605 });
4606 __decorate([
4607 core.Input(),
4608 __metadata("design:type", Object)
4609 ], RouterLink.prototype, "queryParams", void 0);
4610 __decorate([
4611 core.Input(),
4612 __metadata("design:type", String)
4613 ], RouterLink.prototype, "fragment", void 0);
4614 __decorate([
4615 core.Input(),
4616 __metadata("design:type", String)
4617 ], RouterLink.prototype, "queryParamsHandling", void 0);
4618 __decorate([
4619 core.Input(),
4620 __metadata("design:type", Boolean)
4621 ], RouterLink.prototype, "preserveFragment", void 0);
4622 __decorate([
4623 core.Input(),
4624 __metadata("design:type", Boolean)
4625 ], RouterLink.prototype, "skipLocationChange", void 0);
4626 __decorate([
4627 core.Input(),
4628 __metadata("design:type", Boolean)
4629 ], RouterLink.prototype, "replaceUrl", void 0);
4630 __decorate([
4631 core.Input(),
4632 __metadata("design:type", Object)
4633 ], RouterLink.prototype, "state", void 0);
4634 __decorate([
4635 core.Input(),
4636 __metadata("design:type", Object),
4637 __metadata("design:paramtypes", [Object])
4638 ], RouterLink.prototype, "routerLink", null);
4639 __decorate([
4640 core.Input(),
4641 __metadata("design:type", Boolean),
4642 __metadata("design:paramtypes", [Boolean])
4643 ], RouterLink.prototype, "preserveQueryParams", null);
4644 __decorate([
4645 core.HostListener('click'),
4646 __metadata("design:type", Function),
4647 __metadata("design:paramtypes", []),
4648 __metadata("design:returntype", Boolean)
4649 ], RouterLink.prototype, "onClick", null);
4650 RouterLink = __decorate([
4651 core.Directive({ selector: ':not(a):not(area)[routerLink]' }),
4652 __param(2, core.Attribute('tabindex')),
4653 __metadata("design:paramtypes", [Router, ActivatedRoute, String, core.Renderer2, core.ElementRef])
4654 ], RouterLink);
4655 return RouterLink;
4656 }());
4657 /**
4658 * @description
4659 *
4660 * Lets you link to specific routes in your app.
4661 *
4662 * See `RouterLink` for more information.
4663 *
4664 * @ngModule RouterModule
4665 *
4666 * @publicApi
4667 */
4668 var RouterLinkWithHref = /** @class */ (function () {
4669 function RouterLinkWithHref(router, route, locationStrategy) {
4670 var _this = this;
4671 this.router = router;
4672 this.route = route;
4673 this.locationStrategy = locationStrategy;
4674 this.commands = [];
4675 this.subscription = router.events.subscribe(function (s) {
4676 if (s instanceof NavigationEnd) {
4677 _this.updateTargetUrlAndHref();
4678 }
4679 });
4680 }
4681 Object.defineProperty(RouterLinkWithHref.prototype, "routerLink", {
4682 set: function (commands) {
4683 if (commands != null) {
4684 this.commands = Array.isArray(commands) ? commands : [commands];
4685 }
4686 else {
4687 this.commands = [];
4688 }
4689 },
4690 enumerable: true,
4691 configurable: true
4692 });
4693 Object.defineProperty(RouterLinkWithHref.prototype, "preserveQueryParams", {
4694 set: function (value) {
4695 if (core.isDevMode() && console && console.warn) {
4696 console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.');
4697 }
4698 this.preserve = value;
4699 },
4700 enumerable: true,
4701 configurable: true
4702 });
4703 RouterLinkWithHref.prototype.ngOnChanges = function (changes) { this.updateTargetUrlAndHref(); };
4704 RouterLinkWithHref.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
4705 RouterLinkWithHref.prototype.onClick = function (button, ctrlKey, metaKey, shiftKey) {
4706 if (button !== 0 || ctrlKey || metaKey || shiftKey) {
4707 return true;
4708 }
4709 if (typeof this.target === 'string' && this.target != '_self') {
4710 return true;
4711 }
4712 var extras = {
4713 skipLocationChange: attrBoolValue(this.skipLocationChange),
4714 replaceUrl: attrBoolValue(this.replaceUrl),
4715 state: this.state
4716 };
4717 this.router.navigateByUrl(this.urlTree, extras);
4718 return false;
4719 };
4720 RouterLinkWithHref.prototype.updateTargetUrlAndHref = function () {
4721 this.href = this.locationStrategy.prepareExternalUrl(this.router.serializeUrl(this.urlTree));
4722 };
4723 Object.defineProperty(RouterLinkWithHref.prototype, "urlTree", {
4724 get: function () {
4725 return this.router.createUrlTree(this.commands, {
4726 relativeTo: this.route,
4727 queryParams: this.queryParams,
4728 fragment: this.fragment,
4729 preserveQueryParams: attrBoolValue(this.preserve),
4730 queryParamsHandling: this.queryParamsHandling,
4731 preserveFragment: attrBoolValue(this.preserveFragment),
4732 });
4733 },
4734 enumerable: true,
4735 configurable: true
4736 });
4737 __decorate([
4738 core.HostBinding('attr.target'), core.Input(),
4739 __metadata("design:type", String)
4740 ], RouterLinkWithHref.prototype, "target", void 0);
4741 __decorate([
4742 core.Input(),
4743 __metadata("design:type", Object)
4744 ], RouterLinkWithHref.prototype, "queryParams", void 0);
4745 __decorate([
4746 core.Input(),
4747 __metadata("design:type", String)
4748 ], RouterLinkWithHref.prototype, "fragment", void 0);
4749 __decorate([
4750 core.Input(),
4751 __metadata("design:type", String)
4752 ], RouterLinkWithHref.prototype, "queryParamsHandling", void 0);
4753 __decorate([
4754 core.Input(),
4755 __metadata("design:type", Boolean)
4756 ], RouterLinkWithHref.prototype, "preserveFragment", void 0);
4757 __decorate([
4758 core.Input(),
4759 __metadata("design:type", Boolean)
4760 ], RouterLinkWithHref.prototype, "skipLocationChange", void 0);
4761 __decorate([
4762 core.Input(),
4763 __metadata("design:type", Boolean)
4764 ], RouterLinkWithHref.prototype, "replaceUrl", void 0);
4765 __decorate([
4766 core.Input(),
4767 __metadata("design:type", Object)
4768 ], RouterLinkWithHref.prototype, "state", void 0);
4769 __decorate([
4770 core.HostBinding(),
4771 __metadata("design:type", String)
4772 ], RouterLinkWithHref.prototype, "href", void 0);
4773 __decorate([
4774 core.Input(),
4775 __metadata("design:type", Object),
4776 __metadata("design:paramtypes", [Object])
4777 ], RouterLinkWithHref.prototype, "routerLink", null);
4778 __decorate([
4779 core.Input(),
4780 __metadata("design:type", Boolean),
4781 __metadata("design:paramtypes", [Boolean])
4782 ], RouterLinkWithHref.prototype, "preserveQueryParams", null);
4783 __decorate([
4784 core.HostListener('click', ['$event.button', '$event.ctrlKey', '$event.metaKey', '$event.shiftKey']),
4785 __metadata("design:type", Function),
4786 __metadata("design:paramtypes", [Number, Boolean, Boolean, Boolean]),
4787 __metadata("design:returntype", Boolean)
4788 ], RouterLinkWithHref.prototype, "onClick", null);
4789 RouterLinkWithHref = __decorate([
4790 core.Directive({ selector: 'a[routerLink],area[routerLink]' }),
4791 __metadata("design:paramtypes", [Router, ActivatedRoute,
4792 common.LocationStrategy])
4793 ], RouterLinkWithHref);
4794 return RouterLinkWithHref;
4795 }());
4796 function attrBoolValue(s) {
4797 return s === '' || !!s;
4798 }
4799
4800 /**
4801 * @license
4802 * Copyright Google Inc. All Rights Reserved.
4803 *
4804 * Use of this source code is governed by an MIT-style license that can be
4805 * found in the LICENSE file at https://angular.io/license
4806 */
4807 /**
4808 *
4809 * @description
4810 *
4811 * Lets you add a CSS class to an element when the link's route becomes active.
4812 *
4813 * This directive lets you add a CSS class to an element when the link's route
4814 * becomes active.
4815 *
4816 * Consider the following example:
4817 *
4818 * ```
4819 * <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
4820 * ```
4821 *
4822 * When the url is either '/user' or '/user/bob', the active-link class will
4823 * be added to the `a` tag. If the url changes, the class will be removed.
4824 *
4825 * You can set more than one class, as follows:
4826 *
4827 * ```
4828 * <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
4829 * <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>
4830 * ```
4831 *
4832 * You can configure RouterLinkActive by passing `exact: true`. This will add the classes
4833 * only when the url matches the link exactly.
4834 *
4835 * ```
4836 * <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact:
4837 * true}">Bob</a>
4838 * ```
4839 *
4840 * You can assign the RouterLinkActive instance to a template variable and directly check
4841 * the `isActive` status.
4842 * ```
4843 * <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
4844 * Bob {{ rla.isActive ? '(already open)' : ''}}
4845 * </a>
4846 * ```
4847 *
4848 * Finally, you can apply the RouterLinkActive directive to an ancestor of a RouterLink.
4849 *
4850 * ```
4851 * <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
4852 * <a routerLink="/user/jim">Jim</a>
4853 * <a routerLink="/user/bob">Bob</a>
4854 * </div>
4855 * ```
4856 *
4857 * This will set the active-link class on the div tag if the url is either '/user/jim' or
4858 * '/user/bob'.
4859 *
4860 * @ngModule RouterModule
4861 *
4862 * @publicApi
4863 */
4864 var RouterLinkActive = /** @class */ (function () {
4865 function RouterLinkActive(router, element, renderer, link, linkWithHref) {
4866 var _this = this;
4867 this.router = router;
4868 this.element = element;
4869 this.renderer = renderer;
4870 this.link = link;
4871 this.linkWithHref = linkWithHref;
4872 this.classes = [];
4873 this.isActive = false;
4874 this.routerLinkActiveOptions = { exact: false };
4875 this.subscription = router.events.subscribe(function (s) {
4876 if (s instanceof NavigationEnd) {
4877 _this.update();
4878 }
4879 });
4880 }
4881 RouterLinkActive.prototype.ngAfterContentInit = function () {
4882 var _this = this;
4883 this.links.changes.subscribe(function (_) { return _this.update(); });
4884 this.linksWithHrefs.changes.subscribe(function (_) { return _this.update(); });
4885 this.update();
4886 };
4887 Object.defineProperty(RouterLinkActive.prototype, "routerLinkActive", {
4888 set: function (data) {
4889 var classes = Array.isArray(data) ? data : data.split(' ');
4890 this.classes = classes.filter(function (c) { return !!c; });
4891 },
4892 enumerable: true,
4893 configurable: true
4894 });
4895 RouterLinkActive.prototype.ngOnChanges = function (changes) { this.update(); };
4896 RouterLinkActive.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
4897 RouterLinkActive.prototype.update = function () {
4898 var _this = this;
4899 if (!this.links || !this.linksWithHrefs || !this.router.navigated)
4900 return;
4901 Promise.resolve().then(function () {
4902 var hasActiveLinks = _this.hasActiveLinks();
4903 if (_this.isActive !== hasActiveLinks) {
4904 _this.isActive = hasActiveLinks;
4905 _this.classes.forEach(function (c) {
4906 if (hasActiveLinks) {
4907 _this.renderer.addClass(_this.element.nativeElement, c);
4908 }
4909 else {
4910 _this.renderer.removeClass(_this.element.nativeElement, c);
4911 }
4912 });
4913 }
4914 });
4915 };
4916 RouterLinkActive.prototype.isLinkActive = function (router) {
4917 var _this = this;
4918 return function (link) {
4919 return router.isActive(link.urlTree, _this.routerLinkActiveOptions.exact);
4920 };
4921 };
4922 RouterLinkActive.prototype.hasActiveLinks = function () {
4923 var isActiveCheckFn = this.isLinkActive(this.router);
4924 return this.link && isActiveCheckFn(this.link) ||
4925 this.linkWithHref && isActiveCheckFn(this.linkWithHref) ||
4926 this.links.some(isActiveCheckFn) || this.linksWithHrefs.some(isActiveCheckFn);
4927 };
4928 __decorate([
4929 core.ContentChildren(RouterLink, { descendants: true }),
4930 __metadata("design:type", core.QueryList)
4931 ], RouterLinkActive.prototype, "links", void 0);
4932 __decorate([
4933 core.ContentChildren(RouterLinkWithHref, { descendants: true }),
4934 __metadata("design:type", core.QueryList)
4935 ], RouterLinkActive.prototype, "linksWithHrefs", void 0);
4936 __decorate([
4937 core.Input(),
4938 __metadata("design:type", Object)
4939 ], RouterLinkActive.prototype, "routerLinkActiveOptions", void 0);
4940 __decorate([
4941 core.Input(),
4942 __metadata("design:type", Object),
4943 __metadata("design:paramtypes", [Object])
4944 ], RouterLinkActive.prototype, "routerLinkActive", null);
4945 RouterLinkActive = __decorate([
4946 core.Directive({
4947 selector: '[routerLinkActive]',
4948 exportAs: 'routerLinkActive',
4949 }),
4950 __param(3, core.Optional()),
4951 __param(4, core.Optional()),
4952 __metadata("design:paramtypes", [Router, core.ElementRef, core.Renderer2,
4953 RouterLink,
4954 RouterLinkWithHref])
4955 ], RouterLinkActive);
4956 return RouterLinkActive;
4957 }());
4958
4959 /**
4960 * @license
4961 * Copyright Google Inc. All Rights Reserved.
4962 *
4963 * Use of this source code is governed by an MIT-style license that can be
4964 * found in the LICENSE file at https://angular.io/license
4965 */
4966 /**
4967 * Store contextual information about a `RouterOutlet`
4968 *
4969 * @publicApi
4970 */
4971 var OutletContext = /** @class */ (function () {
4972 function OutletContext() {
4973 this.outlet = null;
4974 this.route = null;
4975 this.resolver = null;
4976 this.children = new ChildrenOutletContexts();
4977 this.attachRef = null;
4978 }
4979 return OutletContext;
4980 }());
4981 /**
4982 * Store contextual information about the children (= nested) `RouterOutlet`
4983 *
4984 * @publicApi
4985 */
4986 var ChildrenOutletContexts = /** @class */ (function () {
4987 function ChildrenOutletContexts() {
4988 // contexts for child outlets, by name.
4989 this.contexts = new Map();
4990 }
4991 /** Called when a `RouterOutlet` directive is instantiated */
4992 ChildrenOutletContexts.prototype.onChildOutletCreated = function (childName, outlet) {
4993 var context = this.getOrCreateContext(childName);
4994 context.outlet = outlet;
4995 this.contexts.set(childName, context);
4996 };
4997 /**
4998 * Called when a `RouterOutlet` directive is destroyed.
4999 * We need to keep the context as the outlet could be destroyed inside a NgIf and might be
5000 * re-created later.
5001 */
5002 ChildrenOutletContexts.prototype.onChildOutletDestroyed = function (childName) {
5003 var context = this.getContext(childName);
5004 if (context) {
5005 context.outlet = null;
5006 }
5007 };
5008 /**
5009 * Called when the corresponding route is deactivated during navigation.
5010 * Because the component get destroyed, all children outlet are destroyed.
5011 */
5012 ChildrenOutletContexts.prototype.onOutletDeactivated = function () {
5013 var contexts = this.contexts;
5014 this.contexts = new Map();
5015 return contexts;
5016 };
5017 ChildrenOutletContexts.prototype.onOutletReAttached = function (contexts) { this.contexts = contexts; };
5018 ChildrenOutletContexts.prototype.getOrCreateContext = function (childName) {
5019 var context = this.getContext(childName);
5020 if (!context) {
5021 context = new OutletContext();
5022 this.contexts.set(childName, context);
5023 }
5024 return context;
5025 };
5026 ChildrenOutletContexts.prototype.getContext = function (childName) { return this.contexts.get(childName) || null; };
5027 return ChildrenOutletContexts;
5028 }());
5029
5030 /**
5031 * @license
5032 * Copyright Google Inc. All Rights Reserved.
5033 *
5034 * Use of this source code is governed by an MIT-style license that can be
5035 * found in the LICENSE file at https://angular.io/license
5036 */
5037 /**
5038 * @description
5039 *
5040 * Acts as a placeholder that Angular dynamically fills based on the current router state.
5041 *
5042 * ```
5043 * <router-outlet></router-outlet>
5044 * <router-outlet name='left'></router-outlet>
5045 * <router-outlet name='right'></router-outlet>
5046 * ```
5047 *
5048 * A router outlet will emit an activate event any time a new component is being instantiated,
5049 * and a deactivate event when it is being destroyed.
5050 *
5051 * ```
5052 * <router-outlet
5053 * (activate)='onActivate($event)'
5054 * (deactivate)='onDeactivate($event)'></router-outlet>
5055 * ```
5056 * @ngModule RouterModule
5057 *
5058 * @publicApi
5059 */
5060 var RouterOutlet = /** @class */ (function () {
5061 function RouterOutlet(parentContexts, location, resolver, name, changeDetector) {
5062 this.parentContexts = parentContexts;
5063 this.location = location;
5064 this.resolver = resolver;
5065 this.changeDetector = changeDetector;
5066 this.activated = null;
5067 this._activatedRoute = null;
5068 this.activateEvents = new core.EventEmitter();
5069 this.deactivateEvents = new core.EventEmitter();
5070 this.name = name || PRIMARY_OUTLET;
5071 parentContexts.onChildOutletCreated(this.name, this);
5072 }
5073 RouterOutlet.prototype.ngOnDestroy = function () { this.parentContexts.onChildOutletDestroyed(this.name); };
5074 RouterOutlet.prototype.ngOnInit = function () {
5075 if (!this.activated) {
5076 // If the outlet was not instantiated at the time the route got activated we need to populate
5077 // the outlet when it is initialized (ie inside a NgIf)
5078 var context = this.parentContexts.getContext(this.name);
5079 if (context && context.route) {
5080 if (context.attachRef) {
5081 // `attachRef` is populated when there is an existing component to mount
5082 this.attach(context.attachRef, context.route);
5083 }
5084 else {
5085 // otherwise the component defined in the configuration is created
5086 this.activateWith(context.route, context.resolver || null);
5087 }
5088 }
5089 }
5090 };
5091 Object.defineProperty(RouterOutlet.prototype, "isActivated", {
5092 get: function () { return !!this.activated; },
5093 enumerable: true,
5094 configurable: true
5095 });
5096 Object.defineProperty(RouterOutlet.prototype, "component", {
5097 get: function () {
5098 if (!this.activated)
5099 throw new Error('Outlet is not activated');
5100 return this.activated.instance;
5101 },
5102 enumerable: true,
5103 configurable: true
5104 });
5105 Object.defineProperty(RouterOutlet.prototype, "activatedRoute", {
5106 get: function () {
5107 if (!this.activated)
5108 throw new Error('Outlet is not activated');
5109 return this._activatedRoute;
5110 },
5111 enumerable: true,
5112 configurable: true
5113 });
5114 Object.defineProperty(RouterOutlet.prototype, "activatedRouteData", {
5115 get: function () {
5116 if (this._activatedRoute) {
5117 return this._activatedRoute.snapshot.data;
5118 }
5119 return {};
5120 },
5121 enumerable: true,
5122 configurable: true
5123 });
5124 /**
5125 * Called when the `RouteReuseStrategy` instructs to detach the subtree
5126 */
5127 RouterOutlet.prototype.detach = function () {
5128 if (!this.activated)
5129 throw new Error('Outlet is not activated');
5130 this.location.detach();
5131 var cmp = this.activated;
5132 this.activated = null;
5133 this._activatedRoute = null;
5134 return cmp;
5135 };
5136 /**
5137 * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree
5138 */
5139 RouterOutlet.prototype.attach = function (ref, activatedRoute) {
5140 this.activated = ref;
5141 this._activatedRoute = activatedRoute;
5142 this.location.insert(ref.hostView);
5143 };
5144 RouterOutlet.prototype.deactivate = function () {
5145 if (this.activated) {
5146 var c = this.component;
5147 this.activated.destroy();
5148 this.activated = null;
5149 this._activatedRoute = null;
5150 this.deactivateEvents.emit(c);
5151 }
5152 };
5153 RouterOutlet.prototype.activateWith = function (activatedRoute, resolver) {
5154 if (this.isActivated) {
5155 throw new Error('Cannot activate an already activated outlet');
5156 }
5157 this._activatedRoute = activatedRoute;
5158 var snapshot = activatedRoute._futureSnapshot;
5159 var component = snapshot.routeConfig.component;
5160 resolver = resolver || this.resolver;
5161 var factory = resolver.resolveComponentFactory(component);
5162 var childContexts = this.parentContexts.getOrCreateContext(this.name).children;
5163 var injector = new OutletInjector(activatedRoute, childContexts, this.location.injector);
5164 this.activated = this.location.createComponent(factory, this.location.length, injector);
5165 // Calling `markForCheck` to make sure we will run the change detection when the
5166 // `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component.
5167 this.changeDetector.markForCheck();
5168 this.activateEvents.emit(this.activated.instance);
5169 };
5170 __decorate([
5171 core.Output('activate'),
5172 __metadata("design:type", Object)
5173 ], RouterOutlet.prototype, "activateEvents", void 0);
5174 __decorate([
5175 core.Output('deactivate'),
5176 __metadata("design:type", Object)
5177 ], RouterOutlet.prototype, "deactivateEvents", void 0);
5178 RouterOutlet = __decorate([
5179 core.Directive({ selector: 'router-outlet', exportAs: 'outlet' }),
5180 __param(3, core.Attribute('name')),
5181 __metadata("design:paramtypes", [ChildrenOutletContexts, core.ViewContainerRef,
5182 core.ComponentFactoryResolver, String, core.ChangeDetectorRef])
5183 ], RouterOutlet);
5184 return RouterOutlet;
5185 }());
5186 var OutletInjector = /** @class */ (function () {
5187 function OutletInjector(route, childContexts, parent) {
5188 this.route = route;
5189 this.childContexts = childContexts;
5190 this.parent = parent;
5191 }
5192 OutletInjector.prototype.get = function (token, notFoundValue) {
5193 if (token === ActivatedRoute) {
5194 return this.route;
5195 }
5196 if (token === ChildrenOutletContexts) {
5197 return this.childContexts;
5198 }
5199 return this.parent.get(token, notFoundValue);
5200 };
5201 return OutletInjector;
5202 }());
5203
5204 /**
5205 *@license
5206 *Copyright Google Inc. All Rights Reserved.
5207 *
5208 *Use of this source code is governed by an MIT-style license that can be
5209 *found in the LICENSE file at https://angular.io/license
5210 */
5211 /**
5212 * @description
5213 *
5214 * Provides a preloading strategy.
5215 *
5216 * @publicApi
5217 */
5218 var PreloadingStrategy = /** @class */ (function () {
5219 function PreloadingStrategy() {
5220 }
5221 return PreloadingStrategy;
5222 }());
5223 /**
5224 * @description
5225 *
5226 * Provides a preloading strategy that preloads all modules as quickly as possible.
5227 *
5228 * ```
5229 * RouteModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})
5230 * ```
5231 *
5232 * @publicApi
5233 */
5234 var PreloadAllModules = /** @class */ (function () {
5235 function PreloadAllModules() {
5236 }
5237 PreloadAllModules.prototype.preload = function (route, fn) {
5238 return fn().pipe(operators.catchError(function () { return rxjs.of(null); }));
5239 };
5240 return PreloadAllModules;
5241 }());
5242 /**
5243 * @description
5244 *
5245 * Provides a preloading strategy that does not preload any modules.
5246 *
5247 * This strategy is enabled by default.
5248 *
5249 * @publicApi
5250 */
5251 var NoPreloading = /** @class */ (function () {
5252 function NoPreloading() {
5253 }
5254 NoPreloading.prototype.preload = function (route, fn) { return rxjs.of(null); };
5255 return NoPreloading;
5256 }());
5257 /**
5258 * The preloader optimistically loads all router configurations to
5259 * make navigations into lazily-loaded sections of the application faster.
5260 *
5261 * The preloader runs in the background. When the router bootstraps, the preloader
5262 * starts listening to all navigation events. After every such event, the preloader
5263 * will check if any configurations can be loaded lazily.
5264 *
5265 * If a route is protected by `canLoad` guards, the preloaded will not load it.
5266 *
5267 * @publicApi
5268 */
5269 var RouterPreloader = /** @class */ (function () {
5270 function RouterPreloader(router, moduleLoader, compiler, injector, preloadingStrategy) {
5271 this.router = router;
5272 this.injector = injector;
5273 this.preloadingStrategy = preloadingStrategy;
5274 var onStartLoad = function (r) { return router.triggerEvent(new RouteConfigLoadStart(r)); };
5275 var onEndLoad = function (r) { return router.triggerEvent(new RouteConfigLoadEnd(r)); };
5276 this.loader = new RouterConfigLoader(moduleLoader, compiler, onStartLoad, onEndLoad);
5277 }
5278 RouterPreloader.prototype.setUpPreloading = function () {
5279 var _this = this;
5280 this.subscription =
5281 this.router.events
5282 .pipe(operators.filter(function (e) { return e instanceof NavigationEnd; }), operators.concatMap(function () { return _this.preload(); }))
5283 .subscribe(function () { });
5284 };
5285 RouterPreloader.prototype.preload = function () {
5286 var ngModule = this.injector.get(core.NgModuleRef);
5287 return this.processRoutes(ngModule, this.router.config);
5288 };
5289 // TODO(jasonaden): This class relies on code external to the class to call setUpPreloading. If
5290 // this hasn't been done, ngOnDestroy will fail as this.subscription will be undefined. This
5291 // should be refactored.
5292 RouterPreloader.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
5293 RouterPreloader.prototype.processRoutes = function (ngModule, routes) {
5294 var e_1, _a;
5295 var res = [];
5296 try {
5297 for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
5298 var route = routes_1_1.value;
5299 // we already have the config loaded, just recurse
5300 if (route.loadChildren && !route.canLoad && route._loadedConfig) {
5301 var childConfig = route._loadedConfig;
5302 res.push(this.processRoutes(childConfig.module, childConfig.routes));
5303 // no config loaded, fetch the config
5304 }
5305 else if (route.loadChildren && !route.canLoad) {
5306 res.push(this.preloadConfig(ngModule, route));
5307 // recurse into children
5308 }
5309 else if (route.children) {
5310 res.push(this.processRoutes(ngModule, route.children));
5311 }
5312 }
5313 }
5314 catch (e_1_1) { e_1 = { error: e_1_1 }; }
5315 finally {
5316 try {
5317 if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
5318 }
5319 finally { if (e_1) throw e_1.error; }
5320 }
5321 return rxjs.from(res).pipe(operators.mergeAll(), operators.map(function (_) { return void 0; }));
5322 };
5323 RouterPreloader.prototype.preloadConfig = function (ngModule, route) {
5324 var _this = this;
5325 return this.preloadingStrategy.preload(route, function () {
5326 var loaded$ = _this.loader.load(ngModule.injector, route);
5327 return loaded$.pipe(operators.mergeMap(function (config) {
5328 route._loadedConfig = config;
5329 return _this.processRoutes(config.module, config.routes);
5330 }));
5331 });
5332 };
5333 RouterPreloader = __decorate([
5334 core.Injectable(),
5335 __metadata("design:paramtypes", [Router, core.NgModuleFactoryLoader, core.Compiler,
5336 core.Injector, PreloadingStrategy])
5337 ], RouterPreloader);
5338 return RouterPreloader;
5339 }());
5340
5341 /**
5342 * @license
5343 * Copyright Google Inc. All Rights Reserved.
5344 *
5345 * Use of this source code is governed by an MIT-style license that can be
5346 * found in the LICENSE file at https://angular.io/license
5347 */
5348 var RouterScroller = /** @class */ (function () {
5349 function RouterScroller(router,
5350 /** @docsNotRequired */ viewportScroller, options) {
5351 if (options === void 0) { options = {}; }
5352 this.router = router;
5353 this.viewportScroller = viewportScroller;
5354 this.options = options;
5355 this.lastId = 0;
5356 this.lastSource = 'imperative';
5357 this.restoredId = 0;
5358 this.store = {};
5359 // Default both options to 'disabled'
5360 options.scrollPositionRestoration = options.scrollPositionRestoration || 'disabled';
5361 options.anchorScrolling = options.anchorScrolling || 'disabled';
5362 }
5363 RouterScroller.prototype.init = function () {
5364 // we want to disable the automatic scrolling because having two places
5365 // responsible for scrolling results race conditions, especially given
5366 // that browser don't implement this behavior consistently
5367 if (this.options.scrollPositionRestoration !== 'disabled') {
5368 this.viewportScroller.setHistoryScrollRestoration('manual');
5369 }
5370 this.routerEventsSubscription = this.createScrollEvents();
5371 this.scrollEventsSubscription = this.consumeScrollEvents();
5372 };
5373 RouterScroller.prototype.createScrollEvents = function () {
5374 var _this = this;
5375 return this.router.events.subscribe(function (e) {
5376 if (e instanceof NavigationStart) {
5377 // store the scroll position of the current stable navigations.
5378 _this.store[_this.lastId] = _this.viewportScroller.getScrollPosition();
5379 _this.lastSource = e.navigationTrigger;
5380 _this.restoredId = e.restoredState ? e.restoredState.navigationId : 0;
5381 }
5382 else if (e instanceof NavigationEnd) {
5383 _this.lastId = e.id;
5384 _this.scheduleScrollEvent(e, _this.router.parseUrl(e.urlAfterRedirects).fragment);
5385 }
5386 });
5387 };
5388 RouterScroller.prototype.consumeScrollEvents = function () {
5389 var _this = this;
5390 return this.router.events.subscribe(function (e) {
5391 if (!(e instanceof Scroll))
5392 return;
5393 // a popstate event. The pop state event will always ignore anchor scrolling.
5394 if (e.position) {
5395 if (_this.options.scrollPositionRestoration === 'top') {
5396 _this.viewportScroller.scrollToPosition([0, 0]);
5397 }
5398 else if (_this.options.scrollPositionRestoration === 'enabled') {
5399 _this.viewportScroller.scrollToPosition(e.position);
5400 }
5401 // imperative navigation "forward"
5402 }
5403 else {
5404 if (e.anchor && _this.options.anchorScrolling === 'enabled') {
5405 _this.viewportScroller.scrollToAnchor(e.anchor);
5406 }
5407 else if (_this.options.scrollPositionRestoration !== 'disabled') {
5408 _this.viewportScroller.scrollToPosition([0, 0]);
5409 }
5410 }
5411 });
5412 };
5413 RouterScroller.prototype.scheduleScrollEvent = function (routerEvent, anchor) {
5414 this.router.triggerEvent(new Scroll(routerEvent, this.lastSource === 'popstate' ? this.store[this.restoredId] : null, anchor));
5415 };
5416 RouterScroller.prototype.ngOnDestroy = function () {
5417 if (this.routerEventsSubscription) {
5418 this.routerEventsSubscription.unsubscribe();
5419 }
5420 if (this.scrollEventsSubscription) {
5421 this.scrollEventsSubscription.unsubscribe();
5422 }
5423 };
5424 return RouterScroller;
5425 }());
5426
5427 /**
5428 * @license
5429 * Copyright Google Inc. All Rights Reserved.
5430 *
5431 * Use of this source code is governed by an MIT-style license that can be
5432 * found in the LICENSE file at https://angular.io/license
5433 */
5434 /**
5435 * The directives defined in the `RouterModule`.
5436 */
5437 var ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive, ɵEmptyOutletComponent];
5438 /**
5439 * A [DI token](guide/glossary/#di-token) for the router service.
5440 *
5441 * @publicApi
5442 */
5443 var ROUTER_CONFIGURATION = new core.InjectionToken('ROUTER_CONFIGURATION');
5444 /**
5445 * @docsNotRequired
5446 */
5447 var ROUTER_FORROOT_GUARD = new core.InjectionToken('ROUTER_FORROOT_GUARD');
5448 var ɵ0 = { enableTracing: false };
5449 var ROUTER_PROVIDERS = [
5450 common.Location,
5451 { provide: UrlSerializer, useClass: DefaultUrlSerializer },
5452 {
5453 provide: Router,
5454 useFactory: setupRouter,
5455 deps: [
5456 core.ApplicationRef, UrlSerializer, ChildrenOutletContexts, common.Location, core.Injector,
5457 core.NgModuleFactoryLoader, core.Compiler, ROUTES, ROUTER_CONFIGURATION,
5458 [UrlHandlingStrategy, new core.Optional()], [RouteReuseStrategy, new core.Optional()]
5459 ]
5460 },
5461 ChildrenOutletContexts,
5462 { provide: ActivatedRoute, useFactory: rootRoute, deps: [Router] },
5463 { provide: core.NgModuleFactoryLoader, useClass: core.SystemJsNgModuleLoader },
5464 RouterPreloader,
5465 NoPreloading,
5466 PreloadAllModules,
5467 { provide: ROUTER_CONFIGURATION, useValue: ɵ0 },
5468 ];
5469 function routerNgProbeToken() {
5470 return new core.NgProbeToken('Router', Router);
5471 }
5472 /**
5473 * @usageNotes
5474 *
5475 * RouterModule can be imported multiple times: once per lazily-loaded bundle.
5476 * Since the router deals with a global shared resource--location, we cannot have
5477 * more than one router service active.
5478 *
5479 * That is why there are two ways to create the module: `RouterModule.forRoot` and
5480 * `RouterModule.forChild`.
5481 *
5482 * * `forRoot` creates a module that contains all the directives, the given routes, and the router
5483 * service itself.
5484 * * `forChild` creates a module that contains all the directives and the given routes, but does not
5485 * include the router service.
5486 *
5487 * When registered at the root, the module should be used as follows
5488 *
5489 * ```
5490 * @NgModule({
5491 * imports: [RouterModule.forRoot(ROUTES)]
5492 * })
5493 * class MyNgModule {}
5494 * ```
5495 *
5496 * For submodules and lazy loaded submodules the module should be used as follows:
5497 *
5498 * ```
5499 * @NgModule({
5500 * imports: [RouterModule.forChild(ROUTES)]
5501 * })
5502 * class MyNgModule {}
5503 * ```
5504 *
5505 * @description
5506 *
5507 * Adds router directives and providers.
5508 *
5509 * Managing state transitions is one of the hardest parts of building applications. This is
5510 * especially true on the web, where you also need to ensure that the state is reflected in the URL.
5511 * In addition, we often want to split applications into multiple bundles and load them on demand.
5512 * Doing this transparently is not trivial.
5513 *
5514 * The Angular router service solves these problems. Using the router, you can declaratively specify
5515 * application states, manage state transitions while taking care of the URL, and load bundles on
5516 * demand.
5517 *
5518 * @see [Routing and Navigation](guide/router.html) for an
5519 * overview of how the router service should be used.
5520 *
5521 * @publicApi
5522 */
5523 var RouterModule = /** @class */ (function () {
5524 // Note: We are injecting the Router so it gets created eagerly...
5525 function RouterModule(guard, router) {
5526 }
5527 RouterModule_1 = RouterModule;
5528 /**
5529 * Creates and configures a module with all the router providers and directives.
5530 * Optionally sets up an application listener to perform an initial navigation.
5531 *
5532 * @param routes An array of `Route` objects that define the navigation paths for the application.
5533 * @param config An `ExtraOptions` configuration object that controls how navigation is performed.
5534 * @return The new router module.
5535 */
5536 RouterModule.forRoot = function (routes, config) {
5537 return {
5538 ngModule: RouterModule_1,
5539 providers: [
5540 ROUTER_PROVIDERS,
5541 provideRoutes(routes),
5542 {
5543 provide: ROUTER_FORROOT_GUARD,
5544 useFactory: provideForRootGuard,
5545 deps: [[Router, new core.Optional(), new core.SkipSelf()]]
5546 },
5547 { provide: ROUTER_CONFIGURATION, useValue: config ? config : {} },
5548 {
5549 provide: common.LocationStrategy,
5550 useFactory: provideLocationStrategy,
5551 deps: [
5552 common.PlatformLocation, [new core.Inject(common.APP_BASE_HREF), new core.Optional()], ROUTER_CONFIGURATION
5553 ]
5554 },
5555 {
5556 provide: RouterScroller,
5557 useFactory: createRouterScroller,
5558 deps: [Router, common.ViewportScroller, ROUTER_CONFIGURATION]
5559 },
5560 {
5561 provide: PreloadingStrategy,
5562 useExisting: config && config.preloadingStrategy ? config.preloadingStrategy :
5563 NoPreloading
5564 },
5565 { provide: core.NgProbeToken, multi: true, useFactory: routerNgProbeToken },
5566 provideRouterInitializer(),
5567 ],
5568 };
5569 };
5570 /**
5571 * Creates a module with all the router directives and a provider registering routes.
5572 */
5573 RouterModule.forChild = function (routes) {
5574 return { ngModule: RouterModule_1, providers: [provideRoutes(routes)] };
5575 };
5576 var RouterModule_1;
5577 RouterModule = RouterModule_1 = __decorate([
5578 core.NgModule({
5579 declarations: ROUTER_DIRECTIVES,
5580 exports: ROUTER_DIRECTIVES,
5581 entryComponents: [ɵEmptyOutletComponent]
5582 }),
5583 __param(0, core.Optional()), __param(0, core.Inject(ROUTER_FORROOT_GUARD)), __param(1, core.Optional()),
5584 __metadata("design:paramtypes", [Object, Router])
5585 ], RouterModule);
5586 return RouterModule;
5587 }());
5588 function createRouterScroller(router, viewportScroller, config) {
5589 if (config.scrollOffset) {
5590 viewportScroller.setOffset(config.scrollOffset);
5591 }
5592 return new RouterScroller(router, viewportScroller, config);
5593 }
5594 function provideLocationStrategy(platformLocationStrategy, baseHref, options) {
5595 if (options === void 0) { options = {}; }
5596 return options.useHash ? new common.HashLocationStrategy(platformLocationStrategy, baseHref) :
5597 new common.PathLocationStrategy(platformLocationStrategy, baseHref);
5598 }
5599 function provideForRootGuard(router) {
5600 if (router) {
5601 throw new Error("RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.");
5602 }
5603 return 'guarded';
5604 }
5605 /**
5606 * Registers a [DI provider](guide/glossary#provider) for a set of routes.
5607 * @param routes The route configuration to provide.
5608 *
5609 * @usageNotes
5610 *
5611 * ```
5612 * @NgModule({
5613 * imports: [RouterModule.forChild(ROUTES)],
5614 * providers: [provideRoutes(EXTRA_ROUTES)]
5615 * })
5616 * class MyNgModule {}
5617 * ```
5618 *
5619 * @publicApi
5620 */
5621 function provideRoutes(routes) {
5622 return [
5623 { provide: core.ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes },
5624 { provide: ROUTES, multi: true, useValue: routes },
5625 ];
5626 }
5627 function setupRouter(ref, urlSerializer, contexts, location, injector, loader, compiler, config, opts, urlHandlingStrategy, routeReuseStrategy) {
5628 if (opts === void 0) { opts = {}; }
5629 var router = new Router(null, urlSerializer, contexts, location, injector, loader, compiler, flatten(config));
5630 if (urlHandlingStrategy) {
5631 router.urlHandlingStrategy = urlHandlingStrategy;
5632 }
5633 if (routeReuseStrategy) {
5634 router.routeReuseStrategy = routeReuseStrategy;
5635 }
5636 if (opts.errorHandler) {
5637 router.errorHandler = opts.errorHandler;
5638 }
5639 if (opts.malformedUriErrorHandler) {
5640 router.malformedUriErrorHandler = opts.malformedUriErrorHandler;
5641 }
5642 if (opts.enableTracing) {
5643 var dom_1 = platformBrowser.ɵgetDOM();
5644 router.events.subscribe(function (e) {
5645 dom_1.logGroup("Router Event: " + e.constructor.name);
5646 dom_1.log(e.toString());
5647 dom_1.log(e);
5648 dom_1.logGroupEnd();
5649 });
5650 }
5651 if (opts.onSameUrlNavigation) {
5652 router.onSameUrlNavigation = opts.onSameUrlNavigation;
5653 }
5654 if (opts.paramsInheritanceStrategy) {
5655 router.paramsInheritanceStrategy = opts.paramsInheritanceStrategy;
5656 }
5657 if (opts.urlUpdateStrategy) {
5658 router.urlUpdateStrategy = opts.urlUpdateStrategy;
5659 }
5660 if (opts.relativeLinkResolution) {
5661 router.relativeLinkResolution = opts.relativeLinkResolution;
5662 }
5663 return router;
5664 }
5665 function rootRoute(router) {
5666 return router.routerState.root;
5667 }
5668 /**
5669 * Router initialization requires two steps:
5670 *
5671 * First, we start the navigation in a `APP_INITIALIZER` to block the bootstrap if
5672 * a resolver or a guard executes asynchronously.
5673 *
5674 * Next, we actually run activation in a `BOOTSTRAP_LISTENER`, using the
5675 * `afterPreactivation` hook provided by the router.
5676 * The router navigation starts, reaches the point when preactivation is done, and then
5677 * pauses. It waits for the hook to be resolved. We then resolve it only in a bootstrap listener.
5678 */
5679 var RouterInitializer = /** @class */ (function () {
5680 function RouterInitializer(injector) {
5681 this.injector = injector;
5682 this.initNavigation = false;
5683 this.resultOfPreactivationDone = new rxjs.Subject();
5684 }
5685 RouterInitializer.prototype.appInitializer = function () {
5686 var _this = this;
5687 var p = this.injector.get(common.LOCATION_INITIALIZED, Promise.resolve(null));
5688 return p.then(function () {
5689 var resolve = null;
5690 var res = new Promise(function (r) { return resolve = r; });
5691 var router = _this.injector.get(Router);
5692 var opts = _this.injector.get(ROUTER_CONFIGURATION);
5693 if (_this.isLegacyDisabled(opts) || _this.isLegacyEnabled(opts)) {
5694 resolve(true);
5695 }
5696 else if (opts.initialNavigation === 'disabled') {
5697 router.setUpLocationChangeListener();
5698 resolve(true);
5699 }
5700 else if (opts.initialNavigation === 'enabled') {
5701 router.hooks.afterPreactivation = function () {
5702 // only the initial navigation should be delayed
5703 if (!_this.initNavigation) {
5704 _this.initNavigation = true;
5705 resolve(true);
5706 return _this.resultOfPreactivationDone;
5707 // subsequent navigations should not be delayed
5708 }
5709 else {
5710 return rxjs.of(null);
5711 }
5712 };
5713 router.initialNavigation();
5714 }
5715 else {
5716 throw new Error("Invalid initialNavigation options: '" + opts.initialNavigation + "'");
5717 }
5718 return res;
5719 });
5720 };
5721 RouterInitializer.prototype.bootstrapListener = function (bootstrappedComponentRef) {
5722 var opts = this.injector.get(ROUTER_CONFIGURATION);
5723 var preloader = this.injector.get(RouterPreloader);
5724 var routerScroller = this.injector.get(RouterScroller);
5725 var router = this.injector.get(Router);
5726 var ref = this.injector.get(core.ApplicationRef);
5727 if (bootstrappedComponentRef !== ref.components[0]) {
5728 return;
5729 }
5730 if (this.isLegacyEnabled(opts)) {
5731 router.initialNavigation();
5732 }
5733 else if (this.isLegacyDisabled(opts)) {
5734 router.setUpLocationChangeListener();
5735 }
5736 preloader.setUpPreloading();
5737 routerScroller.init();
5738 router.resetRootComponentType(ref.componentTypes[0]);
5739 this.resultOfPreactivationDone.next(null);
5740 this.resultOfPreactivationDone.complete();
5741 };
5742 RouterInitializer.prototype.isLegacyEnabled = function (opts) {
5743 return opts.initialNavigation === 'legacy_enabled' || opts.initialNavigation === true ||
5744 opts.initialNavigation === undefined;
5745 };
5746 RouterInitializer.prototype.isLegacyDisabled = function (opts) {
5747 return opts.initialNavigation === 'legacy_disabled' || opts.initialNavigation === false;
5748 };
5749 RouterInitializer = __decorate([
5750 core.Injectable(),
5751 __metadata("design:paramtypes", [core.Injector])
5752 ], RouterInitializer);
5753 return RouterInitializer;
5754 }());
5755 function getAppInitializer(r) {
5756 return r.appInitializer.bind(r);
5757 }
5758 function getBootstrapListener(r) {
5759 return r.bootstrapListener.bind(r);
5760 }
5761 /**
5762 * A [DI token](guide/glossary/#di-token) for the router initializer that
5763 * is called after the app is bootstrapped.
5764 *
5765 * @publicApi
5766 */
5767 var ROUTER_INITIALIZER = new core.InjectionToken('Router Initializer');
5768 function provideRouterInitializer() {
5769 return [
5770 RouterInitializer,
5771 {
5772 provide: core.APP_INITIALIZER,
5773 multi: true,
5774 useFactory: getAppInitializer,
5775 deps: [RouterInitializer]
5776 },
5777 { provide: ROUTER_INITIALIZER, useFactory: getBootstrapListener, deps: [RouterInitializer] },
5778 { provide: core.APP_BOOTSTRAP_LISTENER, multi: true, useExisting: ROUTER_INITIALIZER },
5779 ];
5780 }
5781
5782 /**
5783 * @license
5784 * Copyright Google Inc. All Rights Reserved.
5785 *
5786 * Use of this source code is governed by an MIT-style license that can be
5787 * found in the LICENSE file at https://angular.io/license
5788 */
5789 /**
5790 * @publicApi
5791 */
5792 var VERSION = new core.Version('8.2.0');
5793
5794 /**
5795 * @license
5796 * Copyright Google Inc. All Rights Reserved.
5797 *
5798 * Use of this source code is governed by an MIT-style license that can be
5799 * found in the LICENSE file at https://angular.io/license
5800 */
5801
5802 /**
5803 * @license
5804 * Copyright Google Inc. All Rights Reserved.
5805 *
5806 * Use of this source code is governed by an MIT-style license that can be
5807 * found in the LICENSE file at https://angular.io/license
5808 */
5809
5810 /**
5811 * @license
5812 * Copyright Google Inc. All Rights Reserved.
5813 *
5814 * Use of this source code is governed by an MIT-style license that can be
5815 * found in the LICENSE file at https://angular.io/license
5816 */
5817 // This file only reexports content of the `src` folder. Keep it that way.
5818
5819 /**
5820 * @license
5821 * Copyright Google Inc. All Rights Reserved.
5822 *
5823 * Use of this source code is governed by an MIT-style license that can be
5824 * found in the LICENSE file at https://angular.io/license
5825 */
5826
5827 /**
5828 * Generated bundle index. Do not edit.
5829 */
5830
5831 exports.ɵangular_packages_router_router_l = ɵEmptyOutletComponent;
5832 exports.ɵEmptyOutletComponent = ɵEmptyOutletComponent;
5833 exports.ɵangular_packages_router_router_a = ROUTER_FORROOT_GUARD;
5834 exports.ɵangular_packages_router_router_h = RouterInitializer;
5835 exports.ɵangular_packages_router_router_c = createRouterScroller;
5836 exports.ɵangular_packages_router_router_i = getAppInitializer;
5837 exports.ɵangular_packages_router_router_j = getBootstrapListener;
5838 exports.ɵangular_packages_router_router_e = provideForRootGuard;
5839 exports.ɵangular_packages_router_router_d = provideLocationStrategy;
5840 exports.ɵangular_packages_router_router_k = provideRouterInitializer;
5841 exports.ɵangular_packages_router_router_g = rootRoute;
5842 exports.ɵangular_packages_router_router_b = routerNgProbeToken;
5843 exports.ɵangular_packages_router_router_f = setupRouter;
5844 exports.ɵangular_packages_router_router_o = RouterScroller;
5845 exports.ɵangular_packages_router_router_m = Tree;
5846 exports.ɵangular_packages_router_router_n = TreeNode;
5847 exports.RouterLink = RouterLink;
5848 exports.RouterLinkWithHref = RouterLinkWithHref;
5849 exports.RouterLinkActive = RouterLinkActive;
5850 exports.RouterOutlet = RouterOutlet;
5851 exports.ActivationEnd = ActivationEnd;
5852 exports.ActivationStart = ActivationStart;
5853 exports.ChildActivationEnd = ChildActivationEnd;
5854 exports.ChildActivationStart = ChildActivationStart;
5855 exports.GuardsCheckEnd = GuardsCheckEnd;
5856 exports.GuardsCheckStart = GuardsCheckStart;
5857 exports.NavigationCancel = NavigationCancel;
5858 exports.NavigationEnd = NavigationEnd;
5859 exports.NavigationError = NavigationError;
5860 exports.NavigationStart = NavigationStart;
5861 exports.ResolveEnd = ResolveEnd;
5862 exports.ResolveStart = ResolveStart;
5863 exports.RouteConfigLoadEnd = RouteConfigLoadEnd;
5864 exports.RouteConfigLoadStart = RouteConfigLoadStart;
5865 exports.RouterEvent = RouterEvent;
5866 exports.RoutesRecognized = RoutesRecognized;
5867 exports.Scroll = Scroll;
5868 exports.RouteReuseStrategy = RouteReuseStrategy;
5869 exports.Router = Router;
5870 exports.ROUTES = ROUTES;
5871 exports.ROUTER_CONFIGURATION = ROUTER_CONFIGURATION;
5872 exports.ROUTER_INITIALIZER = ROUTER_INITIALIZER;
5873 exports.RouterModule = RouterModule;
5874 exports.provideRoutes = provideRoutes;
5875 exports.ChildrenOutletContexts = ChildrenOutletContexts;
5876 exports.OutletContext = OutletContext;
5877 exports.NoPreloading = NoPreloading;
5878 exports.PreloadAllModules = PreloadAllModules;
5879 exports.PreloadingStrategy = PreloadingStrategy;
5880 exports.RouterPreloader = RouterPreloader;
5881 exports.ActivatedRoute = ActivatedRoute;
5882 exports.ActivatedRouteSnapshot = ActivatedRouteSnapshot;
5883 exports.RouterState = RouterState;
5884 exports.RouterStateSnapshot = RouterStateSnapshot;
5885 exports.PRIMARY_OUTLET = PRIMARY_OUTLET;
5886 exports.convertToParamMap = convertToParamMap;
5887 exports.UrlHandlingStrategy = UrlHandlingStrategy;
5888 exports.DefaultUrlSerializer = DefaultUrlSerializer;
5889 exports.UrlSegment = UrlSegment;
5890 exports.UrlSegmentGroup = UrlSegmentGroup;
5891 exports.UrlSerializer = UrlSerializer;
5892 exports.UrlTree = UrlTree;
5893 exports.VERSION = VERSION;
5894 exports.ɵROUTER_PROVIDERS = ROUTER_PROVIDERS;
5895 exports.ɵflatten = flatten;
5896
5897 Object.defineProperty(exports, '__esModule', { value: true });
5898
5899}));
5900//# sourceMappingURL=router.umd.js.map