@wkgeo/cli 2.0.1 → 2.0.3

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,72 @@
1
+ /**
2
+ * `spec` 命令:把**随包分发**的建站规范 `spec/SITE-SPEC.md` 原文打印出来。
3
+ *
4
+ * ## 为什么是一条命令,而不是"看 README 某一节"
5
+ * 规范和代码一样会变:写在 README 里,AI 端拿到的是**它当时抓到的那一版**;写成命令,
6
+ * `npx @wkgeo/cli@latest spec` 每次都拿到**当前安装包里的那一版**(与 `wkgeo skill` 同理)。
7
+ *
8
+ * ## 三个出口同源(**这是本命令存在的核心理由**)
9
+ * * `wkgeo spec` → 全文(本命令)
10
+ * * `wkgeo spec --agents` → 只打「给 AI 的精简版」,**与 `wkgeo init` 写进项目的内容逐字节相同**
11
+ * * `wkgeo-site-spec` skill → 由 `cli/scripts/gen-site-spec.mjs` 从同一份 markdown 生成
12
+ * 三处都不另写规则;改规则只改 `cli/spec/SITE-SPEC.md`。
13
+ *
14
+ * ## 输出形态(**刻意的例外**,与 `skill` 同一套记法)
15
+ * * 默认(**包括管道/非终端**)→ 纯 markdown 原文,不套 JSON 信封 ——
16
+ * 否则 `wkgeo spec > 规范.md` 得到的是 `{"ok":true,…"markdown":"…\n…"}`,白折腾。
17
+ * * `--json` → 标准信封(给必须统一按 JSON 解析的宿主)。
18
+ *
19
+ * ## 鉴权
20
+ * 不需要登录、不发网络请求(纯本地读文件)。
21
+ */
22
+
23
+ import { SPEC_URL, extractAgentsBrief, readSpecMarkdown } from '../site-spec.mjs';
24
+
25
+ export const specCommand = {
26
+ name: 'spec',
27
+ summary: '打印建站规范(栏目 / 模板 / 首页版块 / 图标)',
28
+ usage: 'wkgeo spec [--agents] [--json]',
29
+ flags: {
30
+ agents: {
31
+ type: 'boolean',
32
+ desc: '只打印「给 AI 的精简版」那一节(= `wkgeo init` 写进 AGENTS.md / CLAUDE.md / .cursorrules / Copilot 指令的内容)',
33
+ },
34
+ },
35
+ examples: [
36
+ 'wkgeo spec # 全文',
37
+ 'wkgeo spec --agents # 只打精简版(要写进项目的那一段)',
38
+ 'wkgeo spec > SITE-SPEC.md # 存成文件(默认就是纯 markdown,不会套 JSON)',
39
+ 'wkgeo spec --json # 机器可读信封',
40
+ ],
41
+ notes: [
42
+ '默认**永远输出 markdown 原文**,即使输出到管道/非终端也不套 JSON 信封 —— 所以 `wkgeo spec > x.md` 直接得到可读文档。',
43
+ '只有显式 `wkgeo spec --json` 才输出信封:{"ok":true,"command":"spec","data":{"path":…,"markdown":…,"bytes":…,"lines":…}}。',
44
+ '本命令不需要登录、不发任何网络请求(纯本地读包内的 spec/SITE-SPEC.md)。',
45
+ '规范里的规则都标了「已实现 / 实现中」;实现中的条目别当既有行为依赖。',
46
+ ],
47
+ async run(ctx) {
48
+ const { out, flags } = ctx;
49
+ const info = readSpecMarkdown(SPEC_URL);
50
+ const agentsOnly = flags.agents === true;
51
+ const markdown = agentsOnly ? extractAgentsBrief(info.markdown) : info.markdown;
52
+ const data = {
53
+ path: info.path,
54
+ agents_only: agentsOnly,
55
+ bytes: Buffer.byteLength(markdown, 'utf8'),
56
+ lines: markdown.split('\n').length,
57
+ markdown,
58
+ };
59
+
60
+ /**
61
+ * 判断依据必须是**用户显式写的 `--json`**(`ctx.flags.json`),不能用 `out.json`:
62
+ * 后者在非终端会自动变 true(全 CLI 的通用约定),那样管道里 `wkgeo spec > x.md`
63
+ * 就会灌进一坨 JSON 信封 —— 正是这里要避免的(与 `wkgeo skill` 同一处理)。
64
+ */
65
+ if (flags.json === true) {
66
+ ctx.done(data);
67
+ return data;
68
+ }
69
+ out.plain(markdown.endsWith('\n') ? markdown : markdown + '\n');
70
+ return data;
71
+ },
72
+ };
@@ -637,6 +637,51 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
637
637
  return '';
