@cnbcool/cnb-cli 1.1.1 → 1.2.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.
@@ -4,459 +4,37 @@
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.parseArguments = parseArguments;
8
- var _fs = _interopRequireDefault(require("fs"));
9
- var _path = _interopRequireDefault(require("path"));
10
- var _modules = require("./modules.help");
11
- var _tools = require("./tools.help");
12
- var _shortcuts = require("./shortcuts");
13
- var _upload = require("./utils/upload");
14
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
15
- const helpFileContent = _fs.default.readFileSync(_path.default.join(__dirname, 'help.json'), 'utf8');
16
- if (!helpFileContent) {
17
- console.error('help.json not found');
18
- process.exit(1);
19
- }
20
- const helpData = JSON.parse(helpFileContent);
21
-
22
- /**
23
- * 解析命令行参数
24
- * 支持:--key value, --key=value, -k value (短参数), 位置参数 (module, tool)
25
- * @returns 解析后的参数对象
26
- */
27
- function parseArguments() {
28
- const args = process.argv.slice(2);
29
- const result = {};
30
- let positionalCount = 0;
31
- let i = 0;
32
- while (i < args.length) {
33
- const arg = args[i];
34
- if (arg.startsWith('--')) {
35
- // --- 处理命名参数 (Options) ---
36
- const fullKey = arg.slice(2);
37
-
38
- // 支持 key=value 格式 (e.g., --config=file.json)
39
- if (fullKey.includes('=')) {
40
- const [key, ...valueParts] = fullKey.split('=');
41
- result[key] = valueParts.join('=');
42
- i++;
43
- continue;
44
- }
45
- const key = fullKey;
46
-
47
- // 检查下一个参数是否是值(不以 - 开头)
48
- const nextArg = args[i + 1];
49
- const isNextArgValue = i + 1 < args.length && !nextArg.startsWith('--') && !nextArg.startsWith('-');
50
- if (isNextArgValue) {
51
- result[key] = nextArg;
52
- i += 2;
53
- } else {
54
- // 没有值,视为布尔标志
55
- result[key] = true;
56
- i++;
57
- }
58
- } else if (arg.startsWith('-') && arg.length > 1 && !/^-?\d+$/.test(arg)) {
59
- // --- 处理短参数 (e.g., -h, -v),排除负数 ---
60
- const key = arg.slice(1);
61
- const nextArg = args[i + 1];
62
- const isNextArgValue = i + 1 < args.length && !nextArg.startsWith('--') && !nextArg.startsWith('-');
63
-
64
- // 只有单字符短参才吞并下一个值 (如 -o output.txt)
65
- if (isNextArgValue && key.length === 1) {
66
- result[key] = nextArg;
67
- i += 2;
68
- } else {
69
- result[key] = true;
70
- i++;
71
- }
72
- } else {
73
- // --- 处理位置参数 (Positional Args) ---
74
- if (positionalCount === 0) {
75
- result.module = arg;
76
- } else if (positionalCount === 1) {
77
- result.tool = arg;
78
- }
79
- positionalCount++;
80
- i++;
81
- }
82
- }
83
- return result;
84
- }
85
-
86
- /**
87
- * 验证必须参数是否存在
88
- * @param params 解析后的参数对象
89
- * @returns 验证结果
90
- */
91
- function validateRequiredParams(params) {
92
- if (!params.tool || params.help) {
93
- return false;
94
- }
95
- return true;
96
- }
97
-
98
- /**
99
- * 尝试解析JSON字符串
100
- * 先将真实控制字符转义为 JSON 合法形式,处理 shell/AI 传入的原始换行等情况
101
- * @param str 要解析的字符串
102
- * @returns 解析后的对象或原始字符串
103
- */
104
- function tryParseJSON(str) {
105
- if (typeof str !== 'string') return str;
106
- const escaped = str.replace(/[\x00-\x1F\x7F]/g, ch => {
107
- const map = {
108
- '\n': '\\n',
109
- '\r': '\\r',
110
- '\t': '\\t',
111
- '\b': '\\b',
112
- '\f': '\\f'
113
- };
114
- return map[ch] || '\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0');
115
- });
116
- try {
117
- return JSON.parse(escaped);
118
- } catch (error) {
119
- return str;
120
- }
121
- }
122
-
123
- /**
124
- * 尝试从文件引用或 stdin 读取内容(类似 curl 的 @file / @- 语法)
125
- */
126
- function tryReadFileRef(str) {
127
- if (typeof str !== 'string' || !str.startsWith('@')) return str;
128
- const ref = str.slice(1);
129
-
130
- // @- 表示从 stdin 读取
131
- if (ref === '-') {
132
- try {
133
- return _fs.default.readFileSync(0, 'utf8').trim();
134
- } catch (e) {
135
- console.error('从 stdin 读取失败:', e.message);
136
- return str;
137
- }
138
- }
139
-
140
- // @/path/to/file 表示从文件读取
141
- if (_fs.default.existsSync(ref)) {
142
- return _fs.default.readFileSync(ref, 'utf8').trim();
143
- }
144
- return str;
145
- }
146
-
147
- /**
148
- * 获取 tool 的参数定义(用于自动分发 --key value 到 path/query)
149
- */
150
- function getToolParamDefs(moduleName, toolName) {
151
- const toolHelp = helpData.modulesHelp?.[moduleName]?.[toolName];
152
- if (!toolHelp) return null;
153
- return toolHelp.help?.parameter || {};
154
- }
155
-
156
- /**
157
- * 格式化参数
158
- * 支持新的 --key value 扁平格式,同时向后兼容旧的 --path/--query JSON 格式。
159
- * 根据 help.json 中的参数定义,自动将扁平参数分发到 path 或 query。
160
- * @param params 原始参数对象
161
- * @returns 格式化后的参数对象,包含 module, tool, path, query, data 等
162
- */
163
- function formatParams(params) {
164
- const formatted = {
165
- module: params.module,
166
- tool: params.tool
167
- };
168
-
169
- // 保留控制标志
170
- if (params.help) formatted.help = true;
171
- if (params.short) formatted.short = true;
172
- if (params.verbose) formatted.verbose = true;
173
-
174
- // 旧格式兼容:--path / --query / --data 是 JSON 字符串
175
- if (typeof params.path === 'string') {
176
- formatted.path = tryParseJSON(tryReadFileRef(params.path));
177
- }
178
- if (typeof params.query === 'string') {
179
- formatted.query = tryParseJSON(tryReadFileRef(params.query));
180
- }
181
- if (typeof params.data === 'string') {
182
- formatted.data = tryParseJSON(tryReadFileRef(params.data));
183
- }
184
-
185
- // 新格式:将其他 --key value 根据 help.json 自动分发到 path/query
186
- const paramDefs = getToolParamDefs(params.module, params.tool);
187
- if (paramDefs) {
188
- const pathDef = paramDefs.path || {};
189
- const queryDef = paramDefs.query || {};
190
- const reservedKeys = new Set(['module', 'tool', 'help', 'short', 'verbose', 'path', 'query', 'data', 'h', 'v']);
191
- for (const [key, value] of Object.entries(params)) {
192
- if (reservedKeys.has(key)) continue;
193
- if (typeof value === 'boolean') continue;
194
- if (pathDef[key]) {
195
- // 归入 path
196
- if (!formatted.path) formatted.path = {};
197
- formatted.path[key] = value;
198
- } else if (queryDef[key]) {
199
- // 归入 query
200
- if (!formatted.query) formatted.query = {};
201
- // 自动转数字
202
- const paramType = queryDef[key].type;
203
- if (paramType === 'number' && typeof value === 'string' && !isNaN(Number(value))) {
204
- formatted.query[key] = Number(value);
205
- } else {
206
- formatted.query[key] = value;
207
- }
208
- } else {
209
- // 未知参数,尝试放入 query(兼容)
210
- if (!formatted.query) formatted.query = {};
211
- formatted.query[key] = typeof value === 'string' && !isNaN(Number(value)) ? Number(value) : value;
212
- }
213
- }
214
- }
215
-
216
- // 当没有传递 query 时,要判断当前 tool 是否支持 query
217
- if (formatted.query === undefined) {
218
- const paramDefs2 = getToolParamDefs(formatted.module, formatted.tool);
219
- if (paramDefs2?.query) {
220
- formatted.query = {};
221
- }
222
- }
223
- return formatted;
224
- }
225
-
226
- /**
227
- * 精简响应对象(非 verbose 模式使用)
228
- * - 去掉 trace(仅错误时保留)
229
- * - 去掉 header(原始 x-cnb-* 头)
230
- * - 仅列表 API 时保留分页信息
231
- */
232
- function compactResponse(response) {
233
- if (!response || typeof response !== 'object') return response;
234
- const compact = {
235
- status: response.status
236
- };
237
-
238
- // 仅错误时保留 trace
239
- if (response.status >= 300 && response.trace) {
240
- compact.trace = response.trace;
241
- }
242
-
243
- // 仅列表 API 时保留分页信息
244
- if (response.total != null) {
245
- compact.page = response.page;
246
- compact.pageSize = response.pageSize;
247
- compact.total = response.total;
248
- compact.totalPages = response.totalPages;
249
- }
250
- compact.data = response.data;
251
- return compact;
252
- }
253
-
254
- /**
255
- * 判断是否是标准响应结构(有 status + data 字段)
256
- * cag.config.js 中的 responseConverter 可能返回裸 data(不含 status),需要区分处理
257
- */
258
- function isStandardResponse(response) {
259
- return response && typeof response === 'object' && typeof response.status === 'number' && 'data' in response;
260
- }
261
-
262
- /**
263
- * 格式化 CLI 输出
264
- * - verbose 模式:完整 JSON(含 trace、header 等全部字段)
265
- * - 快捷命令默认:只输出核心摘要字段
266
- * - 非快捷命令默认:精简 JSON(去掉 trace、header,保留完整 data)
267
- * @param response 原始响应
268
- * @param verbose 是否 verbose 模式
269
- * @param summary 是否 summary 模式
270
- * @param toolKey 当前 tool 标识,格式为 "module/tool",用于匹配摘要配置
271
- */
272
- function formatOutput(response, verbose, summary, toolKey) {
273
- // --verbose 模式:输出完整原始信息
274
- if (verbose) {
275
- return JSON.stringify(response, null, 2);
7
+ Object.defineProperty(exports, "parseArguments", {
8
+ enumerable: true,
9
+ get: function () {
10
+ return _parsers.parseUnknownOptions;
276
11
  }
277
-
278
- // converter 可能返回裸 data(没有标准 {status, data} 结构),直接输出
279
- if (!isStandardResponse(response)) {
280
- if (summary) {
281
- const summarized = (0, _shortcuts.summarizeResponse)(response, toolKey);
282
- if (summarized !== null) {
283
- return JSON.stringify(summarized, null, 2);
284
- }
285
- }
286
- return JSON.stringify(response, null, 2);
287
- }
288
-
289
- // 精简响应
290
- const compact = compactResponse(response);
291
-
292
- // summary 模式:对特定 tool 应用摘要提取(仅成功响应)
293
- if (summary && compact.status >= 200 && compact.status < 300) {
294
- const summarized = (0, _shortcuts.summarizeResponse)(compact.data, toolKey);
295
- if (summarized !== null) {
296
- compact.data = summarized;
297
- }
298
- }
299
- return JSON.stringify(compact, null, 2);
300
- }
301
-
302
- /**
303
- * 显示帮助文档
304
- * - 无参数:显示顶层帮助(模块列表 + 参数说明 + 用法示例)
305
- * - 指定 module:显示模块帮助(工具列表)
306
- * - 指定 module + tool:显示工具帮助(参数详情 + 示例)
307
- */
308
- function showHelp(moduleName, tool) {
309
- if (moduleName && tool) {
310
- (0, _tools.showToolHelp)(helpData, moduleName, tool);
311
- } else if (moduleName) {
312
- (0, _modules.showModuleHelp)(helpData, moduleName);
313
- } else {
314
- const cliCmd = "cnb" || 'cnb';
315
-
316
- // 紧凑的模块列表
317
- const moduleParts = [];
318
- for (const [mod, count] of Object.entries(helpData.mainHelp)) {
319
- moduleParts.push(`${mod}(${count})`);
320
- }
321
-
322
- // 每行放几个模块
323
- const lines = [];
324
- let currentLine = ' ';
325
- for (const part of moduleParts) {
326
- if (currentLine.length + part.length > 78) {
327
- lines.push(currentLine);
328
- currentLine = ' ' + part + ' ';
329
- } else {
330
- currentLine += part + ' ';
331
- }
332
- }
333
- if (currentLine.trim()) lines.push(currentLine);
334
- const helpMsg = `
335
- CNB OpenAPI CLI
336
-
337
- 模块(tool数量):
338
- ${lines.join('\n')}
339
-
340
- 参数:
341
- <module> 模块名称 (如: issues, pulls, git)
342
- <tool> 工具名称 (如: list-issues, get-issue)
343
- --key value 路径或查询参数,CLI 自动识别归类
344
- --data 'JSON' 请求体参数,JSON 字符串
345
- --verbose 输出完整原始响应(含 trace、header 等全部字段)
346
- --help 显示帮助文档
347
- --short 显示当前仓库的快捷命令
348
-
349
- 用法: ${cliCmd} issues list-issues --repo my-org/my-repo --page 1 --pageSize 10
350
- ${cliCmd} issues create-issue --repo my-org/my-repo --data '{"title":"Bug"}'
351
- 帮助: ${cliCmd} <module> --help
352
- ${cliCmd} <module> <tool> --help
353
- 快捷: ${cliCmd} --short
354
- `;
355
- console.log(helpMsg);
356
- }
357
- }
358
-
359
- /**
360
- * 主函数
361
- */
362
- async function main() {
363
- const params = parseArguments();
364
-
365
- // 处理 --short
366
- if (params.short) {
367
- (0, _shortcuts.showShort)();
368
- process.exit(0);
369
- }
370
-
371
- // 尝试解析快捷命令
372
- const shortcut = (0, _shortcuts.resolveShortcut)(params.module, params.tool);
373
- if (shortcut) {
374
- params.module = shortcut.module;
375
- params.tool = shortcut.tool;
376
-
377
- // 自动注入 path 参数
378
- for (const [key, value] of Object.entries(shortcut.autoPath)) {
379
- if (!params[key]) {
380
- params[key] = value;
381
- }
382
- }
383
-
384
- // 自动注入 data 参数
385
- if (shortcut.autoData && !params.data) {
386
- params.data = JSON.stringify(shortcut.autoData);
387
- }
388
- }
389
-
390
- // 验证必须参数
391
- if (!validateRequiredParams(params)) {
392
- showHelp(params.module, params.tool);
393
- process.exit(0);
394
- }
395
-
396
- // 格式化参数
397
- const formattedParams = formatParams(params);
398
-
399
- // 参数预检:缺少必填 path 参数时自动输出 tool help
400
- const toolHelpData = helpData.modulesHelp?.[formattedParams.module]?.[formattedParams.tool];
401
- if (toolHelpData) {
402
- const pathDef = toolHelpData.help?.parameter?.path;
403
- if (pathDef) {
404
- const missingRequired = Object.entries(pathDef).filter(([, p]) => p.required && !formattedParams.path?.[p.name]).map(([k]) => `--${k}`);
405
- if (missingRequired.length > 0) {
406
- console.error(`缺少必填参数: ${missingRequired.join(', ')}\n`);
407
- (0, _tools.showToolHelp)(helpData, formattedParams.module, formattedParams.tool);
408
- process.exit(1);
409
- }
410
- }
411
- }
412
-
413
- // 动态引入模块
414
- const toolPath = _path.default.join(__dirname, '../modules', `${formattedParams.module}/${formattedParams.tool}.js`);
415
- if (!_fs.default.existsSync(toolPath)) {
416
- console.error(`工具文件不存在: ${toolPath}`);
417
- process.exit(1);
418
- }
419
- const toolModule = require(toolPath);
420
- const toolFunction = toolModule.default;
421
- if (!toolFunction) {
422
- console.error(`工具函数不存在`);
423
- process.exit(1);
424
- }
425
- const toolsParam = [];
426
- let pathAndQueryParams = null;
427
- if (formattedParams.path && Object.keys(formattedParams.path).length === 1 && !formattedParams.query) {
428
- pathAndQueryParams = formattedParams.path[Object.keys(formattedParams.path)[0]];
429
- } else {
430
- if (formattedParams.path) {
431
- pathAndQueryParams = {
432
- ...formattedParams.path
433
- };
434
- }
435
- if (formattedParams.query) {
436
- pathAndQueryParams = {
437
- ...(pathAndQueryParams && typeof pathAndQueryParams === 'object' ? pathAndQueryParams : {}),
438
- ...formattedParams.query
439
- };
440
- }
441
- }
442
- if (pathAndQueryParams) {
443
- toolsParam.push(pathAndQueryParams);
444
- }
445
-
446
- // 上传快捷命令:走完整上传流程(获取 URL → PUT 文件 → 返回结果)
447
- let data;
448
- if (shortcut?.upload) {
449
- data = await (0, _upload.handleUpload)(shortcut, formattedParams.data?.file, toolFunction, pathAndQueryParams);
450
- } else {
451
- if (formattedParams.data) {
452
- toolsParam.push(formattedParams.data);
453
- }
454
- data = await toolFunction(...toolsParam);
455
- }
456
- const toolKey = `${formattedParams.module}/${formattedParams.tool}`;
457
- // 快捷命令默认输出摘要,--verbose 时输出全部信息
458
- const isVerbose = !!formattedParams.verbose;
459
- const isSummary = shortcut ? !isVerbose : false;
460
- console.log(formatOutput(data, isVerbose, isSummary, toolKey));
461
- }
462
- main();
12
+ });
13
+ var _commander = require("commander");
14
+ var _extraHelp = require("./lib/extra-help");
15
+ var _registerModules = require("./lib/register-modules");
16
+ var _registerFallback = require("./lib/register-fallback");
17
+ var _parsers = require("./lib/parsers");
18
+ // ============================================================
19
+ // Commander 程序定义
20
+ // ============================================================
21
+
22
+ const program = new _commander.Command();
23
+ program.name("cnb" || 'cnb').description('CNB OpenAPI 命令行工具').allowUnknownOption().allowExcessArguments().helpOption('-h, --help', '显示帮助文档').option('-s, --short', '显示当前仓库的快捷命令').addHelpText('after', (0, _extraHelp.getExtraHelpText)());
24
+
25
+ // ============================================================
26
+ // 注册命令
27
+ // ============================================================
28
+
29
+ (0, _registerModules.registerModuleCommands)(program);
30
+ (0, _registerFallback.registerFallbackAction)(program);
31
+
32
+ // ============================================================
33
+ // 导出(保持兼容性)
34
+ // ============================================================
35
+
36
+ // ============================================================
37
+ // 启动
38
+ // ============================================================
39
+
40
+ program.parseAsync(process.argv);