ztheme-cli 0.0.6 → 0.0.7

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.7**(`npm i -g ztheme-cli` 或 `npx ztheme-cli@0.0.7` 都行,下文统一写 `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.7 check --file app/globals.css --rules 你的主题 --strict
110
110
  env:
111
111
  ZTHEME_BASE: https://你的生产站点
112
112
  ```
@@ -153,8 +153,37 @@ 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
+
156
183
  在 PR 里自动评论(复用 workflow,不单独装 App):
157
184
 
185
+
186
+
158
187
  ```yaml
159
188
  name: PR
160
189
  on: pull_request
@@ -201,6 +230,15 @@ error / 超过 `--max-warnings`;`2` audit 的参数、配置或扫描错误。
201
230
 
202
231
  ## 变更记录
203
232
 
233
+ ### 0.0.7
234
+
235
+ - 新增项目规则 `.ztheme/rules.json`:`radius.maxRem` 与 `spacing.baseUnit` 两条可声明阈值,
236
+ 对应 audit 规则 `no-excessive-radius` / `no-off-grid-spacing`。
237
+ - findings 增加 `policy` / `expected` / `actual`;人类输出直接显示期望值(如「期望 4 的倍数」
238
+ 并建议 `p-3`)。
239
+ - 规则判定合规的任意值不再报(降噪);判不了的值仍交给通用规则,不静默放行。
240
+ - `rules.json` 类型错误或不是 JSON 时退出码为 2,不会当作「没有规则」继续扫。
241
+
204
242
  ### 0.0.6
205
243
 
206
244
  - 新增 `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"];
@@ -253,6 +258,7 @@ function isCommentLine(text, starts, index) {
253
258
  * @param {string[]} [options.exclude]
254
259
  * @param {{ slug?: string | null, source?: string, tokens?: { light?: Record<string,string>, dark?: Record<string,string> } }} [options.theme]
255
260
  * @param {Record<string, string>} [options.severity]
261
+ * @param {{ radius?: { maxRem: number } | null, spacing?: { baseUnit: number } | null } | null} [options.rules]
256
262
  * @param {Array<{ rule?: string, file?: string, value?: string }>} [options.ignore]
257
263
  * @param {Date} [options.now]
258
264
  */
@@ -264,6 +270,7 @@ export async function auditProject(options) {
264
270
  const effectiveInclude = include.length ? include : ["."];
265
271
  const exclude = [...DEFAULT_EXCLUDE, ...(options.exclude ?? [])];
266
272
  const severity = { ...DEFAULT_SEVERITY, ...(options.severity ?? {}) };
273
+ const policy = options.rules ?? null;
267
274
  const ignoreConfig = options.ignore ?? [];
268
275
  const palette = buildPalette(options.theme);
269
276
  const theme = {
@@ -279,7 +286,7 @@ export async function auditProject(options) {
279
286
  let scannedFiles = 0;
280
287
  let summaryIgnored = 0;
281
288
 
282
- const addFinding = (file, starts, index, rule, value, evidence, suggestion) => {
289
+ const addFinding = (file, starts, index, rule, value, evidence, suggestion, extra = null) => {
283
290
  const level = severity[rule] ?? "off";
284
291
  if (level === "off") return;
285
292
  const { line, column } = positionAt(starts, index);
@@ -295,6 +302,9 @@ export async function auditProject(options) {
295
302
  value,
296
303
  evidence,
297
304
  suggestion: suggestion ?? null,
305
+ policy: extra?.policy ?? null,
306
+ expected: extra?.expected ?? null,
307
+ actual: extra?.actual ?? null,
298
308
  });
299
309
  };
300
310
 
@@ -311,7 +321,7 @@ export async function auditProject(options) {
311
321
  const lines = text.split(/\r?\n/);
312
322
  const ignored = ignoredLinesOf(lines);
313
323
 
314
- const emit = (match, rule, value, suggestion) => {
324
+ const emit = (match, rule, value, suggestion, extra) => {
315
325
  const { line } = positionAt(starts, match.index);
316
326
  if (isIgnored(ignored, line, rule)) return "ignored";
317
327
  const ignoreMatch = ignoreConfig.find(
@@ -321,7 +331,7 @@ export async function auditProject(options) {
321
331
  (!entry.file || globToRegExp(entry.file).test(rel))
322
332
  );
323
333
  if (ignoreMatch) return "ignored";
324
- addFinding(rel, starts, match.index, rule, value, match[0], suggestion);
334
+ addFinding(rel, starts, match.index, rule, value, match[0], suggestion, extra);
325
335
  return "added";
326
336
  };
327
337
 
@@ -339,8 +349,23 @@ export async function auditProject(options) {
339
349
  R_ARBITRARY_SIZE.lastIndex = 0;
340
350
  for (const match of text.matchAll(R_ARBITRARY_SIZE)) {
341
351
  const value = match[1];
342
- if (isPureColorValue(value) || isNonScaleValue(value)) continue;
343
352
  if (isCommentLine(text, starts, match.index)) continue;
353
+ // 政策优先:声明了阈值就由它决定报不报,合规时静默(这正是规则的价值)。
354
+ // 判不了(calc/var/%/em、负值)时 applies=false,退回通用规则,不静默放行。
355
+ const prefix = match[0].slice(0, match[0].indexOf("-["));
356
+ const verdict = classifySize(prefix, value, policy);
357
+ if (verdict.applies) {
358
+ if (!verdict.ok) {
359
+ const outcome = emit(match, verdict.rule, value, verdict.suggestion, {
360
+ policy: verdict.rule === RULE_RADIUS ? "radius" : "spacing",
361
+ expected: verdict.expected,
362
+ actual: verdict.actual,
363
+ });
364
+ if (outcome === "ignored") ignoredCount += 1;
365
+ }
366
+ continue;
367
+ }
368
+ if (isPureColorValue(value) || isNonScaleValue(value)) continue;
344
369
  const outcome = emit(match, "no-arbitrary-size", value, null);
345
370
  if (outcome === "ignored") ignoredCount += 1;
346
371
  }
@@ -450,6 +475,7 @@ export async function auditProject(options) {
450
475
  include: effectiveInclude,
451
476
  exclude: options.exclude ?? [],
452
477
  severity,
478
+ rules: policy,
453
479
  },
454
480
  summary: {
455
481
  files: scannedFiles,
@@ -514,6 +540,7 @@ export function formatHuman(result, options = {}) {
514
540
  finding.rule +
515
541
  " " +
516
542
  finding.evidence +
543
+ (finding.expected ? " (期望 " + finding.expected + ")" : "") +
517
544
  (finding.suggestion ? " → " + finding.suggestion : "")
518
545
  );
519
546
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ztheme-cli",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "description": "Ztheme 主题 CLI:从站点拉取主题 CSS 变量,并在仓库里扫设计漂移",
5
5
  "type": "module",
6
6
  "bin": {
@@ -10,6 +10,7 @@
10
10
  "ztheme.mjs",
11
11
  "audit.mjs",
12
12
  "color.mjs",
13
+ "rules.mjs",
13
14
  "README.md",
14
15
  "LICENSE"
15
16
  ],
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,7 @@ 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 { validateRules } from "./rules.mjs";
22
23
 
23
24
  const BASE = (process.env.ZTHEME_BASE ?? "http://localhost:3001").replace(/\/$/, "");
24
25
 
@@ -248,6 +249,26 @@ const loadAuditConfig = (root) => {
248
249
  return { config: parsed, warnings };
249
250
  };
250
251
 
252
+ /**
253
+ * 项目规则:只读阈值(圆角上限、间距基准),级别仍由 audit.json 的 severity 决定。
254
+ * 坏掉的规则文件必须让退出码变成 2——当成「没有规则」继续扫会静默放行。
255
+ */
256
+ const loadAuditRules = (root) => {
257
+ const file = join(root, LOCK_DIR, "rules.json");
258
+ if (!existsSync(file)) return null;
259
+
260
+ let parsed;
261
+ try {
262
+ parsed = JSON.parse(readFileSync(file, "utf8"));
263
+ } catch (error) {
264
+ failWith("无法解析 " + file + ":" + (error?.message ?? error), 2);
265
+ }
266
+ const { policy, warnings, errors } = validateRules(parsed);
267
+ for (const warning of warnings) console.error("[ztheme] 警告:" + warning);
268
+ if (errors.length) failWith("rules.json 无效(" + file + "):" + errors.join(";"), 2);
269
+ return policy;
270
+ };
271
+
251
272
  const readLockFile = (root) => {
252
273
  const file = join(root, LOCK_FILE);
253
274
  if (!existsSync(file)) return null;
@@ -654,6 +675,7 @@ const main = async () => {
654
675
 
655
676
  const { config, warnings } = loadAuditConfig(root);
656
677
  for (const warning of warnings) console.error("[ztheme] 警告:" + warning);
678
+ const rules = loadAuditRules(root);
657
679
 
658
680
  const flagTheme = valueOf("theme");
659
681
  const envTheme = process.env.ZTHEME_THEME;
@@ -683,6 +705,7 @@ const main = async () => {
683
705
  exclude: config.exclude,
684
706
  severity: config.severity,
685
707
  ignore: config.ignore,
708
+ rules,
686
709
  theme,
687
710
  });
688
711