feat: P4-3 eip4-web 前端渲染宿主脚手架(amis 6.13.0 本地化/登录JWT/待办/双闸渲染闸)

- 脚手架:React 18 + Vite 5 + TS;amis 6.13.0 本地 SDK(public/sdk-local,不依赖 CDN,
  照 PoC amis-local.html 范式 amisRequire('amis/embed'))
- 登录页:POST /api/auth/login + JWT 存储(内存+localStorage 折中,XSS 权衡见 README/token.ts)
- 页面渲染 /page/:templateId:取转换后 schema 渲染;开发期静态 mock(public/schemas/ 放
  角色维护/通知管理归档/用户组管理 3 个真实转换产物,均过官方 schema.json 校验闸);
  生产期 schema 接口契约已设计(VITE_SCHEMA_SOURCE 切换)
- 待办页 /todo:GET /api/todo + 503 熔断降级展示
- amis fetcher 适配:复用宿主 axios 注入 Bearer,对接 /api/entity amis CRUD 格式
- axios 拦截器:Bearer 注入 + 401 清会话跳登录
- 联调验证(playwright 无头):登录跳转→渲染用户组(本地库 3 行)→角色维护(真实产物)→
  待办 503 降级→401 跳登录(prod 严格链 8090),5 张截图留 docs/
- 工程化:npm run build → dist/(应用 208KB/gzip 71KB + 本地 SDK 61MB,Nginx 可托管);
  README/报告/gitignore

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 16:13:17 +08:00
parent c51f37e228
commit b3486c093e
140 changed files with 88352 additions and 12 deletions

28
src/api/auth.ts Normal file
View File

@@ -0,0 +1,28 @@
// 登录 API —— POST /api/auth/login(契约见 P2 认证实测报告)
import { http } from './http';
import type { UserProfile } from '../auth/token';
export interface LoginResponse {
success: boolean;
msg?: string;
token: string;
expireSeconds: number;
userId: string;
account: string;
name: string;
roles: string[];
}
export async function login(account: string, password: string): Promise<LoginResponse> {
const { data } = await http.post<LoginResponse>('/api/auth/login', { account, password });
return data;
}
export function toProfile(resp: LoginResponse): UserProfile {
return {
userId: resp.userId,
account: resp.account,
name: resp.name,
roles: resp.roles ?? [],
};
}

42
src/api/http.ts Normal file
View File

@@ -0,0 +1,42 @@
// ============================================================================
// axios 实例 —— 请求注入 Bearer + 响应 401 统一跳登录
// 后端契约(P2 认证实测报告):Authorization: Bearer <jwt>;未认证/伪造/过期 → 401。
// 生产由 Nginx 反代 /api 到后端;开发期由 vite proxy 反代(见 vite.config.ts)。
// ============================================================================
import axios, { AxiosError, type InternalAxiosRequestConfig } from 'axios';
import { clearSession, getToken } from '../auth/token';
// 401 处理回调由应用层(路由)注入,避免 http 层硬依赖 react-router。
let onUnauthorized: (() => void) | null = null;
export function setUnauthorizedHandler(handler: () => void): void {
onUnauthorized = handler;
}
export const http = axios.create({
baseURL: '/',
timeout: 15000,
});
// 请求拦截:带令牌时注入 Bearer 头
http.interceptors.request.use((config: InternalAxiosRequestConfig) => {
const token = getToken();
if (token) {
config.headers.set('Authorization', `Bearer ${token}`);
}
return config;
});
// 响应拦截:401 → 清会话 + 跳登录(登录端点自身的 401 不触发跳转,由调用方处理错误文案)
http.interceptors.response.use(
(resp) => resp,
(error: AxiosError) => {
const status = error.response?.status;
const url = error.config?.url ?? '';
const isLoginCall = url.includes('/api/auth/login');
if (status === 401 && !isLoginCall) {
clearSession();
if (onUnauthorized) onUnauthorized();
}
return Promise.reject(error);
},
);

56
src/api/schema.ts Normal file
View File

