From 96abfaf0d01e67ed94f0149a99d8795b67fa79e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Mon, 23 Nov 2026 10:07:30 +0000 Subject: [PATCH] fix(core): count copied stylesheets and scene scripts toward a bundle's size limit (#8573) --- .../core/src/compiler/compositionSizeLimit.ts | 7 ++ .../htmlBundler.expansionBudget.test.ts | 98 ++++++++++++++++++- packages/core/src/compiler/htmlBundler.ts | 55 ++++++++--- 3 files changed, 148 insertions(+), 12 deletions(-) diff --git a/packages/core/src/compiler/compositionSizeLimit.ts b/packages/core/src/compiler/compositionSizeLimit.ts index 388d2508ee..078a0f2da8 100644 --- a/packages/core/src/compiler/compositionSizeLimit.ts +++ b/packages/core/src/compiler/compositionSizeLimit.ts @@ -63,6 +63,7 @@ const limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSI export const REMOTE_SCRIPTS = "remote scripts"; export const REMOTE_STYLESHEETS = "remote stylesheets"; export const LOCAL_SCRIPTS = "local scripts"; +export const LOCAL_STYLESHEETS = "local stylesheets"; export const ENTRY_PAGE = "the entry page"; function generatedTooLarge(file: string, bytes: number): string { @@ -84,6 +85,12 @@ function generatedTooLarge(file: string, bytes: number): string { "Name each script file in one tag." ); } + if (file === LOCAL_STYLESHEETS) { + return ( + `Local stylesheets copied into the page add up to ${megabytes(bytes)}. ${limitText}. ` + + "Link each stylesheet once and import each file once." + ); + } if (file === REMOTE_SCRIPTS || file === REMOTE_STYLESHEETS) { return ( `Inlined ${file} add up to ${megabytes(bytes)}. ${limitText}. ` + diff --git a/packages/core/src/compiler/htmlBundler.expansionBudget.test.ts b/packages/core/src/compiler/htmlBundler.expansionBudget.test.ts index cdb56e7e91..c59087b322 100644 --- a/packages/core/src/compiler/htmlBundler.expansionBudget.test.ts +++ b/packages/core/src/compiler/htmlBundler.expansionBudget.test.ts @@ -1,11 +1,12 @@ // @vitest-environment node -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, describe, expect, it } from "vitest"; import { MAX_COMPOSITION_HTML_BYTES, MAX_EXPANDED_COMPOSITION_BYTES } from "./compositionSizeLimit"; import { bundleToSingleHtml } from "./htmlBundler"; +const MIB = 1024 * 1024; const dirs: string[] = []; afterAll(() => { for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); @@ -115,6 +116,101 @@ describe("preview bundle expansion budget", () => { expect(String(error)).toContain('Composition file "huge.html"'); }); + it("refuses one stylesheet linked past the page's size limit", async () => { + const links = ''.repeat(70); + const dir = project({ + "index.html": root("").replace("", `${links}`), + "a.css": `/*${"x".repeat(MIB)}*/`, + }); + + const error = await bundleToSingleHtml(dir, { inlineAssets: false, staticGuard: false }).catch( + (caught: unknown) => caught, + ); + + expect(error).toMatchObject({ + code: "COMPOSITION_TOO_LARGE", + publicMetadata: { exceeded: "generated" }, + }); + expect(String(error)).toContain("Link each stylesheet once"); + }); + + it("refuses one stylesheet imported past the page's size limit", async () => { + const dir = project({ + "index.html": root("").replace( + "", + '', + ), + "a.css": '@import "b.css";\n'.repeat(70), + "b.css": `/*${"x".repeat(MIB)}*/`, + }); + + const error = await bundleError(dir); + + expect(error).toMatchObject({ + code: "COMPOSITION_TOO_LARGE", + publicMetadata: { exceeded: "generated" }, + }); + expect(String(error)).toContain("import each file once"); + }); + + it("refuses @imports that copy the same file past the limit", async () => { + // Each level imports the next twice: 2^11 copies of a 64 KiB sheet. + const files: Record = { + "index.html": root("").replace( + "", + '', + ), + "s11.css": `/*${"x".repeat(64 * 1024)}*/`, + }; + for (let level = 0; level < 11; level += 1) { + const next = `s${level + 1}.css`; + files[`s${level}.css`] = `@import "${next}";\n@import url(${next}) print;\n`; + } + + const error = await bundleError(project(files)); + + expect(error).toMatchObject({ + code: "COMPOSITION_TOO_LARGE", + publicMetadata: { exceeded: "generated" }, + }); + }, 30_000); + + it.each([ + [ + "a mounted scene file", + (tags: string) => ({ index: root(mounts("scene.html", 1)), scene: scene(tags) }), + ], + [ + "an inline template", + (tags: string) => ({ + index: root( + `` + + '
', + ), + scene: "", + }), + ], + ])("refuses %s naming one script file by many names past the limit", async (_, page) => { + const names = Array.from({ length: 70 }, (_, i) => `alias-${i}.js`); + const { index, scene: sceneHtml } = page( + names.map((n) => ``).join(""), + ); + const dir = project({ + "index.html": index, + "scene.html": sceneHtml, + "a.js": `//${"x".repeat(MIB)}`, + }); + for (const name of names) symlinkSync(join(dir, "a.js"), join(dir, name)); + + const error = await bundleError(dir); + + expect(error).toMatchObject({ + code: "COMPOSITION_TOO_LARGE", + publicMetadata: { exceeded: "generated" }, + }); + expect(String(error)).toContain("Name each script file in one tag."); + }); + it("still bundles a scene mounted a few times, once per mount", async () => { const dir = project({ "index.html": root(mounts("wrapper.html", 3)), diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts index 3dd8c65695..14c852ea21 100644 --- a/packages/core/src/compiler/htmlBundler.ts +++ b/packages/core/src/compiler/htmlBundler.ts @@ -75,6 +75,7 @@ import { assertCompositionFileSize, CompositionExpansionBudget, LOCAL_SCRIPTS, + LOCAL_STYLESHEETS, } from "./compositionSizeLimit"; import { ensureExternalLinkTag, @@ -286,7 +287,10 @@ function inlineCssFile( cssFileDir: string, projectDir: string, activeImports: Set, + budget: CompositionExpansionBudget, ): string { + // Charged per copy, before its imports are read: a file imported twice at every level doubles per level. + budget.chargeGenerated(LOCAL_STYLESHEETS, Buffer.byteLength(css)); const { stripped: strippedCss, comments: placeholders } = withCommentsStripped(css); const withPlaceholders = replaceMatches( strippedCss, @@ -302,7 +306,7 @@ function inlineCssFile( const content = safeReadFile(resolved); if (content == null) return full; activeImports.add(resolved); - const inlined = inlineCssFile(content, dirname(resolved), projectDir, activeImports); + const inlined = inlineCssFile(content, dirname(resolved), projectDir, activeImports, budget); activeImports.delete(resolved); const trimmedMedia = (mediaQuery || "").trim(); const block = trimmedMedia ? `@media ${trimmedMedia} {\n${inlined}\n}\n` : inlined + "\n"; @@ -1031,7 +1035,25 @@ function localScriptPins( interface SeenCompScripts { srcs: Set; paths: Set; - keepsPinned: (src: string) => boolean; + inlineFile: (src: string, js: string) => DeferredScriptChunk; +} + +/** + * A local script file copied in for a composition. Charged when read, so many names for one file stop at + * the budget; given back if a pin keeps the file external. + */ +function inlinedScriptFile( + js: string, + keepsPinned: () => boolean, + budget: CompositionExpansionBudget, +): DeferredScriptChunk { + const bytes = Buffer.byteLength(js); + budget.chargeGenerated(LOCAL_SCRIPTS, bytes); + return () => { + if (!keepsPinned()) return js; + budget.chargeGenerated(LOCAL_SCRIPTS, -bytes); + return ""; + }; } function hoistExternalScript( @@ -1055,7 +1077,7 @@ function hoistExternalScript( const js = jsPath ? readScriptOnce(jsPath) : null; if (jsPath && js != null) { seen.paths.add(jsPath); - chunks.push(() => (seen.keepsPinned(src) ? "" : js)); + chunks.push(seen.inlineFile(src, js)); return; } } @@ -1216,6 +1238,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi rebaseEntryAuthoredAssetPaths(document, sourceDir, projectDir); } + const budget = new CompositionExpansionBudget(); for (const el of [...document.querySelectorAll('link[rel="stylesheet"]')]) { const href = el.getAttribute("href"); if (!href || !isRelativeUrl(href) || cssStyleMergeKey(el) === undefined) continue; @@ -1229,7 +1252,13 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi const value = el.getAttribute(name); if (value !== null) style.setAttribute(name, value); } - style.textContent = inlineCssFile(css, dirname(cssPath), projectDir, new Set([cssPath])); + style.textContent = inlineCssFile( + css, + dirname(cssPath), + projectDir, + new Set([cssPath]), + budget, + ); el.replaceWith(style); } @@ -1258,7 +1287,6 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi host.hasAttribute("data-composition-src"), ); const sceneSources = new Map(); - const budget = new CompositionExpansionBudget(); const subCompResult = inlineSubCompositions(document, subCompositionHosts, { resolveHtml: (srcPath: string) => { if (!isRelativeUrl(srcPath)) return null; @@ -1321,14 +1349,15 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi }; const pageScriptTags = scriptTagsBySrc(document); const keepsEntryPinned = localScriptPins(document, resolveEntryUrl, pageScriptTags); + const keepsCompPinned = localScriptPins( + document, + (value) => resolveWithinProject(projectDir, decodedUrlPath(value)), + pageScriptTags, + ); const seenCompScripts: SeenCompScripts = { srcs: new Set(), paths: new Set(), - keepsPinned: localScriptPins( - document, - (value) => resolveWithinProject(projectDir, decodedUrlPath(value)), - pageScriptTags, - ), + inlineFile: (src, js) => inlinedScriptFile(js, () => keepsCompPinned(src), budget), }; const scriptFile = (src: string) => (isRelativeUrl(src) && resolveEntryUrl(src)) || src; const scenesByFile = new Map>(); @@ -1359,7 +1388,11 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi const js = jsPath ? readScriptOnce(jsPath) : null; if (jsPath && js != null) { seenCompScripts.paths.add(jsPath); - pushRun(scriptRuns, scene, () => (keepsEntryPinned(extSrc) ? "" : js)); + pushRun( + scriptRuns, + scene, + inlinedScriptFile(js, () => keepsEntryPinned(extSrc), budget), + ); continue; } }