@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.
Files changed (74) hide show
  1. package/package.json +1 -1
  2. package/template/.env +2 -5
  3. package/template/.env.production +6 -0
  4. package/template/README.md +12 -0
  5. package/template/package.json +5 -5
  6. package/template/scripts/build-info.ts +76 -0
  7. package/template/src/adapters/auth/index.ts +1 -1
  8. package/template/src/adapters/auth/types.ts +6 -1
  9. package/template/src/api/auth.ts +3 -2
  10. package/template/src/components/core/layouts/art-guide/index.vue +9 -1
  11. package/template/src/components/core/layouts/art-page-content/index.vue +8 -1
  12. package/template/src/config/index.ts +4 -0
  13. package/template/src/directives/core/access.ts +125 -0
  14. package/template/src/directives/core/auth.ts +7 -62
  15. package/template/src/directives/core/roles.ts +5 -83
  16. package/template/src/env.d.ts +2 -0
  17. package/template/src/hooks/core/useAuth.ts +2 -74
  18. package/template/src/hooks/core/useGuide.ts +6 -0
  19. package/template/src/hooks/core/usePermission.ts +41 -0
  20. package/template/src/hooks/index.ts +1 -0
  21. package/template/src/locales/langs/en.json +11 -1
  22. package/template/src/locales/langs/zh.json +11 -1
  23. package/template/src/main.ts +18 -10
  24. package/template/src/router/core/IframeRouteManager.ts +4 -2
  25. package/template/src/router/core/MenuProcessor.ts +5 -40
  26. package/template/src/router/core/RoutePermissionValidator.ts +6 -149
  27. package/template/src/router/core/access.ts +79 -0
  28. package/template/src/router/guards/afterEach.ts +6 -10
  29. package/template/src/router/guards/beforeEach.ts +143 -100
  30. package/template/src/router/guards/error.ts +42 -0
  31. package/template/src/router/index.ts +2 -0
  32. package/template/src/router/modules/examples.ts +4 -3
  33. package/template/src/router/routes/staticRoutes.ts +5 -3
  34. package/template/src/services/auth.ts +32 -10
  35. package/template/src/services/permission.ts +21 -0
  36. package/template/src/store/modules/menu.ts +28 -8
  37. package/template/src/store/modules/user.ts +72 -35
  38. package/template/src/store/modules/worktab.ts +1 -1
  39. package/template/src/types/api/api.d.ts +4 -1
  40. package/template/src/types/build-info.ts +11 -0
  41. package/template/src/types/config/index.ts +5 -2
  42. package/template/src/types/directive/directive.d.ts +1 -0
  43. package/template/src/types/router/index.ts +6 -0
  44. package/template/src/utils/http/contract.ts +51 -19
  45. package/template/src/utils/http/error.ts +73 -26
  46. package/template/src/utils/http/index.ts +160 -167
  47. package/template/src/utils/http/request-manager.ts +124 -0
  48. package/template/src/utils/http/status.ts +1 -0
  49. package/template/src/utils/permission/index.ts +66 -0
  50. package/template/src/utils/session.ts +24 -0
  51. package/template/src/utils/storage/storage-config.ts +15 -0
  52. package/template/src/utils/storage/storage.ts +5 -3
  53. package/template/src/utils/sys/console.ts +63 -7
  54. package/template/src/utils/sys/diagnostics.ts +180 -0
  55. package/template/src/utils/sys/error-handle.ts +56 -126
  56. package/template/src/utils/sys/recovery.ts +31 -0
  57. package/template/src/views/examples/permissions/index.vue +69 -13
  58. package/template/src/views/exception/403/index.vue +33 -0
  59. package/template/src/views/exception/500/index.vue +52 -10
  60. package/template/tests/e2e/permissions.spec.ts +53 -0
  61. package/template/tests/e2e/session-recovery.spec.ts +49 -0
  62. package/template/tests/unit/build/build-info.spec.ts +151 -0
  63. package/template/tests/unit/diagnostics/diagnostics.spec.ts +132 -0
  64. package/template/tests/unit/diagnostics/router.spec.ts +84 -0
  65. package/template/tests/unit/http/auth-lifecycle.spec.ts +203 -0
  66. package/template/tests/unit/http/contract.spec.ts +46 -0
  67. package/template/tests/unit/http/request.spec.ts +487 -0
  68. package/template/tests/unit/permissions/guard.spec.ts +261 -0
  69. package/template/tests/unit/permissions/guide.spec.ts +30 -0
  70. package/template/tests/unit/permissions/rules.spec.ts +106 -0
  71. package/template/tests/unit/permissions/state-and-directives.spec.ts +176 -0
  72. package/template/tests/unit/router/examples.spec.ts +5 -1
  73. package/template/tsconfig.json +8 -1
  74. package/template/vite.config.ts +19 -9
