befly-shared 1.2.8 → 1.3.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.
Files changed (98) hide show
  1. package/package.json +13 -30
  2. package/utils/arrayToTree.ts +135 -0
  3. package/utils/buildTreeByParentPath.ts +127 -0
  4. package/utils/scanViewsDir.ts +148 -0
  5. package/README.md +0 -439
  6. package/dist/addonHelper.js +0 -83
  7. package/dist/arrayKeysToCamel.js +0 -18
  8. package/dist/arrayToTree.js +0 -23
  9. package/dist/calcPerfTime.js +0 -13
  10. package/dist/configTypes.js +0 -1
  11. package/dist/constants.js +0 -46
  12. package/dist/deepTransformKeys.js +0 -139
  13. package/dist/fieldClear.js +0 -57
  14. package/dist/genShortId.js +0 -12
  15. package/dist/hashPassword.js +0 -22
  16. package/dist/index.js +0 -26
  17. package/dist/keysToCamel.js +0 -21
  18. package/dist/keysToSnake.js +0 -21
  19. package/dist/layouts.js +0 -59
  20. package/dist/pickFields.js +0 -16
  21. package/dist/redisKeys.js +0 -34
  22. package/dist/regex.js +0 -202
  23. package/dist/scanConfig.js +0 -83
  24. package/dist/scanFiles.js +0 -39
  25. package/dist/scanViews.js +0 -48
  26. package/dist/withDefaultColumns.js +0 -32
  27. package/src/addonHelper.ts +0 -88
  28. package/src/arrayKeysToCamel.ts +0 -18
  29. package/src/arrayToTree.ts +0 -31
  30. package/src/calcPerfTime.ts +0 -13
  31. package/src/configTypes.ts +0 -29
  32. package/src/constants.ts +0 -60
  33. package/src/deepTransformKeys.ts +0 -172
  34. package/src/fieldClear.ts +0 -75
  35. package/src/genShortId.ts +0 -12
  36. package/src/hashPassword.ts +0 -27
  37. package/src/index.ts +0 -29
  38. package/src/keysToCamel.ts +0 -22
  39. package/src/keysToSnake.ts +0 -22
  40. package/src/layouts.ts +0 -90
  41. package/src/pickFields.ts +0 -19
  42. package/src/redisKeys.ts +0 -44
  43. package/src/regex.ts +0 -225
  44. package/src/scanConfig.ts +0 -106
  45. package/src/scanFiles.ts +0 -49
  46. package/src/scanViews.ts +0 -55
  47. package/src/withDefaultColumns.ts +0 -36
  48. package/tests/addonHelper.test.ts +0 -55
  49. package/tests/arrayKeysToCamel.test.ts +0 -21
  50. package/tests/arrayToTree.test.ts +0 -98
  51. package/tests/calcPerfTime.test.ts +0 -19
  52. package/tests/deepTransformKeys.test.ts +0 -466
  53. package/tests/fieldClear.test.ts +0 -39
  54. package/tests/keysToCamel.test.ts +0 -22
  55. package/tests/keysToSnake.test.ts +0 -22
  56. package/tests/layouts.test.ts +0 -93
  57. package/tests/pickFields.test.ts +0 -22
  58. package/tests/regex.test.ts +0 -308
  59. package/tests/scanFiles.test.ts +0 -58
  60. package/tests/types.test.ts +0 -289
  61. package/types/addon.d.ts +0 -50
  62. package/types/addonConfigMerge.d.ts +0 -17
  63. package/types/addonHelper.d.ts +0 -24
  64. package/types/api.d.ts +0 -63
  65. package/types/arrayKeysToCamel.d.ts +0 -13
  66. package/types/arrayToTree.d.ts +0 -8
  67. package/types/calcPerfTime.d.ts +0 -4
  68. package/types/common.d.ts +0 -8
  69. package/types/configMerge.d.ts +0 -49
  70. package/types/configTypes.d.ts +0 -28
  71. package/types/constants.d.ts +0 -48
  72. package/types/context.d.ts +0 -38
  73. package/types/crypto.d.ts +0 -23
  74. package/types/database.d.ts +0 -55
  75. package/types/deepTransformKeys.d.ts +0 -84
  76. package/types/fieldClear.d.ts +0 -16
  77. package/types/genShortId.d.ts +0 -10
  78. package/types/hashPassword.d.ts +0 -11
  79. package/types/index.d.ts +0 -23
  80. package/types/jwt.d.ts +0 -99
  81. package/types/keysToCamel.d.ts +0 -10
  82. package/types/keysToSnake.d.ts +0 -10
  83. package/types/layouts.d.ts +0 -29
  84. package/types/loadAndMergeConfig.d.ts +0 -7
  85. package/types/logger.d.ts +0 -22
  86. package/types/menu.d.ts +0 -49
  87. package/types/mergeConfig.d.ts +0 -7
  88. package/types/pickFields.d.ts +0 -4
  89. package/types/redisKeys.d.ts +0 -34
  90. package/types/regex.d.ts +0 -145
  91. package/types/scanConfig.d.ts +0 -7
  92. package/types/scanFiles.d.ts +0 -12
  93. package/types/scanViews.d.ts +0 -11
  94. package/types/table.d.ts +0 -49
  95. package/types/tool.d.ts +0 -67
  96. package/types/types.d.ts +0 -44
  97. package/types/validate.d.ts +0 -69
  98. package/types/withDefaultColumns.d.ts +0 -7
