forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute-config.ts
398 lines (366 loc) · 13 KB
/
route-config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
EnvironmentProviders,
InjectionToken,
Provider,
Type,
inject,
makeEnvironmentProviders,
provideEnvironmentInitializer,
} from '@angular/core';
import { provideServerRendering as provideServerRenderingPlatformServer } from '@angular/platform-server';
import { type DefaultExport, ROUTES, type Route } from '@angular/router';
/**
* The internal path used for the app shell route.
* @internal
*/
const APP_SHELL_ROUTE = 'ng-app-shell';
/**
* Identifies a particular kind of `ServerRenderingFeatureKind`.
* @see {@link ServerRenderingFeature}
*/
enum ServerRenderingFeatureKind {
AppShell,
ServerRoutes,
}
/**
* Helper type to represent a server routes feature.
* @see {@link ServerRenderingFeatureKind}
*/
interface ServerRenderingFeature<FeatureKind extends ServerRenderingFeatureKind> {
ɵkind: FeatureKind;
ɵproviders: (Provider | EnvironmentProviders)[];
}
/**
* Different rendering modes for server routes.
* @see {@link withRoutes}
* @see {@link ServerRoute}
*/
export enum RenderMode {
/** Server-Side Rendering (SSR) mode, where content is rendered on the server for each request. */
Server,
/** Client-Side Rendering (CSR) mode, where content is rendered on the client side in the browser. */
Client,
/** Static Site Generation (SSG) mode, where content is pre-rendered at build time and served as static files. */
Prerender,
}
/**
* 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}
*/
export enum 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.
*/
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.
*/
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.
*/
None,
}
/**
* Common interface for server routes, providing shared properties.
*/
export interface ServerRouteCommon {
/** The path associated with this route. */
path: string;
/** Optional additional headers to include in the response for this route. */
headers?: Record<string, string>;
/** Optional status code to return for this route. */
status?: number;
}
/**
* A server route that uses Client-Side Rendering (CSR) mode.
* @see {@link RenderMode}
*/
export interface ServerRouteClient extends ServerRouteCommon {
/** Specifies that the route uses Client-Side Rendering (CSR) mode. */
renderMode: RenderMode.Client;
}
/**
* A server route that uses Static Site Generation (SSG) mode.
* @see {@link RenderMode}
*/
export interface ServerRoutePrerender extends Omit<ServerRouteCommon, 'status'> {
/** Specifies that the route uses Static Site Generation (SSG) mode. */
renderMode: RenderMode.Prerender;
/** Fallback cannot be specified unless `getPrerenderParams` is used. */
fallback?: never;
}
/**
* A server route configuration that uses Static Site Generation (SSG) mode, including support for routes with parameters.
* @see {@link RenderMode}
* @see {@link ServerRoutePrerender}
* @see {@link PrerenderFallback}
*/
export interface ServerRoutePrerenderWithParams extends Omit<ServerRoutePrerender, 'fallback'> {
/**
* Optional strategy to use if the SSG path is not pre-rendered.
* This is especially relevant for routes with parameterized URLs, where some paths may not be pre-rendered at build time.
*
* This property determines how to handle requests for paths that are not pre-rendered:
* - `PrerenderFallback.Server`: Use Server-Side Rendering (SSR) to dynamically generate the page at request time.
* - `PrerenderFallback.Client`: Use Client-Side Rendering (CSR) to fetch and render the page on the client side.
* - `PrerenderFallback.None`: No fallback; if the path is not pre-rendered, the server will not handle the request.
*
* @default `PrerenderFallback.Server` if not provided.
*/
fallback?: PrerenderFallback;
/**
* A function that returns a Promise resolving to an array of objects, each representing a route path with URL parameters.
* This function runs in the injector context, allowing access to Angular services and dependencies.
*
* It also works for catch-all routes (e.g., `/**`), where the parameter name will be `**` and the return value will be
* the segments of the path, such as `/foo/bar`. These routes can also be combined, e.g., `/product/:id/**`,
* where both a parameterized segment (`:id`) and a catch-all segment (`**`) can be used together to handle more complex paths.
*
* @returns A Promise resolving to an array where each element is an object with string keys (representing URL parameter names)
* and string values (representing the corresponding values for those parameters in the route path).
*
* @example
* ```typescript
* export const serverRouteConfig: ServerRoutes[] = [
* {
* path: '/product/:id',
* renderMode: RenderMode.Prerender,
* async getPrerenderParams() {
* const productService = inject(ProductService);
* const ids = await productService.getIds(); // Assuming this returns ['1', '2', '3']
*
* return ids.map(id => ({ id })); // Generates paths like: ['product/1', 'product/2', 'product/3']
* },
* },
* {
* path: '/product/:id/**',
* renderMode: RenderMode.Prerender,
* async getPrerenderParams() {
* return [
* { id: '1', '**': 'laptop/3' },
* { id: '2', '**': 'laptop/4' }
* ]; // Generates paths like: ['product/1/laptop/3', 'product/2/laptop/4']
* },
* },
* ];
* ```
*/
getPrerenderParams: () => Promise<Record<string, string>[]>;
}
/**
* A server route that uses Server-Side Rendering (SSR) mode.
* @see {@link RenderMode}
*/
export interface ServerRouteServer extends ServerRouteCommon {
/** Specifies that the route uses Server-Side Rendering (SSR) mode. */
renderMode: RenderMode.Server;
}
/**
* Server route configuration.
* @see {@link withRoutes}
*/
export type ServerRoute =
| ServerRouteClient
| ServerRoutePrerender
| ServerRoutePrerenderWithParams
| ServerRouteServer;
/**
* Configuration value for server routes configuration.
* @internal
*/
export interface ServerRoutesConfig {
/**
* Defines the route to be used as the app shell.
*/
appShellRoute?: string;
/** List of server routes for the application. */
routes: ServerRoute[];
}
/**
* Token for providing the server routes configuration.
* @internal
*/
export const SERVER_ROUTES_CONFIG = new InjectionToken<ServerRoutesConfig>('SERVER_ROUTES_CONFIG');
/**
* Configures server-side routing for the application.
*
* This function registers an array of `ServerRoute` definitions, enabling server-side rendering
* for specific URL paths. These routes are used to pre-render content on the server, improving
* initial load performance and SEO.
*
* @param routes - An array of `ServerRoute` objects, each defining a server-rendered route.
* @returns A `ServerRenderingFeature` object configuring server-side routes.
*
* @example
* ```ts
* import { provideServerRendering, withRoutes, ServerRoute, RenderMode } from '@angular/ssr';
*
* const serverRoutes: ServerRoute[] = [
* {
* route: '', // This renders the "/" route on the client (CSR)
* renderMode: RenderMode.Client,
* },
* {
* route: 'about', // This page is static, so we prerender it (SSG)
* renderMode: RenderMode.Prerender,
* },
* {
* route: 'profile', // This page requires user-specific data, so we use SSR
* renderMode: RenderMode.Server,
* },
* {
* route: '**', // All other routes will be rendered on the server (SSR)
* renderMode: RenderMode.Server,
* },
* ];
*
* provideServerRendering(withRoutes(serverRoutes));
* ```
*
* @see {@link provideServerRendering}
* @see {@link ServerRoute}
*/
export function withRoutes(
routes: ServerRoute[],
): ServerRenderingFeature<ServerRenderingFeatureKind.ServerRoutes> {
const config: ServerRoutesConfig = { routes };
return {
ɵkind: ServerRenderingFeatureKind.ServerRoutes,
ɵproviders: [
{
provide: SERVER_ROUTES_CONFIG,
useValue: config,
},
],
};
}
/**
* Configures the shell of the application.
*
* The app shell is a minimal, static HTML page that is served immediately, while the
* full Angular application loads in the background. This improves perceived performance
* by providing instant feedback to the user.
*
* This function configures the app shell route, which serves the provided component for
* requests that do not match any defined server routes.
*
* @param component - The Angular component to render for the app shell. Can be a direct
* component type or a dynamic import function.
* @returns A `ServerRenderingFeature` object configuring the app shell.
*
* @example
* ```ts
* import { provideServerRendering, withAppShell, withRoutes } from '@angular/ssr';
* import { AppShellComponent } from './app-shell.component';
*
* provideServerRendering(
* withRoutes(serverRoutes),
* withAppShell(AppShellComponent)
* );
* ```
*
* @example
* ```ts
* import { provideServerRendering, withAppShell, withRoutes } from '@angular/ssr';
*
* provideServerRendering(
* withRoutes(serverRoutes),
* withAppShell(() =>
* import('./app-shell.component').then((m) => m.AppShellComponent)
* )
* );
* ```
*
* @see {@link provideServerRendering}
* @see {@link https://angular.dev/ecosystem/service-workers/app-shell App shell pattern on Angular.dev}
*/
export function withAppShell(
component: Type<unknown> | (() => Promise<Type<unknown> | DefaultExport<Type<unknown>>>),
): ServerRenderingFeature<ServerRenderingFeatureKind.AppShell> {
const routeConfig: Route = {
path: APP_SHELL_ROUTE,
};
if ('ɵcmp' in component) {
routeConfig.component = component as Type<unknown>;
} else {
routeConfig.loadComponent = component as () => Promise<Type<unknown>>;
}
return {
ɵkind: ServerRenderingFeatureKind.AppShell,
ɵproviders: [
{
provide: ROUTES,
useValue: routeConfig,
multi: true,
},
provideEnvironmentInitializer(() => {
const config = inject(SERVER_ROUTES_CONFIG);
config.appShellRoute = APP_SHELL_ROUTE;
}),
],
};
}
/**
* Configures server-side rendering for an Angular application.
*
* This function sets up the necessary providers for server-side rendering, including
* support for server routes and app shell. It combines features configured using
* `withRoutes` and `withAppShell` to provide a comprehensive server-side rendering setup.
*
* @param features - Optional features to configure additional server rendering behaviors.
* @returns An `EnvironmentProviders` instance with the server-side rendering configuration.
*
* @example
* Basic example of how you can enable server-side rendering in your application
* when using the `bootstrapApplication` function:
*
* ```ts
* import { bootstrapApplication } from '@angular/platform-browser';
* import { provideServerRendering, withRoutes, withAppShell } from '@angular/ssr';
* import { AppComponent } from './app/app.component';
* import { SERVER_ROUTES } from './app/app.server.routes';
* import { AppShellComponent } from './app/app-shell.component';
*
* bootstrapApplication(AppComponent, {
* providers: [
* provideServerRendering(
* withRoutes(SERVER_ROUTES),
* withAppShell(AppShellComponent)
* )
* ]
* });
* ```
* @see {@link withRoutes} configures server-side routing
* @see {@link withAppShell} configures the application shell
*/
export function provideServerRendering(
...features: ServerRenderingFeature<ServerRenderingFeatureKind>[]
): EnvironmentProviders {
let hasAppShell = false;
let hasServerRoutes = false;
const providers: (Provider | EnvironmentProviders)[] = [provideServerRenderingPlatformServer()];
for (const { ɵkind, ɵproviders } of features) {
hasAppShell ||= ɵkind === ServerRenderingFeatureKind.AppShell;
hasServerRoutes ||= ɵkind === ServerRenderingFeatureKind.ServerRoutes;
providers.push(...ɵproviders);
}
if (!hasServerRoutes && hasAppShell) {
throw new Error(
`Configuration error: found 'withAppShell()' without 'withRoutes()' in the same call to 'provideServerRendering()'.` +
`The 'withAppShell()' function requires 'withRoutes()' to be used.`,
);
}
return makeEnvironmentProviders(providers);
}