Files
Jyotisha/frontend/tests/class-name-definition-contract.test.ts
T
Jesse_ChenandClaude Opus 5.5 de9d4826c1 #111 第 3 轮:建档不退回加载、右栏能拖宽、清单不迟到、月亮问句与别人的上升句(BUG-1455~1459)
- 建档重读人物名单时保留旧名单,失败也不卡在加载画面(BUG-1455)
- 对话右栏改用自己的拖宽把手,侧栏与右栏都能用方向键(BUG-1456/1457)
- 启程清单胶囊和首页一起出来,读状态时用上次的样子占位(BUG-1458)
- 起步第一问与别人的天空过场读一次已算好的星盘取星座,上升只在不会换座时用(BUG-1459,产品 10-27 同意)
- 补回删减的断言与三栏说明;登录代码改回原样,替身放进测试;删旧校正画面的无用样式
- 首屏 +7.54% 产品已接受,写进 DESIGN

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LutgzyJqNhPpZy1nFsJtN3
2026-10-27 10:24:57 +08:00

148 lines
6.6 KiB
TypeScript

import assert from "node:assert/strict";
import { readFileSync, readdirSync } from "node:fs";
import test from "node:test";
// Guards the defect class behind BUG-434 / BUG-435: a className the CSS never
// defines renders as an unstyled element and silently breaks the layout, with
// nothing in the build or the type checker to catch it.
//
// Scope: only the project's own class families. A token counts as ours when its
// first segment already names a family in our CSS (`paywall-`, `message-`,
// `dialog-`, `danger-`, ...), which keeps Tailwind utilities out without having
// to enumerate them.
const projectRoot = new URL("../", import.meta.url);
const sourceRoot = new URL("src/", projectRoot);
const walk = (dir: URL, ext: readonly string[]): string[] =>
readdirSync(dir, { recursive: true, encoding: "utf8" })
.filter((entry) => ext.some((suffix) => entry.endsWith(suffix)))
.map((entry) => `src/${entry.split("\\").join("/")}`);
const read = (path: string) => readFileSync(new URL(path, projectRoot), "utf8");
const styleSheets = walk(sourceRoot, [".css"]).map(read);
const componentFiles = walk(sourceRoot, [".tsx", ".ts"]);
// Boundary pages under the root layout carry their rules in an inline <style>.
const inlineStyles = componentFiles.flatMap((path) =>
[...read(path).matchAll(/<style>\{`([\s\S]*?)`\}<\/style>/g)].map((hit) => hit[1]));
// Comments are stripped first: a class name that only survives in a `/* ... */`
// note is not a definition, and counting it would hide exactly the bug we want.
const styleSource = [...styleSheets, ...inlineStyles].join("\n").replace(/\/\*[\s\S]*?\*\//g, " ");
const definedClasses = new Set(
[...styleSource.matchAll(/\.(-?[A-Za-z_][A-Za-z0-9_-]*)/g)].map((hit) => hit[1]),
);
const projectFamilies = new Set([...definedClasses].map((name) => name.split("-")[0]));
// Tailwind utilities whose first segment collides with one of our families.
const tailwindCollisions = new Set([
"inline-flex", "inline-block", "inline-grid", "inline-table",
"select-none", "select-all", "select-text", "select-auto",
]);
// Classes that carry no styling on purpose: dead modifiers on already-styled
// elements, or hooks handed to a component that styles itself. Each one is a
// no-op today; the point of listing them is that a NEW undefined class fails.
//
// The `is-*` entries are state hooks whose visual is carried by a sibling
// element instead — the thinking step's marker icon, the board minute's
// "当前时间" / "已更新" note. `is-changed` left this list in BUG-622 once
// `.personal-report-chart-cell.is-changed` got a fill/stroke rule.
// `sidebar-header` and `chart-nav` land on shadcn components that style
// themselves. The rest are modifiers sitting beside an already-styled class
// on the same element.
const knownUnstyled = new Set([
// 原值:白名单含 birth-time-evidence-receipt
// 新值:删掉这一项
// 原因:唯一使用者随六个旧校正组件删除,白名单不得留陈旧条目
// 原值:is-done 在白名单里,因为当时没有样式。
// 新值:删掉。chart-page-dasha-panel、chat-chart-resize-handle 加入。
// 原因:启程进度条已经给 li.is-done 上色。下面这几个类名落在自己会画样式的
// 折叠内容、分栏、侧栏导航和手机侧栏上,类名只是钩子。
// 原值:chat-chart-resize-handle 在白名单里(落在组件库分栏把手上,由组件自己画)
// 新值:删掉这一项
// 原因:对话右栏改成自己的拖宽把手(BUG-1456),样式表里有了这个类的规则
"chart-page-dasha-panel",
"sidebar-nav-item",
"sidebar-sheet",
"is-live",
"is-working",
"onboarding-step-card",
// 原值:白名单含 personal-report-additional-charts
// 新值:删除这一项
// 原因:唯一使用者随 BUG-1342 删除,白名单不得留陈旧条目
"rectification-terminal-actions",
"rectification-terminal-note",
"sidebar-header",
]);
/** Static class tokens; `${...}` holes split the string and their ragged edges are dropped. */
function staticClassTokens(source: string): string[] {
const segments = [...source.matchAll(/className\s*=\s*"([^"]*)"/g)].map((hit) => hit[1]);
for (const opener of source.matchAll(/className\s*=\s*\{/g)) {
let depth = 1;
let cursor = opener.index + opener[0].length;
const start = cursor;
while (cursor < source.length && depth > 0) {
if (source[cursor] === "{") depth += 1;
else if (source[cursor] === "}") depth -= 1;
cursor += 1;
}
const expression = source.slice(start, cursor - 1);
for (const literal of expression.matchAll(/`([^`]*)`|"([^"]*)"|'([^']*)'/g)) {
segments.push(literal[1] ?? literal[2] ?? literal[3] ?? "");
}
}
return segments.flatMap((segment) => (
` ${segment} `.split(/\$\{[^}]*\}/).flatMap((piece) => {
const tokens = piece.split(/\s+/).filter(Boolean);
if (!/^\s/.test(piece)) tokens.shift();
if (!/\s$/.test(piece)) tokens.pop();
return tokens;
})
));
}
const ownershipSuspects = new Map<string, Set<string>>();
for (const path of componentFiles) {
for (const token of staticClassTokens(read(path))) {
if (definedClasses.has(token)) continue;
if (tailwindCollisions.has(token)) continue;
if (!token.includes("-") || /[:[\]()/@!$.{}]/.test(token)) continue;
if (!projectFamilies.has(token.split("-")[0])) continue;
const seen = ownershipSuspects.get(token) ?? new Set<string>();
seen.add(path);
ownershipSuspects.set(token, seen);
}
}
test("every project class a component renders has a rule in our CSS", () => {
const undefinedClasses = [...ownershipSuspects.entries()]
.filter(([name]) => !knownUnstyled.has(name))
.map(([name, files]) => `${name} (${[...files].sort().join(", ")})`)
.sort();
assert.deepEqual(
undefinedClasses,
[],
"These class names style nothing. Define them in CSS, drop them, or add them "
+ "to knownUnstyled with a reason:\n " + undefinedClasses.join("\n "),
);
});
test("the knownUnstyled allowlist has no stale entries", () => {
// An entry that got a rule, or stopped being rendered, must leave the list —
// otherwise the allowlist grows into a blindfold.
const stale = [...knownUnstyled].filter((name) => (
definedClasses.has(name) || !ownershipSuspects.has(name)
));
assert.deepEqual(stale, [], `no longer undefined-and-used: ${stale.join(", ")}`);
});
test("the guard actually sees the codebase", () => {
assert.ok(componentFiles.length > 100, `only walked ${componentFiles.length} components`);
assert.ok(definedClasses.size > 500, `only parsed ${definedClasses.size} classes`);
assert.ok(projectFamilies.has("paywall") && projectFamilies.has("message"));
});