@kevairy/template 0.1.2 → 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.
- package/package.json +1 -1
- package/template/.env +4 -0
- package/template/.env.production +6 -0
- package/template/.prettierignore +2 -0
- package/template/_gitignore +4 -1
- package/template/package.json +10 -0
- package/template/scripts/gen-offline-icons.mjs +84 -0
- package/template/src/adapters/auth/index.ts +1 -1
- package/template/src/adapters/auth/types.ts +6 -1
- package/template/src/api/auth.ts +3 -2
- package/template/src/components/core/forms/art-wang-editor/index.vue +0 -5
- package/template/src/components/core/layouts/art-guide/index.vue +131 -0
- package/template/src/components/core/layouts/art-header-bar/index.vue +26 -26
- package/template/src/components/core/layouts/art-header-bar/widget/ArtUserMenu.vue +17 -1
- package/template/src/components/core/layouts/art-page-content/index.vue +8 -1
- package/template/src/components/core/layouts/art-screen-lock/index.vue +325 -0
- package/template/src/components/core/layouts/art-settings-panel/widget/SettingActions.vue +0 -1
- package/template/src/components/core/media/art-cutter-img/index.vue +0 -1
- package/template/src/components/core/media/art-video-player/index.vue +0 -10
- package/template/src/config/index.ts +8 -1
- package/template/src/config/modules/component.ts +14 -0
- package/template/src/config/modules/guide.ts +122 -0
- package/template/src/config/modules/headerBar.ts +4 -0
- package/template/src/config/setting.ts +2 -2
- package/template/src/directives/core/access.ts +125 -0
- package/template/src/directives/core/auth.ts +7 -62
- package/template/src/directives/core/roles.ts +5 -83
- package/template/src/env.d.ts +1 -0
- package/template/src/hooks/core/useAuth.ts +2 -74
- package/template/src/hooks/core/useGuide.ts +122 -0
- package/template/src/hooks/core/useHeaderBar.ts +6 -0
- package/template/src/hooks/core/usePermission.ts +41 -0
- package/template/src/hooks/index.ts +1 -0
- package/template/src/locales/index.ts +0 -1
- package/template/src/locales/langs/en.json +77 -6
- package/template/src/locales/langs/zh.json +77 -6
- package/template/src/main.ts +19 -9
- package/template/src/router/core/IframeRouteManager.ts +4 -2
- package/template/src/router/core/MenuProcessor.ts +5 -40
- package/template/src/router/core/RoutePermissionValidator.ts +6 -149
- package/template/src/router/core/access.ts +79 -0
- package/template/src/router/guards/afterEach.ts +6 -10
- package/template/src/router/guards/beforeEach.ts +143 -100
- package/template/src/router/guards/error.ts +42 -0
- package/template/src/router/index.ts +2 -0
- package/template/src/router/modules/examples.ts +4 -3
- package/template/src/router/routes/staticRoutes.ts +5 -3
- package/template/src/services/auth.ts +32 -10
- package/template/src/services/permission.ts +21 -0
- package/template/src/store/modules/lock.ts +125 -0
- package/template/src/store/modules/menu.ts +28 -8
- package/template/src/store/modules/setting.ts +8 -15
- package/template/src/store/modules/user.ts +73 -33
- package/template/src/store/modules/worktab.ts +1 -1
- package/template/src/types/api/api.d.ts +4 -1
- package/template/src/types/config/index.ts +9 -0
- package/template/src/types/directive/directive.d.ts +1 -0
- package/template/src/types/import/components.d.ts +2 -0
- package/template/src/types/router/index.ts +6 -0
- package/template/src/utils/http/contract.ts +51 -19
- package/template/src/utils/http/error.ts +73 -26
- package/template/src/utils/http/index.ts +160 -165
- package/template/src/utils/http/request-manager.ts +124 -0
- package/template/src/utils/http/status.ts +1 -0
- package/template/src/utils/permission/index.ts +66 -0
- package/template/src/utils/session.ts +24 -0
- package/template/src/utils/socket/index.ts +27 -2
- package/template/src/utils/storage/storage-config.ts +15 -0
- package/template/src/utils/storage/storage.ts +5 -3
- package/template/src/utils/sys/diagnostics.ts +180 -0
- package/template/src/utils/sys/error-handle.ts +56 -126
- package/template/src/utils/sys/mittBus.ts +5 -0
- package/template/src/utils/sys/recovery.ts +31 -0
- package/template/src/utils/ui/iconify-loader.ts +32 -18
- package/template/src/utils/ui/offline-icons.json +77 -0
- package/template/src/views/examples/permissions/index.vue +69 -13
- package/template/src/views/examples/search-table/index.vue +2 -3
- package/template/src/views/exception/403/index.vue +33 -0
- package/template/src/views/exception/500/index.vue +52 -10
- package/template/tests/e2e/auth.spec.ts +24 -6
- package/template/tests/e2e/helpers/guide.ts +9 -0
- package/template/tests/e2e/permissions.spec.ts +53 -0
- package/template/tests/e2e/search-table.spec.ts +2 -0
- package/template/tests/e2e/session-recovery.spec.ts +49 -0
- package/template/tests/unit/diagnostics/diagnostics.spec.ts +132 -0
- package/template/tests/unit/diagnostics/router.spec.ts +84 -0
- package/template/tests/unit/http/auth-lifecycle.spec.ts +203 -0
- package/template/tests/unit/http/contract.spec.ts +46 -0
- package/template/tests/unit/http/request.spec.ts +487 -0
- package/template/tests/unit/permissions/guard.spec.ts +261 -0
- package/template/tests/unit/permissions/guide.spec.ts +30 -0
- package/template/tests/unit/permissions/rules.spec.ts +106 -0
- package/template/tests/unit/permissions/state-and-directives.spec.ts +176 -0
- package/template/tests/unit/router/examples.spec.ts +5 -1
- package/template/vite.config.ts +8 -2
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export type PermissionRequirement = string | readonly string[]
|
|
2
|
+
export type PermissionMode = 'any' | 'all'
|
|
3
|
+
|
|
4
|
+
export interface AccessContext {
|
|
5
|
+
ready: boolean
|
|
6
|
+
permissions: readonly string[]
|
|
7
|
+
roles: readonly string[]
|
|
8
|
+
wildcard: string | false
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface AccessMeta {
|
|
12
|
+
roles?: string[]
|
|
13
|
+
permissions?: string[]
|
|
14
|
+
permissionMode?: PermissionMode
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** 适配边界将缺失、重复和非法授权值统一为字符串列表。 */
|
|
18
|
+
export function normalizeGrants(value: unknown): string[] {
|
|
19
|
+
if (!Array.isArray(value)) return []
|
|
20
|
+
return [
|
|
21
|
+
...new Set(
|
|
22
|
+
value
|
|
23
|
+
.filter((item): item is string => typeof item === 'string' && !!item.trim())
|
|
24
|
+
.map((item) => item.trim())
|
|
25
|
+
)
|
|
26
|
+
]
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function isValidRequirement(value: unknown): value is PermissionRequirement {
|
|
30
|
+
const values = typeof value === 'string' ? [value] : value
|
|
31
|
+
return (
|
|
32
|
+
Array.isArray(values) &&
|
|
33
|
+
values.length > 0 &&
|
|
34
|
+
values.every((item) => typeof item === 'string' && !!item.trim())
|
|
35
|
+
)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 空要求也是配置错误;全部匹配不会因空数组而意外放行。 */
|
|
39
|
+
export function matchesGrants(
|
|
40
|
+
grants: readonly string[],
|
|
41
|
+
required: unknown,
|
|
42
|
+
mode: PermissionMode = 'any',
|
|
43
|
+
wildcard: string | false = false
|
|
44
|
+
): boolean {
|
|
45
|
+
if (!isValidRequirement(required)) return false
|
|
46
|
+
if (wildcard && grants.includes(wildcard)) return true
|
|
47
|
+
const values = typeof required === 'string' ? [required] : required
|
|
48
|
+
return mode === 'all'
|
|
49
|
+
? values.every((item) => grants.includes(item.trim()))
|
|
50
|
+
: values.some((item) => grants.includes(item.trim()))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function canAccessMeta(meta: AccessMeta, access: AccessContext): boolean {
|
|
54
|
+
if (!access.ready) return false
|
|
55
|
+
if (meta.roles !== undefined && !matchesGrants(access.roles, meta.roles)) return false
|
|
56
|
+
return (
|
|
57
|
+
meta.permissions === undefined ||
|
|
58
|
+
matchesGrants(access.permissions, meta.permissions, meta.permissionMode, access.wildcard)
|
|
59
|
+
)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function warnInvalidRequirement(value: unknown): void {
|
|
63
|
+
if (import.meta.env.DEV && !isValidRequirement(value)) {
|
|
64
|
+
console.warn('[Permission] 权限要求必须是非空字符串或非空字符串数组', value)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { reportDiagnostic } from '@/utils/sys/diagnostics'
|
|
2
|
+
|
|
3
|
+
type SessionCleanup = () => void | Promise<void>
|
|
4
|
+
const cleanups = new Set<SessionCleanup>()
|
|
5
|
+
|
|
6
|
+
/** 注册同步、可重复执行的会话释放函数;业务 Store、Socket、轮询可在此接入。 */
|
|
7
|
+
export function registerSessionCleanup(cleanup: SessionCleanup): () => void {
|
|
8
|
+
cleanups.add(cleanup)
|
|
9
|
+
return () => {
|
|
10
|
+
cleanups.delete(cleanup)
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function runSessionCleanups(): void {
|
|
15
|
+
for (const cleanup of [...cleanups]) {
|
|
16
|
+
try {
|
|
17
|
+
// 不等待异步尾部;账号状态和任务所有权必须在回调同步部分释放。
|
|
18
|
+
const result = cleanup()
|
|
19
|
+
if (result) void result.catch((error) => reportDiagnostic('session', error))
|
|
20
|
+
} catch (error) {
|
|
21
|
+
reportDiagnostic('session', error)
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -1,3 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WebSocket 客户端(可选工具)
|
|
3
|
+
*
|
|
4
|
+
* 单例封装,内置心跳检测、断线重连(指数退避 + 抖动)、连接超时与离线消息队列。
|
|
5
|
+
*
|
|
6
|
+
* ## 使用说明
|
|
7
|
+
*
|
|
8
|
+
* - 模板默认不接线任何业务实时通道,本工具作为可复用能力导出,业务项目按需引入:
|
|
9
|
+
* `import { WebSocketClient } from '@/utils'`(或默认导出 `@/utils/socket`)。
|
|
10
|
+
* - 连接地址优先取 `getInstance({ url })`,否则回退到环境变量 `VITE_WEBSOCKET_URL`;
|
|
11
|
+
* 两者均未配置时跳过连接,不会抛错。
|
|
12
|
+
*
|
|
13
|
+
* @module utils/socket
|
|
14
|
+
*/
|
|
1
15
|
interface WebSocketOptions {
|
|
2
16
|
url?: string
|
|
3
17
|
messageHandler: (event: MessageEvent) => void
|
|
@@ -9,7 +23,7 @@ interface WebSocketOptions {
|
|
|
9
23
|
connectionTimeout?: number // 连接建立超时时间(ms)
|
|
10
24
|
}
|
|
11
25
|
|
|
12
|
-
export
|
|
26
|
+
export class WebSocketClient {
|
|
13
27
|
private static instance: WebSocketClient | null = null
|
|
14
28
|
private ws: WebSocket | null = null
|
|
15
29
|
private url: string
|
|
@@ -39,7 +53,8 @@ export default class WebSocketClient {
|
|
|
39
53
|
private isReconnecting: boolean = false
|
|
40
54
|
|
|
41
55
|
private constructor(options: WebSocketOptions) {
|
|
42
|
-
|
|
56
|
+
// 使用 Vite 环境变量(VITE_ 前缀);模板默认未配置,接入业务时通过 .env 提供 VITE_WEBSOCKET_URL
|
|
57
|
+
this.url = options.url || (import.meta.env.VITE_WEBSOCKET_URL as string) || ''
|
|
43
58
|
this.messageHandler = options.messageHandler
|
|
44
59
|
this.reconnectInterval = options.reconnectInterval ?? 20 * 1000 // 默认20秒
|
|
45
60
|
this.heartbeatInterval = options.heartbeatInterval ?? 5 * 1000 // 默认5秒
|
|
@@ -72,6 +87,12 @@ export default class WebSocketClient {
|
|
|
72
87
|
}
|
|
73
88
|
|
|
74
89
|
private connect(resetReconnectAttempts: boolean = false): void {
|
|
90
|
+
// 未配置 WebSocket 地址时直接跳过,避免 new WebSocket('') 抛错
|
|
91
|
+
if (!this.url) {
|
|
92
|
+
console.warn('WebSocket 地址未配置(VITE_WEBSOCKET_URL),已跳过连接')
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
|
|
75
96
|
// 如果正在连接中,不重复连接
|
|
76
97
|
if (this.isConnecting) {
|
|
77
98
|
console.log('正在建立WebSocket连接中...')
|
|
@@ -421,3 +442,7 @@ export default class WebSocketClient {
|
|
|
421
442
|
}
|
|
422
443
|
}
|
|
423
444
|
}
|
|
445
|
+
|
|
446
|
+
// 同时保留默认导出,兼容 `import WebSocketClient from '@/utils/socket'` 的旧用法;
|
|
447
|
+
// 命名导出使其可经由 `@/utils` 桶文件(export * from './socket')转发。
|
|
448
|
+
export default WebSocketClient
|
|
@@ -43,6 +43,21 @@ export class StorageConfig {
|
|
|
43
43
|
|
|
44
44
|
/** 上次登录用户ID键名(用于判断是否为同一用户登录) */
|
|
45
45
|
static readonly LAST_USER_ID_KEY = `${AppConfig.storage.namespace}-last-user-id`
|
|
46
|
+
static readonly IFRAME_ROUTES_KEY = `${AppConfig.storage.namespace}-iframe-routes`
|
|
47
|
+
|
|
48
|
+
/** 仅移除本应用管理的键,避免影响同域其他应用。 */
|
|
49
|
+
static clearApplicationStorage(storage: Storage): void {
|
|
50
|
+
const keys = [
|
|
51
|
+
this.VERSION_KEY,
|
|
52
|
+
this.THEME_KEY,
|
|
53
|
+
this.LAST_USER_ID_KEY,
|
|
54
|
+
this.RESPONSIVE_MENU_TYPE_KEY,
|
|
55
|
+
this.IFRAME_ROUTES_KEY
|
|
56
|
+
]
|
|
57
|
+
for (const key of Object.keys(storage)) {
|
|
58
|
+
if (this.isVersionedKey(key) || keys.includes(key)) storage.removeItem(key)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
46
61
|
|
|
47
62
|
/** 响应式布局切换时暂存桌面端菜单类型 */
|
|
48
63
|
static readonly RESPONSIVE_MENU_TYPE_KEY = `${AppConfig.storage.namespace}-responsive-menu-type`
|
|
@@ -32,9 +32,9 @@
|
|
|
32
32
|
* @module utils/storage/storage
|
|
33
33
|
* @author Art Design Pro Team
|
|
34
34
|
*/
|
|
35
|
-
import { router } from '@/router'
|
|
36
35
|
import { useUserStore } from '@/store/modules/user'
|
|
37
36
|
import { StorageConfig } from '@/utils/storage/storage-config'
|
|
37
|
+
import { getSessionVersion } from '@/utils/http/request-manager'
|
|
38
38
|
|
|
39
39
|
/**
|
|
40
40
|
* 存储兼容性管理器
|
|
@@ -109,11 +109,13 @@ class StorageCompatibilityManager {
|
|
|
109
109
|
* 执行系统登出
|
|
110
110
|
*/
|
|
111
111
|
private performSystemLogout(): void {
|
|
112
|
+
const session = getSessionVersion()
|
|
112
113
|
setTimeout(() => {
|
|
114
|
+
if (session !== getSessionVersion()) return
|
|
113
115
|
try {
|
|
114
|
-
|
|
116
|
+
StorageConfig.clearApplicationStorage(localStorage)
|
|
117
|
+
StorageConfig.clearApplicationStorage(sessionStorage)
|
|
115
118
|
useUserStore().logOut()
|
|
116
|
-
router.push({ name: 'Login' })
|
|
117
119
|
console.info('[Storage] 已执行系统登出')
|
|
118
120
|
} catch (error) {
|
|
119
121
|
console.error('[Storage] 系统登出失败:', error)
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
export type DiagnosticKind =
|
|
2
|
+
| 'vue'
|
|
3
|
+
| 'script'
|
|
4
|
+
| 'promise'
|
|
5
|
+
| 'resource'
|
|
6
|
+
| 'http'
|
|
7
|
+
| 'router'
|
|
8
|
+
| 'bootstrap'
|
|
9
|
+
| 'session'
|
|
10
|
+
|
|
11
|
+
export interface DiagnosticContext {
|
|
12
|
+
url?: string
|
|
13
|
+
source?: string
|
|
14
|
+
line?: number
|
|
15
|
+
column?: number
|
|
16
|
+
component?: string
|
|
17
|
+
info?: string
|
|
18
|
+
method?: string
|
|
19
|
+
code?: number
|
|
20
|
+
errorKind?: string
|
|
21
|
+
traceId?: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface DiagnosticRecord {
|
|
25
|
+
id: string
|
|
26
|
+
timestamp: string
|
|
27
|
+
kind: DiagnosticKind
|
|
28
|
+
message: string
|
|
29
|
+
stack?: string
|
|
30
|
+
version: string
|
|
31
|
+
buildId: string
|
|
32
|
+
route: string
|
|
33
|
+
context: DiagnosticContext
|
|
34
|
+
count: number
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type DiagnosticReporter = (record: Readonly<DiagnosticRecord>) => void | Promise<void>
|
|
38
|
+
|
|
39
|
+
const records: DiagnosticRecord[] = []
|
|
40
|
+
const fingerprints = new Map<string, DiagnosticRecord>()
|
|
41
|
+
let reporter: DiagnosticReporter | undefined
|
|
42
|
+
let routeProvider = () => window.location.href
|
|
43
|
+
let sequence = 0
|
|
44
|
+
let reporting = 0
|
|
45
|
+
let windowStart = 0
|
|
46
|
+
let windowCount = 0
|
|
47
|
+
|
|
48
|
+
/** URL 仅保留 origin/path;Hash 路由保留路径,移除查询、锚点和 URL 凭据。 */
|
|
49
|
+
export function diagnosticUrl(value: string): string {
|
|
50
|
+
try {
|
|
51
|
+
const url = new URL(value, window.location.origin)
|
|
52
|
+
if (!['http:', 'https:'].includes(url.protocol)) return `[${url.protocol}]`
|
|
53
|
+
const route = url.hash.startsWith('#/') ? `#${url.hash.slice(1).split(/[?#]/)[0]}` : ''
|
|
54
|
+
return `${url.origin}${url.pathname}${route}`.slice(0, 500)
|
|
55
|
+
} catch {
|
|
56
|
+
return '[invalid URL]'
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function redact(value: string, max = 1000): string {
|
|
61
|
+
return value
|
|
62
|
+
.replace(/(?:https?:\/\/|\/)[^\s"'<>]+/g, (url) => diagnosticUrl(url))
|
|
63
|
+
.replace(/\bBearer\s+[^\s,;]+/gi, 'Bearer [redacted]')
|
|
64
|
+
.replace(/(\b(?:authorization|cookie)\s*[:=]\s*)[^\r\n]+/gi, '$1[redacted]')
|
|
65
|
+
.replace(
|
|
66
|
+
/(["']?(?:access[_-]?token|refresh[_-]?token|token|password|authorization|cookie|secret)["']?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)/gi,
|
|
67
|
+
'$1[redacted]'
|
|
68
|
+
)
|
|
69
|
+
.slice(0, max)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 只接收白名单字段;不收集用户信息、请求头、请求体、响应体或组件实例。 */
|
|
73
|
+
function sanitizeContext(context: DiagnosticContext): DiagnosticContext {
|
|
74
|
+
const result: DiagnosticContext = {}
|
|
75
|
+
for (const key of ['url', 'source'] as const) {
|
|
76
|
+
if (typeof context[key] === 'string') result[key] = diagnosticUrl(context[key])
|
|
77
|
+
}
|
|
78
|
+
for (const key of ['component', 'info', 'method', 'errorKind', 'traceId'] as const) {
|
|
79
|
+
if (typeof context[key] === 'string') result[key] = redact(context[key], 200)
|
|
80
|
+
}
|
|
81
|
+
for (const key of ['line', 'column', 'code'] as const) {
|
|
82
|
+
if (typeof context[key] === 'number' && Number.isFinite(context[key]))
|
|
83
|
+
result[key] = context[key]
|
|
84
|
+
}
|
|
85
|
+
return result
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function setDiagnosticReporter(next?: DiagnosticReporter): void {
|
|
89
|
+
reporter = next
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function setDiagnosticRouteProvider(provider: () => string): void {
|
|
93
|
+
routeProvider = provider
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function getDiagnosticRecords(): DiagnosticRecord[] {
|
|
97
|
+
return records.map((record) => ({ ...record, context: { ...record.context } }))
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function clearDiagnosticRecords(): void {
|
|
101
|
+
records.length = 0
|
|
102
|
+
fingerprints.clear()
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 最多保留 50 条;10 秒内重复仅计数;每分钟最多上报 20 条,同时最多 3 条。 */
|
|
106
|
+
export function reportDiagnostic(
|
|
107
|
+
kind: DiagnosticKind,
|
|
108
|
+
error: unknown,
|
|
109
|
+
context: DiagnosticContext = {}
|
|
110
|
+
): void {
|
|
111
|
+
try {
|
|
112
|
+
const candidate = error as {
|
|
113
|
+
name?: string
|
|
114
|
+
kind?: string
|
|
115
|
+
code?: string
|
|
116
|
+
message?: unknown
|
|
117
|
+
} | null
|
|
118
|
+
if (
|
|
119
|
+
candidate?.name === 'AbortError' ||
|
|
120
|
+
candidate?.name === 'CanceledError' ||
|
|
121
|
+
candidate?.kind === 'cancelled' ||
|
|
122
|
+
candidate?.code === 'ERR_CANCELED'
|
|
123
|
+
)
|
|
124
|
+
return
|
|
125
|
+
const rawMessage =
|
|
126
|
+
error instanceof Error ? error.message : typeof error === 'string' ? error : 'Unknown error'
|
|
127
|
+
if (
|
|
128
|
+
/ResizeObserver loop (?:limit exceeded|completed with undelivered notifications)/.test(
|
|
129
|
+
rawMessage
|
|
130
|
+
)
|
|
131
|
+
)
|
|
132
|
+
return
|
|
133
|
+
const message = redact(rawMessage)
|
|
134
|
+
const sanitized = sanitizeContext(context)
|
|
135
|
+
const stack = error instanceof Error && error.stack ? redact(error.stack, 4000) : undefined
|
|
136
|
+
const route = diagnosticUrl(routeProvider())
|
|
137
|
+
const fingerprint = JSON.stringify([kind, message, stack, route, sanitized])
|
|
138
|
+
const now = Date.now()
|
|
139
|
+
const previous = fingerprints.get(fingerprint)
|
|
140
|
+
if (previous && now - Date.parse(previous.timestamp) < 10000) {
|
|
141
|
+
previous.count++
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
const record: DiagnosticRecord = {
|
|
145
|
+
id: `${now.toString(36)}-${++sequence}`,
|
|
146
|
+
timestamp: new Date(now).toISOString(),
|
|
147
|
+
kind,
|
|
148
|
+
message,
|
|
149
|
+
stack,
|
|
150
|
+
version: __APP_VERSION__,
|
|
151
|
+
buildId: typeof __BUILD_ID__ === 'string' ? __BUILD_ID__ : 'dev',
|
|
152
|
+
route,
|
|
153
|
+
context: sanitized,
|
|
154
|
+
count: 1
|
|
155
|
+
}
|
|
156
|
+
records.push(record)
|
|
157
|
+
fingerprints.set(fingerprint, record)
|
|
158
|
+
if (records.length > 50) {
|
|
159
|
+
const removed = records.shift()
|
|
160
|
+
for (const [key, value] of fingerprints) if (value === removed) fingerprints.delete(key)
|
|
161
|
+
}
|
|
162
|
+
console.error('[Diagnostic]', { ...record, context: { ...record.context } })
|
|
163
|
+
if (now - windowStart >= 60000) {
|
|
164
|
+
windowStart = now
|
|
165
|
+
windowCount = 0
|
|
166
|
+
}
|
|
167
|
+
if (!reporter || windowCount >= 20 || reporting >= 3) return
|
|
168
|
+
windowCount++
|
|
169
|
+
reporting++
|
|
170
|
+
const send = reporter
|
|
171
|
+
void Promise.resolve()
|
|
172
|
+
.then(() => send({ ...record, context: { ...record.context } }))
|
|
173
|
+
.catch(() => console.warn('[Diagnostic] 上报失败,记录已保留在本地内存'))
|
|
174
|
+
.finally(() => {
|
|
175
|
+
reporting--
|
|
176
|
+
})
|
|
177
|
+
} catch {
|
|
178
|
+
// 诊断失败不能影响业务,也不能递归进入全局异常处理器。
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -1,143 +1,73 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
*
|
|
4
|
-
* 提供统一的错误捕获和处理机制
|
|
5
|
-
*
|
|
6
|
-
* ## 主要功能
|
|
7
|
-
*
|
|
8
|
-
* - Vue 运行时错误捕获(组件错误、生命周期错误等)
|
|
9
|
-
* - 全局脚本错误捕获(语法错误、运行时错误等)
|
|
10
|
-
* - Promise 未捕获错误处理(unhandledrejection)
|
|
11
|
-
* - 静态资源加载错误监控(图片、脚本、样式等)
|
|
12
|
-
* - 错误日志记录和上报
|
|
13
|
-
* - 统一的错误处理入口
|
|
14
|
-
*
|
|
15
|
-
* ## 使用场景
|
|
16
|
-
* - 应用启动时安装全局错误处理器
|
|
17
|
-
* - 捕获和记录所有类型的错误
|
|
18
|
-
* - 错误上报到监控平台
|
|
19
|
-
* - 提升应用稳定性和可维护性
|
|
20
|
-
* - 问题排查和调试
|
|
21
|
-
*
|
|
22
|
-
* ## 错误类型
|
|
23
|
-
*
|
|
24
|
-
* - VueError: Vue 组件相关错误
|
|
25
|
-
* - ScriptError: JavaScript 脚本错误
|
|
26
|
-
* - PromiseError: Promise 未捕获的 rejection
|
|
27
|
-
* - ResourceError: 静态资源加载失败
|
|
28
|
-
*
|
|
29
|
-
* @module utils/sys/error-handle
|
|
30
|
-
* @author Art Design Pro Team
|
|
31
|
-
*/
|
|
32
|
-
import type { App } from 'vue'
|
|
1
|
+
import type { App, ComponentPublicInstance } from 'vue'
|
|
2
|
+
import { reportDiagnostic } from './diagnostics'
|
|
33
3
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
if (typeof message === 'string') {
|
|
41
|
-
return message
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
if ('message' in message && typeof message.message === 'string') {
|
|
45
|
-
return message.message
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
return ''
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function isIgnorableScriptError(message: Event | string, source?: string): boolean {
|
|
52
|
-
const normalizedMessage = normalizeErrorMessage(message)
|
|
53
|
-
|
|
54
|
-
if (!normalizedMessage) {
|
|
55
|
-
return false
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
if (IGNORABLE_SCRIPT_ERRORS.some((item) => normalizedMessage.includes(item))) {
|
|
59
|
-
// 浏览器/扩展在布局抖动时常见的 ResizeObserver 噪声,不作为真实异常处理
|
|
60
|
-
return true
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// 浏览器扩展注入脚本偶发的跨域 Script error 也没有排查价值
|
|
64
|
-
if (normalizedMessage === 'Script error.' && source === '') {
|
|
65
|
-
return true
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
return false
|
|
4
|
+
export function vueErrorHandler(
|
|
5
|
+
error: unknown,
|
|
6
|
+
instance: ComponentPublicInstance | null,
|
|
7
|
+
info: string
|
|
8
|
+
): void {
|
|
9
|
+
reportDiagnostic('vue', error, { component: instance?.$options.name, info })
|
|
69
10
|
}
|
|
70
11
|
|
|
71
|
-
/**
|
|
72
|
-
* Vue 运行时错误处理
|
|
73
|
-
*/
|
|
74
|
-
export function vueErrorHandler(err: unknown, instance: any, info: string) {
|
|
75
|
-
console.error('[VueError]', err, info, instance)
|
|
76
|
-
// 这里可以上报到服务端,比如:
|
|
77
|
-
// reportError({ type: 'vue', err, info })
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* 全局脚本错误处理
|
|
82
|
-
*/
|
|
83
12
|
export function scriptErrorHandler(
|
|
84
13
|
message: Event | string,
|
|
85
14
|
source?: string,
|
|
86
|
-
|
|
87
|
-
|
|
15
|
+
line?: number,
|
|
16
|
+
column?: number,
|
|
88
17
|
error?: Error
|
|
89
18
|
): boolean {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
}
|
|
19
|
+
const text = typeof message === 'string' ? message : 'Script error'
|
|
20
|
+
if (text === 'Script error.' && !source) return false
|
|
21
|
+
reportDiagnostic('script', error ?? text, { source, line, column })
|
|
22
|
+
// 保留浏览器默认报错,便于生产环境排查。
|
|
23
|
+
return false
|
|
24
|
+
}
|
|
93
25
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
26
|
+
export function registerPromiseErrorHandler(): () => void {
|
|
27
|
+
const listener = (event: PromiseRejectionEvent) => reportDiagnostic('promise', event.reason)
|
|
28
|
+
window.addEventListener('unhandledrejection', listener)
|
|
29
|
+
return () => window.removeEventListener('unhandledrejection', listener)
|
|
97
30
|
}
|
|
98
31
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
32
|
+
export function registerResourceErrorHandler(): () => void {
|
|
33
|
+
const listener = (event: Event) => {
|
|
34
|
+
const target = event.target
|
|
35
|
+
if (
|
|
36
|
+
target instanceof HTMLImageElement ||
|
|
37
|
+
target instanceof HTMLScriptElement ||
|
|
38
|
+
target instanceof HTMLLinkElement
|
|
39
|
+
) {
|
|
40
|
+
reportDiagnostic('resource', `${target.tagName} load failed`, {
|
|
41
|
+
url: target instanceof HTMLLinkElement ? target.href : target.src
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
window.addEventListener('error', listener, true)
|
|
46
|
+
return () => window.removeEventListener('error', listener, true)
|
|
107
47
|
}
|
|
108
48
|
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
*/
|
|
112
|
-
export function
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
(event
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
// reportError({ type: 'resource', target })
|
|
129
|
-
}
|
|
130
|
-
},
|
|
131
|
-
true // 捕获阶段才能监听到资源错误
|
|
132
|
-
)
|
|
49
|
+
let dispose: (() => void) | undefined
|
|
50
|
+
|
|
51
|
+
/** 在应用初始化之前安装;重复安装不会叠加监听器。 */
|
|
52
|
+
export function setupGlobalErrorHandlers(): () => void {
|
|
53
|
+
if (dispose) return dispose
|
|
54
|
+
const onError = (event: ErrorEvent) => {
|
|
55
|
+
if (event instanceof ErrorEvent)
|
|
56
|
+
scriptErrorHandler(event.message, event.filename, event.lineno, event.colno, event.error)
|
|
57
|
+
}
|
|
58
|
+
window.addEventListener('error', onError)
|
|
59
|
+
const removePromise = registerPromiseErrorHandler()
|
|
60
|
+
const removeResource = registerResourceErrorHandler()
|
|
61
|
+
dispose = () => {
|
|
62
|
+
window.removeEventListener('error', onError)
|
|
63
|
+
removePromise()
|
|
64
|
+
removeResource()
|
|
65
|
+
dispose = undefined
|
|
66
|
+
}
|
|
67
|
+
return dispose
|
|
133
68
|
}
|
|
134
69
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
*/
|
|
138
|
-
export function setupErrorHandle(app: App) {
|
|
70
|
+
export function setupErrorHandle(app: App): void {
|
|
71
|
+
setupGlobalErrorHandlers()
|
|
139
72
|
app.config.errorHandler = vueErrorHandler
|
|
140
|
-
window.onerror = scriptErrorHandler
|
|
141
|
-
registerPromiseErrorHandler()
|
|
142
|
-
registerResourceErrorHandler()
|
|
143
73
|
}
|
|
@@ -36,6 +36,8 @@
|
|
|
36
36
|
* - openSetting: 打开设置面板
|
|
37
37
|
* - openSearchDialog: 打开搜索对话框
|
|
38
38
|
* - openChat: 打开聊天窗口
|
|
39
|
+
* - openLockScreen: 打开锁屏界面
|
|
40
|
+
* - startGuide: 启动新手引导
|
|
39
41
|
*
|
|
40
42
|
* @module utils/sys/mittBus
|
|
41
43
|
* @author Art Design Pro Team
|
|
@@ -53,6 +55,9 @@ type Events = {
|
|
|
53
55
|
// 打开聊天窗口事件 - 无参数
|
|
54
56
|
openChat: void
|
|
55
57
|
// 打开锁屏事件 - 无参数
|
|
58
|
+
openLockScreen: void
|
|
59
|
+
// 启动新手引导事件 - 无参数
|
|
60
|
+
startGuide: void
|
|
56
61
|
}
|
|
57
62
|
|
|
58
63
|
// 创建类型安全的事件总线实例
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ref } from 'vue'
|
|
2
|
+
|
|
3
|
+
export const resourceRecoveryNeeded = ref(false)
|
|
4
|
+
let failedPath = '/'
|
|
5
|
+
|
|
6
|
+
export function isChunkLoadError(error: unknown): boolean {
|
|
7
|
+
return (
|
|
8
|
+
error instanceof Error &&
|
|
9
|
+
/Loading (?:CSS )?chunk|ChunkLoadError|Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module|Unable to preload CSS/i.test(
|
|
10
|
+
`${error.name}: ${error.message}`
|
|
11
|
+
)
|
|
12
|
+
)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function markResourceFailure(path?: string): void {
|
|
16
|
+
resourceRecoveryNeeded.value = true
|
|
17
|
+
if (path?.startsWith('/') && !path.startsWith('//')) failedPath = path
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function clearResourceFailure(): void {
|
|
21
|
+
resourceRecoveryNeeded.value = false
|
|
22
|
+
failedPath = '/'
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 仅由用户点击触发,恢复失败地址后整页刷新,不做自动循环刷新。 */
|
|
26
|
+
export function reloadFailedPage(): void {
|
|
27
|
+
const url = new URL(window.location.href)
|
|
28
|
+
url.hash = `#${failedPath}`
|
|
29
|
+
window.history.replaceState(window.history.state, '', url)
|
|
30
|
+
window.location.reload()
|
|
31
|
+
}
|