ztheme-cli 0.0.5 → 0.0.6

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.
Files changed (5) hide show
  1. package/README.md +222 -45
  2. package/audit.mjs +532 -0
  3. package/color.mjs +228 -0
  4. package/package.json +7 -2
  5. package/ztheme.mjs +213 -5
package/README.md CHANGED
@@ -4,63 +4,229 @@
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
8
 
8
- ## 用法
9
+ ## 前提:告诉它站点在哪
9
10
 
10
11
  ```bash
11
- # 站点地址(默认 http://localhost:3001)
12
- export ZTHEME_BASE=https://你的站点
12
+ export ZTHEME_BASE=https://你的站点 # 默认 http://localhost:3001
13
+ ```
14
+
15
+ CLI **自己不算**对比度:它把解析出的变量 `POST` 给站点的 `/r/check`,和仓库门禁
16
+ `check:presets`、规则接口 `/r/themes/<slug>/rules`、编辑器面板是**同一份实现**。
17
+ 所以站点版本要够新,否则会明确报「站点没有 /r/check 接口(版本过旧?)」——不会退回本地估算。
18
+
19
+ ## 1. 挑主题
20
+
21
+ ```bash
22
+ ztheme list # 列出全部主题(对本地站点实测输出「共 42 套」)
23
+ ztheme show modern-minimal # 单套完整 JSON(light / dark 全部令牌)
24
+ ```
25
+
26
+ ## 2. 落进项目
27
+
28
+ ```bash
29
+ ztheme add modern-minimal # 生成 ./ztheme/modern-minimal.css
30
+ ztheme add modern-minimal --print # 直接打到 stdout,不落盘
31
+ ztheme add modern-minimal --patch globals.css --dry-run # 只报告会改什么
32
+ ztheme add modern-minimal --patch globals.css # 真正写入
33
+ ```
34
+
35
+ `--patch` 用 `/* ztheme:begin <slug> */` … `/* ztheme:end <slug> */` 标记块定位,**幂等**:
36
+ 重复执行只替换同名块,不重复追加,也不碰标记外的任何一行。
37
+ 输出目录可以用 `--out <dir>` 改,默认 `./ztheme/`。
38
+
39
+ ## 3. 校验你自己的 CSS(进 CI 的就是这条)
40
+
41
+ ```bash
42
+ ztheme check --file app/globals.css # 只报告
43
+ ztheme check --file app/globals.css --strict # 不达标 / 无法判定 -> exit 1
44
+ ztheme check --file src/ # 接受目录,一次跑完,末尾给合计
45
+ ztheme check bold-tech --strict # 直接校验站点上的某套预设
46
+ ```
47
+
48
+ 实测输出长这样:
49
+
50
+ ```
51
+ modern-minimal:dark 缺 1 个键
52
+ modern-minimal:检查 5 组配对(边界 2.6,站点契约)
53
+ 对比度全部达标
54
+ ```
55
+
56
+ **三档结果,别混着看**:
57
+
58
+ | 档 | 含义 | `--strict` |
59
+ |---|---|---|
60
+ | 建议修 | 低于边界(默认 2.6),真读不清 | exit 1 |
61
+ | 边界 | 2.6 到阈值之间,肉眼基本看不出 | 只提示 |
62
+ | 无法判定 | `color-mix()`、`transparent`、半透明色——没有底色算不出真实对比度 | **exit 1** |
63
+
64
+ 第三档在 `--strict` 下也算失败是刻意的:0.0.2 时代这些配色被静默跳过,然后打印
65
+ 「对比度全部达标」。**假绿比不检查更危险**。
13
66
 
14
- node cli/ztheme.mjs list # 列出 42 套
15
- node cli/ztheme.mjs show modern-minimal # 打印单套 JSON
16
- node cli/ztheme.mjs add modern-minimal # 生成 ztheme/modern-minimal.css
17
- node cli/ztheme.mjs add modern-minimal --print # 直接输出到 stdout
18
- node cli/ztheme.mjs add modern-minimal --patch globals.css # 写进标记块(幂等)
19
- node cli/ztheme.mjs add modern-minimal --patch globals.css --dry-run # 只报告会改什么
20
- node cli/ztheme.mjs check bold-tech --strict # 亮暗成对 + 对比度自查
21
- node cli/ztheme.mjs check --file app/globals.css --strict # 校验你自己的 CSS(可当 CI 门禁)
67
+ ## 4. 连规则断言一起校验
68
+
69
+ ```bash
70
+ ztheme check --file app/globals.css --rules modern-minimal --strict
22
71
  ```
23
72
 
24
- `check` 的阈值不写死在 CLI 里:它先读站点 `/r/themes/<slug>/rules` 的 `checks` 字段
25
- (与仓库门禁 `check:presets` 共用 `data/preset-checks.json`),站点改阈值 CLI 自动跟随。
26
- 分两档报告:低于边界(默认 2.6)记「建议修」,边界到阈值之间记「边界」;
27
- `--strict` 时两档都会 exit 1,不带时只打印。
73
+ 除了对比度,还会判这套主题的**可判定断言**:圆角档位(control / card / modal)、字距、
74
+ 深浅底明暗。实测输出「规则断言 6 条全部满足」;把 `--radius` 改成 `1.5rem` 会逐条报错并 exit 1。
75
+ 判不了的规则(比如「衬线标题旁不要用同字重」)不以断言形式出现,它们留在规则的
76
+ `advisory` 里当人写建议(接口会标注 level: advisory)——判不了的东西写成断言,只会造一批永远 unknown 的假门。
28
77
 
