Files
weiguang-jewelry-ledger/新账系统/e2e/startup-budget.mjs
T

112 lines
4.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { gzipSync } from 'node:zlib';
import { chromium } from 'playwright';
import { startServer } from './lib/server.js';
import { Session } from './lib/client.js';
const here = path.dirname(fileURLToPath(import.meta.url));
const dist = path.join(here, '..', 'web', 'dist');
const budgets = { login: 320000, create: 360000 };
const manifest = JSON.parse(fs.readFileSync(path.join(dist, '.vite', 'manifest.json'), 'utf8'));
const pageEntries = Object.entries(manifest).filter(
([name, entry]) => name.startsWith('src/pages/') && entry.isDynamicEntry,
);
const startupPages = { login: 'src/pages/Login/LoginPage.tsx', create: 'src/pages/CreateOrder/CreateOrderPage.tsx' };
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'ledger-startup-'));
const server = startServer({ dataDir: fixture });
const results = [];
let browser;
try {
const { base } = await server.ready();
const session = new Session({ base, server });
await session.day('2026-11-20', 9);
await session.post('owner', '/api/setup', {
ownerPassword: 'fixture-owner-123',
assistantPassword: 'fixture-assist-123',
assistant2Password: 'fixture-other-123',
});
if (session.problems.length) throw new Error(session.problems.join('\n'));
browser = await chromium.launch();
for (const [route, limit] of Object.entries(budgets)) {
for (let sample = 1; sample <= 3; sample++) {
const context = await browser.newContext({
viewport: { width: 390, height: 844 },
isMobile: true,
hasTouch: true,
deviceScaleFactor: 2,
});
if (route === 'create') {
const [name, ...value] = session.cookies.owner.split('=');
await context.addCookies([{ name, value: value.join('='), url: base }]);
}
const page = await context.newPage();
const cdp = await context.newCDPSession(page);
await cdp.send('Network.enable');
await cdp.send('Network.setCacheDisabled', { cacheDisabled: true });
await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 });
await cdp.send('Network.emulateNetworkConditions', {
offline: false,
latency: 40,
downloadThroughput: 1600000,
uploadThroughput: 750000,
});
const scripts = new Set();
page.on('request', request => {
const url = new URL(request.url());
if (request.resourceType() === 'script' || url.pathname.endsWith('.js')) scripts.add(url.href);
});
await page.goto(base + '/next/' + (route === 'login' ? 'login' : ''), { waitUntil: 'commit' });
await page
.locator(route === 'login' ? '.login-form input[name=password]' : '[data-field="customer"] input')
.click({ trial: true });
const ms = await page.evaluate(() => Math.round(performance.now()));
const files = [...scripts].sort().map(href => {
const { origin, pathname } = new URL(href);
if (origin !== new URL(base).origin || !pathname.startsWith('/next/')) throw new Error('未知的首屏 JS ' + href);
return {
url: pathname,
gzip: gzipSync(fs.readFileSync(path.join(dist, pathname.slice('/next/'.length))), { level: 6 }).length,
};
});
const fetched = new Set(files.map(file => file.url));
const expected = startupPages[route];
if (!manifest[expected]?.isDynamicEntry || !fetched.has('/next/' + manifest[expected].file)) {
throw new Error('未实际加载当前页面的独立分块 ' + expected);
}
for (const [name, entry] of pageEntries) {
if (name !== expected && fetched.has('/next/' + entry.file)) throw new Error('首屏提前下载其他页面 ' + name);
}
const total = files.reduce((sum, file) => sum + file.gzip, 0);
let firstSwitchMs;
if (route === 'create') {
await page.getByRole('button', { name: '打开导航' }).click();
const link = page.locator('a[data-tab="stock"]:visible').last();
const before = await page.evaluate(() => performance.now());
await link.click();
await page.locator('.inventory-page').waitFor();
firstSwitchMs = Math.round((await page.evaluate(() => performance.now())) - before);
}
results.push({ route, sample, ms, firstSwitchMs, total, limit, files });
console.log(
route,
sample,
total + '/' + limit + ' 字节 gzip,' + ms + ' ms',
firstSwitchMs === undefined ? '' : '首次切页 ' + firstSwitchMs + ' ms',
);
await context.close();
}
}
const out = path.join(here, 'out', 'startup.json');
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, JSON.stringify(results, null, 2) + '\n');
if (results.some(row => row.total > row.limit)) throw new Error('首屏 JS 超出预算,分块明细见 ' + out);
} finally {
await browser?.close();
await server.stop();
fs.rmSync(fixture, { recursive: true, force: true });
}