格式化:Prettier统一代码风格(仅格式,无逻辑变化)

仅为 npm run format 的输出;黄金对照、旧库兼容、浏览器流程与单元测试全部通过且零差异。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
黄健铭andClaude Opus 5.5 committed 2026-12-04 08:58:53 -08:00
1 parent 3743d687e7
commit 28c64814f0
221 files changed
+116943 -26708

No files matched your search

+438 -182
View File
@@ -5,176 +5,371 @@
// node e2e/browser.mjs 录制快照基线到 e2e/baseline/ui/
// node e2e/browser.mjs --check 与基线比较(忽略无意义空白),有差异退出码 1
// --headed 可视化运行;--slow 每步放慢
import {createRequire} from 'node:module';
import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import {fileURLToPath} from 'node:url';
const require=createRequire(import.meta.url);
const {chromium}=require('playwright');
const {startServer}=require('./lib/server.js');
const {Session}=require('./lib/client.js');
const {Normalizer}=require('./lib/normalize.js');
const HERE=path.dirname(fileURLToPath(import.meta.url));
const args=process.argv.slice(2),check=args.includes('--check'),headed=args.includes('--headed');
const BASE_UI=path.join(HERE,'baseline','ui'),OUT_UI=path.join(HERE,'out','ui'),SCREENS=path.join(HERE,'out','screens');
const D0='2026-11-19',D='2026-11-20';
const PW={owner:'browser-owner-pass-1',assistant:'browser-assistant-pass',assistant2:'browser-assistant2-pass'};
const SHANGHAI=8*3600*1000;
const dayStart=date=>Date.parse(date+'T00:00:00Z')-SHANGHAI+10*3600*1000;
import { createRequire } from 'node:module';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const { chromium } = require('playwright');
const { startServer } = require('./lib/server.js');
const { Session } = require('./lib/client.js');
const { Normalizer } = require('./lib/normalize.js');
const HERE = path.dirname(fileURLToPath(import.meta.url));
const args = process.argv.slice(2),
check = args.includes('--check'),
headed = args.includes('--headed');
const BASE_UI = path.join(HERE, 'baseline', 'ui'),
OUT_UI = path.join(HERE, 'out', 'ui'),
SCREENS = path.join(HERE, 'out', 'screens');
const D0 = '2026-11-19',
D = '2026-11-20';
const PW = {
owner: 'browser-owner-pass-1',
assistant: 'browser-assistant-pass',
assistant2: 'browser-assistant2-pass',
};
const SHANGHAI = 8 * 3600 * 1000;
const dayStart = date => Date.parse(date + 'T00:00:00Z') - SHANGHAI + 10 * 3600 * 1000;
const failures=[];const notes=[];
function fail(message){failures.push(message);console.error(' ✗ '+message);}
function ok(message){console.log(' ✓ '+message);}
async function seed(server,base){
// 前置数据只经 HTTP 写入:账号、起始库存、购料和前一天的订单(用于跨天修改申请与前后单切换)。
const s=new Session({base,server});await s.day(D0);
await s.post('owner','/api/setup',{ownerPassword:PW.owner,assistantPassword:PW.assistant,assistant2Password:PW.assistant2});
await s.post('assistant','/api/login',{name:'娜娜',password:PW.assistant});
await s.post('assistant2','/api/login',{name:'小昊',password:PW.assistant2});
for(const [pocket,grams] of [['现货','100'],['金料','50']])await s.post('owner','/api/stock',{date:D0,kind:'opening',pocket,grams,note:'浏览器检查起始库存'});
await s.post('owner','/api/material-purchases',{date:D0,grams:'10',total:'9000',payer:'owner',note:'浏览器检查购料'});
const order=(member,customer,quantity,sale)=>({date:D0,customer,internal_note:'浏览器检查备注',salesperson:{owner:'麦麦',assistant:'娜娜',assistant2:'小昊'}[member],payment_account:{owner:'麦麦微信',assistant:'助理微信',assistant2:'助理2微信'}[member],rounding_mode:'cent',lines:[{name:'足金999',unit:'g',quantity,pocket:'现货',payer:member,sale,cost:String(Math.round(Number(sale)*0.85))}],fee_items:[]});
await s.post('owner','/api/orders/issue',order('owner','昨日老板客户甲','1.5','1500'));
await s.post('assistant','/api/orders/issue',order('assistant','昨日娜娜客户','2','2000'));
await s.post('owner','/api/orders/issue',order('owner','昨日老板客户乙','3','3100'));
await s.post('assistant2','/api/orders/issue',order('assistant2','昨日小昊客户','1','1050'));
if(s.problems.length)throw new Error('前置数据写入失败:\n'+s.problems.join('\n'));
const failures = [];
const notes = [];
function fail(message) {
failures.push(message);
console.error(' ✗ ' + message);
}
function ok(message) {
console.log(' ✓ ' + message);
}
class Browser{
constructor(browser,base,server){this.browser=browser;this.base=base;this.server=server;this.step=0;this.normalizer=new Normalizer();this.normalizer.literal(base,'http://<host>');this.normalizer.literal(base.slice(7),'<host>');this.snapIndex=0;this.allowed=[];this.inflight=0;this.snapshots=[];}
async open(role){
this.role=role;this.context=await this.browser.newContext({viewport:{width:1400,height:1000},locale:'zh-CN',timezoneId:'Asia/Shanghai'});
await this.context.addInitScript(()=>{window.print=()=>{};});this.context.on('page',page=>this.watch(page));this.page=await this.context.newPage();this.page.setDefaultTimeout(8000);await this.page.clock.setFixedTime(new Date(dayStart(D)));
async function seed(server, base) {
// 前置数据只经 HTTP 写入:账号、起始库存、购料和前一天的订单(用于跨天修改申请与前后单切换)。
const s = new Session({ base, server });
await s.day(D0);
await s.post('owner', '/api/setup', {
ownerPassword: PW.owner,
assistantPassword: PW.assistant,
assistant2Password: PW.assistant2,
});
await s.post('assistant', '/api/login', { name: '娜娜', password: PW.assistant });
await s.post('assistant2', '/api/login', { name: '小昊', password: PW.assistant2 });
for (const [pocket, grams] of [
['现货', '100'],
['金料', '50'],
])
await s.post('owner', '/api/stock', { date: D0, kind: 'opening', pocket, grams, note: '浏览器检查起始库存' });
await s.post('owner', '/api/material-purchases', {
date: D0,
grams: '10',
total: '9000',
payer: 'owner',
note: '浏览器检查购料',
});
const order = (member, customer, quantity, sale) => ({
date: D0,
customer,
internal_note: '浏览器检查备注',
salesperson: { owner: '麦麦', assistant: '娜娜', assistant2: '小昊' }[member],
payment_account: { owner: '麦麦微信', assistant: '助理微信', assistant2: '助理2微信' }[member],
rounding_mode: 'cent',
lines: [
{
name: '足金999',
unit: 'g',
quantity,
pocket: '现货',
payer: member,
sale,
cost: String(Math.round(Number(sale) * 0.85)),
},
],
fee_items: [],
});
await s.post('owner', '/api/orders/issue', order('owner', '昨日老板客户甲', '1.5', '1500'));
await s.post('assistant', '/api/orders/issue', order('assistant', '昨日娜娜客户', '2', '2000'));
await s.post('owner', '/api/orders/issue', order('owner', '昨日老板客户乙', '3', '3100'));
await s.post('assistant2', '/api/orders/issue', order('assistant2', '昨日小昊客户', '1', '1050'));
if (s.problems.length) throw new Error('前置数据写入失败:\n' + s.problems.join('\n'));
}
class Browser {
constructor(browser, base, server) {
this.browser = browser;
this.base = base;
this.server = server;
this.step = 0;
this.normalizer = new Normalizer();
this.normalizer.literal(base, 'http://<host>');
this.normalizer.literal(base.slice(7), '<host>');
this.snapIndex = 0;
this.allowed = [];
this.inflight = 0;
this.snapshots = [];
}
async open(role) {
this.role = role;
this.context = await this.browser.newContext({
viewport: { width: 1400, height: 1000 },
locale: 'zh-CN',
timezoneId: 'Asia/Shanghai',
});
await this.context.addInitScript(() => {
window.print = () => {};
});
this.context.on('page', page => this.watch(page));
this.page = await this.context.newPage();
this.page.setDefaultTimeout(8000);
await this.page.clock.setFixedTime(new Date(dayStart(D)));
this.watch(this.page);
}
watch(page){
this.watched??=new WeakSet();if(this.watched.has(page))return;this.watched.add(page);
page.clock?.setFixedTime(new Date(dayStart(D))).catch(()=>{});
page.on('pageerror',e=>fail(`[${this.role}] 页面未捕获错误:${e.message}`));
page.on('console',m=>{if(m.type()==='error')fail(`[${this.role}] 控制台错误:${m.text()}`);});
page.on('dialog',d=>{notes.push(`${this.role} 对话框:${d.message()}`);d.accept();});
page.on('request',()=>{this.inflight++;});
page.on('requestfinished',async r=>{this.inflight--;const res=await r.response();if(res&&res.status()>=400&&!this.isAllowed(r.url(),res.status()))fail(`[${this.role}] 请求失败 ${res.status()} ${r.method()} ${r.url().replace(this.base,'')}`);});
page.on('requestfailed',r=>{this.inflight--;fail(`[${this.role}] 请求未完成 ${r.method()} ${r.url().replace(this.base,'')} ${r.failure()?.errorText}`);});
watch(page) {
this.watched ??= new WeakSet();
if (this.watched.has(page)) return;
this.watched.add(page);
page.clock?.setFixedTime(new Date(dayStart(D))).catch(() => {});
page.on('pageerror', e => fail(`[${this.role}] 页面未捕获错误:${e.message}`));
page.on('console', m => {
if (m.type() === 'error') fail(`[${this.role}] 控制台错误:${m.text()}`);
});
page.on('dialog', d => {
notes.push(`${this.role} 对话框:${d.message()}`);
d.accept();
});
page.on('request', () => {
this.inflight++;
});
page.on('requestfinished', async r => {
this.inflight--;
const res = await r.response();
if (res && res.status() >= 400 && !this.isAllowed(r.url(), res.status()))
fail(`[${this.role}] 请求失败 ${res.status()} ${r.method()} ${r.url().replace(this.base, '')}`);
});
page.on('requestfailed', r => {
this.inflight--;
fail(`[${this.role}] 请求未完成 ${r.method()} ${r.url().replace(this.base, '')} ${r.failure()?.errorText}`);
});
}
isAllowed(url, status) {
return this.allowed.some(([pattern, code]) => code === status && pattern.test(url.replace(this.base, '')));
}
async close() {
await this.context?.close();
this.context = null;
}
isAllowed(url,status){return this.allowed.some(([pattern,code])=>(code===status)&&pattern.test(url.replace(this.base,'')));}
async close(){await this.context?.close();this.context=null;}
// 每个界面动作前把服务器时钟前进 1 秒,使写入时间戳只取决于动作顺序。
async act(fn){this.step++;await this.server.setTime(dayStart(D)+this.step*1000);const result=await fn(this.page);await this.idle();return result;}
async idle(){
const page=this.page;let quiet=0;const deadline=Date.now()+15000;
while(Date.now()<deadline){await page.waitForTimeout(50);if(this.inflight<=0)quiet+=50;else quiet=0;if(quiet>=300)break;}
await page.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>r())));
async act(fn) {
this.step++;
await this.server.setTime(dayStart(D) + this.step * 1000);
const result = await fn(this.page);
await this.idle();
return result;
}
async snap(name){
const label=String(++this.snapIndex).padStart(2,'0')+'-'+name;
async idle() {
const page = this.page;
let quiet = 0;
const deadline = Date.now() + 15000;
while (Date.now() < deadline) {
await page.waitForTimeout(50);
if (this.inflight <= 0) quiet += 50;
else quiet = 0;
if (quiet >= 300) break;
}
await page.evaluate(() => new Promise(r => requestAnimationFrame(() => r())));
}
async snap(name) {
const label = String(++this.snapIndex).padStart(2, '0') + '-' + name;
await this.idle();
// 页面可见文字(含打开的对话框),规范化标识与空白。
const raw=await this.page.evaluate(()=>{
const parts=[...document.body.children].filter(el=>el.id!=='toast'&&el.tagName!=='DIALOG'&&el.tagName!=='SCRIPT').map(el=>el.innerText);// 提示条按真实计时消失,不计入快照
for(const d of document.querySelectorAll('dialog[open]'))parts.push('[对话框]\n'+d.innerText);
const raw = await this.page.evaluate(() => {
const parts = [...document.body.children]
.filter(el => el.id !== 'toast' && el.tagName !== 'DIALOG' && el.tagName !== 'SCRIPT')
.map(el => el.innerText); // 提示条按真实计时消失,不计入快照
for (const d of document.querySelectorAll('dialog[open]')) parts.push('[对话框]\n' + d.innerText);
// 表单控件当前值(innerText 不含输入框内容)
const values=[...document.querySelectorAll('input,select,textarea')].filter(el=>el.offsetParent!==null&&el.type!=='hidden'&&el.type!=='password').map(el=>{const key=el.name||el.id||el.getAttribute('aria-label')||el.type;const value=el.type==='checkbox'||el.type==='radio'?(el.checked?'☑':'☐'):el.tagName==='SELECT'?(el.selectedOptions[0]?.textContent||''):el.value;return key+'='+value;});
return parts.join('\n')+'\n[控件]\n'+values.join('\n');
const values = [...document.querySelectorAll('input,select,textarea')]
.filter(el => el.offsetParent !== null && el.type !== 'hidden' && el.type !== 'password')
.map(el => {
const key = el.name || el.id || el.getAttribute('aria-label') || el.type;
const value =
el.type === 'checkbox' || el.type === 'radio'
? el.checked
? '☑'
: '☐'
: el.tagName === 'SELECT'
? el.selectedOptions[0]?.textContent || ''
: el.value;
return key + '=' + value;
});
return parts.join('\n') + '\n[控件]\n' + values.join('\n');
});
const text=raw.split('\n').map(line=>this.normalizer.string(line).replace(/[\t   ]+/g,' ').trim()).filter(Boolean).join('\n')+'\n';
fs.mkdirSync(OUT_UI,{recursive:true});fs.mkdirSync(SCREENS,{recursive:true});
fs.writeFileSync(path.join(OUT_UI,label+'.txt'),text);
await this.page.screenshot({path:path.join(SCREENS,label+'.png'),fullPage:true});
this.snapshots.push({label,text});return text;
const text =
raw
.split('\n')
.map(line =>
this.normalizer
.string(line)
.replace(/[\t   ]+/g, ' ')
.trim(),
)
.filter(Boolean)
.join('\n') + '\n';
fs.mkdirSync(OUT_UI, { recursive: true });
fs.mkdirSync(SCREENS, { recursive: true });
fs.writeFileSync(path.join(OUT_UI, label + '.txt'), text);
await this.page.screenshot({ path: path.join(SCREENS, label + '.png'), fullPage: true });
this.snapshots.push({ label, text });
return text;
}
// 提交前列出浏览器校验未通过的字段,便于定位表单变化。
async invalid(selector){const names=await this.page.$$eval(selector+' :invalid',els=>els.filter(e=>e.name).map(e=>e.name+'('+(e.validationMessage||'')+')'));if(names.length)fail(`[${this.role}] 表单 ${selector} 有未通过校验的字段:${names.join('、')}`);return names;}
async expectText(text,what){const body=await this.page.evaluate(()=>document.body.innerText+[...document.querySelectorAll('dialog[open]')].map(d=>d.innerText).join('\n'));if(body.includes(text))ok(what||('页面显示 '+text));else fail(`[${this.role}] 页面未显示「${text}」${what?'('+what+')':''}`);}
async login(role,member,label){
async invalid(selector) {
const names = await this.page.$$eval(selector + ' :invalid', els =>
els.filter(e => e.name).map(e => e.name + '(' + (e.validationMessage || '') + ')'),
);
if (names.length) fail(`[${this.role}] 表单 ${selector} 有未通过校验的字段:${names.join('、')}`);
return names;
}
async expectText(text, what) {
const body = await this.page.evaluate(
() => document.body.innerText + [...document.querySelectorAll('dialog[open]')].map(d => d.innerText).join('\n'),
);
if (body.includes(text)) ok(what || '页面显示 ' + text);
else fail(`[${this.role}] 页面未显示「${text}」${what ? '(' + what + ')' : ''}`);
}
async login(role, member, label) {
await this.open(role);
await this.act(p=>p.goto(this.base+'/'));
if(label)await this.snap(label);
await this.act(async p=>{await p.selectOption('#login-form select[name=member]',member);await p.fill('#login-form input[name=password]',PW[role]);await p.click('#login-form button.primary');});
await this.page.waitForSelector('#shell:not([hidden])',{timeout:10000});await this.idle();
await this.act(p => p.goto(this.base + '/'));
if (label) await this.snap(label);
await this.act(async p => {
await p.selectOption('#login-form select[name=member]', member);
await p.fill('#login-form input[name=password]', PW[role]);
await p.click('#login-form button.primary');
});
await this.page.waitForSelector('#shell:not([hidden])', { timeout: 10000 });
await this.idle();
ok(`${role} 登录成功`);
}
async closeDialogs(){for(const close of await this.page.locator('dialog[open] .dialog-close').all())if(await close.isVisible())await this.act(()=>close.click());}
async logout(){await this.closeDialogs();await this.act(p=>p.click('[data-action="logout"]'));await this.close();}
async tab(name){await this.act(p=>p.click(`nav [data-tab="${name}"]`));}
async visitTabs(prefix){
const tabs=await this.page.$$eval('nav [data-tab]',buttons=>buttons.filter(b=>!b.hidden&&!b.disabled&&b.offsetParent!==null).map(b=>b.dataset.tab));
for(const tab of tabs){await this.tab(tab);await this.snap(prefix+'-tab-'+tab);}
async closeDialogs() {
for (const close of await this.page.locator('dialog[open] .dialog-close').all())
if (await close.isVisible()) await this.act(() => close.click());
}
async logout() {
await this.closeDialogs();
await this.act(p => p.click('[data-action="logout"]'));
await this.close();
}
async tab(name) {
await this.act(p => p.click(`nav [data-tab="${name}"]`));
}
async visitTabs(prefix) {
const tabs = await this.page.$$eval('nav [data-tab]', buttons =>
buttons.filter(b => !b.hidden && !b.disabled && b.offsetParent !== null).map(b => b.dataset.tab),
);
for (const tab of tabs) {
await this.tab(tab);
await this.snap(prefix + '-tab-' + tab);
}
ok(`${this.role} 访问全部 ${tabs.length} 个导航页:${tabs.join('、')}`);
return tabs;
}
}
async function flowOwner(b){
await b.login('owner','owner','login-page');
async function flowOwner(b) {
await b.login('owner', 'owner', 'login-page');
await b.snap('owner-home');
await b.visitTabs('owner');
// —— 开单:按克计价 + 附加项目 + 成本行 ——
await b.tab('create');
await b.act(async p=>{
const f=p.locator('#order-form');
await b.act(async p => {
const f = p.locator('#order-form');
await f.locator('input[name=customer]').fill('浏览器客户甲');
await f.locator('input[name=customer_type][value=new]').check();
await f.locator('select[name=member]').selectOption('owner');
const line=f.locator('.line-item').first();
const line = f.locator('.line-item').first();
await line.locator('input[name=quantity]').fill('2.5');
await line.locator('input[name=goldPrice]').fill('950');
await line.locator('input[name=laborRate]').fill('30');
await line.locator('[data-action="add-charge"]').click();
const charge=line.locator('.charge-list > *').first();
const amount=charge.locator('input[type=number]').first();await amount.fill('20');
const charge = line.locator('.charge-list > *').first();
const amount = charge.locator('input[type=number]').first();
await amount.fill('20');
await line.locator('input[name="cost-materialRate"]').fill('880');
await line.locator('input[name="cost-labor"]').fill('25');
await f.locator('[name=internal_note]').fill('#浏览器 内部备注');
// 附加项目对应的内部成本行(必填)
for(const fee of await f.locator('input[name=feeAmount]').all())if(await fee.isVisible()&&!(await fee.inputValue()))await fee.fill('5');
for (const fee of await f.locator('input[name=feeAmount]').all())
if ((await fee.isVisible()) && !(await fee.inputValue())) await fee.fill('5');
});
await b.invalid('#order-form');
const sale=await b.page.locator('#order-form .line-item input[name=sale]').first().inputValue();
if(sale==='2470.00'||sale==='2470')ok('本行销售额自动计算为 2470.00(2.5g×(950+30)+附加 20)');else fail('本行销售额计算不符:'+sale);
const sale = await b.page.locator('#order-form .line-item input[name=sale]').first().inputValue();
if (sale === '2470.00' || sale === '2470') ok('本行销售额自动计算为 2470.00(2.5g×(950+30)+附加 20)');
else fail('本行销售额计算不符:' + sale);
await b.snap('owner-create-filled');
await b.act(p=>p.click('#order-form button[type=submit]'));
await b.act(p => p.click('#order-form button[type=submit]'));
await b.snap('owner-create-submitted');
// 生成后自动打开订单明细
await b.expectText('¥2,470','订单明细显示成交合计 ¥2,470');
await b.expectText('未打印','新单显示未打印');
await b.expectText('¥2,470', '订单明细显示成交合计 ¥2,470');
await b.expectText('未打印', '新单显示未打印');
// —— 客户预览/打印:新窗口点击“打印”后记录已打印 ——
const [popup]=await Promise.all([b.context.waitForEvent('page'),b.act(p=>p.locator('#order-dialog [data-action="print"]').first().click())]);
const main=b.page;b.page=popup;popup.setDefaultTimeout(8000);
await popup.waitForLoadState('load');await b.idle();
const [popup] = await Promise.all([
b.context.waitForEvent('page'),
b.act(p => p.locator('#order-dialog [data-action="print"]').first().click()),
]);
const main = b.page;
b.page = popup;
popup.setDefaultTimeout(8000);
await popup.waitForLoadState('load');
await b.idle();
await b.snap('owner-print-preview');
await b.act(p=>p.click('#print'));
await popup.waitForFunction(()=>document.getElementById('document-print-state')?.textContent.includes('已打印'));
await b.expectText('✓ 已打印','打印预览中点击打印后记录为已打印');
await b.act(p => p.click('#print'));
await popup.waitForFunction(() => document.getElementById('document-print-state')?.textContent.includes('已打印'));
await b.expectText('✓ 已打印', '打印预览中点击打印后记录为已打印');
await b.snap('owner-print-marked');
await popup.close();b.page=main;
await b.act(p=>p.locator('#order-dialog [data-action="close-dialog"]').click());
await popup.close();
b.page = main;
await b.act(p => p.locator('#order-dialog [data-action="close-dialog"]').click());
await b.tab('orders');
await b.expectText('浏览器客户甲','新订单出现在订单列表');
await b.expectText('浏览器客户甲', '新订单出现在订单列表');
await b.snap('owner-orders-after-create');
// —— 订单明细与前后单切换(本月列表含昨天的多张单)——
await b.act(p=>p.click('[data-action="order-period"][data-period="month"]'));
await b.act(p => p.click('[data-action="order-period"][data-period="month"]'));
await b.snap('owner-orders-month');
await b.act(p=>p.locator('[data-action="open-order"]',{hasText:'浏览器客户甲'}).first().click());
await b.expectText('已打印','重新打开明细显示已打印');
await b.act(p => p.locator('[data-action="open-order"]', { hasText: '浏览器客户甲' }).first().click());
await b.expectText('已打印', '重新打开明细显示已打印');
await b.snap('owner-order-detail');
const next=b.page.locator('#order-dialog [data-action="order-detail-next"]');
const prev=b.page.locator('#order-dialog [data-action="order-detail-prev"]');
if(await next.count()&&await next.isEnabled()){await b.act(()=>next.click());await b.snap('owner-order-detail-next');await b.act(()=>prev.click());await b.snap('owner-order-detail-prev');await b.expectText('浏览器客户甲','上一条回到原订单');}
else if(await prev.count()&&await prev.isEnabled()){await b.act(()=>prev.click());await b.snap('owner-order-detail-prev');await b.act(()=>next.click());await b.snap('owner-order-detail-next');await b.expectText('浏览器客户甲','下一条回到原订单');}
else fail('订单明细前后单按钮均不可用');
await b.act(p=>p.locator('#order-dialog [data-action="close-dialog"]').click());
const next = b.page.locator('#order-dialog [data-action="order-detail-next"]');
const prev = b.page.locator('#order-dialog [data-action="order-detail-prev"]');
if ((await next.count()) && (await next.isEnabled())) {
await b.act(() => next.click());
await b.snap('owner-order-detail-next');
await b.act(() => prev.click());
await b.snap('owner-order-detail-prev');
await b.expectText('浏览器客户甲', '上一条回到原订单');
} else if ((await prev.count()) && (await prev.isEnabled())) {
await b.act(() => prev.click());
await b.snap('owner-order-detail-prev');
await b.act(() => next.click());
await b.snap('owner-order-detail-next');
await b.expectText('浏览器客户甲', '下一条回到原订单');
} else fail('订单明细前后单按钮均不可用');
await b.act(p => p.locator('#order-dialog [data-action="close-dialog"]').click());
// —— 每日购料 ——
await b.tab('material-pools');
await b.act(async p=>{const f=p.locator('#material-purchase-form');await f.locator('input[name=grams]').fill('5');await f.locator('input[name=total]').fill('4600');await f.locator('select[name=payer]').selectOption('owner');await f.locator('input[name=note]').fill('浏览器购料');await f.locator('button[type=submit],button.primary').first().click();});
await b.expectText('浏览器购料','购料登记成功');
await b.act(async p => {
const f = p.locator('#material-purchase-form');
await f.locator('input[name=grams]').fill('5');
await f.locator('input[name=total]').fill('4600');
await f.locator('select[name=payer]').selectOption('owner');
await f.locator('input[name=note]').fill('浏览器购料');
await f.locator('button[type=submit],button.primary').first().click();
});
await b.expectText('浏览器购料', '购料登记成功');
await b.snap('owner-material-purchase');
// —— 锁价 ——
await b.tab('create');
await b.act(p=>p.click('[data-action="create-mode"][data-mode="lock"]'));
await b.act(p => p.click('[data-action="create-mode"][data-mode="lock"]'));
await b.snap('owner-price-lock-form');
await priceLockForm(b);
@@ -184,37 +379,45 @@ async function flowOwner(b){
// —— 店铺设置 ——
await b.tab('settings');
await b.act(async p=>{const f=p.locator('#shop-settings-form');await f.locator('input[name=storeName]').fill('浏览器对照珠宝');await f.locator('button[type=submit],button.primary').first().click();});
await b.expectText('浏览器对照珠宝','店铺名称已更新');
await b.act(async p => {
const f = p.locator('#shop-settings-form');
await f.locator('input[name=storeName]').fill('浏览器对照珠宝');
await f.locator('button[type=submit],button.primary').first().click();
});
await b.expectText('浏览器对照珠宝', '店铺名称已更新');
await b.snap('owner-settings-saved');
await b.logout();
}
async function priceLockForm(b){
const form=b.page.locator('form').filter({has:b.page.locator('[name=customer]')}).first();
await b.act(async p=>{
async function priceLockForm(b) {
const form = b.page
.locator('form')
.filter({ has: b.page.locator('[name=customer]') })
.first();
await b.act(async p => {
await form.locator('[name=customer]').fill('浏览器锁价客户');
const radio=form.locator('input[name=customer_type][value=returning]');if(await radio.count())await radio.check();
const radio = form.locator('input[name=customer_type][value=returning]');
if (await radio.count()) await radio.check();
await form.locator('[name=quantity]').first().fill('2');
await form.locator('[name=goldPrice]').first().fill('900');
await form.locator('[name=laborRate]').first().fill('10');
await form.locator('[name=material_rate]').fill('850');
await form.locator('[name=received_amount]').fill('1000');
for(const box of await form.locator('input[type=checkbox][name*=verified]').all())await box.check();
for (const box of await form.locator('input[type=checkbox][name*=verified]').all()) await box.check();
});
await b.invalid('form:has([name=received_amount])');
await b.snap('owner-price-lock-filled');
await b.act(()=>form.locator('button[type=submit]').first().click());
await b.act(() => form.locator('button[type=submit]').first().click());
await b.snap('owner-price-lock-submitted');
await b.closeDialogs();
await b.tab('price-locks');
await b.expectText('浏览器锁价客户','锁价单出现在待交付列表');
await b.expectText('浏览器锁价客户', '锁价单出现在待交付列表');
await b.snap('owner-price-locks-after-create');
}
async function recoveryForm(b){
await b.act(async p=>{
const f=p.locator('#recovery-form');
async function recoveryForm(b) {
await b.act(async p => {
const f = p.locator('#recovery-form');
await f.locator('[name=customer]').fill('浏览器回收客户');
await f.locator('[name=incoming_weight]').first().fill('5');
await f.locator('[name=melted_weight]').first().fill('5');
@@ -223,97 +426,150 @@ async function recoveryForm(b){
await f.locator('[name=verified]').check();
});
await b.snap('owner-recovery-filled');
await b.act(p=>p.locator('#recovery-form button[type=submit]').first().click());
await b.expectText('浏览器回收客户','回收单出现在记录中');
await b.act(p => p.locator('#recovery-form button[type=submit]').first().click());
await b.expectText('浏览器回收客户', '回收单出现在记录中');
await b.snap('owner-recovery-saved');
await b.closeDialogs();
}
async function flowAssistantChange(b){
await b.login('assistant','assistant');
async function flowAssistantChange(b) {
await b.login('assistant', 'assistant');
await b.snap('assistant-home');
await b.visitTabs('assistant');
await b.tab('orders');
await b.act(p=>p.click('[data-action="order-period"][data-period="yesterday"]'));
await b.act(p=>p.locator('[data-action="open-order"]',{hasText:'昨日娜娜客户'}).first().click());
await b.act(p => p.click('[data-action="order-period"][data-period="yesterday"]'));
await b.act(p => p.locator('[data-action="open-order"]', { hasText: '昨日娜娜客户' }).first().click());
await b.snap('assistant-order-detail');
const edit=b.page.locator('#order-dialog button',{hasText:/^申请修改$/}).first();
await b.act(()=>edit.click());
const edit = b.page.locator('#order-dialog button', { hasText: /^申请修改$/ }).first();
await b.act(() => edit.click());
await b.snap('assistant-change-form');
await b.act(async p=>{const f=p.locator('#order-form');await f.locator('input[name=customer]').fill('昨日娜娜客户(改)');await f.locator('input[name=customer_type][value=returning]').check();await f.locator('[name=edit_reason]').fill('客户名写错');await f.locator('[name=edit_verified]').check();});
await b.act(async p => {
const f = p.locator('#order-form');
await f.locator('input[name=customer]').fill('昨日娜娜客户(改)');
await f.locator('input[name=customer_type][value=returning]').check();
await f.locator('[name=edit_reason]').fill('客户名写错');
await f.locator('[name=edit_verified]').check();
});
await b.invalid('#order-form');
await b.act(p=>p.locator('#order-form button[type=submit]').click());
await b.act(p => p.locator('#order-form button[type=submit]').click());
await b.snap('assistant-change-submitted');
await b.expectText('待','提交后显示待复核');
await b.expectText('待', '提交后显示待复核');
await b.logout();
// 麦麦审批
await b.login('owner','owner');
await b.login('owner', 'owner');
await b.tab('orders');
await b.act(p=>p.click('details.order-review-menu > summary'));
await b.act(p=>p.click('[data-action="open-order-changes"]'));
await b.act(p => p.click('details.order-review-menu > summary'));
await b.act(p => p.click('[data-action="open-order-changes"]'));
await b.snap('owner-order-changes');
await b.act(p=>p.locator('dialog[open] button',{hasText:'查看并复核'}).first().click());
await b.act(p => p.locator('dialog[open] button', { hasText: '查看并复核' }).first().click());
await b.snap('owner-order-change-detail');
await b.act(p=>p.locator('dialog[open] button',{hasText:'查看变更并复核'}).first().click());
await b.act(p => p.locator('dialog[open] button', { hasText: '查看变更并复核' }).first().click());
await b.snap('owner-order-change-review');
await b.act(async p=>{const dialog=p.locator('dialog[open]').last();await dialog.locator('[name=note]').fill('已核对');await dialog.locator('[name=verified]').check();});
await b.act(p=>p.locator('dialog[open] button',{hasText:'同意变更并更新原单'}).click());
await b.expectText('昨日娜娜客户(改)','批准后订单明细显示新客户名');
await b.act(async p => {
const dialog = p.locator('dialog[open]').last();
await dialog.locator('[name=note]').fill('已核对');
await dialog.locator('[name=verified]').check();
});
await b.act(p => p.locator('dialog[open] button', { hasText: '同意变更并更新原单' }).click());
await b.expectText('昨日娜娜客户(改)', '批准后订单明细显示新客户名');
await b.snap('owner-order-change-approved');
await b.closeDialogs();
await b.tab('orders');
await b.act(p=>p.click('[data-action="order-period"][data-period="yesterday"]'));
await b.expectText('昨日娜娜客户(改)','批准后订单显示新客户名');
await b.act(p => p.click('[data-action="order-period"][data-period="yesterday"]'));
await b.expectText('昨日娜娜客户(改)', '批准后订单显示新客户名');
await b.snap('owner-orders-after-approve');
await b.logout();
}
async function flowAssistant2(b){
await b.login('assistant2','assistant2');
async function flowAssistant2(b) {
await b.login('assistant2', 'assistant2');
await b.snap('assistant2-home');
await b.visitTabs('assistant2');
await b.logout();
}
function compareSnapshots(snapshots){
const expected=fs.existsSync(BASE_UI)?fs.readdirSync(BASE_UI).filter(f=>f.endsWith('.txt')).sort():[];
const actual=snapshots.map(s=>s.label+'.txt');const problems=[];
for(const name of expected)if(!actual.includes(name))problems.push('缺少页面快照 '+name);
for(const name of actual)if(!expected.includes(name))problems.push('多出页面快照 '+name);
for(const {label,text} of snapshots){
const file=path.join(BASE_UI,label+'.txt');if(!fs.existsSync(file))continue;
const a=fs.readFileSync(file,'utf8').split('\n'),c=text.split('\n');
if(a.join('\n')===c.join('\n'))continue;
let i=0;while(i<a.length&&i<c.length&&a[i]===c[i])i++;
problems.push(`页面快照 ${label} 不同(第 ${i+1} 行起):\n 基线:${(a.slice(i,i+3).join(' ⏎ ')||'(无)').slice(0,300)}\n 实际:${(c.slice(i,i+3).join(' ⏎ ')||'(无)').slice(0,300)}`);
function compareSnapshots(snapshots) {
const expected = fs.existsSync(BASE_UI)
? fs
.readdirSync(BASE_UI)
.filter(f => f.endsWith('.txt'))
.sort()
: [];
const actual = snapshots.map(s => s.label + '.txt');
const problems = [];
for (const name of expected) if (!actual.includes(name)) problems.push('缺少页面快照 ' + name);
for (const name of actual) if (!expected.includes(name)) problems.push('多出页面快照 ' + name);
for (const { label, text } of snapshots) {
const file = path.join(BASE_UI, label + '.txt');
if (!fs.existsSync(file)) continue;
const a = fs.readFileSync(file, 'utf8').split('\n'),
c = text.split('\n');
if (a.join('\n') === c.join('\n')) continue;
let i = 0;
while (i < a.length && i < c.length && a[i] === c[i]) i++;
problems.push(
`页面快照 ${label} 不同(第 ${i + 1} 行起):\n 基线:${(a.slice(i, i + 3).join(' ⏎ ') || '(无)').slice(0, 300)}\n 实际:${(c.slice(i, i + 3).join(' ⏎ ') || '(无)').slice(0, 300)}`,
);
}
return problems;
}
const started=Date.now();
const dataDir=fs.mkdtempSync(path.join(os.tmpdir(),'ledger-browser-'));
const server=startServer({mode:'trial',dataDir,clockStart:new Date(dayStart(D0)).toISOString(),seed:'browser-seed'});
const started = Date.now();
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ledger-browser-'));
const server = startServer({
mode: 'trial',
dataDir,
clockStart: new Date(dayStart(D0)).toISOString(),
seed: 'browser-seed',
});
let browser;
try{
const info=await server.ready();
await seed(server,info.base);
browser=await chromium.launch({headless:!headed,slowMo:args.includes('--slow')?200:0});
fs.rmSync(OUT_UI,{recursive:true,force:true});fs.rmSync(SCREENS,{recursive:true,force:true});
const b=new Browser(browser,info.base,server);
for(const [name,flow] of [['麦麦:登录、全部导航页、开单、打印、前后单、购料、锁价、回收、店铺设置',flowOwner],['娜娜提交跨天修改申请,麦麦批准',flowAssistantChange],['小昊:登录、全部导航页',flowAssistant2]]){
if(args.includes('--only')&&!name.includes(args[args.indexOf('--only')+1]))continue;
console.log('▶ '+name);
try{await flow(b);}catch(error){fail(`流程「${name}」中断:${error.message.split('\n')[0]}`);try{await b.page?.screenshot({path:path.join(SCREENS,'failure-'+b.snapIndex+'.png'),fullPage:true});}catch{}await b.close();}
try {
const info = await server.ready();
await seed(server, info.base);
browser = await chromium.launch({ headless: !headed, slowMo: args.includes('--slow') ? 200 : 0 });
fs.rmSync(OUT_UI, { recursive: true, force: true });
fs.rmSync(SCREENS, { recursive: true, force: true });
const b = new Browser(browser, info.base, server);
for (const [name, flow] of [
['麦麦:登录、全部导航页、开单、打印、前后单、购料、锁价、回收、店铺设置', flowOwner],
['娜娜提交跨天修改申请,麦麦批准', flowAssistantChange],
['小昊:登录、全部导航页', flowAssistant2],
]) {
if (args.includes('--only') && !name.includes(args[args.indexOf('--only') + 1])) continue;
console.log('▶ ' + name);
try {
await flow(b);
} catch (error) {
fail(`流程「${name}」中断:${error.message.split('\n')[0]}`);
try {
await b.page?.screenshot({ path: path.join(SCREENS, 'failure-' + b.snapIndex + '.png'), fullPage: true });
} catch {}
await b.close();
}
}
const seconds=((Date.now()-started)/1000).toFixed(1);
if(check){
const problems=compareSnapshots(b.snapshots);for(const p of problems)console.log(' ✗ '+p);
const failed=failures.length+problems.length>0;
console.log(`browser ${failed?'FAIL':'PASS'}:${b.snapshots.length} 个页面快照,${failures.length} 个运行错误,${problems.length} 处快照差异,用时 ${seconds}s(截图在 e2e/out/screens/)`);
process.exitCode=failed?1:0;
}else{
if(failures.length){console.error(`运行中有 ${failures.length} 个错误,拒绝写入基线`);process.exitCode=1;}
else{fs.rmSync(BASE_UI,{recursive:true,force:true});fs.mkdirSync(BASE_UI,{recursive:true});for(const {label,text} of b.snapshots)fs.writeFileSync(path.join(BASE_UI,label+'.txt'),text);console.log(`基线已写入 e2e/baseline/ui/(${b.snapshots.length} 个页面快照,用时 ${seconds}s)`);}
const seconds = ((Date.now() - started) / 1000).toFixed(1);
if (check) {
const problems = compareSnapshots(b.snapshots);
for (const p of problems) console.log(' ✗ ' + p);
const failed = failures.length + problems.length > 0;
console.log(
`browser ${failed ? 'FAIL' : 'PASS'}:${b.snapshots.length} 个页面快照,${failures.length} 个运行错误,${problems.length} 处快照差异,用时 ${seconds}s(截图在 e2e/out/screens/)`,
);
process.exitCode = failed ? 1 : 0;
} else {
if (failures.length) {
console.error(`运行中有 ${failures.length} 个错误,拒绝写入基线`);
process.exitCode = 1;
} else {
fs.rmSync(BASE_UI, { recursive: true, force: true });
fs.mkdirSync(BASE_UI, { recursive: true });
for (const { label, text } of b.snapshots) fs.writeFileSync(path.join(BASE_UI, label + '.txt'), text);
console.log(`基线已写入 e2e/baseline/ui/(${b.snapshots.length} 个页面快照,用时 ${seconds}s)`);
}
}
if(notes.length&&args.includes('--verbose'))console.log(notes.join('\n'));
}finally{await browser?.close();await server.stop();fs.rmSync(dataDir,{recursive:true,force:true});}
if (notes.length && args.includes('--verbose')) console.log(notes.join('\n'));
} finally {
await browser?.close();
await server.stop();
fs.rmSync(dataDir, { recursive: true, force: true });
}
+35 -11
View File
@@ -2,14 +2,38 @@
'use strict';
// 粗略统计黄金对照覆盖的服务器路由:把记录里的请求归一为“方法 + 路由模板”,与 server.js 中的路由清单对照。
// 用法:node e2e/coverage.js(读取 e2e/baseline/golden/transcript.json)
const fs=require('node:fs'),path=require('node:path');
const transcript=JSON.parse(fs.readFileSync(path.join(__dirname,'baseline','golden','transcript.json'),'utf8'));
const template=p=>p.split('?')[0].replace(/<id\d+>/g,':id').replace(/\d{4}-\d{2}-\d{2}/g,':date').replace(/pocket_:id/g,':pocket').replace(/<backup-file>/g,':file').replace(/\/staff_:id\//,'/:member/').replace(/\/(assistant2?|owner)\/password$/,'/:member/password').replace(/^\/print\/(?!recoveries).+/,'/print/:id');
const ROUTES=`GET /api/session|POST /api/setup|POST /api/login|POST /api/demo-login|POST /api/logout|GET /api/state|GET /api/print-status/order/:id|POST /api/print-status/order/:id|GET /api/print-status/recovery/:id|POST /api/print-status/recovery/:id|GET /api/shop-settings|POST /api/shop-settings|POST /api/printing|GET /api/employees|POST /api/employees|POST /api/employees/:member/update|POST /api/employees/:member/deactivate|POST /api/employees/:member/reactivate|POST /api/employees/:member/delete|GET /api/team-members|POST /api/team-members/:member/password|GET /api/pockets|POST /api/pockets|POST /api/pockets/:pocket/update|GET /api/team-funds|POST /api/team-funds/transfers|POST /api/team-funds/transfer|GET /api/private-operations|GET /api/private-operations/people|POST /api/private-operations/people|GET /api/private-operations/people-history|GET /api/team-profits|GET /api/material-pools|GET /api/material-pools/rolling-preview|POST /api/material-pools/rolling-enable|POST /api/material-pools/quote|GET /api/material-pools/:date|POST /api/material-pools/:date/settlement|GET /api/material-purchase-changes|GET /api/material-purchase-changes/:id|POST /api/material-purchase-changes/:id/approve|POST /api/material-purchase-changes/:id/reject|POST /api/material-purchases|GET /api/material-purchases/:id|POST /api/material-purchases/:id/edit|POST /api/material-purchases/:id/delete|POST /api/material-purchases/:id/change|GET /api/after-sales/changes|GET /api/after-sales/changes/:id|POST /api/after-sales/changes/:id/approve|POST /api/after-sales/changes/:id/reject|POST /api/after-sales|GET /api/after-sales/:id|POST /api/after-sales/:id/update|GET /api/customer-materials|POST /api/customer-materials|GET /api/recoveries|POST /api/recoveries|POST /api/recoveries/quote|GET /api/recoveries/:id|GET /api/recoveries/:id/edit|POST /api/recoveries/:id/update|POST /api/recoveries/:id/cancel|POST /api/recoveries/:id/quote|GET /api/recovery-changes|GET /api/recovery-changes/:id|POST /api/recovery-changes/:id/approve|POST /api/recovery-changes/:id/reject|GET /api/price-locks|POST /api/price-locks|GET /api/price-locks/:id|GET /api/price-locks/:id/edit-context|POST /api/price-locks/:id/deliver|POST /api/price-locks/:id/edit|POST /api/price-locks/:id/cancel|POST /api/price-locks/:id/change-requests|GET /api/price-lock-changes|GET /api/price-lock-changes/:id|POST /api/price-lock-changes/:id/approve|POST /api/price-lock-changes/:id/reject|GET /api/order-note-tags|GET /api/order-changes|GET /api/order-changes/:id|POST /api/order-changes/:id/approve|POST /api/order-changes/:id/reject|GET /api/order-ownership-changes|GET /api/order-ownership-changes/:id|POST /api/order-ownership-changes/:id/approve|POST /api/order-ownership-changes/:id/reject|GET /api/order-cancellations|GET /api/order-cancellations/:id|POST /api/order-cancellations/:id/approve|POST /api/order-cancellations/:id/reject|GET /api/inventory|GET /api/inventory/movements/export.xlsx|GET /api/inventory/movements|GET /api/inventory/movements/:id|POST /api/inventory/movements/:id/update|POST /api/inventory/movements/:id/delete|GET /api/inventory/changes|GET /api/inventory/changes/:id|POST /api/inventory/changes/:id/approve|POST /api/inventory/changes/:id/reject|GET /api/inventory/snapshots|POST /api/inventory/review|GET /api/order-book|GET /api/order-templates|POST /api/order-templates|GET /api/order-templates/:id|POST /api/order-templates/:id/update|POST /api/order-templates/:id/delete|GET /api/people-count|POST /api/people-count|GET /api/people-count-history|GET /api/daily-funds|POST /api/daily-funds/confirm|GET /api/reimbursement-funding-options|GET /api/reimbursements|POST /api/reimbursements|POST /api/reimbursements/:id/update|POST /api/reimbursements/:id/approve|POST /api/reimbursements/:id/reject|GET /api/returned-stock-lots|GET /api/paper-number|GET /api/orders/:id/after-sale|POST /api/orders/:id/after-sale-preview|GET /api/orders/:id|GET /api/orders/:id/public|GET /api/orders/:id/edit|GET /api/orders/:id/change|GET /api/orders/:id/ownership|GET /api/orders/:id/cancellation|POST /api/orders/issue|POST /api/orders|POST /api/orders/:id/edit|POST /api/orders/:id/change|POST /api/orders/:id/ownership|POST /api/orders/:id/cancellation|POST /api/orders/:id/canceltoday|POST /api/orders/:id/confirm|POST /api/orders/:id/receipt|POST /api/orders/:id/complete|POST /api/orders/:id/expense|POST /api/orders/:id/refund|POST /api/orders/:id/return|POST /api/orders/:id/fees|POST /api/orders/:id/cost|POST /api/orders/:id/settlement|POST /api/orders/:id/correct|POST /api/orders/:id/material|GET /print/recoveries/:id|GET /print/:id|GET /api/report|GET /api/export/inventory|POST /api/backup|GET /api/backup/:file|POST /api/sync|POST /api/stock|POST /api/close|POST /api/password|GET /(static assets)`.split('|');
const hits=new Map();
for(const e of transcript.filter(e=>e.method)){let key=e.method+' '+template(e.path);if(e.method==='GET'&&/^\/[\w.-]*$/.test(e.path)&&!e.path.startsWith('/api'))key='GET /(static assets)';const ok=e.status<400;const h=hits.get(key)||{ok:0,err:0};h[ok?'ok':'err']++;hits.set(key,h);}
const covered=ROUTES.filter(r=>hits.has(r)),success=ROUTES.filter(r=>hits.get(r)?.ok);
console.log(`路由清单 ${ROUTES.length} 条;被请求 ${covered.length} 条(${Math.round(covered.length/ROUTES.length*100)}%),其中有成功响应 ${success.length} 条(${Math.round(success.length/ROUTES.length*100)}%)。`);
console.log('\n未请求:\n '+ROUTES.filter(r=>!hits.has(r)).join('\n '));
console.log('\n只有错误响应(拒绝路径):\n '+ROUTES.filter(r=>hits.has(r)&&!hits.get(r).ok).join('\n '));
const extra=[...hits.keys()].filter(k=>!ROUTES.includes(k));if(extra.length)console.log('\n清单外(多为故意的未知地址):\n '+extra.join('\n '));
const fs = require('node:fs'),
path = require('node:path');
const transcript = JSON.parse(fs.readFileSync(path.join(__dirname, 'baseline', 'golden', 'transcript.json'), 'utf8'));
const template = p =>
p
.split('?')[0]
.replace(/<id\d+>/g, ':id')
.replace(/\d{4}-\d{2}-\d{2}/g, ':date')
.replace(/pocket_:id/g, ':pocket')
.replace(/<backup-file>/g, ':file')
.replace(/\/staff_:id\//, '/:member/')
.replace(/\/(assistant2?|owner)\/password$/, '/:member/password')
.replace(/^\/print\/(?!recoveries).+/, '/print/:id');
const ROUTES =
`GET /api/session|POST /api/setup|POST /api/login|POST /api/demo-login|POST /api/logout|GET /api/state|GET /api/print-status/order/:id|POST /api/print-status/order/:id|GET /api/print-status/recovery/:id|POST /api/print-status/recovery/:id|GET /api/shop-settings|POST /api/shop-settings|POST /api/printing|GET /api/employees|POST /api/employees|POST /api/employees/:member/update|POST /api/employees/:member/deactivate|POST /api/employees/:member/reactivate|POST /api/employees/:member/delete|GET /api/team-members|POST /api/team-members/:member/password|GET /api/pockets|POST /api/pockets|POST /api/pockets/:pocket/update|GET /api/team-funds|POST /api/team-funds/transfers|POST /api/team-funds/transfer|GET /api/private-operations|GET /api/private-operations/people|POST /api/private-operations/people|GET /api/private-operations/people-history|GET /api/team-profits|GET /api/material-pools|GET /api/material-pools/rolling-preview|POST /api/material-pools/rolling-enable|POST /api/material-pools/quote|GET /api/material-pools/:date|POST /api/material-pools/:date/settlement|GET /api/material-purchase-changes|GET /api/material-purchase-changes/:id|POST /api/material-purchase-changes/:id/approve|POST /api/material-purchase-changes/:id/reject|POST /api/material-purchases|GET /api/material-purchases/:id|POST /api/material-purchases/:id/edit|POST /api/material-purchases/:id/delete|POST /api/material-purchases/:id/change|GET /api/after-sales/changes|GET /api/after-sales/changes/:id|POST /api/after-sales/changes/:id/approve|POST /api/after-sales/changes/:id/reject|POST /api/after-sales|GET /api/after-sales/:id|POST /api/after-sales/:id/update|GET /api/customer-materials|POST /api/customer-materials|GET /api/recoveries|POST /api/recoveries|POST /api/recoveries/quote|GET /api/recoveries/:id|GET /api/recoveries/:id/edit|POST /api/recoveries/:id/update|POST /api/recoveries/:id/cancel|POST /api/recoveries/:id/quote|GET /api/recovery-changes|GET /api/recovery-changes/:id|POST /api/recovery-changes/:id/approve|POST /api/recovery-changes/:id/reject|GET /api/price-locks|POST /api/price-locks|GET /api/price-locks/:id|GET /api/price-locks/:id/edit-context|POST /api/price-locks/:id/deliver|POST /api/price-locks/:id/edit|POST /api/price-locks/:id/cancel|POST /api/price-locks/:id/change-requests|GET /api/price-lock-changes|GET /api/price-lock-changes/:id|POST /api/price-lock-changes/:id/approve|POST /api/price-lock-changes/:id/reject|GET /api/order-note-tags|GET /api/order-changes|GET /api/order-changes/:id|POST /api/order-changes/:id/approve|POST /api/order-changes/:id/reject|GET /api/order-ownership-changes|GET /api/order-ownership-changes/:id|POST /api/order-ownership-changes/:id/approve|POST /api/order-ownership-changes/:id/reject|GET /api/order-cancellations|GET /api/order-cancellations/:id|POST /api/order-cancellations/:id/approve|POST /api/order-cancellations/:id/reject|GET /api/inventory|GET /api/inventory/movements/export.xlsx|GET /api/inventory/movements|GET /api/inventory/movements/:id|POST /api/inventory/movements/:id/update|POST /api/inventory/movements/:id/delete|GET /api/inventory/changes|GET /api/inventory/changes/:id|POST /api/inventory/changes/:id/approve|POST /api/inventory/changes/:id/reject|GET /api/inventory/snapshots|POST /api/inventory/review|GET /api/order-book|GET /api/order-templates|POST /api/order-templates|GET /api/order-templates/:id|POST /api/order-templates/:id/update|POST /api/order-templates/:id/delete|GET /api/people-count|POST /api/people-count|GET /api/people-count-history|GET /api/daily-funds|POST /api/daily-funds/confirm|GET /api/reimbursement-funding-options|GET /api/reimbursements|POST /api/reimbursements|POST /api/reimbursements/:id/update|POST /api/reimbursements/:id/approve|POST /api/reimbursements/:id/reject|GET /api/returned-stock-lots|GET /api/paper-number|GET /api/orders/:id/after-sale|POST /api/orders/:id/after-sale-preview|GET /api/orders/:id|GET /api/orders/:id/public|GET /api/orders/:id/edit|GET /api/orders/:id/change|GET /api/orders/:id/ownership|GET /api/orders/:id/cancellation|POST /api/orders/issue|POST /api/orders|POST /api/orders/:id/edit|POST /api/orders/:id/change|POST /api/orders/:id/ownership|POST /api/orders/:id/cancellation|POST /api/orders/:id/canceltoday|POST /api/orders/:id/confirm|POST /api/orders/:id/receipt|POST /api/orders/:id/complete|POST /api/orders/:id/expense|POST /api/orders/:id/refund|POST /api/orders/:id/return|POST /api/orders/:id/fees|POST /api/orders/:id/cost|POST /api/orders/:id/settlement|POST /api/orders/:id/correct|POST /api/orders/:id/material|GET /print/recoveries/:id|GET /print/:id|GET /api/report|GET /api/export/inventory|POST /api/backup|GET /api/backup/:file|POST /api/sync|POST /api/stock|POST /api/close|POST /api/password|GET /(static assets)`.split(
'|',
);
const hits = new Map();
for (const e of transcript.filter(e => e.method)) {
let key = e.method + ' ' + template(e.path);
if (e.method === 'GET' && /^\/[\w.-]*$/.test(e.path) && !e.path.startsWith('/api')) key = 'GET /(static assets)';
const ok = e.status < 400;
const h = hits.get(key) || { ok: 0, err: 0 };
h[ok ? 'ok' : 'err']++;
hits.set(key, h);
}
const covered = ROUTES.filter(r => hits.has(r)),
success = ROUTES.filter(r => hits.get(r)?.ok);
console.log(
`路由清单 ${ROUTES.length} 条;被请求 ${covered.length} 条(${Math.round((covered.length / ROUTES.length) * 100)}%),其中有成功响应 ${success.length} 条(${Math.round((success.length / ROUTES.length) * 100)}%)。`,
);
console.log('\n未请求:\n ' + ROUTES.filter(r => !hits.has(r)).join('\n '));
console.log('\n只有错误响应(拒绝路径):\n ' + ROUTES.filter(r => hits.has(r) && !hits.get(r).ok).join('\n '));
const extra = [...hits.keys()].filter(k => !ROUTES.includes(k));
if (extra.length) console.log('\n清单外(多为故意的未知地址):\n ' + extra.join('\n '));
+101 -49
View File
@@ -6,63 +6,115 @@
// FAKE_CLOCK_TICK_MS 每次读取时钟后前进的毫秒数(默认 0:时钟只在控制端设置时变化)
// FAKE_RANDOM_SEED 随机种子(默认 golden-seed)
// FAKE_CLOCK_IPC=1 通过 process.send 通道接受 {type:'fake-clock',op,ms,id} 控制消息
const crypto=require('node:crypto');
const RealDate=Date;
let current=RealDate.parse(process.env.FAKE_CLOCK_START||'2026-11-20T02:00:00.000Z');
if(!Number.isFinite(current))throw new Error('FAKE_CLOCK_START 无效');
let tick=Number(process.env.FAKE_CLOCK_TICK_MS||0);
function read(){const value=current;current+=tick;return value;}
function FakeDate(...args){
if(!new.target)return new RealDate(read()).toString();
return Reflect.construct(RealDate,args.length?args:[read()],new.target);
const crypto = require('node:crypto');
const RealDate = Date;
let current = RealDate.parse(process.env.FAKE_CLOCK_START || '2026-11-20T02:00:00.000Z');
if (!Number.isFinite(current)) throw new Error('FAKE_CLOCK_START 无效');
let tick = Number(process.env.FAKE_CLOCK_TICK_MS || 0);
function read() {
const value = current;
current += tick;
return value;
}
Object.setPrototypeOf(FakeDate,RealDate);
FakeDate.prototype=RealDate.prototype;
FakeDate.now=()=>read();
FakeDate.parse=RealDate.parse;
FakeDate.UTC=RealDate.UTC;
Object.defineProperty(RealDate.prototype,'constructor',{value:FakeDate,writable:true,configurable:true});
globalThis.Date=FakeDate;
function FakeDate(...args) {
if (!new.target) return new RealDate(read()).toString();
return Reflect.construct(RealDate, args.length ? args : [read()], new.target);
}
Object.setPrototypeOf(FakeDate, RealDate);
FakeDate.prototype = RealDate.prototype;
FakeDate.now = () => read();
FakeDate.parse = RealDate.parse;
FakeDate.UTC = RealDate.UTC;
Object.defineProperty(RealDate.prototype, 'constructor', { value: FakeDate, writable: true, configurable: true });
globalThis.Date = FakeDate;
// 计数器式 SHA-256 流,按调用顺序输出确定字节。
const seed=process.env.FAKE_RANDOM_SEED||'golden-seed';
let counter=0,pool=Buffer.alloc(0);
function bytes(n){
while(pool.length<n){const block=crypto.createHash('sha256').update(seed+':'+(counter++)).digest();pool=Buffer.concat([pool,block]);}
const out=Buffer.from(pool.subarray(0,n));pool=pool.subarray(n);return out;
}
function randomBytes(size,callback){
const out=bytes(size);
if(typeof callback==='function'){process.nextTick(callback,null,out);return;}
const seed = process.env.FAKE_RANDOM_SEED || 'golden-seed';
let counter = 0,
pool = Buffer.alloc(0);
function bytes(n) {
while (pool.length < n) {
const block = crypto
.createHash('sha256')
.update(seed + ':' + counter++)
.digest();
pool = Buffer.concat([pool, block]);
}
const out = Buffer.from(pool.subarray(0, n));
pool = pool.subarray(n);
return out;
}
function randomUUID(){
const b=bytes(16);b[6]=(b[6]&0x0f)|0x40;b[8]=(b[8]&0x3f)|0x80;const h=b.toString('hex');
return h.slice(0,8)+'-'+h.slice(8,12)+'-'+h.slice(12,16)+'-'+h.slice(16,20)+'-'+h.slice(20);
function randomBytes(size, callback) {
const out = bytes(size);
if (typeof callback === 'function') {
process.nextTick(callback, null, out);
return;
}
return out;
}
function getRandomValues(array){const b=bytes(array.byteLength);new Uint8Array(array.buffer,array.byteOffset,array.byteLength).set(b);return array;}
function randomFillSync(buffer,offset=0,size){const view=new Uint8Array(buffer.buffer||buffer,buffer.byteOffset||0,buffer.byteLength);const end=size===undefined?view.length:offset+size;view.set(bytes(end-offset),offset);return buffer;}
for(const [name,fn] of Object.entries({randomBytes,randomUUID,getRandomValues,randomFillSync})){try{Object.defineProperty(crypto,name,{value:fn,writable:true,configurable:true,enumerable:true});}catch{try{crypto[name]=fn;}catch{}}}
if(crypto.randomUUID!==randomUUID||crypto.randomBytes!==randomBytes)throw new Error('无法固定 crypto 随机源');
try{Object.defineProperty(globalThis.crypto,'randomUUID',{value:randomUUID,configurable:true,writable:true});Object.defineProperty(globalThis.crypto,'getRandomValues',{value:getRandomValues,configurable:true,writable:true});}catch{}
Math.random=()=>bytes(6).readUIntBE(0,6)/2**48;
function randomUUID() {
const b = bytes(16);
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
const h = b.toString('hex');
return h.slice(0, 8) + '-' + h.slice(8, 12) + '-' + h.slice(12, 16) + '-' + h.slice(16, 20) + '-' + h.slice(20);
}
function getRandomValues(array) {
const b = bytes(array.byteLength);
new Uint8Array(array.buffer, array.byteOffset, array.byteLength).set(b);
return array;
}
function randomFillSync(buffer, offset = 0, size) {
const view = new Uint8Array(buffer.buffer || buffer, buffer.byteOffset || 0, buffer.byteLength);
const end = size === undefined ? view.length : offset + size;
view.set(bytes(end - offset), offset);
return buffer;
}
for (const [name, fn] of Object.entries({ randomBytes, randomUUID, getRandomValues, randomFillSync })) {
try {
Object.defineProperty(crypto, name, { value: fn, writable: true, configurable: true, enumerable: true });
} catch {
try {
crypto[name] = fn;
} catch {}
}
}
if (crypto.randomUUID !== randomUUID || crypto.randomBytes !== randomBytes) throw new Error('无法固定 crypto 随机源');
try {
Object.defineProperty(globalThis.crypto, 'randomUUID', { value: randomUUID, configurable: true, writable: true });
Object.defineProperty(globalThis.crypto, 'getRandomValues', {
value: getRandomValues,
configurable: true,
writable: true,
});
} catch {}
Math.random = () => bytes(6).readUIntBE(0, 6) / 2 ** 48;
const control={
now:()=>current,
set(ms){if(!Number.isFinite(ms))throw new Error('无效时刻');current=ms;},
advance(ms){current+=ms;},
setTick(ms){tick=ms;},
const control = {
now: () => current,
set(ms) {
if (!Number.isFinite(ms)) throw new Error('无效时刻');
current = ms;
},
advance(ms) {
current += ms;
},
setTick(ms) {
tick = ms;
},
RealDate,
};
globalThis.__fakeClock=control;
if(process.env.FAKE_CLOCK_IPC==='1'&&typeof process.send==='function'){
process.on('message',message=>{
if(!message||message.type!=='fake-clock')return;
try{
if(message.op==='set')control.set(message.ms);
else if(message.op==='advance')control.advance(message.ms);
else if(message.op==='tick')control.setTick(message.ms);
process.send({type:'fake-clock-ack',id:message.id,now:current});
}catch(error){process.send({type:'fake-clock-ack',id:message.id,error:error.message});}
globalThis.__fakeClock = control;
if (process.env.FAKE_CLOCK_IPC === '1' && typeof process.send === 'function') {
process.on('message', message => {
if (!message || message.type !== 'fake-clock') return;
try {
if (message.op === 'set') control.set(message.ms);
else if (message.op === 'advance') control.advance(message.ms);
else if (message.op === 'tick') control.setTick(message.ms);
process.send({ type: 'fake-clock-ack', id: message.id, now: current });
} catch (error) {
process.send({ type: 'fake-clock-ack', id: message.id, error: error.message });
}
});
}
File diff suppressed because it is too large. Load diff
+115 -51
View File
@@ -5,61 +5,125 @@
// node e2e/golden.js 录制并写入 e2e/baseline/golden/(若场景出现非预期状态码则拒绝写入,除非 --force)
// node e2e/golden.js --check 重新运行并与基线比较,打印前 N 处差异(--limit N,默认 30),有差异则退出码 1
// node e2e/golden.js --print 只运行并把结果写到 e2e/out/golden/,不比较
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {startServer}=require('./lib/server');
const {Session}=require('./lib/client');
const {Normalizer}=require('./lib/normalize');
const {dumpDatabase}=require('./lib/db-dump');
const {compare,report}=require('./lib/diff');
const scenario=require('./golden-scenario');
const args=process.argv.slice(2),check=args.includes('--check'),printOnly=args.includes('--print'),force=args.includes('--force');
const limit=Number(args[args.indexOf('--limit')+1])||30;
const BASELINE=path.join(__dirname,'baseline','golden'),OUT=path.join(__dirname,'out','golden');
const MASKED='<masked>';
async function run(){
const dataDir=fs.mkdtempSync(path.join(os.tmpdir(),'ledger-golden-'));
const server=startServer({mode:'trial',dataDir,clockStart:scenario.START+'T02:00:00.000Z',seed:'golden-seed'});
const fs = require('node:fs'),
os = require('node:os'),
path = require('node:path');
const { startServer } = require('./lib/server');
const { Session } = require('./lib/client');
const { Normalizer } = require('./lib/normalize');
const { dumpDatabase } = require('./lib/db-dump');
const { compare, report } = require('./lib/diff');
const scenario = require('./golden-scenario');
const args = process.argv.slice(2),
check = args.includes('--check'),
printOnly = args.includes('--print'),
force = args.includes('--force');
const limit = Number(args[args.indexOf('--limit') + 1]) || 30;
const BASELINE = path.join(__dirname, 'baseline', 'golden'),
OUT = path.join(__dirname, 'out', 'golden');
const MASKED = '<masked>';
async function run() {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ledger-golden-'));
const server = startServer({
mode: 'trial',
dataDir,
clockStart: scenario.START + 'T02:00:00.000Z',
seed: 'golden-seed',
});
let session;
try{
const info=await server.ready();
session=new Session({base:info.base,server});
try {
const info = await server.ready();
session = new Session({ base: info.base, server });
await scenario.run(session);
}catch(error){
if(session){fs.mkdirSync(OUT,{recursive:true});fs.writeFileSync(path.join(OUT,'partial-transcript.json'),JSON.stringify(session.entries,null,1));}
if(session?.problems.length)console.error('崩溃前的非预期状态:\n'+session.problems.join('\n'));
error.message+='\n'+server.output();throw error;
}finally{await server.stop();}
const dump=dumpDatabase(path.join(dataDir,'ledger.sqlite'),{mask:{users:{salt:()=>MASKED,hash:()=>MASKED},sessions:{hash:()=>MASKED}}});
fs.rmSync(dataDir,{recursive:true,force:true});
const n=new Normalizer();n.literal(session.base,'http://<host>');n.literal(session.base.slice(7),'<host>');for(const token of session.secrets)n.secret(token);
} catch (error) {
if (session) {
fs.mkdirSync(OUT, { recursive: true });
fs.writeFileSync(path.join(OUT, 'partial-transcript.json'), JSON.stringify(session.entries, null, 1));
}
if (session?.problems.length) console.error('崩溃前的非预期状态:\n' + session.problems.join('\n'));
error.message += '\n' + server.output();
throw error;
} finally {
await server.stop();
}
const dump = dumpDatabase(path.join(dataDir, 'ledger.sqlite'), {
mask: { users: { salt: () => MASKED, hash: () => MASKED }, sessions: { hash: () => MASKED } },
});
fs.rmSync(dataDir, { recursive: true, force: true });
const n = new Normalizer();
n.literal(session.base, 'http://<host>');
n.literal(session.base.slice(7), '<host>');
for (const token of session.secrets) n.secret(token);
// 先按请求顺序规范化,再规范化数据库,使占位符编号由业务发生顺序决定。
// JSON 往返,去掉 undefined 字段,使内存结果与落盘基线同形。
const transcript=JSON.parse(JSON.stringify(session.entries.map(e=>n.value(e))));
const db=JSON.parse(JSON.stringify(n.value(dump)));
return {transcript,db,problems:session.problems};
const transcript = JSON.parse(JSON.stringify(session.entries.map(e => n.value(e))));
const db = JSON.parse(JSON.stringify(n.value(dump)));
return { transcript, db, problems: session.problems };
}
function write(dir,result){
fs.mkdirSync(dir,{recursive:true});fs.rmSync(path.join(OUT,'partial-transcript.json'),{force:true});
fs.writeFileSync(path.join(dir,'transcript.json'),JSON.stringify(result.transcript,null,1)+'\n');
fs.writeFileSync(path.join(dir,'db.json'),JSON.stringify(result.db,null,1)+'\n');
function write(dir, result) {
fs.mkdirSync(dir, { recursive: true });
fs.rmSync(path.join(OUT, 'partial-transcript.json'), { force: true });
fs.writeFileSync(path.join(dir, 'transcript.json'), JSON.stringify(result.transcript, null, 1) + '\n');
fs.writeFileSync(path.join(dir, 'db.json'), JSON.stringify(result.db, null, 1) + '\n');
}
function describeTranscript(transcript){return p=>{const m=p.match(/^\$\[(\d+)\]/);if(!m)return p;const e=transcript[Number(m[1])];return e?`${p} 〔#${e.seq} ${e.actor||''} ${e.method||e.note||''} ${e.path||''}${e.label?' · '+e.label:''}〕`:p;};}
(async()=>{
const started=Date.now();const result=await run();
const seconds=((Date.now()-started)/1000).toFixed(1);
if(result.problems.length){console.error('场景中出现非预期状态码:\n'+result.problems.join('\n'));}
if(check){
write(OUT,result);
const expected={transcript:JSON.parse(fs.readFileSync(path.join(BASELINE,'transcript.json'),'utf8')),db:JSON.parse(fs.readFileSync(path.join(BASELINE,'db.json'),'utf8'))};
const t=compare(expected.transcript,result.transcript),d=compare(expected.db,result.db);
const describeDb=p=>{const m=p.match(/^\$\.tables\.([^.]+)\.rows\[(\d+)\]\[(\d+)\](.*)$/);if(!m)return p;const cols=expected.db.tables[m[1]]?.columns;return `表 ${m[1]} 第 ${Number(m[2])+1} 行 列 ${cols?.[Number(m[3])]??m[3]}${m[4]}`;};
const text=[report('请求记录',t,limit,describeTranscript(expected.transcript)),report('数据库',d,limit,describeDb)].filter(Boolean).join('\n');
if(text)console.log(text);
const failed=t.diffs.length+d.diffs.length>0;
console.log(`golden ${failed?'FAIL':'PASS'}:${result.transcript.length} 条记录,${Object.keys(result.db.tables).length} 张表,用时 ${seconds}s(实际结果在 e2e/out/golden/)`);
process.exit(failed?1:0);
function describeTranscript(transcript) {
return p => {
const m = p.match(/^\$\[(\d+)\]/);
if (!m) return p;
const e = transcript[Number(m[1])];
return e
? `${p} 〔#${e.seq} ${e.actor || ''} ${e.method || e.note || ''} ${e.path || ''}${e.label ? ' · ' + e.label : ''}〕`
: p;
};
}
(async () => {
const started = Date.now();
const result = await run();
const seconds = ((Date.now() - started) / 1000).toFixed(1);
if (result.problems.length) {
console.error('场景中出现非预期状态码:\n' + result.problems.join('\n'));
}
if(printOnly){write(OUT,result);console.log(`已写入 e2e/out/golden/(${result.transcript.length} 条记录,用时 ${seconds}s)`);process.exit(result.problems.length?1:0);}
if(result.problems.length&&!force){console.error('拒绝写入基线:请先修正场景或使用 --force');process.exit(1);}
write(BASELINE,result);console.log(`基线已写入 e2e/baseline/golden/(${result.transcript.length} 条记录,${Object.keys(result.db.tables).length} 张表,用时 ${seconds}s)`);
})().catch(error=>{console.error(error.stack||error);process.exit(2);});
if (check) {
write(OUT, result);
const expected = {
transcript: JSON.parse(fs.readFileSync(path.join(BASELINE, 'transcript.json'), 'utf8')),
db: JSON.parse(fs.readFileSync(path.join(BASELINE, 'db.json'), 'utf8')),
};
const t = compare(expected.transcript, result.transcript),
d = compare(expected.db, result.db);
const describeDb = p => {
const m = p.match(/^\$\.tables\.([^.]+)\.rows\[(\d+)\]\[(\d+)\](.*)$/);
if (!m) return p;
const cols = expected.db.tables[m[1]]?.columns;
return `表 ${m[1]} 第 ${Number(m[2]) + 1} 行 列 ${cols?.[Number(m[3])] ?? m[3]}${m[4]}`;
};
const text = [
report('请求记录', t, limit, describeTranscript(expected.transcript)),
report('数据库', d, limit, describeDb),
]
.filter(Boolean)
.join('\n');
if (text) console.log(text);
const failed = t.diffs.length + d.diffs.length > 0;
console.log(
`golden ${failed ? 'FAIL' : 'PASS'}:${result.transcript.length} 条记录,${Object.keys(result.db.tables).length} 张表,用时 ${seconds}s(实际结果在 e2e/out/golden/)`,
);
process.exit(failed ? 1 : 0);
}
if (printOnly) {
write(OUT, result);
console.log(`已写入 e2e/out/golden/(${result.transcript.length} 条记录,用时 ${seconds}s)`);
process.exit(result.problems.length ? 1 : 0);
}
if (result.problems.length && !force) {
console.error('拒绝写入基线:请先修正场景或使用 --force');
process.exit(1);
}
write(BASELINE, result);
console.log(
`基线已写入 e2e/baseline/golden/(${result.transcript.length} 条记录,${Object.keys(result.db.tables).length} 张表,用时 ${seconds}s)`,
);
})().catch(error => {
console.error(error.stack || error);
process.exit(2);
});
+200 -83
View File
@@ -5,94 +5,211 @@
// 以三个成员身份读取主要接口,记录完整性、结构、行数、原始列内容哈希和规范化响应哈希。
// 基线只含计数与哈希,不含任何客户名称或金额。
// 用法:node e2e/legacy-db.js [--check] [--fixture <path>]
const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');
const {DatabaseSync}=require('node:sqlite');
const {startServer}=require('./lib/server');
const {Session}=require('./lib/client');
const {Normalizer}=require('./lib/normalize');
const {compare,report}=require('./lib/diff');
const args=process.argv.slice(2),check=args.includes('--check');
const FIXTURE=args.includes('--fixture')?args[args.indexOf('--fixture')+1]:'/tmp/refactor-fixtures/demo-ledger.sqlite';
const BASELINE=path.join(__dirname,'baseline','legacy.json');
const CLOCK='2026-12-05T02:00:00.000Z',TODAY='2026-12-05';
const sha=value=>crypto.createHash('sha256').update(value).digest('hex');
function cell(v){return v instanceof Uint8Array?{blob:Buffer.from(v).toString('hex')}:typeof v==='bigint'?{bigint:v.toString()}:v;}
function inspect(file,originalColumns=null){
const db=new DatabaseSync(file,{readOnly:true});
try{
const integrity=db.prepare('PRAGMA integrity_check').all().map(r=>r.integrity_check);
const tables=db.prepare("SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name").all();
const schema={},counts={},hashes={};
for(const {name,sql} of tables){
const q=`"${name.replace(/"/g,'""')}"`;
const columns=db.prepare(`PRAGMA table_info(${q})`).all().map(c=>({name:c.name,type:c.type,notnull:c.notnull,pk:c.pk,dflt:c.dflt_value}));
const indexes=db.prepare(`PRAGMA index_list(${q})`).all().filter(i=>!i.name.startsWith('sqlite_autoindex_')).map(i=>({name:i.name,unique:i.unique,columns:db.prepare(`PRAGMA index_info("${i.name.replace(/"/g,'""')}")`).all().map(c=>c.name)})).sort((a,b)=>a.name<b.name?-1:1);
schema[name]={columns,indexes,withoutRowid:/WITHOUT\s+ROWID/i.test(sql||'')};
counts[name]=db.prepare(`SELECT COUNT(*) AS n FROM ${q}`).get().n;
// 只对“原始列”求内容哈希:升级新增的列不影响对照,原有列的任何改动都会被发现。
const cols=(originalColumns?.[name]??columns.map(c=>c.name)).filter(c=>columns.some(x=>x.name===c));
if(originalColumns&&!originalColumns[name])continue;
const order=schema[name].withoutRowid?cols.map((_,i)=>i+1).join(','):'rowid';
const rows=cols.length?db.prepare(`SELECT ${cols.map(c=>`"${c.replace(/"/g,'""')}"`).join(',')} FROM ${q} ORDER BY ${order}`).all().map(r=>cols.map(c=>cell(r[c]))):[];
hashes[name]=sha(JSON.stringify({cols,rows}));
}
return {integrity,schema,counts,hashes};
}finally{db.close();}
const fs = require('node:fs'),
os = require('node:os'),
path = require('node:path'),
crypto = require('node:crypto');
const { DatabaseSync } = require('node:sqlite');
const { startServer } = require('./lib/server');
const { Session } = require('./lib/client');
const { Normalizer } = require('./lib/normalize');
const { compare, report } = require('./lib/diff');
const args = process.argv.slice(2),
check = args.includes('--check');
const FIXTURE = args.includes('--fixture')
? args[args.indexOf('--fixture') + 1]
: '/tmp/refactor-fixtures/demo-ledger.sqlite';
const BASELINE = path.join(__dirname, 'baseline', 'legacy.json');
const CLOCK = '2026-12-05T02:00:00.000Z',
TODAY = '2026-12-05';
const sha = value => crypto.createHash('sha256').update(value).digest('hex');
function cell(v) {
return v instanceof Uint8Array
? { blob: Buffer.from(v).toString('hex') }
: typeof v === 'bigint'
? { bigint: v.toString() }
: v;
}
const READS=[
'/api/session','/api/state',`/api/order-book?from=2000-01-01&date=${TODAY}`,`/api/report?from=2000-01-01&date=${TODAY}&basis=orderDate`,`/api/report?date=${TODAY}`,
'/api/inventory','/api/inventory/movements','/api/inventory/snapshots','/api/material-pools','/api/price-locks?status=all','/api/recoveries','/api/customer-materials',
`/api/team-funds?date=${TODAY}`,'/api/team-profits',`/api/daily-funds?date=${TODAY}`,'/api/shop-settings','/api/pockets','/api/order-templates','/api/reimbursements',
'/api/order-changes?status=all','/api/order-cancellations?status=all','/api/inventory/changes?status=all','/api/employees','/api/people-count-history',
function inspect(file, originalColumns = null) {
const db = new DatabaseSync(file, { readOnly: true });
try {
const integrity = db
.prepare('PRAGMA integrity_check')
.all()
.map(r => r.integrity_check);
const tables = db.prepare("SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name").all();
const schema = {},
counts = {},
hashes = {};
for (const { name, sql } of tables) {
const q = `"${name.replace(/"/g, '""')}"`;
const columns = db
.prepare(`PRAGMA table_info(${q})`)
.all()
.map(c => ({ name: c.name, type: c.type, notnull: c.notnull, pk: c.pk, dflt: c.dflt_value }));
const indexes = db
.prepare(`PRAGMA index_list(${q})`)
.all()
.filter(i => !i.name.startsWith('sqlite_autoindex_'))
.map(i => ({
name: i.name,
unique: i.unique,
columns: db
.prepare(`PRAGMA index_info("${i.name.replace(/"/g, '""')}")`)
.all()
.map(c => c.name),
}))
.sort((a, b) => (a.name < b.name ? -1 : 1));
schema[name] = { columns, indexes, withoutRowid: /WITHOUT\s+ROWID/i.test(sql || '') };
counts[name] = db.prepare(`SELECT COUNT(*) AS n FROM ${q}`).get().n;
// 只对“原始列”求内容哈希:升级新增的列不影响对照,原有列的任何改动都会被发现。
const cols = (originalColumns?.[name] ?? columns.map(c => c.name)).filter(c => columns.some(x => x.name === c));
if (originalColumns && !originalColumns[name]) continue;
const order = schema[name].withoutRowid ? cols.map((_, i) => i + 1).join(',') : 'rowid';
const rows = cols.length
? db
.prepare(`SELECT ${cols.map(c => `"${c.replace(/"/g, '""')}"`).join(',')} FROM ${q} ORDER BY ${order}`)
.all()
.map(r => cols.map(c => cell(r[c])))
: [];
hashes[name] = sha(JSON.stringify({ cols, rows }));
}
return { integrity, schema, counts, hashes };
} finally {
db.close();
}
}
const READS = [
'/api/session',
'/api/state',
`/api/order-book?from=2000-01-01&date=${TODAY}`,
`/api/report?from=2000-01-01&date=${TODAY}&basis=orderDate`,
`/api/report?date=${TODAY}`,
'/api/inventory',
'/api/inventory/movements',
'/api/inventory/snapshots',
'/api/material-pools',
'/api/price-locks?status=all',
'/api/recoveries',
'/api/customer-materials',
`/api/team-funds?date=${TODAY}`,
'/api/team-profits',
`/api/daily-funds?date=${TODAY}`,
'/api/shop-settings',
'/api/pockets',
'/api/order-templates',
'/api/reimbursements',
'/api/order-changes?status=all',
'/api/order-cancellations?status=all',
'/api/inventory/changes?status=all',
'/api/employees',
'/api/people-count-history',
];
async function run(){
if(!fs.existsSync(FIXTURE))throw new Error('找不到旧库快照:'+FIXTURE);
const dataDir=fs.mkdtempSync(path.join(os.tmpdir(),'ledger-legacy-'));
try{
const file=path.join(dataDir,'ledger.sqlite');fs.copyFileSync(FIXTURE,file);fs.chmodSync(file,0o600);
const before=inspect(file);
const originalColumns=Object.fromEntries(Object.entries(before.schema).map(([t,s])=>[t,s.columns.map(c=>c.name)]));
const server=startServer({mode:'demo',dataDir,startup:'production',clockStart:CLOCK,seed:'legacy-seed'});
const responses={};let startup;
try{
const info=await server.ready();startup=info.startup;
const s=new Session({base:info.base,server});await s.day(TODAY);
const n=new Normalizer();n.literal(info.base,'http://<host>');n.literal(info.base.slice(7),'<host>');
for(const [role,body] of [['owner',{role:'owner'}],['assistant',{role:'assistant'}],['assistant2',{member:'assistant2'}]]){
const login=await s.request(role,'POST','/api/demo-login',{body,expect:'any'});
responses[role]={login:login.status};
for(const route of READS){
const r=await s.request(role,'GET',route,{expect:'any'});
const normalized=n.value(r.body);
responses[role][route]={status:r.status,hash:sha(JSON.stringify(normalized)),keys:normalized&&typeof normalized==='object'&&!Array.isArray(normalized)?Object.keys(normalized).length:null};
async function run() {
if (!fs.existsSync(FIXTURE)) throw new Error('找不到旧库快照:' + FIXTURE);
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ledger-legacy-'));
try {
const file = path.join(dataDir, 'ledger.sqlite');
fs.copyFileSync(FIXTURE, file);
fs.chmodSync(file, 0o600);
const before = inspect(file);
const originalColumns = Object.fromEntries(
Object.entries(before.schema).map(([t, s]) => [t, s.columns.map(c => c.name)]),
);
const server = startServer({
mode: 'demo',
dataDir,
startup: 'production',
clockStart: CLOCK,
seed: 'legacy-seed',
});
const responses = {};
let startup;
try {
const info = await server.ready();
startup = info.startup;
const s = new Session({ base: info.base, server });
await s.day(TODAY);
const n = new Normalizer();
n.literal(info.base, 'http://<host>');
n.literal(info.base.slice(7), '<host>');
for (const [role, body] of [
['owner', { role: 'owner' }],
['assistant', { role: 'assistant' }],
['assistant2', { member: 'assistant2' }],
]) {
const login = await s.request(role, 'POST', '/api/demo-login', { body, expect: 'any' });
responses[role] = { login: login.status };
for (const route of READS) {
const r = await s.request(role, 'GET', route, { expect: 'any' });
const normalized = n.value(r.body);
responses[role][route] = {
status: r.status,
hash: sha(JSON.stringify(normalized)),
keys:
normalized && typeof normalized === 'object' && !Array.isArray(normalized)
? Object.keys(normalized).length
: null,
};
}
}
}finally{await server.stop();}
const after=inspect(file,originalColumns);const afterAll=inspect(file);
const backups=fs.existsSync(path.join(dataDir,'backups'))?fs.readdirSync(path.join(dataDir,'backups')).length:0;
} finally {
await server.stop();
}
const after = inspect(file, originalColumns);
const afterAll = inspect(file);
const backups = fs.existsSync(path.join(dataDir, 'backups'))
? fs.readdirSync(path.join(dataDir, 'backups')).length
: 0;
return {
fixture:{sha256:sha(fs.readFileSync(FIXTURE)),bytes:fs.statSync(FIXTURE).size},
startup:{teamBackupRequired:startup?.team?.required??null,migrationChanged:startup?.migration?.changed??null,backupFiles:backups},
before:{integrity:before.integrity,schema:before.schema,counts:before.counts,hashes:before.hashes},
after:{integrity:after.integrity,schema:afterAll.schema,counts:afterAll.counts,originalColumnHashes:after.hashes},
unchangedOriginalTables:Object.keys(before.hashes).filter(t=>before.hashes[t]===after.hashes[t]).length,
changedOriginalTables:Object.keys(before.hashes).filter(t=>before.hashes[t]!==after.hashes[t]),
fixture: { sha256: sha(fs.readFileSync(FIXTURE)), bytes: fs.statSync(FIXTURE).size },
startup: {
teamBackupRequired: startup?.team?.required ?? null,
migrationChanged: startup?.migration?.changed ?? null,
backupFiles: backups,
},
before: { integrity: before.integrity, schema: before.schema, counts: before.counts, hashes: before.hashes },
after: {
integrity: after.integrity,
schema: afterAll.schema,
counts: afterAll.counts,
originalColumnHashes: after.hashes,
},
unchangedOriginalTables: Object.keys(before.hashes).filter(t => before.hashes[t] === after.hashes[t]).length,
changedOriginalTables: Object.keys(before.hashes).filter(t => before.hashes[t] !== after.hashes[t]),
responses,
};
}finally{fs.rmSync(dataDir,{recursive:true,force:true});}
}
(async()=>{
const started=Date.now();const result=await run();const seconds=((Date.now()-started)/1000).toFixed(1);
const integrityOk=result.before.integrity.join()==='ok'&&result.after.integrity.join()==='ok';
if(check){
const expected=JSON.parse(fs.readFileSync(BASELINE,'utf8'));
const d=compare(expected,JSON.parse(JSON.stringify(result)));const text=report('旧库兼容',d);if(text)console.log(text);
const failed=d.diffs.length>0||!integrityOk;
if(!integrityOk)console.log('完整性检查失败:',result.before.integrity,result.after.integrity);
console.log(`legacy ${failed?'FAIL':'PASS'}:${Object.keys(result.after.counts).length} 张表,${result.unchangedOriginalTables} 张原表内容未变,用时 ${seconds}s`);
process.exit(failed?1:0);
} finally {
fs.rmSync(dataDir, { recursive: true, force: true });
}
if(!integrityOk){console.error('完整性检查失败,拒绝写入基线');process.exit(1);}
fs.mkdirSync(path.dirname(BASELINE),{recursive:true});fs.writeFileSync(BASELINE,JSON.stringify(result,null,1)+'\n');
console.log(`基线已写入 e2e/baseline/legacy.json(${Object.keys(result.after.counts).length} 张表,原表内容变化:${result.changedOriginalTables.join('、')||'无'},用时 ${seconds}s)`);
})().catch(error=>{console.error(error.stack||error);process.exit(2);});
}
(async () => {
const started = Date.now();
const result = await run();
const seconds = ((Date.now() - started) / 1000).toFixed(1);
const integrityOk = result.before.integrity.join() === 'ok' && result.after.integrity.join() === 'ok';
if (check) {
const expected = JSON.parse(fs.readFileSync(BASELINE, 'utf8'));
const d = compare(expected, JSON.parse(JSON.stringify(result)));
const text = report('旧库兼容', d);
if (text) console.log(text);
const failed = d.diffs.length > 0 || !integrityOk;
if (!integrityOk) console.log('完整性检查失败:', result.before.integrity, result.after.integrity);
console.log(
`legacy ${failed ? 'FAIL' : 'PASS'}:${Object.keys(result.after.counts).length} 张表,${result.unchangedOriginalTables} 张原表内容未变,用时 ${seconds}s`,
);
process.exit(failed ? 1 : 0);
}
if (!integrityOk) {
console.error('完整性检查失败,拒绝写入基线');
process.exit(1);
}
fs.mkdirSync(path.dirname(BASELINE), { recursive: true });
fs.writeFileSync(BASELINE, JSON.stringify(result, null, 1) + '\n');
console.log(
`基线已写入 e2e/baseline/legacy.json(${Object.keys(result.after.counts).length} 张表,原表内容变化:${result.changedOriginalTables.join('、') || '无'},用时 ${seconds}s)`,
);
})().catch(error => {
console.error(error.stack || error);
process.exit(2);
});
+132 -48
View File
@@ -1,60 +1,144 @@
'use strict';
// HTTP 驱动与记录器:每次请求前把子进程时钟设为“当天起点 + 步数秒”,保证时间戳只取决于步骤顺序。
const {unzip}=require('./zip');
const SHANGHAI_OFFSET=8*3600*1000;
class Session{
constructor({base,server,startDate,startHour=10}){
this.base=base;this.server=server;this.cookies={};this.users={};this.entries=[];this.seq=0;this.keySeq=0;this.problems=[];this.secrets=[];
this.dayStart=null;this.stepInDay=0;this.startHour=startHour;this.date=null;if(startDate)this.pendingDay=startDate;
const { unzip } = require('./zip');
const SHANGHAI_OFFSET = 8 * 3600 * 1000;
class Session {
constructor({ base, server, startDate, startHour = 10 }) {
this.base = base;
this.server = server;
this.cookies = {};
this.users = {};
this.entries = [];
this.seq = 0;
this.keySeq = 0;
this.problems = [];
this.secrets = [];
this.dayStart = null;
this.stepInDay = 0;
this.startHour = startHour;
this.date = null;
if (startDate) this.pendingDay = startDate;
}
// 把业务“今天”切换到上海时区某日的 startHour 点,之后每次请求前进 1 秒。
async day(date,hour=this.startHour){
this.date=date;this.dayStart=Date.parse(date+'T00:00:00Z')-SHANGHAI_OFFSET+hour*3600*1000;this.stepInDay=0;
await this.server.setTime(this.dayStart);this.note('clock',{date,hour});
async day(date, hour = this.startHour) {
this.date = date;
this.dayStart = Date.parse(date + 'T00:00:00Z') - SHANGHAI_OFFSET + hour * 3600 * 1000;
this.stepInDay = 0;
await this.server.setTime(this.dayStart);
this.note('clock', { date, hour });
}
note(kind, data) {
this.entries.push({ seq: ++this.seq, note: kind, ...data });
}
key(label = 'op') {
this.keySeq++;
return (
'golden-' +
String(this.keySeq).padStart(5, '0') +
'-' +
String(label)
.replace(/[^A-Za-z0-9_-]/g, '')
.slice(0, 40)
).padEnd(16, '0');
}
async tickClock() {
this.stepInDay++;
await this.server.setTime(this.dayStart + this.stepInDay * 1000);
}
note(kind,data){this.entries.push({seq:++this.seq,note:kind,...data});}
key(label='op'){this.keySeq++;return ('golden-'+String(this.keySeq).padStart(5,'0')+'-'+String(label).replace(/[^A-Za-z0-9_-]/g,'').slice(0,40)).padEnd(16,'0');}
async tickClock(){this.stepInDay++;await this.server.setTime(this.dayStart+this.stepInDay*1000);}
// 通用请求。opts: {body, key, headers, noOrigin, noXRW, origin, contentType, label, expect, record:'full'|'status'}
async request(actor,method,path,opts={}){
async request(actor, method, path, opts = {}) {
await this.tickClock();
const isPost=method==='POST';const headers={};
const cookie=actor&&this.cookies[actor];if(cookie)headers.Cookie=cookie;
let key=null;
if(isPost){
if(!opts.noOrigin)headers.Origin=opts.origin||this.base;
if(!opts.noXRW)headers['X-Requested-With']='maimai-ledger';
headers['Content-Type']=opts.contentType||'application/json';
key=opts.key===undefined?this.key(opts.label||path.split('/').filter(Boolean).slice(-1)[0]):opts.key;
if(key!==null)headers['Idempotency-Key']=key;
const isPost = method === 'POST';
const headers = {};
const cookie = actor && this.cookies[actor];
if (cookie) headers.Cookie = cookie;
let key = null;
if (isPost) {
if (!opts.noOrigin) headers.Origin = opts.origin || this.base;
if (!opts.noXRW) headers['X-Requested-With'] = 'maimai-ledger';
headers['Content-Type'] = opts.contentType || 'application/json';
key = opts.key === undefined ? this.key(opts.label || path.split('/').filter(Boolean).slice(-1)[0]) : opts.key;
if (key !== null) headers['Idempotency-Key'] = key;
}
Object.assign(headers,opts.headers||{});
const response=await fetch(this.base+path,{method,headers,...(isPost?{body:typeof opts.body==='string'?opts.body:JSON.stringify(opts.body??{})}:{})});
const type=response.headers.get('content-type')||'';const buffer=Buffer.from(await response.arrayBuffer());
Object.assign(headers, opts.headers || {});
const response = await fetch(this.base + path, {
method,
headers,
...(isPost ? { body: typeof opts.body === 'string' ? opts.body : JSON.stringify(opts.body ?? {}) } : {}),
});
const type = response.headers.get('content-type') || '';
const buffer = Buffer.from(await response.arrayBuffer());
let body;
if(opts.record==='status')body={omitted:true,bytes:buffer.length>0};
else if(type.includes('application/json')){try{body=JSON.parse(buffer.toString('utf8'));}catch{body={invalidJson:buffer.toString('utf8')};}}
else if(type.includes('spreadsheetml')||type.includes('zip')){body={zip:unzip(buffer).map(f=>({name:f.name,text:f.data.toString('utf8')}))};}
else if(type.startsWith('text/'))body={text:buffer.toString('utf8')};
else body={binaryBytes:buffer.length};
const setCookie=response.headers.get('set-cookie');
if(setCookie&&actor){const token=setCookie.split(';')[0];if(/mm_session=[0-9a-f]+/.test(token)){this.cookies[actor]=token;this.secrets.push(token.slice(11));}else if(/mm_session=;/.test(setCookie+';'))delete this.cookies[actor];}
const entry={seq:++this.seq,label:opts.label||null,date:this.date,actor:actor||null,method,path,key,
request:isPost?{headers:{origin:headers.Origin??null,xrw:headers['X-Requested-With']??null,contentType:headers['Content-Type']},body:opts.body??{}}:undefined,
status:response.status,contentType:type,disposition:response.headers.get('content-disposition'),setCookie:setCookie?setCookie.replace(/mm_session=[0-9a-f]+/,'mm_session=<session>'):null,body};
this.entries.push(entry);
if(process.env.GOLDEN_PROBE&&isPost&&this.cookies.owner&&!this.probeFailed){
// 调试用:每次写入后以老板身份读取指定地址,报告第一次失败的步骤(不计入记录)。
const probe=await fetch(this.base+process.env.GOLDEN_PROBE,{headers:{Cookie:this.cookies.owner}});
if(probe.status!==200){this.probeFailed=true;console.error('探测失败于 #'+entry.seq,actor,method,path,opts.label,await probe.text());}
if (opts.record === 'status') body = { omitted: true, bytes: buffer.length > 0 };
else if (type.includes('application/json')) {
try {
body = JSON.parse(buffer.toString('utf8'));
} catch {
body = { invalidJson: buffer.toString('utf8') };
}
} else if (type.includes('spreadsheetml') || type.includes('zip')) {
body = { zip: unzip(buffer).map(f => ({ name: f.name, text: f.data.toString('utf8') })) };
} else if (type.startsWith('text/')) body = { text: buffer.toString('utf8') };
else body = { binaryBytes: buffer.length };
const setCookie = response.headers.get('set-cookie');
if (setCookie && actor) {
const token = setCookie.split(';')[0];
if (/mm_session=[0-9a-f]+/.test(token)) {
this.cookies[actor] = token;
this.secrets.push(token.slice(11));
} else if (/mm_session=;/.test(setCookie + ';')) delete this.cookies[actor];
}
const expect=opts.expect??200;
if(expect!=='any'&&!(Array.isArray(expect)?expect:[expect]).includes(response.status))this.problems.push(`#${entry.seq} ${actor} ${method} ${path} 期望 ${expect} 实际 ${response.status} ${JSON.stringify(body).slice(0,300)}`);
return {status:response.status,body,json:type.includes('json')?body:null,headers:response.headers};
const entry = {
seq: ++this.seq,
label: opts.label || null,
date: this.date,
actor: actor || null,
method,
path,
key,
request: isPost
? {
headers: {
origin: headers.Origin ?? null,
xrw: headers['X-Requested-With'] ?? null,
contentType: headers['Content-Type'],
},
body: opts.body ?? {},
}
: undefined,
status: response.status,
contentType: type,
disposition: response.headers.get('content-disposition'),
setCookie: setCookie ? setCookie.replace(/mm_session=[0-9a-f]+/, 'mm_session=<session>') : null,
body,
};
this.entries.push(entry);
if (process.env.GOLDEN_PROBE && isPost && this.cookies.owner && !this.probeFailed) {
// 调试用:每次写入后以老板身份读取指定地址,报告第一次失败的步骤(不计入记录)。
const probe = await fetch(this.base + process.env.GOLDEN_PROBE, { headers: { Cookie: this.cookies.owner } });
if (probe.status !== 200) {
this.probeFailed = true;
console.error('探测失败于 #' + entry.seq, actor, method, path, opts.label, await probe.text());
}
}
const expect = opts.expect ?? 200;
if (expect !== 'any' && !(Array.isArray(expect) ? expect : [expect]).includes(response.status))
this.problems.push(
`#${entry.seq} ${actor} ${method} ${path} 期望 ${expect} 实际 ${response.status} ${JSON.stringify(body).slice(0, 300)}`,
);
return { status: response.status, body, json: type.includes('json') ? body : null, headers: response.headers };
}
get(actor, path, opts) {
return this.request(actor, 'GET', path, opts).then(r => r.json ?? r.body);
}
getRaw(actor, path, opts) {
return this.request(actor, 'GET', path, opts);
}
post(actor, path, body, opts = {}) {
return this.request(actor, 'POST', path, { ...opts, body }).then(r => r.json ?? r.body);
}
postRaw(actor, path, body, opts = {}) {
return this.request(actor, 'POST', path, { ...opts, body });
}
get(actor,path,opts){return this.request(actor,'GET',path,opts).then(r=>r.json??r.body);}
getRaw(actor,path,opts){return this.request(actor,'GET',path,opts);}
post(actor,path,body,opts={}){return this.request(actor,'POST',path,{...opts,body}).then(r=>r.json??r.body);}
postRaw(actor,path,body,opts={}){return this.request(actor,'POST',path,{...opts,body});}
}
module.exports={Session};
module.exports = { Session };
+35 -20
View File
@@ -1,26 +1,41 @@
'use strict';
// 完整数据库转储:每张表的建表语句、列、索引,以及按 rowid 排序的全部行和全部列。
const {DatabaseSync}=require('node:sqlite');
function cell(value){
if(value instanceof Uint8Array)return {blob:Buffer.from(value).toString('hex')};
if(typeof value==='bigint')return {bigint:value.toString()};
const { DatabaseSync } = require('node:sqlite');
function cell(value) {
if (value instanceof Uint8Array) return { blob: Buffer.from(value).toString('hex') };
if (typeof value === 'bigint') return { bigint: value.toString() };
return value;
}
function dumpDatabase(filename,{mask={}}={}){
const db=new DatabaseSync(filename,{readOnly:true});
try{
const master=db.prepare("SELECT type,name,tbl_name,sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_autoindex_%' ORDER BY type,name").all();
const tables={};
for(const {name,sql} of master.filter(row=>row.type==='table')){
const columns=db.prepare(`PRAGMA table_info("${name.replace(/"/g,'""')}")`).all().map(c=>c.name);
const withoutRowid=/WITHOUT\s+ROWID/i.test(sql||'');
const order=withoutRowid?columns.map((_,i)=>i+1).join(','):'rowid';
const rows=db.prepare(`SELECT * FROM "${name.replace(/"/g,'""')}" ORDER BY ${order}`).all().map(row=>columns.map(c=>{
const masker=mask[name]?.[c];return masker?masker(row[c],row):cell(row[c]);
}));
tables[name]={columns,rows};
function dumpDatabase(filename, { mask = {} } = {}) {
const db = new DatabaseSync(filename, { readOnly: true });
try {
const master = db
.prepare(
"SELECT type,name,tbl_name,sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_autoindex_%' ORDER BY type,name",
)
.all();
const tables = {};
for (const { name, sql } of master.filter(row => row.type === 'table')) {
const columns = db
.prepare(`PRAGMA table_info("${name.replace(/"/g, '""')}")`)
.all()
.map(c => c.name);
const withoutRowid = /WITHOUT\s+ROWID/i.test(sql || '');
const order = withoutRowid ? columns.map((_, i) => i + 1).join(',') : 'rowid';
const rows = db
.prepare(`SELECT * FROM "${name.replace(/"/g, '""')}" ORDER BY ${order}`)
.all()
.map(row =>
columns.map(c => {
const masker = mask[name]?.[c];
return masker ? masker(row[c], row) : cell(row[c]);
}),
);
tables[name] = { columns, rows };
}
return {schema:master.map(({type,name,tbl_name,sql})=>({type,name,table:tbl_name,sql})),tables};
}finally{db.close();}
return { schema: master.map(({ type, name, tbl_name, sql }) => ({ type, name, table: tbl_name, sql })), tables };
} finally {
db.close();
}
}
module.exports={dumpDatabase};
module.exports = { dumpDatabase };
+66 -34
View File
@@ -1,40 +1,72 @@
'use strict';
// 语义比较:对象键顺序不计入差异(另行提示),数组顺序与所有值严格比较。
function short(v){const s=JSON.stringify(v);return s===undefined?'undefined':s.length>300?s.slice(0,300)+'…':s;}
function compare(expected,actual,path='$',out={diffs:[],orderNotes:[]}){
if(Object.is(expected,actual))return out;
const te=Array.isArray(expected)?'array':expected===null?'null':typeof expected,ta=Array.isArray(actual)?'array':actual===null?'null':typeof actual;
if(te!==ta){out.diffs.push({path,expected:short(expected),actual:short(actual)});return out;}
if(te==='array'){
const n=Math.max(expected.length,actual.length);
if(expected.length!==actual.length)out.diffs.push({path:path+'.length',expected:String(expected.length),actual:String(actual.length)});
for(let i=0;i<Math.min(expected.length,actual.length);i++)compare(expected[i],actual[i],path+'['+i+']',out);
for(let i=Math.min(expected.length,actual.length);i<n&&out.diffs.length<100000;i++)out.diffs.push({path:path+'['+i+']',expected:short(expected[i]),actual:short(actual[i])});
return out;
}
if(te==='object'){
const ke=Object.keys(expected),ka=Object.keys(actual);
for(const k of ke)if(!(k in actual))out.diffs.push({path:path+'.'+k,expected:short(expected[k]),actual:'(缺失)'});
for(const k of ka)if(!(k in expected))out.diffs.push({path:path+'.'+k,expected:'(缺失)',actual:short(actual[k])});
for(const k of ke)if(k in actual)compare(expected[k],actual[k],path+'.'+k,out);
const common=ke.filter(k=>k in actual),commonActual=ka.filter(k=>k in expected);
if(common.join('\u0000')!==commonActual.join('\u0000'))out.orderNotes.push(path);
return out;
}
if(te==='string'&&expected.length>120){
// 长字符串只显示首个不同字符附近的片段
let i=0;while(i<expected.length&&expected[i]===actual[i])i++;const from=Math.max(0,i-60);
out.diffs.push({path:path+` @字符${i}`,expected:(from?'…':'')+JSON.stringify(expected.slice(from,i+120)).slice(1,-1)+(i+120<expected.length?'…':''),actual:(from?'…':'')+JSON.stringify(actual.slice(from,i+120)).slice(1,-1)+(i+120<actual.length?'…':'')});return out;
}
out.diffs.push({path,expected:short(expected),actual:short(actual)});return out;
function short(v) {
const s = JSON.stringify(v);
return s === undefined ? 'undefined' : s.length > 300 ? s.slice(0, 300) + '…' : s;
}
function report(name,result,limit=30,describe=p=>p){
const lines=[];
if(result.diffs.length){
lines.push(`${name}:发现 ${result.diffs.length} 处差异,前 ${Math.min(limit,result.diffs.length)} 处:`);
for(const d of result.diffs.slice(0,limit))lines.push(` ${describe(d.path)}\n 基线:${d.expected}\n 实际:${d.actual}`);
function compare(expected, actual, path = '$', out = { diffs: [], orderNotes: [] }) {
if (Object.is(expected, actual)) return out;
const te = Array.isArray(expected) ? 'array' : expected === null ? 'null' : typeof expected,
ta = Array.isArray(actual) ? 'array' : actual === null ? 'null' : typeof actual;
if (te !== ta) {
out.diffs.push({ path, expected: short(expected), actual: short(actual) });
return out;
}
if(result.orderNotes.length)lines.push(`${name}:${result.orderNotes.length} 处对象键顺序变化(不计为失败),例如 ${result.orderNotes.slice(0,3).join('、')}`);
if (te === 'array') {
const n = Math.max(expected.length, actual.length);
if (expected.length !== actual.length)
out.diffs.push({ path: path + '.length', expected: String(expected.length), actual: String(actual.length) });
for (let i = 0; i < Math.min(expected.length, actual.length); i++)
compare(expected[i], actual[i], path + '[' + i + ']', out);
for (let i = Math.min(expected.length, actual.length); i < n && out.diffs.length < 100000; i++)
out.diffs.push({ path: path + '[' + i + ']', expected: short(expected[i]), actual: short(actual[i]) });
return out;
}
if (te === 'object') {
const ke = Object.keys(expected),
ka = Object.keys(actual);
for (const k of ke)
if (!(k in actual)) out.diffs.push({ path: path + '.' + k, expected: short(expected[k]), actual: '(缺失)' });
for (const k of ka)
if (!(k in expected)) out.diffs.push({ path: path + '.' + k, expected: '(缺失)', actual: short(actual[k]) });
for (const k of ke) if (k in actual) compare(expected[k], actual[k], path + '.' + k, out);
const common = ke.filter(k => k in actual),
commonActual = ka.filter(k => k in expected);
if (common.join('\u0000') !== commonActual.join('\u0000')) out.orderNotes.push(path);
return out;
}
if (te === 'string' && expected.length > 120) {
// 长字符串只显示首个不同字符附近的片段
let i = 0;
while (i < expected.length && expected[i] === actual[i]) i++;
const from = Math.max(0, i - 60);
out.diffs.push({
path: path + ` @字符${i}`,
expected:
(from ? '…' : '') +
JSON.stringify(expected.slice(from, i + 120)).slice(1, -1) +
(i + 120 < expected.length ? '…' : ''),
actual:
(from ? '…' : '') +
JSON.stringify(actual.slice(from, i + 120)).slice(1, -1) +
(i + 120 < actual.length ? '…' : ''),
});
return out;
}
out.diffs.push({ path, expected: short(expected), actual: short(actual) });
return out;
}
function report(name, result, limit = 30, describe = p => p) {
const lines = [];
if (result.diffs.length) {
lines.push(`${name}:发现 ${result.diffs.length} 处差异,前 ${Math.min(limit, result.diffs.length)} 处:`);
for (const d of result.diffs.slice(0, limit))
lines.push(` ${describe(d.path)}\n 基线:${d.expected}\n 实际:${d.actual}`);
}
if (result.orderNotes.length)
lines.push(
`${name}:${result.orderNotes.length} 处对象键顺序变化(不计为失败),例如 ${result.orderNotes.slice(0, 3).join('、')}`,
);
return lines.join('\n');
}
module.exports={compare,report};
module.exports = { compare, report };
+36 -18
View File
@@ -1,25 +1,43 @@
'use strict';
// 规范化:按首次出现顺序把随机标识映射为占位符,屏蔽会话令牌、密码哈希、盐和备份文件名。
// 时钟与随机源已固定,因此只做最少屏蔽,避免掩盖真实回归。
const UUID=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
const ORDER_NUMBER=/\b([A-Z]{2})(\d{8})-([0-9A-F]{8})\b/g;
const BACKUP=/ledger-(?:before-[a-z0-9-]+?-)?\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z(?:-[0-9a-f]{8})?\.sqlite/g;
class Normalizer{
constructor(){this.maps={id:new Map(),no:new Map(),secret:new Map()};this.literals=[];}
literal(raw,masked){if(raw)this.literals.push([raw,masked]);}
token(kind,value,prefix){const map=this.maps[kind];if(!map.has(value))map.set(value,`<${prefix}${map.size+1}>`);return map.get(value);}
secret(value){return value?this.token('secret',value,'secret'):value;}
string(s){
if(typeof s!=='string')return s;
for(const [raw,masked] of this.literals)if(s.includes(raw))s=s.split(raw).join(masked);
for(const [raw,masked] of this.maps.secret)if(raw&&s.includes(raw))s=s.split(raw).join(masked);
return s.replace(BACKUP,'<backup-file>').replace(UUID,m=>this.token('id',m.toLowerCase(),'id')).replace(ORDER_NUMBER,(m,prefix,date,hex)=>prefix+date+'-'+this.token('no',hex,'no'));
const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
const ORDER_NUMBER = /\b([A-Z]{2})(\d{8})-([0-9A-F]{8})\b/g;
const BACKUP = /ledger-(?:before-[a-z0-9-]+?-)?\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z(?:-[0-9a-f]{8})?\.sqlite/g;
class Normalizer {
constructor() {
this.maps = { id: new Map(), no: new Map(), secret: new Map() };
this.literals = [];
}
value(v){
if(typeof v==='string')return this.string(v);
if(Array.isArray(v))return v.map(x=>this.value(x));
if(v&&typeof v==='object'){const out={};for(const [k,x] of Object.entries(v))out[this.string(k)]=this.value(x);return out;}
literal(raw, masked) {
if (raw) this.literals.push([raw, masked]);
}
token(kind, value, prefix) {
const map = this.maps[kind];
if (!map.has(value)) map.set(value, `<${prefix}${map.size + 1}>`);
return map.get(value);
}
secret(value) {
return value ? this.token('secret', value, 'secret') : value;
}
string(s) {
if (typeof s !== 'string') return s;
for (const [raw, masked] of this.literals) if (s.includes(raw)) s = s.split(raw).join(masked);
for (const [raw, masked] of this.maps.secret) if (raw && s.includes(raw)) s = s.split(raw).join(masked);
return s
.replace(BACKUP, '<backup-file>')
.replace(UUID, m => this.token('id', m.toLowerCase(), 'id'))
.replace(ORDER_NUMBER, (m, prefix, date, hex) => prefix + date + '-' + this.token('no', hex, 'no'));
}
value(v) {
if (typeof v === 'string') return this.string(v);
if (Array.isArray(v)) return v.map(x => this.value(x));
if (v && typeof v === 'object') {
const out = {};
for (const [k, x] of Object.entries(v)) out[this.string(k)] = this.value(x);
return out;
}
return v;
}
}
module.exports={Normalizer,UUID};
module.exports = { Normalizer, UUID };
+42 -22
View File
@@ -1,29 +1,49 @@
'use strict';
// 由 lib/server.js 以 fork + --require fake-clock.cjs 启动;只通过 IPC 接受启动/停止指令。
// 启动参数来自环境变量 E2E_SERVER_OPTIONS(JSON):{mode,dataDir,startup:'create'|'production'}
const path=require('node:path');
const appDir=path.join(__dirname,'..','..');
const options=JSON.parse(process.env.E2E_SERVER_OPTIONS||'{}');
const send=message=>process.send&&process.send(message);
let app=null;
async function start(){
const server=require(path.join(appDir,'server.js'));
let startup={};
if(options.startup==='production'){
const path = require('node:path');
const appDir = path.join(__dirname, '..', '..');
const options = JSON.parse(process.env.E2E_SERVER_OPTIONS || '{}');
const send = message => process.send && process.send(message);
let app = null;
async function start() {
const server = require(path.join(appDir, 'server.js'));
let startup = {};
if (options.startup === 'production') {
// 与 server.js 正式入口一致:先备份升级前旧库,再 createApp,再显式迁移,最后监听。
startup.team=await server.prepareTeamStartupDatabase(options.dataDir);
app=server.createApp({mode:options.mode,dataDir:options.dataDir,host:'127.0.0.1',port:0});
startup.migration=await server.prepareStartupMigrations(app);
}else{
app=server.createApp({mode:options.mode||'trial',dataDir:options.dataDir,host:'127.0.0.1',port:0,inventorySnapshotLogger:()=>{}});
startup.team = await server.prepareTeamStartupDatabase(options.dataDir);
app = server.createApp({ mode: options.mode, dataDir: options.dataDir, host: '127.0.0.1', port: 0 });
startup.migration = await server.prepareStartupMigrations(app);
} else {
app = server.createApp({
mode: options.mode || 'trial',
dataDir: options.dataDir,
host: '127.0.0.1',
port: 0,
inventorySnapshotLogger: () => {},
});
}
await new Promise((resolve,reject)=>{app.server.once('error',reject);app.server.listen(0,'127.0.0.1',resolve);});
send({type:'ready',port:app.server.address().port,startup});
await new Promise((resolve, reject) => {
app.server.once('error', reject);
app.server.listen(0, '127.0.0.1', resolve);
});
send({ type: 'ready', port: app.server.address().port, startup });
}
process.on('message',async message=>{
if(message?.type!=='stop')return;
try{if(app){app.stop();app.ledger.close();}}catch(error){send({type:'log',message:'stop: '+error.message});}
send({type:'stopped'});setTimeout(()=>process.exit(0),20);
process.on('message', async message => {
if (message?.type !== 'stop') return;
try {
if (app) {
app.stop();
app.ledger.close();
}
} catch (error) {
send({ type: 'log', message: 'stop: ' + error.message });
}
send({ type: 'stopped' });
setTimeout(() => process.exit(0), 20);
});
process.on('disconnect', () => process.exit(0));
start().catch(error => {
send({ type: 'fatal', message: error.stack || String(error) });
setTimeout(() => process.exit(1), 20);
});
process.on('disconnect',()=>process.exit(0));
start().catch(error=>{send({type:'fatal',message:error.stack||String(error)});setTimeout(()=>process.exit(1),20);});
+84 -26
View File
@@ -1,35 +1,93 @@
'use strict';
// 父进程侧:以确定时钟启动应用子进程,提供时钟控制与停止。
const {fork}=require('node:child_process');
const path=require('node:path');
const CLOCK=path.join(__dirname,'..','fake-clock.cjs');
function startServer({mode='trial',dataDir,startup='create',clockStart,seed='golden-seed',tickMs=0,quiet=true}={}){
const child=fork(path.join(__dirname,'server-child.cjs'),[],{
const { fork } = require('node:child_process');
const path = require('node:path');
const CLOCK = path.join(__dirname, '..', 'fake-clock.cjs');
function startServer({
mode = 'trial',
dataDir,
startup = 'create',
clockStart,
seed = 'golden-seed',
tickMs = 0,
quiet = true,
} = {}) {
const child = fork(path.join(__dirname, 'server-child.cjs'), [], {
// E2E_MUTATION_REQUIRE:仅用于自检,额外预加载一个故意改变行为的脚本,确认对照能发现回归。
execArgv:['--require',CLOCK,...(process.env.E2E_MUTATION_REQUIRE?['--require',process.env.E2E_MUTATION_REQUIRE]:[]),'--disable-warning=ExperimentalWarning'],
env:{...process.env,TZ:'Asia/Shanghai',FAKE_CLOCK_IPC:'1',FAKE_CLOCK_START:clockStart||'2026-11-20T02:00:00.000Z',FAKE_RANDOM_SEED:seed,FAKE_CLOCK_TICK_MS:String(tickMs),
FEISHU_CONFIG:path.join(dataDir,'no-feishu.json'),APP_MODE:mode,E2E_SERVER_OPTIONS:JSON.stringify({mode,dataDir,startup})},
stdio:['ignore',quiet?'pipe':'inherit',quiet?'pipe':'inherit','ipc'],
execArgv: [
'--require',
CLOCK,
...(process.env.E2E_MUTATION_REQUIRE ? ['--require', process.env.E2E_MUTATION_REQUIRE] : []),
'--disable-warning=ExperimentalWarning',
],
env: {
...process.env,
TZ: 'Asia/Shanghai',
FAKE_CLOCK_IPC: '1',
FAKE_CLOCK_START: clockStart || '2026-11-20T02:00:00.000Z',
FAKE_RANDOM_SEED: seed,
FAKE_CLOCK_TICK_MS: String(tickMs),
FEISHU_CONFIG: path.join(dataDir, 'no-feishu.json'),
APP_MODE: mode,
E2E_SERVER_OPTIONS: JSON.stringify({ mode, dataDir, startup }),
},
stdio: ['ignore', quiet ? 'pipe' : 'inherit', quiet ? 'pipe' : 'inherit', 'ipc'],
});
let output='';if(quiet){child.stdout.on('data',d=>{output+=d;});child.stderr.on('data',d=>{output+=d;});}
let seq=0;const waiting=new Map();let readyResolve,readyReject;
const ready=new Promise((resolve,reject)=>{readyResolve=resolve;readyReject=reject;});
let stoppedResolve;const stopped=new Promise(resolve=>{stoppedResolve=resolve;});
child.on('message',message=>{
if(message.type==='ready')readyResolve(message);
else if(message.type==='fatal')readyReject(new Error('应用启动失败:'+message.message+'\n'+output));
else if(message.type==='fake-clock-ack'){const w=waiting.get(message.id);waiting.delete(message.id);if(w)message.error?w.reject(new Error(message.error)):w.resolve(message.now);}
else if(message.type==='stopped')stoppedResolve();
let output = '';
if (quiet) {
child.stdout.on('data', d => {
output += d;
});
child.stderr.on('data', d => {
output += d;
});
}
let seq = 0;
const waiting = new Map();
let readyResolve, readyReject;
const ready = new Promise((resolve, reject) => {
readyResolve = resolve;
readyReject = reject;
});
child.on('exit',code=>{readyReject(new Error('应用子进程退出 '+code+'\n'+output));stoppedResolve();for(const w of waiting.values())w.reject(new Error('应用子进程已退出'));});
const clock=(op,ms)=>new Promise((resolve,reject)=>{const id=++seq;waiting.set(id,{resolve,reject});child.send({type:'fake-clock',op,ms,id});});
let stoppedResolve;
const stopped = new Promise(resolve => {
stoppedResolve = resolve;
});
child.on('message', message => {
if (message.type === 'ready') readyResolve(message);
else if (message.type === 'fatal') readyReject(new Error('应用启动失败:' + message.message + '\n' + output));
else if (message.type === 'fake-clock-ack') {
const w = waiting.get(message.id);
waiting.delete(message.id);
if (w) message.error ? w.reject(new Error(message.error)) : w.resolve(message.now);
} else if (message.type === 'stopped') stoppedResolve();
});
child.on('exit', code => {
readyReject(new Error('应用子进程退出 ' + code + '\n' + output));
stoppedResolve();
for (const w of waiting.values()) w.reject(new Error('应用子进程已退出'));
});
const clock = (op, ms) =>
new Promise((resolve, reject) => {
const id = ++seq;
waiting.set(id, { resolve, reject });
child.send({ type: 'fake-clock', op, ms, id });
});
return {
child,
async ready(){const info=await ready;return {...info,base:'http://127.0.0.1:'+info.port};},
setTime:ms=>clock('set',ms),
advance:ms=>clock('advance',ms),
output:()=>output,
async stop(){if(child.exitCode!==null)return;child.send({type:'stop'});await Promise.race([stopped,new Promise(r=>setTimeout(r,5000))]);if(child.exitCode===null)child.kill();},
async ready() {
const info = await ready;
return { ...info, base: 'http://127.0.0.1:' + info.port };
},
setTime: ms => clock('set', ms),
advance: ms => clock('advance', ms),
output: () => output,
async stop() {
if (child.exitCode !== null) return;
child.send({ type: 'stop' });
await Promise.race([stopped, new Promise(r => setTimeout(r, 5000))]);
if (child.exitCode === null) child.kill();
},
};
}
module.exports={startServer};
module.exports = { startServer };
+36 -14
View File
@@ -1,19 +1,41 @@
'use strict';
// 最小 ZIP 读取器(xlsx 用),只支持 stored/deflate。返回 [{name,data:Buffer}],按中央目录顺序。
const zlib=require('node:zlib');
function unzip(buffer){
let eocd=-1;for(let i=buffer.length-22;i>=Math.max(0,buffer.length-65557);i--)if(buffer.readUInt32LE(i)===0x06054b50){eocd=i;break;}
if(eocd<0)throw new Error('不是有效的 ZIP 文件');
const count=buffer.readUInt16LE(eocd+10);let offset=buffer.readUInt32LE(eocd+16);const files=[];
for(let n=0;n<count;n++){
if(buffer.readUInt32LE(offset)!==0x02014b50)throw new Error('ZIP 中央目录损坏');
const method=buffer.readUInt16LE(offset+10),compressed=buffer.readUInt32LE(offset+20),nameLength=buffer.readUInt16LE(offset+28),extraLength=buffer.readUInt16LE(offset+30),commentLength=buffer.readUInt16LE(offset+32),local=buffer.readUInt32LE(offset+42);
const name=buffer.subarray(offset+46,offset+46+nameLength).toString('utf8');
const localName=buffer.readUInt16LE(local+26),localExtra=buffer.readUInt16LE(local+28),start=local+30+localName+localExtra;
const raw=buffer.subarray(start,start+compressed);
const data=method===0?Buffer.from(raw):method===8?zlib.inflateRawSync(raw):(()=>{throw new Error('不支持的压缩方式 '+method);})();
files.push({name,data});offset+=46+nameLength+extraLength+commentLength;
const zlib = require('node:zlib');
function unzip(buffer) {
let eocd = -1;
for (let i = buffer.length - 22; i >= Math.max(0, buffer.length - 65557); i--)
if (buffer.readUInt32LE(i) === 0x06054b50) {
eocd = i;
break;
}
if (eocd < 0) throw new Error('不是有效的 ZIP 文件');
const count = buffer.readUInt16LE(eocd + 10);
let offset = buffer.readUInt32LE(eocd + 16);
const files = [];
for (let n = 0; n < count; n++) {
if (buffer.readUInt32LE(offset) !== 0x02014b50) throw new Error('ZIP 中央目录损坏');
const method = buffer.readUInt16LE(offset + 10),
compressed = buffer.readUInt32LE(offset + 20),
nameLength = buffer.readUInt16LE(offset + 28),
extraLength = buffer.readUInt16LE(offset + 30),
commentLength = buffer.readUInt16LE(offset + 32),
local = buffer.readUInt32LE(offset + 42);
const name = buffer.subarray(offset + 46, offset + 46 + nameLength).toString('utf8');
const localName = buffer.readUInt16LE(local + 26),
localExtra = buffer.readUInt16LE(local + 28),
start = local + 30 + localName + localExtra;
const raw = buffer.subarray(start, start + compressed);
const data =
method === 0
? Buffer.from(raw)
: method === 8
? zlib.inflateRawSync(raw)
: (() => {
throw new Error('不支持的压缩方式 ' + method);
})();
files.push({ name, data });
offset += 46 + nameLength + extraLength + commentLength;
}
return files;
}
module.exports={unzip};
module.exports = { unzip };