@pikecode/api-key-manager 2.0.0 → 2.0.2

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 (60) hide show
  1. package/README.md +444 -151
  2. package/bin/akm.js +340 -11
  3. package/package.json +29 -12
  4. package/src/CommandRegistry.js +58 -3
  5. package/src/commands/BaseCommand.js +68 -1
  6. package/src/commands/add/prompts.js +280 -0
  7. package/src/commands/add/providerSaver.js +74 -0
  8. package/src/commands/add/summaryPrinter.js +29 -0
  9. package/src/commands/add.js +54 -439
  10. package/src/commands/backup.js +396 -0
  11. package/src/commands/batch.js +313 -0
  12. package/src/commands/benchmark.js +323 -0
  13. package/src/commands/claude-clean.js +253 -0
  14. package/src/commands/clone.js +265 -0
  15. package/src/commands/current.js +89 -41
  16. package/src/commands/edit.js +3 -207
  17. package/src/commands/health.js +264 -0
  18. package/src/commands/list.js +120 -35
  19. package/src/commands/mcp.js +467 -0
  20. package/src/commands/remove.js +89 -26
  21. package/src/commands/stats.js +281 -0
  22. package/src/commands/switch/claude-settings-compatibility.js +113 -0
  23. package/src/commands/switch/launch-args-helper.js +84 -0
  24. package/src/commands/switch/provider-choices-helper.js +72 -0
  25. package/src/commands/switch/provider-details-helper.js +46 -0
  26. package/src/commands/switch/provider-edit-questions-helper.js +124 -0
  27. package/src/commands/switch/provider-launcher.js +20 -0
  28. package/src/commands/switch/provider-manager.js +214 -0
  29. package/src/commands/switch/status-helper.js +124 -0
  30. package/src/commands/switch/ui-screen-renderer.js +77 -0
  31. package/src/commands/switch.js +471 -958
  32. package/src/commands/validate.js +310 -0
  33. package/src/config.js +558 -55
  34. package/src/constants/index.js +234 -0
  35. package/src/constants/ui.js +108 -0
  36. package/src/index.js +11 -4
  37. package/src/navigation/EscNavigationManager.js +5 -5
  38. package/src/utils/atomic-file.js +47 -0
  39. package/src/utils/claude-settings.js +4 -4
  40. package/src/utils/codex-files.js +418 -0
  41. package/src/utils/codex-launcher.js +104 -0
  42. package/src/utils/concurrency.js +30 -0
  43. package/src/utils/config-opener.js +22 -2
  44. package/src/utils/env-launcher.js +50 -44
  45. package/src/utils/env-utils.js +52 -0
  46. package/src/utils/error-handler.js +27 -28
  47. package/src/utils/health-checker.js +350 -0
  48. package/src/utils/import-validator.js +212 -0
  49. package/src/utils/inquirer-setup.js +11 -0
  50. package/src/utils/launch-args.js +155 -0
  51. package/src/utils/logger.js +0 -1
  52. package/src/utils/provider-status-checker.js +211 -64
  53. package/src/utils/secrets.js +22 -0
  54. package/src/utils/shell-snippets.js +32 -0
  55. package/src/utils/terminal-format.js +22 -4
  56. package/src/utils/ui-helper.js +96 -86
  57. package/src/utils/update-checker.js +41 -12
  58. package/src/utils/validator.js +136 -89
  59. package/bin/cc.js +0 -101
  60. package/src/utils/storage.js +0 -55
@@ -1,38 +1,7 @@
1
1
  const chalk = require('chalk');
2
2
 
