ztheme-cli 0.0.6 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  > CLI 是本仓原创代码,与 upstream tweakcn 无关。
5
5
 
6
6
  不依赖 shadcn 的主题 CLI。只走 HTTP,不需要 shadcn CLI、不需要 MCP、不需要登录。
7
- 当前版本 **0.0.6**(`npm i -g ztheme-cli` 或 `npx ztheme-cli@0.0.6` 都行,下文统一写 `ztheme`)。
7
+ 当前版本 **0.0.8**(`npm i -g ztheme-cli` 或 `npx ztheme-cli@0.0.8` 都行,下文统一写 `ztheme`)。
8
8
 
9
9
  ## 前提:告诉它站点在哪
10
10
 
@@ -106,7 +106,7 @@ ztheme check --lock --file ztheme/modern-minimal.css --strict
106
106
  ## 7. CI 里最小接入
107
107
 
108
108
  ```yaml
109
- - run: npx ztheme-cli@0.0.6 check --file app/globals.css --rules 你的主题 --strict
109
+ - run: npx ztheme-cli@0.0.8 check --file app/globals.css --rules 你的主题 --strict
110
110
  env:
111
111
  ZTHEME_BASE: https://你的生产站点
112
112
  ```
@@ -153,8 +153,61 @@ ztheme audit . --theme modern-minimal
153
153
  <div className="bg-[#3b82f6]" />
