@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.
Files changed (42) hide show
  1. package/CHANGELOG.md +249 -203
  2. package/README.md +151 -19
  3. package/SKILL.md +108 -27
  4. package/lib/args.mjs +2 -2
  5. package/lib/asset-role.mjs +68 -0
  6. package/lib/cms.mjs +2 -2
  7. package/lib/commands/billing.mjs +56 -10
  8. package/lib/commands/cms.mjs +49 -13
  9. package/lib/commands/content.mjs +108 -0
  10. package/lib/commands/crawl.mjs +219 -0
  11. package/lib/commands/geo.mjs +1673 -0
  12. package/lib/commands/index.mjs +640 -528
  13. package/lib/commands/member.mjs +930 -0
  14. package/lib/commands/seo.mjs +1386 -0
  15. package/lib/commands/siteops.mjs +3 -3
  16. package/lib/commands/sites.mjs +21 -125
  17. package/lib/commands/template.mjs +1474 -0
  18. package/lib/config.mjs +16 -13
  19. package/lib/content-apply.mjs +664 -0
  20. package/lib/content-check.mjs +887 -0
  21. package/lib/content-contract.mjs +957 -0
  22. package/lib/errors.mjs +6 -0
  23. package/lib/format.mjs +5 -1
  24. package/lib/manifest-apply.mjs +1499 -0
  25. package/lib/manifest-schema.json +476 -0
  26. package/lib/manifest.mjs +1082 -0
  27. package/lib/oauth-urls.mjs +1 -1
  28. package/lib/runtime.mjs +5 -1
  29. package/lib/site-create.mjs +536 -0
  30. package/lib/tar.mjs +207 -0
  31. package/lib/template-anim.mjs +1338 -0
  32. package/lib/template-animation.mjs +232 -0
  33. package/lib/template-capture.mjs +700 -0
  34. package/lib/template-gen.mjs +1204 -0
  35. package/lib/template-pack.mjs +206 -0
  36. package/lib/template-package.mjs +522 -0
  37. package/lib/template-publish.mjs +733 -0
  38. package/lib/template-score.mjs +865 -0
  39. package/lib/template-validate.mjs +368 -0
  40. package/lib/template-verify.mjs +434 -0
  41. package/lib/templates-sync.mjs +616 -0
  42. package/package.json +2 -2
