#!/usr/bin/env node // PEP-217: weight of the client JS of every route after `next build` (apps/web/.next). // First load of a route = the chunks the route's page needs on the first visit (layout + page // entries from its client-reference manifest, plus Next's root main files), gzip bytes. // Lazy chunks (next/dynamic, import()) are not part of it — that is the point. // node scripts/bundle-check.mjs compare with docs/bundle-baseline.json, exit 1 if a route grew > 10 % // node scripts/bundle-check.mjs --update write the baseline (on purpose, in the PR that explains the growth) // node scripts/bundle-check.mjs --report print the table only import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { dirname, join, relative } from "node:path"; import { fileURLToPath } from "node:url"; import { gzipSync } from "node:zlib"; const root = join(dirname(fileURLToPath(import.meta.url)), ".."); const web = join(root, "apps/web"); const next = join(web, ".next"); const baselinePath = join(root, "docs/bundle-baseline.json"); export const LIMIT = 0.1; const gz = new Map(); function size(file) { if (!gz.has(file)) gz.set(file, gzipSync(readFileSync(join(next, file))).length); return gz.get(file); } function manifests(dir, out = []) { for (const n of readdirSync(dir)) { const p = join(dir, n); if (statSync(p).isDirectory()) manifests(p, out); else if (n === "page_client-reference-manifest.js") out.push(p); } return out; } /** { route: gzip bytes of the first-load JS }. */ export function measure() { if (!existsSync(join(next, "server/app"))) throw new Error("apps/web/.next не найден — сначала pnpm build"); const build = JSON.parse(readFileSync(join(next, "build-manifest.json"), "utf8")); const common = [...(build.rootMainFiles ?? []), ...(build.polyfillFiles ?? [])].filter((f) => f.endsWith(".js")); const out = {}; for (const m of manifests(join(next, "server/app"))) { const src = readFileSync(m, "utf8"); const entry = /\["([^"]+)"\]\s*=\s*(\{.*\});?\s*$/s.exec(src); if (!entry) continue; const data = JSON.parse(entry[2]); const files = data.entryJSFiles ?? {}; const pageKey = Object.keys(files).find((k) => /\/page$/.test(k)) ?? Object.keys(files).at(-1); if (!pageKey) continue; const route = "/" + relative(join(next, "server/app"), dirname(m)).split("/").filter((s) => !/^\(.*\)$/.test(s)).join("/"); const list = new Set([...common, ...files[pageKey]].filter((f) => f.endsWith(".js"))); out[route === "/" ? "/" : route.replace(/\/$/, "")] = [...list].reduce((a, f) => a + size(f), 0); } return Object.fromEntries(Object.entries(out).sort(([a], [b]) => a.localeCompare(b))); } /** Routes that grew more than `limit` against the baseline; new routes are listed apart. */ export function compare(now, base, limit = LIMIT) { const grew = []; const added = []; for (const [route, bytes] of Object.entries(now)) { const was = base[route]; if (was == null) added.push(route); else if (bytes > was * (1 + limit)) grew.push({ route, was, now: bytes, pct: ((bytes / was - 1) * 100) }); } return { grew, added }; } const kb = (n) => `${(n / 1024).toFixed(1)} КБ`; if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) { const now = measure(); const mode = process.argv[2]; if (mode === "--update") { writeFileSync(baselinePath, JSON.stringify(now, null, 2) + "\n"); console.log(`bundle: эталон записан — маршрутов ${Object.keys(now).length}, docs/bundle-baseline.json`); process.exit(0); } const base = existsSync(baselinePath) ? JSON.parse(readFileSync(baselinePath, "utf8")) : {}; for (const [r, b] of Object.entries(now)) console.log(`${r.padEnd(40)} ${kb(b).padStart(10)}${base[r] ? ` (эталон ${kb(base[r])})` : ""}`); if (mode === "--report") process.exit(0); const { grew, added } = compare(now, base); if (added.length) console.log(`bundle: новые маршруты без эталона: ${added.join(", ")} — обновите эталон: node scripts/bundle-check.mjs --update`); if (grew.length) { for (const g of grew) console.error(`bundle: ${g.route} вырос на ${g.pct.toFixed(1)}% (${kb(g.was)} → ${kb(g.now)}), предел ${LIMIT * 100}%`); console.error("bundle: вынесите тяжёлое в dynamic import или, если рост нужен, обновите эталон: node scripts/bundle-check.mjs --update"); process.exit(1); } console.log("bundle: вес JS первой загрузки в пределах эталона"); }