// Writes .br and .gz beside every compressible file in dist/, so server.mjs // sends the 15 MB binary and 11 MB kernel at a fraction of their size // without compressing on every request. import { readdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { brotliCompressSync, constants, gzipSync } from "node:zlib"; const dist = fileURLToPath(new URL("../dist/", import.meta.url)); const COMPRESSIBLE = /\.(html|js|css|svg|wasm|json|txt|sh|bin)$/; for (const entry of await readdir(dist, { recursive: true, withFileTypes: true })) { if (!entry.isFile() || !COMPRESSIBLE.test(entry.name)) continue; const path = join(entry.parentPath, entry.name); const bytes = await readFile(path); if (bytes.byteLength < 1024) continue; const br = brotliCompressSync(bytes, { params: { [constants.BROTLI_PARAM_QUALITY]: 11, [constants.BROTLI_PARAM_SIZE_HINT]: bytes.byteLength, [constants.BROTLI_PARAM_LGWIN]: 24, }, }); const gz = gzipSync(bytes, { level: 9 }); await writeFile(`${path}.br`, br); await writeFile(`${path}.gz`, gz); console.log( `${path.slice(dist.length)}: ${(bytes.byteLength / 1e6).toFixed(1)} MB → br ${(br.byteLength / 1e6).toFixed(1)} MB, gz ${(gz.byteLength / 1e6).toFixed(1)} MB`, ); }