@@ -0,0 +1,887 @@
1
+ /**
2
+ * `wkgeo content check` —— **一致性自检 + 评分**。
3
+ *
4
+ * 老板 2026-10-30:「建表结构与 CMS 前端表单保持一致」「要有一致性自检和评分」。
5
+ * 本命令把三方摆在一起对:
6
+ * ① `template.json` 契约(`columns[]` / 字段 / 类型 / 必填 / SEO);
7
+ * ② 库里实际结构(`cms_category` 行、`cms_field` 行的 key/type/required/enabled、内容值);
8
+ * ③ 前台渲染真用到的字段(模板 HTML 里的 `{{ content.xxx }}` / `{{ content.ext.xxx }}` / `{{ category.xxx }}`)。
9
+ *
10
+ * 四种情况**一律不通过 → exit 1**(和派发单一致):
11
+ * 类型不符 / 必填缺字段 / 库里多出契约外字段 / 契约声明的栏目在库里缺列。
12
+ * 其余问题(SEO 缺、示例数据没入库、多语言没覆盖…)只扣分 + 出 finding,不拦。
13
+ *
14
+ * 判分:9 维 100 分(`scoreDimensions()` 在 `content-contract.mjs`)。
15
+ * 某维有 error → 该维 0 分;只有 warn → 每条扣 max/3;整维不适用(如离线无 Chrome)→ 从满分里剔除。
16
+ */
17
+
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+
21
+ import {
22
+ contractTypeOfPlatform,
23
+ isUuid,
24
+ normalizeTemplateContract,
25
+ scoreDimensions,
26
+ validateFieldValue,
27
+ } from './content-contract.mjs';
28
+ import { CliError, EXIT, UsageError } from './errors.mjs';
29
+
30
+ /* ------------------------------------------------------------------ 维度定义 */
31
+
32
+ export const CHECK_DIMENSIONS = [
33
+ { key: 'structure', name: '结构完整', max: 14 },
34
+ { key: 'types', name: '类型对齐', max: 16 },
35
+ { key: 'required', name: '必填覆盖', max: 14 },
36
+ { key: 'media', name: '图片规格', max: 10 },
37
+ { key: 'seo', name: 'SEO 字段', max: 10 },
38
+ { key: 'i18n', name: '多语言', max: 8 },
39
+ { key: 'boundary', name: '越界检测', max: 12 },
40
+ { key: 'closure', name: '栏目-页面闭合', max: 10 },
41
+ { key: 'render', name: '渲染闭合', max: 6 },
42
+ ];
43
+
44
+ /** 契约类型 → 库里 `cms_field.type` 允许的原始写法(`gallery` 两个写法都认) */
45
+ const PLATFORM_OF_CONTRACT = {
46
+ text: ['input'],
47
+ textarea: ['textarea'],
48
+ richtext: ['richtext'],
49
+ image: ['image'],
50
+ gallery: ['images', 'imageGroup'],
51
+ file: ['file'],
52
+ video: ['video'],
53
+ number: ['number'],
54
+ date: ['date'],
55
+ select: ['select'],
56
+ boolean: ['switch'],
57
+ link: ['input', 'textarea'],
58
+ phone: ['input'],
59
+ email: ['input'],
60
+ list: null,
61
+ };
62
+
63
+ /** 平台字段类型白名单(与 `aliyun/fc/wkgeo-cms/src/index.js:22487` 的 `allowedFieldTypes` 一致) */
64
+ export const ALLOWED_PLATFORM_TYPES = [
65
+ 'input',
66
+ 'textarea',
67
+ 'number',
68
+ 'date',
69
+ 'select',
70
+ 'switch',
71
+ 'image',
72
+ 'images',
73
+ 'imageGroup',
74
+ 'file',
75
+ 'richtext',
76
+ 'video',
77
+ ];
78
+
79
+ /** 模板 HTML 里 `content.<key>` 这类「视图自带的键」,不是数据库列,别误判 */
80
+ const CONTENT_VIEW_KEYS = new Set([
81
+ 'body',
82
+ 'category_name',
83
+ 'category_slug',
84
+ 'date',
85
+ 'url',
86
+ 'cover_url',
87
+ 'tags',
88
+ 'tagIds',
89
+ 'tagKValue',
90
+ 'ext',
91
+ 'id',
92
+ 'title',
93
+ 'slug',
94
+ 'status',
95
+ 'keywords',
96
+ 'description',
97
+ 'sub_title',
98
+ 'author',
99
+ 'source',
100
+ 'specs',
101
+ 'views',
102
+ 'sort',
103
+ 'pinned',
104
+ 'published_at',
105
+ 'language_code',
106
+ 'redirect_url',
107
+ ]);
108
+
109
+ const err = (where, message, fix) => ({ level: 'error', where, message, fix, hard: true });
110
+ const warn = (where, message, fix) => ({ level: 'warn', where, message, fix });
111
+
112
+ function dim(def, findings, extra = {}) {
113
+ return {
114
+ key: def.key,
115
+ name: def.name,
116
+ max: def.max,
117
+ applicable: extra.applicable !== false,
118
+ note: extra.note || '',
119
+ findings,
120
+ };
121
+ }
122
+
123
+ const dimOf = key => CHECK_DIMENSIONS.find(one => one.key === key);
124
+
125
+ /* ------------------------------------------------------------------ 模板读取 */
126
+
127
+ /**
128
+ * 找模板目录:`<输入>`、`templates/<输入>`、`<输入>/template.json` 三种写法都认。
129
+ *
130
+ * @param {string} input 模板 key 或目录/文件路径
131
+ * @param {{cwd?:string}} [opts]
132
+ * @returns {{dir:string, file:string}|null}
133
+ */
134
+ export function resolveTemplateDir(input, { cwd = process.cwd() } = {}) {
135
+ const raw = String(input == null ? '' : input).trim();
136
+ if (!raw) return null;
137
+ const bases = [path.resolve(cwd, raw), path.resolve(cwd, 'templates', raw)];
138
+ for (const base of bases) {
139
+ const file = base.endsWith('.json') ? base : path.join(base, 'template.json');
140
+ if (fs.existsSync(file)) return { dir: path.dirname(file), file };
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /** 读模板契约(找不到就报能照做的错,不静默当「没有契约」) */
146
+ export function loadTemplateContract(input, opts = {}) {
147
+ const found = resolveTemplateDir(input, opts);
148
+ if (!found) {
149
+ throw new CliError(`找不到模板「${input}」`, {
150
+ kind: 'not_found',
151
+ hint: '--template 收模板 key(`templates/<key>/`)或模板目录 / template.json 的路径',
152
+ });
153
+ }
154
+ let json;
155
+ try {
156
+ json = JSON.parse(fs.readFileSync(found.file, 'utf8'));
157
+ } catch (e) {
158
+ throw new CliError(`模板 ${found.file} 不是合法 JSON(${e.message})`, { kind: 'bad_template' });
159
+ }
160
+ return { ...found, json, contract: normalizeTemplateContract(json, { source: found.dir }) };
161
+ }
162
+
163
+ /** 收模板里的 html 文件(pages/ partials/ 根目录,最多 2 层,跳过 design/ 与 node_modules) */
164
+ export function readTemplateFiles(dir) {
165
+ const out = [];
166
+ const walk = (current, depth) => {
167
+ if (depth > 2) return;
168
+ let entries = [];
169
+ try {
170
+ entries = fs.readdirSync(current, { withFileTypes: true });
171
+ } catch (e) {
172
+ return;
173
+ }
174
+ entries.forEach(entry => {
175
+ if (entry.name === 'node_modules' || entry.name === 'design' || entry.name.startsWith('.')) return;
176
+ const full = path.join(current, entry.name);
177
+ if (entry.isDirectory()) walk(full, depth + 1);
178
+ else if (/\.(html|js)$/i.test(entry.name)) {
179
+ let text = '';
180
+ try {
181
+ text = fs.readFileSync(full, 'utf8');
182
+ } catch (e) {
183
+ return;
184
+ }
185
+ out.push({ file: path.relative(dir, full).replace(/\\/g, '/'), text });
186
+ }
187
+ });
188
+ };
189
+ if (dir && fs.existsSync(dir)) walk(dir, 0);
190
+ return out;
191
+ }
192
+
193
+ /**
194
+ * 从前台模板里抽出「渲染真用到的字段」。
195
+ *
196
+ * 支持 `{{ x }}` / `{{{ x }}}` / `{{#if x}}` / `{{#each xs}}` 四种写法;
197
+ * `content.ext.<k>` 说明前台读的是栏目自定义字段,`content.<k>` 读的是内置列。
198
+ */
199
+ export function extractRenderVars(files) {
200
+ const vars = { content: new Set(), contentExt: new Set(), category: new Set(), page: new Set(), site: new Set(), loops: new Set(), partials: new Set() };
201
+ const tokenRe = /\{\{\{?\s*([^{}]{1,120}?)\s*\}?\}\}/g;
202
+ (files || []).forEach(one => {
203
+ if (!/\.html$/i.test(one.file)) return;
204
+ let text = one.text || '';
205
+ /** 注释里的变量不算引用(`{{! ... }}` 与 html 注释都剔掉,避免误报) */
206
+ text = text.replace(/\{\{![\s\S]*?\}\}/g, '').replace(/<!--[\s\S]*?-->/g, '');
207
+ let m;
208
+ while ((m = tokenRe.exec(text))) {
209
+ let expr = m[1].trim();
210
+ const partial = /^>\s*(.+)$/.exec(expr);
211
+ if (partial) {
212
+ vars.partials.add(partial[1].trim());
213
+ continue;
214
+ }
215
+ expr = expr.replace(/^[#^/]\s*/, '').replace(/^(if|unless|each|with|lookup)\s+/, '').trim();
216
+ const each = /^each\s+(.+)$/.exec(expr);
217
+ if (each) vars.loops.add(each[1].trim());
218
+ const dotted = /^([a-zA-Z_][\w]*)((?:\.[\w]+)*)$/.exec(expr);
219
+ if (!dotted) continue;
220
+ const root = dotted[1];
221
+ const rest = dotted[2] ? dotted[2].slice(1).split('.') : [];
222
+ if (root === 'content' && rest[0] === 'ext' && rest[1]) vars.contentExt.add(rest[1]);
223
+ else if (root === 'content' && rest[0]) vars.content.add(rest[0]);
224
+ else if (root === 'category' && rest[0]) vars.category.add(rest[0]);
225
+ else if (root === 'page' && rest[0]) vars.page.add(rest[0]);
226
+ else if (root === 'site' && rest.length) vars.site.add(rest.join('.'));
227
+ }
228
+ });
229
+ return vars;
230
+ }
231
+
232
+ /* ------------------------------------------------------------------ 站点读取 */
233
+
234
+ async function readSite(siteId, call, { lang = '', maxDetails = 300 } = {}) {
235
+ const langPayload = lang ? { _lang: lang } : {};
236
+ const categories = await call('categoryList', { ...langPayload });
237
+ if (!Array.isArray(categories)) {
238
+ throw new CliError('categoryList 返回的不是栏目数组(CLI 与服务端对不上)', { kind: 'bad_response' });
239
+ }
240
+ const byCategory = new Map();
241
+ let details = 0;
242
+ for (const cat of categories) {
243
+ const fields = await call('fieldList', { scope: 'content', categoryId: cat.id, ...langPayload });
244
+ const fieldMap = new Map();
245
+ (Array.isArray(fields) ? fields : []).forEach(raw => {
246
+ const spec = normalizeFieldSpecLike(raw);
247
+ if (spec.key) fieldMap.set(spec.key, spec);
248
+ });
249
+
250
+ const rows = [];
251
+ let total = 0;
252
+ for (let page = 1; page <= 5; page += 1) {
253
+ const data = await call('contentList', {
254
+ categoryId: cat.id,
255
+ page,
256
+ pageSize: 100,
257
+ ...(cat.kind === 'page' ? { ownerPage: true } : {}),
258
+ ...langPayload,
259
+ });
260
+ const list = (data && data.rows) || [];
261
+ total = Number((data && data.total) || 0);
262
+ rows.push(...list);
263
+ if (!list.length || rows.length >= total) break;
264
+ }
265
+
266
+ const detailMap = new Map();
267
+ for (const row of rows) {
268
+ if (details >= maxDetails) break;
269
+ const detail = await call('contentGet', { id: row.id, ...langPayload });
270
+ detailMap.set(row.id, detail);
271
+ details += 1;
272
+ }
273
+
274
+ byCategory.set(cat.id, { cat, fields: fieldMap, rows, total, details: detailMap, truncated: rows.length < total });
275
+ }
276
+ return { siteId, lang, categories, byCategory, detailCount: details };
277
+ }
278
+
279
+ /** 服务端 fieldList 行 → 检查用的字段规格(契约类型 + 库里特有的 enabled/source/rawType) */
280
+ function normalizeFieldSpecLike(raw) {
281
+ const base = raw && typeof raw === 'object' ? raw : {};
282
+ const type = contractTypeOfPlatform(base.type) || 'text';
283
+ return {
284
+ key: String(base.key || ''),
285
+ label: String(base.label || base.key || ''),
286
+ type,
287
+ rawType: String(base.type || ''),
288
+ required: base.required === true,
289
+ enabled: base.enabled !== false,
290
+ builtin: base.builtin === true,
291
+ source: String(base.source || ''),
292
+ options: base.options && typeof base.options === 'object' ? base.options : {},
293
+ rules: base.rules && typeof base.rules === 'object' ? base.rules : {},
294
+ };
295
+ }
296
+
297
+ /* ------------------------------------------------------------------ 各维度 */
298
+
299
+ function dimStructure({ contract, site }) {
300
+ const findings = [];
301
+ const def = dimOf('structure');
302
+ const columns = contract ? contract.columns : [];
303
+ if (!site && !columns.length) {
304
+ findings.push(err('契约', '既没有 --site 也没有可用契约,没法自检', '至少给一个:`--site <站点ID>` 或 `--template <key>`'));
305
+ }
306
+ if (contract) {
307
+ if (!contract.contractPresent) {
308
+ findings.push(
309
+ warn(
310
+ `模板 ${contract.key || contract.source}`,
311
+ '这份模板没有 `columns[]` 契约段(v1 市场格式),栏目/字段只能靠库里反推',
312
+ '按 docs/规范-模板内容契约.md §2 给模板补 `_format: wkgeo-template@2` + `columns[]`;补之前本维只按库侧计分',
313
+ ),
314
+ );
315
+ }
316
+ if (columns.length) {
317
+ const noFields = columns.filter(one => !one.fields.length).map(one => one.name || one.key);
318
+ if (noFields.length) {
319
+ findings.push(warn('契约 columns[]', `${noFields.length} 个栏目没声明任何字段:${noFields.slice(0, 8).join('、')}`, '栏目至少要声明它要展示的字段,否则 A 无从填'));
320
+ }
321
+ }
322
+ }
323
+ if (site) {
324
+ if (!site.categories.length) {
325
+ findings.push(err('站点', `站点 ${site.siteId} 一个栏目都没有(栏目必须建库)`, '先 `wkgeo sites create` 或装模板,栏目不是前台写死的东西'));
326
+ }
327
+ const badKind = site.categories.filter(one => !['channel', 'list', 'page'].includes(String(one.kind || '')));
328
+ badKind.forEach(one => findings.push(err(`category:${one.name}`, `栏目 kind=「${one.kind}」不在 channel|list|page 里`, '属库结构异常,报给平台侧')));
329
+ const noSlug = site.categories.filter(one => !one.slug);
330
+ noSlug.forEach(one => findings.push(err(`category:${one.name}`, '栏目缺 slug', 'slug 是栏目稳定 key,缺了前台路由立不住')));
331
+ const noPath = site.categories.filter(one => !one.path);
332
+ noPath.forEach(one => findings.push(err(`category:${one.name}`, '栏目缺 path', 'path 由服务端按父级算,缺了说明行没落好')));
333
+ }
334
+ return dim(def, findings, { note: site ? `站点 ${site.categories.length} 个栏目` : '仅契约侧' });
335
+ }
336
+
337
+ function dimTypes({ contract, site }) {
338
+ const findings = [];
339
+ const def = dimOf('types');
340
+ const contractKeys = new Map();
341
+
342
+ if (contract && contract.contractPresent) {
343
+ contract.columns.forEach(col => {
344
+ col.fields.forEach(field => {
345
+ contractKeys.set(`${col.slug || col.key}#${field.key}`, field);
346
+ const allowed = PLATFORM_OF_CONTRACT[field.type];
347
+ if (!field.type) {
348
+ findings.push(err(`契约 ${col.name}.${field.key}`, '字段没写 type', '按契约 §3 填类型(text/textarea/richtext/image/gallery/number/date/select/...)'));
349
+ } else if (field.type === 'list') {
350
+ findings.push(warn(`契约 ${col.name}.${field.key}`, '`list` 类型平台没有对应控件(卡点:库/表单都没有子字段编辑)', '改成多条内容(一个栏目多条 item)或拆成独立字段'));
351
+ } else if (allowed && !allowed.length) {
352
+ findings.push(err(`契约 ${col.name}.${field.key}`, `契约类型 ${field.type} 落不到任何库字段类型`, '见契约 §3 映射表'));
353
+ }
354
+ });
355
+ });
356
+ }
357
+
358
+ if (site) {
359
+ const declared = new Set();
360
+ if (contract && contract.contractPresent) {
361
+ contract.columns.forEach(col => {
362
+ [col.slug, col.key, col.name, String(col.slug || '').replace(/^\//, ''), String(col.slug || '').replace(/\/$/, '')]
363
+ .filter(Boolean)
364
+ .forEach(alias => col.fields.forEach(field => declared.add(`${alias}#${field.key}`)));
365
+ });
366
+ }
367
+
368
+ site.byCategory.forEach(({ cat, fields, rows, details }) => {
369
+ const aliases = [cat.slug, cat.name, String(cat.path || '').replace(/^\/+|\/+$/g, '')].filter(Boolean);
370
+
371
+ fields.forEach((spec, key) => {
372
+ /** ① 库字段类型必须在平台白名单里(建表结构 = CMS 表单控件的唯一来源) */
373
+ if (!ALLOWED_PLATFORM_TYPES.includes(spec.rawType)) {
374
+ findings.push(
375
+ err(
376
+ `field:${cat.name}.${key}`,
377
+ `库里字段「${spec.label}」的 type=「${spec.rawType}」不在平台白名单(${ALLOWED_PLATFORM_TYPES.join('|')})`,
378
+ 'CMS 表单渲染不出这个控件;改正 type 或删掉该字段',
379
+ ),
380
+ );
381
+ }
382
+
383
+ /** ② 契约与库的类型必须对得上 */
384
+ if (contract && contract.contractPresent) {
385
+ const hits = aliases.map(alias => contractKeys.get(`${alias}#${key}`)).filter(Boolean);
386
+ if (hits.length) {
387
+ const wanted = hits[0];
388
+ const accept = PLATFORM_OF_CONTRACT[wanted.type];
389
+ const compatible = accept
390
+ ? accept.includes(spec.rawType) || (accept.includes('images') && spec.rawType === 'imageGroup')
391
+ : false;
392
+ if (!compatible) {
393
+ findings.push(
394
+ err(
395
+ `field:${cat.name}.${key}`,
396
+ `类型不符:契约说「${wanted.type}」(库应为 ${(accept || []).join('/') || '无映射'}),库里是「${spec.rawType}」`,
397
+ '契约与建表必须一致:改字段(fieldSave)或改契约,二者不能各说各话',
398
+ ),
399
+ );
400
+ }
401
+ if (wanted.required === true && spec.required !== true) {
402
+ findings.push(err(`field:${cat.name}.${key}`, `必填不一致:契约 required=true,库里是 false`, '改库字段 required 或改契约'));
403
+ }
404
+ } else {
405
+ /** ③ 库里多出契约外字段(只算本站/本栏目的,公用目录行不算) */
406
+ const scoped = spec.source === 'site' || spec.source === 'category' || spec.builtin === false;
407
+ if (scoped && !declared.size) {
408
+ findings.push(
409
+ err(
410
+ `field:${cat.name}.${key}`,
411
+ `「${cat.name}」有一个契约外字段「${key}」(契约里没声明)`,
412
+ '新增字段必须先改契约再改表单(老板 2026-10-30 的硬规矩)',
413
+ ),
414
+ );
415
+ } else if (!declared.size) {
416
+ /* 契约缺位时不做「多出字段」判断,避免把公用目录当越界 */
417
+ }
418
+ }
419
+ }
420
+
421
+ /** ④ 已存值必须符合字段类型(脏数据是迁移留下的,改不动库也要先说清) */
422
+ if (spec.rawType === 'richtext') return; /* 正文由 platform 存 HTML,不做块校验 */
423
+ details.forEach(detail => {
424
+ const rawValue = valueOf(detail, key);
425
+ if (rawValue === undefined || rawValue === null || rawValue === '') return;
426
+ const stored = storedValueFor(spec, rawValue);
427
+ const issues = validateFieldValue({ ...spec, required: false }, stored);
428
+ issues.slice(0, 1).forEach(message => {
429
+ findings.push(
430
+ warn(
431
+ `content:${cat.name}/${detail.title || detail.id}.${key}`,
432
+ `已存值与类型不符:${message}`,
433
+ '前台会渲染成空或报错;用 content apply 覆盖这一条,或让 CMS 里手工修',
434
+ ),
435
+ );
436
+ });
437
+ });
438
+ });
439
+
440
+ if (rows.length && !fields.size) {
441
+ findings.push(warn(`category:${cat.name}`, `「${cat.name}」有 ${rows.length} 条内容,但一个可用字段都没有`, 'CMS 表单会是空的:给栏目开字段(fieldSetForCategory)'));
442
+ }
443
+ });
444
+ }
445
+
446
+ return dim(def, findings, { note: contract && contract.contractPresent ? '契约 ↔ 库 ↔ 值 三层比对' : '仅库侧白名单' });
447
+ }
448
+
449
+ /** 内容详情里某个字段的现值(真列优先,其次 ext),媒体类还原成 id 供校验 */
450
+ function valueOf(detail, key) {
451
+ if (!detail) return undefined;
452
+ if (key === 'body') return String(detail.body || '');
453
+ if (detail[key] !== undefined && detail[key] !== null) return detail[key];
454
+ const ext = detail.ext && typeof detail.ext === 'object' ? detail.ext : {};
455
+ return ext[key];
456
+ }
457
+
458
+ function storedValueFor(spec, rawValue) {
459
+ if (spec.type === 'gallery' || spec.type === 'file') {
460
+ const list = Array.isArray(rawValue) ? rawValue : [rawValue];
461
+ return list.map(one => (one && typeof one === 'object' ? String(one.id || '') : String(one || ''))).filter(Boolean);
462
+ }
463
+ if (spec.type === 'image' || spec.type === 'video') {
464
+ return rawValue && typeof rawValue === 'object' ? String(rawValue.id || '') : rawValue;
465
+ }
466
+ // 日期:库里的 `published_at` 是 timestamptz,接口回的是完整 ISO(2026-10-30T06:15:52.563+08:00),
467
+ // 契约要求写 YYYY-MM-DD —— 对**已存值**只取日期部分再比,别把服务端自己写的时刻当成脏数据。
468
+ if (spec.type === 'date' && typeof rawValue === 'string' && /^\d{4}-\d{2}-\d{2}/.test(rawValue)) {
469
+ return rawValue.slice(0, 10);
470
+ }
471
+ return rawValue;
472
+ }
473
+
474
+ function dimRequired({ site }) {
475
+ const findings = [];
476
+ const def = dimOf('required');
477
+ if (!site) return dim(def, findings, { applicable: false, note: '没有 --site:必填覆盖率只能对库算' });
478
+
479
+ let published = 0;
480
+ site.byCategory.forEach(({ cat, fields, rows, details }) => {
481
+ if (cat.kind === 'page') {
482
+ const owner = rows[0];
483
+ if (!owner) {
484
+ findings.push(warn(`page:${cat.name}`, `单页「${cat.name}」没有内容行(正文/字段无处落)`, '跑 `wkgeo content apply` 写这个单页,或让服务端 ensurePageContents 补'));
485
+ return;
486
+ }
487
+ const detail = details.get(owner.id);
488
+ if (detail && !String(detail.body || '').trim()) {
489
+ findings.push(warn(`page:${cat.name}`, `单页「${cat.name}」正文为空`, '单页不写正文就是占位页,验收会被打回'));
490
+ }
491
+ return;
492
+ }
493
+ fields.forEach(spec => {
494
+ if (!spec.required || spec.enabled === false) return;
495
+ const missing = [];
496
+ rows.forEach(row => {
497
+ const detail = details.get(row.id);
498
+ if (!detail) return;
499
+ published += 1;
500
+ const rawValue = valueOf(detail, spec.key);
501
+ if (rawValue === undefined || rawValue === null || rawValue === '' || (Array.isArray(rawValue) && !rawValue.length)) {
502
+ missing.push(row.title || row.id);
503
+ }
504
+ });
505
+ if (missing.length) {
506
+ findings.push(
507
+ err(
508
+ `required:${cat.name}.${spec.key}`,
509
+ `必填字段「${spec.label || spec.key}」在 ${missing.length} 条内容上是空的:${missing.slice(0, 3).join('、')}${missing.length > 3 ? '…' : ''}`,
510
+ '补齐这些内容再发布(必填缺字段 = 不通过,前台不该兜底)',
511
+ ),
512
+ );
513
+ }
514
+ });
515
+ });
516
+ return dim(def, findings, { note: `检查 ${site.detailCount} 条内容详情` });
517
+ }
518
+
519
+ function dimMedia({ contract, site }) {
520
+ const findings = [];
521
+ const def = dimOf('media');
522
+ const mediaTypes = new Set(['image', 'gallery', 'file', 'video']);
523
+
524
+ if (contract && contract.contractPresent) {
525
+ contract.columns.forEach(col => {
526
+ col.fields.forEach(field => {
527
+ if (!mediaTypes.has(field.type)) return;
528
+ const rules = field.rules || {};
529
+ const hasSpec = field.imageSpec || rules.maxSizeKb || rules.accept;
530
+ if (!hasSpec) {
531
+ findings.push(
532
+ warn(`契约 ${col.name}.${field.key}`, `媒体字段「${field.label || field.key}」没写规格(尺寸/大小/格式)`, '按契约 §4 写 imageSpec{w,h,ratio,maxKB,formats},A 才知道该产多大'),
533
+ );
534
+ }
535
+ });
536
+ });
537
+ }
538
+
539
+ if (site) {
540
+ site.byCategory.forEach(({ cat, fields }) => {
541
+ fields.forEach((spec, key) => {
542
+ if (!mediaTypes.has(spec.type)) return;
543
+ const rules = spec.rules || {};
544
+ const hasLimit = rules.maxSizeKb || (Array.isArray(rules.accept) && rules.accept.length);
545
+ if (!hasLimit) {
546
+ findings.push(warn(`field:${cat.name}.${key}`, `库里媒体字段「${spec.label || key}」没有大小/格式限制`, '服务端 validateFieldRules 拦不住超大图;补 rules.maxSizeKb / accept'));
547
+ }
548
+ });
549
+ });
550
+ }
551
+ return dim(def, findings, { note: '宽高不校验(老板 2026-10-19 拍板),只查大小/格式/规格声明' });
552
+ }
553
+
554
+ function dimSeo({ contract, site }) {
555
+ const findings = [];
556
+ const def = dimOf('seo');
557
+ if (contract && contract.contractPresent) {
558
+ contract.columns.forEach(col => {
559
+ const seo = col.seo || {};
560
+ if (!seo.title && !seo.description) {
561
+ findings.push(warn(`契约 ${col.name}`, '栏目没写 seo.title / seo.description', '前台 <title>/description 只能靠模板兜,口径就散了'));
562
+ }
563
+ });
564
+ }
565
+ if (site) {
566
+ site.categories.forEach(cat => {
567
+ const hasSeo = String(cat.seo_description || '').trim() || String(cat.description || '').trim();
568
+ if (!hasSeo) findings.push(warn(`category:${cat.name}`, `栏目「${cat.name}」没有 SEO 描述`, '栏目页的 meta description 会空着;在 CMS 里补 seo_description'));
569
+ if (!String(cat.seo_keywords || '').trim()) {
570
+ findings.push(warn(`category:${cat.name}`, `栏目「${cat.name}」没有 SEO 关键词`, '可选,但行业站建议补'));
571
+ }
572
+ });
573
+ site.byCategory.forEach(({ cat, details }) => {
574
+ details.forEach(detail => {
575
+ const title = String(detail.title || '').trim();
576
+ if (title.length > 60) {
577
+ findings.push(warn(`content:${cat.name}/${title.slice(0, 12)}`, `标题 ${title.length} 字(>60 会被搜索结果截断)`, '标题压到 60 字以内,长尾放正文'));
578
+ }
579
+ if (!String(detail.description || '').trim() && !String(detail.body || '').trim()) {
580
+ findings.push(warn(`content:${cat.name}/${title.slice(0, 12)}`, '既没有 description 也没有正文', '前台列表摘要 + 详情页都会空'));
581
+ }
582
+ });
583
+ });
584
+ }
585
+ return dim(def, findings);
586
+ }
587
+
588
+ function dimI18n({ site, templateFiles }) {
589
+ const findings = [];
590
+ const def = dimOf('i18n');
591
+ if (!site) {
592
+ const hasHreflang = (templateFiles || []).some(one => /hreflang|lang\s*=\s*"en"/i.test(one.text || ''));
593
+ if (!hasHreflang) findings.push(warn('模板', '模板里没有 hreflang / 多语言入口', '要做多语言就得给模板留语言切换入口'));
594
+ return dim(def, findings, { applicable: false, note: '没有 --site:多语言只做模板侧检查' });
595
+ }
596
+ /** 栏目树按语言各一棵;这里只能看「当前语言这一棵」,跨语言覆盖要平台侧 langList 才准 */
597
+ const langs = new Set(site.categories.map(one => String(one.language_code || '').trim()).filter(Boolean));
598
+ if (langs.size === 0) {
599
+ findings.push(warn('多语言', '栏目行没有 language_code(老数据),多语言口径无法核对', '服务端现写都带 language_code;老数据等迁移'));
600
+ return dim(def, findings, { applicable: false, note: '缺 language_code,无法核对多语言覆盖' });
601
+ }
602
+ if (site.lang) {
603
+ const offLang = site.categories.filter(one => String(one.language_code || '') !== site.lang);
604
+ if (offLang.length) {
605
+ findings.push(warn('多语言', `${offLang.length} 个栏目不属于语言 ${site.lang}`, '`--lang` 只该看到该语言的树;多了说明服务端按语言过滤没生效'));
606
+ }
607
+ }
608
+ return dim(def, findings, { note: `当前语言 ${site.lang || '(默认)'},${langs.size} 种语言的栏目行` });
609
+ }
610
+
611
+ function dimBoundary({ contract, templateFiles, site }) {
612
+ const findings = [];
613
+ const def = dimOf('boundary');
614
+
615
+ /** ① 前台只读:模板里不能出现写库调用 / 数据库连接串 / 后台接口 */
616
+ const writeRe = /(contentSave|categorySave|fieldSave|INSERT\s+INTO|UPDATE\s+\w+\s+SET|DELETE\s+FROM)/i;
617
+ const dbRe = /(postgres(ql)?:\/\/|tcloudbasegateway|exec-pgsql|supabase|mysql:\/\/)/i;
618
+ (templateFiles || []).forEach(one => {
619
+ if (writeRe.test(one.text || '')) {
620
+ findings.push(err(`模板 ${one.file}`, '模板里出现写库/后台动作字样(前台只读渲染,不许直连写)', '把写入挪回 CMS/CLI;前台只消费渲染结果'));
621
+ }
622
+ if (dbRe.test(one.text || '')) {
623
+ findings.push(err(`模板 ${one.file}`, '模板里出现数据库连接串/网关地址(越界)', '前台任何数据都走 pageRender,不许自带数据通道'));
624
+ }
625
+ });
626
+
627
+ /** ② 模板不得内联业务数据:`columns[].items[]` 是示例,不是内容源 */
628
+ if (contract && contract.contractPresent) {
629
+ const withItems = contract.columns.filter(col => Array.isArray(col.items) && col.items.length);
630
+ if (withItems.length) {
631
+ findings.push(
632
+ warn(
633
+ '契约 columns[].items[]',
634
+ `${withItems.length} 个栏目在模板里带了示例数据(${withItems.map(one => one.name).slice(0, 6).join('、')})`,
635
+ '示例数据只能当「填充样例」;真内容必须入库(content apply),前台渲染只读库',
636
+ ),
637
+ );
638
+ }
639
+ contract.columns.forEach(col => {
640
+ col.fields.forEach(field => {
641
+ const allowed = PLATFORM_OF_CONTRACT[field.type];
642
+ if (field.type && !allowed && field.type !== 'list') {
643
+ findings.push(err(`契约 ${col.name}.${field.key}`, `契约类型「${field.type}」没有平台控件`, '见契约 §3 映射表'));
644
+ }
645
+ });
646
+ });
647
+ }
648
+
649
+ /** ③ CMS 表单字段必须来自契约:库里有、契约没有 = 越界新增 */
650
+ if (site && contract && contract.contractPresent) {
651
+ const declaredByCat = new Map();
652
+ contract.columns.forEach(col => {
653
+ const aliases = [col.slug, col.name, String(col.path || '').replace(/^\/+|\/+$/g, '')]
654
+ .map(one => String(one == null ? '' : one).trim().toLowerCase())
655
+ .filter(Boolean);
656
+ aliases.forEach(alias => declaredByCat.set(alias, new Set(col.fields.map(f => f.key))));
657
+ });
658
+ site.byCategory.forEach(({ cat, fields }) => {
659
+ const key = [cat.slug, cat.name, String(cat.path || '').replace(/^\/+|\/+$/g, '')]
660
+ .map(one => String(one == null ? '' : one).trim().toLowerCase())
661
+ .find(alias => declaredByCat.has(alias));
662
+ if (!key) return;
663
+ const declared = declaredByCat.get(key);
664
+ fields.forEach((spec, fieldKey) => {
665
+ const own = spec.source === 'site' || spec.source === 'category';
666
+ if (own && !declared.has(fieldKey)) {
667
+ findings.push(
668
+ err(
669
+ `boundary:${cat.name}.${fieldKey}`,
670
+ `CMS 表单里有一个契约外字段「${fieldKey}」`,
671
+ '表单字段必须来自契约:先在 contract 的 columns[].fields[] 声明,再 fieldSave 建字段',
672
+ ),
673
+ );
674
+ }
675
+ });
676
+ });
677
+ }
678
+ return dim(def, findings, { note: '前台只读 / 模板不内联数据 / 表单字段来自契约' });
679
+ }
680
+
681
+ function dimClosure({ contract, site, templateFiles }) {
682
+ const findings = [];
683
+ const def = dimOf('closure');
684
+ const htmlFiles = (templateFiles || []).filter(one => /\.html$/i.test(one.file));
685
+ const pages = new Set(htmlFiles.map(one => `/${one.file}`.toLowerCase()));
686
+
687
+ if (contract && contract.contractPresent) {
688
+ contract.columns.forEach(col => {
689
+ const page = String(col.page || 'index').replace(/^\//, '').replace(/\.html$/i, '');
690
+ const exists =
691
+ pages.has(`/pages/${page}.html`.toLowerCase()) ||
692
+ pages.has(`/${page}.html`.toLowerCase()) ||
693
+ pages.has(`/pages/${page}/index.html`.toLowerCase());
694
+ if (!exists) {
695
+ findings.push(
696
+ err(
697
+ `契约 ${col.name}`,
698
+ `栏目声明的页面 /pages/${page}.html 不存在`,
699
+ '栏目必须落到一个真页面;补页面文件或改 columns[].page',
700
+ ),
701
+ );
702
+ }
703
+ });
704
+ }
705
+
706
+ if (site && contract && contract.contractPresent) {
707
+ /** 契约声明的栏目在库里缺列(栏目必须建库) */
708
+ const bySlug = new Map();
709
+ site.categories.forEach(cat => {
710
+ [cat.slug, cat.name, String(cat.path || '').replace(/^\/+|\/+$/g, '')]
711
+ .map(one => String(one == null ? '' : one).trim().toLowerCase())
712
+ .filter(Boolean)
713
+ .forEach(alias => bySlug.set(alias, cat));
714
+ });
715
+ contract.columns.forEach(col => {
716
+ const aliases = [col.slug, col.key, col.name, String(col.path || '').replace(/^\/+|\/+$/g, '')]
717
+ .map(one => String(one == null ? '' : one).trim().toLowerCase())
718
+ .filter(Boolean);
719
+ if (!aliases.some(alias => bySlug.has(alias))) {
720
+ findings.push(
721
+ err(
722
+ `closure:${col.name}`,
723
+ `契约里有栏目「${col.name}」,库里没有对应栏目(栏目必须建库)`,
724
+ '建站时按契约建栏目;A 不能凭空写一个前台才有的栏目',
725
+ ),
726
+ );
727
+ }
728
+ });
729
+ }
730
+
731
+ if (site) {
732
+ const homeish = site.categories.filter(one => ['index', 'home', '/'].includes(String(one.slug || '').toLowerCase()));
733
+ if (!homeish.length) findings.push(err('closure', '站点没有首页栏目(slug=index/home)', '首页栏目必须存在,否则短域首页 404'));
734
+ site.byCategory.forEach(({ cat, rows }) => {
735
+ if (cat.kind === 'channel' && rows.length && !site.categories.some(one => String(one.parent_id || '') === String(cat.id))) {
736
+ findings.push(warn(`closure:${cat.name}`, `栏目「${cat.name}」是 channel 但既没子栏目也没自有内容`, '空壳栏目会出现在导航里;要么补内容,要么收进二级'));
737
+ }
738
+ if (cat.kind === 'list' && !rows.length) {
739
+ findings.push(warn(`closure:${cat.name}`, `列表栏目「${cat.name}」0 条内容`, '前台列表页会空;要么写内容,要么别在导航里露出来'));
740
+ }
741
+ });
742
+ }
743
+ return dim(def, findings, { note: '契约栏目 ↔ 库栏目 ↔ 模板页面 三方闭合' });
744
+ }
745
+
746
+ function dimRender({ contract, templateFiles, site }) {
747
+ const findings = [];
748
+ const def = dimOf('render');
749
+ if (!templateFiles || !templateFiles.length) {
750
+ return dim(def, findings, { applicable: false, note: '没有模板文件:渲染闭合不适用' });
751
+ }
752
+ const vars = extractRenderVars(templateFiles);
753
+ if (!vars.content.size && !vars.contentExt.size && !vars.category.size) {
754
+ findings.push(warn('模板', '模板里没有 `{{ content.* }}` / `{{ category.* }}` 变量(是纯静态页?)', '前台若真不读库,内容就只能写死——与「内容必须入库」冲突'));
755
+ return dim(def, findings);
756
+ }
757
+ if (contract && contract.contractPresent) {
758
+ const declared = new Set();
759
+ contract.columns.forEach(col => col.fields.forEach(field => declared.add(field.key)));
760
+ vars.contentExt.forEach(key => {
761
+ if (!declared.has(key)) {
762
+ findings.push(
763
+ warn(
764
+ `render:content.ext.${key}`,
765
+ `前台渲染读了自定义字段「${key}」,契约里没声明`,
766
+ '要么在 columns[].fields[] 补这个字段并建库字段,要么从模板里去掉这段',
767
+ ),
768
+ );
769
+ }
770
+ });
771
+ vars.content.forEach(key => {
772
+ if (CONTENT_VIEW_KEYS.has(key)) return;
773
+ if (declared.has(key)) return;
774
+ findings.push(warn(`render:content.${key}`, `前台渲染读了 content.${key},但契约/库里都没有这个键`, '补字段或删模板里的这处引用(否则前台渲染为空)'));
775
+ });
776
+ }
777
+ return dim(def, findings, { note: `模板引用 content ${vars.content.size} 键 / ext ${vars.contentExt.size} 键 / category ${vars.category.size} 键` });
778
+ }
779
+
780
+ /* ------------------------------------------------------------------ 命令主体 */
781
+
782
+ function resolveSiteFlag(ctx, flags) {
783
+ const explicit = String(flags.site || '').trim();
784
+ if (explicit) {
785
+ if (!isUuid(explicit)) throw new UsageError(`--site 要站点 uuid(收到:${explicit})`);
786
+ return explicit;
787
+ }
788
+ // `--template` 单独跑 = **离线契约自检**:不去碰本地"当前站点",也不发任何写/读库请求。
789
+ // 否则一次纯模板体检会顺手把本地选中的演示站拉进来,分数被别人的库结构带偏。
790
+ if (String(flags.template || '').trim()) return '';
791
+ const current = ctx.cmsSite();
792
+ return current && current.id ? current.id : '';
793
+ }
794
+
795
+ /**
796
+ * `wkgeo content check [--site <id>] [--template <key>] [--lang <l>] [--json]`
797
+ */
798
+ export async function runContentCheck(ctx, flags = {}) {
799
+ const siteId = resolveSiteFlag(ctx, flags);
800
+ const templateInput = String(flags.template || '').trim();
801
+ if (!siteId && !templateInput) {
802
+ throw new UsageError('要检查什么?加 `--site <站点ID>`、`--template <模板key>`,或两个都给(做契约↔库比对)');
803
+ }
804
+
805
+ const loaded = templateInput ? loadTemplateContract(templateInput) : null;
806
+ const templateFiles = loaded ? readTemplateFiles(loaded.dir) : [];
807
+
808
+ let site = null;
809
+ if (siteId) {
810
+ const call = (action, payload = {}) => ctx.contentCall(action, payload, { siteId });
811
+ site = await readSite(siteId, call, { lang: flags.lang || '', maxDetails: Number(flags.maxDetails || 300) });
812
+ }
813
+
814
+ const context = { contract: loaded ? loaded.contract : null, site, templateFiles };
815
+ const dimensions = [
816
+ dimStructure(context),
817
+ dimTypes(context),
818
+ dimRequired(context),
819
+ dimMedia(context),
820
+ dimSeo(context),
821
+ dimI18n(context),
822
+ dimBoundary(context),
823
+ dimClosure(context),
824
+ dimRender(context),
825
+ ];
826
+
827
+ const score = scoreDimensions(dimensions);
828
+ const findings = [];
829
+ score.dimensions.forEach(one => one.findings.forEach(finding => findings.push({ ...finding, dimension: one.key })));
830
+ const failing = findings.filter(one => one.level === 'error');
831
+
832
+ const result = {
833
+ ok: failing.length === 0,
834
+ siteId: siteId || null,
835
+ template: loaded ? { key: loaded.contract.key || null, dir: loaded.dir, contractPresent: loaded.contract.contractPresent } : null,
836
+ lang: (site && site.lang) || flags.lang || '',
837
+ score,
838
+ findings,
839
+ fixes: findings.map(one => ({ level: one.level, where: one.where, message: one.message, fix: one.fix })),
840
+ stats: {
841
+ categories: site ? site.categories.length : 0,
842
+ contents: site ? [...site.byCategory.values()].reduce((acc, one) => acc + one.rows.length, 0) : 0,
843
+ detailChecked: site ? site.detailCount : 0,
844
+ templateFiles: templateFiles.length,
845
+ },
846
+ };
847
+
848
+ if (failing.length) {
849
+ const lines = failing.slice(0, 30).map(one => ` ✖ [${one.dimension}] ${one.where}:${one.message}`);
850
+ throw new CliError(
851
+ `一致性自检不通过:${failing.length} 处硬问题(得分 ${score.total}/${score.max})`,
852
+ {
853
+ kind: 'contract',
854
+ exitCode: EXIT.ERROR,
855
+ hint: '按 fixes[] 逐条修;四种硬问题(类型不符 / 必填缺 / 契约外字段 / 契约栏目缺库列)一律拦',
856
+ details: result,
857
+ raw: lines.join('\n'),
858
+ },
859
+ );
860
+ }
861
+
862
+ ctx.done(result);
863
+ printHuman(ctx, result);
864
+ return result;
865
+ }
866
+
867
+ function printHuman(ctx, result) {
868
+ const out = ctx.out;
869
+ if (!out) return;
870
+ const { score } = result;
871
+ out.head(`一致性自检:${score.total}/${score.max} 分`);
872
+ score.dimensions.forEach(one => {
873
+ const flag = one.applicable === false ? '—' : `${one.score}/${one.max}`;
874
+ out.line(` ${one.name.padEnd(8, ' ')} ${flag}${one.note ? ` ${one.note}` : ''}`);
875
+ });
876
+ if (result.findings.length) {
877
+ out.line('');
878
+ result.findings.slice(0, 20).forEach(one => {
879
+ const sign = one.level === 'error' ? '✖' : '!';
880
+ out.line(` ${sign} [${one.dimension}] ${one.where}:${one.message}`);
881
+ if (one.fix) out.line(` → ${one.fix}`);
882
+ });
883
+ if (result.findings.length > 20) out.line(` … 还有 ${result.findings.length - 20} 条`);
884
+ }
885
+ out.line('');
886
+ out.ok('通过:没有硬问题(类型/必填/越界字段/栏目缺列)');
887
+ }