Repository navigation
feat(ssr): rewriteModulePreloads for native import maps (#171) - #213
Aukevanoost merged 5 commits into
Conversation
…ation#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 <link rel="preload" as="script" crossorigin> on HTML responses whose esms-options set shimMode to false, and drops content-length. Everything else passes through unchanged.
\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.
Comments and <script> bodies were searched like markup, rel or crossorigin inside another attribute's value counted as the attribute, a > inside a quoted value ended the tag early, and <link-card> counted as <link>. Comments and script elements are now matched whole (to the end of the page when unclosed, as browsers do) and skipped, quoted values may contain >, and rel, type, as and crossorigin are read from parsed attributes. Only the rel attribute changes; the tag name keeps its case. A page in a charset other than UTF-8 is passed through rather than re-encoded.
Aukevanoost
left a comment
There was a problem hiding this comment.
Thanks, this fixes it. I reproduced #171 in Chromium against a production SSR build (Angular 22.2.6, shimMode: false, a lazy host route). It fails without the helper and boots with it, and each chunk is fetched once. The same holds for the minimal version suggested below.
Two smaller asks:
- Add a spec that reads
@angular/build'ssrc/utils/index-file/augment-index-html.js(resolved the waysrc/builders/remote/assets.spec.tsdoes) and checks it still writesrelfirst for modulepreload hints, so a change upstream fails CI on the next bump. - In the docs PR: with
crossOrigin: 'use-credentials', the rewritten preloads aren't reused, because the helper adds a barecrossorigin. A sentence is enough.
| @@ -0,0 +1,95 @@ | |||
| // Comments and `<script>` bodies are matched whole (to the end, if unclosed, as browsers do) so | |||
There was a problem hiding this comment.
Let's take you up on the minimal version. Both inputs are fixed: @angular/ssr writes <link rel="modulepreload" href="…"> (appendPreloadHintsToHtml), @angular/build puts rel first, and our builder writes shimMode as the first key. The comment/script skipping, attribute parsing, case folding, first-block rule and charset check cover markup none of them produce.
One thing a plain literal would miss: with ngCspNonce, Angular adds a nonce to the options tag (<script type="esms-options" nonce="…">), so the detection must allow attributes there:
const MODULE_PRELOAD = '<link rel="modulepreload"';
const NATIVE_IMPORT_MAPS = /<script type="esms-options"[^>]*>\{"shimMode":false/;
// `crossorigin` keeps the preload in CORS mode, so the module import reuses the response (#171).
export async function rewriteModulePreloads(res: Response | null): Promise<Response | null> {
if (!res?.body || !res.headers.get('content-type')?.includes('text/html')) return res;
const html = await res.clone().text();
if (!NATIVE_IMPORT_MAPS.test(html) || !html.includes(MODULE_PRELOAD)) return res;
const headers = new Headers(res.headers);
headers.delete('content-length');
return new Response(html.replaceAll(MODULE_PRELOAD, '<link rel="preload" as="script" crossorigin'), {
status: res.status,
statusText: res.statusText,
headers,
});
}There was a problem hiding this comment.
Done in 935b8f5, as you wrote it, wrapped to 100 columns. I also checked it on a real build with ngCspNonce: the options tag comes out as <script type="esms-options" nonce="…">{"shimMode":false}, and every preload is rewritten.
| index: number; | ||
| } | ||
|
|
||
| /** Wraps `AngularNodeAppEngine.handle()` in `server.ts` under `shimMode: false` (#171). */ |
There was a problem hiding this comment.
Please make this a single // line (house style, see .claude/rules/comments.md).
There was a problem hiding this comment.
Done, it is the // line from your version.
| return new Response(body, { | ||
| status: 200, | ||
| headers: { | ||
| 'content-type': 'text/html; charset=utf-8', |
There was a problem hiding this comment.
Angular sends text/html;charset=UTF-8 (no space, upper case). Please use that as the default here: currently removing the .toLowerCase() in ssr.ts keeps every spec green while the helper would do nothing in production.
There was a problem hiding this comment.
Done: the fixture now sends text/html;charset=UTF-8, as @angular/ssr does.
| expect(out!.statusText).toBe('Not Found'); | ||
| }); | ||
|
|
||
| it('does not add a second crossorigin', async () => { |
There was a problem hiding this comment.
With the minimal version, these specs go: second crossorigin, comment, attribute text, script body, existing as, case, first block, unclosed script and charset (none of those inputs come from Angular or our builder). Please add one with a nonce on the esms-options tag and on the links, as ngCspNonce produces.
There was a problem hiding this comment.
Removed those nine and added keeps the nonce that ngCspNonce adds to esms-options and to the links. I also renamed leaves unparsable esms-options alone to needs the builder's exact {"shimMode":false prefix, since nothing is parsed any more.
|
Couple of small things, for the rest it looks great! |
@angular/ssr writes `<link rel="modulepreload" href="…">`, @angular/build puts `rel` first and the builder writes `shimMode` as the first key, so a literal match replaces the attribute parsing. A spec runs @angular/build's augmentIndexHtml so a change to that order fails CI. The fixtures send `text/html;charset=UTF-8`, as Angular does, and one carries the nonce that ngCspNonce adds.
|
Thanks for reproducing it. Both asks are in 935b8f5:
I updated the description for the minimal version and measured the browsers again with it. |
Backports 22.2.5..22.3.0 onto the Angular 21 layout. Incoming: - #214: @softarc/native-federation ~4.11.0; fromPackageJson() takes an optional base config and autoShareScope resolves projectPath against workspaceRoot. - #171/#213: rewriteModulePreloads (./ssr export) for native import maps. - #209: ngServerMode is set in exposed-module bundles. - #210: the prod node preload no longer passes hostInstances. - #215: NodePackageInstallTask comes from @angular-devkit/schematics/tasks. - Tag-triggered release workflow (staged npm publish). Angular 21 specific adaptations: - Left out the Angular 22.3 bump: kept the -v4 name, 21.2.18 version and ng21 pins; bumped @softarc/native-federation to 4.11 by hand. - Kept the `// upstream:` tags at v21.2.19 (1a728258d6) and the 21.2 debugOptimize note. - Dropped the remote builder, share-utils.spec.ts and tools/esbuild/sourcemap-ignorelist-plugin.ts as before. - @angular/ssr 21.2 emits the same modulepreload markup as 22, so rewriteModulePreloads applies unchanged. - follow-redirects@1 override raised to ^1.16.2 for a high advisory. - pnpm-lock.yaml regenerated rather than merged.
Fixes #171
Problem
With
esmsInitOptions: { shimMode: false },@angular/ssradds a<link rel="modulepreload">for each lazy chunk of the rendered route before</body>. The browser links those modules as soon as it reads them, beforeinitFederationhas added the import map, so a chunk that imports a shared package cannot resolve it and the app does not boot:Fix
rewriteModulePreloads(res: Response | null), exported from a new./ssrentry, in the shape agreed in the issue:esms-optionsstart with{"shimMode":false, allowing other attributes aftertype(thenoncethatngCspNonceadds). There it rewrites<link rel="modulepreload"to<link rel="preload" as="script" crossoriginand dropscontent-length.Response: shim mode, non-HTML responses, pages withoutesms-options, pages with nothing to rewrite, andnull.@angular/ssrwrites<link rel="modulepreload" href="…">(appendPreloadHintsToHtml),@angular/buildwritesrelfirst, and the builder writesshimModeas the first key.ng addis unchanged. I'll open the docs example on native-federation-website once this one is in.Tests
src/ssr.spec.ts: 15 specs for the helper, including a streamed body (the server-rendered path), the content type@angular/ssrsends (text/html;charset=UTF-8), anonceon theesms-optionstag and on the links, and a pass-through whose body is still readable afterwards. One more spec runs@angular/build'saugmentIndexHtml(loaded the wayassets.spec.tsloads Angular's originals) and checks it still writesrelfirst for modulepreload hints, so a change upstream fails CI on the next bump.The
verifyworkflow's steps pass locally on Node 24 and pnpm 11, anddist/package.jsonexports./ssr. (On macOS one existing spec,sourcemap-ignorelist-plugin.spec.ts, also fails onmain, becauseos.tmpdir()is a symlink; withTMPDIRset to its real path all 500 pass.)Measured again with the minimal version, on a host built with this adapter line (Angular 22.2,
shimMode: false, a production build served byAngularNodeAppEngine), with one prerendered and one server-rendered lazy route:Each chunk was requested once in every case (Network events in Chromium and WebKit, Resource Timing in Safari). Firefox is left out, as you noted in the issue: it rejects an import map added after the first module script, so
shimMode: falsedoes not work there with or without this change.In Chromium and WebKit, the same results hold with
ngCspNonceon<app-root>, and with the helper the dev server (ng serve) boots too. WithsubresourceIntegrity: true, Chromium requests the hinted chunks twice, with or without the helper: Angular's SSR hints carry nointegritywhile the imports do, so this PR doesn't change it.