@taicode/common-base 1.2.0 → 1.4.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 (36) hide show
  1. package/output/error/error.d.ts +59 -9
  2. package/output/error/error.d.ts.map +1 -1
  3. package/output/error/error.js +50 -6
  4. package/output/error/index.d.ts +1 -1
  5. package/output/error/index.d.ts.map +1 -1
  6. package/output/logger/formatter.d.ts +71 -0
  7. package/output/logger/formatter.d.ts.map +1 -0
  8. package/output/logger/formatter.js +222 -0
  9. package/output/logger/formatter.test.d.ts +26 -0
  10. package/output/logger/formatter.test.d.ts.map +1 -0
  11. package/output/logger/formatter.test.js +315 -0
  12. package/output/logger/index.d.ts +3 -17
  13. package/output/logger/index.d.ts.map +1 -1
  14. package/output/logger/index.js +3 -34
  15. package/output/logger/logger.d.ts +51 -0
  16. package/output/logger/logger.d.ts.map +1 -0
  17. package/output/logger/logger.js +118 -0
  18. package/output/logger/logger.test.d.ts +19 -0
  19. package/output/logger/logger.test.d.ts.map +1 -1
  20. package/output/logger/logger.test.js +201 -15
  21. package/output/logger/transport.d.ts +124 -0
  22. package/output/logger/transport.d.ts.map +1 -0
  23. package/output/logger/transport.js +153 -0
  24. package/output/logger/transport.test.d.ts +2 -0
  25. package/output/logger/transport.test.d.ts.map +1 -0
  26. package/output/logger/transport.test.js +309 -0
  27. package/output/ring-cache/index.d.ts +6 -0
  28. package/output/ring-cache/index.d.ts.map +1 -0
  29. package/output/ring-cache/index.js +5 -0
  30. package/output/ring-cache/ring-cache.d.ts +125 -0
  31. package/output/ring-cache/ring-cache.d.ts.map +1 -0
  32. package/output/ring-cache/ring-cache.js +197 -0
  33. package/output/ring-cache/ring-cache.test.d.ts +2 -0
  34. package/output/ring-cache/ring-cache.test.d.ts.map +1 -0
  35. package/output/ring-cache/ring-cache.test.js +195 -0
  36. package/package.json +1 -1
