#!/usr/bin/env node /** * Bundle size checker — validates vite build output against .bundlesize.json baseline. * * Usage: * node scripts/check-bundle-size.mjs # check against baseline (requires prior vite build) * node scripts/check-bundle-size.mjs --update-baseline # rebuild baseline from current dist/ * * Methodology: * 1. Reads all .js/.css files from dist/assets/ * 2. Strips Vite content-hash suffix to recover logical chunk names * 3. Groups files sharing the same logical name (e.g. two "Dashboard" chunks) * 4. Computes gzip size for each file using Node zlib (level 6, default) * 5. Compares per-chunk and total gzip sizes against .bundlesize.json thresholds * 6. Asserts the built index.html preload posture: modulepreload links are * limited to the entry's static imports (no lazy route chunks), and the * import map integrity block covers every built JS asset * 7. Exits 0 on pass, 1 on any violation */ import { readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { gzipSync } from 'node:zlib'; import { fileURLToPath } from 'node:url'; const __dirname = fileURLToPath(new URL('.', import.meta.url)); const ROOT = resolve(__dirname, '..'); const DIST_ASSETS = join(ROOT, 'dist', 'assets'); const BASELINE_PATH = join(ROOT, '.bundlesize.json'); // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- /** Strip Vite/Rollup 8-char base64url content hash from filename. */ function logicalName(filename) { // Vite appends -<8 char hash>.; hash chars are [A-Za-z0-9_-] const m = filename.match(/^(.+)-[A-Za-z0-9_-]{8}\.(js|css)$/); if (m) return { name: m[1], ext: m[2] }; // Fallback: return filename without extension const dot = filename.lastIndexOf('.'); return { name: filename.slice(0, dot), ext: filename.slice(dot + 1) }; } function gzipSize(buf) { return gzipSync(buf, { level: 6 }).length; } function fmtKB(bytes) { return (bytes / 1024).toFixed(2) + ' kB'; } // --------------------------------------------------------------------------- // Measure current build // --------------------------------------------------------------------------- function measureBuild() { let files; try { files = readdirSync(DIST_ASSETS); } catch { console.error( 'Error: dist/assets/ not found. Run "npx vite build" first.', ); process.exit(1); } /** @type {Map} */ const groups = new Map(); let totalJsGzip = 0; let totalCssGzip = 0; for (const file of files) { if (!file.endsWith('.js') && !file.endsWith('.css')) continue; const fullPath = join(DIST_ASSETS, file); const buf = readFileSync(fullPath); const gz = gzipSize(buf); const raw = buf.length; const { name, ext } = logicalName(file); // Use name.ext as group key to avoid mixing JS and CSS with same name const groupKey = `${name}.${ext}`; const existing = groups.get(groupKey) || { gzip: 0, raw: 0, ext, name }; existing.gzip += gz; existing.raw += raw; groups.set(groupKey, existing); if (ext === 'js') totalJsGzip += gz; else if (ext === 'css') totalCssGzip += gz; } return { groups, totalJsGzip, totalCssGzip }; } // --------------------------------------------------------------------------- // Built index.html preload posture // --------------------------------------------------------------------------- /** * Verify the deployment-installability preload invariant against the built * index.html (see the subsystem contract clause on modulepreload posture): * - the import map integrity block exists and covers every JS asset in * dist/assets, so dynamic-import SRI stays enforced without preloading; * - modulepreload links reference only the entry chunk's static imports — * preloading lazy route chunks (preloadDynamicChunks: true) would fetch * the whole app at cold start and defeat route-level code splitting. * Returns a list of violation messages (empty on pass). */ function checkPreloadPosture() { const errors = []; let html; try { html = readFileSync(join(ROOT, 'dist', 'index.html'), 'utf8'); } catch { errors.push('dist/index.html not found. Run "npx vite build" first.'); return errors; } const importmapMatch = html.match(/