Files
monkey-ai-web/scripts/verify-build.mjs
T
zhanjunhao b3f4711d20 perf(build): 优化开发预热与首屏分包懒加载
减少应用启动时的静态依赖,增加首屏体积预算与懒加载边界校验。验证通过:875 项单测、UI 依赖审计、ESLint、Prettier、生产构建与首屏产物校验;Chrome 模拟回归通过。
2026-11-20 15:03:30 +08:00

112 lines
3.7 KiB
JavaScript

import { readFile, access } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { gzipSync } from 'node:zlib';
const BOOTSTRAP_GZIP_LIMIT = 820 * 1024;
const NOTICE = 'src/components/layout/NoticeModal.jsx';
const AGREEMENT = 'src/components/common/DocumentRenderer/AgreementModal.jsx';
const HEADER = 'src/components/layout/headerbar/index.jsx';
const HOME = 'src/pages/Home/index.jsx';
const MARKED = 'node_modules/marked/lib/marked.esm.js';
function resolveAsset(root, asset) {
const filename = path.resolve(root, asset.replace(/^\//, ''));
if (!filename.startsWith(root + path.sep))
throw new Error(`Build asset escapes output directory: ${asset}`);
return filename;
}
function staticChunks(manifest, roots) {
const seen = new Set();
const visit = (key) => {
if (seen.has(key)) return;
const chunk = manifest[key];
if (!chunk) throw new Error(`Missing build manifest chunk: ${key}`);
seen.add(key);
for (const dependency of chunk.imports || []) visit(dependency);
};
roots.forEach(visit);
return seen;
}
async function verifyStartup(root) {
const manifest = JSON.parse(
await readFile(path.join(root, '.vite', 'manifest.json'), 'utf8'),
);
const entry = 'index.html';
for (const [routes, deferred] of [
[
[entry, HOME, HEADER],
[NOTICE, MARKED],
],
[
[entry, 'src/components/auth/LoginForm.jsx', HEADER],
[AGREEMENT, NOTICE],
],
[
[entry, 'src/components/auth/RegisterForm.jsx', HEADER],
[AGREEMENT, NOTICE],
],
]) {
const eager = staticChunks(manifest, routes);
for (const feature of deferred) {
if (!manifest[feature]?.isDynamicEntry || eager.has(feature))
throw new Error(`Expected an independent lazy chunk: ${feature}`);
}
}
const files = new Set(
[...staticChunks(manifest, [entry])].map((key) => manifest[key].file),
);
let bootstrapGzipBytes = 0;
for (const file of files) {
const source = await readFile(resolveAsset(root, file));
bootstrapGzipBytes += gzipSync(source).length;
}
if (bootstrapGzipBytes > BOOTSTRAP_GZIP_LIMIT)
throw new Error(
`Bootstrap JS exceeds 820 KiB gzip: ${bootstrapGzipBytes} B`,
);
return { bootstrapGzipBytes, bootstrapChunks: files.size };
}
export async function verifyBuild(directory, { startup = false } = {}) {
const root = path.resolve(directory);
const html = await readFile(path.join(root, 'index.html'), 'utf8');
// Inspect actual resource tags, not URLs embedded in comments or inline scripts.
const markup = html
.replace(/<!--[\s\S]*?-->/g, '')
.replace(/(<script\b[^>]*>)[\s\S]*?<\/script\s*>/gi, '$1</script>');
const tags = [
...markup.matchAll(/<(?:script|link|img|source)\b[^>]*>/gi),
].map((match) => match[0]);
const assets = tags
.flatMap((tag) => [...tag.matchAll(/\s(?:src|href)\s*=["']([^"']+)["']/g)])
.map((match) => match[1].split(/[?#]/)[0])
// The inline brand bootstrap resolves this server placeholder to /logo.svg.
.map((value) => (value === '__WL_BRAND_FAVICON__' ? '/logo.svg' : value))
.filter((value) => value && !/^(?:[a-z]+:|\/\/|#)/i.test(value));
if (!assets.some((value) => /\.js$/.test(value)))
throw new Error('Build has no JavaScript entry');
for (const asset of assets) {
await access(resolveAsset(root, asset));
}
return {
root,
assets: assets.length,
...(startup ? await verifyStartup(root) : {}),
};
}
if (
process.argv[1] &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
const args = process.argv.slice(2);
const directory = args.find((argument) => argument !== '--startup') || 'dist';
console.log(
await verifyBuild(directory, { startup: args.includes('--startup') }),
);
}