@@ -1,16 +1,58 @@
1
- <!-- 500页面 -->
2
1
  <template>
3
- <ArtException
4
- :data="{
5
- title: '500',
6
- desc: $t('exceptionPage.500'),
7
- btnText: $t('exceptionPage.gohome'),
8
- imgUrl
9
- }"
10
- />
2
+ <main class="page-content">
3
+ <KvStatus
4
+ type="error"
5
+ title="500"
6
+ :description="
7
+ errorMessage ||
8
+ $t(
9
+ resourceRecoveryNeeded
10
+ ? 'exceptionPage.resourceFailure'
11
+ : 'exceptionPage.retryDescription'
12
+ )
13
+ "
14
+ :action-text="
15
+ $t(
16
+ retrying
17
+ ? 'access.checking'
18
+ : resourceRecoveryNeeded
19
+ ? 'exceptionPage.reload'
20
+ : 'exceptionPage.retry'
21
+ )
22
+ "
23
+ @action="retry"
24
+ />
25
+ </main>
11
26
  </template>
12
27
 
13
28
  <script setup lang="ts">
14
- import imgUrl from '@imgs/svg/500.svg'
29
+ import { ref } from 'vue'
30
+ import { KvStatus } from '@kevairy/components'
31
+ import { router } from '@/router'
32
+ import { resetRouterState } from '@/router/guards/beforeEach'
33
+ import { useUserStore } from '@/store/modules/user'
34
+ import { resourceRecoveryNeeded, reloadFailedPage } from '@/utils/sys/recovery'
35
+ import { isRequestCanceled } from '@/utils/http/error'
36
+
15
37
  defineOptions({ name: 'Exception500' })
38
+ const retrying = ref(false)
39
+ const errorMessage = ref('')
40
+ const retry = async () => {
41
+ if (retrying.value) return
42
+ if (resourceRecoveryNeeded.value) {
43
+ reloadFailedPage()
44
+ return
45
+ }
46
+ retrying.value = true
47
+ errorMessage.value = ''
48
+ try {
49
+ resetRouterState(0)
50
+ await router.replace(useUserStore().isLogin ? '/' : '/auth/login')
51
+ } catch (error) {
52
+ if (!isRequestCanceled(error))
53
+ errorMessage.value = error instanceof Error ? error.message : String(error)
54
+ } finally {
55
+ retrying.value = false
56
+ }
57
+ }
16
58
  </script>
