@wkgeo/cli 1.1.0 → 1.1.2
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/CHANGELOG.md +45 -0
- package/README.md +163 -25
- package/SKILL.md +121 -36
- package/lib/args.mjs +2 -2
- package/lib/asset-role.mjs +68 -0
- package/lib/cms.mjs +2 -2
- package/lib/commands/billing.mjs +56 -10
- package/lib/commands/cms.mjs +49 -13
- package/lib/commands/content.mjs +108 -0
- package/lib/commands/crawl.mjs +219 -0
- package/lib/commands/geo.mjs +1673 -0
- package/lib/commands/index.mjs +640 -541
- package/lib/commands/member.mjs +930 -0
- package/lib/commands/seo.mjs +1386 -0
- package/lib/commands/siteops.mjs +3 -3
- package/lib/commands/sites.mjs +21 -125
- package/lib/commands/template.mjs +1222 -6
- package/lib/config.mjs +16 -13
- package/lib/content-apply.mjs +664 -0
- package/lib/content-check.mjs +887 -0
- package/lib/content-contract.mjs +957 -0
- package/lib/errors.mjs +6 -0
- package/lib/format.mjs +5 -1
- package/lib/login.mjs +15 -3
- package/lib/manifest-apply.mjs +1499 -0
- package/lib/manifest-schema.json +476 -0
- package/lib/manifest.mjs +1082 -0
- package/lib/oauth-urls.mjs +1 -1
- package/lib/runtime.mjs +5 -1
- package/lib/site-create.mjs +536 -0
- package/lib/template-anim.mjs +1338 -0
- package/lib/template-animation.mjs +232 -0
- package/lib/template-capture.mjs +700 -0
- package/lib/template-gen.mjs +1204 -0
- package/lib/template-pack.mjs +206 -0
- package/lib/template-publish.mjs +733 -0
- package/lib/template-score.mjs +865 -0
- package/lib/template-validate.mjs +368 -0
- package/lib/template-verify.mjs +434 -0
- package/lib/templates-sync.mjs +616 -0
- package/package.json +2 -2
|
@@ -0,0 +1,865 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* **模板自评分(100 分制,四维)** —— `wkgeo template score --dir <模板目录>`。
|
|
3
|
+
*
|
|
4
|
+
* 为什么要它:`validate` 只会说"合格 / 不合格",`verify` 只比像素,两个都回答不了
|
|
5
|
+
* 「这套模板拿去卖,到底哪儿还差一口气」。评分必须**可解释**:每一分都能追到
|
|
6
|
+
* 一条子项、一句扣分理由、一个证据路径(文件 / 目录 / 行号口径的路径字符串)。
|
|
7
|
+
*
|
|
8
|
+
* ## 四个维度(各 25 分)
|
|
9
|
+
* 1. **结构完整**:直接复用 `template-validate.mjs` 的 8 关(manifest/format/site/menus/
|
|
10
|
+
* columns/pages/base/links),**不另写一套规则** —— 校验改了,评分跟着改。
|
|
11
|
+
* 2. **移动适配**:本机 Chrome 真渲染 390 / 768 / 1440 三档,量横向溢出、<12px 字号、
|
|
12
|
+
* <44px 点击区(`offsetWidth/offsetHeight` 取布局盒,不受 transform 影响 ⇒ 可复现)。
|
|
13
|
+
* 3. **视觉层次**:静态读页面与 CSS —— 首屏 h1 / hero / main、留白刻度、配色与字体 token
|
|
14
|
+
* 成体系、图片断链与占位坏图。
|
|
15
|
+
* 4. **动画质量**:静态读 CSS/JS —— 缓动(ease / cubic-bezier vs linear)、时长成组、
|
|
16
|
+
* reveal / counter 类渐进出现、`prefers-reduced-motion` 兜底。判「自然不突兀」,不追花哨。
|
|
17
|
+
*
|
|
18
|
+
* ## 可复现(硬要求)
|
|
19
|
+
* 同一目录两次跑必须**同分**。所以:
|
|
20
|
+
* * 不把时间戳 / 随机数写进结果(`elapsed_ms` 只在命令层,不参与计分);
|
|
21
|
+
* * 文件遍历一律 `sort()`,证据数组去重后排序;
|
|
22
|
+
* * 移动量测固定视口、固定 settle 时间、用布局盒(不用 `getBoundingClientRect`,避免动画位移抖动);
|
|
23
|
+
* * 分数统一 `round1`(一位小数),阈值判定用同一套整数/比较。
|
|
24
|
+
*
|
|
25
|
+
* 等级:A ≥ 85 / B ≥ 70 / C ≥ 55 / D(其余)。
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import fs from 'node:fs';
|
|
29
|
+
import fsp from 'node:fs/promises';
|
|
30
|
+
import path from 'node:path';
|
|
31
|
+
import os from 'node:os';
|
|
32
|
+
import { spawn } from 'node:child_process';
|
|
33
|
+
|
|
34
|
+
import { CliError } from './errors.mjs';
|
|
35
|
+
import { validateTemplate } from './template-validate.mjs';
|
|
36
|
+
import { resolveChrome, startStaticServer } from './template-capture.mjs';
|
|
37
|
+
|
|
38
|
+
/** 评分结果格式(写进 JSON 信封,消费方据此判版本) */
|
|
39
|
+
export const SCORE_FORMAT = 'wkgeo-score@1';
|
|
40
|
+
|
|
41
|
+
/** 等级线(A ≥85 / B ≥70 / C ≥55 / D 其余) */
|
|
42
|
+
export const GRADE_LINES = { A: 85, B: 70, C: 55 };
|
|
43
|
+
|
|
44
|
+
/** 移动适配量测的三档视口(任务口径:390 / 768 / 1440) */
|
|
45
|
+
export const MEASURE_VIEWPORTS = [
|
|
46
|
+
{ name: 'mobile-390', width: 390, height: 844 },
|
|
47
|
+
{ name: 'tablet-768', width: 768, height: 1024 },
|
|
48
|
+
{ name: 'desktop-1440', width: 1440, height: 900 },
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
/** 四维权重(各 25,合计 100) */
|
|
52
|
+
export const DIMENSIONS = [
|
|
53
|
+
{ key: 'structure', name: '结构完整', max: 25 },
|
|
54
|
+
{ key: 'mobile', name: '移动适配', max: 25 },
|
|
55
|
+
{ key: 'visual', name: '视觉层次', max: 25 },
|
|
56
|
+
{ key: 'animation', name: '动画质量', max: 25 },
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
const round1 = (n) => Math.round(Number(n) * 10) / 10;
|
|
60
|
+
const clamp01 = (n) => (n < 0 ? 0 : n > 1 ? 1 : n);
|
|
61
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
62
|
+
|
|
63
|
+
function listFiles(root, filter = null, out = []) {
|
|
64
|
+
let entries = [];
|
|
65
|
+
try {
|
|
66
|
+
entries = fs.readdirSync(root, { withFileTypes: true });
|
|
67
|
+
} catch {
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
71
|
+
for (const e of entries) {
|
|
72
|
+
const full = path.join(root, e.name);
|
|
73
|
+
if (e.isDirectory()) {
|
|
74
|
+
if (e.name === 'node_modules' || e.name === '.git') continue;
|
|
75
|
+
listFiles(full, filter, out);
|
|
76
|
+
} else if (e.isFile() && (!filter || filter(e.name))) {
|
|
77
|
+
out.push(full);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function readTextSafe(file) {
|
|
84
|
+
try {
|
|
85
|
+
return fs.readFileSync(file, 'utf8');
|
|
86
|
+
} catch {
|
|
87
|
+
return '';
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 证据路径统一成「相对模板目录的正斜杠路径」,跨机器稳定 */
|
|
92
|
+
function relTo(dir, file) {
|
|
93
|
+
return path.relative(dir, file).replace(/\\/g, '/');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/* ------------------------------------------------------------------ 1. 结构完整 */
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* 8 关 → 6 个子项(25 分)。分组只做"归并展示",不改校验规则:
|
|
100
|
+
* 同一关的 error 就是这条子项的扣分理由。
|
|
101
|
+
*/
|
|
102
|
+
const STRUCTURE_GROUPS = [
|
|
103
|
+
{ key: 'manifest', name: 'template.json 必填字段', max: 6, checks: ['manifest', 'format'] },
|
|
104
|
+
{ key: 'site', name: '站点信息(site / logo / seo)', max: 3, checks: ['site'] },
|
|
105
|
+
{ key: 'menus', name: '菜单与菜单项', max: 4, checks: ['menus'] },
|
|
106
|
+
{ key: 'columns', name: '栏目与字段', max: 5, checks: ['columns'] },
|
|
107
|
+
{ key: 'pages', name: '页面与单页绑定', max: 5, checks: ['pages'] },
|
|
108
|
+
{ key: 'assets', name: '基础库与资源可达', max: 2, checks: ['base', 'links'] },
|
|
109
|
+
];
|
|
110
|
+
|
|
111
|
+
async function scoreStructure({ dir, cwd }) {
|
|
112
|
+
const validation = await validateTemplate({ dir, cwd, requireDesign: false });
|
|
113
|
+
const byId = new Map(validation.checks.map((c) => [c.id, c]));
|
|
114
|
+
const items = [];
|
|
115
|
+
for (const g of STRUCTURE_GROUPS) {
|
|
116
|
+
const hit = g.checks.map((id) => byId.get(id)).filter(Boolean);
|
|
117
|
+
const okCount = hit.filter((c) => c.ok).length;
|
|
118
|
+
const ratio = hit.length ? okCount / hit.length : 0;
|
|
119
|
+
const reasons = [];
|
|
120
|
+
for (const c of hit) {
|
|
121
|
+
if (!c.ok) reasons.push(`${c.id} 关未过:${(c.errors[0] || '').slice(0, 160)}`);
|
|
122
|
+
else for (const w of (c.warnings || []).slice(0, 1)) reasons.push(`(提醒)${c.id}:${w.slice(0, 120)}`);
|
|
123
|
+
}
|
|
124
|
+
items.push({
|
|
125
|
+
key: g.key,
|
|
126
|
+
name: g.name,
|
|
127
|
+
max: g.max,
|
|
128
|
+
score: round1(g.max * ratio),
|
|
129
|
+
ok: okCount === hit.length && hit.length > 0,
|
|
130
|
+
detail: `${okCount}/${hit.length} 关通过`,
|
|
131
|
+
reasons,
|
|
132
|
+
evidence: hit.map((c) => `template.json#${c.id}(${c.title})`),
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
const score = round1(items.reduce((n, it) => n + it.score, 0));
|
|
136
|
+
return {
|
|
137
|
+
key: 'structure',
|
|
138
|
+
name: '结构完整',
|
|
139
|
+
max: 25,
|
|
140
|
+
score,
|
|
141
|
+
items,
|
|
142
|
+
note: '直接复用 `template validate` 的 8 关(manifest / format / site / menus / columns / pages / base / links),不另写规则',
|
|
143
|
+
validation_ok: validation.ok,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/* ------------------------------------------------------------------ 2. 移动适配 */
|
|
148
|
+
|
|
149
|
+
/** 在页面里跑的量测脚本(返回 JSON 字符串):溢出 / 小字号 / 小点击区 */
|
|
150
|
+
export function buildMeasureExpression() {
|
|
151
|
+
return `(() => {
|
|
152
|
+
const sel = (el) => {
|
|
153
|
+
let s = el.tagName.toLowerCase();
|
|
154
|
+
if (el.id) return s + '#' + el.id;
|
|
155
|
+
const cls = String(el.getAttribute('class') || '').trim().split(/\\s+/).filter(Boolean).slice(0, 2);
|
|
156
|
+
if (cls.length) s += '.' + cls.join('.');
|
|
157
|
+
return s;
|
|
158
|
+
};
|
|
159
|
+
const vw = window.innerWidth || 0;
|
|
160
|
+
const docEl = document.documentElement;
|
|
161
|
+
const bodyW = document.body ? document.body.scrollWidth : 0;
|
|
162
|
+
const scrollWidth = Math.max(docEl ? docEl.scrollWidth : 0, bodyW);
|
|
163
|
+
const overflow = Math.max(0, scrollWidth - vw);
|
|
164
|
+
const offenders = [];
|
|
165
|
+
if (overflow > 1) {
|
|
166
|
+
for (const el of document.querySelectorAll('body *')) {
|
|
167
|
+
const r = el.getBoundingClientRect();
|
|
168
|
+
if (r.width > 0 && (r.right > vw + 1 || r.left < -1)) {
|
|
169
|
+
offenders.push(sel(el) + ' [' + Math.round(r.left) + ',' + Math.round(r.right) + ']');
|
|
170
|
+
if (offenders.length >= 6) break;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const smallText = [];
|
|
175
|
+
const tapTargets = [];
|
|
176
|
+
const seen = new Set();
|
|
177
|
+
let tapTotal = 0;
|
|
178
|
+
for (const el of document.querySelectorAll('body *')) {
|
|
179
|
+
const w = el.offsetWidth || 0;
|
|
180
|
+
const h = el.offsetHeight || 0;
|
|
181
|
+
if (!w || !h) continue;
|
|
182
|
+
const cs = getComputedStyle(el);
|
|
183
|
+
if (cs.visibility === 'hidden' || cs.display === 'none' || cs.opacity === '0') continue;
|
|
184
|
+
let ownText = false;
|
|
185
|
+
for (const n of el.childNodes) {
|
|
186
|
+
if (n.nodeType === 3 && n.textContent && n.textContent.trim().length > 0) { ownText = true; break; }
|
|
187
|
+
}
|
|
188
|
+
if (ownText) {
|
|
189
|
+
const fs2 = parseFloat(cs.fontSize) || 0;
|
|
190
|
+
if (fs2 > 0 && fs2 < 12) {
|
|
191
|
+
const k = 't:' + sel(el) + ':' + fs2;
|
|
192
|
+
if (!seen.has(k)) { seen.add(k); smallText.push(sel(el) + ' ' + fs2 + 'px'); }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (el.matches('a[href],button,input:not([type="hidden"]),select,textarea,[role="button"],[onclick]')) {
|
|
196
|
+
tapTotal += 1;
|
|
197
|
+
if (w < 44 || h < 44) {
|
|
198
|
+
const k = 'b:' + sel(el) + ':' + w + 'x' + h;
|
|
199
|
+
if (!seen.has(k)) { seen.add(k); tapTargets.push(sel(el) + ' ' + w + 'x' + h); }
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
smallText.sort(); tapTargets.sort();
|
|
204
|
+
return JSON.stringify({ vw, scrollWidth, overflow, offenders, smallText, tapTargets, tapTotal });
|
|
205
|
+
})()`;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** 极简 CDP 客户端(与 `template-capture.mjs` 同一套做法;这里是评分侧独立实现,避免动 task-42 的文件) */
|
|
209
|
+
class Cdp {
|
|
210
|
+
constructor(ws) {
|
|
211
|
+
this.ws = ws;
|
|
212
|
+
this.nextId = 1;
|
|
213
|
+
this.pending = new Map();
|
|
214
|
+
this.listeners = [];
|
|
215
|
+
ws.addEventListener('message', (ev) => {
|
|
216
|
+
let msg;
|
|
217
|
+
try {
|
|
218
|
+
msg = JSON.parse(typeof ev.data === 'string' ? ev.data : ev.data.toString());
|
|
219
|
+
} catch {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (msg.id && this.pending.has(msg.id)) {
|
|
223
|
+
const { resolve, reject } = this.pending.get(msg.id);
|
|
224
|
+
this.pending.delete(msg.id);
|
|
225
|
+
if (msg.error) reject(new CliError(`CDP 出错:${msg.error.message || 'unknown'}`, { kind: 'capture', code: 'ECDP' }));
|
|
226
|
+
else resolve(msg.result);
|
|
227
|
+
} else if (msg.method) {
|
|
228
|
+
for (const fn of this.listeners) fn(msg);
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
send(method, params = {}, sessionId) {
|
|
234
|
+
const id = this.nextId++;
|
|
235
|
+
const payload = { id, method, params };
|
|
236
|
+
if (sessionId) payload.sessionId = sessionId;
|
|
237
|
+
return new Promise((resolve, reject) => {
|
|
238
|
+
this.pending.set(id, { resolve, reject });
|
|
239
|
+
this.ws.send(JSON.stringify(payload));
|
|
240
|
+
setTimeout(() => {
|
|
241
|
+
if (this.pending.has(id)) {
|
|
242
|
+
this.pending.delete(id);
|
|
243
|
+
reject(new CliError(`CDP 调用超时:${method}`, { kind: 'capture', code: 'ETIMEOUT' }));
|
|
244
|
+
}
|
|
245
|
+
}, 30000);
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
on(fn) {
|
|
250
|
+
this.listeners.push(fn);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
close() {
|
|
254
|
+
try {
|
|
255
|
+
this.ws.close();
|
|
256
|
+
} catch {
|
|
257
|
+
/* ignore */
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async function killTree(pid) {
|
|
263
|
+
if (!pid) return;
|
|
264
|
+
if (process.platform === 'win32') {
|
|
265
|
+
await new Promise((resolve) => {
|
|
266
|
+
const p = spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
|
|
267
|
+
p.on('close', resolve);
|
|
268
|
+
p.on('error', resolve);
|
|
269
|
+
});
|
|
270
|
+
} else {
|
|
271
|
+
try {
|
|
272
|
+
process.kill(-pid, 'SIGKILL');
|
|
273
|
+
} catch {
|
|
274
|
+
try {
|
|
275
|
+
process.kill(pid, 'SIGKILL');
|
|
276
|
+
} catch {
|
|
277
|
+
/* ignore */
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function removeDir(dir) {
|
|
284
|
+
try {
|
|
285
|
+
await fsp.rm(dir, { recursive: true, force: true });
|
|
286
|
+
} catch {
|
|
287
|
+
/* Windows 偶发占用,留给临时目录清理 */
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function chromeArgs(profileDir) {
|
|
292
|
+
return [
|
|
293
|
+
'--headless=new',
|
|
294
|
+
'--disable-gpu',
|
|
295
|
+
'--hide-scrollbars',
|
|
296
|
+
'--force-device-scale-factor=1',
|
|
297
|
+
'--no-first-run',
|
|
298
|
+
'--no-default-browser-check',
|
|
299
|
+
'--disable-extensions',
|
|
300
|
+
'--disable-background-networking',
|
|
301
|
+
'--disable-sync',
|
|
302
|
+
'--mute-audio',
|
|
303
|
+
`--user-data-dir=${profileDir}`,
|
|
304
|
+
];
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function launchCdp(chromeExe) {
|
|
308
|
+
const exe = resolveChrome(chromeExe);
|
|
309
|
+
const profileDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wk-tpl-score-'));
|
|
310
|
+
const port = 46000 + Math.floor(Math.random() * 8000);
|
|
311
|
+
const child = spawn(exe, [...chromeArgs(profileDir), `--remote-debugging-port=${port}`, 'about:blank'], {
|
|
312
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
313
|
+
windowsHide: true,
|
|
314
|
+
});
|
|
315
|
+
let stderr = '';
|
|
316
|
+
child.stderr.on('data', (d) => {
|
|
317
|
+
if (stderr.length < 8000) stderr += d.toString('utf8');
|
|
318
|
+
});
|
|
319
|
+
const deadline = Date.now() + 20000;
|
|
320
|
+
let wsUrl = null;
|
|
321
|
+
while (Date.now() < deadline) {
|
|
322
|
+
try {
|
|
323
|
+
const res = await fetch(`http://127.0.0.1:${port}/json/version`);
|
|
324
|
+
if (res.ok) {
|
|
325
|
+
const j = await res.json();
|
|
326
|
+
if (j.webSocketDebuggerUrl) {
|
|
327
|
+
wsUrl = j.webSocketDebuggerUrl;
|
|
328
|
+
break;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
} catch {
|
|
332
|
+
/* 端口还没起来 */
|
|
333
|
+
}
|
|
334
|
+
await sleep(120);
|
|
335
|
+
}
|
|
336
|
+
if (!wsUrl) {
|
|
337
|
+
await killTree(child.pid);
|
|
338
|
+
await removeDir(profileDir);
|
|
339
|
+
throw new CliError(`连不上 Chrome 调试端口 ${port}(CDP 不可用)`, {
|
|
340
|
+
kind: 'capture',
|
|
341
|
+
code: 'ECDP',
|
|
342
|
+
hint: `Chrome 输出:${stderr.trim().slice(0, 300) || '(空)'}`,
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
return { child, wsUrl, profileDir };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* 三档视口各量一次(同一个浏览器会话,换 metrics 后重新导航)。
|
|
350
|
+
* @returns {Promise<Array<{name,width,height,overflow,offenders,smallText,tapTargets,tapTotal,error?}>>}
|
|
351
|
+
*/
|
|
352
|
+
export async function measureLayout({ url, chromeExe = null, settleMs = 400 } = {}) {
|
|
353
|
+
const launched = await launchCdp(chromeExe);
|
|
354
|
+
let session = null;
|
|
355
|
+
const results = [];
|
|
356
|
+
try {
|
|
357
|
+
const ws = new WebSocket(launched.wsUrl);
|
|
358
|
+
await new Promise((resolve, reject) => {
|
|
359
|
+
ws.addEventListener('open', resolve, { once: true });
|
|
360
|
+
ws.addEventListener('error', () => reject(new CliError('CDP WebSocket 连接失败', { kind: 'capture', code: 'ECDP' })), { once: true });
|
|
361
|
+
setTimeout(() => reject(new CliError('CDP WebSocket 连接超时', { kind: 'capture', code: 'ECDP' })), 15000);
|
|
362
|
+
});
|
|
363
|
+
session = new Cdp(ws);
|
|
364
|
+
const { targetId } = await session.send('Target.createTarget', { url: 'about:blank' });
|
|
365
|
+
const { sessionId } = await session.send('Target.attachToTarget', { targetId, flatten: true });
|
|
366
|
+
const send = (m, p) => session.send(m, p, sessionId);
|
|
367
|
+
let loadedSeq = 0;
|
|
368
|
+
session.on((msg) => {
|
|
369
|
+
if (msg.sessionId === sessionId && msg.method === 'Page.loadEventFired') loadedSeq += 1;
|
|
370
|
+
});
|
|
371
|
+
await send('Page.enable');
|
|
372
|
+
|
|
373
|
+
for (const vp of MEASURE_VIEWPORTS) {
|
|
374
|
+
const before = loadedSeq;
|
|
375
|
+
await send('Emulation.setDeviceMetricsOverride', { width: vp.width, height: vp.height, deviceScaleFactor: 1, mobile: vp.width < 768 });
|
|
376
|
+
const started = Date.now();
|
|
377
|
+
await send('Page.navigate', { url });
|
|
378
|
+
while (loadedSeq === before && Date.now() - started < 25000) await sleep(80);
|
|
379
|
+
await sleep(settleMs);
|
|
380
|
+
try {
|
|
381
|
+
const r = await send('Runtime.evaluate', { expression: buildMeasureExpression(), returnByValue: true });
|
|
382
|
+
const v = r && r.result ? r.result.value : null;
|
|
383
|
+
const parsed = typeof v === 'string' ? JSON.parse(v) : v || {};
|
|
384
|
+
results.push({ ...vp, ...parsed, error: null });
|
|
385
|
+
} catch (e) {
|
|
386
|
+
results.push({ ...vp, overflow: 0, offenders: [], smallText: [], tapTargets: [], tapTotal: 0, error: (e && e.message) || String(e) });
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return results;
|
|
390
|
+
} finally {
|
|
391
|
+
if (session) session.close();
|
|
392
|
+
await killTree(launched.child.pid);
|
|
393
|
+
await removeDir(launched.profileDir);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** 溢出 / 字号 / 点击区三组子项(25 分 = 溢出 15 + 字号 5 + 点击区 5) */
|
|
398
|
+
function mobileItems(measurements) {
|
|
399
|
+
const items = [];
|
|
400
|
+
const [m390, m768, m1440] = MEASURE_VIEWPORTS.map((vp) => measurements.find((m) => m.name === vp.name) || null);
|
|
401
|
+
|
|
402
|
+
// 15 = 三档各 5 分:溢出 >1px 即 0 分(横向滚动条对移动端是硬伤)
|
|
403
|
+
const overflowScore = [
|
|
404
|
+
[m390, 5, '390 移动'],
|
|
405
|
+
[m768, 5, '768 平板'],
|
|
406
|
+
[m1440, 5, '1440 桌面'],
|
|
407
|
+
];
|
|
408
|
+
let overflowTotal = 0;
|
|
409
|
+
const overflowDetails = [];
|
|
410
|
+
for (const [m, max, label] of overflowScore) {
|
|
411
|
+
if (!m) {
|
|
412
|
+
overflowTotal += 0;
|
|
413
|
+
overflowDetails.push({ label, max, score: 0, reasons: ['未量到(Chrome 不可用或页面加载失败)'], evidence: [] });
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
const bad = Number(m.overflow) > 1;
|
|
417
|
+
const score = bad ? 0 : max;
|
|
418
|
+
overflowTotal += score;
|
|
419
|
+
overflowDetails.push({
|
|
420
|
+
label,
|
|
421
|
+
max,
|
|
422
|
+
score,
|
|
423
|
+
reasons: bad ? [`横向溢出 ${m.overflow}px(scrollWidth ${m.scrollWidth} > 视口 ${m.vw})`, ...m.offenders.slice(0, 3).map((o) => `越界元素 ${o}`)] : [],
|
|
424
|
+
evidence: [`${m.width}x${m.height}`],
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
items.push({
|
|
428
|
+
key: 'overflow',
|
|
429
|
+
name: '三档横向溢出(390 / 768 / 1440)',
|
|
430
|
+
max: 15,
|
|
431
|
+
score: round1(overflowTotal),
|
|
432
|
+
ok: overflowTotal === 15,
|
|
433
|
+
detail: overflowDetails.map((d) => `${d.label} ${d.score}/${d.max}`).join(' · '),
|
|
434
|
+
reasons: overflowDetails.flatMap((d) => d.reasons.map((r) => `[${d.label}] ${r}`)),
|
|
435
|
+
evidence: overflowDetails.flatMap((d) => d.evidence),
|
|
436
|
+
sub: overflowDetails,
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
// 字号:< 12px 的正文文字(三档合计,去重后取最差档的条数)
|
|
440
|
+
const smallCounts = [m390, m768, m1440].filter(Boolean).map((m) => (m.smallText || []).length);
|
|
441
|
+
const worstSmall = smallCounts.length ? Math.max(...smallCounts) : 0;
|
|
442
|
+
items.push({
|
|
443
|
+
key: 'font',
|
|
444
|
+
name: '字号(< 12px 正文)',
|
|
445
|
+
max: 5,
|
|
446
|
+
score: smallCounts.length === 0 ? 0 : round1(5 * clamp01(1 - worstSmall / 8)),
|
|
447
|
+
ok: worstSmall === 0,
|
|
448
|
+
detail: smallCounts.length ? `最差档 ${worstSmall} 处 <12px` : '未量到',
|
|
449
|
+
reasons: worstSmall ? [`最差档有 ${worstSmall} 处正文字号 < 12px`, ...[m390, m768, m1440].filter(Boolean).flatMap((m) => (m.smallText || []).slice(0, 2).map((s) => `[${m.name}] ${s}`))] : [],
|
|
450
|
+
evidence: [m390, m768, m1440].filter(Boolean).map((m) => `${m.width}x${m.height}`),
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
// 点击区:交互元素 < 44px 的占比(取三档最差)
|
|
454
|
+
const ratios = [m390, m768, m1440].filter(Boolean).map((m) => ({ m, ratio: m.tapTotal ? (m.tapTargets || []).length / m.tapTotal : 0 }));
|
|
455
|
+
const worst = ratios.length ? ratios.reduce((a, b) => (b.ratio > a.ratio ? b : a)) : null;
|
|
456
|
+
items.push({
|
|
457
|
+
key: 'tap',
|
|
458
|
+
name: '点击区 ≥ 44px',
|
|
459
|
+
max: 5,
|
|
460
|
+
score: worst ? round1(5 * clamp01(1 - worst.ratio)) : 0,
|
|
461
|
+
ok: !!worst && worst.ratio === 0,
|
|
462
|
+
detail: worst ? `最差档 ${(worst.m.tapTargets || []).length}/${worst.m.tapTotal} 个交互元素不足 44px` : '未量到',
|
|
463
|
+
reasons: worst && worst.ratio > 0 ? [`[${worst.m.name}] ${(worst.m.tapTargets || []).length}/${worst.m.tapTotal} 个交互元素 < 44px`, ...(worst.m.tapTargets || []).slice(0, 3).map((t) => `过小 ${t}`)] : [],
|
|
464
|
+
evidence: worst ? [`${worst.m.width}x${worst.m.height}`] : [],
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
return items;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
async function scoreMobile({ dir, chromeExe = null, noChrome = false, page = '/pages/index.html' }) {
|
|
471
|
+
const base = {
|
|
472
|
+
key: 'mobile',
|
|
473
|
+
name: '移动适配',
|
|
474
|
+
max: 25,
|
|
475
|
+
score: 0,
|
|
476
|
+
items: [],
|
|
477
|
+
note: '本机 Chrome 真渲染:`offsetWidth/offsetHeight` 取布局盒(不受动画 transform 影响 ⇒ 两次跑同分)',
|
|
478
|
+
};
|
|
479
|
+
if (noChrome) {
|
|
480
|
+
return { ...base, skipped: true, items: mobileItems([]), note: `${base.note};已用 --no-chrome 跳过量测` };
|
|
481
|
+
}
|
|
482
|
+
let server = null;
|
|
483
|
+
let measurements = [];
|
|
484
|
+
let chromeError = null;
|
|
485
|
+
try {
|
|
486
|
+
resolveChrome(chromeExe);
|
|
487
|
+
server = await startStaticServer(dir);
|
|
488
|
+
const relPage = String(page).startsWith('/') ? String(page) : `/${page}`;
|
|
489
|
+
const url = server.url.replace(/\/+$/, '') + relPage;
|
|
490
|
+
measurements = await measureLayout({ url, chromeExe });
|
|
491
|
+
// 报告里只记**相对路径**:本地静态服务端口是随机的,写进去两次跑就不同分了
|
|
492
|
+
base.page = relPage;
|
|
493
|
+
} catch (e) {
|
|
494
|
+
chromeError = (e && e.message) || String(e);
|
|
495
|
+
measurements = [];
|
|
496
|
+
} finally {
|
|
497
|
+
if (server) server.close();
|
|
498
|
+
}
|
|
499
|
+
const items = mobileItems(measurements);
|
|
500
|
+
const score = round1(items.reduce((n, it) => n + it.score, 0));
|
|
501
|
+
return {
|
|
502
|
+
...base,
|
|
503
|
+
score,
|
|
504
|
+
items,
|
|
505
|
+
skipped: false,
|
|
506
|
+
chrome_error: chromeError,
|
|
507
|
+
measurements: measurements.map((m) => ({
|
|
508
|
+
name: m.name,
|
|
509
|
+
width: m.width,
|
|
510
|
+
height: m.height,
|
|
511
|
+
overflow: m.overflow,
|
|
512
|
+
scroll_width: m.scrollWidth,
|
|
513
|
+
small_text: (m.smallText || []).length,
|
|
514
|
+
tap_targets: (m.tapTargets || []).length,
|
|
515
|
+
tap_total: m.tapTotal,
|
|
516
|
+
error: m.error || null,
|
|
517
|
+
})),
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/* ------------------------------------------------------------------ 3. 视觉层次 */
|
|
522
|
+
|
|
523
|
+
function extractCssBodies(html) {
|
|
524
|
+
const out = [];
|
|
525
|
+
for (const m of String(html || '').matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)) out.push(m[1]);
|
|
526
|
+
return out;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function countVarUsage(css) {
|
|
530
|
+
return (String(css || '').match(/var\(\s*--/g) || []).length;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function distinctDecl(css, propRe) {
|
|
534
|
+
const vals = new Set();
|
|
535
|
+
for (const m of String(css || '').matchAll(propRe)) {
|
|
536
|
+
const v = String(m[1] || '').trim().replace(/\s+/g, ' ');
|
|
537
|
+
if (v) vals.add(v);
|
|
538
|
+
}
|
|
539
|
+
return [...vals].sort();
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
function scoreVisual({ dir, pageHtml, cssAll, files }) {
|
|
543
|
+
const items = [];
|
|
544
|
+
const html = String(pageHtml || '');
|
|
545
|
+
const css = String(cssAll || '');
|
|
546
|
+
|
|
547
|
+
// 3.1 首屏信息层级(7 = h1 唯一 3 + hero 容器 2 + main/首屏 section 2)
|
|
548
|
+
const h1Count = (html.match(/<h1\b/gi) || []).length;
|
|
549
|
+
const hasHero = /class\s*=\s*["'][^"']*\bhero\b/i.test(html) || /\bid\s*=\s*["']hero["']/i.test(html) || /data-hero/i.test(html);
|
|
550
|
+
const hasMain = /<main\b/i.test(html) || /<section\b/i.test(html);
|
|
551
|
+
let headScore = 0;
|
|
552
|
+
const headReasons = [];
|
|
553
|
+
if (h1Count === 1) headScore += 3;
|
|
554
|
+
else headReasons.push(`<h1> 数量是 ${h1Count}(首屏应恰好 1 个主标题)`);
|
|
555
|
+
if (hasHero) headScore += 2;
|
|
556
|
+
else headReasons.push('首屏没有 hero 容器(class 含 hero / id=hero / data-hero 均未命中),信息层级靠区块堆叠');
|
|
557
|
+
if (hasMain) headScore += 2;
|
|
558
|
+
else headReasons.push('没有 <main> 或 <section> 语义容器');
|
|
559
|
+
items.push({
|
|
560
|
+
key: 'hierarchy',
|
|
561
|
+
name: '首屏信息层级',
|
|
562
|
+
max: 7,
|
|
563
|
+
score: headScore,
|
|
564
|
+
ok: headScore === 7,
|
|
565
|
+
detail: `h1 ${h1Count} 个 · hero ${hasHero ? '有' : '无'} · main/section ${hasMain ? '有' : '无'}`,
|
|
566
|
+
reasons: headReasons,
|
|
567
|
+
evidence: ['pages/'],
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
// 3.2 留白(6 = 间距 token 3 + 区块内边距成组 3)
|
|
571
|
+
const spacingTokens = new Set([...css.matchAll(/--(?:space|spacing|gap)[\w-]*\s*:/gi)].map((m) => m[0].replace(/[\s:]+$/, '')));
|
|
572
|
+
const sectionPaddings = distinctDecl(css, /(?:^|[;{])\s*(?:padding(?:-top|-bottom)?|margin(?:-top|-bottom)?)\s*:\s*([^;}]+)/gi);
|
|
573
|
+
let spaceScore = 0;
|
|
574
|
+
const spaceReasons = [];
|
|
575
|
+
if (spacingTokens.size >= 3) spaceScore += 3;
|
|
576
|
+
else spaceReasons.push(`间距 token 只有 ${spacingTokens.size} 个(≥3 才算成体系)`);
|
|
577
|
+
if (sectionPaddings.length > 0 && sectionPaddings.length <= 12) spaceScore += 3;
|
|
578
|
+
else if (sectionPaddings.length > 12) spaceReasons.push(`留白取值 ${sectionPaddings.length} 种(>12 显得随意,应有刻度)`);
|
|
579
|
+
else spaceReasons.push('CSS 里没有可识别的留白声明');
|
|
580
|
+
items.push({
|
|
581
|
+
key: 'spacing',
|
|
582
|
+
name: '留白与间距刻度',
|
|
583
|
+
max: 6,
|
|
584
|
+
score: spaceScore,
|
|
585
|
+
ok: spaceScore === 6,
|
|
586
|
+
detail: `间距 token ${spacingTokens.size} 个 · 留白取值 ${sectionPaddings.length} 种`,
|
|
587
|
+
reasons: spaceReasons,
|
|
588
|
+
evidence: [...(spacingTokens.size ? ['assets/'] : [])],
|
|
589
|
+
});
|
|
590
|
+
|
|
591
|
+
// 3.3 配色 / 字体 token(6 = 至少 8 个变量 2 + 字体 token 2 + var() 用量 ≥20 2)
|
|
592
|
+
const rootVars = new Set([...css.matchAll(/(--[a-z][\w-]*)\s*:/gi)].map((m) => m[1]));
|
|
593
|
+
const colorVars = [...rootVars].filter((v) => /--(?:color|c-|bg|fg|brand|primary|accent|text|border|surface)/i.test(v));
|
|
594
|
+
const fontVars = [...rootVars].filter((v) => /--(?:font|ff|type)/i.test(v));
|
|
595
|
+
const varUses = countVarUsage(css);
|
|
596
|
+
let tokenScore = 0;
|
|
597
|
+
const tokenReasons = [];
|
|
598
|
+
if (rootVars.size >= 8) tokenScore += 2;
|
|
599
|
+
else tokenReasons.push(`CSS 变量只有 ${rootVars.size} 个(<8,配色/字号没有集中成体系)`);
|
|
600
|
+
if (fontVars.length >= 2) tokenScore += 2;
|
|
601
|
+
else tokenReasons.push(`字体 token ${fontVars.length} 个(<2,中英文字族没有抽出来)`);
|
|
602
|
+
if (varUses >= 20) tokenScore += 2;
|
|
603
|
+
else tokenReasons.push(`var(--…) 用了 ${varUses} 次(<20,token 抽了但没真用起来)`);
|
|
604
|
+
items.push({
|
|
605
|
+
key: 'tokens',
|
|
606
|
+
name: '配色 / 字体 token 成体系',
|
|
607
|
+
max: 6,
|
|
608
|
+
score: tokenScore,
|
|
609
|
+
ok: tokenScore === 6,
|
|
610
|
+
detail: `变量 ${rootVars.size} 个(配色类 ${colorVars.length} / 字体类 ${fontVars.length})· var() 用量 ${varUses}`,
|
|
611
|
+
reasons: tokenReasons,
|
|
612
|
+
evidence: ['assets/'],
|
|
613
|
+
});
|
|
614
|
+
|
|
615
|
+
// 3.4 图片断链与占位坏图(6)
|
|
616
|
+
const pageDir = path.join(dir, 'pages');
|
|
617
|
+
const imgRefs = [...html.matchAll(/<img\b[^>]*>/gi)]
|
|
618
|
+
.map((m) => (m[0].match(/\ssrc\s*=\s*["']([^"']*)["']/i) || [])[1] || '')
|
|
619
|
+
.filter((v) => v && !/^(data:|https?:|\/\/)/i.test(v));
|
|
620
|
+
const uniqueRefs = [...new Set(imgRefs)].sort();
|
|
621
|
+
const broken = [];
|
|
622
|
+
const placeholders = [];
|
|
623
|
+
for (const ref of uniqueRefs) {
|
|
624
|
+
const clean = ref.split('?')[0].replace(/^\.\//, '');
|
|
625
|
+
const candidates = [path.join(dir, clean), path.join(pageDir, clean), path.join(dir, clean.replace(/^(\.\.\/)+/, ''))];
|
|
626
|
+
const hit = candidates.find((p) => {
|
|
627
|
+
try {
|
|
628
|
+
return fs.statSync(p).isFile();
|
|
629
|
+
} catch {
|
|
630
|
+
return false;
|
|
631
|
+
}
|
|
632
|
+
});
|
|
633
|
+
if (!hit) {
|
|
634
|
+
broken.push(ref);
|
|
635
|
+
continue;
|
|
636
|
+
}
|
|
637
|
+
const bytes = fs.statSync(hit).size;
|
|
638
|
+
if (bytes < 512 || /placeholder|dummy|blank|1x1|transparent/i.test(ref)) placeholders.push(`${ref}(${bytes}B)`);
|
|
639
|
+
}
|
|
640
|
+
const imgScore = uniqueRefs.length === 0 ? 6 : round1(6 * clamp01(1 - (broken.length + placeholders.length) / Math.max(1, uniqueRefs.length)));
|
|
641
|
+
const imgReasons = [];
|
|
642
|
+
if (uniqueRefs.length === 0) imgReasons.push('页面里没有 <img>(纯 CSS/SVG 图形,无外部图片依赖)');
|
|
643
|
+
if (broken.length) imgReasons.push(`断链图片 ${broken.length} 处:${broken.slice(0, 3).join('、')}`);
|
|
644
|
+
if (placeholders.length) imgReasons.push(`占位/坏图 ${placeholders.length} 处:${placeholders.slice(0, 3).join('、')}`);
|
|
645
|
+
items.push({
|
|
646
|
+
key: 'images',
|
|
647
|
+
name: '图片断链与占位坏图',
|
|
648
|
+
max: 6,
|
|
649
|
+
score: imgScore,
|
|
650
|
+
ok: broken.length === 0 && placeholders.length === 0,
|
|
651
|
+
detail: `本地图片引用 ${uniqueRefs.length} 个 · 断链 ${broken.length} · 占位 ${placeholders.length}`,
|
|
652
|
+
reasons: imgReasons,
|
|
653
|
+
evidence: uniqueRefs.slice(0, 8),
|
|
654
|
+
});
|
|
655
|
+
|
|
656
|
+
const score = round1(items.reduce((n, it) => n + it.score, 0));
|
|
657
|
+
return { key: 'visual', name: '视觉层次', max: 25, score, items, note: '静态读首页 HTML + 模板 CSS(不依赖截图)' };
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/* ------------------------------------------------------------------ 4. 动画质量 */
|
|
661
|
+
|
|
662
|
+
function scoreAnimation({ cssAll, jsAll, manifest }) {
|
|
663
|
+
const css = String(cssAll || '');
|
|
664
|
+
const js = String(jsAll || '');
|
|
665
|
+
const items = [];
|
|
666
|
+
|
|
667
|
+
const easingTokens = [
|
|
668
|
+
...css.matchAll(/\b(ease-in-out|ease-out|ease-in|ease|linear|steps\([^)]*\)|cubic-bezier\([^)]*\)|spring\([^)]*\))\b/gi),
|
|
669
|
+
].map((m) => m[1].toLowerCase());
|
|
670
|
+
const explicit = easingTokens.filter((t) => /^(ease|ease-in|ease-out|ease-in-out|cubic-bezier)/i.test(t)).length;
|
|
671
|
+
const linear = easingTokens.filter((t) => t === 'linear').length;
|
|
672
|
+
const easingTotal = easingTokens.length;
|
|
673
|
+
let easingScore = 0;
|
|
674
|
+
const easingReasons = [];
|
|
675
|
+
if (easingTotal === 0) {
|
|
676
|
+
easingReasons.push('CSS 里没有任何 transition / animation 的缓动声明(没有可评的动效)');
|
|
677
|
+
} else {
|
|
678
|
+
easingScore = round1(7 * clamp01(explicit / easingTotal));
|
|
679
|
+
if (linear) easingReasons.push(`${linear} 处用 linear(机械感;除非是 marquee/进度条,否则应换 ease / cubic-bezier)`);
|
|
680
|
+
if (explicit === 0) easingReasons.push('没有 ease / cubic-bezier 自定义曲线');
|
|
681
|
+
}
|
|
682
|
+
items.push({
|
|
683
|
+
key: 'easing',
|
|
684
|
+
name: '缓动曲线(ease / cubic-bezier vs linear)',
|
|
685
|
+
max: 7,
|
|
686
|
+
score: easingScore,
|
|
687
|
+
ok: easingTotal > 0 && linear === 0 && explicit > 0,
|
|
688
|
+
detail: `缓动声明 ${easingTotal} 处(explicit ${explicit} / linear ${linear})`,
|
|
689
|
+
reasons: easingReasons,
|
|
690
|
+
evidence: ['assets/'],
|
|
691
|
+
});
|
|
692
|
+
|
|
693
|
+
const durations = new Set();
|
|
694
|
+
for (const m of css.matchAll(/(?:transition|animation)(?:-duration)?\s*:\s*([^;}]+)/gi)) {
|
|
695
|
+
for (const d of m[1].matchAll(/(-?\d*\.?\d+)(ms|s)\b/gi)) {
|
|
696
|
+
const n = parseFloat(d[1]) * (d[2].toLowerCase() === 's' ? 1000 : 1);
|
|
697
|
+
if (n > 0 && n <= 20000) durations.add(Math.round(n));
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
const durList = [...durations].sort((a, b) => a - b);
|
|
701
|
+
let durScore = 0;
|
|
702
|
+
const durReasons = [];
|
|
703
|
+
if (durList.length === 0) durReasons.push('没有可识别的时长(transition-duration / animation-duration)');
|
|
704
|
+
else if (durList.length <= 6) durScore = 6;
|
|
705
|
+
else {
|
|
706
|
+
durScore = round1(6 * clamp01(6 / durList.length));
|
|
707
|
+
durReasons.push(`时长取值 ${durList.length} 种(应成组,≤6 种;现在是 ${durList.slice(0, 8).join('/')}ms…)`);
|
|
708
|
+
}
|
|
709
|
+
if (durList.length && durList.some((d) => d > 1200)) durReasons.push(`有 ${durList.filter((d) => d > 1200).length} 处时长 > 1200ms(突兀风险)`);
|
|
710
|
+
items.push({
|
|
711
|
+
key: 'duration',
|
|
712
|
+
name: '时长 / 延迟成组',
|
|
713
|
+
max: 6,
|
|
714
|
+
score: durScore,
|
|
715
|
+
ok: durList.length > 0 && durList.length <= 6,
|
|
716
|
+
detail: `时长 ${durList.length} 种${durList.length ? `(${durList.slice(0, 6).join('/')}ms)` : ''}`,
|
|
717
|
+
reasons: durReasons,
|
|
718
|
+
evidence: ['assets/'],
|
|
719
|
+
});
|
|
720
|
+
|
|
721
|
+
// 下面每项单独判,理由可读(不做合并正则,避免"命中但说不清是哪条")
|
|
722
|
+
const revealHits = [];
|
|
723
|
+
if (/data-reveal/i.test(css) || /data-reveal/i.test(js)) revealHits.push('data-reveal');
|
|
724
|
+
if (/IntersectionObserver/.test(js)) revealHits.push('IntersectionObserver');
|
|
725
|
+
if (/\.reveal\b|is-visible|data-animate/i.test(css)) revealHits.push('CSS reveal 类');
|
|
726
|
+
const counterHits = [];
|
|
727
|
+
if (/counter|count-?up|data-count|number-?up/i.test(js)) counterHits.push('数字递增脚本');
|
|
728
|
+
if (/counter|count-?up|data-count/i.test(css)) counterHits.push('counter 样式');
|
|
729
|
+
const revealScore = (revealHits.length ? 4 : 0) + (counterHits.length ? 2 : 0);
|
|
730
|
+
const revealReasons = [];
|
|
731
|
+
if (!revealHits.length) revealReasons.push('没有 reveal 类渐进出现(滚动入场 / IntersectionObserver 都没有)');
|
|
732
|
+
if (!counterHits.length) revealReasons.push('没有 counter / 数字递增类动效(可选,但缺了会显得静态)');
|
|
733
|
+
items.push({
|
|
734
|
+
key: 'reveal',
|
|
735
|
+
name: '渐进出现(reveal / counter)',
|
|
736
|
+
max: 6,
|
|
737
|
+
score: revealScore,
|
|
738
|
+
ok: revealHits.length > 0 && counterHits.length > 0,
|
|
739
|
+
detail: `reveal ${revealHits.length ? revealHits.join('+') : '无'} · counter ${counterHits.length ? counterHits.join('+') : '无'}`,
|
|
740
|
+
reasons: revealReasons,
|
|
741
|
+
evidence: revealHits.length || counterHits.length ? ['assets/'] : [],
|
|
742
|
+
});
|
|
743
|
+
|
|
744
|
+
const reducedHits = [];
|
|
745
|
+
if (/prefers-reduced-motion/i.test(css)) reducedHits.push('模板 CSS');
|
|
746
|
+
items.push({
|
|
747
|
+
key: 'reduced-motion',
|
|
748
|
+
name: 'prefers-reduced-motion 兜底',
|
|
749
|
+
max: 6,
|
|
750
|
+
score: reducedHits.length ? 6 : 0,
|
|
751
|
+
ok: reducedHits.length > 0,
|
|
752
|
+
detail: reducedHits.length ? `命中:${reducedHits.join('、')}` : '模板自己的 CSS 里没有 @media (prefers-reduced-motion)',
|
|
753
|
+
reasons: reducedHits.length ? [] : ['模板 CSS 没有 prefers-reduced-motion 兜底(眩晕敏感用户会直接看到全量动画;基础库有兜底但模板自己覆盖的动效不受保护)'],
|
|
754
|
+
evidence: reducedHits.length ? ['assets/'] : [],
|
|
755
|
+
});
|
|
756
|
+
|
|
757
|
+
const score = round1(items.reduce((n, it) => n + it.score, 0));
|
|
758
|
+
return {
|
|
759
|
+
key: 'animation',
|
|
760
|
+
name: '动画质量',
|
|
761
|
+
max: 25,
|
|
762
|
+
score,
|
|
763
|
+
items,
|
|
764
|
+
note: '静态读模板 CSS / JS;判「自然不突兀」(ease 曲线、时长成组、渐进出现、减弱动效兜底),不追花哨',
|
|
765
|
+
manifest_count: manifest && manifest.counts ? manifest.counts.total : null,
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/* ------------------------------------------------------------------ 汇总 */
|
|
770
|
+
|
|
771
|
+
function gradeOf(total) {
|
|
772
|
+
if (total >= GRADE_LINES.A) return 'A';
|
|
773
|
+
if (total >= GRADE_LINES.B) return 'B';
|
|
774
|
+
if (total >= GRADE_LINES.C) return 'C';
|
|
775
|
+
return 'D';
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* 给一个模板目录打分。
|
|
780
|
+
* @param {object} opts
|
|
781
|
+
* @param {string} opts.dir 模板目录(绝对路径)
|
|
782
|
+
* @param {string} [opts.cwd] 相对路径基准(默认 process.cwd())
|
|
783
|
+
* @param {boolean} [opts.noChrome] 跳过 Chrome 量测(移动适配维度按 0 分计,并写明原因)
|
|
784
|
+
* @param {string} [opts.chromeExe] Chrome 可执行文件
|
|
785
|
+
* @param {string} [opts.page] 首页路径(默认 /pages/index.html)
|
|
786
|
+
*/
|
|
787
|
+
export async function scoreTemplate({ dir, cwd = process.cwd(), noChrome = false, chromeExe = null, page = '/pages/index.html' } = {}) {
|
|
788
|
+
const root = path.resolve(cwd, dir || '.');
|
|
789
|
+
let st = null;
|
|
790
|
+
try {
|
|
791
|
+
st = fs.statSync(root);
|
|
792
|
+
} catch {
|
|
793
|
+
st = null;
|
|
794
|
+
}
|
|
795
|
+
if (!st || !st.isDirectory()) {
|
|
796
|
+
throw new CliError(`模板目录不存在:${root}`, { kind: 'usage', code: 'ENODIR', exitCode: 2 });
|
|
797
|
+
}
|
|
798
|
+
if (!fs.existsSync(path.join(root, 'template.json'))) {
|
|
799
|
+
throw new CliError(`不是模板目录(缺 template.json):${root}`, {
|
|
800
|
+
kind: 'usage',
|
|
801
|
+
code: 'ENOTEMPLATE',
|
|
802
|
+
exitCode: 2,
|
|
803
|
+
hint: '给 `wkgeo template init` 产出的模板根目录(含 template.json + pages/ + assets/)',
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
const files = listFiles(root);
|
|
808
|
+
const htmlFiles = files.filter((f) => /\.html$/i.test(f));
|
|
809
|
+
const cssFiles = files.filter((f) => /\.css$/i.test(f));
|
|
810
|
+
const jsFiles = files.filter((f) => /\.js$/i.test(f));
|
|
811
|
+
const cssAll = cssFiles.map(readTextSafe).join('\n');
|
|
812
|
+
const jsAll = jsFiles.map(readTextSafe).join('\n');
|
|
813
|
+
const homeFile = path.join(root, String(page).replace(/^\//, '').replace(/\//g, path.sep));
|
|
814
|
+
const homeHtml = fs.existsSync(homeFile) ? readTextSafe(homeFile) : '';
|
|
815
|
+
const inlineCss = extractCssBodies(homeHtml).join('\n');
|
|
816
|
+
const cssForVisual = `${cssAll}\n${inlineCss}`;
|
|
817
|
+
|
|
818
|
+
const manifestFile = path.join(root, 'design', 'animations.json');
|
|
819
|
+
let manifest = null;
|
|
820
|
+
try {
|
|
821
|
+
manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
|
|
822
|
+
} catch {
|
|
823
|
+
manifest = null;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
const structure = await scoreStructure({ dir: root, cwd });
|
|
827
|
+
const mobile = await scoreMobile({ dir: root, chromeExe, noChrome, page });
|
|
828
|
+
const visual = scoreVisual({ dir: root, pageHtml: homeHtml, cssAll: cssForVisual, files });
|
|
829
|
+
const animation = scoreAnimation({ cssAll, jsAll, manifest });
|
|
830
|
+
|
|
831
|
+
const dims = [structure, mobile, visual, animation];
|
|
832
|
+
const total = round1(dims.reduce((n, d) => n + d.score, 0));
|
|
833
|
+
|
|
834
|
+
return {
|
|
835
|
+
format: SCORE_FORMAT,
|
|
836
|
+
dir: root,
|
|
837
|
+
key: (() => {
|
|
838
|
+
try {
|
|
839
|
+
return JSON.parse(fs.readFileSync(path.join(root, 'template.json'), 'utf8')).key || path.basename(root);
|
|
840
|
+
} catch {
|
|
841
|
+
return path.basename(root);
|
|
842
|
+
}
|
|
843
|
+
})(),
|
|
844
|
+
total,
|
|
845
|
+
max: 100,
|
|
846
|
+
grade: gradeOf(total),
|
|
847
|
+
grade_lines: GRADE_LINES,
|
|
848
|
+
dimensions: dims,
|
|
849
|
+
facts: {
|
|
850
|
+
files: files.length,
|
|
851
|
+
html_files: htmlFiles.length,
|
|
852
|
+
css_files: cssFiles.length,
|
|
853
|
+
js_files: jsFiles.length,
|
|
854
|
+
home_page: relTo(root, homeFile),
|
|
855
|
+
countdowns: {
|
|
856
|
+
small_text: mobile.measurements ? mobile.measurements.reduce((n, m) => n + (m.small_text || 0), 0) : 0,
|
|
857
|
+
tap_targets: mobile.measurements ? mobile.measurements.reduce((n, m) => n + (m.tap_targets || 0), 0) : 0,
|
|
858
|
+
overflow: mobile.measurements ? mobile.measurements.map((m) => m.overflow) : [],
|
|
859
|
+
},
|
|
860
|
+
animations_manifest: manifest ? relTo(root, manifestFile) : null,
|
|
861
|
+
},
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
export default { scoreTemplate, SCORE_FORMAT, GRADE_LINES, MEASURE_VIEWPORTS, DIMENSIONS, buildMeasureExpression, measureLayout };
|