@wkgeo/cli 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +249 -203
  2. package/README.md +151 -19
  3. package/SKILL.md +108 -27
  4. package/lib/args.mjs +2 -2
  5. package/lib/asset-role.mjs +68 -0
  6. package/lib/cms.mjs +2 -2
  7. package/lib/commands/billing.mjs +56 -10
  8. package/lib/commands/cms.mjs +49 -13
  9. package/lib/commands/content.mjs +108 -0
  10. package/lib/commands/crawl.mjs +219 -0
  11. package/lib/commands/geo.mjs +1673 -0
  12. package/lib/commands/index.mjs +640 -528
  13. package/lib/commands/member.mjs +930 -0
  14. package/lib/commands/seo.mjs +1386 -0
  15. package/lib/commands/siteops.mjs +3 -3
  16. package/lib/commands/sites.mjs +21 -125
  17. package/lib/commands/template.mjs +1474 -0
  18. package/lib/config.mjs +16 -13
  19. package/lib/content-apply.mjs +664 -0
  20. package/lib/content-check.mjs +887 -0
  21. package/lib/content-contract.mjs +957 -0
  22. package/lib/errors.mjs +6 -0
  23. package/lib/format.mjs +5 -1
  24. package/lib/manifest-apply.mjs +1499 -0
  25. package/lib/manifest-schema.json +476 -0
  26. package/lib/manifest.mjs +1082 -0
  27. package/lib/oauth-urls.mjs +1 -1
  28. package/lib/runtime.mjs +5 -1
  29. package/lib/site-create.mjs +536 -0
  30. package/lib/tar.mjs +207 -0
  31. package/lib/template-anim.mjs +1338 -0
  32. package/lib/template-animation.mjs +232 -0
  33. package/lib/template-capture.mjs +700 -0
  34. package/lib/template-gen.mjs +1204 -0
  35. package/lib/template-pack.mjs +206 -0
  36. package/lib/template-package.mjs +522 -0
  37. package/lib/template-publish.mjs +733 -0
  38. package/lib/template-score.mjs +865 -0
  39. package/lib/template-validate.mjs +368 -0
  40. package/lib/template-verify.mjs +434 -0
  41. package/lib/templates-sync.mjs +616 -0
  42. package/package.json +2 -2
@@ -25,6 +25,7 @@ import fs from 'node:fs';
25
25
  import path from 'node:path';
26
26
 
27
27
  import { camel } from '../args.mjs';
28
+ import { ASSET_ROLE_HINT, normalizeAssetRole } from '../asset-role.mjs';
28
29
  import { uploadToOss } from '../cms.mjs';
29
30
  import { CliError, UsageError } from '../errors.mjs';
30
31
  import { formatTime } from '../format.mjs';
@@ -639,7 +640,7 @@ export const categoriesBindTemplateCommand = {
639
640
  'wkgeo templates list # 先看本站有哪些 html',
640
641
  ],
641
642
  notes: [
642
- '模板文件白名单:`字母/数字/中划线/下划线 + .html`;文件不存在时服务端会拒绝 —— 这里先查一次并列出可选文件。',
643
+ '模板文件白名单:`字母/数字/中划线/下划线(可用 / 分子目录)+ .html`;文件不存在时服务端会拒绝 —— 这里先查一次并列出可选文件。',
643
644
  '不绑定时按栏目类型自动选:频道页 index.html、单页 about.html、列表页/内容页 content.html。',
644
645
  ],
