@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/CHANGELOG.md +19 -2
- package/README.md +7 -7
- package/SKILL.md +1038 -1038
- package/lib/api.mjs +351 -351
- package/lib/args.mjs +235 -235
- package/lib/build.mjs +1047 -0
- package/lib/cms.mjs +328 -328
- package/lib/commands/auth.mjs +1280 -1280
- package/lib/commands/data.mjs +694 -694
- package/lib/commands/index.mjs +17 -1
- package/lib/commands/init.mjs +111 -111
- package/lib/commands/orders.mjs +691 -691
- package/lib/commands/site.mjs +82 -0
- package/lib/commands/siteops.mjs +382 -0
- package/lib/commands/sites.mjs +968 -801
- package/lib/commands/spec.mjs +72 -72
- package/lib/commands/template.mjs +1484 -1484
- package/lib/config.mjs +57 -4
- package/lib/errors.mjs +446 -336
- package/lib/manifest-apply.mjs +1650 -1650
- package/lib/manifest-schema.json +480 -480
- package/lib/manifest.mjs +1106 -1106
- package/lib/runtime.mjs +798 -654
- package/lib/site-create.mjs +537 -537
- package/lib/site-credentials.mjs +157 -0
- package/lib/site-meta.mjs +474 -0
- package/lib/site-publish.mjs +410 -0
- package/lib/site-spec.mjs +302 -302
- package/lib/site-template.mjs +405 -0
- package/lib/template-gen.mjs +1354 -1354
- package/lib/template-publish.mjs +696 -696
- package/lib/templates-sync.mjs +676 -644
- package/lib/workspace-sync.mjs +386 -0
- package/package.json +56 -56
- package/spec/SITE-SPEC.md +198 -198
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 按站票据(site credential):**一个站点一张短票**,只在这个站点的目录里生效。
|
|
3
|
+
*
|
|
4
|
+
* 背景(老板 2026-11-22:「网站运营」插件 v14 / 平台开关 `SITE_CRED_WRITE_MODE`):
|
|
5
|
+
* 平台把「写站点」从「账号令牌就能写」收紧成「必须用该站的短票写」,
|
|
6
|
+
* 账号令牌写站会被 403 `site_credential_required`。
|
|
7
|
+
* 票由**网站运营面板**在点站点卡片时自动签(`POST /cms {action:'siteKeyMint'}`),
|
|
8
|
+
* 落在本机 `%LOCALAPPDATA%\wkgeo-ops\creds\<siteId>.json`。
|
|
9
|
+
*
|
|
10
|
+
* 这个文件是 CLI 侧的**只读发现器**:
|
|
11
|
+
* · 没有显式 `WKONGAI_CREDENTIALS` / `--credentials` 时,按 **cwd 落在哪个站的目录** 找票;
|
|
12
|
+
* · 找不到 / 票过期 ⇒ 返回 null,CLI 原样用账号凭据(普通目录零影响);
|
|
13
|
+
* · 票文件本身是 CLI 原生凭据形状(含 `access_token` / `expires_at`),
|
|
14
|
+
* 命中后直接把 `config.credentialsFile` 指过去即可,所有命令自动用这张票。
|
|
15
|
+
*
|
|
16
|
+
* ⚠️ 票是明文文件(`%LOCALAPPDATA%` 默认只有当前用户可读)。读到票 = 能写那个站,
|
|
17
|
+
* 所以这里**不做任何日志输出**,也不把 token 往外抛(只给上层文件路径)。
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import os from 'node:os';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
|
|
24
|
+
/** 票据目录的环境变量覆盖(测试 / 多 profile 用;生产走 %LOCALAPPDATA%) */
|
|
25
|
+
export const SITE_CREDS_ENV = 'WKONGAI_SITE_CREDS_DIR';
|
|
26
|
+
|
|
27
|
+
/** 票文件里的标记(`kind`),用于和普通凭据文件区分 */
|
|
28
|
+
export const SITE_CREDENTIAL_KIND = 'site-credential';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 票据目录。
|
|
32
|
+
* ① `WKONGAI_SITE_CREDS_DIR` 显式指定;
|
|
33
|
+
* ② Windows:`%LOCALAPPDATA%\wkgeo-ops\creds`(插件服务端写同一处);
|
|
34
|
+
* ③ 非 Windows / 没有 LOCALAPPDATA:返回空串 ⇒ 这个功能整体关闭(不影响账号凭据)。
|
|
35
|
+
* @returns {string}
|
|
36
|
+
*/
|
|
37
|
+
export function siteCredsDirOf(env = process.env) {
|
|
38
|
+
const explicit = String((env && env[SITE_CREDS_ENV]) || '').trim();
|
|
39
|
+
if (explicit) return path.resolve(explicit);
|
|
40
|
+
const localAppData = String((env && env.LOCALAPPDATA) || '').trim();
|
|
41
|
+
if (localAppData) return path.join(localAppData, 'wkgeo-ops', 'creds');
|
|
42
|
+
if (process.platform === 'win32') return path.join(os.homedir(), 'AppData', 'Local', 'wkgeo-ops', 'creds');
|
|
43
|
+
return '';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 路径比较键:resolve + 去尾分隔符 + win32 小写(和插件 lib 的 pathKeyOf 同口径) */
|
|
47
|
+
export function sitePathKey(dir) {
|
|
48
|
+
let p = path.resolve(String(dir == null ? '' : dir));
|
|
49
|
+
p = p.replace(/[\\/]+$/, '');
|
|
50
|
+
if (process.platform === 'win32') p = p.toLowerCase();
|
|
51
|
+
return p;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** `child` 在 `parent` 里面(含相等) */
|
|
55
|
+
export function isSitePathInside(parent, child) {
|
|
56
|
+
const base = sitePathKey(parent);
|
|
57
|
+
const target = sitePathKey(child);
|
|
58
|
+
if (!base || !target) return false;
|
|
59
|
+
if (base === target) return true;
|
|
60
|
+
return target.startsWith(base + path.sep) || target.startsWith(base + '/');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 把票文件解析成统一记录;形状不对返回 null(坏文件当不存在,绝不抛)。
|
|
65
|
+
* @returns {{kind:string,file:string,siteId:string,siteDir:string,cmsId:string,accessToken:string,expiresAt:string,expiresMs:number,keyPrefix:string}|null}
|
|
66
|
+
*/
|
|
67
|
+
export function normalizeSiteCredential(raw, file = '') {
|
|
68
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
69
|
+
const accessToken = String(raw.access_token || '').trim();
|
|
70
|
+
if (!accessToken) return null;
|
|
71
|
+
const site = raw.site && typeof raw.site === 'object' ? raw.site : {};
|
|
72
|
+
const siteId = String(site.id || raw.site_id || '').trim();
|
|
73
|
+
const siteDir = String(site.dir || site.directory || raw.site_dir || '').trim();
|
|
74
|
+
const expiresAt = String(raw.expires_at || '').trim();
|
|
75
|
+
const expiresMs = expiresAt ? Date.parse(expiresAt) : Number.NaN;
|
|
76
|
+
return {
|
|
77
|
+
kind: SITE_CREDENTIAL_KIND,
|
|
78
|
+
file,
|
|
79
|
+
siteId,
|
|
80
|
+
siteDir,
|
|
81
|
+
cmsId: String(site.cmsId || site.cms_id || raw.cms_id || '').trim(),
|
|
82
|
+
accessToken,
|
|
83
|
+
expiresAt,
|
|
84
|
+
expiresMs: Number.isFinite(expiresMs) ? expiresMs : 0,
|
|
85
|
+
keyPrefix: String(raw.key_prefix || '').trim(),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 读单个票文件;不存在 / 坏 JSON / 形状不对 ⇒ null */
|
|
90
|
+
export function readSiteCredentialFile(file) {
|
|
91
|
+
if (!file) return null;
|
|
92
|
+
let text;
|
|
93
|
+
try {
|
|
94
|
+
text = fs.readFileSync(file, 'utf8');
|
|
95
|
+
} catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
return normalizeSiteCredential(JSON.parse(text), file);
|
|
100
|
+
} catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 票是否按本地记录已过期(留 60 秒时钟偏差;没有过期信息 ⇒ 不当过期,交给服务端判) */
|
|
106
|
+
export function isSiteCredentialExpired(record, { now = Date.now(), skewMs = 60000 } = {}) {
|
|
107
|
+
if (!record) return true;
|
|
108
|
+
if (!record.expiresMs) return false;
|
|
109
|
+
return record.expiresMs - skewMs <= now;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 列出票据目录里的所有票(坏文件跳过;目录不存在 ⇒ 空数组) */
|
|
113
|
+
export function listSiteCredentials({ env = process.env, now = Date.now() } = {}) {
|
|
114
|
+
const dir = siteCredsDirOf(env);
|
|
115
|
+
if (!dir) return [];
|
|
116
|
+
let entries = [];
|
|
117
|
+
try {
|
|
118
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
119
|
+
} catch {
|
|
120
|
+
return [];
|
|
121
|
+
}
|
|
122
|
+
const out = [];
|
|
123
|
+
for (const entry of entries) {
|
|
124
|
+
if (!entry || !entry.isFile || !entry.isFile()) continue;
|
|
125
|
+
if (!/\.json$/i.test(entry.name)) continue;
|
|
126
|
+
const record = readSiteCredentialFile(path.join(dir, entry.name));
|
|
127
|
+
if (!record) continue;
|
|
128
|
+
record.expired = isSiteCredentialExpired(record, { now });
|
|
129
|
+
out.push(record);
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 按当前目录找票:cwd 落在票记录的 `site.dir` 里面(含相等)就算命中。
|
|
136
|
+
* 多个命中取**最深**的那个目录(嵌套绑定不会串站);过期票跳过。
|
|
137
|
+
*
|
|
138
|
+
* @param {{cwd?:string, env?:object, now?:number}} [options]
|
|
139
|
+
* @returns {ReturnType<typeof normalizeSiteCredential>|null}
|
|
140
|
+
*/
|
|
141
|
+
export function findSiteCredentialForCwd({ cwd = '', env = process.env, now = Date.now() } = {}) {
|
|
142
|
+
const target = String(cwd || '').trim();
|
|
143
|
+
if (!target) return null;
|
|
144
|
+
let best = null;
|
|
145
|
+
let bestDepth = -1;
|
|
146
|
+
for (const record of listSiteCredentials({ env, now })) {
|
|
147
|
+
if (record.expired) continue;
|
|
148
|
+
if (!record.siteDir) continue;
|
|
149
|
+
if (!isSitePathInside(record.siteDir, target)) continue;
|
|
150
|
+
const depth = sitePathKey(record.siteDir).length;
|
|
151
|
+
if (depth > bestDepth) {
|
|
152
|
+
best = record;
|
|
153
|
+
bestDepth = depth;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return best;
|
|
157
|
+
}
|
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 栏目树本地镜像(`<dir>/.wkgeo/site.json`)—— `site build` 的附属产物,**只读线上、只写本地**。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么要有这份镜像
|
|
5
|
+
* `site build` 生成 dist 时顺手把「这个站有哪些栏目、各自什么路径 / 层级」落到工作区,
|
|
6
|
+
* 本地改模板 / 对版式 / 排查地址时就不用每次先连一次 CMS。它只是**镜像**:
|
|
7
|
+
* 栏目与内容真源仍在线上,本地不参与编辑(不做双向同步)。
|
|
8
|
+
*
|
|
9
|
+
* ## 目录口径(老板 2026-11-22)
|
|
10
|
+
* 站点根只允许 `AGENTS.md` + `template/` + `html/` + `.wkgeo/`;镜像与
|
|
11
|
+
* `build-manifest.json` 都收进 `.wkgeo/`(首次写入自动建目录)。
|
|
12
|
+
* 旧版把 `site.json` 直接放在站点根:**兼容读取**(`.wkgeo/` 里没有时才读根目录旧文件,
|
|
13
|
+
* 只登记、不迁移、不删),写入永远写 `.wkgeo/`。
|
|
14
|
+
*
|
|
15
|
+
* ## 数据从哪来
|
|
16
|
+
* CMS 公开动作 `publicCategories`(免登录口径,`data:{site,language,total,categories:[树]}`)。
|
|
17
|
+
* 回包栏目节点**仍带正文字段**(`bodyHtml` / `bodyText`,未锁定栏目;task-42 实测),
|
|
18
|
+
* 但镜像口径是「内容只在线上」 ⇒ `tree` 与 `categories` 都只落**结构白名单**
|
|
19
|
+
* (`pickCategoryShape`:身份 / 父子 / 名称 / 地址 / 层级 / 排序 / 类型 / 权限 / 锁定 / 短 seoTitle),
|
|
20
|
+
* 正文与其余展示字段(封面 / 副标题 / 关键词 / 描述 / JSON-LD / 跳转快照等)一律丢弃。
|
|
21
|
+
* 另外派一份**前序扁平表** `categories`(父子关系 / 排序 / 路径都算好),给本地按栏目循环时用。
|
|
22
|
+
*
|
|
23
|
+
* ## 幂等
|
|
24
|
+
* 除 `fetchedAt` 外内容一字不差 ⇒ **不写盘**(mtime 不动),返回 `written:false`;
|
|
25
|
+
* 所以 `site build` 反复跑一个没改栏目表的站,`site.json` 不会被无意义地刷新。
|
|
26
|
+
* 例外:镜像只在旧根目录(兼容读取)时不算幂等命中 —— 必须写一份到 `.wkgeo/`。
|
|
27
|
+
*
|
|
28
|
+
* ## 失败边界
|
|
29
|
+
* 拉取 / 组装失败 ⇒ 返回 `{ok:false, code:'CATEGORIES_FAILED', message}`,**旧 site.json 原样保留**;
|
|
30
|
+
* `site build` 只把它记进 warnings,不阻断页面生成(镜像不该拖垮主链路)。
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import fs from 'node:fs';
|
|
34
|
+
import path from 'node:path';
|
|
35
|
+
|
|
36
|
+
import { createCms } from './cms.mjs';
|
|
37
|
+
|
|
38
|
+
/** 工作区状态目录(站点根只放 AGENTS.md / template/ / html/,状态与对账记录都收进这里) */
|
|
39
|
+
export const WORKSPACE_STATE_DIR = '.wkgeo';
|
|
40
|
+
|
|
41
|
+
/** 工作区里的镜像文件(在 `.wkgeo/` 下,首次写入自动建目录) */
|
|
42
|
+
export const SITE_META_FILE = `${WORKSPACE_STATE_DIR}/site.json`;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 兼容读取:旧版把 `site.json` 直接放在站点根。
|
|
46
|
+
* 只在 `.wkgeo/site.json` 不存在时才读它(只登记、不迁移、不删旧文件);写入永远写 `.wkgeo/`。
|
|
47
|
+
*/
|
|
48
|
+
export const LEGACY_SITE_META_FILE = 'site.json';
|
|
49
|
+
|
|
50
|
+
/** 镜像格式版本(字段形状变了就加,读旧版按全量重写;v2 = 栏目节点改结构白名单) */
|
|
51
|
+
export const SITE_META_VERSION = 2;
|
|
52
|
+
|
|
53
|
+
/** 告警上限:镜像是一个站一个站看,50 条足够,不刷屏 */
|
|
54
|
+
const MAX_WARNINGS = 50;
|
|
55
|
+
|
|
56
|
+
/* -------------------------------------------------------------- 结构白名单 */
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 栏目节点**结构字段**白名单(`tree` 与 `categories` 共用)。
|
|
60
|
+
*
|
|
61
|
+
* `site.json` 只镜像结构 —— 这些字段之外的键(尤其是正文)一律不落盘。
|
|
62
|
+
* 顺序即落盘顺序(固定顺序保证同一份栏目表永远序列化出同一份文本 ⇒ 幂等)。
|
|
63
|
+
*/
|
|
64
|
+
export const CATEGORY_SHAPE_FIELDS = Object.freeze([
|
|
65
|
+
'id',
|
|
66
|
+
'parentId',
|
|
67
|
+
'name',
|
|
68
|
+
'path',
|
|
69
|
+
'url',
|
|
70
|
+
'level',
|
|
71
|
+
'sort',
|
|
72
|
+
'kind',
|
|
73
|
+
'hasChildren',
|
|
74
|
+
'access',
|
|
75
|
+
'locked',
|
|
76
|
+
]);
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* `publicCategories` 回包里**带正文 / 富文本**的字段(task-42 实测:未锁定栏目会带
|
|
80
|
+
* `bodyHtml` / `bodyText`,其余为防御性别名)。
|
|
81
|
+
*
|
|
82
|
+
* 白名单机制本就会把这些键丢掉;显式列出来是为了:① 让「哪些算正文」有据可查;
|
|
83
|
+
* ② 单测拿它做**递归断言**(任何层级出现即失败)。
|
|
84
|
+
*/
|
|
85
|
+
export const CATEGORY_BODY_FIELDS = Object.freeze([
|
|
86
|
+
'bodyHtml',
|
|
87
|
+
'bodyText',
|
|
88
|
+
'body',
|
|
89
|
+
'richText',
|
|
90
|
+
'richtext_id',
|
|
91
|
+
'content',
|
|
92
|
+
'summary',
|
|
93
|
+
]);
|
|
94
|
+
|
|
95
|
+
/** `seoTitle` 长度上限:源里是「短标题」才收,超过 120 字符视为正文类字段丢弃 */
|
|
96
|
+
export const SEO_TITLE_MAX = 120;
|
|
97
|
+
|
|
98
|
+
/** 子栏目:优先认源里的 `hasChildren`,其次 `has_categories` / `hasCategories`,最后看 children */
|
|
99
|
+
function sourceHasChildren(node) {
|
|
100
|
+
if (node.hasChildren !== undefined) return node.hasChildren === true;
|
|
101
|
+
if (node.has_categories !== undefined) return node.has_categories === true;
|
|
102
|
+
if (node.hasCategories !== undefined) return node.hasCategories === true;
|
|
103
|
+
return Array.isArray(node.children) && node.children.length > 0;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 短 SEO 标题:只有非空字符串且 ≤ `SEO_TITLE_MAX` 才收,其余丢弃(返回空串) */
|
|
107
|
+
function shortSeoTitleOf(node) {
|
|
108
|
+
const raw = node.seoTitle;
|
|
109
|
+
if (typeof raw !== 'string') return '';
|
|
110
|
+
const text = raw.trim();
|
|
111
|
+
return text && text.length <= SEO_TITLE_MAX ? text : '';
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 栏目节点 → `site.json` 里的结构形状(**白名单**取字段,其余一律丢弃)。
|
|
116
|
+
*
|
|
117
|
+
* @param {object} node `publicCategories` 回的原始节点(或扁平化时的中间节点)
|
|
118
|
+
* @returns {{id:string,parentId:string,name:string,path:string,url:string,level:number,
|
|
119
|
+
* sort:number,kind:string,hasChildren:boolean,access:string,locked:boolean,
|
|
120
|
+
* seoTitle?:string}}
|
|
121
|
+
*/
|
|
122
|
+
export function pickCategoryShape(node) {
|
|
123
|
+
const src = node && typeof node === 'object' ? node : {};
|
|
124
|
+
const level = Number(src.level);
|
|
125
|
+
const sort = Number(src.sort);
|
|
126
|
+
const shaped = {
|
|
127
|
+
id: src.id === undefined || src.id === null ? '' : String(src.id),
|
|
128
|
+
parentId: src.parentId === undefined || src.parentId === null ? '' : String(src.parentId),
|
|
129
|
+
name: String(src.name || ''),
|
|
130
|
+
path: String(src.path || ''),
|
|
131
|
+
url: String(src.url || ''),
|
|
132
|
+
level: Number.isFinite(level) ? level : 1,
|
|
133
|
+
sort: Number.isFinite(sort) ? sort : 0,
|
|
134
|
+
kind: String(src.kind || ''),
|
|
135
|
+
hasChildren: sourceHasChildren(src),
|
|
136
|
+
access: String(src.access || 'public'),
|
|
137
|
+
locked: src.locked === true,
|
|
138
|
+
};
|
|
139
|
+
const seoTitle = shortSeoTitleOf(src);
|
|
140
|
+
if (seoTitle) shaped.seoTitle = seoTitle;
|
|
141
|
+
return shaped;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* 栏目树 → **结构树**(递归走同一白名单;顺序保持回包原序,方便和线上对照)。
|
|
146
|
+
*
|
|
147
|
+
* `children` 是结构字段(不是正文),始终保留为数组,叶子为 `[]`。
|
|
148
|
+
*
|
|
149
|
+
* @param {Array} tree `publicCategories` 回的 `categories`
|
|
150
|
+
* @returns {Array<object>}
|
|
151
|
+
*/
|
|
152
|
+
export function sanitizeCategoryTree(tree) {
|
|
153
|
+
if (!Array.isArray(tree)) return [];
|
|
154
|
+
return tree.map((node) => {
|
|
155
|
+
const shaped = pickCategoryShape(node);
|
|
156
|
+
shaped.children = sanitizeCategoryTree(node && Array.isArray(node.children) ? node.children : []);
|
|
157
|
+
return shaped;
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/* -------------------------------------------------------------- 地址解析 */
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 栏目 `url` → 站内路径(绝对地址去掉 origin,查询 / 锚点不算路径)。
|
|
165
|
+
*
|
|
166
|
+
* 口径与 build 的 `pagePathFromEntry` 同向,但**宽松一层**:镜像只记录线上给了什么,
|
|
167
|
+
* 地址带查询就丢掉查询(`path` 只留路径),不因此整条跳过;只有「空 / 非法 / 非本站域名」才跳过。
|
|
168
|
+
*
|
|
169
|
+
* @param {string|null|undefined} rawUrl
|
|
170
|
+
* @param {string} [origin] 站点 origin(`https://hanyien.com`)
|
|
171
|
+
* @returns {{path:string, url:string, problem:string}} `path` 为空 = 解析不了(`problem` 是中文原因)
|
|
172
|
+
*/
|
|
173
|
+
export function categoryPathOf(rawUrl, origin) {
|
|
174
|
+
const text = String(rawUrl === null || rawUrl === undefined ? '' : rawUrl).trim();
|
|
175
|
+
if (!text) return { path: '', url: '', problem: '地址为空' };
|
|
176
|
+
|
|
177
|
+
const baseText = String(origin || '').trim().replace(/\/+$/, '');
|
|
178
|
+
let baseHost = '';
|
|
179
|
+
if (baseText) {
|
|
180
|
+
try {
|
|
181
|
+
baseHost = new URL(baseText).host.toLowerCase();
|
|
182
|
+
} catch {
|
|
183
|
+
baseHost = '';
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
let parsed = null;
|
|
188
|
+
try {
|
|
189
|
+
parsed = new URL(text, baseText ? `${baseText}/` : 'https://site-meta.invalid/');
|
|
190
|
+
} catch {
|
|
191
|
+
return { path: '', url: '', problem: '不是合法的 URL' };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (/^https?:\/\//i.test(text) && baseHost && parsed.host.toLowerCase() !== baseHost) {
|
|
195
|
+
return { path: '', url: '', problem: `域名不属于本站(${parsed.host})` };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return { path: parsed.pathname || '/', url: baseText ? parsed.href : text, problem: '' };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/* -------------------------------------------------------------- 排序 / 扁平化 */
|
|
202
|
+
|
|
203
|
+
function nodeSortValue(node) {
|
|
204
|
+
const n = Number(node && node.sort);
|
|
205
|
+
return Number.isFinite(n) ? n : 0;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* 兄弟节点排序:`sort` 升序 → 名称(中文)→ id。
|
|
210
|
+
*
|
|
211
|
+
* 为什么要自己排:镜像要能**复现**,后端回包顺序一变就整份重写会破坏幂等;
|
|
212
|
+
* 固定排序后同一份栏目表永远得到同一份扁平结果。
|
|
213
|
+
*/
|
|
214
|
+
function compareTreeNodes(a, b) {
|
|
215
|
+
const sa = nodeSortValue(a);
|
|
216
|
+
const sb = nodeSortValue(b);
|
|
217
|
+
if (sa !== sb) return sa - sb;
|
|
218
|
+
const na = String((a && a.name) || '');
|
|
219
|
+
const nb = String((b && b.name) || '');
|
|
220
|
+
const byName = na.localeCompare(nb, 'zh');
|
|
221
|
+
if (byName !== 0) return byName;
|
|
222
|
+
const ia = String((a && a.id) || '');
|
|
223
|
+
const ib = String((b && b.id) || '');
|
|
224
|
+
return ia < ib ? -1 : ia > ib ? 1 : 0;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* 栏目树 → 前序扁平表(父在前、子随后;同级按 `compareTreeNodes`)。
|
|
229
|
+
*
|
|
230
|
+
* 扁平项字段固定(本文件对外的接口契约),**与 `tree` 走同一白名单** `pickCategoryShape`:
|
|
231
|
+
* `{id, parentId, name, path, url, level, sort, kind, hasChildren, access, locked}`
|
|
232
|
+
* (源里有短 `seoTitle` 时附带)。扁平表里的 `parentId` / `path` / `url` / `hasChildren`
|
|
233
|
+
* 由本函数**算好覆盖**,其余仍取白名单。
|
|
234
|
+
* 路径解析不了的栏目**跳过并记 warning**,但它的子栏目照常展开(子项的 parentId 仍指向它),
|
|
235
|
+
* 免得因为一个坏地址把整棵子树从镜像里抹掉。
|
|
236
|
+
*
|
|
237
|
+
* @param {Array} tree `publicCategories` 回的 `categories`(或其结构树)
|
|
238
|
+
* @param {string} [origin]
|
|
239
|
+
* @returns {{categories:Array<object>, warnings:string[]}}
|
|
240
|
+
*/
|
|
241
|
+
export function flattenCategoryTree(tree, origin) {
|
|
242
|
+
const categories = [];
|
|
243
|
+
const warnings = [];
|
|
244
|
+
const note = (text) => {
|
|
245
|
+
if (warnings.length < MAX_WARNINGS) warnings.push(text);
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const walk = (nodes, parentId) => {
|
|
249
|
+
if (!Array.isArray(nodes)) return;
|
|
250
|
+
for (const node of [...nodes].sort(compareTreeNodes)) {
|
|
251
|
+
if (!node || typeof node !== 'object') {
|
|
252
|
+
note('栏目树里有一条不是对象的节点,已跳过');
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
const id = node.id === undefined || node.id === null ? '' : String(node.id);
|
|
256
|
+
const name = String(node.name || '');
|
|
257
|
+
const children = Array.isArray(node.children) ? node.children : [];
|
|
258
|
+
const hit = categoryPathOf(node.url, origin);
|
|
259
|
+
if (hit.problem) {
|
|
260
|
+
note(
|
|
261
|
+
`栏目「${name || id || '(未命名)'}」的地址不合法,已跳过:${hit.problem}` +
|
|
262
|
+
(node.url ? `(${String(node.url).slice(0, 200)})` : ''),
|
|
263
|
+
);
|
|
264
|
+
} else {
|
|
265
|
+
const level = Number(node.level);
|
|
266
|
+
const sort = Number(node.sort);
|
|
267
|
+
// 白名单先取结构字段,再由扁平化覆盖算出来的 parentId / path / url / hasChildren
|
|
268
|
+
categories.push({
|
|
269
|
+
...pickCategoryShape(node),
|
|
270
|
+
id,
|
|
271
|
+
parentId,
|
|
272
|
+
name,
|
|
273
|
+
path: hit.path,
|
|
274
|
+
url: hit.url,
|
|
275
|
+
level: Number.isFinite(level) ? level : 1,
|
|
276
|
+
sort: Number.isFinite(sort) ? sort : 0,
|
|
277
|
+
hasChildren: children.length > 0,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
walk(children, id);
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
walk(tree, '');
|
|
285
|
+
return { categories, warnings };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/* -------------------------------------------------------------- 落盘 */
|
|
289
|
+
|
|
290
|
+
/** 原子写:先写 `<file>.tmp` 再 rename(Windows 上 rename 偶发失败就删目标重试一次) */
|
|
291
|
+
function atomicWriteFile(fsImpl, file, data) {
|
|
292
|
+
const tmp = `${file}.tmp`;
|
|
293
|
+
fsImpl.writeFileSync(tmp, data, 'utf8');
|
|
294
|
+
try {
|
|
295
|
+
fsImpl.renameSync(tmp, file);
|
|
296
|
+
return;
|
|
297
|
+
} catch (err) {
|
|
298
|
+
try {
|
|
299
|
+
if (typeof fsImpl.rmSync === 'function') fsImpl.rmSync(file, { force: true });
|
|
300
|
+
} catch {
|
|
301
|
+
/* 目标删不掉:下面第二次 rename 会给出真原因 */
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
fsImpl.renameSync(tmp, file);
|
|
305
|
+
} catch {
|
|
306
|
+
try {
|
|
307
|
+
if (typeof fsImpl.rmSync === 'function') fsImpl.rmSync(tmp, { force: true });
|
|
308
|
+
} catch {
|
|
309
|
+
/* 清理失败不掩盖原始错误 */
|
|
310
|
+
}
|
|
311
|
+
throw err;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** 读一个 JSON 对象文件(不存在 / 坏了都当没有,坏了记一条 warning) */
|
|
317
|
+
function readJsonObjectFile(fsImpl, file, note, displayName) {
|
|
318
|
+
if (typeof fsImpl.existsSync !== 'function' || !fsImpl.existsSync(file)) return null;
|
|
319
|
+
try {
|
|
320
|
+
const parsed = JSON.parse(String(fsImpl.readFileSync(file, 'utf8')));
|
|
321
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('顶层不是对象');
|
|
322
|
+
return parsed;
|
|
323
|
+
} catch (err) {
|
|
324
|
+
note(`旧 ${displayName} 读不出来,按全量重写:${(err && err.message) || err}`);
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* 读旧镜像:优先 `.wkgeo/site.json`;没有才回落站点根下的旧 `site.json`(兼容读取)。
|
|
331
|
+
*
|
|
332
|
+
* 返回 `{meta, legacy}`:`legacy:true` 表示读到的是旧根文件 —— 只用于幂等比较,
|
|
333
|
+
* **不迁移、不删旧文件**;调用方会强制写一份到 `.wkgeo/`(旧文件自然过期,由用户自行清理)。
|
|
334
|
+
*/
|
|
335
|
+
function readOldSiteMeta(fsImpl, file, legacyFile, note) {
|
|
336
|
+
const current = readJsonObjectFile(fsImpl, file, note, SITE_META_FILE);
|
|
337
|
+
if (current) return { meta: current, legacy: false };
|
|
338
|
+
const legacy = readJsonObjectFile(fsImpl, legacyFile, note, LEGACY_SITE_META_FILE);
|
|
339
|
+
return legacy ? { meta: legacy, legacy: true } : null;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** 幂等比较用的「正文」:**不含 fetchedAt**(它每次都变) */
|
|
343
|
+
function metaBodyOf(meta) {
|
|
344
|
+
return {
|
|
345
|
+
version: meta.version,
|
|
346
|
+
site: meta.site,
|
|
347
|
+
counts: meta.counts,
|
|
348
|
+
categories: meta.categories,
|
|
349
|
+
tree: meta.tree,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* 站点解析:`site build` 已经解析好了就直接传 `siteTarget`;
|
|
355
|
+
* 独立调用(只有 `site` / `cmsSite`)时复用 build 的解析逻辑(动态 import 避免静态循环依赖)。
|
|
356
|
+
*/
|
|
357
|
+
async function resolveTargetOrDefault({ siteTarget, site, cmsSite, config, credentials, fetchImpl }) {
|
|
358
|
+
if (siteTarget && siteTarget.id) return siteTarget;
|
|
359
|
+
if (!String(site || '').trim()) {
|
|
360
|
+
throw new Error('缺少站点:要么传已解析的 siteTarget,要么传 site(站点 ID / 域名 / 站名)');
|
|
361
|
+
}
|
|
362
|
+
const { resolveSiteTarget } = await import('./build.mjs');
|
|
363
|
+
return resolveSiteTarget({ site, cmsSite, config, credentials, fetchImpl });
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/* -------------------------------------------------------------- 主入口 */
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* 拉一次公开栏目树,落到 `<dir>/.wkgeo/site.json`(首次写入自动建 `.wkgeo/`)。
|
|
370
|
+
*
|
|
371
|
+
* @param {object} opts
|
|
372
|
+
* @param {string} opts.dir 工作区目录(镜像落在 `<dir>/.wkgeo/site.json`)
|
|
373
|
+
* @param {string} [opts.site] 站点(uuid / 域名 / 站名)—— 没传 `siteTarget` 时用它解析
|
|
374
|
+
* @param {string} [opts.cmsSite] CMS 站 id(跳过 cmsMe 解析;由 `resolveSiteTarget` 消费)
|
|
375
|
+
* @param {object} [opts.siteTarget] 已解析的站点(`site build` 传,省一次解析)
|
|
376
|
+
* @param {object} [opts.config] CLI 配置(`cmsBase` / `httpTimeoutMs`)
|
|
377
|
+
* @param {{access_token:string}} [opts.credentials]
|
|
378
|
+
* @param {Function} [opts.fetchImpl] 注入的 fetch(单测用)
|
|
379
|
+
* @param {object} [opts.fsImpl] 注入的 fs(默认 node:fs;单测用)
|
|
380
|
+
* @param {Function} [opts.log] 诊断日志(不写 stdout)
|
|
381
|
+
* @returns {Promise<object>} 成功:`{ok:true, file, written, site, counts, categories, tree, warnings}`;
|
|
382
|
+
* 失败:`{ok:false, code:'CATEGORIES_FAILED', message, file, written:false, warnings}`
|
|
383
|
+
*/
|
|
384
|
+
export async function pullSiteMeta(opts = {}) {
|
|
385
|
+
const {
|
|
386
|
+
dir,
|
|
387
|
+
site = '',
|
|
388
|
+
cmsSite = '',
|
|
389
|
+
siteTarget = null,
|
|
390
|
+
config = {},
|
|
391
|
+
credentials = null,
|
|
392
|
+
fetchImpl = globalThis.fetch,
|
|
393
|
+
fsImpl = fs,
|
|
394
|
+
log = () => {},
|
|
395
|
+
} = opts;
|
|
396
|
+
|
|
397
|
+
const workDir = path.resolve(String(dir === undefined || dir === null || dir === '' ? '.' : dir));
|
|
398
|
+
const file = path.join(workDir, SITE_META_FILE);
|
|
399
|
+
const legacyFile = path.join(workDir, LEGACY_SITE_META_FILE);
|
|
400
|
+
const warnings = [];
|
|
401
|
+
const note = (text) => {
|
|
402
|
+
if (warnings.length < MAX_WARNINGS) warnings.push(text);
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
try {
|
|
406
|
+
const target = await resolveTargetOrDefault({ siteTarget, site, cmsSite, config, credentials, fetchImpl });
|
|
407
|
+
const token = credentials && credentials.access_token;
|
|
408
|
+
const cms = createCms({ config, fetchImpl });
|
|
409
|
+
const data = await cms.call('publicCategories', { site: target.id }, { token, siteId: target.id });
|
|
410
|
+
|
|
411
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
|
412
|
+
throw new Error('publicCategories 没有返回数据(站点可能不可访问)');
|
|
413
|
+
}
|
|
414
|
+
if (!Array.isArray(data.categories)) {
|
|
415
|
+
throw new Error('publicCategories 回包里没有 categories 数组(格式不符,按失败处理以免清空旧镜像)');
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const brief = data.site && typeof data.site === 'object' ? data.site : {};
|
|
419
|
+
const origin = String(brief.origin || '').replace(/\/+$/, '');
|
|
420
|
+
// 结构树:正文 / 展示字段在落盘前就丢掉;扁平表从结构树再算,两者同一白名单
|
|
421
|
+
const tree = sanitizeCategoryTree(data.categories);
|
|
422
|
+
const flat = flattenCategoryTree(tree, origin);
|
|
423
|
+
warnings.push(...flat.warnings);
|
|
424
|
+
|
|
425
|
+
const siteInfo = {
|
|
426
|
+
id: String(target.id || brief.id || ''),
|
|
427
|
+
cmsId: String(target.cmsId || ''),
|
|
428
|
+
name: String(brief.name || target.label || ''),
|
|
429
|
+
label: String(target.label || brief.name || ''),
|
|
430
|
+
domain: String(brief.domain || ''),
|
|
431
|
+
shortHost: String(brief.prefixHost || ''),
|
|
432
|
+
origin,
|
|
433
|
+
language: String(data.language || ''),
|
|
434
|
+
};
|
|
435
|
+
const body = {
|
|
436
|
+
version: SITE_META_VERSION,
|
|
437
|
+
site: siteInfo,
|
|
438
|
+
counts: { categories: flat.categories.length },
|
|
439
|
+
categories: flat.categories,
|
|
440
|
+
tree,
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
const old = readOldSiteMeta(fsImpl, file, legacyFile, note);
|
|
444
|
+
if (old && old.legacy) {
|
|
445
|
+
note(
|
|
446
|
+
`读到站点根下的旧 ${LEGACY_SITE_META_FILE}(兼容读取,不迁移、不删旧文件);` +
|
|
447
|
+
`本次仍写 ${SITE_META_FILE},旧文件可自行删除`,
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
// 幂等只对「本来就在 .wkgeo/ 里」的镜像生效;读的是旧根文件时必须写一份到 .wkgeo/
|
|
451
|
+
if (old && !old.legacy && JSON.stringify(metaBodyOf(old.meta)) === JSON.stringify(body)) {
|
|
452
|
+
log(`site meta:栏目树无变化(${body.counts.categories} 个栏目),未改 ${SITE_META_FILE}`);
|
|
453
|
+
return { ok: true, file, written: false, site: siteInfo, counts: body.counts, categories: flat.categories, tree, warnings };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const next = {
|
|
457
|
+
version: SITE_META_VERSION,
|
|
458
|
+
fetchedAt: new Date().toISOString(),
|
|
459
|
+
site: siteInfo,
|
|
460
|
+
counts: body.counts,
|
|
461
|
+
categories: flat.categories,
|
|
462
|
+
tree,
|
|
463
|
+
};
|
|
464
|
+
const text = `${JSON.stringify(next, null, 2)}\n`;
|
|
465
|
+
if (typeof fsImpl.mkdirSync === 'function') fsImpl.mkdirSync(path.dirname(file), { recursive: true });
|
|
466
|
+
atomicWriteFile(fsImpl, file, text);
|
|
467
|
+
log(`site meta:写入 ${SITE_META_FILE}(${body.counts.categories} 个栏目,${Buffer.byteLength(text, 'utf8')} 字节)`);
|
|
468
|
+
return { ok: true, file, written: true, site: siteInfo, counts: body.counts, categories: flat.categories, tree, warnings };
|
|
469
|
+
} catch (err) {
|
|
470
|
+
const message = String((err && err.message) || err);
|
|
471
|
+
log(`site meta:栏目树镜像失败(${message}),旧 ${SITE_META_FILE} 保持不变`);
|
|
472
|
+
return { ok: false, code: 'CATEGORIES_FAILED', message, file, written: false, warnings };
|
|
473
|
+
}
|
|
474
|
+
}
|