nex_animation/reports/ui_evidence/nex-p19/deadcss.py

143 lines
7.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""阶段 19 · 产物扫描死 CSS 判定(活体 + 穷举静态)
背景:frontend/dist-b1/(Bundle 取证的对照构建)存在时,Tailwind v4 的自动内容
扫描会把构建产物当源文件读,正式 CSS 因此多出 84 条选择器(≈9.3 kB / 12 %)。
要给 `frontend/dist-*/` 加忽略规则,必须先证明这 84 条**运行时真的是死的**,
不能只靠源码 grep。三条判据同时成立才判定为死:
D1 活体匹配:全 14 路由 × Light/Dark 的实际 DOM,逐条 querySelectorAll 命中 0;
D2 运行时 class 全集:遍历收集的元素 class token,与 84 条类名(按 CSS 转义
规则还原后)交集为空;
D3 静态穷举:把 frontend/src 全文(ts/tsx/css/html)按 CSS 标识符规则切词,
任何一枚候选类名都不作为完整词元出现 ⇒ 拼不出这个类(片段式拼类另由
deadcss-frag.py 证明不存在)。
防呆:登录后必须拿到 pid,且每页必须断言外壳存在 + data-theme 与要求一致,
否则视本行为空跑,直接判失败(上一轮就因为在 :4173 preview 上跑——它不代理
/api——静默退化成登录页,差点把空跑当结论)。
用法:NEX_BASE=http://127.0.0.1:5173 .venv/bin/python reports/ui_evidence/nex-p19/deadcss.py
退出码:0 = 三条全过(死 CSS 成立);1 = 任一不过(不能排除)。
"""
import json, os, re, sys
from playwright.sync_api import sync_playwright
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
BASE = os.environ.get("NEX_BASE", "http://127.0.0.1:5173")
THEMES = os.environ.get("NEX_THEMES", "light,dark").split(",")
WIDTH = int(os.environ.get("NEX_WIDTH", "1440"))
ROUTES = [r for r in os.environ.get(
"NEX_ROUTES",
"/,/assets,/models,/projects/{id}/overview,/projects/{id}/library,"
"/projects/{id}/storyboard,/projects/{id}/dispatch,/projects/{id}/review,"
"/projects/{id}/timeline,/projects/{id}/delivery,/account,/users,/help").split(",") if r]
USER, PWD = os.environ.get("NEX_USER", "admin"), os.environ.get("NEX_PASS", "admin1234")
SELECTORS = json.load(open(os.path.join(HERE, "sel-only-in-distb1.json"), encoding="utf-8"))
sys.path.insert(0, HERE)
from deadcss_lib import css_unescape, selector_tokens, class_tokens, static_tokens
PROJECT_JS = r"""async () => {
const t = localStorage.getItem('nex-auth');
const tok = t ? (JSON.parse(t)?.state?.token || JSON.parse(t)?.token) : '';
const h = {headers: {Authorization: 'Bearer ' + tok}};
const j = await (await fetch('/api/projects', h)).json();
const list = j.projects || j.items || j.data || (Array.isArray(j) ? j : []);
let best = ''; let n = -1;
for (const p of list) {
const s = await (await fetch(`/api/projects/${p.id}/shots`, h)).json();
const c = s.count ?? (s.shots || []).length;
if (c > n) { n = c; best = p.id; }
}
return best || list[0]?.id || '';
}"""
PROBE_JS = r"""(sels) => {
const hits = {};
for (const s of sels) { try { hits[s] = document.querySelectorAll(s).length } catch(e){ hits[s]=-1 } }
const tokens = new Set();
for (const el of document.querySelectorAll('*')) {
const cl = el.getAttribute && el.getAttribute('class');
if (cl) for (const c of cl.split(/\s+/)) if (c) tokens.add(c);
}
return { hits, tokens: [...tokens], theme: document.documentElement.dataset.theme,
shell: { header: !!document.querySelector('header'), aside: !!document.querySelector('aside'),
main: !!document.querySelector('main') },
url: location.pathname };
}"""
def main():
live, errored, warns = {}, {}, []
rt_tokens = set()
nvis = 0
with sync_playwright() as pw:
b = pw.chromium.launch()
pg = b.new_context(viewport={"width": WIDTH, "height": 950}).new_page()
pg.set_default_timeout(20000)
pg.goto(BASE + "/login")
pg.wait_for_selector("#login-user")
pg.fill("#login-user", USER)
pg.fill("#login-pass", PWD)
pg.click("button[type=submit]")
pg.wait_for_url(lambda u: "/login" not in u, timeout=20000)
pid = pg.evaluate(PROJECT_JS)
if not pid:
print("!! 拿不到项目 id —— 后端/登录异常,本次判定作废")
return 1
for theme in THEMES:
for r in ROUTES:
if "{id}" in r:
r = r.replace("{id}", str(pid))
pg.evaluate("(t) => localStorage.setItem('nex-the', t)", theme)
pg.goto(BASE + r)
pg.wait_for_timeout(1100)
res = pg.evaluate(PROBE_JS, SELECTORS)
key = f"{theme} {res['url']}"
if res["theme"] != theme:
warns.append(f"{key}: data-theme={res['theme']} ≠ 要求 {theme}")
if not (res["shell"]["header"] and res["shell"]["main"]):
warns.append(f"{key}: 外壳缺失 header/main(疑似未渲染)")
nvis += 1
rt_tokens |= set(res["tokens"])
for s, n in res["hits"].items():
if n < 0:
errored.setdefault(s, []).append(key)
elif n:
live.setdefault(s, []).append((key, n))
b.close()
for w in warns:
print("!!", w)
ct, nf = class_tokens(os.path.join(ROOT, "frontend", "src"))
raw, nraw = static_tokens(os.path.join(ROOT, "frontend", "src"))
cand = set()
for s in SELECTORS:
cand |= selector_tokens(s)
d1 = sorted(live)
d2 = sorted(cand & rt_tokens)
d3 = sorted(cand & ct) # 判据:类位置
d3raw = sorted(cand & raw) # 诊断:全文切词(会混进属性名/注释,不立案)
print(f"服务={BASE} pid={pid} 遍历={nvis} 页({len(ROUTES)} 路由 × {len(THEMES)} 主题)")
print(f"待判定选择器={len(SELECTORS)} 可求值={len(SELECTORS)-len(errored)} 不可求值={len(errored)}")
print(f"候选类名(还原转义后)= {len(cand)} 枚 样例:{sorted(cand)[:6]}")
print(f"D1 活体命中 = {len(d1)} 条 {[(s, live[s][0]) for s in d1][:8]}")
print(f"D2 运行时 class 交集 = {len(d2)} 枚 {d2[:12]} (运行时 token 全集 {len(rt_tokens)} 枚)")
print(f"D3 类位置词元交集 = {len(d3)} 枚 {d3[:12]} (扫描 {nf} 个 .tsx,类位置词元 {len(ct)} 枚)")
print(" 诊断·全文切词交集 = %d 枚 %s(扫 %d 文件得 %d 枚词元;这些命中都是 CSS 属性名/"
"属性值/注释散文/arbitrary-value 内部,不在类位置,故不立案)"
% (len(d3raw), d3raw, nraw, len(raw)))
for s, v in sorted(errored.items()):
print(f" ERR {s} → {v[:2]}")
ok = not warns and not d1 and not d2 and not d3 and not errored
json.dump({"base": BASE, "pages": nvis, "selectors": len(SELECTORS),
"D1_live": d1, "D2_runtime_intersect": d2, "D3_source_intersect": d3,
"errored": {k: v for k, v in errored.items()}, "warns": warns,
"runtime_tokens": len(rt_tokens), "classpos_tokens": len(ct),
"D3_fulltext_diagnostic": d3raw},
open(os.path.join(HERE, "deadcss-result.json"), "w"), ensure_ascii=False, indent=1)
print("结论:", "三条判据全过 → 84 条确认死 CSS,忽略规则可安全落地"
if ok else "未全过 → 不能直接排除,逐条复核")
return 0 if ok else 1
sys.exit(main())