From 88295d41fe31e876ceabe86d27aca19fe23332be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Mon, 23 Nov 2026 04:05:57 +0000 Subject: [PATCH] fix(core): a page naming one script in thousands of tags builds once (#8549) * test(core): a page naming one script in thousands of tags bundles once * fix(core): a page naming one script in thousands of tags builds once * test(core): a nomodule or data-block twin keeps the regular script, many spellings stay fast * fix(core): keep the regular script beside a nomodule twin and index script tags once * test(core): tags of many types naming one file add a bounded number of copies * fix(core): one file is inlined at most four times, whatever types its tags name * test(core): every data block keeps its text, and many copies of one file are refused * fix(core): charge each inlined script copy to the page's size limit, not a per-type cap * test(core): two data blocks of one type naming one file both keep their text * fix(core): only runnable scripts are deduplicated; every data block keeps its text --- .../core/src/compiler/compositionSizeLimit.ts | 7 + packages/core/src/compiler/externalScripts.ts | 10 +- .../htmlBundler.scriptRepeats.test.ts | 256 ++++++++++++++++++ packages/core/src/compiler/htmlBundler.ts | 195 +++++++++---- 4 files changed, 404 insertions(+), 64 deletions(-) create mode 100644 packages/core/src/compiler/htmlBundler.scriptRepeats.test.ts diff --git a/packages/core/src/compiler/compositionSizeLimit.ts b/packages/core/src/compiler/compositionSizeLimit.ts index ea22c598cb..388d2508ee 100644 --- a/packages/core/src/compiler/compositionSizeLimit.ts +++ b/packages/core/src/compiler/compositionSizeLimit.ts @@ -62,6 +62,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 ENTRY_PAGE = "the entry page"; function generatedTooLarge(file: string, bytes: number): string { @@ -77,6 +78,12 @@ function generatedTooLarge(file: string, bytes: number): string { "Use shorter URLs or bind fewer elements." ); } + if (file === LOCAL_SCRIPTS) { + return ( + `Local scripts copied into their tags add up to ${megabytes(bytes)}. ${limitText}. ` + + "Name each script file in one tag." + ); + } if (file === REMOTE_SCRIPTS || file === REMOTE_STYLESHEETS) { return ( `Inlined ${file} add up to ${megabytes(bytes)}. ${limitText}. ` + diff --git a/packages/core/src/compiler/externalScripts.ts b/packages/core/src/compiler/externalScripts.ts index 3b440ba6cf..43376ad7d3 100644 --- a/packages/core/src/compiler/externalScripts.ts +++ b/packages/core/src/compiler/externalScripts.ts @@ -17,10 +17,11 @@ export function ensureExternalScriptTag( doc: Document, src: string, attributes: ExternalScriptAttributes = {}, -): void { - const existing = [...doc.querySelectorAll("script[src]")].filter( - (el) => el.getAttribute("src")?.trim() === src, - ); + tagsWithSrc?: Element[], +): Element[] { + const existing = + tagsWithSrc ?? + [...doc.querySelectorAll("script[src]")].filter((el) => el.getAttribute("src")?.trim() === src); const requirements = new Set( [attributes.integrity, ...existing.map((el) => el.getAttribute("integrity"))] .map((value) => @@ -49,4 +50,5 @@ export function ensureExternalScriptTag( el.setAttribute("src", src); doc.body.appendChild(el); } + return elements; } diff --git a/packages/core/src/compiler/htmlBundler.scriptRepeats.test.ts b/packages/core/src/compiler/htmlBundler.scriptRepeats.test.ts new file mode 100644 index 0000000000..5d63c103f8 --- /dev/null +++ b/packages/core/src/compiler/htmlBundler.scriptRepeats.test.ts @@ -0,0 +1,256 @@ +// @vitest-environment node +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { parseHTML } from "linkedom"; +import { SCENE_PART_ATTR } from "../sceneParts"; +import { bundleToSingleHtml } from "./htmlBundler"; +import { AFTER_FONTS_SCRIPT_TYPE } from "./scriptRuns"; + +const dirs: string[] = []; +afterAll(() => { + for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); +}); + +function project(files: Record): string { + const dir = mkdtempSync(join(tmpdir(), "hf-bundle-repeats-")); + dirs.push(dir); + for (const [name, text] of Object.entries(files)) writeFileSync(join(dir, name), text); + return dir; +} + +const page = (scripts: string) => ` +
+ +${scripts} +`; + +const tags = (count: number, src: (i: number) => string) => + Array.from({ length: count }, (_, i) => ``).join("\n"); + +// Studio's preview build: the lint pass (staticGuard) is off there, and slow on such pages on its own. +const PREVIEW = { + runtime: "placeholder", + inlineAssets: false, + staticGuard: false, + sceneParts: true, +} as const; +const FOUR_MIB = 4 * 1024 * 1024; +const MIB = 1024 * 1024; + +describe("a page naming one script in thousands of tags", () => { + it("reads and inlines a 4 MiB script once for 3,000 tags", { timeout: 20_000 }, async () => { + const body = `window.big = (window.big || 0) + 1; //${"x".repeat(FOUR_MIB)}`; + const dir = project({ "index.html": page(tags(3_000, () => "big.js")), "big.js": body }); + const heapBefore = process.memoryUsage().heapUsed; + const started = performance.now(); + + const html = await bundleToSingleHtml(dir, PREVIEW); + + expect(performance.now() - started).toBeLessThan(10_000); + expect(process.memoryUsage().heapUsed - heapBefore).toBeLessThan(256 * MIB); + expect(html.split("window.big = ").length - 1).toBe(1); + expect(html.length).toBeLessThan(FOUR_MIB + MIB); + }); + + it( + "bundles 30,000 tags naming a missing script in bounded time", + { timeout: 20_000 }, + async () => { + const dir = project({ "index.html": page(tags(30_000, () => "missing.js")) }); + const started = performance.now(); + + const html = await bundleToSingleHtml(dir, PREVIEW); + + expect(performance.now() - started).toBeLessThan(10_000); + const { document } = parseHTML(html); + expect(document.querySelectorAll('script[src="missing.js"]')).toHaveLength(30_000); + }, + ); + + it("inlines a file once whatever spelling each tag uses", async () => { + const spellings = ["a.js", "./a.js", "sub/../a.js", "a.js"]; + const dir = project({ + "index.html": page(tags(spellings.length, (i) => spellings[i]!) + tags(1, () => "b.js")), + "a.js": "window.a = (window.a || 0) + 1;", + "b.js": "window.b = 1;", + }); + + const html = await bundleToSingleHtml(dir, PREVIEW); + + expect(html.split("window.a = ").length - 1).toBe(1); + expect(html).toContain("window.b = 1;"); + expect(html.indexOf("window.a = ")).toBeLessThan(html.indexOf("window.b = 1;")); + }); + + it( + "keeps every tag of a pinned script external, checking the page once", + { timeout: 20_000 }, + async () => { + const dir = project({ + "index.html": page( + tags(1, () => "pinned.js").replace(">", ' integrity="sha384-YQ==">') + + tags(20_000, () => "pinned.js"), + ), + "pinned.js": "window.pinned = 1;", + }); + const started = performance.now(); + + const html = await bundleToSingleHtml(dir, PREVIEW); + + expect(performance.now() - started).toBeLessThan(10_000); + expect(html).not.toContain("window.pinned = 1;"); + const { document } = parseHTML(html); + const pinned = [...document.querySelectorAll('script[src="pinned.js"]')]; + expect(pinned).toHaveLength(20_001); + for (const el of pinned) expect(el.getAttribute("integrity")).toBe("sha384-YQ=="); + }, + ); + + it( + "keeps 20,000 pinned tags of one script external in bounded time", + { timeout: 20_000 }, + async () => { + const dir = project({ + "index.html": page( + tags(20_000, () => "pinned.js").replaceAll( + ">", + ' integrity="sha384-YQ==" crossorigin="anonymous">', + ), + ), + "pinned.js": "window.pinned = 1;", + }); + const started = performance.now(); + + const html = await bundleToSingleHtml(dir, PREVIEW); + + expect(performance.now() - started).toBeLessThan(10_000); + expect(html).not.toContain("window.pinned = 1;"); + const { document } = parseHTML(html); + expect(document.querySelectorAll('script[src="pinned.js"][integrity]')).toHaveLength(20_000); + }, + ); + + it("inlines a composition script once whatever spelling each scene uses", async () => { + const host = (id: string, start: number, src = "") => + `
`; + const sceneBody = (id: string, src: string) => + `
`; + const dir = project({ + "index.html": ` +
+${host("a", 0, "a.html")}${host("b", 1, "b.html")}${host("c", 2)} +
+ + +`, + "a.html": ``, + "b.html": ``, + "lib.js": "window.lib = (window.lib || 0) + 1;", + }); + + const html = await bundleToSingleHtml(dir, PREVIEW); + + expect(html.split("window.lib = ").length - 1).toBe(1); + const { document } = parseHTML(html); + const lib = [...document.querySelectorAll("script")].find((el) => + el.textContent?.includes("window.lib = "), + ); + // Both scenes name it, so it runs for the film, not inside one scene's part. + expect(lib?.getAttribute(SCENE_PART_ATTR)).toBeNull(); + }); + + it("keeps the regular script after a nomodule tag naming the same file", async () => { + const dir = project({ + "index.html": page('\n'), + "a.js": "window.a = 1;", + }); + + const html = await bundleToSingleHtml(dir, PREVIEW); + + const { document } = parseHTML(html); + const copies = [...document.querySelectorAll("script")].filter((el) => + el.textContent?.includes("window.a = 1;"), + ); + expect(copies).toHaveLength(2); + const runs = (el: Element) => + !el.hasAttribute("nomodule") && el.getAttribute("type") === AFTER_FONTS_SCRIPT_TYPE; + expect(copies.some(runs)).toBe(true); + }); + + it("gives every data block naming one file its text", async () => { + const types = ["text/plain", "application/ld+json", "application/json"]; + const dir = project({ + "index.html": page( + types.map((type) => ``).join("\n"), + ), + "a.json": '{"settings":1}', + }); + + const html = await bundleToSingleHtml(dir, PREVIEW); + + const { document } = parseHTML(html); + for (const type of types) { + expect(document.querySelector(`script[type="${type}"]`)?.textContent).toBe('{"settings":1}'); + } + }); + + it("keeps two data blocks of one type naming one file, each with its text", async () => { + const dir = project({ + "index.html": page( + '\n' + + '', + ), + "a.json": '{"settings":1}', + }); + + const html = await bundleToSingleHtml(dir, PREVIEW); + + const { document } = parseHTML(html); + for (const id of ["primary", "secondary"]) { + expect(document.getElementById(id)?.textContent).toBe('{"settings":1}'); + } + }); + + it("refuses a page whose tags copy one file past the page's size limit", async () => { + const typed = Array.from( + { length: 100 }, + (_, i) => ``, + ); + const dir = project({ + "index.html": page(typed.join("\n")), + "a.js": `//${"x".repeat(MIB)}`, + }); + + const error = await bundleToSingleHtml(dir, PREVIEW).catch((caught: unknown) => caught); + + expect(error).toMatchObject({ + code: "COMPOSITION_TOO_LARGE", + publicMetadata: { exceeded: "generated" }, + }); + expect(String(error)).toContain("Name each script file in one tag."); + }); + + it( + "carries a pin to 20,000 spellings of its file in bounded time", + { timeout: 20_000 }, + async () => { + const dir = project({ + "index.html": page( + '\n' + + tags(20_000, (i) => `pinned.js?v=${i}`), + ), + "pinned.js": "window.pinned = 1;", + }); + const started = performance.now(); + + const html = await bundleToSingleHtml(dir, PREVIEW); + + expect(performance.now() - started).toBeLessThan(10_000); + expect(html).not.toContain("window.pinned = 1;"); + const { document } = parseHTML(html); + expect(document.querySelectorAll('script[src^="pinned.js"][integrity]')).toHaveLength(20_001); + }, + ); +}); diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts index 2919b9cb06..3dd8c65695 100644 --- a/packages/core/src/compiler/htmlBundler.ts +++ b/packages/core/src/compiler/htmlBundler.ts @@ -71,7 +71,11 @@ import { import { validateHyperframeHtmlContract } from "./staticGuard"; import { getHyperframeRuntimeScript } from "../generated/runtime-inline"; import { readDeclaredDefaults } from "../runtime/getVariables"; -import { assertCompositionFileSize, CompositionExpansionBudget } from "./compositionSizeLimit"; +import { + assertCompositionFileSize, + CompositionExpansionBudget, + LOCAL_SCRIPTS, +} from "./compositionSizeLimit"; import { ensureExternalLinkTag, inlineSubCompositions, @@ -131,6 +135,7 @@ interface BundleReadScope { projectDir: string; privateFiles: BundlePrivateFiles; noteRead: (filePath: string) => void; + scripts: Map; } const bundleReads = new AsyncLocalStorage(); @@ -156,6 +161,13 @@ function safeReadFile(filePath: string): string | null { } } +function readScriptOnce(filePath: string): string | null { + const scripts = bundleReads.getStore()?.scripts; + if (!scripts) return safeReadFile(filePath); + if (!scripts.has(filePath)) scripts.set(filePath, safeReadFile(filePath)); + return scripts.get(filePath) ?? null; +} + const CSS_PLACEHOLDER_RE = /\/\*__hf_(?:c|import_)\d+__\*\//g; export function restoreCssPlaceholders(css: string, texts: ReadonlyMap): string { @@ -964,51 +976,86 @@ export type BundlePrivateFiles = "vcs-and-secrets" | "studio"; type DeferredScriptChunk = string | (() => string); -function preserveLocalScriptIntegrity( +/** The page's script tags by `src`, collected at first use; a pin carried to a new spelling adds its tag. */ +function scriptTagsBySrc(doc: Document): () => Map { + let index: Map | undefined; + return () => { + if (index) return index; + index = new Map(); + for (const el of doc.querySelectorAll("script[src]")) { + const src = el.getAttribute("src")?.trim() ?? ""; + const tags = index.get(src); + if (tags) tags.push(el); + else index.set(src, [el]); + } + return index; + }; +} + +/** Whether a local script stays external because a tag pins its file; the page's pins are indexed once. */ +function localScriptPins( doc: Document, - src: string, resolvePath: (src: string) => string | null, -): boolean { - const path = resolvePath(src); - if (!path) return false; - const pinned = [...doc.querySelectorAll("script[src][integrity]")].filter((el) => { - const candidate = el.getAttribute("src") || ""; - return ( - isRelativeUrl(candidate) && - resolvePath(candidate) === path && - el.getAttribute("integrity")?.trim() - ); - }); - for (const el of pinned) ensureExternalScriptTag(doc, src, readExternalScriptAttributes(el)); - return pinned.length > 0; + tagsBySrc: () => Map, +): (src: string) => boolean { + let pins: Map> | undefined; + const carried = new Set(); + return (src) => { + if (!pins) { + pins = new Map(); + for (const el of doc.querySelectorAll("script[src][integrity]")) { + const candidate = el.getAttribute("src") || ""; + if (!isRelativeUrl(candidate) || !el.getAttribute("integrity")?.trim()) continue; + const path = resolvePath(candidate); + if (!path) continue; + const attributes = readExternalScriptAttributes(el); + const key = JSON.stringify(attributes); + const byAttributes = pins.get(path) ?? new Map(); + byAttributes.delete(key); + pins.set(path, byAttributes.set(key, attributes)); + } + } + const path = resolvePath(src); + const pinned = path ? pins.get(path) : undefined; + if (!pinned) return false; + if (!carried.has(src)) { + carried.add(src); + const index = tagsBySrc(); + for (const attributes of pinned.values()) + index.set(src, ensureExternalScriptTag(doc, src, attributes, index.get(src) ?? [])); + } + return true; + }; +} + +interface SeenCompScripts { + srcs: Set; + paths: Set; + keepsPinned: (src: string) => boolean; } function hoistExternalScript( src: string, projectDir: string, doc: Document, - seenSrcs: Set, + seen: SeenCompScripts, chunks: DeferredScriptChunk[], attributes: ExternalScriptAttributes, ): void { if (attributes.integrity?.trim()) { ensureExternalScriptTag(doc, src, attributes); - seenSrcs.add(src); + seen.srcs.add(src); return; } - if (seenSrcs.has(src)) return; - seenSrcs.add(src); + if (seen.srcs.has(src)) return; + seen.srcs.add(src); if (!isNonRelativeUrl(src) && !isAbsolute(src) && attributes.type !== "module") { const jsPath = resolveWithinProject(projectDir, decodedUrlPath(src)); - const js = jsPath ? safeReadFile(jsPath) : null; - if (js != null) { - chunks.push(() => - preserveLocalScriptIntegrity(doc, src, (value) => - resolveWithinProject(projectDir, decodedUrlPath(value)), - ) - ? "" - : js, - ); + if (jsPath && seen.paths.has(jsPath)) return; + const js = jsPath ? readScriptOnce(jsPath) : null; + if (jsPath && js != null) { + seen.paths.add(jsPath); + chunks.push(() => (seen.keepsPinned(src) ? "" : js)); return; } } @@ -1024,7 +1071,7 @@ function hoistCompositionScripts( runtimeScope: string | undefined; runtimeCompId: string | undefined; authoredRootId: string | undefined; - seenCompScriptSrcs: Set; + seenCompScripts: SeenCompScripts; compScriptChunks: DeferredScriptChunk[]; importMaps: ImportMap[]; moduleScripts: string[]; @@ -1050,7 +1097,7 @@ function hoistCompositionScripts( externalSrc, opts.projectDir, opts.document, - opts.seenCompScriptSrcs, + opts.seenCompScripts, opts.compScriptChunks, readExternalScriptAttributes(scriptEl), ); @@ -1087,6 +1134,7 @@ export function bundleToSingleHtml(projectDir: string, options?: BundleOptions): projectDir, privateFiles: options?.privateFiles ?? "studio", noteRead, + scripts: new Map(), }; return bundleReads.run(scope, () => bundleProject(projectDir, options)); } @@ -1188,16 +1236,19 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi // Read before sub-compositions add theirs: only the root's own scripts can reach into scenes. const rootScripts = options?.sceneParts ? [ - ...document.querySelectorAll(`script:not([${RUNTIME_BOOTSTRAP_ATTR}])`), - ...[...document.querySelectorAll("template")].flatMap((t) => [ - ...(templateContent(t)?.querySelectorAll("script") ?? []), - ]), - ].map((el) => { - const src = el.getAttribute("src"); - const path = src && isRelativeUrl(src) ? resolveEntryUrl(src) : null; - const text = src ? (path && safeReadFile(path)) || "" : el.textContent || ""; - return isLibraryCopy(text) ? "" : text; - }) + ...new Set( + [ + ...document.querySelectorAll(`script:not([${RUNTIME_BOOTSTRAP_ATTR}])`), + ...[...document.querySelectorAll("template")].flatMap((t) => [ + ...(templateContent(t)?.querySelectorAll("script") ?? []), + ]), + ].map((el) => { + const src = el.getAttribute("src"); + const path = src && isRelativeUrl(src) ? resolveEntryUrl(src) : null; + return src ? (path && readScriptOnce(path)) || "" : el.textContent || ""; + }), + ), + ].map((text) => (isLibraryCopy(text) ? "" : text)) : []; // Inline sub-compositions (via shared function) @@ -1242,7 +1293,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi tagScenes: options?.sceneParts === true, readProjectScript: (path: string) => { const resolved = isRelativeUrl(path) ? resolveEntryUrl(path) : null; - return resolved ? safeReadFile(resolved) : null; + return resolved ? readScriptOnce(resolved) : null; }, readVariableDefaults: readDeclaredDefaults, parseHostVariables: parseHostVariableValues, @@ -1268,11 +1319,24 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi const compVariablesByComp: Record> = { ...subCompResult.variablesByComp, }; - const seenCompScriptSrcs = new Set(); - const scenesBySrc = new Map>(); + const pageScriptTags = scriptTagsBySrc(document); + const keepsEntryPinned = localScriptPins(document, resolveEntryUrl, pageScriptTags); + const seenCompScripts: SeenCompScripts = { + srcs: new Set(), + paths: new Set(), + keepsPinned: localScriptPins( + document, + (value) => resolveWithinProject(projectDir, decodedUrlPath(value)), + pageScriptTags, + ), + }; + const scriptFile = (src: string) => (isRelativeUrl(src) && resolveEntryUrl(src)) || src; + const scenesByFile = new Map>(); for (const item of subCompResult.scriptItems) - if (item.kind !== "inline") - scenesBySrc.set(item.src, (scenesBySrc.get(item.src) ?? new Set()).add(item.scene)); + if (item.kind !== "inline") { + const file = scriptFile(item.src); + scenesByFile.set(file, (scenesByFile.get(file) ?? new Set()).add(item.scene)); + } for (const scriptItem of subCompResult.scriptItems) { if (scriptItem.kind === "inline") { pushRun(scriptRuns, scriptItem.scene, scriptItem.content); @@ -1281,20 +1345,21 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi const extSrc = scriptItem.src; if (scriptItem.integrity?.trim()) { ensureExternalScriptTag(document, extSrc, scriptItem); - seenCompScriptSrcs.add(extSrc); + seenCompScripts.srcs.add(extSrc); continue; } - if (seenCompScriptSrcs.has(extSrc)) continue; - seenCompScriptSrcs.add(extSrc); + if (seenCompScripts.srcs.has(extSrc)) continue; + seenCompScripts.srcs.add(extSrc); // Run once for the film when scenes share it: a scene mounts without the one that loaded it first. - const scene = (scenesBySrc.get(extSrc)?.size ?? 0) > 1 ? undefined : scriptItem.scene; + const scene = + (scenesByFile.get(scriptFile(extSrc))?.size ?? 0) > 1 ? undefined : scriptItem.scene; if (isRelativeUrl(extSrc) && scriptItem.type !== "module") { const jsPath = resolveEntryUrl(extSrc); - const js = jsPath ? safeReadFile(jsPath) : null; - if (js != null) { - const chunk = () => - preserveLocalScriptIntegrity(document, extSrc, resolveEntryUrl) ? "" : js; - pushRun(scriptRuns, scene, chunk); + if (jsPath && seenCompScripts.paths.has(jsPath)) continue; + const js = jsPath ? readScriptOnce(jsPath) : null; + if (jsPath && js != null) { + seenCompScripts.paths.add(jsPath); + pushRun(scriptRuns, scene, () => (keepsEntryPinned(extSrc) ? "" : js)); continue; } } @@ -1379,7 +1444,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi runtimeScope, runtimeCompId, authoredRootId: authoredRootId ?? undefined, - seenCompScriptSrcs, + seenCompScripts, compScriptChunks, importMaps: subCompResult.importMaps, moduleScripts: subCompResult.moduleScripts, @@ -1416,7 +1481,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi runtimeScope, runtimeCompId, authoredRootId: undefined, - seenCompScriptSrcs, + seenCompScripts, compScriptChunks, importMaps: subCompResult.importMaps, moduleScripts: subCompResult.moduleScripts, @@ -1432,17 +1497,27 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi templateEl.remove(); } + // A file named by several regular (or nomodule) tags runs once, as a composition's scripts do: a copy per tag grew + // the page past memory. Data blocks each keep their text; every copy is charged to the page's budget. + const inlinedRootRuns = new Set(); for (const el of [...document.querySelectorAll("script[src]")]) { const src = el.getAttribute("src"); if (!src || !isRelativeUrl(src)) continue; - if (preserveLocalScriptIntegrity(document, src, resolveEntryUrl)) continue; + if (keepsEntryPinned(src)) continue; // Module scripts can contain static imports whose resolution is relative // to the script URL. Folding their source into a classic inline script // both drops module semantics and changes the import base URL. if ((el.getAttribute("type") || "").trim().toLowerCase() === "module") continue; const jsPath = resolveEntryUrl(src); - const js = jsPath ? safeReadFile(jsPath) : null; - if (js == null) continue; + const run = isJavaScriptType(el) ? `${el.hasAttribute("nomodule")} ${jsPath}` : null; + if (jsPath && run !== null && inlinedRootRuns.has(run)) { + el.remove(); + continue; + } + const js = jsPath ? readScriptOnce(jsPath) : null; + if (!jsPath || js == null) continue; + budget.chargeGenerated(LOCAL_SCRIPTS, Buffer.byteLength(js)); + if (run !== null) inlinedRootRuns.add(run); el.setAttribute(INLINED_FILE_ATTR, src); el.removeAttribute("src"); el.textContent = js;