Skip to content

Write HTML. Render video. Built for agents.

perf(core): a heavy project's first preview page builds without repeated style and path scans (#5893)

Miguel Ángel0d51eb0de46b
diff --git a/packages/core/src/compiler/htmlBundler.entryPaths.test.ts b/packages/core/src/compiler/htmlBundler.entryPaths.test.ts
new file mode 100644
index 0000000000..442774962c
--- /dev/null
+++ b/packages/core/src/compiler/htmlBundler.entryPaths.test.ts
@@ -0,0 +1,58 @@
+// @vitest-environment node
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, expect, it, vi } from "vitest";
+import { bundleToSingleHtml } from "./htmlBundler";
+
+const checked = vi.hoisted(() => [] as string[]);
+
+vi.mock("../safePath.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../safePath.js")>();
+ return {
+ ...actual,
+ isSafePath: (base: string, resolved: string) => {
+ checked.push(resolved);
+ return actual.isSafePath(base, resolved);
+ },
+ };
+});
+
+const dir = mkdtempSync(join(tmpdir(), "hf-bundle-entry-paths-"));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+it("checks each project path once per build, however many times a sub-composition is mounted", async () => {
+ mkdirSync(join(dir, "compositions"), { recursive: true });
+ mkdirSync(join(dir, "assets"), { recursive: true });
+ writeFileSync(join(dir, "assets", "logo.png"), "png");
+ writeFileSync(join(dir, "compositions", "texture.png"), "png");
+ writeFileSync(
+ join(dir, "compositions", "card.html"),
+ `<!doctype html><html><head><style>
+.card { background: url(../assets/logo.png); }
+.card .bg { background: url(texture.png); }
+</style></head><body>
+<div data-composition-id="card" data-width="320" data-height="180" data-start="0" data-duration="2">
+ <div class="bg"></div>
+</div></body></html>`,
+ );
+ const mount = (start: number) =>
+ `<div data-composition-id="card" data-composition-src="compositions/card.html" data-start="${start}"` +
+ ` data-duration="2"></div>`;
+ writeFileSync(
+ join(dir, "index.html"),
+ `<!doctype html><html><body>
+<div data-composition-id="main" data-width="320" data-height="180" data-start="0" data-duration="6">
+${[0, 2, 4].map(mount).join("\n")}
+</div>
+<script>window.__timelines = {};</script>
+</body></html>`,
+ );
+
+ const bundled = await bundleToSingleHtml(dir, { inlineAssets: false });
+
+ expect(bundled).toContain("url(compositions/texture.png)");
+ expect(bundled).toContain("url(assets/logo.png)");
+ const repeated = checked.filter((path, at) => checked.indexOf(path) !== at);
+ expect(repeated).toEqual([]);
+});
diff --git a/packages/core/src/compiler/htmlBundler.test.ts b/packages/core/src/compiler/htmlBundler.test.ts
index 3366608623..8978a74494 100644
--- a/packages/core/src/compiler/htmlBundler.test.ts
+++ b/packages/core/src/compiler/htmlBundler.test.ts
@@ -3646,3 +3646,34 @@ describe("stampHfIds", () => {
expect(logo(html)).not.toContain("data-hf-id");
});
});
+
+describe("emitRootCompositionVariableStyles — authored definitions", () => {
+ function emitted(authoredCss: string): string {
+ const { document } = parseHTML(
+ `<!doctype html><html><head><style>${authoredCss}</style></head>` +
+ `<body><div data-composition-id="card"></div></body></html>`,
+ );
+ emitRootCompositionVariableStyles(document, {
+ card: { accent: "blue", "accent-dark": "navy" },
+ });
+ return document.querySelector("style[data-hf-composition-variables]")?.textContent ?? "";
+ }
+
+ it("leaves a variable the stylesheet defines, whatever space sits before its colon", () => {
+ for (const authored of [
+ ":root{--accent:red}",
+ ":root { --accent : red }",
+ ":root {\n --accent\n : red }",
+ ]) {
+ const css = emitted(authored);
+ expect(css).not.toContain("--accent:");
+ expect(css).toContain("--accent-dark: navy");
+ }
+ });
+
+ it("still emits a variable whose name only begins a longer authored one, or is only read", () => {
+ const css = emitted(":root { --accent-dark: black; } .badge { color: var(--accent); }");
+ expect(css).toContain("--accent: blue");
+ expect(css).not.toContain("--accent-dark");
+ });
+});
diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts
index 39c3e1f6eb..d0cdb1c5f0 100644
--- a/packages/core/src/compiler/htmlBundler.ts
+++ b/packages/core/src/compiler/htmlBundler.ts
@@ -1063,9 +1063,16 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
const entryHtml = readFileSync(indexPath, "utf-8");
const mountedShell = readMountedSceneShell(projectDir, entryFile, entryHtml);
const sourceDir = mountedShell ? projectDir : dirname(indexPath);
+ // Every mount of a sub-composition asks again for each of its url()s; isSafePath realpaths the whole chain.
+ const entryPaths = new Map<string, string | null>();
const resolveEntryPath = (relativePath: string): string | null => {
- const resolved = resolve(sourceDir, relativePath);
- return isSafePath(projectDir, resolved) ? resolved : null;
+ let entry = entryPaths.get(relativePath);
+ if (entry === undefined) {
+ const resolved = resolve(sourceDir, relativePath);
+ entry = isSafePath(projectDir, resolved) ? resolved : null;
+ entryPaths.set(relativePath, entry);
+ }
+ return entry;
};
const resolveEntryUrl = (url: string): string | null => resolveEntryPath(decodedUrlPath(url));
@@ -1538,7 +1545,23 @@ function authoredDefinesPredicate(document: Document): (id: string) => boolean {
const authoredCss = [...document.querySelectorAll("style:not([data-hf-composition-variables])")]
.map((s) => s.textContent || "")
.join("\n");
- return (id) => new RegExp(`${cssVariableName(id)}\\s*:`).test(authoredCss);
+ const defined = namesBeforeAColon(authoredCss);
+ return (id) => defined.has(cssVariableName(id));
+}
+
+/** Every `--name` written right before a `:`, including the tail of a longer word (`.a--b:hover`), in one pass. */
+function namesBeforeAColon(css: string): Set<string> {
+ const names = new Set<string>();
+ const word = /[\w-]+/g;
+ const colonNext = /\s*:/y;
+ for (let match = word.exec(css); match; match = word.exec(css)) {
+ colonNext.lastIndex = word.lastIndex;
+ if (!colonNext.test(css)) continue;
+ const text = match[0];
+ for (let at = text.indexOf("--"); at !== -1; at = text.indexOf("--", at + 1))
+ names.add(text.slice(at));
+ }
+ return names;
}
/**
diff --git a/packages/core/src/fonts/deterministicFonts.ts b/packages/core/src/fonts/deterministicFonts.ts
index df0e1b54ec..68c87c9e88 100644
--- a/packages/core/src/fonts/deterministicFonts.ts
+++ b/packages/core/src/fonts/deterministicFonts.ts
@@ -1886,8 +1886,13 @@ function extractGoogleFontsText(html: string): string | undefined {
// Intentional over-approximation: raw html includes base64, scripts, and
// class names, but they collapse in the Set and the budget gate catches bloat.
const uniqueCharacters = new Set<string>();
- for (const character of new Set([...Array.from(html), ...Array.from(decodedBodyText)])) {
- addCaseClosure(uniqueCharacters, character, locales);
+ const seen = new Set<string>();
+ for (const text of [html, decodedBodyText]) {
+ for (const character of text) {
+ if (seen.has(character)) continue;
+ seen.add(character);
+ addCaseClosure(uniqueCharacters, character, locales);
+ }
}
if (hasTextTransformKeyword(html, FULL_WIDTH_KEYWORD_RE)) addFullwidthVariants(uniqueCharacters);