@kevairy/template 0.1.3 → 0.1.4

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 (67) hide show
  1. package/package.json +1 -1
  2. package/template/.env +2 -2
  3. package/template/.env.production +6 -0
  4. package/template/src/adapters/auth/index.ts +1 -1
  5. package/template/src/adapters/auth/types.ts +6 -1
  6. package/template/src/api/auth.ts +3 -2
  7. package/template/src/components/core/layouts/art-guide/index.vue +9 -1
  8. package/template/src/components/core/layouts/art-page-content/index.vue +8 -1
  9. package/template/src/config/index.ts +4 -0
  10. package/template/src/directives/core/access.ts +125 -0
  11. package/template/src/directives/core/auth.ts +7 -62
  12. package/template/src/directives/core/roles.ts +5 -83
  13. package/template/src/env.d.ts +1 -0
  14. package/template/src/hooks/core/useAuth.ts +2 -74
  15. package/template/src/hooks/core/useGuide.ts +6 -0
  16. package/template/src/hooks/core/usePermission.ts +41 -0
  17. package/template/src/hooks/index.ts +1 -0
  18. package/template/src/locales/langs/en.json +11 -1
  19. package/template/src/locales/langs/zh.json +11 -1
  20. package/template/src/main.ts +18 -10
  21. package/template/src/router/core/IframeRouteManager.ts +4 -2
  22. package/template/src/router/core/MenuProcessor.ts +5 -40
  23. package/template/src/router/core/RoutePermissionValidator.ts +6 -149
  24. package/template/src/router/core/access.ts +79 -0
  25. package/template/src/router/guards/afterEach.ts +6 -10
  26. package/template/src/router/guards/beforeEach.ts +143 -100
  27. package/template/src/router/guards/error.ts +42 -0
  28. package/template/src/router/index.ts +2 -0
  29. package/template/src/router/modules/examples.ts +4 -3
  30. package/template/src/router/routes/staticRoutes.ts +5 -3
  31. package/template/src/services/auth.ts +32 -10
  32. package/template/src/services/permission.ts +21 -0
  33. package/template/src/store/modules/menu.ts +28 -8
  34. package/template/src/store/modules/user.ts +72 -35
  35. package/template/src/store/modules/worktab.ts +1 -1
  36. package/template/src/types/api/api.d.ts +4 -1
  37. package/template/src/types/config/index.ts +5 -0
  38. package/template/src/types/directive/directive.d.ts +1 -0
  39. package/template/src/types/router/index.ts +6 -0
  40. package/template/src/utils/http/contract.ts +51 -19
  41. package/template/src/utils/http/error.ts +73 -26
  42. package/template/src/utils/http/index.ts +160 -167
  43. package/template/src/utils/http/request-manager.ts +124 -0
  44. package/template/src/utils/http/status.ts +1 -0
  45. package/template/src/utils/permission/index.ts +66 -0
  46. package/template/src/utils/session.ts +24 -0
  47. package/template/src/utils/storage/storage-config.ts +15 -0
  48. package/template/src/utils/storage/storage.ts +5 -3
  49. package/template/src/utils/sys/diagnostics.ts +180 -0
  50. package/template/src/utils/sys/error-handle.ts +56 -126
  51. package/template/src/utils/sys/recovery.ts +31 -0
  52. package/template/src/views/examples/permissions/index.vue +69 -13
  53. package/template/src/views/exception/403/index.vue +33 -0
  54. package/template/src/views/exception/500/index.vue +52 -10
  55. package/template/tests/e2e/permissions.spec.ts +53 -0
  56. package/template/tests/e2e/session-recovery.spec.ts +49 -0
  57. package/template/tests/unit/diagnostics/diagnostics.spec.ts +132 -0
  58. package/template/tests/unit/diagnostics/router.spec.ts +84 -0
  59. package/template/tests/unit/http/auth-lifecycle.spec.ts +203 -0
  60. package/template/tests/unit/http/contract.spec.ts +46 -0
  61. package/template/tests/unit/http/request.spec.ts +487 -0
  62. package/template/tests/unit/permissions/guard.spec.ts +261 -0
  63. package/template/tests/unit/permissions/guide.spec.ts +30 -0
  64. package/template/tests/unit/permissions/rules.spec.ts +106 -0
  65. package/template/tests/unit/permissions/state-and-directives.spec.ts +176 -0
  66. package/template/tests/unit/router/examples.spec.ts +5 -1
  67. package/template/vite.config.ts +5 -2