@@ -0,0 +1,56 @@
// ============================================================================
// 页面 schema 获取 —— 双源(开发期静态 mock / 生产期后端接口)
// ----------------------------------------------------------------------------
// templateId → schema 映射:
// - 开发期(VITE_SCHEMA_SOURCE 缺省或 'mock'):读 public/schemas/<id>.json
// (内容是 eip4-poc 转换器对客户库真实模板的转换产物,已过官方 schema.json 校验闸)。
// - 生产期(VITE_SCHEMA_SOURCE='backend'):读后端 schema 接口(契约见下)。
//
// 生产期后端 schema 接口契约(本期为设计,后端 P5 落地):
// GET /api/page/schema/{templateId}
// 响应:200 直接返回 amis 页面 schema(JSON,顶层 type:'page'),
// 由后端在「校验闸」通过后下发(官方 schema.json 校验,见迁移手册 §8 双闸)。
// 404:模板不存在;503:转换器不可用。
// 鉴权:带 Bearer(由 http 拦截器注入)。
// ============================================================================
import { http } from './http';
const SOURCE = (import.meta.env.VITE_SCHEMA_SOURCE as string) || 'mock';
// 开发期 mock:templateId → public/schemas 文件名
const MOCK_MAP: Record<string, string> = {
'role-maintain': '/schemas/role-maintain.json',
'notice-archive': '/schemas/notice-archive.json',
'usergroup-manage': '/schemas/usergroup-manage.json',
};
export interface PageMeta {
id: string;
title: string;
}
// 开发期可选页面清单(供页面入口展示导航)
export const MOCK_PAGES: PageMeta[] = [
{ id: 'usergroup-manage', title: '用户组管理(本地实体联调)' },
{ id: 'role-maintain', title: '角色维护(真实转换产物)' },
{ id: 'notice-archive', title: '通知管理归档(真实转换产物)' },
];
export async function fetchSchema(templateId: string): Promise<Record<string, unknown>> {
if (SOURCE === 'backend') {
const { data } = await http.get<Record<string, unknown>>(
`/api/page/schema/${encodeURIComponent(templateId)}`,
);
return data;
}
// 开发期静态 mock
const path = MOCK_MAP[templateId];
if (!path) {
throw new Error(`未知模板:${templateId}(开发期 mock 未配置)`);
}
const resp = await fetch(path);
if (!resp.ok) {
throw new Error(`加载 schema 失败:${resp.status}`);
}
return (await resp.json()) as Record<string, unknown>;
}

44
src/api/todo.ts Normal file
View File

@@ -0,0 +1,44 @@
// 待办聚合 API —— GET /api/todo(契约见 P3 网关实测报告)
// 引擎(flowable-service)不可达时网关返回 503 FLOW_SERVICE_UNAVAILABLE;前端据此降级展示。
import { http } from './http';
export interface TodoItem {
taskId?: string;
taskName?: string;
assignee?: string;
businessKey?: string;
businessTable?: string | null;
businessSummary?: Record<string, unknown>;
createTime?: string;
processInstanceId?: string;
// 兜底:后端字段命名可能小幅差异,保留透传
[key: string]: unknown;
}
export interface TodoResult {
items: TodoItem[];
/** 503 熔断降级标记:true 表示工作流引擎暂不可达 */
unavailable: boolean;
message?: string;
}
export async function fetchTodo(firstResult = 0, maxResults = 20): Promise<TodoResult> {
try {
const { data } = await http.get<TodoItem[] | { items: TodoItem[] }>('/api/todo', {
params: { firstResult, maxResults },
});
// 网关返回数组(P3 报告示例为列表);兼容 {items:[]} 包裹形态
const items = Array.isArray(data) ? data : (data?.items ?? []);
return { items, unavailable: false };
} catch (err) {
const e = err as { response?: { status?: number; data?: { message?: string; error?: string } } };
if (e.response?.status === 503) {
return {
items: [],
unavailable: true,
message: e.response.data?.message || '工作流引擎服务暂不可达,请稍后重试',
};
}
throw err;
}
}