Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a036f39713 | ||
|
|
3ed3af3962 | ||
|
|
3acbc79008 | ||
|
|
85a7f563f6 | ||
|
|
bed01788fd | ||
|
|
0dac2d3b6e | ||
|
|
449ad16244 | ||
|
|
77060325ef | ||
|
|
8a21d85036 | ||
|
|
ff0f79a473 | ||
|
|
5b886f4fc2 | ||
|
|
1db85be875 | ||
|
|
7d6560703d | ||
|
|
8c8147cd5b |
@@ -0,0 +1,7 @@
|
||||
# 本地纯前端演示模式:仅 vite --mode mock 加载(推荐入口 npm run dev:mock,
|
||||
# 由 scripts/start-mock.mjs 一并拉起 9527 主题静态通道;直接 vite --mode mock 也可,
|
||||
# 但无 VPN 时主题 CSS 取不到、只剩骨架)。build 产物不读任何 .env.*。
|
||||
# 后端/VPN 不可达时,vite dev server 内置中间件按后端契约拦截 /open-gateway/api/internal/**
|
||||
# (见 vite.config.ts gatewayAdminMockPlugin + src/assets/mock/gatewayApi.ts)。
|
||||
VITE_SERVICE_HOST=/open-gateway
|
||||
VITE_IS_MOCK=true
|
||||
@@ -0,0 +1,86 @@
|
||||
# 网关台账前端 Mock 演示指南
|
||||
|
||||
离线(无 VPN、无后端)一键起完整可演示环境:三个治理页全量可看可玩 + YschTheme 主题五档配色。
|
||||
|
||||
## 一条命令
|
||||
|
||||
```cmd
|
||||
cd D:\SoftProject\yunhai\open-gateway\front
|
||||
npm run dev:mock
|
||||
```
|
||||
|
||||
然后浏览器打开 **http://localhost:8131**(自动落在「访问台账」页)。
|
||||
|
||||
前提:Node **20.19.4**(本机 nvm 路径 `D:\nvm\nvm\v20.19.4`,若 `node -v` 不对请先 `nvm use 20.19.4`),`front/node_modules` 已安装。
|
||||
|
||||
`dev:mock`(`scripts/start-mock.mjs`,零依赖)做三件事:
|
||||
|
||||
1. 拉起 **YschTheme 本地静态通道**:`YschTheme/scripts/dev-serve.mjs` 把 `YschTheme/dist/pc` 挂到 `http://localhost:9527/static/`(主题 CSS/JS 不拷进本仓——应用侧不持主题副本是主题仓硬原则);
|
||||
2. 探活 `9527/static/manifest.json`;
|
||||
3. 以 `YH_THEME_PROXY_TARGET=http://localhost:9527` 启动 `vite --mode mock`(8131),vite 的 `/static` 代理由此指向本地通道。
|
||||
|
||||
全程不触网。`Ctrl+C` 退出会一并收掉两个子进程;若 9527 被上次残留进程占用且可服务,脚本会直接复用。
|
||||
|
||||
### 切回真后端
|
||||
|
||||
装好 VPN 后照旧 `npm run dev`(走 `.env.dev`,经 `/open-gateway/api` 代理到 base 域),与 `dev:mock` 互不影响、互不覆盖。线上 build(`npm run build`)不读任何 `.env.*`,行为与 mock 无关。
|
||||
|
||||
## 每页看什么、玩什么
|
||||
|
||||
| 页面 | 看点 / 操作 |
|
||||
| --- | --- |
|
||||
| **/ledger 访问台账** | 233 条调用记录,时间倒序。翻页(24 页);`target` 与 `调用方 appKey` 精确筛选(试试 `notice` + `100001` → 共 5 条;`callerAppKey` 填 `anonymous` 可筛匿名调用,填了查不到的值=空列表);「查看详情」弹窗;状态码色阶:2xx 绿 / 4xx 琥珀 / 5xx 红;「后端码」恒 `-`(流式转发不解析业务 code) |
|
||||
| **/routes 路由注册表** | 28 行路由。行内改 `visibility`(INTERNAL/EXTERNAL)、`authMode`(SIGNED/ANON)、缓存秒数/范围、qps、启停、备注 → 「保存」→ toast「已保存,注册表加载 N 条路由」;离开页面再进来,值保持(内存态);把缓存秒数改成负数保存 → 后端同款报错 toast(`cacheTtlSeconds 非法:-5(须为 ≥0 的整数)`) |
|
||||
| **/targets 目标地址** | 7 个生产 ctx。行内改 `baseUrl` → 保存 → toast「已保存,目标表加载 7 条」;`baseUrl` 清空保存 → 报错 toast;启停开关 |
|
||||
| **顶栏** | 「重载注册表」→ toast「已重载:路由 28 条 / 目标 7 条」+「最后更新 HH:mm:ss」;「手动刷新」重建当前页;MOCK 徽标(仅 mock 模式出现) |
|
||||
| **右上「配色」胶囊** | 五档主题色(原版靛蓝/云海蓝/石墨墨/靛紫/松石绿)+ 侧栏深浅/侧栏跟随/顶部渐变三开关;选择持久化在 localStorage(`yh-theme`),刷新/重开浏览器保持 |
|
||||
|
||||
**Mock 数据的存活性**:PUT 改动只存在于 vite 进程内存——站内切换页面改动**保持**;**浏览器整页刷新/直达(F5)即重置**回静态种子;重启 `dev:mock` 也重置。台账 `ts` 以重置时刻为终点向过去铺 6.5 天,所以永远是"近期"。
|
||||
|
||||
## Mock 数据清单
|
||||
|
||||
数据源:`src/assets/mock/gatewayApi.ts`(种子 + 确定性 LCG,改种子改这里)。
|
||||
|
||||
- **targets(7)**:userbase、userclass、yschcms、svc-hall、flow-center、usermsg、notice;`baseUrl = http://{targetCode}-service:8080`(照 `service/docs/sql/03_target.sql` 语义)。
|
||||
- **routes(28)**:
|
||||
- 22 行 = `service/docs/sql/02_init_routes.sql` 全量种子(全保守档 INTERNAL×SIGNED、cacheTtl 0、qps 0,备注原样照抄);
|
||||
- 6 行治理样本:id23 `yschcms /oapi/site/render/**`(EXTERNAL×ANON,GLOBAL 缓存 600s,qps 50)、id24 `svc-hall /oapi/svc/items/**`(EXTERNAL×ANON,CALLER 缓存 60s)、id25 `notice /oapi/notice/public/**`(EXTERNAL×ANON,GLOBAL 300s,qps 100)、id26 `userbase /oapi/user/batchAdd`(EXTERNAL×SIGNED,qps 5 熔断)、id27 `usermsg /oapi/msg/health`(INTERNAL×ANON,**空备注**样本)、id28 `flow-center /oapi/flow/diagram/**`(**停用**行样本)。
|
||||
- 四种 visibility×authMode 组合、空备注、停用行、差异化 ttl/qps/remark 全覆盖。
|
||||
- **logs(233)**:appKey 取实测值 100001/100007/100009/100010/100013(约六成行),`"anonymous"` 约 46 行,`callerAppKey=null`(未携带 appKey 被网关拒)约 51 行;status 覆盖 200/401/403/404/500(约 125/69/30/3/6);costMs 3~1602ms 快慢兼有;path 为该 target 路由形态(`/**` 或具体 id 段);backendCode 恒 null。
|
||||
|
||||
## 与真实接口的契约对照
|
||||
|
||||
统一信封 `{code:0, msg:"", data:X}`;业务非法一律 **HTTP 200 + `{code:2, msg:"…"}`**(前端 alova 层弹 msg);分页 data 形状 `{total, content, pageIndex, pageSize, totalPages, hasNext}`。
|
||||
|
||||
| 接口 | 契约 | mock 实现 |
|
||||
| --- | --- | --- |
|
||||
| `GET /api/internal/admin/routes?pageIndex&pageSize` | 排序 targetCode,pathPattern;无 keyword 参数 | 一致(localeCompare 排序) |
|
||||
| `PUT /api/internal/admin/routes/{id}` | body 只认 7 键:visibility/authMode/cacheTtlSeconds/cacheScope/rateLimitQps/enabled/remark;visibility∈{INTERNAL,EXTERNAL}、authMode∈{SIGNED,ANON}、cacheScope∈{CALLER,GLOBAL};两 int 须 Number 且 ≥0;**enabled 须真布尔——传字符串 `"true"` 一律按 false 落库(后端真实坑,照抄)**;成功 `data={loaded:路由总条数}`;非法→`{code:2,msg:"visibility 非法:XXX(合法 [EXTERNAL, INTERNAL])"}` | 全部一致,错误消息格式一字不差 |
|
||||
| `GET /api/internal/admin/targets` | 同信封分页 | 一致 |
|
||||
| `PUT /api/internal/admin/targets/{id}` | body{baseUrl 非空, enabled 真布尔};成功 `data={targets:N}` | 一致 |
|
||||
| `GET /api/internal/admin/logs?pageIndex&pageSize&targetCode&callerAppKey` | pageSize 默认 50 上限 500;筛选**精确等值**、空串=不过滤;排序 id desc;`ts` ISO 字符串;backendCode 恒 null | 一致(先过滤再分页) |
|
||||
| `POST /api/internal/routes/refresh` | 无入参 → `data={loaded,targets}` | 一致(返回内存实时条数:28/7) |
|
||||
|
||||
前端请求带 `/open-gateway` 前缀(serviceHost),mock 中间件按剥前缀后的真实路径匹配。
|
||||
|
||||
## 与真后端的差异(mock 不造假接口)
|
||||
|
||||
- **无登录/CAS**(后端本就没有,治理面靠 Caddy 白名单);顶栏用户区是静态占位「网关治理」。
|
||||
- **无 keyword 模糊搜索**(routes 接口没有该参数,别造)。
|
||||
- **无路由/目标的新增与删除**(后端只支持行内编辑)。
|
||||
- **无统计、无时间过滤**(M1 范围,后端尚无接口)。
|
||||
- **无 caller 管理**页(appKey 只出现在台账里)。
|
||||
- 刷新/重启即重置;真实后端当然是持久化的。
|
||||
|
||||
## 主题说明(YschTheme 中央静态通道)
|
||||
|
||||
- **接入方式**:`index.html` 头部一段同步 loader(照 Notice 配方,A 类免插件)引 `/static/js/yh-theme-init.js`;host 优先级 `__APP_CONFIG__.staticHost > baseHost > %VITE_THEME_HOST%(dev 可注入)> 同源 /static/`。网关无 env-config,恒走后两档;build 不替换占位符 → 线上走同源通道,零环境值烧入。
|
||||
- **本地联调**:vite `/static` 代理 → `YH_THEME_PROXY_TARGET`(dev:mock 指本地 9527;`npm run dev` 时指 base 域——**无 VPN 时 `npm run dev` 主题 CSS 取不到,页面剩骨架无皮肤**,这正是 dev:mock 存在的原因)。
|
||||
- **档位**:五档配色 + 侧栏深浅 + 侧栏跟随 + 顶部渐变,状态存 localStorage(`yh-theme`),由 `/static/js/yh-theme-init.js` 在首帧前挂 `<html>` 档位类(防 FOUC)。
|
||||
- **sync 四件**:`src/utils/theme.ts`、`src/components/ThemeSwitcher.vue`、`src/utils/avatar.ts`、`src/components/UserAvatar.vue` 由 YschTheme 下发(consumers.json 已登记 open-gateway 条目)。⚠️ `theme.ts` 顶部有本仓加的 `// @ts-nocheck`(上游为松类型产物)——**下次 `npm run sync` 覆盖后需补回该行**,否则 `npm run typecheck` 报错。
|
||||
|
||||
## 实现备注
|
||||
|
||||
- mock 走 **vite.config.ts 手写 `configureServer` 中间件**(仅 `--mode mock` 注册,先于内部代理),而非常规 `vite-plugin-mock`:后者用 esbuild 独立打包 mock 文件,与 vite 配置是两个模块实例,无法实现「整页刷新重置内存态」;且零新依赖(红线:不引运行时新依赖)。
|
||||
- `.env.mock` 仅两行:`VITE_SERVICE_HOST=/open-gateway` + `VITE_IS_MOCK=true`(后者驱动顶栏 MOCK 徽标,dev/线上恒不出现)。
|
||||
- 非 mock 模式(`npm run dev` / `npm run build`)行为与改造前一致(唯一例外:布局样式改由主题通道下发,本地 `layout.css` 快照已删除)。
|
||||
+16
@@ -4,6 +4,22 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<!-- 主题通道引导(A 类免插件接入,照 Notice 配方):唯一接入点,不装依赖、无需 env-config。
|
||||
origin 零写死,优先级:__APP_CONFIG__.staticHost > baseHost > %VITE_THEME_HOST%(仅 dev 可注入)
|
||||
> 同源 "/static/…"(生产常态:通道与应用同域;本地 dev/mock 由 vite /static 代理兜到通道,
|
||||
dev:mock 时 scripts/start-mock.mjs 把代理目标指到本地 9527,无 VPN 离线可跑)。
|
||||
网关后端无 env-config 端点,__APP_CONFIG__ 恒为空 → 实际恒走后两档。
|
||||
document.write 保证 parser-blocking:档位挂载与 FOUC 门先于首帧;build 不解析内联脚本字符串,
|
||||
占位符原样留字面量 → 判首字符 % 置空,产物零环境值烧入。 -->
|
||||
<script>
|
||||
(function () {
|
||||
var c = window.__APP_CONFIG__ || {};
|
||||
var themeHost = "%VITE_THEME_HOST%";
|
||||
if (themeHost.charAt(0) === "%") themeHost = "";
|
||||
var host = String(c.staticHost || c.baseHost || themeHost).replace(/\/+$/, "");
|
||||
document.write('<script src="' + host + '/static/js/yh-theme-init.js"><\/script>');
|
||||
})();
|
||||
</script>
|
||||
<title><%- title %></title>
|
||||
<%- injectScript %>
|
||||
</head>
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --mode dev",
|
||||
"dev:mock": "node scripts/start-mock.mjs",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"build": "vite build --mode base",
|
||||
"build:base": "vite build --mode base",
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* start-mock.mjs —— 无 VPN 一键离线演示(npm run dev:mock)。
|
||||
*
|
||||
* 做三件事(零第三方依赖,Node 20 自带 fetch):
|
||||
* 1. 拉起 YschTheme 的本地静态通道 scripts/dev-serve.mjs(9527,/dist/pc 挂 /static/);
|
||||
* 2. 探活 9527/static/manifest.json(若端口已被上次残留进程占用且可服务,同样放行);
|
||||
* 3. 以 YH_THEME_PROXY_TARGET=http://localhost:9527 spawn vite --mode mock(8131)。
|
||||
*
|
||||
* 效果:浏览器访问 http://localhost:8131 —— 三页治理台账全量可演示(mock 数据),
|
||||
* 主题 CSS/切换器经本地 9527 供给,全程不触网、不需要 VPN。
|
||||
* 主题静态资源不拷进 front/public(应用侧不持主题副本是主题仓硬原则)。
|
||||
* VPN 恢复后照旧 npm run dev 走真后端,两者互不影响。Ctrl+C 退出会一并收掉两个子进程。
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const frontDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const themeDir = path.resolve(frontDir, "..", "..", "YschTheme");
|
||||
const themeServeScript = path.join(themeDir, "scripts", "dev-serve.mjs");
|
||||
const viteBin = path.join(frontDir, "node_modules", "vite", "bin", "vite.js");
|
||||
const THEME_PORT = 9527;
|
||||
|
||||
const fail = (msg) => {
|
||||
console.error(`[start-mock] ${msg}`);
|
||||
process.exit(1);
|
||||
};
|
||||
|
||||
if (!existsSync(themeServeScript)) {
|
||||
fail(`找不到主题静态服务脚本 ${themeServeScript}(YschTheme 仓位置异常?)`);
|
||||
}
|
||||
if (!existsSync(viteBin)) {
|
||||
fail(`找不到 ${viteBin}(先在 front 目录 npm install)`);
|
||||
}
|
||||
|
||||
/* 1. 本地静态通道(YschTheme 零依赖实现,serve dist/pc 于 /static/) */
|
||||
const themeServer = spawn(process.execPath, [themeServeScript], {
|
||||
cwd: themeDir,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
themeServer.stdout.on("data", (d) => process.stdout.write(`[theme] ${d}`));
|
||||
themeServer.stderr.on("data", (d) => process.stderr.write(`[theme] ${d}`));
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
async function waitThemeReady(tries = 24) {
|
||||
for (let i = 0; i < tries; i++) {
|
||||
try {
|
||||
const res = await fetch(`http://localhost:${THEME_PORT}/static/manifest.json`);
|
||||
if (res.ok) return true;
|
||||
} catch {
|
||||
/* 尚未就绪/端口被占(占位进程若可服务也会在上面返回 ok) */
|
||||
}
|
||||
await sleep(250);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* 2. 探活:主题通道就绪才起前端(演示强依赖主题 CSS) */
|
||||
if (!(await waitThemeReady())) {
|
||||
themeServer.kill();
|
||||
fail(`9527 主题静态通道未就绪 —— 检查 ${themeServeScript} 与 YschTheme/dist/pc 是否存在(必要时先在 YschTheme 跑 npm run gen)`);
|
||||
}
|
||||
console.log(`[start-mock] 主题静态通道就绪 → http://localhost:${THEME_PORT}/static/`);
|
||||
|
||||
/* 3. vite --mode mock(dev server 8131;/static 代理由 YH_THEME_PROXY_TARGET 指向 9527) */
|
||||
const vite = spawn(process.execPath, [viteBin, "--mode", "mock"], {
|
||||
cwd: frontDir,
|
||||
stdio: "inherit",
|
||||
env: { ...process.env, YH_THEME_PROXY_TARGET: `http://localhost:${THEME_PORT}` },
|
||||
});
|
||||
|
||||
const shutdown = () => {
|
||||
vite.kill();
|
||||
themeServer.kill();
|
||||
};
|
||||
vite.on("exit", (code) => {
|
||||
themeServer.kill();
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
themeServer.on("exit", () => {
|
||||
/* 9527 若由残留进程提供则本子进程会因端口占用退出,探活已放行,不必终止演示 */
|
||||
});
|
||||
for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => {
|
||||
shutdown();
|
||||
process.exit(0);
|
||||
});
|
||||
+13
-1
@@ -6,11 +6,13 @@ import { LayoutData } from "./types/Basics";
|
||||
|
||||
const isRouterAlive = ref(true), isLogin = ref(false);
|
||||
|
||||
/** 网关无菜单接口:三个治理页写死为静态菜单(与 notice/userbase 的 LeftMenu 同形) */
|
||||
/** 网关无菜单接口:治理页写死为静态菜单(与 notice/userbase 的 LeftMenu 同形) */
|
||||
const modList = [
|
||||
{ name: "LedgerList", title: "访问台账", page: "/ledger" },
|
||||
{ name: "RouteList", title: "路由注册表", page: "/routes" },
|
||||
{ name: "TargetList", title: "目标地址", page: "/targets" },
|
||||
{ name: "AppList", title: "应用管理", page: "/apps" },
|
||||
{ name: "ProxyTest", title: "代理测试", page: "/proxy-test" },
|
||||
];
|
||||
|
||||
const layoutData: LayoutData = reactive({
|
||||
@@ -63,11 +65,21 @@ const getRouterKey = (route: any) => route?.name;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
/* 照 Notice 配方锁定视口:顶栏/侧栏/面包屑均 fixed,若 body 可滚,整页滚动会让内容
|
||||
从 fixed 导航下方穿过(错位遮挡);改为 main-wrapper 内部滚动 */
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
#app {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.base-wrap-main .main-wrapper {
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -11,6 +11,10 @@ export default {
|
||||
'GatewayAdmin.updateRoute': ['PUT', '/api/internal/admin/routes/{id}'],
|
||||
'GatewayAdmin.targets': ['GET', '/api/internal/admin/targets'],
|
||||
'GatewayAdmin.updateTarget': ['PUT', '/api/internal/admin/targets/{id}'],
|
||||
'GatewayAdmin.apps': ['GET', '/api/internal/admin/apps'],
|
||||
'GatewayAdmin.createApp': ['POST', '/api/internal/admin/apps'],
|
||||
'GatewayAdmin.updateApp': ['PUT', '/api/internal/admin/apps/{id}'],
|
||||
'GatewayAdmin.logs': ['GET', '/api/internal/admin/logs'],
|
||||
'GatewayAdmin.refresh': ['POST', '/api/internal/routes/refresh'],
|
||||
'GatewayAdmin.proxyTest': ['POST', '/api/internal/admin/proxy-test'],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
|
||||
<path fill="#4aaff0" d="M512,585 C415,455 330,398 215,395 C185,395 160,415 160,450 L160,770 C160,815 190,838 240,845 C340,856 430,872 512,888 C594,872 684,856 784,845 C834,838 864,815 864,770 L864,450 C864,415 839,395 809,395 C694,398 609,455 512,585 Z"/>
|
||||
<path fill="#4aaff0" d="M218,312 C335,292 462,352 514,462 C452,404 334,354 218,378 Z"/>
|
||||
<circle fill="#4aaff0" cx="218" cy="345" r="33"/>
|
||||
<path fill="#80d976" d="M508,462 C455,310 525,145 700,105 C758,250 668,425 508,462 Z"/>
|
||||
<path fill="none" stroke="#4aaff0" stroke-width="44" stroke-linecap="round" d="M210,935 Q285.5,881 361,935 T512,935 T663,935 T814,935"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 701 B |
@@ -0,0 +1,555 @@
|
||||
/**
|
||||
* 网关治理管理面本地 Mock(vite --mode mock 专用,由 vite.config.ts 的 configureServer
|
||||
* 中间件在 dev server 内拦截 /open-gateway/api/internal/**,零依赖、零新插件)。
|
||||
*
|
||||
* 背景:本机无内网 VPN 时 base 域不可达,三页治理台账全空。本文件按后端
|
||||
* InternalAdminController / RouteRefreshController 的真实响应契约提供内存数据,
|
||||
* 仅供前端离线演示/走查,字段结构与信封与线上后端保持一致:
|
||||
* - 统一信封 {code:0, msg:"", data:X};业务非法一律 HTTP 200 + {code:2, msg:"…"};
|
||||
* - 分页 data 形状 {total, content, pageIndex, pageSize, totalPages, hasNext};
|
||||
* - PUT routes 只认 7 个治理键;enabled 必须真布尔(字符串 "true" 一律按 false 落库,
|
||||
* 照抄后端真实坑);两个 int 字段须 Number 且 ≥0;
|
||||
* - 后端没有的接口不 mock(登录/CAS、caller CRUD、统计、路由/目标增删均不存在)。
|
||||
*
|
||||
* 数据形态:静态种子 + 内存态——PUT 后再 GET 可见新值;整页刷新(HTML 文档请求)
|
||||
* 由中间件调 resetGatewayMockState() 重置回种子;SPA 站内切换不重置。
|
||||
*/
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { createHmac } from "node:crypto";
|
||||
|
||||
/* ============================ 类型(对齐后端 OpenApi DTO) ============================ */
|
||||
|
||||
type Visibility = "INTERNAL" | "EXTERNAL";
|
||||
type AuthMode = "SIGNED" | "ANON";
|
||||
type CacheScope = "CALLER" | "GLOBAL";
|
||||
|
||||
export interface OpenApiRoute {
|
||||
id: number;
|
||||
targetCode: string;
|
||||
pathPattern: string;
|
||||
httpMethod: string;
|
||||
visibility: Visibility;
|
||||
authMode: AuthMode;
|
||||
cacheTtlSeconds: number;
|
||||
cacheScope: CacheScope;
|
||||
rateLimitQps: number;
|
||||
timeoutMs: number;
|
||||
requestBodyLimitMb: number;
|
||||
enabled: boolean;
|
||||
remark: string;
|
||||
gmtCreate: string;
|
||||
gmtModified: string;
|
||||
}
|
||||
|
||||
export interface OpenApiTarget {
|
||||
id: number;
|
||||
targetCode: string;
|
||||
baseUrl: string;
|
||||
enabled: boolean;
|
||||
gmtCreate: string;
|
||||
gmtModified: string;
|
||||
}
|
||||
|
||||
export interface OpenApiLog {
|
||||
id: number;
|
||||
ts: string;
|
||||
callerAppKey: string | null;
|
||||
targetCode: string;
|
||||
method: string;
|
||||
path: string;
|
||||
status: number;
|
||||
backendCode: null;
|
||||
costMs: number;
|
||||
}
|
||||
|
||||
interface PageResult<T> {
|
||||
total: number;
|
||||
content: T[];
|
||||
pageIndex: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
hasNext: boolean;
|
||||
}
|
||||
|
||||
/* ============================ 静态种子 ============================ */
|
||||
|
||||
const GMT_BASE = "2026-09-12T02:00:00.000Z";
|
||||
const GMT_TUNE = "2026-09-26T06:30:00.000Z";
|
||||
|
||||
/** 7 个生产 ctx(照 service/docs/sql/03_target.sql 语义:容器网内直连 base-url) */
|
||||
const SEED_TARGETS: OpenApiTarget[] = [
|
||||
{ id: 1, targetCode: "userbase", baseUrl: "http://userbase-service:8080", enabled: true, gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 2, targetCode: "userclass", baseUrl: "http://userclass-service:8080", enabled: true, gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 3, targetCode: "yschcms", baseUrl: "http://yschcms-service:8080", enabled: true, gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 4, targetCode: "svc-hall", baseUrl: "http://svc-hall-service:8080", enabled: true, gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 5, targetCode: "flow-center", baseUrl: "http://flow-center-service:8080", enabled: true, gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 6, targetCode: "usermsg", baseUrl: "http://usermsg-service:8080", enabled: true, gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 7, targetCode: "notice", baseUrl: "http://notice-service:8080", enabled: true, gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
];
|
||||
|
||||
/**
|
||||
* 路由种子:service/docs/sql/02_init_routes.sql 的 22 行全保守种子(INTERNAL×SIGNED)打底,
|
||||
* 另补 6 行治理后的样本:EXTERNAL×ANON 豁免 ×3、EXTERNAL×SIGNED ×1、INTERNAL×ANON ×1、
|
||||
* 停用行 ×1、空备注 ×1,覆盖全部枚举组合与差异化 cacheTtl/qps/remark。
|
||||
*/
|
||||
const SEED_ROUTES: OpenApiRoute[] = [
|
||||
// ---- 02_init_routes.sql 种子(22 行,remark 原样照抄)----
|
||||
{ id: 1, targetCode: "userbase", pathPattern: "/oapi/app/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "应用信息:byId/list", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 2, targetCode: "userbase", pathPattern: "/oapi/group/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "组织:tree/byId/list/users/add/edit/delete/batchAdd/move", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 3, targetCode: "userbase", pathPattern: "/oapi/identity/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "身份:current/available/switch", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 4, targetCode: "userbase", pathPattern: "/oapi/user/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "用户:byId/byLoginName/byPhone/modules/add/edit/delete/batchAdd 等 21 端点", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 5, targetCode: "userclass", pathPattern: "/oapi/DbClass/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "OA 兼容:班级", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 6, targetCode: "userclass", pathPattern: "/oapi/Common/FamCom/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "OA 兼容:家属", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 7, targetCode: "userclass", pathPattern: "/oapi/SchGroup/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "OA 兼容:学校组织", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 8, targetCode: "userclass", pathPattern: "/oapi/SchInfo/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "OA 兼容:学校信息", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 9, targetCode: "userclass", pathPattern: "/oapi/SubInfo/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "OA 兼容:学科", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 10, targetCode: "userclass", pathPattern: "/oapi/Schoolen/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "OA 兼容:学段", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 11, targetCode: "userclass", pathPattern: "/oapi/OAStu/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "OA 兼容:学生信息(21 端点)", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 12, targetCode: "userclass", pathPattern: "/oapi/TeachInfo/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "OA 兼容:任教信息", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 13, targetCode: "userclass", pathPattern: "/oapi/OATea/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "OA 兼容:教师信息", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 14, targetCode: "userclass", pathPattern: "/oapi/UserInfo/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "OA 兼容:用户信息", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 15, targetCode: "userclass", pathPattern: "/oapi/VSchClass/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "OA 兼容:虚拟班级(17 端点)", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 16, targetCode: "userclass", pathPattern: "/oapi/group/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "同步:组织(4 端点)", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 17, targetCode: "userclass", pathPattern: "/oapi/user/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "同步:用户(5 端点)", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 18, targetCode: "yschcms", pathPattern: "/oapi/site/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "门户(注册名 yschcms)", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 19, targetCode: "svc-hall", pathPattern: "/oapi/svc/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "事项:items/filters/detail/view/attachments/related/snapshot", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 20, targetCode: "flow-center", pathPattern: "/oapi/flow/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "流程:list/getFlow/apply/instance/progress/diagram/withdraw/callback-reg", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 21, targetCode: "usermsg", pathPattern: "/oapi/msg/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "消息:sendUserMsg/list/unreadCount/read/readAll + todo(inc/reset/list) + ws/ticket", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
{ id: 22, targetCode: "notice", pathPattern: "/oapi/notice/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "字典:getDict", gmtCreate: GMT_BASE, gmtModified: GMT_BASE },
|
||||
// ---- 治理后补充样本(豁免/差异化旋钮/停用/空备注)----
|
||||
{ id: 23, targetCode: "yschcms", pathPattern: "/oapi/site/render/**", httpMethod: "*", visibility: "EXTERNAL", authMode: "ANON", cacheTtlSeconds: 600, cacheScope: "GLOBAL", rateLimitQps: 50, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "门户站点渲染对外只读:豁免签名 + 全局缓存 10 分钟", gmtCreate: GMT_BASE, gmtModified: GMT_TUNE },
|
||||
{ id: 24, targetCode: "svc-hall", pathPattern: "/oapi/svc/items/**", httpMethod: "*", visibility: "EXTERNAL", authMode: "ANON", cacheTtlSeconds: 60, cacheScope: "CALLER", rateLimitQps: 20, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "办事大厅事项对外查询:豁免签名,按调用方隔离缓存", gmtCreate: GMT_BASE, gmtModified: GMT_TUNE },
|
||||
{ id: 25, targetCode: "notice", pathPattern: "/oapi/notice/public/**", httpMethod: "*", visibility: "EXTERNAL", authMode: "ANON", cacheTtlSeconds: 300, cacheScope: "GLOBAL", rateLimitQps: 100, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "通知公告对外只读镜像(旧门户拉取)", gmtCreate: GMT_BASE, gmtModified: GMT_TUNE },
|
||||
{ id: 26, targetCode: "userbase", pathPattern: "/oapi/user/batchAdd", httpMethod: "*", visibility: "EXTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 5, timeoutMs: 30000, requestBodyLimitMb: 10, enabled: true, remark: "批量建号对外(密钥强校验,低 qps 熔断)", gmtCreate: GMT_BASE, gmtModified: GMT_TUNE },
|
||||
{ id: 27, targetCode: "usermsg", pathPattern: "/oapi/msg/health", httpMethod: "*", visibility: "INTERNAL", authMode: "ANON", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 10000, requestBodyLimitMb: 1, enabled: true, remark: "", gmtCreate: GMT_BASE, gmtModified: GMT_TUNE },
|
||||
{ id: 28, targetCode: "flow-center", pathPattern: "/oapi/flow/diagram/**", httpMethod: "*", visibility: "INTERNAL", authMode: "SIGNED", cacheTtlSeconds: 0, cacheScope: "CALLER", rateLimitQps: 0, timeoutMs: 60000, requestBodyLimitMb: 10, enabled: false, remark: "流程图渲染内测:暂关", gmtCreate: GMT_BASE, gmtModified: GMT_TUNE },
|
||||
];
|
||||
|
||||
/** 实测调用方 appKey(用于台账 callerAppKey 样本与筛选演示) */
|
||||
const APP_KEYS = ["100001", "100007", "100009", "100010", "100013"] as const;
|
||||
|
||||
/** 台账时间跨度:以种子重置时刻为终点,向过去铺 6.5 天 */
|
||||
const LOG_SPAN_DAYS = 6.5;
|
||||
const LOG_COUNT = 233;
|
||||
|
||||
/** 确定性伪随机(LCG):同一次进程内种子稳定,刷新/重启后日志可复现同分布 */
|
||||
function lcg(seed: number): () => number {
|
||||
let s = seed >>> 0;
|
||||
return () => {
|
||||
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
|
||||
return s / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
/** 台账种子:按路由表推导 path 形态;覆盖 200/401/403/404/500、anonymous、无钥(null) 401、快慢耗时 */
|
||||
function buildSeedLogs(routes: OpenApiRoute[], now: number): OpenApiLog[] {
|
||||
const rnd = lcg(20261001);
|
||||
const byTarget = new Map<string, { path: string; anon: boolean }[]>();
|
||||
for (const r of routes) {
|
||||
const arr = byTarget.get(r.targetCode) ?? [];
|
||||
arr.push({ path: r.pathPattern, anon: r.authMode === "ANON" });
|
||||
byTarget.set(r.targetCode, arr);
|
||||
}
|
||||
const targetCodes = [...byTarget.keys()];
|
||||
const weight: Record<string, number> = {
|
||||
userbase: 0.22, userclass: 0.14, yschcms: 0.06, "svc-hall": 0.14,
|
||||
"flow-center": 0.12, usermsg: 0.14, notice: 0.18,
|
||||
};
|
||||
const pick = <T,>(arr: readonly T[]): T => arr[Math.floor(rnd() * arr.length)];
|
||||
const pickTarget = (): string => {
|
||||
let r = rnd();
|
||||
for (const t of targetCodes) {
|
||||
r -= weight[t] ?? 0;
|
||||
if (r < 0) return t;
|
||||
}
|
||||
return targetCodes[targetCodes.length - 1];
|
||||
};
|
||||
|
||||
const logs: OpenApiLog[] = [];
|
||||
for (let i = 0; i < LOG_COUNT; i++) {
|
||||
const ts = now - i * ((LOG_SPAN_DAYS * 24 * 3600 * 1000) / LOG_COUNT) - rnd() * 3600 * 1000;
|
||||
const targetCode = pickTarget();
|
||||
const rt = pick(byTarget.get(targetCode) as { path: string; anon: boolean }[]);
|
||||
let path = rt.path;
|
||||
if (rnd() < 0.45 && path.endsWith("/**")) {
|
||||
path = path.slice(0, -3) + "/" + String(Math.floor(rnd() * 900) + 100);
|
||||
}
|
||||
const method = rnd() < 0.7 ? "GET" : "POST";
|
||||
|
||||
let callerAppKey: string | null;
|
||||
let status: number;
|
||||
const cr = rnd();
|
||||
if (cr < 0.6) {
|
||||
// 持钥调用:多数放行,少量鉴权/限流/NotFound/后端炸
|
||||
callerAppKey = pick(APP_KEYS);
|
||||
const sr = rnd();
|
||||
status = sr < 0.78 ? 200 : sr < 0.84 ? 401 : sr < 0.9 ? 403 : sr < 0.95 ? 404 : 500;
|
||||
} else if (cr < 0.8) {
|
||||
// 匿名调用(后端记字符串 "anonymous"):命中豁免(ANON)路由才放行
|
||||
callerAppKey = "anonymous";
|
||||
const sr = rnd();
|
||||
status = rt.anon ? (sr < 0.85 ? 200 : 500) : sr < 0.7 ? 401 : 403;
|
||||
} else {
|
||||
// 未携带 appKey:网关层直接拒(callerAppKey=null 的 401 行)
|
||||
callerAppKey = null;
|
||||
status = rnd() < 0.85 ? 401 : 403;
|
||||
}
|
||||
const costMs = status < 400 ? Math.floor(3 + Math.pow(rnd(), 2) * 1600) : Math.floor(1 + rnd() * 25);
|
||||
logs.push({
|
||||
id: 50000 + (LOG_COUNT - i),
|
||||
ts: new Date(ts).toISOString(),
|
||||
callerAppKey,
|
||||
targetCode,
|
||||
method,
|
||||
path,
|
||||
status,
|
||||
backendCode: null,
|
||||
costMs,
|
||||
});
|
||||
}
|
||||
return logs;
|
||||
}
|
||||
|
||||
/* ============================ 内存态(PUT 可变,刷新重置) ============================ */
|
||||
|
||||
let routes: OpenApiRoute[] = [];
|
||||
let targets: OpenApiTarget[] = [];
|
||||
let logs: OpenApiLog[] = [];
|
||||
|
||||
/** 重置为静态种子(vite 中间件在整页文档请求时调用 → 浏览器刷新即还原) */
|
||||
export function resetGatewayMockState(): void {
|
||||
routes = SEED_ROUTES.map((r) => ({ ...r }));
|
||||
targets = SEED_TARGETS.map((t) => ({ ...t }));
|
||||
logs = buildSeedLogs(SEED_ROUTES, Date.now());
|
||||
}
|
||||
resetGatewayMockState();
|
||||
|
||||
/* ============================ 工具 ============================ */
|
||||
|
||||
function ok<T>(data: T): { code: number; msg: string; data: T } {
|
||||
return { code: 0, msg: "", data };
|
||||
}
|
||||
|
||||
function bizError(msg: string): { code: number; msg: string; data: null } {
|
||||
return { code: 2, msg, data: null };
|
||||
}
|
||||
|
||||
function paginate<T>(list: T[], pageIndex: number, pageSize: number): PageResult<T> {
|
||||
const total = list.length;
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||
return {
|
||||
total,
|
||||
content: list.slice((pageIndex - 1) * pageSize, pageIndex * pageSize),
|
||||
pageIndex,
|
||||
pageSize,
|
||||
totalPages,
|
||||
hasNext: pageIndex < totalPages,
|
||||
};
|
||||
}
|
||||
|
||||
/** 查询参数取正整数:缺省/非法回落 def,上限 cap(logs pageSize 契约:默认 50、上限 500) */
|
||||
function positiveInt(raw: string | null, def: number, cap: number): number {
|
||||
const n = Number(raw);
|
||||
if (!Number.isInteger(n) || n < 1) return def;
|
||||
return Math.min(n, cap);
|
||||
}
|
||||
|
||||
function enumErrMsg(field: string, val: unknown, legal: readonly string[]): string {
|
||||
return `${field} 非法:${val === undefined ? "(缺失)" : String(val)}(合法 [${legal.join(", ")}])`;
|
||||
}
|
||||
|
||||
function intErrMsg(field: string, val: unknown): string {
|
||||
return `${field} 非法:${val === undefined ? "(缺失)" : String(val)}(须为 ≥0 的整数)`;
|
||||
}
|
||||
|
||||
function readBody(req: IncomingMessage): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
req.on("data", (c: Buffer) => chunks.push(c));
|
||||
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
||||
req.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function send(res: ServerResponse, payload: unknown): void {
|
||||
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
||||
res.end(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
/* ============================ 各端点实现 ============================ */
|
||||
|
||||
function listRoutes(q: URLSearchParams): PageResult<OpenApiRoute> {
|
||||
const sorted = [...routes].sort(
|
||||
(a, b) => a.targetCode.localeCompare(b.targetCode) || a.pathPattern.localeCompare(b.pathPattern)
|
||||
);
|
||||
return paginate(sorted, positiveInt(q.get("pageIndex"), 1, 10000), positiveInt(q.get("pageSize"), 10, 500));
|
||||
}
|
||||
|
||||
function listTargets(q: URLSearchParams): PageResult<OpenApiTarget> {
|
||||
const sorted = [...targets].sort((a, b) => a.targetCode.localeCompare(b.targetCode));
|
||||
return paginate(sorted, positiveInt(q.get("pageIndex"), 1, 10000), positiveInt(q.get("pageSize"), 10, 500));
|
||||
}
|
||||
|
||||
function listLogs(q: URLSearchParams): PageResult<OpenApiLog> {
|
||||
const targetCode = (q.get("targetCode") ?? "").trim();
|
||||
const callerAppKey = (q.get("callerAppKey") ?? "").trim();
|
||||
// 筛选为精确等值(空串=不过滤),先过滤再分页,按 id 倒序(最新在前)
|
||||
let rows = logs;
|
||||
if (targetCode) rows = rows.filter((l) => l.targetCode === targetCode);
|
||||
if (callerAppKey) rows = rows.filter((l) => l.callerAppKey === callerAppKey);
|
||||
rows = [...rows].sort((a, b) => b.id - a.id);
|
||||
return paginate(rows, positiveInt(q.get("pageIndex"), 1, 100000), positiveInt(q.get("pageSize"), 50, 500));
|
||||
}
|
||||
|
||||
const VISIBILITIES = ["EXTERNAL", "INTERNAL"] as const;
|
||||
const AUTH_MODES = ["SIGNED", "ANON"] as const;
|
||||
const CACHE_SCOPES = ["CALLER", "GLOBAL"] as const;
|
||||
|
||||
/** PUT /routes/{id}:只认 7 个治理键;校验语义对齐后端(含 enabled 非真布尔按 false 落库的坑) */
|
||||
function updateRoute(id: number, body: any): { code: number; msg: string; data: any } {
|
||||
const row = routes.find((r) => r.id === id);
|
||||
if (!row) return bizError(`路由不存在:id=${id}`);
|
||||
|
||||
if (!VISIBILITIES.includes(body?.visibility)) return bizError(enumErrMsg("visibility", body?.visibility, VISIBILITIES));
|
||||
if (!AUTH_MODES.includes(body?.authMode)) return bizError(enumErrMsg("authMode", body?.authMode, AUTH_MODES));
|
||||
if (!CACHE_SCOPES.includes(body?.cacheScope)) return bizError(enumErrMsg("cacheScope", body?.cacheScope, CACHE_SCOPES));
|
||||
const ttl = body?.cacheTtlSeconds;
|
||||
if (typeof ttl !== "number" || !Number.isInteger(ttl) || ttl < 0) return bizError(intErrMsg("cacheTtlSeconds", ttl));
|
||||
const qps = body?.rateLimitQps;
|
||||
if (typeof qps !== "number" || !Number.isInteger(qps) || qps < 0) return bizError(intErrMsg("rateLimitQps", qps));
|
||||
|
||||
row.visibility = body.visibility;
|
||||
row.authMode = body.authMode;
|
||||
row.cacheScope = body.cacheScope;
|
||||
row.cacheTtlSeconds = ttl;
|
||||
row.rateLimitQps = qps;
|
||||
// enabled 必须真布尔:传字符串 "true" 一律按 false 处理(后端真实行为,勿修)
|
||||
row.enabled = body.enabled === true;
|
||||
row.remark = body.remark == null ? "" : String(body.remark);
|
||||
row.gmtModified = new Date().toISOString();
|
||||
return ok({ loaded: routes.length });
|
||||
}
|
||||
|
||||
/** PUT /targets/{id}:baseUrl 非空 + enabled 真布尔(同款坑) */
|
||||
function updateTarget(id: number, body: any): { code: number; msg: string; data: any } {
|
||||
const row = targets.find((t) => t.id === id);
|
||||
if (!row) return bizError(`目标不存在:id=${id}`);
|
||||
|
||||
const baseUrl = body?.baseUrl;
|
||||
if (typeof baseUrl !== "string" || baseUrl.trim() === "") {
|
||||
return bizError(`baseUrl 非法:${baseUrl === undefined ? "(缺失)" : String(baseUrl)}(须为非空 url)`);
|
||||
}
|
||||
row.baseUrl = baseUrl.trim();
|
||||
row.enabled = body.enabled === true;
|
||||
row.gmtModified = new Date().toISOString();
|
||||
return ok({ targets: targets.length });
|
||||
}
|
||||
|
||||
/* ============================ 代理测试(服务端签名回环的真实语义 mock) ============================ */
|
||||
|
||||
const MOCK_PROXY_SECRET = "mock-secret-0123456789";
|
||||
|
||||
/** 复刻后端 SignVerifyFilter.sortRawQuery:逐对解码、k=v 字典序、& 连接 */
|
||||
function sortRawQuery(rawQuery: string | null): string {
|
||||
if (!rawQuery) return "";
|
||||
const pairs: string[] = [];
|
||||
for (const part of rawQuery.split("&")) {
|
||||
if (!part) continue;
|
||||
const idx = part.indexOf("=");
|
||||
const k = idx < 0 ? part : part.substring(0, idx);
|
||||
const v = idx < 0 ? "" : part.substring(idx + 1);
|
||||
pairs.push(urlDecode(k) + "=" + urlDecode(v));
|
||||
}
|
||||
pairs.sort();
|
||||
return pairs.join("&");
|
||||
}
|
||||
|
||||
/** 复刻后端 URLDecoder.decode(UTF-8):+ 号解为空格;非法 %xx 转义回退原串 */
|
||||
function urlDecode(s: string): string {
|
||||
try {
|
||||
return decodeURIComponent(s.replace(/\+/g, "%20"));
|
||||
} catch {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理测试 mock:错误文案与后端 ProxyTestController 逐字一致,data 形状与真实响应同构。
|
||||
* 校验顺序照后端真实链路:url/appKey → 容忍解析 → 密钥解析(fail-closed)→ 签名 → 路由命中。
|
||||
*/
|
||||
function mockProxyTest(body: any): { code: number; msg: string; data: any } {
|
||||
const method = String(body?.method ?? "GET").trim().toUpperCase() || "GET";
|
||||
const url = typeof body?.url === "string" ? body.url.trim() : "";
|
||||
const appKey = typeof body?.appKey === "string" ? body.appKey.trim() : "";
|
||||
const appSecret = typeof body?.appSecret === "string" ? body.appSecret.trim() : "";
|
||||
if (!url) return bizError("url 不可为空(形如 http://网关域名/{target}/oapi/**)");
|
||||
if (!appKey) return bizError("appKey 不可为空");
|
||||
|
||||
// 容忍解析:剥 scheme,取 path+query(回环只打网关自身,scheme/host 无意义)
|
||||
let pathAndQuery: string;
|
||||
const schemeEnd = url.indexOf("://");
|
||||
if (schemeEnd >= 0) {
|
||||
const pathStart = url.indexOf("/", schemeEnd + 3);
|
||||
if (pathStart < 0) return bizError(`URL 缺少路径(形如 http://host/{target}/oapi/**):${url}`);
|
||||
pathAndQuery = url.substring(pathStart);
|
||||
} else if (url.startsWith("/")) {
|
||||
pathAndQuery = url;
|
||||
} else {
|
||||
pathAndQuery = "/" + url;
|
||||
}
|
||||
const qIdx = pathAndQuery.indexOf("?");
|
||||
const path = qIdx < 0 ? pathAndQuery : pathAndQuery.substring(0, qIdx);
|
||||
const query = qIdx < 0 ? null : pathAndQuery.substring(qIdx + 1);
|
||||
if (!path || path === "/") {
|
||||
return bizError("路径须形如 /{target}/oapi/**(如 /userbase/oapi/user/byId)");
|
||||
}
|
||||
const second = path.indexOf("/", 1);
|
||||
if (second < 0) {
|
||||
return bizError(`路径第二段必须为 oapi(如 /userbase/oapi/user/byId),当前:${path}`);
|
||||
}
|
||||
const target = path.substring(1, second);
|
||||
const rest = path.substring(second);
|
||||
if (!target || target.includes("..")) {
|
||||
return bizError(`target 非法:${target}`);
|
||||
}
|
||||
if (rest !== "/oapi" && !rest.startsWith("/oapi/")) {
|
||||
return bizError(`路径第二段必须为 oapi(如 /userbase/oapi/user/byId),当前:${path}`);
|
||||
}
|
||||
const stripped = rest;
|
||||
|
||||
// 密钥解析(回环前,fail-closed——顺序与后端一致)
|
||||
let secret: string;
|
||||
let secretSource: "INPUT" | "REDIS";
|
||||
if (appSecret) {
|
||||
secret = appSecret;
|
||||
secretSource = "INPUT";
|
||||
} else if ((APP_KEYS as readonly string[]).includes(appKey)) {
|
||||
secret = MOCK_PROXY_SECRET;
|
||||
secretSource = "REDIS";
|
||||
} else {
|
||||
return bizError("appSecret 未填且网关解析不到该 appKey 的密钥(未注册/已禁用/密钥链不可用)");
|
||||
}
|
||||
if (secret.length < 16) {
|
||||
return bizError("签名失败:签名密钥长度不能小于16位");
|
||||
}
|
||||
|
||||
// 签名(复刻 SignUtil.signRequest + buildCanonicalTarget:HMAC-SHA256 → base64)
|
||||
const sorted = sortRawQuery(query);
|
||||
const canonical = sorted ? `${stripped}?${sorted}` : stripped;
|
||||
const timestamp = String(Date.now());
|
||||
const signature = createHmac("sha256", secret).update(`${method}\n${canonical}\n${timestamp}`).digest("base64");
|
||||
|
||||
// 路由命中:targetCode 相等 + pathPattern(剥 /** 后)等于 stripped 或为其路径前缀
|
||||
const hit = routes.find((r) => {
|
||||
if (r.targetCode !== target) return false;
|
||||
const prefix = r.pathPattern.replace(/\/\*\*$/, "");
|
||||
return stripped === prefix || stripped.startsWith(prefix + "/");
|
||||
});
|
||||
|
||||
const base = {
|
||||
target,
|
||||
method,
|
||||
requestUrl: "http://mock-gateway" + pathAndQuery,
|
||||
latencyMs: 20 + Math.floor(Math.random() * 281),
|
||||
bodyTruncated: false,
|
||||
signature: { appKey, timestamp, canonical, signature, secretSource },
|
||||
error: null,
|
||||
};
|
||||
if (!hit) {
|
||||
// 模拟网关裸 404
|
||||
return ok({ ...base, status: 404, contentType: null, body: "" });
|
||||
}
|
||||
const echoBody = JSON.stringify({
|
||||
code: 0,
|
||||
msg: "mock 应答",
|
||||
data: {
|
||||
mock: true,
|
||||
route: { pathPattern: hit.pathPattern, visibility: hit.visibility, authMode: hit.authMode },
|
||||
echo: { method, url },
|
||||
},
|
||||
});
|
||||
return ok({ ...base, status: 200, contentType: "application/json", body: echoBody });
|
||||
}
|
||||
|
||||
/* ============================ 中间件入口(vite dev server 内) ============================ */
|
||||
|
||||
/**
|
||||
* 拦截带 serviceHost 前缀(/open-gateway)的治理面请求。命中并应答返回 true,
|
||||
* 未命中返回 false(交回 vite 内部中间件/代理,非 mock 模式根本不会注册本处理)。
|
||||
*/
|
||||
export async function handleGatewayMockRequest(req: IncomingMessage, res: ServerResponse): Promise<boolean> {
|
||||
const url = new URL(req.url ?? "/", "http://mock.local");
|
||||
const pathname = url.pathname;
|
||||
if (!pathname.startsWith("/open-gateway/api/")) return false;
|
||||
|
||||
const api = pathname.slice("/open-gateway".length);
|
||||
const method = (req.method ?? "GET").toUpperCase();
|
||||
const q = url.searchParams;
|
||||
|
||||
if (api === "/api/internal/admin/routes" && method === "GET") {
|
||||
send(res, ok(listRoutes(q)));
|
||||
return true;
|
||||
}
|
||||
if (api === "/api/internal/admin/targets" && method === "GET") {
|
||||
send(res, ok(listTargets(q)));
|
||||
return true;
|
||||
}
|
||||
if (api === "/api/internal/admin/logs" && method === "GET") {
|
||||
send(res, ok(listLogs(q)));
|
||||
return true;
|
||||
}
|
||||
if (api === "/api/internal/routes/refresh" && method === "POST") {
|
||||
send(res, ok({ loaded: routes.length, targets: targets.length }));
|
||||
return true;
|
||||
}
|
||||
if (api === "/api/internal/admin/proxy-test" && method === "POST") {
|
||||
const body = await readJsonBody(req);
|
||||
if (body === undefined) {
|
||||
send(res, bizError("请求体不是合法 JSON"));
|
||||
return true;
|
||||
}
|
||||
send(res, mockProxyTest(body));
|
||||
return true;
|
||||
}
|
||||
|
||||
let m = /^\/api\/internal\/admin\/routes\/(\d+)$/.exec(api);
|
||||
if (m) {
|
||||
if (method !== "PUT") {
|
||||
send(res, bizError(`不支持的请求:${method} ${api}`));
|
||||
return true;
|
||||
}
|
||||
const body = await readJsonBody(req);
|
||||
if (body === undefined) {
|
||||
send(res, bizError("请求体不是合法 JSON"));
|
||||
return true;
|
||||
}
|
||||
send(res, updateRoute(Number(m[1]), body));
|
||||
return true;
|
||||
}
|
||||
m = /^\/api\/internal\/admin\/targets\/(\d+)$/.exec(api);
|
||||
if (m) {
|
||||
if (method !== "PUT") {
|
||||
send(res, bizError(`不支持的请求:${method} ${api}`));
|
||||
return true;
|
||||
}
|
||||
const body = await readJsonBody(req);
|
||||
if (body === undefined) {
|
||||
send(res, bizError("请求体不是合法 JSON"));
|
||||
return true;
|
||||
}
|
||||
send(res, updateTarget(Number(m[1]), body));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 读 PUT 的 JSON 请求体;空体按 {},解析失败返回 undefined(由调用方回业务错) */
|
||||
async function readJsonBody(req: IncomingMessage): Promise<any | undefined> {
|
||||
const raw = await readBody(req);
|
||||
if (!raw.trim()) return {};
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,274 @@
|
||||
<script setup lang="ts">
|
||||
/* 管理端配色切换器(yh-theme 定稿 07-seam-pure 顶栏「配色」胶囊,方案 §6.5)。
|
||||
* 状态唯一来源:utils/theme(localStorage 持久化 + <html> 档位类名),与门户皮肤包正交。 */
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import {
|
||||
loadThemeState,
|
||||
saveThemeState,
|
||||
applyThemeState,
|
||||
type ThemeName,
|
||||
type ThemeState,
|
||||
} from "@/utils/theme";
|
||||
|
||||
const THEME_META: { name: ThemeName; label: string; color: string }[] = [
|
||||
{ name: "blue", label: "原版靛蓝", color: "#577afb" },
|
||||
{ name: "ocean", label: "云海蓝", color: "#2f7ce0" },
|
||||
{ name: "ink", label: "石墨墨", color: "#3d4d63" },
|
||||
{ name: "violet", label: "靛紫", color: "#6d5ae0" },
|
||||
{ name: "teal", label: "松石绿", color: "#0d9488" },
|
||||
];
|
||||
|
||||
const wrapEl = ref<HTMLElement | null>(null);
|
||||
const open = ref(false);
|
||||
const state = ref<ThemeState>(loadThemeState());
|
||||
/* 挂载即把存储态落到 <html>(与 main.ts initTheme 同源幂等;组件晚于引导挂载时也自洽) */
|
||||
applyThemeState(state.value);
|
||||
|
||||
function commit(patch: Partial<ThemeState>) {
|
||||
state.value = { ...state.value, ...patch };
|
||||
applyThemeState(state.value);
|
||||
saveThemeState(state.value);
|
||||
}
|
||||
|
||||
function toggle(ev: MouseEvent) {
|
||||
ev.stopPropagation();
|
||||
open.value = !open.value;
|
||||
}
|
||||
|
||||
/** 切换器外任意点击即收起(弹层内部点击由 wrap 判定放过) */
|
||||
function onDocClick(ev: MouseEvent) {
|
||||
if (open.value && wrapEl.value && !wrapEl.value.contains(ev.target as Node)) {
|
||||
open.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => document.addEventListener("click", onDocClick, true));
|
||||
onBeforeUnmount(() => document.removeEventListener("click", onDocClick, true));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="wrapEl" class="theme-wrap">
|
||||
<button type="button" class="theme-btn" :class="{ on: open }" @click="toggle">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M12 3a9 9 0 1 0 0 18c1.2 0 1.9-.9 1.9-1.8 0-.6-.3-1-.5-1.4-.2-.4-.4-.8-.4-1.3 0-.9.8-1.7 1.8-1.7H17a4 4 0 0 0 4-4c0-4.3-4-7.8-9-7.8z"/>
|
||||
<circle cx="7.6" cy="11.2" r="1.1"/><circle cx="11" cy="7.6" r="1.1"/><circle cx="15.4" cy="8.6" r="1.1"/>
|
||||
</svg>
|
||||
<span>配色</span>
|
||||
<svg class="caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M5.5 9.5l6.5 6.5 6.5-6.5"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<div class="theme-pop" :class="{ open }">
|
||||
<p class="tp-head">主题色</p>
|
||||
<div class="tp-grid">
|
||||
<button
|
||||
v-for="t in THEME_META"
|
||||
:key="t.name"
|
||||
type="button"
|
||||
class="theme-opt"
|
||||
:class="{ active: state.theme === t.name }"
|
||||
@click="commit({ theme: t.name })"
|
||||
>
|
||||
<i :style="{ background: t.color }"></i>{{ t.label }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="tp-sep"></div>
|
||||
<p class="tp-head">侧栏样式</p>
|
||||
<label class="tp-row">
|
||||
<span>侧栏跟随顶栏色</span>
|
||||
<span class="sw">
|
||||
<input type="checkbox" :checked="state.sideFollow" @change="commit({ sideFollow: ($event.target as HTMLInputElement).checked })" />
|
||||
<i></i>
|
||||
</span>
|
||||
</label>
|
||||
<label class="tp-row" style="margin-top: 9px">
|
||||
<span>侧栏深色(关=浅色)</span>
|
||||
<span class="sw">
|
||||
<input type="checkbox" :checked="state.sideDeep" @change="commit({ sideDeep: ($event.target as HTMLInputElement).checked })" />
|
||||
<i></i>
|
||||
</span>
|
||||
</label>
|
||||
<div class="tp-sep"></div>
|
||||
<label class="tp-row">
|
||||
<span>顶部过渡色(渐变)</span>
|
||||
<span class="sw">
|
||||
<input type="checkbox" :checked="state.gradOn" @change="commit({ gradOn: ($event.target as HTMLInputElement).checked })" />
|
||||
<i></i>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 皮肤规格照搬定稿 07-seam-pure.html .theme-wrap/.theme-btn/.theme-pop 段 */
|
||||
.theme-wrap {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.theme-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 30px;
|
||||
padding: 0 11px;
|
||||
cursor: pointer;
|
||||
border: 1px solid rgba(255, 255, 255, 0.34);
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
color: #fff;
|
||||
font-size: 12.5px;
|
||||
transition: background 0.16s, border-color 0.16s;
|
||||
}
|
||||
.theme-btn:hover,
|
||||
.theme-btn.on {
|
||||
background: rgba(255, 255, 255, 0.26);
|
||||
border-color: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
.theme-btn svg {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
display: block;
|
||||
fill: none;
|
||||
stroke: currentColor;
|
||||
stroke-width: 1.7;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
.theme-btn svg circle {
|
||||
fill: currentColor;
|
||||
stroke: none;
|
||||
}
|
||||
.theme-btn .caret {
|
||||
width: 11px;
|
||||
height: 11px;
|
||||
opacity: 0.85;
|
||||
transition: transform 0.18s;
|
||||
}
|
||||
.theme-btn.on .caret {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
.theme-pop {
|
||||
position: absolute;
|
||||
top: calc(100% + 6px);
|
||||
right: 0;
|
||||
width: 224px;
|
||||
background: #fff;
|
||||
color: var(--text, #1e2635);
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--line, #e9edf5);
|
||||
padding: 12px;
|
||||
box-shadow: 0 12px 34px -10px rgba(16, 24, 40, 0.28), 0 2px 6px rgba(16, 24, 40, 0.08);
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transform: translateY(-6px);
|
||||
transition: 0.18s;
|
||||
z-index: 40;
|
||||
}
|
||||
.theme-pop.open {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transform: translateY(0);
|
||||
}
|
||||
.tp-head {
|
||||
font-size: 11.5px;
|
||||
color: var(--text-3, #98a1b2);
|
||||
letter-spacing: 0.5px;
|
||||
margin: 0 2px 8px;
|
||||
}
|
||||
.tp-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 6px;
|
||||
}
|
||||
.theme-opt {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
height: 32px;
|
||||
padding: 0 8px;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
border: 1px solid var(--line, #e9edf5);
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
color: var(--text-2, #5a6478);
|
||||
font-size: 12px;
|
||||
transition: 0.15s;
|
||||
font-family: inherit;
|
||||
}
|
||||
.theme-opt:hover {
|
||||
border-color: #cfd7e6;
|
||||
background: #fafbfe;
|
||||
}
|
||||
.theme-opt i {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
border-radius: 50%;
|
||||
flex: 0 0 auto;
|
||||
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
.theme-opt.active {
|
||||
border-color: var(--brand, #577afb);
|
||||
color: var(--brand, #577afb);
|
||||
background: var(--brand-soft, #eef2ff);
|
||||
font-weight: 600;
|
||||
}
|
||||
.tp-sep {
|
||||
height: 1px;
|
||||
background: var(--line, #e9edf5);
|
||||
margin: 12px 0 10px;
|
||||
}
|
||||
.tp-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 12.5px;
|
||||
color: var(--text-2, #5a6478);
|
||||
cursor: pointer;
|
||||
padding: 0 2px;
|
||||
}
|
||||
.sw {
|
||||
position: relative;
|
||||
width: 38px;
|
||||
height: 21px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.sw input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
opacity: 0;
|
||||
margin: 0;
|
||||
cursor: pointer;
|
||||
z-index: 1;
|
||||
}
|
||||
.sw i {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 999px;
|
||||
background: #d7dce6;
|
||||
transition: background 0.2s;
|
||||
pointer-events: none;
|
||||
}
|
||||
.sw i::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 2.5px;
|
||||
left: 2.5px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
box-shadow: 0 1px 3px rgba(16, 24, 40, 0.28);
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
.sw input:checked + i {
|
||||
background: var(--brand, #577afb);
|
||||
}
|
||||
.sw input:checked + i::after {
|
||||
transform: translateX(17px);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,102 @@
|
||||
<script lang="ts" setup>
|
||||
/* 默认头像三态组件(YschTheme 公共源,scripts/sync-apps.mjs 下发三端 src/components/UserAvatar.vue):
|
||||
头像 URL 非空 → <img>;否则 style==="text" 且能取到字 → 首字;否则 → 剪影(纯 CSS/SVG,零资源文件)。
|
||||
取值链/取字契约见《设置页修复与默认头像落地方案》§10.1/§10.2;样式全在本文件 <style scoped>(唯一 CSS 源,
|
||||
不进通道 icons.src.css——通道 CSS 对 UserHome 不可达,内联分发才能消双份漂移,见同方案 §10.4)。
|
||||
根元素即 .yh-avatar 圆:尺寸内联必须挂圆本身(挂外层 span 会被 flex 拉成椭圆,§12 踩坑)。 */
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { pickAvatarText, resolveAvatarStyle } from "@/utils/avatar";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** 头像 URL:非空直接 <img>(三态第一优先) */
|
||||
src?: string | null;
|
||||
/** 取字来源(首字态用):经 pickAvatarText 判定,取不到字回落剪影 */
|
||||
name?: string | null;
|
||||
/** 直径 px;font-size = round(size * 0.44) */
|
||||
size?: number;
|
||||
/** 配色场景:light=页面浅底(品牌实底+白内容);brand=header 品牌色底(剪影 S1 玻璃底 / 首字 S2 白底反色,§10.3 分档) */
|
||||
placement?: "light" | "brand";
|
||||
}>(),
|
||||
{ src: null, name: null, size: 28, placement: "light" },
|
||||
);
|
||||
|
||||
const text = computed(() => (props.src ? "" : pickAvatarText(props.name)));
|
||||
/* 外观偏好异步补齐(yh-theme-init 在挂载后拉服务端真源收敛 localStorage 键)会在
|
||||
document 上派发 yh-appearance-updated;tick 自增让 style 依赖失效重读键,三态即时切换(无需刷新)。 */
|
||||
const appearanceTick = ref(0);
|
||||
const onAppearanceUpdated = () => { appearanceTick.value += 1; };
|
||||
onMounted(() => document.addEventListener("yh-appearance-updated", onAppearanceUpdated));
|
||||
onBeforeUnmount(() => document.removeEventListener("yh-appearance-updated", onAppearanceUpdated));
|
||||
const style = computed(() => {
|
||||
appearanceTick.value;
|
||||
return resolveAvatarStyle();
|
||||
});
|
||||
/** 首字态 = style==="text" 且能取到字(契约 §10.2:二者缺一即剪影,取到字但档位是剪影时绝不能出字) */
|
||||
const showText = computed(() => style.value === "text" && !!text.value);
|
||||
|
||||
const rootClass = computed(() => [
|
||||
"yh-avatar",
|
||||
props.placement === "brand" ? "yh-avatar--brand" : "yh-avatar--light",
|
||||
{ "is-text": showText.value },
|
||||
]);
|
||||
|
||||
const rootStyle = computed(() => ({
|
||||
width: `${props.size}px`,
|
||||
height: `${props.size}px`,
|
||||
fontSize: `${Math.round(props.size * 0.44)}px`,
|
||||
}));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span :class="rootClass" :style="rootStyle">
|
||||
<img v-if="src" class="yh-avatar__img" :src="src" alt="" />
|
||||
<template v-else-if="showText">{{ text }}</template>
|
||||
<svg v-else class="yh-avatar__sil" viewBox="0 0 1024 1024" aria-hidden="true">
|
||||
<circle cx="512" cy="399" r="174" />
|
||||
<ellipse cx="512" cy="946" rx="420" ry="240" />
|
||||
</svg>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.yh-avatar {
|
||||
position: relative;
|
||||
border-radius: 50%;
|
||||
overflow: hidden;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
flex: 0 0 auto;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
user-select: none;
|
||||
}
|
||||
.yh-avatar__img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
/* 剪影 SVG:容器圆 overflow:hidden 裁切肩部溢出(禁用 clipPath);overflow:visible 放行 viewBox 外形状 */
|
||||
.yh-avatar__sil {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: visible;
|
||||
fill: currentColor;
|
||||
}
|
||||
/* 页面内(浅底)——品牌实底 + 白内容 */
|
||||
.yh-avatar--light {
|
||||
background: var(--brand, #577afb);
|
||||
color: #fff;
|
||||
}
|
||||
/* header(品牌色底)——与页面内反向:剪影档 = S1 半透明白,首字档 = S2 纯白底 + 品牌色字 */
|
||||
.yh-avatar--brand {
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
color: #fff;
|
||||
}
|
||||
.yh-avatar--brand.is-text {
|
||||
background: #fff;
|
||||
color: var(--brand, #577afb);
|
||||
}
|
||||
</style>
|
||||
+94
-32
@@ -3,6 +3,9 @@ import { computed, ref } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { LayoutData } from "@/types/Basics";
|
||||
import Utils from "@/utils";
|
||||
import config from "@/assets/config/host.config";
|
||||
import ThemeSwitcher from "@/components/ThemeSwitcher.vue";
|
||||
import UserAvatar from "@/components/UserAvatar.vue";
|
||||
|
||||
const props = defineProps<{ layoutData: LayoutData }>();
|
||||
const route = useRoute();
|
||||
@@ -10,6 +13,15 @@ const route = useRoute();
|
||||
const modList = computed(() => props.layoutData.modList || []);
|
||||
const isActive = (m: any) => route.path === m.page;
|
||||
|
||||
/** 面包屑末段:当前路由 meta.title(三个治理页都带) */
|
||||
const currTitle = computed(() => (route.meta as any)?.title || "");
|
||||
|
||||
/** mock 模式徽标:仅 --mode mock(VITE_IS_MOCK=true)时渲染,dev/线上恒不出现 */
|
||||
const isMock = computed(() => !!config.isMock);
|
||||
|
||||
/** 顶栏操作者占位(网关无用户体系;三态头像取首字「网」) */
|
||||
const opName = "网关治理";
|
||||
|
||||
/* 重载注册表(POST /api/internal/routes/refresh):网关热重载路由+目标快照,无须重启 */
|
||||
const reloading = ref(false);
|
||||
const lastReloadTime = ref("");
|
||||
@@ -18,7 +30,7 @@ async function reloadRegistry() {
|
||||
reloading.value = true;
|
||||
try {
|
||||
const d: any = await Apis.GatewayAdmin.refresh({});
|
||||
Message.success(`已重载:路由 ${d?.loaded ?? "-"} 条 / 目标 ${d?.targets ?? "-"} 条`);
|
||||
Message.success(`已重载:路由 ${d?.loaded ?? "-"} 条 / 目标 ${d?.targets ?? "-"} 条 / 应用 ${d?.apps ?? "-"} 条`);
|
||||
lastReloadTime.value = Utils.dateFormat(new Date(), "HH:mm:ss");
|
||||
} catch (e: any) {
|
||||
// 错误提示由 alova 全局 onBizError 弹出,这里不重复弹
|
||||
@@ -32,44 +44,94 @@ const reloadPage = inject("reload", () => {}) as () => void;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="header-container fix">
|
||||
<div class="icon-box fl">
|
||||
<h4 class="fl">{{ layoutData.appName }}</h4>
|
||||
</div>
|
||||
<div class="header-aside fr">
|
||||
<span v-if="lastReloadTime" class="last-reload fl">最后更新 {{ lastReloadTime }}</span>
|
||||
<Button size="small" class="fl reload-btn" @click="reloadPage">手动刷新</Button>
|
||||
<Button type="primary" size="small" class="fl reload-btn" :loading="reloading" @click="reloadRegistry">
|
||||
重载注册表
|
||||
</Button>
|
||||
<span class="name fr">网关治理</span>
|
||||
</div>
|
||||
</header>
|
||||
<div class="layout-wrap">
|
||||
<header class="header-container fix">
|
||||
<!-- 云海 logo 徽标(结构与 Notice 对齐,皮肤见通道 base.layout.css .logo-badge) -->
|
||||
<span class="logo-badge fl"><img src="@/assets/image/yunhai-logo.svg" alt="云海" /></span>
|
||||
<div class="delimiter fl align-middle"></div>
|
||||
<h4 class="fl align-middle">{{ layoutData.appName }}</h4>
|
||||
<div class="school-bg"></div>
|
||||
<div class="header-tools fr">
|
||||
<span v-if="isMock" class="mock-badge" title="当前为本地 mock 数据,重启 dev:mock 后还原">MOCK 数据</span>
|
||||
<span v-if="lastReloadTime" class="last-reload">最后更新 {{ lastReloadTime }}</span>
|
||||
<Button size="small" class="reload-btn" @click="reloadPage">手动刷新</Button>
|
||||
<Button type="primary" size="small" class="reload-btn" :loading="reloading" @click="reloadRegistry">
|
||||
重载注册表
|
||||
</Button>
|
||||
</div>
|
||||
<div class="header-aside fr">
|
||||
<UserAvatar class="fl align-middle" :name="opName" :size="28" placement="brand" />
|
||||
<a class="name fl align-middle text-ellipsis" href="javascript:void(0);">{{ opName }}</a>
|
||||
</div>
|
||||
<!-- 配色切换器(fr 顺序:DOM 后置即位于用户胶囊左侧) -->
|
||||
<div class="theme-cap fr"><ThemeSwitcher /></div>
|
||||
</header>
|
||||
|
||||
<ul class="left-menu">
|
||||
<li class="menu-top-box"></li>
|
||||
<li v-for="m in modList" :key="m.page" :class="{ active: isActive(m) }">
|
||||
<router-link :to="m.page">{{ m.title }}</router-link>
|
||||
</li>
|
||||
<li class="clear-box"></li>
|
||||
</ul>
|
||||
<div class="left-menu">
|
||||
<div class="menu-top-box"></div>
|
||||
<ul>
|
||||
<li v-for="m in modList" :key="m.page" :class="{ active: isActive(m) }">
|
||||
<router-link :to="m.page">{{ m.title }}</router-link>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="clear-box"></div>
|
||||
</div>
|
||||
|
||||
<div class="path-nav">
|
||||
<Breadcrumb separator=">">
|
||||
<BreadcrumbItem>
|
||||
<span class="crumb-home">
|
||||
<i class="iconfont icon-shouye"></i>
|
||||
首页
|
||||
</span>
|
||||
</BreadcrumbItem>
|
||||
<BreadcrumbItem>{{ layoutData.appName }}</BreadcrumbItem>
|
||||
<BreadcrumbItem v-if="currTitle">{{ currTitle }}</BreadcrumbItem>
|
||||
</Breadcrumb>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.header-container .header-aside .name {
|
||||
line-height: 56px;
|
||||
font-size: 14px;
|
||||
/* 仅覆盖/补充必要的动态样式,其余样式由中央静态通道的 base.layout.css(骨架 + 皮肤)提供 */
|
||||
.header-container .logo-badge {
|
||||
margin: 0 10px 0 0;
|
||||
}
|
||||
|
||||
.header-container .header-aside .reload-btn {
|
||||
.theme-cap {
|
||||
height: var(--topbar-h);
|
||||
margin-right: 6px;
|
||||
}
|
||||
/* 面包屑「首页」垂直居中:inline-flex 真居中并关掉骨架给老 iconfont 字体的基线补偿 */
|
||||
.crumb-home {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.crumb-home .iconfont {
|
||||
position: static;
|
||||
top: 0;
|
||||
}
|
||||
/* 顶栏操作区(重载按钮 + mock 徽标):皮肤把 header 改 flex 垂直居中,只留间距 */
|
||||
.header-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-right: 12px;
|
||||
margin-top: 13px;
|
||||
}
|
||||
|
||||
.header-container .header-aside .last-reload {
|
||||
line-height: 56px;
|
||||
.header-tools .reload-btn {
|
||||
margin: 0;
|
||||
}
|
||||
.header-tools .last-reload {
|
||||
font-size: 12px;
|
||||
color: #848c98;
|
||||
margin-right: 12px;
|
||||
color: rgba(255, 255, 255, 0.75);
|
||||
}
|
||||
.header-tools .mock-badge {
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
padding: 5px 10px;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 153, 0, 0.22);
|
||||
border: 1px solid rgba(255, 153, 0, 0.65);
|
||||
color: #ffd49a;
|
||||
}
|
||||
</style>
|
||||
|
||||
+3
-2
@@ -15,8 +15,9 @@ import ViewUIPlus from "view-ui-plus";
|
||||
import "view-ui-plus/dist/styles/viewuiplus.css";
|
||||
|
||||
import "@/assets/styles/main.scss";
|
||||
// 本地化的布局/主题样式(原远程 base.layout.beta / _iview_override / default-theme 合并)
|
||||
import "@/assets/styles/layout.css";
|
||||
// 布局/主题/图标(base.layout.css + iview.override.css + icons.css)由中央静态通道下发:
|
||||
// index.html 的 yh-theme-init.js 按 manifest 版本追加 <link>,天然排在本文件组件库样式之后
|
||||
//(本地 layout.css 快照已随之退役,删防双份漂移)
|
||||
|
||||
import "virtual:uno.css";
|
||||
import "virtual:svg-icons-register";
|
||||
|
||||
@@ -24,6 +24,18 @@ const routes: RouteRecordRaw[] = [
|
||||
component: () => import("@/views/target/TargetList.vue"),
|
||||
meta: { title: "目标地址" },
|
||||
},
|
||||
{
|
||||
path: "/apps",
|
||||
name: "AppList",
|
||||
component: () => import("@/views/app/AppList.vue"),
|
||||
meta: { title: "应用管理" },
|
||||
},
|
||||
{
|
||||
path: "/proxy-test",
|
||||
name: "ProxyTest",
|
||||
component: () => import("@/views/proxytest/ProxyTest.vue"),
|
||||
meta: { title: "代理测试" },
|
||||
},
|
||||
];
|
||||
|
||||
export default routes;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* 默认头像样式(首字 / 剪影)公共源(YschTheme,scripts/sync-apps.mjs 下发三端 src/utils/avatar.ts)。
|
||||
* 取值链与主题同构(theme-core.js resolveEffectiveThemeState 的合成链写法):
|
||||
* URL ?yh-avatar=text|silhouette(仅预览/排障覆盖:只影响读、绝不写回)
|
||||
* > localStorage["yh-avatar"](用户自选,纯字符串)
|
||||
* > localStorage["yh-avatar-sch-default"](学校默认,UserHome 登录后写入)
|
||||
* > "text"(系统默认)
|
||||
* 值域恒为 "text" | "silhouette",键缺失/值非法均静默回落下一级,不报错不阻塞渲染。
|
||||
* 渲染三态与取字规则的唯一契约见 UserHome《设置页修复与默认头像落地方案》§10.1/§10.2。
|
||||
*/
|
||||
|
||||
export type AvatarStyle = "text" | "silhouette";
|
||||
|
||||
interface StorageLike {
|
||||
getItem(k: string): string | null;
|
||||
setItem(k: string, v: string): void;
|
||||
removeItem(k: string): void;
|
||||
}
|
||||
|
||||
export const AVATAR_STORAGE_KEY = "yh-avatar";
|
||||
|
||||
/** 学校默认头像存储键(UserHome 登录时写入;值格式与用户键相同,仅无"用户自选"语义) */
|
||||
export const SCHOOL_DEFAULT_AVATAR_STORAGE_KEY = "yh-avatar-sch-default";
|
||||
|
||||
export const AVATAR_STYLES: readonly AvatarStyle[] = ["text", "silhouette"];
|
||||
|
||||
export const DEFAULT_AVATAR_STYLE: AvatarStyle = "text";
|
||||
|
||||
/** 值合法才采用(用户键/学校键同一判据;脏数据不生效) */
|
||||
function readAvatarStyleOrNull(raw: string | null): AvatarStyle | null {
|
||||
return raw === "text" || raw === "silhouette" ? raw : null;
|
||||
}
|
||||
|
||||
/** URL 覆盖参数(?yh-avatar=text|silhouette):非法值忽略,且只影响"读哪一档"、绝不写回 localStorage */
|
||||
function readAvatarOverride(): AvatarStyle | null {
|
||||
try {
|
||||
const search = (globalThis.location && globalThis.location.search) || "";
|
||||
const m = new RegExp("[?&]yh-avatar=([^&]*)").exec(search);
|
||||
return m ? readAvatarStyleOrNull(decodeURIComponent(m[1])) : null;
|
||||
} catch {
|
||||
/* 无 location 环境(测试/SSR):无覆盖 */
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生效样式合成(与 resolveEffectiveThemeState 同构):
|
||||
* URL 覆盖 > localStorage["yh-avatar"](用户自选)> localStorage["yh-avatar-sch-default"](学校默认)
|
||||
* > DEFAULT_AVATAR_STYLE。
|
||||
*/
|
||||
export function resolveAvatarStyle(storage: StorageLike | undefined = globalThis.localStorage): AvatarStyle {
|
||||
let style: AvatarStyle | null = null;
|
||||
if (storage) {
|
||||
style = readAvatarStyleOrNull(storage.getItem(AVATAR_STORAGE_KEY));
|
||||
if (!style) style = readAvatarStyleOrNull(storage.getItem(SCHOOL_DEFAULT_AVATAR_STORAGE_KEY));
|
||||
}
|
||||
if (!style) style = DEFAULT_AVATAR_STYLE;
|
||||
return readAvatarOverride() || style;
|
||||
}
|
||||
|
||||
/** 保存用户自选(直写 localStorage,无响应式;调用方操作后自行刷新 UI) */
|
||||
export function saveAvatarStyle(style: AvatarStyle, storage: StorageLike | undefined = globalThis.localStorage): void {
|
||||
try {
|
||||
storage?.setItem(AVATAR_STORAGE_KEY, style);
|
||||
} catch {
|
||||
/* 隐私模式/配额失败静默:仅丢持久化,不丢本次会话生效 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 跟随学校默认 = 删用户自选键(之后回落学校默认/系统默认) */
|
||||
export function clearAvatarStyle(storage: StorageLike | undefined = globalThis.localStorage): void {
|
||||
try {
|
||||
storage?.removeItem(AVATAR_STORAGE_KEY);
|
||||
} catch {
|
||||
/* 隐私模式静默 */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取字(顺序判定,先命中先返回):含 "@" 先截 "@" 前段(邮箱取首字母);
|
||||
* 首字符必须用展开 [...s][0](禁用 charAt(0),避免代理对截半出乱码)。
|
||||
* ASCII 字母转大写;纯数字回落 ""(剪影);符号/emoji/空白回落 ""(剪影);其余(CJK 等)原样。
|
||||
*/
|
||||
export function pickAvatarText(name: string | null | undefined): string {
|
||||
let s = String(name ?? "");
|
||||
const at = s.indexOf("@");
|
||||
if (at > -1) s = s.slice(0, at);
|
||||
const ch = [...s.trim()][0];
|
||||
if (ch === undefined) return "";
|
||||
if (/^[A-Za-z]$/.test(ch)) return ch.toUpperCase();
|
||||
if (/^[0-9]$/.test(ch)) return "";
|
||||
if (/^[\p{P}\p{S}\s]$/u.test(ch)) return "";
|
||||
return ch;
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* 本文件由 YschTheme scripts/gen-theme.mjs 从 assets-src/pc/theme-core.js 生成(版本 20261009-1107-1688389),勿手改。
|
||||
* 分发方式:YschTheme `npm run sync` 拷进各端 src/utils/theme.ts(与 ThemeSwitcher.vue 配套,MD5 对齐报告)。
|
||||
* 运行时档位类名由 /static/js/yh-theme-init.js 在 <head> 内先行挂好,本模块只负责读写与切换。
|
||||
*/
|
||||
export type ThemeName = "blue" | "ocean" | "ink" | "violet" | "teal";
|
||||
|
||||
/** 定稿默认档:blue + side-deep + grad-on + 侧栏跟随(D1 拍板 deep) */
|
||||
export interface ThemeState {
|
||||
theme: ThemeName;
|
||||
/** 侧栏深色(false=浅色档) */
|
||||
sideDeep: boolean;
|
||||
/** 顶栏渐变(联动侧栏竖向渐变) */
|
||||
gradOn: boolean;
|
||||
/** 侧栏颜色跟随顶栏品牌色(false=中性灰 side-plain) */
|
||||
sideFollow: boolean;
|
||||
}
|
||||
|
||||
interface StorageLike {
|
||||
getItem(k: string): string | null;
|
||||
setItem(k: string, v: string): void;
|
||||
}
|
||||
|
||||
export const THEME_NAMES: readonly ThemeName[] = ["blue", "ocean", "ink", "violet", "teal"];
|
||||
|
||||
export const THEME_STORAGE_KEY = "yh-theme";
|
||||
|
||||
/* 学校默认档存储键(UserHome 登录时写入;值格式与 yh-theme 完全相同,仅无"用户自选"语义) */
|
||||
export const SCHOOL_DEFAULT_STORAGE_KEY = "yh-theme-sch-default";
|
||||
|
||||
export const DEFAULT_THEME_STATE: ThemeState = {
|
||||
theme: "blue",
|
||||
sideDeep: true,
|
||||
gradOn: true,
|
||||
sideFollow: true
|
||||
};
|
||||
|
||||
/** 宽松解析:任一字段非法/缺失即回退默认档(脏数据不阻塞启动) */
|
||||
export function parseThemeState(raw: string | null): ThemeState {
|
||||
if (!raw) return { ...DEFAULT_THEME_STATE };
|
||||
try {
|
||||
const o = JSON.parse(raw);
|
||||
if (!o || typeof o !== "object") return { ...DEFAULT_THEME_STATE };
|
||||
return {
|
||||
theme: THEME_NAMES.includes(o.theme) ? o.theme : DEFAULT_THEME_STATE.theme,
|
||||
sideDeep: typeof o.sideDeep === "boolean" ? o.sideDeep : DEFAULT_THEME_STATE.sideDeep,
|
||||
gradOn: typeof o.gradOn === "boolean" ? o.gradOn : DEFAULT_THEME_STATE.gradOn,
|
||||
sideFollow: typeof o.sideFollow === "boolean" ? o.sideFollow : DEFAULT_THEME_STATE.sideFollow
|
||||
};
|
||||
} catch {
|
||||
return { ...DEFAULT_THEME_STATE };
|
||||
}
|
||||
}
|
||||
|
||||
/** 严格读取:四字段全部合法才返回状态,否则 null(合成链"值非法→回落下一级"用;用户键仍走宽松解析保现状) */
|
||||
function readThemeStateOrNull(raw: string | null): ThemeState | null {
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const o = JSON.parse(raw);
|
||||
if (!o || typeof o !== "object") return null;
|
||||
if (!THEME_NAMES.includes(o.theme)) return null;
|
||||
if (typeof o.sideDeep !== "boolean" || typeof o.gradOn !== "boolean" || typeof o.sideFollow !== "boolean") return null;
|
||||
return { theme: o.theme, sideDeep: o.sideDeep, gradOn: o.gradOn, sideFollow: o.sideFollow };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** URL 覆盖参数(?yh-theme= / ?yh-side=deep|light / ?yh-grad=on|off):仅预览/排障用,
|
||||
非法值忽略(对应字段不覆盖),且只影响"读哪一档"、绝不写回 localStorage。 */
|
||||
function readThemeOverrides(): { theme?: ThemeName; sideDeep?: boolean; gradOn?: boolean } | null {
|
||||
let out = null;
|
||||
try {
|
||||
const search = (globalThis.location && globalThis.location.search) || "";
|
||||
const get = (name) => {
|
||||
const m = new RegExp("[?&]" + name + "=([^&]*)").exec(search);
|
||||
return m ? decodeURIComponent(m[1]) : null;
|
||||
};
|
||||
const t = get("yh-theme");
|
||||
if (t && THEME_NAMES.includes(t)) {
|
||||
out = out || {};
|
||||
out.theme = t;
|
||||
}
|
||||
const s = get("yh-side");
|
||||
if (s === "deep" || s === "light") {
|
||||
out = out || {};
|
||||
out.sideDeep = s === "deep";
|
||||
}
|
||||
const g = get("yh-grad");
|
||||
if (g === "on" || g === "off") {
|
||||
out = out || {};
|
||||
out.gradOn = g === "on";
|
||||
}
|
||||
} catch {
|
||||
/* 无 location 环境(测试/SSR):无覆盖 */
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生效档合成(唯一实现,init 启动段与 UserHome theme.ts 共用):
|
||||
* URL 覆盖 > localStorage["yh-theme"](用户自选,存在即用——宽松修补,与历史行为一致)
|
||||
* > localStorage["yh-theme-sch-default"](学校默认,整体合法才生效)
|
||||
* > DEFAULT_THEME_STATE。
|
||||
* 键不存在/解析失败/值非法均静默回落,不报错不阻塞首帧。
|
||||
*/
|
||||
export function resolveEffectiveThemeState(storage: StorageLike | undefined = globalThis.localStorage): ThemeState {
|
||||
let state = null;
|
||||
if (storage) {
|
||||
const userRaw = storage.getItem(THEME_STORAGE_KEY);
|
||||
if (userRaw) state = parseThemeState(userRaw);
|
||||
if (!state) state = readThemeStateOrNull(storage.getItem(SCHOOL_DEFAULT_STORAGE_KEY));
|
||||
}
|
||||
if (!state) state = { ...DEFAULT_THEME_STATE };
|
||||
const ov = readThemeOverrides();
|
||||
if (ov) {
|
||||
if (ov.theme) state = { ...state, theme: ov.theme };
|
||||
if (ov.sideDeep != null) state = { ...state, sideDeep: ov.sideDeep };
|
||||
if (ov.gradOn != null) state = { ...state, gradOn: ov.gradOn };
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
export function loadThemeState(storage: StorageLike | undefined = globalThis.localStorage): ThemeState {
|
||||
if (!storage) return { ...DEFAULT_THEME_STATE };
|
||||
return parseThemeState(storage.getItem(THEME_STORAGE_KEY));
|
||||
}
|
||||
|
||||
export function saveThemeState(state: ThemeState, storage: StorageLike | undefined = globalThis.localStorage): void {
|
||||
try {
|
||||
storage?.setItem(THEME_STORAGE_KEY, JSON.stringify(state));
|
||||
} catch {
|
||||
/* 隐私模式/配额失败静默:仅丢持久化,不丢本次会话生效 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 把状态落到根元素档位类名(幂等:先清后挂),返回传入的 state 便于链式 */
|
||||
export function applyThemeState(state: ThemeState, root: HTMLElement = document.documentElement): ThemeState {
|
||||
root.dataset.theme = state.theme;
|
||||
root.classList.toggle("side-deep", state.sideDeep);
|
||||
root.classList.toggle("side-light", !state.sideDeep);
|
||||
root.classList.toggle("grad-on", state.gradOn);
|
||||
root.classList.toggle("grad-off", !state.gradOn);
|
||||
root.classList.toggle("side-plain", !state.sideFollow);
|
||||
return state;
|
||||
}
|
||||
|
||||
/** 启动引导:各端 main.ts(或本仓 init 脚本的启动段)于挂载前调用,消除首帧闪色 */
|
||||
export function initTheme(): ThemeState {
|
||||
return applyThemeState(loadThemeState());
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
<template>
|
||||
<div class="main-wrapper">
|
||||
<div class="main-container">
|
||||
<div class="search-wrap fix">
|
||||
<span class="tip">
|
||||
应用管理(open_api_app):ANON=仅内部入口免签,仍须带 X-App-Key;appKey 填 <b>*</b> =
|
||||
匿名窗口(无票据放行,≤31 天强制到期);改回 SIGNED 前先确认密钥链有该键。
|
||||
</span>
|
||||
<div class="fr">
|
||||
<Button type="primary" @click="openCreate">新增应用</Button>
|
||||
<Button class="ml8" @click="refresh">刷新</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TablePageAlovaNew ref="tableRef" :dataApi="tableApi" :columns="columns" :dataFilter="normalizeRows"
|
||||
:tableHeight="tableHeight">
|
||||
<template #appKey="{ row }">
|
||||
<span v-if="row.appKey === '*'" class="window-tag">*(匿名窗口)</span>
|
||||
<span v-else class="mono">{{ row.appKey }}</span>
|
||||
</template>
|
||||
<template #appName="{ row }">
|
||||
<Input v-model="row.appName" size="small" placeholder="-" />
|
||||
</template>
|
||||
<template #authMode="{ row }">
|
||||
<Select v-model="row.authMode" size="small" style="width: 110px"
|
||||
@on-change="onModeChange(row)">
|
||||
<Option value="SIGNED">SIGNED</Option>
|
||||
<Option value="ANON">ANON</Option>
|
||||
</Select>
|
||||
</template>
|
||||
<template #expireAt="{ row }">
|
||||
<template v-if="row.authMode === 'ANON'">
|
||||
<Input v-model="row.expireAtText" size="small" placeholder="yyyy-MM-dd HH:mm:ss"
|
||||
style="width: 170px" :class="expireClass(row)" />
|
||||
<div :class="expireClass(row)" class="expire-hint">{{ expireHint(row) }}</div>
|
||||
</template>
|
||||
<span v-else class="expire-none">-</span>
|
||||
</template>
|
||||
<template #enabled="{ row }">
|
||||
<i-switch v-model="row.enabled" size="small" />
|
||||
</template>
|
||||
<template #remark="{ row }">
|
||||
<Input v-model="row.remark" size="small" placeholder="-" />
|
||||
</template>
|
||||
<template #gmtModified="{ row }">
|
||||
<span>{{ row.gmtModified ? Utils.dateFormat(row.gmtModified, 'yyyy-MM-dd HH:mm:ss') : '-' }}</span>
|
||||
</template>
|
||||
<template #action="{ row }">
|
||||
<Button type="primary" size="small" :loading="savingId === row.id" @click="save(row)">保存</Button>
|
||||
</template>
|
||||
</TablePageAlovaNew>
|
||||
|
||||
<Modal v-model="createShow" :mask-closable="false" width="560" title="新增应用">
|
||||
<Form :label-width="110" class="app-create-form">
|
||||
<FormItem label="appKey:" required>
|
||||
<Input v-model="createForm.appKey" placeholder="调用方 appKey(唯一;填 * = 匿名窗口行)" />
|
||||
</FormItem>
|
||||
<FormItem label="展示名:">
|
||||
<Input v-model="createForm.appName" placeholder="可选" />
|
||||
</FormItem>
|
||||
<FormItem label="authMode:" required>
|
||||
<Select v-model="createForm.authMode" style="width: 180px">
|
||||
<Option value="SIGNED">SIGNED(验签,缺省)</Option>
|
||||
<Option value="ANON">ANON(内部入口免签)</Option>
|
||||
</Select>
|
||||
</FormItem>
|
||||
<FormItem v-if="createForm.authMode === 'ANON'" label="免签到期:" required>
|
||||
<Input v-model="createForm.expireAt" placeholder="yyyy-MM-dd HH:mm:ss(必填,≤31 天)" />
|
||||
</FormItem>
|
||||
<FormItem label="备注:">
|
||||
<Input v-model="createForm.remark" placeholder="可选" />
|
||||
</FormItem>
|
||||
<div class="form-tip" v-if="createForm.authMode === 'ANON'">
|
||||
免签最长 31 天(每次保存重新起算),到期惰性恢复验签;ANON 应用不要求密钥链有键。
|
||||
</div>
|
||||
</Form>
|
||||
<template #footer>
|
||||
<Button @click="createShow = false">取消</Button>
|
||||
<Button type="primary" :loading="creating" @click="submitCreate">确定</Button>
|
||||
</template>
|
||||
</Modal>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from 'vue';
|
||||
import useCurrentInstance from '@/utils/hook/useCurrentInstance';
|
||||
import TablePageAlovaNew from '@/components/TablePageAlovaNew.vue';
|
||||
import Utils from '@/utils';
|
||||
|
||||
defineOptions({ name: 'AppList' });
|
||||
|
||||
const { $utils } = useCurrentInstance();
|
||||
|
||||
const tableRef = ref<InstanceType<typeof TablePageAlovaNew> | null>(null);
|
||||
const savingId = ref<number | null>(null);
|
||||
|
||||
const tableApi = (params: { pageIndex: number; pageSize: number }) =>
|
||||
Apis.GatewayAdmin.apps({ params, cacheFor: null });
|
||||
|
||||
const tableHeight = ref($utils.useTableHeight({ isOperat: false, isPage: true, isSearch: true }));
|
||||
|
||||
const columns = [
|
||||
{ title: 'id', key: 'id', width: 70, align: 'center' },
|
||||
{ title: 'appKey', slot: 'appKey', width: 160 },
|
||||
{ title: '展示名', slot: 'appName', width: 150 },
|
||||
{ title: 'authMode', slot: 'authMode', width: 130 },
|
||||
{ title: '免签到期', slot: 'expireAt', minWidth: 210 },
|
||||
{ title: '启用', slot: 'enabled', width: 80, align: 'center' },
|
||||
{ title: '备注', slot: 'remark', minWidth: 140 },
|
||||
{ title: '更新时间', slot: 'gmtModified', width: 170 },
|
||||
{ title: '操作', slot: 'action', width: 90, align: 'center', fixed: 'right' as const },
|
||||
];
|
||||
|
||||
/** 服务端 expireAt 为 ISO 串:补一行内编辑用的 "yyyy-MM-dd HH:mm:ss" 文本 */
|
||||
function normalizeRows(rows: any[]) {
|
||||
return (rows || []).map((r: any) => ({
|
||||
...r,
|
||||
expireAtText: r.expireAt ? Utils.dateFormat(r.expireAt, 'yyyy-MM-dd HH:mm:ss') : '',
|
||||
}));
|
||||
}
|
||||
|
||||
const DAY_MS = 24 * 3600 * 1000;
|
||||
const MAX_TTL_DAYS = 31;
|
||||
|
||||
/** 到期可视化:已过期标红、临期(≤3 天)标橙 */
|
||||
function expireState(row: any): 'expired' | 'soon' | 'ok' {
|
||||
if (!row.expireAt) return 'expired';
|
||||
const remain = new Date(String(row.expireAt).replace(/-/g, '/').replace(/T/, ' ')).getTime() - Date.now();
|
||||
if (remain <= 0) return 'expired';
|
||||
if (remain <= 3 * DAY_MS) return 'soon';
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
function expireClass(row: any) {
|
||||
const s = expireState(row);
|
||||
return { 'expire-danger': s === 'expired', 'expire-warning': s === 'soon' };
|
||||
}
|
||||
|
||||
function expireHint(row: any) {
|
||||
const s = expireState(row);
|
||||
if (s === 'expired') return '已过期(免签失效,等同无行)';
|
||||
if (s === 'soon') return '临期,续期请重新保存';
|
||||
return `有效期 ≤${MAX_TTL_DAYS} 天,续期重新起算`;
|
||||
}
|
||||
|
||||
/** 切到 SIGNED 即视为放弃免签:清空行内到期文本(后端落库置 NULL) */
|
||||
function onModeChange(row: any) {
|
||||
if (row.authMode !== 'ANON') {
|
||||
row.expireAtText = '';
|
||||
}
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
tableRef.value?.refreshData();
|
||||
}
|
||||
|
||||
/** 行内编辑:只提交治理字段(appKey 是行身份,后端不接受改动);ANON 行连同到期一起提交 */
|
||||
async function save(row: any) {
|
||||
savingId.value = row.id;
|
||||
try {
|
||||
const data: Record<string, any> = {
|
||||
appName: row.appName,
|
||||
authMode: row.authMode,
|
||||
enabled: row.enabled,
|
||||
remark: row.remark,
|
||||
};
|
||||
if (row.authMode === 'ANON') {
|
||||
data.expireAt = row.expireAtText;
|
||||
}
|
||||
const d: any = await Apis.GatewayAdmin.updateApp({
|
||||
pathParams: { id: row.id },
|
||||
data,
|
||||
});
|
||||
Message.success(`已保存,应用表加载 ${d?.apps ?? '-'} 条`);
|
||||
} catch (e: any) {
|
||||
// 错误提示由 alova 全局 onBizError 弹出,这里只做回滚,避免双 toast
|
||||
tableRef.value?.refreshData();
|
||||
} finally {
|
||||
savingId.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/* 新增应用弹窗(O3:治理页闭环,不留"只有 UI 没有后端"断层) */
|
||||
const createShow = ref(false);
|
||||
const creating = ref(false);
|
||||
const createForm = reactive({
|
||||
appKey: '',
|
||||
appName: '',
|
||||
authMode: 'ANON',
|
||||
expireAt: '',
|
||||
remark: '',
|
||||
});
|
||||
|
||||
function openCreate() {
|
||||
createForm.appKey = '';
|
||||
createForm.appName = '';
|
||||
createForm.authMode = 'ANON';
|
||||
createForm.expireAt = '';
|
||||
createForm.remark = '';
|
||||
createShow.value = true;
|
||||
}
|
||||
|
||||
async function submitCreate() {
|
||||
if (!createForm.appKey || !createForm.appKey.trim()) {
|
||||
Message.warning('appKey 必填');
|
||||
return;
|
||||
}
|
||||
if (createForm.authMode === 'ANON' && !createForm.expireAt.trim()) {
|
||||
Message.warning('authMode=ANON 时免签到期必填(≤31 天)');
|
||||
return;
|
||||
}
|
||||
creating.value = true;
|
||||
try {
|
||||
const d: any = await Apis.GatewayAdmin.createApp({ data: { ...createForm } });
|
||||
Message.success(`已创建,应用表加载 ${d?.apps ?? '-'} 条`);
|
||||
createShow.value = false;
|
||||
tableRef.value?.reloadData('add' as any);
|
||||
} catch (e: any) {
|
||||
// 错误提示由 alova 全局 onBizError 弹出
|
||||
} finally {
|
||||
creating.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.search-wrap {
|
||||
line-height: 32px;
|
||||
|
||||
.tip {
|
||||
color: #848c98;
|
||||
font-size: 13px;
|
||||
|
||||
b {
|
||||
color: #ed4014;
|
||||
}
|
||||
}
|
||||
|
||||
.ml8 {
|
||||
margin-left: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
.window-tag {
|
||||
color: #ff9900;
|
||||
font-family: Menlo, Consolas, monospace;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.expire-hint {
|
||||
font-size: 12px;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
.expire-none {
|
||||
color: #c5c8ce;
|
||||
}
|
||||
|
||||
.expire-warning,
|
||||
.expire-warning.expire-hint {
|
||||
color: #ff9900;
|
||||
}
|
||||
|
||||
.expire-danger,
|
||||
.expire-danger.expire-hint {
|
||||
color: #ed4014;
|
||||
}
|
||||
|
||||
.form-tip {
|
||||
margin: -6px 0 0 110px;
|
||||
font-size: 12px;
|
||||
color: #848c98;
|
||||
line-height: 18px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,256 @@
|
||||
<template>
|
||||
<div class="main-wrapper">
|
||||
<div class="main-container">
|
||||
<div class="search-wrap fix">
|
||||
<span class="tip">
|
||||
代理测试:输入票据与 oapi 地址,网关服务端签名后回环打真实链路(内部入口口径,一律验签)。
|
||||
observe=true 时 200 不代表验签通过,最终判定看「访问台账」。
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="proxy-form">
|
||||
<div class="form-row">
|
||||
<Select v-model="form.method" style="width: 110px">
|
||||
<Option v-for="m in METHODS" :key="m" :value="m">{{ m }}</Option>
|
||||
</Select>
|
||||
<Input v-model="form.url" class="grow" placeholder="http://网关地址/{target}/oapi/**,如 /userbase/oapi/user/byId?id=1" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<Input v-model="form.appKey" placeholder="appKey" style="width: 200px" />
|
||||
<Input v-model="form.appSecret" type="password" placeholder="appSecret(留空 = 由网关密钥链解析)" style="width: 320px" />
|
||||
<Input v-model="form.contentType" class="grow" placeholder="Content-Type" />
|
||||
</div>
|
||||
<div class="form-row" v-if="hasBody">
|
||||
<Input v-model="form.body" type="textarea" :rows="6" placeholder="JSON 请求体(可选)" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<Button type="primary" :loading="sending" @click="send">发送</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="result" v-if="result">
|
||||
<div class="status-line">
|
||||
<Tag :color="statusColor(result.status)">{{ result.status }}</Tag>
|
||||
<span class="dot">·</span>
|
||||
<span>{{ result.latencyMs }}ms</span>
|
||||
<span class="dot">·</span>
|
||||
<span>target={{ result.target }}</span>
|
||||
<span class="dot">·</span>
|
||||
<span>{{ result.contentType || '-' }}</span>
|
||||
<Tag v-if="result.bodyTruncated" color="warning">响应体超 256KB 已截断</Tag>
|
||||
</div>
|
||||
|
||||
<code class="code-line request-url">{{ result.requestUrl }}</code>
|
||||
|
||||
<div v-if="result.error" class="error-line">{{ result.error }}</div>
|
||||
|
||||
<div class="sign-block">
|
||||
<div class="block-title">签名调试</div>
|
||||
<div class="kv-line">
|
||||
<span class="k">appKey</span>
|
||||
<span>{{ result.signature.appKey }}</span>
|
||||
</div>
|
||||
<div class="kv-line">
|
||||
<span class="k">timestamp</span>
|
||||
<span>{{ result.signature.timestamp }}</span>
|
||||
</div>
|
||||
<div class="kv-line">
|
||||
<span class="k">secretSource</span>
|
||||
<span>{{ result.signature.secretSource }}</span>
|
||||
</div>
|
||||
<div class="kv-line">
|
||||
<span class="k">canonical</span>
|
||||
<code class="code-line grow">{{ result.signature.canonical }}</code>
|
||||
<Button size="small" @click="copyText(result.signature.canonical)">复制</Button>
|
||||
</div>
|
||||
<div class="kv-line">
|
||||
<span class="k">signature</span>
|
||||
<code class="code-line grow">{{ result.signature.signature }}</code>
|
||||
<Button size="small" @click="copyText(result.signature.signature)">复制</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="block-title">响应体</div>
|
||||
<pre class="res-body">{{ prettyBody }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, computed } from 'vue';
|
||||
|
||||
defineOptions({ name: 'ProxyTest' });
|
||||
|
||||
const METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];
|
||||
|
||||
const form = reactive({
|
||||
method: 'GET',
|
||||
url: '',
|
||||
appKey: '',
|
||||
appSecret: '',
|
||||
contentType: 'application/json',
|
||||
body: '',
|
||||
});
|
||||
|
||||
const hasBody = computed(() => ['POST', 'PUT', 'DELETE', 'PATCH'].includes(form.method));
|
||||
const sending = ref(false);
|
||||
const result = ref<any>(null);
|
||||
|
||||
async function send() {
|
||||
if (!form.url.trim() || !form.appKey.trim()) {
|
||||
Message.warning('url 与 appKey 必填');
|
||||
return;
|
||||
}
|
||||
sending.value = true;
|
||||
result.value = null;
|
||||
try {
|
||||
const d: any = await Apis.GatewayAdmin.proxyTest({
|
||||
data: {
|
||||
url: form.url,
|
||||
method: form.method,
|
||||
appKey: form.appKey,
|
||||
appSecret: form.appSecret || undefined, // 空串不传 → 后端走 REDIS 解析
|
||||
contentType: hasBody.value ? form.contentType : undefined,
|
||||
body: hasBody.value && form.body.trim() ? form.body : undefined,
|
||||
},
|
||||
});
|
||||
result.value = d;
|
||||
} catch (e) {
|
||||
// code=2 业务错由 alova 全局 onBizError 统一弹 toast
|
||||
} finally {
|
||||
sending.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function statusColor(s: number): string {
|
||||
if (s >= 200 && s < 300) return 'green';
|
||||
if (s >= 400 && s < 500) return 'warning';
|
||||
if (s >= 500) return 'error';
|
||||
return 'default';
|
||||
}
|
||||
|
||||
const prettyBody = computed(() => {
|
||||
const b = result.value?.body ?? '';
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(b), null, 2);
|
||||
} catch {
|
||||
return b;
|
||||
}
|
||||
});
|
||||
|
||||
async function copyText(t: string) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(t);
|
||||
Message.success('已复制');
|
||||
} catch {
|
||||
Message.error('复制失败,请手动选中复制');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.search-wrap {
|
||||
line-height: 32px;
|
||||
|
||||
.tip {
|
||||
color: #848c98;
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
.proxy-form {
|
||||
margin: 14px 0 18px;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 10px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.grow {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.result {
|
||||
.status-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-bottom: 10px;
|
||||
font-size: 13px;
|
||||
|
||||
.dot {
|
||||
color: #c5c8ce;
|
||||
}
|
||||
}
|
||||
|
||||
.code-line {
|
||||
display: block;
|
||||
background: #f5f7f9;
|
||||
border: 1px solid #e3e8ee;
|
||||
border-radius: 4px;
|
||||
padding: 6px 10px;
|
||||
font-family: Consolas, Menlo, monospace;
|
||||
font-size: 12px;
|
||||
color: #2d8cf0;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.request-url {
|
||||
white-space: nowrap;
|
||||
overflow-x: auto;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.error-line {
|
||||
color: #ed4014;
|
||||
font-size: 13px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.sign-block {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.block-title {
|
||||
font-weight: bold;
|
||||
font-size: 13px;
|
||||
margin: 12px 0 8px;
|
||||
}
|
||||
|
||||
.kv-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 8px;
|
||||
|
||||
.k {
|
||||
flex: none;
|
||||
width: 90px;
|
||||
color: #848c98;
|
||||
font-size: 13px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.code-line {
|
||||
flex: 1;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.res-body {
|
||||
background: #f5f7f9;
|
||||
border: 1px solid #e3e8ee;
|
||||
border-radius: 4px;
|
||||
padding: 10px 12px;
|
||||
max-height: 400px;
|
||||
overflow: auto;
|
||||
font-family: Consolas, Menlo, monospace;
|
||||
font-size: 12px;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="main-wrapper">
|
||||
<div class="main-container">
|
||||
<div class="search-wrap fix">
|
||||
<span class="tip">路由注册表(open_api_route):治理旋钮行内编辑,保存后网关热重载,无须重启。</span>
|
||||
<span class="tip">路由注册表(open_api_route):治理旋钮行内编辑,保存后网关热重载,无须重启。qps>0 时按 调用方×本行 限流(超限裸 429,0=不限);timeout/bodyLimit 立即生效。</span>
|
||||
<Button type="primary" class="fr" @click="refresh">刷新</Button>
|
||||
</div>
|
||||
|
||||
@@ -31,6 +31,12 @@
|
||||
<template #rateLimitQps="{ row }">
|
||||
<Input v-model="row.rateLimitQps" type="number" size="small" style="width: 80px" />
|
||||
</template>
|
||||
<template #timeoutMs="{ row }">
|
||||
<Input v-model="row.timeoutMs" type="number" size="small" style="width: 90px" placeholder="1000-120000" />
|
||||
</template>
|
||||
<template #requestBodyLimitMb="{ row }">
|
||||
<Input v-model="row.requestBodyLimitMb" type="number" size="small" style="width: 90px" placeholder="1-100" />
|
||||
</template>
|
||||
<template #enabled="{ row }">
|
||||
<i-switch v-model="row.enabled" size="small" />
|
||||
</template>
|
||||
@@ -72,8 +78,8 @@ const columns = [
|
||||
{ title: 'cacheTtl(s)', slot: 'cacheTtlSeconds', width: 105 },
|
||||
{ title: 'cacheScope', slot: 'cacheScope', width: 120 },
|
||||
{ title: 'qps', slot: 'rateLimitQps', width: 90 },
|
||||
{ title: 'timeout(ms)', key: 'timeoutMs', width: 105, align: 'right' },
|
||||
{ title: 'bodyLimit(mb)', key: 'requestBodyLimitMb', width: 115, align: 'right' },
|
||||
{ title: 'timeout(ms)', slot: 'timeoutMs', width: 115, align: 'right' },
|
||||
{ title: 'bodyLimit(mb)', slot: 'requestBodyLimitMb', width: 125, align: 'right' },
|
||||
{ title: '启用', slot: 'enabled', width: 80, align: 'center' },
|
||||
{ title: '备注', slot: 'remark', minWidth: 160 },
|
||||
{ title: '操作', slot: 'action', width: 90, align: 'center', fixed: 'right' as const },
|
||||
@@ -95,6 +101,8 @@ async function save(row: any) {
|
||||
cacheTtlSeconds: Number(row.cacheTtlSeconds) || 0,
|
||||
cacheScope: row.cacheScope,
|
||||
rateLimitQps: Number(row.rateLimitQps) || 0,
|
||||
timeoutMs: Number(row.timeoutMs) || 30000,
|
||||
requestBodyLimitMb: Number(row.requestBodyLimitMb) || 10,
|
||||
enabled: row.enabled,
|
||||
remark: row.remark,
|
||||
},
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"types": ["vite/client"]
|
||||
"types": ["vite/client", "node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue","types"],
|
||||
|
||||
|
||||
+45
-2
@@ -1,4 +1,4 @@
|
||||
import { ConfigEnv, UserConfig, defineConfig } from "vite";
|
||||
import { ConfigEnv, UserConfig, defineConfig, type Plugin } from "vite";
|
||||
import { createHtmlPlugin } from "vite-plugin-html";
|
||||
import vue from "@vitejs/plugin-vue";
|
||||
import path, { resolve } from "path";
|
||||
@@ -9,6 +9,35 @@ import UnoCSS from "@unocss/vite";
|
||||
import presetUno from "@unocss/preset-uno";
|
||||
import presetRemToPx from "@unocss/preset-rem-to-px";
|
||||
|
||||
// mock 数据层(仅 --mode mock 注册,见下方 gatewayAdminMockPlugin;零依赖手写中间件而非
|
||||
// vite-plugin-mock:后者独立打包 mock 文件为第二模块实例,无法实现"整页刷新重置内存态")
|
||||
import { handleGatewayMockRequest, resetGatewayMockState } from "./src/assets/mock/gatewayApi";
|
||||
|
||||
/** 内置 mock(仅 serve + --mode mock):拦截 /open-gateway/api/internal/** 按后端契约应答。
|
||||
* 直接注册在 configureServer(先于 vite 内部中间件,含 /open-gateway/api 代理);
|
||||
* 整页文档请求(刷新/直达)触发内存态重置回静态种子,SPA 站内切换不重置。 */
|
||||
function gatewayAdminMockPlugin(): Plugin {
|
||||
return {
|
||||
name: "gateway-admin-mock",
|
||||
apply: "serve",
|
||||
configureServer(server) {
|
||||
server.middlewares.use((req, _res, next) => {
|
||||
const accept = String(req.headers.accept ?? "");
|
||||
if (accept.includes("text/html")) resetGatewayMockState();
|
||||
next();
|
||||
});
|
||||
server.middlewares.use(async (req, res, next) => {
|
||||
try {
|
||||
if (!(await handleGatewayMockRequest(req, res))) next();
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
// 构建输出恒为 dist 根:CI 打包 zip 的根目录必须直接是 index.html(projman 前端发布校验 zip 根含 html)。
|
||||
// 不再有 dist/base 中间层——outDir=dist/base 时 zip 打 dist 整层,zip 根只有 base/,发布会校验失败。
|
||||
// dev(--mode dev)读 .env.dev,VITE_SERVICE_HOST 指向同源前缀 /open-gateway(经下方 proxy 打到 base 域)
|
||||
@@ -17,6 +46,8 @@ export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
|
||||
|
||||
return {
|
||||
plugins: [
|
||||
// 仅 --mode mock 启用内置 mock;dev/联调/正式 build 行为零变化
|
||||
...(mode === "mock" ? [gatewayAdminMockPlugin()] : []),
|
||||
vue(),
|
||||
createSvgIconsPlugin({
|
||||
iconDirs: [resolve(process.cwd(), "src/assets/icons")],
|
||||
@@ -90,9 +121,21 @@ export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
|
||||
port: 8131,
|
||||
// 本地联调:/open-gateway/api/* → base 域(Caddy 剥前缀后转发到网关容器网内 10013)
|
||||
// 走代理而非跨源直连:网关无 CORS,且 10013 仅绑容器网内 127.0.0.1
|
||||
// 设 YH_GW_PROXY_TARGET(如 http://localhost:10013)= 不经 base 域直打本地网关,
|
||||
// 此时剥掉 /open-gateway 前缀(原本由 Caddy 剥);不设则行为与线上联调零变化
|
||||
proxy: {
|
||||
"/open-gateway/api": {
|
||||
target: "http://base.yunhaixingtong.com",
|
||||
target: process.env.YH_GW_PROXY_TARGET || "http://base.yunhaixingtong.com",
|
||||
changeOrigin: true,
|
||||
...(process.env.YH_GW_PROXY_TARGET
|
||||
? { rewrite: (p: string) => p.replace(/^\/open-gateway/, "") }
|
||||
: {}),
|
||||
},
|
||||
// 主题通道本地联调(照 Notice 配方):index.html loader 走同源相对 /static/js/yh-theme-init.js,
|
||||
// manifest/CSS 经此代理到中央通道;base 域不可达(无 VPN)时由 npm run dev:mock
|
||||
// (scripts/start-mock.mjs)以 YH_THEME_PROXY_TARGET 把目标覆盖为本地 9527 静态服务。
|
||||
"/static": {
|
||||
target: process.env.YH_THEME_PROXY_TARGET || "http://base.yunhaixingtong.com",
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user