@@ -9,18 +9,26 @@ import '@styles/index.scss' // 样式
9
9
  import '@kevairy/components/style.css' // 公共组件样式
10
10
  import '@utils/sys/console.ts' // 控制台输出内容
11
11
  import { setupGlobDirectives } from './directives'
12
- import { setupErrorHandle } from './utils/sys/error-handle'
12
+ import { setupErrorHandle, setupGlobalErrorHandlers } from './utils/sys/error-handle'
13
+ import { reportDiagnostic } from './utils/sys/diagnostics'
13
14
  import { initializeApp } from './bootstrap/initializeApp'
14
15
  import { setupOfflineIcons } from '@utils/ui/iconify-loader' // 离线图标集(内网可用)
15
16
 
16
- initializeApp()
17
- setupOfflineIcons()
17
+ setupGlobalErrorHandlers()
18
18
 
19
- const app = createApp(App)
20
- initStore(app)
21
- initRouter(app)
22
- setupGlobDirectives(app)
23
- setupErrorHandle(app)
19
+ try {
20
+ initializeApp()
21
+ setupOfflineIcons()
24
22
 
25
- app.use(language)
26
- app.mount('#app')
23
+ const app = createApp(App)
24
+ setupErrorHandle(app)
25
+ initStore(app)
26
+ initRouter(app)
27
+ setupGlobDirectives(app)
28
+
29
+ app.use(language)
30
+ app.mount('#app')
31
+ } catch (error) {
32
+ reportDiagnostic('bootstrap', error)
33
+ throw error
34
+ }
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import type { AppRouteRecord } from '@/types/router'
11
+ import { StorageConfig } from '@/utils/storage/storage-config'
11
12
 
