@wkgeo/cli 0.0.0-stage → 1.0.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +208 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1042 -3
  4. package/SKILL.md +927 -0
  5. package/lib/ai/client.mjs +161 -0
  6. package/lib/ai/config.mjs +221 -0
  7. package/lib/ai/context.mjs +468 -0
  8. package/lib/ai/log.mjs +53 -0
  9. package/lib/api.mjs +339 -0
  10. package/lib/args.mjs +235 -0
  11. package/lib/cli.mjs +168 -0
  12. package/lib/cms.mjs +330 -0
  13. package/lib/commands/ai.mjs +392 -0
  14. package/lib/commands/apps.mjs +116 -0
  15. package/lib/commands/auth.mjs +1288 -0
  16. package/lib/commands/billing.mjs +666 -0
  17. package/lib/commands/cms.mjs +2533 -0
  18. package/lib/commands/config-auth.mjs +621 -0
  19. package/lib/commands/config.mjs +434 -0
  20. package/lib/commands/dnscred.mjs +428 -0
  21. package/lib/commands/domainops.mjs +546 -0
  22. package/lib/commands/domainorder.mjs +439 -0
  23. package/lib/commands/import.mjs +164 -0
  24. package/lib/commands/index.mjs +528 -0
  25. package/lib/commands/logs.mjs +141 -0
  26. package/lib/commands/orders.mjs +444 -0
  27. package/lib/commands/overview.mjs +394 -0
  28. package/lib/commands/plugins.mjs +678 -0
  29. package/lib/commands/site.mjs +435 -0
  30. package/lib/commands/siteops.mjs +1012 -0
  31. package/lib/commands/sites.mjs +905 -0
  32. package/lib/commands/skill.mjs +119 -0
  33. package/lib/config.mjs +351 -0
  34. package/lib/credentials.mjs +160 -0
  35. package/lib/device-store.mjs +132 -0
  36. package/lib/device.mjs +464 -0
  37. package/lib/errors.mjs +299 -0
  38. package/lib/format.mjs +339 -0
  39. package/lib/http.mjs +71 -0
  40. package/lib/index.mjs +44 -0
  41. package/lib/local-import.mjs +185 -0
  42. package/lib/login.mjs +1638 -0
  43. package/lib/oauth-urls.mjs +163 -0
  44. package/lib/page.mjs +393 -0
  45. package/lib/pkce.mjs +48 -0
  46. package/lib/proxy.mjs +454 -0
  47. package/lib/qr.mjs +31 -0
  48. package/lib/runtime.mjs +650 -0
  49. package/lib/site-state.mjs +137 -0
  50. package/package.json +53 -4
  51. package/wkgeo.mjs +17 -0
