@kevairy/template 0.1.3 → 0.1.5
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 +2 -5
- package/template/.env.production +6 -0
- package/template/README.md +12 -0
- package/template/package.json +5 -5
- package/template/scripts/build-info.ts +76 -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/layouts/art-guide/index.vue +9 -1
- package/template/src/components/core/layouts/art-page-content/index.vue +8 -1
- package/template/src/config/index.ts +4 -0
- 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 +2 -0
- package/template/src/hooks/core/useAuth.ts +2 -74
- package/template/src/hooks/core/useGuide.ts +6 -0
- package/template/src/hooks/core/usePermission.ts +41 -0
- package/template/src/hooks/index.ts +1 -0
- package/template/src/locales/langs/en.json +11 -1
- package/template/src/locales/langs/zh.json +11 -1
- package/template/src/main.ts +18 -10
- 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/menu.ts +28 -8
- package/template/src/store/modules/user.ts +72 -35
- package/template/src/store/modules/worktab.ts +1 -1
- package/template/src/types/api/api.d.ts +4 -1
- package/template/src/types/build-info.ts +11 -0
- package/template/src/types/config/index.ts +5 -2
- package/template/src/types/directive/directive.d.ts +1 -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 -167
- 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/storage/storage-config.ts +15 -0
- package/template/src/utils/storage/storage.ts +5 -3
- package/template/src/utils/sys/console.ts +63 -7
- package/template/src/utils/sys/diagnostics.ts +180 -0
- package/template/src/utils/sys/error-handle.ts +56 -126
- package/template/src/utils/sys/recovery.ts +31 -0
- package/template/src/views/examples/permissions/index.vue +69 -13
- package/template/src/views/exception/403/index.vue +33 -0
- package/template/src/views/exception/500/index.vue +52 -10
- package/template/tests/e2e/permissions.spec.ts +53 -0
- package/template/tests/e2e/session-recovery.spec.ts +49 -0
- package/template/tests/unit/build/build-info.spec.ts +151 -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/tsconfig.json +8 -1
- package/template/vite.config.ts +19 -9
|
@@ -1,46 +1,48 @@
|
|
|
1
|
-
import axios, {
|
|
2
|
-
AxiosRequestConfig,
|
|
3
|
-
AxiosResponse,
|
|
4
|
-
InternalAxiosRequestConfig,
|
|
5
|
-
isAxiosError
|
|
6
|
-
} from 'axios'
|
|
1
|
+
import axios, { AxiosHeaders, type AxiosRequestConfig, type AxiosResponse } from 'axios'
|
|
7
2
|
import { useUserStore } from '@/store/modules/user'
|
|
8
3
|
import { ApiStatus } from './status'
|
|
9
|
-
import { HttpError,
|
|
4
|
+
import { HttpError, toHttpError, showError, showSuccess } from './error'
|
|
10
5
|
import { $t } from '@/locales'
|
|
11
6
|
import type { BaseResponse } from '@/types'
|
|
12
7
|
import { createRequestKey, isApiSuccessCode, normalizeApiCode } from './contract'
|
|
8
|
+
import {
|
|
9
|
+
beginRequest,
|
|
10
|
+
runWithSignal,
|
|
11
|
+
throwIfAborted,
|
|
12
|
+
waitForRetry,
|
|
13
|
+
type RequestScope
|
|
14
|
+
} from './request-manager'
|
|
15
|
+
|
|
16
|
+
export { cancelAllPendingRequests } from './request-manager'
|
|
17
|
+
export { isRequestCanceled } from './error'
|
|
13
18
|
|
|
14
19
|
const REQUEST_TIMEOUT = 15000
|
|
15
|
-
// 网络类错误(超时/5xx)的最大重试次数,通过 VITE_HTTP_MAX_RETRIES 配置,默认 0(不重试)。
|
|
16
|
-
// 注意:POST 等非幂等请求重试存在重复提交风险,开启前请确认后端幂等性。
|
|
17
|
-
const MAX_RETRIES = Math.max(0, Math.floor(Number(import.meta.env.VITE_HTTP_MAX_RETRIES) || 0))
|
|
18
20
|
const RETRY_DELAY = 1000
|
|
19
21
|
const UNAUTHORIZED_DEBOUNCE_TIME = 3000
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
let unauthorizedUntil = 0
|
|
23
|
+
|
|
24
|
+
export interface RetryOptions {
|
|
25
|
+
/** 首次发送之外的额外尝试次数,默认读取 VITE_HTTP_MAX_RETRIES。 */
|
|
26
|
+
retries?: number
|
|
27
|
+
/** 两次尝试间隔,毫秒,默认 1000。 */
|
|
28
|
+
delay?: number
|
|
29
|
+
/** 写请求仅在确认后端幂等后显式开启。 */
|
|
30
|
+
allowUnsafe?: boolean
|
|
31
|
+
}
|
|
24
32
|
|
|
25
33
|
export interface ExtendedAxiosRequestConfig extends AxiosRequestConfig {
|
|
26
|
-
/** 是否展示业务错误消息,默认展示 */
|
|
27
34
|
showErrorMessage?: boolean
|
|
28
|
-
/** 是否展示业务成功消息,默认不展示 */
|
|
29
35
|
showSuccessMessage?: boolean
|
|
30
|
-
/**
|
|
36
|
+
/** 默认并行。显式 true 才取消同 scope、同 key 的上一个逻辑请求。 */
|
|
31
37
|
cancelPrevious?: boolean
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
interface TrackedRequestConfig extends InternalAxiosRequestConfig {
|
|
38
|
+
/** 可显式分组不同参数的请求;上传等数据仅在显式指定 key 时去重。 */
|
|
35
39
|
requestKey?: string
|
|
36
|
-
|
|
37
|
-
|
|
40
|
+
/** 各页面/组件可用独立的 string 或 Symbol 防止互相取消。 */
|
|
41
|
+
requestScope?: RequestScope
|
|
42
|
+
retry?: false | RetryOptions
|
|
38
43
|
}
|
|
39
44
|
|
|
40
45
|
const { VITE_API_URL, VITE_WITH_CREDENTIALS, VITE_AUTH_SCHEME } = import.meta.env
|
|
41
|
-
const pendingRequests = new Map<string, AbortController>()
|
|
42
|
-
let requestSequence = 0
|
|
43
|
-
|
|
44
46
|
const axiosInstance = axios.create({
|
|
45
47
|
timeout: REQUEST_TIMEOUT,
|
|
46
48
|
baseURL: VITE_API_URL,
|
|
@@ -48,181 +50,172 @@ const axiosInstance = axios.create({
|
|
|
48
50
|
validateStatus: (status) => status >= 200 && status < 300
|
|
49
51
|
})
|
|
50
52
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const scheme = VITE_AUTH_SCHEME ? `${VITE_AUTH_SCHEME.trim()} ` : ''
|
|
56
|
-
request.headers.set('Authorization', `${scheme}${userStore.accessToken}`)
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
if (request.data && !(request.data instanceof FormData) && !request.headers['Content-Type']) {
|
|
60
|
-
request.headers.set('Content-Type', 'application/json')
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
const baseRequestKey = createRequestKey(request)
|
|
64
|
-
const requestKey =
|
|
65
|
-
request.cancelPrevious === false ? `${baseRequestKey}|${++requestSequence}` : baseRequestKey
|
|
66
|
-
request.requestKey = requestKey
|
|
67
|
-
|
|
68
|
-
if (request.cancelPrevious !== false) {
|
|
69
|
-
pendingRequests.get(baseRequestKey)?.abort('Duplicated request cancelled')
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const controller = new AbortController()
|
|
73
|
-
request.abortController = controller
|
|
74
|
-
request.signal = controller.signal
|
|
75
|
-
pendingRequests.set(requestKey, controller)
|
|
53
|
+
function nonNegativeInteger(value: unknown, fallback: number): number {
|
|
54
|
+
const number = Number(value)
|
|
55
|
+
return Number.isFinite(number) && number >= 0 ? Math.floor(number) : fallback
|
|
56
|
+
}
|
|
76
57
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
58
|
+
function retryPolicy(config: ExtendedAxiosRequestConfig) {
|
|
59
|
+
const safe = ['GET', 'HEAD'].includes(config.method?.toUpperCase() || 'GET')
|
|
60
|
+
const options = config.retry === false ? undefined : config.retry
|
|
61
|
+
return {
|
|
62
|
+
retries:
|
|
63
|
+
config.retry === false || (!safe && options?.allowUnsafe !== true)
|
|
64
|
+
? 0
|
|
65
|
+
: options?.retries === undefined
|
|
66
|
+
? nonNegativeInteger(import.meta.env.VITE_HTTP_MAX_RETRIES, 0)
|
|
67
|
+
: nonNegativeInteger(options.retries, 0),
|
|
68
|
+
delay: nonNegativeInteger(options?.delay, RETRY_DELAY)
|
|
83
69
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
axiosInstance.interceptors.response.use(
|
|
87
|
-
(response: AxiosResponse<BaseResponse>) => {
|
|
88
|
-
removePendingRequest(response.config as TrackedRequestConfig)
|
|
89
|
-
|
|
90
|
-
if (response.status === 204) {
|
|
91
|
-
return response
|
|
92
|
-
}
|
|
70
|
+
}
|
|
93
71
|
|
|
94
|
-
|
|
95
|
-
|
|
72
|
+
function shouldRetry(error: HttpError): boolean {
|
|
73
|
+
if (error.kind === 'network' || error.kind === 'timeout') return true
|
|
74
|
+
return error.kind === 'http' && [408, 500, 502, 503, 504].includes(error.code)
|
|
75
|
+
}
|
|
96
76
|
|
|
97
|
-
|
|
98
|
-
|
|
77
|
+
function prepareHeaders(config: AxiosRequestConfig): AxiosHeaders {
|
|
78
|
+
if (config.headers instanceof AxiosHeaders) return new AxiosHeaders(config.headers)
|
|
79
|
+
const raw = config.headers ?? {}
|
|
80
|
+
const groups = raw as Partial<Record<string, ConstructorParameters<typeof AxiosHeaders>[0]>>
|
|
81
|
+
const methodHeaders = [
|
|
82
|
+
'common',
|
|
83
|
+
'get',
|
|
84
|
+
'head',
|
|
85
|
+
'post',
|
|
86
|
+
'put',
|
|
87
|
+
'patch',
|
|
88
|
+
'delete',
|
|
89
|
+
'options',
|
|
90
|
+
'query'
|
|
91
|
+
]
|
|
92
|
+
const flat = Object.fromEntries(
|
|
93
|
+
Object.entries(raw).filter(([name]) => !methodHeaders.includes(name))
|
|
94
|
+
)
|
|
95
|
+
return AxiosHeaders.concat(
|
|
96
|
+
groups.common,
|
|
97
|
+
groups[(config.method || 'GET').toLowerCase()],
|
|
98
|
+
flat as ConstructorParameters<typeof AxiosHeaders>[0]
|
|
99
|
+
)
|
|
100
|
+
}
|
|
99
101
|
|
|
100
|
-
|
|
102
|
+
function unwrap<T>(response: AxiosResponse<BaseResponse<T>>): T {
|
|
103
|
+
if (response.status === 204 || response.config.method?.toUpperCase() === 'HEAD')
|
|
104
|
+
return undefined as T
|
|
105
|
+
const code = normalizeApiCode(response.data?.code)
|
|
106
|
+
if (isApiSuccessCode(code)) return response.data.data
|
|
107
|
+
throw new HttpError(
|
|
108
|
+
response.data?.message || response.data?.msg || $t('httpMsg.requestFailed'),
|
|
109
|
+
code,
|
|
110
|
+
{
|
|
111
|
+
kind: 'business',
|
|
101
112
|
data: response.data?.data,
|
|
102
113
|
url: response.config.url,
|
|
103
114
|
method: response.config.method?.toUpperCase()
|
|
104
|
-
})
|
|
105
|
-
},
|
|
106
|
-
(error) => {
|
|
107
|
-
if (error?.config) removePendingRequest(error.config as TrackedRequestConfig)
|
|
108
|
-
if (error instanceof HttpError) return Promise.reject(error)
|
|
109
|
-
|
|
110
|
-
if (axios.isCancel(error) || error?.code === 'ERR_CANCELED') {
|
|
111
|
-
return Promise.reject(
|
|
112
|
-
createHttpError($t('httpMsg.requestCancelled'), REQUEST_CANCELLED_CODE, {
|
|
113
|
-
url: error?.config?.url,
|
|
114
|
-
method: error?.config?.method?.toUpperCase()
|
|
115
|
-
})
|
|
116
|
-
)
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
if (isAxiosError(error) && error.response?.status === ApiStatus.unauthorized) {
|
|
120
|
-
handleUnauthorizedError(error.response.data?.message || error.response.data?.msg)
|
|
121
115
|
}
|
|
122
|
-
|
|
123
|
-
return Promise.reject(handleError(error))
|
|
124
|
-
}
|
|
125
|
-
)
|
|
126
|
-
|
|
127
|
-
function createHttpError(
|
|
128
|
-
message: string,
|
|
129
|
-
code: number,
|
|
130
|
-
options?: { data?: unknown; url?: string; method?: string }
|
|
131
|
-
) {
|
|
132
|
-
return new HttpError(message, code, options)
|
|
116
|
+
)
|
|
133
117
|
}
|
|
134
118
|
|
|
135
|
-
function
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
if (
|
|
139
|
-
|
|
140
|
-
useUserStore().clearAuthState()
|
|
141
|
-
unauthorizedTimer = setTimeout(resetUnauthorizedError, UNAUTHORIZED_DEBOUNCE_TIME)
|
|
119
|
+
function handleUnauthorized(error: HttpError): void {
|
|
120
|
+
// 清理会话始终执行;时间窗口只控制提示,不能让新会话的 401 被忽略。
|
|
121
|
+
useUserStore().clearAuthState()
|
|
122
|
+
if (Date.now() >= unauthorizedUntil) {
|
|
123
|
+
unauthorizedUntil = Date.now() + UNAUTHORIZED_DEBOUNCE_TIME
|
|
142
124
|
showError(error)
|
|
143
125
|
}
|
|
144
|
-
|
|
145
|
-
throw error
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function resetUnauthorizedError() {
|
|
149
|
-
isUnauthorizedErrorShown = false
|
|
150
|
-
if (unauthorizedTimer) clearTimeout(unauthorizedTimer)
|
|
151
|
-
unauthorizedTimer = null
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
function removePendingRequest(config: TrackedRequestConfig): void {
|
|
155
|
-
if (!config.requestKey) return
|
|
156
|
-
if (pendingRequests.get(config.requestKey) === config.abortController) {
|
|
157
|
-
pendingRequests.delete(config.requestKey)
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/** 取消当前尚未完成的全部请求。 */
|
|
162
|
-
export function cancelAllPendingRequests(): void {
|
|
163
|
-
pendingRequests.forEach((controller) => controller.abort('All pending requests cancelled'))
|
|
164
|
-
pendingRequests.clear()
|
|
165
126
|
}
|
|
166
127
|
|
|
167
|
-
function
|
|
168
|
-
return
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
ApiStatus.gatewayTimeout
|
|
174
|
-
].includes(statusCode)
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
async function retryRequest<T>(
|
|
178
|
-
config: ExtendedAxiosRequestConfig,
|
|
179
|
-
retries: number = MAX_RETRIES
|
|
180
|
-
): Promise<T> {
|
|
181
|
-
try {
|
|
182
|
-
return await request<T>(config)
|
|
183
|
-
} catch (error) {
|
|
184
|
-
if (retries > 0 && error instanceof HttpError && shouldRetry(error.code)) {
|
|
185
|
-
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY))
|
|
186
|
-
return retryRequest<T>(config, retries - 1)
|
|
187
|
-
}
|
|
188
|
-
throw error
|
|
189
|
-
}
|
|
128
|
+
function cancelledError(config: ExtendedAxiosRequestConfig): HttpError {
|
|
129
|
+
return new HttpError($t('httpMsg.requestCancelled'), ApiStatus.requestCancelled, {
|
|
130
|
+
kind: 'cancelled',
|
|
131
|
+
url: config.url,
|
|
132
|
+
method: config.method?.toUpperCase() || 'GET'
|
|
133
|
+
})
|
|
190
134
|
}
|
|
191
135
|
|
|
192
136
|
async function request<T = unknown>(config: ExtendedAxiosRequestConfig): Promise<T> {
|
|
137
|
+
let managed: ReturnType<typeof beginRequest> | undefined
|
|
193
138
|
try {
|
|
194
|
-
|
|
195
|
-
const
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
139
|
+
if (config.signal?.aborted) throw cancelledError(config)
|
|
140
|
+
const { cancelPrevious, requestKey, requestScope, retry, ...axiosConfig } = config
|
|
141
|
+
const headers = prepareHeaders(config)
|
|
142
|
+
const token = useUserStore().accessToken
|
|
143
|
+
if (token) {
|
|
144
|
+
const scheme = VITE_AUTH_SCHEME?.trim()
|
|
145
|
+
headers.set('Authorization', scheme ? `${scheme} ${token}` : token)
|
|
146
|
+
}
|
|
147
|
+
const prepared = {
|
|
148
|
+
...axiosConfig,
|
|
149
|
+
method: (config.method || 'GET').toUpperCase(),
|
|
150
|
+
baseURL: config.baseURL ?? VITE_API_URL,
|
|
151
|
+
headers
|
|
152
|
+
}
|
|
153
|
+
if (requestKey !== undefined && !requestKey.trim())
|
|
154
|
+
throw new TypeError('requestKey must not be empty')
|
|
155
|
+
const key =
|
|
156
|
+
cancelPrevious === true
|
|
157
|
+
? (requestKey ??
|
|
158
|
+
createRequestKey({
|
|
159
|
+
...prepared,
|
|
160
|
+
headers: Object.fromEntries(
|
|
161
|
+
Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value])
|
|
162
|
+
)
|
|
163
|
+
}))
|
|
164
|
+
: undefined
|
|
165
|
+
managed = beginRequest({ signal: config.signal, key, scope: requestScope })
|
|
166
|
+
const signal = managed.signal
|
|
167
|
+
const policy = retryPolicy({ ...config, retry })
|
|
168
|
+
for (let attempt = 0; ; attempt++) {
|
|
169
|
+
throwIfAborted(signal)
|
|
170
|
+
try {
|
|
171
|
+
const response = await runWithSignal(
|
|
172
|
+
() => axiosInstance.request<BaseResponse<T>>({ ...prepared, signal }),
|
|
173
|
+
signal
|
|
174
|
+
)
|
|
175
|
+
throwIfAborted(signal)
|
|
176
|
+
const data = unwrap(response)
|
|
177
|
+
const message = response.data?.message || response.data?.msg
|
|
178
|
+
if (config.showSuccessMessage && message) showSuccess(message)
|
|
179
|
+
return data
|
|
180
|
+
} catch (caught) {
|
|
181
|
+
throwIfAborted(signal)
|
|
182
|
+
const error = toHttpError(caught)
|
|
183
|
+
if (attempt >= policy.retries || !shouldRetry(error)) throw error
|
|
184
|
+
await waitForRetry(policy.delay, signal)
|
|
204
185
|
}
|
|
205
186
|
}
|
|
206
|
-
|
|
187
|
+
} catch (caught) {
|
|
188
|
+
const error = managed?.signal.aborted ? cancelledError(config) : toHttpError(caught)
|
|
189
|
+
// 先释放当前任务,再让 401 清理其它请求,保留当前错误的 401 语义。
|
|
190
|
+
managed?.finish()
|
|
191
|
+
if (
|
|
192
|
+
error.code === ApiStatus.unauthorized &&
|
|
193
|
+
(error.kind === 'http' || error.kind === 'business')
|
|
194
|
+
) {
|
|
195
|
+
handleUnauthorized(error)
|
|
196
|
+
} else if (error.kind !== 'cancelled') {
|
|
197
|
+
showError(error, config.showErrorMessage !== false)
|
|
198
|
+
}
|
|
199
|
+
throw error
|
|
200
|
+
} finally {
|
|
201
|
+
managed?.finish()
|
|
207
202
|
}
|
|
208
203
|
}
|
|
209
204
|
|
|
210
205
|
const api = {
|
|
211
206
|
get<T>(config: ExtendedAxiosRequestConfig) {
|
|
212
|
-
return
|
|
207
|
+
return request<T>({ ...config, method: 'GET' })
|
|
213
208
|
},
|
|
214
209
|
post<T>(config: ExtendedAxiosRequestConfig) {
|
|
215
|
-
return
|
|
210
|
+
return request<T>({ ...config, method: 'POST' })
|
|
216
211
|
},
|
|
217
212
|
put<T>(config: ExtendedAxiosRequestConfig) {
|
|
218
|
-
return
|
|
213
|
+
return request<T>({ ...config, method: 'PUT' })
|
|
219
214
|
},
|
|
220
215
|
del<T>(config: ExtendedAxiosRequestConfig) {
|
|
221
|
-
return
|
|
216
|
+
return request<T>({ ...config, method: 'DELETE' })
|
|
222
217
|
},
|
|
223
|
-
request
|
|
224
|
-
return retryRequest<T>(config)
|
|
225
|
-
}
|
|
218
|
+
request
|
|
226
219
|
}
|
|
227
220
|
|
|
228
221
|
export default api
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { AxiosRequestConfig } from 'axios'
|
|
2
|
+
|
|
3
|
+
export type RequestScope = string | symbol
|
|
4
|
+
|
|
5
|
+
interface ManagedRequest {
|
|
6
|
+
signal: AbortSignal
|
|
7
|
+
finish: () => void
|
|
8
|
+
cancel: () => void
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const activeRequests = new Set<ManagedRequest>()
|
|
12
|
+
const requestGroups = new Map<RequestScope, Map<string, ManagedRequest>>()
|
|
13
|
+
let sessionVersion = 0
|
|
14
|
+
let sessionClosing = false
|
|
15
|
+
/** 仅远端退出请求可在退出阶段使用此 scope。 */
|
|
16
|
+
export const SIGN_OUT_REQUEST_SCOPE = Symbol('sign-out')
|
|
17
|
+
|
|
18
|
+
export function getSessionVersion(): number {
|
|
19
|
+
return sessionVersion
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 认证边界调用;普通页面取消不改变会话标识。 */
|
|
23
|
+
export function invalidateSessionRequests(): void {
|
|
24
|
+
sessionVersion++
|
|
25
|
+
sessionClosing = false
|
|
26
|
+
cancelAllPendingRequests()
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function closeSessionRequests(): void {
|
|
30
|
+
invalidateSessionRequests()
|
|
31
|
+
sessionClosing = true
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 管理一次逻辑请求,包含所有尝试及重试等待;不依赖认证 Store。 */
|
|
35
|
+
export function beginRequest(options: {
|
|
36
|
+
signal?: AxiosRequestConfig['signal']
|
|
37
|
+
key?: string
|
|
38
|
+
scope?: RequestScope
|
|
39
|
+
}): ManagedRequest {
|
|
40
|
+
const controller = new AbortController()
|
|
41
|
+
const scope = options.scope ?? 'global'
|
|
42
|
+
const source = options.signal
|
|
43
|
+
const onSourceAbort = () => controller.abort('Caller cancelled')
|
|
44
|
+
let finished = false
|
|
45
|
+
const request: ManagedRequest = {
|
|
46
|
+
signal: controller.signal,
|
|
47
|
+
cancel: () => controller.abort('Request cancelled'),
|
|
48
|
+
finish: () => {
|
|
49
|
+
if (finished) return
|
|
50
|
+
finished = true
|
|
51
|
+
source?.removeEventListener?.('abort', onSourceAbort)
|
|
52
|
+
controller.signal.removeEventListener('abort', request.finish)
|
|
53
|
+
activeRequests.delete(request)
|
|
54
|
+
if (options.key !== undefined) {
|
|
55
|
+
const group = requestGroups.get(scope)
|
|
56
|
+
if (group?.get(options.key) === request) group.delete(options.key)
|
|
57
|
+
if (group?.size === 0) requestGroups.delete(scope)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 已取消的新请求不能取消同组中仍有效的旧请求。
|
|
63
|
+
if (source?.aborted || (sessionClosing && scope !== SIGN_OUT_REQUEST_SCOPE)) {
|
|
64
|
+
controller.abort('Caller cancelled')
|
|
65
|
+
return request
|
|
66
|
+
}
|
|
67
|
+
source?.addEventListener?.('abort', onSourceAbort, { once: true })
|
|
68
|
+
controller.signal.addEventListener('abort', request.finish, { once: true })
|
|
69
|
+
if (options.key !== undefined) {
|
|
70
|
+
requestGroups.get(scope)?.get(options.key)?.cancel()
|
|
71
|
+
const group = requestGroups.get(scope) ?? new Map<string, ManagedRequest>()
|
|
72
|
+
group.set(options.key, request)
|
|
73
|
+
requestGroups.set(scope, group)
|
|
74
|
+
}
|
|
75
|
+
activeRequests.add(request)
|
|
76
|
+
return request
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 包括重试等待中的任务;取消后新建的请求使用独立控制器。 */
|
|
80
|
+
export function cancelAllPendingRequests(): void {
|
|
81
|
+
for (const request of [...activeRequests]) request.cancel()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function throwIfAborted(signal: AbortSignal): void {
|
|
85
|
+
if (signal.aborted) throw new DOMException('Request cancelled', 'AbortError')
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 即使自定义 transport 忽略 signal,也不交付过期响应或处理其 401。 */
|
|
89
|
+
export function runWithSignal<T>(task: () => Promise<T>, signal: AbortSignal): Promise<T> {
|
|
90
|
+
return new Promise((resolve, reject) => {
|
|
91
|
+
const abort = () => reject(new DOMException('Request cancelled', 'AbortError'))
|
|
92
|
+
if (signal.aborted) {
|
|
93
|
+
abort()
|
|
94
|
+
return
|
|
95
|
+
}
|
|
96
|
+
signal.addEventListener('abort', abort, { once: true })
|
|
97
|
+
Promise.resolve()
|
|
98
|
+
.then(() => {
|
|
99
|
+
throwIfAborted(signal)
|
|
100
|
+
return task()
|
|
101
|
+
})
|
|
102
|
+
.then(resolve, reject)
|
|
103
|
+
.finally(() => signal.removeEventListener('abort', abort))
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function waitForRetry(delay: number, signal: AbortSignal): Promise<void> {
|
|
108
|
+
return new Promise((resolve, reject) => {
|
|
109
|
+
if (signal.aborted) {
|
|
110
|
+
reject(new DOMException('Request cancelled', 'AbortError'))
|
|
111
|
+
return
|
|
112
|
+
}
|
|
113
|
+
const abort = () => {
|
|
114
|
+
clearTimeout(timer)
|
|
115
|
+
signal.removeEventListener('abort', abort)
|
|
116
|
+
reject(new DOMException('Request cancelled', 'AbortError'))
|
|
117
|
+
}
|
|
118
|
+
const timer = setTimeout(() => {
|
|
119
|
+
signal.removeEventListener('abort', abort)
|
|
120
|
+
resolve()
|
|
121
|
+
}, delay)
|
|
122
|
+
signal.addEventListener('abort', abort, { once: true })
|
|
123
|
+
})
|
|
124
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -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)
|