#!/usr/bin/env node /* token-audit.js —— 设计 token 现状审计(只读) * * 用途:给 docs/standards/design-tokens.md 提供可复核的数字,将来也能当「棘轮」基线。 * 不改任何文件;输出 Markdown 表格 + 关键告警。 * * 用法:node scripts/token-audit.js [--json] */ 'use strict' const fs = require('fs') const path = require('path') const ROOT = path.join(__dirname, '..') const read = (p) => { try { return fs.readFileSync(p, 'utf8') } catch (e) { return '' } } const css = read(path.join(ROOT, 'style.css')) const siteCss = read(path.join(ROOT, 'site', 'assets', 'style.css')) function walk (dir, out) { let ents = [] try { ents = fs.readdirSync(dir, { withFileTypes: true }) } catch (e) { return out } for (const e of ents) { const p = path.join(dir, e.name) if (e.isDirectory()) walk(p, out) else if (/\.(css|js)$/i.test(e.name)) out.push(p) } return out } const pluginFiles = walk(path.join(ROOT, 'plugins'), []) const count = (re, src) => (src.match(re) || []).length const uniqSorted = (arr, numeric) => Array.from(new Set(arr)).sort(numeric ? (a, b) => a - b : undefined) /* ---------- 1. 变量:定义 / 引用 / 未定义 / 死变量 ---------- */ // 定义可以写在一行里的任意位置(--rd-sm: 6px; --rd: 8px; 这种),不能只认行首 const defs = uniqSorted((css.match(/(?:^|[\s;{])--[a-z0-9-]+\s*:/gim) || []).map((s) => s.trim().replace(/^[;{]/, '').trim().replace(/\s*:$/, ''))) const refs = uniqSorted((css.match(/var\(\s*--[a-z0-9-]+/gi) || []).map((s) => s.replace(/var\(\s*/, ''))) // 运行时由 JS 写入的变量(app.js / canvas-*.js 里 setProperty),不算缺失 const RUNTIME_SET = new Set(['--iwb-dock-l', '--iwb-dock-r', '--iwb-fb-k', '--iwb-node-color']) const undefinedRefs = refs.filter((r) => !defs.includes(r) && !RUNTIME_SET.has(r)) const usedCount = {} for (const r of refs) usedCount[r] = count(new RegExp('var\\(\\s*' + r + '(?=[,)])', 'g'), css) const deadTokens = defs.filter((d) => !usedCount[d] && !new RegExp('var\\(\\s*' + d + '\\s*[,)]').test(css)) /* ---------- 2. 命名空间:几套并存 ---------- */ const ns = (re) => uniqSorted((css.match(re) || [])).length const namespaces = { '--iwb-*(旧宿主)': ns(/--iwb-[a-z0-9-]+/g), '--sp-*(间距)': ns(/--sp-[a-z0-9-]+/g), '--rd*(圆角)': ns(/--rd[a-z0-9-]*/g), '--fs-*(字号)': ns(/--fs-[a-z0-9-]+/g), '--sh-*(阴影)': ns(/--sh-[a-z0-9-]+/g), '--tr-*(过渡)': ns(/--tr-[a-z0-9-]+/g) } /* ---------- 3. 硬编码 vs token 采用率 ---------- */ const hard = { '十六进制色值': count(/#[0-9a-fA-F]{3,8}\b/g, css), 'rgba()/rgb()': count(/rgba?\([^)]*\)/g, css), 'font-size 写死': count(/font-size:\s*[0-9.]+px/g, css), 'border-radius 写死': count(/border-radius:\s*[0-9.]+px/g, css), 'padding/margin/gap 写死': count(/(?:padding|margin|gap)[a-z-]*:\s*[0-9.]+px/g, css), 'box-shadow 声明': count(/box-shadow\s*:/g, css), 'z-index 声明': count(/z-index\s*:/g, css) } const scale = (re) => { const vals = (css.match(re) || []).map((s) => parseFloat(String(s).match(/[0-9.]+/)[0])) return vals } const fontSizes = scale(/font-size:\s*[0-9.]+px/g) const radii = scale(/border-radius:\s*[0-9.]+px/g) const spacings = scale(/(?:padding|margin|gap)[a-z-]*:\s*[0-9.]+px/g) const zindex = (css.match(/z-index:\s*-?[0-9]+/g) || []).map((s) => parseInt(String(s).match(/-?[0-9]+$/)[0], 10)) const shadows = uniqSorted((css.match(/box-shadow:[^;}]*/g) || []).map((s) => s.replace(/\s+/g, ' ').trim())) const tokenUse = { 'var(--sp-*)': count(/var\(--sp-[0-9]/g, css), 'var(--rd*)': count(/var\(--rd/g, css), 'var(--fs-*)': count(/var\(--fs-[0-9a-z]/g, css), 'var(--sh-*)': count(/var\(--sh-/g, css), 'var(--tr-*)': count(/var\(--tr-/g, css) } /* ---------- 4. 插件侧 ---------- */ const pluginBad = [] for (const f of pluginFiles) { const src = read(f) // 与 tests/plugin-theme-contract-test.js 同口径:只数 background/color/border 声明里直接写 hex const re = /(background(?:-color)?|color|border(?:-color)?)\s*:\s*([^;'"]{0,80})/gi let m let n = 0 while ((m = re.exec(src))) { const val = m[2] if (!/#[0-9a-f]{3,8}/i.test(val)) continue if (/var\(--[a-z0-9-]+\s*,\s*#[0-9a-f]{3,8}/i.test(val)) continue n++ } if (n) pluginBad.push({ file: path.relative(ROOT, f), hex: n }) } const pluginTokenUse = pluginFiles.reduce((a, f) => a + count(/var\(--iwb-/g, read(f)), 0) /* ---------- 5. 官网 / 市场页 ---------- */ const siteVars = uniqSorted((siteCss.match(/--[a-z0-9-]+:/gi) || []).map((s) => s.trim().replace(/:$/, ''))) const report = { cssLines: css.split('\n').length, defs: defs.length, refs: refs.length, undefinedRefs, deadTokens, namespaces, hard, fontSizes: { distinct: uniqSorted(fontSizes, true), count: fontSizes.length }, radii: { distinct: uniqSorted(radii, true), count: radii.length }, spacings: { distinct: uniqSorted(spacings, true), count: spacings.length }, zindex: { distinct: uniqSorted(zindex, true), count: zindex.length }, shadows: { distinct: shadows.length }, tokenUse, pluginBad, pluginTokenUse, siteVars } if (process.argv.includes('--contrast')) { // 复现 docs/standards/design-tokens.md §1.5 的对比度实测(需要 theme-tokens.js 可独立运行) const sandbox = {} try { new Function('window', read(path.join(ROOT, 'src', 'theme-tokens.js')))(sandbox) } catch (e) { console.log('无法加载 theme-tokens.js:' + e.message) process.exit(1) } const T = sandbox.IWBThemeTokens const SURFACES = ['bg', 'panel', 'layer', 'layer2', 'nodeBg', 'canvasBg', 'pluginSurface', 'pluginCard'] for (const dark of [false, true]) { const t = T.derive(T.DEFAULTS, dark) console.log('\n### ' + (dark ? '暗色' : '亮色') + ':文字对各表面(≥4.5 达标)\n') console.log('| 表面 | text | text2 | textDim |\n|---|---|---|---|') for (const s of SURFACES) { const row = ['text', 'text2', 'textDim'].map((f) => { const v = T.contrast(t[f], t[s]).toFixed(2) return Number(v) < 4.5 ? '**' + v + '**' : v }) console.log('| ' + s + ' | ' + row.join(' | ') + ' |') } } console.log('\n### 同名 token:静态 CSS vs derive()(暗色)\n') console.log('| token | `:root` 静态 | derive 默认 |\n|---|---|---|') const STATIC_DARK = { '--iwb-bg': '#757575', '--iwb-panel': '#a5a5a5', '--iwb-layer': '#9c9c9c', '--iwb-layer2': '#b0b0b0', '--iwb-node-bg': '#b3b3b3', '--iwb-text': '#111111', '--iwb-text2': '#2f2f2f' } const d = T.derive(T.DEFAULTS, true) const KEYS = { '--iwb-bg': 'bg', '--iwb-panel': 'panel', '--iwb-layer': 'layer', '--iwb-layer2': 'layer2', '--iwb-node-bg': 'nodeBg', '--iwb-text': 'text', '--iwb-text2': 'text2' } for (const [k, key] of Object.entries(KEYS)) console.log('| `' + k + '` | `' + STATIC_DARK[k] + '` | `' + d[key] + '` |') process.exit(0) } if (process.argv.includes('--json')) { console.log(JSON.stringify(report, null, 2)) process.exit(0) } const pad = (s, n) => String(s) + ' '.repeat(Math.max(0, n - String(s).replace(/[\u4e00-\u9fa5]/g, 'xx').length)) console.log('## 1. 变量规模\n') console.log(`| 指标 | 数值 |\n|---|---|`) console.log(`| style.css 行数 | ${report.cssLines} |`) console.log(`| 定义的 --* 变量 | ${defs.length} |`) console.log(`| 被 var() 引用的变量 | ${refs.length} |`) console.log(`| **引用了但从未定义** | **${undefinedRefs.length}** → ${undefinedRefs.join(' ')} |`) console.log(`| 定义了但从未引用 | ${deadTokens.length} |`) console.log('\n## 2. 命名空间并存\n') console.log('| 命名空间 | 变量个数 |\n|---|---|') for (const [k, v] of Object.entries(namespaces)) console.log(`| ${k} | ${v} |`) console.log('\n## 3. 硬编码 vs token\n') console.log('| 类别 | 写死数量 |\n|---|---|') for (const [k, v] of Object.entries(hard)) console.log(`| ${k} | ${v} |`) console.log('\n基础尺寸 token 实际采用:') for (const [k, v] of Object.entries(tokenUse)) console.log(`- ${k}: ${v} 次`) console.log('\n## 4. 尺度离散度\n') console.log('| 尺度 | 取值种类 | 实际分布 |\n|---|---|---|') console.log(`| 字号 | ${report.fontSizes.distinct.length} | ${report.fontSizes.distinct.join(' / ')} |`) console.log(`| 圆角 | ${report.radii.distinct.length} | ${report.radii.distinct.join(' / ')} |`) console.log(`| 间距 | ${report.spacings.distinct.length} | ${report.spacings.distinct.join(' / ')} |`) console.log(`| z-index | ${report.zindex.distinct.length} | ${report.zindex.distinct.join(' / ')} |`) console.log(`| box-shadow 写法 | ${report.shadows.distinct} | — |`) console.log('\n## 5. 插件侧\n') console.log(`- 插件文件数:${pluginFiles.length},引用 var(--iwb-*) 共 ${pluginTokenUse} 次`) console.log('- 含硬编码 hex 的文件:') for (const p of pluginBad.sort((a, b) => b.hex - a.hex)) console.log(` - ${p.file} → ${p.hex} 处`) console.log('\n## 6. 官网样式\n') console.log(`- site/assets/style.css 定义变量:${siteVars.join(' ') || '(无)'}`)