@@ -1,23 +1,73 @@
1
- interface ErrorOptions {
1
+ /**
2
+ * 错误类型模块
3
+ * key 为错误的类型
4
+ * value 为错误的上下文类型
5
+ * 错误的上下文可以帮助系统更好的理解和处理错误
6
+ * 一般存放的是错误发生时的关键信息,例如请求的路径,参数等等
7
+ * 输入错误时输入的字段信息,校验规则等等
8
+ * 可以通过模块声明合并来定义全局错误类型:
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * declare module '@taicode/common-base/error' {
13
+ * interface UserErrorTypes {
14
+ * 'validation-failed': { field?: string; value?: unknown; rule?: string }
15
+ * 'permission-denied': { resource?: string; action?: string; userId?: string }
16
+ * 'not-found': { id?: string; type?: string; query?: Record<string, unknown> }
17
+ * }
18
+ *
19
+ * interface SystemErrorTypes {
20
+ * 'database-error': { query?: string; table?: string; operation?: string }
21
+ * 'network-error': { url?: string; method?: string; status?: number }
22
+ * 'service-unavailable': { service?: string; endpoint?: string; retryAfter?: number }
23
+ * }
24
+ * }
25
+ *
26
+ * // 然后可以这样使用:
27
+ * const userError = new UserError('validation-failed', '邮箱格式无效', {
28
+ * field: 'email',
29
+ * value: 'invalid-email',
30
+ * rule: 'email-format'
31
+ * })
32
+ * const systemError = new SystemError('database-error', '数据库连接失败', {
33
+ * table: 'users',
34
+ * query: 'SELECT * FROM users',
35
+ * operation: 'select'
36
+ * })
37
+ * ```
38
+ */
39
+ interface ErrorContext {
40
+ /** 导致此错误的原因,通常是另一个错误或异常 */
2
41
  cause?: unknown;
3
42
  }
43
+ export interface UserErrorTypes {
44
+ }
45
+ export interface SystemErrorTypes {
46
+ }
47
+ type UserErrorType = keyof UserErrorTypes extends never ? string : Extract<keyof UserErrorTypes, string>;
48
+ type SystemErrorType = keyof SystemErrorTypes extends never ? string : Extract<keyof SystemErrorTypes, string>;
49
+ type UserErrorContext<T extends string> = T extends keyof UserErrorTypes ? UserErrorTypes[T] & ErrorContext : ErrorContext;
50
+ type SystemErrorContext<T extends string> = T extends keyof SystemErrorTypes ? SystemErrorTypes[T] & ErrorContext : ErrorContext;
4
51
  /** 用户可见的错误 */
5
- export declare class UserError<T extends string> extends Error {
52
+ export declare class UserError<T extends string = UserErrorType> extends Error {
6
53
  type: T;
7
54
  message: string;
8
- constructor(type: T, message: string, options?: ErrorOptions);
9
- static is<T extends string>(error: unknown): error is UserError<T>;
55
+ context?: UserErrorContext<T> | undefined;
56
+ constructor(type: T, message: string, context?: UserErrorContext<T> | undefined);
57
+ static is<T extends string = UserErrorType>(error: unknown): error is UserError<T>;
10
58
  }
11
59
  /** 系统错误 */
12
- export declare class SystemError<T extends string> extends Error {
60
+ export declare class SystemError<T extends string = SystemErrorType> extends Error {
13
61
  type: T;
14
62
  message: string;
15
- constructor(type: T, message: string, options?: ErrorOptions);
16
- static is<T extends string>(error: unknown): error is SystemError<T>;
63
+ context?: SystemErrorContext<T> | undefined;
64
+ constructor(type: T, message: string, context?: SystemErrorContext<T> | undefined);
65
+ static is<T extends string = SystemErrorType>(error: unknown): error is SystemError<T>;
17
66
  }
18
67
  export declare class UnknownError extends Error {
19
- constructor(message: string, options?: ErrorOptions);
20
- static is(error: unknown): boolean;
68
+ context?: ErrorContext | undefined;
69
+ constructor(message: string, context?: ErrorContext | undefined);
70
+ static is(error: unknown): error is UnknownError;
21
71
  }
22
72
  export {};
23
73
  //# sourceMappingURL=error.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../../source/error/error.ts"],"names":[],"mappings":"AAAA,UAAU,YAAY;IACpB,KAAK,CAAC,EAAE,OAAO,CAAA;CAChB;AAED,cAAc;AACd,qBAAa,SAAS,CAAC,CAAC,SAAS,MAAM,CAAE,SAAQ,KAAK;IACjC,IAAI,EAAE,CAAC;IAAS,OAAO,EAAE,MAAM;gBAA/B,IAAI,EAAE,CAAC,EAAS,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;IAK1E,MAAM,CAAC,EAAE,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,SAAS,CAAC,CAAC,CAAC;CAGnE;AAED,WAAW;AACX,qBAAa,WAAW,CAAC,CAAC,SAAS,MAAM,CAAE,SAAQ,KAAK;IACnC,IAAI,EAAE,CAAC;IAAS,OAAO,EAAE,MAAM;gBAA/B,IAAI,EAAE,CAAC,EAAS,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;IAK1E,MAAM,CAAC,EAAE,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,WAAW,CAAC,CAAC,CAAC;CAGrE;AAED,qBAAa,YAAa,SAAQ,KAAK;gBACzB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;IAKnD,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO;CAGnC"}
1
+ {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../../source/error/error.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,UAAU,YAAY;IACpB,2BAA2B;IAC3B,KAAK,CAAC,EAAE,OAAO,CAAA;CAChB;AAID,MAAM,WAAW,cAAc;CAAG;AAClC,MAAM,WAAW,gBAAgB;CAAG;AAGpC,KAAK,aAAa,GAAG,MAAM,cAAc,SAAS,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,cAAc,EAAE,MAAM,CAAC,CAAA;AACxG,KAAK,eAAe,GAAG,MAAM,gBAAgB,SAAS,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,gBAAgB,EAAE,MAAM,CAAC,CAAA;AAG9G,KAAK,gBAAgB,CAAC,CAAC,SAAS,MAAM,IAAI,CAAC,SAAS,MAAM,cAAc,GACpE,cAAc,CAAC,CAAC,CAAC,GAAG,YAAY,GAChC,YAAY,CAAA;AAEhB,KAAK,kBAAkB,CAAC,CAAC,SAAS,MAAM,IAAI,CAAC,SAAS,MAAM,gBAAgB,GACxE,gBAAgB,CAAC,CAAC,CAAC,GAAG,YAAY,GAClC,YAAY,CAAA;AAEhB,cAAc;AACd,qBAAa,SAAS,CAAC,CAAC,SAAS,MAAM,GAAG,aAAa,CAAE,SAAQ,KAAK;IACjD,IAAI,EAAE,CAAC;IAAS,OAAO,EAAE,MAAM;IAAS,OAAO,CAAC,EAAE,gBAAgB,CAAC,CAAC,CAAC;gBAArE,IAAI,EAAE,CAAC,EAAS,OAAO,EAAE,MAAM,EAAS,OAAO,CAAC,EAAE,gBAAgB,CAAC,CAAC,CAAC,YAAA;IAKxF,MAAM,CAAC,EAAE,CAAC,CAAC,SAAS,MAAM,GAAG,aAAa,EAAE,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,SAAS,CAAC,CAAC,CAAC;CAGnF;AAED,WAAW;AACX,qBAAa,WAAW,CAAC,CAAC,SAAS,MAAM,GAAG,eAAe,CAAE,SAAQ,KAAK;IACrD,IAAI,EAAE,CAAC;IAAS,OAAO,EAAE,MAAM;IAAS,OAAO,CAAC,EAAE,kBAAkB,CAAC,CAAC,CAAC;gBAAvE,IAAI,EAAE,CAAC,EAAS,OAAO,EAAE,MAAM,EAAS,OAAO,CAAC,EAAE,kBAAkB,CAAC,CAAC,CAAC,YAAA;IAK1F,MAAM,CAAC,EAAE,CAAC,CAAC,SAAS,MAAM,GAAG,eAAe,EAAE,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,WAAW,CAAC,CAAC,CAAC;CAGvF;AAED,qBAAa,YAAa,SAAQ,KAAK;IACD,OAAO,CAAC,EAAE,YAAY;gBAA9C,OAAO,EAAE,MAAM,EAAS,OAAO,CAAC,EAAE,YAAY,YAAA;IAK1D,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY;CAGjD"}
@@ -1,11 +1,51 @@
1
+ /**
2
+ * 错误类型模块
3
+ * key 为错误的类型
4
+ * value 为错误的上下文类型
5
+ * 错误的上下文可以帮助系统更好的理解和处理错误
6
+ * 一般存放的是错误发生时的关键信息,例如请求的路径,参数等等
7
+ * 输入错误时输入的字段信息,校验规则等等
8
+ * 可以通过模块声明合并来定义全局错误类型:
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * declare module '@taicode/common-base/error' {
13
+ * interface UserErrorTypes {
14
+ * 'validation-failed': { field?: string; value?: unknown; rule?: string }
15
+ * 'permission-denied': { resource?: string; action?: string; userId?: string }
16
+ * 'not-found': { id?: string; type?: string; query?: Record<string, unknown> }
17
+ * }
18
+ *
19
+ * interface SystemErrorTypes {
20
+ * 'database-error': { query?: string; table?: string; operation?: string }
21
+ * 'network-error': { url?: string; method?: string; status?: number }
22
+ * 'service-unavailable': { service?: string; endpoint?: string; retryAfter?: number }
23
+ * }
24
+ * }
25
+ *
26
+ * // 然后可以这样使用:
27
+ * const userError = new UserError('validation-failed', '邮箱格式无效', {
28
+ * field: 'email',
29
+ * value: 'invalid-email',
30
+ * rule: 'email-format'
31
+ * })
32
+ * const systemError = new SystemError('database-error', '数据库连接失败', {
33
+ * table: 'users',
34
+ * query: 'SELECT * FROM users',
35
+ * operation: 'select'
36
+ * })
37
+ * ```
38
+ */
1
39
  /** 用户可见的错误 */
2
40
  export class UserError extends Error {
3
41
  type;
4
42
  message;
5
- constructor(type, message, options) {
6
- super(message, options);
43
+ context;
44
+ constructor(type, message, context) {
45
+ super(message, context);
7
46
  this.type = type;
8
47
  this.message = message;
48
+ this.context = context;
9
49
  this.name = 'UserError';
10
50
  }
11
51
  static is(error) {
@@ -16,10 +56,12 @@ export class UserError extends Error {
16
56
  export class SystemError extends Error {
17
57
  type;
18
58
  message;
19
- constructor(type, message, options) {
20
- super(message, options);
59
+ context;
60
+ constructor(type, message, context) {
61
+ super(message, context);
21
62
  this.type = type;
22
63
  this.message = message;
64
+ this.context = context;
23
65
  this.name = 'SystemError';
24
66
  }
25
67
  static is(error) {
@@ -27,8 +69,10 @@ export class SystemError extends Error {
27
69
  }
28
70
  }
29
71
  export class UnknownError extends Error {
30
- constructor(message, options) {
31
- super(message, options);
72
+ context;
73
+ constructor(message, context) {
74
+ super(message, context);
75
+ this.context = context;
32
76
  this.name = 'UnknownError';
33
77
  }
34
78
  static is(error) {
@@ -1,2 +1,2 @@
1
- export { UserError, SystemError, UnknownError } from './error';
1
+ export { UserError, SystemError, UnknownError, UserErrorTypes, SystemErrorTypes } from './error';
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/error/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/error/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,WAAW,EACX,YAAY,EACZ,cAAc,EACd,gBAAgB,EACjB,MAAM,SAAS,CAAA"}
@@ -0,0 +1,71 @@
1
+ export interface FormatterConfig {
2
+ /** 错误对象格式化器 */
3
+ error?: (error: unknown) => string;
4
+ /** 日期格式化器 */
5
+ date?: (date: Date) => string;
6
+ /** 对象格式化器 */
7
+ object?: (obj: any) => string;
8
+ /** 数组格式化器 */
9
+ array?: (arr: any[]) => string;
10
+ /** 函数格式化器 */
11
+ function?: (fn: Function) => string;
12
+ /** 其他类型格式化器 */
13
+ other?: (value: any) => string;
14
+ }
15
+ /**
16
+ * 日志格式化器接口
17
+ * 定义格式化器的核心方法
18
+ */
19
+ export interface LogFormatter {
20
+ /** 格式化单个参数 */
21
+ format(arg: any): string;
22
+ /** 格式化参数数组 */
23
+ formatArguments(args: any[]): string[];
24
+ }
25
+ export interface ErrorFormatterOptions {
26
+ /** 是否显示堆栈信息 */
27
+ showStack?: boolean;
28
+ /** 是否显示错误上下文 */
29
+ showContext?: boolean;
30
+ /** 是否使用颜色(在支持的终端中) */
31
+ useColors?: boolean;
32
+ }
33
+ /**
34
+ * 日志格式化器
35
+ * 负责根据配置格式化各种类型的参数
36
+ */
37
+ export declare class DefaultLogFormatter implements LogFormatter {
38
+ private errorOptions;
39
+ private config;
40
+ constructor(config?: FormatterConfig, errorOptions?: ErrorFormatterOptions);
41
+ /**
42
+ * 格式化单个参数
43
+ */
44
+ format(arg: any): string;
45
+ /**
46
+ * 格式化参数数组
47
+ */
48
+ formatArguments(args: any[]): string[];
49
+ /**
50
+ * 格式化错误对象
51
+ */
52
+ private formatError;
53
+ private formatUserError;
54
+ private formatSystemError;
55
+ private formatUnknownError;
56
+ private formatGenericError;
57
+ private formatUnknownValue;
58
+ private formatContext;
59
+ private colorize;
60
+ private formatDate;
61
+ private formatObject;
62
+ private formatArray;
63
+ private formatFunction;
64
+ private formatSimple;
65
+ private formatOther;
66
+ }
67
+ /**
68
+ * 默认的日志格式化器实例
69
+ */
70
+ export declare const defaultLogFormatter: DefaultLogFormatter;
71
+ //# sourceMappingURL=formatter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatter.d.ts","sourceRoot":"","sources":["../../source/logger/formatter.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,eAAe;IAC9B,eAAe;IACf,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,MAAM,CAAA;IAClC,aAAa;IACb,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,MAAM,CAAA;IAC7B,aAAa;IACb,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,MAAM,CAAA;IAC7B,aAAa;IACb,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,MAAM,CAAA;IAC9B,aAAa;IACb,QAAQ,CAAC,EAAE,CAAC,EAAE,EAAE,QAAQ,KAAK,MAAM,CAAA;IACnC,eAAe;IACf,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,MAAM,CAAA;CAC/B;AAED;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,cAAc;IACd,MAAM,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,CAAA;IACxB,cAAc;IACd,eAAe,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,MAAM,EAAE,CAAA;CACvC;AAED,MAAM,WAAW,qBAAqB;IACpC,eAAe;IACf,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,gBAAgB;IAChB,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,sBAAsB;IACtB,SAAS,CAAC,EAAE,OAAO,CAAA;CACpB;AAED;;;GAGG;AACH,qBAAa,mBAAoB,YAAW,YAAY;IACtD,OAAO,CAAC,YAAY,CAAuB;IAC3C,OAAO,CAAC,MAAM,CAA0C;gBAE5C,MAAM,GAAE,eAAoB,EAAE,YAAY,GAAE,qBAA0B;IAgBlF;;OAEG;IACH,MAAM,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM;IAwBxB;;OAEG;IACH,eAAe,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,MAAM,EAAE;IAItC;;OAEG;IACH,OAAO,CAAC,WAAW;IA0BnB,OAAO,CAAC,eAAe;IAiBvB,OAAO,CAAC,iBAAiB;IAiBzB,OAAO,CAAC,kBAAkB;IAiB1B,OAAO,CAAC,kBAAkB;IAuB1B,OAAO,CAAC,kBAAkB;IAI1B,OAAO,CAAC,aAAa;IAYrB,OAAO,CAAC,QAAQ;IAehB,OAAO,CAAC,UAAU;IAIlB,OAAO,CAAC,YAAY;IAWpB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,cAAc;IAItB,OAAO,CAAC,YAAY;IAWpB,OAAO,CAAC,WAAW;CAWpB;AAED;;GAEG;AACH,eAAO,MAAM,mBAAmB,qBAA4B,CAAA"}
@@ -0,0 +1,222 @@
1
+ /**
2
+ * 格式化器配置模块
3
+ * 提供各种类型数据的格式化功能
4
+ */
5
+ import { UserError, SystemError, UnknownError } from '../error';
6
+ /**
7
+ * 日志格式化器
8
+ * 负责根据配置格式化各种类型的参数
9
+ */
10
+ export class DefaultLogFormatter {
11
+ errorOptions;
12
+ config;
13
+ constructor(config = {}, errorOptions = {}) {
14
+ this.errorOptions = {
15
+ showStack: errorOptions.showStack ?? true,
16
+ showContext: errorOptions.showContext ?? true,
17
+ useColors: errorOptions.useColors ?? true,
18
+ };
19
+ this.config = {
20
+ date: config.date || this.formatDate.bind(this),
21
+ object: config.object || this.formatObject.bind(this),
22
+ array: config.array || this.formatArray.bind(this),
23
+ function: config.function || this.formatFunction.bind(this),
24
+ other: config.other || this.formatOther.bind(this),
25
+ };
26
+ }
27
+ /**
28
+ * 格式化单个参数
29
+ */
30
+ format(arg) {
31
+ if (arg instanceof Error) {
32
+ return this.formatError(arg, this.errorOptions);
33
+ }
34
+ if (arg instanceof Date) {
35
+ return this.config.date(arg);
36
+ }
37
+ if (Array.isArray(arg)) {
38
+ return this.config.array(arg);
39
+ }
40
+ if (typeof arg === 'function') {
41
+ return this.config.function(arg);
42
+ }
43
+ if (typeof arg === 'object' && arg !== null) {
44
+ return this.config.object(arg);
45
+ }
46
+ return this.config.other(arg);
47
+ }
48
+ /**
49
+ * 格式化参数数组
50
+ */
51
+ formatArguments(args) {
52
+ return args.map(arg => this.format(arg));
53
+ }
54
+ /**
55
+ * 格式化错误对象
56
+ */
57
+ formatError(error, options = {}) {
58
+ const opts = {
59
+ showStack: options.showStack ?? true,
60
+ showContext: options.showContext ?? true,
61
+ useColors: options.useColors ?? true,
62
+ };
63
+ if (UserError.is(error)) {
64
+ return this.formatUserError(error, opts);
65
+ }
66
+ if (SystemError.is(error)) {
67
+ return this.formatSystemError(error, opts);
68
+ }
69
+ if (UnknownError.is(error)) {
70
+ return this.formatUnknownError(error, opts);
71
+ }
72
+ if (error instanceof Error) {
73
+ return this.formatGenericError(error, opts);
74
+ }
75
+ return this.formatUnknownValue(error);
76
+ }
77
+ formatUserError(error, opts) {
78
+ const lines = [
79
+ this.colorize(`🚫 User Error [${error.type}]`, 'red', opts.useColors),
80
+ `Message: ${error.message}`,
81
+ ];
82
+ if (opts.showContext && error.context) {
83
+ lines.push(`Context: ${this.formatContext(error.context)}`);
84
+ }
85
+ if (opts.showStack && error.stack) {
86
+ lines.push(`Stack: ${error.stack}`);
87
+ }
88
+ return lines.join('\n ');
89
+ }
90
+ formatSystemError(error, opts) {
91
+ const lines = [
92
+ this.colorize(`⚠️ System Error [${error.type}]`, 'yellow', opts.useColors),
93
+ `Message: ${error.message}`,
94
+ ];
95
+ if (opts.showContext && error.context) {
96
+ lines.push(`Context: ${this.formatContext(error.context)}`);
97
+ }
98
+ if (opts.showStack && error.stack) {
99
+ lines.push(`Stack: ${error.stack}`);
100
+ }
101
+ return lines.join('\n ');
102
+ }
103
+ formatUnknownError(error, opts) {
104
+ const lines = [
105
+ this.colorize('❓ Unknown Error', 'magenta', opts.useColors),
106
+ `Message: ${error.message}`,
107
+ ];
108
+ if (opts.showContext && error.context) {
109
+ lines.push(`Context: ${this.formatContext(error.context)}`);
110
+ }
111
+ if (opts.showStack && error.stack) {
112
+ lines.push(`Stack: ${error.stack}`);
113
+ }
114
+ return lines.join('\n ');
115
+ }
116
+ formatGenericError(error, opts) {
117
+ const lines = [
118
+ this.colorize(`💥 ${error.name}`, 'red', opts.useColors),
119
+ `Message: ${error.message}`,
120
+ ];
121
+ // 处理额外的错误属性
122
+ const additionalProps = Object.getOwnPropertyNames(error)
123
+ .filter(prop => !['name', 'message', 'stack'].includes(prop))
124
+ .map(prop => `${prop}: ${this.formatSimple(error[prop])}`)
125
+ .filter(Boolean);
126
+ if (additionalProps.length > 0) {
127
+ lines.push(`Additional: ${additionalProps.join(', ')}`);
128
+ }
129
+ if (opts.showStack && error.stack) {
130
+ lines.push(`Stack: ${error.stack}`);
131
+ }
132
+ return lines.join('\n ');
133
+ }
134
+ formatUnknownValue(value) {
135
+ return `Unknown Error: ${this.formatOther(value)}`;
136
+ }
137
+ formatContext(context) {
138
+ if (!context || typeof context !== 'object') {
139
+ return String(context);
140
+ }
141
+ try {
142
+ return JSON.stringify(context, null, 2);
143
+ }
144
+ catch {
145
+ return String(context);
146
+ }
147
+ }
148
+ colorize(text, color, useColors) {
149
+ if (!useColors) {
150
+ return text;
151
+ }
152
+ const colors = {
153
+ red: '\x1b[31m',
154
+ yellow: '\x1b[33m',
155
+ magenta: '\x1b[35m',
156
+ reset: '\x1b[0m',
157
+ };
158
+ return `${colors[color] || ''}${text}${colors.reset}`;
159
+ }
160
+ formatDate(date) {
161
+ return date.toISOString();
162
+ }
163
+ formatObject(obj) {
164
+ if (obj === null)
165
+ return 'null';
166
+ if (obj === undefined)
167
+ return 'undefined';
168
+ try {
169
+ return JSON.stringify(obj, null, 2);
170
+ }
171
+ catch {
172
+ return String(obj);
173
+ }
174
+ }
175
+ formatArray(arr) {
176
+ try {
177
+ return JSON.stringify(arr, null, 2);
178
+ }
179
+ catch {
180
+ return String(arr);
181
+ }
182
+ }
183
+ formatFunction(fn) {
184
+ return `[Function: ${fn.name || 'anonymous'}]`;
185
+ }
186
+ formatSimple(value) {
187
+ if (value === null)
188
+ return 'null';
189
+ if (value === undefined)
190
+ return 'undefined';
191
+ if (typeof value === 'string')
192
+ return value;
193
+ if (typeof value === 'number' || typeof value === 'boolean')
194
+ return String(value);
195
+ if (typeof value === 'symbol')
196
+ return value.toString();
197
+ if (typeof value === 'bigint')
198
+ return value.toString() + 'n';
199
+ return String(value);
200
+ }
201
+ formatOther(value) {
202
+ if (value === null)
203
+ return '[null]';
204
+ if (value === undefined)
205
+ return '[undefined]';
206
+ if (typeof value === 'string')
207
+ return value; // 字符串保持原样,不添加类型标识
208
+ if (typeof value === 'number')
209
+ return `${value}`;
210
+ if (typeof value === 'boolean')
211
+ return `${value}`;
212
+ if (typeof value === 'symbol')
213
+ return `[symbol] ${value.toString()}`;
214
+ if (typeof value === 'bigint')
215
+ return `[bigint] ${value.toString()}n`;
216
+ return String(value);
217
+ }
218
+ }
219
+ /**
220
+ * 默认的日志格式化器实例
221
+ */
222
+ export const defaultLogFormatter = new DefaultLogFormatter();
@@ -0,0 +1,26 @@
1
+ declare module '../error' {
2
+ interface UserErrorTypes {
3
+ 'validation-failed': {
4
+ field?: string;
5
+ value?: unknown;
6
+ rule?: string;
7
+ };
8
+ 'test-error': {
9
+ field?: string;
10
+ };
11
+ }
12
+ interface SystemErrorTypes {
13
+ 'database-error': {
14
+ query?: string;
15
+ table?: string;
16
+ operation?: string;
17
+ };
18
+ 'network-error': {
19
+ url?: string;
20
+ method?: string;
21
+ status?: number;
22
+ };
23
+ }
24
+ }
25
+ export {};
26
+ //# sourceMappingURL=formatter.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatter.test.d.ts","sourceRoot":"","sources":["../../source/logger/formatter.test.ts"],"names":[],"mappings":"AAKA,OAAO,QAAQ,UAAU,CAAC;IACxB,UAAU,cAAc;QACtB,mBAAmB,EAAE;YAAE,KAAK,CAAC,EAAE,MAAM,CAAC;YAAC,KAAK,CAAC,EAAE,OAAO,CAAC;YAAC,IAAI,CAAC,EAAE,MAAM,CAAA;SAAE,CAAA;QACvE,YAAY,EAAE;YAAE,KAAK,CAAC,EAAE,MAAM,CAAA;SAAE,CAAA;KACjC;IAED,UAAU,gBAAgB;QACxB,gBAAgB,EAAE;YAAE,KAAK,CAAC,EAAE,MAAM,CAAC;YAAC,KAAK,CAAC,EAAE,MAAM,CAAC;YAAC,SAAS,CAAC,EAAE,MAAM,CAAA;SAAE,CAAA;QACxE,eAAe,EAAE;YAAE,GAAG,CAAC,EAAE,MAAM,CAAC;YAAC,MAAM,CAAC,EAAE,MAAM,CAAC;YAAC,MAAM,CAAC,EAAE,MAAM,CAAA;SAAE,CAAA;KACpE;CACF"}