154
154
  ```
155
155
 
156
+ ### 项目规则:`.ztheme/rules.json`
157
+
158
+ audit 默认只把 `rounded-[20px]`、`p-[13px]` 当成「任意值」。要让它按你的设计系统判断,
159
+ 在 `.ztheme/rules.json` 声明阈值:
160
+
161
+ ```json
162
+ {
163
+ "schemaVersion": 1,
164
+ "radius": { "maxRem": 0.5 },
165
+ "spacing": { "baseUnit": 4 }
166
+ }
167
+ ```
168
+
169
+ | 规则 | 触发 | 例子 |
170
+ |---|---|---|
171
+ | `no-excessive-radius` | 声明 `radius.maxRem` 后,圆角超过上限 | `rounded-[20px]`(1.25rem > 0.5rem)→ 建议 `rounded-lg` |
172
+ | `no-off-grid-spacing` | 声明 `spacing.baseUnit` 后,间距不是基准的整数倍 | `p-[13px]` → 建议 `p-3` |
173
+
174
+ 判定落在 `rounded-*` 与 `p/m/gap/space-*` 上。**合规的值不再报**(规则的价值就是降噪);
175
+ 判不了的值(`calc()`、`var()`、百分比、`em`、负值)退回通用规则,不静默放行。
176
+ `w-*` / `h-*` / `size-*` / `text-*` 不受间距政策约束——布局尺寸常常是有意的。
177
+
178
+ 严重级别仍然只写在 `.ztheme/audit.json` 的 `severity` 里。`rules.json` 写坏(类型错、不是
179
+ JSON)会让 audit 以退出码 2 结束,而不是当作「没有规则」继续扫。
180
+
181
+ > 阈值不自动从主题派生:「主题圆角 0.5rem」推不出「这个项目只准用这么大」,后者是团队的决定。
182
+
183
+ ### 自动修:`--fix`
184
+
185
+ ```bash
186
+ ztheme audit . --fix # 只打印 patch,不改任何文件
187
+ ztheme audit . --fix --write # 真正落盘,写完自动重扫并报告剩余
188
+ ztheme audit . --fix --json # fixes 数组 + diff,仍然不写盘
189
+ ```
190
+
191
+ 能自动修的三类:圆角/间距政策命中(换成规则允许的档位)、颜色命中(换成对应的 token 类,
192
+ 如 `bg-[#3b82f6]` → `bg-primary`)、行内纯颜色(换成 `var(--token)`)。`style` 里的
193
+ `boxShadow` 这类组合值不修——换掉整段会丢语义。`no-hardcoded-color` 永不自动修:
194
+ 在 TS 常量里塞 `var()` 是错的。
195
+
196
+ 每条修复带 `confidence`:
197
+
198
+ | 值 | 含义 | 处理建议 |
199
+ |---|---|---|
200
+ | `policy` | 违反了 `.ztheme/rules.json` 声明的上限 | 直接接受 |
201
+ | `exact` | 与某个 token 肉眼同色(ΔE < 2) | 直接接受 |
202
+ | `near` | 近似色或就近取整 | **先看**:dry-run 会把它们单独列出来 |
203
+
204
+ diff 是逐行的(`--- a/` / `+++ b/`),所有替换都不增删换行,所以行号与原文一一对应。
205
+ `--write` 只改命中的那几个字符,文件其余字节(包括 CRLF)不动。
206
+
156
207
  在 PR 里自动评论(复用 workflow,不单独装 App):
157
208
 
209
+
210
+
158
211
  ```yaml
159
212
  name: PR
160
213
  on: pull_request
@@ -186,6 +239,7 @@ workflow 按 `<!-- ztheme-audit -->` 更新同一条评论,不刷屏;完整
186
239
  | `init <slug> [--dir .]` | 生成 CSS + `AGENTS.md` 片段 + 主题锁 |
187
240
  | `check --lock [--file <css>]` | 与锁文件比对,报漂移 |
188
241
  | `audit [path] [--json] [--theme <slug>] [--max-warnings n]` | 扫组件源码里的硬编码颜色与任意值 |
242
+ | `audit [path] --fix [--write]` | 打印可审阅的 patch;`--write` 才落盘 |
189
243
  | `--help` | 打印用法 |
190
244
 
191
245
  退出码:`0` 通过;`1` `--strict` 下出现「建议修」或「无法判定」,或有漂移,或 audit 有
@@ -201,6 +255,24 @@ error / 超过 `--max-warnings`;`2` audit 的参数、配置或扫描错误。
201
255
 
202
256
  ## 变更记录
203
257
 
258
+ ### 0.0.8
259
+
260
+ - 新增 `audit --fix`:把建议落成可审阅的逐行 patch,**默认不写盘**,`--write` 才落盘。
261
+ - 每条修复带 `confidence`(`policy` / `exact` / `near`);近似色与就近取整单列提示。
262
+ - 行内颜色只修纯颜色值(`color: "#666"` → `var(--muted-foreground)`),组合值不碰;
263
+ `no-hardcoded-color` 永不自动修。
264
+ - 修复顺带修正了行内颜色定位偏移:此前 `style` 的 `{{` 之后 8 个字符没算进列号。
265
+ - `--fix --json` 输出 `fixes` / `diff` / `written`,`schemaVersion` 仍为 1。
266
+
267
+ ### 0.0.7
268
+
269
+ - 新增项目规则 `.ztheme/rules.json`:`radius.maxRem` 与 `spacing.baseUnit` 两条可声明阈值,
270
+ 对应 audit 规则 `no-excessive-radius` / `no-off-grid-spacing`。
271
+ - findings 增加 `policy` / `expected` / `actual`;人类输出直接显示期望值(如「期望 4 的倍数」
272
+ 并建议 `p-3`)。
273
+ - 规则判定合规的任意值不再报(降噪);判不了的值仍交给通用规则,不静默放行。
274
+ - `rules.json` 类型错误或不是 JSON 时退出码为 2,不会当作「没有规则」继续扫。
275
+
204
276
  ### 0.0.6
205
277
 
206
278
  - 新增 `audit`:扫描 TSX/JSX/TS/JS 里的任意色值、任意尺寸、行内颜色;命中颜色时给最近的
package/audit.mjs CHANGED
@@ -8,6 +8,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
8
8
  import { join, sep } from "node:path";
9
9
 
10
10
  import { deltaE, parseColor } from "./color.mjs";
11
+ import { RULE_RADIUS, classifySize } from "./rules.mjs";
11
12
 
12
13
  export const TOOL = "ztheme-cli";
13
14
  export const SCHEMA_VERSION = 1;
@@ -26,6 +27,10 @@ export const DEFAULT_SEVERITY = {
26
27
  "no-arbitrary-size": "warn",
27
28
  "no-inline-color": "warn",
28
29
  "no-hardcoded-color": "off",
30
+ // 这两条只在 .ztheme/rules.json 声明了对应阈值时才会出手;默认级别只影响
31
+ // 声明之后的阻断与否,不会凭空产生命中。
32
+ "no-excessive-radius": "warn",
33
+ "no-off-grid-spacing": "warn",
29
34
  };
30
35
 
31
36
  const DEFAULT_INCLUDE = ["app", "components", "src", "pages"];
@@ -201,7 +206,7 @@ function buildPalette(theme) {
201
206
  return palette;
202
207
  }
203
208
 
204
- function suggestColor(value, palette) {
209
+ function suggestColorMatch(value, palette) {
205
210
  if (!palette.size) return null;
206
211
  const parsed = parseColor(value) ?? parseColor(extractColor(value) ?? "");
207
212
  if (!parsed) return null;
@@ -211,7 +216,11 @@ function suggestColor(value, palette) {
211
216
  if (!best || distance < best.distance) best = { token, distance };
212
217
  }
213
218
  if (!best || best.distance >= 10) return null;
214
- return "--" + best.token;
219
+ return { suggestion: "--" + best.token, distance: best.distance };
220
+ }
221
+
222
+ function suggestColor(value, palette) {
223
+ return suggestColorMatch(value, palette)?.suggestion ?? null;
215
224
  }
216
225
 
217
226
  function ignoredLinesOf(lines) {
@@ -253,6 +262,7 @@ function isCommentLine(text, starts, index) {
253
262
  * @param {string[]} [options.exclude]
254
263
  * @param {{ slug?: string | null, source?: string, tokens?: { light?: Record<string,string>, dark?: Record<string,string> } }} [options.theme]
255
264
  * @param {Record<string, string>} [options.severity]
265
+ * @param {{ radius?: { maxRem: number } | null, spacing?: { baseUnit: number } | null } | null} [options.rules]
256
266
  * @param {Array<{ rule?: string, file?: string, value?: string }>} [options.ignore]
257
267
  * @param {Date} [options.now]
258
268
  */
@@ -264,6 +274,7 @@ export async function auditProject(options) {
264
274
  const effectiveInclude = include.length ? include : ["."];
265
275
  const exclude = [...DEFAULT_EXCLUDE, ...(options.exclude ?? [])];
266
276
  const severity = { ...DEFAULT_SEVERITY, ...(options.severity ?? {}) };
277
+ const policy = options.rules ?? null;
267
278
  const ignoreConfig = options.ignore ?? [];
268
279
  const palette = buildPalette(options.theme);
269
280
  const theme = {
@@ -279,7 +290,7 @@ export async function auditProject(options) {
279
290
  let scannedFiles = 0;
280
291
  let summaryIgnored = 0;
281
292
 
282
- const addFinding = (file, starts, index, rule, value, evidence, suggestion) => {
293
+ const addFinding = (file, starts, index, rule, value, evidence, suggestion, extra = null) => {
283
294
  const level = severity[rule] ?? "off";
284
295
  if (level === "off") return;
285
296
  const { line, column } = positionAt(starts, index);
@@ -295,6 +306,12 @@ export async function auditProject(options) {
295
306
  value,
296
307
  evidence,
297
308
  suggestion: suggestion ?? null,
309
+ policy: extra?.policy ?? null,
310
+ expected: extra?.expected ?? null,
311
+ actual: extra?.actual ?? null,
312
+ // fix 是「可直接落盘的替换」:绝对偏移 + 新文本;confidence 让 --fix 能区分
313
+ // 「可证明等价」(exact / policy)与「近似」(near),后者必须人先看一眼。
314
+ fix: extra?.fix ?? null,
298
315
  });
299
316
  };
300
317
 
@@ -311,7 +328,7 @@ export async function auditProject(options) {
311
328
  const lines = text.split(/\r?\n/);
312
329
  const ignored = ignoredLinesOf(lines);
313
330
 
314
- const emit = (match, rule, value, suggestion) => {
331
+ const emit = (match, rule, value, suggestion, extra) => {
315
332
  const { line } = positionAt(starts, match.index);
316
333
  if (isIgnored(ignored, line, rule)) return "ignored";
317
334
  const ignoreMatch = ignoreConfig.find(
@@ -321,7 +338,7 @@ export async function auditProject(options) {
321
338
  (!entry.file || globToRegExp(entry.file).test(rel))
322
339
  );
323
340
  if (ignoreMatch) return "ignored";
324
- addFinding(rel, starts, match.index, rule, value, match[0], suggestion);
341
+ addFinding(rel, starts, match.index, rule, value, match[0], suggestion, extra);
325
342
  return "added";
326
343
  };
327
344
 
@@ -332,15 +349,49 @@ export async function auditProject(options) {
332
349
  const value = match[1];
333
350
  if (!isColorValue(value) || value.includes("var(")) continue;
334
351
  if (isCommentLine(text, starts, match.index)) continue;
335
- const outcome = emit(match, "no-arbitrary-color", value, suggestColor(value, palette));
352
+ const detail = suggestColorMatch(value, palette);
353
+ let fix = null;
354
+ const bracket = match[0].indexOf("-[");
355
+ if (detail && bracket > 0) {
356
+ fix = {
357
+ start: match.index,
358
+ end: match.index + match[0].length,
359
+ text: match[0].slice(0, bracket) + "-" + detail.suggestion.slice(2),
360
+ confidence: detail.distance < 2 ? "exact" : "near",
361
+ };
362
+ }
363
+ const outcome = emit(match, "no-arbitrary-color", value, detail?.suggestion ?? null, { fix });
336
364
  if (outcome === "ignored") ignoredCount += 1;
337
365
  }
338
366
 
339
367
  R_ARBITRARY_SIZE.lastIndex = 0;
340
368
  for (const match of text.matchAll(R_ARBITRARY_SIZE)) {
341
369
  const value = match[1];
342
- if (isPureColorValue(value) || isNonScaleValue(value)) continue;
343
370
  if (isCommentLine(text, starts, match.index)) continue;
371
+ // 政策优先:声明了阈值就由它决定报不报,合规时静默(这正是规则的价值)。
372
+ // 判不了(calc/var/%/em、负值)时 applies=false,退回通用规则,不静默放行。
373
+ const prefix = match[0].slice(0, match[0].indexOf("-["));
374
+ const verdict = classifySize(prefix, value, policy);
375
+ if (verdict.applies) {
376
+ if (!verdict.ok) {
377
+ const outcome = emit(match, verdict.rule, value, verdict.suggestion, {
378
+ policy: verdict.rule === RULE_RADIUS ? "radius" : "spacing",
379
+ expected: verdict.expected,
380
+ actual: verdict.actual,
381
+ fix: verdict.suggestion
382
+ ? {
383
+ start: match.index,
384
+ end: match.index + match[0].length,
385
+ text: verdict.suggestion,
386
+ confidence: "policy",
387
+ }
388
+ : null,
389
+ });
390
+ if (outcome === "ignored") ignoredCount += 1;
391
+ }
392
+ continue;
393
+ }
394
+ if (isPureColorValue(value) || isNonScaleValue(value)) continue;
344
395
  const outcome = emit(match, "no-arbitrary-size", value, null);
345
396
  if (outcome === "ignored") ignoredCount += 1;
346
397
  }
@@ -349,14 +400,34 @@ export async function auditProject(options) {
349
400
  for (const block of text.matchAll(R_STYLE_BLOCK)) {
350
401
  const blockStart = block.index ?? 0;
351
402
  const body = block[1] ?? "";
403
+ // property.index 是相对 body 的;body 从 `{{` 之后开始。少加这段偏移会让
404
+ // 行内颜色的定位(以及 fix 区间)整体前移 8 个字符。
405
+ const bodyOffset = (block[0] ?? "").indexOf("{{") + 2;
352
406
  R_STYLE_COLOR.lastIndex = 0;
353
407
  for (const property of body.matchAll(R_STYLE_COLOR)) {
354
408
  const rawValue = property[3] ?? "";
355
409
  if (!isColorValue(rawValue) || rawValue.includes("var(")) continue;
356
410
  const value = extractColor(rawValue) ?? rawValue;
357
- const index = blockStart + (property.index ?? 0);
411
+ const index = blockStart + bodyOffset + (property.index ?? 0);
358
412
  const fakeMatch = { index, 0: property[0] };
359
- const outcome = emit(fakeMatch, "no-inline-color", value, suggestColor(value, palette));
413
+ const detail = suggestColorMatch(value, palette);
414
+ // 只修「整个值就是一个颜色」的属性。boxShadow 这类组合值换掉整段会丢语义,
415
+ // 宁可让人手工改。
416
+ let fix = null;
417
+ if (detail && isPureColorValue(rawValue)) {
418
+ const colon = property[0].indexOf(":");
419
+ const quoteAt = property[0].indexOf(property[2], colon + 1);
420
+ if (quoteAt >= 0) {
421
+ const start = index + quoteAt + 1;
422
+ fix = {
423
+ start,
424
+ end: start + rawValue.length,
425
+ text: "var(" + detail.suggestion + ")",
426
+ confidence: detail.distance < 2 ? "exact" : "near",
427
+ };
428
+ }
429
+ }
430
+ const outcome = emit(fakeMatch, "no-inline-color", value, detail?.suggestion ?? null, { fix });
360
431
  if (outcome === "ignored") ignoredCount += 1;
361
432
  }
362
433
  }
@@ -450,6 +521,7 @@ export async function auditProject(options) {
450
521
  include: effectiveInclude,
451
522
  exclude: options.exclude ?? [],
452
523
  severity,
524
+ rules: policy,
453
525
  },
454
526
  summary: {
455
527
  files: scannedFiles,
@@ -514,6 +586,7 @@ export function formatHuman(result, options = {}) {
514
586
  finding.rule +
515
587
  " " +
516
588
  finding.evidence +
589
+ (finding.expected ? " (期望 " + finding.expected + ")" : "") +
517
590
  (finding.suggestion ? " → " + finding.suggestion : "")
518
591
  );
519
592
  }
package/fix.mjs ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * 把 finding 上的 fix 区间落成文本,并打印可审阅的 patch。
3
+ *
4
+ * 所有可修命中都是「同一个 token 内的局部替换」,不会增删换行——因此 applyFixes
5
+ * 之后行数与原文一一对应,diff 只需要逐行比较,不必引入 LCS。
6
+ */
7
+
8
+ /**
9
+ * 应用修复。区间按位置排序后先筛重叠(位置靠前的优先),再从后往前替换,
10
+ * 这样前面区间的偏移不会被后面的长度变化挤走。
11
+ */
12
+ export function applyFixes(text, fixes) {
13
+ if (!Array.isArray(fixes) || fixes.length === 0) return text;
14
+
15
+ const ordered = [...fixes]
16
+ .filter((fix) => Number.isInteger(fix.start) && Number.isInteger(fix.end))
17
+ .filter((fix) => fix.start >= 0 && fix.end >= fix.start)
18
+ .sort((left, right) => left.start - right.start);
19
+
20
+ const accepted = [];
21
+ let end = -1;
22
+ for (const fix of ordered) {
23
+ if (fix.start < end) continue; // 与前一个已接受区间重叠:跳过,不制造坏代码
24
+ accepted.push(fix);
25
+ end = fix.end;
26
+ }
27
+
28
+ let output = text;
29
+ for (let index = accepted.length - 1; index >= 0; index--) {
30
+ const fix = accepted[index];
31
+ output = output.slice(0, fix.start) + fix.text + output.slice(fix.end);
32
+ }
33
+ return output;
34
+ }
35
+
36
+ function splitLines(text) {
37
+ const lines = text.split("\n");
38
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
39
+ return lines;
40
+ }
41
+
42
+ const stripCr = (line) => (line.endsWith("\r") ? line.slice(0, -1) : line);
43
+
44
+ /**
45
+ * 逐行 diff。`context` 是改动行上下文行数;相邻 hunk 自动合并。
46
+ * 行数不变是 applyFixes 的保证,这里仍按两边的最大长度遍历,避免越界。
47
+ */
48
+ export function diffLines(file, before, after, context = 3) {
49
+ if (before === after) return "";
50
+
51
+ const oldLines = splitLines(before);
52
+ const newLines = splitLines(after);
53
+ const total = Math.max(oldLines.length, newLines.length);
54
+
55
+ const changed = [];
56
+ for (let index = 0; index < total; index++) {
57
+ if ((oldLines[index] ?? "") !== (newLines[index] ?? "")) changed.push(index);
58
+ }
59
+ if (changed.length === 0) return "";
60
+
61
+ const hunks = [];
62
+ for (const index of changed) {
63
+ const start = Math.max(0, index - context);
64
+ const end = Math.min(total - 1, index + context);
65
+ const last = hunks[hunks.length - 1];
66
+ if (last && start <= last.end + 1) last.end = Math.max(last.end, end);
67
+ else hunks.push({ start, end });
68
+ }
69
+
70
+ const output = ["--- a/" + file, "+++ b/" + file];
71
+ for (const hunk of hunks) {
72
+ const count = hunk.end - hunk.start + 1;
73
+ output.push(
74
+ "@@ -" + (hunk.start + 1) + "," + count + " +" + (hunk.start + 1) + "," + count + " @@"
75
+ );
76
+ for (let index = hunk.start; index <= hunk.end; index++) {
77
+ const oldLine = oldLines[index] ?? "";
78
+ const newLine = newLines[index] ?? "";
79
+ if (oldLine === newLine) {
80
+ output.push(" " + stripCr(oldLine));
81
+ } else {
82
+ output.push("-" + stripCr(oldLine));
83
+ output.push("+" + stripCr(newLine));
84
+ }
85
+ }
86
+ }
87
+ return output.join("\n");
88
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ztheme-cli",
3
- "version": "0.0.6",
3
+ "version": "0.0.8",
4
4
  "description": "Ztheme 主题 CLI:从站点拉取主题 CSS 变量,并在仓库里扫设计漂移",
5
5
  "type": "module",
6
6
  "bin": {
@@ -10,6 +10,8 @@
10
10
  "ztheme.mjs",
11
11
  "audit.mjs",
12
12
  "color.mjs",
13
+ "rules.mjs",
14
+ "fix.mjs",
13
15
  "README.md",
14
16
  "LICENSE"
15
17
  ],
package/rules.mjs ADDED
@@ -0,0 +1,186 @@
1
+ /**
2
+ * 项目规则(.ztheme/rules.json):校验与判定。
3
+ *
4
+ * 规则只表达阈值(圆角上限、间距基准),不表达严重级别——severity 只放在
5
+ * .ztheme/audit.json 一处,避免两个文件都能改级别时出现「谁生效」的争论。
6
+ *
7
+ * 零依赖、纯函数、无 IO:CLI 负责读文件,这里只负责判断。
8
+ */
9
+ export const RULES_FILE = ".ztheme/rules.json";
10
+ export const RULES_SCHEMA_VERSION = 1;
11
+
12
+ export const RULE_RADIUS = "no-excessive-radius";
13
+ export const RULE_SPACING = "no-off-grid-spacing";
14
+
15
+ const KNOWN_KEYS = ["schemaVersion", "radius", "spacing"];
16
+
17
+ /** Tailwind 默认圆角刻度(rem)。用于在越界时给出「最近的合法档」。 */
18
+ const RADIUS_TIERS = [
19
+ ["sm", 0.125],
20
+ ["md", 0.375],
21
+ ["lg", 0.5],
22
+ ["xl", 0.75],
23
+ ["2xl", 1],
24
+ ["3xl", 1.5],
25
+ ];
26
+
27
+ /** 受间距政策约束的 Tailwind 前缀。布局尺寸(w/h/size)与字号刻意不在内。 */
28
+ const SPACING_PREFIX =
29
+ /^(?:p|px|py|pt|pr|pb|pl|m|mx|my|mt|mr|mb|ml|gap|gap-x|gap-y|space-x|space-y)$/;
30
+
31
+ const fmtRem = (value) => String(Number(value.toFixed(4))) + "rem";
32
+
33
+ /** 单个值 → rem。只认 px/rem/0;负值、百分比、calc/var/em 一律 null(不猜)。 */
34
+ function remOf(value) {
35
+ const raw = value.trim();
36
+ if (raw === "0") return 0;
37
+ let match = raw.match(/^(\d*\.?\d+)rem$/i);
38
+ if (match) return parseFloat(match[1]);
39
+ match = raw.match(/^(\d*\.?\d+)px$/i);
40
+ if (match) return parseFloat(match[1]) / 16;
41
+ return null;
42
+ }
43
+
44
+ /** 单个值 → px(16px = 1rem)。规则同 remOf。 */
45
+ function pxOf(value) {
46
+ const rem = remOf(value);
47
+ return rem === null ? null : Math.round(rem * 16 * 1e6) / 1e6;
48
+ }
49
+
50
+ const splitValues = (value) =>
51
+ String(value)
52
+ .split("_")
53
+ .map((part) => part.trim())
54
+ .filter(Boolean);
55
+
56
+ /** 多值(如 `7px_8px`)取最大;任一值判不了就整体判不了。 */
57
+ export function radiusRemOf(value) {
58
+ let max = null;
59
+ for (const part of splitValues(value)) {
60
+ const rem = remOf(part);
61
+ if (rem === null) return null;
62
+ if (max === null || rem > max) max = rem;
63
+ }
64
+ return max;
65
+ }
66
+
67
+ export function spacingPxOf(value) {
68
+ let max = null;
69
+ for (const part of splitValues(value)) {
70
+ const px = pxOf(part);
71
+ if (px === null) return null;
72
+ if (max === null || px > max) max = px;
73
+ }
74
+ return max;
75
+ }
76
+
77
+ /** 越界时建议「允许范围内最大的那一档」,拼回原前缀(rounded-t → rounded-t-lg)。 */
78
+ export function nearestRadiusClass(prefix, maxRem) {
79
+ const allowed = RADIUS_TIERS.filter(([, rem]) => rem <= maxRem + 1e-9);
80
+ if (!allowed.length) return prefix + "-none";
81
+ return prefix + "-" + allowed[allowed.length - 1][0];
82
+ }
83
+
84
+ /** 间距按基准单位就近取整,拼回原前缀(px → px-3)。 */
85
+ export function nearestSpacingClass(prefix, px, baseUnit) {
86
+ return prefix + "-" + Math.max(0, Math.round(px / baseUnit));
87
+ }
88
+
89
+ /**
90
+ * 政策判定。
91
+ * - `{ applies: false }`:这条值不归政策管(或判不了),调用方继续走通用规则。
92
+ * - `{ applies: true, ok: true }`:合规,调用方应静默(规则的价值就是降噪)。
93
+ * - `{ applies: true, ok: false, ... }`:越界,调用方按 `rule` 报。
94
+ */
95
+ export function classifySize(prefix, value, policy) {
96
+ if (!policy) return { applies: false };
97
+
98
+ if (policy.radius && /^rounded(?:-|$)/.test(prefix)) {
99
+ const rem = radiusRemOf(value);
100
+ if (rem === null) return { applies: false };
101
+ if (rem <= policy.radius.maxRem + 1e-9) return { applies: true, ok: true };
102
+ return {
103
+ applies: true,
104
+ ok: false,
105
+ rule: RULE_RADIUS,
106
+ expected: "≤" + fmtRem(policy.radius.maxRem),
107
+ actual: fmtRem(rem),
108
+ suggestion: nearestRadiusClass(prefix, policy.radius.maxRem),
109
+ };
110
+ }
111
+
112
+ if (policy.spacing && SPACING_PREFIX.test(prefix)) {
113
+ const px = spacingPxOf(value);
114
+ if (px === null) return { applies: false };
115
+ const quotient = px / policy.spacing.baseUnit;
116
+ if (Math.abs(quotient - Math.round(quotient)) < 1e-9) return { applies: true, ok: true };
117
+ return {
118
+ applies: true,
119
+ ok: false,
120
+ rule: RULE_SPACING,
121
+ expected: policy.spacing.baseUnit + " 的倍数",
122
+ actual: px + "px",
123
+ suggestion: nearestSpacingClass(prefix, px, policy.spacing.baseUnit),
124
+ };
125
+ }
126
+
127
+ return { applies: false };
128
+ }
129
+
130
+ export function validateRules(parsed) {
131
+ const warnings = [];
132
+ const errors = [];
133
+ const policy = { radius: null, spacing: null };
134
+
135
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
136
+ return { policy, warnings, errors: ["rules 必须是对象"] };
137
+ }
138
+
139
+ for (const key of Object.keys(parsed)) {
140
+ if (!KNOWN_KEYS.includes(key)) warnings.push("未知配置项 " + key + "(已忽略)");
141
+ }
142
+
143
+ if (parsed.schemaVersion !== undefined && parsed.schemaVersion !== RULES_SCHEMA_VERSION) {
144
+ warnings.push(
145
+ "schemaVersion 是 " + parsed.schemaVersion + ",本工具只认识 " + RULES_SCHEMA_VERSION
146
+ );
147
+ }
148
+
149
+ if (parsed.radius !== undefined) {
150
+ if (!parsed.radius || typeof parsed.radius !== "object" || Array.isArray(parsed.radius)) {
151
+ errors.push("radius 必须是对象");
152
+ } else {
153
+ const maxRem = parsed.radius.maxRem;
154
+ if (maxRem !== undefined) {
155
+ if (typeof maxRem !== "number" || !Number.isFinite(maxRem) || maxRem <= 0) {
156
+ errors.push("radius.maxRem 必须是大于 0 的数字");
157
+ } else {
158
+ policy.radius = { maxRem };
159
+ }
160
+ }
161
+ for (const key of Object.keys(parsed.radius)) {
162
+ if (key !== "maxRem") warnings.push("未知配置项 radius." + key + "(已忽略)");
163
+ }
164
+ }
165
+ }
166
+
167
+ if (parsed.spacing !== undefined) {
168
+ if (!parsed.spacing || typeof parsed.spacing !== "object" || Array.isArray(parsed.spacing)) {
169
+ errors.push("spacing 必须是对象");
170
+ } else {
171
+ const baseUnit = parsed.spacing.baseUnit;
172
+ if (baseUnit !== undefined) {
173
+ if (!Number.isInteger(baseUnit) || baseUnit <= 0) {
174
+ errors.push("spacing.baseUnit 必须是大于 0 的整数");
175
+ } else {
176
+ policy.spacing = { baseUnit };
177
+ }
178
+ }
179
+ for (const key of Object.keys(parsed.spacing)) {
180
+ if (key !== "baseUnit") warnings.push("未知配置项 spacing." + key + "(已忽略)");
181
+ }
182
+ }
183
+ }
184
+
185
+ return { policy, warnings, errors };
186
+ }
package/ztheme.mjs CHANGED
@@ -19,6 +19,8 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSy
19
19
  import { join, resolve } from "node:path";
20
20
 
21
21
  import { auditProject, formatHuman, formatJson } from "./audit.mjs";
22
+ import { applyFixes, diffLines } from "./fix.mjs";
23
+ import { validateRules } from "./rules.mjs";
22
24
 
23
25
  const BASE = (process.env.ZTHEME_BASE ?? "http://localhost:3001").replace(/\/$/, "");
24
26
 
@@ -248,6 +250,26 @@ const loadAuditConfig = (root) => {
248
250
  return { config: parsed, warnings };
249
251
  };
250
252
 
253
+ /**
254
+ * 项目规则:只读阈值(圆角上限、间距基准),级别仍由 audit.json 的 severity 决定。
255
+ * 坏掉的规则文件必须让退出码变成 2——当成「没有规则」继续扫会静默放行。
256
+ */
257
+ const loadAuditRules = (root) => {
258
+ const file = join(root, LOCK_DIR, "rules.json");
259
+ if (!existsSync(file)) return null;
260
+
261
+ let parsed;
262
+ try {
263
+ parsed = JSON.parse(readFileSync(file, "utf8"));
264
+ } catch (error) {
265
+ failWith("无法解析 " + file + ":" + (error?.message ?? error), 2);
266
+ }
267
+ const { policy, warnings, errors } = validateRules(parsed);
268
+ for (const warning of warnings) console.error("[ztheme] 警告:" + warning);
269
+ if (errors.length) failWith("rules.json 无效(" + file + "):" + errors.join(";"), 2);
270
+ return policy;
271
+ };
272
+
251
273
  const readLockFile = (root) => {
252
274
  const file = join(root, LOCK_FILE);
253
275
  if (!existsSync(file)) return null;
@@ -287,6 +309,102 @@ const loadAuditTheme = async (root, slug) => {
287
309
  return { slug, source: "none", tokens: undefined };
288
310
  };
289
311
 
312
+ /**
313
+ * 把 findings 上的 fix 区间按文件归组,算出改前/改后与 patch。
314
+ * 只读不写——落盘是调用方在 --write 时做的事。
315
+ */
316
+ const buildFixPlan = (root, result) => {
317
+ const byFile = new Map();
318
+ for (const finding of result.findings) {
319
+ if (!finding.fix) continue;
320
+ if (!byFile.has(finding.file)) byFile.set(finding.file, []);
321
+ byFile.get(finding.file).push(finding);
322
+ }
323
+
324
+ const files = [];
325
+ const fixes = [];
326
+ const patches = [];
327
+ for (const [file, findings] of byFile) {
328
+ const before = readFileSync(join(root, file), "utf8");
329
+ const after = applyFixes(
330
+ before,
331
+ findings.map((finding) => finding.fix)
332
+ );
333
+ const diff = diffLines(file, before, after);
334
+ files.push({ file, before, after, diff });
335
+ if (diff) patches.push(diff);
336
+ for (const finding of findings) {
337
+ fixes.push({
338
+ file: finding.file,
339
+ line: finding.line,
340
+ column: finding.column,
341
+ rule: finding.rule,
342
+ from: finding.evidence,
343
+ to: finding.fix.text,
344
+ confidence: finding.fix.confidence,
345
+ });
346
+ }
347
+ }
348
+
349
+ fixes.sort(
350
+ (left, right) =>
351
+ left.file.localeCompare(right.file) || left.line - right.line || left.column - right.column
352
+ );
353
+ return {
354
+ files,
355
+ fixes,
356
+ diff: patches.join("\n"),
357
+ near: fixes.filter((fix) => fix.confidence === "near"),
358
+ };
359
+ };
360
+
361
+ const formatFixHuman = (result, plan, options) => {
362
+ const manual = result.findings.length - plan.fixes.length;
363
+ const lines = [];
364
+
365
+ if (!plan.fixes.length) {
366
+ lines.push("没有可自动修的问题(" + manual + " 条需要人工处理)");
367
+ return lines.join("\n");
368
+ }
369
+
370
+ const near = plan.near.length;
371
+ if (options.write) {
372
+ lines.push(
373
+ "已写入 " +
374
+ plan.files.filter((entry) => entry.diff).length +
375
+ " 个文件 · " +
376
+ plan.fixes.length +
377
+ " 处" +
378
+ (near ? "(其中近似 " + near + " 处)" : "")
379
+ );
380
+ lines.push("剩余 " + result.summary.warnings + " 条告警 · " + result.summary.errors + " 条错误");
381
+ } else {
382
+ lines.push(
383
+ "可自动修 " +
384
+ plan.fixes.length +
385
+ " 处" +
386
+ (near ? "(其中近似 " + near + " 处)" : "") +
387
+ ",需人工 " +
388
+ manual +
389
+ " 处"
390
+ );
391
+ }
392
+
393
+ if (near) {
394
+ lines.push("");
395
+ lines.push("近似修复(不是同色,换的是最近的 token / 刻度)请先确认:");
396
+ for (const fix of plan.near.slice(0, 10)) {
397
+ lines.push(" " + fix.file + ":" + fix.line + " " + fix.from + " → " + fix.to);
398
+ }
399
+ }
400
+
401
+ if (plan.diff) {
402
+ lines.push("");
403
+ lines.push(plan.diff);
404
+ }
405
+ return lines.join("\n");
406
+ };
407
+
290
408
 
291
409
  const TOKENS = [
292
410
  "background", "foreground", "card", "card-foreground", "popover", "popover-foreground",
@@ -335,6 +453,7 @@ const main = async () => {
335
453
  ztheme check --lock [--file x.css]
336
454
  与锁文件比对:本地 CSS 变差、或站点主题已更新时报警(--strict 判失败)
337
455
  ztheme audit [path] [--json] [--theme <slug>] [--max-warnings <n>] [--quiet]
456
+ ztheme audit [path] --fix [--write] 打印可审阅的 patch;--write 才落盘
338
457
  扫描 TSX/JSX/TS/JS 里的硬编码颜色与任意值;
339
458
  --json 只输出 JSON;默认只告警,不阻断
340
459
  环境变量:
@@ -654,6 +773,7 @@ const main = async () => {
654
773
 
655
774
  const { config, warnings } = loadAuditConfig(root);
656
775
  for (const warning of warnings) console.error("[ztheme] 警告:" + warning);
776
+ const rules = loadAuditRules(root);
657
777
 
658
778
  const flagTheme = valueOf("theme");
659
779
  const envTheme = process.env.ZTHEME_THEME;
@@ -676,18 +796,44 @@ const main = async () => {
676
796
  maxWarnings = parsed;
677
797
  }
678
798
 
799
+ const fixMode = flags.has("fix");
800
+ const writeMode = flags.has("write");
801
+ if (writeMode && !fixMode) failWith("--write 需要和 --fix 一起用", 2);
802
+
679
803
  const theme = slug ? await loadAuditTheme(root, slug) : null;
680
- const result = await auditProject({
804
+ const scanOptions = {
681
805
  root,
682
806
  include: config.include,
683
807
  exclude: config.exclude,
684
808
  severity: config.severity,
685
809
  ignore: config.ignore,
810
+ rules,
686
811
  theme,
687
- });
688
-
689
- if (flags.has("json")) console.log(formatJson(result));
690
- else console.log(formatHuman(result, { quiet: flags.has("quiet") }));
812
+ };
813
+ let result = await auditProject(scanOptions);
814
+
815
+ if (fixMode) {
816
+ const plan = buildFixPlan(root, result);
817
+ if (writeMode) {
818
+ for (const entry of plan.files) {
819
+ if (!entry.diff) continue;
820
+ writeFileSync(join(root, entry.file), entry.after, "utf8");
821
+ }
822
+ // 写后重扫:报告的是「现在还剩什么」,不是「刚才修了什么」。
823
+ result = await auditProject(scanOptions);
824
+ }
825
+ if (flags.has("json")) {
826
+ console.log(
827
+ formatJson({ ...result, fixes: plan.fixes, diff: plan.diff, written: writeMode })
828
+ );
829
+ } else {
830
+ console.log(formatFixHuman(result, plan, { write: writeMode }));
831
+ }
832
+ } else if (flags.has("json")) {
833
+ console.log(formatJson(result));
834
+ } else {
835
+ console.log(formatHuman(result, { quiet: flags.has("quiet") }));
836
+ }
691
837
 
692
838
  if (result.errors.length > 0) {
693
839
  process.exitCode = 2;