-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathssr.mjs
2402 lines (2376 loc) · 100 KB
/
ssr.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { APP_BASE_HREF, PlatformLocation } from '@angular/common';
import { ɵConsole as _Console, InjectionToken, makeEnvironmentProviders, runInInjectionContext, ɵENABLE_ROOT_COMPONENT_BOOTSTRAP as _ENABLE_ROOT_COMPONENT_BOOTSTRAP, ApplicationRef, Compiler, REQUEST, REQUEST_CONTEXT, RESPONSE_INIT, LOCALE_ID, ɵresetCompiledComponents as _resetCompiledComponents } from '@angular/core';
import { ɵSERVER_CONTEXT as _SERVER_CONTEXT, renderModule, renderApplication, platformServer, INITIAL_CONFIG } from '@angular/platform-server';
import { ROUTES, ɵloadChildren as _loadChildren, Router } from '@angular/router';
import Beasties from '../third_party/beasties/index.js';
/**
* Manages server-side assets.
*/
class ServerAssets {
manifest;
/**
* Creates an instance of ServerAsset.
*
* @param manifest - The manifest containing the server assets.
*/
constructor(manifest) {
this.manifest = manifest;
}
/**
* Retrieves the content of a server-side asset using its path.
*
* @param path - The path to the server asset within the manifest.
* @returns The server asset associated with the provided path, as a `ServerAsset` object.
* @throws Error - Throws an error if the asset does not exist.
*/
getServerAsset(path) {
const asset = this.manifest.assets[path];
if (!asset) {
throw new Error(`Server asset '${path}' does not exist.`);
}
return asset;
}
/**
* Checks if a specific server-side asset exists.
*
* @param path - The path to the server asset.
* @returns A boolean indicating whether the asset exists.
*/
hasServerAsset(path) {
return !!this.manifest.assets[path];
}
/**
* Retrieves the asset for 'index.server.html'.
*
* @returns The `ServerAsset` object for 'index.server.html'.
* @throws Error - Throws an error if 'index.server.html' does not exist.
*/
getIndexServerHtml() {
return this.getServerAsset('index.server.html');
}
}
/**
* A set of log messages that should be ignored and not printed to the console.
*/
const IGNORED_LOGS = new Set(['Angular is running in development mode.']);
/**
* Custom implementation of the Angular Console service that filters out specific log messages.
*
* This class extends the internal Angular `ɵConsole` class to provide customized logging behavior.
* It overrides the `log` method to suppress logs that match certain predefined messages.
*/
class Console extends _Console {
/**
* Logs a message to the console if it is not in the set of ignored messages.
*
* @param message - The message to log to the console.
*
* This method overrides the `log` method of the `ɵConsole` class. It checks if the
* message is in the `IGNORED_LOGS` set. If it is not, it delegates the logging to
* the parent class's `log` method. Otherwise, the message is suppressed.
*/
log(message) {
if (!IGNORED_LOGS.has(message)) {
super.log(message);
}
}
}
/**
* The Angular app manifest object.
* This is used internally to store the current Angular app manifest.
*/
let angularAppManifest;
/**
* Sets the Angular app manifest.
*
* @param manifest - The manifest object to set for the Angular application.
*/
function setAngularAppManifest(manifest) {
angularAppManifest = manifest;
}
/**
* Gets the Angular app manifest.
*
* @returns The Angular app manifest.
* @throws Will throw an error if the Angular app manifest is not set.
*/
function getAngularAppManifest() {
if (!angularAppManifest) {
throw new Error('Angular app manifest is not set. ' +
`Please ensure you are using the '@angular/build:application' builder to build your server application.`);
}
return angularAppManifest;
}
/**
* The Angular app engine manifest object.
* This is used internally to store the current Angular app engine manifest.
*/
let angularAppEngineManifest;
/**
* Sets the Angular app engine manifest.
*
* @param manifest - The engine manifest object to set.
*/
function setAngularAppEngineManifest(manifest) {
angularAppEngineManifest = manifest;
}
/**
* Gets the Angular app engine manifest.
*
* @returns The Angular app engine manifest.
* @throws Will throw an error if the Angular app engine manifest is not set.
*/
function getAngularAppEngineManifest() {
if (!angularAppEngineManifest) {
throw new Error('Angular app engine manifest is not set. ' +
`Please ensure you are using the '@angular/build:application' builder to build your server application.`);
}
return angularAppEngineManifest;
}
/**
* Removes the trailing slash from a URL if it exists.
*
* @param url - The URL string from which to remove the trailing slash.
* @returns The URL string without a trailing slash.
*
* @example
* ```js
* stripTrailingSlash('path/'); // 'path'
* stripTrailingSlash('/path'); // '/path'
* stripTrailingSlash('/'); // '/'
* stripTrailingSlash(''); // ''
* ```
*/
function stripTrailingSlash(url) {
// Check if the last character of the URL is a slash
return url.length > 1 && url[url.length - 1] === '/' ? url.slice(0, -1) : url;
}
/**
* Removes the leading slash from a URL if it exists.
*
* @param url - The URL string from which to remove the leading slash.
* @returns The URL string without a leading slash.
*
* @example
* ```js
* stripLeadingSlash('/path'); // 'path'
* stripLeadingSlash('/path/'); // 'path/'
* stripLeadingSlash('/'); // '/'
* stripLeadingSlash(''); // ''
* ```
*/
function stripLeadingSlash(url) {
// Check if the first character of the URL is a slash
return url.length > 1 && url[0] === '/' ? url.slice(1) : url;
}
/**
* Adds a leading slash to a URL if it does not already have one.
*
* @param url - The URL string to which the leading slash will be added.
* @returns The URL string with a leading slash.
*
* @example
* ```js
* addLeadingSlash('path'); // '/path'
* addLeadingSlash('/path'); // '/path'
* ```
*/
function addLeadingSlash(url) {
// Check if the URL already starts with a slash
return url[0] === '/' ? url : `/${url}`;
}
/**
* Adds a trailing slash to a URL if it does not already have one.
*
* @param url - The URL string to which the trailing slash will be added.
* @returns The URL string with a trailing slash.
*
* @example
* ```js
* addTrailingSlash('path'); // 'path/'
* addTrailingSlash('path/'); // 'path/'
* ```
*/
function addTrailingSlash(url) {
// Check if the URL already end with a slash
return url[url.length - 1] === '/' ? url : `${url}/`;
}
/**
* Joins URL parts into a single URL string.
*
* This function takes multiple URL segments, normalizes them by removing leading
* and trailing slashes where appropriate, and then joins them into a single URL.
*
* @param parts - The parts of the URL to join. Each part can be a string with or without slashes.
* @returns The joined URL string, with normalized slashes.
*
* @example
* ```js
* joinUrlParts('path/', '/to/resource'); // '/path/to/resource'
* joinUrlParts('/path/', 'to/resource'); // '/path/to/resource'
* joinUrlParts('', ''); // '/'
* ```
*/
function joinUrlParts(...parts) {
const normalizeParts = [];
for (const part of parts) {
if (part === '') {
// Skip any empty parts
continue;
}
let normalizedPart = part;
if (part[0] === '/') {
normalizedPart = normalizedPart.slice(1);
}
if (part[part.length - 1] === '/') {
normalizedPart = normalizedPart.slice(0, -1);
}
if (normalizedPart !== '') {
normalizeParts.push(normalizedPart);
}
}
return addLeadingSlash(normalizeParts.join('/'));
}
/**
* Strips `/index.html` from the end of a URL's path, if present.
*
* This function is used to convert URLs pointing to an `index.html` file into their directory
* equivalents. For example, it transforms a URL like `http://www.example.com/page/index.html`
* into `http://www.example.com/page`.
*
* @param url - The URL object to process.
* @returns A new URL object with `/index.html` removed from the path, if it was present.
*
* @example
* ```typescript
* const originalUrl = new URL('http://www.example.com/page/index.html');
* const cleanedUrl = stripIndexHtmlFromURL(originalUrl);
* console.log(cleanedUrl.href); // Output: 'http://www.example.com/page'
* ```
*/
function stripIndexHtmlFromURL(url) {
if (url.pathname.endsWith('/index.html')) {
const modifiedURL = new URL(url);
// Remove '/index.html' from the pathname
modifiedURL.pathname = modifiedURL.pathname.slice(0, /** '/index.html'.length */ -11);
return modifiedURL;
}
return url;
}
/**
* Resolves `*` placeholders in a path template by mapping them to corresponding segments
* from a base path. This is useful for constructing paths dynamically based on a given base path.
*
* The function processes the `toPath` string, replacing each `*` placeholder with
* the corresponding segment from the `fromPath`. If the `toPath` contains no placeholders,
* it is returned as-is. Invalid `toPath` formats (not starting with `/`) will throw an error.
*
* @param toPath - A path template string that may contain `*` placeholders. Each `*` is replaced
* by the corresponding segment from the `fromPath`. Static paths (e.g., `/static/path`) are returned
* directly without placeholder replacement.
* @param fromPath - A base path string, split into segments, that provides values for
* replacing `*` placeholders in the `toPath`.
* @returns A resolved path string with `*` placeholders replaced by segments from the `fromPath`,
* or the `toPath` returned unchanged if it contains no placeholders.
*
* @throws If the `toPath` does not start with a `/`, indicating an invalid path format.
*
* @example
* ```typescript
* // Example with placeholders resolved
* const resolvedPath = buildPathWithParams('/*\/details', '/123/abc');
* console.log(resolvedPath); // Outputs: '/123/details'
*
* // Example with a static path
* const staticPath = buildPathWithParams('/static/path', '/base/unused');
* console.log(staticPath); // Outputs: '/static/path'
* ```
*/
function buildPathWithParams(toPath, fromPath) {
if (toPath[0] !== '/') {
throw new Error(`Invalid toPath: The string must start with a '/'. Received: '${toPath}'`);
}
if (fromPath[0] !== '/') {
throw new Error(`Invalid fromPath: The string must start with a '/'. Received: '${fromPath}'`);
}
if (!toPath.includes('/*')) {
return toPath;
}
const fromPathParts = fromPath.split('/');
const toPathParts = toPath.split('/');
const resolvedParts = toPathParts.map((part, index) => toPathParts[index] === '*' ? fromPathParts[index] : part);
return joinUrlParts(...resolvedParts);
}
/**
* Renders an Angular application or module to an HTML string.
*
* This function determines whether the provided `bootstrap` value is an Angular module
* or a bootstrap function and calls the appropriate rendering method (`renderModule` or
* `renderApplication`) based on that determination.
*
* @param html - The HTML string to be used as the initial document content.
* @param bootstrap - Either an Angular module type or a function that returns a promise
* resolving to an `ApplicationRef`.
* @param url - The URL of the application. This is used for server-side rendering to
* correctly handle route-based rendering.
* @param platformProviders - An array of platform providers to be used during the
* rendering process.
* @param serverContext - A string representing the server context, used to provide additional
* context or metadata during server-side rendering.
* @returns A promise that resolves to a string containing the rendered HTML.
*/
function renderAngular(html, bootstrap, url, platformProviders, serverContext) {
const providers = [
{
provide: _SERVER_CONTEXT,
useValue: serverContext,
},
{
// An Angular Console Provider that does not print a set of predefined logs.
provide: _Console,
// Using `useClass` would necessitate decorating `Console` with `@Injectable`,
// which would require switching from `ts_library` to `ng_module`. This change
// would also necessitate various patches of `@angular/bazel` to support ESM.
useFactory: () => new Console(),
},
...platformProviders,
];
// A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.
const urlToRender = stripIndexHtmlFromURL(url).toString();
return isNgModule(bootstrap)
? renderModule(bootstrap, {
url: urlToRender,
document: html,
extraProviders: providers,
})
: renderApplication(bootstrap, {
url: urlToRender,
document: html,
platformProviders: providers,
});
}
/**
* Type guard to determine if a given value is an Angular module.
* Angular modules are identified by the presence of the `ɵmod` static property.
* This function helps distinguish between Angular modules and bootstrap functions.
*
* @param value - The value to be checked.
* @returns True if the value is an Angular module (i.e., it has the `ɵmod` property), false otherwise.
*/
function isNgModule(value) {
return 'ɵmod' in value;
}
/**
* Creates a promise that resolves with the result of the provided `promise` or rejects with an
* `AbortError` if the `AbortSignal` is triggered before the promise resolves.
*
* @param promise - The promise to monitor for completion.
* @param signal - An `AbortSignal` used to monitor for an abort event. If the signal is aborted,
* the returned promise will reject.
* @param errorMessagePrefix - A custom message prefix to include in the error message when the operation is aborted.
* @returns A promise that either resolves with the value of the provided `promise` or rejects with
* an `AbortError` if the `AbortSignal` is triggered.
*
* @throws {AbortError} If the `AbortSignal` is triggered before the `promise` resolves.
*/
function promiseWithAbort(promise, signal, errorMessagePrefix) {
return new Promise((resolve, reject) => {
const abortHandler = () => {
reject(new DOMException(`${errorMessagePrefix} was aborted.\n${signal.reason}`, 'AbortError'));
};
// Check for abort signal
if (signal.aborted) {
abortHandler();
return;
}
signal.addEventListener('abort', abortHandler, { once: true });
promise
.then(resolve)
.catch(reject)
.finally(() => {
signal.removeEventListener('abort', abortHandler);
});
});
}
/**
* The internal path used for the app shell route.
* @internal
*/
const APP_SHELL_ROUTE = 'ng-app-shell';
/**
* Identifies a particular kind of `ServerRoutesFeatureKind`.
* @see {@link ServerRoutesFeature}
* @developerPreview
*/
var ServerRoutesFeatureKind;
(function (ServerRoutesFeatureKind) {
ServerRoutesFeatureKind[ServerRoutesFeatureKind["AppShell"] = 0] = "AppShell";
})(ServerRoutesFeatureKind || (ServerRoutesFeatureKind = {}));
/**
* Different rendering modes for server routes.
* @see {@link provideServerRouting}
* @see {@link ServerRoute}
* @developerPreview
*/
var RenderMode;
(function (RenderMode) {
/** Server-Side Rendering (SSR) mode, where content is rendered on the server for each request. */
RenderMode[RenderMode["Server"] = 0] = "Server";
/** Client-Side Rendering (CSR) mode, where content is rendered on the client side in the browser. */
RenderMode[RenderMode["Client"] = 1] = "Client";
/** Static Site Generation (SSG) mode, where content is pre-rendered at build time and served as static files. */
RenderMode[RenderMode["Prerender"] = 2] = "Prerender";
})(RenderMode || (RenderMode = {}));
/**
* Defines the fallback strategies for Static Site Generation (SSG) routes when a pre-rendered path is not available.
* This is particularly relevant for routes with parameterized URLs where some paths might not be pre-rendered at build time.
* @see {@link ServerRoutePrerenderWithParams}
* @developerPreview
*/
var PrerenderFallback;
(function (PrerenderFallback) {
/**
* Fallback to Server-Side Rendering (SSR) if the pre-rendered path is not available.
* This strategy dynamically generates the page on the server at request time.
*/
PrerenderFallback[PrerenderFallback["Server"] = 0] = "Server";
/**
* Fallback to Client-Side Rendering (CSR) if the pre-rendered path is not available.
* This strategy allows the page to be rendered on the client side.
*/
PrerenderFallback[PrerenderFallback["Client"] = 1] = "Client";
/**
* No fallback; if the path is not pre-rendered, the server will not handle the request.
* This means the application will not provide any response for paths that are not pre-rendered.
*/
PrerenderFallback[PrerenderFallback["None"] = 2] = "None";
})(PrerenderFallback || (PrerenderFallback = {}));
/**
* Token for providing the server routes configuration.
* @internal
*/
const SERVER_ROUTES_CONFIG = new InjectionToken('SERVER_ROUTES_CONFIG');
/**
* Sets up the necessary providers for configuring server routes.
* This function accepts an array of server routes and optional configuration
* options, returning an `EnvironmentProviders` object that encapsulates
* the server routes and configuration settings.
*
* @param routes - An array of server routes to be provided.
* @param options - (Optional) An object containing additional configuration options for server routes.
* @returns An `EnvironmentProviders` instance with the server routes configuration.
*
* @see {@link ServerRoute}
* @see {@link ServerRoutesConfigOptions}
* @see {@link provideServerRouting}
* @deprecated use `provideServerRouting`. This will be removed in version 20.
* @developerPreview
*/
function provideServerRoutesConfig(routes, options) {
if (typeof ngServerMode === 'undefined' || !ngServerMode) {
throw new Error(`The 'provideServerRoutesConfig' function should not be invoked within the browser portion of the application.`);
}
return makeEnvironmentProviders([
{
provide: SERVER_ROUTES_CONFIG,
useValue: { routes, ...options },
},
]);
}
/**
* Sets up the necessary providers for configuring server routes.
* This function accepts an array of server routes and optional configuration
* options, returning an `EnvironmentProviders` object that encapsulates
* the server routes and configuration settings.
*
* @param routes - An array of server routes to be provided.
* @param features - (Optional) server routes features.
* @returns An `EnvironmentProviders` instance with the server routes configuration.
*
* @see {@link ServerRoute}
* @see {@link withAppShell}
* @developerPreview
*/
function provideServerRouting(routes, ...features) {
const config = { routes };
const hasAppShell = features.some((f) => f.ɵkind === ServerRoutesFeatureKind.AppShell);
if (hasAppShell) {
config.appShellRoute = APP_SHELL_ROUTE;
}
const providers = [
{
provide: SERVER_ROUTES_CONFIG,
useValue: config,
},
];
for (const feature of features) {
providers.push(...feature.ɵproviders);
}
return makeEnvironmentProviders(providers);
}
/**
* Configures the app shell route with the provided component.
*
* The app shell serves as the main entry point for the application and is commonly used
* to enable server-side rendering (SSR) of the application shell. It handles requests
* that do not match any specific server route, providing a fallback mechanism and improving
* perceived performance during navigation.
*
* This configuration is particularly useful in applications leveraging Progressive Web App (PWA)
* patterns, such as service workers, to deliver a seamless user experience.
*
* @param component The Angular component to render for the app shell route.
* @returns A server routes feature configuration for the app shell.
*
* @see {@link provideServerRouting}
* @see {@link https://angular.dev/ecosystem/service-workers/app-shell | App shell pattern on Angular.dev}
*/
function withAppShell(component) {
const routeConfig = {
path: APP_SHELL_ROUTE,
};
if ('ɵcmp' in component) {
routeConfig.component = component;
}
else {
routeConfig.loadComponent = component;
}
return {
ɵkind: ServerRoutesFeatureKind.AppShell,
ɵproviders: [
{
provide: ROUTES,
useValue: routeConfig,
multi: true,
},
],
};
}
/**
* A route tree implementation that supports efficient route matching, including support for wildcard routes.
* This structure is useful for organizing and retrieving routes in a hierarchical manner,
* enabling complex routing scenarios with nested paths.
*
* @typeParam AdditionalMetadata - Type of additional metadata that can be associated with route nodes.
*/
class RouteTree {
/**
* The root node of the route tree.
* All routes are stored and accessed relative to this root node.
*/
root = this.createEmptyRouteTreeNode();
/**
* Inserts a new route into the route tree.
* The route is broken down into segments, and each segment is added to the tree.
* Parameterized segments (e.g., :id) are normalized to wildcards (*) for matching purposes.
*
* @param route - The route path to insert into the tree.
* @param metadata - Metadata associated with the route, excluding the route path itself.
*/
insert(route, metadata) {
let node = this.root;
const segments = this.getPathSegments(route);
const normalizedSegments = [];
for (const segment of segments) {
// Replace parameterized segments (e.g., :id) with a wildcard (*) for matching
const normalizedSegment = segment[0] === ':' ? '*' : segment;
let childNode = node.children.get(normalizedSegment);
if (!childNode) {
childNode = this.createEmptyRouteTreeNode();
node.children.set(normalizedSegment, childNode);
}
node = childNode;
normalizedSegments.push(normalizedSegment);
}
// At the leaf node, store the full route and its associated metadata
node.metadata = {
...metadata,
route: addLeadingSlash(normalizedSegments.join('/')),
};
}
/**
* Matches a given route against the route tree and returns the best matching route's metadata.
* The best match is determined by the lowest insertion index, meaning the earliest defined route
* takes precedence.
*
* @param route - The route path to match against the route tree.
* @returns The metadata of the best matching route or `undefined` if no match is found.
*/
match(route) {
const segments = this.getPathSegments(route);
return this.traverseBySegments(segments)?.metadata;
}
/**
* Converts the route tree into a serialized format representation.
* This method converts the route tree into an array of metadata objects that describe the structure of the tree.
* The array represents the routes in a nested manner where each entry includes the route and its associated metadata.
*
* @returns An array of `RouteTreeNodeMetadata` objects representing the route tree structure.
* Each object includes the `route` and associated metadata of a route.
*/
toObject() {
return Array.from(this.traverse());
}
/**
* Constructs a `RouteTree` from an object representation.
* This method is used to recreate a `RouteTree` instance from an array of metadata objects.
* The array should be in the format produced by `toObject`, allowing for the reconstruction of the route tree
* with the same routes and metadata.
*
* @param value - An array of `RouteTreeNodeMetadata` objects that represent the serialized format of the route tree.
* Each object should include a `route` and its associated metadata.
* @returns A new `RouteTree` instance constructed from the provided metadata objects.
*/
static fromObject(value) {
const tree = new RouteTree();
for (const { route, ...metadata } of value) {
tree.insert(route, metadata);
}
return tree;
}
/**
* A generator function that recursively traverses the route tree and yields the metadata of each node.
* This allows for easy and efficient iteration over all nodes in the tree.
*
* @param node - The current node to start the traversal from. Defaults to the root node of the tree.
*/
*traverse(node = this.root) {
if (node.metadata) {
yield node.metadata;
}
for (const childNode of node.children.values()) {
yield* this.traverse(childNode);
}
}
/**
* Extracts the path segments from a given route string.
*
* @param route - The route string from which to extract segments.
* @returns An array of path segments.
*/
getPathSegments(route) {
return route.split('/').filter(Boolean);
}
/**
* Recursively traverses the route tree from a given node, attempting to match the remaining route segments.
* If the node is a leaf node (no more segments to match) and contains metadata, the node is yielded.
*
* This function prioritizes exact segment matches first, followed by wildcard matches (`*`),
* and finally deep wildcard matches (`**`) that consume all segments.
*
* @param segments - The array of route path segments to match against the route tree.
* @param node - The current node in the route tree to start traversal from. Defaults to the root node.
* @param currentIndex - The index of the segment in `remainingSegments` currently being matched.
* Defaults to `0` (the first segment).
*
* @returns The node that best matches the remaining segments or `undefined` if no match is found.
*/
traverseBySegments(segments, node = this.root, currentIndex = 0) {
if (currentIndex >= segments.length) {
return node.metadata ? node : node.children.get('**');
}
if (!node.children.size) {
return undefined;
}
const segment = segments[currentIndex];
// 1. Attempt exact match with the current segment.
const exactMatch = node.children.get(segment);
if (exactMatch) {
const match = this.traverseBySegments(segments, exactMatch, currentIndex + 1);
if (match) {
return match;
}
}
// 2. Attempt wildcard match ('*').
const wildcardMatch = node.children.get('*');
if (wildcardMatch) {
const match = this.traverseBySegments(segments, wildcardMatch, currentIndex + 1);
if (match) {
return match;
}
}
// 3. Attempt double wildcard match ('**').
return node.children.get('**');
}
/**
* Creates an empty route tree node.
* This helper function is used during the tree construction.
*
* @returns A new, empty route tree node.
*/
createEmptyRouteTreeNode() {
return {
children: new Map(),
};
}
}
/**
* The maximum number of module preload link elements that should be added for
* initial scripts.
*/
const MODULE_PRELOAD_MAX = 10;
/**
* Regular expression to match segments preceded by a colon in a string.
*/
const URL_PARAMETER_REGEXP = /(?<!\\):([^/]+)/g;
/**
* An set of HTTP status codes that are considered valid for redirect responses.
*/
const VALID_REDIRECT_RESPONSE_CODES = new Set([301, 302, 303, 307, 308]);
/**
* Handles a single route within the route tree and yields metadata or errors.
*
* @param options - Configuration options for handling the route.
* @returns An async iterable iterator yielding `RouteTreeNodeMetadata` or an error object.
*/
async function* handleRoute(options) {
try {
const { metadata, currentRoutePath, route, compiler, parentInjector, serverConfigRouteTree, entryPointToBrowserMapping, invokeGetPrerenderParams, includePrerenderFallbackRoutes, } = options;
const { redirectTo, loadChildren, loadComponent, children, ɵentryName } = route;
if (ɵentryName && loadComponent) {
appendPreloadToMetadata(ɵentryName, entryPointToBrowserMapping, metadata, true);
}
if (metadata.renderMode === RenderMode.Prerender) {
yield* handleSSGRoute(serverConfigRouteTree, typeof redirectTo === 'string' ? redirectTo : undefined, metadata, parentInjector, invokeGetPrerenderParams, includePrerenderFallbackRoutes);
}
else if (typeof redirectTo === 'string') {
if (metadata.status && !VALID_REDIRECT_RESPONSE_CODES.has(metadata.status)) {
yield {
error: `The '${metadata.status}' status code is not a valid redirect response code. ` +
`Please use one of the following redirect response codes: ${[...VALID_REDIRECT_RESPONSE_CODES.values()].join(', ')}.`,
};
}
else {
yield { ...metadata, redirectTo: resolveRedirectTo(metadata.route, redirectTo) };
}
}
else {
yield metadata;
}
// Recursively process child routes
if (children?.length) {
yield* traverseRoutesConfig({
...options,
routes: children,
parentRoute: currentRoutePath,
parentPreloads: metadata.preload,
});
}
// Load and process lazy-loaded child routes
if (loadChildren) {
if (ɵentryName) {
// When using `loadChildren`, the entire feature area (including multiple routes) is loaded.
// As a result, we do not want all dynamic-import dependencies to be preload, because it involves multiple dependencies
// across different child routes. In contrast, `loadComponent` only loads a single component, which allows
// for precise control over preloading, ensuring that the files preloaded are exactly those required for that specific route.
appendPreloadToMetadata(ɵentryName, entryPointToBrowserMapping, metadata, false);
}
const loadedChildRoutes = await _loadChildren(route, compiler, parentInjector).toPromise();
if (loadedChildRoutes) {
const { routes: childRoutes, injector = parentInjector } = loadedChildRoutes;
yield* traverseRoutesConfig({
...options,
routes: childRoutes,
parentInjector: injector,
parentRoute: currentRoutePath,
parentPreloads: metadata.preload,
});
}
}
}
catch (error) {
yield {
error: `Error in handleRoute for '${options.currentRoutePath}': ${error.message}`,
};
}
}
/**
* Traverses an array of route configurations to generate route tree node metadata.
*
* This function processes each route and its children, handling redirects, SSG (Static Site Generation) settings,
* and lazy-loaded routes. It yields route metadata for each route and its potential variants.
*
* @param options - The configuration options for traversing routes.
* @returns An async iterable iterator yielding either route tree node metadata or an error object with an error message.
*/
async function* traverseRoutesConfig(options) {
const { routes: routeConfigs, parentPreloads, parentRoute, serverConfigRouteTree } = options;
for (const route of routeConfigs) {
const { matcher, path = matcher ? '**' : '' } = route;
const currentRoutePath = joinUrlParts(parentRoute, path);
if (matcher && serverConfigRouteTree) {
let foundMatch = false;
for (const matchedMetaData of serverConfigRouteTree.traverse()) {
if (!matchedMetaData.route.startsWith(currentRoutePath)) {
continue;
}
foundMatch = true;
matchedMetaData.presentInClientRouter = true;
if (matchedMetaData.renderMode === RenderMode.Prerender) {
yield {
error: `The route '${stripLeadingSlash(currentRoutePath)}' is set for prerendering but has a defined matcher. ` +
`Routes with matchers cannot use prerendering. Please specify a different 'renderMode'.`,
};
continue;
}
yield* handleRoute({
...options,
currentRoutePath,
route,
metadata: {
...matchedMetaData,
preload: parentPreloads,
route: matchedMetaData.route,
presentInClientRouter: undefined,
},
});
}
if (!foundMatch) {
yield {
error: `The route '${stripLeadingSlash(currentRoutePath)}' has a defined matcher but does not ` +
'match any route in the server routing configuration. Please ensure this route is added to the server routing configuration.',
};
}
continue;
}
let matchedMetaData;
if (serverConfigRouteTree) {
matchedMetaData = serverConfigRouteTree.match(currentRoutePath);
if (!matchedMetaData) {
yield {
error: `The '${stripLeadingSlash(currentRoutePath)}' route does not match any route defined in the server routing configuration. ` +
'Please ensure this route is added to the server routing configuration.',
};
continue;
}
matchedMetaData.presentInClientRouter = true;
}
yield* handleRoute({
...options,
metadata: {
renderMode: RenderMode.Prerender,
...matchedMetaData,
preload: parentPreloads,
// Match Angular router behavior
// ['one', 'two', ''] -> 'one/two/'
// ['one', 'two', 'three'] -> 'one/two/three'
route: path === '' ? addTrailingSlash(currentRoutePath) : currentRoutePath,
presentInClientRouter: undefined,
},
currentRoutePath,
route,
});
}
}
/**
* Appends preload information to the metadata object based on the specified entry-point and chunk mappings.
*
* This function extracts preload data for a given entry-point from the provided chunk mappings. It adds the
* corresponding browser bundles to the metadata's preload list, ensuring no duplicates and limiting the total
* preloads to a predefined maximum.
*/
function appendPreloadToMetadata(entryName, entryPointToBrowserMapping, metadata, includeDynamicImports) {
const existingPreloads = metadata.preload ?? [];
if (!entryPointToBrowserMapping || existingPreloads.length >= MODULE_PRELOAD_MAX) {
return;
}
const preload = entryPointToBrowserMapping[entryName];
if (!preload?.length) {
return;
}
// Merge existing preloads with new ones, ensuring uniqueness and limiting the total to the maximum allowed.
const combinedPreloads = new Set(existingPreloads);
for (const { dynamicImport, path } of preload) {
if (dynamicImport && !includeDynamicImports) {
continue;
}
combinedPreloads.add(path);
if (combinedPreloads.size === MODULE_PRELOAD_MAX) {
break;
}
}
metadata.preload = Array.from(combinedPreloads);
}
/**
* Handles SSG (Static Site Generation) routes by invoking `getPrerenderParams` and yielding
* all parameterized paths, returning any errors encountered.
*
* @param serverConfigRouteTree - The tree representing the server's routing setup.
* @param redirectTo - Optional path to redirect to, if specified.
* @param metadata - The metadata associated with the route tree node.
* @param parentInjector - The dependency injection container for the parent route.
* @param invokeGetPrerenderParams - A flag indicating whether to invoke the `getPrerenderParams` function.
* @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result.
* @returns An async iterable iterator that yields route tree node metadata for each SSG path or errors.
*/
async function* handleSSGRoute(serverConfigRouteTree, redirectTo, metadata, parentInjector, invokeGetPrerenderParams, includePrerenderFallbackRoutes) {
if (metadata.renderMode !== RenderMode.Prerender) {
throw new Error(`'handleSSGRoute' was called for a route which rendering mode is not prerender.`);
}
const { route: currentRoutePath, fallback, ...meta } = metadata;
const getPrerenderParams = 'getPrerenderParams' in meta ? meta.getPrerenderParams : undefined;
if ('getPrerenderParams' in meta) {
delete meta['getPrerenderParams'];
}
if (redirectTo !== undefined) {
meta.redirectTo = resolveRedirectTo(currentRoutePath, redirectTo);
}
if (!URL_PARAMETER_REGEXP.test(currentRoutePath)) {
// Route has no parameters
yield {
...meta,
route: currentRoutePath,
};
return;
}
if (invokeGetPrerenderParams) {
if (!getPrerenderParams) {
yield {
error: `The '${stripLeadingSlash(currentRoutePath)}' route uses prerendering and includes parameters, but 'getPrerenderParams' ` +
`is missing. Please define 'getPrerenderParams' function for this route in your server routing configuration ` +
`or specify a different 'renderMode'.`,
};
return;
}
if (serverConfigRouteTree) {
// Automatically resolve dynamic parameters for nested routes.
const catchAllRoutePath = joinUrlParts(currentRoutePath, '**');
const match = serverConfigRouteTree.match(catchAllRoutePath);
if (match && match.renderMode === RenderMode.Prerender && !('getPrerenderParams' in match)) {
serverConfigRouteTree.insert(catchAllRoutePath, {
...match,
presentInClientRouter: true,
getPrerenderParams,
});
}
}
const parameters = await runInInjectionContext(parentInjector, () => getPrerenderParams());
try {
for (const params of parameters) {
const routeWithResolvedParams = currentRoutePath.replace(URL_PARAMETER_REGEXP, (match) => {
const parameterName = match.slice(1);
const value = params[parameterName];
if (typeof value !== 'string') {
throw new Error(`The 'getPrerenderParams' function defined for the '${stripLeadingSlash(currentRoutePath)}' route ` +
`returned a non-string value for parameter '${parameterName}'. ` +
`Please make sure the 'getPrerenderParams' function returns values for all parameters ` +
'specified in this route.');
}
return value;
});
yield {
...meta,
route: routeWithResolvedParams,
redirectTo: redirectTo === undefined
? undefined
: resolveRedirectTo(routeWithResolvedParams, redirectTo),
};
}
}
catch (error) {
yield { error: `${error.message}` };
return;
}
}
// Handle fallback render modes
if (includePrerenderFallbackRoutes &&
(fallback !== PrerenderFallback.None || !invokeGetPrerenderParams)) {
yield {
...meta,
route: currentRoutePath,
renderMode: fallback === PrerenderFallback.Client ? RenderMode.Client : RenderMode.Server,
};
}
}
/**
* Resolves the `redirectTo` property for a given route.
*
* This function processes the `redirectTo` property to ensure that it correctly
* resolves relative to the current route path. If `redirectTo` is an absolute path,
* it is returned as is. If it is a relative path, it is resolved based on the current route path.
*