29
- `add` 默认写到 `./ztheme/<slug>.css`,内容是 `:root` 与 `.dark` 两段 CSS 变量。
30
- 把它 `@import` 到 `globals.css`(放在 Tailwind 之后)即可。
78
+ ## 5. 建立「本项目设计系统」:`init`
79
+
80
+ ```bash
81
+ ztheme init modern-minimal # 写到当前目录
82
+ ztheme init modern-minimal --dir . # 显式指定项目根
83
+ ```
84
+
85
+ 产物三件套:
86
+
87
+ | 文件 | 内容 |
88
+ |---|---|
89
+ | `ztheme/<slug>.css` | `:root` + `.dark` 两段 CSS 变量 |
90
+ | `AGENTS.md` | 一个幂等标记块:令牌表 + 可判定断言 + 禁用组合 + **改完必须跑的那条命令** |
91
+ | `.ztheme/theme-lock.json` | slug + 主题 digest + 阈值 + 断言 + 锁定时刻的判定结果 |
92
+
93
+ `AGENTS.md` 里写的是**相对项目根**的路径(`ztheme/<slug>.css`),可以直接提交进仓库。
94
+ (0.0.4 曾把本机绝对路径写进去,换台机器就跑不了;0.0.5 修了,并有测试守着。)
95
+
96
+ ## 6. 防「站点主题更新了、项目还停在旧版」:`check --lock`
97
+
98
+ ```bash
99
+ ztheme check --lock --file ztheme/modern-minimal.css
100
+ ztheme check --lock --file ztheme/modern-minimal.css --strict
101
+ ```
102
+
103
+ 报两类漂移:① 本地 CSS 比锁定版本变差;② 站点上那套主题的 digest 变了。
104
+ 正常时输出「无漂移:主题与锁定版本一致」;`--strict` 下有漂移即 exit 1。
105
+
106
+ ## 7. CI 里最小接入
107
+
108
+ ```yaml
109
+ - run: npx ztheme-cli@0.0.6 check --file app/globals.css --rules 你的主题 --strict
110
+ env:
111
+ ZTHEME_BASE: https://你的生产站点
112
+ ```
113
+
114
+ ## 8. 仓库级自查:`audit`
115
+
116
+ `check` 看的是 CSS 令牌文件;`audit` 看的是组件源码——AI 最容易写坏的地方。
117
+
118
+ ```bash
119
+ ztheme audit . # 人类摘要,前 10 条
120
+ ztheme audit . --json # stdout 只输出 JSON,适合 agent / CI
121
+ ztheme audit . --max-warnings 0 # 有告警就 exit 1
122
+ ztheme audit . --theme modern-minimal
123
+ ```
124
+
125
+ 扫四类:`bg-[#…]` / `text-[#…]` 这类任意色值、`p-[13px]` / `rounded-[7px]` 这类任意尺寸、
126
+ `style={{ color: "#666" }}` 这类行内颜色,以及可选的裸色值(默认关闭)。
127
+ 命中颜色时会给最近的 token 建议(OKLab 距离,< 10 才给),只报告不改代码。
128
+
129
+ 主题来源:`--theme` > `.ztheme/audit.json` 的 `theme` > lock。本地有
130
+ `ztheme/<slug>.css` 时离线读;没有才回站点拉。拉不到只关闭建议,不阻断扫描。
131
+ 本地想看到 token 建议:先 `npm run dev`(默认 `ZTHEME_BASE` 就是 `http://localhost:3001`),
132
+ 再用 `--theme <slug>`;或先 `ztheme init <slug>` 生成 lock 与本地 CSS。
133
+
134
+ > Windows PowerShell 5.1 的 `>` 会把输出写成 UTF-16,后续 JSON 解析会失败。写文件请用
135
+ > `ztheme audit . --json | Out-File -Encoding utf8 audit.json`;bash、macOS 与 PowerShell 7 的 `>` 没这个问题。
136
+
137
+ 配置(`.ztheme/audit.json`):
138
+
139
+ ```json
140
+ {
141
+ "theme": "modern-minimal",
142
+ "exclude": ["components/ui", "**/*.test.tsx"],
143
+ "severity": { "no-arbitrary-size": "warn", "no-inline-color": "error" },
144
+ "ignore": [{ "rule": "no-arbitrary-color", "file": "app/experiments/**" }],
145
+ "maxWarnings": 50
146
+ }
147
+ ```
148
+
149
+ 行内抑制:
150
+
151
+ ```tsx
152
+ // ztheme-ignore-next-line no-arbitrary-color
153
+ <div className="bg-[#3b82f6]" />
154
+ ```
155
+
156
+ 在 PR 里自动评论(复用 workflow,不单独装 App):
157
+
158
+ ```yaml
159
+ name: PR
160
+ on: pull_request
161
+ jobs:
162
+ design:
163
+ permissions:
164
+ contents: read
165
+ pull-requests: write
166
+ uses: zuoyunlai/Ztheme/.github/workflows/ztheme-audit.yml@main
167
+ with:
168
+ theme: modern-minimal
169
+ ```
170
+
171
+ workflow 按 `<!-- ztheme-audit -->` 更新同一条评论,不刷屏;完整 JSON 在 artifact。
172
+ 静态扫描的边界:不解析动态拼接的 className,不做 AST;`components/ui/`、品牌图标目录、
173
+ 生成的图片路由默认跳过;字号任意值与 `ch`/`em` 相对单位 v1 不报。
174
+
175
+ ## 命令速查
176
+
177
+ | 命令 | 作用 |
178
+ |---|---|
179
+ | `list` | 列出全部主题 |
180
+ | `show <slug>` | 打印单套主题 JSON |
181
+ | `add <slug> [--out dir] [--print]` | 生成 `<dir>/<slug>.css` |
182
+ | `add <slug> --patch <css> [--dry-run]` | 写进标记块(幂等) |
183
+ | `check <slug> [--strict]` | 校验站点上的预设 |
184
+ | `check --file <path> [--strict]` | 校验本地 CSS(也接受目录),可当 CI 门禁 |
185
+ | `check --file <path> --rules <slug>` | 同时校验该主题的规则断言 |
186
+ | `init <slug> [--dir .]` | 生成 CSS + `AGENTS.md` 片段 + 主题锁 |
187
+ | `check --lock [--file <css>]` | 与锁文件比对,报漂移 |
188
+ | `audit [path] [--json] [--theme <slug>] [--max-warnings n]` | 扫组件源码里的硬编码颜色与任意值 |
189
+ | `--help` | 打印用法 |
190
+
191
+ 退出码:`0` 通过;`1` `--strict` 下出现「建议修」或「无法判定」,或有漂移,或 audit 有
192
+ error / 超过 `--max-warnings`;`2` audit 的参数、配置或扫描错误。
31
193
 
32
194
  ## 为什么这么小
33
195
 
34
- - **零依赖**:只用 Node 内置 `fetch` 与 `node:fs`,不引入 commander / chalk 之类
35
- - **改文件只改自己那块**:默认只生成新文件;`--patch` 用
36
- `/* ztheme:begin <slug> */ … /* ztheme:end <slug> */` 标记块定位,
37
- 重复执行替换同名块、不会重复追加,也不碰标记外的内容
196
+ - **零依赖**:只用 Node 内置 `fetch`、`node:fs`、`node:crypto`
197
+ - **算法只有一份,在服务端**:CLI 不自带亮度计算。多一份实现就多一个漂移源——
198
+ 实测 0.0.2 的 CLI 认 hex / oklch 但不认 rgb / hsl / 命名色,于是把不达标配色判成「全部达标」
199
+ - **改文件只改自己那块**:默认只生成新文件;`--patch` 只动标记块内
38
200
  - **数据面与站点同一套**:`/r/themes/<slug>` 的 `cssVars` 就是站点门禁校验过的产物
39
201
 
40
- ## 0.0.3 变了什么
202
+ ## 变更记录
41
203
 
42
- - **判定交给站点**:`check` 不再自带亮度算法,而是把解析出的变量
43
- `POST` 到站点的 `/r/check`(与门禁、规则接口、编辑器面板同一份实现)。
44
- 0.0.2 各自算一份,实测 hex 判失败、rgb/hsl/命名色却打印「对比度全部达标」。
45
- - **无法判定不再静默跳过**:`color-mix()`、`transparent`、半透明色有底色才算得出,
46
- CLI 会把它们列成「无法判定」;`--strict` 下这些也算失败(不达标 ≠ 达标)。
47
- - **CSS 变量解析不再要求末尾分号**:原来靠正则 `--x: y;`,globals.css 最后一行的
48
- 变量会被静默丢掉。
49
- - **`check --file` 支持目录**:一次 CI 跑完整个项目,最后给一条合计。
204
+ ### 0.0.6
50
205
 
51
- ## 0.0.5 修了什么
206
+ - 新增 `audit`:扫描 TSX/JSX/TS/JS 里的任意色值、任意尺寸、行内颜色;命中颜色时给最近的
207
+ token 建议;`--json` 供 agent / CI 消费;默认只告警。零依赖、纯静态扫描。
208
+ - `init` 的 `AGENTS.md` 增加 `npx ztheme-cli audit --json` 自查命令。
209
+ - 新增可复用 workflow `.github/workflows/ztheme-audit.yml`:PR 评论 + artifact + 真实退出码。
210
+
211
+ ### 0.0.5
52
212
 
53
213
  - `init` 打印的 `@import` 与写进 `AGENTS.md` 的验收命令**改成相对项目根的路径**。
54
214
  0.0.4 在 `--dir` 传绝对路径时会写出本机绝对路径,那条命令贴进别人的仓库就跑不了。
55
215
 
56
- ## 0.0.4 变了什么
216
+ ### 0.0.4
217
+
218
+ - `init <slug>`:一条命令建立「本项目设计系统」——生成 `ztheme/<slug>.css`、
219
+ 往 `AGENTS.md` 写幂等标记块、生成 `.ztheme/theme-lock.json`
220
+ - `check --lock`:本地 CSS 变差、或站点主题已更新都报漂移;`--strict` 判失败
221
+ - 锁文件记的是**判定结果**(fails / warns / unknown + 断言),不是「差不多能过」
57
222
 
