@angular/ssr 0.0.0-PLACEHOLDER → 17.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,289 @@
1
+ import { ɵSERVER_CONTEXT, INITIAL_CONFIG, renderApplication, renderModule } from '@angular/platform-server';
2
+ import * as fs from 'node:fs';
3
+ import { resolve, dirname } from 'node:path';
4
+ import { URL } from 'node:url';
5
+ import Critters from 'critters';
6
+ import { readFile } from 'node:fs/promises';
7
+
8
+ /**
9
+ * Pattern used to extract the media query set by Critters in an `onload` handler.
10
+ */
11
+ const MEDIA_SET_HANDLER_PATTERN = /^this\.media=["'](.*)["'];?$/;
12
+ /**
13
+ * Name of the attribute used to save the Critters media query so it can be re-assigned on load.
14
+ */
15
+ const CSP_MEDIA_ATTR = 'ngCspMedia';
16
+ /**
17
+ * Script text used to change the media value of the link tags.
18
+ */
19
+ const LINK_LOAD_SCRIPT_CONTENT = [
20
+ `(() => {`,
21
+ // Save the `children` in a variable since they're a live DOM node collection.
22
+ // We iterate over the direct descendants, instead of going through a `querySelectorAll`,
23
+ // because we know that the tags will be directly inside the `head`.
24
+ ` const children = document.head.children;`,
25
+ // Declare `onLoad` outside the loop to avoid leaking memory.
26
+ // Can't be an arrow function, because we need `this` to refer to the DOM node.
27
+ ` function onLoad() {this.media = this.getAttribute('${CSP_MEDIA_ATTR}');}`,
28
+ // Has to use a plain for loop, because some browsers don't support
29
+ // `forEach` on `children` which is a `HTMLCollection`.
30
+ ` for (let i = 0; i < children.length; i++) {`,
31
+ ` const child = children[i];`,
32
+ ` child.hasAttribute('${CSP_MEDIA_ATTR}') && child.addEventListener('load', onLoad);`,
33
+ ` }`,
34
+ `})();`,
35
+ ].join('\n');
36
+ class CrittersExtended extends Critters {
37
+ constructor(optionsExtended, resourceCache) {
38
+ super({
39
+ logger: {
40
+ warn: (s) => this.warnings.push(s),
41
+ error: (s) => this.errors.push(s),
42
+ info: () => { },
43
+ },
44
+ logLevel: 'warn',
45
+ path: optionsExtended.outputPath,
46
+ publicPath: optionsExtended.deployUrl,
47
+ compress: !!optionsExtended.minify,
48
+ pruneSource: false,
49
+ reduceInlineStyles: false,
50
+ mergeStylesheets: false,
51
+ // Note: if `preload` changes to anything other than `media`, the logic in
52
+ // `embedLinkedStylesheetOverride` will have to be updated.
53
+ preload: 'media',
54
+ noscriptFallback: true,
55
+ inlineFonts: true,
56
+ });
57
+ this.optionsExtended = optionsExtended;
58
+ this.resourceCache = resourceCache;
59
+ this.warnings = [];
60
+ this.errors = [];
61
+ this.addedCspScriptsDocuments = new WeakSet();
62
+ this.documentNonces = new WeakMap();
63
+ /**
64
+ * Override of the Critters `embedLinkedStylesheet` method
65
+ * that makes it work with Angular's CSP APIs.
66
+ */
67
+ this.embedLinkedStylesheetOverride = async (link, document) => {
68
+ if (link.getAttribute('media') === 'print' && link.next?.name === 'noscript') {
69
+ // Workaround for https://github.com/GoogleChromeLabs/critters/issues/64
70
+ // NB: this is only needed for the webpack based builders.
71
+ const media = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);
72
+ if (media) {
73
+ link.removeAttribute('onload');
74
+ link.setAttribute('media', media[1]);
75
+ link?.next?.remove();
76
+ }
77
+ }
78
+ const returnValue = await this.initialEmbedLinkedStylesheet(link, document);
79
+ const cspNonce = this.findCspNonce(document);
80
+ if (cspNonce) {
81
+ const crittersMedia = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);
82
+ if (crittersMedia) {
83
+ // If there's a Critters-generated `onload` handler and the file has an Angular CSP nonce,
84
+ // we have to remove the handler, because it's incompatible with CSP. We save the value
85
+ // in a different attribute and we generate a script tag with the nonce that uses
86
+ // `addEventListener` to apply the media query instead.
87
+ link.removeAttribute('onload');
88
+ link.setAttribute(CSP_MEDIA_ATTR, crittersMedia[1]);
89
+ this.conditionallyInsertCspLoadingScript(document, cspNonce);
90
+ }
91
+ // Ideally we would hook in at the time Critters inserts the `style` tags, but there isn't
92
+ // a way of doing that at the moment so we fall back to doing it any time a `link` tag is
93
+ // inserted. We mitigate it by only iterating the direct children of the `<head>` which
94
+ // should be pretty shallow.
95
+ document.head.children.forEach((child) => {
96
+ if (child.tagName === 'style' && !child.hasAttribute('nonce')) {
97
+ child.setAttribute('nonce', cspNonce);
98
+ }
99
+ });
100
+ }
101
+ return returnValue;
102
+ };
103
+ // We can't use inheritance to override `embedLinkedStylesheet`, because it's not declared in
104
+ // the `Critters` .d.ts which means that we can't call the `super` implementation. TS doesn't
105
+ // allow for `super` to be cast to a different type.
106
+ this.initialEmbedLinkedStylesheet = this.embedLinkedStylesheet;
107
+ this.embedLinkedStylesheet = this.embedLinkedStylesheetOverride;
108
+ }
109
+ async readFile(path) {
110
+ let resourceContent = this.resourceCache.get(path);
111
+ if (resourceContent === undefined) {
112
+ resourceContent = await readFile(path, 'utf-8');
113
+ this.resourceCache.set(path, resourceContent);
114
+ }
115
+ return resourceContent;
116
+ }
117
+ /**
118
+ * Finds the CSP nonce for a specific document.
119
+ */
120
+ findCspNonce(document) {
121
+ if (this.documentNonces.has(document)) {
122
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
123
+ return this.documentNonces.get(document);
124
+ }
125
+ // HTML attribute are case-insensitive, but the parser used by Critters is case-sensitive.
126
+ const nonceElement = document.querySelector('[ngCspNonce], [ngcspnonce]');
127
+ const cspNonce = nonceElement?.getAttribute('ngCspNonce') || nonceElement?.getAttribute('ngcspnonce') || null;
128
+ this.documentNonces.set(document, cspNonce);
129
+ return cspNonce;
130
+ }
131
+ /**
132
+ * Inserts the `script` tag that swaps the critical CSS at runtime,
133
+ * if one hasn't been inserted into the document already.
134
+ */
135
+ conditionallyInsertCspLoadingScript(document, nonce) {
136
+ if (this.addedCspScriptsDocuments.has(document)) {
137
+ return;
138
+ }
139
+ if (document.head.textContent.includes(LINK_LOAD_SCRIPT_CONTENT)) {
140
+ // Script was already added during the build.
141
+ this.addedCspScriptsDocuments.add(document);
142
+ return;
143
+ }
144
+ const script = document.createElement('script');
145
+ script.setAttribute('nonce', nonce);
146
+ script.textContent = LINK_LOAD_SCRIPT_CONTENT;
147
+ // Append the script to the head since it needs to
148
+ // run as early as possible, after the `link` tags.
149
+ document.head.appendChild(script);
150
+ this.addedCspScriptsDocuments.add(document);
151
+ }
152
+ }
153
+ class InlineCriticalCssProcessor {
154
+ constructor(options) {
155
+ this.options = options;
156
+ this.resourceCache = new Map();
157
+ }
158
+ async process(html, options) {
159
+ const critters = new CrittersExtended({ ...this.options, ...options }, this.resourceCache);
160
+ const content = await critters.process(html);
161
+ return {
162
+ content,
163
+ errors: critters.errors.length ? critters.errors : undefined,
164
+ warnings: critters.warnings.length ? critters.warnings : undefined,
165
+ };
166
+ }
167
+ }
168
+
169
+ const SSG_MARKER_REGEXP = /ng-server-context=["']\w*\|?ssg\|?\w*["']/;
170
+ /**
171
+ * A common rendering engine utility. This abstracts the logic
172
+ * for handling the platformServer compiler, the module cache, and
173
+ * the document loader
174
+ */
175
+ class CommonEngine {
176
+ constructor(bootstrap, providers = []) {
177
+ this.bootstrap = bootstrap;
178
+ this.providers = providers;
179
+ this.templateCache = new Map();
180
+ this.pageIsSSG = new Map();
181
+ this.inlineCriticalCssProcessor = new InlineCriticalCssProcessor({
182
+ minify: false,
183
+ });
184
+ }
185
+ /**
186
+ * Render an HTML document for a specific URL with specified
187
+ * render options
188
+ */
189
+ async render(opts) {
190
+ const { inlineCriticalCss = true, url } = opts;
191
+ if (opts.publicPath && opts.documentFilePath && url !== undefined) {
192
+ const pathname = canParseUrl(url) ? new URL(url).pathname : url;
193
+ // Remove leading forward slash.
194
+ const pagePath = resolve(opts.publicPath, pathname.substring(1), 'index.html');
195
+ if (pagePath !== resolve(opts.documentFilePath)) {
196
+ // View path doesn't match with prerender path.
197
+ const pageIsSSG = this.pageIsSSG.get(pagePath);
198
+ if (pageIsSSG === undefined) {
199
+ if (await exists(pagePath)) {
200
+ const content = await fs.promises.readFile(pagePath, 'utf-8');
201
+ const isSSG = SSG_MARKER_REGEXP.test(content);
202
+ this.pageIsSSG.set(pagePath, isSSG);
203
+ if (isSSG) {
204
+ return content;
205
+ }
206
+ }
207
+ else {
208
+ this.pageIsSSG.set(pagePath, false);
209
+ }
210
+ }
211
+ else if (pageIsSSG) {
212
+ // Serve pre-rendered page.
213
+ return fs.promises.readFile(pagePath, 'utf-8');
214
+ }
215
+ }
216
+ }
217
+ // if opts.document dosen't exist then opts.documentFilePath must
218
+ const extraProviders = [
219
+ { provide: ɵSERVER_CONTEXT, useValue: 'ssr' },
220
+ ...(opts.providers ?? []),
221
+ ...this.providers,
222
+ ];
223
+ let document = opts.document;
224
+ if (!document && opts.documentFilePath) {
225
+ document = await this.getDocument(opts.documentFilePath);
226
+ }
227
+ if (document) {
228
+ extraProviders.push({
229
+ provide: INITIAL_CONFIG,
230
+ useValue: {
231
+ document,
232
+ url: opts.url,
233
+ },
234
+ });
235
+ }
236
+ const moduleOrFactory = this.bootstrap || opts.bootstrap;
237
+ if (!moduleOrFactory) {
238
+ throw new Error('A module or bootstrap option must be provided.');
239
+ }
240
+ const html = await (isBootstrapFn(moduleOrFactory)
241
+ ? renderApplication(moduleOrFactory, { platformProviders: extraProviders })
242
+ : renderModule(moduleOrFactory, { extraProviders }));
243
+ if (!inlineCriticalCss) {
244
+ return html;
245
+ }
246
+ const { content, errors, warnings } = await this.inlineCriticalCssProcessor.process(html, {
247
+ outputPath: opts.publicPath ?? (opts.documentFilePath ? dirname(opts.documentFilePath) : ''),
248
+ });
249
+ // eslint-disable-next-line no-console
250
+ warnings?.forEach((m) => console.warn(m));
251
+ // eslint-disable-next-line no-console
252
+ errors?.forEach((m) => console.error(m));
253
+ return content;
254
+ }
255
+ /** Retrieve the document from the cache or the filesystem */
256
+ async getDocument(filePath) {
257
+ let doc = this.templateCache.get(filePath);
258
+ if (!doc) {
259
+ doc = await fs.promises.readFile(filePath, 'utf-8');
260
+ this.templateCache.set(filePath, doc);
261
+ }
262
+ return doc;
263
+ }
264
+ }
265
+ async function exists(path) {
266
+ try {
267
+ await fs.promises.access(path, fs.constants.F_OK);
268
+ return true;
269
+ }
270
+ catch {
271
+ return false;
272
+ }
273
+ }
274
+ function isBootstrapFn(value) {
275
+ // We can differentiate between a module and a bootstrap function by reading `cmp`:
276
+ return typeof value === 'function' && !('ɵmod' in value);
277
+ }
278
+ // The below can be removed in favor of URL.canParse() when Node.js 18 is dropped
279
+ function canParseUrl(url) {
280
+ try {
281
+ return !!new URL(url);
282
+ }
283
+ catch {
284
+ return false;
285
+ }
286
+ }
287
+
288
+ export { CommonEngine };
289
+ //# sourceMappingURL=ssr.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssr.mjs","sources":["../../../../../../../packages/angular/ssr/src/inline-css-processor.ts","../../../../../../../packages/angular/ssr/src/common-engine.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\nimport Critters from 'critters';\nimport { readFile } from 'node:fs/promises';\n\n/**\n * Pattern used to extract the media query set by Critters in an `onload` handler.\n */\nconst MEDIA_SET_HANDLER_PATTERN = /^this\\.media=[\"'](.*)[\"'];?$/;\n\n/**\n * Name of the attribute used to save the Critters media query so it can be re-assigned on load.\n */\nconst CSP_MEDIA_ATTR = 'ngCspMedia';\n\n/**\n * Script text used to change the media value of the link tags.\n */\nconst LINK_LOAD_SCRIPT_CONTENT = [\n `(() => {`,\n // Save the `children` in a variable since they're a live DOM node collection.\n // We iterate over the direct descendants, instead of going through a `querySelectorAll`,\n // because we know that the tags will be directly inside the `head`.\n ` const children = document.head.children;`,\n // Declare `onLoad` outside the loop to avoid leaking memory.\n // Can't be an arrow function, because we need `this` to refer to the DOM node.\n ` function onLoad() {this.media = this.getAttribute('${CSP_MEDIA_ATTR}');}`,\n // Has to use a plain for loop, because some browsers don't support\n // `forEach` on `children` which is a `HTMLCollection`.\n ` for (let i = 0; i < children.length; i++) {`,\n ` const child = children[i];`,\n ` child.hasAttribute('${CSP_MEDIA_ATTR}') && child.addEventListener('load', onLoad);`,\n ` }`,\n `})();`,\n].join('\\n');\n\nexport interface InlineCriticalCssProcessOptions {\n outputPath?: string;\n}\n\nexport interface InlineCriticalCssProcessorOptions {\n minify?: boolean;\n deployUrl?: string;\n}\n\nexport interface InlineCriticalCssResult {\n content: string;\n warnings?: string[];\n errors?: string[];\n}\n\n/** Partial representation of an `HTMLElement`. */\ninterface PartialHTMLElement {\n getAttribute(name: string): string | null;\n setAttribute(name: string, value: string): void;\n hasAttribute(name: string): boolean;\n removeAttribute(name: string): void;\n appendChild(child: PartialHTMLElement): void;\n remove(): void;\n name: string;\n textContent: string;\n tagName: string | null;\n children: PartialHTMLElement[];\n next: PartialHTMLElement | null;\n prev: PartialHTMLElement | null;\n}\n\n/** Partial representation of an HTML `Document`. */\ninterface PartialDocument {\n head: PartialHTMLElement;\n createElement(tagName: string): PartialHTMLElement;\n querySelector(selector: string): PartialHTMLElement | null;\n}\n\n/** Signature of the `Critters.embedLinkedStylesheet` method. */\ntype EmbedLinkedStylesheetFn = (\n link: PartialHTMLElement,\n document: PartialDocument,\n) => Promise<unknown>;\n\nclass CrittersExtended extends Critters {\n readonly warnings: string[] = [];\n readonly errors: string[] = [];\n private initialEmbedLinkedStylesheet: EmbedLinkedStylesheetFn;\n private addedCspScriptsDocuments = new WeakSet<PartialDocument>();\n private documentNonces = new WeakMap<PartialDocument, string | null>();\n\n // Inherited from `Critters`, but not exposed in the typings.\n protected embedLinkedStylesheet!: EmbedLinkedStylesheetFn;\n\n constructor(\n readonly optionsExtended: InlineCriticalCssProcessorOptions & InlineCriticalCssProcessOptions,\n private readonly resourceCache: Map<string, string>,\n ) {\n super({\n logger: {\n warn: (s: string) => this.warnings.push(s),\n error: (s: string) => this.errors.push(s),\n info: () => {},\n },\n logLevel: 'warn',\n path: optionsExtended.outputPath,\n publicPath: optionsExtended.deployUrl,\n compress: !!optionsExtended.minify,\n pruneSource: false,\n reduceInlineStyles: false,\n mergeStylesheets: false,\n // Note: if `preload` changes to anything other than `media`, the logic in\n // `embedLinkedStylesheetOverride` will have to be updated.\n preload: 'media',\n noscriptFallback: true,\n inlineFonts: true,\n });\n\n // We can't use inheritance to override `embedLinkedStylesheet`, because it's not declared in\n // the `Critters` .d.ts which means that we can't call the `super` implementation. TS doesn't\n // allow for `super` to be cast to a different type.\n this.initialEmbedLinkedStylesheet = this.embedLinkedStylesheet;\n this.embedLinkedStylesheet = this.embedLinkedStylesheetOverride;\n }\n\n public override async readFile(path: string): Promise<string> {\n let resourceContent = this.resourceCache.get(path);\n if (resourceContent === undefined) {\n resourceContent = await readFile(path, 'utf-8');\n this.resourceCache.set(path, resourceContent);\n }\n\n return resourceContent;\n }\n\n /**\n * Override of the Critters `embedLinkedStylesheet` method\n * that makes it work with Angular's CSP APIs.\n */\n private embedLinkedStylesheetOverride: EmbedLinkedStylesheetFn = async (link, document) => {\n if (link.getAttribute('media') === 'print' && link.next?.name === 'noscript') {\n // Workaround for https://github.com/GoogleChromeLabs/critters/issues/64\n // NB: this is only needed for the webpack based builders.\n const media = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);\n if (media) {\n link.removeAttribute('onload');\n link.setAttribute('media', media[1]);\n link?.next?.remove();\n }\n }\n\n const returnValue = await this.initialEmbedLinkedStylesheet(link, document);\n const cspNonce = this.findCspNonce(document);\n\n if (cspNonce) {\n const crittersMedia = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);\n\n if (crittersMedia) {\n // If there's a Critters-generated `onload` handler and the file has an Angular CSP nonce,\n // we have to remove the handler, because it's incompatible with CSP. We save the value\n // in a different attribute and we generate a script tag with the nonce that uses\n // `addEventListener` to apply the media query instead.\n link.removeAttribute('onload');\n link.setAttribute(CSP_MEDIA_ATTR, crittersMedia[1]);\n this.conditionallyInsertCspLoadingScript(document, cspNonce);\n }\n\n // Ideally we would hook in at the time Critters inserts the `style` tags, but there isn't\n // a way of doing that at the moment so we fall back to doing it any time a `link` tag is\n // inserted. We mitigate it by only iterating the direct children of the `<head>` which\n // should be pretty shallow.\n document.head.children.forEach((child) => {\n if (child.tagName === 'style' && !child.hasAttribute('nonce')) {\n child.setAttribute('nonce', cspNonce);\n }\n });\n }\n\n return returnValue;\n };\n\n /**\n * Finds the CSP nonce for a specific document.\n */\n private findCspNonce(document: PartialDocument): string | null {\n if (this.documentNonces.has(document)) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.documentNonces.get(document)!;\n }\n\n // HTML attribute are case-insensitive, but the parser used by Critters is case-sensitive.\n const nonceElement = document.querySelector('[ngCspNonce], [ngcspnonce]');\n const cspNonce =\n nonceElement?.getAttribute('ngCspNonce') || nonceElement?.getAttribute('ngcspnonce') || null;\n\n this.documentNonces.set(document, cspNonce);\n\n return cspNonce;\n }\n\n /**\n * Inserts the `script` tag that swaps the critical CSS at runtime,\n * if one hasn't been inserted into the document already.\n */\n private conditionallyInsertCspLoadingScript(document: PartialDocument, nonce: string): void {\n if (this.addedCspScriptsDocuments.has(document)) {\n return;\n }\n\n if (document.head.textContent.includes(LINK_LOAD_SCRIPT_CONTENT)) {\n // Script was already added during the build.\n this.addedCspScriptsDocuments.add(document);\n\n return;\n }\n\n const script = document.createElement('script');\n script.setAttribute('nonce', nonce);\n script.textContent = LINK_LOAD_SCRIPT_CONTENT;\n // Append the script to the head since it needs to\n // run as early as possible, after the `link` tags.\n document.head.appendChild(script);\n this.addedCspScriptsDocuments.add(document);\n }\n}\n\nexport class InlineCriticalCssProcessor {\n private readonly resourceCache = new Map<string, string>();\n\n constructor(protected readonly options: InlineCriticalCssProcessorOptions) {}\n\n async process(\n html: string,\n options: InlineCriticalCssProcessOptions,\n ): Promise<InlineCriticalCssResult> {\n const critters = new CrittersExtended({ ...this.options, ...options }, this.resourceCache);\n const content = await critters.process(html);\n\n return {\n content,\n errors: critters.errors.length ? critters.errors : undefined,\n warnings: critters.warnings.length ? critters.warnings : undefined,\n };\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\nimport { ApplicationRef, StaticProvider, Type } from '@angular/core';\nimport {\n INITIAL_CONFIG,\n renderApplication,\n renderModule,\n ɵSERVER_CONTEXT,\n} from '@angular/platform-server';\nimport * as fs from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { URL } from 'node:url';\nimport { InlineCriticalCssProcessor } from './inline-css-processor';\n\nconst SSG_MARKER_REGEXP = /ng-server-context=[\"']\\w*\\|?ssg\\|?\\w*[\"']/;\n\nexport interface CommonEngineRenderOptions {\n bootstrap?: Type<{}> | (() => Promise<ApplicationRef>);\n providers?: StaticProvider[];\n url?: string;\n document?: string;\n documentFilePath?: string;\n /**\n * Reduce render blocking requests by inlining critical CSS.\n * Defaults to true.\n */\n inlineCriticalCss?: boolean;\n /**\n * Base path location of index file.\n * Defaults to the 'documentFilePath' dirname when not provided.\n */\n publicPath?: string;\n}\n\n/**\n * A common rendering engine utility. This abstracts the logic\n * for handling the platformServer compiler, the module cache, and\n * the document loader\n */\nexport class CommonEngine {\n private readonly templateCache = new Map<string, string>();\n private readonly inlineCriticalCssProcessor: InlineCriticalCssProcessor;\n private readonly pageIsSSG = new Map<string, boolean>();\n\n constructor(\n private bootstrap?: Type<{}> | (() => Promise<ApplicationRef>),\n private providers: StaticProvider[] = [],\n ) {\n this.inlineCriticalCssProcessor = new InlineCriticalCssProcessor({\n minify: false,\n });\n }\n\n /**\n * Render an HTML document for a specific URL with specified\n * render options\n */\n async render(opts: CommonEngineRenderOptions): Promise<string> {\n const { inlineCriticalCss = true, url } = opts;\n\n if (opts.publicPath && opts.documentFilePath && url !== undefined) {\n const pathname = canParseUrl(url) ? new URL(url).pathname : url;\n // Remove leading forward slash.\n const pagePath = resolve(opts.publicPath, pathname.substring(1), 'index.html');\n\n if (pagePath !== resolve(opts.documentFilePath)) {\n // View path doesn't match with prerender path.\n const pageIsSSG = this.pageIsSSG.get(pagePath);\n if (pageIsSSG === undefined) {\n if (await exists(pagePath)) {\n const content = await fs.promises.readFile(pagePath, 'utf-8');\n const isSSG = SSG_MARKER_REGEXP.test(content);\n this.pageIsSSG.set(pagePath, isSSG);\n\n if (isSSG) {\n return content;\n }\n } else {\n this.pageIsSSG.set(pagePath, false);\n }\n } else if (pageIsSSG) {\n // Serve pre-rendered page.\n return fs.promises.readFile(pagePath, 'utf-8');\n }\n }\n }\n\n // if opts.document dosen't exist then opts.documentFilePath must\n const extraProviders: StaticProvider[] = [\n { provide: ɵSERVER_CONTEXT, useValue: 'ssr' },\n ...(opts.providers ?? []),\n ...this.providers,\n ];\n\n let document = opts.document;\n if (!document && opts.documentFilePath) {\n document = await this.getDocument(opts.documentFilePath);\n }\n\n if (document) {\n extraProviders.push({\n provide: INITIAL_CONFIG,\n useValue: {\n document,\n url: opts.url,\n },\n });\n }\n\n const moduleOrFactory = this.bootstrap || opts.bootstrap;\n if (!moduleOrFactory) {\n throw new Error('A module or bootstrap option must be provided.');\n }\n\n const html = await (isBootstrapFn(moduleOrFactory)\n ? renderApplication(moduleOrFactory, { platformProviders: extraProviders })\n : renderModule(moduleOrFactory, { extraProviders }));\n\n if (!inlineCriticalCss) {\n return html;\n }\n\n const { content, errors, warnings } = await this.inlineCriticalCssProcessor.process(html, {\n outputPath: opts.publicPath ?? (opts.documentFilePath ? dirname(opts.documentFilePath) : ''),\n });\n\n // eslint-disable-next-line no-console\n warnings?.forEach((m) => console.warn(m));\n // eslint-disable-next-line no-console\n errors?.forEach((m) => console.error(m));\n\n return content;\n }\n\n /** Retrieve the document from the cache or the filesystem */\n private async getDocument(filePath: string): Promise<string> {\n let doc = this.templateCache.get(filePath);\n\n if (!doc) {\n doc = await fs.promises.readFile(filePath, 'utf-8');\n this.templateCache.set(filePath, doc);\n }\n\n return doc;\n }\n}\n\nasync function exists(path: fs.PathLike): Promise<boolean> {\n try {\n await fs.promises.access(path, fs.constants.F_OK);\n\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isBootstrapFn(value: unknown): value is () => Promise<ApplicationRef> {\n // We can differentiate between a module and a bootstrap function by reading `cmp`:\n return typeof value === 'function' && !('ɵmod' in value);\n}\n\n// The below can be removed in favor of URL.canParse() when Node.js 18 is dropped\nfunction canParseUrl(url: string): boolean {\n try {\n return !!new URL(url);\n } catch {\n return false;\n }\n}\n"],"names":[],"mappings":";;;;;;;AAWA;;AAEG;AACH,MAAM,yBAAyB,GAAG,8BAA8B,CAAC;AAEjE;;AAEG;AACH,MAAM,cAAc,GAAG,YAAY,CAAC;AAEpC;;AAEG;AACH,MAAM,wBAAwB,GAAG;IAC/B,CAAU,QAAA,CAAA;;;;IAIV,CAA4C,0CAAA,CAAA;;;AAG5C,IAAA,CAAA,qDAAA,EAAwD,cAAc,CAAM,IAAA,CAAA;;;IAG5E,CAA+C,6CAAA,CAAA;IAC/C,CAAgC,8BAAA,CAAA;AAChC,IAAA,CAAA,wBAAA,EAA2B,cAAc,CAA+C,6CAAA,CAAA;IACxF,CAAK,GAAA,CAAA;IACL,CAAO,KAAA,CAAA;AACR,CAAA,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AA8Cb,MAAM,gBAAiB,SAAQ,QAAQ,CAAA;IAUrC,WACW,CAAA,eAAoF,EAC5E,aAAkC,EAAA;AAEnD,QAAA,KAAK,CAAC;AACJ,YAAA,MAAM,EAAE;AACN,gBAAA,IAAI,EAAE,CAAC,CAAS,KAAK,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;AAC1C,gBAAA,KAAK,EAAE,CAAC,CAAS,KAAK,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACzC,gBAAA,IAAI,EAAE,MAAK,GAAG;AACf,aAAA;AACD,YAAA,QAAQ,EAAE,MAAM;YAChB,IAAI,EAAE,eAAe,CAAC,UAAU;YAChC,UAAU,EAAE,eAAe,CAAC,SAAS;AACrC,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AAC,GAAG,CAAC,CAAC;AACvB,KAAA;IAAC,MAAM;AACN,QAAA,OAAO,KAAK,CAAC;AACd,KAAA;AACH;;;;"}
package/index.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ import { ApplicationRef } from '@angular/core';
2
+ import { StaticProvider } from '@angular/core';
3
+ import { Type } from '@angular/core';
4
+
5
+ /**
6
+ * A common rendering engine utility. This abstracts the logic
7
+ * for handling the platformServer compiler, the module cache, and
8
+ * the document loader
9
+ */
10
+ export declare class CommonEngine {
11
+ private bootstrap?;
12
+ private providers;
13
+ private readonly templateCache;
14
+ private readonly inlineCriticalCssProcessor;
15
+ private readonly pageIsSSG;
16
+ constructor(bootstrap?: Type<{}> | (() => Promise<ApplicationRef>) | undefined, providers?: StaticProvider[]);
17
+ /**
18
+ * Render an HTML document for a specific URL with specified
19
+ * render options
20
+ */
21
+ render(opts: CommonEngineRenderOptions): Promise<string>;
22
+ /** Retrieve the document from the cache or the filesystem */
23
+ private getDocument;
24
+ }
25
+
26
+ export declare interface CommonEngineRenderOptions {
27
+ bootstrap?: Type<{}> | (() => Promise<ApplicationRef>);
28
+ providers?: StaticProvider[];
29
+ url?: string;
30
+ document?: string;
31
+ documentFilePath?: string;
32
+ /**
33
+ * Reduce render blocking requests by inlining critical CSS.
34
+ * Defaults to true.
35
+ */
36
+ inlineCriticalCss?: boolean;
37
+ /**
38
+ * Base path location of index file.
39
+ * Defaults to the 'documentFilePath' dirname when not provided.
40
+ */
41
+ publicPath?: string;
42
+ }
43
+
44
+ export { }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@angular/ssr",
3
- "version": "0.0.0-PLACEHOLDER",
3
+ "version": "17.0.0-next.1",
4
4
  "description": "Angular server side rendering utilities",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/angular/angular-cli",
@@ -8,5 +8,32 @@
8
8
  "angular",
9
9
  "ssr",
10
10
  "universal"
11
- ]
11
+ ],
12
+ "dependencies": {
13
+ "critters": "0.0.20",
14
+ "tslib": "^2.3.0"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/angular/angular-cli.git"
19
+ },
20
+ "peerDependencies": {
21
+ "@angular/common": "^17.0.0 || ^17.0.0-next.0",
22
+ "@angular/core": "^17.0.0 || ^17.0.0-next.0"
23
+ },
24
+ "schematics": "./schematics/collection.json",
25
+ "module": "./fesm2022/ssr.mjs",
26
+ "typings": "./index.d.ts",
27
+ "type": "module",
28
+ "exports": {
29
+ "./package.json": {
30
+ "default": "./package.json"
31
+ },
32
+ ".": {
33
+ "types": "./index.d.ts",
34
+ "esm2022": "./esm2022/index.mjs",
35
+ "esm": "./esm2022/index.mjs",
36
+ "default": "./fesm2022/ssr.mjs"
37
+ }
38
+ }
12
39
  }
