befly 3.8.30 → 3.8.32

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 (47) hide show
  1. package/README.md +83 -0
  2. package/{config.ts → befly.config.ts} +26 -6
  3. package/checks/checkApp.ts +31 -1
  4. package/hooks/cors.ts +3 -3
  5. package/hooks/parser.ts +3 -3
  6. package/hooks/validator.ts +1 -1
  7. package/lib/cacheHelper.ts +0 -6
  8. package/lib/cipher.ts +2 -1
  9. package/lib/connect.ts +17 -19
  10. package/lib/jwt.ts +1 -1
  11. package/lib/logger.ts +1 -1
  12. package/lib/validator.ts +149 -384
  13. package/loader/loadHooks.ts +4 -3
  14. package/loader/loadPlugins.ts +7 -9
  15. package/main.ts +22 -36
  16. package/package.json +6 -5
  17. package/plugins/cipher.ts +1 -1
  18. package/plugins/config.ts +3 -4
  19. package/plugins/db.ts +4 -5
  20. package/plugins/jwt.ts +3 -2
  21. package/plugins/logger.ts +6 -6
  22. package/plugins/redis.ts +8 -12
  23. package/router/static.ts +3 -6
  24. package/sync/syncAll.ts +7 -12
  25. package/sync/syncApi.ts +4 -3
  26. package/sync/syncDb.ts +6 -5
  27. package/sync/syncDev.ts +9 -8
  28. package/sync/syncMenu.ts +174 -132
  29. package/tests/integration.test.ts +2 -6
  30. package/tests/redisHelper.test.ts +1 -2
  31. package/tests/validator.test.ts +611 -85
  32. package/types/befly.d.ts +7 -0
  33. package/types/cache.d.ts +73 -0
  34. package/types/common.d.ts +1 -37
  35. package/types/database.d.ts +5 -0
  36. package/types/index.ts +5 -5
  37. package/types/plugin.d.ts +1 -4
  38. package/types/redis.d.ts +37 -2
  39. package/types/table.d.ts +6 -44
  40. package/util.ts +283 -0
  41. package/tests/validator-advanced.test.ts +0 -653
  42. package/types/addon.d.ts +0 -50
  43. package/types/crypto.d.ts +0 -23
  44. package/types/jwt.d.ts +0 -99
  45. package/types/logger.d.ts +0 -13
  46. package/types/tool.d.ts +0 -67
  47. package/types/validator.d.ts +0 -43