package/lib/http.mjs ADDED
@@ -0,0 +1,71 @@
1
+ /**
2
+ * HTTP 薄封装:超时、JSON、错误不吞。
3
+ *
4
+ * 为什么不用 axios/got/node-fetch:
5
+ * 1. 老板明确要"尽量零第三方依赖"(npx 一行就能跑、审计面小、不怕供应链)。
6
+ * 2. Node 18+ 自带 fetch,够用。
7
+ *
8
+ * 为什么返回 `{status:0, networkError}` 而不是直接 throw:
9
+ * 调用方需要**保留原始 message**(DNS 失败?TLS 失败?超时?),
10
+ * 而这些信息只有 catch 里才有。统一在这里收口,上层就不会写出"失败了"这种吞错误的代码。
11
+ */
12
+
13
+ export const DEFAULT_TIMEOUT_MS = 30000;
14
+
15
+ /**
16
+ * @returns {Promise<{status:number, headers:any, text:string, body:any, parseError:string|null, networkError?:string, cause?:any}>}
17
+ */
18
+ export async function request(url, options = {}) {
19
+ const {
20
+ method = 'GET',
21
+ headers = {},
22
+ body,
23
+ timeoutMs = DEFAULT_TIMEOUT_MS,
24
+ fetchImpl = globalThis.fetch,
25
+ redirect = 'follow',
26
+ } = options;
27
+
28
+ if (typeof fetchImpl !== 'function') {
29
+ return { status: 0, headers: null, text: '', body: null, parseError: null, networkError: '当前 Node 没有可用的 fetch(需要 Node 18+)' };
30
+ }
31
+
32
+ const controller = new AbortController();
33
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
34
+ try {
35
+ const res = await fetchImpl(url, { method, headers, body, signal: controller.signal, redirect });
36
+ const text = await res.text();
37
+ let parsed = null;
38
+ let parseError = null;
39
+ if (text) {
40
+ try {
41
+ parsed = JSON.parse(text);
42
+ } catch (e) {
43
+ parseError = e.message;
44
+ }
45
+ }
46
+ return { status: res.status, headers: res.headers, text, body: parsed, parseError };
47
+ } catch (e) {
48
+ const aborted = e && (e.name === 'AbortError' || /aborted/i.test(String(e.message)));
49
+ return {
50
+ status: 0,
51
+ headers: null,
52
+ text: '',
53
+ body: null,
54
+ parseError: null,
55
+ networkError: aborted ? `请求超时(${timeoutMs}ms 内没有响应)` : (e && e.message) || String(e),
56
+ cause: e,
57
+ };
58
+ } finally {
59
+ clearTimeout(timer);
60
+ }
61
+ }
62
+
63
+ /** form-urlencoded 编码(OAuth 的 token/revoke/introspect 三个端点都用它) */
64
+ export function encodeForm(obj) {
65
+ const usp = new URLSearchParams();
66
+ for (const [k, v] of Object.entries(obj || {})) {
67
+ if (v === undefined || v === null) continue;
68
+ usp.append(k, String(v));
69
+ }
70
+ return usp.toString();
71
+ }
package/lib/index.mjs ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * 库入口(给"想在 Node 里直接调"的用法,比如我们自己的 AI 端把 CLI 当函数用)。
3
+ *
4
+ * ⚠️ 这里导出的东西**都不打印令牌**;`login()` 返回的对象里含 access_token,
5
+ * 调用方自己要负责不要把它打到日志里(CLI 内部就是这么做的)。
6
+ */
7
+
8
+ export { run } from './cli.mjs';
9
+ export { createRuntime, createOutput, okEnvelope, errorEnvelope } from './runtime.mjs';
10
+ export { createApi } from './api.mjs';
11
+ /** CMS 面(栏目 / 内容 / 素材 / 模板)的客户端与"直传 OSS"那一步 */
12
+ export { createCms, uploadToOss, CMS_ACTIONS } from './cms.mjs';
13
+ /** 本地"当前站点"(`wkgeo site use` 写的 `~/.wkongai/config.json`) */
14
+ export { readSiteState, writeSiteState, clearSiteState } from './site-state.mjs';
15
+ export {
16
+ runLogin,
17
+ openInBrowser,
18
+ defaultOpenBrowser,
19
+ defaultOpenBrowserAsync,
20
+ openInBrowserWithFallback,
21
+ /** 「把网址交给用户浏览器」的唯一入口(login / 钱包充值共用) */
22
+ openUrlForUser,
23
+ } from './login.mjs';
24
+ export { COMMANDS, renderHelp } from './commands/index.mjs';
25
+ export {
26
+ resolveConfig,
27
+ stripTrailingSlash,
28
+ withTrailingSlash,
29
+ parseDurationMs,
30
+ DEFAULT_BASE,
31
+ DEFAULT_CMS_BASE,
32
+ DEFAULT_CLIENT_ID,
33
+ DEFAULT_SCOPE,
34
+ } from './config.mjs';
35
+ export {
36
+ readCredentials,
37
+ writeCredentials,
38
+ deleteCredentials,
39
+ credentialsFromToken,
40
+ checkFileMode,
41
+ } from './credentials.mjs';
42
+ export { classifyResponse, CliError, UsageError, EXIT } from './errors.mjs';
43
+ export { createVerifier, challengeOf, createState } from './pkce.mjs';
44
+ export { maskToken, redact, formatMoney, renderTable } from './format.mjs';
@@ -0,0 +1,185 @@
1
+ /**
2
+ * 「老站导入」的本机脚本发现与参数拼装。
3
+ *
4
+ * ## 为什么 CLI 不自己抓站、不自己写库
5
+ * 抓取 / URL 层级 → 栏目树 / 正文白名单 / 幂等键这套逻辑已经有**能跑的实现**:
6
+ * `tencent/cloudbase/import-site.mjs`(21 项单测、默认 dry-run)。CLI 再写一套 = 两份行为会漂。
7
+ *
8
+ * ## 但也**不能**让 CLI 直接持有数据库凭证
9
+ * 那个脚本走 `service_role` 直连 PG(服务端密钥在 `tencent/cloudbase/.env` 里,CLI 不读它),
10
+ * 与"桌面/CLI 永远拿不到 AK"是同一条边界。所以这里的定位是明确的:
11
+ * **它是运维/管理员在本机跑的一个包装**,不是给客户用的导入通道 ——
12
+ * 带鉴权的 HTTP 导入入口还在后端待办(见 docs/规划-CLI与AI建站.md §5.2)。
13
+ * ⇒ 命令本身不碰数据库,只负责"找脚本 + 拼参数 + 起子进程 + 如实转述退出码"。
14
+ *
15
+ * ## 为什么要单独一个文件
16
+ * "脚本在哪"和"参数怎么拼"都是**纯函数**,可以在单测里把这两个容易写歪的地方钉住
17
+ * (拼错一个 `--site` 就等于把内容导进别的站)。
18
+ */
19
+
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import { spawnSync } from 'node:child_process';
23
+
24
+ /** 脚本相对仓库根的位置(本文件在 `cli/lib/`,往上两级就是仓库根) */
25
+ const SCRIPT_RELATIVE = ['tencent', 'cloudbase', 'import-site.mjs'];
26
+
27
+ /** 只看普通文件(避免把目录 / 断链当成脚本) */
28
+ function isFile(p) {
29
+ try {
30
+ return fs.statSync(p).isFile();
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * 找本机的导入脚本(**只看约定位置**;显式配置由 `resolveImportScript` 处理)。
38
+ *
39
+ * 顺序(命中即返回):
40
+ * 1. **包内相对路径** `../../tencent/cloudbase/import-site.mjs`(在本仓库里跑 `node cli/wkgeo.mjs` 时命中);
41
+ * 2. `cwd/tencent/cloudbase/import-site.mjs`;
42
+ * 3. `cwd/import-site.mjs`(把脚本单独拷到当前目录的场景)。
43
+ *
44
+ * ⚠️ 刻意**不**在 npm 安装目录里到处找:npx 装的包里没有这个脚本(也不该有,
45
+ * `package.json` 的 `files` 只带 `wkgeo.mjs` / `lib` / 文档),找不到时给的是
46
+ * "请在有本仓库的机器上运行",而不是让用户对着 ENOENT 发呆。
47
+ *
48
+ * @returns {string} 绝对路径;找不到返回 `''`
49
+ */
50
+ export function findImportScript({ cwd = process.cwd(), moduleUrl = import.meta.url } = {}) {
51
+ const candidates = [];
52
+ try {
53
+ /** `cli/lib/local-import.mjs` → `../../tencent/cloudbase/import-site.mjs` = 仓库根下的同目录 */
54
+ candidates.push(filePathFromUrl(new URL(`../../${SCRIPT_RELATIVE.join('/')}`, moduleUrl)));
55
+ } catch {
56
+ /* moduleUrl 不是合法 URL(测试里传了怪值):跳过这一项 */
57
+ }
58
+ candidates.push(path.join(cwd, ...SCRIPT_RELATIVE));
59
+ candidates.push(path.join(cwd, SCRIPT_RELATIVE[SCRIPT_RELATIVE.length - 1]));
60
+
61
+ for (const one of candidates) {
62
+ if (one && isFile(one)) return one;
63
+ }
64
+ return '';
65
+ }
66
+
67
+ /** file: URL → 本地路径(Windows 上要还原成 `F:\…` 这种形态) */
68
+ function filePathFromUrl(url) {
69
+ const href = String(url && url.href ? url.href : url);
70
+ return decodeURIComponent(href.replace(/^file:\/\//i, '').replace(/^\/([A-Za-z]:)/, '$1'));
71
+ }
72
+
73
+ /**
74
+ * 命令层用的"解析脚本"入口 —— 与 `findImportScript` 的区别是**严格对待显式配置**。
75
+ *
76
+ * ⚠️ 为什么必须严格:`WKONGAI_IMPORT_SCRIPT` 是用户**明确指定**的脚本。
77
+ * 如果它写错了却悄悄回落到仓库里的默认脚本,用户会以为跑的是他指定的那份
78
+ * (参数/分支可能完全不一样)—— 这种"看起来成功"的错最难查。
79
+ * ⇒ 显式给了但不存在:直接报错,不回落。
80
+ *
81
+ * @returns {{script:string, error:null|{kind:string, message:string, hint:string}}}
82
+ */
83
+ export function resolveImportScript({ env = {}, cwd = process.cwd(), moduleUrl = import.meta.url } = {}) {
84
+ const explicit = String((env && env.WKONGAI_IMPORT_SCRIPT) || '').trim();
85
+ if (explicit) {
86
+ const abs = path.resolve(cwd, explicit);
87
+ if (!isFile(abs)) {
88
+ return {
89
+ script: '',
90
+ error: {
91
+ kind: 'import_unavailable',
92
+ message: `指定的导入脚本不存在:${explicit}`,
93
+ hint: 'WKONGAI_IMPORT_SCRIPT 要指向一个真实存在的 `import-site.mjs`(用绝对路径最稳)。',
94
+ },
95
+ };
96
+ }
97
+ return { script: abs, error: null };
98
+ }
99
+ const script = findImportScript({ cwd, moduleUrl });
100
+ if (!script) {
101
+ return {
102
+ script: '',
103
+ error: {
104
+ kind: 'import_unavailable',
105
+ message: '没有找到本地导入器(tencent/cloudbase/import-site.mjs)',
106
+ hint:
107
+ '`import` 目前只有"本机运维脚本"这一条路(service_role 直连数据库,需要运维权限);' +
108
+ '带鉴权的 HTTP 导入入口后端还没做。请在有本仓库的机器上运行,' +
109
+ '或用环境变量 WKONGAI_IMPORT_SCRIPT 指定脚本路径。',
110
+ },
111
+ };
112
+ }
113
+ return { script, error: null };
114
+ }
115
+
116
+ /**
117
+ * 拼传给 `import-site.mjs` 的参数(**只拼它认识的**:它遇到未知参数会直接报错)。
118
+ *
119
+ * @param {object} opts
120
+ * @param {string} opts.url 老站首页(必填)
121
+ * @param {string} opts.site 目标站(站点 ID / 域名 / 临时域名 / 站点名)
122
+ * @param {boolean} [opts.apply] true = 真写库;false/undefined = dry-run(脚本默认就是 dry-run)
123
+ * @param {string} [opts.status] `draft`(默认)/ `published`
124
+ * @param {string} [opts.out] 中间 JSON 落盘路径
125
+ * @param {number|string} [opts.maxPages]
126
+ * @param {number|string} [opts.delay] 每页间隔毫秒
127
+ * @param {string} [opts.include] 只抓匹配这个正则的路径
128
+ * @param {string} [opts.exclude] 跳过匹配这个正则的路径
129
+ * @param {boolean} [opts.overwrite] 已存在的同名内容也覆盖正文
130
+ * @param {boolean} [opts.noProbe] 不去探测(脚本的 `--no-probe`)
131
+ * @returns {string[]}
132
+ */
133
+ export function buildImportArgs(opts = {}) {
134
+ const args = [];
135
+ const url = String(opts.url || '').trim();
136
+ if (!url) throw new Error('缺少 --url');
137
+ args.push(`--url=${url}`);
138
+
139
+ const site = String(opts.site || '').trim();
140
+ if (site) args.push(`--site=${site}`);
141
+
142
+ /** 默认 dry-run:只有显式 apply 才写库(脚本自己也是这个口径,这里不重复给 --dry-run 也行) */
143
+ if (opts.apply === true) args.push('--apply');
144
+
145
+ if (opts.status !== undefined && opts.status !== '') args.push(`--status=${String(opts.status)}`);
146
+ if (opts.out !== undefined && opts.out !== '') args.push(`--out=${String(opts.out)}`);
147
+ if (opts.maxPages !== undefined && opts.maxPages !== '') args.push(`--max-pages=${String(opts.maxPages)}`);
148
+ if (opts.delay !== undefined && opts.delay !== '') args.push(`--delay=${String(opts.delay)}`);
149
+ if (opts.include !== undefined && opts.include !== '') args.push(`--include=${String(opts.include)}`);
150
+ if (opts.exclude !== undefined && opts.exclude !== '') args.push(`--exclude=${String(opts.exclude)}`);
151
+ if (opts.overwrite === true) args.push('--overwrite');
152
+ if (opts.noProbe === true) args.push('--no-probe');
153
+ return args;
154
+ }
155
+
156
+ /**
157
+ * 起子进程跑脚本(**默认实现**;单测通过 `runtime.runScript` 注入替身)。
158
+ *
159
+ * 为什么默认 `spawnSync` 而不是异步 `spawn`:
160
+ * 导入是一个"长时间、人盯着看进度"的动作,同步阻塞反而最简单(stdio 直通终端,
161
+ * Ctrl+C 就是 Ctrl+C)。JSON 模式下 stdout/stderr 改走管道,由调用方收进信封。
162
+ */
163
+ export function runNodeCommand(command, args, options = {}) {
164
+ const res = spawnSync(command, args, {
165
+ encoding: 'utf8',
166
+ maxBuffer: 64 * 1024 * 1024,
167
+ ...options,
168
+ });
169
+ if (res && res.error) {
170
+ return { status: 1, stdout: String(res.stdout || ''), stderr: String(res.stderr || res.error.message || ''), error: res.error };
171
+ }
172
+ return {
173
+ status: typeof res.status === 'number' ? res.status : 1,
174
+ stdout: String(res.stdout || ''),
175
+ stderr: String(res.stderr || ''),
176
+ error: null,
177
+ };
178
+ }
179
+
180
+ /** 取日志尾巴(JSON 信封里不带整份日志,只带最后一段足够定位问题的) */
181
+ export function tailText(text, maxChars = 4000) {
182
+ const s = String(text || '');
183
+ if (s.length <= maxChars) return s;
184
+ return `…(前 ${s.length - maxChars} 字符省略)…\n${s.slice(-maxChars)}`;
185
+ }