ztheme-cli 0.0.5 → 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 +260 -45
- package/audit.mjs +559 -0
- package/color.mjs +228 -0
- package/package.json +8 -2
- package/rules.mjs +186 -0
- package/ztheme.mjs +236 -5
package/audit.mjs
ADDED
|
@@ -0,0 +1,559 @@
|
|
|
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
|
+
import { RULE_RADIUS, classifySize } from "./rules.mjs";
|
|
12
|
+
|
|
13
|
+
export const TOOL = "ztheme-cli";
|
|
14
|
+
export const SCHEMA_VERSION = 1;
|
|
15
|
+
|
|
16
|
+
const VERSION = (() => {
|
|
17
|
+
try {
|
|
18
|
+
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"));
|
|
19
|
+
return typeof pkg.version === "string" ? pkg.version : "0.0.0";
|
|
20
|
+
} catch {
|
|
21
|
+
return "0.0.0";
|
|
22
|
+
}
|
|
23
|
+
})();
|
|
24
|
+
|
|
25
|
+
export const DEFAULT_SEVERITY = {
|
|
26
|
+
"no-arbitrary-color": "warn",
|
|
27
|
+
"no-arbitrary-size": "warn",
|
|
28
|
+
"no-inline-color": "warn",
|
|
29
|
+
"no-hardcoded-color": "off",
|
|
30
|
+
// 这两条只在 .ztheme/rules.json 声明了对应阈值时才会出手;默认级别只影响
|
|
31
|
+
// 声明之后的阻断与否,不会凭空产生命中。
|
|
32
|
+
"no-excessive-radius": "warn",
|
|
33
|
+
"no-off-grid-spacing": "warn",
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const DEFAULT_INCLUDE = ["app", "components", "src", "pages"];
|
|
37
|
+
const DEFAULT_EXCLUDE = [
|
|
38
|
+
"node_modules",
|
|
39
|
+
".next",
|
|
40
|
+
".git",
|
|
41
|
+
"dist",
|
|
42
|
+
"build",
|
|
43
|
+
"coverage",
|
|
44
|
+
".ztheme",
|
|
45
|
+
"ztheme",
|
|
46
|
+
"components/ui",
|
|
47
|
+
"**/icons/**",
|
|
48
|
+
"**/opengraph-image.tsx",
|
|
49
|
+
"**/twitter-image.tsx",
|
|
50
|
+
"**/icon.tsx",
|
|
51
|
+
"**/apple-icon.tsx",
|
|
52
|
+
];
|
|
53
|
+
const SOURCE_EXT = /\.(tsx|jsx|ts|js)$/i;
|
|
54
|
+
const MAX_FILE_SIZE = 1024 * 1024;
|
|
55
|
+
|
|
56
|
+
const COLOR_TOKENS = [
|
|
57
|
+
"background",
|
|
58
|
+
"foreground",
|
|
59
|
+
"card",
|
|
60
|
+
"card-foreground",
|
|
61
|
+
"popover",
|
|
62
|
+
"popover-foreground",
|
|
63
|
+
"primary",
|
|
64
|
+
"primary-foreground",
|
|
65
|
+
"secondary",
|
|
66
|
+
"secondary-foreground",
|
|
67
|
+
"muted",
|
|
68
|
+
"muted-foreground",
|
|
69
|
+
"accent",
|
|
70
|
+
"accent-foreground",
|
|
71
|
+
"destructive",
|
|
72
|
+
"destructive-foreground",
|
|
73
|
+
"border",
|
|
74
|
+
"input",
|
|
75
|
+
"ring",
|
|
76
|
+
"chart-1",
|
|
77
|
+
"chart-2",
|
|
78
|
+
"chart-3",
|
|
79
|
+
"chart-4",
|
|
80
|
+
"chart-5",
|
|
81
|
+
];
|
|
82
|
+
|
|
83
|
+
const COLOR_PATTERN =
|
|
84
|
+
/#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})\b|rgba?\([^)]*\)|hsla?\([^)]*\)|oklch\([^)]*\)/i;
|
|
85
|
+
|
|
86
|
+
const R_COLOR_VALUE =
|
|
87
|
+
/\b(?:bg|text|border(?:-[trblxy])?|fill|stroke|from|via|to|ring|outline(?:-[a-z]+)?|divide(?:-[xy])?|decoration|caret|accent)-\[([^\]\n]+)\]/g;
|
|
88
|
+
const R_ARBITRARY_SIZE =
|
|
89
|
+
/\b(?:rounded(?:-[a-z]+)?|p[xytrbl]?|m[xytrbl]?|gap(?:-[xy])?|space-[xy]|shadow)-\[([^\]\n]+)\]/g;
|
|
90
|
+
const R_STYLE_BLOCK = /style\s*=\s*\{\{([\s\S]*?)\}\}/g;
|
|
91
|
+
const R_STYLE_COLOR =
|
|
92
|
+
/(?:^|[,{\s])(color|background|backgroundColor|borderColor|fill|stroke|boxShadow)\s*:\s*(["'`])([^"'`]*)\2/g;
|
|
93
|
+
const R_QUOTED = /(["'`])([^"'`]*)\1/g;
|
|
94
|
+
const R_IGNORE = /ztheme-ignore(?:-next-line)?\s*([a-z-]+)?/;
|
|
95
|
+
|
|
96
|
+
const toPosix = (value) => value.split(sep).join("/");
|
|
97
|
+
|
|
98
|
+
function globToRegExp(pattern) {
|
|
99
|
+
const normalized = pattern.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
100
|
+
let source = "";
|
|
101
|
+
for (let index = 0; index < normalized.length; index++) {
|
|
102
|
+
const char = normalized[index];
|
|
103
|
+
if (char === "*") {
|
|
104
|
+
if (normalized[index + 1] === "*") {
|
|
105
|
+
source += ".*";
|
|
106
|
+
index += 1;
|
|
107
|
+
if (normalized[index + 1] === "/") index += 1;
|
|
108
|
+
} else {
|
|
109
|
+
source += "[^/]*";
|
|
110
|
+
}
|
|
111
|
+
} else if (char === "?") {
|
|
112
|
+
source += "[^/]";
|
|
113
|
+
} else {
|
|
114
|
+
source += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return new RegExp("^" + source + "$");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isExcluded(relPath, exclude) {
|
|
121
|
+
for (const pattern of exclude) {
|
|
122
|
+
if (!/[*?]/.test(pattern)) {
|
|
123
|
+
const trimmed = pattern.replace(/\/+$/, "");
|
|
124
|
+
if (relPath === trimmed || relPath.startsWith(trimmed + "/")) return true;
|
|
125
|
+
} else if (globToRegExp(pattern).test(relPath)) {
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function lineStartsOf(text) {
|
|
133
|
+
const starts = [0];
|
|
134
|
+
for (let index = 0; index < text.length; index++) {
|
|
135
|
+
if (text[index] === "\n") starts.push(index + 1);
|
|
136
|
+
}
|
|
137
|
+
return starts;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function positionAt(starts, index) {
|
|
141
|
+
let low = 0;
|
|
142
|
+
let high = starts.length - 1;
|
|
143
|
+
while (low <= high) {
|
|
144
|
+
const mid = Math.floor((low + high) / 2);
|
|
145
|
+
if (starts[mid] <= index) low = mid + 1;
|
|
146
|
+
else high = mid - 1;
|
|
147
|
+
}
|
|
148
|
+
const lineIndex = Math.max(0, high);
|
|
149
|
+
return { line: lineIndex + 1, column: index - starts[lineIndex] + 1 };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function lineAt(text, starts, index) {
|
|
153
|
+
const { line } = positionAt(starts, index);
|
|
154
|
+
const start = starts[line - 1];
|
|
155
|
+
const end = text.indexOf("\n", start);
|
|
156
|
+
return text.slice(start, end < 0 ? text.length : end);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function extractColor(text) {
|
|
160
|
+
const match = COLOR_PATTERN.exec(text);
|
|
161
|
+
return match ? match[0] : null;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function isColorValue(value) {
|
|
165
|
+
if (/^(?:white|black)$/i.test(value.trim())) return true;
|
|
166
|
+
return COLOR_PATTERN.test(value);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 只有「整个值就是颜色」才算颜色;`shadow-[0_2px_4px_#000]` 仍是尺寸类 */
|
|
170
|
+
function isPureColorValue(value) {
|
|
171
|
+
const trimmed = value.trim();
|
|
172
|
+
if (/^(?:white|black)$/i.test(trimmed)) return true;
|
|
173
|
+
if (parseColor(trimmed)) return true;
|
|
174
|
+
return (
|
|
175
|
+
/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(trimmed) ||
|
|
176
|
+
/^(?:rgba?|hsla?|oklch)\([^)]*\)$/i.test(trimmed)
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function isNonScaleValue(value) {
|
|
181
|
+
if (value.includes("var(")) return true;
|
|
182
|
+
if (
|
|
183
|
+
/^(?:inherit|initial|unset|revert|revert-layer|auto|none|full|transparent|currentcolor)$/i.test(
|
|
184
|
+
value.trim()
|
|
185
|
+
)
|
|
186
|
+
) {
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
return (
|
|
190
|
+
/^(?:var|calc|clamp|min|max|env|theme)\(/i.test(value.trim()) ||
|
|
191
|
+
/^-?[\d.]+(?:ch|em|ex|cap|ic|lh|rlh)$/i.test(value.trim())
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function buildPalette(theme) {
|
|
196
|
+
const palette = new Map();
|
|
197
|
+
for (const mode of ["light", "dark"]) {
|
|
198
|
+
const tokens = theme?.tokens?.[mode];
|
|
199
|
+
if (!tokens) continue;
|
|
200
|
+
for (const token of COLOR_TOKENS) {
|
|
201
|
+
if (palette.has(token)) continue;
|
|
202
|
+
const parsed = parseColor(tokens[token]);
|
|
203
|
+
if (parsed) palette.set(token, parsed);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return palette;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function suggestColor(value, palette) {
|
|
210
|
+
if (!palette.size) return null;
|
|
211
|
+
const parsed = parseColor(value) ?? parseColor(extractColor(value) ?? "");
|
|
212
|
+
if (!parsed) return null;
|
|
213
|
+
let best = null;
|
|
214
|
+
for (const [token, candidate] of palette) {
|
|
215
|
+
const distance = deltaE(parsed, candidate);
|
|
216
|
+
if (!best || distance < best.distance) best = { token, distance };
|
|
217
|
+
}
|
|
218
|
+
if (!best || best.distance >= 10) return null;
|
|
219
|
+
return "--" + best.token;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function ignoredLinesOf(lines) {
|
|
223
|
+
const ignored = new Map();
|
|
224
|
+
const mark = (lineNumber, rule) => {
|
|
225
|
+
if (!ignored.has(lineNumber)) ignored.set(lineNumber, { all: false, rules: new Set() });
|
|
226
|
+
const entry = ignored.get(lineNumber);
|
|
227
|
+
if (rule) entry.rules.add(rule);
|
|
228
|
+
else entry.all = true;
|
|
229
|
+
};
|
|
230
|
+
for (let index = 0; index < lines.length; index++) {
|
|
231
|
+
const line = lines[index];
|
|
232
|
+
const match = R_IGNORE.exec(line);
|
|
233
|
+
if (!match) continue;
|
|
234
|
+
const rule = match[1] || null;
|
|
235
|
+
if (line.includes("ztheme-ignore-next-line")) mark(index + 2, rule);
|
|
236
|
+
else mark(index + 1, rule);
|
|
237
|
+
}
|
|
238
|
+
return ignored;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function isIgnored(ignored, line, rule) {
|
|
242
|
+
const entry = ignored.get(line);
|
|
243
|
+
if (!entry) return false;
|
|
244
|
+
return entry.all || entry.rules.has(rule);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function isCommentLine(text, starts, index) {
|
|
248
|
+
const line = lineAt(text, starts, index).trim();
|
|
249
|
+
return (
|
|
250
|
+
line.startsWith("//") || line.startsWith("/*") || line.startsWith("*") || line.startsWith("{/*")
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* @param {object} options
|
|
256
|
+
* @param {string} options.root
|
|
257
|
+
* @param {string[]} [options.include]
|
|
258
|
+
* @param {string[]} [options.exclude]
|
|
259
|
+
* @param {{ slug?: string | null, source?: string, tokens?: { light?: Record<string,string>, dark?: Record<string,string> } }} [options.theme]
|
|
260
|
+
* @param {Record<string, string>} [options.severity]
|
|
261
|
+
* @param {{ radius?: { maxRem: number } | null, spacing?: { baseUnit: number } | null } | null} [options.rules]
|
|
262
|
+
* @param {Array<{ rule?: string, file?: string, value?: string }>} [options.ignore]
|
|
263
|
+
* @param {Date} [options.now]
|
|
264
|
+
*/
|
|
265
|
+
export async function auditProject(options) {
|
|
266
|
+
const root = options.root ?? process.cwd();
|
|
267
|
+
const include = (options.include ?? DEFAULT_INCLUDE).filter((entry) =>
|
|
268
|
+
existsSync(join(root, entry))
|
|
269
|
+
);
|
|
270
|
+
const effectiveInclude = include.length ? include : ["."];
|
|
271
|
+
const exclude = [...DEFAULT_EXCLUDE, ...(options.exclude ?? [])];
|
|
272
|
+
const severity = { ...DEFAULT_SEVERITY, ...(options.severity ?? {}) };
|
|
273
|
+
const policy = options.rules ?? null;
|
|
274
|
+
const ignoreConfig = options.ignore ?? [];
|
|
275
|
+
const palette = buildPalette(options.theme);
|
|
276
|
+
const theme = {
|
|
277
|
+
slug: options.theme?.slug ?? null,
|
|
278
|
+
source: options.theme?.source ?? null,
|
|
279
|
+
suggestions: palette.size > 0,
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
const findings = [];
|
|
283
|
+
const errors = [];
|
|
284
|
+
const skipped = [];
|
|
285
|
+
const seen = new Set();
|
|
286
|
+
let scannedFiles = 0;
|
|
287
|
+
let summaryIgnored = 0;
|
|
288
|
+
|
|
289
|
+
const addFinding = (file, starts, index, rule, value, evidence, suggestion, extra = null) => {
|
|
290
|
+
const level = severity[rule] ?? "off";
|
|
291
|
+
if (level === "off") return;
|
|
292
|
+
const { line, column } = positionAt(starts, index);
|
|
293
|
+
const key = [file, line, column, rule, value].join("\u0000");
|
|
294
|
+
if (seen.has(key)) return;
|
|
295
|
+
seen.add(key);
|
|
296
|
+
findings.push({
|
|
297
|
+
file,
|
|
298
|
+
line,
|
|
299
|
+
column,
|
|
300
|
+
rule,
|
|
301
|
+
severity: level,
|
|
302
|
+
value,
|
|
303
|
+
evidence,
|
|
304
|
+
suggestion: suggestion ?? null,
|
|
305
|
+
policy: extra?.policy ?? null,
|
|
306
|
+
expected: extra?.expected ?? null,
|
|
307
|
+
actual: extra?.actual ?? null,
|
|
308
|
+
});
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
const scanFile = (absolute, rel) => {
|
|
312
|
+
let text;
|
|
313
|
+
try {
|
|
314
|
+
text = readFileSync(absolute, "utf8");
|
|
315
|
+
} catch (error) {
|
|
316
|
+
errors.push({ file: rel, message: String(error?.message ?? error) });
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
scannedFiles += 1;
|
|
320
|
+
const starts = lineStartsOf(text);
|
|
321
|
+
const lines = text.split(/\r?\n/);
|
|
322
|
+
const ignored = ignoredLinesOf(lines);
|
|
323
|
+
|
|
324
|
+
const emit = (match, rule, value, suggestion, extra) => {
|
|
325
|
+
const { line } = positionAt(starts, match.index);
|
|
326
|
+
if (isIgnored(ignored, line, rule)) return "ignored";
|
|
327
|
+
const ignoreMatch = ignoreConfig.find(
|
|
328
|
+
(entry) =>
|
|
329
|
+
(!entry.rule || entry.rule === rule) &&
|
|
330
|
+
(!entry.value || entry.value === value) &&
|
|
331
|
+
(!entry.file || globToRegExp(entry.file).test(rel))
|
|
332
|
+
);
|
|
333
|
+
if (ignoreMatch) return "ignored";
|
|
334
|
+
addFinding(rel, starts, match.index, rule, value, match[0], suggestion, extra);
|
|
335
|
+
return "added";
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
let ignoredCount = 0;
|
|
339
|
+
|
|
340
|
+
R_COLOR_VALUE.lastIndex = 0;
|
|
341
|
+
for (const match of text.matchAll(R_COLOR_VALUE)) {
|
|
342
|
+
const value = match[1];
|
|
343
|
+
if (!isColorValue(value) || value.includes("var(")) continue;
|
|
344
|
+
if (isCommentLine(text, starts, match.index)) continue;
|
|
345
|
+
const outcome = emit(match, "no-arbitrary-color", value, suggestColor(value, palette));
|
|
346
|
+
if (outcome === "ignored") ignoredCount += 1;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
R_ARBITRARY_SIZE.lastIndex = 0;
|
|
350
|
+
for (const match of text.matchAll(R_ARBITRARY_SIZE)) {
|
|
351
|
+
const value = match[1];
|
|
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;
|
|
369
|
+
const outcome = emit(match, "no-arbitrary-size", value, null);
|
|
370
|
+
if (outcome === "ignored") ignoredCount += 1;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
R_STYLE_BLOCK.lastIndex = 0;
|
|
374
|
+
for (const block of text.matchAll(R_STYLE_BLOCK)) {
|
|
375
|
+
const blockStart = block.index ?? 0;
|
|
376
|
+
const body = block[1] ?? "";
|
|
377
|
+
R_STYLE_COLOR.lastIndex = 0;
|
|
378
|
+
for (const property of body.matchAll(R_STYLE_COLOR)) {
|
|
379
|
+
const rawValue = property[3] ?? "";
|
|
380
|
+
if (!isColorValue(rawValue) || rawValue.includes("var(")) continue;
|
|
381
|
+
const value = extractColor(rawValue) ?? rawValue;
|
|
382
|
+
const index = blockStart + (property.index ?? 0);
|
|
383
|
+
const fakeMatch = { index, 0: property[0] };
|
|
384
|
+
const outcome = emit(fakeMatch, "no-inline-color", value, suggestColor(value, palette));
|
|
385
|
+
if (outcome === "ignored") ignoredCount += 1;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const hardcodedLevel = severity["no-hardcoded-color"] ?? "off";
|
|
390
|
+
if (hardcodedLevel !== "off") {
|
|
391
|
+
for (let index = 0; index < lines.length; index++) {
|
|
392
|
+
const line = lines[index];
|
|
393
|
+
if (isCommentLine(text, starts, starts[index])) continue;
|
|
394
|
+
if (line.includes("className") || line.includes("style") || line.includes("import "))
|
|
395
|
+
continue;
|
|
396
|
+
R_QUOTED.lastIndex = 0;
|
|
397
|
+
for (const quoted of line.matchAll(R_QUOTED)) {
|
|
398
|
+
const raw = quoted[2] ?? "";
|
|
399
|
+
if (!isColorValue(raw)) continue;
|
|
400
|
+
const value = extractColor(raw) ?? raw;
|
|
401
|
+
const fakeMatch = { index: starts[index] + (quoted.index ?? 0), 0: quoted[0] };
|
|
402
|
+
const outcome = emit(
|
|
403
|
+
fakeMatch,
|
|
404
|
+
"no-hardcoded-color",
|
|
405
|
+
value,
|
|
406
|
+
suggestColor(value, palette)
|
|
407
|
+
);
|
|
408
|
+
if (outcome === "ignored") ignoredCount += 1;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// 标记数可能大于实际命中数;以实际被抑制的 finding 为准
|
|
414
|
+
summaryIgnored += ignoredCount;
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
const visit = (absolute, rel) => {
|
|
418
|
+
let stat;
|
|
419
|
+
try {
|
|
420
|
+
stat = statSync(absolute);
|
|
421
|
+
} catch (error) {
|
|
422
|
+
errors.push({ file: rel || ".", message: String(error?.message ?? error) });
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
if (stat.isDirectory()) {
|
|
426
|
+
let entries;
|
|
427
|
+
try {
|
|
428
|
+
entries = readdirSync(absolute);
|
|
429
|
+
} catch (error) {
|
|
430
|
+
errors.push({ file: rel || ".", message: String(error?.message ?? error) });
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
for (const entry of entries) {
|
|
434
|
+
const childRel = rel && rel !== "." ? rel + "/" + entry : entry;
|
|
435
|
+
if (isExcluded(childRel, exclude)) continue;
|
|
436
|
+
visit(join(absolute, entry), childRel);
|
|
437
|
+
}
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
if (!stat.isFile() || !SOURCE_EXT.test(absolute)) return;
|
|
441
|
+
if (stat.size > MAX_FILE_SIZE) {
|
|
442
|
+
skipped.push({ file: rel, reason: "too-large" });
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
scanFile(absolute, rel);
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
for (const entry of effectiveInclude) {
|
|
449
|
+
const absolute = entry === "." ? root : join(root, entry);
|
|
450
|
+
if (!existsSync(absolute)) continue;
|
|
451
|
+
visit(absolute, entry === "." ? "" : toPosix(entry));
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
findings.sort((left, right) => {
|
|
455
|
+
return (
|
|
456
|
+
left.file.localeCompare(right.file) ||
|
|
457
|
+
left.line - right.line ||
|
|
458
|
+
left.column - right.column ||
|
|
459
|
+
left.rule.localeCompare(right.rule) ||
|
|
460
|
+
left.value.localeCompare(right.value)
|
|
461
|
+
);
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
const warnings = findings.filter((finding) => finding.severity === "warn").length;
|
|
465
|
+
const errorCount = findings.filter((finding) => finding.severity === "error").length;
|
|
466
|
+
const generatedAt = (options.now instanceof Date ? options.now : new Date()).toISOString();
|
|
467
|
+
|
|
468
|
+
return {
|
|
469
|
+
schemaVersion: SCHEMA_VERSION,
|
|
470
|
+
tool: TOOL,
|
|
471
|
+
toolVersion: VERSION,
|
|
472
|
+
generatedAt,
|
|
473
|
+
theme,
|
|
474
|
+
config: {
|
|
475
|
+
include: effectiveInclude,
|
|
476
|
+
exclude: options.exclude ?? [],
|
|
477
|
+
severity,
|
|
478
|
+
rules: policy,
|
|
479
|
+
},
|
|
480
|
+
summary: {
|
|
481
|
+
files: scannedFiles,
|
|
482
|
+
errors: errorCount,
|
|
483
|
+
warnings,
|
|
484
|
+
ignored: summaryIgnored,
|
|
485
|
+
skipped: skipped.length,
|
|
486
|
+
},
|
|
487
|
+
findings,
|
|
488
|
+
skipped,
|
|
489
|
+
errors,
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
export function formatJson(result) {
|
|
494
|
+
return JSON.stringify(result, null, 2);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
export function formatHuman(result, options = {}) {
|
|
498
|
+
const quiet = options.quiet === true;
|
|
499
|
+
const lines = [];
|
|
500
|
+
lines.push(
|
|
501
|
+
"ztheme audit · " +
|
|
502
|
+
result.summary.files +
|
|
503
|
+
" 个文件 · " +
|
|
504
|
+
result.summary.warnings +
|
|
505
|
+
" 条告警 · " +
|
|
506
|
+
result.summary.errors +
|
|
507
|
+
" 条错误"
|
|
508
|
+
);
|
|
509
|
+
if (result.theme.slug) {
|
|
510
|
+
lines.push(
|
|
511
|
+
"主题 " +
|
|
512
|
+
result.theme.slug +
|
|
513
|
+
"(" +
|
|
514
|
+
result.theme.source +
|
|
515
|
+
(result.theme.suggestions ? "" : ",建议已关闭") +
|
|
516
|
+
")"
|
|
517
|
+
);
|
|
518
|
+
} else {
|
|
519
|
+
lines.push("未指定主题:只报告漂移,不给 token 建议");
|
|
520
|
+
}
|
|
521
|
+
if (result.summary.ignored) lines.push("已忽略 " + result.summary.ignored + " 条");
|
|
522
|
+
if (quiet) return lines.join("\n");
|
|
523
|
+
|
|
524
|
+
let currentFile = null;
|
|
525
|
+
const limit = options.limit ?? 10;
|
|
526
|
+
for (const finding of result.findings.slice(0, limit)) {
|
|
527
|
+
if (finding.file !== currentFile) {
|
|
528
|
+
currentFile = finding.file;
|
|
529
|
+
lines.push("");
|
|
530
|
+
lines.push(finding.file);
|
|
531
|
+
}
|
|
532
|
+
lines.push(
|
|
533
|
+
" " +
|
|
534
|
+
finding.line +
|
|
535
|
+
":" +
|
|
536
|
+
finding.column +
|
|
537
|
+
" " +
|
|
538
|
+
finding.severity +
|
|
539
|
+
" " +
|
|
540
|
+
finding.rule +
|
|
541
|
+
" " +
|
|
542
|
+
finding.evidence +
|
|
543
|
+
(finding.expected ? " (期望 " + finding.expected + ")" : "") +
|
|
544
|
+
(finding.suggestion ? " → " + finding.suggestion : "")
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
if (result.findings.length > limit) {
|
|
548
|
+
lines.push("");
|
|
549
|
+
lines.push("前 " + limit + " 条已展示;完整结果用 --json。");
|
|
550
|
+
}
|
|
551
|
+
if (result.errors.length) {
|
|
552
|
+
lines.push("");
|
|
553
|
+
lines.push("无法扫描 " + result.errors.length + " 个文件:");
|
|
554
|
+
for (const error of result.errors.slice(0, 5)) {
|
|
555
|
+
lines.push(" ! " + error.file + ":" + error.message);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
return lines.join("\n");
|
|
559
|
+
}
|