@@ -0,0 +1,9 @@
1
+ {
2
+ "schematics": {
3
+ "ng-add": {
4
+ "description": "Adds Angular SSR to the application without affecting any templates",
5
+ "factory": "./ng-add",
6
+ "schema": "./ng-add/schema.json"
7
+ }
8
+ }
9
+ }
@@ -0,0 +1,67 @@
1
+ import 'zone.js/node';
2
+
3
+ import { APP_BASE_HREF } from '@angular/common';
4
+ import { CommonEngine } from '@angular/ssr';
5
+ import * as express from 'express';
6
+ import { existsSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import <% if (isStandalone) { %>bootstrap<% } else { %>{ AppServerModule }<% } %> from './src/<%= stripTsExtension(main) %>';
9
+
10
+ // The Express app is exported so that it can be used by serverless Functions.
11
+ export function app(): express.Express {
12
+ const server = express();
13
+ const distFolder = join(process.cwd(), '<%= browserDistDirectory %>');
14
+ const indexHtml = existsSync(join(distFolder, 'index.original.html'))
15
+ ? join(distFolder, 'index.original.html')
16
+ : join(distFolder, 'index.html');
17
+
18
+ const commonEngine = new CommonEngine();
19
+
20
+ server.set('view engine', 'html');
21
+ server.set('views', distFolder);
22
+
23
+ // Example Express Rest API endpoints
24
+ // server.get('/api/**', (req, res) => { });
25
+ // Serve static files from /browser
26
+ server.get('*.*', express.static(distFolder, {
27
+ maxAge: '1y'
28
+ }));
29
+
30
+ // All regular routes use the Angular engine
31
+ server.get('*', (req, res, next) => {
32
+ commonEngine
33
+ .render({
34
+ <% if (isStandalone) { %>bootstrap<% } else { %>bootstrap: AppServerModule<% } %>,
35
+ documentFilePath: indexHtml,
36
+ url: req.originalUrl,
37
+ publicPath: distFolder,
38
+ providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }],
39
+ })
40
+ .then((html) => res.send(html))
41
+ .catch((err) => next(err));
42
+ });
43
+
44
+ return server;
45
+ }
46
+
47
+ function run(): void {
48
+ const port = process.env['PORT'] || 4000;
49
+
50
+ // Start up the Node server
51
+ const server = app();
52
+ server.listen(port, () => {
53
+ console.log(`Node Express server listening on http://localhost:${port}`);
54
+ });
55
+ }
56
+
57
+ // Webpack will replace 'require' with '__webpack_require__'
58
+ // '__non_webpack_require__' is a proxy to Node 'require'
59
+ // The below code is to ensure that the server is run only when not requiring the bundle.
60
+ declare const __non_webpack_require__: NodeRequire;
61
+ const mainModule = __non_webpack_require__.main;
62
+ const moduleFilename = mainModule && mainModule.filename || '';
63
+ if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
64
+ run();
65
+ }
66
+
67
+ <% if (isStandalone) { %>export default bootstrap;<% } else { %>export * from './src/<%= stripTsExtension(main) %>';<% } %>
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @license
3
+ * Copyright Google LLC All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by an MIT-style license that can be
6
+ * found in the LICENSE file at https://angular.io/license
7
+ */
8
+ import { Rule } from '@angular-devkit/schematics';
9
+ import { Schema as AddUniversalOptions } from './schema';
10
+ export default function (options: AddUniversalOptions): Rule;