package/src/fieldClear.ts DELETED
@@ -1,75 +0,0 @@
1
- // fieldClear 工具函数实现
2
- // 支持 pick/omit/keepValues/excludeValues,处理对象和数组
3
-
4
- export interface FieldClearOptions {
5
- pickKeys?: string[]; // 只保留这些字段
6
- omitKeys?: string[]; // 排除这些字段
7
- keepValues?: any[]; // 只保留这些值
8
- excludeValues?: any[]; // 排除这些值
9
- keepMap?: Record<string, any>; // 强制保留的键值对(优先级最高,忽略 excludeValues)
10
- }
11
-
12
- export type FieldClearResult<T> = T extends Array<infer U> ? Array<FieldClearResult<U>> : T extends object ? { [K in keyof T]?: T[K] } : T;
13
-
14
- function isObject(val: unknown): val is Record<string, any> {
15
- return val !== null && typeof val === 'object' && !Array.isArray(val);
16
- }
17
-
18
- function isArray(val: unknown): val is any[] {
19
- return Array.isArray(val);
20
- }
21
-
22
- export function fieldClear<T = any>(data: T | T[], options: FieldClearOptions = {}): FieldClearResult<T> {
23
- const { pickKeys, omitKeys, keepValues, excludeValues, keepMap } = options;
24
-
25
- const filterObj = (obj: Record<string, any>) => {
26
- let result: Record<string, any> = {};
27
- let keys = Object.keys(obj);
28
- if (pickKeys && pickKeys.length) {
29
- keys = keys.filter((k) => pickKeys.includes(k));
30
- }
31
- if (omitKeys && omitKeys.length) {
32
- keys = keys.filter((k) => !omitKeys.includes(k));
33
- }
34
- for (const key of keys) {
35
- const value = obj[key];
36
-
37
- // 1. 优先检查 keepMap
38
- if (keepMap && key in keepMap) {
39
- if (Object.is(keepMap[key], value)) {
40
- result[key] = value;
41
- continue;
42
- }
43
- }
44
-
45
- // 2. 检查 keepValues (只保留指定值)
46
- if (keepValues && keepValues.length && !keepValues.includes(value)) {
47
- continue;
48
- }
49
-
50
- // 3. 检查 excludeValues (排除指定值)
51
- if (excludeValues && excludeValues.length && excludeValues.includes(value)) {
52
- continue;
53
- }
54
- result[key] = value;
55
- }
56
- return result;
57
- };
58
-
59
- if (isArray(data)) {
60
- return (data as any[])
61
- .map((item) => (isObject(item) ? filterObj(item) : item))
62
- .filter((item) => {
63
- if (isObject(item)) {
64
- // 只保留有内容的对象
65
- return Object.keys(item).length > 0;
66
- }
67
- // 原始值直接保留
68
- return true;
69
- }) as FieldClearResult<T>;
70
- }
71
- if (isObject(data)) {
72
- return filterObj(data as Record<string, any>) as FieldClearResult<T>;
73
- }
74
- return data as FieldClearResult<T>;
75
- }
package/src/genShortId.ts DELETED
@@ -1,12 +0,0 @@
1
- /**
2
- * 生成短 ID
3
- * 由时间戳(base36)+ 随机字符组成,约 13 位
4
- * - 前 8 位:时间戳(可排序)
5
- * - 后 5 位:随机字符(防冲突)
6
- * @returns 短 ID 字符串
7
- * @example
8
- * genShortId() // "lxyz1a2b3c4"
9
- */
10
- export function genShortId(): string {
11
- return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
12
- }
@@ -1,27 +0,0 @@
1
- /**
2
- * 密码哈希工具
3
- * 使用 SHA-256 + 盐值对密码进行单向哈希
4
- */
5
-
6
- /**
7
- * 使用 SHA-256 对密码进行哈希
8
- * @param password - 原始密码
9
- * @param salt - 盐值,默认为 befly
10
- * @returns 哈希后的密码(十六进制字符串)
11
- */
12
- export async function hashPassword(password: string, salt: string = 'befly'): Promise<string> {
13
- const data = password + salt;
14
-
15
- // 将字符串转换为 Uint8Array
16
- const encoder = new TextEncoder();
17
- const dataBuffer = encoder.encode(data);
18
-
19
- // 使用 Web Crypto API 进行 SHA-256 哈希
20
- const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
21
-
22
- // 将 ArrayBuffer 转换为十六进制字符串
23
- const hashArray = Array.from(new Uint8Array(hashBuffer));
24
- const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
25
-
26
- return hashHex;
27
- }
package/src/index.ts DELETED
@@ -1,29 +0,0 @@
1
- /**
2
- * Befly Shared 统一导出
3
- * 跨包共享的工具函数、常量、类型定义
4
- */
5
-
6
- // 常量(运行时)
7
- export * from './constants.js';
8
-
9
- // Redis 键和正则
10
- export * from './redisKeys.js';
11
- export * from './regex.js';
12
-
13
- // 工具函数
14
- export * from './addonHelper.js';
15
- export * from './arrayKeysToCamel.js';
16
- export * from './arrayToTree.js';
17
- export * from './calcPerfTime.js';
18
- export * from './configTypes.js';
19
- export * from './deepTransformKeys.js';
20
- export * from './genShortId.js';
21
- export * from './scanConfig.js';
22
- export * from './fieldClear.js';
23
- export * from './keysToCamel.js';
24
- export * from './keysToSnake.js';
25
- export * from './layouts.js';
26
- export * from './pickFields.js';
27
- export * from './scanFiles.js';
28
- export * from './scanViews.js';
29
- export * from './withDefaultColumns.js';
@@ -1,22 +0,0 @@
1
- import { isPlainObject } from 'es-toolkit/compat';
2
- import { camelCase } from 'es-toolkit/string';
3
-
4
- /**
5
- * 对象字段名转小驼峰
6
- * @param obj - 源对象
7
- * @returns 字段名转为小驼峰格式的新对象
8
- *
9
- * @example
10
- * keysToCamel({ user_id: 123, user_name: 'John' }) // { userId: 123, userName: 'John' }
11
- * keysToCamel({ created_at: 1697452800000 }) // { createdAt: 1697452800000 }
12
- */
13
- export const keysToCamel = <T = any>(obj: Record<string, any>): T => {
14
- if (!obj || !isPlainObject(obj)) return obj as T;
15
-
16
- const result: any = {};
17
- for (const [key, value] of Object.entries(obj)) {
18
- const camelKey = camelCase(key);
19
- result[camelKey] = value;
20
- }
21
- return result;
22
- };
@@ -1,22 +0,0 @@
1
- import { isPlainObject } from 'es-toolkit/compat';
2
- import { snakeCase } from 'es-toolkit/string';
3
-
4
- /**
5
- * 对象字段名转下划线
6
- * @param obj - 源对象
7
- * @returns 字段名转为下划线格式的新对象
8
- *
9
- * @example
10
- * keysToSnake({ userId: 123, userName: 'John' }) // { user_id: 123, user_name: 'John' }
11
- * keysToSnake({ createdAt: 1697452800000 }) // { created_at: 1697452800000 }
12
- */
13
- export const keysToSnake = <T = any>(obj: Record<string, any>): T => {
14
- if (!obj || !isPlainObject(obj)) return obj as T;
15
-
16
- const result: any = {};
17
- for (const [key, value] of Object.entries(obj)) {
18
- const snakeKey = snakeCase(key);
19
- result[snakeKey] = value;
20
- }
21
- return result;
22
- };
package/src/layouts.ts DELETED
@@ -1,90 +0,0 @@
1
- /**
2
- * 路由配置接口
3
- */
4
- export interface RouteConfig {
5
- path?: string;
6
- component?: any;
7
- children?: RouteConfig[];
8
- meta?: Record<string, any>;
9
- [key: string]: any;
10
- }
11
-
12
- /**
13
- * 布局配置接口
14
- */
15
- export interface LayoutConfig {
16
- path: string;
17
- layoutName: string;
18
- component: any;
19
- children?: LayoutConfig[];
20
- meta?: Record<string, any>;
21
- [key: string]: any;
22
- }
23
-
24
- /**
25
- * 自定义布局处理函数
26
- * 根据文件名后缀判断使用哪个布局
27
- * @param routes - 原始路由配置
28
- * @param inheritLayout - 继承的布局名称(来自父级目录)
29
- * @returns 处理后的布局配置(不包含实际的布局组件导入)
30
- */
31
- export function Layouts(routes: RouteConfig[], inheritLayout: string = ''): LayoutConfig[] {
32
- const result: LayoutConfig[] = [];
33
-
34
- for (const route of routes) {
35
- const currentPath = route.path || '';
36
-
37
- // 检查当前路径是否有 _数字 格式
38
- const pathMatch = currentPath.match(/_(\d+)$/);
39
- const currentLayout = pathMatch ? pathMatch[1] : inheritLayout;
40
-
41
- // 如果有子路由,说明这是中间节点(目录),不包裹布局,只递归处理子路由
42
- if (route.children && route.children.length > 0) {
43
- // 清理路径:如果是 xxx_数字 格式,去掉 _数字
44
- const cleanPath = pathMatch ? currentPath.replace(/_\d+$/, '') : currentPath;
45
-
46
- // 直接递归处理子路由,不添加当前层级到结果
47
- const childConfigs = Layouts(route.children, currentLayout);
48
-
49
- // 将子路由的路径前缀加上当前路径
50
- for (const child of childConfigs) {
51
- result.push({
52
- ...child,
53
- path: cleanPath ? `${cleanPath}/${child.path}`.replace(/\/+/g, '/') : child.path
54
- });
55
- }
56
- continue;
57
- }
58
-
59
- // 没有子路由的叶子节点,需要包裹布局
60
- const lastPart = currentPath;
61
-
62
- // 匹配 _数字 格式(如 index_1, news_2)
63
- const match = lastPart.match(/_(\d+)$/);
64
- // 优先使用文件自己的布局,其次使用继承的布局,最后使用 default
65
- const layoutName = match ? match[1] : currentLayout || 'default';
66
-
67
- // 计算清理后的路径
68
- let cleanPath;
69
- if (lastPart === 'index' || (lastPart.startsWith('index_') && match)) {
70
- // index 或 index_数字 → 改为空路径(由父级路径表示)
71
- cleanPath = '';
72
- } else if (match) {
73
- // xxx_数字 → 去掉 _数字 后缀
74
- cleanPath = lastPart.replace(/_\d+$/, '');
75
- } else {
76
- // 其他 → 保持原样
77
- cleanPath = lastPart;
78
- }
79
-
80
- // 返回布局配置(不执行实际导入)
81
- result.push({
82
- path: cleanPath,
83
- layoutName: layoutName,
84
- component: route.component,
85
- meta: route.meta
86
- });
87
- }
88
-
89
- return result;
90
- }
package/src/pickFields.ts DELETED
@@ -1,19 +0,0 @@
1
- import { isPlainObject } from 'es-toolkit/compat';
2
-
3
- /**
4
- * 挑选指定字段
5
- */
6
- export const pickFields = <T extends Record<string, any>>(obj: T, keys: string[]): Partial<T> => {
7
- if (!obj || (!isPlainObject(obj) && !Array.isArray(obj))) {
8
- return {};
9
- }
10
-
11
- const result: any = {};
12
- for (const key of keys) {
13
- if (key in obj) {
14
- result[key] = obj[key];
15
- }
16
- }
17
-
18
- return result;
19
- };
package/src/redisKeys.ts DELETED
@@ -1,44 +0,0 @@
1
- /**
2
- * Redis Key 统一管理
3
- * 所有 Redis 缓存键在此统一定义,避免硬编码分散
4
- */
5
-
6
- /**
7
- * Redis Key 生成函数集合
8
- */
9
- export const RedisKeys = {
10
- /** 所有接口缓存 */
11
- apisAll: () => 'befly:apis:all',
12
-
13
- /** 所有菜单缓存 */
14
- menusAll: () => 'befly:menus:all',
15
-
16
- /** 角色信息缓存(完整角色对象) */
17
- roleInfo: (roleCode: string) => `befly:role:info:${roleCode}`,
18
-
19
- /** 角色接口权限缓存(Set 集合) */
20
- roleApis: (roleCode: string) => `befly:role:apis:${roleCode}`,
21
-
22
- /** 表结构缓存 */
23
- tableColumns: (table: string) => `befly:table:columns:${table}`
24
- } as const;
25
-
26
- /**
27
- * Redis TTL(过期时间)常量配置(单位:秒)
28
- */
29
- export const RedisTTL = {
30
- /** 表结构缓存 - 1小时 */
31
- tableColumns: 3600,
32
-
33
- /** 角色接口权限 - 24小时 */
34
- roleApis: 86400,
35
-
36
- /** 角色信息 - 24小时 */
37
- roleInfo: 86400,
38
-
39
- /** 接口列表 - 永久(不过期) */
40
- apisAll: null,
41
-
42
- /** 菜单列表 - 永久(不过期) */
43
- menusAll: null
44
- } as const;
package/src/regex.ts DELETED
@@ -1,225 +0,0 @@
1
- /**
2
- * 内置正则表达式别名
3
- * 用于表单验证和数据校验
4
- * 命名规范:小驼峰格式
5
- */
6
- export const RegexAliases = {
7
- // ============================================
8
- // 数字类型
9
- // ============================================
10
- /** 正整数(不含0) */
11
- number: '^\\d+$',
12
- /** 整数(含负数) */
13
- integer: '^-?\\d+$',
14
- /** 浮点数 */
15
- float: '^-?\\d+(\\.\\d+)?$',
16
- /** 正整数(不含0) */
17
- positive: '^[1-9]\\d*$',
18
- /** 负整数 */
19
- negative: '^-\\d+$',
20
- /** 零 */
21
- zero: '^0$',
22
-
23
- // ============================================
24
- // 字符串类型
25
- // ============================================
26
- /** 纯字母 */
27
- word: '^[a-zA-Z]+$',
28
- /** 字母和数字 */
29
- alphanumeric: '^[a-zA-Z0-9]+$',
30
- /** 字母、数字和下划线 */
31
- alphanumeric_: '^[a-zA-Z0-9_]+$',
32
- /** 字母、数字、下划线和短横线 */
33
- alphanumericDash_: '^[a-zA-Z0-9_-]+$',
34
- /** 小写字母 */
35
- lowercase: '^[a-z]+$',
36
- /** 大写字母 */
37
- uppercase: '^[A-Z]+$',
38
-
39
- // ============================================
40
- // 中文
41
- // ============================================
42
- /** 纯中文 */
43
- chinese: '^[\\u4e00-\\u9fa5]+$',
44
- /** 中文和字母 */
45
- chineseWord: '^[\\u4e00-\\u9fa5a-zA-Z]+$',
46
-
47
- // ============================================
48
- // 常用格式
49
- // ============================================
50
- /** 邮箱地址 */
51
- email: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$',
52
- /** 中国大陆手机号 */
53
- phone: '^1[3-9]\\d{9}$',
54
- /** 固定电话(区号-号码) */
55
- telephone: '^0\\d{2,3}-?\\d{7,8}$',
56
- /** URL 地址 */
57
- url: '^https?://',
58
- /** IPv4 地址 */
59
- ip: '^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$',
60
- /** IPv6 地址 */
61
- ipv6: '^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$',
62
- /** 域名 */
63
- domain: '^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$',
64
-
65
- // ============================================
66
- // 特殊格式
67
- // ============================================
68
- /** UUID */
69
- uuid: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
70
- /** 十六进制字符串 */
71
- hex: '^[0-9a-fA-F]+$',
72
- /** Base64 编码 */
73
- base64: '^[A-Za-z0-9+/=]+$',
74
- /** MD5 哈希 */
75
- md5: '^[a-f0-9]{32}$',
76
- /** SHA1 哈希 */
77
- sha1: '^[a-f0-9]{40}$',
78
- /** SHA256 哈希 */
79
- sha256: '^[a-f0-9]{64}$',
80
-
81
- // ============================================
82
- // 日期时间
83
- // ============================================
84
- /** 日期 YYYY-MM-DD */
85
- date: '^\\d{4}-\\d{2}-\\d{2}$',
86
- /** 时间 HH:MM:SS */
87
- time: '^\\d{2}:\\d{2}:\\d{2}$',
88
- /** ISO 日期时间 */
89
- datetime: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}',
90
- /** 年份 */
91
- year: '^\\d{4}$',
92
- /** 月份 01-12 */
93
- month: '^(0[1-9]|1[0-2])$',
94
- /** 日期 01-31 */
95
- day: '^(0[1-9]|[12]\\d|3[01])$',
96
-
97
- // ============================================
98
- // 代码相关
99
- // ============================================
100
- /** 变量名 */
101
- variable: '^[a-zA-Z_][a-zA-Z0-9_]*$',
102
- /** 常量名(全大写) */
103
- constant: '^[A-Z][A-Z0-9_]*$',
104
- /** 包名(小写+连字符) */
105
- package: '^[a-z][a-z0-9-]*$',
106
-
107
- // ============================================
108
- // 证件相关
109
- // ============================================
110
- /** 中国身份证号(18位) */
111
- idCard: '^\\d{17}[\\dXx]$',
112
- /** 护照号 */
113
- passport: '^[a-zA-Z0-9]{5,17}$',
114
-
115
- // ============================================
116
- // 账号相关(国内常用)
117
- // ============================================
118
- /** 银行卡号(16-19位数字) */
119
- bankCard: '^\\d{16,19}$',
120
- /** 微信号(6-20位,字母开头,可包含字母、数字、下划线、减号) */
121
- wechat: '^[a-zA-Z][a-zA-Z0-9_-]{5,19}$',
122
- /** QQ号(5-11位数字,首位非0) */
123
- qq: '^[1-9]\\d{4,10}$',
124
- /** 支付宝账号(手机号或邮箱) */
125
- alipay: '^(1[3-9]\\d{9}|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,})$',
126
- /** 用户名(4-20位,字母开头,可包含字母、数字、下划线) */
127
- username: '^[a-zA-Z][a-zA-Z0-9_]{3,19}$',
128
- /** 昵称(2-20位,支持中文、字母、数字) */
129
- nickname: '^[\\u4e00-\\u9fa5a-zA-Z0-9]{2,20}$',
130
-
131
- // ============================================
132
- // 密码强度
133
- // ============================================
134
- /** 弱密码(至少6位) */
135
- passwordWeak: '^.{6,}$',
136
- /** 中等密码(至少8位,包含字母和数字) */
137
- passwordMedium: '^(?=.*[a-zA-Z])(?=.*\\d).{8,}$',
138
- /** 强密码(至少8位,包含大小写字母、数字和特殊字符) */
139
- passwordStrong: '^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@#$%^&*]).{8,}$',
140
-
141
- // ============================================
142
- // 其他常用
143
- // ============================================
144
- /** 车牌号(新能源+普通) */
145
- licensePlate: '^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$',
146
- /** 邮政编码 */
147
- postalCode: '^\\d{6}$',
148
- /** 版本号(语义化版本) */
149
- semver: '^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.]+)?(\\+[a-zA-Z0-9.]+)?$',
150
- /** 颜色值(十六进制) */
151
- colorHex: '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$',
152
-
153
- // ============================================
154
- // 空值
155
- // ============================================
156
- /** 空字符串 */
157
- empty: '^$',
158
- /** 非空 */
159
- notempty: '.+'
160
- } as const;
161
-
162
- /**
163
- * 正则别名类型
164
- */
165
- export type RegexAliasName = keyof typeof RegexAliases;
166
-
167
- // ============================================
168
- // 正则表达式缓存(性能优化)
169
- // ============================================
170
- const regexCache = new Map<string, RegExp>();
171
-
172
- /**
173
- * 获取正则表达式字符串
174
- * @param name 正则别名(以 @ 开头)或自定义正则字符串
175
- * @returns 正则表达式字符串
176
- */
177
- export function getRegex(name: string): string {
178
- if (name.startsWith('@')) {
179
- const alias = name.slice(1) as RegexAliasName;
180
- return RegexAliases[alias] || name;
181
- }
182
- return name;
183
- }
184
-
185
- /**
186
- * 获取编译后的正则表达式对象(带缓存)
187
- * @param pattern 正则别名或正则字符串
188
- * @param flags 正则标志(如 'i', 'g')
189
- * @returns 编译后的 RegExp 对象
190
- */
191
- export function getCompiledRegex(pattern: string, flags?: string): RegExp {
192
- const regexStr = getRegex(pattern);
193
- const cacheKey = `${regexStr}:${flags || ''}`;
194
-
195
- let cached = regexCache.get(cacheKey);
196
- if (!cached) {
197
- cached = new RegExp(regexStr, flags);
198
- regexCache.set(cacheKey, cached);
199
- }
200
- return cached;
201
- }
202
-
203
- /**
204
- * 验证值是否匹配正则(使用缓存)
205
- * @param value 要验证的值
206
- * @param pattern 正则别名或正则字符串
207
- * @returns 是否匹配
208
- */
209
- export function matchRegex(value: string, pattern: string): boolean {
210
- return getCompiledRegex(pattern).test(value);
211
- }
212
-
213
- /**
214
- * 清除正则缓存
215
- */
216
- export function clearRegexCache(): void {
217
- regexCache.clear();
218
- }
219
-
220
- /**
221
- * 获取缓存大小
222
- */
223
- export function getRegexCacheSize(): number {
224
- return regexCache.size;
225
- }
package/src/scanConfig.ts DELETED
@@ -1,106 +0,0 @@
1
- import { existsSync } from 'node:fs';
2
- import { isAbsolute, join } from 'node:path';
3
-
4
- import { mergeAndConcat } from 'merge-anything';
5
- import { isPlainObject } from 'es-toolkit';
6
- import { get, set } from 'es-toolkit/compat';
7
-
8
- import type { LoadConfigOptions } from './configTypes.js';
9
-
10
- /**
11
- * 扫描并合并配置文件(矩阵搜索:dirs × files)
12
- * @param options - 加载选项
13
- * @returns 合并后的配置对象(或第一个找到的配置)
14
- */
15
- export async function scanConfig(options: LoadConfigOptions): Promise<Record<string, any>> {
16
- const {
17
- //
18
- cwd = process.cwd(),
19
- dirs,
20
- files,
21
- extensions = ['.js', '.ts', '.json'],
22
- mode = 'first',
23
- paths,
24
- defaults = {}
25
- } = options;
26
-
27
- // 参数验证
28
- if (!Array.isArray(dirs) || dirs.length === 0) {
29
- throw new Error('dirs 必须是非空数组');
30
- }
31
- if (!Array.isArray(files) || files.length === 0) {
32
- throw new Error('files 必须是非空数组');
33
- }
34
-
35
- const configs: Record<string, any>[] = [];
36
-
37
- // 矩阵搜索:dirs × files × extensions
38
- for (const dir of dirs) {
39
- // 如果是绝对路径则直接使用,否则拼接 cwd
40
- const fullDir = isAbsolute(dir) ? dir : join(cwd, dir);
41
-
42
- for (const file of files) {
43
- for (const ext of extensions) {
44
- const fileName = file.endsWith(ext) ? file : file + ext;
45
- const filePath = join(fullDir, fileName);
46
-
47
- if (existsSync(filePath)) {
48
- try {
49
- // 动态导入配置文件(使用 import 断言处理 JSON)
50
- let data: any;
51
-
52
- if (ext === '.json') {
53
- // JSON 文件使用 import 断言
54
- const module = await import(filePath, { with: { type: 'json' } });
55
- data = module.default;
56
- } else {
57
- // JS/TS 文件使用动态导入
58
- const module = await import(filePath);
59
- data = module.default || module;
60
-
61
- // 处理 async 函数导出(如 defineAddonConfig)
62
- if (data instanceof Promise) {
63
- data = await data;
64
- }
65
- }
66
-
67
- // 验证配置数据
68
- if (!isPlainObject(data)) {
69
- continue;
70
- }
71
-
72
- configs.push(data);
73
-
74
- // 如果模式为 'first',找到第一个配置后立即返回
75
- if (mode === 'first') {
76
- return data;
77
- }
78
-
79
- // 找到后跳过同名文件的其他扩展名
80
- break;
81
- } catch (error: any) {
82
- console.error(`加载配置文件失败: ${filePath}`, error.message);
83
- }
84
- }
85
- }
86
- }
87
- }
88
-
89
- // 合并配置(使用 mergeAndConcat 深度合并)
90
- // 合并顺序:defaults ← configs[0] ← configs[1] ← ...
91
- const finalConfig = mergeAndConcat(defaults, ...configs);
92
-
93
- // 如果指定了 paths,则只返回指定路径的字段
94
- if (paths && paths.length > 0) {
95
- const result: Record<string, any> = {};
96
- for (const path of paths) {
97
- const value = get(finalConfig, path);
98
- if (value !== undefined) {
99
- set(result, path, value);
100
- }
101
- }
102
- return result;
103
- }
104
-
105
- return finalConfig;
106
- }