@wkgeo/cli 2.0.3 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/build.mjs ADDED
@@ -0,0 +1,1047 @@
1
+ /**
2
+ * 本地静态生成(`wkgeo site build`)—— **只读线上、只写本地**。
3
+ *
4
+ * ## 这一层要解决的事
5
+ * 老板口径(2026-11-22):「既然工作在本地了,静态页面也在本地生成,最后再传 OSS」。
6
+ * 于是 `site build` 只负责**把站点生成成一份 dist**(HTML + 站点资源包 + 模板静态资产),
7
+ * 不发布、不上传、不写任何线上数据。
8
+ *
9
+ * ## 数据从哪来(三块,全部走 CMS 公开动作,形状以真机回包为准)
10
+ * ① `siteAssetBundle` → `{hash, css, js}`:站点 CSS/JS 原文(未压缩)。落在**模板目录**的
11
+ * `template/css/site-<hash>.css` / `template/js/site-<hash>.js` —— 模板与静态资产是一条
12
+ * 发布链路(`/template/...`),build **不往 html 里复制任何资产**;
13
+ * ② `publicSitemap`(`format:'json'`)→ 栏目 / 内容 / 标签的地址 → 去重、严格校验后成页清单;
14
+ * ③ `pageRender`(`assets:'external'` + `assetBase:'/template/'` + `assetHash`)→ 每页 HTML。
15
+ * 页面里的 `<link>` / `<script>` 是 `/template/css/site-<hash>.css` 这类**站内绝对路径**,
16
+ * 本地预览把站点根(`<域名>\`)当静态根就能直接打开。
17
+ *
18
+ * ## 目录口径(老板 2026-11-22 rev4)
19
+ * `<域名>\template\` 模板源(HTML + css/ + js/ + assets/,就地改,build 不复制出去)
20
+ * `<域名>\html\` build 产物(只出页面;`html\upload\` 放本地化后的上传素材)
21
+ * 站点根只有 AGENTS.md + template/ + html/ + .wkgeo/,**没有** assets/、没有 dist/。
22
+ *
23
+ * ## 为什么路径映射要照抄发布器
24
+ * 发布器(`aliyun/fc/wkgeo-site-publish`)落桶口径是「目录风格」:
25
+ * `/` → `index.html`;`/about/` → `about/index.html`。
26
+ * 本地 html 必须一模一样,否则之后「传 OSS」还得再映射一次(两份口径迟早分叉)。
27
+ *
28
+ * ## 幂等
29
+ * `<dir>/.wkgeo/build-manifest.json` 记每个页面的 `{path, file, sha256}`;下次生成到同一路径时
30
+ * sha256 相同且文件还在 ⇒ `skipped`(不写盘,计数照报)。旧版清单在站点根
31
+ * (`<dir>/build-manifest.json`):**兼容读取**做幂等判定,但写入永远只写 `.wkgeo/`。
32
+ *
33
+ * ## 只读的边界
34
+ * 发的都是**渲染 / 读清单**类动作,没有一条写请求;失败也不回滚线上 —— 它本来就没碰线上。
35
+ */
36
+
37
+ import fs from 'node:fs';
38
+ import path from 'node:path';
39
+ import crypto from 'node:crypto';
40
+
41
+ import { createApi } from './api.mjs';
42
+ import { createCms } from './cms.mjs';
43
+ import { pullSiteMeta, LEGACY_SITE_META_FILE, SITE_META_FILE, WORKSPACE_STATE_DIR } from './site-meta.mjs';
44
+ import { CliError, EXIT, UsageError } from './errors.mjs';
45
+ import { looksLikeUuid, matchSiteRow } from './commands/cms.mjs';
46
+
47
+ /** 本地生成清单文件(在 `.wkgeo/` 下,与 `site.json` 并列;首次写入自动建目录) */
48
+ export const BUILD_MANIFEST_FILE = `${WORKSPACE_STATE_DIR}/build-manifest.json`;
49
+
50
+ /**
51
+ * 兼容读取:旧版把生成清单直接放在站点根。
52
+ * 只在 `.wkgeo/build-manifest.json` 不存在时才读它(只用于幂等判定,不迁移、不删);写入永远写 `.wkgeo/`。
53
+ */
54
+ export const LEGACY_BUILD_MANIFEST_FILE = 'build-manifest.json';
55
+
56
+ /** 站点资源包的对外前缀(模板 & 站点资源统一走 `/template/...`,见 rev4 目录口径) */
57
+ export const TEMPLATE_ASSET_BASE = '/template/';
58
+
59
+ /**
60
+ * 站点资源包的对外前缀(**历史口径**:老发布器写 `/assets/...`)。
61
+ * 2026-11-22 rev4 起本地 build 用 `TEMPLATE_ASSET_BASE`;这个常量保留只为兼容
62
+ * 已发布的旧产物与 `checkInternalLinks` 的跳过前缀。
63
+ */
64
+ export const ASSET_BASE = '/assets/';
65
+
66
+ /** 本地产物目录名(老板 2026-11-22 rev4:build 只出页面,落在 `<站点目录>\html\`) */
67
+ export const DEFAULT_OUT_DIR = 'html';
68
+
69
+ /** 与发布器同口径的并发(4 页同时在渲染,上限 16 防止把 CMS 打满) */
70
+ const DEFAULT_CONCURRENCY = 4;
71
+ const MAX_CONCURRENCY = 16;
72
+
73
+ /** `assetHash` 的合法形状(cms 侧只认这个;对不上页面会引用不存在的文件名) */
74
+ const ASSET_HASH_RE = /^[a-f0-9]{6,40}$/i;
75
+
76
+ /** 页面级致命错误(重试没用 / 站点整体不可用)—— 直接终止整批 */
77
+ function isFatalRenderError(err) {
78
+ if (!err) return false;
79
+ if (err.code === 410 || err.kind === 'SITE_UNAVAILABLE') return true;
80
+ if (err.exitCode === EXIT.AUTH) return true;
81
+ if (err.exitCode === EXIT.RATE_LIMIT) return true;
82
+ return ['forbidden', 'cms_auth', 'cms_not_member', 'cms_scope', 'cms_site_required'].includes(err.kind);
83
+ }
84
+
85
+ /* -------------------------------------------------------------- 路径与文件 */
86
+
87
+ /** 站内路径 → dist 里的相对文件(目录风格,与发布器 `publishTargetOf` 同口径) */
88
+ export function pageFileOf(pagePath) {
89
+ const rel = String(pagePath || '')
90
+ .replace(/^\/+/, '')
91
+ .replace(/\/+$/, '');
92
+ return rel ? `${rel}/index.html` : 'index.html';
93
+ }
94
+
95
+ /**
96
+ * 站内路径的**形状**校验(镜像 `cms-publish.js` 的 `publishPathProblem`)。
97
+ * @returns {string} 空串 = 合法,否则是中文原因
98
+ */
99
+ function pagePathShapeProblem(rawPath) {
100
+ const text = String(rawPath === null || rawPath === undefined ? '' : rawPath).trim();
101
+ if (!text) return '路径为空';
102
+ if (!text.startsWith('/')) return '路径不是 / 开头';
103
+ if (text.includes('?') || text.includes('#')) return '路径含查询/锚点';
104
+ if (text.includes('//')) return '路径含重复斜杠';
105
+ const inner = text.replace(/^\/+|\/+$/g, '');
106
+ if (inner && inner.split('/').some((seg) => !seg)) return '路径含空段';
107
+ if (/[\s\u0000-\u001f\u007f]/.test(text)) return '路径含空白/控制字符';
108
+ try {
109
+ new URL(text, 'https://build.invalid');
110
+ } catch {
111
+ return '路径不能解析成 URL';
112
+ }
113
+ return '';
114
+ }
115
+
116
+ /**
117
+ * sitemap 的一条地址 → 站内路径(**严格模式**:不猜着修,非法就带原因跳过)。
118
+ *
119
+ * 镜像 cms 侧 `sitemapUrlProblem`:绝对地址的 host 必须属于本站;不接受查询 / 锚点;
120
+ * 统一补尾斜杠。之所以不"宽松归一化":`例`.com 拼进路径那种事故就是猜出来的。
121
+ *
122
+ * @returns {{path:string, problem:string}}
123
+ */
124
+ export function pagePathFromEntry(rawUrl, origin) {
125
+ const text = String(rawUrl === null || rawUrl === undefined ? '' : rawUrl).trim();
126
+ if (!text) return { path: '', problem: '地址为空' };
127
+ const baseText = String(origin || '').trim().replace(/\/+$/, '');
128
+ let baseHost = '';
129
+ if (baseText) {
130
+ try {
131
+ baseHost = new URL(baseText).host.toLowerCase();
132
+ } catch {
133
+ baseHost = '';
134
+ }
135
+ }
136
+ let pathname = '';
137
+ if (/^https?:\/\//i.test(text)) {
138
+ if (text.includes('?') || text.includes('#')) return { path: '', problem: '地址含查询/锚点' };
139
+ let parsed = null;
140
+ try {
141
+ parsed = new URL(text);
142
+ } catch {
143
+ return { path: '', problem: '不是合法的绝对 URL' };
144
+ }
145
+ if (baseHost && parsed.host.toLowerCase() !== baseHost) return { path: '', problem: `域名不属于本站(${parsed.host})` };
146
+ pathname = parsed.pathname;
147
+ } else if (text.startsWith('/')) {
148
+ if (text.includes('?') || text.includes('#')) return { path: '', problem: '地址含查询/锚点' };
149
+ pathname = text;
150
+ if (baseText) {
151
+ try {
152
+ const full = new URL(text, `${baseText}/`);
153
+ if (baseHost && full.host.toLowerCase() !== baseHost) return { path: '', problem: `域名不属于本站(${full.host})` };
154
+ } catch {
155
+ return { path: '', problem: '拼不成合法的绝对 URL' };
156
+ }
157
+ }
158
+ } else {
159
+ return { path: '', problem: '不是 / 开头也不是 http(s) 绝对地址' };
160
+ }
161
+ if (!pathname) pathname = '/';
162
+ if (!pathname.endsWith('/')) pathname = `${pathname}/`;
163
+ const shape = pagePathShapeProblem(pathname);
164
+ if (shape) return { path: '', problem: shape };
165
+ return { path: pathname, problem: '' };
166
+ }
167
+
168
+ /**
169
+ * `publicSitemap`(format json)的回包 → 页清单 + 跳过告警。
170
+ *
171
+ * 口径照抄发布器 `publishPathsFromSitemapDetailed`:**`/` 永远第一个**,然后栏目 → 内容 → 标签,
172
+ * 同名路径去重(栏目与单页内容常指向同一路径);非法条目跳过并记 warning。
173
+ *
174
+ * 条目取址兼容 `url` 与 `path` 两种字段:contents / tags 的契约是 `url`(可能绝对地址),
175
+ * 而 categories 的回包历史上只带 `path`(`cms-public-render` 的列名就是 path)——
176
+ * 两个都认,避免"栏目全被跳过、只生成一个首页"这种哑巴故障。
177
+ *
178
+ * @returns {{paths:string[], warnings:string[], emptySite:boolean}}
179
+ */
180
+ export function pagePathsFromSitemap(payload) {
181
+ const data = payload && typeof payload === 'object' ? payload : {};
182
+ const origin = String((data.site && data.site.origin) || '').replace(/\/+$/, '');
183
+ const categories = Array.isArray(data.categories) ? data.categories : [];
184
+ const contents = Array.isArray(data.contents) ? data.contents : [];
185
+ const tags = Array.isArray(data.tags) ? data.tags : [];
186
+ const kinds = { category: '栏目', content: '内容', tag: '标签' };
187
+ const warnings = [];
188
+ const paths = ['/'];
189
+ const seen = new Set(paths);
190
+ const push = (kind, one) => {
191
+ const rawUrl = one && (one.url || one.path);
192
+ const hit = pagePathFromEntry(rawUrl, origin);
193
+ if (hit.problem) {
194
+ const name = String((one && (one.name || one.title)) || '');
195
+ const id = String((one && one.id) || '');
196
+ if (warnings.length < 50) {
197
+ warnings.push(
198
+ `${kinds[kind] || kind}「${name || id || '(未命名)'}」的 sitemap 地址不合法,已跳过:${hit.problem}` +
199
+ (rawUrl ? `(${String(rawUrl).slice(0, 200)})` : ''),
200
+ );
201
+ }
202
+ return;
203
+ }
204
+ if (seen.has(hit.path)) return;
205
+ seen.add(hit.path);
206
+ paths.push(hit.path);
207
+ };
208
+ categories.forEach((one) => push('category', one));
209
+ contents.forEach((one) => push('content', one));
210
+ tags.forEach((one) => push('tag', one));
211
+ return { paths, warnings, emptySite: categories.length === 0 && contents.length === 0 };
212
+ }
213
+
214
+ /**
215
+ * 老地址跳转页(镜像 `aliyun/fc/_shared/seo-redirect.js`)。
216
+ *
217
+ * 发布器对 `pageRender` 回的 `redirectTo` 就是写这张页:**相对地址**的 meta refresh + canonical +
218
+ * `noindex,follow`,静态站不需要 301 也能跳,搜索引擎把权重并到新地址。
219
+ */
220
+ export function redirectPageHtml(target, titleText) {
221
+ const to = String(target || '');
222
+ const safe = to.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
223
+ const title = String(titleText || '').trim() || '页面地址已更新';
224
+ const titleSafe = title.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
225
+ return `<!doctype html>
226
+ <html lang="zh-CN">
227
+ <head>
228
+ <meta charset="utf-8">
229
+ <meta name="viewport" content="width=device-width,initial-scale=1">
230
+ <meta name="robots" content="noindex,follow">
231
+ <link rel="canonical" href="${safe}">
232
+ <meta http-equiv="refresh" content="0; url=${safe}">
233
+ <title>${titleSafe}</title>
234
+ <script>location.replace(${JSON.stringify(to)}+location.search+location.hash);</script>
235
+ </head>
236
+ <body style="font-family:system-ui,-apple-system,'PingFang SC','Microsoft YaHei',sans-serif;padding:48px 20px;color:#333">
237
+ <p style="margin:0 0 12px">页面地址已更新。</p>
238
+ <p style="margin:0"><a href="${safe}">${safe}</a></p>
239
+ </body>
240
+ </html>
241
+ `;
242
+ }
243
+
244
+ /* -------------------------------------------------------------- 小工具 */
245
+
246
+ function sha256Of(text) {
247
+ return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
248
+ }
249
+
250
+ function byteLength(text) {
251
+ return Buffer.byteLength(String(text || ''), 'utf8');
252
+ }
253
+
254
+ function normalizeAssetMode(raw) {
255
+ const text = String(raw || 'external').trim().toLowerCase();
256
+ if (text === 'external' || text === 'inline') return text;
257
+ throw new UsageError(`--assets 只支持 external / inline,收到:${raw}`);
258
+ }
259
+
260
+ /**
261
+ * 本地产物目录名:默认 `html`(老板 2026-11-22 rev4)。
262
+ *
263
+ * 只接受**单层文件夹名**(`html` / `.tmp-build` 这类拼错的绝对路径 / `..` 一律拒绝),
264
+ * 避免 `--out ../../x` 把产物写到站外。旧 `dist` 仍然可用(显式传才用,不再默认)。
265
+ */
266
+ function normalizeOutDir(raw) {
267
+ const text = String(raw === undefined || raw === null || raw === '' ? DEFAULT_OUT_DIR : raw).trim();
268
+ if (!text || /[\\/]/.test(text) || text === '.' || text === '..' || /^[a-zA-Z]:/.test(text)) {
269
+ throw new UsageError(`--out 只接受单层目录名(默认 html),收到:${raw}`);
270
+ }
271
+ return text;
272
+ }
273
+
274
+ function normalizeConcurrency(raw) {
275
+ if (raw === undefined || raw === null || raw === '') return DEFAULT_CONCURRENCY;
276
+ const n = Number(raw);
277
+ if (!Number.isFinite(n) || n < 1) throw new UsageError(`--concurrency 必须是正整数,收到:${raw}`);
278
+ return Math.min(Math.floor(n), MAX_CONCURRENCY);
279
+ }
280
+
281
+ function normalizeMaxPages(raw) {
282
+ if (raw === undefined || raw === null || raw === '') return 0;
283
+ const n = Number(raw);
284
+ if (n === 0) return 0; // 0 / 不传 = 不限页数
285
+ if (!Number.isFinite(n) || n < 1) throw new UsageError(`--max-pages 必须是正整数(0 = 不限),收到:${raw}`);
286
+ return Math.floor(n);
287
+ }
288
+
289
+ /** 递归遍历目录(只收文件;符号链接目录不追,避免绕圈) */
290
+ function walkFiles(fsImpl, root) {
291
+ const out = [];
292
+ const walk = (relDir) => {
293
+ const abs = relDir ? path.join(root, relDir) : root;
294
+ let entries = [];
295
+ try {
296
+ entries = fsImpl.readdirSync(abs, { withFileTypes: true });
297
+ } catch {
298
+ return;
299
+ }
300
+ for (const entry of entries) {
301
+ const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
302
+ if (entry.isDirectory()) walk(rel);
303
+ else if (entry.isFile()) out.push(rel);
304
+ }
305
+ };
306
+ walk('');
307
+ return out;
308
+ }
309
+
310
+ /** 先写 `.tmp` 再 rename(rename 失败退化成"删了再 rename",Windows 上偶发占用) */
311
+ function atomicWrite(fsImpl, file, data) {
312
+ const tmp = `${file}.tmp`;
313
+ fsImpl.writeFileSync(tmp, data);
314
+ try {
315
+ fsImpl.renameSync(tmp, file);
316
+ } catch (e) {
317
+ try {
318
+ if (typeof fsImpl.rmSync === 'function') fsImpl.rmSync(file, { force: true });
319
+ } catch {
320
+ /* 忽略:下面 rename 会给出真原因 */
321
+ }
322
+ try {
323
+ fsImpl.renameSync(tmp, file);
324
+ } catch {
325
+ try {
326
+ fsImpl.writeFileSync(file, data);
327
+ if (typeof fsImpl.rmSync === 'function') fsImpl.rmSync(tmp, { force: true });
328
+ } catch {
329
+ throw e;
330
+ }
331
+ }
332
+ }
333
+ }
334
+
335
+ /* -------------------------------------------------------------- 站内链接体检 */
336
+
337
+ /** 不做链接体检的站内路径前缀(静态资产 / 接口 / CMS 后台,本来就不在站点页清单里) */
338
+ const LINK_SKIP_PREFIXES = ['/assets/', '/template/', '/html/', '/api/', '/cms/'];
339
+
340
+ /** 不做链接体检的站内路径(站点级固定文件,由发布器自己产出) */
341
+ const LINK_SKIP_PATHS = new Set(['/favicon.ico', '/robots.txt', '/sitemap.xml', '/llms.txt']);
342
+
343
+ /** 体检结果里最多列多少条缺失(`missing_count` 仍是总数,防止大站把 payload 撑爆) */
344
+ const MAX_LINK_MISSING = 200;
345
+
346
+ /**
347
+ * 一条 `href` / `src` 属性值 → 要体检的站内绝对路径(空串 = 不体检)。
348
+ *
349
+ * 口径(派单 task-41):只认 `/` 开头且不是 `//` 的站内绝对路径;剥 `#hash` / `?query`;
350
+ * `/assets/`、站点固定文件、`/api/`、`/cms/` 直接跳过。
351
+ */
352
+ function internalLinkPathOf(raw) {
353
+ let text = String(raw === null || raw === undefined ? '' : raw).trim();
354
+ if (!text || text.charAt(0) !== '/' || text.charAt(1) === '/') return '';
355
+ text = text.split('#')[0].split('?')[0].trim();
356
+ if (!text) return '';
357
+ if (text === '/') return '/';
358
+ if (!text.startsWith('/')) return '';
359
+ if (LINK_SKIP_PATHS.has(text)) return '';
360
+ if (LINK_SKIP_PREFIXES.some((prefix) => text.startsWith(prefix))) return '';
361
+ return text;
362
+ }
363
+
364
+ /**
365
+ * 页面 HTML 里的站内绝对链接(`href` / `src` 两种属性;`data-href` / `srcset` 不算)。
366
+ * @returns {string[]} 按出现顺序,含重复
367
+ */
368
+ function internalLinksInHtml(html) {
369
+ const out = [];
370
+ const text = String(html || '');
371
+ const re = /(?<![-.\w])(?:href|src)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
372
+ let hit;
373
+ while ((hit = re.exec(text))) {
374
+ const target = internalLinkPathOf(hit[1] !== undefined ? hit[1] : hit[2]);
375
+ if (target) out.push(target);
376
+ }
377
+ return out;
378
+ }
379
+
380
+ /** 比较用:去掉尾斜杠(`/` 仍保留),让 `/about/` 与 `/about` 视为同一页(容错) */
381
+ function linkCompareKey(raw) {
382
+ const text = String(raw === null || raw === undefined ? '' : raw).trim();
383
+ if (!text || !text.startsWith('/')) return '';
384
+ const noTrail = text.replace(/\/+$/, '');
385
+ return noTrail || '/';
386
+ }
387
+
388
+ /**
389
+ * 站内链接体检:扫本次生成 / 跳过的页面 HTML,把指向「不存在的页面」的站内绝对链接记下来。
390
+ *
391
+ * 只报警、不改 exit 码(老板 2026-11-22 口径:本地 build 时把模板里的死链暴露出来)。
392
+ * 允许集合 = **全量 sitemap 路径**(`allSitemapPaths`,截断前;`--max-pages` 只限制生成,不缩小已知页面)
393
+ * + 调用方补充的页清单 / 栏目镜像路径(`allowedPaths`)+ 首页 `/`:
394
+ * `new Set([...allSitemapPaths, ...categoryPaths, ...generatedPaths, '/'])`。
395
+ * 只有既不在 sitemap、也不在栏目表里的链接才算 missing;
396
+ * 同一个页面里重复出现的同一个坏链接只记一条。
397
+ *
398
+ * @param {object} opts
399
+ * @param {object} [opts.fsImpl] 注入的 fs(默认 node:fs;单测用)
400
+ * @param {string} opts.distDir dist 根目录
401
+ * @param {Array<{path:string,file:string,status:string}>} [opts.pages] 本次页清单(只扫 written/skipped)
402
+ * @param {string[]} [opts.allSitemapPaths] 全量 sitemap 路径(**截断前**的完整数组)
403
+ * @param {string[]} [opts.allowedPaths] 补充允许集合(页清单 + 栏目镜像路径)
404
+ * @param {string} [opts.templateDir] 模板目录(保留参数;当前只体检 dist 产物,不扫模板源码)
405
+ * @returns {{checked:number, known_pages:number, missing:Array<{from:string,href:string}>, missing_count:number}}
406
+ */
407
+ export function linkCheck(opts = {}) {
408
+ const { fsImpl = fs, distDir, pages = [], allSitemapPaths = [], allowedPaths = [] } = opts || {};
409
+ const allowed = new Set();
410
+ const addAllowed = (raw) => {
411
+ const key = linkCompareKey(raw);
412
+ if (key) allowed.add(key);
413
+ };
414
+ addAllowed('/');
415
+ const sitemapKnown = new Set(['/']);
416
+ for (const one of Array.isArray(allSitemapPaths) ? allSitemapPaths : []) {
417
+ const key = linkCompareKey(one);
418
+ if (!key) continue;
419
+ sitemapKnown.add(key);
420
+ allowed.add(key);
421
+ }
422
+ for (const one of Array.isArray(allowedPaths) ? allowedPaths : []) addAllowed(one);
423
+
424
+ const list = (Array.isArray(pages) ? pages : []).filter(
425
+ (one) => one && one.file && (one.status === 'written' || one.status === 'skipped'),
426
+ );
427
+ let checked = 0;
428
+ let missingCount = 0;
429
+ const missing = [];
430
+ const seenMissing = new Set();
431
+ for (const page of list) {
432
+ let html = '';
433
+ try {
434
+ html = String(fsImpl.readFileSync(path.join(distDir, String(page.file)), 'utf8'));
435
+ } catch {
436
+ continue; // 文件读不到就不体检这一页(写盘失败已经有自己的 warning)
437
+ }
438
+ for (const href of internalLinksInHtml(html)) {
439
+ checked += 1;
440
+ const key = linkCompareKey(href);
441
+ if (!key || allowed.has(key)) continue;
442
+ const token = `${page.file}\u0000${href}`;
443
+ if (seenMissing.has(token)) continue;
444
+ seenMissing.add(token);
445
+ missingCount += 1;
446
+ if (missing.length < MAX_LINK_MISSING) missing.push({ from: page.file, href });
447
+ }
448
+ }
449
+ return { checked, known_pages: sitemapKnown.size, missing, missing_count: missingCount };
450
+ }
451
+
452
+ /**
453
+ * `<dir>/.wkgeo/site.json`(栏目镜像)里的栏目路径 —— 链接体检允许集合的一部分。
454
+ * 镜像刚拉成功就直接用内存里的扁平表;失败 / 独立调用时回落读盘(先 `.wkgeo/`,
455
+ * 没有再读旧版放在站点根的 `site.json`;读不出来只返回空,不报错)。
456
+ */
457
+ function siteCategoryPathsOf({ fsImpl, workDir, siteMeta }) {
458
+ const out = [];
459
+ const collect = (list) => {
460
+ for (const one of Array.isArray(list) ? list : []) {
461
+ const p = one && one.path;
462
+ if (p) out.push(String(p));
463
+ }
464
+ };
465
+ if (siteMeta && siteMeta.ok) {
466
+ collect(siteMeta.categories);
467
+ return out;
468
+ }
469
+ try {
470
+ const candidates = [path.join(workDir, SITE_META_FILE), path.join(workDir, LEGACY_SITE_META_FILE)];
471
+ for (const file of candidates) {
472
+ if (typeof fsImpl.existsSync !== 'function' || !fsImpl.existsSync(file)) continue;
473
+ try {
474
+ const parsed = JSON.parse(String(fsImpl.readFileSync(file, 'utf8')));
475
+ collect(parsed && parsed.categories);
476
+ } catch {
477
+ /* 坏镜像:继续看下一个候选(兼容旧布局) */
478
+ }
479
+ break;
480
+ }
481
+ } catch {
482
+ /* 镜像读不出来就只用页清单,不影响主链路 */
483
+ }
484
+ return out;
485
+ }
486
+
487
+ /* -------------------------------------------------------------- 站点解析 */
488
+
489
+ /**
490
+ * CMS 成员站列表(`cmsMe` 不带 `x-cms-site` 的回包 `mySites`,平台维 id)。
491
+ *
492
+ * 为什么需要:平台 `listSites` 只查「自己名下」的站,协作站 / 主站管理员在那里可能是 0 条;
493
+ * 而 `cmsMe.mySites`(`listMySites`)是「成员 + owner」口径,域名 / 短域 / 站名都在。
494
+ * 解析失败只返回空数组(让外层报「没找到站点」并提示 `--cms-site`),不吞鉴权错误。
495
+ */
496
+ async function listCmsMemberSites({ config, fetchImpl, token }) {
497
+ const cms = createCms({ config, fetchImpl });
498
+ let me = null;
499
+ try {
500
+ me = await cms.call('cmsMe', {}, { token });
501
+ } catch (err) {
502
+ if (err && (err.exitCode === EXIT.AUTH || err.kind === 'cms_auth')) throw err;
503
+ return [];
504
+ }
505
+ const list = me && Array.isArray(me.mySites) ? me.mySites : [];
506
+ return list
507
+ .map((s) => ({
508
+ id: s && s.id,
509
+ name: s && s.name,
510
+ domain: s && s.domain,
511
+ domains: s && s.domain ? [s.domain] : [],
512
+ prefix_host: s && s.prefixHost,
513
+ }))
514
+ .filter((r) => r.id);
515
+ }
516
+
517
+ /**
518
+ * 解析出「平台站 id(public.site.id)」+「CMS 站 id(site_cms.id,`pageRender.siteId` 要它)」。
519
+ *
520
+ * cmsId 三条路(派单口径):
521
+ * ① `--cms-site <uuid>` 直接给;
522
+ * ② `cmsMe` 回包:`data.siteId` = CMS 维 id、`data.siteRowId` = 平台维 id,**两者对得上才认**;
523
+ * ③ 都拿不到 ⇒ 报错让人用 `--cms-site`(平台 `sites get` 不回 cms_id,别指望它)。
524
+ *
525
+ * @returns {Promise<{id:string, cmsId:string, label:string, matchedBy:string, cmsSource:'flag'|'cmsMe'}>}
526
+ */
527
+ export async function resolveSiteTarget({ site, cmsSite, config, credentials, fetchImpl }) {
528
+ const token = credentials && credentials.access_token;
529
+ const wanted = String(site || '').trim();
530
+ if (!wanted) {
531
+ throw new UsageError('没选站点:加 `--site <站点ID|域名|站名>`,或先 `wkgeo site use <站点ID>`', {
532
+ hint: '`site build` 只生成这一个站的 dist,绝不替你猜站。',
533
+ });
534
+ }
535
+
536
+ let publicId = '';
537
+ let label = '';
538
+ let matchedBy = '';
539
+ if (looksLikeUuid(wanted)) {
540
+ publicId = wanted;
541
+ matchedBy = 'id';
542
+ } else {
543
+ /** 平台 `listSites` 只覆盖「自己名下的站」;协作站 / 主站管理员在平台侧可能 0 条 ⇒ 回落 CMS `mySites` */
544
+ const api = createApi({ config, fetchImpl });
545
+ let rows = [];
546
+ let platformError = null;
547
+ try {
548
+ const res = await api.data('listSites', { limit: 200 }, { token });
549
+ rows = (res && Array.isArray(res.rows) ? res.rows : []).map((r) => r || {});
550
+ } catch (err) {
551
+ platformError = err;
552
+ }
553
+ let hit = matchSiteRow(rows, wanted);
554
+ if (!hit) {
555
+ const cmsRows = await listCmsMemberSites({ config, fetchImpl, token });
556
+ if (cmsRows.length) rows = cmsRows;
557
+ hit = matchSiteRow(rows, wanted);
558
+ }
559
+ if (!hit) {
560
+ const detail = platformError ? `(平台站列表也不可用:${(platformError && platformError.message) || platformError})` : '';
561
+ throw new CliError(`没有找到站点「${wanted}」(按域名 / 站名都没匹配上)${detail}`, {
562
+ kind: 'not_found',
563
+ code: 404,
564
+ hint: rows.length
565
+ ? `你能进的站:${rows
566
+ .slice(0, 10)
567
+ .map((r) => `${r.name || '(未命名)'}=${r.id}`)
568
+ .join(';')}${rows.length > 10 ? ` …共 ${rows.length} 个` : ''};也可以直接给站点 ID。`
569
+ : '当前账号名下没有站点(协作站也不在 CMS 成员表里)—— 请直接用站点 ID 或加 `--cms-site`。',
570
+ });
571
+ }
572
+ publicId = String(hit.id);
573
+ label = String(hit.label || '');
574
+ matchedBy = hit.matched_by || 'domain';
575
+ }
576
+
577
+ const explicitCms = String(cmsSite || '').trim();
578
+ if (explicitCms) {
579
+ if (!looksLikeUuid(explicitCms)) throw new UsageError(`--cms-site 要填 CMS 站点 ID(uuid),收到:${explicitCms}`);
580
+ return { id: publicId, cmsId: explicitCms, label, matchedBy, cmsSource: 'flag' };
581
+ }
582
+
583
+ /** ② `cmsMe`:Bearer 桥按 `x-cms-site`(平台站 id)解析出这个站,回包同时带两个维度的 id */
584
+ const cms = createCms({ config, fetchImpl });
585
+ let me = null;
586
+ try {
587
+ me = await cms.call('cmsMe', {}, { token, siteId: publicId });
588
+ } catch (err) {
589
+ if (err && (err.exitCode === EXIT.AUTH || err.kind === 'cms_auth')) throw err;
590
+ throw new CliError(`解析 CMS 站点 ID 失败:${(err && err.message) || err}`, {
591
+ kind: 'cms_site_unresolved',
592
+ code: (err && err.code) || null,
593
+ hint: '加 `--cms-site <CMS 站点ID>` 重试(CMS 后台站点设置里能看到);也可以先 `wkgeo site use <站点ID>` 再跑。',
594
+ cause: err,
595
+ });
596
+ }
597
+ const gotCms = String((me && me.siteId) || '').trim();
598
+ const gotRow = String((me && me.siteRowId) || '').trim();
599
+ if (gotRow && gotRow.toLowerCase() !== publicId.toLowerCase()) {
600
+ throw new CliError(
601
+ `站点对不上:--site 给的是 ${publicId},但当前 CMS 会话解析到的是 ${gotRow}`,
602
+ {
603
+ kind: 'cms_site_mismatch',
604
+ hint: '用 `--cms-site <CMS 站点ID>` 明确指定,或换成正确的站点 ID 重试(不会替你猜)。',
605
+ },
606
+ );
607
+ }
608
+ if (!gotCms) {
609
+ throw new CliError('没能解析出 CMS 站点 ID(cmsMe 没回 siteId)', {
610
+ kind: 'cms_site_unresolved',
611
+ hint: '加 `--cms-site <CMS 站点ID>` 重试;平台 `sites get` 不回 cms_id,这个只能从 CMS 后台或 cmsMe 拿。',
612
+ });
613
+ }
614
+ return { id: publicId, cmsId: gotCms, label: label || String((me && me.siteName) || ''), matchedBy, cmsSource: 'cmsMe' };
615
+ }
616
+
617
+ /* -------------------------------------------------------------- 资源包 */
618
+
619
+ /** 取站点资源包(CSS/JS 原文 + hash),落**模板目录**的 css/ 与 js/(页面引用 `/template/...`) */
620
+ function writeAssetBundle({ fsImpl, templateDir, bundle, warnings }) {
621
+ const hash = String((bundle && bundle.hash) || '').trim();
622
+ if (!ASSET_HASH_RE.test(hash)) {
623
+ throw new CliError('站点资源包没有可用的 hash(siteAssetBundle 回包缺 hash)', {
624
+ kind: 'asset_bundle',
625
+ hint: '稍后重试;一直这样请反馈服务端 `siteAssetBundle` 的回包字段(本题按 hash 落 site-<hash>.css|js)。',
626
+ });
627
+ }
628
+ const css = String((bundle && bundle.css) || '');
629
+ const js = String((bundle && bundle.js) || '');
630
+ const files = [
631
+ { rel: `css/site-${hash}.css`, body: css, kind: 'css', url: `${TEMPLATE_ASSET_BASE}css/site-${hash}.css` },
632
+ { rel: `js/site-${hash}.js`, body: js, kind: 'js', url: `${TEMPLATE_ASSET_BASE}js/site-${hash}.js` },
633
+ ];
634
+ const written = [];
635
+ for (const one of files) {
636
+ const abs = path.join(templateDir, one.rel);
637
+ try {
638
+ fsImpl.mkdirSync(path.dirname(abs), { recursive: true });
639
+ atomicWrite(fsImpl, abs, one.body);
640
+ written.push(one);
641
+ } catch (err) {
642
+ warnings.push(`站点资源包写盘失败(template/${one.rel}):${(err && err.message) || err}`);
643
+ }
644
+ }
645
+ return {
646
+ mode: 'external',
647
+ asset_base: TEMPLATE_ASSET_BASE,
648
+ hash,
649
+ css_file: `template/css/site-${hash}.css`,
650
+ js_file: `template/js/site-${hash}.js`,
651
+ css_url: `${TEMPLATE_ASSET_BASE}css/site-${hash}.css`,
652
+ js_url: `${TEMPLATE_ASSET_BASE}js/site-${hash}.js`,
653
+ css_bytes: byteLength(css),
654
+ js_bytes: byteLength(js),
655
+ written: written.length,
656
+ };
657
+ }
658
+
659
+ /**
660
+ * 模板静态资产(图片 / 字体 / 模板自带 css)**只检查、不复制**。
661
+ *
662
+ * 老板 2026-11-22 rev4:资产全部留在 `template\` 就地改,build 只出页面;
663
+ * 本地预览把站点根当静态根,页面里的 `/template/...` 就能直接开到这些文件。
664
+ */
665
+ function inspectTemplateAssets({ fsImpl, dir, warnings }) {
666
+ const srcRoot = path.join(dir, 'template', 'assets');
667
+ const available = fsImpl.existsSync(srcRoot);
668
+ if (!available) {
669
+ warnings.push('模板资产目录不存在(template/assets)—— 页面里的图片 / 字体在本地预览会 404;先把模板拉全再 build。');
670
+ }
671
+ return { mode: 'reference', dir: srcRoot, available, copied: 0, files: [] };
672
+ }
673
+
674
+ /* -------------------------------------------------------------- 渲染 */
675
+
676
+ /** 清点一页:found:false / 空 HTML / redirectTo 三种都按发布器口径处理 */
677
+ function pageContentOf(data) {
678
+ const redirectTo = String((data && data.redirectTo) || '').trim();
679
+ if (redirectTo && redirectTo.charAt(0) === '/') {
680
+ return { kind: 'redirect', html: redirectPageHtml(redirectTo, data && data.title), redirectTo };
681
+ }
682
+ if (!data || data.found !== true) return { kind: 'not_found', html: '' };
683
+ const html = String(data.html || '');
684
+ if (!html) return { kind: 'empty', html: '' };
685
+ return { kind: 'page', html };
686
+ }
687
+
688
+ /**
689
+ * 一页的完整处理:pageRender → 算 sha256 → 幂等判定 → 原子落盘。
690
+ * @returns {{entry:object}}
691
+ */
692
+ function renderOnePage({ cms, token, siteTarget, pagePath, assetsMode, assetHash, distDir, manifestEntry, fsImpl }) {
693
+ return (async () => {
694
+ const body = { siteId: siteTarget.cmsId, path: pagePath, surface: 'publish' };
695
+ if (assetsMode === 'external') {
696
+ body.assets = 'external';
697
+ body.assetBase = TEMPLATE_ASSET_BASE;
698
+ if (assetHash) body.assetHash = assetHash;
699
+ }
700
+ const data = await cms.call('pageRender', body, { token, siteId: siteTarget.id });
701
+ const content = pageContentOf(data);
702
+ if (content.kind === 'not_found') {
703
+ return {
704
+ entry: {
705
+ path: pagePath,
706
+ file: pageFileOf(pagePath),
707
+ sha256: '',
708
+ bytes: 0,
709
+ status: 'failed',
710
+ reason: '页面在 CMS 里不存在(pageRender found=false)',
711
+ code: 'NOT_FOUND',
712
+ },
713
+ };
714
+ }
715
+ if (content.kind === 'empty') {
716
+ return {
717
+ entry: {
718
+ path: pagePath,
719
+ file: pageFileOf(pagePath),
720
+ sha256: '',
721
+ bytes: 0,
722
+ status: 'failed',
723
+ reason: '渲染结果为空 HTML',
724
+ code: 'EMPTY_HTML',
725
+ },
726
+ };
727
+ }
728
+
729
+ const relFile = pageFileOf(pagePath);
730
+ const sha256 = sha256Of(content.html);
731
+ const bytes = byteLength(content.html);
732
+ const baseEntry = {
733
+ path: pagePath,
734
+ file: relFile,
735
+ sha256,
736
+ bytes,
737
+ status: 'written',
738
+ kind: content.kind,
739
+ };
740
+ if (content.kind === 'redirect') baseEntry.redirect_to = content.redirectTo;
741
+
742
+ const absFile = path.join(distDir, relFile);
743
+ const sameSha = manifestEntry && manifestEntry.sha256 === sha256;
744
+ if (sameSha && fsImpl.existsSync(absFile)) {
745
+ return { entry: { ...baseEntry, status: 'skipped' } };
746
+ }
747
+ fsImpl.mkdirSync(path.dirname(absFile), { recursive: true });
748
+ atomicWrite(fsImpl, absFile, content.html);
749
+ return { entry: baseEntry };
750
+ })();
751
+ }
752
+
753
+ /* -------------------------------------------------------------- 主流程 */
754
+
755
+ /**
756
+ * 生成一个站的本地静态产物。
757
+ *
758
+ * @param {object} opts
759
+ * @param {string} opts.dir 工作区目录(里面有 `template/`;html/ 落它下面,
760
+ * `build-manifest.json` 落 `<dir>/.wkgeo/`)
761
+ * @param {string} [opts.site] 站点(uuid / 域名 / 站名;空 ⇒ 报用法错误,命令层已把本地选站补进来)
762
+ * @param {string} [opts.cmsSite] CMS 站 id(跳过 cmsMe 解析)
763
+ * @param {'external'|'inline'} [opts.assets='external'] 站点资源外部化模式
764
+ * @param {number} [opts.concurrency=4]
765
+ * @param {number} [opts.maxPages=0] 0 = 不限
766
+ * @param {object} [opts.config] 注入的 CLI 配置(`base` / `cmsBase` / `httpTimeoutMs`)
767
+ * @param {{access_token:string}} [opts.credentials]
768
+ * @param {Function} [opts.fetchImpl] 注入的 fetch(单测用)
769
+ * @param {object} [opts.fsImpl] 注入的 fs(默认 node:fs;单测用)
770
+ * @param {Function} [opts.log] 诊断日志(不写 stdout)
771
+ * @returns {Promise<object>} payload(`--json` 的那份数据)
772
+ */
773
+ export async function buildStaticSite(opts = {}) {
774
+ const {
775
+ dir,
776
+ site = '',
777
+ cmsSite = '',
778
+ assets = 'external',
779
+ outDir = '',
780
+ concurrency = DEFAULT_CONCURRENCY,
781
+ maxPages = 0,
782
+ config = {},
783
+ credentials = null,
784
+ fetchImpl = globalThis.fetch,
785
+ fsImpl = fs,
786
+ log = () => {},
787
+ } = opts;
788
+
789
+ const workDir = path.resolve(String(dir === undefined || dir === null || dir === '' ? '.' : dir));
790
+ const assetsMode = normalizeAssetMode(assets);
791
+ const limit = normalizeConcurrency(concurrency);
792
+ const maxPagesLimit = normalizeMaxPages(maxPages);
793
+ if (!credentials || !credentials.access_token) {
794
+ throw new CliError('内部错误:site build 需要登录态(缺少 access_token)', { kind: 'internal', exitCode: EXIT.AUTH });
795
+ }
796
+
797
+ const warnings = [];
798
+ const siteTarget = await resolveSiteTarget({ site, cmsSite, config, credentials, fetchImpl });
799
+ log(`site build:站点 ${siteTarget.id}(CMS ${siteTarget.cmsId},来源 ${siteTarget.cmsSource})`);
800
+
801
+ /**
802
+ * ⓪ 栏目树镜像:`<dir>/.wkgeo/site.json`(只读线上、只写本地)。
803
+ * 失败只记 warning、旧镜像保留,**不阻断**页面生成 —— 镜像不是主链路。
804
+ */
805
+ const siteMeta = await pullSiteMeta({
806
+ dir: workDir,
807
+ siteTarget,
808
+ config,
809
+ credentials,
810
+ fetchImpl,
811
+ fsImpl,
812
+ log,
813
+ });
814
+ warnings.push(...siteMeta.warnings);
815
+ if (!siteMeta.ok) {
816
+ warnings.push(`栏目树镜像 ${SITE_META_FILE} 未更新(${siteMeta.code}):${siteMeta.message};旧文件保持不变`);
817
+ }
818
+
819
+ const cms = createCms({ config, fetchImpl });
820
+ const token = credentials.access_token;
821
+ const outDirName = normalizeOutDir(outDir);
822
+ const distDir = path.join(workDir, outDirName);
823
+
824
+ fsImpl.mkdirSync(distDir, { recursive: true });
825
+
826
+ /** ① 站点资源包(external 模式才有;inline 模式页面自带样式)→ 落 template/css|js(引用 `/template/...`) */
827
+ let assetInfo = { mode: 'inline' };
828
+ if (assetsMode === 'external') {
829
+ const bundle = await cms.call(
830
+ 'siteAssetBundle',
831
+ { siteId: siteTarget.cmsId },
832
+ { token, siteId: siteTarget.id },
833
+ );
834
+ assetInfo = writeAssetBundle({ fsImpl, templateDir: path.join(workDir, 'template'), bundle, warnings });
835
+ }
836
+
837
+ /** ② 模板静态资产:**只检查不复制**(rev4:资产留在 template/,本地预览用站点根) */
838
+ const templateAssets = inspectTemplateAssets({ fsImpl, dir: workDir, warnings });
839
+
840
+ /** ③ 页清单:首页 + 栏目 + 内容 + 标签(严格校验、去重) */
841
+ const sitemap = await cms.call('publicSitemap', { site: siteTarget.id, format: 'json' }, { token, siteId: siteTarget.id });
842
+ const listed = pagePathsFromSitemap(sitemap);
843
+ warnings.push(...listed.warnings);
844
+ /** 全量 sitemap 路径(截断前)—— 链接体检的「已知页面」集合,`--max-pages` 只影响生成、不影响它 */
845
+ const allSitemapPaths = listed.paths;
846
+ let paths = allSitemapPaths;
847
+ let limited = false;
848
+ if (maxPagesLimit > 0 && paths.length > maxPagesLimit) {
849
+ paths = allSitemapPaths.slice(0, maxPagesLimit);
850
+ limited = true;
851
+ }
852
+ const totalAvailable = allSitemapPaths.length;
853
+
854
+ /** 旧 manifest:幂等判定用(先 `.wkgeo/`;没有再兼容读旧版放站点根的清单,只读不写) */
855
+ const manifestFile = path.join(workDir, BUILD_MANIFEST_FILE);
856
+ const legacyManifestFile = path.join(workDir, LEGACY_BUILD_MANIFEST_FILE);
857
+ const exists = typeof fsImpl.existsSync === 'function' ? (p) => fsImpl.existsSync(p) : () => false;
858
+ const oldManifestFile = exists(manifestFile) ? manifestFile : exists(legacyManifestFile) ? legacyManifestFile : '';
859
+ if (oldManifestFile && oldManifestFile === legacyManifestFile) {
860
+ warnings.push(
861
+ `读到站点根下的旧 ${LEGACY_BUILD_MANIFEST_FILE}(兼容读取,只用于幂等判定,不迁移、不删旧文件);` +
862
+ `本次仍写 ${BUILD_MANIFEST_FILE},旧文件可自行删除`,
863
+ );
864
+ }
865
+ let oldManifest = null;
866
+ if (oldManifestFile) {
867
+ try {
868
+ const text = fsImpl.readFileSync(oldManifestFile, 'utf8');
869
+ const parsed = JSON.parse(String(text));
870
+ if (parsed && typeof parsed === 'object' && Array.isArray(parsed.pages)) oldManifest = parsed;
871
+ } catch (err) {
872
+ warnings.push(`旧 build-manifest.json 读不出来,按全量重写:${(err && err.message) || err}`);
873
+ }
874
+ }
875
+ const oldPages = new Map();
876
+ for (const one of (oldManifest && oldManifest.pages) || []) {
877
+ if (one && one.path) oldPages.set(String(one.path), one);
878
+ }
879
+
880
+ /** ④ 逐页渲染(并发有上限;单页失败不中断整批,站点级故障才终止) */
881
+ const results = new Array(paths.length);
882
+ let fatalError = null;
883
+ let cursor = 0;
884
+ const renderNext = async () => {
885
+ for (;;) {
886
+ if (fatalError) return;
887
+ const index = cursor;
888
+ cursor += 1;
889
+ if (index >= paths.length) return;
890
+ const pagePath = paths[index];
891
+ try {
892
+ const { entry } = await renderOnePage({
893
+ cms,
894
+ token,
895
+ siteTarget,
896
+ pagePath,
897
+ assetsMode,
898
+ assetHash: assetInfo.mode === 'external' ? assetInfo.hash : '',
899
+ distDir,
900
+ manifestEntry: oldPages.get(pagePath) || null,
901
+ fsImpl,
902
+ });
903
+ results[index] = entry;
904
+ if (entry.status === 'written') log(` + ${pagePath} → ${entry.file}(${entry.bytes} B)`);
905
+ } catch (err) {
906
+ if (isFatalRenderError(err)) {
907
+ if (!fatalError) fatalError = { err, pagePath };
908
+ return;
909
+ }
910
+ results[index] = {
911
+ path: pagePath,
912
+ file: pageFileOf(pagePath),
913
+ sha256: '',
914
+ bytes: 0,
915
+ status: 'failed',
916
+ reason: (err && err.message) || String(err),
917
+ code: (err && err.code) || null,
918
+ };
919
+ log(` ✗ ${pagePath}:${(err && err.message) || err}`);
920
+ }
921
+ }
922
+ };
923
+ const workerCount = Math.max(1, Math.min(limit, paths.length));
924
+ await Promise.all(Array.from({ length: workerCount }, () => renderNext()));
925
+
926
+ if (fatalError) {
927
+ const err = fatalError.err;
928
+ if (err && (err.code === 410 || err.kind === 'SITE_UNAVAILABLE')) {
929
+ throw new CliError('站点当前不可访问(已下架 / 已到期),不能本地生成', {
930
+ kind: 'SITE_UNAVAILABLE',
931
+ code: 410,
932
+ hint: '站点状态问题,不是命令写错:等站点恢复(续费 / 上架)后重试。',
933
+ cause: err,
934
+ });
935
+ }
936
+ throw err;
937
+ }
938
+
939
+ const pages = results.filter(Boolean);
940
+ const counts = {
941
+ total: pages.length,
942
+ written: pages.filter((one) => one.status === 'written').length,
943
+ skipped: pages.filter((one) => one.status === 'skipped').length,
944
+ failed: pages.filter((one) => one.status === 'failed').length,
945
+ };
946
+
947
+ /**
948
+ * ⑤ 站内链接体检(对照组 = 全量 sitemap 路径 + 本次页清单 + `site.json` 栏目路径)——
949
+ * 只报警、**不改 exit 码**(老板 2026-11-22:本地 build 时把模板里的死链暴露出来)。
950
+ * `--max-pages` 只限制生成页数,**不缩小已知页面集合**:sitemap 里存在但本次没生成的内容页
951
+ * 不算死链(否则 `--max-pages 5` 会误报上百条);`known_pages` = 全量 sitemap 路径数。
952
+ */
953
+ const linkCheckResult = linkCheck({
954
+ fsImpl,
955
+ distDir,
956
+ pages,
957
+ allSitemapPaths,
958
+ allowedPaths: pages.map((one) => one.path).concat(siteCategoryPathsOf({ fsImpl, workDir, siteMeta })),
959
+ });
960
+ if (linkCheckResult.missing_count > 0) {
961
+ const examples = linkCheckResult.missing
962
+ .slice(0, 3)
963
+ .map((one) => `${one.from} → ${one.href}`)
964
+ .join(';');
965
+ warnings.push(
966
+ `${linkCheckResult.missing_count} 个站内链接指向不存在的页面(只报警,不影响生成)` + (examples ? `:${examples}` : ''),
967
+ );
968
+ }
969
+
970
+ /** ⑥ 写本地清单(只记写入 / 跳过的页;失败的页下次自然重试) */
971
+ const manifest = {
972
+ version: 1,
973
+ generated_at: new Date().toISOString(),
974
+ site: {
975
+ id: siteTarget.id,
976
+ cms_id: siteTarget.cmsId,
977
+ label: siteTarget.label,
978
+ matched_by: siteTarget.matchedBy,
979
+ cms_source: siteTarget.cmsSource,
980
+ },
981
+ out_dir: outDirName,
982
+ assets: assetInfo,
983
+ template_assets: {
984
+ mode: templateAssets.mode,
985
+ dir: templateAssets.dir,
986
+ available: templateAssets.available,
987
+ copied: templateAssets.copied,
988
+ },
989
+ pages: pages
990
+ .filter((one) => one.status !== 'failed')
991
+ .map((one) => ({ path: one.path, file: one.file, sha256: one.sha256, bytes: one.bytes, status: one.status })),
992
+ };
993
+ try {
994
+ if (typeof fsImpl.mkdirSync === 'function') fsImpl.mkdirSync(path.dirname(manifestFile), { recursive: true });
995
+ atomicWrite(fsImpl, manifestFile, `${JSON.stringify(manifest, null, 2)}\n`);
996
+ } catch (err) {
997
+ warnings.push(`${BUILD_MANIFEST_FILE} 写盘失败:${(err && err.message) || err}`);
998
+ }
999
+
1000
+ const payload = {
1001
+ ok: counts.failed === 0,
1002
+ site: {
1003
+ id: siteTarget.id,
1004
+ cms_id: siteTarget.cmsId,
1005
+ label: siteTarget.label,
1006
+ matched_by: siteTarget.matchedBy,
1007
+ cms_source: siteTarget.cmsSource,
1008
+ origin: String((sitemap && sitemap.site && sitemap.site.origin) || ''),
1009
+ },
1010
+ dir: workDir,
1011
+ out: distDir,
1012
+ out_dir: outDirName,
1013
+ /** 兼容旧字段(2026-11-22 rev4 起产物叫 html;`dist` 不再是默认目录名) */
1014
+ dist: distDir,
1015
+ assets: assetInfo,
1016
+ template_assets: {
1017
+ mode: templateAssets.mode,
1018
+ dir: templateAssets.dir,
1019
+ available: templateAssets.available,
1020
+ copied: templateAssets.copied,
1021
+ files: templateAssets.files,
1022
+ },
1023
+ pages,
1024
+ counts,
1025
+ link_check: linkCheckResult,
1026
+ page_limit: { max_pages: maxPagesLimit, limited, total_available: totalAvailable, empty_site: listed.emptySite },
1027
+ manifest_file: manifestFile,
1028
+ site_meta: {
1029
+ file: siteMeta.file,
1030
+ categories: siteMeta.ok ? siteMeta.counts.categories : 0,
1031
+ written: siteMeta.ok && siteMeta.written === true,
1032
+ },
1033
+ warnings,
1034
+ read_only: true,
1035
+ };
1036
+ if (counts.failed > 0) {
1037
+ const err = new CliError(`本地生成完成,但有 ${counts.failed} 个页面失败`, {
1038
+ kind: 'build_failed',
1039
+ exitCode: EXIT.ERROR,
1040
+ hint: '看 pages[].reason(或人类输出的「✗」行):改完线上内容重跑即可,幂等(成功页会 skipped)。',
1041
+ });
1042
+ err.details = payload;
1043
+ err.raw = payload;
1044
+ throw err;
1045
+ }
1046
+ return payload;
1047
+ }