Files
romm/frontend/scripts/precompress.ts
Sam Dornan 64740468ec fix(frontend): address the review findings on the precompress plugin
The summary divided by zero and printed "NaN% smaller" when nothing
cleared the extension and size filters.

The comment on the extension list said it tracks gzip_types, which was
wrong twice over: .svg, .wasm, .webmanifest and .map are absent from that
directive, and gzip_static serves a .gz sibling without consulting it at
all. Someone editing either list on the strength of that comment would
have changed behaviour silently.

Storybook builds ran the plugin too, gzipping storybook-static that nginx
never serves. It is stripped alongside vite-plugin-pwa, which .storybook
already does for the same reason.

The Python test could only grep vite.config.js for the call, so a gutted
closeBundle or apply: "serve" left it green. A vitest suite now runs the
hooks against a temporary directory and checks the archive round-trips,
that small and already-compressed files are skipped, and that a rerun does
not compress its own output.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HDXxq3vAxJVGhm1pQuK8V7
2026-09-12 02:09:24 +00:00

88 lines
2.6 KiB
TypeScript

/**
* precompress — a build plugin that writes a .gz sibling for each built asset.
*
* nginx serves these directly via `gzip_static`, so the bundle is compressed
* once at build time rather than on every cold page load.
*
* Level 9 is affordable because it runs once. The ratio lands within a percent
* of what nginx produces at runtime, so the win is the CPU, not the bytes.
* Files without a .gz sibling still fall back to on-the-fly gzip.
*/
import { readdir, readFile, stat, writeFile } from "node:fs/promises";
import { extname, join, resolve } from "node:path";
import { constants, gzipSync } from "node:zlib";
import type { Plugin } from "vite";
// gzip_static serves a .gz sibling whatever gzip_types says, so this list alone
// decides what is precompressed. Already-compressed formats only grow.
const COMPRESSIBLE = new Set([
".css",
".html",
".js",
".json",
".map",
".mjs",
".svg",
".txt",
".wasm",
".webmanifest",
".xml",
]);
// nginx's gzip_min_length: below this the encoding overhead outweighs the win.
const MIN_BYTES = 1024;
async function* walk(dir: string): AsyncGenerator<string> {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const path = join(dir, entry.name);
if (entry.isDirectory()) yield* walk(path);
else if (entry.isFile()) yield path;
}
}
export function precompress(): Plugin {
let outDir = "";
return {
name: "romm:precompress",
apply: "build",
// `post` so the service worker vite-plugin-pwa emits is compressed too.
enforce: "post",
configResolved(config) {
outDir = resolve(config.root, config.build.outDir);
},
async closeBundle() {
let raw = 0;
let packed = 0;
let count = 0;
for await (const path of walk(outDir)) {
if (!COMPRESSIBLE.has(extname(path))) continue;
const { size } = await stat(path);
if (size < MIN_BYTES) continue;
const gzipped = gzipSync(await readFile(path), {
level: constants.Z_BEST_COMPRESSION,
});
// A .gz larger than its source would make nginx serve the worse one.
if (gzipped.byteLength >= size) continue;
await writeFile(`${path}.gz`, gzipped);
raw += size;
packed += gzipped.byteLength;
count += 1;
}
const mib = (bytes: number) => (bytes / 1024 ** 2).toFixed(1);
this.info(
count === 0
? "nothing to compress"
: `${count} files, ${mib(raw)} MiB -> ${mib(packed)} MiB ` +
`(${Math.round((1 - packed / raw) * 100)}% smaller)`,
);
},
};
}