@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,664 @@
1
+ /**
2
+ * `wkgeo content apply` —— **写内容的唯一原语**。
3
+ *
4
+ * ## 为什么要有它
5
+ * 老板 2026-10-30:「内容必须入库」「栏目必须建库」「三来源怎么分析是 A 的事,平台只给原语」。
6
+ * 于是 CLI 提供这一个入口:AI(A)把「从模板 / 网址 / 文件里分析出来的东西」写成一份 manifest,
7
+ * 由本命令**一次落库**——校验、diff、dry-run、幂等、拒绝,全在这里,A 不需要(也不允许)
8
+ * 自己拼 contentSave 请求。
9
+ *
10
+ * ## 硬规矩(都在代码里,不靠文档自觉)
11
+ * 1. **默认 dry-run**:不带 `--confirm` 只算不写。要真写必须显式 `--confirm`。
12
+ * 2. **逐栏目(section)upsert**:按 `slug` → `title` 匹配既有内容,命中就更新,没命中才新建。
13
+ * 同一份 manifest 连跑两次:第二次 created=0 / updated=0(幂等)。
14
+ * 3. **未知栏目 / 未知字段 → 拒绝**,并**一条都不写**(`rejected[]` 点名到 `sections[i].items[j]`)。
15
+ * 服务端对未知字段是**静默塞进 ext** 的(`splitContentExt`),这里必须提前挡住。
16
+ * 4. **类型不符 → 拒绝**:image 传 URL/文件名、number 传 `"abc"`、richtext 传裸 HTML,一律 exit 1。
17
+ * 5. **只走 CLI 自己的内容动作**(`ctx.contentCall` → `wkgeo-cli-fc` 的 B1 45 条),
18
+ * **不直连数据库**:写库只有 contentSave 一条路,审计/计数/限频都还在。
19
+ *
20
+ * ## 数据形状
21
+ * manifest(`--manifest <file|->`)与契约见 `docs/规范-模板内容契约.md` §5;
22
+ * 纯函数(归一 / 校验 / diff)在 `cli/lib/content-contract.mjs`,本文件只做**编排 + 落库**。
23
+ */
24
+
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+
28
+ import {
29
+ CONTRACT_TYPES,
30
+ isUuid,
31
+ normalizeFieldSpec,
32
+ normalizeManifest,
33
+ renderBlocksToHtml,
34
+ validateFieldValue,
35
+ } from './content-contract.mjs';
36
+ import { CliError, EXIT, UsageError } from './errors.mjs';
37
+
38
+ /** contentList 一页最多 100(服务端 `Math.min(100, pageSize)`),最多翻 5 页 = 500 条 / 栏目 */
39
+ const LIST_PAGE_SIZE = 100;
40
+ const LIST_MAX_PAGES = 5;
41
+
42
+ /* ------------------------------------------------------------------ 读 manifest */
43
+
44
+ /**
45
+ * 读 manifest 文本(`-` = 从 stdin 读,给 `... | wkgeo content fill --manifest -` 用)。
46
+ *
47
+ * @param {string} src 文件路径或 `-`
48
+ * @param {{stdin?: NodeJS.ReadableStream|{isTTY?:boolean,fd?:number}}} [io]
49
+ */
50
+ export function readManifestSource(src, io = {}) {
51
+ const spec = String(src == null ? '' : src).trim();
52
+ if (!spec) throw new UsageError('--manifest 要一个文件路径(或 `-` 表示从标准输入读)');
53
+ if (spec === '-') {
54
+ try {
55
+ /** fd 0 同步读:CLI 是短命进程,同步最简单,也不需要把 stdin 变成流的生命周期管理 */
56
+ return fs.readFileSync(0, 'utf8');
57
+ } catch (e) {
58
+ throw new CliError(`从标准输入读 manifest 失败(${(e && e.message) || e})`, {
59
+ kind: 'io',
60
+ hint: '改成 `--manifest <文件>` 试试;Windows PowerShell 里管道传中文请用 `-Encoding UTF8` 落成文件再读',
61
+ });
62
+ }
63
+ }
64
+ const abs = path.resolve(spec);
65
+ try {
66
+ return fs.readFileSync(abs, 'utf8');
67
+ } catch (e) {
68
+ throw new CliError(`读不到 manifest:${abs}`, {
69
+ kind: 'io',
70
+ hint: `${(e && e.code) || (e && e.message) || '未知原因'};--manifest 要一个可读的 JSON 文件路径`,
71
+ });
72
+ }
73
+ }
74
+
75
+ /** 文本 → manifest 对象(JSON 解析失败给能照做的错误) */
76
+ export function parseManifestText(text, where = 'manifest') {
77
+ try {
78
+ return JSON.parse(String(text || ''));
79
+ } catch (e) {
80
+ throw new CliError(`${where} 不是合法 JSON(${(e && e.message) || e})`, {
81
+ kind: 'bad_manifest',
82
+ hint: '先 `node -e "JSON.parse(require(\'fs\').readFileSync(\'<文件>\',\'utf8\'))"` 自查,再重跑',
83
+ });
84
+ }
85
+ }
86
+
87
+ /* ------------------------------------------------------------------ 站点快照 */
88
+
89
+ /** 统一给每个请求带上当前语言(`_lang` 是 content-core 认的键) */
90
+ function langPayload(lang) {
91
+ return lang ? { _lang: lang } : {};
92
+ }
93
+
94
+ function assertCategoryRows(rows, action) {
95
+ if (!Array.isArray(rows)) {
96
+ throw new CliError(`${action} 返回的不是栏目数组(服务端可能改过响应形状)`, {
97
+ kind: 'bad_response',
98
+ hint: '把 `--verbose` 的原始响应发回来,这个是 CLI 与服务端对不上,不是你的清单写错了',
99
+ });
100
+ }
101
+ return rows;
102
+ }
103
+
104
+ /**
105
+ * 把一个栏目下的内容**全部**翻回来(最多 500 条;超了就在 plan 里报出来,不静默截断)。
106
+ */
107
+ async function fetchContents(call, categoryId, lang, opts = {}) {
108
+ const rows = [];
109
+ let total = 0;
110
+ for (let page = 1; page <= LIST_MAX_PAGES; page += 1) {
111
+ const data = await call('contentList', {
112
+ categoryId,
113
+ page,
114
+ pageSize: LIST_PAGE_SIZE,
115
+ ...(opts.ownerPage ? { ownerPage: true } : {}),
116
+ ...langPayload(lang),
117
+ });
118
+ const list = (data && data.rows) || [];
119
+ total = Number((data && data.total) || 0);
120
+ rows.push(...list);
121
+ if (!list.length || rows.length >= total) break;
122
+ }
123
+ return { rows, total, truncated: total > rows.length };
124
+ }
125
+
126
+ /**
127
+ * 读站点快照:栏目树 + 每个要写栏目生效的内容字段 + 已有内容。
128
+ *
129
+ * @param {(action:string, payload?:object)=>Promise<any>} call 已绑定站点/语言的 contentCall
130
+ * @param {{lang?:string, categoryIds?:string[]}} opts
131
+ */
132
+ export async function loadSnapshot(call, opts = {}) {
133
+ const lang = opts.lang || '';
134
+ const categories = assertCategoryRows(await call('categoryList', { ...langPayload(lang) }), 'categoryList');
135
+
136
+ const fieldsByCategory = new Map();
137
+ const contentsByCategory = new Map();
138
+ const pagesByCategory = new Map();
139
+ const wanted = Array.isArray(opts.categoryIds) && opts.categoryIds.length
140
+ ? categories.filter(one => opts.categoryIds.includes(one.id))
141
+ : categories;
142
+
143
+ for (const cat of wanted) {
144
+ const fields = await call('fieldList', { scope: 'content', categoryId: cat.id, ...langPayload(lang) });
145
+ const map = new Map();
146
+ (Array.isArray(fields) ? fields : []).forEach(raw => {
147
+ const spec = normalizeFieldSpec(raw, 'platform');
148
+ if (spec.key) map.set(spec.key, { ...spec, enabled: raw.enabled !== false, builtin: raw.builtin === true, column: raw.column || '' });
149
+ });
150
+ fieldsByCategory.set(cat.id, map);
151
+
152
+ if (cat.kind === 'page') {
153
+ const pageRows = await fetchContents(call, cat.id, lang, { ownerPage: true });
154
+ pagesByCategory.set(cat.id, pageRows);
155
+ } else {
156
+ contentsByCategory.set(cat.id, await fetchContents(call, cat.id, lang));
157
+ }
158
+ }
159
+
160
+ return { categories, fieldsByCategory, contentsByCategory, pagesByCategory };
161
+ }
162
+
163
+ /* ------------------------------------------------------------------ 解析栏目引用 */
164
+
165
+ /**
166
+ * 按 ref 找栏目:**slug / path / key / name** 四种写法都认,找不到或有歧义都如实报。
167
+ *
168
+ * 为什么允许 name:A 从网址/文件里分析出来的是「栏目名」,不是 slug;
169
+ * 但**写库只认既有栏目**(栏目必须建库——模板阶段定的结构,A 不能自己造栏目)。
170
+ *
171
+ * @param {Array} categories `categoryList` 的行
172
+ * @param {string} ref
173
+ * @returns {{category?:object, error?:string, candidates?:string[]}}
174
+ */
175
+ export function resolveCategoryRef(categories, ref) {
176
+ const want = String(ref == null ? '' : ref).trim().replace(/^\/+|\/+$/g, '');
177
+ if (!want) return { error: '栏目 key 为空' };
178
+ const list = Array.isArray(categories) ? categories : [];
179
+ const normPath = one => String(one.path || '').replace(/^\/+|\/+$/g, '');
180
+ const eq = (a, b) => String(a == null ? '' : a).trim().toLowerCase() === String(b == null ? '' : b).trim().toLowerCase();
181
+
182
+ for (const test of [
183
+ one => eq(one.slug, want),
184
+ one => eq(one.key, want),
185
+ one => eq(normPath(one), want),
186
+ one => eq(one.name, want),
187
+ ]) {
188
+ const hits = list.filter(test);
189
+ if (hits.length === 1) return { category: hits[0] };
190
+ if (hits.length > 1) {
191
+ return {
192
+ error: `「${want}」匹配到 ${hits.length} 个栏目(${hits.map(one => `${one.name} ${one.path}`).join(' / ')})`,
193
+ candidates: hits.map(one => one.path),
194
+ };
195
+ }
196
+ }
197
+ return { error: `站点里没有栏目「${want}」(既不是 slug/key/path 也不是栏目名)` };
198
+ }
199
+
200
+ /* ------------------------------------------------------------------ 值归一与比较 */
201
+
202
+ /** 内容行的字段值(真列优先,其次 ext)——与服务端 `splitContentExt` 同一口径 */
203
+ export function valueOfContent(detail, key) {
204
+ if (!detail) return undefined;
205
+ if (key === 'body') return String(detail.body || '');
206
+ if (detail[key] !== undefined && detail[key] !== null) return detail[key];
207
+ const ext = detail.ext && typeof detail.ext === 'object' ? detail.ext : {};
208
+ return ext[key];
209
+ }
210
+
211
+ function assetIdsOf(value) {
212
+ if (value === null || value === undefined) return [];
213
+ const list = Array.isArray(value) ? value : [value];
214
+ return list.map(one => (one && typeof one === 'object' ? String(one.id || '') : String(one || ''))).filter(Boolean);
215
+ }
216
+
217
+ /** 值比较:媒体类按素材 id 序列比(详情接口会把 id 补成卡片对象) */
218
+ export function valuesEqual(fieldType, a, b) {
219
+ const media = fieldType === 'gallery' || fieldType === 'file';
220
+ if (media) return assetIdsOf(a).join('|') === assetIdsOf(b).join('|');
221
+ if (a === undefined || a === null || a === '') return b === undefined || b === null || b === '';
222
+ if (b === undefined || b === null || b === '') return false;
223
+ if (typeof a === 'object' || typeof b === 'object') return JSON.stringify(a) === JSON.stringify(b);
224
+ return String(a) === String(b);
225
+ }
226
+
227
+ /* ------------------------------------------------------------------ 计划(纯函数) */
228
+
229
+ /**
230
+ * 根据 manifest + 快照算出「要写什么」。**纯函数**(不调接口,测试只喂数据)。
231
+ *
232
+ * @param {object} manifest `normalizeManifest()` 的输出
233
+ * @param {object} snapshot `loadSnapshot()` 的输出
234
+ * @returns {{items:Array, rejected:Array, errors:Array}}
235
+ */
236
+ export function planFromManifest(manifest, snapshot) {
237
+ const items = [];
238
+ const rejected = [];
239
+ const errors = [];
240
+ const snapshotCategories = (snapshot && snapshot.categories) || [];
241
+ const fieldsByCategory = (snapshot && snapshot.fieldsByCategory) || new Map();
242
+ const contentsByCategory = (snapshot && snapshot.contentsByCategory) || new Map();
243
+ const pagesByCategory = (snapshot && snapshot.pagesByCategory) || new Map();
244
+
245
+ (manifest.errors || []).forEach(err => {
246
+ rejected.push({ where: err.where || 'manifest', code: 'bad_manifest', message: err.message, fix: err.fix || '' });
247
+ });
248
+
249
+ /** ---- 内容栏目 ---- */
250
+ (manifest.sections || []).forEach(section => {
251
+ const hit = resolveCategoryRef(snapshotCategories, section.key);
252
+ if (hit.error) {
253
+ section.items.forEach((item, ii) => {
254
+ rejected.push({
255
+ where: `${section.at}.items[${ii}]`,
256
+ code: 'unknown_section',
257
+ message: `栏目 ${section.key}:${hit.error}`,
258
+ fix: '栏目必须由模板建库(sites create / template install 阶段);A 不能自己造栏目。改 section.key 或先补栏目',
259
+ });
260
+ });
261
+ return;
262
+ }
263
+ const cat = hit.category;
264
+ if (cat.kind === 'page') {
265
+ section.items.forEach((item, ii) => {
266
+ rejected.push({
267
+ where: `${section.at}.items[${ii}]`,
268
+ code: 'page_kind_mismatch',
269
+ message: `栏目「${cat.name}」是单页(kind=page),不能放多条内容`,
270
+ fix: '单页请写到 manifest 的 pages[](正文/SEO 各一份),不要放 sections[]',
271
+ });
272
+ });
273
+ return;
274
+ }
275
+
276
+ const fieldMap = fieldsByCategory.get(cat.id) || new Map();
277
+ const existing = contentsByCategory.get(cat.id) || { rows: [] };
278
+
279
+ section.items.forEach(item => {
280
+ const fieldErrors = [];
281
+ const values = {};
282
+ let bodyHtml = null;
283
+ let bodyType = null;
284
+
285
+ Object.entries(item.fields || {}).forEach(([key, value]) => {
286
+ const spec = fieldMap.get(key);
287
+ if (!spec) {
288
+ rejected.push({
289
+ where: `${item.at}.fields.${key}`,
290
+ code: 'unknown_field',
291
+ message: `栏目「${cat.name}」没有字段「${key}」(契约外的字段一律不写)`,
292
+ fix: `可用字段:${[...fieldMap.keys()].join(' / ') || '(该栏目一个可用字段都没有)'};新增字段必须先改契约 + 建字段(fieldSave)`,
293
+ });
294
+ return;
295
+ }
296
+ if (spec.enabled === false) {
297
+ rejected.push({
298
+ where: `${item.at}.fields.${key}`,
299
+ code: 'disabled_field',
300
+ message: `字段「${spec.label || key}」在该栏目已停用(enabled=false),写入不会进表单`,
301
+ fix: '先在 CMS 字段设置里启用它,或从清单里删掉这个字段',
302
+ });
303
+ return;
304
+ }
305
+ const found = validateFieldValue(spec, value);
306
+ if (found.length) {
307
+ found.forEach(message => {
308
+ rejected.push({ where: `${item.at}.fields.${key}`, code: 'type_mismatch', message, fix: '按契约 §3 的类型表改值;类型不对不写库' });
309
+ fieldErrors.push(message);
310
+ });
311
+ return;
312
+ }
313
+ if (key === 'body') {
314
+ bodyType = spec.type;
315
+ bodyHtml = renderBlocksToHtml(value);
316
+ return;
317
+ }
318
+ values[key] = value;
319
+ });
320
+
321
+ if (!item.title) {
322
+ rejected.push({ where: item.at, code: 'bad_title', message: '内容缺少 title', fix: '每条内容必须有 title(库里 title 必填)' });
323
+ return;
324
+ }
325
+ if (item.title.length > 200) {
326
+ rejected.push({ where: item.at, code: 'bad_title', message: `title 超过 200 字(${item.title.length})`, fix: '标题压到 200 字以内' });
327
+ return;
328
+ }
329
+ if (fieldErrors.length) return;
330
+
331
+ /** 匹配既有内容:slug 优先,其次 title(两次跑同一份清单必须落在同一行上) */
332
+ const rows = existing.rows || [];
333
+ let matched = null;
334
+ if (item.slug) matched = rows.find(one => String(one.slug || '') === item.slug) || null;
335
+ if (!matched) matched = rows.find(one => String(one.title || '').trim() === item.title) || null;
336
+ const ambiguous = matched && rows.filter(one => String(one.title || '').trim() === item.title).length > 1;
337
+
338
+ items.push({
339
+ kind: 'content',
340
+ where: item.at,
341
+ category: cat,
342
+ title: item.title,
343
+ slug: item.slug,
344
+ status: item.status || manifest.status || '',
345
+ sort: item.sort,
346
+ pinned: item.pinned,
347
+ values,
348
+ bodyHtml,
349
+ bodyType,
350
+ matchedId: matched ? matched.id : null,
351
+ matchedTitle: matched ? matched.title : '',
352
+ warnings: ambiguous ? [`栏目「${cat.name}」里有 ${rows.filter(one => String(one.title || '').trim() === item.title).length} 条同名内容,按第一条更新`] : [],
353
+ });
354
+ });
355
+ });
356
+
357
+ /** ---- 单页(kind=page 的栏目) ---- */
358
+ (manifest.pages || []).forEach(page => {
359
+ const hit = resolveCategoryRef(snapshotCategories, page.key);
360
+ if (hit.error) {
361
+ rejected.push({
362
+ where: page.at,
363
+ code: 'unknown_page',
364
+ message: `单页 ${page.key}:${hit.error}`,
365
+ fix: 'pages[].key 必须是站点里已有的单页栏目(kind=page)',
366
+ });
367
+ return;
368
+ }
369
+ const cat = hit.category;
370
+ if (cat.kind !== 'page') {
371
+ rejected.push({
372
+ where: page.at,
373
+ code: 'page_kind_mismatch',
374
+ message: `栏目「${cat.name}」是 ${cat.kind} 类型,不是单页`,
375
+ fix: '多条的列表内容请放 sections[];pages[] 只写单页栏目',
376
+ });
377
+ return;
378
+ }
379
+ const fieldMap = fieldsByCategory.get(cat.id) || new Map();
380
+ const values = {};
381
+ Object.entries(page.fields || {}).forEach(([key, value]) => {
382
+ const spec = fieldMap.get(key);
383
+ if (!spec) {
384
+ rejected.push({
385
+ where: `${page.at}.fields.${key}`,
386
+ code: 'unknown_field',
387
+ message: `单页「${cat.name}」没有字段「${key}」`,
388
+ fix: `可用字段:${[...fieldMap.keys()].join(' / ') || '(无)'}`,
389
+ });
390
+ return;
391
+ }
392
+ const found = validateFieldValue(spec, value);
393
+ found.forEach(message => rejected.push({ where: `${page.at}.fields.${key}`, code: 'type_mismatch', message }));
394
+ if (!found.length) values[key] = value;
395
+ });
396
+
397
+ let bodyHtml = null;
398
+ if (page.body) {
399
+ try {
400
+ bodyHtml = renderBlocksToHtml(page.body);
401
+ } catch (e) {
402
+ rejected.push({ where: `${page.at}.body`, code: 'type_mismatch', message: `正文块结构不合法:${e.message}` });
403
+ }
404
+ }
405
+
406
+ const pageRows = pagesByCategory.get(cat.id) || { rows: [] };
407
+ const ownerRow = (pageRows.rows || []).find(one => String(one.owner_category_id || '') === String(cat.id)) || (pageRows.rows || [])[0] || null;
408
+
409
+ items.push({
410
+ kind: 'page',
411
+ where: page.at,
412
+ category: cat,
413
+ title: page.title || cat.name,
414
+ seo: page.seo || {},
415
+ values,
416
+ bodyHtml,
417
+ matchedId: ownerRow ? ownerRow.id : null,
418
+ ownerMissing: !ownerRow,
419
+ warnings: [],
420
+ });
421
+ });
422
+
423
+ return { items, rejected, errors };
424
+ }
425
+
426
+ /**
427
+ * 一条计划 item 相对库里的现状:新建 / 更新 / 跳过。
428
+ *
429
+ * @param {object} item `planFromManifest()` 的 item
430
+ * @param {object|null} detail `contentGet` 的详情(新建时为 null)
431
+ */
432
+ export function classifyItem(item, detail) {
433
+ if (!detail) return { action: 'create', changed: Object.keys(item.values || {}).concat(item.bodyHtml ? ['body'] : []) };
434
+ if (item.kind === 'page') {
435
+ const changed = [];
436
+ if (item.title && String(detail.title || '') !== item.title) changed.push('title');
437
+ if (item.bodyHtml !== null && String(detail.body || '') !== item.bodyHtml) changed.push('body');
438
+ Object.entries(item.values || {}).forEach(([key, value]) => {
439
+ if (!valuesEqual('', valueOfContent(detail, key), value)) changed.push(key);
440
+ });
441
+ return { action: changed.length ? 'update' : 'skip', changed };
442
+ }
443
+ const changed = [];
444
+ if (item.status && String(detail.status || '') !== item.status) changed.push('status');
445
+ if (item.sort !== null && item.sort !== undefined && Number(detail.sort || 0) !== Number(item.sort)) changed.push('sort');
446
+ if (item.pinned !== null && item.pinned !== undefined && (detail.pinned === true) !== (item.pinned === true)) changed.push('pinned');
447
+ Object.entries(item.values || {}).forEach(([key, value]) => {
448
+ const spec = { gallery: 'gallery', file: 'file', image: 'image', video: 'video' };
449
+ if (!valuesEqual(spec[key] || '', valueOfContent(detail, key), value)) changed.push(key);
450
+ });
451
+ if (item.bodyHtml !== null && String(detail.body || '') !== item.bodyHtml) changed.push('body');
452
+ if (item.slug && String(detail.slug || '') !== item.slug) changed.push('slug');
453
+ return { action: changed.length ? 'update' : 'skip', changed };
454
+ }
455
+
456
+ /* ------------------------------------------------------------------ 落库 */
457
+
458
+ function contentSavePayload(item, lang) {
459
+ const payload = {
460
+ category_id: item.category.id,
461
+ title: item.title,
462
+ ext: { ...item.values },
463
+ ...langPayload(lang),
464
+ };
465
+ if (item.kind === 'page') {
466
+ if (item.matchedId) payload.id = item.matchedId;
467
+ } else {
468
+ if (item.matchedId) payload.id = item.matchedId;
469
+ if (item.slug) payload.slug = item.slug;
470
+ if (item.status) payload.status = item.status;
471
+ if (item.sort !== null && item.sort !== undefined) payload.sort = item.sort;
472
+ if (item.pinned !== null && item.pinned !== undefined) payload.pinned = item.pinned;
473
+ }
474
+ if (item.bodyHtml !== null) payload.body = item.bodyHtml;
475
+ return payload;
476
+ }
477
+
478
+ /** 单页还要先把栏目本身(标题/SEO)对齐 —— 那是 `categorySave`,不是 `contentSave` */
479
+ async function savePageCategory(call, item, lang) {
480
+ const cat = item.category;
481
+ const payload = { id: cat.id, ...langPayload(lang) };
482
+ const changed = [];
483
+ if (item.title && String(cat.name || '') !== item.title) {
484
+ payload.name = item.title;
485
+ changed.push('name');
486
+ }
487
+ if (item.seo) {
488
+ if (item.seo.description && String(cat.seo_description || '') !== item.seo.description) {
489
+ payload.seo_description = item.seo.description;
490
+ changed.push('seo_description');
491
+ }
492
+ if (item.seo.keywords && String(cat.seo_keywords || '') !== item.seo.keywords) {
493
+ payload.seo_keywords = item.seo.keywords;
494
+ changed.push('seo_keywords');
495
+ }
496
+ if (item.seo.title && String(cat.seo_title || '') !== item.seo.title) {
497
+ /** 栏目的「SEO 标题」在库里就是 `seo_description` 的姊妹字段 `name`;没有独立列 ⇒ 记 warn 不写 */
498
+ item.warnings.push('栏目的 SEO 标题没有独立列(cms_category 只有 seo_description/seo_keywords),seo.title 未写库');
499
+ }
500
+ }
501
+ if (!changed.length) return { changed: [] };
502
+ await call('categorySave', payload);
503
+ return { changed };
504
+ }
505
+
506
+ /* ------------------------------------------------------------------ 命令主体 */
507
+
508
+ function resolveSiteId(ctx, flags, manifest) {
509
+ const raw = String((manifest && manifest.siteId) || flags.site || '').trim();
510
+ const site = raw ? { id: raw } : ctx.cmsSite();
511
+ if (!site.id) {
512
+ throw new UsageError(
513
+ 'CLI 内容动作要指定站点:manifest 里写 siteId,或加 --site <站点ID>,或先 `wkgeo site use <站点ID>`',
514
+ );
515
+ }
516
+ if (!isUuid(site.id)) throw new UsageError(`站点 ID 要 uuid(收到:${site.id})`);
517
+ return site.id;
518
+ }
519
+
520
+ /**
521
+ * `wkgeo content apply --site <id> --manifest <file|-> [--dry-run|--confirm] [--json]`
522
+ *
523
+ * @param {object} ctx runtime(命令层传进来)
524
+ * @param {object} flags 已解析的命令参数
525
+ */
526
+ export async function runContentApply(ctx, flags = {}) {
527
+ const confirm = flags.confirm === true;
528
+ if (confirm && flags.dryRun === true) throw new UsageError('--confirm 与 --dry-run 不能同时给(默认就是 dry-run)');
529
+
530
+ const raw = parseManifestText(readManifestSource(flags.manifest), '--manifest');
531
+ const manifest = normalizeManifest(raw, { siteId: flags.site || '', lang: flags.lang || '' });
532
+ const siteId = resolveSiteId(ctx, flags, manifest);
533
+ const lang = manifest.lang || flags.lang || '';
534
+ const call = (action, payload = {}) => ctx.contentCall(action, payload, { siteId });
535
+
536
+ /** 第一遍:先只读栏目树,把清单里引用到的栏目 id 收出来(别把整站的字段/内容都拉一遍) */
537
+ const categories = assertCategoryRows(await call('categoryList', { ...langPayload(lang) }), 'categoryList');
538
+ const needed = [];
539
+ [...manifest.sections, ...manifest.pages].forEach(one => {
540
+ const hit = resolveCategoryRef(categories, one.key);
541
+ if (hit.category) needed.push(hit.category.id);
542
+ });
543
+
544
+ const snapshot = await loadSnapshot(call, { lang, categoryIds: needed });
545
+ snapshot.categories = categories;
546
+ const plan = planFromManifest(manifest, snapshot);
547
+
548
+ /** 第二遍:命中既有内容的,取详情才知道「更新」还是「跳过」 */
549
+ const details = new Map();
550
+ for (const item of plan.items) {
551
+ if (!item.matchedId) continue;
552
+ const detail = await call('contentGet', { id: item.matchedId, ...langPayload(lang) });
553
+ details.set(item.matchedId, detail);
554
+ }
555
+
556
+ const changes = { created: 0, updated: 0, skipped: 0, rejected: plan.rejected.length };
557
+ const perSection = [];
558
+ for (const item of plan.items) {
559
+ const verdict = classifyItem(item, item.matchedId ? details.get(item.matchedId) : null);
560
+ item.action = verdict.action;
561
+ item.changed = verdict.changed;
562
+ if (verdict.action === 'create') changes.created += 1;
563
+ else if (verdict.action === 'update') changes.updated += 1;
564
+ else changes.skipped += 1;
565
+ const bucket = perSection.find(one => one.category.id === item.category.id);
566
+ const row = { title: item.title, where: item.where, action: verdict.action, changed: verdict.changed, warnings: item.warnings };
567
+ if (bucket) bucket.items.push(row);
568
+ else perSection.push({ category: item.category, kind: item.kind, items: [row] });
569
+ }
570
+
571
+ const result = {
572
+ ok: plan.rejected.length === 0,
573
+ dry_run: !confirm,
574
+ siteId,
575
+ lang: lang || '(站点默认语言)',
576
+ changes,
577
+ sections: perSection.map(one => ({
578
+ key: one.category.slug || one.category.id,
579
+ name: one.category.name,
580
+ path: one.category.path,
581
+ kind: one.kind,
582
+ created: one.items.filter(x => x.action === 'create').length,
583
+ updated: one.items.filter(x => x.action === 'update').length,
584
+ skipped: one.items.filter(x => x.action === 'skip').length,
585
+ items: one.items,
586
+ })),
587
+ rejected: plan.rejected,
588
+ };
589
+
590
+ /** 有拒绝:**一条都不写**,直接把清单问题全列出来(不写完再回滚,不留半成品) */
591
+ if (plan.rejected.length) {
592
+ const lines = plan.rejected.slice(0, 30).map(one => ` ✖ ${one.where}:${one.message}`);
593
+ throw new CliError(
594
+ `清单有 ${plan.rejected.length} 处不合法,未写库(${changes.created + changes.updated} 条待写被拦下)`,
595
+ {
596
+ kind: 'contract',
597
+ exitCode: EXIT.ERROR,
598
+ hint: '按下面的点位改清单后重跑;拒绝项一律不静默丢弃,也不会写一半',
599
+ details: result,
600
+ raw: lines.join('\n'),
601
+ },
602
+ );
603
+ }
604
+
605
+ if (!confirm) {
606
+ ctx.done({ ...result, message: 'dry-run:只算不写。确认无误后加 --confirm 落库' });
607
+ printHuman(ctx, result);
608
+ return result;
609
+ }
610
+
611
+ /** ---- 真写 ---- */
612
+ for (const item of plan.items) {
613
+ if (item.action === 'skip') continue;
614
+ if (item.kind === 'page') {
615
+ const catResult = await savePageCategory(call, item, lang);
616
+ item.categoryChanges = catResult.changed;
617
+ if (item.ownerMissing) {
618
+ const ensured = await call('contentEnsurePage', { categoryId: item.category.id, ...langPayload(lang) });
619
+ const rows = (ensured && ensured.rows) || [];
620
+ const own = rows.find(one => String(one.owner_category_id || '') === String(item.category.id)) || rows[0];
621
+ if (!own) {
622
+ throw new CliError(`单页「${item.category.name}」没有内容行,补建也失败`, {
623
+ kind: 'server',
624
+ hint: '这是平台侧的问题:单页栏目应当由服务端自动建一条内容(ensurePageContents)。请把这条报给 Lead',
625
+ });
626
+ }
627
+ item.matchedId = own.id;
628
+ }
629
+ }
630
+ await call('contentSave', contentSavePayload(item, lang));
631
+ }
632
+
633
+ result.dry_run = false;
634
+ result.ok = true;
635
+ ctx.done(result);
636
+ printHuman(ctx, result);
637
+ return result;
638
+ }
639
+
640
+ /** 人类可读输出(`--json` 时 `out.*` 全部静音,只有 `done()` 的信封进 stdout) */
641
+ function printHuman(ctx, result) {
642
+ const out = ctx.out;
643
+ if (!result || !out) return;
644
+ out.head(result.dry_run ? '内容清单预演(dry-run,未写库)' : '内容清单已写库');
645
+ out.line(`站点 ${result.siteId} 语言 ${result.lang}`);
646
+ result.sections.forEach(section => {
647
+ out.line(
648
+ `栏目 ${section.key}(${section.name} ${section.path || ''}):新增 ${section.created} / 更新 ${section.updated} / 跳过 ${section.skipped}`,
649
+ );
650
+ section.items.slice(0, 12).forEach(item => {
651
+ const sign = item.action === 'create' ? '+' : item.action === 'update' ? '~' : '=';
652
+ const what = item.action === 'skip' ? '(无变化)' : item.changed.length ? `(${item.changed.join(',')})` : '';
653
+ out.line(` ${sign} ${item.title}${what}`);
654
+ });
655
+ if (section.items.length > 12) out.line(` … 还有 ${section.items.length - 12} 条`);
656
+ });
657
+ out.line(
658
+ `合计:新增 ${result.changes.created} / 更新 ${result.changes.updated} / 跳过 ${result.changes.skipped} / 拒绝 ${result.changes.rejected}`,
659
+ );
660
+ if (result.dry_run) out.info('加 --confirm 才会真写库。');
661
+ else out.ok('已写库(内容状态按清单 / 默认 published);要对外可见再跑 `wkgeo publish start`。');
662
+ }
663
+
664
+ export { CONTRACT_TYPES };