befly-shared 1.1.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 (76) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +442 -0
  3. package/dist/addonHelper.js +83 -0
  4. package/dist/arrayKeysToCamel.js +18 -0
  5. package/dist/arrayToTree.js +23 -0
  6. package/dist/calcPerfTime.js +13 -0
  7. package/dist/configTypes.js +1 -0
  8. package/dist/defineAddonConfig.js +40 -0
  9. package/dist/fieldClear.js +57 -0
  10. package/dist/genShortId.js +12 -0
  11. package/dist/index.js +25 -0
  12. package/dist/keysToCamel.js +21 -0
  13. package/dist/keysToSnake.js +21 -0
  14. package/dist/layouts.js +59 -0
  15. package/dist/pickFields.js +16 -0
  16. package/dist/redisKeys.js +34 -0
  17. package/dist/regex.js +200 -0
  18. package/dist/scanConfig.js +82 -0
  19. package/dist/scanFiles.js +39 -0
  20. package/dist/scanViews.js +48 -0
  21. package/dist/types.js +46 -0
  22. package/package.json +40 -0
  23. package/src/addonHelper.ts +88 -0
  24. package/src/arrayKeysToCamel.ts +18 -0
  25. package/src/arrayToTree.ts +31 -0
  26. package/src/calcPerfTime.ts +13 -0
  27. package/src/configTypes.ts +27 -0
  28. package/src/defineAddonConfig.ts +45 -0
  29. package/src/fieldClear.ts +75 -0
  30. package/src/genShortId.ts +12 -0
  31. package/src/index.ts +28 -0
  32. package/src/keysToCamel.ts +22 -0
  33. package/src/keysToSnake.ts +22 -0
  34. package/src/layouts.ts +90 -0
  35. package/src/pickFields.ts +19 -0
  36. package/src/redisKeys.ts +44 -0
  37. package/src/regex.ts +223 -0
  38. package/src/scanConfig.ts +104 -0
  39. package/src/scanFiles.ts +49 -0
  40. package/src/scanViews.ts +55 -0
  41. package/src/types.ts +338 -0
  42. package/tests/addonHelper.test.ts +55 -0
  43. package/tests/arrayKeysToCamel.test.ts +21 -0
  44. package/tests/arrayToTree.test.ts +98 -0
  45. package/tests/calcPerfTime.test.ts +19 -0
  46. package/tests/fieldClear.test.ts +39 -0
  47. package/tests/keysToCamel.test.ts +22 -0
  48. package/tests/keysToSnake.test.ts +22 -0
  49. package/tests/layouts.test.ts +93 -0
  50. package/tests/pickFields.test.ts +22 -0
  51. package/tests/regex.test.ts +308 -0
  52. package/tests/scanFiles.test.ts +58 -0
  53. package/tests/types.test.ts +283 -0
  54. package/types/addonConfigMerge.d.ts +17 -0
  55. package/types/addonHelper.d.ts +24 -0
  56. package/types/arrayKeysToCamel.d.ts +13 -0
  57. package/types/arrayToTree.d.ts +8 -0
  58. package/types/calcPerfTime.d.ts +4 -0
  59. package/types/configMerge.d.ts +49 -0
  60. package/types/configTypes.d.ts +26 -0
  61. package/types/defineAddonConfig.d.ts +19 -0
  62. package/types/fieldClear.d.ts +16 -0
  63. package/types/genShortId.d.ts +10 -0
  64. package/types/index.d.ts +22 -0
  65. package/types/keysToCamel.d.ts +10 -0
  66. package/types/keysToSnake.d.ts +10 -0
  67. package/types/layouts.d.ts +29 -0
  68. package/types/loadAndMergeConfig.d.ts +7 -0
  69. package/types/mergeConfig.d.ts +7 -0
  70. package/types/pickFields.d.ts +4 -0
  71. package/types/redisKeys.d.ts +34 -0
  72. package/types/regex.d.ts +143 -0
  73. package/types/scanConfig.d.ts +7 -0
  74. package/types/scanFiles.d.ts +12 -0
  75. package/types/scanViews.d.ts +11 -0
  76. package/types/types.d.ts +274 -0
