From ea8b396ac827b1948a26d74b991b622d76fd06b4 Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:19:42 -0600 Subject: [PATCH] Re-render incrementally cached pages when their stylesheets change UnoCSS fills its page-ssr stylesheet after transform, so Astro's route dependency hash missed changes to it. When the icon safelist (fetched from the network at build time) changed between builds of one commit, restored API reference pages kept linking a page-ssr.*.css that the new build no longer emitted, causing 404s in production. Fold each page's emitted stylesheets into its dependency hash. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/frontend/patches/README.md | 2 +- src/frontend/patches/astro@7.4.1.patch | 52 ++++++++++++- .../unit/incremental-build.vitest.test.ts | 77 ++++++++++++++++++- 3 files changed, 125 insertions(+), 6 deletions(-) diff --git a/src/frontend/patches/README.md b/src/frontend/patches/README.md index c674508c15..654b56f6a4 100644 --- a/src/frontend/patches/README.md +++ b/src/frontend/patches/README.md @@ -7,6 +7,6 @@ regenerated (`bun patch `, edit, then `bun patch --commit `) | Patch | Why | | --- | --- | | `@astrojs__starlight@0.41.3.patch` | Starlight search must initialize and dispose per element across `ClientRouter` swaps, not only on `DOMContentLoaded` ([#1673](https://github.com/microsoft/aspire.dev/issues/1673)). The sidebar group caret is drawn with a CSS mask from the shared stylesheet instead of an inline SVG repeated for every group (hundreds per API reference page). Also skips untranslated locale fallback routes: StaticHost serves the English page in place (`LocaleFallbackMiddleware`) and `src/scripts/locale-fallback.ts` localizes the chrome, instead of emitting a full English copy per locale. On those pages search waits for `data-translations-pending` to clear, then reads the localized `data-translations` (including Pagefind's own strings for the locale) while it keeps searching the English index. | -| `astro@7.4.1.patch` | Imported SVGs are callable components that can't be structured-cloned, so the parallel prerender worker keeps only their image metadata before posting results. | +| `astro@7.4.1.patch` | Imported SVGs are callable components that can't be structured-cloned, so the parallel prerender worker keeps only their image metadata before posting results. Incremental builds also fold the stylesheets a page links into its route dependency hash: UnoCSS fills its `page-ssr` CSS after transform, so the module graph misses a change to it, and a restored page would link a stylesheet the new build no longer emits (404 on `/_astro/page-ssr.*.css`). | | `starlight-page-actions@0.7.0.patch` | Keeps accessible actions across page swaps, allows readable heading markup, and points Markdown actions on untranslated locale pages to the default-locale Markdown. The dropdown's external-link icon is a CSS mask instead of an inline SVG per item. | | `starlight-plugin-icons@1.1.6.patch` | Temporary network-resilience fix for `getMaterialIconsData`: falls back to the vendored `.starlight-icons` cache when the icon-data fetch fails. Remove once [Rettend/starlight-plugin-icons#9](https://github.com/Rettend/starlight-plugin-icons/pull/9) is merged and released. | diff --git a/src/frontend/patches/astro@7.4.1.patch b/src/frontend/patches/astro@7.4.1.patch index da74376149..3f50fbf622 100644 --- a/src/frontend/patches/astro@7.4.1.patch +++ b/src/frontend/patches/astro@7.4.1.patch @@ -1,5 +1,55 @@ +diff --git a/dist/core/build/generate.js b/dist/core/build/generate.js +index 5c6179d54bb73e7ecc95ed1e6d4c026df9e23c9a..77817fd87dcefb67c35c5927b4dc8705b2e6163a 100644 +--- a/dist/core/build/generate.js ++++ b/dist/core/build/generate.js +@@ -1,3 +1,4 @@ ++import crypto from "node:crypto"; + import nodeFs from "node:fs"; + import os from "node:os"; + import { fileURLToPath } from "node:url"; +@@ -24,6 +25,7 @@ import { IncrementalBuildCache } from "./incremental.js"; + import { computeConfigHash } from "./config-hash/index.js"; + import { computeLockfileHash } from "./lockfile/index.js"; + import { hasPrerenderedPages } from "./internal.js"; ++import { getPageData } from "./runtime.js"; + import { buildPhase } from "./timings/index.js"; + import { getTimeStat, shouldAppendForwardSlash } from "./util.js"; + export async function generatePages(options, internals, prerenderOutputDir, builder) { +@@ -478,6 +480,23 @@ export async function renderPath({ prerenderer, pathname, route, options, routeT + metadata + }; + } ++const routeDependencyHashes = new WeakMap(); ++/** ++* The route's module-graph hash plus the stylesheets its HTML links. CSS generated after ++* transform (UnoCSS fills a placeholder) is invisible to the module graph, so without the ++* emitted sheets a restored page can link a stylesheet this build no longer writes. ++*/ ++function getRouteDependencyHash(internals, route) { ++ let hash = routeDependencyHashes.get(route); ++ if (hash !== undefined) return hash; ++ hash = internals.pageDependencyHashes?.get(route.component) ?? ""; ++ const sheets = getPageData(internals, route.route, route.component)?.styles.map(({ sheet }) => sheet.type === "external" ? `external:${sheet.src}` : `inline:${sheet.content}`).sort(); ++ if (sheets?.length) { ++ hash = crypto.createHash("sha256").update(hash).update("\n").update(sheets.join("\n")).digest("hex"); ++ } ++ routeDependencyHashes.set(route, hash); ++ return hash; ++} + /** + * Generate a single path using the prerenderer interface. + * Orchestrates rendering via `renderPath()` and writes the result to the filesystem. +@@ -498,7 +517,7 @@ async function generatePathWithPrerenderer(prerenderer, pathname, route, options + // Relative path from the resolved client output directory for cache storage + const relativeOutFile = outFile.href.slice(options.outputDirectories.client.href.length); + // Look up the dependency hash for this route +- const dependencyHash = internals.pageDependencyHashes?.get(route.component) ?? ""; ++ const dependencyHash = getRouteDependencyHash(internals, route); + const hasServerIsland = internals.serverIslandPageComponents?.has(route.component) ?? false; + // Incremental build: check if we can skip this path + if (cacheKey !== undefined && cache?.canSkip(route.component, pathname, dependencyHash, cacheKey, hasServerIsland)) { diff --git a/dist/core/build/prerender-worker.js b/dist/core/build/prerender-worker.js -index 90889cc530bac8d7498858ab78c45a40460984a8..932447d4f6cd8e989ed0ee8cbd34df8947be6d44 100644 +index 90889cc530bac8d7498858ab78c45a40460984a8..c2c23022787ab4e3192ef192bf557cd5a23dd0a7 100644 --- a/dist/core/build/prerender-worker.js +++ b/dist/core/build/prerender-worker.js @@ -110,6 +110,11 @@ async function start() { diff --git a/src/frontend/tests/unit/incremental-build.vitest.test.ts b/src/frontend/tests/unit/incremental-build.vitest.test.ts index 9df97ac844..48609faad0 100644 --- a/src/frontend/tests/unit/incremental-build.vitest.test.ts +++ b/src/frontend/tests/unit/incremental-build.vitest.test.ts @@ -95,11 +95,11 @@ async function writeProjectFile(project: string, file: string, content: string): await writeFile(join(project, file), content); } -async function createProject(): Promise { +async function createProject(files: Record = FILES): Promise { const project = await mkdtemp(join(tmpdir(), 'aspire-incremental-build-')); directories.push(project); await symlink(join(frontendRoot, 'node_modules'), join(project, 'node_modules'), 'junction'); - for (const [file, content] of Object.entries(FILES)) { + for (const [file, content] of Object.entries(files)) { await writeProjectFile(project, file, content); } await mkdir(join(project, 'src/utils'), { recursive: true }); @@ -113,11 +113,22 @@ function writeDocument(project: string, name: string, summary: string): Promise< return writeProjectFile(project, `data/${name}.json`, JSON.stringify({ package: { name }, summary })); } -async function build(project: string, buildId: string, commit = 'commit-a'): Promise { +async function build( + project: string, + buildId: string, + commit = 'commit-a', + extraEnv: Record = {} +): Promise { const { NODE_ENV: _nodeEnv, MODE: _mode, VITEST: _vitest, ...env } = process.env; await run('bun', ['--bun', 'node_modules/astro/bin/astro.mjs', 'build'], { cwd: project, - env: { ...env, ASTRO_TELEMETRY_DISABLED: '1', FIXTURE_BUILD_ID: buildId, PUBLIC_GIT_COMMIT_ID: commit }, + env: { + ...env, + ...extraEnv, + ASTRO_TELEMETRY_DISABLED: '1', + FIXTURE_BUILD_ID: buildId, + PUBLIC_GIT_COMMIT_ID: commit, + }, maxBuffer: 16 * 1024 * 1024, }); } @@ -207,3 +218,61 @@ test('incremental builds reuse unchanged pages, invalidate changed inputs and pr expect(cached.filter((file) => file.includes('alpha')).length).toBeGreaterThan(0); expect(cached.filter((file) => file.includes('beta'))).toEqual([]); }, 300_000); + +// UnoCSS fills its `page-ssr` stylesheet after Vite transforms modules, so the route's +// dependency hash only sees a placeholder. Production's icon safelist comes from network +// data at build time; when it changed between builds of one commit, restored API pages +// kept linking a stylesheet the new build no longer emitted. +const STYLESHEET_FILES: Record = { + 'package.json': FILES['package.json'], + 'astro.config.mjs': ` + import { defineConfig } from 'astro/config'; + import UnoCSS from 'unocss/astro'; + export default defineConfig({ + cacheDir: './.astro-cache', + integrations: [UnoCSS({ injectReset: false })], + build: { inlineStylesheets: 'never' }, + experimental: { parallelPrerender: { workers: 2 }, incrementalBuild: true }, + });`, + 'uno.config.mjs': ` + import { defineConfig } from 'unocss'; + export default defineConfig({ + rules: [[/^fixture-([a-z]+)$/, ([, color]) => ({ color })]], + safelist: (process.env.FIXTURE_SAFELIST ?? '').split(',').filter(Boolean), + });`, + 'src/pages/index.astro': `

home|{process.env.FIXTURE_BUILD_ID}

`, + 'src/pages/reference/[package].astro': `--- + export function getStaticPaths() { + return [{ cacheKey: 'alpha', params: { package: 'alpha' } }]; + } + --- +

alpha|{process.env.FIXTURE_BUILD_ID}

`, +}; + +function stylesheets(output: Record, file: string): string[] { + return [...(output[file] ?? '').matchAll(/href="\/(_astro\/[^"]+\.css)"/g)] + .map((match) => match[1]) + .sort(); +} + +test('incremental builds re-render cached pages whose emitted stylesheets changed', async () => { + const project = await createProject(STYLESHEET_FILES); + + await build(project, 'cold', 'commit-a', { FIXTURE_SAFELIST: 'fixture-red' }); + const cold = await readOutput(project); + expect(stylesheets(cold, 'reference/alpha/index.html')).toHaveLength(1); + + await build(project, 'safelist', 'commit-a', { FIXTURE_SAFELIST: 'fixture-red,fixture-blue' }); + const safelist = await readOutput(project); + const home = stylesheets(safelist, 'index.html'); + expect(home).toHaveLength(1); + expect(home).not.toEqual(stylesheets(cold, 'index.html')); + expect(stylesheets(safelist, 'reference/alpha/index.html')).toEqual(home); + expect(Object.keys(safelist)).toContain(home[0]); + expect(rendered(safelist, 'reference/alpha/index.html')).toBe('alpha|safelist'); + + // Unchanged stylesheets still let the page be reused. + await build(project, 'warm', 'commit-a', { FIXTURE_SAFELIST: 'fixture-red,fixture-blue' }); + const warm = await readOutput(project); + expect(rendered(warm, 'reference/alpha/index.html')).toBe('alpha|safelist'); +}, 300_000);