58
- - `init <slug>`:一条命令建立「本项目设计系统」——
59
- 生成 `ztheme/<slug>.css`、往 `AGENTS.md` 写一个幂等标记块(令牌表 + 可判定断言 +
60
- 禁止组合 + **改完必须跑的那条命令**)、生成 `.ztheme/theme-lock.json`
61
- - `check --lock`:与锁文件比对。本地 CSS 比锁定版本变差、或站点上的主题已更新,
62
- 都报漂移;`--strict` 判失败。防「站点主题更新了、项目还停在旧版」
63
- - 锁文件记的是**判定结果**(fails/warns/unknown + 断言),不是「差不多能过」)
223
+ ### 0.0.3
224
+
225
+ - **判定交给站点**:`check` 不再自带亮度算法,改为 `POST /r/check`。0.0.2 各自算一份,
226
+ 实测 hex 判失败、rgb / hsl / 命名色却打印「对比度全部达标」
227
+ - **无法判定不再静默跳过**:单独列出,`--strict` 下算失败
228
+ - **CSS 变量解析不再要求末尾分号**:原来靠带分号的正则,globals.css 最后一行的变量会被静默丢掉
229
+ - **`check --file` 支持目录**:一次 CI 跑完整个项目,末尾给一条合计
64
230
 
65
231
  ## 尚未做
66
232
 
@@ -69,15 +235,24 @@ node cli/ztheme.mjs check --file app/globals.css --strict # 校验你自己的
69
235
 
70
236
  ## 发版(维护者)
71
237
 
72
- 本机 `~/.npmrc` 默认 `registry=https://registry.npmmirror.com`(国内镜像)。
73
- **所有写操作必须显式指向官方 registry**,否则请求打到镜像并返回
74
- `401 Unauthorized … Login first`——那不是没登录,是镜像不提供写接口:
238
+ 本机 `~/.npmrc` 默认指向 `registry.npmmirror.com`(国内镜像)。
239
+ 镜像不提供写接口,打过去会返回 `401 Unauthorized` / `ENEEDAUTH`——那不是没登录。
240
+ `cli/package.json` 已用 `publishConfig.registry` 钉住官方 registry,所以直接发即可:
75
241
 
76
242
  ```bash
77
243
  cd cli
244
+ npm publish
245
+ ```
246
+
247
+ 如果换到别的包或本字段被删掉,才需要显式指定:
248
+
249
+ ```bash
78
250
  npm publish --registry=https://registry.npmjs.org
79
251
  ```
80
252
 
253
+ 注意语法:`npm publish` 后面跟的是**本地目录或 tarball**。写成 `npm publish ztheme-cli@0.0.5`
254
+ 会被当成「去 registry 找一个还不存在的包」,报 `ETARGET`——先有鸡还是先有蛋。
255
+
81
256
  账号是 `auth-and-writes` 2FA 时,写操作会要求一次性密码:
82
257
 
83
258
  ```
@@ -85,11 +260,13 @@ npm error code EOTP
85
260
  npm error Open this URL in your browser to authenticate:
86
261
  ```
87
262
 
88
- 在**能交互的终端**里跑,按提示打开 URL 或输入 6 位 OTP。CI / 非交互环境
89
- 要绕过这道门,得用 npmjs.com 生成的 **Automation** token(该类 token 不受
90
- OTP 拦截),写进 `~/.npmrc` 的 `//registry.npmjs.org/:_authToken`。
263
+ 在**能交互的终端**里跑,按提示打开 URL 或输入 6 位 OTP。CI / 非交互环境要绕过这道门,
264
+ 得用 npmjs.com 生成的 **Automation** token(该类 token 不受 OTP 拦截),
265
+ 写进 `~/.npmrc` 的 `//registry.npmjs.org/:_authToken`。
91
266
 
92
- 发布后用官方 registry 核对,别信 `npm view` 的默认值(可能命中镜像或本地缓存):
267
+ **「CLI 打印了 + 包名@版本」不等于「registry 能查到」**:实测 0.0.4 要轮询 5 次、
268
+ 0.0.5 要轮询 6 次(约 100 秒)才出现。发布后用官方 registry 核对,
269
+ 别信 `npm view` 的默认值(本机 registry 指向镜像时读到的是镜像值):
93
270
 
