Skip to content

Commit cd975d8

Browse files
fix(core/bundler): inline fonts and images so a lone bundle renders (#3590)
`bundleToSingleHtml` documented itself as producing "a single self-contained HTML file", but `INLINE_MIME` covered only `.svg`, `.json`, `.txt`, `.cube` and `.xml`. Every font and raster image stayed a live project-relative reference. That is invisible to every consumer in this repo, because each one serves the bundled string from a server rooted at the project directory, so the relative paths resolve. It breaks the moment the bundle is stored on its own, with no sibling asset directory: the font 404s and the page silently reflows in a fallback face, which is worse than a visible failure. Widen the inline set to fonts (woff2/woff/ttf/otf) and raster images (png/jpg/jpeg/gif/webp/avif), behind a 2 MiB per-asset cap. The cap is measured against this repo's own assets rather than guessed: the largest of 164 tracked `.woff2` files is 105 KB, and the largest of 284 tracked raster images is 2.00 MB, so everything in-tree inlines while a video-sized file cannot. Oversized assets keep their relative URL and warn, reusing the existing "may not be self-contained" wording. Audio and video stay external on purpose: they are large, streamed rather than laid out, and their absence is obvious rather than silent. Scripts already had a better path (`script[src]` is folded in as source), so they are deliberately not added to the MIME table. The five rebasing tests that asserted a relative path survived now assert the data URL's decoded content instead. That is a stronger check: resolving from the wrong base directory finds no file, so nothing inlines and the assertion fails.
1 parent 4c26ffe commit cd975d8

2 files changed

Lines changed: 135 additions & 7 deletions

File tree

‎packages/core/src/compiler/htmlBundler.test.ts‎

Lines changed: 78 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,16 @@ function makeTempProject(files: Record<string, string>): string {
2020
return dir;
2121
}
2222

23+
/**
24+
* The data URL a correctly-resolved asset must inline to. Asserting on the
25+
* asset's CONTENT, not on the rewritten path string, is what proves rebasing
26+
* resolved to the right file: resolving from the wrong base directory finds no
27+
* file at all, so nothing is inlined and the assertion fails.
28+
*/
29+
function inlinedAs(mime: string, content: string): string {
30+
return `data:${mime};base64,${Buffer.from(content, "utf-8").toString("base64")}`;
31+
}
32+
2333
function makeColorGradingProject(lutSrc: string, files: Record<string, string> = {}): string {
2434
return makeTempProject({
2535
"index.html": `<!doctype html>
@@ -1211,7 +1221,7 @@ describe("bundleToSingleHtml", () => {
12111221

12121222
const bundled = await bundleToSingleHtml(dir);
12131223

1214-
expect(bundled).toContain("url('styles/assets/fonts/brand.woff2')");
1224+
expect(bundled).toContain(`url('${inlinedAs("font/woff2", "fake-font-data")}')`);
12151225
expect(bundled).not.toContain("url('assets/fonts/brand.woff2')");
12161226
expect(bundled).not.toContain("@import");
12171227
});
@@ -1230,7 +1240,7 @@ describe("bundleToSingleHtml", () => {
12301240

12311241
const bundled = await bundleToSingleHtml(dir);
12321242

1233-
expect(bundled).toContain("url('theme/images/grain.png')");
1243+
expect(bundled).toContain(`url('${inlinedAs("image/png", "fake-image-data")}')`);
12341244
expect(bundled).not.toContain("url('./images/grain.png')");
12351245
});
12361246

@@ -1249,7 +1259,7 @@ describe("bundleToSingleHtml", () => {
12491259

12501260
const bundled = await bundleToSingleHtml(dir);
12511261

1252-
expect(bundled).toContain("url('assets/bg.png')");
1262+
expect(bundled).toContain(`url('${inlinedAs("image/png", "fake-image")}')`);
12531263
expect(bundled).not.toContain("url('../../assets/bg.png')");
12541264
});
12551265

@@ -1273,7 +1283,7 @@ describe("bundleToSingleHtml", () => {
12731283

12741284
expect(bundled).toContain("url('https://cdn.example.com/font.woff2')");
12751285
expect(bundled).toContain("url('data:image/svg+xml,<svg/>')");
1276-
expect(bundled).toContain("url('styles/img/bg.png')");
1286+
expect(bundled).toContain(`url('${inlinedAs("image/png", "fake")}')`);
12771287
});
12781288

12791289
it("preserves url() query strings and hash fragments during rebasing", async () => {
@@ -1290,7 +1300,70 @@ describe("bundleToSingleHtml", () => {
12901300

12911301
const bundled = await bundleToSingleHtml(dir);
12921302

1293-
expect(bundled).toContain("url('styles/sprite.png?v=2#section')");
1303+
// The query/hash suffix rides along onto the inlined data URL.
1304+
expect(bundled).toContain(`url('${inlinedAs("image/png", "fake-sprite")}?v=2#section')`);
1305+
});
1306+
1307+
it("inlines fonts, images and scripts so no relative asset reference survives", async () => {
1308+
const dir = makeTempProject({
1309+
"index.html": `<!doctype html>
1310+
<html><head>
1311+
<style>
1312+
@font-face { font-family: "Brand"; src: url('assets/fonts/brand.woff2') format('woff2'); }
1313+
.hero { background: url('assets/hero.jpg'); }
1314+
</style>
1315+
</head><body>
1316+
<div data-composition-id="root" data-width="320" data-height="180">
1317+
<img id="logo" src="assets/logo.png" srcset="assets/logo2x.webp 2x">
1318+
<video id="clip" poster="assets/poster.gif"></video>
1319+
</div>
1320+
<script src="assets/app.js"></script>
1321+
<script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
1322+
</body></html>`,
1323+
"assets/fonts/brand.woff2": "font-bytes",
1324+
"assets/hero.jpg": "hero-bytes",
1325+
"assets/logo.png": "logo-bytes",
1326+
"assets/logo2x.webp": "logo2x-bytes",
1327+
"assets/poster.gif": "poster-bytes",
1328+
"assets/app.js": "window.__APP_LOADED__ = true;",
1329+
});
1330+
1331+
const bundled = await bundleToSingleHtml(dir);
1332+
1333+
// Each asset arrives as its own bytes, which is what proves its path
1334+
// resolved to the right file rather than merely being rewritten.
1335+
expect(bundled).toContain(inlinedAs("font/woff2", "font-bytes"));
1336+
expect(bundled).toContain(inlinedAs("image/jpeg", "hero-bytes"));
1337+
expect(bundled).toContain(inlinedAs("image/png", "logo-bytes"));
1338+
expect(bundled).toContain(inlinedAs("image/webp", "logo2x-bytes"));
1339+
expect(bundled).toContain(inlinedAs("image/gif", "poster-bytes"));
1340+
// A local classic script is folded in as source, not as a data: URL.
1341+
expect(bundled).toContain("window.__APP_LOADED__ = true;");
1342+
1343+
// Nothing still points into the sibling assets/ directory that a consumer
1344+
// storing this bundle as a lone file will not have.
1345+
expect(bundled).not.toMatch(/["'(]assets\//);
1346+
});
1347+
1348+
it("leaves an oversized asset relative and warns rather than inlining it", async () => {
1349+
const dir = makeTempProject({
1350+
"index.html": `<!doctype html>
1351+
<html><body>
1352+
<div data-composition-id="root" data-width="320" data-height="180">
1353+
<img id="big" src="assets/huge.png">
1354+
</div>
1355+
<script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
1356+
</body></html>`,
1357+
"assets/huge.png": "x".repeat(2 * 1024 * 1024 + 1),
1358+
});
1359+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
1360+
1361+
const bundled = await bundleToSingleHtml(dir);
1362+
1363+
expect(bundled).toContain('src="assets/huge.png"');
1364+
expect(bundled).not.toContain("data:image/png");
1365+
expect(warn.mock.calls.flat().join(" ")).toContain("may not be self-contained");
1366+
warn.mockRestore();
12941367
});
12951368

12961369
it("deduplicates diamond @import (same file imported by two parents)", async () => {

‎packages/core/src/compiler/htmlBundler.ts‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export { FLATTENED_INNER_ROOT_STRIP_ATTRS } from "../runtime/flattenedRoot";
88
import { parseHostVariableValues, warnUnknownEnumValues } from "../runtime/getVariables";
99
import { sanitizeCssValue } from "../runtime/applyVariableBindings";
1010
import { cssVariableName } from "../tokenSlug";
11-
import { readFileSync, existsSync } from "fs";
11+
import { readFileSync, existsSync, statSync } from "fs";
1212
import { resolve, relative, dirname, isAbsolute, sep } from "path";
1313
import { CSS_URL_RE, isNonRelativeUrl } from "./assetPaths.js";
1414
import { transformSync } from "esbuild";
@@ -299,8 +299,54 @@ const INLINE_MIME: Record<string, string> = {
299299
".txt": "text/plain",
300300
".cube": "text/plain",
301301
".xml": "application/xml",
302+
// Fonts and raster images. A bundle handed to a consumer that stores it as a
303+
// lone object — no sibling `assets/` directory — 404s on every surviving
304+
// relative reference, and a missing font silently reflows the whole frame
305+
// rather than failing loudly. Media (mp4/webm/mp3/wav) is deliberately absent:
306+
// it is large, streamed rather than laid out, and its absence is obvious.
307+
".woff2": "font/woff2",
308+
".woff": "font/woff",
309+
".ttf": "font/ttf",
310+
".otf": "font/otf",
311+
".png": "image/png",
312+
".jpg": "image/jpeg",
313+
".jpeg": "image/jpeg",
314+
".gif": "image/gif",
315+
".webp": "image/webp",
316+
".avif": "image/avif",
302317
};
303318

319+
/**
320+
* Per-asset ceiling on base64 inlining.
321+
*
322+
* Base64 costs ~33% over the raw bytes, so an unbounded rule turns one careless
323+
* 40 MB asset into a bundle no browser should be asked to parse. 2 MiB is
324+
* measured against this repo's own assets rather than picked: the largest of
325+
* 164 tracked `.woff2` files is 105 KB (p90 75 KB) and the largest of 284
326+
* tracked raster images is 2.00 MB (p90 437 KB). So every font and effectively
327+
* every image in-tree inlines, while a video-sized file cannot.
328+
*
329+
* Oversized assets keep their project-relative URL — correct wherever the
330+
* bundle is served from its project directory, and warned about because that is
331+
* exactly where "self-contained" stops being true.
332+
*/
333+
const MAX_INLINE_ASSET_BYTES = 2 * 1024 * 1024;
334+
335+
function safeStatSize(filePath: string): number | null {
336+
try {
337+
return statSync(filePath).size;
338+
} catch {
339+
return null;
340+
}
341+
}
342+
343+
function warnAssetTooLargeToInline(assetPath: string, byteLength: number): void {
344+
const mb = (byteLength / (1024 * 1024)).toFixed(1);
345+
console.warn(
346+
`[HyperFrames] Not inlining "${assetPath}" (${mb} MB exceeds the ${MAX_INLINE_ASSET_BYTES / (1024 * 1024)} MB inline limit). The bundle may not be self-contained.`,
347+
);
348+
}
349+
304350
function maybeInlineRelativeAssetUrl(urlValue: string, projectDir: string): string | null {
305351
if (!urlValue || !isRelativeUrl(urlValue)) return null;
306352
const { basePath, suffix } = splitUrlSuffix(urlValue.trim());
@@ -310,6 +356,13 @@ function maybeInlineRelativeAssetUrl(urlValue: string, projectDir: string): stri
310356
const ext = filePath.toLowerCase().match(/\.[^.]+$/)?.[0] ?? "";
311357
const mimeType = INLINE_MIME[ext];
312358
if (!mimeType) return null;
359+
// Size-check before reading: an oversized asset must not be pulled into memory
360+
// just to be discarded.
361+
const byteLength = safeStatSize(filePath);
362+
if (byteLength !== null && byteLength > MAX_INLINE_ASSET_BYTES) {
363+
warnAssetTooLargeToInline(basePath, byteLength);
364+
return null;
365+
}
313366
const content = safeReadFileBuffer(filePath);
314367
if (content == null) return null;
315368
const dataUrl = `data:${mimeType};base64,${content.toString("base64")}`;
@@ -724,7 +777,9 @@ export interface BundleOptions {
724777
* - Injects the HyperFrames runtime script
725778
* - Inlines local CSS and JS files
726779
* - Inlines sub-composition HTML fragments (data-composition-src)
727-
* - Inlines small textual assets as data URLs
780+
* - Inlines textual assets, fonts and raster images as data URLs, up to a
781+
* per-asset size limit; audio/video and oversized assets keep their
782+
* project-relative URL and require the project directory to be served
728783
*/
729784

730785
type DeferredScriptChunk = string | (() => string);

0 commit comments

Comments
 (0)