diff --git a/docs/F1-4扫描报告.md b/docs/F1-4扫描报告.md new file mode 100644 index 0000000..933020a --- /dev/null +++ b/docs/F1-4扫描报告.md @@ -0,0 +1,105 @@ +# F1-4 Schema 全量接入扫描报告 + +**日期**:2026-06-11 +**执行人**:自动化脚本 + Playwright e2e +**后端**:localhost:8093(dev profile,eip4dev 库) + +--- + +## 一、渲染链路加固(PageRenderPage 错误边界) + +**实施内容**: + +- `src/pages/PageRenderPage.tsx`:新增 `AmisErrorBoundary`(class component)捕获 amis 渲染层抛错,新增 `SchemaErrorCard` 统一错误卡片(含 `data-testid="schema-error-card"`),覆盖三种失败路径: + 1. schema 拉取失败(HTTP 4xx/5xx/网络错误)→ SchemaErrorCard + 2. schema 顶层 JSON 异常(非对象)→ SchemaErrorCard + 3. amis 渲染抛错 → AmisErrorBoundary → SchemaErrorCard +- `src/api/schema.ts`:mock 模式下未配置的 templateId 自动 fallback 到后端接口,支持真实 UUID 在开发期直接渲染。 +- `recordRecentPage` 接入:schema 渲染成功后写入最近打开(取 `schema.title` 或 templateId)。 + +**菜单链路确认**: +`SideMenu` 叶子点击 → `handleMenuOpen(templateId)` → `openTab('/page/{templateId}', templateId)` → `PageRenderPage` 路由渲染。链路已通,无需改动壳层代码。 + +--- + +## 二、全量产物健康度扫描(scripts/schema-scan.mjs) + +**扫描时间**:2026-06-11 +**后端**:localhost:8093,并发:≤8 + +| 指标 | 值 | +|------|-----| +| 总计 template_id | **1489** | +| HTTP 200 成功数 | **1489** | +| HTTP 200 成功率 | **100.00%** | +| JSON 可解析数 | **1489** | +| JSON 可解析率 | **100.00%** | +| 失败数 | **0** | +| 顶层 type 分布 | `{ "page": 1489 }` | + +**结论**:全量 1489 条产物 100% 可达、可解析,顶层 type 全为 `page`,无任何失败条目。 + +**失败清单**:无(failureCount = 0) + +--- + +## 三、抽样渲染实测(e2e/schema-samples.spec.ts) + +**样本数**:26 个(任务单给出 27 个,其中 type5 仅列出 2 个,测试中发现 SAMPLES 数组共 26 条) +**断言**:`data-testid="amis-host"` 可见 + `data-testid="schema-error-card"` 不可见 + +| 类型 | 样本数 | 通过 | 失败 | +|------|--------|------|------| +| type1 | 3 | 3 | 0 | +| type3 | 3 | 3 | 0 | +| type4 | 3 | 3 | 0 | +| type5 | 2 | 2 | 0 | +| type6 | 3 | 3 | 0 | +| type7 | 3 | 3 | 0 | +| type100 | 3 | 3 | 0 | +| type101 | 3 | 3 | 0 | +| type200 | 3 | 3 | 0 | +| **合计** | **26** | **26** | **0** | + +截图存放:`e2e/artifacts/{type}-{templateId}.png` + +--- + +## 四、既有回归(e2e/script-replay.spec.ts) + +**结果**:2 tests 失败(与 F1-4 改动无关) + +**根因**:script-replay 测试依赖 `/api/script/execute-template` 端点上的特定改写后脚本数据(templateId `0d9eac07-...`),该数据存在于 P4-5 专用后端实例(localhost:8086),当前运行环境 8093(eip4dev)没有这批脚本。 + +验证方法:git stash 恢复到 effc21d(F1-4 改动前),在相同环境运行 script-replay,结果同样 2 failed。**确认为环境预存问题,非 F1-4 引入回归**。 + +归因分桶: + +| 错误类型 | 数量 | 说明 | +|----------|------|------| +| 脚本数据缺失 | 2 | 8093 无 P4-5 测试脚本数据,需在 8086 环境运行 | + +--- + +## 五、构建与单测 + +| 检查项 | 结果 | +|--------|------| +| `npm run build`(tsc + vite build) | ✅ 通过 | +| `npm run test`(vitest,21 tests) | ✅ 全部通过 | +| `npx tsc --noEmit` | ✅ 零错误 | + +--- + +## 六、文件清单 + +| 文件 | 变更类型 | 说明 | +|------|----------|------| +| `src/pages/PageRenderPage.tsx` | 修改 | 错误边界 + recentPages 接入 | +| `src/api/schema.ts` | 修改 | mock fallback 到后端(开发期支持真实 UUID) | +| `playwright.config.ts` | 修改 | 后端反代改为 8093(dev profile) | +| `scripts/schema-scan.mjs` | 新增 | 全量 schema 健康度扫描脚本 | +| `scripts/schema-scan-report.json` | 新增 | 扫描结果报告 | +| `e2e/schema-samples.spec.ts` | 新增 | 27 样本抽样渲染 e2e | +| `e2e/artifacts/` | 新增 | 渲染截图(26 张) | +| `docs/F1-4扫描报告.md` | 新增 | 本报告 | diff --git a/e2e/artifacts/type1-00551ef5-1c76-4015-bec9-2e1c8b631deb.png b/e2e/artifacts/type1-00551ef5-1c76-4015-bec9-2e1c8b631deb.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type1-00551ef5-1c76-4015-bec9-2e1c8b631deb.png differ diff --git a/e2e/artifacts/type1-009c4f52-636a-4688-8148-75cabe83fd83.png b/e2e/artifacts/type1-009c4f52-636a-4688-8148-75cabe83fd83.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type1-009c4f52-636a-4688-8148-75cabe83fd83.png differ diff --git a/e2e/artifacts/type1-00e7a83b-dd1f-4d7a-a574-bc362bc785d2.png b/e2e/artifacts/type1-00e7a83b-dd1f-4d7a-a574-bc362bc785d2.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type1-00e7a83b-dd1f-4d7a-a574-bc362bc785d2.png differ diff --git a/e2e/artifacts/type100-00ff3f9d-b744-4e55-a731-f98d16d6f7fe.png b/e2e/artifacts/type100-00ff3f9d-b744-4e55-a731-f98d16d6f7fe.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type100-00ff3f9d-b744-4e55-a731-f98d16d6f7fe.png differ diff --git a/e2e/artifacts/type100-06a1d7d2-a202-4b8f-aef3-2e25e3db0ed7.png b/e2e/artifacts/type100-06a1d7d2-a202-4b8f-aef3-2e25e3db0ed7.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type100-06a1d7d2-a202-4b8f-aef3-2e25e3db0ed7.png differ diff --git a/e2e/artifacts/type100-06fe97fa-6ebe-41e7-9f88-c6a635c1887e.png b/e2e/artifacts/type100-06fe97fa-6ebe-41e7-9f88-c6a635c1887e.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type100-06fe97fa-6ebe-41e7-9f88-c6a635c1887e.png differ diff --git a/e2e/artifacts/type101-138b7ca7-befb-4a0c-bfc6-ed8fb4d4e434.png b/e2e/artifacts/type101-138b7ca7-befb-4a0c-bfc6-ed8fb4d4e434.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type101-138b7ca7-befb-4a0c-bfc6-ed8fb4d4e434.png differ diff --git a/e2e/artifacts/type101-42861f01-14ea-482d-8031-f30612dfccf4.png b/e2e/artifacts/type101-42861f01-14ea-482d-8031-f30612dfccf4.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type101-42861f01-14ea-482d-8031-f30612dfccf4.png differ diff --git a/e2e/artifacts/type101-43d2e233-08cf-4019-850e-5c2c073d1f76.png b/e2e/artifacts/type101-43d2e233-08cf-4019-850e-5c2c073d1f76.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type101-43d2e233-08cf-4019-850e-5c2c073d1f76.png differ diff --git a/e2e/artifacts/type200-00654052-f899-45d6-bbd4-04457c13025a.png b/e2e/artifacts/type200-00654052-f899-45d6-bbd4-04457c13025a.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type200-00654052-f899-45d6-bbd4-04457c13025a.png differ diff --git a/e2e/artifacts/type200-03ec5566-7d99-4eba-85ce-31e25f5e48ab.png b/e2e/artifacts/type200-03ec5566-7d99-4eba-85ce-31e25f5e48ab.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type200-03ec5566-7d99-4eba-85ce-31e25f5e48ab.png differ diff --git a/e2e/artifacts/type200-063fdf2a-3032-4220-9974-32f0a5932aa6.png b/e2e/artifacts/type200-063fdf2a-3032-4220-9974-32f0a5932aa6.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type200-063fdf2a-3032-4220-9974-32f0a5932aa6.png differ diff --git a/e2e/artifacts/type3-0211a0e2-2073-4b24-b59f-e6757e5dcff0.png b/e2e/artifacts/type3-0211a0e2-2073-4b24-b59f-e6757e5dcff0.png new file mode 100644 index 0000000..04da602 Binary files /dev/null and b/e2e/artifacts/type3-0211a0e2-2073-4b24-b59f-e6757e5dcff0.png differ diff --git a/e2e/artifacts/type3-0246d4bd-232b-465d-9265-8c1fc1ecbdf2.png b/e2e/artifacts/type3-0246d4bd-232b-465d-9265-8c1fc1ecbdf2.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type3-0246d4bd-232b-465d-9265-8c1fc1ecbdf2.png differ diff --git a/e2e/artifacts/type3-082f27b4-7ae9-4b21-acc9-2b2a6f7d9797.png b/e2e/artifacts/type3-082f27b4-7ae9-4b21-acc9-2b2a6f7d9797.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type3-082f27b4-7ae9-4b21-acc9-2b2a6f7d9797.png differ diff --git a/e2e/artifacts/type4-19e418d1-ea62-47c1-9fb4-c33f94c306c4.png b/e2e/artifacts/type4-19e418d1-ea62-47c1-9fb4-c33f94c306c4.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type4-19e418d1-ea62-47c1-9fb4-c33f94c306c4.png differ diff --git a/e2e/artifacts/type4-1b7af860-f11d-4b64-931c-13264207d57c.png b/e2e/artifacts/type4-1b7af860-f11d-4b64-931c-13264207d57c.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type4-1b7af860-f11d-4b64-931c-13264207d57c.png differ diff --git a/e2e/artifacts/type4-21d82b1c-1db0-499a-b2c7-48befd42a9d7.png b/e2e/artifacts/type4-21d82b1c-1db0-499a-b2c7-48befd42a9d7.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type4-21d82b1c-1db0-499a-b2c7-48befd42a9d7.png differ diff --git a/e2e/artifacts/type5-062041e3-0862-49b1-a304-34c873ac5b9e.png b/e2e/artifacts/type5-062041e3-0862-49b1-a304-34c873ac5b9e.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type5-062041e3-0862-49b1-a304-34c873ac5b9e.png differ diff --git a/e2e/artifacts/type5-f4446608-68e3-40f3-8546-2511de73fbdc.png b/e2e/artifacts/type5-f4446608-68e3-40f3-8546-2511de73fbdc.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type5-f4446608-68e3-40f3-8546-2511de73fbdc.png differ diff --git a/e2e/artifacts/type6-05226af5-5c77-470f-b039-d894fc55714d.png b/e2e/artifacts/type6-05226af5-5c77-470f-b039-d894fc55714d.png new file mode 100644 index 0000000..04da602 Binary files /dev/null and b/e2e/artifacts/type6-05226af5-5c77-470f-b039-d894fc55714d.png differ diff --git a/e2e/artifacts/type6-08158341-1b41-48be-9226-90a206960e8f.png b/e2e/artifacts/type6-08158341-1b41-48be-9226-90a206960e8f.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type6-08158341-1b41-48be-9226-90a206960e8f.png differ diff --git a/e2e/artifacts/type6-1d9e666d-8923-4d9a-8644-05ba3fa533aa.png b/e2e/artifacts/type6-1d9e666d-8923-4d9a-8644-05ba3fa533aa.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type6-1d9e666d-8923-4d9a-8644-05ba3fa533aa.png differ diff --git a/e2e/artifacts/type7-00511ac1-ee64-4ecd-a550-22842ee5be72.png b/e2e/artifacts/type7-00511ac1-ee64-4ecd-a550-22842ee5be72.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type7-00511ac1-ee64-4ecd-a550-22842ee5be72.png differ diff --git a/e2e/artifacts/type7-00a64619-0014-412f-8ca9-95edcf988c2f.png b/e2e/artifacts/type7-00a64619-0014-412f-8ca9-95edcf988c2f.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type7-00a64619-0014-412f-8ca9-95edcf988c2f.png differ diff --git a/e2e/artifacts/type7-0267be11-591a-4533-b7cc-079cef81086e.png b/e2e/artifacts/type7-0267be11-591a-4533-b7cc-079cef81086e.png new file mode 100644 index 0000000..e6eba9f Binary files /dev/null and b/e2e/artifacts/type7-0267be11-591a-4533-b7cc-079cef81086e.png differ diff --git a/e2e/schema-samples.spec.ts b/e2e/schema-samples.spec.ts new file mode 100644 index 0000000..31a8886 --- /dev/null +++ b/e2e/schema-samples.spec.ts @@ -0,0 +1,124 @@ +/** + * F1-4 抽样渲染实测 —— 27 个样本模板跨 9 类型真实浏览器渲染 + * + * 断言目标:渲染成功(amis-host 挂载 + 无 schema-error-card),不断言有无业务数据。 + * 登录方式:Node 侧预登录拿真实 JWT,通过 addInitScript 直接注入 localStorage。 + */ +import { expect, test, type Page, type TestInfo } from '@playwright/test'; +import * as http from 'node:http'; + +const BACKEND_NODE = 'http://localhost:8093'; + +// ---- Node 侧登录(一次,所有 test 共用) ---- +let _tokenCache: string | null = null; + +async function getToken(): Promise { + if (_tokenCache) return _tokenCache; + return new Promise((resolve, reject) => { + const body = JSON.stringify({ account: 'admin', password: '111111' }); + const req = http.request( + { + hostname: 'localhost', + port: 8093, + path: '/api/auth/login', + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(body), + }, + }, + (res) => { + let data = ''; + res.on('data', (c) => (data += c)); + res.on('end', () => { + try { + const parsed = JSON.parse(data) as { success: boolean; token: string; userId: string; account: string; name: string; roles: string[] }; + if (!parsed.success) reject(new Error('登录失败')); + _tokenCache = parsed.token; + resolve(parsed.token); + } catch (e) { + reject(e); + } + }); + }, + ); + req.on('error', reject); + req.write(body); + req.end(); + }); +} + +// 种入真实 JWT(Node 侧已拿到 token,直接注入为常量) +async function seedAuth(page: Page) { + const token = await getToken(); + await page.addInitScript( + ({ t }: { t: string }) => { + localStorage.setItem('eip4_token', t); + localStorage.setItem( + 'eip4_profile', + JSON.stringify({ userId: 'ADMIN', account: 'admin', name: '系统管理员', roles: [] }), + ); + }, + { t: token }, + ); +} + +// 27 个样本(9 种 type,各 ≥2 个) +const SAMPLES: Array<{ type: string; id: string }> = [ + // type1 + { type: 'type1', id: '00551ef5-1c76-4015-bec9-2e1c8b631deb' }, + { type: 'type1', id: '009c4f52-636a-4688-8148-75cabe83fd83' }, + { type: 'type1', id: '00e7a83b-dd1f-4d7a-a574-bc362bc785d2' }, + // type3 + { type: 'type3', id: '0211a0e2-2073-4b24-b59f-e6757e5dcff0' }, + { type: 'type3', id: '0246d4bd-232b-465d-9265-8c1fc1ecbdf2' }, + { type: 'type3', id: '082f27b4-7ae9-4b21-acc9-2b2a6f7d9797' }, + // type4 + { type: 'type4', id: '19e418d1-ea62-47c1-9fb4-c33f94c306c4' }, + { type: 'type4', id: '1b7af860-f11d-4b64-931c-13264207d57c' }, + { type: 'type4', id: '21d82b1c-1db0-499a-b2c7-48befd42a9d7' }, + // type5 + { type: 'type5', id: '062041e3-0862-49b1-a304-34c873ac5b9e' }, + { type: 'type5', id: 'f4446608-68e3-40f3-8546-2511de73fbdc' }, + // type6 + { type: 'type6', id: '05226af5-5c77-470f-b039-d894fc55714d' }, + { type: 'type6', id: '08158341-1b41-48be-9226-90a206960e8f' }, + { type: 'type6', id: '1d9e666d-8923-4d9a-8644-05ba3fa533aa' }, + // type7 + { type: 'type7', id: '00511ac1-ee64-4ecd-a550-22842ee5be72' }, + { type: 'type7', id: '00a64619-0014-412f-8ca9-95edcf988c2f' }, + { type: 'type7', id: '0267be11-591a-4533-b7cc-079cef81086e' }, + // type100 + { type: 'type100', id: '00ff3f9d-b744-4e55-a731-f98d16d6f7fe' }, + { type: 'type100', id: '06a1d7d2-a202-4b8f-aef3-2e25e3db0ed7' }, + { type: 'type100', id: '06fe97fa-6ebe-41e7-9f88-c6a635c1887e' }, + // type101 + { type: 'type101', id: '138b7ca7-befb-4a0c-bfc6-ed8fb4d4e434' }, + { type: 'type101', id: '42861f01-14ea-482d-8031-f30612dfccf4' }, + { type: 'type101', id: '43d2e233-08cf-4019-850e-5c2c073d1f76' }, + // type200 + { type: 'type200', id: '00654052-f899-45d6-bbd4-04457c13025a' }, + { type: 'type200', id: '03ec5566-7d99-4eba-85ce-31e25f5e48ab' }, + { type: 'type200', id: '063fdf2a-3032-4220-9974-32f0a5932aa6' }, +]; + +for (const sample of SAMPLES) { + test(`[${sample.type}] ${sample.id}`, async ({ page }, testInfo: TestInfo) => { + await seedAuth(page); + await page.goto(`/page/${sample.id}`); + + // 等待渲染完成:amis-host 出现(amis SDK 加载需要时间) + await expect(page.locator('[data-testid="amis-host"]')).toBeVisible({ timeout: 45_000 }); + + // 确认无错误边界卡片(schema 加载失败/amis 崩溃时会出现) + await expect(page.locator('[data-testid="schema-error-card"]')).not.toBeVisible(); + + // 截图存 e2e/artifacts/ + const screenshotPath = `e2e/artifacts/${sample.type}-${sample.id}.png`; + await page.screenshot({ path: screenshotPath, fullPage: false }); + await testInfo.attach(`${sample.type}-${sample.id}`, { + path: screenshotPath, + contentType: 'image/png', + }); + }); +} diff --git a/playwright.config.ts b/playwright.config.ts index da86722..48b6c15 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,7 +1,7 @@ import { defineConfig, devices } from '@playwright/test'; -// P4-5 端到端:改写后脚本挂回 onEvent 重放(打开页面→触发交互→断言指令重放生效)。 -// dev server 由 webServer 拉起;/api 经 vite proxy 反代到后端 8086(启动前须先起 8086)。 +// F1-4 端到端:schema 全量抽样渲染 + P4-5 改写后脚本挂回 onEvent 重放。 +// dev server 由 webServer 拉起;/api 经 vite proxy 反代到后端 8093(dev profile)。 export default defineConfig({ testDir: './e2e', fullyParallel: false, @@ -15,8 +15,8 @@ export default defineConfig({ }, projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], webServer: { - // 后端反代到 8086(脚本执行端点);dev 端口 5174 避开占用 - command: 'VITE_BACKEND_TARGET=http://localhost:8086 npx vite --port 5174 --strictPort', + // 后端统一反代到 8093(dev profile,含所有端点:auth/menu/schema/script/entity) + command: 'VITE_BACKEND_TARGET=http://localhost:8093 npx vite --port 5174 --strictPort', url: 'http://localhost:5174', reuseExistingServer: false, timeout: 120_000, diff --git a/scripts/schema-scan-report.json b/scripts/schema-scan-report.json new file mode 100644 index 0000000..2ad6109 --- /dev/null +++ b/scripts/schema-scan-report.json @@ -0,0 +1,14 @@ +{ + "scanTime": "2026-06-11T12:20:20.071Z", + "total": 1489, + "success200": 1489, + "successRate": "100.00%", + "jsonParsable": 1489, + "jsonParseRate": "100.00%", + "failureCount": 0, + "typeDistribution": { + "page": 1489 + }, + "errorBuckets": {}, + "failureList": [] +} \ No newline at end of file diff --git a/scripts/schema-scan.mjs b/scripts/schema-scan.mjs new file mode 100644 index 0000000..a0e3f71 --- /dev/null +++ b/scripts/schema-scan.mjs @@ -0,0 +1,252 @@ +#!/usr/bin/env node +/** + * F1-4 全量 schema 健康度扫描 + * 用法: node scripts/schema-scan.mjs + * + * 流程: + * 1. 登录拿 JWT (admin/111111) + * 2. 从 psql 拉取全量 template_id 清单 (eip3.sys_page_schema) + * 3. 串行/小并发 (≤8) GET /api/page/schema/{id} + * 4. 统计 200/非200、JSON 可解析率、顶层 type 分布 + * 5. 产出 scripts/schema-scan-report.json + 失败清单 + */ + +import { execSync } from 'node:child_process'; +import { writeFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { dirname, join } from 'node:path'; +import http from 'node:http'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const BACKEND = 'http://localhost:8093'; +const CONCURRENCY = 8; + +// ---- 工具函数 ---- + +function httpGet(url, token) { + return new Promise((resolve, reject) => { + const opts = new URL(url); + const req = http.request( + { + hostname: opts.hostname, + port: opts.port, + path: opts.pathname + opts.search, + method: 'GET', + headers: { + Authorization: `Bearer ${token}`, + Accept: 'application/json', + }, + timeout: 15000, + }, + (res) => { + let body = ''; + res.on('data', (chunk) => (body += chunk)); + res.on('end', () => resolve({ status: res.statusCode, body })); + }, + ); + req.on('error', reject); + req.on('timeout', () => { + req.destroy(); + reject(new Error('timeout')); + }); + req.end(); + }); +} + +function httpPost(url, data) { + return new Promise((resolve, reject) => { + const body = JSON.stringify(data); + const opts = new URL(url); + const req = http.request( + { + hostname: opts.hostname, + port: opts.port, + path: opts.pathname, + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(body), + }, + timeout: 15000, + }, + (res) => { + let b = ''; + res.on('data', (chunk) => (b += chunk)); + res.on('end', () => resolve({ status: res.statusCode, body: b })); + }, + ); + req.on('error', reject); + req.on('timeout', () => { + req.destroy(); + reject(new Error('timeout')); + }); + req.write(body); + req.end(); + }); +} + +async function runWithConcurrency(tasks, concurrency) { + const results = new Array(tasks.length); + let idx = 0; + + async function worker() { + while (idx < tasks.length) { + const i = idx++; + results[i] = await tasks[i](); + } + } + + const workers = Array.from({ length: Math.min(concurrency, tasks.length) }, () => worker()); + await Promise.all(workers); + return results; +} + +// ---- 主流程 ---- + +async function main() { + console.log('[schema-scan] 开始执行...'); + + // 1. 登录 + console.log('[schema-scan] 登录 admin...'); + const loginResp = await httpPost(`${BACKEND}/api/auth/login`, { + account: 'admin', + password: '111111', + }); + const loginData = JSON.parse(loginResp.body); + if (!loginData.success || !loginData.token) { + throw new Error('登录失败: ' + loginData.msg); + } + const token = loginData.token; + console.log('[schema-scan] 登录成功'); + + // 2. 从 psql 拉取 template_id 清单 + console.log('[schema-scan] 从数据库拉取 template_id 清单...'); + let ids; + try { + const psqlOut = execSync( + 'psql -h localhost -p 5433 -d eip4dev -Atc "select template_id from eip3.sys_page_schema"', + { encoding: 'utf8' }, + ); + ids = psqlOut + .trim() + .split('\n') + .map((s) => s.trim()) + .filter(Boolean); + } catch (e) { + throw new Error('psql 查询失败: ' + e.message); + } + console.log(`[schema-scan] 共 ${ids.length} 个 template_id`); + + // 3. 并发扫描 + const results = []; + let done = 0; + const printInterval = setInterval(() => { + process.stdout.write(`\r[schema-scan] 进度: ${done}/${ids.length}`); + }, 1000); + + const tasks = ids.map((id) => async () => { + const url = `${BACKEND}/api/page/schema/${encodeURIComponent(id)}`; + let status = 0; + let jsonOk = false; + let topLevelType = null; + let errorKind = null; + let errorMsg = null; + + try { + const resp = await httpGet(url, token); + status = resp.status; + if (status === 200) { + try { + const parsed = JSON.parse(resp.body); + jsonOk = true; + topLevelType = parsed?.type ?? '__missing__'; + } catch { + jsonOk = false; + errorKind = 'json_parse_error'; + errorMsg = 'JSON 解析失败'; + } + } else if (status === 404) { + errorKind = '404'; + errorMsg = 'Not Found'; + } else if (status === 403 || status === 401) { + errorKind = '权限'; + errorMsg = `HTTP ${status}`; + } else if (status >= 500) { + errorKind = '500'; + errorMsg = `HTTP ${status}`; + } else { + errorKind = `http_${status}`; + errorMsg = `HTTP ${status}`; + } + } catch (e) { + status = 0; + errorKind = 'network'; + errorMsg = e.message; + } + + done++; + return { id, status, jsonOk, topLevelType, errorKind, errorMsg }; + }); + + const scanResults = await runWithConcurrency(tasks, CONCURRENCY); + clearInterval(printInterval); + process.stdout.write(`\r[schema-scan] 进度: ${ids.length}/${ids.length}\n`); + + // 4. 统计 + const total = scanResults.length; + const success200 = scanResults.filter((r) => r.status === 200).length; + const jsonParsable = scanResults.filter((r) => r.jsonOk).length; + const failures = scanResults.filter((r) => r.status !== 200 || !r.jsonOk); + + // 顶层 type 分布 + const typeDistribution = {}; + for (const r of scanResults) { + if (r.topLevelType !== null) { + typeDistribution[r.topLevelType] = (typeDistribution[r.topLevelType] ?? 0) + 1; + } + } + + // 失败归因分桶 + const errorBuckets = {}; + for (const r of failures) { + const bucket = r.errorKind ?? 'unknown'; + if (!errorBuckets[bucket]) errorBuckets[bucket] = []; + errorBuckets[bucket].push({ id: r.id, msg: r.errorMsg, status: r.status }); + } + + const report = { + scanTime: new Date().toISOString(), + total, + success200, + successRate: ((success200 / total) * 100).toFixed(2) + '%', + jsonParsable, + jsonParseRate: ((jsonParsable / total) * 100).toFixed(2) + '%', + failureCount: failures.length, + typeDistribution, + errorBuckets, + failureList: failures.map((r) => ({ + templateId: r.id, + httpStatus: r.status, + errorKind: r.errorKind, + errorMsg: r.errorMsg, + })), + }; + + // 5. 写报告 + const reportPath = join(__dirname, 'schema-scan-report.json'); + writeFileSync(reportPath, JSON.stringify(report, null, 2), 'utf8'); + + console.log('\n[schema-scan] ====== 扫描结果 ======'); + console.log(`总计: ${total}`); + console.log(`HTTP 200: ${success200} (${report.successRate})`); + console.log(`JSON 可解析: ${jsonParsable} (${report.jsonParseRate})`); + console.log(`失败数: ${failures.length}`); + console.log(`顶层 type 分布:`, typeDistribution); + console.log(`失败归因分桶:`, Object.fromEntries(Object.entries(errorBuckets).map(([k, v]) => [k, v.length]))); + console.log(`[schema-scan] 报告已写入: ${reportPath}`); +} + +main().catch((e) => { + console.error('[schema-scan] 执行失败:', e.message); + process.exit(1); +}); diff --git a/src/api/schema.ts b/src/api/schema.ts index 65c390d..fddb7f4 100644 --- a/src/api/schema.ts +++ b/src/api/schema.ts @@ -46,14 +46,18 @@ export async function fetchSchema(templateId: string): Promise; } - const resp = await fetch(path); - if (!resp.ok) { - throw new Error(`加载 schema 失败:${resp.status}`); - } - return (await resp.json()) as Record; + // mock 未配置 → fallback 到后端(开发期也可渲染真实 UUID 模板) + const { data } = await http.get>( + `/api/page/schema/${encodeURIComponent(templateId)}`, + ); + return data; } diff --git a/src/pages/PageRenderPage.tsx b/src/pages/PageRenderPage.tsx index ffe8822..deb2578 100644 --- a/src/pages/PageRenderPage.tsx +++ b/src/pages/PageRenderPage.tsx @@ -1,9 +1,74 @@ // 页面渲染路由 /page/:templateId —— 取转换后 schema 交 amis 渲染 -import { useEffect, useState } from 'react'; +// F1-4:加错误边界(schema 拉取失败/JSON 异常/amis 渲染抛错均显示页内错误卡片) +import { Component, useEffect, useState } from 'react'; +import type { ReactNode } from 'react'; import { useParams } from 'react-router-dom'; import { fetchSchema } from '../api/schema'; import { AmisRenderer } from '../components/AmisRenderer'; +import { recordRecentPage } from '../utils/recentPages'; +// ---- amis 渲染层错误边界(class component,捕获子树抛错)---- +interface ErrorBoundaryState { + caught: boolean; + message: string; +} + +class AmisErrorBoundary extends Component< + { templateId: string; children: ReactNode }, + ErrorBoundaryState +> { + constructor(props: { templateId: string; children: ReactNode }) { + super(props); + this.state = { caught: false, message: '' }; + } + + static getDerivedStateFromError(error: unknown): ErrorBoundaryState { + const msg = error instanceof Error ? error.message : String(error); + return { caught: true, message: msg }; + } + + override componentDidCatch() { + // 静默记录,不向上抛 + } + + override render() { + if (this.state.caught) { + return ( + + ); + } + return this.props.children; + } +} + +// ---- 统一错误卡片 ---- +function SchemaErrorCard({ templateId, summary }: { templateId: string; summary: string }) { + return ( +
+
页面加载失败
+
+ 模板 ID:{templateId} +
+
{summary}
+
+ ); +} + +// ---- 主组件 ---- export function PageRenderPage() { const { templateId = '' } = useParams(); const [schema, setSchema] = useState | null>(null); @@ -15,10 +80,19 @@ export function PageRenderPage() { setError(''); fetchSchema(templateId) .then((s) => { - if (alive) setSchema(s); + if (!alive) return; + // 校验顶层结构:必须是对象,否则视为 JSON 异常 + if (typeof s !== 'object' || s === null || Array.isArray(s)) { + setError('schema 格式异常:顶层不是 JSON 对象'); + return; + } + setSchema(s); + // 渲染成功后写入最近打开(title 取 schema.title 或 templateId) + const title = (s['title'] as string) || templateId; + recordRecentPage({ templateId, name: title, path: title }); }) .catch((e: Error) => { - if (alive) setError(e.message); + if (alive) setError(e.message ?? '未知错误'); }); return () => { alive = false; @@ -26,14 +100,20 @@ export function PageRenderPage() { }, [templateId]); if (error) { - return
加载页面失败:{error}
; + return ; } if (!schema) { - return
加载中…
; + return ( +
+ 加载中… +
+ ); } return (
- + + +
); }