645
646
  async run(ctx) {
@@ -658,8 +659,10 @@ export const categoriesBindTemplateCommand = {
658
659
 
659
660
  let templatePath = '';
660
661
  if (!clear) {
661
- if (!/^[A-Za-z0-9_-]+\.html$/.test(wanted)) {
662
- throw new UsageError(`模板文件名不合法:${wanted}\n只允许 字母/数字/中划线/下划线 + .html,例如 about.html`);
662
+ if (!/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*\.html$/i.test(wanted)) {
663
+ throw new UsageError(
664
+ `模板文件名不合法:${wanted}\n只允许 字母/数字/中划线/下划线(可用 / 分子目录)+ .html,例如 about.html / news/list.html`,
665
+ );
663
666
  }
664
667
  /** 先查一次本站模板,把"没有这个文件"变成一句带候选的错误(服务端也会查,但它的报错没有候选列表) */
665
668
  const tpl = await ctx.cmsCall('templateGet', {});
@@ -1078,21 +1081,25 @@ const MAX_UPLOAD_BYTES = 200 * 1024 * 1024;
1078
1081
  export const assetsUploadCommand = {
1079
1082
  name: 'assets upload',
1080
1083
  summary: '上传素材(签名 → 直传 OSS → 登记;CLI 不碰 AK,二进制不进云函数)',
1081
- usage: 'wkgeo assets upload <本地文件> [--name 显示名] [--site <站点ID>]',
1082
- args: [{ name: 'file', required: true, desc: '本地文件路径(图片 / 视频 / 文档 / PDF / 压缩包)' }],
1084
+ usage: 'wkgeo assets upload <本地文件> [--name 显示名] [--role image|css|js|file] [--site <站点ID>]',
1085
+ args: [{ name: 'file', required: true, desc: '本地文件路径(图片 / 视频 / 文档 / PDF / 压缩包 / css / js)' }],
1083
1086
  flags: {
1084
1087
  name: { type: 'string', desc: '素材显示名(默认取文件名)' },
1088
+ role: { type: 'string', desc: `素材角色:${ASSET_ROLE_HINT}(默认按扩展名推断)` },
1085
1089
  ...SITE_FLAG,
1086
1090
  },
1087
1091
  examples: [
1088
1092
  'wkgeo assets upload ./logo.png',
1089
1093
  'wkgeo assets upload "D:\\图\\展会.jpg" --name 展会现场',
1094
+ 'wkgeo assets upload ./site.css --role css',
1090
1095
  'wkgeo assets upload ./brochure.pdf --json # 拿 id 去挂内容:contents update <id> --attachments <素材ID>',
1091
1096
  ],
1092
1097
  notes: [
1093
1098
  '三步走:`assetSign` 取票据(锁 key/大小,10 分钟)→ 用票据把文件 POST 到 OSS → `assetRegister` 落库并回读校验。',
1094
1099
  'CLI 只做搬运:既不保存也不打印 OSS 的 AccessKey(AK 只在云函数里)。',
1095
1100
  '支持的扩展名与上限由服务端决定(图片 10MB / PDF 50MB / 视频 200MB …)。',
1101
+ '`--role` 是素材角色(image / css / js / file,缺省按扩展名推断):它随 `assetSign` / `assetRegister` 一起透传;服务端素材表暂未收这一列(多传会被忽略,不会报错)。',
1102
+ '站点样式 / 脚本要进页面:放模板工程里用 `wkgeo templates save assets/site.css` 上模板,发布时服务端会合并成 `assets/css/site-<hash>.css` 外链。',
1096
1103
  ],
1097
1104
  async run(ctx) {
1098
1105
  const { out, flags } = ctx;
@@ -1115,9 +1122,12 @@ export const assetsUploadCommand = {
1115
1122
 
1116
1123
  const fileName = path.basename(filePath);
1117
1124
  const displayName = String(flags.name || fileName).trim() || fileName;
1125
+ const roleRes = normalizeAssetRole(flags.role, fileName);
1126
+ if (roleRes.error) throw new UsageError(roleRes.error, { hint: `--role 只收 ${ASSET_ROLE_HINT}` });
1127
+ const role = roleRes.role;
1118
1128
 
1119
1129
  /** ① 取直传票据(fileName 决定 kind / mime,bytes 让服务端提前挡掉超限) */
1120
- const ticket = await ctx.contentCall('assetSign', { fileName, bytes: stat.size });
1130
+ const ticket = await ctx.contentCall('assetSign', { fileName, bytes: stat.size, role });
1121
1131
  if (!ticket || !ticket.key || !ticket.uploadUrl) {
1122
1132
  throw new CliError('服务端没有返回直传票据(assetSign)', {
1123
1133
  kind: 'bad_response',
@@ -1130,18 +1140,19 @@ export const assetsUploadCommand = {
1130
1140
  await uploadToOss({ ticket, buffer, fileName, fetchImpl: ctx.fetchImpl });
1131
1141
 
1132
1142
  /** ③ 登记落库(服务端会回读一次 OSS,确认文件真的在) */
1133
- const asset = await ctx.contentCall('assetRegister', { key: ticket.key, name: displayName });
1143
+ const asset = await ctx.contentCall('assetRegister', { key: ticket.key, name: displayName, role });
1134
1144
  const data = {
1135
1145
  site_id: siteIdOf(site),
1136
1146
  asset,
1137
1147
  key: ticket.key,
1148
+ role,
1138
1149
  url: (asset && asset.url) || ticket.url || '',
1139
1150
  };
1140
1151
 
1141
1152
  if (!out.json) {
1142
1153
  out.ok(`素材已上传:${(asset && asset.name) || displayName}`);
1143
1154
  out.line(` 素材 ID:${(asset && asset.id) || '-'}`);
1144
- out.line(` 类型:${(asset && asset.kind) || ticket.kind || '-'}(${formatBytes(stat.size)})`);
1155
+ out.line(` 类型:${(asset && asset.kind) || ticket.kind || '-'}(${formatBytes(stat.size)})· 角色:${role}`);
1145
1156
  out.line(` 地址:${data.url || '-'}`);
1146
1157
  out.info(` 引用它:\`wkgeo contents update <内容ID> --cover ${(asset && asset.id) || '<素材ID>'}\``);
1147
1158
  }
@@ -1494,11 +1505,31 @@ export const templatesGetCommand = {
1494
1505
  /** 服务端上限:`templateMaxBytes = 400 * 1024`(按**字符**算) */
1495
1506
  const TEMPLATE_MAX_CHARS = 400 * 1024;
1496
1507
 
1508
+ /**
1509
+ * 模板文件路径口径 —— 与服务端 `wkgeo-cms/src/template-files.js:51-52` / `index.js` 的
1510
+ * `templateFilePathPattern` 对齐(task-46):既收根目录的 `index.html`,也收子目录里的
1511
+ * `assets/site.css`、`assets/site.js`(可编辑集 = html/css/js,含 .min.css / .min.js)。
1512
+ * 图片**不在**这里:图片走 `assets upload`(模板里的 `<img src="/assets/...">` 由发布侧处理)。
1513
+ */
1514
+ const TEMPLATE_FILE_RE = /^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*\.(?:html|css|js|min\.css|min\.js)$/i;
1515
+
1516
+ /** 扩展名只收这几种(其余如 .png 会被服务端单独拒,本地先挡省一次往返) */
1517
+ const TEMPLATE_FILE_HINT = '.html / .css / .js / .min.css / .min.js(可用 / 分子目录)';
1518
+
1497
1519
  export const templatesSaveCommand = {
1498
1520
  name: 'templates save',
1499
- summary: '新建 / 覆盖一个模板 html(≤40 万字符,写操作会记系统日志)',
1500
- usage: 'wkgeo templates save <模板文件名.html> (--file <本地文件> | --content <源码>) [--site <站点ID>]',
1501
- args: [{ name: 'path', required: true, desc: '模板文件名,如 index.html(字母/数字/中划线/下划线 + .html)' }],
1521
+ summary: '新建 / 覆盖一个模板文件(html / css / js,≤40 万字符,写操作会记系统日志)',
1522
+ usage:
1523
+ 'wkgeo templates save <模板文件路径> (--file <本地文件> | --content <源码>) [--site <站点ID>]\n' +
1524
+ ' 例:wkgeo templates save index.html --file ./index.html\n' +
1525
+ ' wkgeo templates save assets/site.css --file ./assets/site.css',
1526
+ args: [
1527
+ {
1528
+ name: 'path',
1529
+ required: true,
1530
+ desc: `模板文件路径,如 index.html / assets/site.css(字母/数字/中划线/下划线,可用 / 分子目录;收 ${TEMPLATE_FILE_HINT})`,
1531
+ },
1532
+ ],
1502
1533
  flags: {
1503
1534
  file: { type: 'string', desc: '从本地文件读源码' },
1504
1535
  content: { type: 'string', desc: '直接给源码(与 --file 二选一;适合短模板)' },
@@ -1507,18 +1538,23 @@ export const templatesSaveCommand = {
1507
1538
  examples: [
1508
1539
  'wkgeo templates save index.html --file ./index.html',
1509
1540
  'wkgeo templates save about.html --content "<!doctype html><h1>{{ category.name }}</h1>"',
1541
+ 'wkgeo templates save assets/site.css --file ./assets/site.css',
1542
+ 'wkgeo templates save assets/site.js --file ./assets/site.js',
1510
1543
  ],
1511
1544
  notes: [
1512
1545
  '同名文件直接覆盖(服务端 `on conflict do update`);改坏了用 `wkgeo templates get <文件名>` 先取回旧源码备份。',
1546
+ `路径口径与服务端一致:字母/数字/中划线/下划线,可用 \`/\` 分子目录,扩展名收 ${TEMPLATE_FILE_HINT};图片不上这条路(用 \`assets upload\`)。`,
1547
+ '模板里的 css / js 由发布侧合并成 `<站点>/assets/css/site-<hash>.css`、`assets/js/site-<hash>.js` 并改成外链(页面里不再内联)。',
1513
1548
  '模板语法与可用变量见 docs/功能-模板.md(`{{ category.name }}` / `{{#each contents}}` 等)。',
1514
1549
  ],
1515
1550
  async run(ctx) {
1516
1551
  const { out, flags } = ctx;
1517
1552
  const site = ctx.cmsSite();
1518
1553
  const filePath = String(ctx.positional.path || '').trim();
1519
- if (!/^[A-Za-z0-9_-]+\.html$/.test(filePath)) {
1554
+ if (!TEMPLATE_FILE_RE.test(filePath)) {
1520
1555
  throw new UsageError(
1521
- `模板文件名不合法:${filePath || '(空)'}\n只允许 字母/数字/中划线/下划线 + .html,例如 index.html / news-list.html`,
1556
+ `模板文件名不合法:${filePath || '(空)'}\n只允许 字母/数字/中划线/下划线(可用 / 分子目录)+ ${TEMPLATE_FILE_HINT},` +
1557
+ '例如 index.html / news-list.html / assets/site.css',
1522
1558
  );
1523
1559
  }
1524
1560
  const hasFile = flags.file !== undefined;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * `wkgeo content` —— **写内容 / 查一致性** 的三个原语(2026-10-30 task-178 拆开)。
3
+ *
4
+ * 老板 2026-10-30 定的三件事落在这里:
5
+ * 1. 「内容必须入库、栏目必须建库、框架样式不许前端写死」⇒ 写内容只走 content 组的两条命令:
6
+ * * `content apply`(本体在 `cli/lib/manifest-apply.mjs`)= **建站清单落站**,收 `--file site-manifest.json`;
7
+ * * `content fill`(本文件)= **模板内容契约填库**,收 `--manifest`(`sections[]` / `pages[]` 形状);
8
+ * 2. 「建表结构与 CMS 前端表单保持一致、字段类型对齐」⇒ `content check` 把契约/库/前台拉在一起比;
9
+ * 3. 「三来源(模板/网址/文件)怎么分析是 A 的事,平台只给原语 + 规范 skill」⇒
10
+ * 命令只收一份 manifest,不猜、不抓、不解析文档;那部分在
11
+ * `docs/规范-建站三来源-20261031.md`(A 用自己的浏览器/office 能力做)。
12
+ *
13
+ * 与 `wkgeo contents *` 的分工(别混):
14
+ * * `contents *` = 单人单条的 CMS CRUD(改一条、看一条),后台按钮的等价物;
15
+ * * `content apply` / `content fill` = **一次落一整份清单**,带 dry-run / diff / 幂等 / 拒绝;
16
+ * * `content check` = **只读**自检 + 评分,不改任何数据。
17
+ *
18
+ * 为什么拆两个命令(task-178):task-73 的两条实现线(建站清单 `site-manifest@1`、模板内容契约
19
+ * `sections[]/pages[]`)曾挤在同一个 `content apply` 里靠 `--file` / `--manifest` 分流,
20
+ * 结果模板契约那条从 CLI 表面消失。现在一条命令只认一种清单,参数表互不重叠。
21
+ */
22
+
23
+ import { CliError } from '../errors.mjs';
24
+ import { runContentApply } from '../content-apply.mjs';
25
+ import { runContentCheck } from '../content-check.mjs';
26
+
27
+ const SITE_FLAG = {
28
+ site: {
29
+ type: 'string',
30
+ desc: '站点 ID(uuid;默认用 `wkgeo site use` 选中的站点)',
31
+ },
32
+ };
33
+
34
+ const LANG_FLAG = {
35
+ lang: {
36
+ type: 'string',
37
+ desc: '语言(zh-CN / en…;默认站点默认语言)',
38
+ },
39
+ };
40
+
41
+ export const contentFillCommand = {
42
+ name: 'content fill',
43
+ summary: '按模板内容清单(sections[]/pages[])一次填库(默认 dry-run;--confirm 才写;逐栏目 upsert、幂等、未知字段拒绝)',
44
+ usage: 'wkgeo content fill --site <站点ID> --manifest <文件|-> [--confirm] [--lang <l>] [--json]',
45
+ args: [],
46
+ flags: {
47
+ manifest: { type: 'string', required: true, desc: '模板内容清单 JSON 文件路径(`sections[]`/`pages[]` 形状);`-` = 从标准输入读' },
48
+ confirm: { type: 'boolean', desc: '真的写库(不加就是 dry-run,只算不写)' },
49
+ 'dry-run': { type: 'boolean', desc: '显式 dry-run(与默认一致;和 --confirm 互斥)' },
50
+ ...SITE_FLAG,
51
+ ...LANG_FLAG,
52
+ },
53
+ examples: [
54
+ 'wkgeo content fill --site 8f3c1a2e-… --manifest .tmp-build/t173/site-content.json',
55
+ 'wkgeo content fill --site 8f3c1a2e-… --manifest - --dry-run < 清单.json',
56
+ 'wkgeo content fill --site 8f3c1a2e-… --manifest 清单.json --confirm --json',
57
+ ],
58
+ notes: [
59
+ '**默认 dry-run**:只输出「每个栏目新增/更新/跳过几条」与人话预览,一条不写。要写必须显式 `--confirm`。',
60
+ '**逐栏目 upsert**:按 `slug`(其次 `title`)匹配既有内容;同一份清单连跑两次,第二次 created=0 / updated=0。',
61
+ '**拒绝即全不写**:未知栏目、未知字段、停用字段、类型不符(image 传 URL、number 传 "abc"、richtext 传裸 HTML…)都会进 `rejected[]` 并 exit 1,**一条都不落库**,绝不静默丢字段。',
62
+ '**栏目必须先在库里**:本命令不建栏目(那是 `sites create` / 模板安装阶段的事),A 不能自己造栏目。单页写 `pages[]`,列表写 `sections[]`。',
63
+ '值形状见 `docs/规范-模板内容契约.md` §5;图片/附件一律传**素材 id**(先用 `wkgeo assets upload` 传 OSS)。',
64
+ '**建站清单(`site-manifest.json`:栏目/导航/素材/内容整站一次落)不是本命令**,走 `wkgeo content apply --file <site-manifest.json>`(见 `docs/规范-建站内容契约.md`)。',
65
+ ],
66
+ async run(ctx) {
67
+ const result = await runContentApply(ctx, ctx.flags);
68
+ /** 拒绝项:runContentApply 已抛 CliError(exit 1),这里只剩成功路径 */
69
+ if (result && result.ok === false) throw new CliError('清单未通过校验', { kind: 'contract', exitCode: 1, details: result });
70
+ return result;
71
+ },
72
+ };
73
+
74
+ export const contentCheckCommand = {
75
+ name: 'content check',
76
+ summary: '一致性自检 + 评分:契约(template.json)↔ 库(cms_category/cms_field/值)↔ 前台渲染字段',
77
+ usage: 'wkgeo content check [--site <站点ID>] [--template <模板key>] [--lang <l>] [--json]',
78
+ args: [],
79
+ flags: {
80
+ ...SITE_FLAG,
81
+ template: { type: 'string', desc: '模板 key(`templates/<key>/`)或模板目录 / template.json 路径' },
82
+ ...LANG_FLAG,
83
+ 'max-details': { type: 'number', desc: '最多取多少条内容详情做值校验(默认 300,防大站跑太久)' },
84
+ },
85
+ examples: [
86
+ 'wkgeo content check --site 8f3c1a2e-…',
87
+ 'wkgeo content check --template qbk-enterprise',
88
+ 'wkgeo content check --site 8f3c1a2e-… --template ind-law-firm --json',
89
+ ],
90
+ notes: [
91
+ '9 维 100 分:结构完整 14 / 类型对齐 16 / 必填覆盖 14 / 图片规格 10 / SEO 10 / 多语言 8 / 越界检测 12 / 栏目-页面闭合 10 / 渲染闭合 6。',
92
+ '**四种硬问题直接 exit 1**:类型不符、必填缺字段、库里多出契约外字段、契约声明的栏目在库里缺列。其余只扣分 + 出 finding。',
93
+ '只读:本命令不写任何数据(不复用 CMS 的写动作),可以随时跑。',
94
+ '`--template` 单独跑 = 离线契约自检(不需要登录);`--site` 单独跑 = 库侧自检;两个都给 = 三方比对。',
95
+ ],
96
+ async run(ctx) {
97
+ return runContentCheck(ctx, ctx.flags);
98
+ },
99
+ };
100
+
101
+ /**
102
+ * `content` 组三条命令(task-178 拆开):
103
+ * * `content apply` —— 建站清单落站(本体 `cli/lib/manifest-apply.mjs`,`--file site-manifest.json`);
104
+ * * `content fill` —— 模板内容契约填库(本文件,`--manifest`,`sections[]`/`pages[]`);
105
+ * * `content check` —— 只读一致性自检 + 评分。
106
+ * 三条各注册一份,**不再**靠某条命令动态 import 另一条的实现兜底。
107
+ */
108
+ export const contentCommands = [contentFillCommand, contentCheckCommand];
@@ -0,0 +1,219 @@
1
+ /**
2
+ * `wkgeo crawl` —— 并发抓整站,只出「结构化摘要 + 正文」,**不回传整页 HTML**。
3
+ *
4
+ * ## 为什么要有这条命令(task-84)
5
+ * 老站导入以前是「一页一次模型往返」:每页 4–10s、每进程 300–600MB,
6
+ * 100 页就等于把一次导入拖成十几分钟,还按页付模型钱。
7
+ * 抓取本身是**确定性的活**(BFS、同源、去重、限速、超时重试),不该烧模型:
8
+ * * 并发 6(默认,上限 10),同 host 间隔 ≥150ms(robots 的 Crawl-delay 更大时以它为准);
9
+ * * 单页超时 15s + 重试 1 次;429 不重试并**把并发降到 2**;
10
+ * * 每页只回标题 / 正文 / 图片 / 结构信号,整页 HTML 在链内就丢掉了。
11
+ * 模型只该花在两处:**批量抽取**(10–20 页/次)和**失败页托底**(每批 ≤20 页)。
12
+ *
13
+ * ## 它不吃谁的钱
14
+ * 这条命令**一次模型调用都没有**(结果里 `stats.modelCalls === 0`)。
15
+ * 要写进 CMS 请走 `wkgeo import` / `wkgeo import-v2`(那条链才有三档容错与 AI 托底)。
16
+ *
17
+ * ## 位置
18
+ * 抓取器源码在仓库里:`aliyun/fc/wkgeo-site-builder/fn/src/crawler/index.mjs`
19
+ * (云函数打包是平铺的,所以真正的实现在 `fn/src/crawl-site.mjs` + `fn/src/crawl-http.mjs`)。
20
+ * 从 npm 装的 CLI 里没有这份源码 —— 那时会直接说"没有本地抓取器",而不是给一个看不懂的报错。
21
+ */
22
+
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+ import { fileURLToPath, pathToFileURL } from 'node:url';
26
+
27
+ import { CliError, UsageError } from '../errors.mjs';
28
+
29
+ /** 仓库内抓取器的相对位置(相对本文件:cli/lib/commands/ → 仓库根) */
30
+ const CRAWLER_RELATIVE = ['aliyun', 'fc', 'wkgeo-site-builder', 'fn', 'src', 'crawler', 'index.mjs'];
31
+
32
+ function filePathFromUrl(url) {
33
+ try {
34
+ return fileURLToPath(url);
35
+ } catch {
36
+ return '';
37
+ }
38
+ }
39
+
40
+ /**
41
+ * 找抓取器模块。
42
+ * 1. `WKONGAI_CRAWL_MODULE` 显式指定(给了但不存在 ⇒ **明确报错,不回落**);
43
+ * 2. 本文件相对位置(仓库内正常用法);
44
+ * 3. 当前工作目录下同一条相对路径(在仓库任意子目录里跑也能找到)。
45
+ */
46
+ export function resolveCrawlerModule({ env = process.env, cwd = process.cwd(), moduleUrl = import.meta.url } = {}) {
47
+ const explicit = String((env && env.WKONGAI_CRAWL_MODULE) || '').trim();
48
+ if (explicit) {
49
+ const abs = path.resolve(cwd, explicit);
50
+ if (fs.existsSync(abs)) return { module: abs, source: 'env' };
51
+ return {
52
+ module: '',
53
+ source: '',
54
+ error: {
55
+ kind: 'crawler_missing',
56
+ message: `WKONGAI_CRAWL_MODULE 指向的抓取器不存在:${abs}`,
57
+ hint: '去掉这个环境变量(用仓库内置的那份),或把路径改成 …/fn/src/crawler/index.mjs 的绝对路径。',
58
+ },
59
+ };
60
+ }
61
+
62
+ const inRepo = filePathFromUrl(new URL(`../../../${CRAWLER_RELATIVE.join('/')}`, moduleUrl));
63
+ if (inRepo && fs.existsSync(inRepo)) return { module: inRepo, source: 'repo' };
64
+
65
+ const fromCwd = path.resolve(cwd, ...CRAWLER_RELATIVE);
66
+ if (fs.existsSync(fromCwd)) return { module: fromCwd, source: 'cwd' };
67
+
68
+ return {
69
+ module: '',
70
+ source: '',
71
+ error: {
72
+ kind: 'crawler_missing',
73
+ message: '没有本地抓取器:这个 CLI 是 npm 包里装的,仓库源码(fn/src/crawler/)不在包内。',
74
+ hint:
75
+ '两条路:① 在 wkgeo 仓库根目录下运行(抓取器随源码走);' +
76
+ '② 用 WKONGAI_CRAWL_MODULE=<仓库>/aliyun/fc/wkgeo-site-builder/fn/src/crawler/index.mjs 指过去。',
77
+ },
78
+ };
79
+ }
80
+
81
+ function intFlag(value, fallback, { min, max, name }) {
82
+ if (value === undefined || value === null || value === '') return fallback;
83
+ const n = Number(value);
84
+ if (!Number.isFinite(n)) throw new UsageError(`--${name} 要一个数字,收到:${value}`);
85
+ if (n < min || n > max) throw new UsageError(`--${name} 取值 ${min}..${max},收到:${n}`);
86
+ return Math.trunc(n);
87
+ }
88
+
89
+ export const crawlCommand = {
90
+ name: 'crawl',
91
+ summary: '并发抓整站(确定性爬虫、零模型调用):只出结构化摘要与正文,不回传整页 HTML',
92
+ usage:
93
+ 'wkgeo crawl <url> [--max-pages=150] [--concurrency=6] [--page-timeout=15000]\n' +
94
+ ' [--min-interval=150] [--no-robots] [--out <json>] [--json]',
95
+ args: [{ name: 'url', required: true, desc: '入口地址(http/https,同源 BFS 从这里开始)' }],
96
+ flags: {
97
+ 'max-pages': { type: 'string', desc: '最多抓多少页(默认 150)' },
98
+ concurrency: { type: 'string', desc: '并发数(默认 6,上限 10;命中 429 自动降到 2)' },
99
+ 'page-timeout': { type: 'string', desc: '单页超时毫秒(默认 15000;最小 1000)。注意不是全局的 --timeout(那个是登录回调超时)' },
100
+ 'min-interval': { type: 'string', desc: '同 host 最小间隔毫秒(默认 150;robots 的 Crawl-delay 更大时以它为准)' },
101
+ 'no-robots': { type: 'boolean', desc: '不读 robots.txt(只在自己站点上用;默认遵从)' },
102
+ out: { type: 'string', desc: '把完整结果(summary,不含 HTML)写成 JSON 文件' },
103
+ 'allow-private': { type: 'boolean', hidden: true, desc: '放开内网地址闸门(只给离线夹具用,别对真站用)' },
104
+ },
105
+ examples: [
106
+ 'wkgeo crawl https://old-site.com --json # 抓完直接吐结构化结果(不含 HTML)',
107
+ 'wkgeo crawl https://old-site.com --max-pages 60 --out .tmp-build/crawl.json',
108
+ 'wkgeo crawl https://old-site.com --concurrency 4 --page-timeout 20000 --min-interval 300',
109
+ ],
110
+ notes: [
111
+ '**零模型调用**:这条命令只抓 + 抽正文,`stats.modelCalls` 恒为 0;要写进 CMS 请走 `wkgeo import` / `wkgeo import-v2`(那条链才有三档容错与 AI 托底)。',
112
+ '礼貌默认值:同 host 间隔 ≥150ms、单页超时 15s、失败重试 1 次、429 不重试并降并发到 2、robots 的 `Disallow` 不抓(记进 failures)。',
113
+ '只支持**企业展示站**:政府 / 教育 / 军队 / 协会类域名,以及黑名单站点与内网地址会被直接拒(合规闸门 `crawl-gate.mjs`)。',
114
+ '返回体里**没有整页 HTML**(`html` / `bodyHtml` 都不在):抓取器在链路内就丢掉它,只留标题 / 正文 / 图片 / 结构信号。',
115
+ ],
116
+ async run(ctx) {
117
+ const { out, flags, positional } = ctx;
118
+
119
+ const url = String((positional && positional.url) || '').trim();
120
+ if (!/^https?:\/\//i.test(url)) {
121
+ throw new UsageError(`<url> 要以 http:// 或 https:// 开头,收到:${url || '(空)'}`);
122
+ }
123
+
124
+ const maxPages = intFlag(flags.maxPages, 150, { min: 1, max: 2000, name: 'max-pages' });
125
+ const concurrency = intFlag(flags.concurrency, 6, { min: 1, max: 10, name: 'concurrency' });
126
+ const timeoutMs = intFlag(flags.pageTimeout, 15000, { min: 1000, max: 120000, name: 'page-timeout' });
127
+ const minHostIntervalMs = intFlag(flags.minInterval, 150, { min: 0, max: 10000, name: 'min-interval' });
128
+
129
+ const resolved = resolveCrawlerModule({ env: ctx.env, cwd: process.cwd() });
130
+ if (resolved.error) {
131
+ throw new CliError(resolved.error.message, { kind: resolved.error.kind, hint: resolved.error.hint });
132
+ }
133
+
134
+ let crawler;
135
+ try {
136
+ crawler = await import(pathToFileURL(resolved.module).href);
137
+ } catch (e) {
138
+ throw new CliError(`抓取器加载失败:${(e && e.message) || e}`, {
139
+ kind: 'crawler_load_failed',
140
+ hint: '确认这份源码没被改坏:`node -e "import(\'…/fn/src/crawler/index.mjs\').then(m=>console.log(Object.keys(m)))"`。',
141
+ });
142
+ }
143
+ if (typeof crawler.crawlSite !== 'function') {
144
+ throw new CliError('抓取器没有导出 crawlSite(),源码不完整或版本不匹配', { kind: 'crawler_bad_export' });
145
+ }
146
+
147
+ if (!out.json) {
148
+ out.head('并发抓整站(确定性爬虫,零模型调用)');
149
+ out.line(` 入口:${url}`);
150
+ out.line(` 上限:${maxPages} 页 · 并发 ${concurrency} · 单页超时 ${timeoutMs}ms · 同 host 间隔 ≥${minHostIntervalMs}ms`);
151
+ out.line(` 抓取器:${resolved.module}`);
152
+ out.line('');
153
+ }
154
+
155
+ let result;
156
+ try {
157
+ result = await crawler.crawlSite({
158
+ entryUrl: url,
159
+ maxPages,
160
+ concurrency,
161
+ timeoutMs,
162
+ minHostIntervalMs,
163
+ respectRobots: flags.noRobots !== true,
164
+ allowPrivateHosts: flags.allowPrivate === true,
165
+ onProgress: out.json
166
+ ? null
167
+ : (ev) => {
168
+ if (ev.phase === 'page') out.line(` ${ev.ok ? '·' : '✗'} ${ev.done}/${ev.total} ${ev.url}`);
169
+ },
170
+ });
171
+ } catch (e) {
172
+ throw new CliError(`抓取失败:${(e && e.message) || e}`, {
173
+ kind: 'crawl_failed',
174
+ code: (e && e.code) || undefined,
175
+ hint:
176
+ '常见原因:网址打不开 / 被合规闸门拒(政府·教育·协会·内网)/ 目标站全站禁抓(robots)。' +
177
+ '先 `--max-pages 3` 试抓首页定位。',
178
+ });
179
+ }
180
+
181
+ const data = {
182
+ url,
183
+ entry: result.entry,
184
+ stats: result.stats,
185
+ pages: result.pages,
186
+ failures: result.failures,
187
+ crawler_module: resolved.module,
188
+ };
189
+
190
+ const outFile = String(flags.out || '').trim();
191
+ if (outFile) {
192
+ const abs = path.resolve(process.cwd(), outFile);
193
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
194
+ fs.writeFileSync(abs, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
195
+ data.out_file = abs;
196
+ }
197
+
198
+ if (!out.json) {
199
+ const s = result.stats;
200
+ out.line('');
201
+ out.ok(`抓完 ${s.pagesFetched} 页,失败 ${s.pagesFailed} 项,用时 ${(s.durationMs / 1000).toFixed(1)}s(${s.pagesPerSecond} 页/秒)`);
202
+ out.line(` 并发:起始 ${s.concurrencyStart} → 结束 ${s.concurrencyFinal}(峰值 ${s.concurrencyPeak})${s.throttled ? ' · 目标站限流过,已降并发' : ''}`);
203
+ out.line(` 跳过:重复 ${s.skippedDuplicate} · 外站 ${s.skippedExternal} · 非页面扩展名 ${s.skippedExtension} · 超深 ${s.skippedDepth}`);
204
+ out.line(` robots:${s.robots.ok ? `已读(禁抓 ${s.robots.blocked} 条)` : '未取到,按未禁止处理'} · 同 host 间隔 ${s.minIntervalMs}ms`);
205
+ if (result.failures.length) {
206
+ out.line('');
207
+ out.warn(` 失败 ${result.failures.length} 项(前 10 条):`);
208
+ for (const f of result.failures.slice(0, 10)) {
209
+ out.line(` - ${f.url}(${f.kind}${f.httpStatus ? ` ${f.httpStatus}` : ''}):${String(f.reason).slice(0, 80)}`);
210
+ }
211
+ }
212
+ if (outFile) out.info(` 结果已写入:${data.out_file}`);
213
+ out.info(' 下一步:要写进 CMS 就走 `wkgeo import` / `wkgeo import-v2`(那条链才有三档容错与 AI 托底)。');
214
+ } else {
215
+ ctx.done(data);
216
+ }
217
+ return data;
218
+ },
219
+ };