99 lines
3.8 KiB
TypeScript
99 lines
3.8 KiB
TypeScript
/**
|
|
* main.ts
|
|
* 用途:Vue 应用启动入口(pinia / router / i18n / 401 fetch 包装)。
|
|
* 依赖:App.vue、router、i18n、config、auth sync、agentTabs、chunkLoadRecovery。
|
|
* 逻辑:挂载前设置 document.title;包装 fetch 以刷新 token;仅会话类 401 才派发未授权事件;
|
|
* 监听 vite:preloadError,部署后旧 hash 分包 404 时刷新一次(含 Chat 懒加载作业面)。
|
|
*/
|
|
import { createApp } from 'vue';
|
|
import './style.css';
|
|
import App from './App.vue';
|
|
import router from './app/router';
|
|
import i18n from './i18n';
|
|
import { config } from './config';
|
|
import { pinia } from './app/plugins/pinia';
|
|
import { bindAuthStoreSync } from './features/auth/stores/auth.store';
|
|
import { refreshAccessToken, getAuthToken, initAuthSync, isSessionUnauthorizedError } from '@/shared/utils/auth';
|
|
import { initAgentTabSync } from '@/shared/utils/agentTabs';
|
|
import { setupVitePreloadErrorRecovery } from '@/shared/utils/chunkLoadRecovery';
|
|
|
|
initAuthSync();
|
|
initAgentTabSync();
|
|
setupVitePreloadErrorRecovery();
|
|
document.title = String(i18n.global.t(config.appTitleKey));
|
|
|
|
/**
|
|
* 从 401 响应 envelope 读取 error.code,供会话失效判断使用。
|
|
* 核心逻辑:clone 后再 json,避免消耗原 Response body。
|
|
* @param res - fetch 原始响应
|
|
* @returns 错误码;无法解析时为空字符串
|
|
*/
|
|
async function readApiErrorCode(res: Response): Promise<string> {
|
|
try {
|
|
const body = await res.clone().json();
|
|
return String(body?.error?.code || body?.code || '').trim();
|
|
} catch {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
const _rawFetch = window.fetch.bind(window);
|
|
window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
|
|
const runFetch = (nextInit?: RequestInit) => _rawFetch(input, nextInit);
|
|
let reqInit = init;
|
|
let res = await runFetch(reqInit);
|
|
try {
|
|
const url = typeof input === 'string' ? input : (input instanceof URL ? input.toString() : input.url);
|
|
const isApi = url.includes('/api/');
|
|
const isRefreshApi = url.includes('/api/user/casdoor/refresh');
|
|
const isLoginApi =
|
|
url.includes('/api/user/login') ||
|
|
url.includes('/api/user/casdoor/password-login') ||
|
|
url.includes('/api/user/casdoor/login');
|
|
const isOptionalSsoCatalogApi = /\/api\/sso\/apps(?:\?|$)/.test(url);
|
|
if (res.status === 401 && isApi && !isRefreshApi) {
|
|
const errorCode = await readApiErrorCode(res);
|
|
if (isSessionUnauthorizedError(errorCode)) {
|
|
const refreshed = await refreshAccessToken();
|
|
if (refreshed) {
|
|
const mergedHeaders = new Headers((reqInit && reqInit.headers) || {});
|
|
mergedHeaders.set('Authorization', `Bearer ${getAuthToken()}`);
|
|
reqInit = { ...(reqInit || {}), headers: mergedHeaders };
|
|
res = await runFetch(reqInit);
|
|
}
|
|
}
|
|
}
|
|
if (res.status === 401 && isApi && !isLoginApi && !isOptionalSsoCatalogApi) {
|
|
const errorCode = await readApiErrorCode(res);
|
|
if (isSessionUnauthorizedError(errorCode)) {
|
|
window.dispatchEvent(new CustomEvent('hxops:unauthorized', { detail: { url, status: res.status } }));
|
|
}
|
|
}
|
|
} catch {
|
|
// no-op
|
|
}
|
|
return res;
|
|
};
|
|
|
|
const app = createApp(App);
|
|
app.use(pinia);
|
|
bindAuthStoreSync();
|
|
app.use(router);
|
|
app.use(i18n);
|
|
app.mount('#app');
|
|
|
|
if ('serviceWorker' in navigator) {
|
|
window.addEventListener('load', async () => {
|
|
try {
|
|
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
await Promise.all(registrations.map((registration) => registration.unregister()));
|
|
if ('caches' in window) {
|
|
const cacheKeys = await window.caches.keys();
|
|
await Promise.all(cacheKeys.map((key) => window.caches.delete(key)));
|
|
}
|
|
} catch (err) {
|
|
console.error('Service worker cleanup failed:', err);
|
|
}
|
|
});
|
|
}
|