perf(cli): stop gzipping the studio bundle on loopback

Compression made the cold open slower on the only transport this server has.
It binds 127.0.0.1 with no --host, and measured there the six bundle assets
took 69.8 ms with gzip against 7.9 ms raw; the 4.1 MB chunk alone was 49.4 ms
against 3.1 ms. hono/compress is removed, which also retires the Vary header
question it raised. If remote serving ever matters, compress at build time
rather than per request.

The cache policy is now decided by route instead of by filename. Reading a
content hash out of a name cannot work: rollup's alphabet is base64url and
includes a hyphen, so roughly one hashed file in ten was misread as unhashed,
and the immutable header also leaked onto hand-authored public/ files served
by the same handler. packages/studio/vite.config.ts sets neither
build.assetsDir nor publicDir, so dist/assets holds only rollup's hashed
emits and every public/ file lands at the dist root. /assets/* is therefore
immutable and /icons/* and /favicon.svg keep revalidating, with no heuristic
in between.

The shell is no-cache rather than no-store. It carries no ETag, so both force
the same full refetch, but no-store puts the document on Chrome's bfcache
blocklist: leaving Studio and pressing Back would cold-boot the app instead
of restoring it.
This commit is contained in:
Miguel Angel Simon Sierra
2026-09-12 06:00:09 -04:00
parent e3f6d7d768
commit 4b784207d1
3 changed files with 49 additions and 85 deletions
@@ -148,16 +148,19 @@ describe("Studio bundle file reads", () => {
},
);
// /assets/ holds only Vite's content-hashed emits, so it is served immutable
// while the hand-authored public/ files keep revalidating. Cache policy
// itself is owned by studioServer.staticAssets.test.ts.
it.each([
["assets/main.js", "text/javascript"],
["icons/logo.svg", "image/svg+xml"],
["favicon.svg", "image/svg+xml"],
])("preserves %s MIME and cache headers", async (name, mime) => {
["assets/main.js", "text/javascript", "public, max-age=31536000, immutable"],
["icons/logo.svg", "image/svg+xml", "no-store"],
["favicon.svg", "image/svg+xml", "no-store"],
])("preserves %s MIME and cache headers", async (name, mime, cacheControl) => {
fs.writeFileSync(path.join(hooks.studioDir, name), "");
const response = await server.app.request(`/${name}`);
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toContain(mime);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(response.headers.get("cache-control")).toBe(cacheControl);
expect(await response.text()).toBe("");
expectClosed();
});
@@ -2,13 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as fs from "node:fs";
import * as path from "node:path";
import { tmpdir } from "node:os";
import { createStudioServer, isContentHashedAsset, type StudioServer } from "./studioServer.js";
import { createStudioServer, type StudioServer } from "./studioServer.js";
/**
* Cache and transfer policy for the studio bundle. A content-hashed URL can
* never serve different bytes, so it is safe to keep forever; everything else
* the same routes serve (public/ files, the HTML shell) changes under a
* stable URL and must keep revalidating.
* Cache policy for the studio bundle, decided by ROUTE. Vite emits only
* content-hashed files under dist/assets, so that path can be immutable;
* public/ files (icons, favicon) keep their names across builds and the HTML
* shell names the current bundle, so both must revalidate.
*/
const hooks = vi.hoisted(() => ({ studioDir: "" }));
@@ -26,9 +26,13 @@ vi.mock("node:path", async (importOriginal) => {
};
});
// A real filename from `bun run --filter @hyperframes/studio build`.
const HASHED_BUNDLE = "index-BRr1JoHX.js";
// Large enough to clear hono's 1KB compression threshold.
const BUNDLE_BYTES = `export const studio = ${JSON.stringify("x".repeat(4096))};\n`;
const BUNDLE_BYTES = "export const studio = 1;";
// Hand-authored, hyphenated, carrying capitals and digits — the shape no
// filename heuristic can separate from a rollup hash. It lives under /icons/,
// so the route answers correctly without having to.
const PUBLIC_ICON = "brand-Logo2026x.svg";
let root: string;
let server: StudioServer;
@@ -39,8 +43,10 @@ beforeEach(() => {
const projectDir = path.join(root, "project");
fs.mkdirSync(projectDir);
fs.mkdirSync(path.join(hooks.studioDir, "assets"), { recursive: true });
fs.mkdirSync(path.join(hooks.studioDir, "icons"), { recursive: true });
fs.writeFileSync(path.join(hooks.studioDir, "assets", HASHED_BUNDLE), BUNDLE_BYTES);
fs.writeFileSync(path.join(hooks.studioDir, "assets", "unhashed.js"), BUNDLE_BYTES);
fs.writeFileSync(path.join(hooks.studioDir, "icons", PUBLIC_ICON), "<svg/>");
fs.writeFileSync(path.join(hooks.studioDir, "favicon.svg"), "<svg/>");
fs.writeFileSync(
path.join(hooks.studioDir, "index.html"),
"<html><head></head><body>Studio</body></html>",
@@ -55,64 +61,41 @@ afterEach(() => {
});
describe("studio bundle cache policy", () => {
it("serves a content-hashed asset as immutable", async () => {
it("serves everything under /assets/ as immutable", async () => {
const response = await server.app.request(`/assets/${HASHED_BUNDLE}`);
expect(response.status).toBe(200);
expect(response.headers.get("Cache-Control")).toBe("public, max-age=31536000, immutable");
});
it("keeps an unhashed asset revalidating", async () => {
const response = await server.app.request("/assets/unhashed.js");
it("does not make a public/ icon immutable, however hash-like its name", async () => {
const response = await server.app.request(`/icons/${PUBLIC_ICON}`);
expect(response.status).toBe(200);
expect(response.headers.get("Cache-Control")).toBe("no-store");
});
it("keeps the HTML shell revalidating, since it names the hashed bundle", async () => {
it("keeps the favicon revalidating", async () => {
const response = await server.app.request("/favicon.svg");
expect(response.status).toBe(200);
expect(response.headers.get("Cache-Control")).toBe("no-store");
});
it("revalidates the HTML shell without evicting it from bfcache", async () => {
const response = await server.app.request("/");
expect(response.status).toBe(200);
expect(response.headers.get("Cache-Control")).toBe("no-store");
// `no-cache`, not `no-store`: same refetch, but `no-store` would blocklist
// the document from Chrome's bfcache and cold-boot Studio on Back.
expect(response.headers.get("Cache-Control")).toBe("no-cache");
});
// The first four are real filenames from `bun run --filter @hyperframes/studio build`.
it.each([
["index-BRr1JoHX.js", true],
["index-DnRfAiK2.css", true],
["hyperframes-player-lPOqAC3l.js", true],
["index-RPEcu_bT.js", true],
["unhashed.js", false],
["vite-manifest.json", false],
["favicon.svg", false],
// A hyphenated name is not a hash, however many capitals it carries: only
// the segment after the last hyphen is a hash candidate.
["user-Guide-v2.js", false],
["brand-Logo-Dark.svg", false],
])("classifies %s", (name, hashed) => {
expect(isContentHashedAsset(name)).toBe(hashed);
});
});
describe("studio bundle transfer encoding", () => {
it("compresses a bundle for a client that accepts gzip", async () => {
it("sends the bundle uncompressed, which loopback measures faster", async () => {
const response = await server.app.request(`/assets/${HASHED_BUNDLE}`, {
headers: { "Accept-Encoding": "gzip, deflate, br" },
});
expect(response.status).toBe(200);
expect(response.headers.get("Content-Encoding")).toBe("gzip");
// The middleware must not corrupt the payload it shrinks. `Response.text()`
// does not decode Content-Encoding, so unwrap it explicitly.
const body = response.body;
if (!body) throw new Error("compressed response had no body");
const decoded = await new Response(body.pipeThrough(new DecompressionStream("gzip"))).text();
expect(decoded).toBe(BUNDLE_BYTES);
});
it("sends the raw bytes to a client that accepts no encoding", async () => {
const response = await server.app.request(`/assets/${HASHED_BUNDLE}`);
expect(response.headers.get("Content-Encoding")).toBeNull();
expect(await response.text()).toBe(BUNDLE_BYTES);
});
+12 -34
View File
@@ -6,7 +6,6 @@
*/
import { Hono, type Context } from "hono";
import { compress } from "hono/compress";
import { streamSSE } from "hono/streaming";
import { existsSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
import { resolve, join, basename } from "node:path";
@@ -60,25 +59,11 @@ import {
const STUDIO_MANUAL_EDITS_PATH = ".hyperframes/studio-manual-edits.json";
// Vite emits built chunks and assets as `<name>-<hash>.<ext>` with rollup's
// 8-character base64url content hash (`index-BRr1JoHX.js`), so a hashed URL's
// bytes can never change and the browser may keep them forever. The HTML shell
// and public/ files keep their names across builds and must keep revalidating.
const HASH_SUFFIX_RE = /-([A-Za-z0-9_]{8,})\.[A-Za-z0-9]+$/;
// Vite emits only content-hashed files under dist/assets; hand-authored
// public/ files land at the dist root. The route is the signal because the
// filename is not: rollup's base64url hash may itself contain a hyphen.
const IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
/**
* Only the segment after the LAST hyphen counts, and it must carry a digit,
* underscore or capital. That is what separates a real hash from an ordinary
* hyphenated word of the same length (`vite-manifest.json`, `user-Guide-v2.js`),
* and it errs the safe way: an all-lower-case hash would simply keep
* revalidating, which is the behaviour before this change.
*/
export function isContentHashedAsset(filePath: string): boolean {
const suffix = HASH_SUFFIX_RE.exec(basename(filePath))?.[1];
return suffix !== undefined && /[A-Z0-9_]/.test(suffix);
}
const REMOTE_GIF_IMG_SRC_RE =
/<img\b[^>]*?\bsrc\s*=\s*["'](https?:\/\/[^"']+\.gif(?:[?#][^"']*)?)["'][^>]*>/gi;
@@ -895,25 +880,17 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
});
// Studio SPA static files
const serveStudioStaticFile = (c: Context) => {
const serveStudioStaticFile = (cacheControl: string) => (c: Context) => {
const filePath = resolve(studioDir, c.req.path.slice(1));
const content = readBundleFile(filePath);
if (content === null) return c.text("not found", 404);
return new Response(content, {
headers: {
"Content-Type": getMimeType(filePath),
"Cache-Control": isContentHashedAsset(filePath) ? IMMUTABLE_CACHE_CONTROL : "no-store",
},
headers: { "Content-Type": getMimeType(filePath), "Cache-Control": cacheControl },
});
};
// Runtime gzip: the studio bundle is several megabytes of JavaScript and was
// being shipped raw on every cold open. Hono's middleware already skips
// already-compressed content types and anything under its size threshold, so
// only /assets/* needs it — public/ holds icons and the favicon.
app.use("/assets/*", compress());
app.get("/assets/*", serveStudioStaticFile);
app.get("/icons/*", serveStudioStaticFile);
app.get("/favicon.svg", serveStudioStaticFile);
app.get("/assets/*", serveStudioStaticFile(IMMUTABLE_CACHE_CONTROL));
app.get("/icons/*", serveStudioStaticFile("no-store"));
app.get("/favicon.svg", serveStudioStaticFile("no-store"));
// ── Runtime env injection ───────────────────────────────────────────────
// When the studio is served as a pre-built SPA, Vite `VITE_STUDIO_*` env
@@ -1009,9 +986,10 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
if (headScript) {
html = html.replace("<head>", `<head>${headScript}`);
}
// The shell must never be cached: it is the only thing that names the
// current hashed bundle, and those are now served as immutable.
return c.html(html, 200, { "Cache-Control": "no-store" });
// The shell names the current hashed bundle, so it always revalidates.
// `no-cache` not `no-store`: same refetch without an ETag, but `no-store`
// would blocklist the document from Chrome's bfcache.
return c.html(html, 200, { "Cache-Control": "no-cache" });
});
return { app, watcher, adapter };