@wkgeo/cli 2.0.3 → 2.1.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.
@@ -0,0 +1,405 @@
1
+ /**
2
+ * 新建站点模板(task-51 · 2026-11-22)
3
+ * ============================================================================
4
+ *
5
+ * ## 老板口径(别改)
6
+ * 新建模板 = **先建站内模板行 → 拉成带 `template-manifest.json` 的本地工程 → 改名改 → 再 push**。
7
+ * **禁止**把站内当前模板 pull 到新目录再 push —— `templates push` 只认 `manifest.templateId`,
8
+ * 会写回**原模板**,新建就变成了"改老模板"。
9
+ *
10
+ * ## 三源(服务端 `templateCreate` 负责复制,CLI 只传 `from` 字符串)
11
+ * * `base` —— 服务端内置基础模板(`default-base-template.js`);
12
+ * * `site` —— 本站**当前启用**模板的全部文件;
13
+ * * `market:<key>` —— 模板市场里那套(OSS `template/<key>/`);
14
+ * * `url:<参考站>` —— 一期**不镜像整站**:页面仍取 `base`,参考站只写进
15
+ * `template.json.origin.reference`(本模块采集页型 / 导航 / 配色要点,失败只记
16
+ * `referenceError`,**不阻断建模板**)。
17
+ *
18
+ * ## 流程(`--confirm` 才真做)
19
+ * 1. `templateCreate`(服务端:插模板行 + 复制文件 + 写站副本,`is_active=false`);
20
+ * 2. `templates pull` 到 `<dir>/templates/<key>`(带 manifest,后续 push 认它);
21
+ * 3. 改 `template.json`:key / name / version `1.0.0` / summary 追加「基于 <源> 新建」
22
+ * (`url:` 源再写 `origin.reference`);
23
+ * 4. 重写 manifest 里 `template.json` 的 sha256 / 字节数 + 整套 `contentHash`。
24
+ *
25
+ * **pull 失败 ⇒ 回滚**(`templateUninstall` 删掉刚建的那行),exit 1 且消息带「已回滚」。
26
+ *
27
+ * ## 为什么单独一个模块(不塞进 commands/site.mjs)
28
+ * 建模板是**纯文件 + 一次服务端调用**的逻辑,放独立模块才能被单测直接喂假 `runCli` / 假 `fetch`,
29
+ * 命令层只负责解析参数 + 打印。
30
+ */
31
+
32
+ import fs from 'node:fs';
33
+ import path from 'node:path';
34
+
35
+ import { CliError, UsageError, EXIT } from './errors.mjs';
36
+ import { MANIFEST_FILE, contentHashOf, pullTemplate, sha256Hex } from './templates-sync.mjs';
37
+
38
+ /** 服务端模板 key 口径(与 `cms-template.js` 的 `templateCreateKeyPattern` 一致) */
39
+ export const TEMPLATE_CREATE_KEY_PATTERN = /^[a-z0-9][a-z0-9-]{1,60}$/;
40
+ /** 服务端模板名字上限(按字符数) */
41
+ export const TEMPLATE_CREATE_NAME_MAX = 40;
42
+ /** 新建模板工程的起始版本 */
43
+ export const TEMPLATE_CREATE_VERSION = '1.0.0';
44
+ /** 内置基础模板的页面文件数(21 个;+1 个 template.json = 22)—— 只用于 dry-run 的"预计文件数" */
45
+ const BASE_TEMPLATE_FILE_COUNT = 21;
46
+
47
+ /**
48
+ * 名字 → 合法 key 的兜底(`--key` 没给时用)。
49
+ *
50
+ * 只留小写字母 / 数字,其余一律 `-`,折叠连续 `-`、去首尾 `-`,最长 61 位;
51
+ * 开头不是字母数字就把前面多余的剪掉。中文字符会被整段替换掉 ⇒ 中文名一般得显式给 `--key`。
52
+ *
53
+ * @param {string} name
54
+ * @returns {string} 合法 key;实在转不出来返回 ''
55
+ */
56
+ export function slugifyTemplateKey(name) {
57
+ const raw = String(name === undefined || name === null ? '' : name);
58
+ const base = raw
59
+ .toLowerCase()
60
+ .replace(/[^a-z0-9]+/g, '-')
61
+ .replace(/^-+|-+$/g, '')
62
+ .slice(0, 61)
63
+ .replace(/-+$/g, '');
64
+ if (!base) return '';
65
+ if (!/^[a-z0-9]/.test(base)) return '';
66
+ return TEMPLATE_CREATE_KEY_PATTERN.test(base) ? base : '';
67
+ }
68
+
69
+ /**
70
+ * 解析 `--from`:`base` / `site` / `market:<key>` / `url:<参考站>`。
71
+ *
72
+ * @param {string} raw
73
+ * @returns {{kind: string, label: string, value: string, key?: string, ref?: string}}
74
+ * @throws {UsageError}
75
+ */
76
+ export function parseCreateFrom(raw) {
77
+ const text = String(raw === undefined || raw === null ? '' : raw).trim();
78
+ if (!text || text === 'base') return { kind: 'base', label: '基础模板', value: 'base' };
79
+ if (text === 'site') return { kind: 'site', label: '本站当前模板', value: 'site' };
80
+ if (text.startsWith('market:')) {
81
+ const key = text.slice('market:'.length).trim();
82
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(key)) {
83
+ throw new UsageError(`--from market: 后面要跟市场模板 key(小写字母 / 数字 / 连字符),收到:${key || '(空)'}`);
84
+ }
85
+ return { kind: 'market', key, label: `市场模板 ${key}`, value: `market:${key}` };
86
+ }
87
+ if (text.startsWith('url:')) {
88
+ const ref = text.slice('url:'.length).trim();
89
+ if (!/^https?:\/\/[^\s]+$/i.test(ref)) {
90
+ throw new UsageError(`--from url: 后面要跟完整网址(http:// 或 https:// 开头),收到:${ref || '(空)'}`);
91
+ }
92
+ return { kind: 'url', ref, label: `参考站 ${ref}`, value: `url:${ref}` };
93
+ }
94
+ throw new UsageError('--from 只认 base / site / market:<key> / url:<参考站>,收到:' + text);
95
+ }
96
+
97
+ /**
98
+ * 采集参考站要点(**尽力而为**:一期只写进 `template.json.origin.reference`,失败不阻断建模板)。
99
+ *
100
+ * 只做最轻的静态解析(不跑浏览器、不依赖外部服务):标题 / 导航链接文本 / 十六进制配色 / 站内页型。
101
+ *
102
+ * @param {string} url 参考站地址
103
+ * @param {{fetch?: Function, timeoutMs?: number, now?: () => Date}} [opts]
104
+ * @returns {Promise<{ok: true, reference: object}|{ok: false, error: string}>}
105
+ */
106
+ export async function collectUrlReference(url, opts = {}) {
107
+ const fetcher = typeof opts.fetch === 'function' ? opts.fetch : globalThis.fetch;
108
+ const timeoutMs = Number(opts.timeoutMs) > 0 ? Number(opts.timeoutMs) : 8000;
109
+ const now = typeof opts.now === 'function' ? opts.now : () => new Date();
110
+ if (typeof fetcher !== 'function') return { ok: false, error: '当前环境没有 fetch,跳过参考站采集' };
111
+
112
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
113
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
114
+ try {
115
+ let res;
116
+ try {
117
+ res = await fetcher(url, { redirect: 'follow', signal: controller ? controller.signal : undefined });
118
+ } finally {
119
+ if (timer) clearTimeout(timer);
120
+ }
121
+ if (!res || res.ok === false) return { ok: false, error: `参考站返回 ${res && res.status ? res.status : '(无响应)'}` };
122
+ const html = String((await res.text()) || '');
123
+ if (!html.trim()) return { ok: false, error: '参考站返回空页面' };
124
+
125
+ const title = textOf((html.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1]).slice(0, 200);
126
+ const anchor = /<a\b[^>]*href=["']([^"'#]+)["'][^>]*>([\s\S]*?)<\/a>/gi;
127
+ const navTexts = [];
128
+ const pages = [];
129
+ for (const hit of html.matchAll(anchor)) {
130
+ const href = String(hit[1] || '').trim();
131
+ const label = textOf(hit[2]).slice(0, 40);
132
+ if (label && navTexts.length < 12 && !navTexts.includes(label)) navTexts.push(label);
133
+ if (href.startsWith('/') && !href.startsWith('//') && pages.length < 20 && !pages.includes(href)) pages.push(href);
134
+ }
135
+ const colors = [];
136
+ for (const hit of html.matchAll(/#[0-9a-fA-F]{6}\b|#[0-9a-fA-F]{3}\b/g)) {
137
+ const color = String(hit[0] || '').toLowerCase();
138
+ if (colors.length < 5 && !colors.includes(color)) colors.push(color);
139
+ }
140
+ return {
141
+ ok: true,
142
+ reference: {
143
+ url,
144
+ fetchedAt: now().toISOString(),
145
+ title,
146
+ navigation: navTexts,
147
+ pages,
148
+ colors,
149
+ },
150
+ };
151
+ } catch (error) {
152
+ return { ok: false, error: String((error && error.message) || error) };
153
+ }
154
+ }
155
+
156
+ /** HTML 片段 → 纯文本(去标签、压空白、解几个常见实体) */
157
+ function textOf(html) {
158
+ return String(html === undefined || html === null ? '' : html)
159
+ .replace(/<script[\s\S]*?<\/script>/gi, ' ')
160
+ .replace(/<style[\s\S]*?<\/style>/gi, ' ')
161
+ .replace(/<[^>]+>/g, ' ')
162
+ .replace(/&nbsp;/gi, ' ')
163
+ .replace(/&amp;/gi, '&')
164
+ .replace(/&lt;/gi, '<')
165
+ .replace(/&gt;/gi, '>')
166
+ .replace(/&quot;/gi, '"')
167
+ .replace(/\s+/g, ' ')
168
+ .trim();
169
+ }
170
+
171
+ /**
172
+ * 用 `runCli(action, payload)` 造一个 `templates-sync` 要的 api 适配器。
173
+ *
174
+ * @param {(action: string, payload?: object) => Promise<any>} runCli
175
+ * @returns {{get: Function, list: Function}}
176
+ */
177
+ function apiOfRunCli(runCli) {
178
+ if (typeof runCli !== 'function') throw new CliError('内部错误:createSiteTemplate 缺少 runCli');
179
+ return {
180
+ async get(templateId) {
181
+ return runCli('templateGet', templateId ? { templateId: String(templateId) } : {});
182
+ },
183
+ async list() {
184
+ return runCli('templateList');
185
+ },
186
+ };
187
+ }
188
+
189
+ /** 回包若是 `{ok:false}` 形态,按业务错误抛出来(正常 `cmsCall` 会直接抛,这里是兜底) */
190
+ function assertServiceOk(result, what) {
191
+ if (result && typeof result === 'object' && result.ok === false) {
192
+ throw new CliError(`${what}失败:${result.message || result.code || '服务端没给原因'}`, {
193
+ code: result.code,
194
+ exitCode: EXIT.ERROR,
195
+ raw: result,
196
+ });
197
+ }
198
+ return result;
199
+ }
200
+
201
+ /**
202
+ * 改 `template.json` 并重写 manifest(pull 之后、返回之前)。
203
+ *
204
+ * @returns {{meta: object, reference?: object, referenceError?: string}}
205
+ */
206
+ function rewriteTemplateJson({ target, key, name, from, reference }) {
207
+ const file = path.join(target, 'template.json');
208
+ let meta = {};
209
+ if (fs.existsSync(file)) {
210
+ try {
211
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
212
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) meta = parsed;
213
+ } catch {
214
+ /** 内容坏了也照改:下面会用合成值覆盖关键字段 */
215
+ meta = {};
216
+ }
217
+ }
218
+ const summaryLine = `基于 ${from.label} 新建`;
219
+ const prevSummary = String(meta.summary || '').trim();
220
+ const summary = prevSummary.includes(summaryLine) ? prevSummary : prevSummary ? `${prevSummary};${summaryLine}` : summaryLine;
221
+
222
+ const next = {
223
+ ...meta,
224
+ key,
225
+ name,
226
+ version: TEMPLATE_CREATE_VERSION,
227
+ summary,
228
+ };
229
+ if (from.kind === 'url' && reference) {
230
+ next.origin = { ...(meta.origin && typeof meta.origin === 'object' ? meta.origin : {}), reference };
231
+ }
232
+ fs.mkdirSync(path.dirname(file), { recursive: true });
233
+ fs.writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`, 'utf8');
234
+ return { meta: next, reference };
235
+ }
236
+
237
+ /**
238
+ * 让 manifest 跟改过的 `template.json` 对账(sha256 / bytes / contentHash 三处)。
239
+ */
240
+ function refreshManifestForTemplateJson(target) {
241
+ const manifestPath = path.join(target, MANIFEST_FILE);
242
+ if (!fs.existsSync(manifestPath)) return null;
243
+ let manifest;
244
+ try {
245
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
246
+ } catch {
247
+ return null;
248
+ }
249
+ if (!manifest || !Array.isArray(manifest.files)) return null;
250
+ const file = path.join(target, 'template.json');
251
+ const buf = fs.readFileSync(file);
252
+ const sha256 = sha256Hex(buf);
253
+ const hit = manifest.files.find((one) => one && one.path === 'template.json');
254
+ if (hit) {
255
+ hit.bytes = buf.length;
256
+ hit.sha256 = sha256;
257
+ hit.encoding = 'utf8';
258
+ } else {
259
+ manifest.files.push({ path: 'template.json', bytes: buf.length, sha256, encoding: 'utf8' });
260
+ manifest.files.sort((a, b) => String(a.path).localeCompare(String(b.path)));
261
+ }
262
+ manifest.contentHash = contentHashOf(manifest.files);
263
+ fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
264
+ return manifest;
265
+ }
266
+
267
+ /**
268
+ * **新建站点模板**(`wkgeo site template new` 的本体)。
269
+ *
270
+ * @param {object} opts
271
+ * @param {string} opts.dir 本地模板工程根目录(模板会落在 `<dir>/templates/<key>`)
272
+ * @param {string} opts.name 模板名字(1~40 字)
273
+ * @param {string} [opts.key] key(不传就用名字 slug 兜底)
274
+ * @param {string} [opts.from='base'] `base` / `site` / `market:<key>` / `url:<参考站>`
275
+ * @param {boolean} [opts.confirm=false] false = dry-run(零网络零写盘)
276
+ * @param {boolean} [opts.json=false] 调用方是否要 JSON(只影响返回里的展示提示)
277
+ * @param {Function} opts.runCli `(action, payload) => Promise<data>`,真实实现是 `ctx.cmsCall`
278
+ * @param {Function} [opts.fetch] 参考站采集用(默认 globalThis.fetch)
279
+ * @param {object} [opts.api] 高级:直接注入 `templates-sync` 的 api 适配器
280
+ * @param {string} [opts.siteId] 站点 id(只用于回报 / manifest)
281
+ * @param {string} [opts.cwd=process.cwd()] 相对目录基准
282
+ * @param {() => Date} [opts.now] 时钟注入(单测固定 fetchedAt)
283
+ * @returns {Promise<object>}
284
+ */
285
+ export async function createSiteTemplate({
286
+ dir = '',
287
+ name = '',
288
+ key = '',
289
+ from = 'base',
290
+ confirm = false,
291
+ json = false,
292
+ runCli = null,
293
+ fetch: fetchImpl = undefined,
294
+ api = null,
295
+ siteId = '',
296
+ cwd = process.cwd(),
297
+ now = () => new Date(),
298
+ } = {}) {
299
+ /** ── 参数校验(dry-run 也要校验:先把"会失败"的地方告诉用户) ── */
300
+ const rawDir = String(dir === undefined || dir === null ? '' : dir).trim();
301
+ if (!rawDir) throw new UsageError('必须给 --dir <目录>(模板工程放哪个目录)\n例:wkgeo site template new --dir ./my-site --name 新模板');
302
+ const rawName = String(name === undefined || name === null ? '' : name).trim();
303
+ if (!rawName) throw new UsageError('必须给 --name <模板名字>(1~40 个字)');
304
+ if ([...rawName].length > TEMPLATE_CREATE_NAME_MAX) {
305
+ throw new UsageError(`模板名字最多 ${TEMPLATE_CREATE_NAME_MAX} 个字,收到 ${[...rawName].length} 个`);
306
+ }
307
+ const rawKey = String(key === undefined || key === null ? '' : key).trim().toLowerCase();
308
+ const finalKey = rawKey || slugifyTemplateKey(rawName);
309
+ if (!TEMPLATE_CREATE_KEY_PATTERN.test(finalKey)) {
310
+ throw new UsageError(
311
+ `模板 key 不合法(只认小写字母 / 数字 / 连字符,2~61 位,字母数字开头):${finalKey || '(空)'}\n` +
312
+ '请用 --key 指定,例如 --key my-new-template',
313
+ );
314
+ }
315
+ const fromParsed = parseCreateFrom(from);
316
+
317
+ const root = path.resolve(cwd, rawDir);
318
+ const target = path.join(root, 'templates', finalKey);
319
+ if (fs.existsSync(target)) {
320
+ throw new UsageError(`目录已存在:${target}\n换一个 --key,或先把它删掉 / 挪走(模板不会覆盖已有工程)`);
321
+ }
322
+
323
+ /** ── dry-run:零网络、零写盘 ── */
324
+ if (confirm !== true) {
325
+ return {
326
+ dry_run: true,
327
+ action: 'templateCreate',
328
+ key: finalKey,
329
+ name: rawName,
330
+ from: fromParsed.value,
331
+ from_label: fromParsed.label,
332
+ dir: target,
333
+ site_id: String(siteId || ''),
334
+ /** `base` / `url` 的页面数已知(内置 21 页 + template.json);`market` / `site` 得建完才知道 */
335
+ estimated_files: fromParsed.kind === 'base' || fromParsed.kind === 'url' ? BASE_TEMPLATE_FILE_COUNT + 1 : null,
336
+ confirm_hint: '确认无误后加 --confirm 真建(会先在线上建一套模板再拉到本地)',
337
+ };
338
+ }
339
+
340
+ if (typeof runCli !== 'function') throw new CliError('内部错误:createSiteTemplate 缺少 runCli');
341
+
342
+ /** ── 1) 线上建模板(服务端复制来源文件;建完 `is_active=false`) ── */
343
+ const created = assertServiceOk(
344
+ await runCli('templateCreate', { name: rawName, key: finalKey, from: fromParsed.value }),
345
+ '新建模板',
346
+ );
347
+ const templateId = String((created && created.template && created.template.id) || '').trim();
348
+ if (!templateId) throw new CliError('新建模板失败:服务端没返回模板 id', { raw: created });
349
+
350
+ /** ── 2) 拉到本地工程(带 template-manifest.json) ── */
351
+ let pulled;
352
+ try {
353
+ pulled = await pullTemplate({
354
+ siteId: String(siteId || ''),
355
+ templateKeyOrId: templateId,
356
+ dir: target,
357
+ api: api || apiOfRunCli(runCli),
358
+ force: false,
359
+ cwd,
360
+ now,
361
+ });
362
+ } catch (error) {
363
+ /** 失败就回滚:删掉刚建的模板行(`templateUninstall` 只删"没启用"的行,正好是刚建这套) */
364
+ try {
365
+ await Promise.resolve(runCli('templateUninstall', { templateId }));
366
+ } catch {
367
+ /** 回滚自己也失败:下面消息里如实说"回滚没成功,请到 CMS 手动删" */
368
+ }
369
+ throw new CliError(
370
+ `模板建好了但拉取文件失败,已回滚(删掉刚建的模板),原模板工程未生成:${String((error && error.message) || error)}`,
371
+ { exitCode: EXIT.ERROR, cause: error },
372
+ );
373
+ }
374
+
375
+ /** ── 3) 参考站采集(`url:` 源才做;失败只记 referenceError,不阻断) ── */
376
+ let reference = null;
377
+ let referenceError = '';
378
+ if (fromParsed.kind === 'url') {
379
+ const collected = await collectUrlReference(fromParsed.ref, { fetch: fetchImpl, now });
380
+ if (collected.ok) reference = collected.reference;
381
+ else referenceError = collected.error;
382
+ }
383
+
384
+ /** ── 4) 改 template.json + 让 manifest 对账 ── */
385
+ rewriteTemplateJson({ target, key: finalKey, name: rawName, from: fromParsed, reference });
386
+ const manifest = refreshManifestForTemplateJson(target);
387
+ const fileCount = manifest && Array.isArray(manifest.files) ? manifest.files.length : pulled && pulled.fileCount ? pulled.fileCount : 0;
388
+
389
+ const data = {
390
+ ok: true,
391
+ action: 'templateCreate',
392
+ key: finalKey,
393
+ name: rawName,
394
+ version: TEMPLATE_CREATE_VERSION,
395
+ from: fromParsed.value,
396
+ dir: target,
397
+ manifest: path.join(target, MANIFEST_FILE),
398
+ template_id: templateId,
399
+ files: fileCount,
400
+ site_id: String(siteId || ''),
401
+ };
402
+ if (reference) data.reference = reference;
403
+ if (referenceError) data.referenceError = referenceError;
404
+ return data;
405
+ }