@cnbcool/cnb-cli 1.0.7 → 1.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cnbcool/cnb-cli",
3
- "version": "1.0.7",
3
+ "version": "1.1.0",
4
4
  "description": "CNB OpenAPI 命令行工具,基于 CNB 平台 Swagger 自动生成,支持 Issues、PR、Git、组织管理等全部 API 操作",
5
5
  "main": "skills/cnb-api/scripts/core/index.js",
6
6
  "bin": {
@@ -34,7 +34,7 @@
34
34
  "author": "",
35
35
  "license": "MIT",
36
36
  "devDependencies": {
37
- "@cnbcool/cnb-api-generate": "^1.2.3",
37
+ "@cnbcool/cnb-api-generate": "^1.2.5",
38
38
  "skills": "^1.4.4"
39
39
  }
40
40
  }
@@ -10,6 +10,7 @@ var _path = _interopRequireDefault(require("path"));
10
10
  var _modules = require("./modules.help");
11
11
  var _tools = require("./tools.help");
12
12
  var _shortcuts = require("./shortcuts");
13
+ var _upload = require("./utils/upload");
13
14
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
14
15
  const helpFileContent = _fs.default.readFileSync(_path.default.join(__dirname, 'help.json'), 'utf8');
15
16
  if (!helpFileContent) {
@@ -169,7 +170,6 @@ function formatParams(params) {
169
170
  if (params.help) formatted.help = true;
170
171
  if (params.short) formatted.short = true;
171
172
  if (params.verbose) formatted.verbose = true;
172
- if (params.summary) formatted.summary = true;
173
173
 
174
174
  // 旧格式兼容:--path / --query / --data 是 JSON 字符串
175
175
  if (typeof params.path === 'string') {
@@ -187,7 +187,7 @@ function formatParams(params) {
187
187
  if (paramDefs) {
188
188
  const pathDef = paramDefs.path || {};
189
189
  const queryDef = paramDefs.query || {};
190
- const reservedKeys = new Set(['module', 'tool', 'help', 'short', 'verbose', 'summary', 'path', 'query', 'data', 'h', 'v']);
190
+ const reservedKeys = new Set(['module', 'tool', 'help', 'short', 'verbose', 'path', 'query', 'data', 'h', 'v']);
191
191
  for (const [key, value] of Object.entries(params)) {
192
192
  if (reservedKeys.has(key)) continue;
193
193
  if (typeof value === 'boolean') continue;
@@ -262,8 +262,8 @@ function isStandardResponse(response) {
262
262
  /**
263
263
  * 格式化 CLI 输出
264
264
  * - verbose 模式:完整 JSON(含 trace、header 等全部字段)
265
- * - summary 模式:只输出核心摘要字段(需要 --summary 显式指定)
266
- * - 默认:精简 JSON(去掉 trace、header,保留完整 data)
265
+ * - 快捷命令默认:只输出核心摘要字段
266
+ * - 非快捷命令默认:精简 JSON(去掉 trace、header,保留完整 data)
267
267
  * @param response 原始响应
268
268
  * @param verbose 是否 verbose 模式
269
269
  * @param summary 是否 summary 模式
@@ -289,7 +289,7 @@ function formatOutput(response, verbose, summary, toolKey) {
289
289
  // 精简响应
290
290
  const compact = compactResponse(response);
291
291
 
292
- // --summary 模式:对特定 tool 应用摘要提取(仅成功响应)
292
+ // summary 模式:对特定 tool 应用摘要提取(仅成功响应)
293
293
  if (summary && compact.status >= 200 && compact.status < 300) {
294
294
  const summarized = (0, _shortcuts.summarizeResponse)(compact.data, toolKey);
295
295
  if (summarized !== null) {
@@ -342,7 +342,7 @@ ${lines.join('\n')}
342
342
  <tool> 工具名称 (如: list-issues, get-issue)
343
343
  --key value 路径或查询参数,CLI 自动识别归类
344
344
  --data 'JSON' 请求体参数,JSON 字符串
345
- --verbose 输出完整响应(含 trace、header
345
+ --verbose 输出完整原始响应(含 trace、header 等全部字段)
346
346
  --help 显示帮助文档
347
347
  --short 显示当前仓库的快捷命令
348
348
 
@@ -371,24 +371,13 @@ async function main() {
371
371
  // 尝试解析快捷命令
372
372
  const shortcut = (0, _shortcuts.resolveShortcut)(params.module, params.tool);
373
373
  if (shortcut) {
374
+ params.module = shortcut.module;
374
375
  params.tool = shortcut.tool;
375
376
 
376
- // 自动注入 path 参数(兼容新旧格式)
377
- // 新格式:用户可能直接传了 --repo xxx,检查扁平参数是否已存在
378
- const autoPathKeys = Object.keys(shortcut.autoPath);
379
- const hasPathAlready = params.path || autoPathKeys.some(k => params[k]);
380
- if (!hasPathAlready) {
381
- if (autoPathKeys.length > 0) {
382
- // 新格式:直接注入为扁平参数
383
- for (const [key, value] of Object.entries(shortcut.autoPath)) {
384
- if (!params[key]) {
385
- params[key] = value;
386
- }
387
- }
388
- } else {
389
- const envHint = params.module === 'issues' ? 'CNB_REPO_SLUG 和 CNB_ISSUE_IID' : 'CNB_REPO_SLUG 和 CNB_PULL_REQUEST_IID';
390
- console.error(`快捷命令需要环境变量 ${envHint},或手动传参数。\n` + `提示:运行 ${"cnb" || 'cnb'} --short 查看快捷命令详情。`);
391
- process.exit(1);
377
+ // 自动注入 path 参数
378
+ for (const [key, value] of Object.entries(shortcut.autoPath)) {
379
+ if (!params[key]) {
380
+ params[key] = value;
392
381
  }
393
382
  }
394
383
 
@@ -453,11 +442,21 @@ async function main() {
453
442
  if (pathAndQueryParams) {
454
443
  toolsParam.push(pathAndQueryParams);
455
444
  }
456
- if (formattedParams.data) {
457
- toolsParam.push(formattedParams.data);
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);
458
455
  }
459
- const data = await toolFunction(...toolsParam);
460
456
  const toolKey = `${formattedParams.module}/${formattedParams.tool}`;
461
- console.log(formatOutput(data, !!formattedParams.verbose, !!formattedParams.summary, toolKey));
457
+ // 快捷命令默认输出摘要,--verbose 时输出全部信息
458
+ const isVerbose = !!formattedParams.verbose;
459
+ const isSummary = shortcut ? !isVerbose : false;
460
+ console.log(formatOutput(data, isVerbose, isSummary, toolKey));
462
461
  }
463
462
  main();
@@ -29,11 +29,18 @@ function showModuleHelp(helpData, moduleName) {
29
29
  process.exit(1);
30
30
  }
31
31
  const cliCmd = "cnb" || 'cnb';
32
+ const entries = Object.values(moduleHelpData).map(info => ({
33
+ name: info.filename,
34
+ summary: trimSummary(info.summary || '')
35
+ }));
36
+ const maxNameLen = Math.max(...entries.map(e => e.name.length));
37
+ const pad = maxNameLen + 2;
32
38
  let toolListMsg = '';
33
- for (const [, info] of Object.entries(moduleHelpData)) {
34
- const name = info.filename;
35
- const summary = info.summary;
36
- toolListMsg += ` ${name.padEnd(30)} ${summary}\n`;
39
+ for (const {
40
+ name,
41
+ summary
42
+ } of entries) {
43
+ toolListMsg += ` ${name.padEnd(pad)} ${summary}\n`;
37
44
  }
38
45
  const helpMsg = `
39
46
  ${moduleName} 模块
@@ -88,6 +88,18 @@ const ISSUE_SHORTCUTS = [{
88
88
  realTool: 'post-issue-assignees',
89
89
  description: '添加处理人',
90
90
  dataTip: "--data '{\"assignees\":[\"username\"]}'"
91
+ }, {
92
+ shortName: 'upload-file',
93
+ realTool: 'post-issue-file-asset-upload-url',
94
+ description: '上传文件',
95
+ upload: true,
96
+ dataTip: "--data '{\"file\":\"文件路径\"}'"
97
+ }, {
98
+ shortName: 'upload-image',
99
+ realTool: 'post-issue-image-asset-upload-url',
100
+ description: '上传图片',
101
+ upload: true,
102
+ dataTip: "--data '{\"file\":\"图片路径\"}'"
91
103
  }];
92
104
  const PR_SHORTCUTS = [{
93
105
  shortName: 'get',
@@ -131,16 +143,50 @@ const PR_SHORTCUTS = [{
131
143
  shortName: 'list-assignees',
132
144
  realTool: 'list-pull-assignees',
133
145
  description: '查看处理人'
146
+ }, {
147
+ shortName: 'upload-file',
148
+ realTool: 'upload-files',
149
+ description: '上传文件',
150
+ repoOnly: true,
151
+ upload: true,
152
+ dataTip: "--data '{\"file\":\"文件路径\"}'"
153
+ }, {
154
+ shortName: 'upload-image',
155
+ realTool: 'upload-imgs',
156
+ description: '上传图片',
157
+ repoOnly: true,
158
+ upload: true,
159
+ dataTip: "--data '{\"file\":\"图片路径\"}'"
134
160
  }];
135
161
 
136
162
  // ============================================================
137
163
  // --short 帮助输出
138
164
  // ============================================================
139
165
 
166
+ /** 计算字符串的显示宽度(中文/全角占2,英文/半角占1) */
167
+ function displayWidth(str) {
168
+ let width = 0;
169
+ for (const ch of str) {
170
+ const code = ch.codePointAt(0) || 0;
171
+ // CJK、全角字符占2宽度
172
+ width += code >= 0x1100 && (code <= 0x115f || code === 0x2329 || code === 0x232a || code >= 0x2e80 && code <= 0x3247 || code >= 0x3250 && code <= 0x4dbf || code >= 0x4e00 && code <= 0xa4c6 || code >= 0xa960 && code <= 0xa97c || code >= 0xac00 && code <= 0xd7a3 || code >= 0xf900 && code <= 0xfaff || code >= 0xfe10 && code <= 0xfe19 || code >= 0xfe30 && code <= 0xfe6b || code >= 0xff01 && code <= 0xff60 || code >= 0xffe0 && code <= 0xffe6 || code >= 0x1f000 && code <= 0x1fbff || code >= 0x20000 && code <= 0x2fffd || code >= 0x30000 && code <= 0x3fffd) ? 2 : 1;
173
+ }
174
+ return width;
175
+ }
176
+
177
+ /** 用全角空格将字符串补齐到指定显示宽度 */
178
+ function padToWidth(str, targetWidth) {
179
+ const diff = targetWidth - displayWidth(str);
180
+ if (diff <= 0) return str;
181
+ // 每个全角空格占2宽度
182
+ const fullSpaces = Math.floor(diff / 2);
183
+ const halfSpace = diff % 2 === 1 ? ' ' : '';
184
+ return str + ' '.repeat(fullSpaces) + halfSpace;
185
+ }
140
186
  function formatShortcutList(shortcuts, cliCmd, moduleName) {
141
- const maxDescLen = Math.max(...shortcuts.map(s => s.description.length));
187
+ const maxWidth = Math.max(...shortcuts.map(s => displayWidth(s.description)));
142
188
  return shortcuts.map(s => {
143
- const desc = s.description.padEnd(maxDescLen + 2, ' '); // 全角空格对齐
189
+ const desc = padToWidth(s.description, maxWidth + 2);
144
190
  const cmd = `${cliCmd} ${moduleName} ${s.shortName}`;
145
191
  const dataPart = s.dataTip ? ` ${s.dataTip}` : '';
146
192
  return ` ${desc} ${cmd}${dataPart}`;
@@ -150,52 +196,45 @@ function showShort() {
150
196
  const ctx = detectEventContext();
151
197
  const cliCmd = "cnb" || 'cnb';
152
198
  const repo = getRepo();
153
- if (ctx === 'issue') {
154
- const number = getIssueNumber();
155
- const list = formatShortcutList(ISSUE_SHORTCUTS, cliCmd, 'issues');
156
- console.log(`
157
- 📋 当前场景: Issue 事件 (Issue #${number})
158
- 仓库: ${repo}
159
-
160
- 常用快捷命令(path 参数已从环境变量自动获取):
161
- ${list}
162
-
163
- 提示: 以上命令自动使用环境变量 CNB_REPO_SLUG 和 CNB_ISSUE_IID,无需手动传 --path
164
- 添加 --summary 可只输出核心摘要字段
165
- `);
166
- } else if (ctx === 'pull_request') {
167
- const number = getPRNumber();
168
- const list = formatShortcutList(PR_SHORTCUTS, cliCmd, 'pulls');
199
+ if (ctx === 'issue' || ctx === 'pull_request') {
200
+ const isIssue = ctx === 'issue';
201
+ const number = isIssue ? getIssueNumber() : getPRNumber();
202
+ const emoji = isIssue ? '📋' : '🔀';
203
+ const label = isIssue ? 'Issue' : 'Pull Request';
204
+ const tag = isIssue ? 'Issue' : 'PR';
205
+ const moduleName = isIssue ? 'issues' : 'pulls';
206
+ const shortcuts = isIssue ? ISSUE_SHORTCUTS : PR_SHORTCUTS;
207
+ const envVars = isIssue ? 'CNB_REPO_SLUG 和 CNB_ISSUE_IID' : 'CNB_REPO_SLUG 和 CNB_PULL_REQUEST_IID';
208
+ const list = formatShortcutList(shortcuts, cliCmd, moduleName);
169
209
  console.log(`
170
- 🔀 当前场景: Pull Request 事件 (PR #${number})
210
+ ${emoji} 当前场景: ${label} 事件 (${tag} #${number})
171
211
  仓库: ${repo}
172
212
 
173
213
  常用快捷命令(path 参数已从环境变量自动获取):
174
214
  ${list}
175
215
 
176
- 提示: 以上命令自动使用环境变量 CNB_REPO_SLUG 和 CNB_PULL_REQUEST_IID,无需手动传 --path
177
- 添加 --summary 可只输出核心摘要字段
216
+ 提示: ${tag} 相关命令会自动使用 ${envVars}
217
+ 默认只输出摘要信息,添加 --verbose 可输出全部信息
178
218
  `);
179
219
  } else {
180
- // 未知上下文,两组都显示
181
220
  const issueList = formatShortcutList(ISSUE_SHORTCUTS, cliCmd, 'issues');
182
221
  const prList = formatShortcutList(PR_SHORTCUTS, cliCmd, 'pulls');
183
222
  console.log(`
184
223
  ⚠️ 未检测到 Issue/PR 事件上下文
185
224
  (CNB_ISSUE_IID 和 CNB_PULL_REQUEST_IID 均未设置)
186
225
 
187
- 📋 Issue 场景常用命令(需要设置 CNB_ISSUE_IID 环境变量):
226
+ 📋 Issue 场景常用命令:
188
227
  ${issueList}
189
228
 
190
- 🔀 PR 场景常用命令(需要设置 CNB_PULL_REQUEST_IID 环境变量):
229
+ 🔀 PR 场景常用命令:
191
230
  ${prList}
192
231
 
193
- 提示: 快捷命令需要以下环境变量:
232
+ 提示: 快捷命令可使用以下环境变量:
194
233
  CNB_REPO_SLUG - 仓库路径
195
- CNB_ISSUE_IID - Issue 编号 (Issue 事件)
196
- CNB_PULL_REQUEST_IID - PR 编号 (PR 事件)
234
+ CNB_ISSUE_IID - Issue 编号(Issue 相关快捷命令)
235
+ CNB_PULL_REQUEST_IID - PR 编号(PR 相关快捷命令)
197
236
 
198
- 添加 --summary 可只输出核心摘要字段
237
+ 默认只输出摘要信息,添加 --verbose 可输出全部信息
199
238
  `);
200
239
  }
201
240
  }
@@ -204,50 +243,35 @@ ${prList}
204
243
  // 快捷命令解析
205
244
  // ============================================================
206
245
 
246
+ function buildAutoPath(moduleName, repoOnly) {
247
+ const repo = process.env.CNB_REPO_SLUG || '';
248
+ if (repoOnly) return {
249
+ repo
250
+ };
251
+ const number = moduleName === 'issues' ? process.env.CNB_ISSUE_IID || '' : process.env.CNB_PULL_REQUEST_IID || '';
252
+ return {
253
+ repo,
254
+ number
255
+ };
256
+ }
257
+
207
258
  /**
208
259
  * 尝试将用户输入的 module + tool 解析为快捷命令
209
260
  *
210
- * 即使环境变量未设置,也会完成 shortName → realTool 的映射,
211
- * 只是 autoPath 为 null,调用方需要用户手动传 --path。
212
- *
213
261
  * @returns 解析结果,如果不是快捷命令则返回 null
214
262
  */
215
263
  function resolveShortcut(moduleName, toolName) {
216
264
  if (!moduleName || !toolName) return null;
217
-
218
- // 根据 module 名确定对应的快捷命令表
219
- let shortcuts = null;
220
- let autoPath = null;
221
- if (moduleName === 'issues') {
222
- shortcuts = ISSUE_SHORTCUTS;
223
- const repo = process.env.CNB_REPO_SLUG;
224
- const number = process.env.CNB_ISSUE_IID;
225
- if (repo && number) {
226
- autoPath = {
227
- repo,
228
- number
229
- };
230
- }
231
- } else if (moduleName === 'pulls') {
232
- shortcuts = PR_SHORTCUTS;
233
- const repo = process.env.CNB_REPO_SLUG;
234
- const number = process.env.CNB_PULL_REQUEST_IID;
235
- if (repo && number) {
236
- autoPath = {
237
- repo,
238
- number
239
- };
240
- }
241
- }
265
+ const shortcuts = moduleName === 'issues' ? ISSUE_SHORTCUTS : moduleName === 'pulls' ? PR_SHORTCUTS : null;
242
266
  if (!shortcuts) return null;
243
-
244
- // 在快捷命令表中查找匹配的 shortName
245
267
  const matched = shortcuts.find(s => s.shortName === toolName);
246
268
  if (!matched) return null;
247
269
  return {
270
+ module: moduleName,
248
271
  tool: matched.realTool,
249
- autoPath: autoPath || {},
250
- autoData: matched.autoData || null
272
+ autoPath: buildAutoPath(moduleName, !!matched.repoOnly),
273
+ autoData: matched.autoData || null,
274
+ upload: !!matched.upload
251
275
  };
252
276
  }
253
277
 
@@ -263,41 +287,151 @@ function resolveShortcut(moduleName, toolName) {
263
287
  * - 数组响应:对 data 中每个元素应用提取函数
264
288
  */
265
289
  const SUMMARY_EXTRACTORS = {
266
- // Issue 详情摘要:只保留标题和正文
290
+ // Issue 详情摘要:保留标题、状态、标签和正文
291
+ // 过滤: number, state_reason, assignees, author, created_at, updated_at 等
267
292
  'issues/get-issue': item => ({
268
293
  title: item.title,
294
+ state: item.state,
295
+ labels: item.labels?.map?.(l => l.name).filter(Boolean) || [],
269
296
  body: item.body
270
297
  }),
271
298
  // Issue 更新摘要:只保留状态变更结果
299
+ // 过滤: title, body, labels, assignees, author, created_at, updated_at 等
272
300
  'issues/update-issue': item => ({
273
301
  number: item.number,
274
302
  state: item.state,
275
303
  state_reason: item.state_reason
276
304
  }),
277
- // Issue 添加处理人摘要:只保留处理人列表
305
+ // Issue 评论列表摘要:只保留作者用户名、内容和创建时间
306
+ // 过滤: author 完整对象(avatar/email/freeze/is_npc/nickname), reactions, updated_at
307
+ 'issues/list-issue-comments': item => ({
308
+ id: item.id,
309
+ author: item.author?.username,
310
+ body: item.body,
311
+ created_at: item.created_at
312
+ }),
313
+ // Issue 发表评论摘要:只保留评论 ID 和创建时间(body 已在请求中传入,无需重复)
314
+ // 过滤: body(请求已传入), author 完整对象(avatar/email/freeze/is_npc/nickname/username), reactions, updated_at
315
+ 'issues/post-issue-comment': item => ({
316
+ id: item.id,
317
+ created_at: item.created_at
318
+ }),
319
+ // Issue 标签列表摘要:保留名称、颜色和描述
320
+ // 过滤: id
321
+ 'issues/list-issue-labels': item => ({
322
+ name: item.name,
323
+ color: item.color,
324
+ description: item.description
325
+ }),
326
+ // Issue 添加标签摘要:只保留 ID 和颜色(name 已在请求中传入,无需重复)
327
+ // 过滤: name(请求已传入), description
328
+ 'issues/post-issue-labels': item => ({
329
+ id: item.id,
330
+ color: item.color
331
+ }),
332
+ // Issue 处理人列表摘要:保留用户名和昵称
333
+ // 过滤: avatar, email, freeze, is_npc
334
+ 'issues/list-issue-assignees': item => ({
335
+ username: item.username,
336
+ nickname: item.nickname
337
+ }),
338
+ // Issue 添加处理人摘要:保留处理人用户名和昵称列表
339
+ // 过滤: assignees 中每个用户的 avatar/email/freeze/is_npc,以及 issue 其他字段
278
340
  'issues/post-issue-assignees': item => ({
279
341
  number: item.number,
280
- assignees: item.assignees?.map?.(a => a.username).filter(Boolean) || []
342
+ assignees: item.assignees?.map?.(a => ({
343
+ username: a.username,
344
+ nickname: a.nickname
345
+ })).filter(a => a.username) || []
281
346
  }),
282
- // PR 详情摘要:只保留标题、状态、正文和分支信息
347
+ // PR 详情摘要:保留标题、状态、标签、正文和分支信息
348
+ // 过滤: number, author, assignees, reviewers, created_at, updated_at, base/head 完整对象等
283
349
  'pulls/get-pull': item => ({
284
350
  title: item.title,
285
351
  state: item.state,
352
+ labels: item.labels?.map?.(l => l.name).filter(Boolean) || [],
286
353
  base: item.base?.ref,
287
354
  head: item.head?.ref,
288
355
  body: item.body
289
356
  }),
290
- // PR 文件列表摘要:只保留文件名、变更状态和增删行数
357
+ // PR 文件列表摘要:保留文件名、sha、变更状态和增删行数
358
+ // 过滤: patch, blob_url, raw_url, contents_url, previous_filename
291
359
  'pulls/list-pull-files': item => ({
292
360
  filename: item.filename,
361
+ sha: item.sha,
293
362
  status: item.status,
294
363
  additions: item.additions,
295
364
  deletions: item.deletions
296
365
  }),
297
366
  // PR 提交列表摘要:只保留 sha 前 8 位和 commit message
367
+ // 过滤: sha 完整值, commit 完整对象(author/committer/tree/verification), parents, url 等
298
368
  'pulls/list-pull-commits': item => ({
299
369
  sha: typeof item.sha === 'string' ? item.sha.substring(0, 8) : item.sha,
300
370
  message: item.commit?.message
371
+ }),
372
+ // PR 评论列表摘要:保留作者用户名和昵称、内容和创建时间
373
+ // 过滤: author 完整对象(avatar/email/freeze/is_npc), reactions, updated_at
374
+ 'pulls/list-pull-comments': item => ({
375
+ id: item.id,
376
+ author: item.author?.username,
377
+ nickname: item.author?.nickname,
378
+ body: item.body,
379
+ created_at: item.created_at
380
+ }),
381
+ // PR 发表评论摘要:只保留评论 ID 和创建时间(body 已在请求中传入,无需重复)
382
+ // 过滤: body(请求已传入), author 完整对象(avatar/email/freeze/is_npc/nickname/username), reactions, updated_at
383
+ 'pulls/post-pull-comment': item => ({
384
+ id: item.id,
385
+ created_at: item.created_at
386
+ }),
387
+ // PR 标签列表摘要:保留 ID、名称、颜色和描述
388
+ // 过滤: 无
389
+ 'pulls/list-pull-labels': item => ({
390
+ id: item.id,
391
+ name: item.name,
392
+ color: item.color,
393
+ description: item.description
394
+ }),
395
+ // PR 添加标签摘要:只保留 ID 和颜色(name 已在请求中传入,无需重复)
396
+ // 过滤: name(请求已传入), description
397
+ 'pulls/post-pull-labels': item => ({
398
+ id: item.id,
399
+ color: item.color
400
+ }),
401
+ // PR CI 状态摘要:保留整体状态和各检查项的核心信息(sha 截断为前 8 位)
402
+ // 过滤: sha 完整值, statuses 中每项的 target_url/created_at/updated_at
403
+ 'pulls/list-pull-commit-statuses': item => ({
404
+ sha: typeof item.sha === 'string' ? item.sha.substring(0, 8) : item.sha,
405
+ state: item.state,
406
+ statuses: item.statuses?.map?.(s => ({
407
+ context: s.context,
408
+ state: s.state,
409
+ description: s.description
410
+ })) || []
411
+ }),
412
+ // PR 评审列表摘要:保留作者用户名和昵称、状态和内容
413
+ // 过滤: author 完整对象(avatar/email/freeze/is_npc), created_at, updated_at
414
+ 'pulls/list-pull-reviews': item => ({
415
+ id: item.id,
416
+ author: item.author?.username,
417
+ nickname: item.author?.nickname,
418
+ state: item.state,
419
+ body: item.body
420
+ }),
421
+ // PR 处理人列表摘要:保留用户名和昵称
422
+ // 过滤: avatar, email, freeze, is_npc
423
+ 'pulls/list-pull-assignees': item => ({
424
+ username: item.username,
425
+ nickname: item.nickname
426
+ }),
427
+ // PR 添加处理人摘要:保留处理人用户名和昵称列表
428
+ // 过滤: assignees 中每个用户的 avatar/email/freeze/is_npc,以及 PR 其他字段
429
+ 'pulls/post-pull-assignees': item => ({
430
+ number: item.number,
431
+ assignees: item.assignees?.map?.(a => ({
432
+ username: a.username,
433
+ nickname: a.nickname
434
+ })).filter(a => a.username) || []
301
435
  })
302
436
  };
303
437
 
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.handleUpload = handleUpload;
7
+ var _fs = _interopRequireDefault(require("fs"));
8
+ var _path = _interopRequireDefault(require("path"));
9
+ var _mimeTypes = require("mime-types");
10
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
11
+ /**
12
+ * 完整上传流程
13
+ * 1. 读取本地文件 → 获取 name/size
14
+ * 2. 调用上传 API → 获取 upload_url
15
+ * 3. PUT 文件内容到 upload_url(流式上传)
16
+ * 4. 返回最终结果
17
+ */
18
+
19
+ // 上传文件大小上限:100MB
20
+ const MAX_FILE_SIZE = 100 * 1024 * 1024;
21
+
22
+ /**
23
+ * 处理完整上传流程
24
+ * @param shortcut 解析后的快捷命令
25
+ * @param filePath 本地文件路径
26
+ * @param toolFunction 原始上传 API 函数(获取 upload_url)
27
+ * @param toolsParam API 调用的 path 参数(repo 或 {repo, number})
28
+ */
29
+ async function handleUpload(shortcut, filePath, toolFunction, toolsParam) {
30
+ // 校验 file 参数
31
+ if (!filePath || typeof filePath !== 'string') {
32
+ return {
33
+ status: 400,
34
+ data: {
35
+ error: `上传命令需要指定文件路径,如: --data '{"file":"./path/to/file"}'`
36
+ }
37
+ };
38
+ }
39
+
40
+ // 1. 读取本地文件信息
41
+ if (!_fs.default.existsSync(filePath)) {
42
+ return {
43
+ status: 400,
44
+ data: {
45
+ error: `文件不存在: ${filePath}`
46
+ }
47
+ };
48
+ }
49
+ const stat = _fs.default.statSync(filePath);
50
+ if (!stat.isFile()) {
51
+ return {
52
+ status: 400,
53
+ data: {
54
+ error: `不是文件: ${filePath}`
55
+ }
56
+ };
57
+ }
58
+ const fileName = _path.default.basename(filePath);
59
+ const fileSize = stat.size;
60
+ if (fileSize === 0) {
61
+ return {
62
+ status: 400,
63
+ data: {
64
+ error: '文件为空'
65
+ }
66
+ };
67
+ }
68
+ if (fileSize > MAX_FILE_SIZE) {
69
+ return {
70
+ status: 400,
71
+ data: {
72
+ error: `文件过大 (${(fileSize / 1024 / 1024).toFixed(1)}MB),上限 ${MAX_FILE_SIZE / 1024 / 1024}MB`
73
+ }
74
+ };
75
+ }
76
+ const contentType = (0, _mimeTypes.lookup)(filePath) || 'application/octet-stream';
77
+
78
+ // 2. 调用上传 API 获取 upload_url
79
+ const isIssueUpload = shortcut.module === 'issues';
80
+ const requestBody = isIssueUpload ? {
81
+ name: fileName,
82
+ size: fileSize,
83
+ content_type: contentType
84
+ } : {
85
+ name: fileName,
86
+ size: fileSize
87
+ };
88
+ const uploadResponse = await toolFunction(toolsParam, requestBody);
89
+
90
+ // 提取 upload_url(兼容标准响应和裸响应)
91
+ const responseData = uploadResponse?.data ?? uploadResponse;
92
+ const uploadUrl = responseData?.upload_url;
93
+ if (!uploadUrl) {
94
+ return uploadResponse; // 获取 URL 失败,直接返回原始错误
95
+ }
96
+
97
+ // 3. PUT 文件内容到 upload_url(流式读取,避免大文件撑爆内存)
98
+ const fileStream = _fs.default.createReadStream(filePath);
99
+ const putHeaders = {
100
+ 'Content-Type': contentType,
101
+ 'Content-Length': String(fileSize)
102
+ };
103
+ const putResponse = await fetch(uploadUrl, {
104
+ method: 'PUT',
105
+ headers: putHeaders,
106
+ body: fileStream,
107
+ // @ts-ignore duplex required for streaming body in Node.js fetch
108
+ duplex: 'half'
109
+ });
110
+ if (!putResponse.ok) {
111
+ const errText = await putResponse.text().catch(() => '');
112
+ return {
113
+ status: putResponse.status,
114
+ data: {
115
+ error: `文件上传失败: ${putResponse.statusText}`,
116
+ detail: errText
117
+ }
118
+ };
119
+ }
120
+
121
+ // 4. 返回最终结果
122
+ if (isIssueUpload) {
123
+ return {
124
+ status: 200,
125
+ data: {
126
+ asset_link: responseData.asset_link,
127
+ name: fileName,
128
+ size: fileSize
129
+ }
130
+ };
131
+ }
132
+ return {
133
+ status: 200,
134
+ data: {
135
+ name: responseData.assets?.name || fileName,
136
+ path: responseData.assets?.path,
137
+ size: fileSize,
138
+ token: responseData.token
139
+ }
140
+ };
141
+ }
@@ -1,140 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = convertLink;
7
- /**
8
- * 把文本里的相对路径转换为绝对路径
9
- * 与 codebuddy/skills/cnb-text-relative-path-converter/scripts/convertLink.js 逻辑一致
10
- *
11
- * @param {String} text 待转换的文本
12
- * @param {String} repoSlug 仓库路径
13
- * @param {String} branchOrSha 可选,分支或SHA
14
- * @returns {String}
15
- */
16
- function convertLink(text, repoSlug, branchOrSha) {
17
- // 查询所有代码块的位置
18
- let codeBlockPositions = [];
19
- let index = 0;
20
- while (index !== -1) {
21
- const nextIndex = text.indexOf('```', index);
22
- if (nextIndex === -1) break;
23
- codeBlockPositions.push(nextIndex);
24
- index = nextIndex + 3; // 跳过已匹配的三个反引号
25
- }
26
- if (codeBlockPositions.length % 2 !== 0) {
27
- codeBlockPositions = codeBlockPositions.slice(0, codeBlockPositions.length - 1);
28
- }
29
-
30
- // 查询所有行内代码块的位置
31
- let inlineCodeBlockPositions = [];
32
- index = 0;
33
- while (index < text.length) {
34
- const nextIndex = text.indexOf('`', index);
35
- if (nextIndex === -1) break;
36
- // 检查是否是单独的反引号(不是代码块的一部分)
37
- if ((nextIndex === 0 || text.charAt(nextIndex - 1) !== '`') && (nextIndex === text.length - 1 || text.charAt(nextIndex + 1) !== '`')) {
38
- inlineCodeBlockPositions.push(nextIndex);
39
- }
40
- index = nextIndex + 1;
41
- }
42
- if (inlineCodeBlockPositions.length % 2 !== 0) {
43
- inlineCodeBlockPositions = inlineCodeBlockPositions.slice(0, inlineCodeBlockPositions.length - 1);
44
- }
45
-
46
- // 整理起始和结束位置
47
- const excludedRanges = [...codeBlockPositions, ...inlineCodeBlockPositions].reduce((result, item, index) => {
48
- if (index % 2 === 0) {
49
- return result.concat([[item]]);
50
- }
51
- result[result.length - 1].push(item);
52
- return result;
53
- }, []);
54
-
55
- // Helper function to check if an index is within excluded ranges
56
- const isInExcludedRange = index => {
57
- return excludedRanges.some(([start, end]) => index >= start && index < end);
58
- };
59
- let match;
60
-
61
- // Collect all replacements with their positions
62
- const replacements = [];
63
-
64
- // Match markdown links and images: [text](url) and ![alt](url)
65
- const markdownLinkRegex = /!?\[([^\]]+)\]\(([^)]+)\)/g;
66
- while ((match = markdownLinkRegex.exec(text)) !== null) {
67
- if (!isInExcludedRange(match.index)) {
68
- // Calculate URL position: match.index + length of "![" + match[1] + "]("
69
- const prefixLength = (match[0].startsWith('!') ? 1 : 0) + 1 + match[1].length + 2;
70
- const urlStart = match.index + prefixLength;
71
- const urlEnd = urlStart + match[2].length;
72
- const newUrl = normaliseLink(match[2], repoSlug, branchOrSha);
73
- if (newUrl !== match[2]) {
74
- replacements.push({
75
- start: urlStart,
76
- end: urlEnd,
77
- newUrl
78
- });
79
- }
80
- }
81
- }
82
-
83
- // Match HTML tags: <img src="..."> and <a href="...">
84
- const htmlTagRegex = /\s(src|href)=["']([^"']+)["']/gi;
85
- while ((match = htmlTagRegex.exec(text)) !== null) {
86
- if (!isInExcludedRange(match.index)) {
87
- const urlStart = match.index + match[0].indexOf(match[2]);
88
- const urlEnd = urlStart + match[2].length;
89
- const newUrl = normaliseLink(match[2], repoSlug, branchOrSha);
90
- if (newUrl !== match[2]) {
91
- replacements.push({
92
- start: urlStart,
93
- end: urlEnd,
94
- newUrl
95
- });
96
- }
97
- }
98
- }
99
-
100
- // Sort replacements by start position in descending order
101
- replacements.sort((a, b) => b.start - a.start);
102
-
103
- // Apply replacements from end to start to maintain correct indices
104
- let result = text;
105
- for (const {
106
- start,
107
- end,
108
- newUrl
109
- } of replacements) {
110
- result = result.substring(0, start) + newUrl + result.substring(end);
111
- }
112
- return result;
113
- }
114
-
115
- /**
116
- * 相对路径转换为绝对路径
117
- * 与 codebuddy/skills/text-path-converter/scripts/convertLink.js 逻辑一致
118
- *
119
- * @param {String} link 待转换的链接
120
- * @param {String} repoSlug 仓库路径
121
- * @param {String} branchOrSha 分支或SHA,默认为 HEAD
122
- * @returns {String}
123
- */
124
- function normaliseLink(link, repoSlug, branchOrSha = 'HEAD') {
125
- const baseURL = `${process.env.CNB_WEB_ENDPOINT}/${repoSlug}`;
126
- if (link.startsWith('/-/')) {
127
- return `${baseURL}${link}`;
128
- }
129
- if (link.indexOf('/-/') === -1 && (link.startsWith('../') || link.startsWith('./') || link.startsWith('/') && !link.startsWith('//'))) {
130
- let chunks = link.split('/');
131
- // 过滤掉空字符串和 . .. 这些无效路径
132
- chunks = chunks.filter(chunk => !!chunk && chunk !== '.' && chunk !== '..');
133
- if (chunks.length === 0) {
134
- return link;
135
- }
136
- chunks.unshift(branchOrSha);
137
- return `${baseURL}/-/git/raw/${chunks.join('/')}`;
138
- }
139
- return link;
140
- }
@@ -1,6 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
-
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
@@ -1,5 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
@@ -1,70 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = _default;
7
- var _core = _interopRequireDefault(require("../../core/core.js"));
8
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
9
- // @ts-nocheck
10
- /* tslint:disable */
11
- /* eslint-disable */
12
- /*
13
- * -------------------------------------------------------------------------
14
- * ## THIS FILE WAS GENERATED VIA CNB-API-GENERATE ##
15
- * ## ##
16
- * ## AUTHOR: bapelin ##
17
- * ## SOURCE: https://cnb.cool/cnb/frontend-science/cnb-api-generate ##
18
- * -------------------------------------------------------------------------
19
- * @Version 1.2.1
20
- * @Source /{repo}/-/build/ai/auto-pr
21
- */
22
-
23
- /**
24
- * @description Other reuqest params
25
- */
26
-
27
- /**
28
- * @description AiAutoPrRes Success Response Type
29
- */
30
-
31
- /**
32
- * @description AiAutoPrError Error Response Type
33
- */
34
-
35
- /**
36
- * @description 访问令牌调用此接口需包含以下权限。Required permissions for access token.
37
- * repo-code:rw
38
- * @tags AI
39
- * @name aiAutoPr
40
- * @summary 根据传入的需求内容和需求标题借助 AI 自动编码并提 PR。Automatically code and create a PR with AI based on the input requirement content and title.
41
- * @request post:/{repo}/-/build/ai/auto-pr
42
-
43
- ----------------------------------
44
- * @param {string} arg0
45
- * @param {DtoAiAutoPrReq} arg1
46
- * @param {RequestConfig} arg2 - Other reuqest params
47
- */
48
- async function _default(repo, request, {
49
- req,
50
- options,
51
- ...axiosConfig
52
- } = {}) {
53
- return await _core.default.request({
54
- ...axiosConfig,
55
- _next_req: req,
56
- options: options,
57
- url: `/${repo}/-/build/ai/auto-pr`,
58
- _apiTag: "/{repo}/-/build/ai/auto-pr",
59
- method: "post",
60
- data: request,
61
- _originParams: {
62
- method: "post",
63
- _apiTag: "/{repo}/-/build/ai/auto-pr",
64
- path: {
65
- repo
66
- },
67
- body: request
68
- }
69
- });
70
- }
@@ -1,75 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = _default;
7
- var _core = _interopRequireDefault(require("../../core/core.js"));
8
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
9
- // @ts-nocheck
10
- /* tslint:disable */
11
- /* eslint-disable */
12
- /*
13
- * -------------------------------------------------------------------------
14
- * ## THIS FILE WAS GENERATED VIA CNB-API-GENERATE ##
15
- * ## ##
16
- * ## AUTHOR: bapelin ##
17
- * ## SOURCE: https://cnb.woa.com/cnb/frontend-science/cnb-api-generate ##
18
- * -------------------------------------------------------------------------
19
- * @Version 2.2.0
20
- * @Source /{repo}/-/files/{filePath}
21
- */
22
-
23
- /**
24
- * @description getFiles request params
25
- */
26
-
27
- /**
28
- * @description Other reuqest params
29
- */
30
-
31
- /**
32
- * @description GetFilesRes Success Response Type
33
- */
34
-
35
- /**
36
- * @description GetFilesError Error Response Type
37
- */
38
-
39
- /**
40
- * @description 访问令牌调用此接口需包含以下权限。Required permissions for access token.
41
- * repo-contents:r
42
- * @tags Pulls,Issues
43
- * @name getFiles
44
- * @summary 获取 issue 文件或合并请求文件的请求,返回文件二进制内容。Request to retrieve file of issues and pull requests, returns binary content.
45
- * @request get:/{repo}/-/files/{filePath}
46
-
47
- ----------------------------------
48
- * @param {GetFilesParams} arg0 - getFiles request params
49
- * @param {RequestConfig} arg1 - Other reuqest params
50
- */
51
- async function _default({
52
- repo,
53
- filePath
54
- }, {
55
- req,
56
- options,
57
- ...axiosConfig
58
- } = {}) {
59
- return await _core.default.request({
60
- ...axiosConfig,
61
- _next_req: req,
62
- options: options,
63
- url: `/${repo}/-/files/${filePath}`,
64
- _apiTag: "/{repo}/-/files/{filePath}",
65
- method: "get",
66
- _originParams: {
67
- method: "get",
68
- _apiTag: "/{repo}/-/files/{filePath}",
69
- path: {
70
- repo,
71
- filePath
72
- }
73
- }
74
- });
75
- }
@@ -1,75 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = _default;
7
- var _core = _interopRequireDefault(require("../../core/core.js"));
8
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
9
- // @ts-nocheck
10
- /* tslint:disable */
11
- /* eslint-disable */
12
- /*
13
- * -------------------------------------------------------------------------
14
- * ## THIS FILE WAS GENERATED VIA CNB-API-GENERATE ##
15
- * ## ##
16
- * ## AUTHOR: bapelin ##
17
- * ## SOURCE: https://cnb.woa.com/cnb/frontend-science/cnb-api-generate ##
18
- * -------------------------------------------------------------------------
19
- * @Version 2.2.0
20
- * @Source /{repo}/-/imgs/{imgPath}
21
- */
22
-
23
- /**
24
- * @description getImgs request params
25
- */
26
-
27
- /**
28
- * @description Other reuqest params
29
- */
30
-
31
- /**
32
- * @description GetImgsRes Success Response Type
33
- */
34
-
35
- /**
36
- * @description GetImgsError Error Response Type
37
- */
38
-
39
- /**
40
- * @description 访问令牌调用此接口需包含以下权限。Required permissions for access token.
41
- * repo-contents:r
42
- * @tags Pulls,Issues
43
- * @name getImgs
44
- * @summary 获取 issue 图片或合并请求图片的请求,返回图片二进制内容。Request to retrieve image of issues and pull requests, returns binary content.
45
- * @request get:/{repo}/-/imgs/{imgPath}
46
-
47
- ----------------------------------
48
- * @param {GetImgsParams} arg0 - getImgs request params
49
- * @param {RequestConfig} arg1 - Other reuqest params
50
- */
51
- async function _default({
52
- repo,
53
- imgPath
54
- }, {
55
- req,
56
- options,
57
- ...axiosConfig
58
- } = {}) {
59
- return await _core.default.request({
60
- ...axiosConfig,
61
- _next_req: req,
62
- options: options,
63
- url: `/${repo}/-/imgs/${imgPath}`,
64
- _apiTag: "/{repo}/-/imgs/{imgPath}",
65
- method: "get",
66
- _originParams: {
67
- method: "get",
68
- _apiTag: "/{repo}/-/imgs/{imgPath}",
69
- path: {
70
- repo,
71
- imgPath
72
- }
73
- }
74
- });
75
- }