94
271
  ```bash
95
272
  curl -s https://registry.npmjs.org/ztheme-cli | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{const j=JSON.parse(s);console.log(j['dist-tags'].latest,Object.keys(j.versions).join(','))})"
package/audit.mjs ADDED
@@ -0,0 +1,532 @@
1
+ /**
2
+ * ztheme audit —— 在用户仓库里找设计漂移(零依赖)。
3
+ *
4
+ * 只做静态、高置信度的检查:Tailwind 任意值、行内颜色、裸色值(默认关闭)。
5
+ * 不解析动态字符串、不做 AST、不复制对比度算法;对比度仍归 check / POST /r/check。
6
+ */
7
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
8
+ import { join, sep } from "node:path";
9
+
10
+ import { deltaE, parseColor } from "./color.mjs";
11
+
12
+ export const TOOL = "ztheme-cli";
13
+ export const SCHEMA_VERSION = 1;
14
+
15
+ const VERSION = (() => {
16
+ try {
17
+ const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"));
18
+ return typeof pkg.version === "string" ? pkg.version : "0.0.0";
19
+ } catch {
20
+ return "0.0.0";
21
+ }
22
+ })();
23
+
24
+ export const DEFAULT_SEVERITY = {
25
+ "no-arbitrary-color": "warn",
26
+ "no-arbitrary-size": "warn",
27
+ "no-inline-color": "warn",
28
+ "no-hardcoded-color": "off",
29
+ };
30
+
31
+ const DEFAULT_INCLUDE = ["app", "components", "src", "pages"];
32
+ const DEFAULT_EXCLUDE = [
33
+ "node_modules",
34
+ ".next",
35
+ ".git",
36
+ "dist",
37
+ "build",
38
+ "coverage",
39
+ ".ztheme",
40
+ "ztheme",
41
+ "components/ui",
42
+ "**/icons/**",
43
+ "**/opengraph-image.tsx",
44
+ "**/twitter-image.tsx",
45
+ "**/icon.tsx",
46
+ "**/apple-icon.tsx",
47
+ ];
48
+ const SOURCE_EXT = /\.(tsx|jsx|ts|js)$/i;
49
+ const MAX_FILE_SIZE = 1024 * 1024;
50
+
51
+ const COLOR_TOKENS = [
52
+ "background",
53
+ "foreground",
54
+ "card",
55
+ "card-foreground",
56
+ "popover",
57
+ "popover-foreground",
58
+ "primary",
59
+ "primary-foreground",
60
+ "secondary",
61
+ "secondary-foreground",
62
+ "muted",
63
+ "muted-foreground",
64
+ "accent",
65
+ "accent-foreground",
66
+ "destructive",
67
+ "destructive-foreground",
68
+ "border",
69
+ "input",
70
+ "ring",
71
+ "chart-1",
72
+ "chart-2",
73
+ "chart-3",
74
+ "chart-4",
75
+ "chart-5",
76
+ ];
77
+
78
+ const COLOR_PATTERN =
79
+ /#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})\b|rgba?\([^)]*\)|hsla?\([^)]*\)|oklch\([^)]*\)/i;
80
+
81
+ const R_COLOR_VALUE =
82
+ /\b(?:bg|text|border(?:-[trblxy])?|fill|stroke|from|via|to|ring|outline(?:-[a-z]+)?|divide(?:-[xy])?|decoration|caret|accent)-\[([^\]\n]+)\]/g;
83
+ const R_ARBITRARY_SIZE =
84
+ /\b(?:rounded(?:-[a-z]+)?|p[xytrbl]?|m[xytrbl]?|gap(?:-[xy])?|space-[xy]|shadow)-\[([^\]\n]+)\]/g;
85
+ const R_STYLE_BLOCK = /style\s*=\s*\{\{([\s\S]*?)\}\}/g;
86
+ const R_STYLE_COLOR =
87
+ /(?:^|[,{\s])(color|background|backgroundColor|borderColor|fill|stroke|boxShadow)\s*:\s*(["'`])([^"'`]*)\2/g;
88
+ const R_QUOTED = /(["'`])([^"'`]*)\1/g;
89
+ const R_IGNORE = /ztheme-ignore(?:-next-line)?\s*([a-z-]+)?/;
90
+
91
+ const toPosix = (value) => value.split(sep).join("/");
92
+
93
+ function globToRegExp(pattern) {
94
+ const normalized = pattern.replace(/\\/g, "/").replace(/^\.\//, "");
95
+ let source = "";
96
+ for (let index = 0; index < normalized.length; index++) {
97
+ const char = normalized[index];
98
+ if (char === "*") {
99
+ if (normalized[index + 1] === "*") {
100
+ source += ".*";
101
+ index += 1;
102
+ if (normalized[index + 1] === "/") index += 1;
103
+ } else {
104
+ source += "[^/]*";
105
+ }
106
+ } else if (char === "?") {
107
+ source += "[^/]";
108
+ } else {
109
+ source += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
110
+ }
111
+ }
112
+ return new RegExp("^" + source + "$");
113
+ }
114
+
115
+ function isExcluded(relPath, exclude) {
116
+ for (const pattern of exclude) {
117
+ if (!/[*?]/.test(pattern)) {
118
+ const trimmed = pattern.replace(/\/+$/, "");
119
+ if (relPath === trimmed || relPath.startsWith(trimmed + "/")) return true;
120
+ } else if (globToRegExp(pattern).test(relPath)) {
121
+ return true;
122
+ }
123
+ }
124
+ return false;
125
+ }
126
+
127
+ function lineStartsOf(text) {
128
+ const starts = [0];
129
+ for (let index = 0; index < text.length; index++) {
130
+ if (text[index] === "\n") starts.push(index + 1);
131
+ }
132
+ return starts;
133
+ }
134
+
135
+ function positionAt(starts, index) {
136
+ let low = 0;
137
+ let high = starts.length - 1;
138
+ while (low <= high) {
139
+ const mid = Math.floor((low + high) / 2);
140
+ if (starts[mid] <= index) low = mid + 1;
141
+ else high = mid - 1;
142
+ }
143
+ const lineIndex = Math.max(0, high);
144
+ return { line: lineIndex + 1, column: index - starts[lineIndex] + 1 };
145
+ }
146
+
147
+ function lineAt(text, starts, index) {
148
+ const { line } = positionAt(starts, index);
149
+ const start = starts[line - 1];
150
+ const end = text.indexOf("\n", start);
151
+ return text.slice(start, end < 0 ? text.length : end);
152
+ }
153
+
154
+ function extractColor(text) {
155
+ const match = COLOR_PATTERN.exec(text);
156
+ return match ? match[0] : null;
157
+ }
158
+
159
+ function isColorValue(value) {
160
+ if (/^(?:white|black)$/i.test(value.trim())) return true;
161
+ return COLOR_PATTERN.test(value);
162
+ }
163
+
164
+ /** 只有「整个值就是颜色」才算颜色;`shadow-[0_2px_4px_#000]` 仍是尺寸类 */
165
+ function isPureColorValue(value) {
166
+ const trimmed = value.trim();
167
+ if (/^(?:white|black)$/i.test(trimmed)) return true;
168
+ if (parseColor(trimmed)) return true;
169
+ return (
170
+ /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(trimmed) ||
171
+ /^(?:rgba?|hsla?|oklch)\([^)]*\)$/i.test(trimmed)
172
+ );
173
+ }
174
+
175
+ function isNonScaleValue(value) {
176
+ if (value.includes("var(")) return true;
177
+ if (
178
+ /^(?:inherit|initial|unset|revert|revert-layer|auto|none|full|transparent|currentcolor)$/i.test(
179
+ value.trim()
180
+ )
181
+ ) {
182
+ return true;
183
+ }
184
+ return (
185
+ /^(?:var|calc|clamp|min|max|env|theme)\(/i.test(value.trim()) ||
186
+ /^-?[\d.]+(?:ch|em|ex|cap|ic|lh|rlh)$/i.test(value.trim())
187
+ );
188
+ }
189
+
190
+ function buildPalette(theme) {
191
+ const palette = new Map();
192
+ for (const mode of ["light", "dark"]) {
193
+ const tokens = theme?.tokens?.[mode];
194
+ if (!tokens) continue;
195
+ for (const token of COLOR_TOKENS) {
196
+ if (palette.has(token)) continue;
197
+ const parsed = parseColor(tokens[token]);
198
+ if (parsed) palette.set(token, parsed);
199
+ }
200
+ }
201
+ return palette;
202
+ }
203
+
204
+ function suggestColor(value, palette) {
205
+ if (!palette.size) return null;
206
+ const parsed = parseColor(value) ?? parseColor(extractColor(value) ?? "");
207
+ if (!parsed) return null;
208
+ let best = null;
209
+ for (const [token, candidate] of palette) {
210
+ const distance = deltaE(parsed, candidate);
211
+ if (!best || distance < best.distance) best = { token, distance };
212
+ }
213
+ if (!best || best.distance >= 10) return null;
214
+ return "--" + best.token;
215
+ }
216
+
217
+ function ignoredLinesOf(lines) {
218
+ const ignored = new Map();
219
+ const mark = (lineNumber, rule) => {
220
+ if (!ignored.has(lineNumber)) ignored.set(lineNumber, { all: false, rules: new Set() });
221
+ const entry = ignored.get(lineNumber);
222
+ if (rule) entry.rules.add(rule);
223
+ else entry.all = true;
224
+ };
225
+ for (let index = 0; index < lines.length; index++) {
226
+ const line = lines[index];
227
+ const match = R_IGNORE.exec(line);
228
+ if (!match) continue;
229
+ const rule = match[1] || null;
230
+ if (line.includes("ztheme-ignore-next-line")) mark(index + 2, rule);
231
+ else mark(index + 1, rule);
232
+ }
233
+ return ignored;
234
+ }
235
+
236
+ function isIgnored(ignored, line, rule) {
237
+ const entry = ignored.get(line);
238
+ if (!entry) return false;
239
+ return entry.all || entry.rules.has(rule);
240
+ }
241
+
242
+ function isCommentLine(text, starts, index) {
243
+ const line = lineAt(text, starts, index).trim();
244
+ return (
245
+ line.startsWith("//") || line.startsWith("/*") || line.startsWith("*") || line.startsWith("{/*")
246
+ );
247
+ }
248
+
249
+ /**
250
+ * @param {object} options
251
+ * @param {string} options.root
252
+ * @param {string[]} [options.include]
253
+ * @param {string[]} [options.exclude]
254
+ * @param {{ slug?: string | null, source?: string, tokens?: { light?: Record<string,string>, dark?: Record<string,string> } }} [options.theme]
255
+ * @param {Record<string, string>} [options.severity]
256
+ * @param {Array<{ rule?: string, file?: string, value?: string }>} [options.ignore]
257
+ * @param {Date} [options.now]
258
+ */
259
+ export async function auditProject(options) {
260
+ const root = options.root ?? process.cwd();
261
+ const include = (options.include ?? DEFAULT_INCLUDE).filter((entry) =>
262
+ existsSync(join(root, entry))
263
+ );
264
+ const effectiveInclude = include.length ? include : ["."];
265
+ const exclude = [...DEFAULT_EXCLUDE, ...(options.exclude ?? [])];
266
+ const severity = { ...DEFAULT_SEVERITY, ...(options.severity ?? {}) };
267
+ const ignoreConfig = options.ignore ?? [];
268
+ const palette = buildPalette(options.theme);
269
+ const theme = {
270
+ slug: options.theme?.slug ?? null,
271
+ source: options.theme?.source ?? null,
272
+ suggestions: palette.size > 0,
273
+ };
274
+
275
+ const findings = [];
276
+ const errors = [];
277
+ const skipped = [];
278
+ const seen = new Set();
279
+ let scannedFiles = 0;
280
+ let summaryIgnored = 0;
281
+
282
+ const addFinding = (file, starts, index, rule, value, evidence, suggestion) => {
283
+ const level = severity[rule] ?? "off";
284
+ if (level === "off") return;
285
+ const { line, column } = positionAt(starts, index);
286
+ const key = [file, line, column, rule, value].join("\u0000");
287
+ if (seen.has(key)) return;
288
+ seen.add(key);
289
+ findings.push({
290
+ file,
291
+ line,
292
+ column,
293
+ rule,
294
+ severity: level,
295
+ value,
296
+ evidence,
297
+ suggestion: suggestion ?? null,
298
+ });
299
+ };
300
+
301
+ const scanFile = (absolute, rel) => {
302
+ let text;
303
+ try {
304
+ text = readFileSync(absolute, "utf8");
305
+ } catch (error) {
306
+ errors.push({ file: rel, message: String(error?.message ?? error) });
307
+ return;
308
+ }
309
+ scannedFiles += 1;
310
+ const starts = lineStartsOf(text);
311
+ const lines = text.split(/\r?\n/);
312
+ const ignored = ignoredLinesOf(lines);
313
+
314
+ const emit = (match, rule, value, suggestion) => {
315
+ const { line } = positionAt(starts, match.index);
316
+ if (isIgnored(ignored, line, rule)) return "ignored";
317
+ const ignoreMatch = ignoreConfig.find(
318
+ (entry) =>
319
+ (!entry.rule || entry.rule === rule) &&
320
+ (!entry.value || entry.value === value) &&
321
+ (!entry.file || globToRegExp(entry.file).test(rel))
322
+ );
323
+ if (ignoreMatch) return "ignored";
324
+ addFinding(rel, starts, match.index, rule, value, match[0], suggestion);
325
+ return "added";
326
+ };
327
+
328
+ let ignoredCount = 0;
329
+
330
+ R_COLOR_VALUE.lastIndex = 0;
331
+ for (const match of text.matchAll(R_COLOR_VALUE)) {
332
+ const value = match[1];
333
+ if (!isColorValue(value) || value.includes("var(")) continue;
334
+ if (isCommentLine(text, starts, match.index)) continue;
335
+ const outcome = emit(match, "no-arbitrary-color", value, suggestColor(value, palette));
336
+ if (outcome === "ignored") ignoredCount += 1;
337
+ }
338
+
339
+ R_ARBITRARY_SIZE.lastIndex = 0;
340
+ for (const match of text.matchAll(R_ARBITRARY_SIZE)) {
341
+ const value = match[1];
342
+ if (isPureColorValue(value) || isNonScaleValue(value)) continue;
343
+ if (isCommentLine(text, starts, match.index)) continue;
344
+ const outcome = emit(match, "no-arbitrary-size", value, null);
345
+ if (outcome === "ignored") ignoredCount += 1;
346
+ }
347
+
348
+ R_STYLE_BLOCK.lastIndex = 0;
349
+ for (const block of text.matchAll(R_STYLE_BLOCK)) {
350
+ const blockStart = block.index ?? 0;
351
+ const body = block[1] ?? "";
352
+ R_STYLE_COLOR.lastIndex = 0;
353
+ for (const property of body.matchAll(R_STYLE_COLOR)) {
354
+ const rawValue = property[3] ?? "";
355
+ if (!isColorValue(rawValue) || rawValue.includes("var(")) continue;
356
+ const value = extractColor(rawValue) ?? rawValue;
357
+ const index = blockStart + (property.index ?? 0);
358
+ const fakeMatch = { index, 0: property[0] };
359
+ const outcome = emit(fakeMatch, "no-inline-color", value, suggestColor(value, palette));
360
+ if (outcome === "ignored") ignoredCount += 1;
361
+ }
362
+ }
363
+
364
+ const hardcodedLevel = severity["no-hardcoded-color"] ?? "off";
365
+ if (hardcodedLevel !== "off") {
366
+ for (let index = 0; index < lines.length; index++) {
367
+ const line = lines[index];
368
+ if (isCommentLine(text, starts, starts[index])) continue;
369
+ if (line.includes("className") || line.includes("style") || line.includes("import "))
370
+ continue;
371
+ R_QUOTED.lastIndex = 0;
372
+ for (const quoted of line.matchAll(R_QUOTED)) {
373
+ const raw = quoted[2] ?? "";
374
+ if (!isColorValue(raw)) continue;
375
+ const value = extractColor(raw) ?? raw;
376
+ const fakeMatch = { index: starts[index] + (quoted.index ?? 0), 0: quoted[0] };
377
+ const outcome = emit(
378
+ fakeMatch,
379
+ "no-hardcoded-color",
380
+ value,
381
+ suggestColor(value, palette)
382
+ );
383
+ if (outcome === "ignored") ignoredCount += 1;
384
+ }
385
+ }
386
+ }
387
+
388
+ // 标记数可能大于实际命中数;以实际被抑制的 finding 为准
389
+ summaryIgnored += ignoredCount;
390
+ };
391
+
392
+ const visit = (absolute, rel) => {
393
+ let stat;
394
+ try {
395
+ stat = statSync(absolute);
396
+ } catch (error) {
397
+ errors.push({ file: rel || ".", message: String(error?.message ?? error) });
398
+ return;
399
+ }
400
+ if (stat.isDirectory()) {
401
+ let entries;
402
+ try {
403
+ entries = readdirSync(absolute);
404
+ } catch (error) {
405
+ errors.push({ file: rel || ".", message: String(error?.message ?? error) });
406
+ return;
407
+ }
408
+ for (const entry of entries) {
409
+ const childRel = rel && rel !== "." ? rel + "/" + entry : entry;
410
+ if (isExcluded(childRel, exclude)) continue;
411
+ visit(join(absolute, entry), childRel);
412
+ }
413
+ return;
414
+ }
415
+ if (!stat.isFile() || !SOURCE_EXT.test(absolute)) return;
416
+ if (stat.size > MAX_FILE_SIZE) {
417
+ skipped.push({ file: rel, reason: "too-large" });
418
+ return;
419
+ }
420
+ scanFile(absolute, rel);
421
+ };
422
+
423
+ for (const entry of effectiveInclude) {
424
+ const absolute = entry === "." ? root : join(root, entry);
425
+ if (!existsSync(absolute)) continue;
426
+ visit(absolute, entry === "." ? "" : toPosix(entry));
427
+ }
428
+
429
+ findings.sort((left, right) => {
430
+ return (
431
+ left.file.localeCompare(right.file) ||
432
+ left.line - right.line ||
433
+ left.column - right.column ||
434
+ left.rule.localeCompare(right.rule) ||
435
+ left.value.localeCompare(right.value)
436
+ );
437
+ });
438
+
439
+ const warnings = findings.filter((finding) => finding.severity === "warn").length;
440
+ const errorCount = findings.filter((finding) => finding.severity === "error").length;
441
+ const generatedAt = (options.now instanceof Date ? options.now : new Date()).toISOString();
442
+
443
+ return {
444
+ schemaVersion: SCHEMA_VERSION,
445
+ tool: TOOL,
446
+ toolVersion: VERSION,
447
+ generatedAt,
448
+ theme,
449
+ config: {
450
+ include: effectiveInclude,
451
+ exclude: options.exclude ?? [],
452
+ severity,
453
+ },
454
+ summary: {
455
+ files: scannedFiles,
456
+ errors: errorCount,
457
+ warnings,
458
+ ignored: summaryIgnored,
459
+ skipped: skipped.length,
460
+ },
461
+ findings,
462
+ skipped,
463
+ errors,
464
+ };
465
+ }
466
+
467
+ export function formatJson(result) {
468
+ return JSON.stringify(result, null, 2);
469
+ }
470
+
471
+ export function formatHuman(result, options = {}) {
472
+ const quiet = options.quiet === true;
473
+ const lines = [];
474
+ lines.push(
475
+ "ztheme audit · " +
476
+ result.summary.files +
477
+ " 个文件 · " +
478
+ result.summary.warnings +
479
+ " 条告警 · " +
480
+ result.summary.errors +
481
+ " 条错误"
482
+ );
483
+ if (result.theme.slug) {
484
+ lines.push(
485
+ "主题 " +
486
+ result.theme.slug +
487
+ "(" +
488
+ result.theme.source +
489
+ (result.theme.suggestions ? "" : ",建议已关闭") +
490
+ ")"
491
+ );
492
+ } else {
493
+ lines.push("未指定主题:只报告漂移,不给 token 建议");
494
+ }
495
+ if (result.summary.ignored) lines.push("已忽略 " + result.summary.ignored + " 条");
496
+ if (quiet) return lines.join("\n");
497
+
498
+ let currentFile = null;
499
+ const limit = options.limit ?? 10;
500
+ for (const finding of result.findings.slice(0, limit)) {
501
+ if (finding.file !== currentFile) {
502
+ currentFile = finding.file;
503
+ lines.push("");
504
+ lines.push(finding.file);
505
+ }
506
+ lines.push(
507
+ " " +
508
+ finding.line +
509
+ ":" +
510
+ finding.column +
511
+ " " +
512
+ finding.severity +
513
+ " " +
514
+ finding.rule +
515
+ " " +
516
+ finding.evidence +
517
+ (finding.suggestion ? " → " + finding.suggestion : "")
518
+ );
519
+ }
520
+ if (result.findings.length > limit) {
521
+ lines.push("");
522
+ lines.push("前 " + limit + " 条已展示;完整结果用 --json。");
523
+ }
524
+ if (result.errors.length) {
525
+ lines.push("");
526
+ lines.push("无法扫描 " + result.errors.length + " 个文件:");
527
+ for (const error of result.errors.slice(0, 5)) {
528
+ lines.push(" ! " + error.file + ":" + error.message);
529
+ }
530
+ }
531
+ return lines.join("\n");
532
+ }
package/color.mjs ADDED
@@ -0,0 +1,228 @@
1
+ /**
2
+ * 颜色解析(零依赖)。
3
+ *
4
+ * 只做 audit 建议需要的事:把 hex / rgb / hsl / oklch 转成 OKLab,再比较距离。
5
+ * 判定原则与 utils/contrast-check.ts 保持一致:无法解析、半透明、transparent、
6
+ * color-mix 一律返回 null —— 不猜、不静默当黑色。
7
+ */
8
+
9
+ /** @typedef {{ l: number, a: number, b: number }} Oklab */
10
+
11
+ const clamp01 = (value) => Math.min(1, Math.max(0, value));
12
+
13
+ const NAMED = {
14
+ white: [1, 1, 1],
15
+ black: [0, 0, 0],
16
+ };
17
+
18
+ const srgbToLinear = (channel) =>
19
+ channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
20
+
21
+ /**
22
+ * sRGB(0..1)→ OKLab。
23
+ * @param {number} r
24
+ * @param {number} g
25
+ * @param {number} b
26
+ * @returns {Oklab}
27
+ */
28
+ function srgbToOklab(r, g, b) {
29
+ const lr = srgbToLinear(clamp01(r));
30
+ const lg = srgbToLinear(clamp01(g));
31
+ const lb = srgbToLinear(clamp01(b));
32
+
33
+ const l = 0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb;
34
+ const m = 0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb;
35
+ const s = 0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb;
36
+
37
+ const l_ = Math.cbrt(l);
38
+ const m_ = Math.cbrt(m);
39
+ const s_ = Math.cbrt(s);
40
+
41
+ return {
42
+ l: 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,
43
+ a: 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,
44
+ b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_,
45
+ };
46
+ }
47
+
48
+ function hslToRgb(hue, saturation, lightness) {
49
+ const h = ((hue % 360) + 360) % 360;
50
+ const s = clamp01(saturation);
51
+ const l = clamp01(lightness);
52
+ const c = (1 - Math.abs(2 * l - 1)) * s;
53
+ const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
54
+ const m = l - c / 2;
55
+
56
+ let r = 0;
57
+ let g = 0;
58
+ let b = 0;
59
+ if (h < 60) [r, g, b] = [c, x, 0];
60
+ else if (h < 120) [r, g, b] = [x, c, 0];
61
+ else if (h < 180) [r, g, b] = [0, c, x];
62
+ else if (h < 240) [r, g, b] = [0, x, c];
63
+ else if (h < 300) [r, g, b] = [x, 0, c];
64
+ else [r, g, b] = [c, 0, x];
65
+
66
+ return [r + m, g + m, b + m];
67
+ }
68
+
69
+ function parseNumber(value) {
70
+ if (typeof value !== "string") return null;
71
+ const raw = value.trim();
72
+ if (!raw) return null;
73
+ if (raw.endsWith("%")) {
74
+ const n = Number(raw.slice(0, -1));
75
+ return Number.isFinite(n) ? n / 100 : null;
76
+ }
77
+ const n = Number(raw);
78
+ return Number.isFinite(n) ? n : null;
79
+ }
80
+
81
+ function parseAlpha(parts) {
82
+ // parts 里最后一个可能是 alpha(用 / 分隔);无 alpha 视为 1
83
+ if (!parts.length) return 1;
84
+ const alpha = parseNumber(parts[parts.length - 1]);
85
+ if (alpha === null) return null;
86
+ return alpha <= 1 ? alpha : alpha / 100;
87
+ }
88
+
89
+ /** @returns {Oklab | null} */
90
+ function parseHex(raw) {
91
+ const match = /^#([0-9a-f]{3,8})$/i.exec(raw);
92
+ if (!match) return null;
93
+ let hex = match[1].toLowerCase();
94
+ if (hex.length === 3 || hex.length === 4) {
95
+ hex = hex
96
+ .split("")
97
+ .map((char) => char + char)
98
+ .join("");
99
+ }
100
+ if (hex.length !== 6 && hex.length !== 8) return null;
101
+
102
+ const alpha = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
103
+ if (alpha < 1) return null;
104
+
105
+ const r = parseInt(hex.slice(0, 2), 16) / 255;
106
+ const g = parseInt(hex.slice(2, 4), 16) / 255;
107
+ const b = parseInt(hex.slice(4, 6), 16) / 255;
108
+ return srgbToOklab(r, g, b);
109
+ }
110
+
111
+ /** @returns {Oklab | null} */
112
+ function parseRgb(raw) {
113
+ const match = /^rgba?\(([\s\S]+)\)$/i.exec(raw);
114
+ if (!match) return null;
115
+
116
+ const [body, ...alphaParts] = match[1].split("/");
117
+ const tokens = body
118
+ .trim()
119
+ .split(/[\s,]+/)
120
+ .map((token) => token.trim())
121
+ .filter(Boolean);
122
+ if (tokens.length !== 3) return null;
123
+
124
+ const alpha = parseAlpha(alphaParts.length ? alphaParts : []);
125
+ if (alpha === null || alpha < 1) return null;
126
+
127
+ const channels = tokens.map((token) => {
128
+ if (token.endsWith("%")) {
129
+ const n = Number(token.slice(0, -1));
130
+ return Number.isFinite(n) ? (n / 100) * 255 : null;
131
+ }
132
+ const n = Number(token);
133
+ return Number.isFinite(n) ? n : null;
134
+ });
135
+ if (channels.some((value) => value === null)) return null;
136
+
137
+ const [r, g, b] = channels;
138
+ return srgbToOklab(r / 255, g / 255, b / 255);
139
+ }
140
+
141
+ /** @returns {Oklab | null} */
142
+ function parseHsl(raw) {
143
+ const match = /^hsla?\(([\s\S]+)\)$/i.exec(raw);
144
+ if (!match) return null;
145
+
146
+ const [body, ...alphaParts] = match[1].split("/");
147
+ const tokens = body
148
+ .trim()
149
+ .split(/[\s,]+/)
150
+ .map((token) => token.trim())
151
+ .filter(Boolean);
152
+ if (tokens.length !== 3) return null;
153
+
154
+ const alpha = parseAlpha(alphaParts.length ? alphaParts : []);
155
+ if (alpha === null || alpha < 1) return null;
156
+
157
+ const hue = Number(tokens[0].replace(/deg$/i, ""));
158
+ const saturation = parseNumber(tokens[1]);
159
+ const lightness = parseNumber(tokens[2]);
160
+ if (!Number.isFinite(hue) || saturation === null || lightness === null) return null;
161
+
162
+ const [r, g, b] = hslToRgb(hue, saturation, lightness);
163
+ return srgbToOklab(r, g, b);
164
+ }
165
+
166
+ /** @returns {Oklab | null} */
167
+ function parseOklch(raw) {
168
+ const match = /^oklch\(([\s\S]+)\)$/i.exec(raw);
169
+ if (!match) return null;
170
+
171
+ const [body, ...alphaParts] = match[1].split("/");
172
+ const tokens = body
173
+ .trim()
174
+ .split(/[\s,]+/)
175
+ .map((token) => token.trim())
176
+ .filter(Boolean);
177
+ if (tokens.length !== 3) return null;
178
+
179
+ const alpha = parseAlpha(alphaParts.length ? alphaParts : []);
180
+ if (alpha === null || alpha < 1) return null;
181
+
182
+ const lightness = parseNumber(tokens[0]);
183
+ const chroma = parseNumber(tokens[1]);
184
+ const hue = Number(tokens[2].replace(/deg$/i, ""));
185
+ if (lightness === null || chroma === null || !Number.isFinite(hue)) return null;
186
+ if (lightness < 0 || lightness > 1 || chroma < 0) return null;
187
+
188
+ const radians = (hue * Math.PI) / 180;
189
+ return {
190
+ l: lightness,
191
+ a: chroma * Math.cos(radians),
192
+ b: chroma * Math.sin(radians),
193
+ };
194
+ }
195
+
196
+ /**
197
+ * 解析任意 CSS 颜色为 OKLab;无法判定时返回 null。
198
+ * @param {unknown} input
199
+ * @returns {Oklab | null}
200
+ */
201
+ export function parseColor(input) {
202
+ if (typeof input !== "string") return null;
203
+ const raw = input.trim().toLowerCase();
204
+ if (!raw) return null;
205
+ if (raw === "transparent" || raw === "currentcolor" || raw === "none") return null;
206
+ if (raw.startsWith("color-mix(")) return null;
207
+
208
+ const named = NAMED[raw];
209
+ if (named) return srgbToOklab(named[0], named[1], named[2]);
210
+
211
+ if (raw.startsWith("#")) return parseHex(raw);
212
+ if (raw.startsWith("rgb")) return parseRgb(raw);
213
+ if (raw.startsWith("hsl")) return parseHsl(raw);
214
+ if (raw.startsWith("oklch")) return parseOklch(raw);
215
+ return null;
216
+ }
217
+
218
+ /**
219
+ * OKLab 距离(×100,便于用 2/10 这类阈值表达)。
220
+ * @param {Oklab} left
221
+ * @param {Oklab} right
222
+ */
223
+ export function deltaE(left, right) {
224
+ const dl = left.l - right.l;
225
+ const da = left.a - right.a;
226
+ const db = left.b - right.b;
227
+ return Math.sqrt(dl * dl + da * da + db * db) * 100;
228
+ }
package/package.json CHANGED
@@ -1,19 +1,24 @@
1
1
  {
2
2
  "name": "ztheme-cli",
3
- "version": "0.0.5",
4
- "description": "Ztheme 主题 CLI:不依赖 shadcn,从站点直接拉取主题 CSS 变量",
3
+ "version": "0.0.6",
4
+ "description": "Ztheme 主题 CLI:从站点拉取主题 CSS 变量,并在仓库里扫设计漂移",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "ztheme": "ztheme.mjs"
8
8
  },
9
9
  "files": [
10
10
  "ztheme.mjs",
11
+ "audit.mjs",
12
+ "color.mjs",
11
13
  "README.md",
12
14
  "LICENSE"
13
15
  ],
14
16
  "engines": {
15
17
  "node": ">=18"
16
18
  },
19
+ "publishConfig": {
20
+ "registry": "https://registry.npmjs.org"
21
+ },
17
22
  "license": "MIT",
18
23
  "repository": {
19
24
  "type": "git",
package/ztheme.mjs CHANGED
@@ -2,19 +2,23 @@
2
2
  /**
3
3
  * ztheme —— 不依赖 shadcn 的主题 CLI。
4
4
  *
5
- * 只做三件事,全部走 HTTP:读索引、看单套、落到本地 CSS。
5
+ * 只做四件事:读索引、看单套、落到本地 CSS、扫仓库漂移。
6
+ * 前 3 件全部走 HTTP;audit 在本地静态扫描,不复制服务端的判定算法。
6
7
  * 不用 shadcn CLI、不用 MCP、不需要登录,只要求 Node 18+(用内置 fetch)。
7
8
  *
8
9
  * node cli/ztheme.mjs list
9
10
  * node cli/ztheme.mjs show modern-minimal
10
11
  * node cli/ztheme.mjs add modern-minimal [--out ztheme] [--print]
11
12
  * node cli/ztheme.mjs check modern-minimal [--strict]
13
+ * node cli/ztheme.mjs audit [path] [--json]
12
14
  *
13
15
  * 默认站点取 ZTHEME_BASE 环境变量,否则 http://localhost:3001。
14
16
  */
15
17
  import { createHash } from "node:crypto";
16
18
  import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
17
- import { join } from "node:path";
19
+ import { join, resolve } from "node:path";
20
+
21
+ import { auditProject, formatHuman, formatJson } from "./audit.mjs";
18
22
 
19
23
  const BASE = (process.env.ZTHEME_BASE ?? "http://localhost:3001").replace(/\/$/, "");
20
24
 
@@ -140,6 +144,150 @@ const digestOf = (value) =>
140
144
  const LOCK_DIR = ".ztheme";
141
145
  const LOCK_FILE = join(LOCK_DIR, "theme-lock.json");
142
146
 
147
+ const failWith = (msg, code = 1) => {
148
+ console.error("[ztheme] " + msg);
149
+ process.exit(code);
150
+ };
151
+
152
+ const tryGetJson = async (path) => {
153
+ try {
154
+ const res = await fetch(BASE + path);
155
+ if (!res.ok) return null;
156
+ return await res.json();
157
+ } catch {
158
+ return null;
159
+ }
160
+ };
161
+
162
+ /** 支持 --name value 与 --name=value;缺值返回 undefined */
163
+ const valueOf = (name) => {
164
+ const prefix = "--" + name + "=";
165
+ const inline = argv.find((arg) => arg.startsWith(prefix));
166
+ if (inline) return inline.slice(prefix.length);
167
+ const index = argv.indexOf("--" + name);
168
+ if (index < 0) return undefined;
169
+ const value = argv[index + 1];
170
+ return value && !value.startsWith("--") ? value : undefined;
171
+ };
172
+
173
+ /** audit 的位置参数:跳过 --theme / --max-warnings 的取值 */
174
+ const auditTargetOf = () => {
175
+ const rest = argv.slice(1);
176
+ for (let index = 0; index < rest.length; index++) {
177
+ const arg = rest[index];
178
+ if (arg === "--theme" || arg === "--max-warnings") {
179
+ index += 1;
180
+ continue;
181
+ }
182
+ if (arg.startsWith("--")) continue;
183
+ return arg;
184
+ }
185
+ return ".";
186
+ };
187
+
188
+ const loadAuditConfig = (root) => {
189
+ const file = join(root, LOCK_DIR, "audit.json");
190
+ if (!existsSync(file)) return { config: {}, warnings: [] };
191
+
192
+ let parsed;
193
+ try {
194
+ parsed = JSON.parse(readFileSync(file, "utf8"));
195
+ } catch (error) {
196
+ failWith("无法解析 " + file + ":" + (error?.message ?? error), 2);
197
+ }
198
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
199
+ failWith("audit 配置必须是对象:" + file, 2);
200
+ }
201
+
202
+ const warnings = [];
203
+ const allowed = ["theme", "include", "exclude", "severity", "ignore", "maxWarnings"];
204
+ for (const key of Object.keys(parsed)) {
205
+ if (!allowed.includes(key)) warnings.push("未知配置项 " + key + "(已忽略)");
206
+ }
207
+ for (const key of ["include", "exclude"]) {
208
+ if (
209
+ parsed[key] !== undefined &&
210
+ (!Array.isArray(parsed[key]) || parsed[key].some((value) => typeof value !== "string"))
211
+ ) {
212
+ failWith("audit." + key + " 必须是字符串数组", 2);
213
+ }
214
+ }
215
+ if (parsed.theme !== undefined && typeof parsed.theme !== "string") {
216
+ failWith("audit.theme 必须是字符串", 2);
217
+ }
218
+ if (
219
+ parsed.maxWarnings !== undefined &&
220
+ (!Number.isInteger(parsed.maxWarnings) || parsed.maxWarnings < 0)
221
+ ) {
222
+ failWith("audit.maxWarnings 必须是非负整数", 2);
223
+ }
224
+ if (parsed.severity !== undefined) {
225
+ if (!parsed.severity || typeof parsed.severity !== "object" || Array.isArray(parsed.severity)) {
226
+ failWith("audit.severity 必须是对象", 2);
227
+ }
228
+ for (const [rule, level] of Object.entries(parsed.severity)) {
229
+ if (!["off", "warn", "error"].includes(level)) {
230
+ failWith("audit.severity." + rule + " 必须是 off / warn / error", 2);
231
+ }
232
+ }
233
+ }
234
+ if (parsed.ignore !== undefined) {
235
+ if (!Array.isArray(parsed.ignore)) failWith("audit.ignore 必须是数组", 2);
236
+ for (const entry of parsed.ignore) {
237
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
238
+ failWith("audit.ignore 的每一项必须是对象", 2);
239
+ }
240
+ for (const key of ["rule", "file", "value"]) {
241
+ if (entry[key] !== undefined && typeof entry[key] !== "string") {
242
+ failWith("audit.ignore." + key + " 必须是字符串", 2);
243
+ }
244
+ }
245
+ }
246
+ }
247
+
248
+ return { config: parsed, warnings };
249
+ };
250
+
251
+ const readLockFile = (root) => {
252
+ const file = join(root, LOCK_FILE);
253
+ if (!existsSync(file)) return null;
254
+ try {
255
+ return JSON.parse(readFileSync(file, "utf8"));
256
+ } catch (error) {
257
+ failWith("无法解析锁文件 " + file + ":" + (error?.message ?? error), 2);
258
+ }
259
+ };
260
+
261
+ /**
262
+ * audit 的主题来源:本地 CSS 优先(离线、可复现),否则回站点。
263
+ * 拉取失败不阻断扫描,只关闭建议。
264
+ */
265
+ const loadAuditTheme = async (root, slug) => {
266
+ const cssFile = join(root, "ztheme", slug + ".css");
267
+ if (existsSync(cssFile)) {
268
+ const vars = parseCssVars(readFileSync(cssFile, "utf8"));
269
+ if (Object.keys(vars.light).length || Object.keys(vars.dark).length) {
270
+ return { slug, source: "lock", tokens: vars };
271
+ }
272
+ }
273
+
274
+ const item = await tryGetJson("/r/themes/" + slug);
275
+ if (item?.cssVars) {
276
+ return {
277
+ slug,
278
+ source: "site",
279
+ tokens: {
280
+ light: item.cssVars.light ?? {},
281
+ dark: item.cssVars.dark ?? {},
282
+ },
283
+ };
284
+ }
285
+
286
+ console.error("[ztheme] 无法读取主题 " + slug + ",继续扫描但关闭 token 建议");
287
+ return { slug, source: "none", tokens: undefined };
288
+ };
289
+
290
+
143
291
  const TOKENS = [
144
292
  "background", "foreground", "card", "card-foreground", "popover", "popover-foreground",
145
293
  "primary", "primary-foreground", "secondary", "secondary-foreground",
@@ -186,8 +334,13 @@ const main = async () => {
186
334
  ztheme init <slug> [--dir .] 生成 ztheme/<slug>.css + AGENTS.md 片段 + .ztheme/theme-lock.json
187
335
  ztheme check --lock [--file x.css]
188
336
  与锁文件比对:本地 CSS 变差、或站点主题已更新时报警(--strict 判失败)
337
+ ztheme audit [path] [--json] [--theme <slug>] [--max-warnings <n>] [--quiet]
338
+ 扫描 TSX/JSX/TS/JS 里的硬编码颜色与任意值;
339
+ --json 只输出 JSON;默认只告警,不阻断
189
340
  环境变量:
190
- ZTHEME_BASE 站点地址,默认 ${BASE}`);
341
+ ZTHEME_BASE 站点地址,默认 ${BASE}
342
+ ZTHEME_THEME audit 的对照主题(等价 --theme)
343
+ ZTHEME_MAX_WARNINGS audit 的告警阈值(等价 --max-warnings)`);
191
344
  return;
192
345
  }
193
346
 
@@ -296,13 +449,17 @@ const main = async () => {
296
449
  "",
297
450
  " npx ztheme-cli check --file " + relCss + " --rules " + slug + " --strict",
298
451
  "",
452
+ "提交前自查(必须跑,别只看截图):",
453
+ "",
454
+ " npx ztheme-cli audit --json",
455
+ "",
299
456
  "### 可判定断言",
300
457
  "",
301
458
  ...assertions.map((a) => "- " + a.kind + (a.token ? "(" + a.token + ")" : "") + " 应为 " + a.expect),
302
459
  "",
303
- "### 禁用组合",
460
+ "### 建议(不是硬约束,硬约束见上)",
304
461
  "",
305
- ...((rulesRes.rules && rulesRes.rules.forbidden) || []).map((f) => "- " + f),
462
+ ...((rulesRes.rules && rulesRes.rules.advisory) || []).map((f) => "- " + f),
306
463
  "",
307
464
  "### 令牌",
308
465
  "",
@@ -490,6 +647,57 @@ const main = async () => {
490
647
  return;
491
648
  }
492
649
 
650
+ if (cmd === "audit") {
651
+ const target = auditTargetOf();
652
+ const root = resolve(target);
653
+ if (!existsSync(root)) failWith("扫描目录不存在:" + root, 2);
654
+
655
+ const { config, warnings } = loadAuditConfig(root);
656
+ for (const warning of warnings) console.error("[ztheme] 警告:" + warning);
657
+
658
+ const flagTheme = valueOf("theme");
659
+ const envTheme = process.env.ZTHEME_THEME;
660
+ const configTheme = typeof config.theme === "string" ? config.theme : undefined;
661
+ const lock = readLockFile(root);
662
+ const slug =
663
+ (flagTheme && flagTheme.trim()) ||
664
+ (envTheme && envTheme.trim()) ||
665
+ configTheme ||
666
+ lock?.slug ||
667
+ null;
668
+
669
+ const rawMax = valueOf("max-warnings") ?? process.env.ZTHEME_MAX_WARNINGS ?? config.maxWarnings;
670
+ let maxWarnings = null;
671
+ if (rawMax !== undefined && rawMax !== null && String(rawMax).trim() !== "") {
672
+ const parsed = Number(rawMax);
673
+ if (!Number.isInteger(parsed) || parsed < 0) {
674
+ failWith("--max-warnings 需要非负整数", 2);
675
+ }
676
+ maxWarnings = parsed;
677
+ }
678
+
679
+ const theme = slug ? await loadAuditTheme(root, slug) : null;
680
+ const result = await auditProject({
681
+ root,
682
+ include: config.include,
683
+ exclude: config.exclude,
684
+ severity: config.severity,
685
+ ignore: config.ignore,
686
+ theme,
687
+ });
688
+
689
+ if (flags.has("json")) console.log(formatJson(result));
690
+ else console.log(formatHuman(result, { quiet: flags.has("quiet") }));
691
+
692
+ if (result.errors.length > 0) {
693
+ process.exitCode = 2;
694
+ return;
695
+ }
696
+ const overBudget = maxWarnings !== null && result.summary.warnings > maxWarnings;
697
+ if (result.summary.errors > 0 || overBudget) process.exitCode = 1;
698
+ return;
699
+ }
700
+
493
701
  die("未知命令 " + cmd + "(用 --help 看用法)");
494
702
  };
495
703