@yivan-lab/pretty-please 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 (86) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +380 -0
  3. package/bin/pls.js +681 -0
  4. package/bin/pls.tsx +541 -0
  5. package/dist/bin/pls.d.ts +2 -0
  6. package/dist/bin/pls.js +429 -0
  7. package/dist/src/ai.d.ts +48 -0
  8. package/dist/src/ai.js +295 -0
  9. package/dist/src/builtin-detector.d.ts +15 -0
  10. package/dist/src/builtin-detector.js +83 -0
  11. package/dist/src/chat-history.d.ts +26 -0
  12. package/dist/src/chat-history.js +81 -0
  13. package/dist/src/components/Chat.d.ts +13 -0
  14. package/dist/src/components/Chat.js +80 -0
  15. package/dist/src/components/ChatStatus.d.ts +9 -0
  16. package/dist/src/components/ChatStatus.js +34 -0
  17. package/dist/src/components/CodeColorizer.d.ts +12 -0
  18. package/dist/src/components/CodeColorizer.js +82 -0
  19. package/dist/src/components/CommandBox.d.ts +10 -0
  20. package/dist/src/components/CommandBox.js +45 -0
  21. package/dist/src/components/CommandGenerator.d.ts +20 -0
  22. package/dist/src/components/CommandGenerator.js +116 -0
  23. package/dist/src/components/ConfigDisplay.d.ts +9 -0
  24. package/dist/src/components/ConfigDisplay.js +42 -0
  25. package/dist/src/components/ConfigWizard.d.ts +9 -0
  26. package/dist/src/components/ConfigWizard.js +72 -0
  27. package/dist/src/components/ConfirmationPrompt.d.ts +12 -0
  28. package/dist/src/components/ConfirmationPrompt.js +26 -0
  29. package/dist/src/components/Duration.d.ts +9 -0
  30. package/dist/src/components/Duration.js +21 -0
  31. package/dist/src/components/HistoryDisplay.d.ts +9 -0
  32. package/dist/src/components/HistoryDisplay.js +51 -0
  33. package/dist/src/components/HookManager.d.ts +10 -0
  34. package/dist/src/components/HookManager.js +88 -0
  35. package/dist/src/components/InlineRenderer.d.ts +12 -0
  36. package/dist/src/components/InlineRenderer.js +75 -0
  37. package/dist/src/components/MarkdownDisplay.d.ts +13 -0
  38. package/dist/src/components/MarkdownDisplay.js +197 -0
  39. package/dist/src/components/MultiStepCommandGenerator.d.ts +25 -0
  40. package/dist/src/components/MultiStepCommandGenerator.js +142 -0
  41. package/dist/src/components/TableRenderer.d.ts +12 -0
  42. package/dist/src/components/TableRenderer.js +66 -0
  43. package/dist/src/config.d.ts +29 -0
  44. package/dist/src/config.js +203 -0
  45. package/dist/src/history.d.ts +20 -0
  46. package/dist/src/history.js +113 -0
  47. package/dist/src/mastra-agent.d.ts +7 -0
  48. package/dist/src/mastra-agent.js +31 -0
  49. package/dist/src/multi-step.d.ts +41 -0
  50. package/dist/src/multi-step.js +67 -0
  51. package/dist/src/shell-hook.d.ts +35 -0
  52. package/dist/src/shell-hook.js +348 -0
  53. package/dist/src/sysinfo.d.ts +15 -0
  54. package/dist/src/sysinfo.js +52 -0
  55. package/dist/src/ui/theme.d.ts +26 -0
  56. package/dist/src/ui/theme.js +31 -0
  57. package/dist/src/utils/console.d.ts +44 -0
  58. package/dist/src/utils/console.js +114 -0
  59. package/package.json +78 -0
  60. package/src/ai.js +324 -0
  61. package/src/builtin-detector.js +98 -0
  62. package/src/chat-history.js +94 -0
  63. package/src/components/Chat.tsx +122 -0
  64. package/src/components/ChatStatus.tsx +53 -0
  65. package/src/components/CodeColorizer.tsx +128 -0
  66. package/src/components/CommandBox.tsx +60 -0
  67. package/src/components/CommandGenerator.tsx +184 -0
  68. package/src/components/ConfigDisplay.tsx +64 -0
  69. package/src/components/ConfigWizard.tsx +101 -0
  70. package/src/components/ConfirmationPrompt.tsx +41 -0
  71. package/src/components/Duration.tsx +24 -0
  72. package/src/components/HistoryDisplay.tsx +69 -0
  73. package/src/components/HookManager.tsx +150 -0
  74. package/src/components/InlineRenderer.tsx +123 -0
  75. package/src/components/MarkdownDisplay.tsx +288 -0
  76. package/src/components/MultiStepCommandGenerator.tsx +229 -0
  77. package/src/components/TableRenderer.tsx +110 -0
  78. package/src/config.js +221 -0
  79. package/src/history.js +131 -0
  80. package/src/mastra-agent.ts +35 -0
  81. package/src/multi-step.ts +93 -0
  82. package/src/shell-hook.js +393 -0
  83. package/src/sysinfo.js +57 -0
  84. package/src/ui/theme.ts +37 -0
  85. package/src/utils/console.js +130 -0
  86. package/tsconfig.json +23 -0