638
638
  }
639
639
 
640
+ /**
641
+ * **这个栏目自己那一页**(老板 2026-11-21):「尽量每一个栏目制作一个模版 …… 复制一个模版绑定
642
+ * 当前的栏目,这样就方便后期修改」。
643
+ *
644
+ * 口径:
645
+ * * **清单没写 `templateFile`** 才算(写了就听清单的,上面 `resolveManifestTemplateFile` 已校验);
646
+ * * **只给新建的栏目用**(存量那行一律不碰 —— 客户自己挑过的模板页不能被一次 `content apply` 覆盖);
647
+ * * 模板里**声明了** `pages/c-<slug>.html` 才绑(判据走契约的 `templatePageBindings`)——
648
+ * base 模板 / `wkgeo template init` 出来的模板会给每个栏目做一份;
649
+ * 没做 ⇒ 空串 = 不绑(前台按类型自动选,兜底一个字没改)。
650
+ *
651
+ * @returns {Promise<string>} 要绑的模板页;`''` = 不绑
652
+ */
653
+ async function resolveOwnPerCategoryPage(cat, kind) {
654
+ const bindingContract = await loadTemplateBindingContract();
655
+ if (!bindingContract || typeof bindingContract.perCategoryPagePath !== 'function') return '';
656
+ const meta = await loadSiteTemplateMeta();
657
+ if (!meta) return '';
658
+ const own = bindingContract.perCategoryPagePath(String(cat.slug || cat.name || ''));
659
+ if (!own) return '';
660
+ const declared = new Set(
661
+ (typeof bindingContract.templatePageBindings === 'function' ? bindingContract.templatePageBindings(meta) : [])
662
+ .map(one => String((one && one.path) || '')),
663
+ );
664
+ if (!declared.has(own)) return '';
665
+ const verdict = await templateBindingVerdict(
666
+ {
667
+ key: cat.slug,
668
+ name: cat.name,
669
+ kind,
670
+ fieldsEnabled: null,
671
+ customFields: (cat.fields || []).map(one => String((one && one.key) || one || '')),
672
+ },
673
+ own,
674
+ );
675
+ if (verdict && verdict.ok === false) {
676
+ warnings.push({
677
+ path: `categories.${cat.slug}.templateFile`,
678
+ message: `模板里有 ${own},但与栏目类型不匹配,已跳过绑定(前台按类型自动选):${verdict.message}`,
679
+ });
680
+ return '';
681
+ }
682
+ return own;
683
+ }
684
+
640
685
  /* ── 栏目 ─────────────────────────────────────────────────── */
641
686
 
642
687
  /** 本次清单 `menus[]` 声明的导航 path(懒算一次;`menus[]` 是导航唯一真相) */
@@ -754,6 +799,11 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
754
799
  const kind = mapped ? mapped.kind : cat.kind;
755
800
  /** 模板绑定先过契约(计划期就定下来:不合法 ⇒ 空串 + 一条 ⚠,创建 / 更新两条分支共用) */
756
801
  const templateFile = await resolveManifestTemplateFile(cat, kind);
802
+ /**
803
+ * ★ 2026-11-21(每栏目一个模板页):**新建**栏目、且清单没指定模板页时,
804
+ * 绑它自己那一页(模板里声明了 `pages/c-<slug>.html` 才算)。存量栏目一律不碰。
805
+ */
806
+ const boundTemplate = templateFile || (existing ? '' : await resolveOwnPerCategoryPage(cat, kind));
757
807
  /** 导航归属:true / false / undefined(undefined = 本次不动,老行为) */
758
808
  const inMenu = navStateOf(cat, wantPath);
759
809
  if (inMenu === false) hidden.push(cat.name);
@@ -765,7 +815,7 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
765
815
  planned: 'create',
766
816
  action: 'create',
767
817
  label,
768
- detail: `新建栏目(${kind}${inMenu === false ? ',不进导航' : ''})${templateFile ? ` 模板 ${templateFile}` : ''}`,
818
+ detail: `新建栏目(${kind}${inMenu === false ? ',不进导航' : ''})${boundTemplate ? ` 模板 ${boundTemplate}` : ''}`,
769
819
  };
