From c7eb5b684e5e966c40ba2df6c3c6e1d05c413178 Mon Sep 17 00:00:00 2001 From: Dat Ha Date: Wed, 25 Nov 2026 23:14:07 +0700 Subject: [PATCH 1/4] feat(ssr): rewriteModulePreloads for native import maps (#171) With shimMode: false, @angular/ssr's route modulepreload hints link lazy chunks before initFederation adds the import map, so a chunk importing a shared package fails to resolve it. The helper, exported from ./ssr, rewrites those hints to on HTML responses whose esms-options set shimMode to false, and drops content-length. Everything else passes through unchanged. --- knip.json | 1 + package.json | 5 ++ src/ssr.spec.ts | 179 ++++++++++++++++++++++++++++++++++++++++++++++++ src/ssr.ts | 46 +++++++++++++ 4 files changed, 231 insertions(+) create mode 100644 src/ssr.spec.ts create mode 100644 src/ssr.ts diff --git a/knip.json b/knip.json index 25125398..40b43484 100644 --- a/knip.json +++ b/knip.json @@ -5,6 +5,7 @@ "src/config.ts", "src/internal.ts", "src/node-preload.ts", + "src/ssr.ts", "src/builders/*/builder.ts", "src/schematics/*/schematic.ts", "src/generators/*/generator.ts", diff --git a/package.json b/package.json index 6e78a99d..5e4c03b5 100644 --- a/package.json +++ b/package.json @@ -60,6 +60,11 @@ "types": "./src/node-preload.d.ts", "import": "./src/node-preload.js", "default": "./src/node-preload.js" + }, + "./ssr": { + "types": "./src/ssr.d.ts", + "import": "./src/ssr.js", + "default": "./src/ssr.js" } }, "homepage": "https://native-federation.com/docs/v4/angular-adapter/", diff --git a/src/ssr.spec.ts b/src/ssr.spec.ts new file mode 100644 index 00000000..b79294c6 --- /dev/null +++ b/src/ssr.spec.ts @@ -0,0 +1,179 @@ +import { describe, it, expect } from 'vitest'; +import { rewriteModulePreloads } from './ssr'; + +const NATIVE = ''; +const SHIM = ''; + +function page(esmsOptions: string, preloads: string): string { + return ( + '\n\t\t' + + `${esmsOptions}${preloads}` + ); +} + +function html(body: string, headers: Record = {}): Response { + return new Response(body, { + status: 200, + headers: { + 'content-type': 'text/html; charset=utf-8', + 'content-length': String(new TextEncoder().encode(body).length), + ...headers, + }, + }); +} + +describe('rewriteModulePreloads', () => { + it('turns modulepreload hints into script preloads under native import maps', async () => { + const res = html( + page( + NATIVE, + '' + + '', + ), + ); + + const out = await rewriteModulePreloads(res); + const body = await out!.text(); + + expect(body).toContain(''); + expect(body).toContain(''); + expect(body).not.toContain('modulepreload'); + }); + + it('drops content-length, which the rewrite makes wrong, and keeps the rest', async () => { + const res = html(page(NATIVE, ''), { + 'x-custom': 'kept', + }); + + const out = await rewriteModulePreloads(res); + + expect(out!.headers.has('content-length')).toBe(false); + expect(out!.headers.get('x-custom')).toBe('kept'); + expect(out!.headers.get('content-type')).toBe('text/html; charset=utf-8'); + expect(out!.status).toBe(200); + }); + + it('keeps the status of an error page it rewrites', async () => { + const body = page(NATIVE, ''); + const res = new Response(body, { + status: 404, + statusText: 'Not Found', + headers: { 'content-type': 'text/html' }, + }); + + const out = await rewriteModulePreloads(res); + + expect(await out!.text()).toContain('rel="preload" as="script"'); + expect(out!.status).toBe(404); + expect(out!.statusText).toBe('Not Found'); + }); + + it('does not add a second crossorigin', async () => { + const res = html( + page(NATIVE, ''), + ); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain( + '', + ); + }); + + it('leaves shim mode alone, returning the same response with its body unread', async () => { + const body = page(SHIM, ''); + const res = html(body); + + const out = await rewriteModulePreloads(res); + + // The body must still be readable: writeResponseToNodeResponse streams it next. + expect(out).toBe(res); + expect(await out!.text()).toBe(body); + }); + + it('reads native mode from esms-options that carry other keys too', async () => { + const options = ''; + const res = html(page(options, '')); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain(''); + }); + + it('rewrites a streamed body, as the engine returns for server-rendered routes', async () => { + const source = page(NATIVE, ''); + const bytes = new TextEncoder().encode(source); + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(bytes.slice(0, 40)); + controller.enqueue(bytes.slice(40)); + controller.close(); + }, + }); + const res = new Response(stream, { headers: { 'content-type': 'text/html' } }); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain(''); + }); + + it('leaves other links and attributes alone', async () => { + const res = html( + page( + NATIVE, + '' + + '' + + '' + + '' + + '', + ), + ); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain( + '', + ); + expect(body).toContain(''); + expect(body).toContain(''); + expect(body).toContain(''); + expect(body).toContain(''); + }); + + it('leaves a page with no esms-options alone', async () => { + const res = html(page('', '')); + + expect(await rewriteModulePreloads(res)).toBe(res); + }); + + it('leaves unparsable esms-options alone', async () => { + const res = html( + page( + '', + '', + ), + ); + + expect(await rewriteModulePreloads(res)).toBe(res); + }); + + it('leaves non-HTML responses alone', async () => { + // A body that would be rewritten if it were HTML, so only the content type can stop it. + const res = new Response(page(NATIVE, ''), { + headers: { 'content-type': 'text/plain' }, + }); + + expect(await rewriteModulePreloads(res)).toBe(res); + }); + + it('returns the same response when there is nothing to rewrite', async () => { + const res = html(page(NATIVE, '')); + + expect(await rewriteModulePreloads(res)).toBe(res); + }); + + it('passes null through, for routes the engine does not handle', async () => { + expect(await rewriteModulePreloads(null)).toBeNull(); + }); +}); diff --git a/src/ssr.ts b/src/ssr.ts new file mode 100644 index 00000000..22be7a61 --- /dev/null +++ b/src/ssr.ts @@ -0,0 +1,46 @@ +const ESMS_OPTIONS = + /]*\btype\s*=\s*["']esms-options["'][^>]*>([\s\S]*?)<\/script>/i; +// Only an exact `rel` of `modulepreload`: never `data-rel`, never `rel="modulepreload foo"`. +const REL_MODULEPRELOAD = String.raw`(?])`; +const MODULE_PRELOAD = new RegExp(String.raw`]*${REL_MODULEPRELOAD}[^>]*>`, 'gi'); +const REL_ATTRIBUTE = new RegExp(REL_MODULEPRELOAD, 'i'); +const CROSSORIGIN_ATTRIBUTE = /\scrossorigin\b/i; + +/** Wraps `AngularNodeAppEngine.handle()` in `server.ts` under `shimMode: false` (#171). */ +export async function rewriteModulePreloads(res: Response | null): Promise { + if (!res || !res.body) return res; + const contentType = res.headers.get('content-type') ?? ''; + if (!contentType.toLowerCase().includes('text/html')) return res; + + const html = await res.clone().text(); + if (!usesNativeImportMaps(html)) return res; + + const rewritten = html.replace(MODULE_PRELOAD, toScriptPreload); + if (rewritten === html) return res; + + const headers = new Headers(res.headers); + headers.delete('content-length'); + return new Response(rewritten, { + status: res.status, + statusText: res.statusText, + headers, + }); +} + +function usesNativeImportMaps(html: string): boolean { + const options = ESMS_OPTIONS.exec(html)?.[1]; + if (!options) return false; + try { + return (JSON.parse(options) as { shimMode?: unknown }).shimMode === false; + } catch { + return false; + } +} + +// `crossorigin` keeps the preload in CORS mode, so the module import reuses the response. +function toScriptPreload(tag: string): string { + const replacement = CROSSORIGIN_ATTRIBUTE.test(tag) + ? 'rel="preload" as="script"' + : 'rel="preload" as="script" crossorigin'; + return tag.replace(REL_ATTRIBUTE, replacement); +} From 2cc91fd9c0cd568799c87eaeb09d1d3b6209f629 Mon Sep 17 00:00:00 2001 From: Dat Ha Date: Wed, 25 Nov 2026 23:55:08 +0700 Subject: [PATCH 2/4] fix(ssr): don't read esms-options from a data-type attribute \btype matched data-type="esms-options", so a decoy block before the real one decided the mode. Guard it like the rel match, and note that the first block wins. --- src/ssr.spec.ts | 7 +++++++ src/ssr.ts | 3 ++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/ssr.spec.ts b/src/ssr.spec.ts index b79294c6..22b7ad25 100644 --- a/src/ssr.spec.ts +++ b/src/ssr.spec.ts @@ -141,6 +141,13 @@ describe('rewriteModulePreloads', () => { expect(body).toContain(''); }); + it('ignores a data-type attribute that only looks like esms-options', async () => { + const decoy = ''; + const res = html(page(decoy + SHIM, '')); + + expect(await rewriteModulePreloads(res)).toBe(res); + }); + it('leaves a page with no esms-options alone', async () => { const res = html(page('', '')); diff --git a/src/ssr.ts b/src/ssr.ts index 22be7a61..252c1e59 100644 --- a/src/ssr.ts +++ b/src/ssr.ts @@ -1,5 +1,6 @@ +// First block wins: the builder writes it right after ``; HTML comments aren't skipped. const ESMS_OPTIONS = - /]*\btype\s*=\s*["']esms-options["'][^>]*>([\s\S]*?)<\/script>/i; + /]*(?]*>([\s\S]*?)<\/script>/i; // Only an exact `rel` of `modulepreload`: never `data-rel`, never `rel="modulepreload foo"`. const REL_MODULEPRELOAD = String.raw`(?])`; const MODULE_PRELOAD = new RegExp(String.raw`]*${REL_MODULEPRELOAD}[^>]*>`, 'gi'); From a1e5bb4d8509ff4775a7550d8c0e38d56bae9210 Mon Sep 17 00:00:00 2001 From: Dat Ha Date: Thu, 26 Nov 2026 01:59:14 +0700 Subject: [PATCH 3/4] fix(ssr): read tags and attributes instead of matching flat text Comments and '; + const res = html(page(NATIVE, script + '')); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain(script); + expect(body).toContain(''); + }); + + it('leaves custom elements whose names start with link or script alone', async () => { + const custom = + '' + + '{"shimMode":true}'; + const res = html(page(NATIVE, custom + '')); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain(custom); + expect(body).toContain(''); + }); + + it('keeps an existing as instead of adding a second one', async () => { + const res = html(page(NATIVE, '')); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain(''); + }); + + it('matches case-insensitively and keeps the tag name as written', async () => { + const options = ''; + const res = html(page(options, '')); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain(''); + }); + + it('takes the mode from the first esms-options block only', async () => { + const res = html(page(SHIM + NATIVE, '')); + + expect(await rewriteModulePreloads(res)).toBe(res); + }); + + it('treats everything after an unclosed script as its body, as browsers do', async () => { + const res = html(page(NATIVE, ''; const SHIM = ''; @@ -15,7 +25,8 @@ function html(body: string, headers: Record = {}): Response { return new Response(body, { status: 200, headers: { - 'content-type': 'text/html; charset=utf-8', + // What `@angular/ssr` sends: no space, upper case. + 'content-type': 'text/html;charset=UTF-8', 'content-length': String(new TextEncoder().encode(body).length), ...headers, }, @@ -49,7 +60,7 @@ describe('rewriteModulePreloads', () => { expect(out!.headers.has('content-length')).toBe(false); expect(out!.headers.get('x-custom')).toBe('kept'); - expect(out!.headers.get('content-type')).toBe('text/html; charset=utf-8'); + expect(out!.headers.get('content-type')).toBe('text/html;charset=UTF-8'); expect(out!.status).toBe(200); }); @@ -68,18 +79,6 @@ describe('rewriteModulePreloads', () => { expect(out!.statusText).toBe('Not Found'); }); - it('does not add a second crossorigin', async () => { - const res = html( - page(NATIVE, ''), - ); - - const body = await (await rewriteModulePreloads(res))!.text(); - - expect(body).toContain( - '', - ); - }); - it('leaves shim mode alone, returning the same response with its body unread', async () => { const body = page(SHIM, ''); const res = html(body); @@ -100,6 +99,20 @@ describe('rewriteModulePreloads', () => { expect(body).toContain(''); }); + it('keeps the nonce that ngCspNonce adds to esms-options and to the links', async () => { + // Angular's addNonce appends `nonce` after the attributes already there. + const options = ''; + const res = html( + page(options, ''), + ); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain( + '', + ); + }); + it('rewrites a streamed body, as the engine returns for server-rendered routes', async () => { const source = page(NATIVE, ''); const bytes = new TextEncoder().encode(source); @@ -148,40 +161,6 @@ describe('rewriteModulePreloads', () => { expect(await rewriteModulePreloads(res)).toBe(res); }); - it('ignores esms-options inside an HTML comment', async () => { - const commented = ``; - const res = html(page(commented + SHIM, '')); - - expect(await rewriteModulePreloads(res)).toBe(res); - }); - - it('reads attributes, not text inside other attribute values', async () => { - const res = html( - page( - NATIVE, - '' + - '' + - '', - ), - ); - - const body = await (await rewriteModulePreloads(res))!.text(); - - expect(body).toContain(''); - expect(body).toContain(''); - }); - - it('leaves preload markup inside a script body alone', async () => { - const script = ''; - const res = html(page(NATIVE, script + '')); - - const body = await (await rewriteModulePreloads(res))!.text(); - - expect(body).toContain(script); - expect(body).toContain(''); - }); - it('leaves custom elements whose names start with link or script alone', async () => { const custom = '' + @@ -194,50 +173,13 @@ describe('rewriteModulePreloads', () => { expect(body).toContain(''); }); - it('keeps an existing as instead of adding a second one', async () => { - const res = html(page(NATIVE, '')); - - const body = await (await rewriteModulePreloads(res))!.text(); - - expect(body).toContain(''); - }); - - it('matches case-insensitively and keeps the tag name as written', async () => { - const options = ''; - const res = html(page(options, '')); - - const body = await (await rewriteModulePreloads(res))!.text(); - - expect(body).toContain(''); - }); - - it('takes the mode from the first esms-options block only', async () => { - const res = html(page(SHIM + NATIVE, '')); - - expect(await rewriteModulePreloads(res)).toBe(res); - }); - - it('treats everything after an unclosed script as its body, as browsers do', async () => { - const res = html(page(NATIVE, '', @@ -267,3 +209,19 @@ describe('rewriteModulePreloads', () => { expect(await rewriteModulePreloads(null)).toBeNull(); }); }); + +describe("@angular/build's modulepreload hints", () => { + // The helper matches the literal ` { + const { content } = await augmentIndexHtml({ + html: '', + sri: false, + files: [], + entrypoints: [], + loadOutputFile: async () => '', + hints: [{ url: 'chunk-ABC.js', mode: 'modulepreload' }], + }); + + expect(content).toContain(''); + }); +}); diff --git a/src/ssr.ts b/src/ssr.ts index 73a829c9..a65a3a7a 100644 --- a/src/ssr.ts +++ b/src/ssr.ts @@ -1,95 +1,17 @@ -// Comments and `