@zhin.js/core 1.0.39 → 1.0.41

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 (46) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/lib/ai/index.d.ts +10 -5
  3. package/lib/ai/index.d.ts.map +1 -1
  4. package/lib/ai/index.js +7 -4
  5. package/lib/ai/index.js.map +1 -1
  6. package/lib/built/common-adapter-tools.d.ts.map +1 -1
  7. package/lib/built/common-adapter-tools.js +38 -32
  8. package/lib/built/common-adapter-tools.js.map +1 -1
  9. package/lib/cron.d.ts +2 -43
  10. package/lib/cron.d.ts.map +1 -1
  11. package/lib/cron.js +2 -126
  12. package/lib/cron.js.map +1 -1
  13. package/lib/errors.d.ts +3 -146
  14. package/lib/errors.d.ts.map +1 -1
  15. package/lib/errors.js +3 -279
  16. package/lib/errors.js.map +1 -1
  17. package/lib/feature.d.ts +5 -87
  18. package/lib/feature.d.ts.map +1 -1
  19. package/lib/feature.js +4 -105
  20. package/lib/feature.js.map +1 -1
  21. package/lib/index.d.ts +1 -0
  22. package/lib/index.d.ts.map +1 -1
  23. package/lib/scheduler/index.d.ts +3 -7
  24. package/lib/scheduler/index.d.ts.map +1 -1
  25. package/lib/scheduler/index.js +2 -9
  26. package/lib/scheduler/index.js.map +1 -1
  27. package/lib/types.d.ts +8 -1
  28. package/lib/types.d.ts.map +1 -1
  29. package/lib/utils.d.ts +7 -52
  30. package/lib/utils.d.ts.map +1 -1
  31. package/lib/utils.js +9 -325
  32. package/lib/utils.js.map +1 -1
  33. package/package.json +6 -4
  34. package/src/ai/index.ts +15 -9
  35. package/src/built/common-adapter-tools.ts +38 -32
  36. package/src/cron.ts +2 -140
  37. package/src/errors.ts +15 -334
  38. package/src/feature.ts +5 -154
  39. package/src/index.ts +3 -1
  40. package/src/scheduler/index.ts +8 -17
  41. package/src/types.ts +10 -2
  42. package/src/utils.ts +37 -334
  43. package/tests/cron.test.ts +4 -299
  44. package/tests/errors.test.ts +17 -307
  45. package/tests/utils.test.ts +11 -516
  46. package/tests/feature.test.ts +0 -145