770
820
  entry.run = async (row) => {
771
821
  const payload = { name: cat.name, slug: cat.slug, kind, sort: cat.sort };
@@ -773,7 +823,7 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
773
823
  const liveParentId = cat.parent ? (state.catIdBySlug.get(cat.parent) || {}).id || '' : '';
774
824
  const effectiveParentId = liveParentId || parentId;
775
825
  if (effectiveParentId) payload.parent_id = effectiveParentId;
776
- if (templateFile) payload.template_path = templateFile;
826
+ if (boundTemplate) payload.template_path = boundTemplate;
777
827
  if (cat.description) payload.description = cat.description;
778
828
  if (cat.seoDescription) payload.seo_description = cat.seoDescription;
779
829
  if (cat.seoKeywords) payload.seo_keywords = cat.seoKeywords;
@@ -0,0 +1,302 @@
1
+ /**
2
+ * 建站规范(SITE-SPEC)读取层 —— **唯一主源 = 包内 `spec/SITE-SPEC.md`**。
3
+ *
4
+ * ## 为什么要有这一层
5
+ * 规范只有一份文件,但出口有三个:
6
+ * ① `wkgeo spec`(人 / 本地 CLI 里的 agent 主动跑);
7
+ * ② `wkgeo init` 把「给 AI 的精简版」写进项目的 AGENTS.md / CLAUDE.md / .cursorrules /
8
+ * .github/copilot-instructions.md(**agent 启动时自己读**,这才是"自动读到"的入口);
9
+ * ③ `wkgeo-site-spec` skill(DSH 本机 / 云端沙箱加载)。
10
+ * 三个出口**不能各写一份**(一定会漂移),所以:
11
+ * * ②③ 的内容都从这份 markdown 里**切出来 / 生成**;
12
+ * * 口径标记写在 markdown 里(`<!-- wkgeo:site-spec:agents:begin -->` … `end`),
13
+ * 这里只做"按标记切",不在这里复制规则文本。
14
+ *
15
+ * ## 路径解析(与 `skill.mjs` 同一个坑)
16
+ * `import.meta.url` = `<包根>/lib/site-spec.mjs` ⇒ 往上一级是包根,再进 `spec/`。
17
+ * **绝不能**用 `process.cwd()`:AI 端几乎总在别的目录里跑,npx 更是如此。
18
+ */
19
+
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import { fileURLToPath, pathToFileURL } from 'node:url';
23
+
24
+ import { CliError, EXIT, UsageError } from './errors.mjs';
25
+
26
+ /** 包根下的 `spec/SITE-SPEC.md` */
27
+ export const SPEC_URL = new URL('../spec/SITE-SPEC.md', import.meta.url);
28
+
29
+ /** 「给 AI 的精简版」在 markdown 里的起止标记(改标记 = 三处一起变,别只改一边) */
30
+ export const BRIEF_BEGIN = '<!-- wkgeo:site-spec:agents:begin -->';
31
+ export const BRIEF_END = '<!-- wkgeo:site-spec:agents:end -->';
32
+
33
+ /** 写进项目文件的那一段也用同一对标记包起来(重复跑靠它原地替换,不重复追加) */
34
+ export const BLOCK_BEGIN = '<!-- wkgeo:site-spec:begin -->';
35
+ export const BLOCK_END = '<!-- wkgeo:site-spec:end -->';
36
+
37
+ /** 沙箱任务提示词里那几行的标记(云端 AI 读不到本地文件,只能靠提示词 + 镜像里的 skill) */
38
+ export const PROMPT_BEGIN = '<!-- wkgeo:site-spec:prompt:begin -->';
39
+ export const PROMPT_END = '<!-- wkgeo:site-spec:prompt:end -->';
40
+
41
+ /**
42
+ * 四个约定文件 —— 覆盖主流 coding agent 的"启动即读"文件。
43
+ *
44
+ * ⚠️ CLI **不判断**调用者是哪个 agent(`process.env` 里没有可靠特征,用户在任意 shell 里跑、
45
+ * 或被别的工具当子进程调,都会误判)。所以默认**全写**,用 `--agents` 让用户自己挑。
46
+ */
47
+ export const AGENT_FILES = Object.freeze([
48
+ Object.freeze({
49
+ key: 'agents',
50
+ path: 'AGENTS.md',
51
+ label: 'DSH / Codex / 通用 AGENTS.md',
52
+ aliases: ['agents', 'agents.md', 'codex', 'dsh'],
53
+ }),
54
+ Object.freeze({
55
+ key: 'claude',
56
+ path: 'CLAUDE.md',
57
+ label: 'Claude Code CLAUDE.md',
58
+ aliases: ['claude', 'claude.md', 'claude-code'],
59
+ }),
60
+ Object.freeze({
61
+ key: 'cursor',
62
+ path: '.cursorrules',
63
+ label: 'Cursor .cursorrules',
64
+ aliases: ['cursor', '.cursorrules'],
65
+ }),
66
+ Object.freeze({
67
+ key: 'copilot',
68
+ path: '.github/copilot-instructions.md',
69
+ label: 'GitHub Copilot 指令文件',
70
+ aliases: ['copilot', 'github', 'copilot-instructions'],
71
+ }),
72
+ ]);
73
+
74
+ /**
75
+ * 读主源 markdown。
76
+ *
77
+ * @param {URL|string} [src] 默认包内 `spec/SITE-SPEC.md`(单测可指到别处)
78
+ * @returns {{path:string, markdown:string, bytes:number, lines:number}}
79
+ * @throws {CliError} 文件缺失 ⇒ `kind="missing_spec"`、exit 1、带中文 hint(不打堆栈)
80
+ */
81
+ export function readSpecMarkdown(src = SPEC_URL) {
82
+ const url = src instanceof URL ? src : pathToFileURL(String(src));
83
+ let filePath = String(url);
84
+ try {
85
+ filePath = fileURLToPath(url);
86
+ } catch {
87
+ /* 非 file: URL 时退回原样展示,别为展示路径把命令搞崩 */
88
+ }
89
+ try {
90
+ const markdown = fs.readFileSync(url, 'utf8');
91
+ return {
92
+ path: filePath,
93
+ markdown,
94
+ bytes: Buffer.byteLength(markdown, 'utf8'),
95
+ lines: markdown.split('\n').length,
96
+ };
97
+ } catch (e) {
98
+ const why = (e && e.code) || '读取失败';
99
+ throw new CliError(`当前安装包里没有建站规范(spec/SITE-SPEC.md):${filePath}(${why})`, {
100
+ kind: 'missing_spec',
101
+ code: (e && e.code) || null,
102
+ exitCode: EXIT.ERROR,
103
+ hint:
104
+ '这不是命令用错了:多半是开发目录里只拷了 lib/、或分发包缺了 files 白名单里的 spec/。' +
105
+ '可改用官方包 `npx -y @wkgeo/cli@latest spec`,或直接看仓库里的 cli/spec/SITE-SPEC.md',
106
+ cause: e,
107
+ });
108
+ }
109
+ }
110
+
111
+ /**
112
+ * 从全文里切出两个标记之间的正文(通用:精简版 / 沙箱提示词精要都走它)。
113
+ *
114
+ * @param {string} markdown
115
+ * @param {string} begin 起标记
116
+ * @param {string} end 止标记
117
+ * @param {string} what 报错时怎么称呼这一段(中文)
118
+ * @returns {string} 已去首尾空行、末尾带一个换行
119
+ * @throws {CliError} 标记缺失 / 顺序颠倒 / 空段 ⇒ 直接报错(宁可炸,也别写一份空规范出去)
120
+ */
121
+ export function extractSection(markdown, begin, end, what = '规范段落') {
122
+ const text = String(markdown || '');
123
+ const start = text.indexOf(begin);
124
+ const stop = text.indexOf(end);
125
+ if (start === -1 || stop === -1 || stop < start) {
126
+ throw new CliError(`建站规范里找不到${what}的标记(begin/end),无法生成`, {
127
+ kind: 'spec_marker_missing',
128
+ exitCode: EXIT.ERROR,
129
+ hint: `规范里必须有 ${begin} 与 ${end} 两行,且 begin 在 end 之前`,
130
+ });
131
+ }
132
+ const body = text
133
+ .slice(start + begin.length, stop)
134
+ .replace(/^\r?\n/, '')
135
+ .replace(/\s+$/, '');
136
+ if (!body.trim()) {
137
+ throw new CliError(`${what}的标记之间是空的,拒绝写出去`, {
138
+ kind: 'spec_marker_empty',
139
+ exitCode: EXIT.ERROR,
140
+ });
141
+ }
142
+ return body + '\n';
143
+ }
144
+
145
+ /**
146
+ * 「给 AI 的精简版」—— 写进项目四个约定文件的那一段。
147
+ *
148
+ * @param {string} markdown
149
+ * @returns {string}
150
+ */
151
+ export function extractAgentsBrief(markdown) {
152
+ return extractSection(markdown, BRIEF_BEGIN, BRIEF_END, '「给 AI 的精简版」');
153
+ }
154
+
155
+ /**
156
+ * 沙箱任务提示词里的精要(云端 AI 看不到本地文件,只能靠提示词 + 镜像里的 skill)。
157
+ *
158
+ * @param {string} markdown
159
+ * @returns {string}
160
+ */
161
+ export function extractPromptBrief(markdown) {
162
+ return extractSection(markdown, PROMPT_BEGIN, PROMPT_END, '「沙箱提示词精要」');
163
+ }
164
+
165
+ /**
166
+ * 解析 `--agents` 的取值。
167
+ *
168
+ * `all`(默认) = 四个都写;`none` = 一个都不写;
169
+ * 其它 = 逗号 / 空格分隔的点名:认 key(`agents` / `claude` / `cursor` / `copilot`)、
170
+ * 认文件名(`AGENTS.md` / `CLAUDE.md` / `.cursorrules` / `.github/copilot-instructions.md`)、
171
+ * 也认简写(`codex` / `dsh` / `github`)。
172
+ *
173
+ * @param {string|boolean|undefined} value
174
+ * @returns {Array<typeof AGENT_FILES[number]>}
175
+ * @throws {UsageError} 认不出来的名字 ⇒ 列出可用值(别静默忽略)
176
+ */
177
+ export function resolveAgentFiles(value) {
178
+ const raw = value === undefined || value === null || value === true ? 'all' : String(value).trim();
179
+ if (!raw || raw.toLowerCase() === 'all') return [...AGENT_FILES];
180
+ if (raw.toLowerCase() === 'none') return [];
181
+ const wanted = raw
182
+ .split(/[,\s]+/)
183
+ .map((one) => one.trim())
184
+ .filter(Boolean);
185
+ const out = [];
186
+ const unknown = [];
187
+ for (const name of wanted) {
188
+ const lower = name.toLowerCase().replace(/\\/g, '/');
189
+ const hit = AGENT_FILES.find(
190
+ (one) => one.key === lower || one.path.toLowerCase() === lower || one.aliases.includes(lower),
191
+ );
192
+ if (!hit) {
193
+ unknown.push(name);
194
+ continue;
195
+ }
196
+ if (!out.includes(hit)) out.push(hit);
197
+ }
198
+ if (unknown.length) {
199
+ const usable = AGENT_FILES.map((one) => `${one.key}(${one.path})`).join(' / ');
200
+ throw new UsageError(`--agents 不认识:${unknown.join(', ')}\n可用:all / none / ${usable}`);
201
+ }
202
+ return out;
203
+ }
204
+
205
+ /** 现有文件用的换行符(Windows 项目里多半是 CRLF,插入段跟着走,别混出两种) */
206
+ function eolOf(text) {
207
+ return String(text || '').includes('\r\n') ? '\r\n' : '\n';
208
+ }
209
+
210
+ /** 把块里的 `\n` 换成目标换行符 */
211
+ function withEol(block, eol) {
212
+ return eol === '\n' ? block : block.split('\n').join(eol);
213
+ }
214
+
215
+ /**
216
+ * 把「精简版」并进一份已有文件的内容 —— **纯函数**(单测直接对拍)。
217
+ *
218
+ * 四种结果:
219
+ * * `created` 文件原本不存在 / 空 ⇒ 直接就是这一段;
220
+ * * `replaced` 已有我们那一段(begin/end 都在)⇒ **原地替换**(改规范后重跑不会重复追加);
221
+ * * `appended` 文件有内容但没有我们的标记 ⇒ **只在末尾追加**,用户写的一个字不动;
222
+ * * `unchanged` 算出来的全文与原来一字节不差 ⇒ 不写盘(幂等)。
223
+ *
224
+ * @param {string|null} existing 已有内容(null = 文件不存在)
225
+ * @param {string} brief 「给 AI 的精简版」正文(末尾带换行)
226
+ * @returns {{content:string, action:'created'|'replaced'|'appended'|'unchanged'}}
227
+ */
228
+ export function upsertBriefBlock(existing, brief) {
229
+ const body = String(brief || '').replace(/\s+$/, '');
230
+ const block = `${BLOCK_BEGIN}\n${body}\n${BLOCK_END}`;
231
+ if (existing === null || existing === undefined || !String(existing).trim()) {
232
+ const content = `${block}\n`;
233
+ return { content, action: 'created' };
234
+ }
235
+ const text = String(existing);
236
+ const eol = eolOf(text);
237
+ const marker = withEol(block, eol);
238
+ const start = text.indexOf(BLOCK_BEGIN);
239
+ const end = text.indexOf(BLOCK_END, start === -1 ? 0 : start);
240
+ if (start !== -1 && end !== -1) {
241
+ const after = text.slice(end + BLOCK_END.length);
242
+ const next = text.slice(0, start) + marker + after;
243
+ return { content: next, action: next === text ? 'unchanged' : 'replaced' };
244
+ }
245
+ /* 没有我们的标记 ⇒ 追加到末尾;文件末尾没换行就先补一个,段间留一个空行 */
246
+ const base = text.endsWith('\n') ? text : text + eol;
247
+ const next = `${base}${eol}${marker}${eol}`;
248
+ return { content: next, action: 'appended' };
249
+ }
250
+
251
+ /**
252
+ * 规划「四个约定文件各要写成什么」—— **不写盘**(dry-run 与真写共用同一份计划)。
253
+ *
254
+ * @param {{dir?:string, markdown:string, files?:Array, exists?:Function, readFile?:Function}} input
255
+ * @returns {Array<{key,path,action,absPath,content,reason}>}
256
+ */
257
+ export function planAgentFiles(input = {}) {
258
+ const dir = path.resolve(String(input.dir || process.cwd()));
259
+ const files = Array.isArray(input.files) ? input.files : [...AGENT_FILES];
260
+ const brief = extractAgentsBrief(input.markdown);
261
+ const read = input.readFile || ((p) => (fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null));
262
+ const rows = [];
263
+ for (const one of files) {
264
+ const absPath = path.join(dir, one.path.split('/').join(path.sep));
265
+ const existing = read(absPath);
266
+ const { content, action } = upsertBriefBlock(existing, brief);
267
+ rows.push({
268
+ key: one.key,
269
+ path: one.path,
270
+ label: one.label,
271
+ absPath,
272
+ action,
273
+ content,
274
+ existed: existing !== null && existing !== undefined,
275
+ });
276
+ }
277
+ return rows;
278
+ }
279
+
280
+ /**
281
+ * 落盘(只写 `action !== 'unchanged'` 的行)。
282
+ *
283
+ * @param {Array} plan `planAgentFiles()` 的结果
284
+ * @param {{mkdir?:Function, writeFile?:Function}} [io] 单测注入点
285
+ * @returns {{written:string[], skipped:string[]}}
286
+ */
287
+ export function writeAgentFiles(plan, io = {}) {
288
+ const mkdir = io.mkdir || ((p) => fs.mkdirSync(p, { recursive: true }));
289
+ const writeFile = io.writeFile || ((p, c) => fs.writeFileSync(p, c, 'utf8'));
290
+ const written = [];
291
+ const skipped = [];
292
+ for (const row of plan) {
293
+ if (row.action === 'unchanged') {
294
+ skipped.push(row.path);
295
+ continue;
296
+ }
297
+ mkdir(path.dirname(row.absPath));
298
+ writeFile(row.absPath, row.content);
299
+ written.push(row.path);
300
+ }
301
+ return { written, skipped };
302
+ }
@@ -39,6 +39,69 @@ export const DESIGN_VIEWPORTS = VIEWPORTS;
39
39
 
40
40
  const HERE = path.dirname(fileURLToPath(import.meta.url));
41
41
 
42
+ // ------------------------------------------------- 每栏目一个模板页(2026-11-21)
43
+
44
+ /**
45
+ * 模板绑定契约(唯一真源:`aliyun/fc/_shared/template-binding-contract.js`)。
46
+ * CLI 不打包它,运行时按相对路径现取(与 `manifest-apply.mjs` 同一个套路);取不到 ⇒ 本能力静默跳过。
47
+ */
48
+ let bindingContractPromise = null;
49
+ function loadBindingContract() {
50
+ if (!bindingContractPromise) {
51
+ const url = new URL('../../aliyun/fc/_shared/template-binding-contract.js', import.meta.url);
52
+ bindingContractPromise = import(url.href).then((m) => m.default || m).catch(() => null);
53
+ }
54
+ return bindingContractPromise;
55
+ }
56
+
57
+ /**
58
+ * **给每个栏目复制一份自己的模板页**(老板 2026-11-21):
59
+ * 「尽量每一个栏目制作一个模版,哪怕一样的,也复制一个模版绑定当前的栏目,这样就方便后期修改。」
60
+ *
61
+ * 命名规则 / 撞名兜底全在契约里(`perCategoryPagePath`:`pages/c-<slug>.html`,撞名 `-2`、`-3` …),
62
+ * 这里只负责**落文件**:
63
+ * * 模板里已经有这一页 ⇒ 不动(`action:'keep'`,客户改过的那份保留);
64
+ * * 没有 ⇒ 从该栏目当前用的那页复制一份(内容一模一样,换绑不改版式);
65
+ * * 同时在 `template.json.bindings[]` 声明这一页的类型,后台绑定时才校验得住。
66
+ *
67
+ * @returns {Promise<{pages: Array, bindings: Array, warnings: string[], supported: boolean}>}
68
+ */
69
+ export async function materializePerColumnPages({ outDir, columns, files, say }) {
70
+ const contract = await loadBindingContract();
71
+ if (!contract || typeof contract.planPerCategoryPages !== 'function') {
72
+ return { pages: [], bindings: [], warnings: ['没取到模板绑定契约,跳过「每栏目一个模板页」'], supported: false };
73
+ }
74
+ const plan = contract.planPerCategoryPages({ columns, files });
75
+ const pages = [];
76
+ for (const one of plan.pages) {
77
+ if (one.action === 'keep') {
78
+ pages.push({ ...one, wrote: false });
79
+ continue;
80
+ }
81
+ const srcAbs = path.join(outDir, one.sourcePath.split('/').join(path.sep));
82
+ const dstAbs = path.join(outDir, one.path.split('/').join(path.sep));
83
+ const bytes = await fsp.readFile(srcAbs);
84
+ await fsp.writeFile(dstAbs, bytes);
85
+ pages.push({ ...one, wrote: true, bytes: bytes.length });
86
+ }
87
+ /**
88
+ * 声明这些页的 `target_type`(从**来源页**的名字推断:index ⇒ list、about ⇒ single_page …)。
89
+ * 认不出来就不声明 —— 契约口径是「缺省不报错」,不硬编一个类型去拦客户。
90
+ */
91
+ const bindings = [];
92
+ for (const one of plan.pages) {
93
+ const targetType = contract.targetTypeFromPath(one.sourcePath) || '';
94
+ if (!targetType) continue;
95
+ bindings.push({ path: one.path, target_type: targetType });
96
+ }
97
+ if (typeof say === 'function' && pages.length) {
98
+ say(`每栏目一个模板页:${pages.length} 个(pages/c-<slug>.html;新复制 ${plan.stats.copy} 个、已有 ${plan.stats.kept} 个)`);
99
+ }
100
+ if (typeof say === 'function') for (const one of plan.warnings) say(` ⚠️ ${one}`);
101
+ return { pages, bindings, warnings: plan.warnings, supported: true };
102
+ }
103
+
104
+
42
105
  // ---------------------------------------------------------------- 基础文本工具
43
106
 
44
107
  const ENTITIES = {
@@ -756,6 +819,12 @@ export async function generateFromUrl({
756
819
  // key 由栏目名派生(中文名 slugify 为空 → 退到页面名),同名再 -2 去重
757
820
  let base = spec.key || slugify(spec.name) || slugify(spec.page) || "column";
758
821
  if (!/^[a-z0-9][a-z0-9-]*$/.test(base)) base = slugify(spec.page) || "column";
822
+ /**
823
+ * 首页那一栏的 key 统一成 `home`(2026-11-21):中文菜单名 slugify 之后是空 ⇒ 以前落到页面名
824
+ * `index`,跟平台预置栏目的 slug(`home`)对不上 —— 于是「每栏目一个模板页」会做成
825
+ * `pages/c-index.html`,而建站播种按栏目 slug 找的是 `pages/c-home.html`,白做一份。
826
+ */
827
+ if (base === "index") base = "home";
759
828
  let k = base;
760
829
  let i = 2;
761
830
  while (usedKeys.has(k)) k = `${base}-${i++}`;
@@ -845,6 +914,17 @@ export async function generateFromUrl({
845
914
  });
846
915
 
847
916
  const demo = columns.some((c) => c.items.length > 0);
917
+ /**
918
+ * ★ 2026-11-21(老板):**每个栏目复制一份自己的模板页** ——
919
+ * `pages/c-<slug>.html`,内容与它当前用的那页一模一样;后期只改自己那份,不影响别的栏目。
920
+ * 这些页同时进 `template.json.files[]`(打包/发布要带上)与 `bindings[]`(后台绑定要校验)。
921
+ */
922
+ const mirrorPages = await materializePerColumnPages({
923
+ outDir,
924
+ columns,
925
+ files: pagesOut.map((p) => `pages/${p.name}.html`),
926
+ say,
927
+ });
848
928
  const template = {
849
929
  _format: TEMPLATE_FORMAT,
850
930
  key,
@@ -863,7 +943,11 @@ export async function generateFromUrl({
863
943
  columns,
864
944
  requires: [],
865
945
  data: {},
866
- files: pagesOut.map((p) => `pages/${p.name}.html`).concat(['partials/header.html', 'partials/nav.html', 'partials/footer.html', 'assets/img/placeholder.svg']),
946
+ files: pagesOut
947
+ .map((p) => `pages/${p.name}.html`)
948
+ .concat(mirrorPages.pages.map((p) => p.path))
949
+ .concat(['partials/header.html', 'partials/nav.html', 'partials/footer.html', 'assets/img/placeholder.svg']),
950
+ ...(mirrorPages.bindings.length ? { bindings: mirrorPages.bindings } : {}),
867
951
  };
868
952
 
869
953
  // ---- 8) assets/base + 占位图 + template.json ----
@@ -904,6 +988,7 @@ export async function generateFromUrl({
904
988
  assetErrors: localized.errors.length,
905
989
  unmappedLinks: [...new Set(unmapped)].length,
906
990
  partials: [partHeader, partNav, partFooter].filter(Boolean).length,
991
+ perColumnPages: mirrorPages.pages.length,
907
992
  },
908
993
  pages: pagesOut,
909
994
  };
@@ -1066,6 +1151,12 @@ export async function generateFromDir({ srcDir, outDir, key, capture = true, des
1066
1151
  // key 由栏目名派生(中文名 slugify 为空 → 退到页面名),同名再 -2 去重
1067
1152
  let base = spec.key || slugify(spec.name) || slugify(spec.page) || "column";
1068
1153
  if (!/^[a-z0-9][a-z0-9-]*$/.test(base)) base = slugify(spec.page) || "column";
1154
+ /**
1155
+ * 首页那一栏的 key 统一成 `home`(2026-11-21):中文菜单名 slugify 之后是空 ⇒ 以前落到页面名
1156
+ * `index`,跟平台预置栏目的 slug(`home`)对不上 —— 于是「每栏目一个模板页」会做成
1157
+ * `pages/c-index.html`,而建站播种按栏目 slug 找的是 `pages/c-home.html`,白做一份。
1158
+ */
1159
+ if (base === "index") base = "home";
1069
1160
  let k = base;
1070
1161
  let i = 2;
1071
1162
  while (usedKeys.has(k)) k = `${base}-${i++}`;
@@ -1162,6 +1253,17 @@ export async function generateFromDir({ srcDir, outDir, key, capture = true, des
1162
1253
  };
1163
1254
  });
1164
1255
 
1256
+ /**
1257
+ * ★ 2026-11-21(老板):**每个栏目复制一份自己的模板页** —— 与 from-url 同一套规则
1258
+ * (`pages/c-<slug>.html`;内容一样,文件独立,后期只改自己那份)。
1259
+ */
1260
+ const mirrorPages = await materializePerColumnPages({
1261
+ outDir,
1262
+ columns,
1263
+ files: pagesOut.map((p) => `pages/${p.name}.html`),
1264
+ say,
1265
+ });
1266
+
1165
1267
  const template = {
1166
1268
  _format: TEMPLATE_FORMAT,
1167
1269
  key,
@@ -1180,7 +1282,11 @@ export async function generateFromDir({ srcDir, outDir, key, capture = true, des
1180
1282
  columns,
1181
1283
  requires: [],
1182
1284
  data: {},
1183
- files: pagesOut.map((p) => `pages/${p.name}.html`).concat(['partials/header.html', 'partials/nav.html', 'partials/footer.html', 'assets/img/placeholder.svg']),
1285
+ files: pagesOut
1286
+ .map((p) => `pages/${p.name}.html`)
1287
+ .concat(mirrorPages.pages.map((p) => p.path))
1288
+ .concat(['partials/header.html', 'partials/nav.html', 'partials/footer.html', 'assets/img/placeholder.svg']),
1289
+ ...(mirrorPages.bindings.length ? { bindings: mirrorPages.bindings } : {}),
1184
1290
  };
1185
1291
 
1186
1292
  const baseDir = resolveBaseDir(null, {});
@@ -1223,6 +1329,7 @@ export async function generateFromDir({ srcDir, outDir, key, capture = true, des
1223
1329
  items: columns.reduce((n, c) => n + c.items.length, 0),
1224
1330
  assets: copied.length,
1225
1331
  partials: [pH, pN, pF].filter(Boolean).length,
1332
+ perColumnPages: mirrorPages.pages.length,
1226
1333
  },
1227
1334
  pages: pagesOut,
1228
1335
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wkgeo/cli",
3
- "version": "2.0.1",
3
+ "version": "2.0.3",
4
4
  "description": "云站平台官方命令行客户端(@wkgeo/cli):授权登录一次,之后建站 / 下单 / 钱包支付 / 查余额都不用再登录(OAuth 授权码 + PKCE,公共客户端,零第三方依赖)",
5
5
  "keywords": [
6
6
  "wkgeo",
@@ -24,6 +24,7 @@
24
24
  "files": [
25
25
  "wkgeo.mjs",
26
26
  "lib",
27
+ "spec",
27
28
  "README.md",
28
29
  "SKILL.md",
29
30
  "CHANGELOG.md",