package/types/befly.d.ts CHANGED
@@ -124,6 +124,13 @@ export interface BeflyOptions {
124
124
  disableHooks?: string[];
125
125
  /** 禁用的插件列表 */
126
126
  disablePlugins?: string[];
127
+ /** 隐藏的菜单路径列表(不同步到数据库) */
128
+ hiddenMenus?: string[];
129
+ /**
130
+ * Addon 运行时配置
131
+ * 按 addon 名称分组,如 addons.admin.email
132
+ */
133
+ addons?: Record<string, Record<string, any>>;
127
134
  /** 其他插件配置 */
128
135
  [key: string]: any;
129
136
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * 缓存助手类型定义
3
+ */
4
+
5
+ import type { BeflyContext } from './befly.js';
6
+
7
+ /**
8
+ * 缓存助手类
9
+ * 负责在服务器启动时缓存接口、菜单和角色权限到 Redis
10
+ */
11
+ export interface CacheHelper {
12
+ /**
13
+ * 缓存所有接口到 Redis
14
+ */
15
+ cacheApis(): Promise<void>;
16
+
17
+ /**
18
+ * 缓存所有菜单到 Redis(从数据库读取)
19
+ */
20
+ cacheMenus(): Promise<void>;
21
+
22
+ /**
23
+ * 缓存所有角色的接口权限到 Redis
24
+ * 优化:使用 Promise.all 利用 Bun Redis 自动 pipeline 特性
25
+ */
26
+ cacheRolePermissions(): Promise<void>;
27
+
28
+ /**
29
+ * 缓存所有数据(接口、菜单、角色权限)
30
+ */
31
+ cacheAll(): Promise<void>;
32
+
33
+ /**
34
+ * 获取缓存的所有接口
35
+ * @returns 接口列表
36
+ */
37
+ getApis(): Promise<any[]>;
38
+
39
+ /**
40
+ * 获取缓存的所有菜单
41
+ * @returns 菜单列表
42
+ */
43
+ getMenus(): Promise<any[]>;
44
+
45
+ /**
46
+ * 获取角色的接口权限
47
+ * @param roleCode - 角色代码
48
+ * @returns 接口路径列表
49
+ */
50
+ getRolePermissions(roleCode: string): Promise<string[]>;
51
+
52
+ /**
53
+ * 检查角色是否有指定接口权限
54
+ * @param roleCode - 角色代码
55
+ * @param apiPath - 接口路径(格式:METHOD/path)
56
+ * @returns 是否有权限
57
+ */
58
+ checkRolePermission(roleCode: string, apiPath: string): Promise<boolean>;
59
+
60
+ /**
61
+ * 删除角色的接口权限缓存
62
+ * @param roleCode - 角色代码
63
+ * @returns 是否删除成功
64
+ */
65
+ deleteRolePermissions(roleCode: string): Promise<boolean>;
66
+ }
67
+
68
+ /**
69
+ * CacheHelper 构造函数类型
70
+ */
71
+ export interface CacheHelperConstructor {
72
+ new (befly: BeflyContext): CacheHelper;
73
+ }
package/types/common.d.ts CHANGED
@@ -1,10 +1,8 @@
1
1
  /**
2
2
  * Befly 框架通用类型定义
3
- * Core 专用类型,befly-shared 的类型请直接从 befly-shared 导入
3
+ * Core 专用类型,通用类型请直接从 befly-shared/types 导入
4
4
  */
5
5
 
6
- import type { SqlValue } from 'befly-shared/types';
7
-
8
6
  // ============================================
9
7
  // Core 专用类型(不适合放在 shared 中的类型)
10
8
  // ============================================
@@ -45,22 +43,6 @@ export type ComparisonOperator = '=' | '>' | '<' | '>=' | '<=' | '!=' | '<>' | '
45
43
  */
46
44
  export type JoinType = 'INNER' | 'LEFT' | 'RIGHT' | 'FULL';
47
45
 
48
- /**
49
- * 日志级别
50
- */
51
- export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
52
-
53
- /**
54
- * 日志配置
55
- */
56
- export interface LoggerConfig {
57
- level?: LogLevel;
58
- transport?: {
59
- target: string;
60
- options?: Record<string, any>;
61
- };
62
- }
63
-
64
46
  /**
65
47
  * 工具函数返回类型
66
48
  */
@@ -70,14 +52,6 @@ export interface ToolResponse<T = any> {
70
52
  error?: string;
71
53
  }
72
54
 
73
- /**
74
- * 分页参数
75
- */
76
- export interface PaginationParams {
77
- page: number;
78
- limit: number;
79
- }
80
-
81
55
  /**
82
56
  * 可选字段
83
57
  */
@@ -88,16 +62,6 @@ export type Optional<T> = T | null | undefined;
88
62
  */
89
63
  export type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]> } : T;
90
64
 
91
- /**
92
- * 保留字段(系统自动管理)
93
- */
94
- export type ReservedFields = 'id' | 'created_at' | 'updated_at' | 'deleted_at' | 'state';
95
-
96
- /**
97
- * 排除保留字段
98
- */
99
- export type ExcludeReserved<T> = Omit<T, ReservedFields>;
100
-
101
65
  /**
102
66
  * 数据库记录基础类型
103
67
  */
@@ -369,6 +369,11 @@ export interface DbHelper {
369
369
  * 查询单个字段值
370
370
  */
371
371
  getFieldValue<T = any>(options: Omit<QueryOptions, 'fields'> & { field: string }): Promise<T | null>;
372
+
373
+ /**
374
+ * 清理数据或 where 条件(默认排除 null 和 undefined)
375
+ */
376
+ cleanFields<T extends Record<string, any>>(data: T, excludeValues?: any[], keepValues?: Record<string, any>): Partial<T>;
372
377
  }
373
378
 
374
379
  /**
package/types/index.ts CHANGED
@@ -1,19 +1,19 @@
1
1
  /**
2
2
  * 类型定义导出
3
+ *
4
+ * 注意:通用类型已迁移到 befly-shared/types
5
+ * - addon, crypto, jwt, logger, tool 等类型请从 befly-shared/types 导入
3
6
  */
4
7
 
5
- export * from './addon.js';
6
8
  export * from './api.js';
7
9
  export * from './befly.js';
10
+ export * from './cache.js';
8
11
  export * from './common.js';
9
12
  export * from './context.js';
10
- export * from './crypto.js';
11
13
  export * from './database.js';
12
- export * from './jwt.js';
13
- export * from './logger.js';
14
+ export * from './hook.js';
14
15
  export * from './plugin.js';