@@ -0,0 +1,83 @@
1
+ import fs from 'node:fs';
2
+ import { join } from 'pathe';
3
+ import { statSync, existsSync } from 'node:fs';
4
+ /**
5
+ * 扫描所有可用的 addon
6
+ * 优先从本地 addons/ 目录加载,其次从 node_modules/@befly-addon/ 加载
7
+ * @param cwd - 项目根目录,默认为 process.cwd()
8
+ * @returns addon 名称数组
9
+ */
10
+ export const scanAddons = (cwd = process.cwd()) => {
11
+ const addons = new Set();
12
+ // const projectAddonsDir = join(cwd, 'addons');
13
+ // 1. 扫描本地 addons 目录(优先级高)
14
+ // if (existsSync(projectAddonsDir)) {
15
+ // try {
16
+ // const localAddons = fs.readdirSync(projectAddonsDir).filter((name) => {
17
+ // const fullPath = join(projectAddonsDir, name);
18
+ // try {
19
+ // const stat = statSync(fullPath);
20
+ // return stat.isDirectory() && !name.startsWith('_');
21
+ // } catch {
22
+ // return false;
23
+ // }
24
+ // });
25
+ // localAddons.forEach((name) => addons.add(name));
26
+ // } catch (err) {
27
+ // // 忽略本地目录读取错误
28
+ // }
29
+ // }
30
+ // 2. 扫描 node_modules/@befly-addon 目录
31
+ const beflyDir = join(cwd, 'node_modules', '@befly-addon');
32
+ if (existsSync(beflyDir)) {
33
+ try {
34
+ const npmAddons = fs.readdirSync(beflyDir).filter((name) => {
35
+ // 如果本地已存在,跳过 npm 包版本
36
+ if (addons.has(name))
37
+ return false;
38
+ const fullPath = join(beflyDir, name);
39
+ try {
40
+ const stat = statSync(fullPath);
41
+ return stat.isDirectory();
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ });
47
+ npmAddons.forEach((name) => addons.add(name));
48
+ }
49
+ catch {
50
+ // 忽略 npm 目录读取错误
51
+ }
52
+ }
53
+ return Array.from(addons).sort();
54
+ };
55
+ /**
56
+ * 获取 addon 的指定子目录路径
57
+ * 优先返回本地 addons 目录,其次返回 node_modules 目录
58
+ * @param name - addon 名称
59
+ * @param subDir - 子目录名称
60
+ * @param cwd - 项目根目录,默认为 process.cwd()
61
+ * @returns 完整路径
62
+ */
63
+ export const getAddonDir = (name, subDir, cwd = process.cwd()) => {
64
+ // 优先使用本地 addons 目录
65
+ // const projectAddonsDir = join(cwd, 'addons');
66
+ // const localPath = join(projectAddonsDir, name, subDir);
67
+ // if (existsSync(localPath)) {
68
+ // return localPath;
69
+ // }
70
+ // 降级使用 node_modules 目录
71
+ return join(cwd, 'node_modules', '@befly-addon', name, subDir);
72
+ };
73
+ /**
74
+ * 检查 addon 子目录是否存在
75
+ * @param name - addon 名称
76
+ * @param subDir - 子目录名称
77
+ * @param cwd - 项目根目录,默认为 process.cwd()
78
+ * @returns 是否存在
79
+ */
80
+ export const addonDirExists = (name, subDir, cwd = process.cwd()) => {
81
+ const dir = getAddonDir(name, subDir, cwd);
82
+ return existsSync(dir) && statSync(dir).isDirectory();
83
+ };
@@ -0,0 +1,18 @@
1
+ import { keysToCamel } from './keysToCamel.js';
2
+ /**
3
+ * 数组对象字段名批量转小驼峰
4
+ * @param arr - 源数组
5
+ * @returns 字段名转为小驼峰格式的新数组
6
+ *
7
+ * @example
8
+ * arrayKeysToCamel([
9
+ * { user_id: 1, user_name: 'John' },
10
+ * { user_id: 2, user_name: 'Jane' }
11
+ * ])
12
+ * // [{ userId: 1, userName: 'John' }, { userId: 2, userName: 'Jane' }]
13
+ */
14
+ export const arrayKeysToCamel = (arr) => {
15
+ if (!arr || !Array.isArray(arr))
16
+ return arr;
17
+ return arr.map((item) => keysToCamel(item));
18
+ };
@@ -0,0 +1,23 @@
1
+ // arrayToTree 工具函数实现
2
+ export function arrayToTree(items, options = {}) {
3
+ const { idField = 'id', pidField = 'pid', childrenField = 'children', rootPid = 0, mapFn } = options;
4
+ const tree = [];
5
+ for (const item of items) {
6
+ const pid = item[pidField];
7
+ // 用 Object.is 判断,兼容 null/undefined/0
8
+ if (Object.is(pid, rootPid)) {
9
+ let node = { ...item };
10
+ if (mapFn)
11
+ node = mapFn(node);
12
+ const children = arrayToTree(items, {
13
+ ...options,
14
+ rootPid: node[idField]
15
+ });
16
+ if (children.length > 0) {
17
+ node[childrenField] = children;
18
+ }
19
+ tree.push(node);
20
+ }
21
+ }
22
+ return tree;
23
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * 计算性能时间差
3
+ */
4
+ export const calcPerfTime = (startTime, endTime = Bun.nanoseconds()) => {
5
+ const elapsedMs = (endTime - startTime) / 1_000_000;
6
+ if (elapsedMs < 1000) {
7
+ return `${elapsedMs.toFixed(2)} 毫秒`;
8
+ }
9
+ else {
10
+ const elapsedSeconds = elapsedMs / 1000;
11
+ return `${elapsedSeconds.toFixed(2)} 秒`;
12
+ }
13
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,40 @@
1
+ import { join, basename } from 'pathe';
2
+ import { mergeAndConcat } from 'merge-anything';
3
+ import { scanConfig } from './scanConfig.js';
4
+ /**
5
+ * Addon 配置定义函数
6
+ * 接受 addon 配置对象,从当前执行目录的 config 目录下查找同名配置文件进行合并
7
+ * 只能在 addon.config.js 文件中使用
8
+ * @param metaDirname - import.meta.dirname
9
+ * @param addonConfig - addon 配置对象
10
+ * @returns 合并后的配置对象
11
+ * @example
12
+ * ```ts
13
+ * // 在 packages/addonAdmin/addon.config.js 中
14
+ * import { defineAddonConfig } from 'befly-shared';
15
+ *
16
+ * export default defineAddonConfig(import.meta.dirname, {
17
+ * menus: [...]
18
+ * });
19
+ * // 自动从目录名提取 addon 名称,并从 process.cwd()/config/addonAdmin.{js,ts,json} 读取配置并合并
20
+ * ```
21
+ */
22
+ export async function defineAddonConfig(metaDirname, addonConfig = {}) {
23
+ try {
24
+ // 1. 使用 pathe 的 basename 获取完整的目录名(保留 addon 前缀)
25
+ const addonName = basename(metaDirname);
26
+ // 2. 从当前执行目录的 config 目录查找配置
27
+ const projectConfigDir = join(process.cwd(), 'config');
28
+ // 3. 使用 scanConfig 加载项目配置
29
+ const projectConfig = await scanConfig({
30
+ dirs: [projectConfigDir],
31
+ files: [addonName]
32
+ });
33
+ // 4. 合并 addon 配置和项目配置(项目配置优先级更高)
34
+ return mergeAndConcat({}, addonConfig, projectConfig);
35
+ }
36
+ catch (error) {
37
+ console.error('defineAddonConfig 失败:', error.message);
38
+ return addonConfig;
39
+ }
40
+ }
@@ -0,0 +1,57 @@
1
+ // fieldClear 工具函数实现
2
+ // 支持 pick/omit/keepValues/excludeValues,处理对象和数组
3
+ function isObject(val) {
4
+ return val !== null && typeof val === 'object' && !Array.isArray(val);
5
+ }
6
+ function isArray(val) {
7
+ return Array.isArray(val);
8
+ }
9
+ export function fieldClear(data, options = {}) {
10
+ const { pickKeys, omitKeys, keepValues, excludeValues, keepMap } = options;
11
+ const filterObj = (obj) => {
12
+ let result = {};
13
+ let keys = Object.keys(obj);
14
+ if (pickKeys && pickKeys.length) {
15
+ keys = keys.filter((k) => pickKeys.includes(k));
16
+ }
17
+ if (omitKeys && omitKeys.length) {
18
+ keys = keys.filter((k) => !omitKeys.includes(k));
19
+ }
20
+ for (const key of keys) {
21
+ const value = obj[key];
22
+ // 1. 优先检查 keepMap
23
+ if (keepMap && key in keepMap) {
24
+ if (Object.is(keepMap[key], value)) {
25
+ result[key] = value;
26
+ continue;
27
+ }
28
+ }
29
+ // 2. 检查 keepValues (只保留指定值)
30
+ if (keepValues && keepValues.length && !keepValues.includes(value)) {
31
+ continue;
32
+ }
33
+ // 3. 检查 excludeValues (排除指定值)
34
+ if (excludeValues && excludeValues.length && excludeValues.includes(value)) {
35
+ continue;
36
+ }
37
+ result[key] = value;
38
+ }
39
+ return result;
40
+ };
41
+ if (isArray(data)) {
42
+ return data
43
+ .map((item) => (isObject(item) ? filterObj(item) : item))
44
+ .filter((item) => {
45
+ if (isObject(item)) {
46
+ // 只保留有内容的对象
47
+ return Object.keys(item).length > 0;
48
+ }
49
+ // 原始值直接保留
50
+ return true;
51
+ });
52
+ }
53
+ if (isObject(data)) {
54
+ return filterObj(data);
55
+ }
56
+ return data;
57
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * 生成短 ID
3
+ * 由时间戳(base36)+ 随机字符组成,约 13 位
4
+ * - 前 8 位:时间戳(可排序)
5
+ * - 后 5 位:随机字符(防冲突)
6
+ * @returns 短 ID 字符串
7
+ * @example
8
+ * genShortId() // "lxyz1a2b3c4"
9
+ */
10
+ export function genShortId() {
11
+ return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
12
+ }
package/dist/index.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Befly Shared 统一导出
3
+ * 跨包共享的工具函数、常量、类型定义
4
+ */
5
+ // 类型定义
6
+ export * from './types.js';
7
+ // 常量配置
8
+ export * from './redisKeys.js';
9
+ export * from './regex.js';
10
+ // 工具函数
11
+ export * from './defineAddonConfig.js';
12
+ export * from './addonHelper.js';
13
+ export * from './arrayKeysToCamel.js';
14
+ export * from './arrayToTree.js';
15
+ export * from './calcPerfTime.js';
16
+ export * from './configTypes.js';
17
+ export * from './genShortId.js';
18
+ export * from './scanConfig.js';
19
+ export * from './fieldClear.js';
20
+ export * from './keysToCamel.js';
21
+ export * from './keysToSnake.js';
22
+ export * from './layouts.js';
23
+ export * from './pickFields.js';
24
+ export * from './scanFiles.js';
25
+ export * from './scanViews.js';
@@ -0,0 +1,21 @@
1
+ import { isPlainObject } from 'es-toolkit/compat';
2
+ import { camelCase } from 'es-toolkit/string';
3
+ /**
4
+ * 对象字段名转小驼峰
5
+ * @param obj - 源对象
6
+ * @returns 字段名转为小驼峰格式的新对象
7
+ *
8
+ * @example
9
+ * keysToCamel({ user_id: 123, user_name: 'John' }) // { userId: 123, userName: 'John' }
10
+ * keysToCamel({ created_at: 1697452800000 }) // { createdAt: 1697452800000 }
11
+ */
12
+ export const keysToCamel = (obj) => {
13
+ if (!obj || !isPlainObject(obj))
14
+ return obj;
15
+ const result = {};
16
+ for (const [key, value] of Object.entries(obj)) {
17
+ const camelKey = camelCase(key);
18
+ result[camelKey] = value;
19
+ }
20
+ return result;
21
+ };
@@ -0,0 +1,21 @@
1
+ import { isPlainObject } from 'es-toolkit/compat';
2
+ import { snakeCase } from 'es-toolkit/string';
3
+ /**
4
+ * 对象字段名转下划线
5
+ * @param obj - 源对象
6
+ * @returns 字段名转为下划线格式的新对象
7
+ *
8
+ * @example
9
+ * keysToSnake({ userId: 123, userName: 'John' }) // { user_id: 123, user_name: 'John' }
10
+ * keysToSnake({ createdAt: 1697452800000 }) // { created_at: 1697452800000 }
11
+ */
12
+ export const keysToSnake = (obj) => {
13
+ if (!obj || !isPlainObject(obj))
14
+ return obj;
15
+ const result = {};
16
+ for (const [key, value] of Object.entries(obj)) {
17
+ const snakeKey = snakeCase(key);
18
+ result[snakeKey] = value;
19
+ }
20
+ return result;
21
+ };
@@ -0,0 +1,59 @@
1
+ /**
2
+ * 自定义布局处理函数
3
+ * 根据文件名后缀判断使用哪个布局
4
+ * @param routes - 原始路由配置
5
+ * @param inheritLayout - 继承的布局名称(来自父级目录)
6
+ * @returns 处理后的布局配置(不包含实际的布局组件导入)
7
+ */
8
+ export function Layouts(routes, inheritLayout = '') {
9
+ const result = [];
10
+ for (const route of routes) {
11
+ const currentPath = route.path || '';
12
+ // 检查当前路径是否有 _数字 格式
13
+ const pathMatch = currentPath.match(/_(\d+)$/);
14
+ const currentLayout = pathMatch ? pathMatch[1] : inheritLayout;
15
+ // 如果有子路由,说明这是中间节点(目录),不包裹布局,只递归处理子路由
16
+ if (route.children && route.children.length > 0) {
17
+ // 清理路径:如果是 xxx_数字 格式,去掉 _数字
18
+ const cleanPath = pathMatch ? currentPath.replace(/_\d+$/, '') : currentPath;
19
+ // 直接递归处理子路由,不添加当前层级到结果
20
+ const childConfigs = Layouts(route.children, currentLayout);
21
+ // 将子路由的路径前缀加上当前路径
22
+ for (const child of childConfigs) {
23
+ result.push({
24
+ ...child,
25
+ path: cleanPath ? `${cleanPath}/${child.path}`.replace(/\/+/g, '/') : child.path
26
+ });
27
+ }
28
+ continue;
29
+ }
30
+ // 没有子路由的叶子节点,需要包裹布局
31
+ const lastPart = currentPath;
32
+ // 匹配 _数字 格式(如 index_1, news_2)
33
+ const match = lastPart.match(/_(\d+)$/);
34
+ // 优先使用文件自己的布局,其次使用继承的布局,最后使用 default
35
+ const layoutName = match ? match[1] : currentLayout || 'default';
36
+ // 计算清理后的路径
37
+ let cleanPath;
38
+ if (lastPart === 'index' || (lastPart.startsWith('index_') && match)) {
39
+ // index 或 index_数字 → 改为空路径(由父级路径表示)
40
+ cleanPath = '';
41
+ }
42
+ else if (match) {
43
+ // xxx_数字 → 去掉 _数字 后缀
44
+ cleanPath = lastPart.replace(/_\d+$/, '');
45
+ }
46
+ else {
47
+ // 其他 → 保持原样
48
+ cleanPath = lastPart;
49
+ }
50
+ // 返回布局配置(不执行实际导入)
51
+ result.push({
52
+ path: cleanPath,
53
+ layoutName: layoutName,
54
+ component: route.component,
55
+ meta: route.meta
56
+ });
57
+ }
58
+ return result;
59
+ }
@@ -0,0 +1,16 @@
1
+ import { isPlainObject } from 'es-toolkit/compat';
2
+ /**
3
+ * 挑选指定字段
4
+ */
5
+ export const pickFields = (obj, keys) => {
6
+ if (!obj || (!isPlainObject(obj) && !Array.isArray(obj))) {
7
+ return {};
8
+ }
9
+ const result = {};
10
+ for (const key of keys) {
11
+ if (key in obj) {
12
+ result[key] = obj[key];
13
+ }
14
+ }
15
+ return result;
16
+ };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Redis Key 统一管理
3
+ * 所有 Redis 缓存键在此统一定义,避免硬编码分散
4
+ */
5
+ /**
6
+ * Redis Key 生成函数集合
7
+ */
8
+ export const RedisKeys = {
9
+ /** 所有接口缓存 */
10
+ apisAll: () => 'befly:apis:all',
11
+ /** 所有菜单缓存 */
12
+ menusAll: () => 'befly:menus:all',
13
+ /** 角色信息缓存(完整角色对象) */
14
+ roleInfo: (roleCode) => `befly:role:info:${roleCode}`,
15
+ /** 角色接口权限缓存(Set 集合) */
16
+ roleApis: (roleCode) => `befly:role:apis:${roleCode}`,
17
+ /** 表结构缓存 */
18
+ tableColumns: (table) => `befly:table:columns:${table}`
19
+ };
20
+ /**
21
+ * Redis TTL(过期时间)常量配置(单位:秒)
22
+ */
23
+ export const RedisTTL = {
24
+ /** 表结构缓存 - 1小时 */
25
+ tableColumns: 3600,
26
+ /** 角色接口权限 - 24小时 */
27
+ roleApis: 86400,
28
+ /** 角色信息 - 24小时 */
29
+ roleInfo: 86400,
30
+ /** 接口列表 - 永久(不过期) */
31
+ apisAll: null,
32
+ /** 菜单列表 - 永久(不过期) */
33
+ menusAll: null
34
+ };
package/dist/regex.js ADDED
@@ -0,0 +1,200 @@
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
+ word: '^[a-zA-Z]+$',
27
+ /** 字母和数字 */
28
+ alphanumeric: '^[a-zA-Z0-9]+$',
29
+ /** 字母、数字和下划线 */
30
+ alphanumericUnderscore: '^[a-zA-Z0-9_]+$',
31
+ /** 小写字母 */
32
+ lowercase: '^[a-z]+$',
33
+ /** 大写字母 */
34
+ uppercase: '^[A-Z]+$',
35
+ // ============================================
36
+ // 中文
37
+ // ============================================
38
+ /** 纯中文 */
39
+ chinese: '^[\\u4e00-\\u9fa5]+$',
40
+ /** 中文和字母 */
41
+ chineseWord: '^[\\u4e00-\\u9fa5a-zA-Z]+$',
42
+ // ============================================
43
+ // 常用格式
44
+ // ============================================
45
+ /** 邮箱地址 */
46
+ email: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$',
47
+ /** 中国大陆手机号 */
48
+ phone: '^1[3-9]\\d{9}$',
49
+ /** 固定电话(区号-号码) */
50
+ telephone: '^0\\d{2,3}-?\\d{7,8}$',
51
+ /** URL 地址 */
52
+ url: '^https?://',
53
+ /** IPv4 地址 */
54
+ ip: '^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$',
55
+ /** IPv6 地址 */
56
+ ipv6: '^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$',
57
+ /** 域名 */
58
+ domain: '^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$',
59
+ // ============================================
60
+ // 特殊格式
61
+ // ============================================
62
+ /** UUID */
63
+ uuid: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
64
+ /** 十六进制字符串 */
65
+ hex: '^[0-9a-fA-F]+$',
66
+ /** Base64 编码 */
67
+ base64: '^[A-Za-z0-9+/=]+$',
68
+ /** MD5 哈希 */
69
+ md5: '^[a-f0-9]{32}$',
70
+ /** SHA1 哈希 */
71
+ sha1: '^[a-f0-9]{40}$',
72
+ /** SHA256 哈希 */
73
+ sha256: '^[a-f0-9]{64}$',
74
+ // ============================================
75
+ // 日期时间
76
+ // ============================================
77
+ /** 日期 YYYY-MM-DD */
78
+ date: '^\\d{4}-\\d{2}-\\d{2}$',
79
+ /** 时间 HH:MM:SS */
80
+ time: '^\\d{2}:\\d{2}:\\d{2}$',
81
+ /** ISO 日期时间 */
82
+ datetime: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}',
83
+ /** 年份 */
84
+ year: '^\\d{4}$',
85
+ /** 月份 01-12 */
86
+ month: '^(0[1-9]|1[0-2])$',
87
+ /** 日期 01-31 */
88
+ day: '^(0[1-9]|[12]\\d|3[01])$',
89
+ // ============================================
90
+ // 代码相关
91
+ // ============================================
92
+ /** 变量名 */
93
+ variable: '^[a-zA-Z_][a-zA-Z0-9_]*$',
94
+ /** 常量名(全大写) */
95
+ constant: '^[A-Z][A-Z0-9_]*$',
96
+ /** 包名(小写+连字符) */
97
+ package: '^[a-z][a-z0-9-]*$',
98
+ // ============================================
99
+ // 证件相关
100
+ // ============================================
101
+ /** 中国身份证号(18位) */
102
+ idCard: '^\\d{17}[\\dXx]$',
103
+ /** 护照号 */
104
+ passport: '^[a-zA-Z0-9]{5,17}$',
105
+ // ============================================
106
+ // 账号相关(国内常用)
107
+ // ============================================
108
+ /** 银行卡号(16-19位数字) */
109
+ bankCard: '^\\d{16,19}$',
110
+ /** 微信号(6-20位,字母开头,可包含字母、数字、下划线、减号) */
111
+ wechat: '^[a-zA-Z][a-zA-Z0-9_-]{5,19}$',
112
+ /** QQ号(5-11位数字,首位非0) */
113
+ qq: '^[1-9]\\d{4,10}$',
114
+ /** 支付宝账号(手机号或邮箱) */
115
+ alipay: '^(1[3-9]\\d{9}|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,})$',
116
+ /** 用户名(4-20位,字母开头,可包含字母、数字、下划线) */
117
+ username: '^[a-zA-Z][a-zA-Z0-9_]{3,19}$',
118
+ /** 昵称(2-20位,支持中文、字母、数字) */
119
+ nickname: '^[\\u4e00-\\u9fa5a-zA-Z0-9]{2,20}$',
120
+ // ============================================
121
+ // 密码强度
122
+ // ============================================
123
+ /** 弱密码(至少6位) */
124
+ passwordWeak: '^.{6,}$',
125
+ /** 中等密码(至少8位,包含字母和数字) */
126
+ passwordMedium: '^(?=.*[a-zA-Z])(?=.*\\d).{8,}$',
127
+ /** 强密码(至少8位,包含大小写字母、数字和特殊字符) */
128
+ passwordStrong: '^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@#$%^&*]).{8,}$',
129
+ // ============================================
130
+ // 其他常用
131
+ // ============================================
132
+ /** 车牌号(新能源+普通) */
133
+ licensePlate: '^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$',
134
+ /** 邮政编码 */
135
+ postalCode: '^\\d{6}$',
136
+ /** 版本号(语义化版本) */
137
+ semver: '^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.]+)?(\\+[a-zA-Z0-9.]+)?$',
138
+ /** 颜色值(十六进制) */
139
+ colorHex: '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$',
140
+ // ============================================
141
+ // 空值
142
+ // ============================================
143
+ /** 空字符串 */
144
+ empty: '^$',
145
+ /** 非空 */
146
+ notempty: '.+'
147
+ };
148
+ // ============================================
149
+ // 正则表达式缓存(性能优化)
150
+ // ============================================
151
+ const regexCache = new Map();
152
+ /**
153
+ * 获取正则表达式字符串
154
+ * @param name 正则别名(以 @ 开头)或自定义正则字符串
155
+ * @returns 正则表达式字符串
156
+ */
157
+ export function getRegex(name) {
158
+ if (name.startsWith('@')) {
159
+ const alias = name.slice(1);
160
+ return RegexAliases[alias] || name;
161
+ }
162
+ return name;
163
+ }
164
+ /**
165
+ * 获取编译后的正则表达式对象(带缓存)
166
+ * @param pattern 正则别名或正则字符串
167
+ * @param flags 正则标志(如 'i', 'g')
168
+ * @returns 编译后的 RegExp 对象
169
+ */
170
+ export function getCompiledRegex(pattern, flags) {
171
+ const regexStr = getRegex(pattern);
172
+ const cacheKey = `${regexStr}:${flags || ''}`;
173
+ let cached = regexCache.get(cacheKey);
174
+ if (!cached) {
175
+ cached = new RegExp(regexStr, flags);
176
+ regexCache.set(cacheKey, cached);
177
+ }
178
+ return cached;
179
+ }
180
+ /**
181
+ * 验证值是否匹配正则(使用缓存)
182
+ * @param value 要验证的值
183
+ * @param pattern 正则别名或正则字符串
184
+ * @returns 是否匹配
185
+ */
186
+ export function matchRegex(value, pattern) {
187
+ return getCompiledRegex(pattern).test(value);
188
+ }
189
+ /**
190
+ * 清除正则缓存
191
+ */
192
+ export function clearRegexCache() {
193
+ regexCache.clear();
194
+ }
195
+ /**
196
+ * 获取缓存大小
197
+ */
198
+ export function getRegexCacheSize() {
199
+ return regexCache.size;
200
+ }