3
3
  class UIHelper {
4
- // 颜色主题
5
- static colors = {
6
- primary: chalk.cyan,
7
- secondary: chalk.blue,
8
- success: chalk.green,
9
- warning: chalk.yellow,
10
- error: chalk.red,
11
- info: chalk.white,
12
- muted: chalk.gray,
13
- accent: chalk.magenta
14
- };
15
-
16
- // 图标
17
- static icons = {
18
- success: '✅',
19
- error: '❌',
20
- warning: '⚠️',
21
- info: 'ℹ️',
22
- loading: '⏳',
23
- arrow: '→',
24
- back: '🔙',
25
- home: '🏠',
26
- settings: '⚙️',
27
- add: '➕',
28
- edit: '✏️',
29
- delete: '🗑️',
30
- launch: '🚀',
31
- list: '📋',
32
- config: '🛠️',
33
- current: '🎯',
34
- search: '🔍'
35
- };
4
+ // 创建标题
36
5
 
37
6
  // 创建标题
38
7
  static createTitle(text, icon = '') {
@@ -47,36 +16,37 @@ class UIHelper {
47
16
 
48
17
  // 创建项目列表
49
18
  static createItem(label, value, isSelected = false) {
50
- const icon = isSelected ? this.icons.current : '•';
51
- const color = isSelected ? this.colors.primary : this.colors.info;
19
+ const icon = isSelected ? UIHelper.icons.current : '•';
20
+ const color = isSelected ? UIHelper.colors.primary : UIHelper.colors.info;
52
21
  return `${color(icon)} ${label}`;
53
22
  }
54
23
 
55
24
  // 创建操作按钮
56
25
  static createButton(label, action, icon = '') {
57
26
  const fullIcon = icon ? `${icon} ` : '';
58
- return `${this.colors.accent(fullIcon)}${this.colors.info(label)}`;
27
+ return `${UIHelper.colors.accent(fullIcon)}${UIHelper.colors.info(label)}`;
59
28
  }
60
29
 
61
30
  // 创建状态指示器
62
31
  static createStatus(status, label) {
63
32
  const statusConfig = {
64
- current: { icon: this.icons.current, color: this.colors.success },
65
- active: { icon: '🟢', color: this.colors.success },
66
- inactive: { icon: '⚫', color: this.colors.muted },
67
- loading: { icon: this.icons.loading, color: this.colors.warning },
68
- error: { icon: this.icons.error, color: this.colors.error }
33
+ current: { icon: UIHelper.icons.current, color: UIHelper.colors.success },
34
+ active: { icon: chalk.green('●'), color: UIHelper.colors.success },
35
+ inactive: { icon: chalk.gray('·'), color: UIHelper.colors.muted },
36
+ loading: { icon: UIHelper.icons.loading, color: UIHelper.colors.warning },
37
+ error: { icon: UIHelper.icons.error, color: UIHelper.colors.error }
69
38
  };
70
39
 
71
40
  const config = statusConfig[status] || statusConfig.inactive;
72
- return `${config.color(config.icon)} ${this.colors.info(label)}`;
41
+ return `${config.color(config.icon)} ${UIHelper.colors.info(label)}`;
73
42
  }
74
43
 
75
44
  // 格式化供应商信息
76
45
  static formatProvider(provider) {
77
46
  const status = provider.current ? 'current' : 'inactive';
78
- const statusText = this.createStatus(status, provider.name);
79
- const displayName = this.colors.secondary(`(${provider.displayName})`);
47
+ const statusText = UIHelper.createStatus(status, provider.name);
48
+ const displayName = UIHelper.colors.secondary(`(${provider.displayName})`);
49
+
80
50
  return `${statusText} ${displayName}`;
81
51
  }
82
52
 
@@ -87,73 +57,80 @@ class UIHelper {
87
57
  const filled = '█'.repeat(progress);
88
58
  const emptySpace = '░'.repeat(empty);
89
59
  const percentage = Math.floor((current / total) * 100);
90
-
91
- return `${this.colors.primary(filled)}${this.colors.muted(emptySpace)} ${this.colors.info(percentage + '%')}`;
60
+
61
+ return `${UIHelper.colors.primary(filled)}${UIHelper.colors.muted(emptySpace)} ${UIHelper.colors.info(percentage + '%')}`;
92
62
  }
93
63
 
94
64
  // 创建表格
95
65
  static createTable(headers, rows) {
96
66
  const columnWidths = headers.map(header => Math.max(header.length, ...rows.map(row => String(row[headers.indexOf(header)]).length)));
97
-
67
+
98
68
  let result = '';
99
-
69
+
100
70
  // 表头
101
71
  const headerRow = headers.map((header, i) => header.padEnd(columnWidths[i])).join(' │ ');
102
- result += `${this.colors.primary(headerRow)}\n`;
103
-
72
+ result += `${UIHelper.colors.primary(headerRow)}\n`;
73
+
104
74
  // 分隔线
105
75
  const separator = columnWidths.map(width => '─'.repeat(width)).join('─┼─');
106
- result += `${this.colors.muted(separator)}\n`;
107
-
76
+ result += `${UIHelper.colors.muted(separator)}\n`;
77
+
108
78
  // 数据行
109
79
  rows.forEach(row => {
110
80
  const dataRow = row.map((cell, i) => String(cell).padEnd(columnWidths[i])).join(' │ ');
111
- result += `${this.colors.info(dataRow)}\n`;
81
+ result += `${UIHelper.colors.info(dataRow)}\n`;
112
82
  });
113
-
83
+
114
84
  return result;
115
85
  }
116
86
 
87
+ // 剥离 ANSI 转义码后的可见字符长度
88
+ static _visibleLength(str) {
89
+ return str.replace(/\x1b\[[0-9;]*m/g, '').length;
90
+ }
91
+
117
92
  // 创建卡片式布局
118
93
  static createCard(title, content, icon = '') {
119
94
  const lines = content.split('\n');
120
- const maxLineLength = Math.max(...lines.map(line => line.length));
95
+ const maxLineLength = Math.max(...lines.map(line => UIHelper._visibleLength(line)));
96
+ const iconPrefix = icon ? `${icon} ` : '';
97
+ const titleVisible = UIHelper._visibleLength(title);
121
98
  const horizontalBorder = '─'.repeat(maxLineLength + 4);
122
-
123
- let result = `${this.colors.primary(`┌─${horizontalBorder}─┐`)}\n`;
124
- result += `${this.colors.primary('│')} ${chalk.bold.white(icon ? `${icon} ` : '')}${chalk.bold.white(title)}${' '.repeat(maxLineLength - title.length - (icon ? 2 : 0))} ${this.colors.primary('│')}\n`;
125
- result += `${this.colors.primary('├─')}${this.colors.muted(horizontalBorder)}${this.colors.primary('─┤')}\n`;
126
-
99
+
100
+ let result = `${UIHelper.colors.primary(`┌─${horizontalBorder}─┐`)}\n`;
101
+ result += `${UIHelper.colors.primary('│')} ${chalk.bold.white(iconPrefix)}${chalk.bold.white(title)}${' '.repeat(Math.max(0, maxLineLength - titleVisible - iconPrefix.length))} ${UIHelper.colors.primary('│')}\n`;
102
+ result += `${UIHelper.colors.primary('├─')}${UIHelper.colors.muted(horizontalBorder)}${UIHelper.colors.primary('─┤')}\n`;
103
+
127
104
  lines.forEach(line => {
128
- result += `${this.colors.primary('│')} ${this.colors.info(line)}${' '.repeat(maxLineLength - line.length)} ${this.colors.primary('│')}\n`;
105
+ result += `${UIHelper.colors.primary('│')} ${UIHelper.colors.info(line)}${' '.repeat(Math.max(0, maxLineLength - UIHelper._visibleLength(line)))} ${UIHelper.colors.primary('│')}\n`;
129
106
  });
130
-
131
- result += `${this.colors.primary('└─')}${this.colors.muted(horizontalBorder)}${this.colors.primary('─┘')}`;
107
+
108
+ result += `${UIHelper.colors.primary('└─')}${UIHelper.colors.muted(horizontalBorder)}${UIHelper.colors.primary('─┘')}`;
132
109
  return result;
133
110
  }
134
111
 
135
112
  // 创建操作菜单
136
113
  static createMenu(title, options) {
137
- let result = `${this.createTitle(title, this.icons.list)}\n\n`;
138
-
114
+ let result = `${UIHelper.createTitle(title, UIHelper.icons.list)}\n\n`;
115
+
139
116
  options.forEach((option, index) => {
140
- const number = this.colors.muted(`[${index + 1}]`);
117
+ const number = UIHelper.colors.muted(`[${index + 1}]`);
141
118
  const icon = option.icon || '•';
142
- const description = option.description ? this.colors.muted(` - ${option.description}`) : '';
143
- result += `${number} ${this.colors.accent(icon)} ${this.colors.info(option.label)}${description}\n`;
119
+ const description = option.description ? UIHelper.colors.muted(` - ${option.description}`) : '';
120
+ result += `${number} ${UIHelper.colors.accent(icon)} ${UIHelper.colors.info(option.label)}${description}\n`;
144
121
  });
145
-
146
- result += `\n${this.colors.muted(this.createSeparator())}\n`;
147
- result += `${this.colors.warning('请选择操作 (输入数字): ')}`;
148
-
122
+
123
+ result += `\n${UIHelper.colors.muted(UIHelper.createSeparator())}\n`;
124
+ result += `${UIHelper.colors.warning('请选择操作 (输入数字): ')}`;
125
+
149
126
  return result;
150
127
  }
151
128
 
152
129
  // 创建确认对话框
153
130
  static createConfirmDialog(message, options = ['确认', '取消']) {
154
- return `${this.colors.warning(message)}\n\n` +
155
- `${this.colors.success('[Y]')} ${this.colors.info(options[0])} ` +
156
- `${this.colors.error('[N]')} ${this.colors.info(options[1])}`;
131
+ return `${UIHelper.colors.warning(message)}\n\n` +
132
+ `${UIHelper.colors.success('[Y]')} ${UIHelper.colors.info(options[0])} ` +
133
+ `${UIHelper.colors.error('[N]')} ${UIHelper.colors.info(options[1])}`;
157
134
  }
158
135
 
159
136
  // 格式化时间
@@ -161,32 +138,32 @@ class UIHelper {
161
138
  const date = new Date(dateString);
162
139
  const now = new Date();
163
140
  const diff = now - date;
164
-
141
+
165
142
  if (diff < 60000) return '刚刚';
166
143
  if (diff < 3600000) return `${Math.floor(diff / 60000)} 分钟前`;
167
144
  if (diff < 86400000) return `${Math.floor(diff / 3600000)} 小时前`;
168
145
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)} 天前`;
169
-
146
+
170
147
  return date.toLocaleDateString('zh-CN');
171
148
  }
172
149
 
173
150
  // 创建搜索框
174
151
  static createSearchBox(placeholder = '搜索...') {
175
- return `${this.colors.info(this.icons.search)} ${this.colors.muted(placeholder)}`;
152
+ return `${UIHelper.colors.info(UIHelper.icons.search)} ${UIHelper.colors.muted(placeholder)}`;
176
153
  }
177
154
 
178
155
  // 创建提示框
179
156
  static createTooltip(text) {
180
- return `${this.colors.muted('💡 ' + text)}`;
157
+ return `${UIHelper.colors.muted('💡 ' + text)}`;
181
158
  }
182
159
 
183
160
  // 创建加载动画
184
161
  static createLoadingAnimation(text = '加载中...') {
185
162
  const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
186
163
  let frameIndex = 0;
187
-
164
+
188
165
  return setInterval(() => {
189
- process.stdout.write(`\r${this.colors.warning(frames[frameIndex])} ${this.colors.info(text)}`);
166
+ process.stdout.write(`\r${UIHelper.colors.warning(frames[frameIndex])} ${UIHelper.colors.info(text)}`);
190
167
  frameIndex = (frameIndex + 1) % frames.length;
191
168
  }, 100);
192
169
  }
@@ -199,12 +176,12 @@ class UIHelper {
199
176
 
200
177
  // 创建快捷键提示
201
178
  static createShortcutHint(key, action) {
202
- return `${this.colors.muted('[')}${this.colors.primary(key)}${this.colors.muted(']')} ${this.colors.info(action)}`;
179
+ return `${UIHelper.colors.muted('[')}${UIHelper.colors.primary(key)}${UIHelper.colors.muted(']')} ${UIHelper.colors.info(action)}`;
203
180
  }
204
181
 
205
182
  // 创建 ESC 键提示
206
183
  static createESCHint(action = '返回') {
207
- return `${this.colors.muted('[')}${this.colors.primary('ESC')}${this.colors.muted(']')} ${this.colors.info(action)}`;
184
+ return `${UIHelper.colors.muted('[')}${UIHelper.colors.primary('ESC')}${UIHelper.colors.muted(']')} ${UIHelper.colors.info(action)}`;
208
185
  }
209
186
 
210
187
  // 创建提示行
@@ -212,16 +189,49 @@ class UIHelper {
212
189
  if (!pairs.length) {
213
190
  return '';
214
191
  }
215
- const hints = pairs.map(([key, action]) => this.createShortcutHint(key, action));
216
- return `${this.colors.muted('提示: ')}${hints.join(this.colors.muted(' · '))}`;
192
+ const hints = pairs.map(([key, action]) => UIHelper.createShortcutHint(key, action));
193
+ return `${UIHelper.colors.muted('提示: ')}${hints.join(UIHelper.colors.muted(' · '))}`;
217
194
  }
218
195
 
219
196
  // 创建步骤指示
220
197
  static createStepIndicator(current, total, label) {
221
- const prefix = this.colors.muted(`步骤 ${current}/${total}`);
222
- const title = label ? ` ${this.colors.info(label)}` : '';
198
+ const prefix = UIHelper.colors.muted(`步骤 ${current}/${total}`);
199
+ const title = label ? ` ${UIHelper.colors.info(label)}` : '';
223
200
  return `${prefix}${title}`;
224
201
  }
225
202
  }
226
203
 
204
+ // 颜色主题
205
+ UIHelper.colors = {
206
+ primary: chalk.cyan,
207
+ secondary: chalk.blue,
208
+ success: chalk.green,
209
+ warning: chalk.yellow,
210
+ error: chalk.red,
211
+ info: chalk.white,
212
+ muted: chalk.gray,
213
+ accent: chalk.magenta
214
+ };
215
+
216
+ // 图标
217
+ UIHelper.icons = {
218
+ success: '✓',
219
+ error: '✗',
220
+ warning: '!',
221
+ info: 'i',
222
+ loading: '…',
223
+ arrow: '→',
224
+ back: '←',
225
+ home: '~',
226
+ settings: '*',
227
+ add: '+',
228
+ edit: '~',
229
+ delete: '-',
230
+ launch: '▶',
231
+ list: '≡',
232
+ config: '#',
233
+ current: '›',
234
+ search: '?'
235
+ };
236
+
227
237
  module.exports = { UIHelper };
@@ -1,7 +1,19 @@
1
+ /**
2
+ * Update Checker Utility
3
+ * 检查 npm 包更新
4
+ * @module utils/update-checker
5
+ */
6
+
1
7
  const chalk = require('chalk');
2
8
  const inquirer = require('inquirer');
3
9
  const spawn = require('cross-spawn');
4
10
 
11
+ /**
12
+ * 比较两个版本号
13
+ * @param {string} a - 版本号 A
14
+ * @param {string} b - 版本号 B
15
+ * @returns {number} -1 表示 a < b, 0 表示相等, 1 表示 a > b
16
+ */
5
17
  function compareVersions(a, b) {
6
18
  const pa = String(a).split('.').map(Number);
7
19
  const pb = String(b).split('.').map(Number);
@@ -15,21 +27,31 @@ function compareVersions(a, b) {
15
27
  return 0;
16
28
  }
17
29
 
30
+ /**
31
+ * 获取 npm 包的最新版本号
32
+ * @param {string} pkgName - 包名
33
+ * @param {number} [timeoutMs=4000] - 超时时间(毫秒)
34
+ * @returns {Promise<string|null>} 最新版本号,失败返回 null
35
+ */
18
36
  function getLatestVersion(pkgName, timeoutMs = 4000) {
19
- return new Promise((resolve, reject) => {
37
+ return new Promise((resolve, _reject) => {
20
38
  let done = false;
21
39
  const child = spawn('npm', ['view', pkgName, 'version', '--json'], {
22
- shell: process.platform === 'win32',
23
- stdio: ['ignore', 'pipe', 'ignore'],
40
+ shell: false,
41
+ stdio: ['ignore', 'pipe', 'ignore']
24
42
  });
25
43
 
26
44
  let out = '';
27
- child.stdout.on('data', (d) => (out += d.toString()))
45
+ child.stdout.on('data', (d) => (out += d.toString()));
28
46
 
29
47
  const t = setTimeout(() => {
30
48
  if (done) return;
31
49
  done = true;
32
- try { child.kill(); } catch {}
50
+ try {
51
+ child.kill();
52
+ } catch {
53
+ // npm view 超时后终止进程失败不影响更新检查结果。
54
+ }
33
55
  resolve(null);
34
56
  }, timeoutMs);
35
57
 
@@ -86,8 +108,8 @@ async function checkForUpdates({ packageName, currentVersion }) {
86
108
  type: 'confirm',
87
109
  name: 'doUpdate',
88
110
  message: '是否立即更新并重启?',
89
- default: false,
90
- },
111
+ default: false
112
+ }
91
113
  ]);
92
114
 
93
115
  if (!doUpdate) return;
@@ -95,8 +117,8 @@ async function checkForUpdates({ packageName, currentVersion }) {
95
117
  console.log(chalk.yellow('开始更新,请稍候...'));
96
118
  await new Promise((resolve) => {
97
119
  const child = spawn('npm', ['i', '-g', `${packageName}@latest`], {
98
- shell: process.platform === 'win32',
99
- stdio: 'inherit',
120
+ shell: false,
121
+ stdio: 'inherit'
100
122
  });
101
123
  child.on('close', (code) => resolve(code === 0));
102
124
  }).then((ok) => {
@@ -105,9 +127,15 @@ async function checkForUpdates({ packageName, currentVersion }) {
105
127
  return;
106
128
  }
107
129
  console.log(chalk.green('更新成功,正在重启...'));
108
- const child = spawn('cc', process.argv.slice(2), {
109
- shell: true,
110
- stdio: 'inherit',
130
+ const scriptPath = process.argv[1];
131
+ const restartCommand = scriptPath ? process.execPath : packageName;
132
+ const restartArgs = scriptPath
133
+ ? [scriptPath, ...process.argv.slice(2)]
134
+ : process.argv.slice(2);
135
+
136
+ const child = spawn(restartCommand, restartArgs, {
137
+ shell: false,
138
+ stdio: 'inherit'
111
139
  });
112
140
  child.on('close', (code) => {
113
141
  process.exit(code || 0);
@@ -115,6 +143,7 @@ async function checkForUpdates({ packageName, currentVersion }) {
115
143
  });
116
144
  }
117
145
  } catch {
146
+ // 更新检查必须静默失败,避免影响主命令执行。
118
147
  }
119
148
  }
120
149