15
16
  export * from './redis.js';
16
17
  export * from './table.js';
17
- export * from './tool.js';
18
18
  export * from './validator.js';
19
19
  export * from './sync.js';
package/types/plugin.d.ts CHANGED
@@ -28,14 +28,11 @@ export interface Plugin {
28
28
  after?: string[];
29
29
 
30
30
  /** 插件初始化函数 */
31
- handler?: (context: BeflyContext, config?: Record<string, any>) => any | Promise<any>;
31
+ handler?: (context: BeflyContext) => any | Promise<any>;
32
32
 
33
33
  /** @deprecated use handler instead */
34
34
  onInit?: PluginInitFunction;
35
35
 
36
- /** 插件配置 */
37
- config?: Record<string, any>;
38
-
39
36
  /** 插件描述 */
40
37
  description?: string;
41
38
 
package/types/redis.d.ts CHANGED
@@ -23,14 +23,13 @@ export type RedisTTL = number | null;
23
23
  * Redis 助手接口
24
24
  */
25
25
  export interface RedisHelper {
26
+ // ==================== 基础操作 ====================
26
27
  /** 设置对象到 Redis */
27
28
  setObject<T = any>(key: string, obj: T, ttl?: RedisTTL): Promise<string | null>;
28
29
  /** 从 Redis 获取对象 */
29
30
  getObject<T = any>(key: string): Promise<T | null>;
30
31
  /** 从 Redis 删除对象 */
31
32
  delObject(key: string): Promise<void>;
32
- /** 生成基于时间的唯一 ID */
33
- genTimeID(): Promise<number>;
34
33
  /** 设置字符串值 */
35
34
  setString(key: string, value: string, ttl?: RedisTTL): Promise<string | null>;
36
35
  /** 获取字符串值 */
@@ -41,6 +40,42 @@ export interface RedisHelper {
41
40
  expire(key: string, seconds: number): Promise<number>;
42
41
  /** 获取剩余过期时间 */
43
42
  ttl(key: string): Promise<number>;
43
+ /** 删除键 */
44
+ del(key: string): Promise<number>;
44
45
  /** 测试 Redis 连接 */
45
46
  ping(): Promise<string>;
47
+
48
+ // ==================== ID 生成 ====================
49
+ /** 生成基于时间的唯一 ID (14位纯数字) */
50
+ genTimeID(): Promise<number>;
51
+ /** 批量生成基于时间的唯一 ID */
52
+ genTimeIDBatch(count: number): Promise<number[]>;
53
+
54
+ // ==================== Set 操作 ====================
55
+ /** 向 Set 中添加一个或多个成员 */
56
+ sadd(key: string, members: string[]): Promise<number>;
57
+ /** 判断成员是否在 Set 中 */
58
+ sismember(key: string, member: string): Promise<number>;
59
+ /** 获取 Set 的成员数量 */
60
+ scard(key: string): Promise<number>;
61
+ /** 获取 Set 的所有成员 */
62
+ smembers(key: string): Promise<string[]>;
63
+
64
+ // ==================== 批量操作 ====================
65
+ /** 批量设置对象 */
66
+ setBatch<T = any>(items: Array<{ key: string; value: T; ttl?: number | null }>): Promise<number>;
67
+ /** 批量获取对象 */
68
+ getBatch<T = any>(keys: string[]): Promise<Array<T | null>>;
69
+ /** 批量删除键 */
70
+ delBatch(keys: string[]): Promise<number>;
71
+ /** 批量检查键是否存在 */
72
+ existsBatch(keys: string[]): Promise<boolean[]>;
73
+ /** 批量设置过期时间 */
74
+ expireBatch(items: Array<{ key: string; seconds: number }>): Promise<number>;
75
+ /** 批量获取剩余过期时间 */
76
+ ttlBatch(keys: string[]): Promise<number[]>;
77
+ /** 批量向多个 Set 添加成员 */
78
+ saddBatch(items: Array<{ key: string; members: string[] }>): Promise<number>;
79
+ /** 批量检查成员是否在 Set 中 */
80
+ sismemberBatch(items: Array<{ key: string; member: string }>): Promise<boolean[]>;
46
81
  }
package/types/table.d.ts CHANGED
@@ -1,50 +1,11 @@
1
1
  /**
2
2
  * 表类型定义 - 用于增强 DbHelper 泛型推断
3
+ *
4
+ * 基础类型(SystemFields, BaseTable, InsertType, UpdateType, SelectType)
5
+ * 请直接从 befly-shared/types 导入
3
6
  */
4
7
 
5
- // ============================================
6
- // 基础表类型
7
- // ============================================
8
-
9
- /**
10
- * 系统字段(所有表都有的字段)
11
- */
12
- export interface SystemFields {
13
- /** 主键 ID(雪花 ID) */
14
- id: number;
15
- /** 状态:0=已删除, 1=正常, 2=禁用 */
16
- state: number;
17
- /** 创建时间(毫秒时间戳) */
18
- createdAt: number;
19
- /** 更新时间(毫秒时间戳) */
20
- updatedAt: number;
21
- /** 删除时间(毫秒时间戳,软删除时设置) */
22
- deletedAt: number | null;
23
- }
24
-
25
- /**
26
- * 基础表类型(包含系统字段)
27
- */
28
- export type BaseTable<T extends Record<string, any>> = T & SystemFields;
29
-
30
- // ============================================
31
- // 表操作类型工具
32
- // ============================================
33
-
34
- /**
35
- * 插入类型:排除系统自动生成的字段
36
- */
37
- export type InsertType<T> = Omit<T, keyof SystemFields>;
38
-
39
- /**
40
- * 更新类型:所有字段可选,排除不可修改的系统字段
41
- */
42
- export type UpdateType<T> = Partial<Omit<T, 'id' | 'createdAt' | 'updatedAt' | 'deletedAt'>>;
43
-
44
- /**
45
- * 查询结果类型:完整的表记录
46
- */
47
- export type SelectType<T> = T;
8
+ import type { BaseTable, InsertType, UpdateType } from 'befly-shared/types';
48
9
 
49
10
  // ============================================
50
11
  // 数据库表映射接口
@@ -205,7 +166,8 @@ export type TypedWhereConditions<T> = Partial<T> & // 精确匹配
205
166
  ArrayConditions<T> & // 数组操作符
206
167
  StringConditions<T> & // 字符串操作符
207
168
  RangeConditions<T> & // 范围操作符
208
- NullConditions<T> & { // 空值操作符
169
+ NullConditions<T> & {
170
+ // 空值操作符
209
171
  /** OR 条件组 */
210
172
  $or?: TypedWhereConditions<T>[];
211
173
  /** AND 条件组 */
package/util.ts ADDED
@@ -0,0 +1,283 @@
1
+ /**
2
+ * 核心工具函数
3
+ */
4
+
5
+ // 内部依赖
6
+ import { existsSync } from 'node:fs';
7
+
8
+ /**
9
+ * 进程角色信息
10
+ */
11
+ export interface ProcessRole {
12
+ /** 进程角色:primary(主进程)或 worker(工作进程) */
13
+ role: 'primary' | 'worker';
14
+ /** 实例 ID(PM2 或 Bun Worker) */
15
+ instanceId: string | null;
16
+ /** 运行环境:bun-cluster、pm2-cluster 或 standalone */
17
+ env: 'bun-cluster' | 'pm2-cluster' | 'standalone';
18
+ }
19
+
20
+ /**
21
+ * 获取当前进程角色信息
22
+ * @returns 进程角色、实例 ID 和运行环境
23
+ */
24
+ export function getProcessRole(): ProcessRole {
25
+ const bunWorkerId = process.env.BUN_WORKER_ID;
26
+ const pm2InstanceId = process.env.PM2_INSTANCE_ID;
27
+
28
+ // Bun 集群模式
29
+ if (bunWorkerId !== undefined) {
30
+ return {
31
+ role: bunWorkerId === '' ? 'primary' : 'worker',
32
+ instanceId: bunWorkerId || '0',
33
+ env: 'bun-cluster'
34
+ };
35
+ }
36
+
37
+ // PM2 集群模式
38
+ if (pm2InstanceId !== undefined) {
39
+ return {
40
+ role: pm2InstanceId === '0' ? 'primary' : 'worker',
41
+ instanceId: pm2InstanceId,
42
+ env: 'pm2-cluster'
43
+ };
44
+ }
45
+
46
+ // 单进程模式
47
+ return {
48
+ role: 'primary',
49
+ instanceId: null,
50
+ env: 'standalone'
51
+ };
52
+ }
53
+
54
+ /**
55
+ * 检测当前进程是否为主进程
56
+ * 用于集群模式下避免重复执行同步任务
57
+ * - Bun 集群:BUN_WORKER_ID 为空时是主进程
58
+ * - PM2 集群:PM2_INSTANCE_ID 为 '0' 或不存在时是主进程
59
+ * @returns 是否为主进程
60
+ */
61
+ export function isPrimaryProcess(): boolean {
62
+ return getProcessRole().role === 'primary';
63
+ }
64
+
65
+ // 外部依赖
66
+ import { camelCase } from 'es-toolkit/string';
67
+ import { scanFiles } from 'befly-shared/scanFiles';
68
+
69
+ // 相对导入
70
+ import { Logger } from './lib/logger.js';
71
+
72
+ // 类型导入
73
+ import type { Plugin } from './types/plugin.js';
74
+ import type { Hook } from './types/hook.js';
75
+ import type { CorsConfig, BeflyContext } from './types/befly.js';
76
+ import type { RequestContext } from './types/context.js';
77
+ import type { PluginRequestHook, Next } from './types/plugin.js';
78
+
79
+ /**
80
+ * 创建错误响应(专用于 Hook 中间件)
81
+ * 在钩子中提前拦截请求时使用
82
+ * @param ctx - 请求上下文
83
+ * @param msg - 错误消息
84
+ * @param code - 错误码,默认 1
85
+ * @param data - 附加数据,默认 null
86
+ * @param detail - 详细信息,用于标记具体提示位置,默认 null
87
+ * @returns Response 对象
88
+ */
89
+ export function ErrorResponse(ctx: RequestContext, msg: string, code: number = 1, data: any = null, detail: any = null): Response {
90
+ // 记录拦截日志
91
+ if (ctx.requestId) {
92
+ const duration = Date.now() - ctx.now;
93
+ const user = ctx.user?.id ? `[User:${ctx.user.id}]` : '[Guest]';
94
+ Logger.info(`[${ctx.requestId}] ${ctx.route} ${user} ${duration}ms [${msg}]`);
95
+ }
96
+
97
+ return Response.json(
98
+ {
99
+ code: code,
100
+ msg: msg,
101
+ data: data,
102
+ detail: detail
103
+ },
104
+ {
105
+ headers: ctx.corsHeaders
106
+ }
107
+ );
108
+ }
109
+
110
+ /**
111
+ * 创建最终响应(专用于 API 路由结尾)
112
+ * 自动处理 ctx.response/ctx.result,并记录请求日志
113
+ * @param ctx - 请求上下文
114
+ * @returns Response 对象
115
+ */
116
+ export function FinalResponse(ctx: RequestContext): Response {
117
+ // 记录请求日志
118
+ if (ctx.api && ctx.requestId) {
119
+ const duration = Date.now() - ctx.now;
120
+ const user = ctx.user?.id ? `[User:${ctx.user.id}]` : '[Guest]';
121
+ Logger.info(`[${ctx.requestId}] ${ctx.route} ${user} ${duration}ms`);
122
+ }
123
+
124
+ // 1. 如果已经有 response,直接返回
125
+ if (ctx.response) {
126
+ return ctx.response;
127
+ }
128
+
129
+ // 2. 如果有 result,格式化为响应
130
+ if (ctx.result !== undefined) {
131
+ let result = ctx.result;
132
+
133
+ // 如果是字符串,自动包裹为成功响应
134
+ if (typeof result === 'string') {
135
+ result = {
136
+ code: 0,
137
+ msg: result
138
+ };
139
+ }
140
+ // 如果是对象,自动补充 code: 0
141
+ else if (result && typeof result === 'object') {
142
+ if (!('code' in result)) {
143
+ result = {
144
+ code: 0,
145
+ ...result
146
+ };
147
+ }
148
+ }
149
+
150
+ // 处理 BigInt 序列化问题
151
+ if (result && typeof result === 'object') {
152
+ const jsonString = JSON.stringify(result, (key, value) => (typeof value === 'bigint' ? value.toString() : value));
153
+ return new Response(jsonString, {
154
+ headers: {
155
+ ...ctx.corsHeaders,
156
+ 'Content-Type': 'application/json'
157
+ }
158
+ });
159
+ } else {
160
+ return Response.json(result, {
161
+ headers: ctx.corsHeaders
162
+ });
163
+ }
164
+ }
165
+
166
+ // 3. 默认响应:没有生成响应
167
+ return Response.json(
168
+ {
169
+ code: 1,
170
+ msg: '未生成响应'
171
+ },
172
+ {
173
+ headers: ctx.corsHeaders
174
+ }
175
+ );
176
+ }
177
+
178
+ /**
179
+ * 设置 CORS 响应头
180
+ * @param req - 请求对象
181
+ * @param config - CORS 配置(可选)
182
+ * @returns CORS 响应头对象
183
+ */
184
+ export function setCorsOptions(req: Request, config: CorsConfig = {}): Record<string, string> {
185
+ const origin = config.origin || '*';
186
+ return {
187
+ 'Access-Control-Allow-Origin': origin === '*' ? req.headers.get('origin') || '*' : origin,
188
+ 'Access-Control-Allow-Methods': config.methods || 'GET, POST, PUT, DELETE, OPTIONS',
189
+ 'Access-Control-Allow-Headers': config.allowedHeaders || 'Content-Type, Authorization, authorization, token',
190
+ 'Access-Control-Expose-Headers': config.exposedHeaders || 'Content-Range, X-Content-Range, Authorization, authorization, token',
191
+ 'Access-Control-Max-Age': String(config.maxAge || 86400),
192
+ 'Access-Control-Allow-Credentials': config.credentials || 'true'
193
+ };
194
+ }
195
+
196
+ /**
197
+ * 扫描模块(插件或钩子)
198
+ * @param dir - 目录路径
199
+ * @param type - 模块类型(core/addon/app)
200
+ * @param moduleLabel - 模块标签(如"插件"、"钩子")
201
+ * @param addonName - 组件名称(仅 type='addon' 时需要)
202
+ * @returns 模块列表
203
+ */
204
+ export async function scanModules<T extends Plugin | Hook>(dir: string, type: 'core' | 'addon' | 'app', moduleLabel: string, addonName?: string): Promise<T[]> {
205
+ if (!existsSync(dir)) return [];
206
+
207
+ const items: T[] = [];
208
+ const files = await scanFiles(dir, '*.{ts,js}');
209
+
210
+ for (const { filePath, fileName } of files) {
211
+ // 生成模块名称
212
+ const name = camelCase(fileName);
213
+ const moduleName = type === 'core' ? name : type === 'addon' ? `addon_${camelCase(addonName!)}_${name}` : `app_${name}`;
214
+
215
+ try {
216
+ const normalizedFilePath = filePath.replace(/\\/g, '/');
217
+ const moduleImport = await import(normalizedFilePath);
218
+ const item = moduleImport.default;
219
+
220
+ item.name = moduleName;
221
+ // 为 addon 模块记录 addon 名称
222
+ if (type === 'addon' && addonName) {
223
+ item.addonName = addonName;
224
+ }
225
+ items.push(item);
226
+ } catch (err: any) {
227
+ const typeLabel = type === 'core' ? '核心' : type === 'addon' ? `组件${addonName}` : '项目';
228
+ Logger.error({ err: err, module: fileName }, `${typeLabel}${moduleLabel} 导入失败`);
229
+ process.exit(1);
230
+ }
231
+ }
232
+
233
+ return items;
234
+ }
235
+
236
+ /**
237
+ * 排序模块(根据依赖关系)
238
+ * @param modules - 待排序的模块列表
239
+ * @returns 排序后的模块列表,如果存在循环依赖或依赖不存在则返回 false
240
+ */
241
+ export function sortModules<T extends { name?: string; after?: string[] }>(modules: T[]): T[] | false {
242
+ const result: T[] = [];
243
+ const visited = new Set<string>();
244
+ const visiting = new Set<string>();
245
+ const moduleMap: Record<string, T> = Object.fromEntries(modules.map((m) => [m.name!, m]));
246
+ let isPass = true;
247
+
248
+ // 检查依赖是否存在
249
+ for (const module of modules) {
250
+ if (module.after) {
251
+ for (const dep of module.after) {
252
+ if (!moduleMap[dep]) {
253
+ Logger.error({ module: module.name, dependency: dep }, '依赖的模块未找到');
254
+ isPass = false;
255
+ }
256
+ }
257
+ }
258
+ }
259
+
260
+ if (!isPass) return false;
261
+
262
+ const visit = (name: string): void => {
263
+ if (visited.has(name)) return;
264
+ if (visiting.has(name)) {
265
+ Logger.error({ module: name }, '模块循环依赖');
266
+ isPass = false;
267
+ return;
268
+ }
269
+
270
+ const module = moduleMap[name];
271
+ if (!module) return;
272
+
273
+ visiting.add(name);
274
+ (module.after || []).forEach(visit);
275
+ visiting.delete(name);
276
+ visited.add(name);
277
+ result.push(module);
278
+ };
279
+
280
+ modules.forEach((m) => visit(m.name!));
281
+
282
+ return isPass ? result : false;
283
+ }