@@ -0,0 +1,348 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import chalk from 'chalk';
5
+ import { CONFIG_DIR, getConfig, setConfigValue } from './config.js';
6
+ import { getHistory } from './history.js';
7
+ const SHELL_HISTORY_FILE = path.join(CONFIG_DIR, 'shell_history.jsonl');
8
+ const MAX_SHELL_HISTORY = 20;
9
+ // Hook 标记,用于识别我们添加的内容
10
+ const HOOK_START_MARKER = '# >>> pretty-please shell hook >>>';
11
+ const HOOK_END_MARKER = '# <<< pretty-please shell hook <<<';
12
+ /**
13
+ * 检测当前 shell 类型
14
+ */
15
+ export function detectShell() {
16
+ const shell = process.env.SHELL || '';
17
+ if (shell.includes('zsh'))
18
+ return 'zsh';
19
+ if (shell.includes('bash'))
20
+ return 'bash';
21
+ // Windows PowerShell
22
+ if (process.platform === 'win32')
23
+ return 'powershell';
24
+ return 'unknown';
25
+ }
26
+ /**
27
+ * 获取 shell 配置文件路径
28
+ */
29
+ export function getShellConfigPath(shellType) {
30
+ const home = os.homedir();
31
+ switch (shellType) {
32
+ case 'zsh':
33
+ return path.join(home, '.zshrc');
34
+ case 'bash':
35
+ // macOS 使用 .bash_profile,Linux 使用 .bashrc
36
+ if (process.platform === 'darwin') {
37
+ return path.join(home, '.bash_profile');
38
+ }
39
+ return path.join(home, '.bashrc');
40
+ case 'powershell':
41
+ // PowerShell profile 路径
42
+ return path.join(home, 'Documents', 'PowerShell', 'Microsoft.PowerShell_profile.ps1');
43
+ default:
44
+ return null;
45
+ }
46
+ }
47
+ /**
48
+ * 生成 zsh hook 脚本
49
+ */
50
+ function generateZshHook() {
51
+ return `
52
+ ${HOOK_START_MARKER}
53
+ # 记录命令到 pretty-please 历史
54
+ __pls_preexec() {
55
+ __PLS_LAST_CMD="$1"
56
+ __PLS_CMD_START=$(date +%s)
57
+ }
58
+
59
+ __pls_precmd() {
60
+ local exit_code=$?
61
+ if [[ -n "$__PLS_LAST_CMD" ]]; then
62
+ local end_time=$(date +%s)
63
+ local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
64
+ # 转义命令中的特殊字符
65
+ local escaped_cmd=$(echo "$__PLS_LAST_CMD" | sed 's/\\\\/\\\\\\\\/g; s/"/\\\\"/g')
66
+ echo "{\\"cmd\\":\\"$escaped_cmd\\",\\"exit\\":$exit_code,\\"time\\":\\"$timestamp\\"}" >> "${CONFIG_DIR}/shell_history.jsonl"
67
+ # 保持文件不超过 ${MAX_SHELL_HISTORY} 行
68
+ tail -n ${MAX_SHELL_HISTORY} "${CONFIG_DIR}/shell_history.jsonl" > "${CONFIG_DIR}/shell_history.jsonl.tmp" && mv "${CONFIG_DIR}/shell_history.jsonl.tmp" "${CONFIG_DIR}/shell_history.jsonl"
69
+ unset __PLS_LAST_CMD
70
+ fi
71
+ }
72
+
73
+ autoload -Uz add-zsh-hook
74
+ add-zsh-hook preexec __pls_preexec
75
+ add-zsh-hook precmd __pls_precmd
76
+ ${HOOK_END_MARKER}
77
+ `;
78
+ }
79
+ /**
80
+ * 生成 bash hook 脚本
81
+ */
82
+ function generateBashHook() {
83
+ return `
84
+ ${HOOK_START_MARKER}
85
+ # 记录命令到 pretty-please 历史
86
+ __pls_prompt_command() {
87
+ local exit_code=$?
88
+ local last_cmd=$(history 1 | sed 's/^ *[0-9]* *//')
89
+ if [[ -n "$last_cmd" && "$last_cmd" != "$__PLS_LAST_CMD" ]]; then
90
+ __PLS_LAST_CMD="$last_cmd"
91
+ local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
92
+ local escaped_cmd=$(echo "$last_cmd" | sed 's/\\\\/\\\\\\\\/g; s/"/\\\\"/g')
93
+ echo "{\\"cmd\\":\\"$escaped_cmd\\",\\"exit\\":$exit_code,\\"time\\":\\"$timestamp\\"}" >> "${CONFIG_DIR}/shell_history.jsonl"
94
+ tail -n ${MAX_SHELL_HISTORY} "${CONFIG_DIR}/shell_history.jsonl" > "${CONFIG_DIR}/shell_history.jsonl.tmp" && mv "${CONFIG_DIR}/shell_history.jsonl.tmp" "${CONFIG_DIR}/shell_history.jsonl"
95
+ fi
96
+ }
97
+
98
+ if [[ ! "$PROMPT_COMMAND" =~ __pls_prompt_command ]]; then
99
+ PROMPT_COMMAND="__pls_prompt_command;\${PROMPT_COMMAND}"
100
+ fi
101
+ ${HOOK_END_MARKER}
102
+ `;
103
+ }
104
+ /**
105
+ * 生成 PowerShell hook 脚本
106
+ */
107
+ function generatePowerShellHook() {
108
+ return `
109
+ ${HOOK_START_MARKER}
110
+ # 记录命令到 pretty-please 历史
111
+ $Global:__PlsLastCmd = ""
112
+
113
+ function __Pls_RecordCommand {
114
+ $lastCmd = (Get-History -Count 1).CommandLine
115
+ if ($lastCmd -and $lastCmd -ne $Global:__PlsLastCmd) {
116
+ $Global:__PlsLastCmd = $lastCmd
117
+ $exitCode = $LASTEXITCODE
118
+ if ($null -eq $exitCode) { $exitCode = 0 }
119
+ $timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
120
+ $escapedCmd = $lastCmd -replace '\\\\', '\\\\\\\\' -replace '"', '\\\\"'
121
+ $json = "{\`"cmd\`":\`"$escapedCmd\`",\`"exit\`":$exitCode,\`"time\`":\`"$timestamp\`"}"
122
+ Add-Content -Path "${CONFIG_DIR}/shell_history.jsonl" -Value $json
123
+ # 保持文件不超过 ${MAX_SHELL_HISTORY} 行
124
+ $content = Get-Content "${CONFIG_DIR}/shell_history.jsonl" -Tail ${MAX_SHELL_HISTORY}
125
+ $content | Set-Content "${CONFIG_DIR}/shell_history.jsonl"
126
+ }
127
+ }
128
+
129
+ if (-not (Get-Variable -Name __PlsPromptBackup -ErrorAction SilentlyContinue)) {
130
+ $Global:__PlsPromptBackup = $function:prompt
131
+ function Global:prompt {
132
+ __Pls_RecordCommand
133
+ & $Global:__PlsPromptBackup
134
+ }
135
+ }
136
+ ${HOOK_END_MARKER}
137
+ `;
138
+ }
139
+ /**
140
+ * 生成 hook 脚本
141
+ */
142
+ function generateHookScript(shellType) {
143
+ switch (shellType) {
144
+ case 'zsh':
145
+ return generateZshHook();
146
+ case 'bash':
147
+ return generateBashHook();
148
+ case 'powershell':
149
+ return generatePowerShellHook();
150
+ default:
151
+ return null;
152
+ }
153
+ }
154
+ /**
155
+ * 安装 shell hook
156
+ */
157
+ export async function installShellHook() {
158
+ const shellType = detectShell();
159
+ const configPath = getShellConfigPath(shellType);
160
+ if (!configPath) {
161
+ console.log(chalk.red(`❌ 不支持的 shell 类型: ${shellType}`));
162
+ return false;
163
+ }
164
+ const hookScript = generateHookScript(shellType);
165
+ if (!hookScript) {
166
+ console.log(chalk.red(`❌ 无法为 ${shellType} 生成 hook 脚本`));
167
+ return false;
168
+ }
169
+ // 检查是否已安装
170
+ if (fs.existsSync(configPath)) {
171
+ const content = fs.readFileSync(configPath, 'utf-8');
172
+ if (content.includes(HOOK_START_MARKER)) {
173
+ console.log(chalk.yellow('⚠️ Shell hook 已安装,跳过'));
174
+ setConfigValue('shellHook', true);
175
+ return true;
176
+ }
177
+ }
178
+ // 确保配置目录存在
179
+ if (!fs.existsSync(CONFIG_DIR)) {
180
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
181
+ }
182
+ // 备份原配置文件
183
+ if (fs.existsSync(configPath)) {
184
+ const backupPath = configPath + '.pls-backup';
185
+ fs.copyFileSync(configPath, backupPath);
186
+ console.log(chalk.gray(`已备份原配置文件到: ${backupPath}`));
187
+ }
188
+ // 追加 hook 脚本
189
+ fs.appendFileSync(configPath, hookScript);
190
+ // 更新配置
191
+ setConfigValue('shellHook', true);
192
+ console.log(chalk.green(`✅ Shell hook 已安装到: ${configPath}`));
193
+ console.log(chalk.yellow('⚠️ 请重启终端或执行以下命令使其生效:'));
194
+ console.log(chalk.cyan(` source ${configPath}`));
195
+ return true;
196
+ }
197
+ /**
198
+ * 卸载 shell hook
199
+ */
200
+ export function uninstallShellHook() {
201
+ const shellType = detectShell();
202
+ const configPath = getShellConfigPath(shellType);
203
+ if (!configPath || !fs.existsSync(configPath)) {
204
+ console.log(chalk.yellow('⚠️ 未找到 shell 配置文件'));
205
+ setConfigValue('shellHook', false);
206
+ return true;
207
+ }
208
+ let content = fs.readFileSync(configPath, 'utf-8');
209
+ // 移除 hook 脚本
210
+ const startIndex = content.indexOf(HOOK_START_MARKER);
211
+ const endIndex = content.indexOf(HOOK_END_MARKER);
212
+ if (startIndex === -1 || endIndex === -1) {
213
+ console.log(chalk.yellow('⚠️ 未找到已安装的 hook'));
214
+ setConfigValue('shellHook', false);
215
+ return true;
216
+ }
217
+ // 移除从标记开始到结束的所有内容(包括换行符)
218
+ const before = content.substring(0, startIndex);
219
+ const after = content.substring(endIndex + HOOK_END_MARKER.length);
220
+ content = before + after.replace(/^\n/, '');
221
+ fs.writeFileSync(configPath, content);
222
+ setConfigValue('shellHook', false);
223
+ // 清空 shell 历史文件
224
+ if (fs.existsSync(SHELL_HISTORY_FILE)) {
225
+ fs.unlinkSync(SHELL_HISTORY_FILE);
226
+ }
227
+ console.log(chalk.green('✅ Shell hook 已卸载'));
228
+ console.log(chalk.yellow('⚠️ 请重启终端使其生效'));
229
+ return true;
230
+ }
231
+ /**
232
+ * 读取 shell 历史记录
233
+ */
234
+ export function getShellHistory() {
235
+ const config = getConfig();
236
+ // 如果未启用 shell hook,返回空数组
237
+ if (!config.shellHook) {
238
+ return [];
239
+ }
240
+ if (!fs.existsSync(SHELL_HISTORY_FILE)) {
241
+ return [];
242
+ }
243
+ try {
244
+ const content = fs.readFileSync(SHELL_HISTORY_FILE, 'utf-8');
245
+ const lines = content.trim().split('\n').filter(line => line.trim());
246
+ return lines.map(line => {
247
+ try {
248
+ return JSON.parse(line);
249
+ }
250
+ catch {
251
+ return null;
252
+ }
253
+ }).filter(Boolean);
254
+ }
255
+ catch {
256
+ return [];
257
+ }
258
+ }
259
+ /**
260
+ * 从 pls history 中查找匹配的记录
261
+ * @param {string} prompt - pls 命令后面的 prompt 部分
262
+ * @returns {object|null} 匹配的 pls history 记录
263
+ */
264
+ function findPlsHistoryMatch(prompt) {
265
+ const plsHistory = getHistory();
266
+ // 尝试精确匹配 userPrompt
267
+ for (const record of plsHistory) {
268
+ if (record.userPrompt === prompt) {
269
+ return record;
270
+ }
271
+ }
272
+ // 尝试模糊匹配(处理引号等情况)
273
+ const normalizedPrompt = prompt.trim().replace(/^["']|["']$/g, '');
274
+ for (const record of plsHistory) {
275
+ if (record.userPrompt === normalizedPrompt) {
276
+ return record;
277
+ }
278
+ }
279
+ return null;
280
+ }
281
+ /**
282
+ * 格式化 shell 历史供 AI 使用
283
+ * 对于 pls 命令,会从 pls history 中查找对应的详细信息
284
+ */
285
+ export function formatShellHistoryForAI() {
286
+ const history = getShellHistory();
287
+ if (history.length === 0) {
288
+ return '';
289
+ }
290
+ // pls 的子命令列表(这些不是 AI prompt)
291
+ const plsSubcommands = ['config', 'history', 'hook', 'help', '--help', '-h', '--version', '-v'];
292
+ const lines = history.map((item, index) => {
293
+ const status = item.exit === 0 ? '✓' : `✗ 退出码:${item.exit}`;
294
+ // 检查是否是 pls 命令
295
+ const plsMatch = item.cmd.match(/^(pls|please)\s+(.+)$/);
296
+ if (plsMatch) {
297
+ let args = plsMatch[2];
298
+ // 去掉 --debug / -d 选项,获取真正的参数
299
+ args = args.replace(/^(--debug|-d)\s+/, '');
300
+ const firstArg = args.split(/\s+/)[0];
301
+ // 如果是子命令,当作普通命令处理
302
+ if (plsSubcommands.includes(firstArg)) {
303
+ return `${index + 1}. ${item.cmd} ${status}`;
304
+ }
305
+ // 是 AI prompt,尝试从 pls history 查找详细信息
306
+ const prompt = args;
307
+ const plsRecord = findPlsHistoryMatch(prompt);
308
+ if (plsRecord) {
309
+ // 找到对应的 pls 记录,展示详细信息
310
+ if (plsRecord.reason === 'builtin') {
311
+ return `${index + 1}. [pls] "${prompt}" → 生成命令: ${plsRecord.command} (包含 builtin,未执行)`;
312
+ }
313
+ else if (plsRecord.executed) {
314
+ const execStatus = plsRecord.exitCode === 0 ? '✓' : `✗ 退出码:${plsRecord.exitCode}`;
315
+ return `${index + 1}. [pls] "${prompt}" → 实际执行: ${plsRecord.command} ${execStatus}`;
316
+ }
317
+ else {
318
+ return `${index + 1}. [pls] "${prompt}" → 生成命令: ${plsRecord.command} (用户取消执行)`;
319
+ }
320
+ }
321
+ // 找不到记录,只显示原始命令
322
+ return `${index + 1}. [pls] "${prompt}" ${status}`;
323
+ }
324
+ // 普通命令
325
+ return `${index + 1}. ${item.cmd} ${status}`;
326
+ });
327
+ return `【用户终端最近执行的命令】\n${lines.join('\n')}`;
328
+ }
329
+ /**
330
+ * 获取 hook 状态
331
+ */
332
+ export function getHookStatus() {
333
+ const config = getConfig();
334
+ const shellType = detectShell();
335
+ const configPath = getShellConfigPath(shellType);
336
+ let installed = false;
337
+ if (configPath && fs.existsSync(configPath)) {
338
+ const content = fs.readFileSync(configPath, 'utf-8');
339
+ installed = content.includes(HOOK_START_MARKER);
340
+ }
341
+ return {
342
+ enabled: config.shellHook,
343
+ installed,
344
+ shellType,
345
+ configPath,
346
+ historyFile: SHELL_HISTORY_FILE
347
+ };
348
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * 收集系统信息
3
+ */
4
+ export function collectSystemInfo(): {
5
+ os: NodeJS.Platform;
6
+ arch: NodeJS.Architecture;
7
+ shell: string;
8
+ packageManager: string;
9
+ cwd: string;
10
+ user: string;
11
+ };
12
+ /**
13
+ * 将系统信息格式化为字符串(供 AI 使用)
14
+ */
15
+ export function formatSystemInfo(): string;
@@ -0,0 +1,52 @@
1
+ import os from 'os';
2
+ import { execSync } from 'child_process';
3
+ /**
4
+ * 检测包管理器
5
+ */
6
+ function detectPackageManager() {
7
+ const managers = [
8
+ { name: 'brew', command: 'brew' },
9
+ { name: 'apt', command: 'apt-get' },
10
+ { name: 'dnf', command: 'dnf' },
11
+ { name: 'yum', command: 'yum' },
12
+ { name: 'pacman', command: 'pacman' },
13
+ { name: 'zypper', command: 'zypper' },
14
+ { name: 'apk', command: 'apk' }
15
+ ];
16
+ for (const mgr of managers) {
17
+ try {
18
+ execSync(`which ${mgr.command}`, { stdio: 'ignore' });
19
+ return mgr.name;
20
+ }
21
+ catch {
22
+ // 继续检测下一个
23
+ }
24
+ }
25
+ return 'unknown';
26
+ }
27
+ /**
28
+ * 获取当前 Shell
29
+ */
30
+ function getCurrentShell() {
31
+ return process.env.SHELL || 'unknown';
32
+ }
33
+ /**
34
+ * 收集系统信息
35
+ */
36
+ export function collectSystemInfo() {
37
+ return {
38
+ os: os.platform(),
39
+ arch: os.arch(),
40
+ shell: getCurrentShell(),
41
+ packageManager: detectPackageManager(),
42
+ cwd: process.cwd(),
43
+ user: os.userInfo().username
44
+ };
45
+ }
46
+ /**
47
+ * 将系统信息格式化为字符串(供 AI 使用)
48
+ */
49
+ export function formatSystemInfo() {
50
+ const info = collectSystemInfo();
51
+ return `OS: ${info.os}, Arch: ${info.arch}, Shell: ${info.shell}, PkgMgr: ${info.packageManager}, CWD: ${info.cwd}`;
52
+ }
@@ -0,0 +1,26 @@
1
+ export declare const theme: {
2
+ readonly primary: "#00D9FF";
3
+ readonly secondary: "#A78BFA";
4
+ readonly accent: "#F472B6";
5
+ readonly success: "#10B981";
6
+ readonly error: "#EF4444";
7
+ readonly warning: "#F59E0B";
8
+ readonly info: "#3B82F6";
9
+ readonly text: {
10
+ readonly primary: "#E5E7EB";
11
+ readonly secondary: "#9CA3AF";
12
+ readonly muted: "#6B7280";
13
+ readonly dim: "#4B5563";
14
+ };
15
+ readonly border: "#374151";
16
+ readonly divider: "#1F2937";
17
+ readonly code: {
18
+ readonly background: "#1F2937";
19
+ readonly text: "#E5E7EB";
20
+ readonly keyword: "#C678DD";
21
+ readonly string: "#98C379";
22
+ readonly function: "#61AFEF";
23
+ readonly comment: "#5C6370";
24
+ };
25
+ };
26
+ export type Theme = typeof theme;
@@ -0,0 +1,31 @@
1
+ // 主题配置 - 优雅的配色方案
2
+ export const theme = {
3
+ // 主色调
4
+ primary: '#00D9FF', // 青色 - 主要交互元素
5
+ secondary: '#A78BFA', // 紫色 - 次要元素
6
+ accent: '#F472B6', // 粉色 - 强调元素
7
+ // 状态色
8
+ success: '#10B981', // 绿色 - 成功
9
+ error: '#EF4444', // 红色 - 错误
10
+ warning: '#F59E0B', // 橙色 - 警告
11
+ info: '#3B82F6', // 蓝色 - 信息
12
+ // 文本色
13
+ text: {
14
+ primary: '#E5E7EB', // 主文本
15
+ secondary: '#9CA3AF', // 次要文本
16
+ muted: '#6B7280', // 弱化文本
17
+ dim: '#4B5563', // 暗淡文本
18
+ },
19
+ // 边框和分隔
20
+ border: '#374151', // 边框色
21
+ divider: '#1F2937', // 分隔线
22
+ // 代码相关
23
+ code: {
24
+ background: '#1F2937',
25
+ text: '#E5E7EB',
26
+ keyword: '#C678DD',
27
+ string: '#98C379',
28
+ function: '#61AFEF',
29
+ comment: '#5C6370',
30
+ }
31
+ };
@@ -0,0 +1,44 @@
1
+ /**
2
+ * 计算字符串的显示宽度(中文占2个宽度)
3
+ */
4
+ export function getDisplayWidth(str: any): number;
5
+ /**
6
+ * 绘制命令框(原生版本)
7
+ */
8
+ export function drawCommandBox(command: any, title?: string): void;
9
+ /**
10
+ * 格式化耗时
11
+ */
12
+ export function formatDuration(ms: any): string;
13
+ /**
14
+ * 输出分隔线
15
+ */
16
+ export function printSeparator(text?: string, length?: number): void;
17
+ /**
18
+ * 输出成功消息
19
+ */
20
+ export function success(message: any): void;
21
+ /**
22
+ * 输出错误消息
23
+ */
24
+ export function error(message: any): void;
25
+ /**
26
+ * 输出警告消息
27
+ */
28
+ export function warning(message: any): void;
29
+ /**
30
+ * 输出信息消息
31
+ */
32
+ export function info(message: any): void;
33
+ /**
34
+ * 输出灰色文本
35
+ */
36
+ export function muted(message: any): void;
37
+ /**
38
+ * 输出标题
39
+ */
40
+ export function title(message: any): void;
41
+ /**
42
+ * 输出主色文本
43
+ */
44
+ export function primary(message: any): void;
@@ -0,0 +1,114 @@
1
+ import chalk from 'chalk';
2
+ /**
3
+ * 原生控制台输出工具函数
4
+ * 用于不需要 Ink 的场景,避免清屏和性能问题
5
+ */
6
+ // 主题色
7
+ const colors = {
8
+ primary: '#00D9FF',
9
+ secondary: '#A78BFA',
10
+ accent: '#F472B6',
11
+ success: '#10B981',
12
+ error: '#EF4444',
13
+ warning: '#F59E0B',
14
+ info: '#3B82F6',
15
+ muted: '#6B7280',
16
+ };
17
+ /**
18
+ * 计算字符串的显示宽度(中文占2个宽度)
19
+ */
20
+ export function getDisplayWidth(str) {
21
+ let width = 0;
22
+ for (const char of str) {
23
+ if (char.match(/[\u4e00-\u9fff\u3400-\u4dbf\uff00-\uffef\u3000-\u303f]/)) {
24
+ width += 2;
25
+ }
26
+ else {
27
+ width += 1;
28
+ }
29
+ }
30
+ return width;
31
+ }
32
+ /**
33
+ * 绘制命令框(原生版本)
34
+ */
35
+ export function drawCommandBox(command, title = '生成命令') {
36
+ const lines = command.split('\n');
37
+ const titleWidth = getDisplayWidth(title);
38
+ const maxContentWidth = Math.max(...lines.map(l => getDisplayWidth(l)));
39
+ const boxWidth = Math.max(maxContentWidth + 4, titleWidth + 6, 20);
40
+ const topPadding = boxWidth - titleWidth - 5;
41
+ const topBorder = '┌─ ' + title + ' ' + '─'.repeat(topPadding) + '┐';
42
+ const bottomBorder = '└' + '─'.repeat(boxWidth - 2) + '┘';
43
+ console.log(chalk.hex(colors.warning)(topBorder));
44
+ for (const line of lines) {
45
+ const lineWidth = getDisplayWidth(line);
46
+ const padding = ' '.repeat(boxWidth - lineWidth - 4);
47
+ console.log(chalk.hex(colors.warning)('│ ') +
48
+ chalk.hex(colors.primary)(line) +
49
+ padding +
50
+ chalk.hex(colors.warning)(' │'));
51
+ }
52
+ console.log(chalk.hex(colors.warning)(bottomBorder));
53
+ }
54
+ /**
55
+ * 格式化耗时
56
+ */
57
+ export function formatDuration(ms) {
58
+ if (ms < 1000) {
59
+ return `${ms}ms`;
60
+ }
61
+ return `${(ms / 1000).toFixed(2)}s`;
62
+ }
63
+ /**
64
+ * 输出分隔线
65
+ */
66
+ export function printSeparator(text = '输出', length = 38) {
67
+ const textPart = text ? ` ${text} ` : '';
68
+ const lineLength = Math.max(0, length - textPart.length);
69
+ const leftDashes = '─'.repeat(Math.floor(lineLength / 2));
70
+ const rightDashes = '─'.repeat(Math.ceil(lineLength / 2));
71
+ console.log(chalk.gray(`${leftDashes}${textPart}${rightDashes}`));
72
+ }
73
+ /**
74
+ * 输出成功消息
75
+ */
76
+ export function success(message) {
77
+ console.log(chalk.hex(colors.success)('✓ ' + message));
78
+ }
79
+ /**
80
+ * 输出错误消息
81
+ */
82
+ export function error(message) {
83
+ console.log(chalk.hex(colors.error)('✗ ' + message));
84
+ }
85
+ /**
86
+ * 输出警告消息
87
+ */
88
+ export function warning(message) {
89
+ console.log(chalk.hex(colors.warning)('⚠️ ' + message));
90
+ }
91
+ /**
92
+ * 输出信息消息
93
+ */
94
+ export function info(message) {
95
+ console.log(chalk.hex(colors.info)(message));
96
+ }
97
+ /**
98
+ * 输出灰色文本
99
+ */
100
+ export function muted(message) {
101
+ console.log(chalk.hex(colors.muted)(message));
102
+ }
103
+ /**
104
+ * 输出标题
105
+ */
106
+ export function title(message) {
107
+ console.log(chalk.bold(message));
108
+ }
109
+ /**
110
+ * 输出主色文本
111
+ */
112
+ export function primary(message) {
113
+ console.log(chalk.hex(colors.primary)(message));
114
+ }