282 lines
17 KiB
JavaScript
282 lines
17 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 产物预算闸(阶段 16 · 任务 3):给构建产物一条**会响**的体积上限。
|
||
*
|
||
* 症状:`vite.config.ts` 的 `chunkSizeWarningLimit: 1200` 从阶段 8.5 起常驻一条
|
||
* `(!) Some chunks are larger than 1200 kB after minification`——它只是构建器
|
||
* 打印的一行字,**退出码永远是 0**。于是两件事被悄悄做掉了:谁把首屏 chunk 从
|
||
* 1 246 kB 抬到 1 280 kB、1 300 kB,构建照样绿;而那条警告因为「一直在那儿」
|
||
* 被当成噪音划走。阶段 9/14/15 的结论是「不改分包」——**不改更需要一把尺子**:
|
||
* 不改 = 现状是基线,任何往上的漂移必须有人拦,不能靠谁偶然瞄一眼构建日志。
|
||
*
|
||
* 做法:上限按三层来源取,**先登记的、后兜底**,命中哪一层就打印哪一层的文件与字节:
|
||
* A) 显式 `--config <file>`:只认这一份(判据 ㉒ 的反向验证靠它喂夹具,
|
||
* 显式指定的来源不许被项目默认值污染,所以它没 budget 就是 DEGRADED,不往下兜)。
|
||
* B) 构建器落盘配置 `output.budget`(`<dist>/.vite/rollup.config.json`)。
|
||
* 本项目长期走不到这一层:vite 8.3.4 + rolldown 1.2.13 既不落那份配置
|
||
* (实测 `dist/` 只有 assets/help/index.html),`OutputOptions` 里也没有
|
||
* `budget` 字段(grep 过 rolldown 的 d.mts)。
|
||
* C) 项目自己登记的预算文件 `frontend/chunk-budget.json`(阶段 24 补的来源,
|
||
* `--budget-file` 可显式指定)。B 读不出上限时才读它;它坏了 / 没 budget 键 /
|
||
* 原值读不出正数 ⇒ **点名响**,不冒充「没有预算」也不悄悄兜底。
|
||
* 三层都没有时**退化到 1 500 kB 并显式打印 `DEGRADED`**。
|
||
* 退化必须看得见,不许把兜底数字伪装成「配置里写的」;退化也不许放宽判定。
|
||
* 然后逐个量 `dist` 里的 `.js`/`.css`,超限就点名 + 退出码非零。
|
||
*
|
||
* 为什么不「把 chunkSizeWarningLimit 调到 1300 让警告消失」:那是**加阈值**,本次禁止
|
||
* (阶段 8.5 §6.3:抬阈值捂警告仍然禁止)。这把闸的语义是「产物不得越过预算」,
|
||
* 与那条 >1 200 kB 的**警告**互不干涉:警告继续如实报,闸门在真越界时才阻断。
|
||
* 兜底 1 500 kB = 阶段 15 基线(`chunk-after.txt`:`ui-*.js` 1 275.93 kB)之上
|
||
* 留 17.5 % 余量——够一次正常的功能增量,不够一次无声的重依赖引入。
|
||
*
|
||
* 大小口径:raw(磁盘字节),**kB = 1000 B(十进制)**——与 vite 控制台同一把尺。
|
||
* 这是实测钉的,不是猜的:`ui-DsRXK1XH.js` 落盘 1 275 933 B,vite 打印 `1,275.93 kB`,
|
||
* `chunkSizeWarningLimit` 按同一把尺比较,阶段 15 基线(首屏 1 559.97 / 全部 1 963.80)
|
||
* 也是十进制——本脚本对同一份产物报「合计 1 963.80 kB」,与 `chunk-after.txt` 逐位吻合。
|
||
* ⚠ 仓库里另有两把尺:`chunkinfo.mjs` 用 n/1024 却标 kB(同一个文件它报 1 246.03),
|
||
* 与这里差 2.4 %;跨脚本比大小先认尺子(已登记阶段 16 报告 §7,本轮不动它)。
|
||
* gzip/brotli 只进明细不参与判定:传输看压缩、parse 看 raw,判定挑最严的那一个。
|
||
*
|
||
* 四条「不许沉默」的守卫:
|
||
* 1) `dist` 不存在 / 没有 assets / 一个 .js|.css 都没有 → 红(没构建等于没量);
|
||
* 2) 配置文件 / 预算文件存在但不是合法 JSON → 红(配置坏了不能当成「没有 budget」混成 DEGRADED);
|
||
* 显式 `--config` / `--budget-file` 指不到文件 → 红(夹具前提变了就是错);
|
||
* 预算文件在却没有 budget 键 / 原值读不出正数 → 红(文件在而读不出上限,等于没有预算);
|
||
* 3) 读到了 budget → 打印来源文件 + 原始字节 + 换算后的 kB,数字可回溯;
|
||
* 4) 没读到 → 打印 `DEGRADED` + 原因,并按兜底值照判(退化≠放宽)。
|
||
*
|
||
* budget 支持的形状(构建器今天不产这份配置,所以形状按「能宽就宽、但不猜单位」处理,
|
||
* 每一条都原样打印以便人工复核;单位一律**字节**,与 rollup/rolldown 的尺寸类选项一致):
|
||
* · `output.budget = 1500000` → 全量上限
|
||
* · `output.budget = { maximumSize: 1500000 }`(或 maxSize/limit/max)→ 同上
|
||
* · `output.budget = [ {maximumSize, name?, type?}, … ]` → 逐条作用域:
|
||
* `type:'chunk'` 只管 `.js`,`type:'asset'` 只管非 `.js`(css 等),不写 = 都管;
|
||
* `name` 是 glob(`assets/ui-*.js`),不写 = 全部文件;
|
||
* 一个文件命中多条时取**最具体**的那条(name > type > 全局),同层取更小的上限;
|
||
* · `outputs[].output.budget` 也读(多 output 配置)。
|
||
* 一条都读不出来 → 与「没有该键」同样处理:DEGRADED + 兜底。
|
||
*
|
||
* 用法:
|
||
* node scripts/ui/chunkbudget.mjs # 默认 frontend/dist + frontend/chunk-budget.json
|
||
* node scripts/ui/chunkbudget.mjs --dist DIR # 指定产物目录
|
||
* node scripts/ui/chunkbudget.mjs --budget-file F.json # 指定项目预算文件(阶段 24 的来源 C)
|
||
* node scripts/ui/chunkbudget.mjs --dist D --config C.json # 反向验证:喂一份带 budget 的配置
|
||
* node scripts/ui/chunkbudget.mjs --json # 机读(gateprobe 用)
|
||
* 退出码:0 全部在预算内;1 有越界 / 产物或配置不可信。
|
||
*/
|
||
import fs from 'node:fs'
|
||
import path from 'node:path'
|
||
import zlib from 'node:zlib'
|
||
import { fileURLToPath } from 'node:url'
|
||
|
||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||
const FALLBACK_KB = 1500 // 没读到 budget 时的兜底上限(依据见文件头「为什么不抬阈值」)
|
||
const CONFIG_REL = path.join('.vite', 'rollup.config.json') // 构建器落盘配置相对 dist 的位置
|
||
const VITE_WARN_KB = 1200 // 只用来标注「vite 已警告」,判定不看它(调大数字 ≠ 整改)
|
||
const kb = (n) => n / 1000 // 十进制:与 vite 控制台 / chunkSizeWarningLimit / 阶段 15 基线同尺
|
||
const fmt = (n) => kb(n).toFixed(2).padStart(9)
|
||
|
||
/* ---------- 参数 ---------- */
|
||
const argv = process.argv.slice(2)
|
||
const arg = (name, dflt) => {
|
||
const i = argv.indexOf('--' + name)
|
||
return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : dflt
|
||
}
|
||
const JSON_OUT = argv.includes('--json')
|
||
const DIST = path.resolve(arg('dist', path.join(HERE, '../../frontend/dist')))
|
||
const CONFIG_GIVEN = arg('config', null)
|
||
// 项目自己登记的预算文件(阶段 24):构建器不落盘 rollup.config.json,唯一来源等于长期 DEGRADED。
|
||
const BUDGET_FILE_GIVEN = arg('budget-file', null)
|
||
const BUDGET_FILE = path.resolve(BUDGET_FILE_GIVEN ?? path.join(HERE, '../../frontend/chunk-budget.json'))
|
||
|
||
const fails = []
|
||
const die = (msg) => fails.push(msg)
|
||
|
||
/* ---------- 1. 上限从哪来 ---------- */
|
||
const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null)
|
||
function readEntries(budget) {
|
||
const list = Array.isArray(budget) ? budget : [budget]
|
||
const out = []
|
||
for (const item of list) {
|
||
const max = num(item) ?? (item && typeof item === 'object'
|
||
? (num(item.maximumSize) ?? num(item.maxSize) ?? num(item.limit) ?? num(item.max)) : null)
|
||
if (max == null) continue
|
||
const name = item && typeof item === 'object' ? (item.name || item.pattern || null) : null
|
||
const type = item && typeof item === 'object' ? (item.type || null) : null
|
||
if (type && !['chunk', 'asset'].includes(type)) { // 认不出的作用域不猜,直接响
|
||
die(`BUDGET-TYPE budget.type=${JSON.stringify(type)} 不在册(只认 chunk / asset) → 猜错作用域等于把上限悄悄放宽`)
|
||
continue
|
||
}
|
||
out.push({ max, name, type })
|
||
}
|
||
return out
|
||
}
|
||
|
||
/* 来源字符串:文件 + 原值字节 + 换算 kB + 作用域,数字可回溯(守卫 3) */
|
||
const entriesText = (src, es) => `${src} = ${es.map((e) => `${e.max} B=${kb(e.max).toFixed(2)} kB${e.name || e.type ? `(${[e.type, e.name].filter(Boolean).join(' ')}→${e.name || '全部'})` : ''}`).join(' · ')}`
|
||
|
||
/* 从一份 JSON 文档里抓 budget 原值(顶层 output.budget / budget / outputs[].output.budget) */
|
||
function grabRaws(doc) {
|
||
const raws = []
|
||
const grab = (o) => {
|
||
if (!o || typeof o !== 'object') return
|
||
if (o.output && o.output.budget !== undefined) raws.push(o.output.budget)
|
||
else if (o.budget !== undefined) raws.push(o.budget)
|
||
}
|
||
grab(doc)
|
||
if (Array.isArray(doc.outputs)) for (const o of doc.outputs) grab(o)
|
||
return raws
|
||
}
|
||
|
||
const configPath = CONFIG_GIVEN ? path.resolve(CONFIG_GIVEN) : path.join(DIST, CONFIG_REL)
|
||
let configUntrusted = false // CONFIG-BAD / CONFIG-MISSING:这种情况**不许**冒充 DEGRADED
|
||
const configFound = fs.existsSync(configPath)
|
||
let entries = []
|
||
let budgetSource = null
|
||
let degraded = null
|
||
let configRaw = null
|
||
|
||
if (CONFIG_GIVEN && !configFound) {
|
||
die(`CONFIG-MISSING 指定的配置不存在:${configPath} → 反向验证的夹具前提变了,不许退化成兜底继续跑`)
|
||
degraded = '指定的配置文件不存在'; configUntrusted = true
|
||
} else if (configFound) {
|
||
try {
|
||
configRaw = JSON.parse(fs.readFileSync(configPath, 'utf8'))
|
||
} catch (e) {
|
||
die(`CONFIG-BAD 配置不是合法 JSON:${configPath} —— ${e.message} → 配置坏了必须响,不许混成 DEGRADED 用兜底蒙过去`)
|
||
degraded = '配置解析失败(见 CONFIG-BAD)'; configUntrusted = true
|
||
}
|
||
if (configRaw) {
|
||
const raws = grabRaws(configRaw)
|
||
if (!raws.length) {
|
||
degraded = `配置里没有 output.budget(${configPath})`
|
||
} else {
|
||
entries = raws.flatMap(readEntries)
|
||
if (!entries.length) degraded = `output.budget 读不出可用上限(原值 ${JSON.stringify(raws[0]).slice(0, 120)})`
|
||
else budgetSource = entriesText(configPath + ' · output.budget', entries)
|
||
}
|
||
}
|
||
} else {
|
||
degraded = `构建器未落盘配置(找不到 ${path.join(DIST, CONFIG_REL)})`
|
||
}
|
||
/* 来源 C(阶段 24):项目自己登记的预算文件。
|
||
* 什么时候才读它:没显式 --config(显式 = 反向验证夹具,不许被默认值污染)、
|
||
* 且构建器那一份没给出上限(不落盘 / 没 budget 键)。
|
||
* 三条红线照旧:读到了就打印来源与字节;坏了就响,不冒充「没有预算」;
|
||
* 缺文件在没显式指定时才算「没有这一层」,显式 --budget-file 指不到就是错。 */
|
||
let budgetFileUsed = null
|
||
if (!CONFIG_GIVEN && !entries.length) {
|
||
if (!fs.existsSync(BUDGET_FILE)) {
|
||
if (BUDGET_FILE_GIVEN) {
|
||
die(`BUDGET-FILE-MISSING 指定的预算文件不存在:${BUDGET_FILE} → 显式指定的来源找不到就是错,不许退到兜底继续跑`)
|
||
degraded = '指定的预算文件不存在'; configUntrusted = true
|
||
} else {
|
||
degraded = (degraded ? degraded + ';' : '') + `项目预算文件也不存在(${BUDGET_FILE})`
|
||
}
|
||
} else {
|
||
let doc = null
|
||
try {
|
||
doc = JSON.parse(fs.readFileSync(BUDGET_FILE, 'utf8'))
|
||
} catch (e) {
|
||
die(`BUDGET-FILE-BAD 预算文件不是合法 JSON:${BUDGET_FILE} —— ${e.message} → 配置坏了必须响,不许混成 DEGRADED 用兜底蒙过去`)
|
||
degraded = '预算文件解析失败(见 BUDGET-FILE-BAD)'; configUntrusted = true
|
||
}
|
||
if (doc !== null) {
|
||
const raws = grabRaws(doc)
|
||
if (!raws.length) {
|
||
die(`BUDGET-FILE-EMPTY ${BUDGET_FILE} 里没有 budget / output.budget 键 → 文件在却读不出上限,等于没有预算,不许静默兜底`)
|
||
degraded = '预算文件里没有 budget 键(见 BUDGET-FILE-EMPTY)'; configUntrusted = true
|
||
} else {
|
||
const es = raws.flatMap(readEntries)
|
||
if (!es.length) {
|
||
die(`BUDGET-FILE-SHAPE budget 原值 ${JSON.stringify(raws[0]).slice(0, 120)} 读不出正数上限 → 猜单位等于把上限悄悄放宽`)
|
||
degraded = 'budget 原值读不出可用上限(见 BUDGET-FILE-SHAPE)'; configUntrusted = true
|
||
} else {
|
||
entries = es // 上限真正生效的一条:只记来源不装 entries = 空转
|
||
budgetFileUsed = BUDGET_FILE
|
||
budgetSource = entriesText(BUDGET_FILE + ' · budget', es)
|
||
degraded = null
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
const fallbackKB = FALLBACK_KB
|
||
if (degraded) entries = []
|
||
|
||
/* 一个文件适用哪条上限:name 命中 > type 命中 > 全局;同层取更小的;都没有 → 兜底 */
|
||
const glob = (p) => new RegExp('^' + p.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$')
|
||
function limitFor(rel) {
|
||
const isJs = rel.endsWith('.js')
|
||
let best = null
|
||
for (const e of entries) {
|
||
if (e.type === 'chunk' && !isJs) continue
|
||
if (e.type === 'asset' && isJs) continue
|
||
if (e.name && !glob(e.name).test(rel) && !glob(e.name).test(path.basename(rel))) continue
|
||
const spec = (e.name ? 2 : 0) + (e.type ? 1 : 0)
|
||
if (!best || spec > best.spec || (spec === best.spec && e.max < best.max)) best = { max: e.max, spec }
|
||
}
|
||
return best ? best.max : (degraded ? fallbackKB * 1000 : entries.length ? Math.min(...entries.map((e) => e.max)) : fallbackKB * 1000)
|
||
}
|
||
|
||
/* ---------- 2. 逐个量产物 ---------- */
|
||
const ASSETS = path.join(DIST, 'assets')
|
||
let files = []
|
||
if (!fs.existsSync(DIST)) {
|
||
die(`NO-DIST 产物目录不存在:${DIST} → 先 cd frontend && npm run build,没构建等于没量,不能算通过`)
|
||
} else if (!fs.existsSync(ASSETS)) {
|
||
die(`NO-ASSETS 产物里没有 assets:${ASSETS} → 空产物不能算通过`)
|
||
} else {
|
||
const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => {
|
||
const p = path.join(d, e.name)
|
||
if (e.isDirectory()) return e.name === '.vite' ? [] : walk(p)
|
||
return /\.(js|css)$/.test(e.name) && !e.name.endsWith('.map') ? [p] : []
|
||
})
|
||
files = walk(DIST)
|
||
if (!files.length) die(`EMPTY 产物里没有任何 .js/.css:${DIST} → 空产物不能算通过`)
|
||
}
|
||
|
||
const rows = files.map((f) => {
|
||
const buf = fs.readFileSync(f)
|
||
const rel = path.relative(DIST, f)
|
||
const limit = limitFor(rel)
|
||
return { rel, raw: buf.length, gzip: zlib.gzipSync(buf, { level: 9 }).length,
|
||
brotli: zlib.brotliCompressSync(buf).length, limit, over: buf.length > limit }
|
||
}).sort((a, b) => b.raw - a.raw)
|
||
|
||
for (const r of rows) {
|
||
if (r.over) die(`OVER ${r.rel} raw ${kb(r.raw).toFixed(2)} kB > 预算 ${kb(r.limit).toFixed(2)} kB(超 ${kb(r.raw - r.limit).toFixed(2)} kB · gzip ${kb(r.gzip).toFixed(2)} kB)`)
|
||
}
|
||
|
||
/* ---------- 3. 输出 ---------- */
|
||
const verdict = fails.length ? 'FAIL' : 'OK'
|
||
const total = rows.reduce((a, r) => a + r.raw, 0)
|
||
const totalBytes = rows.reduce((a, r) => a + r.raw, 0)
|
||
const degradedText = configUntrusted
|
||
? `不可信 —— 配置/预算文件读坏了(见 CONFIG-BAD / CONFIG-MISSING / BUDGET-FILE-*),不冒充 DEGRADED 也不假装按兜底量过`
|
||
: (degraded ? `DEGRADED —— ${degraded};退化到兜底 ${fallbackKB} kB(兜底≠放宽,判定照旧)` : null)
|
||
if (JSON_OUT) {
|
||
console.log(JSON.stringify({
|
||
verdict, dist: DIST, configPath, configFound, budgetSource,
|
||
degraded: !!degraded && !configUntrusted, configUntrusted, degradedReason: degraded, fallbackKB,
|
||
files: rows.map((r) => ({ rel: r.rel, rawKB: +kb(r.raw).toFixed(2), gzipKB: +kb(r.gzip).toFixed(2),
|
||
brotliKB: +kb(r.brotli).toFixed(2), limitKB: +kb(r.limit).toFixed(2), over: r.over })),
|
||
totalKB: +kb(totalBytes).toFixed(2), fails,
|
||
}))
|
||
} else {
|
||
console.log(`CHUNKBUDGET ${verdict}`)
|
||
console.log(` 产物目录 : ${DIST}`)
|
||
console.log(` 预算来源 : ${budgetSource || degradedText}`)
|
||
console.log(` 判定口径 : raw(磁盘字节)· kB = 1000 B(与 vite 控制台 / chunkSizeWarningLimit / 阶段 15 基线同尺)`)
|
||
console.log(` 产物 : ${rows.length} 个 .js/.css · 合计 raw ${fmt(totalBytes)} kB` + (degraded ? `(逐文件预算 ${fallbackKB} kB = 兜底,非登记值)` : budgetFileUsed ? '(逐文件预算见来源行)' : ''))
|
||
const widest = Math.max(...rows.map((r) => r.rel.length), 4)
|
||
console.log(' ' + '文件'.padEnd(widest + 3) + ' raw gzip brotli 预算 判定')
|
||
for (const r of rows) {
|
||
console.log(' ' + r.rel.padEnd(widest + 3) + fmt(r.raw) + fmt(r.gzip) + fmt(r.brotli) + fmt(r.limit)
|
||
+ (r.over ? ' OVER' : (kb(r.raw) > VITE_WARN_KB ? ' 慢(vite 已在警告,不参与判定)' : ' ok')))
|
||
}
|
||
for (const l of fails) console.log(' ' + l)
|
||
if (fails.length) console.log(' → 先查是不是新依赖进了首屏(node scripts/ui/chunkinfo.mjs 看成分),不许调大数字把它捂住')
|
||
}
|
||
process.exit(fails.length ? 1 : 0)
|