@@ -0,0 +1,53 @@
1
+ import { expect, test, type Page } from '@playwright/test'
2
+ import { skipInitialGuide } from './helpers/guide'
3
+
4
+ async function selectProfile(page: Page, name: string) {
5
+ const select = page.getByRole('combobox', { name: '演示身份' })
6
+ await select.focus()
7
+ await select.press('ArrowDown')
8
+ await page.getByRole('option', { name, exact: true }).click()
9
+ }
10
+
11
+ test('keeps hook and directive permissions consistent through grant, revoke, restore and protected detail navigation', async ({
12
+ page
13
+ }) => {
14
+ await page.goto('/#/examples/permissions')
15
+ await page.getByRole('button', { name: '进入系统(Mock)' }).click()
16
+ await skipInitialGuide(page)
17
+ const create = page.getByRole('button', { name: '新增资源', exact: true })
18
+ const edit = page.getByRole('button', { name: '编辑资源', exact: true })
19
+ const exportButton = page.getByRole('button', { name: '导出数据', exact: true })
20
+ const approve = page.getByRole('button', { name: '审核资源', exact: true })
21
+ await expect(approve).toBeEnabled()
22
+ await selectProfile(page, '普通成员')
23
+ await expect(create).toBeVisible()
24
+ await expect(edit).toBeVisible()
25
+ await expect(exportButton).toBeVisible()
26
+ await expect(approve).toBeDisabled()
27
+ await selectProfile(page, '无操作权限')
28
+ await expect(create).toBeHidden()
29
+ await expect(edit).toBeHidden()
30
+ await expect(exportButton).toBeHidden()
31
+ await expect(approve).toBeDisabled()
32
+ await expect(page.getByText('管理员区域', { exact: true })).toBeHidden()
33
+ await selectProfile(page, '模板管理员')
34
+ await expect(create).toBeVisible()
35
+ await expect(exportButton).toBeVisible()
36
+ await expect(approve).toBeEnabled()
37
+ await expect(page.getByText('管理员区域', { exact: true })).toBeVisible()
38
+ await selectProfile(page, '无操作权限')
39
+ await page.evaluate(() => {
40
+ location.hash = '/examples/navigation/detail/42'
41
+ })
42
+ await expect(page).toHaveURL(/#\/403$/)
43
+ await page.evaluate(() => {
44
+ location.hash = '/examples/permissions'
45
+ })
46
+ await expect(page.getByRole('heading', { name: '权限演练场' })).toBeVisible()
47
+ await selectProfile(page, '普通成员')
48
+ await page.evaluate(() => {
49
+ location.hash = '/examples/navigation/detail/42'
50
+ })
51
+ await expect(page).toHaveURL(/#\/examples\/navigation\/detail\/42$/)
52
+ await expect(page.getByText('42', { exact: true }).first()).toBeVisible()
53
+ })
@@ -0,0 +1,49 @@
1
+ import { expect, test } from '@playwright/test'
2
+ import { skipInitialGuide } from './helpers/guide'
3
+
4
+ test('discards cached page state on logout and reinitializes the same account', async ({
5
+ page
6
+ }) => {
7
+ await page.goto('/#/examples/search-table')
8
+ await page.getByRole('button', { name: '进入系统(Mock)' }).click()
9
+ await expect(page.getByText('共 68 项')).toBeVisible()
10
+ await skipInitialGuide(page)
11
+ await page.getByPlaceholder('服务名称或编码').fill('SERVICE_001')
12
+ await page.getByRole('button', { name: '查询', exact: true }).click()
13
+ await expect(page.getByText('共 1 项')).toBeVisible()
14
+ await page.locator('.user-menu-avatar').hover()
15
+ await page.getByText('退出登录', { exact: true }).click()
16
+ await page.getByRole('button', { name: '确定', exact: true }).click()
17
+ await expect(page).toHaveURL(/#\/auth\/login/)
18
+ await page.getByRole('button', { name: '进入系统(Mock)' }).click()
19
+ await expect(page).toHaveURL(/#\/examples\/search-table/)
20
+ await expect(page.getByText('共 68 项')).toBeVisible()
21
+ await expect(page.getByPlaceholder('服务名称或编码')).toHaveValue('')
22
+ // 引导完成属于偏好,重新登录不再次启动。
23
+ await expect(page.getByRole('dialog', { name: '欢迎使用 Admin Template' })).toBeHidden()
24
+ })
25
+
26
+ test('offers explicit reload after a failed lazy chunk and recovers the requested page', async ({
27
+ page
28
+ }) => {
29
+ const diagnostics: string[] = []
30
+ page.on('console', (message) => {
31
+ if (message.type() === 'error') diagnostics.push(message.text())
32
+ })
33
+ await page.goto('/#/dashboard/console')
34
+ await page.getByRole('button', { name: '进入系统(Mock)' }).click()
35
+ await expect(page.getByRole('heading', { name: 'Admin Template' })).toBeVisible()
36
+ await skipInitialGuide(page)
37
+ // 登录后才阻断尚未加载的业务资源,恢复页应已随入口可用。
38
+ await page.route('**/assets/*.js', (route) => route.abort('failed'))
39
+ await page.evaluate(() => {
40
+ window.location.hash = '#/examples/search-table'
41
+ })
42
+ await expect(page).toHaveURL(/#\/500/)
43
+ await expect(page.getByRole('button', { name: '刷新并重试' })).toBeVisible()
44
+ expect(diagnostics.some((message) => message.includes('[Diagnostic]'))).toBe(true)
45
+ await page.unroute('**/assets/*.js')
46
+ await page.getByRole('button', { name: '刷新并重试' }).click()
47
+ await expect(page).toHaveURL(/#\/examples\/search-table/)
48
+ await expect(page.getByText('共 68 项')).toBeVisible()
49
+ })
@@ -0,0 +1,151 @@
1
+ // @vitest-environment node
2
+ import { execFileSync } from 'node:child_process'
3
+ import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { runInNewContext } from 'node:vm'
8
+ import { build } from 'vite'
9
+ import { afterEach, describe, expect, it, vi } from 'vitest'
10
+ import { buildInfoPlugin, createBuildInfo } from '../../../scripts/build-info'
11
+
12
+ const directories: string[] = []
13
+ const git = (root: string, ...args: string[]) =>
14
+ execFileSync('git', args, {
15
+ cwd: root,
16
+ encoding: 'utf8',
17
+ stdio: ['ignore', 'pipe', 'pipe']
18
+ }).trim()
19
+
20
+ async function fixture(withGit = false) {
21
+ const root = await realpath(await mkdtemp(path.join(os.tmpdir(), 'kevairy-build-info-')))
22
+ directories.push(root)
23
+ await writeFile(path.join(root, 'package.json'), JSON.stringify({ version: '1.2.3' }))
24
+ if (withGit) {
25
+ git(root, 'init')
26
+ git(root, 'add', 'package.json')
27
+ git(
28
+ root,
29
+ '-c',
30
+ 'user.name=Build Test',
31
+ '-c',
32
+ 'user.email=build-test@example.invalid',
33
+ '-c',
34
+ 'commit.gpgsign=false',
35
+ '-c',
36
+ 'core.hooksPath=/dev/null',
37
+ 'commit',
38
+ '-m',
39
+ 'Initial fixture'
40
+ )
41
+ }
42
+ return root
43
+ }
44
+
45
+ afterEach(async () => {
46
+ vi.useRealTimers()
47
+ await Promise.all(directories.splice(0).map((root) => rm(root, { recursive: true, force: true })))
48
+ })
49
+
50
+ describe('build identity', () => {
51
+ it('uses the project version and creates distinct IDs even within the same millisecond', async () => {
52
+ const root = await fixture()
53
+ vi.useFakeTimers()
54
+ vi.setSystemTime(new Date('2026-11-11T07:30:00.000Z'))
55
+ const first = createBuildInfo({ root, mode: 'production' })
56
+ const second = createBuildInfo({ root, mode: 'production' })
57
+ expect(first).toMatchObject({
58
+ version: '1.2.3',
59
+ builtAt: '2026-11-11T07:30:00.000Z',
60
+ gitCommit: null,
61
+ gitDirty: null,
62
+ mode: 'production'
63
+ })
64
+ expect(first.buildId).toMatch(/^20261111T073000000Z-nogit-[a-f0-9]{8}$/)
65
+ expect(second.buildId).not.toBe(first.buildId)
66
+ expect(JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8')).version).toBe(
67
+ '1.2.3'
68
+ )
69
+ })
70
+
71
+ it('records clean commits and detects both tracked and untracked changes', async () => {
72
+ const root = await fixture(true)
73
+ const clean = createBuildInfo({ root, mode: 'production' })
74
+ expect(clean.gitCommit).toBe(git(root, 'rev-parse', 'HEAD'))
75
+ expect(clean.gitDirty).toBe(false)
76
+ await writeFile(path.join(root, 'new-file.txt'), 'Untracked change')
77
+ expect(createBuildInfo({ root, mode: 'production' }).gitDirty).toBe(true)
78
+ await rm(path.join(root, 'new-file.txt'))
79
+ await writeFile(path.join(root, 'package.json'), JSON.stringify({ version: '1.2.4' }))
80
+ const dirty = createBuildInfo({ root, mode: 'production' })
81
+ expect(dirty.gitDirty).toBe(true)
82
+ expect(dirty.buildId).toContain('-dirty-')
83
+ expect(dirty.version).toBe('1.2.4')
84
+ expect(dirty.gitCommit).toBe(clean.gitCommit)
85
+ })
86
+
87
+ it('handles a repository without a first commit and supports CI overrides', async () => {
88
+ const root = await fixture()
89
+ git(root, 'init')
90
+ expect(createBuildInfo({ root, mode: 'production' })).toMatchObject({
91
+ gitCommit: null,
92
+ gitDirty: true
93
+ })
94
+ const options = { root, mode: 'staging', buildId: 'pipeline-123', gitCommit: 'a'.repeat(40) }
95
+ expect(createBuildInfo(options)).toMatchObject({
96
+ buildId: 'pipeline-123',
97
+ gitCommit: 'a'.repeat(40),
98
+ gitDirty: null,
99
+ mode: 'staging'
100
+ })
101
+ expect(createBuildInfo({ ...options, gitDirty: 'false' }).gitDirty).toBe(false)
102
+ expect(() => createBuildInfo({ ...options, gitDirty: 'invalid' })).toThrow('BUILD_GIT_DIRTY')
103
+ })
104
+
105
+ it('keeps the startup identity in minified production JS and matches version.json', async () => {
106
+ const root = await fixture()
107
+ const consolePath = fileURLToPath(new URL('../../../src/utils/sys/console.ts', import.meta.url))
108
+ await writeFile(
109
+ path.join(root, 'index.html'),
110
+ '<script type="module" src="/entry.ts"></script>'
111
+ )
112
+ await writeFile(
113
+ path.join(root, 'entry.ts'),
114
+ `
115
+ import ${JSON.stringify(consolePath)}
116
+ console.info('business-log-must-be-removed')
117
+ globalThis.diagnosticIdentity = [__APP_VERSION__, __BUILD_ID__]
118
+ `
119
+ )
120
+ await writeFile(
121
+ path.join(root, 'config.ts'),
122
+ `
123
+ export default { systemInfo: { name: 'Fixture App', description: 'Test' } }
124
+ `
125
+ )
126
+ const info = createBuildInfo({ root, mode: 'production' })
127
+ const result = await build({
128
+ root,
129
+ configFile: false,
130
+ logLevel: 'silent',
131
+ base: '/admin/',
132
+ plugins: [buildInfoPlugin(info)],
133
+ resolve: { alias: { '@/config': path.join(root, 'config.ts') } },
134
+ esbuild: { pure: ['console.log', 'console.debug', 'console.info'], drop: ['debugger'] },
135
+ build: { write: false, modulePreload: false, minify: 'esbuild' }
136
+ })
137
+ if (Array.isArray(result) || !('output' in result)) throw new Error('Expected one build output')
138
+ const manifest = result.output.find((item) => item.fileName === 'version.json')
139
+ if (!manifest || manifest.type !== 'asset') throw new Error('Missing version.json')
140
+ expect(JSON.parse(String(manifest.source))).toEqual(info)
141
+ const entry = result.output.find((item) => item.type === 'chunk' && item.isEntry)
142
+ if (!entry || entry.type !== 'chunk') throw new Error('Missing entry JS')
143
+ const log = vi.fn()
144
+ const context = { console: { info: log }, diagnosticIdentity: [] }
145
+ runInNewContext(entry.code, context)
146
+ expect(log).toHaveBeenCalledTimes(1)
147
+ expect(log.mock.calls[0].at(-1)).toEqual(info)
148
+ expect(context.diagnosticIdentity).toEqual([info.version, info.buildId])
149
+ expect(entry.code).not.toContain('business-log-must-be-removed')
150
+ })
151
+ })
@@ -0,0 +1,132 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import { flushPromises } from '@vue/test-utils'
3
+
4
+ beforeEach(() => {
5
+ vi.resetModules()
6
+ vi.spyOn(console, 'error').mockImplementation(() => {})
7
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
8
+ })
9
+ afterEach(() => {
10
+ vi.restoreAllMocks()
11
+ })
12
+
13
+ describe('production diagnostics', () => {
14
+ it('redacts URL queries, credentials and common secrets without collecting payloads', async () => {
15
+ const diagnostics = await import('@/utils/sys/diagnostics')
16
+ diagnostics.setDiagnosticRouteProvider(() => '/account?token=route-secret#private')
17
+ const error = new Error(
18
+ 'Failed https://user:pass@example.com/api?token=url-secret Authorization=header-secret Bearer bearer-secret password=password-secret'
19
+ )
20
+ diagnostics.reportDiagnostic('http', error, {
21
+ url: '/api?token=query-secret',
22
+ method: 'GET',
23
+ code: 500,
24
+ ...{ data: 'body-secret', headers: 'headers-secret' }
25
+ })
26
+ const [record] = diagnostics.getDiagnosticRecords()
27
+ expect(record.version).toBe('test')
28
+ expect(record.buildId).toBeTruthy()
29
+ const serialized = JSON.stringify(record)
30
+ for (const secret of [
31
+ 'user:pass',
32
+ 'route-secret',
33
+ 'url-secret',
34
+ 'header-secret',
35
+ 'bearer-secret',
36
+ 'password-secret',
37
+ 'query-secret',
38
+ 'body-secret',
39
+ 'headers-secret'
40
+ ]) {
41
+ expect(serialized).not.toContain(secret)
42
+ }
43
+ expect(record.context).toEqual({
44
+ url: `${window.location.origin}/api`,
45
+ method: 'GET',
46
+ code: 500
47
+ })
48
+ record.context.method = 'mutated'
49
+ expect(diagnostics.getDiagnosticRecords()[0].context.method).toBe('GET')
50
+ diagnostics.reportDiagnostic('script', new Error('password="multi word secret"'), {
51
+ url: 'data:text/plain;base64,sensitive-body'
52
+ })
53
+ const last = JSON.stringify(diagnostics.getDiagnosticRecords().at(-1))
54
+ expect(last).not.toContain('multi word secret')
55
+ expect(last).not.toContain('sensitive-body')
56
+ })
57
+
58
+ it('ignores cancellations and noise, deduplicates repeats and bounds retained records', async () => {
59
+ const { reportDiagnostic, getDiagnosticRecords } = await import('@/utils/sys/diagnostics')
60
+ reportDiagnostic('promise', new DOMException('Canceled', 'AbortError'))
61
+ reportDiagnostic('http', { kind: 'cancelled' })
62
+ reportDiagnostic('script', 'ResizeObserver loop limit exceeded')
63
+ expect(getDiagnosticRecords()).toEqual([])
64
+ const error = new Error('Repeated failure')
65
+ reportDiagnostic('script', error)
66
+ reportDiagnostic('script', error)
67
+ expect(getDiagnosticRecords()[0].count).toBe(2)
68
+ for (let i = 0; i < 80; i++) reportDiagnostic('script', `Failure ${i}`)
69
+ expect(getDiagnosticRecords()).toHaveLength(50)
70
+ expect(getDiagnosticRecords().at(-1)?.message).toBe('Failure 79')
71
+ })
72
+
73
+ it('limits reporting and isolates both synchronous and asynchronous reporter failures', async () => {
74
+ const { reportDiagnostic, setDiagnosticReporter, getDiagnosticRecords } = await import(
75
+ '@/utils/sys/diagnostics'
76
+ )
77
+ const reporter = vi
78
+ .fn()
79
+ .mockImplementationOnce(() => {
80
+ throw new Error('Sync reporter error')
81
+ })
82
+ .mockRejectedValue(new Error('Async reporter error'))
83
+ setDiagnosticReporter(reporter)
84
+ for (let i = 0; i < 30; i++) {
85
+ reportDiagnostic('script', `Failure ${i}`)
86
+ await flushPromises()
87
+ }
88
+ expect(reporter).toHaveBeenCalledTimes(20)
89
+ expect(getDiagnosticRecords()).toHaveLength(30)
90
+ expect(console.warn).toHaveBeenCalled()
91
+ })
92
+
93
+ it('installs listeners once, preserves browser errors and removes all global listeners', async () => {
94
+ const { setupGlobalErrorHandlers, scriptErrorHandler, vueErrorHandler } = await import(
95
+ '@/utils/sys/error-handle'
96
+ )
97
+ const { getDiagnosticRecords } = await import('@/utils/sys/diagnostics')
98
+ const stop = setupGlobalErrorHandlers()
99
+ expect(setupGlobalErrorHandlers()).toBe(stop)
100
+ try {
101
+ window.dispatchEvent(
102
+ new ErrorEvent('error', {
103
+ message: 'Runtime failure',
104
+ error: new Error('Runtime failure'),
105
+ filename: '/entry.js?secret=1',
106
+ lineno: 8
107
+ })
108
+ )
109
+ const rejection = new Event('unhandledrejection')
110
+ Object.assign(rejection, { reason: new Error('Promise failure') })
111
+ window.dispatchEvent(rejection)
112
+ const image = document.createElement('img')
113
+ image.src = '/image.png?token=secret'
114
+ document.body.appendChild(image)
115
+ image.dispatchEvent(new Event('error'))
116
+ image.remove()
117
+ vueErrorHandler(new Error('Vue failure'), null, 'render function')
118
+ expect(getDiagnosticRecords().map((record) => record.kind)).toEqual([
119
+ 'script',
120
+ 'promise',
121
+ 'resource',
122
+ 'vue'
123
+ ])
124
+ expect(scriptErrorHandler('Browser fallback')).toBe(false)
125
+ } finally {
126
+ stop()
127
+ }
128
+ const count = getDiagnosticRecords().length
129
+ window.dispatchEvent(new ErrorEvent('error', { message: 'After disposal' }))
130
+ expect(getDiagnosticRecords()).toHaveLength(count)
131
+ })
132
+ })
@@ -0,0 +1,84 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import { createMemoryHistory, createRouter } from 'vue-router'
3
+ import { flushPromises } from '@vue/test-utils'
4
+
5
+ vi.mock('@/router/guards/beforeEach', () => ({ closeLoading: vi.fn() }))
6
+ vi.mock('@/utils/http/error', () => ({
7
+ isRequestCanceled: (error: Error) => error.name === 'AbortError'
8
+ }))
9
+ vi.mock('nprogress', () => ({ default: { done: vi.fn() } }))
10
+ beforeEach(() => {
11
+ vi.resetModules()
12
+ vi.spyOn(console, 'error').mockImplementation(() => {})
13
+ })
14
+ afterEach(() => vi.restoreAllMocks())
15
+
16
+ describe('router recovery', () => {
17
+ it('does not navigate away from a new session when an old lazy import fails late', async () => {
18
+ const { setupRouterErrorHandler } = await import('@/router/guards/error')
19
+ const { invalidateSessionRequests } = await import('@/utils/http/request-manager')
20
+ let fail!: (error: Error) => void
21
+ const router = createRouter({
22
+ history: createMemoryHistory(),
23
+ routes: [
24
+ {
25
+ path: '/old',
26
+ component: () =>
27
+ new Promise((_, reject) => {
28
+ fail = reject
29
+ })
30
+ },
31
+ { path: '/new', component: { render: () => null } },
32
+ { path: '/500', name: 'Exception500', component: { render: () => null } }
33
+ ]
34
+ })
35
+ const stop = setupRouterErrorHandler(router)
36
+ try {
37
+ const old = router.push('/old').catch(() => {})
38
+ await flushPromises()
39
+ invalidateSessionRequests()
40
+ await router.push('/new')
41
+ fail(new Error('Failed to fetch dynamically imported module'))
42
+ await old
43
+ await flushPromises()
44
+ expect(router.currentRoute.value.path).toBe('/new')
45
+ } finally {
46
+ stop()
47
+ }
48
+ })
49
+
50
+ it('captures failed lazy imports and opens the eager recovery page without retry loops', async () => {
51
+ const { setupRouterErrorHandler } = await import('@/router/guards/error')
52
+ const { resourceRecoveryNeeded } = await import('@/utils/sys/recovery')
53
+ const { getDiagnosticRecords } = await import('@/utils/sys/diagnostics')
54
+ const error = new Error(
55
+ 'Failed to fetch dynamically imported module: https://example.com/assets/old.js?token=secret'
56
+ )
57
+ const router = createRouter({
58
+ history: createMemoryHistory(),
59
+ routes: [
60
+ { path: '/broken', component: () => Promise.reject(error) },
61
+ { path: '/500', name: 'Exception500', component: { render: () => null } }
62
+ ]
63
+ })
64
+ const stop = setupRouterErrorHandler(router)
65
+ try {
66
+ await expect(router.push('/broken?token=secret')).rejects.toBe(error)
67
+ await flushPromises()
68
+ expect(router.currentRoute.value.path).toBe('/500')
69
+ expect(resourceRecoveryNeeded.value).toBe(true)
70
+ expect(getDiagnosticRecords()).toHaveLength(1)
71
+ expect(JSON.stringify(getDiagnosticRecords())).not.toContain('secret')
72
+ const preload = new Event('vite:preloadError')
73
+ Object.assign(preload, { payload: error })
74
+ window.dispatchEvent(preload)
75
+ expect(preload.defaultPrevented).toBe(false)
76
+ expect(getDiagnosticRecords().at(-1)?.kind).toBe('resource')
77
+ } finally {
78
+ stop()
79
+ }
80
+ const count = getDiagnosticRecords().length
81
+ window.dispatchEvent(new Event('vite:preloadError'))
82
+ expect(getDiagnosticRecords()).toHaveLength(count)
83
+ })
84
+ })