@wkgeo/cli 1.0.0 → 1.1.1
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 +249 -203
- package/README.md +151 -19
- package/SKILL.md +108 -27
- 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 -528
- 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 +1474 -0
- 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/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/tar.mjs +207 -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-package.mjs +522 -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,1474 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `wkgeo template init` —— 一条命令把基础库(`@wkgeo/base-template`)从 npm 下到本地。
|
|
3
|
+
*
|
|
4
|
+
* ## 老板的原话与定调(2026-10-30)
|
|
5
|
+
* 「基础模版可以开源到 github,或者国内的哪里吗,这样别人 init 初始化的时候就可以下载整套内容」
|
|
6
|
+
* → 「还是放 npm」。所以这里走 **npm 公开包 + npmmirror 镜像**,不做 GitHub 拉源码。
|
|
7
|
+
*
|
|
8
|
+
* ## 一条命令干的事
|
|
9
|
+
* 读 registry 元数据 → 选版本(`dist-tags.latest` 或 `--version`)→ 下 `dist.tarball`
|
|
10
|
+
* → **校验 `dist.integrity`(sha512)** → 解包(防路径穿越)→ 只取白名单
|
|
11
|
+
* → 落 `--to/<模板目录>`(默认 `./_base`)→ 跑包内 `tools/check-base.mjs` 自检。
|
|
12
|
+
*
|
|
13
|
+
* ## 缓存
|
|
14
|
+
* `~/.wkgeo/cache/base/<version>/`(`WKGEO_TEMPLATE_CACHE` 可改)。第二次 init **不发网络请求**;
|
|
15
|
+
* `--force` 强制重下;`--offline` 只读缓存,没缓存就报"哪两个 URL 该能访问"。
|
|
16
|
+
*
|
|
17
|
+
* ## 为什么不复用 `npm install`
|
|
18
|
+
* 1. 不装新依赖、不写 node_modules,也不让用户机器上的 `.npmrc`(可能有公司源/镜像 token)参与;
|
|
19
|
+
* 2. integrity 校验与解包安全策略要**由我们说了算**(拒绝符号链接、只落白名单);
|
|
20
|
+
* 3. 语义是"拷一套模板出来",不是"装一个库进来"——落地目录要能直接 `wkgeo template push`。
|
|
21
|
+
*
|
|
22
|
+
* 相关文档:`docs/功能-基础库分发.md`、`docs/规范-基础库开源内容边界.md`。
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import fs from 'node:fs';
|
|
26
|
+
import path from 'node:path';
|
|
27
|
+
|
|
28
|
+
import { CliError, UsageError, EXIT } from '../errors.mjs';
|
|
29
|
+
// task-46:运行时的动画提取(本文件只加一条子命令,不改已有 shoot/score/publish/init 等代码)
|
|
30
|
+
import { extractAnimationsForCli, printExtractSummary } from '../template-animation.mjs';
|
|
31
|
+
import {
|
|
32
|
+
PACKAGE_NAME,
|
|
33
|
+
cacheRootOf,
|
|
34
|
+
copyTree,
|
|
35
|
+
downloadToCache,
|
|
36
|
+
listCachedVersions,
|
|
37
|
+
packageDirName,
|
|
38
|
+
readCache,
|
|
39
|
+
readLatestPointer,
|
|
40
|
+
registryPlan,
|
|
41
|
+
metadataUrl,
|
|
42
|
+
selfCheck,
|
|
43
|
+
} from '../template-package.mjs';
|
|
44
|
+
import {
|
|
45
|
+
DESIGN_VIEWPORTS,
|
|
46
|
+
generateFromDir,
|
|
47
|
+
generateFromUrl,
|
|
48
|
+
normalizeSiteUrl,
|
|
49
|
+
prepareOutDir,
|
|
50
|
+
slugify,
|
|
51
|
+
} from '../template-gen.mjs';
|
|
52
|
+
import { captureDesign, inspectDesign, resolveChrome, startStaticServer } from '../template-capture.mjs';
|
|
53
|
+
import { verifyTemplate } from '../template-verify.mjs';
|
|
54
|
+
import { extractAnimationsFromDir, writeAnimationManifest, ANIM_MANIFEST_FILE } from '../template-anim.mjs';
|
|
55
|
+
import { assertValid, validateTemplate } from '../template-validate.mjs';
|
|
56
|
+
import { packTemplate } from '../template-pack.mjs';
|
|
57
|
+
import * as scoreMod from '../template-score.mjs';
|
|
58
|
+
import * as publishMod from '../template-publish.mjs';
|
|
59
|
+
import { pullTemplate, pushTemplate } from '../templates-sync.mjs';
|
|
60
|
+
import * as commandsIndex from './index.mjs';
|
|
61
|
+
|
|
62
|
+
function fmtBytes(n) {
|
|
63
|
+
if (!Number.isFinite(n)) return '?';
|
|
64
|
+
if (n < 1024) return `${n}B`;
|
|
65
|
+
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;
|
|
66
|
+
return `${(n / 1024 / 1024).toFixed(2)}MB`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function readJsonSafe(file) {
|
|
70
|
+
try {
|
|
71
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
72
|
+
} catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 目标目录:`--to` 是**父目录**,落 `<to>/<模板目录名>`;`--to` 本身已是该名字时直接用 */
|
|
78
|
+
export function resolveTarget(toFlag, dirName, cwd = process.cwd()) {
|
|
79
|
+
const parent = path.resolve(cwd, toFlag || '.');
|
|
80
|
+
if (path.basename(parent) === dirName) return { parent, target: parent, nested: false };
|
|
81
|
+
return { parent, target: path.join(parent, dirName), nested: true };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const templateInitCommand = {
|
|
85
|
+
name: 'template init',
|
|
86
|
+
summary: '一条命令下载整套基础库(npm);或从网址 / 本地静态站生成一套 v2 模板(含 design/ 载图)',
|
|
87
|
+
usage:
|
|
88
|
+
'wkgeo template init [--to <父目录>] [--version <x.y.z>] [--registry npm|npmmirror] [--offline] [--force] [--json]\n' +
|
|
89
|
+
'wkgeo template init --from-url <url> --key <k> --out <目录> [--chrome <exe>]\n' +
|
|
90
|
+
'wkgeo template init --from-dir <静态站目录> --key <k> --out <目录>\n' +
|
|
91
|
+
'wkgeo template init --to . # 落到 ./_base(npm 基础库)\n' +
|
|
92
|
+
'wkgeo template init --from-url https://qibukuai.com/ --key qbk-mirror --out ./tpl',
|
|
93
|
+
args: [],
|
|
94
|
+
flags: {
|
|
95
|
+
to: { type: 'string', desc: '落到哪个**父目录**下(默认当前目录;最终目录是 <父目录>/_base)' },
|
|
96
|
+
version: { type: 'string', desc: '包版本 x.y.z(默认 dist-tags.latest;不带值的 --version 是全局「打印 CLI 版本」)' },
|
|
97
|
+
registry: { type: 'string', desc: '优先源:npm(=官方 registry.npmjs.org,默认)/ npmmirror(国内镜像);失败都自动回落另一个' },
|
|
98
|
+
offline: { type: 'boolean', desc: '只读本地缓存,不联网(没缓存就报错并贴出该访问的 URL)' },
|
|
99
|
+
force: { type: 'boolean', desc: '强制重下并覆盖已存在的目标目录;生成模式下也用它覆盖非空 --out' },
|
|
100
|
+
'from-url': { type: 'string', desc: '从网址生成模板:抓站镜像 + 反推 template.json + Chrome 载图(design/)' },
|
|
101
|
+
'from-dir': { type: 'string', desc: '从本地静态站目录生成模板:同一套 v2 口径 + 载图' },
|
|
102
|
+
key: { type: 'string', desc: '模板 key(kebab-case);目录名必须等于 key:<out> 名不同时会落到 <out>/<key>' },
|
|
103
|
+
out: { type: 'string', desc: '生成模式的目标目录(模板根)' },
|
|
104
|
+
chrome: { type: 'string', desc: 'Chrome 可执行文件路径(默认自动找本机 Chrome;也可设 WKGEO_CHROME)' },
|
|
105
|
+
'max-pages': { type: 'number', desc: 'from-url 最多抓几个页面(默认 8,含首页)' },
|
|
106
|
+
'no-design': { type: 'boolean', desc: '跳过 Chrome 载图(只给自查用;验收要求 design/,正式生成别加)' },
|
|
107
|
+
},
|
|
108
|
+
examples: [
|
|
109
|
+
'wkgeo template init',
|
|
110
|
+
'wkgeo template init --to templates',
|
|
111
|
+
'wkgeo template init --registry npmmirror',
|
|
112
|
+
'wkgeo template init --version 1.0.0 --force',
|
|
113
|
+
'wkgeo template init --offline --json',
|
|
114
|
+
'wkgeo template init --from-url https://example.com/ --key demo-site --out .tmp/demo',
|
|
115
|
+
'wkgeo template init --from-dir ./my-static-site --key my-site --out .tmp/my-site',
|
|
116
|
+
],
|
|
117
|
+
notes: [
|
|
118
|
+
`包名固定 \`${PACKAGE_NAME}\`(scoped 公开包,MIT);镜像为 registry.npmmirror.com。`,
|
|
119
|
+
'下载后会校验 `dist.integrity`(sha512),不符**立即失败并删临时文件**,不会"换个源再试试"。',
|
|
120
|
+
'解包拒绝 `..` / 绝对路径 / 盘符 / 符号链接,且只落白名单条目(assets / starter / tools + 元数据)。',
|
|
121
|
+
'缓存 `~/.wkgeo/cache/base/<version>/`;第二次 init 命中缓存不发请求,`--force` 强制重下。',
|
|
122
|
+
'`--offline` 无缓存时退出码 1,错误里会贴出该能访问的两个 registry URL 与本地缓存路径。',
|
|
123
|
+
'装完自动跑包内 `tools/check-base.mjs starter`(自检不过 = 退出码 1,目录会留着便于排查)。',
|
|
124
|
+
'小坑:`--version` **必须带值**(`--version 1.0.0`);只写 `--version` 是全局行为「打印 CLI 版本」。',
|
|
125
|
+
'生成模式(`--from-url` / `--from-dir`):抓站/读站 → `pages/*.html` + `partials/` + `assets/`(含 `assets/base/`)+ v2 `template.json`,并**必须载图**。',
|
|
126
|
+
'载图 = 本机 Chrome `--headless=new` 截 `design/desktop-1440.png` / `design/mobile-375.png`(再各出 `-t0` / `-t1500` 两帧);截图失败整体退出码 1。',
|
|
127
|
+
'生成完自动跑 9 关校验;不通过退出码 1(产物保留便于排查)。',
|
|
128
|
+
],
|
|
129
|
+
async run(ctx) {
|
|
130
|
+
if (ctx.flags.fromUrl !== undefined || ctx.flags.fromDir !== undefined) {
|
|
131
|
+
return runGenerate(ctx);
|
|
132
|
+
}
|
|
133
|
+
const { out, flags } = ctx;
|
|
134
|
+
const t0 = Date.now();
|
|
135
|
+
const log = (s) => out.line(String(s));
|
|
136
|
+
|
|
137
|
+
const cacheRoot = cacheRootOf(ctx.env || process.env);
|
|
138
|
+
const plan = registryPlan(flags.registry === undefined ? null : String(flags.registry), ctx.env || process.env);
|
|
139
|
+
const wanted = flags.version ? String(flags.version).trim() : null;
|
|
140
|
+
const offline = flags.offline === true;
|
|
141
|
+
const force = flags.force === true;
|
|
142
|
+
|
|
143
|
+
if (!out.json) {
|
|
144
|
+
out.head(`基础库模板下载(${PACKAGE_NAME})`);
|
|
145
|
+
log(` 缓存目录 ${cacheRoot}${offline ? ' · 离线模式(只读缓存)' : ''}`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
let record = null;
|
|
149
|
+
let cacheHit = false;
|
|
150
|
+
|
|
151
|
+
// ---- 1) 离线:只读缓存 ----
|
|
152
|
+
if (offline) {
|
|
153
|
+
const versions = listCachedVersions(cacheRoot);
|
|
154
|
+
const pick = wanted || readLatestPointer(cacheRoot) || versions[versions.length - 1] || null;
|
|
155
|
+
const hit = pick ? readCache(cacheRoot, pick) : null;
|
|
156
|
+
if (!hit) {
|
|
157
|
+
const urls = plan.map((r) => metadataUrl(r.base)).join('\n - ');
|
|
158
|
+
throw new CliError(
|
|
159
|
+
`离线模式没有可用缓存${wanted ? `(要 ${wanted})` : ''}:${cacheRoot} 下没有完整版本。\n` +
|
|
160
|
+
` 可用版本:${versions.length ? versions.join(', ') : '(空)'}\n` +
|
|
161
|
+
` 联网执行一次即可填充缓存:wkgeo template init${wanted ? ` --version ${wanted}` : ''}\n` +
|
|
162
|
+
` 该能访问的 registry:\n - ${urls}`,
|
|
163
|
+
{ kind: 'cache', code: 'ECACHEMISS', hint: '去掉 --offline 重跑,或换 --registry npmmirror' },
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
cacheHit = true;
|
|
167
|
+
record = { ...hit.meta, cache: { hit: true, dir: hit.dir, pkgDir: hit.pkgDir }, timings: { totalMs: 0 }, registryLabel: hit.meta.registry_base };
|
|
168
|
+
if (!out.json) log(` ✓ 命中缓存 ${pick}(${hit.counted.files} 文件 / ${fmtBytes(hit.counted.bytes)})`);
|
|
169
|
+
} else {
|
|
170
|
+
// ---- 2) 在线:先看缓存(`--version` 指定版本,或缓存里的 latest 指针)----
|
|
171
|
+
if (!force) {
|
|
172
|
+
const candidate = wanted || readLatestPointer(cacheRoot);
|
|
173
|
+
const hit = candidate ? readCache(cacheRoot, candidate) : null;
|
|
174
|
+
if (hit) {
|
|
175
|
+
cacheHit = true;
|
|
176
|
+
record = { ...hit.meta, cache: { hit: true, dir: hit.dir, pkgDir: hit.pkgDir }, timings: { totalMs: 0 }, registryLabel: hit.meta.registry_base };
|
|
177
|
+
if (!out.json) log(` ✓ 命中缓存 ${candidate}(${hit.counted.files} 文件 / ${fmtBytes(hit.counted.bytes)})· 未联网(--force 可强制重下)`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (!record) {
|
|
181
|
+
if (!out.json) log(' 正在读 registry 元数据…');
|
|
182
|
+
record = await downloadToCache({
|
|
183
|
+
fetchImpl: ctx.fetchImpl,
|
|
184
|
+
plan,
|
|
185
|
+
wanted,
|
|
186
|
+
cacheRoot,
|
|
187
|
+
timeoutMs: Number(ctx.flags.httpTimeout || 30000),
|
|
188
|
+
log: out.json ? null : log,
|
|
189
|
+
});
|
|
190
|
+
if (!out.json) {
|
|
191
|
+
log(` 来源 ${record.registryLabel} · ${record.version} · ${fmtBytes(record.size_bytes)} · ${record.file_count} 文件`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ---- 3) 落地 ----
|
|
197
|
+
const dirName = packageDirName(record.cache.pkgDir);
|
|
198
|
+
const { target } = resolveTarget(flags.to === undefined ? null : String(flags.to), dirName, process.cwd());
|
|
199
|
+
|
|
200
|
+
const existed = fs.existsSync(target) && fs.readdirSync(target).length > 0;
|
|
201
|
+
if (existed && !force) {
|
|
202
|
+
throw new CliError(`目标目录已存在且不为空:${target}`, {
|
|
203
|
+
kind: 'usage',
|
|
204
|
+
code: 'EEXIST',
|
|
205
|
+
exitCode: 2,
|
|
206
|
+
hint: '加 `--force` 覆盖,或换一个 `--to <父目录>`',
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
if (existed && force) {
|
|
210
|
+
if (!out.json) log(` 覆盖已有目录 ${target}`);
|
|
211
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
212
|
+
}
|
|
213
|
+
copyTree(record.cache.pkgDir, target);
|
|
214
|
+
|
|
215
|
+
const installed = (() => {
|
|
216
|
+
let files = 0;
|
|
217
|
+
let bytes = 0;
|
|
218
|
+
const walk = (d) => {
|
|
219
|
+
for (const it of fs.readdirSync(d, { withFileTypes: true })) {
|
|
220
|
+
const p = path.join(d, it.name);
|
|
221
|
+
if (it.isDirectory()) walk(p);
|
|
222
|
+
else if (it.isFile()) {
|
|
223
|
+
files += 1;
|
|
224
|
+
bytes += fs.statSync(p).size;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
walk(target);
|
|
229
|
+
return { files, bytes };
|
|
230
|
+
})();
|
|
231
|
+
|
|
232
|
+
// ---- 4) 自检 ----
|
|
233
|
+
const finalCheck = selfCheck(target);
|
|
234
|
+
|
|
235
|
+
const versionsFile = readJsonSafe(path.join(target, 'versions.json')) || {};
|
|
236
|
+
const versionFile = (() => {
|
|
237
|
+
try {
|
|
238
|
+
return fs.readFileSync(path.join(target, 'VERSION'), 'utf8').trim();
|
|
239
|
+
} catch {
|
|
240
|
+
return '';
|
|
241
|
+
}
|
|
242
|
+
})();
|
|
243
|
+
|
|
244
|
+
if (!out.json) {
|
|
245
|
+
if (!finalCheck.ok) {
|
|
246
|
+
out.warn(`自检未通过(${finalCheck.mode}):${finalCheck.detail}`);
|
|
247
|
+
}
|
|
248
|
+
out.ok(
|
|
249
|
+
`已安装到 ${target}(${installed.files} 文件 / ${fmtBytes(installed.bytes)})` +
|
|
250
|
+
`${cacheHit ? ' · 缓存命中' : ''}`,
|
|
251
|
+
);
|
|
252
|
+
log(` VERSION ${versionFile || '?'} · 内容版本 ${versionsFile.contentVersion || '?'} · 来自 ${record.registry_base || record.registry}`);
|
|
253
|
+
log(` 自检 ${finalCheck.mode}:${finalCheck.ok ? 'PASS' : 'FAIL'} — ${finalCheck.detail}`);
|
|
254
|
+
log(` 耗时 ${Date.now() - t0}ms`);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const payload = {
|
|
258
|
+
package: PACKAGE_NAME,
|
|
259
|
+
version: record.version,
|
|
260
|
+
content_version: versionsFile.contentVersion || null,
|
|
261
|
+
version_file: versionFile || null,
|
|
262
|
+
registry: record.registry || null,
|
|
263
|
+
registry_base: record.registry_base || record.registryLabel || null,
|
|
264
|
+
tarball: record.tarball || null,
|
|
265
|
+
integrity: record.integrity || null,
|
|
266
|
+
size_bytes: record.size_bytes || null,
|
|
267
|
+
file_count: record.file_count || null,
|
|
268
|
+
target,
|
|
269
|
+
files_written: installed.files,
|
|
270
|
+
bytes_written: installed.bytes,
|
|
271
|
+
cache_hit: cacheHit,
|
|
272
|
+
cache_dir: record.cache.dir,
|
|
273
|
+
self_check: {
|
|
274
|
+
ok: finalCheck.ok,
|
|
275
|
+
mode: finalCheck.mode,
|
|
276
|
+
detail: finalCheck.detail,
|
|
277
|
+
exit_code: finalCheck.exitCode,
|
|
278
|
+
},
|
|
279
|
+
elapsed_ms: Date.now() - t0,
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
// 自检不过:目录留着便于排查,但**退出码必须非 0**(否则"装坏了"在 CI 里看不出来)
|
|
283
|
+
if (!finalCheck.ok) {
|
|
284
|
+
throw new CliError(`安装完成但自检未通过(${finalCheck.mode}):${finalCheck.detail}`, {
|
|
285
|
+
kind: 'verify',
|
|
286
|
+
code: 'ECHECKFAIL',
|
|
287
|
+
hint: `目录已保留在 ${target},可手工跑 \`node ${path.join(target, 'tools', 'check-base.mjs')} starter\` 看明细`,
|
|
288
|
+
raw: payload,
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
ctx.done(payload);
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
// ---------------------------------------------------------------- 生成模式
|
|
297
|
+
|
|
298
|
+
function designListing(designDir, frames = true) {
|
|
299
|
+
const out = [];
|
|
300
|
+
for (const vp of DESIGN_VIEWPORTS) {
|
|
301
|
+
const names = [`${vp.name}.png`];
|
|
302
|
+
if (frames) names.push(`${vp.name}-t0.png`, `${vp.name}-t1500.png`);
|
|
303
|
+
for (const name of names) {
|
|
304
|
+
const file = path.join(designDir, name);
|
|
305
|
+
try {
|
|
306
|
+
const st = fs.statSync(file);
|
|
307
|
+
out.push({ name, path: file, bytes: st.size, width: vp.width, height: vp.height });
|
|
308
|
+
} catch {
|
|
309
|
+
out.push({ name, path: file, bytes: 0, width: vp.width, height: vp.height, missing: true });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return out;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* `template init --from-url|--from-dir`:生成一套 v2 模板 + design/ 载图 + 9 关自检。
|
|
318
|
+
* 退出码:0 成功|1 抓站/截图/校验失败|2 用法错误。
|
|
319
|
+
*/
|
|
320
|
+
async function runGenerate(ctx) {
|
|
321
|
+
const { out, flags } = ctx;
|
|
322
|
+
const fromUrlRaw = flags.fromUrl === undefined ? null : String(flags.fromUrl);
|
|
323
|
+
const fromDirRaw = flags.fromDir === undefined ? null : String(flags.fromDir);
|
|
324
|
+
if (fromUrlRaw && fromDirRaw) throw new UsageError('`--from-url` 与 `--from-dir` 只能二选一');
|
|
325
|
+
if (!flags.out) {
|
|
326
|
+
throw new UsageError('生成模式必须给 `--out <目录>`(模板根)', {
|
|
327
|
+
hint: '例:wkgeo template init --from-url https://qibukuai.com/ --key qbk-mirror --out ./tpl',
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
const outAbs = path.resolve(process.cwd(), String(flags.out));
|
|
331
|
+
const key = slugify(flags.key ? String(flags.key) : path.basename(outAbs));
|
|
332
|
+
if (!/^[a-z0-9][a-z0-9-]{1,60}$/.test(key)) {
|
|
333
|
+
throw new UsageError(`模板 key 不合法:${JSON.stringify(key)}`, { hint: 'kebab-case:小写字母/数字/-,2–61 字符' });
|
|
334
|
+
}
|
|
335
|
+
// key 必须等于目录名(§3 约定):<out> 名不是 key 就落到 <out>/<key>
|
|
336
|
+
const target = path.basename(outAbs) === key ? outAbs : path.join(outAbs, key);
|
|
337
|
+
const doCapture = flags.noDesign !== true;
|
|
338
|
+
const chromeExe = flags.chrome ? String(flags.chrome) : null;
|
|
339
|
+
if (doCapture) resolveChrome(chromeExe); // 截图链路有问题要在**写文件之前**失败
|
|
340
|
+
|
|
341
|
+
const siteUrl = fromUrlRaw ? normalizeSiteUrl(fromUrlRaw).href : null;
|
|
342
|
+
const srcDir = fromDirRaw ? path.resolve(process.cwd(), fromDirRaw) : null;
|
|
343
|
+
if (srcDir && !fs.existsSync(srcDir)) throw new UsageError(`--from-dir 目录不存在:${srcDir}`);
|
|
344
|
+
|
|
345
|
+
const t0 = Date.now();
|
|
346
|
+
await prepareOutDir(target, { force: flags.force === true });
|
|
347
|
+
|
|
348
|
+
const logLine = (s) => {
|
|
349
|
+
if (!out.json) out.line(` ${s}`);
|
|
350
|
+
};
|
|
351
|
+
if (!out.json) {
|
|
352
|
+
out.head(`生成模板 ${key}${siteUrl ? ` ← ${siteUrl}` : ` ← ${srcDir}`}`);
|
|
353
|
+
out.line(` 目标目录 ${target}${doCapture ? '(含 Chrome 载图)' : '(--no-design:跳过载图)'}`);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
let warnings = [];
|
|
357
|
+
try {
|
|
358
|
+
const res = siteUrl
|
|
359
|
+
? await generateFromUrl({
|
|
360
|
+
url: siteUrl,
|
|
361
|
+
outDir: target,
|
|
362
|
+
key,
|
|
363
|
+
fetchImpl: ctx.fetchImpl,
|
|
364
|
+
timeoutMs: Number(flags.httpTimeout || 30000),
|
|
365
|
+
maxPages: Number(flags.maxPages || 8),
|
|
366
|
+
capture: doCapture,
|
|
367
|
+
chromeExe,
|
|
368
|
+
logLine,
|
|
369
|
+
})
|
|
370
|
+
: await generateFromDir({ srcDir, outDir: target, key, capture: doCapture, chromeExe, logLine });
|
|
371
|
+
warnings = (res && res.warnings) || [];
|
|
372
|
+
} catch (e) {
|
|
373
|
+
if (e instanceof CliError) throw e;
|
|
374
|
+
throw new CliError(`生成失败:${e && e.message ? e.message : e}`, {
|
|
375
|
+
kind: 'generate',
|
|
376
|
+
code: 'EGENERATE',
|
|
377
|
+
exitCode: EXIT.ERROR,
|
|
378
|
+
cause: e,
|
|
379
|
+
hint: `已写入的文件保留在 ${target},便于排查`,
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
const manifest = readJsonSafe(path.join(target, 'template.json')) || {};
|
|
384
|
+
const pagesDir = path.join(target, 'pages');
|
|
385
|
+
const pages = fs.existsSync(pagesDir)
|
|
386
|
+
? fs.readdirSync(pagesDir).filter((f) => f.endsWith('.html')).sort()
|
|
387
|
+
: [];
|
|
388
|
+
const designDir = path.join(target, 'design');
|
|
389
|
+
const design = designListing(designDir, doCapture);
|
|
390
|
+
const validation = await validateTemplate({ dir: target, cwd: process.cwd() });
|
|
391
|
+
|
|
392
|
+
if (!out.json) {
|
|
393
|
+
if (warnings.length) {
|
|
394
|
+
out.warn(`抓站告警 ${warnings.length} 条:`);
|
|
395
|
+
for (const w of warnings.slice(0, 8)) out.line(` ! ${w}`);
|
|
396
|
+
}
|
|
397
|
+
out.ok(
|
|
398
|
+
`已生成 ${target}:页面 ${pages.length} · 栏目 ${(manifest.columns || []).length} · ` +
|
|
399
|
+
`菜单 ${(manifest.menus && manifest.menus.top ? manifest.menus.top : []).length} · ` +
|
|
400
|
+
`设计图 ${design.filter((d) => !d.missing).length}/${design.length}`,
|
|
401
|
+
);
|
|
402
|
+
for (const d of design) {
|
|
403
|
+
out.line(` ${d.missing ? '✗' : '✓'} design/${d.name}${d.missing ? '(缺)' : ` · ${d.width}x${d.height} · ${fmtBytes(d.bytes)}`}`);
|
|
404
|
+
}
|
|
405
|
+
out.line(` 9 关校验 ${validation.ok ? 'PASS(9/9)' : `FAIL(${validation.summary.failed} 关不过)`}`);
|
|
406
|
+
for (const c of validation.checks) {
|
|
407
|
+
if (!c.ok) out.line(` ✗ ${c.id} ${c.title}: ${c.errors.slice(0, 3).join(';')}`);
|
|
408
|
+
}
|
|
409
|
+
out.line(` 耗时 ${Date.now() - t0}ms`);
|
|
410
|
+
if (validation.ok) out.line(` 下一步:wkgeo template verify --dir ${target}`);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const payload = {
|
|
414
|
+
mode: siteUrl ? 'url' : 'dir',
|
|
415
|
+
key,
|
|
416
|
+
dir: target,
|
|
417
|
+
source: siteUrl || srcDir,
|
|
418
|
+
title: manifest.name || null,
|
|
419
|
+
pages,
|
|
420
|
+
page_count: pages.length,
|
|
421
|
+
columns: (manifest.columns || []).map((c) => ({ key: c.key, name: c.name, page: c.page, items: (c.items || []).length })),
|
|
422
|
+
column_count: (manifest.columns || []).length,
|
|
423
|
+
menus: {
|
|
424
|
+
top: (manifest.menus && manifest.menus.top ? manifest.menus.top : []).map((m) => m.label),
|
|
425
|
+
footer: (manifest.menus && manifest.menus.footer ? manifest.menus.footer : []).map((m) => m.label),
|
|
426
|
+
},
|
|
427
|
+
design: design.map((d) => ({ name: d.name, path: d.path, bytes: d.bytes, missing: !!d.missing })),
|
|
428
|
+
design_count: design.filter((d) => !d.missing).length,
|
|
429
|
+
validation: { ok: validation.ok, failed: validation.summary.failed, checks: validation.checks.map((c) => ({ id: c.id, ok: c.ok, errors: c.errors })) },
|
|
430
|
+
warnings,
|
|
431
|
+
elapsed_ms: Date.now() - t0,
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
if (!validation.ok) {
|
|
435
|
+
const bad = validation.checks.filter((c) => !c.ok).map((c) => c.id);
|
|
436
|
+
throw new CliError(`模板已生成但 9 关校验未通过(${bad.join(', ')})`, {
|
|
437
|
+
kind: 'verify',
|
|
438
|
+
code: 'EVALIDATE',
|
|
439
|
+
exitCode: EXIT.ERROR,
|
|
440
|
+
hint: `产物保留在 ${target};` +
|
|
441
|
+
(design.some((d) => d.missing) ? '缺 design 图时先跑 `wkgeo template capture`;' : '') +
|
|
442
|
+
'逐关明细见 --json 的 validation.checks',
|
|
443
|
+
raw: payload,
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
ctx.done(payload);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// ---------------------------------------------------------------- template capture
|
|
450
|
+
|
|
451
|
+
export const templateCaptureCommand = {
|
|
452
|
+
name: 'template capture',
|
|
453
|
+
summary: '只载图:起本地静态服务(或直接给网址)→ 本机 Chrome 截图到 design/(主帧 + t0/t1500 两帧)',
|
|
454
|
+
usage:
|
|
455
|
+
'wkgeo template capture --dir <模板目录> [--page /pages/index.html] [--out <目录>] [--chrome <exe>] [--no-frames] [--json]\n' +
|
|
456
|
+
'wkgeo template capture --url <https://站点> --out <目录>',
|
|
457
|
+
args: [],
|
|
458
|
+
flags: {
|
|
459
|
+
dir: { type: 'string', desc: '模板目录(起 node 静态服务,页面从 pages/ 取)' },
|
|
460
|
+
url: { type: 'string', desc: '直接截线上站点(与 --dir 二选一)' },
|
|
461
|
+
page: { type: 'string', desc: '站内页面路径(默认 --dir 时 /pages/index.html,--url 时 /)' },
|
|
462
|
+
out: { type: 'string', desc: '截图目录(默认 <模板目录>/design)' },
|
|
463
|
+
chrome: { type: 'string', desc: 'Chrome 可执行文件(默认自动找;也可设 WKGEO_CHROME)' },
|
|
464
|
+
'no-frames': { type: 'boolean', desc: '只截主帧,不截 -t0 / -t1500 动画两帧' },
|
|
465
|
+
},
|
|
466
|
+
examples: [
|
|
467
|
+
'wkgeo template capture --dir ./tpl/qbk-mirror',
|
|
468
|
+
'wkgeo template capture --dir ./tpl/qbk-mirror --page /pages/about.html --no-frames',
|
|
469
|
+
'wkgeo template capture --url https://qibukuai.com/ --out .tmp-build/t142/cap',
|
|
470
|
+
],
|
|
471
|
+
notes: [
|
|
472
|
+
'主帧用 `--headless=new --virtual-time-budget=4000`(**与 tools/render-compare 完全同口径**,否则自比一致率没意义)。',
|
|
473
|
+
't0 / t1500 用 CDP 真实时间抓(load 后约 120ms 与 1500ms),用来出动画清单;用虚拟时间抓两帧会一模一样。',
|
|
474
|
+
'截图失败(找不到 Chrome / 超时 / 没产物)一律退出码 1 并给中文原因;不会写半套 design/。',
|
|
475
|
+
],
|
|
476
|
+
async run(ctx) {
|
|
477
|
+
const { out, flags } = ctx;
|
|
478
|
+
const dirFlag = flags.dir ? path.resolve(process.cwd(), String(flags.dir)) : null;
|
|
479
|
+
const urlFlag = flags.url ? normalizeSiteUrl(String(flags.url)).href : null;
|
|
480
|
+
if (!dirFlag && !urlFlag) throw new UsageError('要给 `--dir <模板目录>` 或 `--url <网址>`');
|
|
481
|
+
if (dirFlag && urlFlag) throw new UsageError('`--dir` 与 `--url` 只能二选一');
|
|
482
|
+
if (dirFlag && !fs.existsSync(dirFlag)) throw new UsageError(`模板目录不存在:${dirFlag}`);
|
|
483
|
+
const frames = flags.noFrames !== true;
|
|
484
|
+
const page = String(flags.page || (dirFlag ? '/pages/index.html' : '/'));
|
|
485
|
+
const designDir = flags.out ? path.resolve(process.cwd(), String(flags.out)) : path.join(dirFlag || process.cwd(), 'design');
|
|
486
|
+
const chromeExe = resolveChrome(flags.chrome ? String(flags.chrome) : null);
|
|
487
|
+
const t0 = Date.now();
|
|
488
|
+
|
|
489
|
+
let server = null;
|
|
490
|
+
try {
|
|
491
|
+
const baseUrl = dirFlag ? (server = await startStaticServer(dirFlag)).url : urlFlag;
|
|
492
|
+
const url = baseUrl.replace(/\/+$/, '') + (page.startsWith('/') ? page : `/${page}`);
|
|
493
|
+
if (!out.json) {
|
|
494
|
+
out.head(`载图 ${url}`);
|
|
495
|
+
out.line(` Chrome ${chromeExe}`);
|
|
496
|
+
out.line(` 输出 ${designDir}(主帧 ×${DESIGN_VIEWPORTS.length}${frames ? ' + 动画两帧' : ''})`);
|
|
497
|
+
}
|
|
498
|
+
await captureDesign({
|
|
499
|
+
url,
|
|
500
|
+
dir: designDir,
|
|
501
|
+
frames,
|
|
502
|
+
chromeExe,
|
|
503
|
+
// 只有 `--dir` 时模板源码就在本地,才能顺手抽动画清单/几何证据;`--url` 拍的是原站,没有源码可抽
|
|
504
|
+
templateDir: dirFlag,
|
|
505
|
+
page: dirFlag ? page : undefined,
|
|
506
|
+
onProgress: (s) => {
|
|
507
|
+
if (!out.json) out.line(` ${s}`);
|
|
508
|
+
},
|
|
509
|
+
});
|
|
510
|
+
const files = designListing(designDir, frames);
|
|
511
|
+
const missing = files.filter((f) => f.missing);
|
|
512
|
+
if (missing.length) {
|
|
513
|
+
throw new CliError(`载图不完整,缺 ${missing.map((m) => m.name).join(', ')}`, {
|
|
514
|
+
kind: 'capture',
|
|
515
|
+
code: 'ECAPTURE',
|
|
516
|
+
exitCode: EXIT.ERROR,
|
|
517
|
+
hint: `Chrome 没吐出这些文件:${designDir}`,
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
if (!out.json) {
|
|
521
|
+
for (const f of files) out.line(` ✓ design/${f.name} · ${f.width}x${f.height} · ${fmtBytes(f.bytes)}`);
|
|
522
|
+
out.ok(`载图完成:${files.length} 张 / 耗时 ${Date.now() - t0}ms`);
|
|
523
|
+
}
|
|
524
|
+
ctx.done({
|
|
525
|
+
url,
|
|
526
|
+
design: files.map((f) => ({ name: f.name, path: f.path, bytes: f.bytes, width: f.width, height: f.height })),
|
|
527
|
+
count: files.length,
|
|
528
|
+
frames,
|
|
529
|
+
chrome: chromeExe,
|
|
530
|
+
elapsed_ms: Date.now() - t0,
|
|
531
|
+
});
|
|
532
|
+
} finally {
|
|
533
|
+
if (server) server.close();
|
|
534
|
+
}
|
|
535
|
+
},
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
// ---------------------------------------------------------------- template verify
|
|
539
|
+
|
|
540
|
+
function printVerifyReport(out, r) {
|
|
541
|
+
out.head(`自比 ${r.dir}`);
|
|
542
|
+
out.line(` 设计图 ${r.design} · 页面 ${r.page} · 阈值 ${r.threshold}`);
|
|
543
|
+
for (const v of r.viewports) {
|
|
544
|
+
out.line(
|
|
545
|
+
` ${v.pass ? '✓' : '✗'} ${v.name}(${v.width}x${v.height})一致率 ${(v.ratio * 100).toFixed(2)}% · ` +
|
|
546
|
+
`差异 ${v.mismatch}/${v.total} 像素`,
|
|
547
|
+
);
|
|
548
|
+
if (v.diffPath) out.line(` 差异图 ${v.diffPath}`);
|
|
549
|
+
if (v.renderPath) out.line(` 实拍图 ${v.renderPath}`);
|
|
550
|
+
}
|
|
551
|
+
const anims = r.animations || [];
|
|
552
|
+
if (anims.length) {
|
|
553
|
+
const total = anims.reduce((n, a) => n + a.regions.length, 0);
|
|
554
|
+
out.line(` 动画清单(-t0 vs -t1500,共 ${total} 处):`);
|
|
555
|
+
for (const a of anims) {
|
|
556
|
+
for (const g of a.regions) {
|
|
557
|
+
out.line(` · ${a.viewport} 区域 (${g.x},${g.y}) ${g.w}×${g.h} · 热格 ${g.cells} · 该视口变化 ${(a.changedRatio * 100).toFixed(2)}%`);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
} else {
|
|
561
|
+
out.line(' 动画清单:两帧无差异(首屏无时间型动画)');
|
|
562
|
+
}
|
|
563
|
+
if (r.animationNote) out.line(` 说明 ${r.animationNote}`);
|
|
564
|
+
|
|
565
|
+
// 动画对账:期望(清单)vs 实测(模板渲染页两帧)
|
|
566
|
+
const rc = r.reconcile;
|
|
567
|
+
if (rc) {
|
|
568
|
+
const head = rc.ok ? '✓' : '✗';
|
|
569
|
+
out.line(
|
|
570
|
+
` ${head} 动画对账(${rc.attribution === 'geom' ? '几何归因' : rc.attribution === 'none' ? '跳过' : '按数量比'}):` +
|
|
571
|
+
`期望 ${rc.expected} 处 · 命中 ${rc.matched} 处 · 缺失 ${rc.missing.length} 处 · 多余 ${rc.extra.length} 处`
|
|
572
|
+
);
|
|
573
|
+
for (const b of rc.byViewport || []) {
|
|
574
|
+
if (b.countMode) continue;
|
|
575
|
+
out.line(` · ${b.viewport} 实测区域 ${b.observed} 处 / 命中 ${b.matched} 处`);
|
|
576
|
+
}
|
|
577
|
+
for (const m of rc.missing) out.line(` ✗ 缺失 ${m.id} · ${m.kind} · ${m.selector}`);
|
|
578
|
+
for (const x of rc.extra) out.line(` ✗ 多余 ${x.viewport} ${x.region}`);
|
|
579
|
+
for (const u of rc.unmapped || []) out.line(` ! 未映射 ${u.id} · ${u.selector} · ${u.reason}`);
|
|
580
|
+
if (rc.note) out.line(` 说明 ${rc.note}`);
|
|
581
|
+
} else if (r.animCheck === false) {
|
|
582
|
+
out.line(' 动画对账:已用 --no-anim 关闭');
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
export const templateVerifyCommand = {
|
|
587
|
+
name: 'template verify',
|
|
588
|
+
summary: '自比门禁:起本地静态服务 → Chrome 截图 → 与 design/ 逐像素比对(桌面/移动一致率都必须 ≥95%)+ 动画清单',
|
|
589
|
+
usage:
|
|
590
|
+
'wkgeo template verify --dir <模板目录> [--design <design 目录>] [--page /pages/index.html] [--threshold 0.95]\n' +
|
|
591
|
+
' [--tolerance 12] [--out <报告目录>] [--chrome <exe>] [--json]',
|
|
592
|
+
args: [],
|
|
593
|
+
flags: {
|
|
594
|
+
dir: { type: 'string', desc: '模板目录(含 template.json + pages/ + design/)' },
|
|
595
|
+
design: { type: 'string', desc: 'design 目录(默认 <dir>/design)' },
|
|
596
|
+
page: { type: 'string', desc: '要比的页面路径(默认 /pages/index.html)' },
|
|
597
|
+
threshold: { type: 'number', desc: '一致率下限(默认 0.95;低于它退出码 1)' },
|
|
598
|
+
tolerance: { type: 'number', desc: '单通道色差容忍(默认 12,同 render-compare)' },
|
|
599
|
+
out: { type: 'string', desc: '报告 / 差异图输出目录(默认 .wkgeo-verify/<模板>-<时间戳>)' },
|
|
600
|
+
chrome: { type: 'string', desc: 'Chrome 可执行文件(默认自动找)' },
|
|
601
|
+
compare: { type: 'string', desc: '像素比对脚本(默认 tools/render-compare/compare.mjs;找不到就 exit 2)' },
|
|
602
|
+
'no-anim': { type: 'boolean', desc: '只比像素,不做动画对账(不额外起 Chrome 量 t0/t1500)' },
|
|
603
|
+
},
|
|
604
|
+
examples: [
|
|
605
|
+
'wkgeo template verify --dir ./tpl/qbk-mirror',
|
|
606
|
+
'wkgeo template verify --dir ./tpl/qbk-mirror --threshold 0.99 --out .tmp-build/t142/verify',
|
|
607
|
+
'wkgeo template verify --dir ./tpl/demo --json',
|
|
608
|
+
],
|
|
609
|
+
notes: [
|
|
610
|
+
'比对**不另写一套**:spawn `node tools/render-compare/compare.mjs`(task-45 产物)并读它的 report.json。',
|
|
611
|
+
'找不到 compare.mjs → 退出码 2(环境缺失,不是模板不合格)。',
|
|
612
|
+
'两个视口各跑一次(1440x900 / 375x812);任一 <95% → 退出码 1 并打印差异图路径。',
|
|
613
|
+
'动画清单 = design/<视口>-t0.png 与 -t1500.png 的差异聚类(16px 网格 + 连通域),无差异就如实报 0 处。',
|
|
614
|
+
],
|
|
615
|
+
async run(ctx) {
|
|
616
|
+
const { out, flags } = ctx;
|
|
617
|
+
const dir = path.resolve(process.cwd(), String(flags.dir || '.'));
|
|
618
|
+
if (!fs.existsSync(dir)) throw new UsageError(`模板目录不存在:${dir}`);
|
|
619
|
+
const designDir = flags.design ? path.resolve(process.cwd(), String(flags.design)) : path.join(dir, 'design');
|
|
620
|
+
const opts = {
|
|
621
|
+
dir,
|
|
622
|
+
designDir,
|
|
623
|
+
page: flags.page ? String(flags.page) : '/pages/index.html',
|
|
624
|
+
threshold: flags.threshold === undefined ? 0.95 : Number(flags.threshold),
|
|
625
|
+
tolerance: flags.tolerance === undefined ? 12 : Number(flags.tolerance),
|
|
626
|
+
outDir: flags.out ? path.resolve(process.cwd(), String(flags.out)) : null,
|
|
627
|
+
chromeExe: flags.chrome ? String(flags.chrome) : null,
|
|
628
|
+
compareScript: flags.compare ? path.resolve(process.cwd(), String(flags.compare)) : null,
|
|
629
|
+
animCheck: flags.noAnim !== true,
|
|
630
|
+
onProgress: (s) => {
|
|
631
|
+
if (!out.json) out.line(` ${s}`);
|
|
632
|
+
},
|
|
633
|
+
};
|
|
634
|
+
let result;
|
|
635
|
+
try {
|
|
636
|
+
result = await verifyTemplate(opts);
|
|
637
|
+
} catch (e) {
|
|
638
|
+
if (e && e.payload && e.payload.viewports) {
|
|
639
|
+
printVerifyReport(out, e.payload);
|
|
640
|
+
if (!out.json) {
|
|
641
|
+
const why = e.code === 'EANIM' ? '动画对账不通过' : `自比未达标(阈值 ${e.payload.threshold})`;
|
|
642
|
+
out.err(`${why} → 退出码 1`);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
throw e;
|
|
646
|
+
}
|
|
647
|
+
printVerifyReport(out, result);
|
|
648
|
+
if (!out.json) out.ok(`自比通过:桌面 ${(result.viewports[0].ratio * 100).toFixed(2)}% · 移动 ${(result.viewports[1].ratio * 100).toFixed(2)}%`);
|
|
649
|
+
ctx.done(result);
|
|
650
|
+
},
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
// ---------------------------------------------------------------- template anim
|
|
654
|
+
|
|
655
|
+
export const templateAnimCommand = {
|
|
656
|
+
name: 'template anim',
|
|
657
|
+
summary: '抽取模板动画(@keyframes / animation / transition / 滚动入场)→ 映射 _base 动效词汇 → 写 design/animations.json',
|
|
658
|
+
usage: 'wkgeo template anim --dir <模板目录> [--page /pages/index.html] [--no-write] [--json]',
|
|
659
|
+
args: [],
|
|
660
|
+
flags: {
|
|
661
|
+
dir: { type: 'string', desc: '模板目录(读 pages/ + assets/ 里的 HTML/CSS/JS)' },
|
|
662
|
+
page: { type: 'string', desc: '主页面路径(默认 /pages/index.html;只影响清单里的 page 字段与内联源)' },
|
|
663
|
+
'no-write': { type: 'boolean', desc: '只打印,不写 design/animations.json' },
|
|
664
|
+
},
|
|
665
|
+
examples: [
|
|
666
|
+
'wkgeo template anim --dir ./tpl/qbk-mirror',
|
|
667
|
+
'wkgeo template anim --dir ./tpl/demo --json',
|
|
668
|
+
'wkgeo template anim --dir ./tpl/demo --no-write',
|
|
669
|
+
],
|
|
670
|
+
notes: [
|
|
671
|
+
'抽四类:`@keyframes` 循环/一次性、`animation` 简写、`transition`(hover 态)、滚动入场(IntersectionObserver / `data-reveal` / class 切换)。',
|
|
672
|
+
'每条动画映射到 `_base` 现成类名/属性(`.anim-float` / `.anim-pulse` / `.anim-gradient` / `.anim-shine` / `.marquee` / `[data-reveal]` / `[data-parallax]`),不造新体系;映射不了标 `unmapped` 并写明中文原因。',
|
|
673
|
+
'清单写 `<dir>/design/animations.json`(`_format: wkgeo-anim@1`),随包分发;`verify` 用它和实测两帧对账。',
|
|
674
|
+
],
|
|
675
|
+
async run(ctx) {
|
|
676
|
+
const { out, flags } = ctx;
|
|
677
|
+
const dir = path.resolve(process.cwd(), String(flags.dir || '.'));
|
|
678
|
+
if (!fs.existsSync(dir)) throw new UsageError(`模板目录不存在:${dir}`);
|
|
679
|
+
const page = flags.page ? String(flags.page) : '/pages/index.html';
|
|
680
|
+
const { manifest, files } = await extractAnimationsFromDir({ dir, page });
|
|
681
|
+
const designDir = path.join(dir, 'design');
|
|
682
|
+
let written = null;
|
|
683
|
+
if (flags.noWrite !== true) written = await writeAnimationManifest(designDir, manifest);
|
|
684
|
+
|
|
685
|
+
if (!out.json) {
|
|
686
|
+
const c = manifest.counts;
|
|
687
|
+
out.head(`动画清单 ${dir}`);
|
|
688
|
+
out.line(` 源 ${files.css.length} 个 CSS / ${files.js.length} 个 JS / ${files.html.length} 个 HTML · @keyframes ${c.keyframes} 组`);
|
|
689
|
+
out.line(
|
|
690
|
+
` 动画 ${c.total} 处:load ${c.load} · scroll ${c.scroll} · hover ${c.hover} · 首屏预期 ${c.expectInWindow} 处 · ` +
|
|
691
|
+
`映射 exact ${c.exact} / alias ${c.alias} / 未映射 ${c.unmapped}`
|
|
692
|
+
);
|
|
693
|
+
if (!c.total) {
|
|
694
|
+
out.line(' 此站无动画:源码里没有 @keyframes、没有 animation/transition 声明、也没有滚动入场脚本');
|
|
695
|
+
}
|
|
696
|
+
for (const a of manifest.animations) {
|
|
697
|
+
const t = a.timing || {};
|
|
698
|
+
const dur = t.durationMs ? `${t.durationMs}ms` : '-';
|
|
699
|
+
const dl = t.delayMs ? `+${t.delayMs}ms` : '';
|
|
700
|
+
const target = a.base ? a.base.class || (a.base.attrs ? JSON.stringify(a.base.attrs) : a.base.keyframes || 'base') : '—';
|
|
701
|
+
out.line(
|
|
702
|
+
` ${a.map.status === 'unmapped' ? '!' : '✓'} ${a.id} ${a.kind.padEnd(9)} ${String(a.trigger).padEnd(6)} ` +
|
|
703
|
+
`${dur}${dl} ${a.selector} → ${target}`
|
|
704
|
+
);
|
|
705
|
+
if (a.map.status === 'unmapped' && a.map.reason) out.line(` ! ${a.map.reason}`);
|
|
706
|
+
}
|
|
707
|
+
if (written) out.ok(`清单已写入 ${path.relative(process.cwd(), written) || written}(${ANIM_MANIFEST_FILE})`);
|
|
708
|
+
else out.line(' (--no-write,未落盘)');
|
|
709
|
+
}
|
|
710
|
+
ctx.done({
|
|
711
|
+
dir,
|
|
712
|
+
page,
|
|
713
|
+
manifest,
|
|
714
|
+
file: written,
|
|
715
|
+
files,
|
|
716
|
+
counts: manifest.counts,
|
|
717
|
+
warnings: manifest.warnings,
|
|
718
|
+
});
|
|
719
|
+
},
|
|
720
|
+
};
|
|
721
|
+
|
|
722
|
+
// ---------------------------------------------------------------- template validate
|
|
723
|
+
|
|
724
|
+
export const templateValidateCommand = {
|
|
725
|
+
name: 'template validate',
|
|
726
|
+
summary: '单独校验模板目录(9 关:清单/格式/site/菜单/栏目/页面/基础库/资源/设计图),exit 非 0 = 不合格',
|
|
727
|
+
usage: 'wkgeo template validate --dir <模板目录> [--base <_base 目录>] [--no-design] [--json]',
|
|
728
|
+
args: [],
|
|
729
|
+
flags: {
|
|
730
|
+
dir: { type: 'string', desc: '模板目录' },
|
|
731
|
+
base: { type: 'string', desc: '_base 目录(默认自动找 templates/_base;用于 assets/base 逐字节比对)' },
|
|
732
|
+
'no-design': { type: 'boolean', desc: '不要求 design/ 截图(只适合自查,pack 仍会要求)' },
|
|
733
|
+
},
|
|
734
|
+
examples: ['wkgeo template validate --dir ./tpl/qbk-mirror', 'wkgeo template validate --dir ./tpl/demo --json'],
|
|
735
|
+
notes: [
|
|
736
|
+
'9 关:manifest / format / site / menus / columns / pages / base / links / design。',
|
|
737
|
+
'合格 exit 0;任何一关 error → exit 1(并逐条打印);参数错 → exit 2。',
|
|
738
|
+
],
|
|
739
|
+
async run(ctx) {
|
|
740
|
+
const { out, flags } = ctx;
|
|
741
|
+
const dir = path.resolve(process.cwd(), String(flags.dir || '.'));
|
|
742
|
+
if (!fs.existsSync(dir)) throw new UsageError(`模板目录不存在:${dir}`);
|
|
743
|
+
const result = await validateTemplate({
|
|
744
|
+
dir,
|
|
745
|
+
base: flags.base ? path.resolve(process.cwd(), String(flags.base)) : null,
|
|
746
|
+
cwd: process.cwd(),
|
|
747
|
+
requireDesign: flags.noDesign !== true,
|
|
748
|
+
});
|
|
749
|
+
if (!out.json) {
|
|
750
|
+
out.head(`校验 ${result.dir}`);
|
|
751
|
+
for (const c of result.checks) {
|
|
752
|
+
out.line(` ${c.ok ? '✓' : '✗'} ${c.id.padEnd(8)} ${c.title}`);
|
|
753
|
+
for (const e of c.errors.slice(0, 6)) out.line(` ✗ ${e}`);
|
|
754
|
+
for (const w of c.warnings.slice(0, 6)) out.line(` ! ${w}`);
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
if (!result.ok) {
|
|
758
|
+
const bad = result.checks.filter((c) => !c.ok).map((c) => c.id);
|
|
759
|
+
throw new CliError(`校验未通过:${bad.join(', ')}(${result.summary.failed} 关)`, {
|
|
760
|
+
kind: 'validate',
|
|
761
|
+
code: 'EVALIDATE',
|
|
762
|
+
exitCode: EXIT.ERROR,
|
|
763
|
+
hint: '按上面逐关明细改;`--json` 里有完整 checks',
|
|
764
|
+
raw: result,
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
if (!out.json) out.ok(`校验通过(9/9)· ${result.dir}`);
|
|
768
|
+
ctx.done(result);
|
|
769
|
+
},
|
|
770
|
+
};
|
|
771
|
+
|
|
772
|
+
// ---------------------------------------------------------------- template pack
|
|
773
|
+
|
|
774
|
+
export const templatePackCommand = {
|
|
775
|
+
name: 'template pack',
|
|
776
|
+
summary: '打可分发的 zip:同步 _base → assets/base/、design/ 入包、9 关校验不过就不出包',
|
|
777
|
+
usage: 'wkgeo template pack --dir <模板目录> [--out <zip>] [--base <_base 目录>] [--json]',
|
|
778
|
+
args: [],
|
|
779
|
+
flags: {
|
|
780
|
+
dir: { type: 'string', desc: '模板目录(默认当前目录)' },
|
|
781
|
+
out: { type: 'string', desc: 'zip 路径(默认 <key>-<version>.zip)' },
|
|
782
|
+
base: { type: 'string', desc: '_base 目录(默认自动找)' },
|
|
783
|
+
},
|
|
784
|
+
examples: ['wkgeo template pack --dir ./tpl/qbk-mirror', 'wkgeo template pack --dir ./tpl/qbk-mirror --out .tmp-build/t142/qbk.zip'],
|
|
785
|
+
notes: [
|
|
786
|
+
'打包前把 `templates/_base/assets/**` 逐字节同步到 `<模板>/assets/base/`(§3 约定,validate/pack 都查)。',
|
|
787
|
+
'zip 内必有:template.json、pages/、partials/、assets/(含 assets/base/base.css)、design/*.png。',
|
|
788
|
+
'zip 自己写(zlib deflateRaw + 自算 CRC32):不 npm install、不依赖外部 archiver。',
|
|
789
|
+
],
|
|
790
|
+
async run(ctx) {
|
|
791
|
+
const { out, flags } = ctx;
|
|
792
|
+
const dir = path.resolve(process.cwd(), String(flags.dir || '.'));
|
|
793
|
+
if (!fs.existsSync(dir)) throw new UsageError(`模板目录不存在:${dir}`);
|
|
794
|
+
const res = await packTemplate({
|
|
795
|
+
dir,
|
|
796
|
+
out: flags.out ? String(flags.out) : null,
|
|
797
|
+
base: flags.base ? String(flags.base) : null,
|
|
798
|
+
cwd: process.cwd(),
|
|
799
|
+
onProgress: (s) => {
|
|
800
|
+
if (!out.json) out.line(` ${s}`);
|
|
801
|
+
},
|
|
802
|
+
});
|
|
803
|
+
if (!out.json) {
|
|
804
|
+
out.ok(`已打包 ${res.zip}(${res.count} 文件 / ${fmtBytes(res.bytes)})`);
|
|
805
|
+
out.line(' 必需条目 ✓ template.json ✓ pages/index.html ✓ assets/base/base.css ✓ design/*.png');
|
|
806
|
+
const groups = new Map();
|
|
807
|
+
for (const n of res.files) {
|
|
808
|
+
const top = n.includes('/') ? n.split('/')[0] : '(根)';
|
|
809
|
+
groups.set(top, (groups.get(top) || 0) + 1);
|
|
810
|
+
}
|
|
811
|
+
out.line(` 内容 ${[...groups.entries()].map(([k, v]) => `${k}:${v}`).join(' · ')}`);
|
|
812
|
+
}
|
|
813
|
+
ctx.done({ zip: res.zip, bytes: res.bytes, count: res.count, files: res.files, base_sync: res.baseSync });
|
|
814
|
+
},
|
|
815
|
+
};
|
|
816
|
+
|
|
817
|
+
// ---------------------------------------------------------------- template preview
|
|
818
|
+
|
|
819
|
+
export const templatePreviewCommand = {
|
|
820
|
+
name: 'template preview',
|
|
821
|
+
summary: '本地起静态服务预览模板(默认随机端口;--timeout 到点自动退,便于脚本自测)',
|
|
822
|
+
usage: 'wkgeo template preview --dir <模板目录|模板根> [--port 8080] [--page /pages/index.html] [--timeout 秒] [--json]',
|
|
823
|
+
args: [],
|
|
824
|
+
flags: {
|
|
825
|
+
dir: { type: 'string', desc: '要服务的根目录(模板目录 = 能直接访问 /pages/index.html)' },
|
|
826
|
+
port: { type: 'number', desc: '端口(默认 0 = 随机空闲端口)' },
|
|
827
|
+
page: { type: 'string', desc: '打印的入口页面(默认 /pages/index.html)' },
|
|
828
|
+
timeout: { type: 'number', desc: 'N 秒后自动关闭(不写则一直服务到 Ctrl+C)' },
|
|
829
|
+
},
|
|
830
|
+
examples: ['wkgeo template preview --dir ./tpl/qbk-mirror', 'wkgeo template preview --dir ./tpl/qbk-mirror --port 8099 --timeout 30'],
|
|
831
|
+
notes: [
|
|
832
|
+
'服务就是 `template capture` / `verify` 用的同一个 node:http 静态服务(拒绝 .. 越界、no-store)。',
|
|
833
|
+
'`--json` 会先吐一行 URL 信封再开始服务,方便脚本抓地址。',
|
|
834
|
+
],
|
|
835
|
+
async run(ctx) {
|
|
836
|
+
const { out, flags } = ctx;
|
|
837
|
+
const dir = path.resolve(process.cwd(), String(flags.dir || '.'));
|
|
838
|
+
if (!fs.existsSync(dir)) throw new UsageError(`目录不存在:${dir}`);
|
|
839
|
+
const page = String(flags.page || '/pages/index.html');
|
|
840
|
+
const server = await startStaticServer(dir, { port: flags.port === undefined ? 0 : Number(flags.port) });
|
|
841
|
+
const url = server.url.replace(/\/+$/, '') + (page.startsWith('/') ? page : `/${page}`);
|
|
842
|
+
if (!out.json) {
|
|
843
|
+
out.head(`预览 ${dir}`);
|
|
844
|
+
out.line(` 地址 http://127.0.0.1:${server.port}${page}`);
|
|
845
|
+
out.ok(`服务中(Ctrl+C 结束${flags.timeout !== undefined ? `,或 ${flags.timeout}s 后自动退` : ''})`);
|
|
846
|
+
} else {
|
|
847
|
+
ctx.done({ dir, port: server.port, url, page });
|
|
848
|
+
}
|
|
849
|
+
const timeoutSec = flags.timeout === undefined ? 0 : Number(flags.timeout);
|
|
850
|
+
if (timeoutSec > 0) await ctx.sleep(timeoutSec * 1000);
|
|
851
|
+
else await new Promise((resolve) => {
|
|
852
|
+
process.once('SIGINT', resolve);
|
|
853
|
+
process.once('SIGTERM', resolve);
|
|
854
|
+
});
|
|
855
|
+
server.close();
|
|
856
|
+
return undefined;
|
|
857
|
+
},
|
|
858
|
+
};
|
|
859
|
+
|
|
860
|
+
// ---------------------------------------------------------------- template shoot(task-44)
|
|
861
|
+
|
|
862
|
+
/** 截图前先看目录到底缺什么(缺件要 exit 2 说清楚,不能等 Chrome 崩) */
|
|
863
|
+
function shootMissingPieces(dir, page) {
|
|
864
|
+
const rel = String(page || '/pages/index.html').replace(/^\/+/, '');
|
|
865
|
+
const missing = [];
|
|
866
|
+
if (!fs.existsSync(path.join(dir, 'template.json'))) missing.push('template.json');
|
|
867
|
+
if (!fs.existsSync(path.join(dir, rel.replace(/\//g, path.sep)))) missing.push(rel);
|
|
868
|
+
if (!fs.existsSync(path.join(dir, 'assets'))) missing.push('assets/');
|
|
869
|
+
return missing;
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
export const templateShootCommand = {
|
|
873
|
+
name: 'template shoot',
|
|
874
|
+
summary: '一条命令出 design/ 六图:桌面 1440 + 移动 375 主帧,各带 t0 / t1500 两帧(全页口径与 verify 一致)',
|
|
875
|
+
usage: 'wkgeo template shoot --dir <模板目录> [--out <目录>] [--page /pages/index.html] [--chrome <exe>] [--json]',
|
|
876
|
+
args: [],
|
|
877
|
+
flags: {
|
|
878
|
+
dir: { type: 'string', desc: '模板目录(必须在目录内起静态服务截图)' },
|
|
879
|
+
out: { type: 'string', desc: '截图目录(默认 <模板目录>/design)' },
|
|
880
|
+
page: { type: 'string', desc: '首页路径(默认 /pages/index.html)' },
|
|
881
|
+
chrome: { type: 'string', desc: 'Chrome 可执行文件(默认自动找;也可设 WKGEO_CHROME)' },
|
|
882
|
+
},
|
|
883
|
+
examples: [
|
|
884
|
+
'wkgeo template shoot --dir ./templates/qbk-enterprise --out .tmp-build/t144/shoot-qbk',
|
|
885
|
+
'wkgeo template shoot --dir ./tpl/demo --json',
|
|
886
|
+
],
|
|
887
|
+
notes: [
|
|
888
|
+
'与 `capture` 同一条腿(`captureDesign`),区别是**固定六图口径**:主帧 desktop-1440 / mobile-375 + 各自 -t0 / -t1500。',
|
|
889
|
+
'主帧走 `--headless=new --virtual-time-budget=4000`(与 tools/render-compare 同口径);t0/t1500 走 CDP 真实时间。',
|
|
890
|
+
'缺件(不是模板目录 / 缺 pages/index.html)→ **exit 2** 并列出缺什么;截图失败(Chrome 不在 / 超时 / 缺图)→ exit 1。',
|
|
891
|
+
'顺带写 `design/animations.json`(源码可抽时),这样紧接着跑 `verify` 能做动画对账。',
|
|
892
|
+
],
|
|
893
|
+
async run(ctx) {
|
|
894
|
+
const { out, flags } = ctx;
|
|
895
|
+
const dir = path.resolve(process.cwd(), String(flags.dir || '.'));
|
|
896
|
+
if (!fs.existsSync(dir)) throw new UsageError(`模板目录不存在:${dir}`);
|
|
897
|
+
const page = String(flags.page || '/pages/index.html');
|
|
898
|
+
const missing = shootMissingPieces(dir, page);
|
|
899
|
+
if (missing.length) {
|
|
900
|
+
throw new UsageError(`目录不是可截图的模板,缺 ${missing.length} 项:${missing.join('、')}`, {
|
|
901
|
+
hint: 'shoot 需要 template.json + 首页 + assets/;基础库脚手架(如 templates/base-starter)本身不是可发布的模板,先用 `template init --from-*` 生成一套',
|
|
902
|
+
});
|
|
903
|
+
}
|
|
904
|
+
const designDir = flags.out ? path.resolve(process.cwd(), String(flags.out)) : path.join(dir, 'design');
|
|
905
|
+
const chromeExe = resolveChrome(flags.chrome ? String(flags.chrome) : null);
|
|
906
|
+
const started = Date.now();
|
|
907
|
+
let server = null;
|
|
908
|
+
try {
|
|
909
|
+
server = await startStaticServer(dir);
|
|
910
|
+
const url = server.url.replace(/\/+$/, '') + (page.startsWith('/') ? page : `/${page}`);
|
|
911
|
+
if (!out.json) {
|
|
912
|
+
out.head(`截图 ${url}`);
|
|
913
|
+
out.line(` Chrome ${chromeExe}`);
|
|
914
|
+
out.line(` 输出 ${designDir}(主帧 2 张 + 动画两帧 4 张 = 6 张)`);
|
|
915
|
+
}
|
|
916
|
+
await captureDesign({
|
|
917
|
+
url,
|
|
918
|
+
dir: designDir,
|
|
919
|
+
frames: true,
|
|
920
|
+
chromeExe,
|
|
921
|
+
templateDir: dir,
|
|
922
|
+
page,
|
|
923
|
+
onProgress: (s) => {
|
|
924
|
+
if (!out.json) out.line(` ${s}`);
|
|
925
|
+
},
|
|
926
|
+
});
|
|
927
|
+
} finally {
|
|
928
|
+
if (server) server.close();
|
|
929
|
+
}
|
|
930
|
+
const design = designListing(designDir, true);
|
|
931
|
+
const lost = design.filter((d) => d.missing);
|
|
932
|
+
if (lost.length) {
|
|
933
|
+
throw new CliError(`截图不完整,缺 ${lost.length} 张:${lost.map((m) => m.name).join(', ')}`, {
|
|
934
|
+
kind: 'capture',
|
|
935
|
+
code: 'ECAPTURE',
|
|
936
|
+
exitCode: EXIT.ERROR,
|
|
937
|
+
hint: `Chrome 没吐出这些文件:${designDir}`,
|
|
938
|
+
raw: { design },
|
|
939
|
+
});
|
|
940
|
+
}
|
|
941
|
+
if (!out.json) {
|
|
942
|
+
for (const d of design) out.line(` ✓ design/${d.name} · ${d.width}x${d.height} · ${fmtBytes(d.bytes)}`);
|
|
943
|
+
out.ok(`六图齐全 · ${design.length} 张 · 耗时 ${Date.now() - started}ms`);
|
|
944
|
+
}
|
|
945
|
+
ctx.done({
|
|
946
|
+
dir,
|
|
947
|
+
out: designDir,
|
|
948
|
+
page,
|
|
949
|
+
chrome: chromeExe,
|
|
950
|
+
design: design.map((d) => ({ name: d.name, path: d.path, bytes: d.bytes, width: d.width, height: d.height })),
|
|
951
|
+
count: design.length,
|
|
952
|
+
elapsed_ms: Date.now() - started,
|
|
953
|
+
});
|
|
954
|
+
},
|
|
955
|
+
};
|
|
956
|
+
|
|
957
|
+
// ---------------------------------------------------------------- template score(task-44)
|
|
958
|
+
|
|
959
|
+
function printScore(out, s) {
|
|
960
|
+
out.head(`评分 ${s.dir}`);
|
|
961
|
+
for (const d of s.dimensions) {
|
|
962
|
+
out.line(` ${d.name.padEnd(6)} ${String(d.score).padStart(5)} / ${d.max}`);
|
|
963
|
+
for (const it of d.items) {
|
|
964
|
+
out.line(` ${it.ok ? '✓' : '·'} ${it.name} ${it.score}/${it.max}${it.detail ? ` — ${it.detail}` : ''}`);
|
|
965
|
+
for (const r of (it.reasons || []).slice(0, 4)) out.line(` - ${r}`);
|
|
966
|
+
}
|
|
967
|
+
if (d.chrome_error) out.line(` - Chrome 量测失败:${d.chrome_error.slice(0, 200)}`);
|
|
968
|
+
}
|
|
969
|
+
out.line('');
|
|
970
|
+
out.line(` 合计 ${s.total} / 100 → 等级 ${s.grade}(A≥85 / B≥70 / C≥55 / D)`);
|
|
971
|
+
if (s.grade !== 'A') {
|
|
972
|
+
const worst = [...s.dimensions].sort((a, b) => a.score / a.max - b.score / b.max)[0];
|
|
973
|
+
out.line(` 最短板:${worst.name}(${worst.score}/${worst.max})`);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
export const templateScoreCommand = {
|
|
978
|
+
name: 'template score',
|
|
979
|
+
summary: '自评分(100 分制,四维):结构完整 / 移动适配 / 视觉层次 / 动画质量,逐项给扣分理由与证据',
|
|
980
|
+
usage: 'wkgeo template score --dir <模板目录> [--out report.json] [--no-chrome] [--page /pages/index.html] [--json]',
|
|
981
|
+
args: [],
|
|
982
|
+
flags: {
|
|
983
|
+
dir: { type: 'string', desc: '模板目录' },
|
|
984
|
+
out: { type: 'string', desc: '把评分报告写到这个 JSON 文件(内容与 --json 信封一致)' },
|
|
985
|
+
'no-chrome': { type: 'boolean', desc: '不跑 Chrome(移动适配维度按 0 分计并写明原因;CI 无 Chrome 时用)' },
|
|
986
|
+
chrome: { type: 'string', desc: 'Chrome 可执行文件(默认自动找)' },
|
|
987
|
+
page: { type: 'string', desc: '首页路径(默认 /pages/index.html)' },
|
|
988
|
+
},
|
|
989
|
+
examples: [
|
|
990
|
+
'wkgeo template score --dir ./templates/qbk-enterprise',
|
|
991
|
+
'wkgeo template score --dir ./templates/ind-law-firm --out .tmp-build/t144/score-ind-law-firm.json --json',
|
|
992
|
+
],
|
|
993
|
+
notes: [
|
|
994
|
+
'四维各 25 分:① 结构完整(复用 `validate` 的 8 关)② 移动适配(Chrome 真渲染 390/768/1440 量溢出/字号/点击区)③ 视觉层次(首屏层级/留白/token/图片)④ 动画质量(缓动/时长/渐进/减弱动效)。',
|
|
995
|
+
'**同目录两次跑必须同分**:结果里没有时间戳、没有随机数,遍历与证据数组都排序;移动量测用 `offsetWidth/offsetHeight`(布局盒,不吃 transform)。',
|
|
996
|
+
'评分不改任何文件(`--out` 除外)。等级 A≥85 / B≥70 / C≥55 / D。',
|
|
997
|
+
],
|
|
998
|
+
async run(ctx) {
|
|
999
|
+
const { out, flags } = ctx;
|
|
1000
|
+
const dir = path.resolve(process.cwd(), String(flags.dir || '.'));
|
|
1001
|
+
const started = Date.now();
|
|
1002
|
+
const result = await scoreMod.scoreTemplate({
|
|
1003
|
+
dir,
|
|
1004
|
+
cwd: process.cwd(),
|
|
1005
|
+
noChrome: flags.noChrome === true,
|
|
1006
|
+
chromeExe: flags.chrome ? String(flags.chrome) : null,
|
|
1007
|
+
page: flags.page ? String(flags.page) : '/pages/index.html',
|
|
1008
|
+
});
|
|
1009
|
+
let reportFile = null;
|
|
1010
|
+
if (flags.out) {
|
|
1011
|
+
reportFile = path.resolve(process.cwd(), String(flags.out));
|
|
1012
|
+
fs.mkdirSync(path.dirname(reportFile), { recursive: true });
|
|
1013
|
+
fs.writeFileSync(reportFile, `${JSON.stringify(result, null, 2)}\n`, 'utf8');
|
|
1014
|
+
}
|
|
1015
|
+
if (!out.json) {
|
|
1016
|
+
printScore(out, result);
|
|
1017
|
+
if (reportFile) out.ok(`报告 ${reportFile}`);
|
|
1018
|
+
}
|
|
1019
|
+
ctx.done({ ...result, report: reportFile, elapsed_ms: Date.now() - started });
|
|
1020
|
+
},
|
|
1021
|
+
};
|
|
1022
|
+
|
|
1023
|
+
// ---------------------------------------------------------------- template publish(task-44)
|
|
1024
|
+
|
|
1025
|
+
function printPublishPlan(out, r) {
|
|
1026
|
+
const p = r.plan.market;
|
|
1027
|
+
out.head(`发布计划${r.dryRun ? '(dry-run,加 --confirm 才真写)' : ''} · key ${r.key}`);
|
|
1028
|
+
out.line(` 桶 ${r.plan.bucket} / ${r.plan.region} · 前缀 ${r.plan.oss_prefix}`);
|
|
1029
|
+
out.line(
|
|
1030
|
+
` 文件 ${r.plan.file_count} 个(template.json.items)· OSS 对象 ${r.plan.oss_object_count} 个(含 template.json)· ` +
|
|
1031
|
+
`合计 ${fmtBytes(r.plan.total_bytes)} · digest ${String(r.plan.digest).slice(0, 16)}…`,
|
|
1032
|
+
);
|
|
1033
|
+
out.line(
|
|
1034
|
+
` 市场行 name=${p.name} · sort=${p.sort} · price_cents=${p.price_cents} · ` +
|
|
1035
|
+
`demo=${p.demo ? p.demo.key : '-'} · industries=${(p.industries || []).length}`,
|
|
1036
|
+
);
|
|
1037
|
+
out.line(` 现有市场行 ${r.before.market ? `有(version ${r.before.market.version} / files ${r.before.market.files_count})` : '无(将新建)'} · 现有 OSS 对象 ${r.before.oss_objects} 个`);
|
|
1038
|
+
out.line(` 将上传:`);
|
|
1039
|
+
for (const u of r.plan.uploads.slice(0, 6)) out.line(` ↑ ${u.key}(${fmtBytes(u.bytes)})`);
|
|
1040
|
+
if (r.plan.uploads.length > 6) out.line(` … 其余 ${r.plan.uploads.length - 6} 个`);
|
|
1041
|
+
if (r.plan.prune.stale.length) {
|
|
1042
|
+
out.warn(`prune 将删除 ${r.plan.prune.stale.length} 个不在本次清单里的旧对象:`);
|
|
1043
|
+
for (const s of r.plan.prune.stale.slice(0, 8)) out.line(` × ${s.key}`);
|
|
1044
|
+
} else {
|
|
1045
|
+
out.line(` prune:前缀下现有 ${r.before.oss_objects} 个对象,无旧对象需要删`);
|
|
1046
|
+
}
|
|
1047
|
+
out.line(` 存档 ${r.archive.dir}:publish-${r.key}.plan.json / .market-before.json / .oss-before.json${r.dryRun ? '' : ' / .market-after.json / .oss-after.json / .readback.json'}`);
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
function printPublishResult(out, r) {
|
|
1051
|
+
for (const s of r.steps) {
|
|
1052
|
+
const detail = s.detail && typeof s.detail === 'object' ? '' : s.detail ? ` ${s.detail}` : '';
|
|
1053
|
+
out.line(` ${s.status === 'ok' ? '✓' : s.status === 'failed' ? '✗' : '·'} ${s.step}${detail}`);
|
|
1054
|
+
}
|
|
1055
|
+
const c = r.checks || {};
|
|
1056
|
+
out.line(
|
|
1057
|
+
` 回读:市场行 ${c.market_row_exists ? '存在' : '缺失'} · templateId ${c.template_id} · ` +
|
|
1058
|
+
`files ${c.files_count_actual}/${c.files_count_expected} · OSS ${c.oss_object_count_actual}/${c.oss_object_count_expected} · ` +
|
|
1059
|
+
`HEAD 200 ${c.oss_all_head_200 ? '全通过' : '有缺失'}`,
|
|
1060
|
+
);
|
|
1061
|
+
if (c.public_object) out.line(` 对象直链 ${c.public_object.status} ${fmtBytes(c.public_object.bytes)}`);
|
|
1062
|
+
if (c.preview_page) out.line(` 预览短链 ${c.preview_page.status} ${fmtBytes(c.preview_page.bytes)}`);
|
|
1063
|
+
if (r.deleted && r.deleted.length) out.line(` prune 删除 ${r.deleted.length} 个旧对象`);
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
export const templatePublishCommand = {
|
|
1067
|
+
name: 'template publish',
|
|
1068
|
+
summary: '发布闭环:打包 → 传 OSS → upsert 市场行 → 回读校验(默认 dry-run,--confirm 才真写)',
|
|
1069
|
+
usage: 'wkgeo template publish --dir <模板目录> [--key <k>] [--dry-run] [--confirm] [--no-prune] [--archive <目录>] [--no-preview] [--json]',
|
|
1070
|
+
args: [],
|
|
1071
|
+
flags: {
|
|
1072
|
+
dir: { type: 'string', desc: '模板目录(读 template.json 的 files 作为发布清单)' },
|
|
1073
|
+
key: { type: 'string', desc: '覆盖市场 key(默认 template.json.key 或目录名)' },
|
|
1074
|
+
'dry-run': { type: 'boolean', desc: '只打印计划 + 存前档(默认行为,显式写出来便于脚本)' },
|
|
1075
|
+
confirm: { type: 'boolean', desc: '真写:传 OSS + upsert 市场行(没有它一律只读)' },
|
|
1076
|
+
'no-prune': { type: 'boolean', desc: '不删前缀下不在本次清单里的旧对象(默认会删,见 AGENTS.md §2.8)' },
|
|
1077
|
+
archive: { type: 'string', desc: '前后存档目录(默认 .tmp-build/t144)' },
|
|
1078
|
+
'no-preview': { type: 'boolean', desc: '回读时不请求预览短链(离线/内网时用)' },
|
|
1079
|
+
},
|
|
1080
|
+
examples: [
|
|
1081
|
+
'wkgeo template publish --dir ./templates/qbk-enterprise # dry-run 看计划',
|
|
1082
|
+
'wkgeo template publish --dir ./templates/qbk-enterprise --json # dry-run 的 JSON 计划',
|
|
1083
|
+
'wkgeo template publish --dir ./tpl/demo --key t144-probe --confirm # 真写(测试 key)',
|
|
1084
|
+
],
|
|
1085
|
+
notes: [
|
|
1086
|
+
'凭据只从 env / 本机 `oss.env` / `tencent/cloudbase/.env` 读,**永不打印**(只报"已配置 + 来源路径 + 末 4 位")。',
|
|
1087
|
+
'真写前先把**市场行 + OSS 前缀清单**存档到 `.tmp-build/t144/`(`--archive` 可改),写完再存一份,前后可比。',
|
|
1088
|
+
'OSS 走手写 V1 签名(CLI 零依赖,不引 ali-oss);`prefix`/`max-keys` 这类普通查询参数**不进签名**,进了会 SignatureDoesNotMatch。',
|
|
1089
|
+
'顺序:上传 → prune(新替旧)→ upsert 市场行(`version` 自增、`sha256` = 发布清单摘要)→ 回读(行 / files 数 / OSS HEAD / 对象直链 / 预览短链)。',
|
|
1090
|
+
'任一回读校验不过 → exit 1 并逐项打印;参数或凭据问题 → exit 2。',
|
|
1091
|
+
],
|
|
1092
|
+
async run(ctx) {
|
|
1093
|
+
const { out, flags } = ctx;
|
|
1094
|
+
if (flags.confirm === true && flags.dryRun === true) throw new UsageError('`--confirm` 与 `--dry-run` 只能二选一');
|
|
1095
|
+
const confirm = flags.confirm === true;
|
|
1096
|
+
const dir = path.resolve(process.cwd(), String(flags.dir || '.'));
|
|
1097
|
+
if (!fs.existsSync(dir)) throw new UsageError(`模板目录不存在:${dir}`);
|
|
1098
|
+
const started = Date.now();
|
|
1099
|
+
const result = await publishMod.publishTemplate({
|
|
1100
|
+
dir,
|
|
1101
|
+
key: flags.key ? String(flags.key) : null,
|
|
1102
|
+
confirm,
|
|
1103
|
+
prune: flags.noPrune !== true,
|
|
1104
|
+
archiveDir: flags.archive ? path.resolve(process.cwd(), String(flags.archive)) : path.join(process.cwd(), '.tmp-build', 't144'),
|
|
1105
|
+
preview: flags.noPreview !== true,
|
|
1106
|
+
cwd: process.cwd(),
|
|
1107
|
+
onStep: (s) => {
|
|
1108
|
+
if (!out.json) out.line(` · ${s.step}${typeof s.detail === 'object' ? '' : s.detail ? ` ${s.detail}` : ''}`);
|
|
1109
|
+
},
|
|
1110
|
+
});
|
|
1111
|
+
if (!out.json) {
|
|
1112
|
+
printPublishPlan(out, result);
|
|
1113
|
+
if (!result.dryRun) {
|
|
1114
|
+
printPublishResult(out, result);
|
|
1115
|
+
if (result.ok) out.ok(`已发布 ${result.key}(${result.plan.file_count} 文件 / ${result.plan.oss_object_count} 对象)`);
|
|
1116
|
+
else out.err(`回读校验未通过:${result.key}`);
|
|
1117
|
+
} else {
|
|
1118
|
+
out.ok('dry-run 完成:没有写任何东西(加 --confirm 真发布)');
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
const payload = {
|
|
1122
|
+
dry_run: result.dryRun,
|
|
1123
|
+
ok: result.ok,
|
|
1124
|
+
key: result.key,
|
|
1125
|
+
plan: result.plan,
|
|
1126
|
+
steps: result.steps,
|
|
1127
|
+
archive: result.archive,
|
|
1128
|
+
warnings: result.warnings,
|
|
1129
|
+
before: result.before,
|
|
1130
|
+
after: result.after || null,
|
|
1131
|
+
checks: result.checks || null,
|
|
1132
|
+
uploaded: result.uploaded || null,
|
|
1133
|
+
deleted: result.deleted || null,
|
|
1134
|
+
elapsed_ms: Date.now() - started,
|
|
1135
|
+
};
|
|
1136
|
+
if (!result.dryRun && !result.ok) {
|
|
1137
|
+
throw new CliError(`发布回读校验未通过:${result.key}`, {
|
|
1138
|
+
kind: 'publish',
|
|
1139
|
+
code: 'EREADBACK',
|
|
1140
|
+
exitCode: EXIT.ERROR,
|
|
1141
|
+
hint: '看 checks 里哪一项不过(行 / files 数 / OSS HEAD / 直链 / 预览短链)',
|
|
1142
|
+
raw: payload,
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
ctx.done(payload);
|
|
1146
|
+
},
|
|
1147
|
+
};
|
|
1148
|
+
|
|
1149
|
+
// ---------------------------------------------------------------- template animation(task-46:运行时提取)
|
|
1150
|
+
|
|
1151
|
+
export const templateAnimationCommand = {
|
|
1152
|
+
name: 'template animation',
|
|
1153
|
+
summary:
|
|
1154
|
+
'运行时提取动画与交互(headless Chrome + CDP)→ keyframes/animations/transitions/scrollTriggers/reducedMotion + layering/easing/rhythm 原始值',
|
|
1155
|
+
usage:
|
|
1156
|
+
'wkgeo template animation --dir <模板目录> [--page /pages/x.html] [--url <网址>] [--out <json>] [--virtual-time-budget 4000] [--json]',
|
|
1157
|
+
args: [],
|
|
1158
|
+
flags: {
|
|
1159
|
+
dir: { type: 'string', desc: '模板目录(读 pages/*.html + assets/,静态服务在本地跑,只读)' },
|
|
1160
|
+
url: { type: 'string', desc: '直接采线上页(只读;只抓这一页,不爬站)' },
|
|
1161
|
+
page: { type: 'string', desc: '只采指定页(可重复);不给就采 template.json / pages/ 里的全部页面' },
|
|
1162
|
+
out: { type: 'string', desc: 'JSON 落盘路径(默认写 .tmp-build 下的临时文件并打印)' },
|
|
1163
|
+
'virtual-time-budget': { type: 'number', desc: '加载后静置上限 ms(默认 4000;内部最多等 1500ms,见文档稳定性口径)' },
|
|
1164
|
+
seed: { type: 'number', desc: '随机口径(只影响调试端口与并列排序,默认 0)' },
|
|
1165
|
+
chrome: { type: 'string', desc: '本机 chrome.exe 路径(默认自动找;也可用 CHROME_PATH)' },
|
|
1166
|
+
tool: { type: 'string', desc: '提取器脚本路径(默认在仓库里往上找 tools/render-compare/animation-extract.mjs)' },
|
|
1167
|
+
},
|
|
1168
|
+
examples: [
|
|
1169
|
+
'wkgeo template animation --dir ./templates/qbk-enterprise --out ./anim.json',
|
|
1170
|
+
'wkgeo template animation --dir ./templates/ind-law-firm --page /pages/index.html --json',
|
|
1171
|
+
'wkgeo template animation --url https://qibukuai.com/ --json',
|
|
1172
|
+
],
|
|
1173
|
+
notes: [
|
|
1174
|
+
'**只读**:不改页面、不改模板、不写对方站点;每页一个独立标签页,采完关掉。',
|
|
1175
|
+
'五类产出:`keyframes[]`(名称/规则文本/出处/被哪些选择器引用)、`animations[]`(选择器/属性/duration/delay/iteration/direction/fill/easing)、`transitions[]`(触发条件)、`scrollTriggers[]`(IntersectionObserver / scroll 监听 / data-* 与 class 钩子,带阈值与一次性/重复)、`reducedMotion`(有无 prefers-reduced-motion 兜底与覆盖面)。',
|
|
1176
|
+
'另给 `quality`:layering(同屏条数 / delay 错峰 / 入场层级)、easing(自定义曲线占比 / 是否只有 ease/linear)、rhythm(时长分档占比 / 循环条数)——**只给原始值,不下体检结论**(评分在 task-68)。',
|
|
1177
|
+
'稳定性:计数只来自 CSSOM 原文 + DOM 静态结构(不来自帧/时间采样),同一输入两次 `summary` 逐字节一致;`--virtual-time-budget` 只当"加载后静置上限",`--seed` 只影响端口与排序。',
|
|
1178
|
+
'和 `wkgeo template anim` 的区别:`anim` 读源码出"映射到 _base 词汇"的清单;`animation` 真跑页面出运行时结构化数据(只读源码看不出 `!important` 掐死、JS 加 class 的入场)。',
|
|
1179
|
+
],
|
|
1180
|
+
async run(ctx) {
|
|
1181
|
+
const { out, flags } = ctx;
|
|
1182
|
+
const dir = flags.dir ? path.resolve(process.cwd(), String(flags.dir)) : null;
|
|
1183
|
+
const url = flags.url ? String(flags.url) : null;
|
|
1184
|
+
if (dir && !fs.existsSync(dir)) throw new UsageError(`模板目录不存在:${dir}`);
|
|
1185
|
+
if (!dir && !url) throw new UsageError('必须给 --dir <模板目录> 或 --url <网址>(--help 看用法)');
|
|
1186
|
+
const budget = Number(flags.virtualTimeBudget);
|
|
1187
|
+
const r = await extractAnimationsForCli({
|
|
1188
|
+
dir,
|
|
1189
|
+
url,
|
|
1190
|
+
page: flags.page ? String(flags.page) : null,
|
|
1191
|
+
out: flags.out ? String(flags.out) : null,
|
|
1192
|
+
virtualTimeBudget: Number.isFinite(budget) && budget > 0 ? budget : 4000,
|
|
1193
|
+
seed: Number(flags.seed) || 0,
|
|
1194
|
+
chrome: flags.chrome ? String(flags.chrome) : null,
|
|
1195
|
+
toolPath: flags.tool ? String(flags.tool) : null,
|
|
1196
|
+
});
|
|
1197
|
+
const json = r.json;
|
|
1198
|
+
if (!out.json) printExtractSummary(out, json);
|
|
1199
|
+
if (r.outFile) out.ok(`已写 ${path.relative(process.cwd(), r.outFile) || r.outFile}(${json._format || 'wkgeo-anim-extract@1'})`);
|
|
1200
|
+
ctx.done({
|
|
1201
|
+
dir,
|
|
1202
|
+
url,
|
|
1203
|
+
out: r.outFile,
|
|
1204
|
+
elapsedMs: r.elapsedMs,
|
|
1205
|
+
summary: json.summary,
|
|
1206
|
+
quality: json.quality,
|
|
1207
|
+
counts: json.summary ? json.summary.counts : null,
|
|
1208
|
+
warnings: json.warnings || [],
|
|
1209
|
+
});
|
|
1210
|
+
},
|
|
1211
|
+
};
|
|
1212
|
+
|
|
1213
|
+
// ---------------------------------------------------------------- templates pull / push(2026-11-01 老板单)
|
|
1214
|
+
|
|
1215
|
+
/**
|
|
1216
|
+
* 老板(2026-11-01):「我不需要在线编辑那一块,那一块功能可以取消。如果我编辑的话,
|
|
1217
|
+
* 我就在我的 CLI 里面去编辑,本地电脑绑定客户端 + CLI。」
|
|
1218
|
+
*
|
|
1219
|
+
* ⇒ 模板的编辑入口从「CMS 里点开 Monaco」改成「`templates pull` 拉下来 → 本地编辑器改 →
|
|
1220
|
+
* `templates push` 推回 → `publish --confirm` 生效」。CMS 那边只隐藏入口,
|
|
1221
|
+
* 服务端 `templateFileSave` 保留(push 就是用它)。
|
|
1222
|
+
*
|
|
1223
|
+
* 文件逻辑全在 `lib/templates-sync.mjs`(可单测、不碰网络);这里只做参数 → 调用 → 打印。
|
|
1224
|
+
*/
|
|
1225
|
+
|
|
1226
|
+
/** 站点参数(与 `cms.mjs` 的 SITE_FLAG 同口径;那边没导出,这里不跨文件借私有常量) */
|
|
1227
|
+
const TEMPLATES_SITE_FLAG = {
|
|
1228
|
+
site: { type: 'string', desc: '站点 ID(uuid);不传就用 `wkgeo site use` 选中的那个(`wkgeo sites list` 可查 ID)' },
|
|
1229
|
+
};
|
|
1230
|
+
|
|
1231
|
+
/**
|
|
1232
|
+
* 命令层 → `templates-sync` 的适配器:只做"动作名映射",业务判断不放在这里。
|
|
1233
|
+
*
|
|
1234
|
+
* 用的是**现有**三个服务端动作,本单不新增动作:
|
|
1235
|
+
* `templateList`(按 key 找模板时要它)/ `templateGet`(取文件)/ `templateFileSave`(写文件)。
|
|
1236
|
+
*/
|
|
1237
|
+
function templatesApiOf(ctx) {
|
|
1238
|
+
return {
|
|
1239
|
+
// 当前站(push 时用来跟 manifest.siteId 对账,防跨站写)
|
|
1240
|
+
currentSiteId: () => {
|
|
1241
|
+
try {
|
|
1242
|
+
return ctx.cmsSite().id || '';
|
|
1243
|
+
} catch {
|
|
1244
|
+
return '';
|
|
1245
|
+
}
|
|
1246
|
+
},
|
|
1247
|
+
list: () => ctx.cmsCall('templateList'),
|
|
1248
|
+
get: (templateId) => ctx.cmsCall('templateGet', templateId ? { templateId: String(templateId) } : {}),
|
|
1249
|
+
save: ({ path: filePath, content, templateId }) =>
|
|
1250
|
+
ctx.cmsCall('templateFileSave', {
|
|
1251
|
+
path: filePath,
|
|
1252
|
+
content,
|
|
1253
|
+
// 只在 manifest 记了 templateId 时带上:不带 = 服务端写"当前启用"那套(可能与本地不是同一套)
|
|
1254
|
+
...(templateId ? { templateId: String(templateId) } : {}),
|
|
1255
|
+
}),
|
|
1256
|
+
};
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
/** 把四类差异打成一张表(人类模式才有;JSON 模式走 ctx.done 的信封) */
|
|
1260
|
+
function printPushPlan(out, plan) {
|
|
1261
|
+
out.head(
|
|
1262
|
+
`改动计划:新增 ${plan.added.length} / 改动 ${plan.changed.length} / 远端多余 ${plan.removed.length} / 未变 ${plan.unchanged.length}`,
|
|
1263
|
+
);
|
|
1264
|
+
const rows = [];
|
|
1265
|
+
for (const f of plan.added) rows.push(['+', f.path, fmtBytes(f.bytes)]);
|
|
1266
|
+
for (const f of plan.changed) {
|
|
1267
|
+
const before = Number.isFinite(f.remote_bytes) ? fmtBytes(f.remote_bytes) : '?';
|
|
1268
|
+
rows.push(['~', f.path, `${before} → ${fmtBytes(f.bytes)}`]);
|
|
1269
|
+
}
|
|
1270
|
+
for (const f of plan.removed) {
|
|
1271
|
+
rows.push([plan.prune ? '-' : '?', f.path, fmtBytes(f.bytes)]);
|
|
1272
|
+
}
|
|
1273
|
+
if (rows.length) out.table(['', '文件', '大小'], rows);
|
|
1274
|
+
else out.info('本地与远端一致:没有要写的文件');
|
|
1275
|
+
if (plan.removed.length) {
|
|
1276
|
+
out.info(
|
|
1277
|
+
plan.prune
|
|
1278
|
+
? '(`-` = 本地已删、远端还在,列进待删;服务端目前没有删除模板文件的动作,push 不会真删)'
|
|
1279
|
+
: '(`?` = 本地已删、远端还在;默认不动远端,要列成待删加 --prune)',
|
|
1280
|
+
);
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
export const templatesPullCommand = {
|
|
1285
|
+
name: 'templates pull',
|
|
1286
|
+
summary: '把本站一套模板的全部文件拉到本地目录(manifest 记 sha256;二进制按 base64 还原成真文件)',
|
|
1287
|
+
usage:
|
|
1288
|
+
'wkgeo templates pull --dir <目录> [--site <站点ID>] [--template <key|id>] [--force]\n' +
|
|
1289
|
+
'wkgeo templates pull --dir ./my-template # 当前启用那套\n' +
|
|
1290
|
+
'wkgeo templates pull --dir ./tpl --template qbk-enterprise --site <站点ID>\n' +
|
|
1291
|
+
'wkgeo templates pull --dir ./tpl --force # 目录非空也覆盖',
|
|
1292
|
+
args: [],
|
|
1293
|
+
flags: {
|
|
1294
|
+
dir: { type: 'string', required: true, desc: '落到哪个本地目录(不存在就建;非空目录要加 --force)' },
|
|
1295
|
+
template: { type: 'string', desc: '模板 key 或 id(默认当前启用那套;key 先查 `templateList` 再取)' },
|
|
1296
|
+
force: { type: 'boolean', desc: '目标目录非空时也覆盖(默认拒绝,避免把已有文件冲掉)' },
|
|
1297
|
+
...TEMPLATES_SITE_FLAG,
|
|
1298
|
+
},
|
|
1299
|
+
examples: [
|
|
1300
|
+
'wkgeo templates pull --dir ./my-template',
|
|
1301
|
+
'wkgeo templates pull --dir ./tpl --template qbk-enterprise',
|
|
1302
|
+
'wkgeo templates pull --dir ./tpl --site 11111111-2222-4333-8444-555555555555',
|
|
1303
|
+
'wkgeo templates pull --dir ./tpl --force --json',
|
|
1304
|
+
],
|
|
1305
|
+
notes: [
|
|
1306
|
+
'文件按**模板内相对路径**落盘(`pages/index.html`、`partials/header.html`、`assets/style.css`…),目录结构与线上一致。',
|
|
1307
|
+
'`dir/template-manifest.json` 记 `siteId/templateId/key/contentHash/pulledAt` 与每个文件的 `bytes/sha256/encoding`;push 靠它对账,**别手工改**。',
|
|
1308
|
+
'二进制(png/jpg/webp/gif/ico/woff/woff2/ttf/eot/mp4…)按 base64 还原成**真文件**(不是把 base64 文本写进去);`svg` 按文本处理。',
|
|
1309
|
+
'路径安全:拒绝绝对路径 / 盘符 / 反斜杠 / `..` / 百分号编码 / 控制字符 / 整条超 200 字符或单段超 64 字符;落盘前再校验一次"没跑出目标目录"。',
|
|
1310
|
+
'单文件上限沿用服务端:文本 ≤40 万字符、二进制 ≤40 万字节;超了直接失败并指出是第几个文件(不打印正文)。',
|
|
1311
|
+
'拉完改文件 → `wkgeo templates push --dir <目录> --dry-run` 看差异 → `--confirm` 推回 → `wkgeo publish --confirm` 生效。',
|
|
1312
|
+
],
|
|
1313
|
+
async run(ctx) {
|
|
1314
|
+
const { out, flags } = ctx;
|
|
1315
|
+
if (!flags.dir) throw new UsageError('必须给 --dir <目录>\n例:wkgeo templates pull --dir ./my-template');
|
|
1316
|
+
const site = ctx.cmsSite();
|
|
1317
|
+
const r = await pullTemplate({
|
|
1318
|
+
siteId: site.id,
|
|
1319
|
+
templateKeyOrId: flags.template ? String(flags.template) : '',
|
|
1320
|
+
dir: String(flags.dir),
|
|
1321
|
+
api: templatesApiOf(ctx),
|
|
1322
|
+
force: flags.force === true,
|
|
1323
|
+
});
|
|
1324
|
+
|
|
1325
|
+
out.ok(
|
|
1326
|
+
`已拉取 ${r.fileCount} 个文件(${fmtBytes(r.bytes)}${r.binaryCount ? `,其中二进制 ${r.binaryCount}` : ''})→ ${r.dir}`,
|
|
1327
|
+
);
|
|
1328
|
+
out.info(`模板:${r.template.name || '-'}(key ${r.template.key || '-'} · id ${r.template.id || '-'})`);
|
|
1329
|
+
out.info(`manifest:${r.manifestPath}(contentHash ${r.contentHash.slice(0, 12)}…)`);
|
|
1330
|
+
out.table(
|
|
1331
|
+
['文件', '大小', '编码'],
|
|
1332
|
+
r.files.map((f) => [f.path, fmtBytes(f.bytes), f.encoding]),
|
|
1333
|
+
);
|
|
1334
|
+
out.notice('改完:`wkgeo templates push --dir <目录> --dry-run` 看差异 → `--confirm` 推回 → `wkgeo publish --confirm` 生效');
|
|
1335
|
+
|
|
1336
|
+
ctx.done({
|
|
1337
|
+
dir: r.dir,
|
|
1338
|
+
manifest: r.manifestPath,
|
|
1339
|
+
site_id: r.site_id,
|
|
1340
|
+
template: r.template,
|
|
1341
|
+
picked_by: r.picked_by,
|
|
1342
|
+
content_hash: r.contentHash,
|
|
1343
|
+
file_count: r.fileCount,
|
|
1344
|
+
binary_count: r.binaryCount,
|
|
1345
|
+
bytes: r.bytes,
|
|
1346
|
+
files: r.files,
|
|
1347
|
+
next: 'wkgeo templates push --dir <目录> --dry-run',
|
|
1348
|
+
});
|
|
1349
|
+
},
|
|
1350
|
+
};
|
|
1351
|
+
|
|
1352
|
+
export const templatesPushCommand = {
|
|
1353
|
+
name: 'templates push',
|
|
1354
|
+
summary: '把本地目录的改动推回线上模板(默认只算计划、零写请求;--confirm 才写)',
|
|
1355
|
+
usage:
|
|
1356
|
+
'wkgeo templates push --dir <目录> [--dry-run] [--confirm] [--prune] [--site <站点ID>]\n' +
|
|
1357
|
+
'wkgeo templates push --dir ./my-template --dry-run # 只看差异,退出码 0\n' +
|
|
1358
|
+
'wkgeo templates push --dir ./my-template --confirm # 真写\n' +
|
|
1359
|
+
'wkgeo templates push --dir ./my-template --confirm --prune # 顺带把"本地已删"的列成待删',
|
|
1360
|
+
args: [],
|
|
1361
|
+
flags: {
|
|
1362
|
+
dir: { type: 'string', required: true, desc: '本地模板目录(要有 pull 生成的 template-manifest.json)' },
|
|
1363
|
+
'dry-run': { type: 'boolean', desc: '只算计划、零写请求,退出码 0(不加 --confirm 又没 --dry-run 时退出码 2)' },
|
|
1364
|
+
confirm: { type: 'boolean', desc: '确认真写远端(不加它:只打印计划,一个写请求都不发)' },
|
|
1365
|
+
prune: { type: 'boolean', desc: '把"本地已删、远端还在"的文件列进待删(默认不动远端;服务端暂无删除动作,列出来不执行)' },
|
|
1366
|
+
...TEMPLATES_SITE_FLAG,
|
|
1367
|
+
},
|
|
1368
|
+
examples: [
|
|
1369
|
+
'wkgeo templates push --dir ./my-template --dry-run',
|
|
1370
|
+
'wkgeo templates push --dir ./my-template --confirm',
|
|
1371
|
+
'wkgeo templates push --dir ./my-template --confirm --prune --json',
|
|
1372
|
+
],
|
|
1373
|
+
notes: [
|
|
1374
|
+
'逐文件比对**远端 sha256**(内容口径),分四类:`added` 新增 / `changed` 改动 / `removed` 本地已删 / `unchanged` 未变。',
|
|
1375
|
+
'**默认零写请求**:不加 `--confirm` 只打计划;加了 `--dry-run` 退出码 0,两者都不加退出码 2(脚本里容易区分"忘了确认"与"跑失败")。',
|
|
1376
|
+
'**默认不删远端**;`--prune` 只把 removed 列进 `plan.willDelete`(服务端无"删模板文件"动作,不执行删除)。',
|
|
1377
|
+
'写的是 manifest 里那套模板(`templateId`);manifest 没记 id 时才落到"当前启用"那套。',
|
|
1378
|
+
'全部写成功才回写 manifest 的 `contentHash/pushedAt`;有失败**不写 manifest**,下次 push 还能算对差异。',
|
|
1379
|
+
'失败会报「第几个文件 + 路径 + 原因」(不打印文件正文);已写进去的不会重复写。',
|
|
1380
|
+
'二进制模板文件当前**推不上去**(服务端 `templateFileSave` 只收 html/css/js/json,图片请走 `wkgeo assets upload`)。',
|
|
1381
|
+
'推完要 `wkgeo publish --confirm` 才生效——push 只改模板文件,不改线上已发布的产物。',
|
|
1382
|
+
],
|
|
1383
|
+
async run(ctx) {
|
|
1384
|
+
const { out, flags } = ctx;
|
|
1385
|
+
if (!flags.dir) throw new UsageError('必须给 --dir <目录>\n例:wkgeo templates push --dir ./my-template --dry-run');
|
|
1386
|
+
const confirm = flags.confirm === true;
|
|
1387
|
+
const dryRun = flags.dryRun === true;
|
|
1388
|
+
|
|
1389
|
+
const r = await pushTemplate({
|
|
1390
|
+
dir: String(flags.dir),
|
|
1391
|
+
api: templatesApiOf(ctx),
|
|
1392
|
+
confirm,
|
|
1393
|
+
prune: flags.prune === true,
|
|
1394
|
+
});
|
|
1395
|
+
|
|
1396
|
+
printPushPlan(out, r.plan);
|
|
1397
|
+
for (const w of r.warnings || []) out.warn(w);
|
|
1398
|
+
|
|
1399
|
+
const payload = {
|
|
1400
|
+
dir: r.dir,
|
|
1401
|
+
manifest: r.manifestPath,
|
|
1402
|
+
site_id: r.site_id,
|
|
1403
|
+
template: r.template,
|
|
1404
|
+
plan: r.plan,
|
|
1405
|
+
warnings: r.warnings,
|
|
1406
|
+
applied: r.applied === true,
|
|
1407
|
+
written: r.written,
|
|
1408
|
+
content_hash: r.contentHash || null,
|
|
1409
|
+
// 给脚本/agent 的下一步:push 只改模板文件,线上产物要 publish 才变
|
|
1410
|
+
next: 'wkgeo publish --confirm',
|
|
1411
|
+
};
|
|
1412
|
+
|
|
1413
|
+
if (!confirm) {
|
|
1414
|
+
if (dryRun) {
|
|
1415
|
+
out.info('--dry-run:只算了计划,一个写请求都没发(退出码 0)');
|
|
1416
|
+
ctx.done({ ...payload, dry_run: true });
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
// 计划已经打印在最上面;这里用退出码 2 把"忘了 --confirm"和"真失败"分开
|
|
1420
|
+
throw new CliError(
|
|
1421
|
+
'templates push 未确认:上面是计划,**什么都没写**(零写请求)。真写加 --confirm;只想看计划加 --dry-run',
|
|
1422
|
+
{
|
|
1423
|
+
kind: 'confirm_required',
|
|
1424
|
+
exitCode: EXIT.USAGE,
|
|
1425
|
+
details: { plan: r.plan, warnings: r.warnings },
|
|
1426
|
+
hint: '确认差异没问题后:wkgeo templates push --dir <目录> --confirm',
|
|
1427
|
+
},
|
|
1428
|
+
);
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
out.ok(`已写入 ${r.written.length} 个文件(模板 ${r.template.id || '当前启用'}${r.contentHash ? ` · 新 contentHash ${String(r.contentHash).slice(0, 12)}…` : ''})`);
|
|
1432
|
+
out.notice('下一步:`wkgeo publish --confirm` 使改动生效(只 push 不发布,线上还是旧的)');
|
|
1433
|
+
ctx.done({ ...payload, dry_run: false, pushed_at: r.written_at || null });
|
|
1434
|
+
},
|
|
1435
|
+
};
|
|
1436
|
+
|
|
1437
|
+
// ---------------------------------------------------------------- 自注册(task-44;不许改 index.mjs)
|
|
1438
|
+
|
|
1439
|
+
/**
|
|
1440
|
+
* `shoot` / `score` / `publish` 三条命令必须在 `createRuntime` 之前进 `COMMANDS`,
|
|
1441
|
+
* 否则 `resolveCommand` 直接抛"不认识的命令:template shoot"。
|
|
1442
|
+
*
|
|
1443
|
+
* 本轮 `cli/lib/commands/index.mjs` **不允许改**(另一任务同时在改它),且 template.mjs
|
|
1444
|
+
* 里并没有派单假设的 `register(program)` 钩子。所以用 ESM 循环导入做一次注册:
|
|
1445
|
+
* `index.mjs` 的 `COMMAND_NAMES = COMMANDS.map((c) => c.name)` 会读
|
|
1446
|
+
* `templatePreviewCommand.name`,此时(循环导入已回到 index.mjs 尾部)`COMMANDS` 已初始化,
|
|
1447
|
+
* 在这个 getter 里 push 三条命令,`cli.mjs` 建 runtime 时就已经在册。
|
|
1448
|
+
*
|
|
1449
|
+
* 已知副作用:`COMMAND_NAMES` 里不含这 3 个名字(该导出全仓无引用,只影响自检脚本;
|
|
1450
|
+
* 帮助文本走 `COMMANDS`,仍然能看到三条命令)。
|
|
1451
|
+
*/
|
|
1452
|
+
let templateExtrasRegistered = false;
|
|
1453
|
+
function registerTemplateExtras() {
|
|
1454
|
+
if (templateExtrasRegistered) return;
|
|
1455
|
+
const list = commandsIndex && commandsIndex.COMMANDS;
|
|
1456
|
+
if (!Array.isArray(list)) return;
|
|
1457
|
+
for (const spec of [templateShootCommand, templateScoreCommand, templatePublishCommand, templateAnimationCommand]) {
|
|
1458
|
+
if (!list.includes(spec)) list.push(spec);
|
|
1459
|
+
}
|
|
1460
|
+
templateExtrasRegistered = true;
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
Object.defineProperty(templatePreviewCommand, 'name', {
|
|
1464
|
+
configurable: true,
|
|
1465
|
+
enumerable: true,
|
|
1466
|
+
get() {
|
|
1467
|
+
try {
|
|
1468
|
+
registerTemplateExtras();
|
|
1469
|
+
} catch {
|
|
1470
|
+
/* 循环导入未完成时读取:保持未注册,下次访问再试 */
|
|
1471
|
+
}
|
|
1472
|
+
return 'template preview';
|
|
1473
|
+
},
|
|
1474
|
+
});
|