@wkgeo/cli 1.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +163 -25
  3. package/SKILL.md +121 -36
  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 -541
  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 +1222 -6
  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/login.mjs +15 -3
  25. package/lib/manifest-apply.mjs +1499 -0
  26. package/lib/manifest-schema.json +476 -0
  27. package/lib/manifest.mjs +1082 -0
  28. package/lib/oauth-urls.mjs +1 -1
  29. package/lib/runtime.mjs +5 -1
  30. package/lib/site-create.mjs +536 -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-publish.mjs +733 -0
  37. package/lib/template-score.mjs +865 -0
  38. package/lib/template-validate.mjs +368 -0
  39. package/lib/template-verify.mjs +434 -0
  40. package/lib/templates-sync.mjs +616 -0
  41. package/package.json +2 -2
@@ -0,0 +1,1082 @@
1
+ /**
2
+ * 建站内容契约 `wkgeo-site-manifest@1` —— 结构定义 + 零依赖校验(task-73)。
3
+ *
4
+ * ## 这个文件为什么存在
5
+ * A(agent)从三来源(模板 / 网址 / 文件)产出的是**内容成品**;平台负责「契约 + 校验 + 落库 + 发布」。
6
+ * 两边之间唯一的对接面就是一份 `site-manifest.json`。所以:
7
+ * * 契约(字段 / 枚举 / 默认值 / 上限)只在这里定义一次,文档 `docs/规范-建站内容契约.md` 与
8
+ * JSON Schema(`cli/lib/manifest-schema.json`,由 `manifestJsonSchema()` 生成)都跟着它走;
9
+ * * **零依赖**:CLI 不引第三方包(见 package.json),所以校验是手写的 —— 不用 ajv。
10
+ * JSON Schema 文件是给外部工具 / 人看的**同一份约束的可移植描述**,真正的判定以本文件为准。
11
+ *
12
+ * ## 两类问题,两种后果(这是本契约最重要的口径)
13
+ * * `errors`(致命)→ 整份 manifest 不可执行:格式/枚举/跨引用(栏目 slug 重复、父栏目不存在、
14
+ * `unfilled` 缺失…)。CLI 直接退出码 2,一条都不写库。
15
+ * * `itemErrors`(单条)→ 只废掉那一条:内容 title 为空、正文文件不存在、素材文件缺失…
16
+ * 其余照常落库,退出码 1,`failed[]` 里带上 `{item, reason}`,修完可以续跑(幂等)。
17
+ * * `warnings` → 不挡执行,但必须让老板看见(例如 `seo.title` 平台没有对应字段)。
18
+ *
19
+ * ## 幂等(第二次 apply 必须全 skipped)
20
+ * 栏目按 slug、内容按 slug(缺省 title)、素材按 **`(sha256, role)`**(task-46;老口径是显示名,
21
+ * 同一份文件换个 key 就会重传)匹配;正文 HTML **不比原文**,因为服务端
22
+ * `sanitizeByEnv` 会改写它 —— 所以 apply 会把「我写进去的正文指纹」记在内容的 `ext._wk_manifest`
23
+ * 里(`{format, body_sha256, applied_at}`),第二次读到同一个指纹就跳过。见 `createApplyEngine()`。
24
+ */
25
+
26
+ import crypto from 'node:crypto';
27
+ import fs from 'node:fs';
28
+ import path from 'node:path';
29
+
30
+ import { ASSET_ROLES, inferAssetRole, normalizeAssetRole } from './asset-role.mjs';
31
+
32
+ /* `ASSET_ROLES` / `inferAssetRole` 从本文件对外也是契约的一部分(文档与测试照着这里写) */
33
+ export { ASSET_ROLES, inferAssetRole, normalizeAssetRole };
34
+
35
+ /* ------------------------------------------------------------------ 常量 */
36
+
37
+ /** 本版 manifest 的唯一版本号;任何字段的增删都要换版本号 */
38
+ export const MANIFEST_FORMAT = 'wkgeo-site-manifest@1';
39
+
40
+ /** 契约里的栏目类型 → 服务端 `cms_category.kind`(`categories save --type` 的映射见文档) */
41
+ export const CATEGORY_TYPES = ['list', 'single', 'channel'];
42
+ export const CATEGORY_TYPE_TO_KIND = Object.freeze({ list: 'list', single: 'page', channel: 'channel' });
43
+ /** 反查:服务端 kind → 契约 type(读回来做 diff 用) */
44
+ export const KIND_TO_CATEGORY_TYPE = Object.freeze({ list: 'list', page: 'single', channel: 'channel' });
45
+
46
+ export const CONTENT_STATUS = ['draft', 'published', 'hidden'];
47
+ /** 素材用途;`logo` 会额外写进站点信息(`siteInfoSave.values.logo`) */
48
+ export const ASSET_USES = ['logo', 'banner', 'cover', 'content', 'download'];
49
+ /** `unfilled[].reason` 的封闭取值 —— 老板要能一眼看出「为什么没填」 */
50
+ export const UNFILLED_REASONS = ['来源缺失', '需老板确认', '版权不明', '平台不支持'];
51
+
52
+ /** 自定义字段类型(与云函数 `allowedFieldTypes` 一字不差,见 content-core.js) */
53
+ export const FIELD_TYPES = [
54
+ 'input',
55
+ 'textarea',
56
+ 'number',
57
+ 'date',
58
+ 'select',
59
+ 'switch',
60
+ 'image',
61
+ 'images',
62
+ 'imageGroup',
63
+ 'file',
64
+ 'richtext',
65
+ 'video',
66
+ ];
67
+
68
+ /** 上限。超了就是契约违规(致命),不是"尽力而为" */
69
+ export const LIMITS = Object.freeze({
70
+ menus: 50,
71
+ menuDepth: 3,
72
+ categories: 200,
73
+ contents: 500,
74
+ assets: 100,
75
+ singles: 50,
76
+ fieldsPerCategory: 30,
77
+ unfilled: 200,
78
+ bodyBytes: 512 * 1024, // 单篇正文 ≤ 512KB(服务端还会再过一遍 sanitize)
79
+ assetBytes: 200 * 1024 * 1024, // 与 `wkgeo assets upload` 的 MAX_UPLOAD_BYTES 对齐
80
+ nameChars: 100,
81
+ titleChars: 200,
82
+ slugChars: 60,
83
+ seoDescriptionChars: 500,
84
+ seoKeywordsChars: 300,
85
+ altChars: 200,
86
+ customFieldKeys: 40,
87
+ });
88
+
89
+ const SLUG_RE = /^[a-z0-9][a-z0-9_-]{0,59}$/;
90
+ const PATH_RE = /^\/[a-z0-9][a-z0-9_/-]*\/$/i;
91
+ const FIELD_KEY_RE = /^[a-zA-Z][a-zA-Z0-9_]{0,39}$/;
92
+ const LANG_RE = /^[a-z]{2}(-[a-zA-Z]{2,4})?$/;
93
+ const UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
94
+
95
+ /* ------------------------------------------------------------------ 小工具 */
96
+
97
+ function isPlainObject(v) {
98
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
99
+ }
100
+
101
+ /** 取字符串并 trim(非字符串一律当空) */
102
+ function text(v) {
103
+ return typeof v === 'string' ? v.trim() : typeof v === 'number' ? String(v) : '';
104
+ }
105
+
106
+ /** 压成一行(报错信息里截断,别把整段正文打到终端) */
107
+ function oneLine(v, max = 160) {
108
+ const s = String(v == null ? '' : v)
109
+ .replace(/\s+/g, ' ')
110
+ .trim();
111
+ if (!s) return '';
112
+ return s.length > max ? `${s.slice(0, max)}…` : s;
113
+ }
114
+
115
+ /** slug 归一:去首尾斜杠、空白转 `-`、小写 —— 与服务端 `handleCategorySave` 的算法一致 */
116
+ export function slugify(v) {
117
+ return String(v == null ? '' : v)
118
+ .trim()
119
+ .replace(/^\/+|\/+$/g, '')
120
+ .replace(/\s+/g, '-')
121
+ .toLowerCase();
122
+ }
123
+
124
+ /** 路径归一:`product` / `/product` / `product/` 都变 `/product/`;空 → `/` */
125
+ export function normalizePath(v) {
126
+ const s = String(v == null ? '' : v)
127
+ .trim()
128
+ .replace(/^\/+|\/+$/g, '');
129
+ return s ? `/${s}/` : '/';
130
+ }
131
+
132
+ /** 子栏目路径:父路径 + 自己 slug(服务端 path 算法同此,见 content-core.js:1908) */
133
+ export function childPath(parentPath, slug) {
134
+ const base = normalizePath(parentPath);
135
+ return base === '/' ? `/${slug}/` : `${base}${slug}/`;
136
+ }
137
+
138
+ function num(v, dflt) {
139
+ const n = Number(v);
140
+ return Number.isFinite(n) ? n : dflt;
141
+ }
142
+
143
+ function bool(v) {
144
+ return v === true || v === 'true' || v === 1 || v === '1';
145
+ }
146
+
147
+ function looksLikeUuid(v) {
148
+ return UUID_RE.test(text(v));
149
+ }
150
+
151
+ /**
152
+ * 素材内容指纹(去重键的一半):读不到就回空串,调用方退回「大小 + 文件名」当键。
153
+ * 用 `io`(`opts.fs`)而不是全局 fs,测试里可以塞假文件系统。
154
+ */
155
+ function sha256Of(io, abs) {
156
+ try {
157
+ return crypto.createHash('sha256').update(io.readFileSync(abs)).digest('hex');
158
+ } catch {
159
+ return '';
160
+ }
161
+ }
162
+
163
+ /** `parent` 既认 slug 也认 path(`/product/` → `product`)—— A 写哪种都别卡它 */
164
+ function parentSlugOf(v) {
165
+ const s = text(v);
166
+ if (!s) return '';
167
+ const seg = s.replace(/^\/+|\/+$/g, '').split('/').filter(Boolean);
168
+ return slugify(seg.length ? seg[seg.length - 1] : '');
169
+ }
170
+
171
+ /* ------------------------------------------------------------------ 校验主入口 */
172
+
173
+ /**
174
+ * 校验并归一 manifest。
175
+ *
176
+ * @param {any} doc `JSON.parse` 之后的原始对象
177
+ * @param {{baseDir?:string, fs?:typeof fs}} [opts] `baseDir` = manifest 所在目录(`bodyFile` / `assets[].path` 的相对基准)
178
+ * @returns {{manifest:object|null, errors:Array<{path:string,message:string}>,
179
+ * itemErrors:Array<{item:string,reason:string}>, warnings:Array<{path:string,message:string}>}}
180
+ */
181
+ export function validateManifest(doc, opts = {}) {
182
+ const baseDir = path.resolve(opts.baseDir || process.cwd());
183
+ const io = opts.fs || fs;
184
+ const errors = [];
185
+ const itemErrors = [];
186
+ const warnings = [];
187
+ const fail = (at, message) => errors.push({ path: at, message });
188
+ const bad = (item, reason) => itemErrors.push({ item, reason });
189
+ const warn = (at, message) => warnings.push({ path: at, message });
190
+
191
+ if (!isPlainObject(doc)) {
192
+ fail('$', 'manifest 顶层必须是一个 JSON 对象(形如 {"_format":"wkgeo-site-manifest@1", …})');
193
+ return { manifest: null, errors, itemErrors, warnings };
194
+ }
195
+
196
+ /* ── 0. 版本号:先认它,不认就没什么好谈的 */
197
+ const format = text(doc._format);
198
+ if (!format) {
199
+ fail('_format', `缺少 _format —— 本版必须写 "${MANIFEST_FORMAT}"`);
200
+ } else if (format !== MANIFEST_FORMAT) {
201
+ fail('_format', `版本不认识:"${oneLine(format, 40)}"(本版只认 "${MANIFEST_FORMAT}")`);
202
+ }
203
+ const KNOWN_TOP = new Set([
204
+ '_format',
205
+ '_source',
206
+ '_note',
207
+ 'site',
208
+ 'menus',
209
+ 'categories',
210
+ 'contents',
211
+ 'assets',
212
+ 'singles',
213
+ 'unfilled',
214
+ 'buildMode',
215
+ ]);
216
+ for (const key of Object.keys(doc)) {
217
+ if (!KNOWN_TOP.has(key) && !key.startsWith('_')) {
218
+ warn(key, `未知顶层字段 "${key}"(已忽略;契约字段见 docs/规范-建站内容契约.md)`);
219
+ }
220
+ }
221
+
222
+ /* ── 1. site */
223
+ const siteIn = isPlainObject(doc.site) ? doc.site : null;
224
+ const site = { name: '', lang: '', templateKey: '' };
225
+ if (!siteIn) {
226
+ fail('site', '缺少 site 对象(至少要 {name, lang})');
227
+ } else {
228
+ site.name = text(siteIn.name);
229
+ site.lang = text(siteIn.lang);
230
+ site.templateKey = text(siteIn.templateKey);
231
+ /**
232
+ * task-95:建站模式(顶层 `buildMode` 或 `site.buildMode` 都认;默认 optimize)。
233
+ * 只影响「原样复制 / 优化修改」这一个选择,**不含任何必含范围勾选**。
234
+ */
235
+ site.buildMode = text(siteIn.buildMode != null ? siteIn.buildMode : doc.buildMode);
236
+ if (site.buildMode && site.buildMode !== 'origin_copy' && site.buildMode !== 'optimize') {
237
+ warn('buildMode', `不认识的建站模式「${site.buildMode}」(只认 origin_copy / optimize,已按 optimize 处理)`);
238
+ site.buildMode = '';
239
+ }
240
+ if (!site.name) fail('site.name', '站点名必填(用来核对 --site 指到的站对不对)');
241
+ else if (site.name.length > LIMITS.nameChars) fail('site.name', `站点名超长:${site.name.length} > ${LIMITS.nameChars}`);
242
+ if (!site.lang) fail('site.lang', '语言必填(如 zh-CN / en)');
243
+ else if (!LANG_RE.test(site.lang)) fail('site.lang', `语言格式不对:"${site.lang}"(形如 zh-CN / en)`);
244
+ if (site.templateKey && !/^[a-z0-9][a-z0-9_-]{0,60}$/.test(site.templateKey)) {
245
+ fail('site.templateKey', `模板 key 格式不对:"${site.templateKey}"`);
246
+ }
247
+ }
248
+
249
+ /* ── 2. assets(先做:内容会引用素材 key) */
250
+ const assets = [];
251
+ const assetByKey = new Map();
252
+ const assetByName = new Map();
253
+ if (doc.assets != null && !Array.isArray(doc.assets)) fail('assets', 'assets 必须是数组');
254
+ const assetsIn = Array.isArray(doc.assets) ? doc.assets : [];
255
+ if (assetsIn.length > LIMITS.assets) fail('assets', `素材过多:${assetsIn.length} > 上限 ${LIMITS.assets}`);
256
+ assetsIn.forEach((raw, i) => {
257
+ const at = `assets[${i}]`;
258
+ if (!isPlainObject(raw)) {
259
+ fail(at, '素材必须是对象 {key?, path, use, alt?}');
260
+ return;
261
+ }
262
+ const rel = text(raw.path);
263
+ if (!rel) {
264
+ bad(`asset#${i}`, '缺少 path(素材在本地的相对路径)');
265
+ return;
266
+ }
267
+ const abs = path.resolve(baseDir, rel);
268
+ let st = null;
269
+ try {
270
+ st = io.statSync(abs);
271
+ } catch {
272
+ st = null;
273
+ }
274
+ const label = oneLine(rel, 60);
275
+ if (!st || !st.isFile()) {
276
+ bad(`asset:${label}`, `素材文件不存在:${abs}`);
277
+ return;
278
+ }
279
+ if (st.size > LIMITS.assetBytes) {
280
+ bad(`asset:${label}`, `素材超过单文件上限 ${LIMITS.assetBytes} 字节:${st.size}`);
281
+ return;
282
+ }
283
+ const use = text(raw.use) || 'content';
284
+ if (!ASSET_USES.includes(use)) {
285
+ fail(`${at}.use`, `use 只能是 ${ASSET_USES.join(' / ')},收到 "${use}"`);
286
+ }
287
+ /* 角色:显式给了就听显式的,否则按扩展名推断(.css→css、.js→js、图片→image、其余→file) */
288
+ const roleRes = normalizeAssetRole(text(raw.role), rel);
289
+ if (roleRes.error) {
290
+ fail(`${at}.role`, roleRes.error);
291
+ return;
292
+ }
293
+ const role = roleRes.role;
294
+ const explicitKey = text(raw.key);
295
+ const baseKey = slugify(explicitKey || path.basename(rel).replace(/\.[^.]+$/, '')) || `asset-${i}`;
296
+ /* 显示名:给了 alt/name 就用它,否则回落成 key(key 唯一 ⇒ 回落名也唯一,不会自己撞自己) */
297
+ const nameGiven = oneLine(text(raw.alt) || text(raw.name), LIMITS.altChars);
298
+ /* 去重键:同一份文件(同 sha256)+ 同一个 role 才算同一个素材 */
299
+ const sha256 = sha256Of(io, abs);
300
+ const digest = `${sha256 || `size:${st.size}:${path.basename(rel)}`}:${role}`;
301
+ /* key 撞车:显式给了 key 就是写错了(报错);隐式 key 撞车多半是 `site.css` / `site.js`
302
+ 这种同名不同扩展,用扩展名区分开,别让一个 assets/ 目录直接卡住。 */
303
+ let key = baseKey;
304
+ if (assetByKey.has(key)) {
305
+ const prev = assetByKey.get(key);
306
+ const prevByName = nameGiven ? assetByName.get(nameGiven.toLowerCase()) : null;
307
+ const willMerge = Boolean(prevByName && prevByName.digest === digest);
308
+ if (!willMerge) {
309
+ if (explicitKey) {
310
+ fail(`${at}.key`, `素材 key 重复:"${key}"(与 assets[${prev.index}] 相同)—— 换一个 key,或删掉重复声明`);
311
+ return;
312
+ }
313
+ const ext = (path.extname(rel) || '').replace(/^\./, '').toLowerCase() || 'file';
314
+ const cands = [`${baseKey}-${ext}`, ...Array.from({ length: 50 }, (_, n) => `${baseKey}-${ext}-${n + 2}`)];
315
+ key = cands.map((one) => slugify(one)).find((one) => one && !assetByKey.has(one)) || '';
316
+ if (!key) {
317
+ fail(`${at}.key`, `素材 key 撞车太多次:"${baseKey}" —— 显式给每条素材一个 key`);
318
+ return;
319
+ }
320
+ warn(`${at}.key`, `key "${baseKey}" 已被 assets[${prev.index}] 用掉,这条改用 "${key}"(也可以用 key 显式指定)`);
321
+ }
322
+ }
323
+ const displayName = nameGiven || key;
324
+ const sameName = nameGiven ? assetByName.get(displayName.toLowerCase()) : null;
325
+ if (sameName && sameName.digest !== digest) {
326
+ fail(
327
+ `${at}`,
328
+ `素材显示名重复:"${displayName}",但文件内容或角色不同(已有 role=${sameName.role})—— ` +
329
+ 'apply 靠显示名认领已有素材,重名会串到别的素材;给其中一条换个 alt/name',
330
+ );
331
+ return;
332
+ }
333
+ if (sameName) {
334
+ /* 同一份文件换个 key 再声明一次:合并成一条素材,旧/新 key 都指向它 */
335
+ if (!assetByKey.has(key)) {
336
+ assetByKey.set(key, sameName);
337
+ if (!sameName.aliases.includes(key)) sameName.aliases.push(key);
338
+ }
339
+ warn(
340
+ `${at}`,
341
+ `与 assets[${sameName.index}] 是同一份文件(sha256 相同、role 同为 ${role}):合并成一条素材,key "${key}" 记为别名`,
342
+ );
343
+ return;
344
+ }
345
+ const row = {
346
+ index: i,
347
+ key,
348
+ name: displayName,
349
+ use,
350
+ role,
351
+ sha256: sha256 || '',
352
+ digest,
353
+ /** 同一份文件 / 同一条素材的其它 key(contents 的 attachments / cover 用哪个都行) */
354
+ aliases: [],
355
+ alt: text(raw.alt),
356
+ path: abs,
357
+ relPath: rel,
358
+ bytes: st.size,
359
+ at,
360
+ };
361
+ assetByKey.set(key, row);
362
+ assetByName.set(displayName.toLowerCase(), row);
363
+ assets.push(row);
364
+ if (use !== 'download' && !text(raw.alt)) {
365
+ warn(`${at}.alt`, `图片素材建议给 alt("${label}" 没有)—— SEO 与无障碍都要用`);
366
+ }
367
+ });
368
+ /* 同一份文件被当成两种角色(既 css 又 image):各登记一次,但要说一声,别让人以为去重没生效 */
369
+ const rolesBySha = new Map();
370
+ for (const one of assets) {
371
+ if (!one.sha256) continue;
372
+ const set = rolesBySha.get(one.sha256) || new Set();
373
+ set.add(one.role);
374
+ rolesBySha.set(one.sha256, set);
375
+ }
376
+ for (const [, roles] of rolesBySha) {
377
+ if (roles.size > 1) {
378
+ warn(
379
+ 'assets',
380
+ `同一份文件被声明成多种角色(${[...roles].join(' / ')}):会各登记一条素材(去重键是 sha256 + role,不是只看内容)`,
381
+ );
382
+ break;
383
+ }
384
+ }
385
+
386
+ /* ── 3. categories(先收集,再算 path / 继承 type) */
387
+ const catsIn = Array.isArray(doc.categories) ? doc.categories : [];
388
+ if (doc.categories != null && !Array.isArray(doc.categories)) fail('categories', 'categories 必须是数组');
389
+ if (catsIn.length > LIMITS.categories) fail('categories', `栏目过多:${catsIn.length} > 上限 ${LIMITS.categories}`);
390
+ const categories = [];
391
+ const catBySlug = new Map();
392
+ catsIn.forEach((raw, i) => {
393
+ const at = `categories[${i}]`;
394
+ if (!isPlainObject(raw)) {
395
+ fail(at, '栏目必须是对象');
396
+ return;
397
+ }
398
+ const slug = slugify(raw.slug);
399
+ if (!slug) {
400
+ fail(`${at}.slug`, '缺少 slug');
401
+ return;
402
+ }
403
+ if (!SLUG_RE.test(slug)) {
404
+ fail(`${at}.slug`, `slug 只能是小写字母 / 数字 / 下划线 / 连字符且 ≤ ${LIMITS.slugChars} 字:"${slug}"`);
405
+ return;
406
+ }
407
+ if (catBySlug.has(slug)) {
408
+ fail(`${at}.slug`, `栏目 slug 重复:"${slug}"(与 categories[${catBySlug.get(slug).index}] 相同)`);
409
+ return;
410
+ }
411
+ const name = text(raw.name);
412
+ if (!name) fail(`${at}.name`, '栏目名必填');
413
+ else if (name.length > LIMITS.nameChars) fail(`${at}.name`, `栏目名超长:${name.length} > ${LIMITS.nameChars}`);
414
+ const type = text(raw.type) || 'list';
415
+ if (!CATEGORY_TYPES.includes(type)) {
416
+ fail(`${at}.type`, `type 只能是 ${CATEGORY_TYPES.join(' / ')},收到 "${type}"`);
417
+ }
418
+ if (raw.sort != null && !Number.isFinite(Number(raw.sort))) fail(`${at}.sort`, `sort 必须是数字,收到 "${raw.sort}"`);
419
+ const templateFile = text(raw.templateFile);
420
+ if (templateFile && !/\.html$/i.test(templateFile)) {
421
+ fail(`${at}.templateFile`, `模板文件必须是本站已有的 .html(如 list.html),收到 "${templateFile}"`);
422
+ }
423
+ const seoDescription = text(raw.seoDescription ?? (isPlainObject(raw.seo) ? raw.seo.description : ''));
424
+ const seoKeywords = text(raw.seoKeywords ?? (isPlainObject(raw.seo) ? raw.seo.keywords : ''));
425
+ if (seoDescription.length > LIMITS.seoDescriptionChars) {
426
+ fail(`${at}.seoDescription`, `栏目描述超长:${seoDescription.length} > ${LIMITS.seoDescriptionChars}`);
427
+ }
428
+ if (seoKeywords.length > LIMITS.seoKeywordsChars) {
429
+ fail(`${at}.seoKeywords`, `栏目关键词超长:${seoKeywords.length} > ${LIMITS.seoKeywordsChars}`);
430
+ }
431
+ const declaredPath = text(raw.path);
432
+ if (declaredPath && !PATH_RE.test(declaredPath)) {
433
+ fail(`${at}.path`, `path 形如 "/product/"(前后都有斜杠),收到 "${declaredPath}"`);
434
+ }
435
+
436
+ /* fields:栏目自己的自定义字段 */
437
+ const fields = [];
438
+ const fieldKeys = new Set();
439
+ if (raw.fields != null && !Array.isArray(raw.fields)) fail(`${at}.fields`, 'fields 必须是数组');
440
+ const fieldsIn = Array.isArray(raw.fields) ? raw.fields : [];
441
+ if (fieldsIn.length > LIMITS.fieldsPerCategory) {
442
+ fail(`${at}.fields`, `字段过多:${fieldsIn.length} > 上限 ${LIMITS.fieldsPerCategory}`);
443
+ }
444
+ fieldsIn.forEach((fr, fi) => {
445
+ const fat = `${at}.fields[${fi}]`;
446
+ if (!isPlainObject(fr)) {
447
+ fail(fat, '字段必须是对象 {key, label, type}');
448
+ return;
449
+ }
450
+ const key = text(fr.key);
451
+ if (!FIELD_KEY_RE.test(key)) {
452
+ fail(`${fat}.key`, `字段 key 必须是字母开头的字母/数字/下划线(≤40 字),收到 "${key}"`);
453
+ return;
454
+ }
455
+ if (fieldKeys.has(key)) {
456
+ fail(`${fat}.key`, `字段 key 在本栏目重复:"${key}"`);
457
+ return;
458
+ }
459
+ fieldKeys.add(key);
460
+ const ftype = text(fr.type) || 'input';
461
+ if (!FIELD_TYPES.includes(ftype)) {
462
+ fail(`${fat}.type`, `字段类型只能是 ${FIELD_TYPES.join(' / ')},收到 "${ftype}"`);
463
+ }
464
+ fields.push({
465
+ index: fi,
466
+ key,
467
+ label: oneLine(text(fr.label) || key, LIMITS.nameChars),
468
+ type: ftype,
469
+ required: bool(fr.required),
470
+ options: isPlainObject(fr.options) || Array.isArray(fr.options) ? fr.options : null,
471
+ sort: num(fr.sort, fi * 10),
472
+ formGroup: text(fr.formGroup) || '',
473
+ at: fat,
474
+ });
475
+ });
476
+
477
+ const row = {
478
+ index: i,
479
+ slug,
480
+ name,
481
+ type,
482
+ kind: CATEGORY_TYPE_TO_KIND[type] || 'list',
483
+ parent: parentSlugOf(raw.parent ?? raw.parentSlug),
484
+ sort: num(raw.sort, i * 10),
485
+ templateFile,
486
+ seoDescription,
487
+ seoKeywords,
488
+ description: text(raw.description),
489
+ fields,
490
+ declaredPath: declaredPath ? normalizePath(declaredPath) : '',
491
+ path: '',
492
+ level: 0,
493
+ at,
494
+ };
495
+ catBySlug.set(slug, row);
496
+ categories.push(row);
497
+ });
498
+
499
+ /* path / level / 子栏目 type 继承(服务端:kind 只有一级能定,子栏目继承父) */
500
+ const resolved = new Set();
501
+ let progress = true;
502
+ while (progress) {
503
+ progress = false;
504
+ for (const row of categories) {
505
+ if (resolved.has(row.slug)) continue;
506
+ if (!row.parent) {
507
+ row.path = `/${row.slug}/`;
508
+ row.level = 1;
509
+ resolved.add(row.slug);
510
+ progress = true;
511
+ continue;
512
+ }
513
+ const parent = catBySlug.get(row.parent);
514
+ if (!parent || !resolved.has(parent.slug)) continue;
515
+ row.path = childPath(parent.path, row.slug);
516
+ row.level = parent.level + 1;
517
+ if (row.type !== parent.type) {
518
+ warn(
519
+ `${row.at}.type`,
520
+ `子栏目继承父栏目类型:父「${parent.slug}」是 ${parent.type},这里写的 ${row.type} 不生效(服务端同样忽略)`,
521
+ );
522
+ row.type = parent.type;
523
+ row.kind = CATEGORY_TYPE_TO_KIND[row.type];
524
+ }
525
+ resolved.add(row.slug);
526
+ progress = true;
527
+ }
528
+ }
529
+ for (const row of categories) {
530
+ if (resolved.has(row.slug)) {
531
+ if (row.declaredPath && row.declaredPath !== row.path) {
532
+ fail(`${row.at}.path`, `path 与 slug/层级算出来的不一致:声明 "${row.declaredPath}",按契约应为 "${row.path}"`);
533
+ }
534
+ row.path = row.path || row.declaredPath;
535
+ continue;
536
+ }
537
+ /* 没算出来:父栏目不在 manifest 里(运行时按站点已有栏目解析),或者父链有环 */
538
+ if (catBySlug.has(row.parent)) {
539
+ fail(`${row.at}.parent`, `父栏目「${row.parent}」形成环(顺着 parent 绕回自己),无法计算 path`);
540
+ } else {
541
+ warn(
542
+ `${row.at}.parent`,
543
+ `父栏目「${row.parent}」不在 manifest 里 —— 运行时按站点已有栏目解析;解析不到会直接失败(退出码 2)`,
544
+ );
545
+ row.path = row.declaredPath;
546
+ }
547
+ }
548
+
549
+ /* ── 4. contents */
550
+ const contents = [];
551
+ const contentKeys = new Set();
552
+ const seoTitleWarned = new Set();
553
+ if (doc.contents != null && !Array.isArray(doc.contents)) fail('contents', 'contents 必须是数组');
554
+ const contentsIn = Array.isArray(doc.contents) ? doc.contents : [];
555
+ if (contentsIn.length > LIMITS.contents) fail('contents', `内容过多:${contentsIn.length} > 上限 ${LIMITS.contents}`);
556
+ contentsIn.forEach((raw, i) => {
557
+ const at = `contents[${i}]`;
558
+ if (!isPlainObject(raw)) {
559
+ fail(at, '内容必须是对象');
560
+ return;
561
+ }
562
+ const one = readContentLike(raw, at, { defaultStatus: 'published', warn, fail, bad, assetByKey, baseDir, io, seoTitleWarned });
563
+ if (!one) return;
564
+ const itemKey = `content:${one.categorySlug}/${one.slug || one.title || `#${i}`}`;
565
+ one.item = itemKey;
566
+ one.index = i;
567
+ one.at = at;
568
+ if (contentKeys.has(itemKey.toLowerCase())) {
569
+ bad(itemKey, '同一栏目下 slug(或缺省时的标题)重复 —— 第二次 apply 会认错条目');
570
+ return;
571
+ }
572
+ contentKeys.add(itemKey.toLowerCase());
573
+ contents.push(one);
574
+ });
575
+
576
+ /* ── 5. singles(单页:绑定一个 single 类型栏目,页内只有一条内容) */
577
+ const singles = [];
578
+ const singleKeys = new Set();
579
+ if (doc.singles != null && !Array.isArray(doc.singles)) fail('singles', 'singles 必须是数组');
580
+ const singlesIn = Array.isArray(doc.singles) ? doc.singles : [];
581
+ if (singlesIn.length > LIMITS.singles) fail('singles', `单页过多:${singlesIn.length} > 上限 ${LIMITS.singles}`);
582
+ singlesIn.forEach((raw, i) => {
583
+ const at = `singles[${i}]`;
584
+ if (!isPlainObject(raw)) {
585
+ fail(at, '单页必须是对象');
586
+ return;
587
+ }
588
+ const one = readContentLike(raw, at, { defaultStatus: 'published', warn, fail, bad, assetByKey, baseDir, io, seoTitleWarned });
589
+ if (!one) return;
590
+ const bound = catBySlug.get(one.categorySlug);
591
+ if (bound && bound.type !== 'single') {
592
+ fail(
593
+ `${at}.categorySlug`,
594
+ `栏目「${one.categorySlug}」在 manifest 里是 ${bound.type} 类型;单页只能绑 single 栏目`,
595
+ );
596
+ return;
597
+ }
598
+ if (!bound) {
599
+ warn(`${at}.categorySlug`, `栏目「${one.categorySlug}」不在 manifest 里 —— 运行时要求站点上已有该 slug 的 single 栏目`);
600
+ }
601
+ const itemKey = `single:${one.categorySlug}`;
602
+ if (singleKeys.has(itemKey)) {
603
+ bad(itemKey, '同一个 single 栏目绑了两条单页内容');
604
+ return;
605
+ }
606
+ singleKeys.add(itemKey);
607
+ one.item = itemKey;
608
+ one.index = i;
609
+ one.at = at;
610
+ one.title = one.title || (bound ? bound.name : '');
611
+ if (!one.title) bad(itemKey, 'title 为空(单页内容标题必填,服务端会 400)');
612
+ singles.push(one);
613
+ });
614
+
615
+ /* ── 6. menus(导航:只认 path,落地时按 path 找栏目) */
616
+ const menus = [];
617
+ const menuPaths = new Set();
618
+ if (doc.menus != null && !Array.isArray(doc.menus)) fail('menus', 'menus 必须是数组');
619
+ const menusIn = Array.isArray(doc.menus) ? doc.menus : [];
620
+ if (menusIn.length > LIMITS.menus) fail('menus', `导航项过多:${menusIn.length} > 上限 ${LIMITS.menus}`);
621
+ const walkMenus = (list, depth, prefix) => {
622
+ const out = [];
623
+ list.forEach((raw, i) => {
624
+ const at = `${prefix}[${i}]`;
625
+ if (!isPlainObject(raw)) {
626
+ fail(at, '导航项必须是对象 {label, path}');
627
+ return;
628
+ }
629
+ if (depth > LIMITS.menuDepth) {
630
+ fail(at, `导航最多 ${LIMITS.menuDepth} 级(服务端限制)`);
631
+ return;
632
+ }
633
+ const label = text(raw.label);
634
+ if (!label) fail(`${at}.label`, '导航显示名必填');
635
+ const rawPath = text(raw.path);
636
+ let p = '';
637
+ if (!rawPath) {
638
+ fail(`${at}.path`, '导航项必须给 path(如 "/product/"),不允许只有名字 —— 猜路径就是错');
639
+ } else if (!PATH_RE.test(rawPath)) {
640
+ fail(`${at}.path`, `path 形如 "/product/",收到 "${rawPath}"`);
641
+ } else {
642
+ p = normalizePath(rawPath);
643
+ if (menuPaths.has(p)) fail(`${at}.path`, `菜单 path 重复:"${p}"`);
644
+ menuPaths.add(p);
645
+ }
646
+ const childrenIn = Array.isArray(raw.children) ? raw.children : [];
647
+ const children = childrenIn.length ? walkMenus(childrenIn, depth + 1, `${at}.children`) : [];
648
+ out.push({
649
+ index: i,
650
+ label: oneLine(label, LIMITS.nameChars),
651
+ path: p,
652
+ sort: num(raw.sort, i * 10),
653
+ children,
654
+ at,
655
+ });
656
+ });
657
+ return out;
658
+ };
659
+ if (menusIn.length) menus.push(...walkMenus(menusIn, 1, 'menus'));
660
+
661
+ /* ── 7. unfilled(必填:没填的要说清楚,缺这个字段整份不合格) */
662
+ const unfilled = [];
663
+ if (!Array.isArray(doc.unfilled)) {
664
+ fail('unfilled', '缺少 unfilled(必填)—— 没填的项逐条写清 item + reason;全填齐了就写 []');
665
+ } else {
666
+ if (doc.unfilled.length > LIMITS.unfilled) {
667
+ fail('unfilled', `未填充项过多:${doc.unfilled.length} > 上限 ${LIMITS.unfilled}`);
668
+ }
669
+ doc.unfilled.forEach((raw, i) => {
670
+ const at = `unfilled[${i}]`;
671
+ if (!isPlainObject(raw)) {
672
+ fail(at, '未填充项必须是对象 {item, reason, detail?}');
673
+ return;
674
+ }
675
+ const item = text(raw.item);
676
+ const reason = text(raw.reason);
677
+ if (!item) fail(`${at}.item`, 'item 必填(写清哪个位置没填,如 "categories[2].seoDescription")');
678
+ if (!reason) fail(`${at}.reason`, `reason 必填,取值 ${UNFILLED_REASONS.join(' / ')}(可以补 detail 说明)`);
679
+ else if (!UNFILLED_REASONS.includes(reason)) {
680
+ fail(`${at}.reason`, `reason 只能是 ${UNFILLED_REASONS.join(' / ')},收到 "${oneLine(reason, 20)}"`);
681
+ }
682
+ unfilled.push({ index: i, item: oneLine(item, 200), reason, detail: text(raw.detail), at });
683
+ });
684
+ }
685
+
686
+ /* ── 8. 数量上限之外的整体性检查 */
687
+ if (!categories.length && !singles.length && !ASSETS_ONLY(assets) && !unfilled.length) {
688
+ warn('$', '这份 manifest 没带栏目 / 内容 / 素材,apply 只会校验,不会写任何东西');
689
+ }
690
+ const counts = {
691
+ menus: countMenus(menus),
692
+ categories: categories.length,
693
+ contents: contents.length,
694
+ assets: assets.length,
695
+ singles: singles.length,
696
+ unfilled: unfilled.length,
697
+ };
698
+
699
+ const manifest = {
700
+ format: MANIFEST_FORMAT,
701
+ baseDir,
702
+ source: isPlainObject(doc._source) ? doc._source : {},
703
+ note: text(doc._note),
704
+ site,
705
+ menus,
706
+ categories,
707
+ contents,
708
+ assets,
709
+ singles,
710
+ unfilled,
711
+ counts,
712
+ /* 单条失败(itemErrors)的条目 key,运行时直接跳过执行并记 failed */
713
+ brokenItems: new Set(itemErrors.map((one) => one.item)),
714
+ };
715
+
716
+ return { manifest, errors, itemErrors, warnings };
717
+ }
718
+
719
+ /** 只有素材、没有栏目/单页 —— 也算一次有效(比如只补品牌图) */
720
+ function ASSETS_ONLY(assets) {
721
+ return assets.length > 0;
722
+ }
723
+
724
+ function countMenus(menus) {
725
+ let n = 0;
726
+ for (const one of menus) {
727
+ n += 1 + countMenus(one.children || []);
728
+ }
729
+ return n;
730
+ }
731
+
732
+ /**
733
+ * `contents[]` 与 `singles[]` 共用的形状(单页就是"绑死在栏目上的那一条内容")。
734
+ * 返回 `null` 表示形状坏到没法继续(已记 fatal)。
735
+ */
736
+ function readContentLike(raw, at, env) {
737
+ const { warn, fail, bad, assetByKey, baseDir, io, seoTitleWarned, defaultStatus } = env;
738
+ const categorySlug = slugify(raw.categorySlug ?? raw.category);
739
+ if (!categorySlug) {
740
+ fail(`${at}.categorySlug`, '缺少 categorySlug(内容必须挂在栏目下)');
741
+ return null;
742
+ }
743
+ const title = oneLine(text(raw.title), LIMITS.titleChars + 40);
744
+ const slugRaw = text(raw.slug).replace(/^\/+|\/+$/g, '');
745
+ let slug = '';
746
+ if (slugRaw) {
747
+ if (/\s/.test(slugRaw)) fail(`${at}.slug`, `slug 不能含空格:"${slugRaw}"`);
748
+ else if (slugRaw.length > LIMITS.slugChars) fail(`${at}.slug`, `slug 超长:${slugRaw.length} > ${LIMITS.slugChars}`);
749
+ else slug = slugRaw.toLowerCase();
750
+ }
751
+ const itemKey = `content:${categorySlug}/${slug || title || '?'}`;
752
+
753
+ /* title:空 → 单条失败(不是整份失败),这样其余条目照常落库 */
754
+ if (!title) bad(itemKey, 'title 为空(内容标题必填,服务端会 400)');
755
+ else if (text(raw.title).length > LIMITS.titleChars) {
756
+ bad(itemKey, `title 超长:${text(raw.title).length} > ${LIMITS.titleChars}`);
757
+ }
758
+
759
+ const status = text(raw.status) || defaultStatus;
760
+ if (!CONTENT_STATUS.includes(status)) bad(itemKey, `status 只能是 ${CONTENT_STATUS.join(' / ')},收到 "${status}"`);
761
+
762
+ const seo = isPlainObject(raw.seo) ? raw.seo : {};
763
+ const seoTitle = text(seo.title);
764
+ const description = text(seo.description ?? raw.description);
765
+ const keywords = text(seo.keywords ?? raw.keywords);
766
+ if (description.length > LIMITS.seoDescriptionChars) {
767
+ bad(itemKey, `seo.description 超长:${description.length} > ${LIMITS.seoDescriptionChars}`);
768
+ }
769
+ if (keywords.length > LIMITS.seoKeywordsChars) {
770
+ bad(itemKey, `seo.keywords 超长:${keywords.length} > ${LIMITS.seoKeywordsChars}`);
771
+ }
772
+ if (seoTitle && !seoTitleWarned.has('seo.title')) {
773
+ seoTitleWarned.add('seo.title');
774
+ warn(
775
+ `${at}.seo.title`,
776
+ '平台没有独立的 seo_title 字段(页面 <title> 取内容 title)—— seo.title 只做校验与提示,不会入库',
777
+ );
778
+ }
779
+ if (seoTitle.length > LIMITS.titleChars) bad(itemKey, `seo.title 超长:${seoTitle.length} > ${LIMITS.titleChars}`);
780
+
781
+ /* 正文:bodyFile 或 body,二选一 */
782
+ const bodyFile = text(raw.bodyFile);
783
+ const bodyInline = typeof raw.body === 'string' ? raw.body : '';
784
+ if (bodyFile && bodyInline) fail(`${at}`, 'bodyFile 与 body 只能二选一(正文来源要唯一)');
785
+ let bodyPath = '';
786
+ let bodyBytes = 0;
787
+ if (bodyFile) {
788
+ bodyPath = path.resolve(baseDir, bodyFile);
789
+ let st = null;
790
+ try {
791
+ st = io.statSync(bodyPath);
792
+ } catch {
793
+ st = null;
794
+ }
795
+ if (!st || !st.isFile()) {
796
+ bad(itemKey, `正文文件不存在:${bodyPath}`);
797
+ bodyPath = '';
798
+ } else if (st.size > LIMITS.bodyBytes) {
799
+ bad(itemKey, `正文超过单篇上限 ${LIMITS.bodyBytes} 字节:${st.size}`);
800
+ bodyPath = '';
801
+ } else {
802
+ bodyBytes = st.size;
803
+ }
804
+ }
805
+ if (bodyInline && Buffer.byteLength(bodyInline, 'utf8') > LIMITS.bodyBytes) {
806
+ bad(itemKey, `正文超过单篇上限 ${LIMITS.bodyBytes} 字节`);
807
+ }
808
+
809
+ /* 附件 / 封面:认 assets[] 的 key,也认站点上已有素材的 uuid */
810
+ const attachmentsIn = Array.isArray(raw.attachments) ? raw.attachments : [];
811
+ const attachments = [];
812
+ for (const ref of attachmentsIn) {
813
+ const r = text(ref);
814
+ if (!r) continue;
815
+ if (assetByKey.has(slugify(r))) {
816
+ attachments.push({ key: slugify(r), mode: 'manifest' });
817
+ } else if (looksLikeUuid(r)) {
818
+ attachments.push({ key: r, mode: 'site' });
819
+ } else {
820
+ bad(itemKey, `attachments 引用了 assets[] 里没有的素材 "${r}"(要么补进 assets[],要么直接给站点素材 uuid)`);
821
+ }
822
+ }
823
+ let cover = '';
824
+ const coverRaw = text(raw.cover);
825
+ if (coverRaw) {
826
+ if (assetByKey.has(slugify(coverRaw))) cover = slugify(coverRaw);
827
+ else if (looksLikeUuid(coverRaw)) cover = coverRaw;
828
+ else bad(itemKey, `cover 引用了 assets[] 里没有的素材 "${coverRaw}"`);
829
+ }
830
+
831
+ /* 自定义字段:键要合法、条数有上限;值原样透传给服务端 ext */
832
+ const customFields = {};
833
+ if (raw.customFields != null && !isPlainObject(raw.customFields)) {
834
+ bad(itemKey, 'customFields 必须是对象 {字段key: 值}');
835
+ } else if (isPlainObject(raw.customFields)) {
836
+ const keys = Object.keys(raw.customFields);
837
+ if (keys.length > LIMITS.customFieldKeys) {
838
+ bad(itemKey, `customFields 过多:${keys.length} > ${LIMITS.customFieldKeys}`);
839
+ }
840
+ for (const key of keys) {
841
+ if (!FIELD_KEY_RE.test(key)) bad(itemKey, `customFields 的键不合法:"${key}"(字母开头,≤40 字)`);
842
+ else customFields[key] = raw.customFields[key];
843
+ }
844
+ }
845
+
846
+ if (raw.sort != null && !Number.isFinite(Number(raw.sort))) bad(itemKey, `sort 必须是数字,收到 "${raw.sort}"`);
847
+
848
+ return {
849
+ categorySlug,
850
+ title: text(raw.title),
851
+ slug,
852
+ status,
853
+ seoTitle,
854
+ description,
855
+ keywords,
856
+ bodyPath,
857
+ bodyInline,
858
+ bodyBytes,
859
+ attachments,
860
+ cover,
861
+ customFields,
862
+ sort: num(raw.sort, 0),
863
+ pinned: bool(raw.pinned),
864
+ item: itemKey,
865
+ at,
866
+ };
867
+ }
868
+
869
+ /* ------------------------------------------------------------------ 汇总 */
870
+
871
+ /** 人类可读的一句话摘要(表头用) */
872
+ export function summarizeManifest(manifest) {
873
+ if (!manifest) return '';
874
+ const c = manifest.counts || {};
875
+ return `栏目 ${c.categories || 0} | 内容 ${c.contents || 0} | 单页 ${c.singles || 0} | 素材 ${c.assets || 0} | 导航 ${c.menus || 0} | 未填 ${c.unfilled || 0}`;
876
+ }
877
+
878
+ /** 展开菜单树 → 扁平列表(带 depth,执行时按深度先父后子) */
879
+ export function flattenMenus(menus, depth = 1, out = []) {
880
+ for (const one of menus || []) {
881
+ out.push({ ...one, depth });
882
+ flattenMenus(one.children, depth + 1, out);
883
+ }
884
+ return out;
885
+ }
886
+
887
+ /** 栏目排序:父在前、子在后(同级按 sort) */
888
+ export function sortCategoriesForApply(categories) {
889
+ const bySlug = new Map(categories.map((one) => [one.slug, one]));
890
+ const done = [];
891
+ const seen = new Set();
892
+ const visit = (row, guard = 0) => {
893
+ if (!row || seen.has(row.slug) || guard > 40) return;
894
+ if (row.parent && bySlug.has(row.parent) && !seen.has(row.parent)) visit(bySlug.get(row.parent), guard + 1);
895
+ seen.add(row.slug);
896
+ done.push(row);
897
+ };
898
+ for (const row of [...categories].sort((a, b) => a.sort - b.sort || a.slug.localeCompare(b.slug))) visit(row);
899
+ return done;
900
+ }
901
+
902
+ /* ------------------------------------------------------------------ JSON Schema */
903
+
904
+ /**
905
+ * JSON Schema(draft-07):契约的**可移植描述**,给 A / 外部工具 / 编辑器做静态校验。
906
+ *
907
+ * 由本文件生成(`wkgeo content apply --schema`),所以不会与校验逻辑漂移。
908
+ * 注意:跨条目引用(栏目 slug 重复 / 父栏目存在 / 附件必须已在 assets[] 里)与文件存在性
909
+ * 是 JSON Schema 表达不了的部分,只有 `validateManifest()` 会查。
910
+ */
911
+ export function manifestJsonSchema() {
912
+ const str = (extra = {}) => ({ type: 'string', ...extra });
913
+ const defs = {};
914
+
915
+ defs.field = {
916
+ type: 'object',
917
+ required: ['key'],
918
+ additionalProperties: false,
919
+ properties: {
920
+ key: str({ pattern: '^[a-zA-Z][a-zA-Z0-9_]{0,39}$', description: '字段 key(与后台自定义字段一致)' }),
921
+ label: str({ maxLength: LIMITS.nameChars, description: '默认取 key' }),
922
+ type: { enum: FIELD_TYPES, description: '默认 input' },
923
+ required: { type: 'boolean', description: '默认 false' },
924
+ options: { description: 'select 的选项:{"值":"显示名"} 或 ["值"]' },
925
+ sort: { type: 'number', description: '默认按声明顺序 ×10' },
926
+ formGroup: str({ description: '后台表单分组(可选)' }),
927
+ },
928
+ };
929
+
930
+ defs.category = {
931
+ type: 'object',
932
+ required: ['slug', 'name'],
933
+ additionalProperties: false,
934
+ properties: {
935
+ slug: str({ pattern: '^[a-z0-9][a-z0-9_-]{0,59}$', description: '栏目唯一标识;apply 按它幂等' }),
936
+ name: str({ maxLength: LIMITS.nameChars }),
937
+ path: str({ pattern: '^/[a-z0-9][a-z0-9_/-]*/$', description: '可选;给了就必须与 slug/层级算出来的一致' }),
938
+ type: {
939
+ enum: CATEGORY_TYPES,
940
+ description: 'list=列表页(默认)| single=单页 | channel=频道页(首页/总览;子栏目继承父)',
941
+ },
942
+ parent: str({ description: '父栏目 slug 或 path;子栏目继承父的类型' }),
943
+ sort: { type: 'number', description: '同级排序,默认按声明顺序 ×10' },
944
+ templateFile: str({ pattern: '\\.html$', description: '本站已有的模板文件(如 list.html),必须是 .html' }),
945
+ description: str({ description: '栏目简介,落 description' }),
946
+ seoDescription: str({ maxLength: LIMITS.seoDescriptionChars, description: '回退读 seo.description' }),
947
+ seoKeywords: str({ maxLength: LIMITS.seoKeywordsChars, description: '回退读 seo.keywords' }),
948
+ fields: { type: 'array', maxItems: LIMITS.fieldsPerCategory, items: { $ref: '#/definitions/field' } },
949
+ },
950
+ };
951
+
952
+ defs.asset = {
953
+ type: 'object',
954
+ required: ['path'],
955
+ additionalProperties: false,
956
+ properties: {
957
+ key: str({ description: '给 contents[].attachments / cover 引用;默认取文件名' }),
958
+ path: str({ description: '相对 manifest 的本地路径(≤200MB)' }),
959
+ use: { enum: ASSET_USES, description: '默认 content;logo 会同时写进站点信息' },
960
+ role: {
961
+ enum: ASSET_ROLES,
962
+ description:
963
+ '素材角色:缺省按扩展名推断(.css→css、.js→js、图片→image、其余→file);去重键是 (sha256, role)',
964
+ },
965
+ alt: str({ maxLength: LIMITS.altChars, description: 'alt / 素材显示名;apply 按它认领已有素材(重名会报错)' }),
966
+ name: str({ maxLength: LIMITS.nameChars, description: 'alt 缺省时的显示名' }),
967
+ },
968
+ };
969
+
970
+ const contentCommon = {
971
+ categorySlug: str({ description: '挂到哪个栏目(slug)' }),
972
+ title: str({ maxLength: LIMITS.titleChars, description: '必填;空=这一条失败(其余照常)' }),
973
+ slug: str({ maxLength: LIMITS.slugChars, description: '内容 slug;缺省用 title 认领' }),
974
+ status: { enum: CONTENT_STATUS, description: '默认 published(A 交的是成品)' },
975
+ seo: {
976
+ type: 'object',
977
+ additionalProperties: false,
978
+ properties: {
979
+ title: str({ maxLength: LIMITS.titleChars, description: '仅提示:平台无 seo_title 字段' }),
980
+ description: str({ maxLength: LIMITS.seoDescriptionChars }),
981
+ keywords: str({ maxLength: LIMITS.seoKeywordsChars }),
982
+ },
983
+ },
984
+ bodyFile: str({ description: '正文 HTML 文件(相对 manifest,≤512KB);与 body 二选一' }),
985
+ body: str({ description: '正文 HTML 字符串;与 bodyFile 二选一' }),
986
+ attachments: { type: 'array', items: str(), description: '素材 key 或站点素材 uuid' },
987
+ cover: str({ description: '封面素材 key 或 uuid' }),
988
+ customFields: { type: 'object', description: '栏目自定义字段的值(键必须是该栏目 fields[] 里的 key)' },
989
+ sort: { type: 'number' },
990
+ pinned: { type: 'boolean' },
991
+ };
992
+
993
+ defs.content = {
994
+ type: 'object',
995
+ required: ['categorySlug', 'title'],
996
+ additionalProperties: false,
997
+ properties: contentCommon,
998
+ };
999
+ defs.single = {
1000
+ type: 'object',
1001
+ required: ['categorySlug'],
1002
+ additionalProperties: true,
1003
+ properties: contentCommon,
1004
+ description: '单页内容:绑一个 type=single 的栏目;title 缺省取栏目名',
1005
+ };
1006
+
1007
+ defs.menu = {
1008
+ type: 'object',
1009
+ required: ['label', 'path'],
1010
+ additionalProperties: false,
1011
+ properties: {
1012
+ label: str({ maxLength: LIMITS.nameChars }),
1013
+ path: str({ pattern: '^/[a-z0-9][a-z0-9_/-]*/$', description: '必须等于某个栏目的 path' }),
1014
+ sort: { type: 'number' },
1015
+ children: {
1016
+ type: 'array',
1017
+ maxItems: LIMITS.menus,
1018
+ items: { $ref: '#/definitions/menu' },
1019
+ description: `最多 ${LIMITS.menuDepth} 级`,
1020
+ },
1021
+ },
1022
+ };
1023
+
1024
+ defs.unfilled = {
1025
+ type: 'object',
1026
+ required: ['item', 'reason'],
1027
+ additionalProperties: false,
1028
+ properties: {
1029
+ item: str({ description: '哪个位置没填,如 categories[2].seoDescription' }),
1030
+ reason: { enum: UNFILLED_REASONS, description: '为什么没填' },
1031
+ detail: str({ description: '补充说明(谁去补 / 卡在哪)' }),
1032
+ },
1033
+ };
1034
+
1035
+ return {
1036
+ $schema: 'http://json-schema.org/draft-07/schema#',
1037
+ $id: 'https://wkgeo.cn/schema/wkgeo-site-manifest@1.json',
1038
+ title: 'wkgeo-site-manifest@1',
1039
+ description:
1040
+ 'A(agent)→ 平台的建站内容契约:A 交这份 manifest,`wkgeo content apply --file <它>` 负责校验、幂等落库、按需发布。' +
1041
+ '未覆盖的跨引用与文件存在性由 CLI 内置校验负责。',
1042
+ type: 'object',
1043
+ required: ['_format', 'site', 'unfilled'],
1044
+ additionalProperties: true,
1045
+ properties: {
1046
+ _format: { const: MANIFEST_FORMAT },
1047
+ _source: {
1048
+ type: 'object',
1049
+ description: '来源说明(给老板看的溯源信息;不进库)',
1050
+ additionalProperties: true,
1051
+ },
1052
+ _note: str({ description: '给老板/接手下一位的一句话(不进库)' }),
1053
+ site: {
1054
+ type: 'object',
1055
+ required: ['name', 'lang'],
1056
+ additionalProperties: false,
1057
+ properties: {
1058
+ name: str({ maxLength: LIMITS.nameChars, description: '必须与 --site 指到的站点同名(否则报错,防错站)' }),
1059
+ lang: str({ pattern: '^[a-z]{2}(-[a-zA-Z]{2,4})?$' }),
1060
+ templateKey: str({ description: '期望的模板 key(只校验/提示,apply 不自动装模板)' }),
1061
+ },
1062
+ },
1063
+ menus: { type: 'array', maxItems: LIMITS.menus, items: { $ref: '#/definitions/menu' } },
1064
+ categories: {
1065
+ type: 'array',
1066
+ maxItems: LIMITS.categories,
1067
+ items: { $ref: '#/definitions/category' },
1068
+ description: 'slug 必须唯一;parent 必须能在本数组或站点已有栏目里解析到',
1069
+ },
1070
+ contents: { type: 'array', maxItems: LIMITS.contents, items: { $ref: '#/definitions/content' } },
1071
+ assets: { type: 'array', maxItems: LIMITS.assets, items: { $ref: '#/definitions/asset' } },
1072
+ singles: { type: 'array', maxItems: LIMITS.singles, items: { $ref: '#/definitions/single' } },
1073
+ unfilled: {
1074
+ type: 'array',
1075
+ maxItems: LIMITS.unfilled,
1076
+ items: { $ref: '#/definitions/unfilled' },
1077
+ description: '必填:没填的项 + 原因;全填齐写 []',
1078
+ },
1079
+ },
1080
+ definitions: defs,
1081
+ };
1082
+ }