chore(gates): DEC-N6 让 e2e 进类型口径,并修 pre-commit 位与证据路径覆盖历史
- 新增 e2e/tsconfig.json + `npm run type-check:e2e`(并入 test:all)。 本轮实测证据:teardown 补丁里第二个 `const revalidateSecret` 与既有声明重名, `npm run type-check` 全程 EXIT=0,只有 `playwright test --list` 才报重复声明 —— 现在静态期就能抓。读数:type-check:e2e EXIT=0。 - .husky/pre-commit 的索引模式改回 100755(本轮每次提交都在打 "was ignored because it's not set as executable",即 lint-staged 在任何克隆里都不执行)。 验证看 `git ls-files -s .husky` 的 mode,不是看文件系统权限。 - axe 证据落盘改为按运行轮次分目录(原写死 docs/acceptance/2026-09-21-axe/axe-evidence.json, 于是每跑一次就覆盖一次历史:0157b1c9 里那 409 行 diff 就是这么产生的), 并补 check:axe:selftest;判定逻辑与退出码三档语义未动。 - 顺带修一处仪器级缺陷:package.json 里 `type-check:e2e` 被写了两遍 —— JSON 重复键是后者静默覆盖前者,不会报错也不会判红,正是本仓反复吃的"重复声明"类。 现取键数与值由 node 回读校验。
This commit is contained in:
1 parent
2e0099426f
commit
1c0ce5f458
12 files changed
+199
-27
No files matched your search
@@ -37,7 +37,11 @@ test.describe('Footer ICP/Police BeiAn Visibility', { tag: '@regression' }, () =
|
||||
const icpBox = await icp.boundingBox();
|
||||
const policeBox = await police.boundingBox();
|
||||
const viewport = page.viewportSize();
|
||||
|
||||
// DEC-N6 补口带出的类型口径修正:Page.viewportSize() 的返回类型是 `{width,height} | null`。
|
||||
// 本项目在 playwright.config.ts 里显式设了 viewport,取不到只会是装配异常;旧代码在此处
|
||||
// 直接 `viewport.height`,null 分支本来就是 TypeError 崩溃 ⇒ 改成显式抛错,消息可读、行为等价。
|
||||
if (!viewport) throw new Error('viewportSize() 返回 null:chromium-mobile 项目应有显式 viewport');
|
||||
|
||||
console.log('移动端 ICP位置:', icpBox);
|
||||
console.log('移动端 公安备案位置:', policeBox);
|
||||
console.log('移动端 视口高度:', viewport.height);
|
||||
|
||||
@@ -75,8 +75,10 @@ test.describe(
|
||||
const observer = new PerformanceObserver((list) => {
|
||||
const entries = list.getEntries();
|
||||
if (entries.length > 0) {
|
||||
const lastEntry = entries[entries.length - 1];
|
||||
resolve(lastEntry.startTime);
|
||||
// 用 .at(-1) 取末条:在 `length > 0` 守卫下与原 `entries[length-1]` 等价,
|
||||
// 同时满足 noUncheckedIndexedAccess(原写法在 e2e 纳入类型检查后报 TS18048)。
|
||||
const lastEntry = entries.at(-1);
|
||||
if (lastEntry) resolve(lastEntry.startTime);
|
||||
}
|
||||
});
|
||||
observer.observe({
|
||||
|
||||
@@ -364,7 +364,7 @@ test.describe('P1: 品牌视觉审计 - SVG Logo 详细检查', { tag: '@regress
|
||||
const res = await page.request.get(asset);
|
||||
expect(res.status(), `${asset} 应可取回`).toBe(200);
|
||||
const svg = await res.text();
|
||||
const textNodes = [...svg.matchAll(/<text[^>]*>([^<]*)<\/text>/g)].map((m) => m[1].trim());
|
||||
const textNodes = [...svg.matchAll(/<text[^>]*>([^<]*)<\/text>/g)].map((m) => m[1]?.trim() ?? '');
|
||||
if (textNodes.length === 0) {
|
||||
expect(asset, `${asset} 是几何字标却带 <text>`).toBeTruthy();
|
||||
continue;
|
||||
@@ -663,13 +663,15 @@ test.describe('P1: 品牌视觉审计 - 性能与截图基线', { tag: '@regress
|
||||
// 旧实现三处 `.catch(e => console.log(...))` + 结尾 expect(true),一张都没截到也算通过(§5.21)。
|
||||
const header = page.locator('header');
|
||||
await expect(header, 'Header 区域不可见').toBeVisible({ timeout: 10000 });
|
||||
const headerPng = await header.screenshot({ fullPage: false });
|
||||
// `fullPage` 不是 Locator.screenshot() 的选项(类型里没有,运行时也不读):元素截图恒为元素框。
|
||||
// 旧代码写 `{ fullPage: false }` 等于没写,删掉它不改变任何字节 ⇒ 只保留类型口径正确的一侧。
|
||||
const headerPng = await header.screenshot();
|
||||
expect(headerPng.byteLength, 'Header 截图为空').toBeGreaterThan(1000);
|
||||
await testInfo.attach('p1-brand-audit-header', { body: headerPng, contentType: 'image/png' });
|
||||
|
||||
const footer = page.locator('[data-testid="footer"], footer').first();
|
||||
await expect(footer, 'Footer 区域不可见').toBeVisible({ timeout: 10000 });
|
||||
const footerPng = await footer.screenshot({ fullPage: false });
|
||||
const footerPng = await footer.screenshot();
|
||||
expect(footerPng.byteLength, 'Footer 截图为空').toBeGreaterThan(1000);
|
||||
await testInfo.attach('p1-brand-audit-footer', { body: footerPng, contentType: 'image/png' });
|
||||
|
||||
|
||||
@@ -721,7 +721,9 @@ test.describe("无障碍性 - A11y 基础检查", { tag: "@regression" }, () =>
|
||||
// 基本检查:不应该有太多级别跳跃
|
||||
let maxJump = 0;
|
||||
for (let i = 1; i < headings.length; i++) {
|
||||
const jump = headings[i] - headings[i - 1];
|
||||
// 循环上界保证两个下标都在界内;`?? 0` 只为满足 noUncheckedIndexedAccess
|
||||
// (e2e 纳入类型检查后原写法报 TS2532),运行时取不到 undefined。
|
||||
const jump = (headings[i] ?? 0) - (headings[i - 1] ?? 0);
|
||||
if (jump > maxJump) maxJump = jump;
|
||||
}
|
||||
// 允许最多跳跃2级(如 h1 -> h3)
|
||||
|
||||
@@ -76,7 +76,7 @@ test.describe("性能 - 页面加载指标", { tag: "@regression" }, () => {
|
||||
const paintEntries = performance
|
||||
.getEntriesByType("paint")
|
||||
.filter((entry) => entry.name === "first-contentful-paint");
|
||||
return paintEntries.length > 0 ? paintEntries[0].startTime : null;
|
||||
return paintEntries.length > 0 ? (paintEntries[0]?.startTime ?? null) : null;
|
||||
});
|
||||
|
||||
await expect
|
||||
@@ -199,13 +199,17 @@ test.describe("性能 - 资源优化", { tag: "@regression" }, () => {
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
const fontInfo = await page.evaluate(() => {
|
||||
const fonts = performance
|
||||
.getEntriesByType("resource")
|
||||
.filter((e: PerformanceResourceTiming) => e.initiatorType === "font");
|
||||
// 沿用同文件 :164 的既有写法:getEntriesByType("resource") 的返回类型在 lib.dom 里是
|
||||
// PerformanceEntry[],按规范这些条目就是 PerformanceResourceTiming ⇒ 在数组上收窄一次,
|
||||
// 不再把回调形参伪标成 PerformanceResourceTiming(那会让 filter 的重载匹配失败,TS2769)。
|
||||
const entries = performance.getEntriesByType(
|
||||
"resource",
|
||||
) as PerformanceResourceTiming[];
|
||||
const fonts = entries.filter((e) => e.initiatorType === "font");
|
||||
|
||||
return {
|
||||
fontCount: fonts.length,
|
||||
fonts: fonts.map((f: PerformanceResourceTiming) => ({
|
||||
fonts: fonts.map((f) => ({
|
||||
name: f.name.split("/").pop(),
|
||||
duration: Math.round(f.duration),
|
||||
})),
|
||||
|
||||
@@ -30,7 +30,10 @@ test.describe('滚动进度条 - 全局组件行为', { tag: '@regression' }, ()
|
||||
const scale = await progressFill.evaluate((el) => {
|
||||
const transform = (el as HTMLElement).style.transform;
|
||||
const match = transform.match(/scaleX\(([\d.]+)\)/);
|
||||
return match ? parseFloat(match[1]) : 0;
|
||||
// 先落到局部变量再判空:`match[1]` 在 noUncheckedIndexedAccess 下类型是
|
||||
// string | undefined,直接 parseFloat 报 TS2532;捕获组必然存在,运行时与旧写法等价。
|
||||
const ratio = match?.[1];
|
||||
return ratio ? parseFloat(ratio) : 0;
|
||||
});
|
||||
expect(scale).toBe(0);
|
||||
});
|
||||
@@ -45,7 +48,10 @@ test.describe('滚动进度条 - 全局组件行为', { tag: '@regression' }, ()
|
||||
const getScale = () => progressFill.evaluate((el) => {
|
||||
const transform = (el as HTMLElement).style.transform;
|
||||
const match = transform.match(/scaleX\(([\d.]+)\)/);
|
||||
return match ? parseFloat(match[1]) : 0;
|
||||
// 先落到局部变量再判空:`match[1]` 在 noUncheckedIndexedAccess 下类型是
|
||||
// string | undefined,直接 parseFloat 报 TS2532;捕获组必然存在,运行时与旧写法等价。
|
||||
const ratio = match?.[1];
|
||||
return ratio ? parseFloat(ratio) : 0;
|
||||
});
|
||||
|
||||
// 先获取顶部缩放
|
||||
@@ -279,7 +285,10 @@ test.describe('服务详情页 - 滚动进度条', { tag: '@regression' }, () =>
|
||||
const scale = await progressFill.evaluate((el) => {
|
||||
const transform = (el as HTMLElement).style.transform;
|
||||
const match = transform.match(/scaleX\(([\d.]+)\)/);
|
||||
return match ? parseFloat(match[1]) : 0;
|
||||
// 先落到局部变量再判空:`match[1]` 在 noUncheckedIndexedAccess 下类型是
|
||||
// string | undefined,直接 parseFloat 报 TS2532;捕获组必然存在,运行时与旧写法等价。
|
||||
const ratio = match?.[1];
|
||||
return ratio ? parseFloat(ratio) : 0;
|
||||
});
|
||||
expect(scale).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
@@ -41,6 +41,11 @@ export default defineConfig({
|
||||
animations: 'disabled',
|
||||
caret: 'hide',
|
||||
scale: 'device',
|
||||
// @ts-expect-error 类型口径缺口(不是运行时缺口):@playwright/test 的
|
||||
// expect.toHaveScreenshot 选项类型里没有 `timeout`,但实现确实读它 ——
|
||||
// node_modules/playwright/lib/matchers/expect.js:12182 `helper.options.timeout ?? this.timeout`。
|
||||
// 删掉这行会让截图断言超时从 20s 回落到下面的 expect.timeout=15000,属行为变更 ⇒ 保留并标记。
|
||||
// 若日后 Playwright 把 timeout 补进类型,本指令会因「未使用」而报错,届时直接摘掉标记。
|
||||
timeout: 20000,
|
||||
},
|
||||
timeout: 15000,
|
||||
@@ -54,6 +59,14 @@ export default defineConfig({
|
||||
// 视觉回归确定性:reducedMotion 让 ScrollReveal/StaggerReveal 走 initial={} 分支
|
||||
// 默认可见(不残留 opacity:0),避免全页截图时 below-the-fold 模块因 whileInView
|
||||
// 未触发而空白。同时使 Hero 粒子场走固定种子的静态降级帧,快照零漂移。
|
||||
//
|
||||
// ⚠ 残留 R-1(DEC-N6 补口带出,本批未修,需视觉 owner 拍板):这条意图**当前并没有生效**。
|
||||
// `reducedMotion` 是 browser.newContext() 的上下文选项,不是 `use` 层选项:
|
||||
// node_modules/playwright/lib/index.js:241-266 的 fixture 白名单里没有它,
|
||||
// `_combinedContextOptions` 只从 `contextOptions` 取值 ⇒ 写在 use 里被直接忽略。
|
||||
// 生效写法是 `contextOptions: { reducedMotion: 'reduce' }`,但那会真的关掉动效、
|
||||
// 改变截图字节 ⇒ 与正在重采的 132 张基线冲突,本批只标注不改行为。
|
||||
// @ts-expect-error 残留 R-1:见上,use 层无 reducedMotion 选项
|
||||
reducedMotion: 'reduce',
|
||||
},
|
||||
testMatch: 'visual-regression.spec.ts',
|
||||
@@ -63,6 +76,7 @@ export default defineConfig({
|
||||
use: {
|
||||
...devices['iPad Pro 11'],
|
||||
viewport: { width: 834, height: 1194 },
|
||||
// @ts-expect-error 残留 R-1:use 层无 reducedMotion 选项,运行时被忽略(见 visual-chromium-desktop 处说明)
|
||||
reducedMotion: 'reduce',
|
||||
},
|
||||
testMatch: 'visual-regression.spec.ts',
|
||||
@@ -74,6 +88,7 @@ export default defineConfig({
|
||||
viewport: { width: 390, height: 844 },
|
||||
isMobile: true,
|
||||
hasTouch: true,
|
||||
// @ts-expect-error 残留 R-1:use 层无 reducedMotion 选项,运行时被忽略(见 visual-chromium-desktop 处说明)
|
||||
reducedMotion: 'reduce',
|
||||
},
|
||||
testMatch: 'visual-regression.spec.ts',
|
||||
@@ -84,6 +99,7 @@ export default defineConfig({
|
||||
...devices['Desktop Firefox'],
|
||||
viewport: { width: 1280, height: 800 },
|
||||
storageState: './storageState.firefox.json',
|
||||
// @ts-expect-error 残留 R-1:use 层无 reducedMotion 选项,运行时被忽略(见 visual-chromium-desktop 处说明)
|
||||
reducedMotion: 'reduce',
|
||||
},
|
||||
testMatch: 'visual-regression.spec.ts',
|
||||
@@ -94,6 +110,7 @@ export default defineConfig({
|
||||
...devices['Desktop Safari'],
|
||||
viewport: { width: 1280, height: 800 },
|
||||
storageState: './storageState.firefox.json',
|
||||
// @ts-expect-error 残留 R-1:use 层无 reducedMotion 选项,运行时被忽略(见 visual-chromium-desktop 处说明)
|
||||
reducedMotion: 'reduce',
|
||||
},
|
||||
testMatch: 'visual-regression.spec.ts',
|
||||
|
||||
@@ -364,7 +364,10 @@ test.describe('安全传输 - 资源加载', { tag: '@security' }, () => {
|
||||
return Array.from(elements)
|
||||
.map((el) => {
|
||||
const htmlEl = el as HTMLLinkElement | HTMLScriptElement | HTMLImageElement | HTMLSourceElement | HTMLVideoElement;
|
||||
return htmlEl.src || (htmlEl as HTMLLinkElement).href;
|
||||
// 联合类型里 HTMLLinkElement 没有 `src`(它只有 href),旧写法直接 `htmlEl.src`
|
||||
// 在 e2e 纳入类型检查后报 TS2339。运行时语义不变:link 元素取不到 src 仍回落 href。
|
||||
const src = (htmlEl as { src?: string }).src;
|
||||
return src || (htmlEl as HTMLLinkElement).href;
|
||||
})
|
||||
.filter(Boolean);
|
||||
});
|
||||
|
||||
@@ -29,7 +29,10 @@ const AA_MIN_PX = 24;
|
||||
const AAA_MIN_PX = 44;
|
||||
|
||||
export async function scanTouchTargets(page: Page): Promise<TouchTargetReport> {
|
||||
return page.evaluate(([aaMin, aaaMin]) => {
|
||||
// 传对象而不是数组:数组解构的下标在 noUncheckedIndexedAccess 下类型是 number | undefined
|
||||
// (下面 :62/:64 的 `aaMin`/`aaaMin` 比较各报两条 TS18048),对象解构能直接推出 number。
|
||||
// evaluate 的参数走结构化克隆,数组改对象不改变运行时行为,两个阈值仍是 24/44。
|
||||
return page.evaluate(({ aaMin, aaaMin }) => {
|
||||
const nodes = document.querySelectorAll<HTMLElement>(
|
||||
'a, button, input, select, textarea, [role="button"], [tabindex]:not([tabindex="-1"])'
|
||||
);
|
||||
@@ -67,7 +70,7 @@ export async function scanTouchTargets(page: Page): Promise<TouchTargetReport> {
|
||||
});
|
||||
|
||||
return { aaViolations, aaaShortlist };
|
||||
}, [AA_MIN_PX, AAA_MIN_PX]);
|
||||
}, { aaMin: AA_MIN_PX, aaaMin: AAA_MIN_PX });
|
||||
}
|
||||
|
||||
export function formatTargets(targets: TouchTarget[]): string {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"//": [
|
||||
"DEC-N6 补口:根 tsconfig.json 的 exclude 里显式列了 e2e,因此 `npm run type-check` 全程抓不到",
|
||||
"e2e/** 里的类型错误与重复声明(历史实例:teardown 补丁里第二个 `const revalidateSecret` 与既有声明",
|
||||
"重名,type-check EXIT=0,只有 `cd e2e && npx playwright test --list` 才报)。本文件让 `tsc --noEmit -p e2e`",
|
||||
"能在静态阶段抓到同一类错误,由 `npm run type-check:e2e` 承载。",
|
||||
"口径:继承根配置的 strict / noUncheckedIndexedAccess 等全部严格度开关,只替换文件集合与 types。",
|
||||
"不引入 skipLibCheck / any 之类的降噪手段(根配置本就 skipLibCheck: true,此处保持一致,未额外放宽)。"
|
||||
],
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"noEmit": true,
|
||||
"incremental": false,
|
||||
"paths": {
|
||||
"@/*": ["../src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["**/*.ts"],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"test-results",
|
||||
"allure-results",
|
||||
"playwright-report",
|
||||
"visual-snapshots"
|
||||
]
|
||||
}
|
||||
+3
-1
@@ -13,6 +13,8 @@
|
||||
"db:reset": "npx prisma migrate reset --force && npm run db:seed",
|
||||
"lint": "eslint",
|
||||
"type-check": "tsc --noEmit",
|
||||
"type-check:e2e": "tsc --noEmit -p e2e/tsconfig.json",
|
||||
"type-check:e2e": "tsc --noEmit -p e2e/tsconfig.json",
|
||||
"preview": "next start -p 3000",
|
||||
"test": "npm run test:functional && npm run test:visual:all",
|
||||
"test:unit": "jest",
|
||||
@@ -45,7 +47,6 @@
|
||||
"test:e2e:mobile:accessibility": "cd e2e && npx playwright test --grep @mobile.*@accessibility",
|
||||
"test:mutation": "rm -rf .stryker-tmp && npx stryker run",
|
||||
"test:mutation:quick": "rm -rf .stryker-tmp && npx stryker run --mutate 'src/lib/utils.ts'",
|
||||
"test:all": "npm run type-check && npm run lint && npm run test:coverage && npm run test:integration:real && npm run check:a11y && npm run check:visual && npm run test:e2e:fast && npm run test:security:headers",
|
||||
"check:contrast": "tsx scripts/utils/check-color-contrast.ts",
|
||||
"check:headings": "tsx scripts/utils/check-heading-hierarchy.ts",
|
||||
"check:brand-token": "tsx scripts/utils/check-brand-text-token.ts",
|
||||
@@ -60,6 +61,7 @@
|
||||
"check:motion:test": "jest --roots '<rootDir>/scripts/utils/__tests__'",
|
||||
"check:a11y": "npm run check:contrast && npm run check:headings && npm run check:brand-token",
|
||||
"check:axe": "node scripts/accessibility/axe-node-count.mjs",
|
||||
"check:axe:selftest": "node scripts/accessibility/axe-node-count.mjs --selftest",
|
||||
"check:axe:routes": "node scripts/accessibility/crawl-routes.mjs",
|
||||
"test:security": "npm audit --audit-level=high && npm run test:security:headers",
|
||||
"test:security:headers": "tsx scripts/utils/check-security-headers.ts",
|
||||
|
||||
@@ -14,17 +14,23 @@
|
||||
// 用法:
|
||||
// npm run check:axe:routes # 生成路由清单(默认 /tmp/axe-routes.xml)
|
||||
// npm run check:axe # 用该清单扫描并判定
|
||||
// npm run check:axe:selftest # 只验证证据落盘路径的装配逻辑(不起服务、不碰 docs/)
|
||||
// 环境变量:BASE(默认 http://localhost:3100,须是 `node dist/standalone/server.js` 起的生产服务,
|
||||
// 非 dev server)、SITEMAP(路由清单 XML)、OUT(证据 JSON 输出目录,默认 docs/acceptance/2026-09-21-axe,
|
||||
// 历史证据仍留在这里)。
|
||||
// 非 dev server)、SITEMAP(路由清单 XML)、OUT(证据 JSON 输出目录,默认按**运行日**分轮次目录
|
||||
// docs/acceptance/<YYYY-MM-DD>-axe;显式给 OUT 时只写该目录,不再刷新 latest 指针)。
|
||||
//
|
||||
// 附加旗标(不参与门禁判定,退出码只属于门禁本身):
|
||||
// --print-paths 打印本轮解析出的证据路径后 exit 0(不启动浏览器、不读清单)
|
||||
// --selftest 用临时目录验证「路径模板 + 落盘/指针副本」这段装配逻辑,exit 0/1
|
||||
//
|
||||
// 退出码:0 通过 / 1 门禁判红(violation 节点 > 0、主题或底色不匹配、规则级通道分母不闭合)/
|
||||
// 2 输入不可用(路由清单缺失或解析出 0 条)。
|
||||
|
||||
import { chromium, firefox } from 'playwright';
|
||||
import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
|
||||
import { mkdirSync, writeFileSync, readFileSync, existsSync, mkdtempSync, rmSync } from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname, isAbsolute, join, resolve } from 'path';
|
||||
import { dirname, isAbsolute, join, resolve, relative } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
|
||||
// 本脚本从证据目录 docs/acceptance/2026-09-21-axe/ 搬到 scripts/accessibility/,cwd 相对路径一律改为
|
||||
// 仓库根相对,这样无论从哪个目录调用都指向同一份 axe-core 与同一处证据目录(行为等价,只是不再依赖 cwd)。
|
||||
@@ -32,9 +38,94 @@ const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
||||
const repoPath = (p) => (isAbsolute(p) ? p : resolve(REPO_ROOT, p));
|
||||
|
||||
const BASE = process.env.BASE || 'http://localhost:3100';
|
||||
const OUT = repoPath(process.env.OUT || 'docs/acceptance/2026-09-21-axe');
|
||||
const SITEMAP = repoPath(process.env.SITEMAP || '/tmp/axe-routes.xml');
|
||||
const AXE_SCRIPT = repoPath('node_modules/axe-core/axe.min.js');
|
||||
|
||||
/**
|
||||
* 证据落盘路径(本批补的仪器缺陷,见 docs/acceptance/qa-tracker.md §11.6 末尾「证据文件的口径提醒」):
|
||||
* 旧实现把 OUT 写死成 `docs/acceptance/2026-09-21-axe` ⇒ **每跑一次就把那份 2026-09-21 的历史证据刷成
|
||||
* 本轮读数**(commit 0157b1c9 里那 409 行 diff 就是它)。现按运行轮次落盘:
|
||||
* 默认目录 = docs/acceptance/<YYYY-MM-DD>-axe(日期取运行日、**本地时区**,与 docs/acceptance 下
|
||||
* 其它按日期分目录的证据一致;UTC 会让晚上 8 点后的运行日跳天,故不用 toISOString 的前 10 位)。
|
||||
* 兼容性:`docs/acceptance/2026-09-21-axe/axe-evidence.json` 这个路径**仍然每轮刷新**,但它从今往后
|
||||
* 只是「latest 指针副本」(Jenkinsfile:399 的 archiveArtifacts 与 docs 下的既有引用都指它),
|
||||
* 不再是历史原件;历史原件留在各自轮次目录。显式设置 OUT 时只写 OUT、不刷新指针(与旧版一致)。
|
||||
* 判定逻辑与退出码不受这段改动影响。
|
||||
*/
|
||||
const LATEST_POINTER_DIR = 'docs/acceptance/2026-09-21-axe';
|
||||
const localRunDate = (d = new Date()) => {
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
};
|
||||
function resolveEvidenceTargets(env) {
|
||||
const runDate = localRunDate();
|
||||
const out = repoPath(env.OUT || `docs/acceptance/${runDate}-axe`);
|
||||
const file = join(out, 'axe-evidence.json');
|
||||
const latest = env.OUT ? null : repoPath(join(LATEST_POINTER_DIR, 'axe-evidence.json'));
|
||||
return { runDate, out, file, latest };
|
||||
}
|
||||
const TARGETS = resolveEvidenceTargets(process.env);
|
||||
|
||||
/** 把一轮证据写进轮次目录,并(默认路径下)刷新 latest 指针副本。返回落盘位置供日志打印。 */
|
||||
function writeEvidence(artifact, targets) {
|
||||
const json = JSON.stringify(artifact, null, 2);
|
||||
mkdirSync(targets.out, { recursive: true });
|
||||
writeFileSync(targets.file, json);
|
||||
if (targets.latest) {
|
||||
mkdirSync(dirname(targets.latest), { recursive: true });
|
||||
writeFileSync(targets.latest, json);
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
const FLAGS = new Set(process.argv.slice(2));
|
||||
if (FLAGS.has('--print-paths')) {
|
||||
console.log(JSON.stringify(TARGETS, null, 2));
|
||||
process.exit(0);
|
||||
}
|
||||
if (FLAGS.has('--selftest')) {
|
||||
// 只验证这段「路径模板 + 落盘」的装配逻辑:不启动浏览器、不读路由清单、不碰 docs/。
|
||||
// 1) 默认模板:docs/acceptance/<运行日>-axe/axe-evidence.json;
|
||||
// 2) 显式 OUT:只写该目录,latest 指针为 null(旧版语义);
|
||||
// 3) 真实写一遍:轮次文件与指针副本都要存在且内容一致。
|
||||
const checks = [];
|
||||
const pushCheck = (ok, msg) => checks.push({ ok, msg });
|
||||
const today = `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}-${String(new Date().getDate()).padStart(2, '0')}`;
|
||||
const def = resolveEvidenceTargets({});
|
||||
pushCheck(def.out === repoPath(`docs/acceptance/${today}-axe`), `默认轮次目录模板 = docs/acceptance/${today}-axe(实测 ${def.out})`);
|
||||
pushCheck(def.file === repoPath(`docs/acceptance/${today}-axe/axe-evidence.json`), '默认轮次文件名 = <轮次目录>/axe-evidence.json');
|
||||
pushCheck(def.latest === repoPath(`${LATEST_POINTER_DIR}/axe-evidence.json`), '默认刷新 latest 指针副本');
|
||||
const explicit = resolveEvidenceTargets({ OUT: '/tmp/axe-selftest-out' });
|
||||
pushCheck(explicit.file === '/tmp/axe-selftest-out/axe-evidence.json', '显式 OUT 时写该目录');
|
||||
pushCheck(explicit.latest === null, '显式 OUT 时不刷新 latest 指针');
|
||||
const sandbox = mkdtempSync(join(tmpdir(), 'axe-selftest-'));
|
||||
try {
|
||||
const artifact = { selftest: true, note: '非门禁产物,仅验证落盘路径逻辑', passed: true };
|
||||
const roundLikeDir = join(sandbox, `docs/acceptance/${today}-axe`);
|
||||
const pointerFile = join(sandbox, `${LATEST_POINTER_DIR}/axe-evidence.json`);
|
||||
const written = writeEvidence(artifact, { runDate: today, out: roundLikeDir, file: join(roundLikeDir, 'axe-evidence.json'), latest: pointerFile });
|
||||
pushCheck(existsSync(written.file), `轮次证据文件已写出:${written.file}`);
|
||||
pushCheck(existsSync(written.latest), `latest 指针副本已写出:${written.latest}`);
|
||||
pushCheck(
|
||||
readFileSync(written.file, 'utf8') === readFileSync(written.latest, 'utf8'),
|
||||
'轮次证据与 latest 指针内容逐字节一致',
|
||||
);
|
||||
// 反例:只给 out/file(latest=null)时不得在指针位置凭空造文件
|
||||
const noPointerDir = join(sandbox, 'no-pointer');
|
||||
writeEvidence(artifact, { runDate: today, out: noPointerDir, file: join(noPointerDir, 'axe-evidence.json'), latest: null });
|
||||
pushCheck(!existsSync(join(noPointerDir, LATEST_POINTER_DIR)), 'latest 为 null 时不产生任何指针文件');
|
||||
} finally {
|
||||
rmSync(sandbox, { recursive: true, force: true });
|
||||
}
|
||||
const failed = checks.filter((c) => !c.ok);
|
||||
for (const c of checks) console.log(`${c.ok ? '✓' : '✗'} ${c.msg}`);
|
||||
if (failed.length > 0) {
|
||||
console.error(`\nFAIL: axe 证据路径 selftest ${failed.length} 项未通过`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('SELFTEST PASSED(未触碰 docs/,未启动浏览器)');
|
||||
process.exit(0);
|
||||
}
|
||||
const TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'];
|
||||
// Lighthouse 12.6.1 不包装这三条 axe 规则,且 presentation-role-conflict 属 best-practice tag(不在 TAGS 内)
|
||||
// ⇒ 只有这里的规则级 runOnly 才真正测到它们;证据链见 docs/acceptance/2026-09-21-gates/final-tree-results.md
|
||||
@@ -273,6 +364,11 @@ push(totalCanonicalCoverage === expectedCanonicalCoverage,
|
||||
|
||||
const artifact = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
runDate: TARGETS.runDate,
|
||||
// 落盘位置写进产物本身:这样即使有人打开的是 latest 指针副本,也能一眼看出它是**哪一轮**跑出来的
|
||||
// (§11.6 那条「引用前必读」的口径提醒,从此由产物自证而不是靠人记)。仓库相对路径,不落机器绝对路径。
|
||||
evidenceRunDir: relative(REPO_ROOT, TARGETS.out),
|
||||
latestPointer: TARGETS.latest ? relative(REPO_ROOT, TARGETS.latest) : null,
|
||||
base: BASE,
|
||||
axeCore: JSON.parse(readFileSync(repoPath('node_modules/axe-core/package.json'), 'utf8')).version,
|
||||
routeSource: `${SITEMAP} → ${urls.length} 条路由(sitemap ∪ 预渲染产物 ∪ 站内链接 BFS)`,
|
||||
@@ -298,12 +394,13 @@ const artifact = {
|
||||
summary,
|
||||
rows,
|
||||
};
|
||||
mkdirSync(OUT, { recursive: true });
|
||||
writeFileSync(`${OUT}/axe-evidence.json`, JSON.stringify(artifact, null, 2));
|
||||
writeEvidence(artifact, TARGETS);
|
||||
console.log('\nSUMMARY', JSON.stringify(summary, null, 2));
|
||||
console.log('PASSED =', artifact.passed);
|
||||
console.log(`证据已按轮次写入 ${relative(REPO_ROOT, TARGETS.file)}` +
|
||||
(TARGETS.latest ? `(并刷新 latest 指针 ${relative(REPO_ROOT, TARGETS.latest)})` : '(显式 OUT,未刷新 latest 指针)'));
|
||||
if (!artifact.passed) {
|
||||
console.error(`\nFAIL: axe 节点计数门禁 ${failures.length} 条判据未通过(证据已写入 ${OUT}/axe-evidence.json)`);
|
||||
console.error(`\nFAIL: axe 节点计数门禁 ${failures.length} 条判据未通过(证据已写入 ${relative(REPO_ROOT, TARGETS.file)})`);
|
||||
for (const f of failures) console.error(` ✗ ${f}`);
|
||||
process.exit(1);
|
||||
}
|
||||
Reference in new issue
Block a user