12
13
  export class IframeRouteManager {
13
14
  private static instance: IframeRouteManager
@@ -50,6 +51,7 @@ export class IframeRouteManager {
50
51
  */
51
52
  clear(): void {
52
53
  this.iframeRoutes = []
54
+ sessionStorage.removeItem(StorageConfig.IFRAME_ROUTES_KEY)
53
55
  }
54
56
 
55
57
  /**
@@ -57,7 +59,7 @@ export class IframeRouteManager {
57
59
  */
58
60
  save(): void {
59
61
  if (this.iframeRoutes.length > 0) {
60
- sessionStorage.setItem('iframeRoutes', JSON.stringify(this.iframeRoutes))
62
+ sessionStorage.setItem(StorageConfig.IFRAME_ROUTES_KEY, JSON.stringify(this.iframeRoutes))
61
63
  }
62
64
  }
63
65
 
@@ -66,7 +68,7 @@ export class IframeRouteManager {
66
68
  */
67
69
  load(): void {
68
70
  try {
69
- const data = sessionStorage.getItem('iframeRoutes')
71
+ const data = sessionStorage.getItem(StorageConfig.IFRAME_ROUTES_KEY)
70
72
  if (data) {
71
73
  this.iframeRoutes = JSON.parse(data)
72
74
  }
@@ -8,7 +8,6 @@
8
8
  */
9
9
 
10
10
  import type { AppRouteRecord } from '@/types/router'
11
- import { useUserStore } from '@/store/modules/user'
12
11
  import { useAppMode } from '@/hooks/core/useAppMode'
13
12
  import { navigationAdapter } from '@/adapters/navigation'
14
13
  import { asyncRoutes } from '../routes/asyncRoutes'
@@ -40,47 +39,16 @@ export class MenuProcessor {
40
39
  * 处理前端控制模式的菜单
41
40
  */
42
41
  private async processFrontendMenu(): Promise<AppRouteRecord[]> {
43
- const userStore = useUserStore()
44
- const roles = userStore.info?.roles
45
-
46
- let menuList = [...asyncRoutes]
47
-
48
- // 根据角色过滤菜单
49
- if (roles && roles.length > 0) {
50
- menuList = this.filterMenuByRoles(menuList, roles)
51
- }
52
-
53
- return this.filterEmptyMenus(menuList)
42
+ return this.filterEmptyMenus([...asyncRoutes])
54
43
  }
55
44
 
56
- /**
57
- * 处理后端控制模式的菜单
58
- */
45
+ /** 后端只负责提供授权路由源;本地限制在菜单 Store 和守卫统一执行。 */
59
46
  private async processBackendMenu(): Promise<AppRouteRecord[]> {
60
47
  const list = await navigationAdapter.getMenuList()
48
+ if (!Array.isArray(list)) throw new Error('菜单适配器必须返回路由数组')
61
49
  return this.filterEmptyMenus(list)
62
50
  }
63
51
 
64
- /**
65
- * 根据角色过滤菜单
66
- */
67
- private filterMenuByRoles(menu: AppRouteRecord[], roles: string[]): AppRouteRecord[] {
68
- return menu.reduce((acc: AppRouteRecord[], item) => {
69
- const itemRoles = item.meta?.roles
70
- const hasPermission = !itemRoles || itemRoles.some((role) => roles?.includes(role))
71
-
72
- if (hasPermission) {
73
- const filteredItem = { ...item }
74
- if (filteredItem.children?.length) {
75
- filteredItem.children = this.filterMenuByRoles(filteredItem.children, roles)
76
- }
77
- acc.push(filteredItem)
78
- }
79
-
80
- return acc
81
- }, [])
82
- }
83
-
84
52
  /**
85
53
  * 递归过滤空菜单项
86
54
  */
@@ -98,10 +66,7 @@ export class MenuProcessor {
98
66
  return item
99
67
  })
100
68
  .filter((item) => {
101
- // 如果定义了 children 属性(即使是空数组),说明这是一个目录菜单,应该保留
102
- if ('children' in item) {
103
- return true
104
- }
69
+ if (item.children?.length) return true
105
70
 
106
71
  // 如果有外链或 iframe,保留
107
72
  if (item.meta?.isIframe === true || item.meta?.link) {
@@ -122,7 +87,7 @@ export class MenuProcessor {
122
87
  * 验证菜单列表是否有效
123
88
  */
124
89
  validateMenuList(menuList: AppRouteRecord[]): boolean {
125
- return Array.isArray(menuList) && menuList.length > 0
90
+ return Array.isArray(menuList)
126
91
  }
127
92
 
128
93
  /**
@@ -1,161 +1,18 @@
1
- /**
2
- * 路由权限验证模块
3
- *
4
- * 提供路由权限验证和路径检查功能
5
- *
6
- * ## 主要功能
7
- *
8
- * - 验证路径是否在用户菜单权限中
9
- * - 构建菜单路径集合(扁平化处理)
10
- * - 支持动态路由参数匹配
11
- * - 路径前缀匹配
12
- *
13
- * ## 使用场景
14
- *
15
- * - 路由守卫中验证用户权限
16
- * - 动态路由注册后的权限检查
17
- * - 防止用户访问无权限的页面
18
- *
19
- * @module router/core/RoutePermissionValidator
20
- * @author Art Design Pro Team
21
- */
22
-
23
1
  import type { AppRouteRecord } from '@/types/router'
2
+ import { resolveRouteChain } from './access'
24
3
 
25
- /**
26
- * 路由权限验证器
27
- */
4
+ /** 路径必须实际声明在授权路由树中,父路径不会授予任意后代路径。 */
28
5
  export class RoutePermissionValidator {
29
- /**
30
- * 验证路径是否在用户菜单权限中
31
- * @param targetPath 目标路径
32
- * @param menuList 菜单列表
33
- * @returns 是否有权限访问
34
- */
35
6
  static hasPermission(targetPath: string, menuList: AppRouteRecord[]): boolean {
36
- // 根路径始终允许访问
37
- if (targetPath === '/') {
38
- return true
39
- }
40
-
41
- return this.matchRoute(targetPath, menuList)
7
+ return targetPath === '/' || resolveRouteChain(targetPath, menuList).length > 0
42
8
  }
43
9
 
44
- /**
45
- * 构建菜单路径集合(扁平化处理)
46
- * @param menuList 菜单列表
47
- * @param pathSet 路径集合
48
- * @returns 路径集合
49
- */
50
- static buildMenuPathSet(
51
- menuList: AppRouteRecord[],
52
- pathSet: Set<string> = new Set()
53
- ): Set<string> {
54
- if (!Array.isArray(menuList) || menuList.length === 0) {
55
- return pathSet
56
- }
57
-
58
- for (const menuItem of menuList) {
59
- if (!menuItem.path) {
60
- continue
61
- }
62
-
63
- // 标准化路径并添加到集合
64
- const menuPath = menuItem.path.startsWith('/') ? menuItem.path : `/${menuItem.path}`
65
- pathSet.add(menuPath)
66
-
67
- // 递归处理子菜单
68
- if (menuItem.children?.length) {
69
- this.buildMenuPathSet(menuItem.children, pathSet)
70
- }
71
- }
72
-
73
- return pathSet
74
- }
75
-
76
- /**
77
- * 检查目标路径是否匹配集合中的某个路径前缀
78
- * 用于支持动态路由参数匹配,如 /user/123 匹配 /user
79
- * @param targetPath 目标路径
80
- * @param pathSet 路径集合
81
- * @returns 是否匹配
82
- */
83
- static checkPathPrefix(targetPath: string, pathSet: Set<string>): boolean {
84
- // 遍历路径集合,检查是否有前缀匹配
85
- for (const menuPath of pathSet) {
86
- if (targetPath.startsWith(`${menuPath}/`)) {
87
- return true
88
- }
89
- }
90
- return false
91
- }
92
-
93
- /**
94
- * 递归匹配路由配置,支持隐藏路由和动态参数路由
95
- */
96
10
  static matchRoute(targetPath: string, routes: AppRouteRecord[]): boolean {
97
- if (!Array.isArray(routes) || routes.length === 0) {
98
- return false
99
- }
100
-
101
- for (const route of routes) {
102
- if (!route.path) {
103
- continue
104
- }
105
-
106
- const routePath = route.path.startsWith('/') ? route.path : `/${route.path}`
107
-
108
- if (
109
- routePath === targetPath ||
110
- this.isDynamicRouteMatch(targetPath, routePath) ||
111
- targetPath.startsWith(`${routePath}/`)
112
- ) {
113
- return true
114
- }
115
-
116
- if (route.children?.length && this.matchRoute(targetPath, route.children)) {
117
- return true
118
- }
119
- }
120
-
121
- return false
122
- }
123
-
124
- /**
125
- * 检查目标路径是否匹配动态参数路由,如 /demo/123 匹配 /demo/:id
126
- */
127
- static isDynamicRouteMatch(targetPath: string, routePath: string): boolean {
128
- if (!routePath.includes(':')) {
129
- return false
130
- }
131
-
132
- const pattern = routePath
133
- .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
134
- .replace(/:([^/]+)/g, '[^/]+')
135
- .replace(/\\\*/g, '.*')
136
-
137
- return new RegExp(`^${pattern}$`).test(targetPath)
11
+ return resolveRouteChain(targetPath, routes).length > 0
138
12
  }
139
13
 
140
- /**
141
- * 验证并返回有效的路径
142
- * 如果目标路径无权限,返回首页路径
143
- * @param targetPath 目标路径
144
- * @param menuList 菜单列表
145
- * @param homePath 首页路径
146
- * @returns 验证后的路径
147
- */
148
- static validatePath(
149
- targetPath: string,
150
- menuList: AppRouteRecord[],
151
- homePath: string = '/'
152
- ): { path: string; hasPermission: boolean } {
14
+ static validatePath(targetPath: string, menuList: AppRouteRecord[], homePath = '/') {
153
15
  const hasPermission = this.hasPermission(targetPath, menuList)
154
-
155
- if (hasPermission) {
156
- return { path: targetPath, hasPermission: true }
157
- }
158
-
159
- return { path: homePath, hasPermission: false }
16
+ return { path: hasPermission ? targetPath : homePath, hasPermission }
160
17
  }
161
18
  }
@@ -0,0 +1,79 @@
1
+ import { createMemoryHistory, createRouter, type RouteRecordRaw, type Router } from 'vue-router'
2
+ import type { AppRouteRecord } from '@/types/router'
3
+ import { canAccessMeta, type AccessContext, type AccessMeta } from '@/utils/permission'
4
+
5
+ const matchers = new WeakMap<AppRouteRecord[], Router>()
6
+ const unmatchedRoute = Symbol('unmatched-access-route')
7
+
8
+ /** 复用 Vue Router 的路径匹配,覆盖参数、可选段和自定义正则,禁止父路径前缀放行。 */
9
+ export function resolveRouteChain(path: string, routes: AppRouteRecord[]) {
10
+ let matcher = matchers.get(routes)
11
+ if (!matcher) {
12
+ const records = (items: AppRouteRecord[]): RouteRecordRaw[] =>
13
+ items
14
+ .filter((item) => !/^https?:\/\//.test(item.path))
15
+ .map((item) => ({
16
+ path: item.path,
17
+ name: item.name,
18
+ meta: item.meta,
19
+ component: { render: () => null },
20
+ children: records(item.children ?? [])
21
+ }))
22
+ matcher = createRouter({
23
+ history: createMemoryHistory(),
24
+ routes: [
25
+ ...records(routes),
26
+ { path: '/:pathMatch(.*)*', name: unmatchedRoute, component: { render: () => null } }
27
+ ]
28
+ })
29
+ matchers.set(routes, matcher)
30
+ }
31
+ return matcher.resolve(path).matched.filter((record) => record.name !== unmatchedRoute)
32
+ }
33
+
34
+ export function canAccessRoute(
35
+ path: string,
36
+ routes: AppRouteRecord[],
37
+ access: AccessContext
38
+ ): boolean {
39
+ const chain = resolveRouteChain(path, routes)
40
+ return (
41
+ chain.length > 0 && chain.every((record) => canAccessMeta(record.meta as AccessMeta, access))
42
+ )
43
+ }
44
+
45
+ export function firstAccessiblePath(routes: AppRouteRecord[]): string {
46
+ for (const route of routes) {
47
+ if (route.meta.isHide || /^https?:\/\//.test(route.path)) continue
48
+ const childPath = firstAccessiblePath(route.children ?? [])
49
+ if (childPath) return childPath
50
+ if (route.component && route.component !== '/index/index' && !route.path.includes(':'))
51
+ return route.path
52
+ }
53
+ return ''
54
+ }
55
+
56
+ /** 父级限制始终生效;隐藏仅影响菜单展示,不改变访问规则。 */
57
+ export function filterAccessibleRoutes(
58
+ routes: AppRouteRecord[],
59
+ access: AccessContext
60
+ ): AppRouteRecord[] {
61
+ return routes.flatMap((route) => {
62
+ if (!canAccessMeta(route.meta, access)) return []
63
+ const children = route.children ? filterAccessibleRoutes(route.children, access) : undefined
64
+ if (
65
+ route.children &&
66
+ !children?.length &&
67
+ (!route.component || route.component === '/index/index')
68
+ )
69
+ return []
70
+ let redirect = route.redirect
71
+ if (
72
+ children?.length &&
73
+ (typeof redirect !== 'string' || !resolveRouteChain(redirect, children).length)
74
+ ) {
75
+ redirect = firstAccessiblePath(children) || children[0].path
76
+ }
77
+ return [{ ...route, redirect, children }]
78
+ })
79
+ }
@@ -1,16 +1,17 @@
1
- import { nextTick } from 'vue'
2
1
  import { useSettingStore } from '@/store/modules/setting'
3
2
  import { Router } from 'vue-router'
4
3
  import NProgress from 'nprogress'
5
4
  import { useCommon } from '@/hooks/core/useCommon'
6
- import { loadingService } from '@/utils/ui'
7
- import { getPendingLoading, resetPendingLoading } from './beforeEach'
5
+ import { closeLoading, getRouteInitInProgress } from './beforeEach'
6
+ import { clearResourceFailure } from '@/utils/sys/recovery'
8
7
 
9
8
  /** 路由全局后置守卫 */
10
9
  export function setupAfterEachGuard(router: Router) {
11
10
  const { scrollToTop } = useCommon()
12
11
 
13
- router.afterEach(() => {
12
+ router.afterEach((to, _from, failure) => {
13
+ if (failure && getRouteInitInProgress()) return
14
+ if (!failure && to.name !== 'Exception500') clearResourceFailure()
14
15
  scrollToTop()
15
16
 
16
17
  // 关闭进度条
@@ -24,11 +25,6 @@ export function setupAfterEachGuard(router: Router) {
24
25
  }
25
26
 
26
27
  // 关闭 loading 效果
27
- if (getPendingLoading()) {
28
- nextTick(() => {
29
- loadingService.hideLoading()
30
- resetPendingLoading()
31
- })
32
- }
28
+ closeLoading()
33
29
  })
34
30
  }