ops-toolkit 1.1.0 → 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.
package/docs/API.md ADDED
@@ -0,0 +1,850 @@
1
+ # Ops Toolkit API 文档
2
+
3
+ ## 核心 API
4
+
5
+ ### CLIApp
6
+
7
+ CLI应用程序主类,负责整个系统的初始化和运行。
8
+
9
+ ```typescript
10
+ import { CLIApp } from '@/cli/app';
11
+
12
+ const app = new CLIApp(version);
13
+ await app.initialize();
14
+ await app.start();
15
+ ```
16
+
17
+ #### 构造函数
18
+
19
+ ```typescript
20
+ constructor(version?: string)
21
+ ```
22
+
23
+ **参数:**
24
+
25
+ - `version` (可选): 应用程序版本号
26
+
27
+ #### 方法
28
+
29
+ ##### `initialize()`
30
+
31
+ 初始化应用程序。
32
+
33
+ ```typescript
34
+ public async initialize(): Promise<void>
35
+ ```
36
+
37
+ **抛出异常:**
38
+
39
+ - `ConfigError`: 配置初始化失败
40
+ - `CLIError`: 系统初始化失败
41
+
42
+ ##### `start()`
43
+
44
+ 启动CLI应用程序。
45
+
46
+ ```typescript
47
+ public async start(): Promise<void>
48
+ ```
49
+
50
+ ### CommandRegistry
51
+
52
+ 命令注册系统,管理所有命令的注册和执行。
53
+
54
+ ```typescript
55
+ import { CommandRegistry, type CommandDefinition } from '@/cli/command-registry';
56
+
57
+ const registry = new CommandRegistry(program);
58
+ registry.register(commandDefinition);
59
+ ```
60
+
61
+ #### 接口定义
62
+
63
+ ```typescript
64
+ interface CommandDefinition {
65
+ name: string;
66
+ description: string;
67
+ alias?: string;
68
+ options?: CommandOption[];
69
+ subcommands?: CommandDefinition[];
70
+ action: (options: CommandOptions) => Promise<void> | void;
71
+ }
72
+
73
+ interface CommandOption {
74
+ flags: string;
75
+ description: string;
76
+ defaultValue?: string | boolean | string[];
77
+ }
78
+ ```
79
+
80
+ #### 方法
81
+
82
+ ##### `register()`
83
+
84
+ 注册单个命令。
85
+
86
+ ```typescript
87
+ public register(commandDef: CommandDefinition): void
88
+ ```
89
+
90
+ **参数:**
91
+
92
+ - `commandDef`: 命令定义对象
93
+
94
+ **抛出异常:**
95
+
96
+ - `Error`: 命令验证失败
97
+
98
+ ##### `registerMultiple()`
99
+
100
+ 批量注册命令。
101
+
102
+ ```typescript
103
+ public registerMultiple(commandDefs: CommandDefinition[]): void
104
+ ```
105
+
106
+ **参数:**
107
+
108
+ - `commandDefs`: 命令定义数组
109
+
110
+ ##### `getCommands()`
111
+
112
+ 获取所有已注册的命令。
113
+
114
+ ```typescript
115
+ public getCommands(): CommandDefinition[]
116
+ ```
117
+
118
+ **返回值:** 命令定义数组
119
+
120
+ ##### `getCommand()`
121
+
122
+ 根据名称获取命令。
123
+
124
+ ```typescript
125
+ public getCommand(name: string): CommandDefinition | undefined
126
+ ```
127
+
128
+ **参数:**
129
+
130
+ - `name`: 命令名称
131
+
132
+ **返回值:** 命令定义或undefined
133
+
134
+ ### CommandDiscovery
135
+
136
+ 命令发现器,自动扫描和加载命令模块。
137
+
138
+ ```typescript
139
+ import { CommandDiscovery } from '@/cli/command-discovery';
140
+
141
+ const discovery = new CommandDiscovery(registry);
142
+ await discovery.discoverAndRegister();
143
+ ```
144
+
145
+ #### 构造函数
146
+
147
+ ```typescript
148
+ constructor(commandRegistry: CommandRegistry, commandsDir?: string)
149
+ ```
150
+
151
+ **参数:**
152
+
153
+ - `commandRegistry`: 命令注册器实例
154
+ - `commandsDir` (可选): 命令目录路径
155
+
156
+ #### 方法
157
+
158
+ ##### `discoverAndRegister()`
159
+
160
+ 发现并注册所有命令。
161
+
162
+ ```typescript
163
+ public async discoverAndRegister(): Promise<void>
164
+ ```
165
+
166
+ ## 配置 API
167
+
168
+ ### ConfigManager
169
+
170
+ 配置管理系统,提供配置的加载、保存、验证等功能。
171
+
172
+ ```typescript
173
+ import { ConfigManager, type OpsConfig } from '@/utils/config';
174
+
175
+ await ConfigManager.initialize();
176
+ const config = ConfigManager.get();
177
+ await ConfigManager.set('monitor.refreshInterval', 3000);
178
+ ```
179
+
180
+ #### 接口定义
181
+
182
+ ```typescript
183
+ interface OpsConfig {
184
+ version?: string;
185
+ environment?: 'development' | 'production' | 'test';
186
+ monitor: {
187
+ refreshInterval: number;
188
+ showProcesses: boolean;
189
+ maxProcesses: number;
190
+ enableRealTime: boolean;
191
+ };
192
+ logs: {
193
+ defaultPath: string;
194
+ maxLines: number;
195
+ follow: boolean;
196
+ level: LogLevel;
197
+ enableFileLogging: boolean;
198
+ logDirectory: string;
199
+ };
200
+ deploy: {
201
+ defaultEnv: string;
202
+ backupEnabled: boolean;
203
+ confirmBeforeDeploy: boolean;
204
+ rollbackEnabled: boolean;
205
+ maxRetries: number;
206
+ };
207
+ system: {
208
+ showHiddenServices: boolean;
209
+ cacheTimeout: number;
210
+ enableNotifications: boolean;
211
+ };
212
+ ui: {
213
+ theme: string;
214
+ animations: boolean;
215
+ sound: boolean;
216
+ language: string;
217
+ };
218
+ }
219
+ ```
220
+
221
+ #### 静态方法
222
+
223
+ ##### `initialize()`
224
+
225
+ 初始化配置系统。
226
+
227
+ ```typescript
228
+ static async initialize(): Promise<void>
229
+ ```
230
+
231
+ **抛出异常:**
232
+
233
+ - `ConfigError`: 配置初始化失败
234
+
235
+ ##### `get()`
236
+
237
+ 获取配置值。
238
+
239
+ ```typescript
240
+ static get(): OpsConfig
241
+ static get<T>(key: string): T
242
+ ```
243
+
244
+ **参数:**
245
+
246
+ - `key` (可选): 配置键名,支持点分隔符
247
+
248
+ **返回值:** 配置对象或指定键的值
249
+
250
+ **示例:**
251
+
252
+ ```typescript
253
+ const fullConfig = ConfigManager.get();
254
+ const refreshInterval = ConfigManager.get<number>('monitor.refreshInterval');
255
+ ```
256
+
257
+ ##### `set()`
258
+
259
+ 设置配置值。
260
+
261
+ ```typescript
262
+ static async set<T>(key: string, value: T): Promise<void>
263
+ ```
264
+
265
+ **参数:**
266
+
267
+ - `key`: 配置键名,支持点分隔符
268
+ - `value`: 配置值
269
+
270
+ **抛出异常:**
271
+
272
+ - `ConfigError`: 配置设置失败
273
+
274
+ **示例:**
275
+
276
+ ```typescript
277
+ await ConfigManager.set('monitor.refreshInterval', 5000);
278
+ await ConfigManager.set('logs.level', LogLevel.DEBUG);
279
+ ```
280
+
281
+ ##### `reset()`
282
+
283
+ 重置配置为默认值。
284
+
285
+ ```typescript
286
+ static async reset(): Promise<void>
287
+ ```
288
+
289
+ ##### `reload()`
290
+
291
+ 重新加载配置文件。
292
+
293
+ ```typescript
294
+ static async reload(): Promise<void>
295
+ ```
296
+
297
+ ##### `registerValidator()`
298
+
299
+ 注册配置验证器。
300
+
301
+ ```typescript
302
+ static registerValidator(name: string, validator: ConfigValidator): void
303
+ ```
304
+
305
+ **参数:**
306
+
307
+ - `name`: 验证器名称
308
+ - `validator`: 验证器实例
309
+
310
+ ##### `cleanOldBackups()`
311
+
312
+ 清理旧的配置备份。
313
+
314
+ ```typescript
315
+ static async cleanOldBackups(maxBackups?: number): Promise<void>
316
+ ```
317
+
318
+ **参数:**
319
+
320
+ - `maxBackups` (可选): 最大备份数量,默认10
321
+
322
+ ## 日志 API
323
+
324
+ ### Logger
325
+
326
+ 增强的日志系统,支持多种日志级别和输出格式。
327
+
328
+ ```typescript
329
+ import { Logger, LogLevel } from '@/utils/logger';
330
+
331
+ // 基本使用
332
+ Logger.info('应用启动');
333
+ Logger.error('操作失败', error);
334
+ Logger.success('操作完成');
335
+
336
+ // 配置日志系统
337
+ Logger.configure({
338
+ level: LogLevel.DEBUG,
339
+ enableFileLogging: true,
340
+ logDirectory: './logs',
341
+ });
342
+ ```
343
+
344
+ #### 日志级别
345
+
346
+ ```typescript
347
+ enum LogLevel {
348
+ DEBUG = 0,
349
+ INFO = 1,
350
+ WARN = 2,
351
+ ERROR = 3,
352
+ CRITICAL = 4,
353
+ }
354
+ ```
355
+
356
+ #### 静态方法
357
+
358
+ ##### `configure()`
359
+
360
+ 配置日志系统。
361
+
362
+ ```typescript
363
+ static configure(config: Partial<LogConfig>): void
364
+ ```
365
+
366
+ **参数:**
367
+
368
+ - `config`: 日志配置对象
369
+
370
+ **配置接口:**
371
+
372
+ ```typescript
373
+ interface LogConfig {
374
+ level: LogLevel;
375
+ enableFileLogging: boolean;
376
+ logDirectory: string;
377
+ maxFileSize: number;
378
+ maxFiles: number;
379
+ enableConsoleColors: boolean;
380
+ enableStructuredOutput: boolean;
381
+ }
382
+ ```
383
+
384
+ ##### `debug()`
385
+
386
+ 记录调试日志。
387
+
388
+ ```typescript
389
+ static debug(message: string, context?: Record<string, unknown>, module?: string): void
390
+ ```
391
+
392
+ ##### `info()`
393
+
394
+ 记录信息日志。
395
+
396
+ ```typescript
397
+ static info(message: string, context?: Record<string, unknown>, module?: string): void
398
+ ```
399
+
400
+ ##### `warn()`
401
+
402
+ 记录警告日志。
403
+
404
+ ```typescript
405
+ static warn(message: string, context?: Record<string, unknown>, module?: string): void
406
+ ```
407
+
408
+ ##### `warning()`
409
+
410
+ 记录警告日志(别名)。
411
+
412
+ ```typescript
413
+ static warning(message: string, context?: Record<string, unknown>, module?: string): void
414
+ ```
415
+
416
+ ##### `error()`
417
+
418
+ 记录错误日志。
419
+
420
+ ```typescript
421
+ static error(message: string, error?: Error | unknown, context?: Record<string, unknown>, module?: string): void
422
+ ```
423
+
424
+ ##### `critical()`
425
+
426
+ 记录严重错误日志。
427
+
428
+ ```typescript
429
+ static critical(message: string, error?: Error | unknown, context?: Record<string, unknown>, module?: string): void
430
+ ```
431
+
432
+ ##### `success()`
433
+
434
+ 记录成功日志(带绿色标记)。
435
+
436
+ ```typescript
437
+ static success(message: string, context?: Record<string, unknown>, module?: string): void
438
+ ```
439
+
440
+ ##### `showTitle()`
441
+
442
+ 显示标题。
443
+
444
+ ```typescript
445
+ static showTitle(text: string, font?: string): void
446
+ ```
447
+
448
+ ##### `showBox()`
449
+
450
+ 显示带边框的文本。
451
+
452
+ ```typescript
453
+ static showBox(content: string, options?: Record<string, unknown>): void
454
+ ```
455
+
456
+ ##### `spinner()`
457
+
458
+ 创建加载动画。
459
+
460
+ ```typescript
461
+ static spinner(message: string): Spinner
462
+ ```
463
+
464
+ **返回值:** Spinner对象,包含start、stop、succeed等方法
465
+
466
+ ##### `getLogBuffer()`
467
+
468
+ 获取日志缓冲区。
469
+
470
+ ```typescript
471
+ static getLogBuffer(): LogEntry[]
472
+ ```
473
+
474
+ ##### `setLevel()`
475
+
476
+ 设置日志级别。
477
+
478
+ ```typescript
479
+ static setLevel(level: LogLevel): void
480
+ ```
481
+
482
+ ##### `enableFileLogging()`
483
+
484
+ 启用文件日志。
485
+
486
+ ```typescript
487
+ static enableFileLogging(directory?: string): void
488
+ ```
489
+
490
+ ## 错误处理 API
491
+
492
+ ### 自定义错误类
493
+
494
+ ```typescript
495
+ import { CLIError, CommandError, ConfigError, SystemError } from '@/utils/error-handlers';
496
+
497
+ // 创建自定义错误
498
+ const error = new CLIError('CLI操作失败', 'CUSTOM_ERROR', 2);
499
+ const cmdError = new CommandError('命令执行失败', 'my-command');
500
+ const cfgError = new ConfigError('配置项无效');
501
+ const sysError = new SystemError('系统资源不足');
502
+ ```
503
+
504
+ #### CLIError
505
+
506
+ 基础CLI错误类。
507
+
508
+ ```typescript
509
+ class CLIError extends Error {
510
+ public readonly code: string;
511
+ public readonly exitCode: number;
512
+
513
+ constructor(message: string, code?: string, exitCode?: number);
514
+ }
515
+ ```
516
+
517
+ #### CommandError
518
+
519
+ 命令执行错误。
520
+
521
+ ```typescript
522
+ class CommandError extends CLIError {
523
+ constructor(message: string, command?: string);
524
+ }
525
+ ```
526
+
527
+ #### ConfigError
528
+
529
+ 配置相关错误。
530
+
531
+ ```typescript
532
+ class ConfigError extends CLIError {
533
+ constructor(message: string);
534
+ }
535
+ ```
536
+
537
+ #### SystemError
538
+
539
+ 系统级错误。
540
+
541
+ ```typescript
542
+ class SystemError extends CLIError {
543
+ constructor(message: string);
544
+ }
545
+ ```
546
+
547
+ ### 错误处理函数
548
+
549
+ ```typescript
550
+ import { errorHandler, withAsyncErrorHandling, setupErrorHandlers } from '@/utils/error-handlers';
551
+
552
+ // 设置全局错误处理
553
+ setupErrorHandlers();
554
+
555
+ // 直接处理错误
556
+ try {
557
+ // 业务逻辑
558
+ } catch (error) {
559
+ errorHandler(
560
+ error,
561
+ {
562
+ command: 'my-command',
563
+ action: 'execute',
564
+ },
565
+ ErrorSeverity.MEDIUM
566
+ );
567
+ }
568
+
569
+ // 包装异步函数
570
+ const safeExecute = withAsyncErrorHandling(
571
+ async (input: string) => {
572
+ // 业务逻辑
573
+ },
574
+ { command: 'my-command' },
575
+ ErrorSeverity.LOW
576
+ );
577
+ ```
578
+
579
+ ### ErrorReporter
580
+
581
+ 错误报告系统。
582
+
583
+ ```typescript
584
+ import { ErrorReporter, ErrorSeverity } from '@/utils/error-reporter';
585
+
586
+ // 创建错误报告
587
+ const report = ErrorReporter.createReport(
588
+ 'ERROR_CODE',
589
+ '错误描述',
590
+ ErrorSeverity.HIGH,
591
+ { command: 'my-command' },
592
+ originalError
593
+ );
594
+
595
+ // 报告错误
596
+ ErrorReporter.report(report);
597
+
598
+ // 获取错误报告
599
+ const reports = ErrorReporter.getAllReports();
600
+ const specificReport = ErrorReporter.getReport(reportId);
601
+
602
+ // 解决错误
603
+ ErrorReporter.resolveReport(reportId);
604
+ ```
605
+
606
+ ## 系统工具 API
607
+
608
+ ### SystemUtils
609
+
610
+ 系统相关工具函数。
611
+
612
+ ```typescript
613
+ import { SystemUtils } from '@/utils/system';
614
+
615
+ // 获取系统信息
616
+ const systemInfo = await SystemUtils.getSystemInfo();
617
+
618
+ // 获取内存使用情况
619
+ const memoryUsage = SystemUtils.getMemoryUsage();
620
+
621
+ // 获取CPU使用率
622
+ const cpuUsage = await SystemUtils.getCpuUsage();
623
+
624
+ // 获取进程列表
625
+ const processes = await SystemUtils.getProcessList();
626
+
627
+ // 执行系统命令
628
+ const output = await SystemUtils.execCommand('ls -la');
629
+
630
+ // 格式化字节大小
631
+ const formatted = SystemUtils.formatBytes(1024 * 1024);
632
+
633
+ // 格式化运行时间
634
+ const uptime = SystemUtils.formatUptime(3600);
635
+ ```
636
+
637
+ #### 方法
638
+
639
+ ##### `getSystemInfo()`
640
+
641
+ 获取系统信息。
642
+
643
+ ```typescript
644
+ static async getSystemInfo(): Promise<{
645
+ hostname: string;
646
+ platform: string;
647
+ arch: string;
648
+ uptime: number;
649
+ loadAverage: number[];
650
+ totalMemory: number;
651
+ freeMemory: number;
652
+ cpus: os.CpuInfo[];
653
+ }>
654
+ ```
655
+
656
+ ##### `getMemoryUsage()`
657
+
658
+ 获取内存使用情况。
659
+
660
+ ```typescript
661
+ static getMemoryUsage(): {
662
+ total: number;
663
+ free: number;
664
+ used: number;
665
+ percentage: number;
666
+ }
667
+ ```
668
+
669
+ ##### `getCpuUsage()`
670
+
671
+ 获取CPU使用率。
672
+
673
+ ```typescript
674
+ static getCpuUsage(): Promise<number>
675
+ ```
676
+
677
+ ##### `getProcessList()`
678
+
679
+ 获取进程列表。
680
+
681
+ ```typescript
682
+ static async getProcessList(): Promise<Array<{
683
+ pid: number;
684
+ user: string;
685
+ cpu: number;
686
+ memory: number;
687
+ command: string;
688
+ }>>
689
+ ```
690
+
691
+ ##### `execCommand()`
692
+
693
+ 执行系统命令。
694
+
695
+ ```typescript
696
+ static async execCommand(command: string): Promise<string>
697
+ ```
698
+
699
+ ##### `formatBytes()`
700
+
701
+ 格式化字节大小。
702
+
703
+ ```typescript
704
+ static formatBytes(bytes: number): string
705
+ ```
706
+
707
+ ##### `formatUptime()`
708
+
709
+ 格式化运行时间。
710
+
711
+ ```typescript
712
+ static formatUptime(seconds: number): string
713
+ ```
714
+
715
+ ## 类型定义
716
+
717
+ ### CommandOptions
718
+
719
+ 命令选项类型。
720
+
721
+ ```typescript
722
+ interface CommandOptions {
723
+ [key: string]: string | boolean | number | undefined;
724
+ }
725
+ ```
726
+
727
+ ### LogLevel
728
+
729
+ 日志级别枚举。
730
+
731
+ ```typescript
732
+ enum LogLevel {
733
+ DEBUG = 0,
734
+ INFO = 1,
735
+ WARN = 2,
736
+ ERROR = 3,
737
+ CRITICAL = 4,
738
+ }
739
+ ```
740
+
741
+ ### ErrorSeverity
742
+
743
+ 错误严重程度。
744
+
745
+ ```typescript
746
+ enum ErrorSeverity {
747
+ LOW = 'low',
748
+ MEDIUM = 'medium',
749
+ HIGH = 'high',
750
+ CRITICAL = 'critical',
751
+ }
752
+ ```
753
+
754
+ ## 使用示例
755
+
756
+ ### 完整的命令实现
757
+
758
+ ```typescript
759
+ import { type CommandDefinition } from '@/cli/command-registry';
760
+ import { Logger } from '@/utils/logger';
761
+ import { ConfigManager } from '@/utils/config';
762
+ import { CommandError, errorHandler } from '@/utils/error-handlers';
763
+
764
+ export const MyCommand: CommandDefinition = {
765
+ name: 'my-command',
766
+ description: '我的自定义命令',
767
+ alias: 'mc',
768
+ options: [
769
+ {
770
+ flags: '-f, --force',
771
+ description: '强制执行',
772
+ defaultValue: false,
773
+ },
774
+ {
775
+ flags: '-t, --timeout <number>',
776
+ description: '超时时间(秒)',
777
+ defaultValue: '30',
778
+ },
779
+ ],
780
+ subcommands: [
781
+ {
782
+ name: 'sub1',
783
+ description: '子命令1',
784
+ action: async options => {
785
+ const config = ConfigManager.get();
786
+ Logger.info('执行子命令1', { options, config });
787
+
788
+ if (options.force) {
789
+ Logger.warning('强制执行模式');
790
+ }
791
+
792
+ try {
793
+ // 业务逻辑
794
+ await doSomething();
795
+ Logger.success('操作完成');
796
+ } catch (error) {
797
+ errorHandler(
798
+ error,
799
+ {
800
+ command: 'my-command',
801
+ action: 'sub1',
802
+ },
803
+ ErrorSeverity.MEDIUM
804
+ );
805
+ }
806
+ },
807
+ },
808
+ ],
809
+ action: async options => {
810
+ const timeout = parseInt(options.timeout?.toString() || '30');
811
+ Logger.info('执行主命令', { timeout, force: options.force });
812
+
813
+ try {
814
+ await withTimeout(doMainOperation(), timeout * 1000);
815
+ Logger.success('主命令执行完成');
816
+ } catch (error) {
817
+ if (error instanceof CommandError) {
818
+ throw error;
819
+ }
820
+ errorHandler(
821
+ error,
822
+ {
823
+ command: 'my-command',
824
+ action: 'main',
825
+ },
826
+ ErrorSeverity.HIGH
827
+ );
828
+ }
829
+ },
830
+ };
831
+
832
+ async function doSomething(): Promise<void> {
833
+ // 实现业务逻辑
834
+ }
835
+
836
+ async function doMainOperation(): Promise<void> {
837
+ // 实现主要操作
838
+ }
839
+
840
+ function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
841
+ return Promise.race([
842
+ promise,
843
+ new Promise<never>((_, reject) => setTimeout(() => reject(new Error('操作超时')), timeoutMs)),
844
+ ]);
845
+ }
846
+
847
+ export default MyCommand;
848
+ ```
849
+
850
+ 这个API文档提供了完整的接口说明和使用示例,帮助开发者快速理解和使用Ops Toolkit的各种功能。