@@ -59,55 +59,55 @@ export const GROUP_METHOD_SPECS: GroupMethodSpec[] = [
59
59
  {
60
60
  method: 'kickMember',
61
61
  toolSuffix: 'kick_member',
62
- description: '将成员踢出群/服务器',
62
+ description: '将成员踢出群/服务器。适用于严重违规、广告号等需要移除的场景。踢出后该成员将无法再进入群聊(部分平台可重新邀请)。如果只需要用户名而没有 user_id,请先调用 list_members 查询',
63
63
  keywords: ['踢', 'kick', '移除', '踢出'],
64
64
  permissionLevel: 'group_admin',
65
65
  extraParams: {
66
- user_id: { type: 'string', description: '目标用户 ID' },
66
+ user_id: { type: 'string', description: '目标用户 ID(如果只有昵称,先用 list_members 查询获取)' },
67
67
  },
68
68
  extraRequired: ['user_id'],
69
69
  },
70
70
  {
71
71
  method: 'muteMember',
72
72
  toolSuffix: 'mute_member',
73
- description: '禁言群成员(duration=0 解除)',
74
- keywords: ['禁言', 'mute', '静音', '解除禁言'],
73
+ description: '禁言或解除禁言群成员。适用于违规发言、刷屏、骚扰他人等需要临时限制发言的场景。duration 单位为秒,传 0 表示解除禁言。默认禁言 10 分钟(600秒)。如果只有昵称而没有 user_id,请先调用 list_members 查询',
74
+ keywords: ['禁言', 'mute', '静音', '解除禁言', '解禁', '闭嘴'],
75
75
  permissionLevel: 'group_admin',
76
76
  extraParams: {
77
- user_id: { type: 'string', description: '目标用户 ID' },
78
- duration: { type: 'number', description: '禁言时长(秒),0=解除', default: 600 },
77
+ user_id: { type: 'string', description: '目标用户 ID(如果只有昵称,先用 list_members 查询获取)' },
78
+ duration: { type: 'number', description: '禁言时长(秒),0=解除禁言,默认600(10分钟)。常用值:60=1分钟, 600=10分钟, 3600=1小时, 86400=1天', default: 600 },
79
79
  },
80
80
  extraRequired: ['user_id'],
81
81
  },
82
82
  {
83
83
  method: 'setMemberNickname',
84
84
  toolSuffix: 'set_nickname',
85
- description: '设置群成员昵称/名片',
86
- keywords: ['昵称', '名片', 'nickname', 'card'],
85
+ description: '设置群成员的群昵称/名片。仅修改群内显示名称,不影响用户的全局昵称。如果只有昵称而没有 user_id,请先调用 list_members 查询',
86
+ keywords: ['昵称', '名片', 'nickname', 'card', '改名片'],
87
87
  permissionLevel: 'group_admin',
88
88
  extraParams: {
89
- user_id: { type: 'string', description: '目标用户 ID' },
90
- nickname: { type: 'string', description: '新昵称' },
89
+ user_id: { type: 'string', description: '目标用户 ID(如果只有昵称,先用 list_members 查询获取)' },
90
+ nickname: { type: 'string', description: '新的群昵称/名片' },
91
91
  },
92
92
  extraRequired: ['user_id', 'nickname'],
93
93
  },
94
94
  {
95
95
  method: 'setAdmin',
96
96
  toolSuffix: 'set_admin',
97
- description: '设置/取消群管理员',
98
- keywords: ['管理员', 'admin', '设置管理'],
97
+ description: '设置或取消群管理员。注意:此操作需要群主权限,普通管理员无法执行。enable=true 为设置管理员,enable=false 为取消管理员。如果只有昵称而没有 user_id,请先调用 list_members 查询',
98
+ keywords: ['管理员', 'admin', '设置管理', '取消管理', '提升管理', '撤销管理'],
99
99
  permissionLevel: 'group_owner',
100
100
  extraParams: {
101
- user_id: { type: 'string', description: '目标用户 ID' },
102
- enable: { type: 'boolean', description: '设置(true)/取消(false)', default: true },
101
+ user_id: { type: 'string', description: '目标用户 ID(如果只有昵称,先用 list_members 查询获取)' },
102
+ enable: { type: 'boolean', description: 'true=设置为管理员,false=取消管理员身份', default: true },
103
103
  },
104
104
  extraRequired: ['user_id'],
105
105
  },
106
106
  {
107
107
  method: 'listMembers',
108
108
  toolSuffix: 'list_members',
109
- description: '获取群/服务器成员列表',
110
- keywords: ['成员', '列表', 'members', 'list'],
109
+ description: '获取群/服务器成员列表。返回所有成员的 ID、昵称、名片、角色等信息。当用户提供昵称/名片而非 ID 时,应先调用此工具查询成员列表,从中匹配到目标用户的 user_id,再执行禁言、踢人等操作',
110
+ keywords: ['成员', '列表', 'members', 'list', '查找', '搜索用户'],
111
111
  permissionLevel: 'user',
112
112
  extraParams: {},
113
113
  preExecutable: true,
@@ -115,52 +115,52 @@ export const GROUP_METHOD_SPECS: GroupMethodSpec[] = [
115
115
  {
116
116
  method: 'banMember',
117
117
  toolSuffix: 'ban_member',
118
- description: '封禁成员',
119
- keywords: ['封禁', 'ban', '拉黑'],
118
+ description: '永久封禁成员(拉入黑名单)。与踢人(kick)不同,封禁后该成员无法再加入群聊。适用于恶意用户、严重违规等需要永久禁止的场景。如果只有昵称而没有 user_id,请先调用 list_members 查询',
119
+ keywords: ['封禁', 'ban', '拉黑', '黑名单'],
120
120
  permissionLevel: 'group_admin',
121
121
  extraParams: {
122
- user_id: { type: 'string', description: '目标用户 ID' },
123
- reason: { type: 'string', description: '封禁原因' },
122
+ user_id: { type: 'string', description: '目标用户 ID(如果只有昵称,先用 list_members 查询获取)' },
123
+ reason: { type: 'string', description: '封禁原因(将记录在封禁日志中)' },
124
124
  },
125
125
  extraRequired: ['user_id'],
126
126
  },
127
127
  {
128
128
  method: 'unbanMember',
129
129
  toolSuffix: 'unban_member',
130
- description: '解除封禁',
131
- keywords: ['解封', 'unban', '解除封禁'],
130
+ description: '解除封禁,将成员从黑名单中移除。解除后该成员可以重新加入群聊。如果只有昵称而没有 user_id,请先调用 list_members 查询',
131
+ keywords: ['解封', 'unban', '解除封禁', '移出黑名单'],
132
132
  permissionLevel: 'group_admin',
133
133
  extraParams: {
134
- user_id: { type: 'string', description: '目标用户 ID' },
134
+ user_id: { type: 'string', description: '目标用户 ID(如果只有昵称,先用 list_members 查询获取)' },
135
135
  },
136
136
  extraRequired: ['user_id'],
137
137
  },
138
138
  {
139
139
  method: 'setGroupName',
140
140
  toolSuffix: 'set_group_name',
141
- description: '修改群名称',
142
- keywords: ['群名', '改名', 'group name'],
141
+ description: '修改群/服务器名称。修改后所有成员立即可见新群名',
142
+ keywords: ['群名', '改名', 'group name', '修改群名'],
143
143
  permissionLevel: 'group_admin',
144
144
  extraParams: {
145
- name: { type: 'string', description: '新群名' },
145
+ name: { type: 'string', description: '新群名称' },
146
146
  },
147
147
  extraRequired: ['name'],
148
148
  },
149
149
  {
150
150
  method: 'muteAll',
151
151
  toolSuffix: 'mute_all',
152
- description: '全员禁言/解除全员禁言',
153
- keywords: ['全员禁言', 'mute all', '全体禁言'],
152
+ description: '开启或关闭全员禁言。开启后除管理员外所有成员都无法发言。适用于紧急维护、重要通知、聊天秩序混乱等场景。enable=true 开启,enable=false 解除',
153
+ keywords: ['全员禁言', 'mute all', '全体禁言', '全体解禁'],
154
154
  permissionLevel: 'group_admin',
155
155
  extraParams: {
156
- enable: { type: 'boolean', description: '开启(true)/解除(false)', default: true },
156
+ enable: { type: 'boolean', description: 'true=开启全员禁言,false=解除全员禁言', default: true },
157
157
  },
158
158
  },
159
159
  {
160
160
  method: 'getGroupInfo',
161
161
  toolSuffix: 'get_group_info',
162
- description: '获取群/服务器基本信息',
163
- keywords: ['群信息', 'group info', '群资料'],
162
+ description: '获取群/服务器基本信息,包括群名、群主、成员数量、创建时间等。用于了解群聊概况',
163
+ keywords: ['群信息', 'group info', '群资料', '群详情'],
164
164
  permissionLevel: 'user',
165
165
  extraParams: {},
166
166
  preExecutable: true,
@@ -173,7 +173,13 @@ export const GROUP_METHOD_SPECS: GroupMethodSpec[] = [
173
173
 
174
174
  export const GROUP_MANAGEMENT_SKILL_DESCRIPTION =
175
175
  '群聊管理能力:在 IM 系统中对群/服务器进行管理,包括踢人、禁言、封禁、' +
176
- '设置管理员、修改群名、查看成员列表等操作。具体可用的操作取决于平台和 Bot 权限。';
176
+ '设置管理员、修改群名、查看成员列表等操作。具体可用的操作取决于平台和 Bot 权限。\n\n' +
177
+ '使用指南:\n' +
178
+ '1. 用户提供昵称/名片而非 ID 时,必须先调用 list_members 查询成员列表,从返回结果中匹配目标用户的 user_id,再执行后续操作\n' +
179
+ '2. 禁言(mute_member)适用场景:违规发言、刷屏、骚扰他人等;传 duration=0 可解除禁言\n' +
180
+ '3. 设置/取消管理员(set_admin)需要群主权限,普通管理员无法操作;enable=false 为取消管理员\n' +
181
+ '4. 踢人(kick_member)是将成员移出群聊,封禁(ban_member)是永久拉黑,两者不同\n' +
182
+ '5. 操作前应确认目标用户正确,避免误操作';
177
183
 
178
184
  export const GROUP_MANAGEMENT_SKILL_TAGS = ['group', 'management', 'im', 'admin'];
179
185
  export const GROUP_MANAGEMENT_SKILL_KEYWORDS = [
package/src/cron.ts CHANGED
@@ -1,142 +1,4 @@
1
- import { Cron as Croner } from 'croner';
2
-
3
1
  /**
4
- * Cron 定时任务类
5
- * 基于 croner 实现的定时任务调度器 (无需 Luxon,内存占用更小)
2
+ * Re-export from @zhin.js/kernel for backward compatibility.
6
3
  */
7
- export class Cron {
8
- private job: Croner | null = null;
9
- id:string = '';
10
- private callback: () => void | Promise<void>;
11
- private isDisposed = false;
12
- private _cronExpression: string;
13
-
14
- /**
15
- * 创建一个新的 Cron 实例
16
- * @param cronExpression - Cron 表达式 (例如: '0 0 * * *' 表示每天午夜执行)
17
- * @param callback - 要执行的回调函数
18
- */
19
- constructor(cronExpression: string, callback: () => void | Promise<void>) {
20
- this.id=Math.random().toString(36).substring(2, 10);
21
- try {
22
- this._cronExpression = cronExpression;
23
- this.callback = callback;
24
-
25
- // 验证 cron 表达式是否有效 (不启动)
26
- const testJob = new Croner(cronExpression, { paused: true });
27
- testJob.stop();
28
- } catch (error) {
29
- throw new Error(`Invalid cron expression "${cronExpression}": ${(error as Error).message}`);
30
- }
31
- }
32
-
33
- /**
34
- * 启动定时任务
35
- */
36
- run(): void {
37
- if (this.isDisposed) {
38
- throw new Error('Cannot run a disposed cron job');
39
- }
40
-
41
- if (this.job) {
42
- return; // 已经在运行中
43
- }
44
-
45
- // 创建并启动任务
46
- this.job = new Croner(this._cronExpression, async () => {
47
- try {
48
- await this.callback();
49
- } catch (error) {
50
- console.error(`Error executing cron callback: ${(error as Error).message}`);
51
- }
52
- });
53
- }
54
-
55
- /**
56
- * 停止定时任务
57
- */
58
- stop(): void {
59
- if (this.job) {
60
- this.job.stop();
61
- this.job = null;
62
- }
63
- }
64
-
65
- /**
66
- * 销毁定时任务,释放资源
67
- */
68
- dispose(): void {
69
- this.stop();
70
- this.isDisposed = true;
71
- }
72
-
73
- /**
74
- * 获取下一次执行时间
75
- */
76
- getNextExecutionTime(): Date {
77
- if (this.isDisposed) {
78
- throw new Error('Cannot get next execution time for a disposed cron job');
79
- }
80
-
81
- // 创建临时任务来获取下次执行时间
82
- const tempJob = new Croner(this._cronExpression, { paused: true });
83
- const nextRun = tempJob.nextRun();
84
- tempJob.stop();
85
-
86
- if (!nextRun) {
87
- throw new Error('Cannot determine next execution time');
88
- }
89
-
90
- return nextRun;
91
- }
92
-
93
- /**
94
- * 检查任务是否正在运行
95
- */
96
- get running(): boolean {
97
- return this.job !== null;
98
- }
99
-
100
- /**
101
- * 检查任务是否已被销毁
102
- */
103
- get disposed(): boolean {
104
- return this.isDisposed;
105
- }
106
-
107
- /**
108
- * 获取原始的 cron 表达式字符串
109
- */
110
- get cronExpression(): string {
111
- return this._cronExpression;
112
- }
113
- }
114
-
115
- //
116
- // Cron 表达式格式说明:
117
- //
118
- // 标准格式: "分 时 日 月 周" (5 字段)
119
- //
120
- // 字段说明:
121
- // - 分: 0-59
122
- // - 时: 0-23
123
- // - 日: 1-31
124
- // - 月: 1-12 (或 JAN-DEC)
125
- // - 周: 0-7 (0和7都表示周日,或 SUN-SAT)
126
- //
127
- // > croner 也支持 6 字段格式 "秒 分 时 日 月 周",但推荐使用 5 字段格式。
128
- //
129
- // 特殊字符:
130
- // - 星号: 匹配任意值
131
- // - 问号: 用于日和周字段,表示不指定值
132
- // - 横线: 表示范围,如 1-5
133
- // - 逗号: 表示列表,如 1,3,5
134
- // - 斜杠: 表示步长,如 */15 表示每15分钟
135
- //
136
- // 常用示例:
137
- // - "0 0 * * *": 每天午夜执行
138
- // - "*/15 * * * *": 每15分钟执行
139
- // - "0 12 * * *": 每天中午12点执行
140
- // - "0 0 1 * *": 每月1号午夜执行
141
- // - "0 0 * * 0": 每周日午夜执行
142
- //
4
+ export { Cron } from '@zhin.js/kernel';
package/src/errors.ts CHANGED
@@ -1,70 +1,21 @@
1
- // ============================================================================
2
- // 错误处理系统
3
- // ============================================================================
4
-
5
1
  /**
6
- * 基础错误类,所有自定义错误都应该继承此类
2
+ * Re-export generic errors from @zhin.js/kernel
7
3
  */
8
- export class ZhinError extends Error {
9
- public readonly code: string
10
- public readonly timestamp: Date
11
- public readonly context?: Record<string, any>
12
-
13
- constructor(message: string, code: string = 'ZHIN_ERROR', context?: Record<string, any>) {
14
- super(message)
15
- this.name = this.constructor.name
16
- this.code = code
17
- this.timestamp = new Date()
18
- this.context = context
19
-
20
- // 确保错误堆栈正确显示
21
- if (Error.captureStackTrace) {
22
- Error.captureStackTrace(this, this.constructor)
23
- }
24
- }
25
-
26
- /**
27
- * 转换为JSON格式
28
- */
29
- toJSON() {
30
- return {
31
- name: this.name,
32
- message: this.message,
33
- code: this.code,
34
- timestamp: this.timestamp.toISOString(),
35
- context: this.context,
36
- stack: this.stack
37
- }
38
- }
39
-
40
- /**
41
- * 转换为用户友好的格式
42
- */
43
- toUserString(): string {
44
- return `[${this.code}] ${this.message}`
45
- }
46
- }
4
+ export {
5
+ ZhinError,
6
+ ConfigError,
7
+ PluginError,
8
+ ConnectionError,
9
+ ContextError,
10
+ ValidationError,
11
+ PermissionError,
12
+ TimeoutError,
13
+ ErrorManager,
14
+ RetryManager,
15
+ CircuitBreaker,
16
+ } from '@zhin.js/kernel';
47
17
 
48
- /**
49
- * 配置相关错误
50
- */
51
- export class ConfigError extends ZhinError {
52
- constructor(message: string, context?: Record<string, any>) {
53
- super(message, 'CONFIG_ERROR', context)
54
- }
55
- }
56
-
57
- /**
58
- * 插件相关错误
59
- */
60
- export class PluginError extends ZhinError {
61
- public readonly pluginName: string
62
-
63
- constructor(message: string, pluginName: string, context?: Record<string, any>) {
64
- super(message, 'PLUGIN_ERROR', { ...context, pluginName })
65
- this.pluginName = pluginName
66
- }
67
- }
18
+ import { ZhinError } from '@zhin.js/kernel';
68
19
 
69
20
  /**
70
21
  * 适配器相关错误
@@ -80,18 +31,6 @@ export class AdapterError extends ZhinError {
80
31
  }
81
32
  }
82
33
 
83
- /**
84
- * 连接相关错误
85
- */
86
- export class ConnectionError extends ZhinError {
87
- public readonly retryable: boolean
88
-
89
- constructor(message: string, retryable: boolean = true, context?: Record<string, any>) {
90
- super(message, 'CONNECTION_ERROR', { ...context, retryable })
91
- this.retryable = retryable
92
- }
93
- }
94
-
95
34
  /**
96
35
  * 消息处理错误
97
36
  */
@@ -105,261 +44,3 @@ export class MessageError extends ZhinError {
105
44
  this.channelId = channelId
106
45
  }
107
46
  }
108
-
109
- /**
110
- * 上下文相关错误
111
- */
112
- export class ContextError extends ZhinError {
113
- public readonly contextName: string
114
-
115
- constructor(message: string, contextName: string, context?: Record<string, any>) {
116
- super(message, 'CONTEXT_ERROR', { ...context, contextName })
117
- this.contextName = contextName
118
- }
119
- }
120
-
121
- /**
122
- * 验证错误
123
- */
124
- export class ValidationError extends ZhinError {
125
- public readonly field?: string
126
- public readonly value?: any
127
-
128
- constructor(message: string, field?: string, value?: any, context?: Record<string, any>) {
129
- super(message, 'VALIDATION_ERROR', { ...context, field, value })
130
- this.field = field
131
- this.value = value
132
- }
133
- }
134
-
135
- /**
136
- * 权限错误
137
- */
138
- export class PermissionError extends ZhinError {
139
- public readonly userId?: string
140
- public readonly requiredPermission?: string
141
-
142
- constructor(message: string, userId?: string, requiredPermission?: string, context?: Record<string, any>) {
143
- super(message, 'PERMISSION_ERROR', { ...context, userId, requiredPermission })
144
- this.userId = userId
145
- this.requiredPermission = requiredPermission
146
- }
147
- }
148
-
149
- /**
150
- * 超时错误
151
- */
152
- export class TimeoutError extends ZhinError {
153
- public readonly timeoutMs: number
154
-
155
- constructor(message: string, timeoutMs: number, context?: Record<string, any>) {
156
- super(message, 'TIMEOUT_ERROR', { ...context, timeoutMs })
157
- this.timeoutMs = timeoutMs
158
- }
159
- }
160
-
161
- /**
162
- * 错误处理器接口
163
- */
164
- export interface ErrorHandler {
165
- (error: Error, context?: Record<string, any>): void | Promise<void>
166
- }
167
-
168
- /**
169
- * 错误管理器
170
- */
171
- export class ErrorManager {
172
- private handlers: Map<string, ErrorHandler[]> = new Map()
173
- private globalHandlers: ErrorHandler[] = []
174
-
175
- /**
176
- * 注册错误处理器
177
- */
178
- register(errorType: string, handler: ErrorHandler): void {
179
- if (!this.handlers.has(errorType)) {
180
- this.handlers.set(errorType, [])
181
- }
182
- this.handlers.get(errorType)!.push(handler)
183
- }
184
-
185
- /**
186
- * 注册全局错误处理器
187
- */
188
- registerGlobal(handler: ErrorHandler): void {
189
- this.globalHandlers.push(handler)
190
- }
191
-
192
- /**
193
- * 处理错误
194
- */
195
- async handle(error: Error, context?: Record<string, any>): Promise<void> {
196
- // 首先调用全局处理器
197
- for (const handler of this.globalHandlers) {
198
- try {
199
- await handler(error, context)
200
- } catch (handlerError) {
201
- // console.error 已替换为注释
202
- }
203
- }
204
-
205
- // 然后调用特定类型的处理器
206
- const errorType = error.constructor.name
207
- const handlers = this.handlers.get(errorType) || []
208
-
209
- for (const handler of handlers) {
210
- try {
211
- await handler(error, context)
212
- } catch (handlerError) {
213
- // console.error 已替换为注释
214
- }
215
- }
216
- }
217
-
218
- /**
219
- * 移除错误处理器
220
- */
221
- unregister(errorType: string, handler: ErrorHandler): boolean {
222
- const handlers = this.handlers.get(errorType)
223
- if (handlers) {
224
- const index = handlers.indexOf(handler)
225
- if (index !== -1) {
226
- handlers.splice(index, 1)
227
- return true
228
- }
229
- }
230
- return false
231
- }
232
-
233
- /**
234
- * 清理所有处理器
235
- */
236
- clear(): void {
237
- this.handlers.clear()
238
- this.globalHandlers.length = 0
239
- }
240
- }
241
-
242
- /**
243
- * 错误重试工具
244
- */
245
- export class RetryManager {
246
- /**
247
- * 执行重试逻辑
248
- */
249
- static async retry<T>(
250
- fn: () => Promise<T>,
251
- options: {
252
- maxRetries?: number
253
- delay?: number
254
- exponentialBackoff?: boolean
255
- retryCondition?: (error: Error) => boolean
256
- } = {}
257
- ): Promise<T> {
258
- const {
259
- maxRetries = 3,
260
- delay = 1000,
261
- exponentialBackoff = true,
262
- retryCondition = () => true
263
- } = options
264
-
265
- let lastError: Error
266
-
267
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
268
- try {
269
- return await fn()
270
- } catch (error) {
271
- lastError = error as Error
272
-
273
- // 如果是最后一次尝试或不满足重试条件,直接抛出错误
274
- if (attempt === maxRetries || !retryCondition(lastError)) {
275
- throw lastError
276
- }
277
-
278
- // 计算延迟时间
279
- const currentDelay = exponentialBackoff
280
- ? delay * Math.pow(2, attempt)
281
- : delay
282
-
283
- // 等待后重试
284
- await new Promise(resolve => setTimeout(resolve, currentDelay))
285
- }
286
- }
287
-
288
- throw lastError!
289
- }
290
- }
291
-
292
- /**
293
- * 断路器模式实现
294
- */
295
- export class CircuitBreaker {
296
- private failures: number = 0
297
- private lastFailureTime: number = 0
298
- private state: 'CLOSED' | 'OPEN' | 'HALF_OPEN' = 'CLOSED'
299
-
300
- constructor(
301
- private failureThreshold: number = 5,
302
- private timeoutMs: number = 60000,
303
- private monitoringPeriodMs: number = 10000
304
- ) {}
305
-
306
- /**
307
- * 执行受保护的操作
308
- */
309
- async execute<T>(fn: () => Promise<T>): Promise<T> {
310
- if (this.state === 'OPEN') {
311
- if (Date.now() - this.lastFailureTime > this.timeoutMs) {
312
- this.state = 'HALF_OPEN'
313
- } else {
314
- throw new Error('Circuit breaker is OPEN')
315
- }
316
- }
317
-
318
- try {
319
- const result = await fn()
320
- this.onSuccess()
321
- return result
322
- } catch (error) {
323
- this.onFailure()
324
- throw error
325
- }
326
- }
327
-
328
- private onSuccess(): void {
329
- this.failures = 0
330
- this.state = 'CLOSED'
331
- }
332
-
333
- private onFailure(): void {
334
- this.failures++
335
- this.lastFailureTime = Date.now()
336
-
337
- if (this.failures >= this.failureThreshold) {
338
- this.state = 'OPEN'
339
- }
340
- }
341
-
342
- /**
343
- * 获取断路器状态
344
- */
345
- getState(): 'CLOSED' | 'OPEN' | 'HALF_OPEN' {
346
- return this.state
347
- }
348
-
349
- /**
350
- * 重置断路器
351
- */
352
- reset(): void {
353
- this.failures = 0
354
- this.lastFailureTime = 0
355
- this.state = 'CLOSED'
356
- }
357
- }
358
-
359
- // 默认错误管理器实例
360
- export const errorManager = new ErrorManager()
361
-
362
- // 默认错误处理器
363
- errorManager.registerGlobal((error, context) => {
364
- // Default error handler - logs to console
365
- })