Compare commits
8 Commits
8a7a3b45ff
...
0e11ea321c
| Author | SHA1 | Date | |
|---|---|---|---|
| 0e11ea321c | |||
| 33d26a616e | |||
| 40c0b30f24 | |||
| fc78928af8 | |||
| af4268fb02 | |||
| 0e60c74c00 | |||
| e8d986f1ff | |||
| 7ba4d3d7b1 |
@@ -0,0 +1,12 @@
|
||||
# Loaded by npm run dev. Override locally in .env.development.local.
|
||||
# Public configuration only; VITE_* values are exposed to the browser.
|
||||
VITE_REACT_APP_SERVER_URL=
|
||||
VITE_CLOUD_BRAIN_UI_ENABLED=false
|
||||
|
||||
# Vite development proxy only. Keep the browser URL empty to use this proxy.
|
||||
DEV_PROXY_TARGET=http://134.175.227.134:13000
|
||||
|
||||
# Optional analytics. Empty IDs disable script injection.
|
||||
VITE_UMAMI_WEBSITE_ID=
|
||||
VITE_UMAMI_SCRIPT_URL=https://analytics.umami.is/script.js
|
||||
VITE_GOOGLE_ANALYTICS_ID=
|
||||
@@ -1,3 +0,0 @@
|
||||
# Frontend build-time feature flags. Rebuild the frontend after changing them.
|
||||
# Missing or false keeps the Cloud Brain suite hidden and blocks direct routes.
|
||||
VITE_CLOUD_BRAIN_UI_ENABLED=false
|
||||
@@ -0,0 +1,11 @@
|
||||
# Loaded by npm run build. Override locally in .env.production.local or in CI.
|
||||
# Public configuration only; VITE_* values are exposed to the browser.
|
||||
# Empty URL uses same-origin requests; configure your production reverse proxy.
|
||||
# Set a backend root URL for cross-origin requests, then rebuild and redeploy.
|
||||
VITE_REACT_APP_SERVER_URL=
|
||||
VITE_CLOUD_BRAIN_UI_ENABLED=false
|
||||
|
||||
# Optional analytics. Empty IDs disable script injection.
|
||||
VITE_UMAMI_WEBSITE_ID=
|
||||
VITE_UMAMI_SCRIPT_URL=https://analytics.umami.is/script.js
|
||||
VITE_GOOGLE_ANALYTICS_ID=
|
||||
+3
-4
@@ -44,8 +44,8 @@ Thumbs.db
|
||||
Desktop.ini
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.*.example
|
||||
!.env.development
|
||||
!.env.production
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
@@ -55,8 +55,7 @@ npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.idea
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
# i18n 批次中间产物(可由 scripts/i18n_kt_batches.cjs 重新生成,勿入库)
|
||||
scripts/kt_batches/
|
||||
scripts/kt_out/
|
||||
scripts/kt_out/
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Generated build output and tool caches are not source files.
|
||||
node_modules/
|
||||
dist/
|
||||
dist-ssr/
|
||||
build/
|
||||
coverage/
|
||||
.nyc_output/
|
||||
.vite/
|
||||
.cache/
|
||||
+4
-1
@@ -1 +1,4 @@
|
||||
module.exports = require('@so1ve/prettier-config');
|
||||
export default {
|
||||
singleQuote: true,
|
||||
jsxSingleQuote: true,
|
||||
};
|
||||
|
||||
@@ -1,228 +0,0 @@
|
||||
# 前端性能优化报告 - Weelink Monkey AI
|
||||
|
||||
## ✅ 已完成的性能优化 (2026-02-12 更新)
|
||||
|
||||
### 🎉 主要成就
|
||||
|
||||
#### 1. **react-icons (83MB) - ✅ 已完全移除**
|
||||
|
||||
- **优化方案**: 创建自定义内联 SVG 图标组件 ([BrandIcons.jsx](src/components/common/icons/BrandIcons.jsx))
|
||||
- **替换的文件**: 全部7个文件已完成替换
|
||||
- ✅ `components/settings/personal/sections/AccountBindingSection.jsx`
|
||||
- ✅ `components/topup/modals/PaymentConfirmModal.jsx`
|
||||
- ✅ `pages/Recharge/RechargePanel.jsx`
|
||||
- ✅ `components/topup/RechargeCard.jsx`
|
||||
- ✅ `components/table/channels/ChannelsColumnDefs.jsx`
|
||||
- ✅ `components/settings/personal/cards/AccountManagement.jsx`
|
||||
- ✅ `components/settings/personal/modals/WeChatBindModal.jsx`
|
||||
- **从 package.json 移除**: ✅ 完成
|
||||
- **节省空间**: **~83MB → 0MB** (100% 优化)
|
||||
- **实际效果**: 构建产物减少约 2-3MB (gzip后)
|
||||
|
||||
#### 2. **@lobehub/icons - 保留使用**
|
||||
|
||||
- **使用文件**: 2个
|
||||
- `pages/Home/index.jsx`
|
||||
- `helpers/render.jsx`
|
||||
- **原因**: 这些是 AI 模型品牌图标(OpenAI, Claude, Gemini等),是项目核心功能
|
||||
- **优化**: 通过 tree-shaking 和具名导入已优化加载
|
||||
- **实际打包**: ~5MB → ~500KB (通过 tree-shaking)
|
||||
|
||||
### 🟡 现有依赖(已优化)
|
||||
|
||||
#### 3. **lucide-react**
|
||||
|
||||
- **状态**: ✅ 正在使用,已通过 tree-shaking 优化
|
||||
- **导入方式**: 具名导入确保仅打包使用的图标
|
||||
- **用途**: 通用 UI 图标 (替代了大部分 react-icons)
|
||||
- **实际打包**: ~40MB → ~50-100KB (通过 tree-shaking)
|
||||
|
||||
#### 4. **mermaid (图表库)**
|
||||
|
||||
- **状态**: ✅ 已懒加载
|
||||
- **文件**: `components/common/markdown/MarkdownRenderer.jsx`
|
||||
- **优化**: 仅在需要时动态加载
|
||||
|
||||
#### 5. **katex (数学公式渲染)**
|
||||
|
||||
- **状态**: ✅ 已通过 Vite chunk 分离
|
||||
- **优化**: 独立chunk,按需加载
|
||||
|
||||
#### 6. **@visactor (图表可视化)**
|
||||
|
||||
- **状态**: ✅ 已通过 Vite chunk 分离
|
||||
- **包含**: react-vchart, vchart, vchart-semi-theme
|
||||
- **优化**: 独立chunk,按需加载
|
||||
|
||||
### 🎯 新增优化项
|
||||
|
||||
✅ **Vite 构建配置优化**
|
||||
|
||||
- 启用 esbuild 压缩
|
||||
- 移除生产环境的 console 和 debugger
|
||||
- 优化 tree-shaking 配置
|
||||
- 细粒度的代码分割 (12+ chunks)
|
||||
- Target ES2015 减少polyfill
|
||||
|
||||
✅ **已完成的优化项目**
|
||||
|
||||
- Google Fonts 依赖已移除
|
||||
- Telegram 登录组件已懒加载
|
||||
- MapleBackground 动画已优化
|
||||
- 首屏 loading 动画已优化
|
||||
- Mermaid 已懒加载
|
||||
- **react-icons 已完全移除** ⭐ NEW
|
||||
|
||||
---
|
||||
|
||||
## 📊 优化前后对比
|
||||
|
||||
| 库名 | 优化前 | 优化后 | 节省 | 状态 |
|
||||
| -------------- | ---------- | --------------------- | ----------- | ------------- |
|
||||
| react-icons | 83MB | 0MB | **-83MB** | ✅ **已移除** |
|
||||
| lucide-react | 40MB | ~100KB (tree-shaking) | **-39.9MB** | ✅ **已优化** |
|
||||
| @lobehub/icons | 5MB | ~500KB (tree-shaking) | **-4.5MB** | ✅ **已优化** |
|
||||
| @visactor | 10MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** |
|
||||
| mermaid | 3MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** |
|
||||
| katex | 2MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** |
|
||||
| **依赖总计** | **~143MB** | **~600KB + 懒加载** | **~99% ⬇️** | ✅ **完成** |
|
||||
|
||||
---
|
||||
|
||||
## 🎯 优化技术细节
|
||||
|
||||
### ✅ 已实施的优化
|
||||
|
||||
1. **移除 react-icons (83MB)**
|
||||
- 创建自定义 SVG 组件库 `BrandIcons.jsx`
|
||||
- 包含品牌图标: Wechat, Alipay, Stripe, Telegram, Discord, Linux, Shuffle
|
||||
- 所有7个文件已完成迁移
|
||||
- 从 package.json 移除依赖
|
||||
|
||||
2. **优化图标库使用**
|
||||
- lucide-react: 使用具名导入 ✅
|
||||
- @lobehub/icons: 保留(AI模型图标必需) ✅
|
||||
- 自定义SVG: 零依赖,体积最小 ✅
|
||||
|
||||
3. **Vite 构建优化**
|
||||
|
||||
```javascript
|
||||
// 压缩配置
|
||||
- esbuild 压缩 (速度+体积优化)
|
||||
- 移除 console/debugger
|
||||
- tree-shaking 优化
|
||||
|
||||
// 代码分割 (12+ chunks)
|
||||
- react-core
|
||||
- semi-ui / semi-icons
|
||||
- vchart (图表)
|
||||
- mermaid (流程图)
|
||||
- markdown / katex
|
||||
- lobe-icons / lucide-icons
|
||||
- i18n / utils
|
||||
- react-components
|
||||
```
|
||||
|
||||
### 📋 下一步可选优化
|
||||
|
||||
1. **CDN 加速 (可选)**
|
||||
- 考虑使用国内CDN加速 Semi UI
|
||||
- 使用CDN加速大型依赖(mermaid, vchart)
|
||||
|
||||
2. **图片优化 (可选)**
|
||||
- WebP 格式转换
|
||||
- 图片懒加载
|
||||
- 响应式图片
|
||||
|
||||
---
|
||||
|
||||
## 🚀 实际优化效果
|
||||
|
||||
### 打包体积对比
|
||||
|
||||
| 指标 | 优化前 | 优化后 | 提升 |
|
||||
| --------------------- | ------ | ------- | ------------- |
|
||||
| 初始JS依赖 | ~143MB | ~10MB\* | **93%** ⬇️ |
|
||||
| 主chunk (预估) | ~2.5MB | ~800KB | **68%** ⬇️ |
|
||||
| gzip 后 (预估) | ~8MB | ~2-3MB | **62-75%** ⬇️ |
|
||||
| 首屏加载时间 (中国4G) | 4-8秒 | 1.5-3秒 | **50-75%** ⬇️ |
|
||||
|
||||
\*通过 tree-shaking + 代码分割 + 懒加载实现
|
||||
|
||||
### 📈 预期用户体验提升
|
||||
|
||||
| 场景 | 优化前 | 优化后 | 改善 |
|
||||
| ------------- | --------- | ----------- | ---------- |
|
||||
| 🇨🇳 中国4G网络 | 6-8秒白屏 | 2-3秒可交互 | ⭐⭐⭐⭐⭐ |
|
||||
| 🌐 国际网络 | 3-5秒 | 1-2秒 | ⭐⭐⭐⭐ |
|
||||
| 📱 移动端 | 较慢 | 流畅 | ⭐⭐⭐⭐⭐ |
|
||||
| 🔄 页面切换 | 卡顿 | 即时响应 | ⭐⭐⭐⭐⭐ |
|
||||
|
||||
---
|
||||
|
||||
## ✅ 优化完成清单
|
||||
|
||||
### 🎉 已完成 (2026-02-12)
|
||||
|
||||
- [x] 移除 react-icons (83MB → 0MB)
|
||||
- [x] 创建自定义 SVG 图标组件
|
||||
- [x] 替换所有7个使用文件
|
||||
- [x] 从 package.json 移除
|
||||
- [x] 优化 Vite 构建配置
|
||||
- [x] 启用 esbuild 压缩
|
||||
- [x] 优化 tree-shaking
|
||||
- [x] 细粒度代码分割 (12+ chunks)
|
||||
- [x] 移除生产环境 console
|
||||
- [x] 懒加载大型依赖
|
||||
- [x] Telegram 登录组件
|
||||
- [x] Mermaid 图表
|
||||
- [x] @visactor 图表库
|
||||
- [x] katex 数学公式
|
||||
- [x] 优化图标库
|
||||
- [x] lucide-react 具名导入
|
||||
- [x] @lobehub/icons tree-shaking
|
||||
|
||||
### 📋 可选后续优化
|
||||
|
||||
- [ ] 配置 CDN 加速(Semi UI, 大型依赖)
|
||||
- [ ] 图片优化 (WebP, 懒加载)
|
||||
- [ ] 启用 Brotli 压缩
|
||||
- [ ] 添加性能监控
|
||||
|
||||
### 🧪 验证步骤
|
||||
|
||||
运行以下命令验证优化效果:
|
||||
|
||||
```bash
|
||||
cd web
|
||||
npm install # 安装依赖(已移除 react-icons)
|
||||
npm run build # 构建生产版本
|
||||
```
|
||||
|
||||
查看构建产物:
|
||||
|
||||
```bash
|
||||
ls -lh dist/assets/ # 查看打包后的文件大小
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📝 变更记录
|
||||
|
||||
**2026-02-12 (本次优化)**
|
||||
|
||||
- ✅ 完全移除 react-icons (83MB)
|
||||
- ✅ 创建自定义品牌图标组件
|
||||
- ✅ 优化 Vite 构建配置
|
||||
- ✅ 实现细粒度代码分割
|
||||
- ✅ 优化图标库 tree-shaking
|
||||
|
||||
**预期收益**:
|
||||
|
||||
- 依赖体积减少 ~93%
|
||||
- 首屏加载时间减少 50-75%
|
||||
- 中国用户体验显著提升
|
||||
|
||||
---
|
||||
|
||||
最后更新: 2026-02-12
|
||||
@@ -15,81 +15,67 @@
|
||||
| 用途 | 当前方案 |
|
||||
| --- | --- |
|
||||
| 页面开发 | React 18,JavaScript / JSX,ES Modules |
|
||||
| 构建与开发服务 | Vite 5,Bun 锁文件 `bun.lock` |
|
||||
| 构建与开发服务 | Vite 5,npm 锁文件 `package-lock.json` |
|
||||
| 路由 | React Router 6,BrowserRouter |
|
||||
| UI 与样式 | Semi Design、部分 Ant Design 6、Tailwind CSS 3、CSS 变量 |
|
||||
| UI 与样式 | Semi Design、Tailwind CSS 3、CSS 变量;清单另有 antd 5 |
|
||||
| 请求与流式响应 | Axios、Fetch、`sse.js` |
|
||||
| 状态管理 | React Context 和业务 Hooks |
|
||||
| 国际化 | i18next、react-i18next |
|
||||
| 富文本与可视化 | React Markdown、KaTeX、Mermaid、VChart、React Flow |
|
||||
| 测试与检查 | Node.js 内置测试运行器、ESLint 8、Prettier 3 |
|
||||
|
||||
具体依赖版本以 [package.json](./package.json) 和 [bun.lock](./bun.lock) 为准。项目虽然包含 TypeScript 依赖,但现有应用主要使用 JS / JSX,`build` 不包含独立类型检查。
|
||||
具体声明与锁定版本见 [package.json](./package.json) 和 [package-lock.json](./package-lock.json)。应用主要使用 JS / JSX,build 不包含独立类型检查。
|
||||
|
||||
## 2. 本地启动
|
||||
|
||||
### 环境准备
|
||||
|
||||
建议使用 Node.js 22 LTS 或 24 LTS,以及支持当前 `bun.lock` 格式的 Bun 1.3.x。仓库没有通过 `engines` 或版本文件强制固定运行时;团队应统一具体版本。
|
||||
使用 Node.js >=22.13.0 和 npm >=10;本次验证为 Node.js 22.23.3 / npm 10.9.9。项目通过 engines 声明要求,packageManager 记录 npm 版本。
|
||||
|
||||
先向后端负责人获取可用的联调地址、测试账号和权限,以及必要的模型/渠道配置。前端仓库没有默认测试账号,也没有完整的离线 Mock 服务。
|
||||
|
||||
```bash
|
||||
git clone --branch weiyuan https://git.weytoken.com/qiubs/monkey-ai-web.git
|
||||
cd monkey-ai-web
|
||||
bun install --frozen-lockfile
|
||||
bun run dev
|
||||
npm ci
|
||||
npm run dev
|
||||
```
|
||||
|
||||
已经拿到本地目录的同学,直接在该目录运行后两条命令即可。
|
||||
|
||||
默认访问 <http://localhost:5173>,端口被占用时以终端实际输出为准。开发服务监听 `0.0.0.0`。默认后端地址为 `http://localhost:3000`,具体代理配置见下一节。
|
||||
默认访问 <http://localhost:5173>,端口被占用时以终端实际输出为准。开发服务监听 `0.0.0.0`。开发代理目标由 `DEV_PROXY_TARGET` 指定,具体代理配置见下一节。
|
||||
|
||||
需要调整功能开关时,将 `.env.example` 复制为 `.env.local`:
|
||||
项目已提供两个自动加载的环境配置,无需复制示例文件:
|
||||
|
||||
```bash
|
||||
# Git Bash / macOS / Linux
|
||||
cp .env.example .env.local
|
||||
```
|
||||
| 命令 | 默认模式 | 配置文件 |
|
||||
| --- | --- | --- |
|
||||
| `npm run dev` | development | `.env.development` |
|
||||
| `npm run build` | production | `.env.production` |
|
||||
| `npm run preview` | 预览已有产物 | 使用构建时已写入的配置,不重新应用环境变量 |
|
||||
|
||||
```powershell
|
||||
# PowerShell
|
||||
Copy-Item .env.example .env.local
|
||||
```
|
||||
个人覆盖配置可写入 `.env.development.local` 或 `.env.production.local`(Git 忽略)。同名变量优先级从高到低:启动终端/CI > `.env.[mode].local` > `.env.[mode]` > `.env.local` > `.env`。旧的 `.env.local` 仍被加载,但与模式文件重名的变量会被模式文件覆盖,请迁移到对应的 `.local` 文件。可通过 Vite 的 `--mode` 显式选择其他模式。
|
||||
|
||||
项目使用 Bun 锁定依赖,ESLint 和国际化脚本也调用 `bunx`,建议统一使用 Bun。修改依赖时同步提交 `package.json` 和 `bun.lock`;不要混用包管理器重新生成依赖树。
|
||||
`.env.example` 原本只是示例,不会被 Vite 自动加载,现已移除。两个环境文件仅存公开默认值,修改后需重启开发服务或重新构建生产产物。
|
||||
|
||||
项目统一使用 npm,提交 package.json 与 package-lock.json。首次安装及 CI 使用 `npm ci`;有意更新依赖时使用 `npm install`,检查并提交锁文件变化。不要使用 Bun 或 Yarn 重新生成另一套锁文件。
|
||||
|
||||
## 3. 后端联调与环境配置
|
||||
|
||||
### 推荐:浏览器同源请求,通过 Vite 代理后端
|
||||
|
||||
保持 [public/config.js](./public/config.js) 中 `SERVER_URL` 为空,也不设置 `VITE_REACT_APP_SERVER_URL`:
|
||||
不设置 `VITE_REACT_APP_SERVER_URL`(或设为空字符串),接口默认使用当前网页域名。
|
||||
|
||||
```js
|
||||
window.__APP_CONFIG__ = {
|
||||
SERVER_URL: '',
|
||||
};
|
||||
```
|
||||
|
||||
[vite.config.js](./vite.config.js) 将下列前缀转发到 `http://localhost:3000`:
|
||||
[vite.config.js](./vite.config.js) 将下列前缀转发到 `DEV_PROXY_TARGET` 指定的后端:
|
||||
|
||||
```text
|
||||
/api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno
|
||||
```
|
||||
|
||||
其中 `/v1` 已启用 WebSocket 代理。连接远程测试后端时,修改所需代理项的 `target`,然后重启开发服务;代理目标目前是写在配置文件中的,**没有读取专用的代理环境变量**。`package.json` 中的 `proxy` 字段不是这里的生效入口。
|
||||
其中 `/v1` 已启用 WebSocket 代理。连接远程测试后端时,修改 `.env.development` 或 `.env.development.local` 中的 `DEV_PROXY_TARGET`,然后重启开发服务。该变量仅供 Vite 代理使用,不暴露给浏览器;默认保留原联调地址 `http://134.175.227.134:13000`。生产部署需由 Nginx/网关配置同源反向代理。`package.json` 中的 `proxy` 字段不是这里的生效入口。
|
||||
|
||||
### 可选:浏览器直接访问独立后端域名
|
||||
|
||||
可以配置运行时文件:
|
||||
|
||||
```js
|
||||
window.__APP_CONFIG__ = {
|
||||
SERVER_URL: 'https://api.example.com',
|
||||
};
|
||||
```
|
||||
|
||||
也可以在 `.env.local` 中配置构建变量:
|
||||
在 `.env.development` / `.env.production` 或对应的 `.local` 覆盖文件中配置构建变量:
|
||||
|
||||
```dotenv
|
||||
VITE_REACT_APP_SERVER_URL=https://api.example.com
|
||||
@@ -98,32 +84,31 @@ VITE_CLOUD_BRAIN_UI_ENABLED=false
|
||||
|
||||
接口根地址由 [src/helpers/config.js](./src/helpers/config.js) 决定,优先级为:
|
||||
|
||||
1. 非空的 `window.__APP_CONFIG__.SERVER_URL`。
|
||||
2. 非空的 `import.meta.env.VITE_REACT_APP_SERVER_URL`。
|
||||
3. 空字符串,使用当前网页域名。
|
||||
1. 非空的 `import.meta.env.VITE_REACT_APP_SERVER_URL`(构建变量)。
|
||||
2. 空字符串,使用当前网页域名(同源)。
|
||||
|
||||
地址填写后端根地址,不要额外添加 `/api`,业务请求会自己带上接口路径。直接连接独立域名时,请求不经过 Vite 的本地代理;后端需要正确配置 CORS、凭证和 Cookie 策略。公共 Axios 实例在根地址非空时启用 `withCredentials`。
|
||||
|
||||
`public/config.js` 在入口模块之前加载,构建后成为 `dist/config.js`。部署时修改这个文件并刷新页面即可切换运行时地址;环境变量则需要重启开发服务或重新构建。运行时地址为空时仍会回退到构建变量,不会强制覆盖为同源模式。
|
||||
已移除 `public/config.js` 及其入口脚本,不再支持部署后直接修改 `dist/config.js` 切换后端。旧部署如依赖该能力,需迁移为构建前设置 `VITE_REACT_APP_SERVER_URL`,或清空该变量后重新构建并配置同源反向代理。开发时修改变量需重启服务,生产时需重新构建并发布;仅修改部署服务器环境变量或刷新页面不会改变已有产物中的地址。
|
||||
|
||||
### 其他配置
|
||||
|
||||
| 配置 | 作用 | 生效方式 |
|
||||
| --- | --- | --- |
|
||||
| `VITE_CLOUD_BRAIN_UI_ENABLED` | 云脑套件入口与路由开关,默认关闭 | 构建时;修改后重启开发服务或重新构建 |
|
||||
| `VITE_UMAMI_WEBSITE_ID` | 启用 Umami 统计脚本注入 | Vite 配置读取进程环境变量 |
|
||||
| `VITE_UMAMI_WEBSITE_ID` | 启用 Umami 统计脚本注入 | Vite 按当前 mode 加载环境文件,终端/CI 优先 |
|
||||
| `VITE_UMAMI_SCRIPT_URL` | Umami 脚本地址 | 同上,默认 `https://analytics.umami.is/script.js` |
|
||||
| `VITE_GOOGLE_ANALYTICS_ID` | 启用 Google Analytics 脚本注入 | 同上 |
|
||||
|
||||
统计脚本插件使用 `process.env`,没有显式调用 Vite `loadEnv`;如果使用 Node/npm 运行 Vite,不要假定只写 `.env.local` 就能让配置文件读到这些统计变量,应由启动终端或 CI 环境注入。
|
||||
统计脚本插件与前端配置共用 Vite 环境加载规则;ID 留空时不注入脚本。生产统计 ID 通常只配置在 `.env.production` 或生产 CI 中。
|
||||
|
||||
前端环境变量和 `config.js` 都会暴露给浏览器,仅放公开配置,不放上游模型密钥或后端机密。
|
||||
前端构建变量会暴露给浏览器,仅放公开配置,不放上游模型密钥或后端机密。
|
||||
|
||||
## 4. 目录与代码入口
|
||||
|
||||
```text
|
||||
monkey-ai-web/
|
||||
├── public/ # 原样复制到构建目录的资源、logo、运行时 config.js
|
||||
├── public/ # 原样复制到构建目录的静态资源、logo
|
||||
├── scripts/ # 国际化提取、翻译整理等辅助脚本
|
||||
├── src/
|
||||
│ ├── index.jsx # React 挂载、语言初始化、全局 Provider
|
||||
@@ -132,8 +117,7 @@ monkey-ai-web/
|
||||
│ ├── components/ # 通用及业务组件,含 layout、auth、settings
|
||||
│ ├── pages/ # 页面和业务模块
|
||||
│ ├── hooks/ # 按业务拆分的数据与交互逻辑
|
||||
│ ├── context/ # User、Status、Theme、Org 等状态
|
||||
│ ├── contexts/ # PlaygroundContext;与 context/ 均为现有目录
|
||||
│ ├── context/ # User、Status、Theme、Org、Playground 等状态
|
||||
│ ├── helpers/ # API 实例、鉴权、配置、主题、通用工具
|
||||
│ ├── services/ # 会话、安全验证等服务封装
|
||||
│ ├── constants/ # 业务常量和接口定义
|
||||
@@ -142,11 +126,11 @@ monkey-ai-web/
|
||||
│ ├── styles/ # 主题 token、企业空间等样式
|
||||
│ └── docs/ # 随前端提供的静态文档内容
|
||||
├── tests/ # 部分 Node 测试,其他测试与源码相邻
|
||||
├── index.html # HTML 入口、启动占位画面、config.js 加载
|
||||
├── index.html # HTML 入口、启动占位画面、入口模块加载
|
||||
├── vite.config.js # 代理、别名、打包拆分
|
||||
├── tailwind.config.js # Tailwind 与品牌色变量映射
|
||||
├── package.json
|
||||
└── bun.lock
|
||||
└── package-lock.json
|
||||
```
|
||||
|
||||
主要启动链路:`index.html` → `src/index.jsx` → `components/layout/PageLayout.jsx` → `App.jsx` → 业务页面。`PageLayout` 拉取 `/api/status`,校验用户会话,并组织全局布局。
|
||||
@@ -210,9 +194,9 @@ monkey-ai-web/
|
||||
当前目录登记了简体中文、繁体中文、英语、日语、韩语、越南语和泰语。虽然存在 `fr.json`、`ru.json`,且提取配置包含这两种语言,但它们没有登记到运行时语言目录,不能据此判断界面已开放法语和俄语。
|
||||
|
||||
```bash
|
||||
bun run i18n:extract
|
||||
bun run i18n:status
|
||||
bun run i18n:lint
|
||||
npm run i18n:extract
|
||||
npm run i18n:status
|
||||
npm run i18n:lint
|
||||
```
|
||||
|
||||
提取和同步可能修改语言包,提交前检查 diff。新增语言除了登记前端目录,还需与后端支持语言列表对齐。
|
||||
@@ -221,33 +205,34 @@ bun run i18n:lint
|
||||
|
||||
| 命令 | 用途 |
|
||||
| --- | --- |
|
||||
| `bun run dev` | 启动开发服务 |
|
||||
| `bun run build` | Vite 生产构建,输出 `dist/` |
|
||||
| `bun run preview` | 预览构建结果,默认端口 4173 |
|
||||
| `bun run test` | 调用 `node --test` 执行现有测试 |
|
||||
| `bun run eslint` | JS / JSX 静态检查 |
|
||||
| `bun run eslint:fix` | 自动修复可修复的 ESLint 问题 |
|
||||
| `bun run lint` | Prettier 格式检查,并非 ESLint |
|
||||
| `bun run lint:fix` | Prettier 全项目格式化,会批量修改文件 |
|
||||
| `bun run i18n:sync` | 同步语言资源结构 |
|
||||
| `npm run dev` | 启动开发服务 |
|
||||
| `npm run build` | Vite 生产构建,输出 `dist/` |
|
||||
| `npm run preview` | 预览构建结果,默认端口 4173 |
|
||||
| `npm run test` | 调用 `node --test` 执行现有测试 |
|
||||
| `npm run check` | 依次执行 ESLint、测试和生产构建,任一步失败即停止 |
|
||||
| `npm run eslint` | JS / JSX 静态检查 |
|
||||
| `npm run eslint:fix` | 自动修复可修复的 ESLint 问题 |
|
||||
| `npm run lint` | Prettier 格式检查,并非 ESLint |
|
||||
| `npm run lint:fix` | Prettier 全项目格式化,会批量修改文件 |
|
||||
| `npm run i18n:sync` | 同步语言资源结构 |
|
||||
|
||||
建议开发分支从 `weiyuan` 创建。提交前执行相关测试、ESLint 和构建,检查登录、修改页面、接口错误提示与移动布局。`bun run build` 只执行 Vite 构建,不会自动执行 ESLint 或测试。
|
||||
建议开发分支从 `weiyuan` 创建。提交前执行相关测试、ESLint 和构建,检查登录、修改页面、接口错误提示与移动布局。`npm run build` 只执行 Vite 构建,不会自动执行 ESLint 或测试。
|
||||
|
||||
当前 ESLint 对 JS / JSX 配置了版权头、未定义标识符、未使用导入和 Hooks 规则,新增文件参考相邻文件的头部格式。
|
||||
|
||||
### 当前交接注意点
|
||||
|
||||
1. **格式化配置存在模块格式问题**:`.prettierrc.mjs` 使用了 `module.exports = require(...)`。按 Node ESM 加载会报 `require is not defined in ES module scope`;使用 Prettier 前需要将配置改为正确的 ESM 写法或调整为合适的 CommonJS 配置形式。本文未修改该配置。
|
||||
2. **构建产物尚未被仓库规则排除**:当前 `.gitignore` 忽略 `/build`,但 Vite 默认输出 `/dist`。构建后提交前检查 `git status`,避免把生成文件提交;团队可后续补充 `/dist` 忽略规则。
|
||||
1. **格式化配置已统一**:`.prettierrc.mjs` 使用 ESM 导出,保留原有单引号规则;`.prettierignore` 排除构建产物与工具缓存。全仓仍有历史格式差异,修改时只格式化涉及的文件,不要为修复业务问题运行全仓 `lint:fix`。
|
||||
2. **构建产物已忽略**:`dist/` 不提交,部署时使用 `npm run build` 生成。
|
||||
3. **历史说明可能落后于代码**:部分子目录 README 仍写着 `web/src/...`,或把已经实现的功能描述成占位页。当前路径应去掉原来的 `web/` 前缀,行为以源码为准。原项目的后端、运维文档和部分注释引用的外部路径不在本仓库中。
|
||||
4. **本次交接未执行安装、构建或完整测试**:本文依据当前源码与配置整理,命令列为开发流程,不代表该版本已经完成环境验收。
|
||||
4. **验证记录**:维护性优化后,179 项测试和生产构建通过,ESLint 无错误但仍有 172 个历史警告,详见 [维护性优化报告](./docs/MAINTAINABILITY_REPORT.md)。
|
||||
|
||||
## 7. 构建与部署
|
||||
|
||||
```bash
|
||||
bun install --frozen-lockfile
|
||||
bun run build
|
||||
bun run preview
|
||||
npm ci
|
||||
npm run build
|
||||
npm run preview
|
||||
```
|
||||
|
||||
将 `dist/` 作为静态站点发布,部署环境需处理:
|
||||
@@ -255,7 +240,7 @@ bun run preview
|
||||
- **路由回退**:本项目使用 BrowserRouter。直接访问 `/org/...` 等页面时,静态服务器需回退到 `index.html`,否则刷新会返回 404。
|
||||
- **接口转发**:生产环境配置实际的反向代理或独立后端地址。Vite 的开发代理不会打包进静态文件;`preview` 仅供本地预览,不能代替生产网关。
|
||||
- **实时响应**:使用 SSE 的接口需要关闭响应缓冲并设置合理超时;使用 WebSocket 时配置连接升级转发。
|
||||
- **配置缓存**:`config.js`、`index.html` 应允许及时更新,带哈希的静态资源可以使用长缓存。
|
||||
- **发布与缓存**:`index.html` 应允许及时更新,带哈希的静态资源可以使用长缓存。后端构建变量包含在产物中,切换地址需重新构建并发布配套 HTML 与资源,不再有独立 `config.js` 缓存。
|
||||
- **部署路径**:当前按域名根路径部署,资源和路由包含根路径引用。部署到子目录需另行检查 Vite `base`、路由和静态资源地址。
|
||||
|
||||
仓库中的 `vercel.json` 目前只有 GitHub 通知设置,没有配置 SPA 路由回退或后端代理,不能视为完整部署配置。
|
||||
@@ -267,11 +252,11 @@ bun run preview
|
||||
| 页面可打开,但提示无法加载状态或接口失败 | 后端是否可用;Network 中 `/api/status` 的目标地址与响应;Vite 代理是否正确 |
|
||||
| 登录后仍回到登录页 | `/api/user/self`、Cookie 是否发送、跨域凭证策略,以及测试账号状态 |
|
||||
| 企业数据为空或串到其他企业 | 当前组织选择、`current_org_id` 与请求中的 `X-Org-Id` |
|
||||
| 修改环境变量后无变化 | 是否重启开发服务或重新构建;`config.js` 是否覆盖环境变量;浏览器缓存 |
|
||||
| 修改环境变量后无变化 | 是否重启开发服务或重新构建并发布;构建时的变量值;HTML 与静态资源缓存 |
|
||||
| 云脑相关菜单找不到 | `VITE_CLOUD_BRAIN_UI_ENABLED`、后台模块开关和当前账号权限 |
|
||||
| 线上子页面刷新 404 | 静态服务器是否设置 SPA 回退,且接口路径没有误回退到 HTML |
|
||||
| 对话内容等到结束才一次性显示 | SSE 响应、反向代理缓冲和超时设置 |
|
||||
| 格式检查报 `require` / `module` 未定义 | 上述 `.prettierrc.mjs` 模块格式问题 |
|
||||
| 修改品牌后仍看到旧 Logo 或颜色 | 后端品牌设置、主题本地缓存以及 `config.js` / 静态资源缓存 |
|
||||
| 格式检查提示大量 Code style issues | 全仓仍有历史格式差异;保留统一配置,只格式化本次修改文件 |
|
||||
| 修改品牌后仍看到旧 Logo 或颜色 | 后端品牌设置、主题本地缓存以及 HTML / 静态资源缓存 |
|
||||
|
||||
首次联调建议依次确认:开发服务启动 → `/api/status` 正常 → 登录与 `/api/user/self` 正常 → 业务页面读取数据 → 选择已配置的测试模型验证对话。接口字段和业务权限问题需与后端负责人共同确认。
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
# 维护性优化报告
|
||||
|
||||
日期:2026-10-21
|
||||
|
||||
## 目标与边界
|
||||
|
||||
在保持现有页面、路由、接口和有效持久化数据兼容的前提下,提取重复规则、降低模块耦合、修复已确认的问题,并补充可执行回归测试。未升级依赖、迁移技术栈、调整 UI 或重写核心业务流程。
|
||||
|
||||
“无法优化”没有可客观证明的终点。本轮以已识别的低风险优化完成、相关测试与构建通过、独立复查未发现新增正确性问题为停止条件,不把缺少业务环境验证的重构视为安全优化。
|
||||
|
||||
## 已完成的改动
|
||||
|
||||
### 1. 通用存储解析与表格紧凑模式
|
||||
|
||||
- 新增 `src/helpers/storageJson.js`,统一处理 JSON 解析、数组/对象形状校验和存储读取失败;每次返回独立的默认容器,不共享可变状态。
|
||||
- 新增 `src/helpers/tableCompactMode.js`,将表格偏好从依赖 React/UI 的 `utils.jsx` 中分离,读取与跨标签页事件使用相同解析规则。
|
||||
- `utils.jsx` 保留原有导出,旧调用方无需迁移;存储键、每个表格的独立设置和有效值的真假判断保持兼容。
|
||||
- 紧凑模式写入失败仍为尽力保存,不阻止本页面切换。非法跨标签页值现在统一恢复为默认非紧凑模式,而不是保留过期状态。
|
||||
|
||||
### 2. 通知已读状态
|
||||
|
||||
- 新增 `src/helpers/notificationReadState.js`,集中公告标识、未读列表、已读合并和持久化规则。
|
||||
- `useNotifications` 的未读数量来自未读列表,避免两套独立筛选逻辑;稳定空公告数组和回调依赖,消除该处 Hooks 警告。
|
||||
- 保持“发布日期 + 内容前 30 字符”的既有公告标识、重复公告计数、已读历史和关闭通知的处理顺序。
|
||||
- 非法或非数组存储数据按未读处理;写入失败仍向上传播,不假装持久化成功。
|
||||
|
||||
### 3. 日志列偏好
|
||||
|
||||
- 新增 `src/helpers/columnVisibility.js`,由用量日志和任务日志共同使用,复用统一存储解析器。
|
||||
- 合并顺序为:当前默认列 → 已保存的合法布尔值 → 强制隐藏列。
|
||||
- 新增列获得默认值,显式 `false` 保留;未知列和非法字段值被忽略,非管理员不能通过本地偏好显示管理员专属列。
|
||||
- 保留两种日志各自的存储键、默认列、重置/全选行为和接口请求。
|
||||
- 未扩大为通用数据 Hook,避免把不同业务表格的请求与生命周期强行统一。
|
||||
|
||||
### 4. 企业用量筛选参数
|
||||
|
||||
- 新增 `src/helpers/orgLogFilters.js`,明细、汇总、排行复用用户、时间和模型筛选字段的接口映射。
|
||||
- 分页、排行数量和绕过缓存参数继续由具体接口管理,不混入共享筛选参数。
|
||||
- 保留原有空值/零值省略规则;没有修改请求代次控制、组织请求头或明细 `total=-1` 时保留已知总数的行为。
|
||||
|
||||
### 5. 用户管理分页与错误状态
|
||||
|
||||
- 修复修改每页条数时已将页面设为 1、却用旧页码发请求的问题;现在统一调用 `refresh(1, size)`。
|
||||
- 翻页、调整每页条数和刷新复用相同请求路径,保留当前表单筛选条件,不再在调整条数后丢失搜索。
|
||||
- 用户搜索通过 Axios `params` 编码,防止 `&`、`+`、`#` 等字符改变查询含义。
|
||||
- `loadUsers` / `searchUsers` 使用 `finally` 复位加载状态;翻页入口处理请求拒绝,避免一直显示加载或未处理的 Promise 拒绝。
|
||||
- 保留现有导出接口、首次请求的 page=0 约定及空筛选回退行为。
|
||||
- 浏览器验收发现 Semi 调整每页条数后还会自动触发页码回调,从第 3 页的 10 条改为 20 条时,会额外请求第 2 页的旧 10 条,覆盖正确结果。已在通用分页工厂增加默认关闭的 `preventPageChangeOnPageSizeChange` 选项,仅用户列表启用;由用户列表的条数处理函数负责重置第 1 页,其他表格行为不变。
|
||||
|
||||
### 6. 开发检查工具
|
||||
|
||||
- 将 `.prettierrc.mjs` 改为有效的 ESM,删除 `package.json` 中重复的 Prettier 配置,并保留原先实际生效的单引号选项。原先 package.json 配置优先命中,掩盖了 `.mjs` 的加载错误。
|
||||
- 新增 `.prettierignore`,排除构建产物、覆盖率和工具缓存,不屏蔽业务源码的历史格式问题。
|
||||
- 补齐 `public/config.js` 和两个既有测试文件的标准许可证头,清除 3 个 ESLint 错误,不禁用规则。
|
||||
- 修复 `scripts/translated_ja.json` 缺少结束括号导致的 JSON 语法错误,没有修改翻译内容或补造缺失翻译。
|
||||
- 新增 `npm run check`,依次执行 ESLint、测试和生产构建;任一步失败即停止。该命令不代表全仓格式检查、浏览器测试或类型检查通过。
|
||||
- 同步 README 和项目分析中的过期说明;依赖清单版本及锁文件保持不变。
|
||||
|
||||
## 验证结果
|
||||
|
||||
环境:Windows 10 / Git Bash,Node.js 22.23.3,npm 10.9.9。
|
||||
|
||||
| 检查 | 优化前 | 优化后 |
|
||||
| --------------------------------- | ---------------------------------------- | ------------------------------------------- |
|
||||
| `npm test` | 128 通过,0 失败 | 179 通过,0 失败;新增 51 项 |
|
||||
| `npm run eslint` | 3 错误,173 警告;退出 1 | 0 错误,172 警告;退出 0 |
|
||||
| `npm run build` | 通过,有大 chunk 告警 | 通过,仍有大 chunk 告警 |
|
||||
| `npm run check` | 无统一入口 | 通过,包含上述三项 |
|
||||
| `npm run lint` | 因 JSON 语法错误退出 2,另有历史格式差异 | 不再有解析/配置错误;仍因历史格式差异退出 1 |
|
||||
| 已修改的 JS/JSX/MJS/JSON 格式检查 | — | 通过 |
|
||||
| 仓库已跟踪及非忽略的 JSON 解析 | — | 33 个文件全部可解析 |
|
||||
| `git diff --check` | — | 通过 |
|
||||
| 独立 code review | — | 未发现本次改动新增的正确性问题 |
|
||||
|
||||
新增测试分布:
|
||||
|
||||
- `src/helpers/storageJson.test.js`:18 项,覆盖存储异常、通知标识/合并、紧凑模式独立设置和失败策略。
|
||||
- `src/helpers/columnVisibility.test.js`:12 项,覆盖默认值合并、非法值、角色限制及输入不变性。
|
||||
- `src/helpers/orgLogFilters.test.js`:4 项,覆盖字段映射、省略规则、端点隔离和输入不变性。
|
||||
- `src/hooks/users/useUsersData.test.js`:13 项,执行真实 Hook 导出的分页/搜索处理函数,并使用 Axios 实际序列化逻辑验证参数;React 状态与 effect 通过轻量测试替身驱动。
|
||||
|
||||
- `tests/users-pagination.test.js`:4 项,执行已安装 Semi 的真实分页 foundation,验证用户列表接线、桌面/移动端调整条数只触发一次回调、后续翻页可用,以及其他表格的默认行为保持不变。
|
||||
|
||||
上述 Node 测试不模拟完整 React 调度、StrictMode、DOM 或后端权限,不能替代浏览器和真实后端验收。
|
||||
|
||||
生产构建的 `/`、`/login`、`/org/login`、`/console/user`、`/config.js` 已通过 HTTP 冒烟:均返回 200,HTML 有 React root 和可访问的生产入口 JS。
|
||||
|
||||
### 提交前浏览器验收
|
||||
|
||||
使用 Chrome 155.0.8059.85 headless、独立浏览器上下文和生产预览的随机本地端口;桌面视口 1440×900,移动视口 390×844,DPR=1,语言 zh-CN。Playwright 工具安装在系统临时目录,不改项目依赖或锁文件。所有业务 API 由本地 fixture 拦截,外部请求阻断,没有接触真实用户会话或执行后端写入。
|
||||
|
||||
以下场景通过真实点击、输入和网络请求观察验收:
|
||||
|
||||
1. 用户管理页加载,已查看桌面及移动端截图,列表和操作区正常渲染。
|
||||
2. 搜索 `alice & bob+#?=user`,翻到第 3 页后改为每页 20 条:只发出一次第 1 页、20 条的请求,搜索参数完整保留,显示 20 行。修复前实际复现了旧条数的第二次请求;修复后通过。
|
||||
3. 两个标签页之间双向切换紧凑模式,当前页立即更新,另一页通过真实 storage 事件同步。
|
||||
4. 非数组的通知已读存储可恢复,打开通知并点击“我知道了”后写入兼容格式的已读键。
|
||||
5. 移动端列表可见,点击“显示操作项”后可操作搜索控件。
|
||||
6. 分页接口主动返回 HTTP 503 后加载状态复位;恢复接口后点击查询成功。未出现未处理的 Promise 拒绝。
|
||||
|
||||
最终浏览器复验没有 pageerror 或非预期 console error;主动注入的 503 产生预期网络/Axios 错误日志。最初调试中的选择器不匹配、缺少 fixture 字段已在测试脚本中修正,没有为测试修改业务返回值。真实登录、权限与线上后端仍未验收。
|
||||
|
||||
本地浏览器验收脚本、结果和截图位于系统临时目录 `monkey-ai-acceptance-A0u9pq`,不纳入应用产物;防回归的 4 项 Semi 分页测试已纳入仓库。按用户要求删除不再保留的 npm 迁移和性能历史报告,并清理其失效引用。
|
||||
|
||||
## 保留的风险与后续工作
|
||||
|
||||
- 172 个历史 ESLint 警告仍需按具体场景处理。没有批量补 effect 依赖、禁用规则或修改告警级别,避免引入重复请求与循环渲染。
|
||||
- 全仓仍有数百个文件的历史格式差异。仅格式化涉及的代码,不用大面积格式变动掩盖业务差异。
|
||||
- 大 chunk 告警仍在;拆包、图标和可视化依赖优化需要浏览器加载与缓存证据,不能凭构建耗时宣称页面性能提升。
|
||||
- 真实登录、企业切换、后端权限及业务接口仍需在可用测试环境验收;本地 fixture 浏览器结果不代表真实后端联调通过。
|
||||
- 本轮没有实施全局异步请求竞态治理、统一所有数据 Hook、依赖升级或大型页面拆分。这些改变影响范围较大,需要明确业务契约和更完整的集成测试。
|
||||
|
||||
建议日常运行 `npm run check`;涉及页面改动时同时验证浏览器场景,对本次编辑的文件执行 `npx prettier <文件列表> --check`。不要将这份报告理解为整个项目已无缺陷或不存在进一步优化空间。
|
||||
@@ -0,0 +1,374 @@
|
||||
# 前端模块化改造:可行性评审与渐进实施方案
|
||||
|
||||
> 整理日期:2026-10-27。面向项目维护者、新接手开发者和技术负责人。
|
||||
> 配套导读:[页面渲染、路由与 API 调用链分析](./RENDER_ROUTING_API_REFACTOR.zh-CN.md)。本文集中说明改造决策、实施步骤和验收要求;源码依据及行号基准为 `weiyuan` 分支、提交 `821577f`。
|
||||
> 本次交付是源码评审与实施设计,不是已完成的重构。未修改应用代码,未执行测试、构建或浏览器验收;历史测试记录不代表本次验证结果。后端授权规则未在本次前端仓库评审中验证。
|
||||
|
||||
## 1. 决策摘要
|
||||
|
||||
**建议批准“保行为的顶层路由模块化”,有条件推进“用户查询 service 试点”;暂不批准全站目录重排、统一守卫、布局重构和 HTTP 客户端重写。**
|
||||
|
||||
采用沿用 React Router、保持已有 URL 与权限、按业务拆分路由、渐进建立领域接口边界的路线。实施以可核对的行为基线和分批验收为前提,不将目录调整等同于维护性提升。
|
||||
|
||||
| 维度 | 评估 | 决策依据 |
|
||||
| ------------------ | -------------- | -------------------------------------------------------- |
|
||||
| 技术可行性 | 高 | 当前 Router 可支持 RouteObject/useRoutes,无须迁移技术栈 |
|
||||
| 首期维护收益 | 明确,但局部 | 路由归属和策略入口更清晰;不会自动解决大型业务页面可读性 |
|
||||
| 行为回归风险 | 中高 | 企业限制、动态权限、认证时序、key、重定向相互影响 |
|
||||
| 新人独立一次性交付 | 不建议 | 隐性规则需要维护者/产品确认,不能靠代码推断业务意图 |
|
||||
| 后端依赖 | 首期无需改接口 | 仍需测试账号、配置样本和真实会话联调支持 |
|
||||
| 性能收益 | 不承诺 | 拆文件不是性能优化,构建及请求行为需单独观察 |
|
||||
|
||||
**首期完成的定义:一个新人能准确找到路由、权限和用户查询入口,且原行为通过对照验证;不是 App 行数下降,也不是所有模块都有 service。**
|
||||
|
||||
## 2. 当前问题:不是缺少分层,而是边界不稳定
|
||||
|
||||
现有用户列表已经具备:
|
||||
|
||||
```text
|
||||
App 路由 → User 页面 → UsersTable → useUsersData → API
|
||||
```
|
||||
|
||||
因此,不需要推翻重建 MVC、引入 Redux 或把全部文件搬到 features。当前主要成本是:
|
||||
|
||||
| 问题 | 源码证据 | 实际维护成本 |
|
||||
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
|
||||
| 路由声明与业务访问策略混合 | [App.jsx](../src/App.jsx#L105-L231) | 新增页面前要理解企业放行、动态配置、守卫等多套规则 |
|
||||
| URL 前缀不等于权限边界 | [App.jsx](../src/App.jsx#L317-L348) | `/console` 下同时存在登录、Admin、Root 三种权限 |
|
||||
| 布局规则独立依赖路径字符串 | [PageLayout.jsx](../src/components/layout/PageLayout.jsx#L94-L131) | 新路由可能匹配页面却漏配滚动、侧栏和顶栏 |
|
||||
| 布局承担会话与站点初始化 | [PageLayout.jsx](../src/components/layout/PageLayout.jsx#L193-L254) | 搬布局会间接改变请求时机和会话恢复 |
|
||||
| 守卫等待条件并非完全相同 | [auth.jsx](../src/helpers/auth.jsx#L59-L142) | 表面相似的包装不能直接统一 |
|
||||
| service 已存在但契约不一致 | [playgroundConversation.js](../src/services/playgroundConversation.js)、[secureVerification.js](../src/services/secureVerification.js) | 不能按“从零建立统一层”机械迁移 |
|
||||
| 公共 API 包含业务逻辑及登录副作用 | [api.js](../src/helpers/api.js)、[loginFlow.js](../src/helpers/loginFlow.js#L41-L58) | 移动入口可能捕获旧实例或改变错误处理 |
|
||||
|
||||
这是一项**职责整理与行为显式化工程**,不是换框架工程。对新人而言,减少“为改一个功能必须了解全站规则”的成本,比减少文件数量更重要。
|
||||
|
||||
## 3. 技术选型与关键约束
|
||||
|
||||
### 3.1 设计原则
|
||||
|
||||
- 保留现有 BrowserRouter 和 Provider 层级。
|
||||
- 以模块化 RouteObject + `useRoutes` 为目标,不为拆文件迁移 Data Router。
|
||||
- lazy 声明放在模块顶层,不放进组件或路由工厂。
|
||||
- 复用现有 PrivateRoute、AdminRoute、RootRoute,不按 URL 前缀套统一权限。
|
||||
- 首期不搬 pages/components/hooks,不改变页面业务状态归属。
|
||||
- 企业限制先原样提取、测试,再讨论简化。
|
||||
- service 首轮保持 Axios response,不全局修改拦截器返回结构。
|
||||
- 保留不同网络传输方式,不把 Fetch/SSE 强行收敛到普通 Axios 请求。
|
||||
|
||||
### 3.2 行为兼容约束
|
||||
|
||||
#### A. “等待认证完成”的描述不能一概而论
|
||||
|
||||
当前 `PrivateRoute` 先判断 `userState.user`,已有用户时直接渲染;`AdminRoute`、`RootRoute` 则先检查“未完成认证且有缓存”。`AuthRedirect` 同样先判断当前用户。
|
||||
|
||||
因此,对“Context 已有用户、authChecked=false、本地仍有缓存”这个输入,不同守卫可能表现不同。不能将其概括为“所有守卫都等待认证完成”。
|
||||
|
||||
**实施要求:分别锁定各守卫的判断顺序,不在模块化 PR 中统一。** 是否应调整为统一等待,是独立的会话策略决策,需要考虑公共页、已登录导航及服务端会话校验,不等同于发现了可直接修复的漏洞。
|
||||
|
||||
#### B. 64 条声明不等于 64 个测试用例
|
||||
|
||||
分析基准中的顶层声明数量可用于检查迁移遗漏,但不能覆盖动态配置、角色、认证中间态、内部子路由、旧地址与具体通配匹配关系。
|
||||
|
||||
应建立“路由清单 + 策略矩阵 + 关键导航序列”三类基线。不能通过检查路径数量相等就认定迁移正确。
|
||||
|
||||
#### C. API 重建有会话隔离用途,不只是重装配置
|
||||
|
||||
`loginFlow.js` 在设置登录用户后调用 `updateAPI()`。新实例拥有新的在途请求集合,避免新会话直接复用旧实例中的请求。
|
||||
|
||||
service 必须在函数调用时读取 `API` 的 live binding,不能模块顶层保存 `const client = API` 或绑定 `API.get`。重建实例不等于取消旧请求,也不能据此认为旧结果回写问题已经解决。
|
||||
|
||||
### 3.3 路由方案比较
|
||||
|
||||
| 方案 | 优点 | 代价与结论 |
|
||||
| --------------------------------------- | -------------------------------- | ---------------------------------------------------- |
|
||||
| A:按业务提取 JSX 路由片段 | 最接近现有实现,便于逐行对照 | 可以作为长期方案,但重复包装仍需维护 |
|
||||
| B:RouteObject + useRoutes | 路径与元素配置集中,易按模块组合 | **本方案选择**;保留现有 BrowserRouter 与守卫 |
|
||||
| C:createBrowserRouter + RouterProvider | 支持路由级 loader/action | 涉及上下文和数据生命周期迁移,不是本次拆分的必要条件 |
|
||||
|
||||
迁移至 B 时,用 `createRoutesFromElements` 临时承接旧声明,再逐模块替换为对象,不必先完成一次全量 JSX 拆分。不要使用 `<Routes><ConsoleRoutes /></Routes>` 注册自定义路由组件:Routes 接收的声明应为 Route 或 Fragment,而不是等待自定义组件渲染出的 Route。
|
||||
|
||||
本期无需升级 Router。未来若采用 Data Router,应明确最低依赖版本;当前锁定版本支持相关 API,不代表声明下界 `^6.3.0` 已保证 6.4+ 能力。
|
||||
|
||||
## 4. 范围与不做事项
|
||||
|
||||
### 首期范围
|
||||
|
||||
1. 顶层路由行为清单与高风险用例。
|
||||
2. 企业访问策略的纯函数提取及测试。
|
||||
3. 顶层路由按业务拆分,保留既有守卫、lazy、Suspense、key 和跳转。
|
||||
4. 用户列表与搜索 API 的独立试点,在路由变更稳定后提交。
|
||||
5. 更新新人开发指南和模块维护约定。
|
||||
|
||||
### 明确不做
|
||||
|
||||
- 不升级 Router,不引入 Data Router、查询缓存库或全仓 TypeScript。
|
||||
- 不移动全站目录,不自动生成菜单,不建设通用权限 DSL。
|
||||
- 不改企业内部权限、不重排 Provider、不迁移启动副作用。
|
||||
- 不改分页页码、错误提示规则、取消语义和去重算法。
|
||||
- 不改体验中心未知路径行为、不统一 `/` 与 `/home` 布局。
|
||||
- 不声称解决所有大组件和复杂 Hook;相关问题另建治理清单。
|
||||
|
||||
## 5. 目标结构及依赖规则
|
||||
|
||||
```text
|
||||
src/
|
||||
App.jsx # 保留 SetupCheck、企业限制与路由出口的顺序
|
||||
router/
|
||||
AppRoutes.jsx # useRoutes,仅消费路由配置
|
||||
createAppRoutes.jsx # 组装;不发请求、不持有业务状态
|
||||
modules/
|
||||
console.routes.jsx
|
||||
public.routes.jsx
|
||||
auth.routes.jsx
|
||||
account.routes.jsx
|
||||
organization.routes.jsx
|
||||
experience.routes.jsx
|
||||
client.routes.jsx
|
||||
legacy.routes.jsx
|
||||
policy/
|
||||
useRoutePolicy.js # Context/现有成员 Hook 的适配
|
||||
orgAccessPolicy.js # 无 React、无存储、无网络的纯判断
|
||||
services/
|
||||
users.js # 首批仅用户列表与搜索
|
||||
pages/ # 原位置不变
|
||||
hooks/ # 原位置不变
|
||||
helpers/api.js # 首期保留
|
||||
```
|
||||
|
||||
目录逐批创建,不提前铺空文件。企业认证路径归 auth,而非仅按 `/org` 前缀归企业工作区。
|
||||
|
||||
### 职责合同
|
||||
|
||||
| 层 | 可以做 | 不应做 |
|
||||
| -------------- | ------------------------------------- | ------------------------------------ |
|
||||
| router/modules | 声明路径、页面、原有守卫/开关/边界 | 发业务请求、维护列表状态 |
|
||||
| policy Hook | 读取 Context 和现有成员状态,组织输入 | 另建一套用户缓存、改变初始化时机 |
|
||||
| policy 纯函数 | 根据输入返回放行/限制结果 | 读 localStorage、调用 Hook、执行导航 |
|
||||
| 页面与业务组件 | UI 组合与事件接线 | 为同一领域重复拼接口协议 |
|
||||
| 业务 Hook | loading、筛选、分页、业务失败反馈 | 创建第二个 HTTP 客户端 |
|
||||
| service | 方法、URL、参数、原样响应/拒绝 | toast、路由跳转、React state |
|
||||
| HTTP 客户端 | 地址、凭证、拦截器、在途去重 | 感知用户表格页码等领域 UI |
|
||||
|
||||
新代码优先直接导入具体模块;不新增全项目聚合出口,不为了“少写 import”隐藏依赖。已有导入暂不全仓修改。
|
||||
|
||||
## 6. 路由迁移设计
|
||||
|
||||
### 6.1 先建立可比较的契约
|
||||
|
||||
建议建立 `docs/ROUTE_CONTRACT.zh-CN.md`,每条声明记录:
|
||||
|
||||
- path、所属模块、目标组件或重定向目标。
|
||||
- 守卫类型及包装顺序,包含功能关闭时是否仍经过守卫。
|
||||
- 动态条件与默认值来源。
|
||||
- Suspense 是否存在、key 是否使用 pathname。
|
||||
- replace、query/hash 保留策略、OAuth provider type。
|
||||
- 是否后代 Routes 入口、具体路径与通配入口的关系。
|
||||
- 当前布局规则及验证状态。
|
||||
|
||||
清单依据旧代码独立建立并评审,不由新路由表生成后反过来证明自己正确。运行时路由表仍只有一份,文档不参与运行时权限判断。
|
||||
|
||||
### 6.2 分批迁移但保持同一棵匹配树
|
||||
|
||||
1. 先引入 `useRoutes(createRoutesFromElements(原有声明))`,不改元素内容。
|
||||
2. 保留旧声明转换出的剩余路由对象,逐批与新模块数组合并,交给同一个 useRoutes。
|
||||
3. 每迁移一个 path,同一提交中删除对应旧声明;不允许新旧重复注册。
|
||||
4. 每批检查 catch-all 唯一、具体路径不丢失、后代入口仍有 `/*`。
|
||||
5. 全量迁移后删除临时转换层。
|
||||
|
||||
不创建第二个 BrowserRouter,不长期维护两个并行路由系统。工厂函数只组合元素,不调用 Hook;Hook 在稳定组件顶层调用。
|
||||
|
||||
App 的企业限制可继续在子组件 AppRoutes 挂载前返回 Navigate,从而保留原有“受限时不渲染路由出口”的组织方式。不要把 useRoutes 放在同一组件的条件 return 后面。
|
||||
|
||||
### 6.3 第一批选择控制台的三种权限代表
|
||||
|
||||
从 `/console/user`、`/console/my-commission`、`/console/commission` 开始,分别验证 Admin、Private、Root。试点通过后再迁移其余控制台、公共/认证、企业/体验入口、兼容路由。
|
||||
|
||||
迁移必须保留以下反例:
|
||||
|
||||
- 不能给全部 `/console` 路由加 Admin 父守卫。
|
||||
- `/login` 是 Suspense 外包 AuthRedirect,不能为整齐擅自倒置。
|
||||
- `/user-center/*` 没有 pathname key,不能统一加 key。
|
||||
- OAuth OIDC 分支与其他回调的 key 配置有差异。
|
||||
- 云脑开关关闭时部分路径直接跳转,不应无意新增鉴权步骤。
|
||||
- `/pricing` 保留 query/hash,其他旧跳转不能默认照搬这个策略。
|
||||
|
||||
### 6.4 抽象的停止条件
|
||||
|
||||
首轮允许保留重复 JSX。只有多条路由经验证确实具备相同包装顺序和重挂载规则,才提取公共包装。
|
||||
|
||||
不以 `auth: true` 替代全部访问语义,不把复杂条件塞进万能 Guard。更短但更隐晦的代码不是本次目标。
|
||||
|
||||
### 6.5 企业策略提取边界
|
||||
|
||||
| 提取对象 | 目标位置 | 必须保留的行为 |
|
||||
| ------------ | -------------------------- | ------------------------------------------------------------ |
|
||||
| 模块登录配置 | useRoutePolicy | HeaderNavModules 的默认值与 requireAuth 解析 |
|
||||
| 企业路径放行 | orgAccessPolicy | 精确路径或 `prefix + '/'`,不能扩大为裸 startsWith |
|
||||
| orgConfined | 纯函数判断与 Hook 输入适配 | 成员未加载不提前重定向;企业中心关闭不形成跳转循环 |
|
||||
| 企业顶栏例外 | 纯策略函数 | 顶栏配置入口、tutorial/recharge 开关与企业管理员技能超市例外 |
|
||||
|
||||
先原样提取再测试,不新增全站阻塞等待,也不改变成员查询 Hook 的调用条件。菜单显示、路由放行和后端授权是不同边界,不能相互替代。
|
||||
|
||||
## 7. 用户查询 API 试点
|
||||
|
||||
### 7.1 契约
|
||||
|
||||
新增 users service,仅封装列表和搜索;保持完整 Axios response。示意:
|
||||
|
||||
```js
|
||||
import { API } from '../helpers/api';
|
||||
|
||||
export function listUsers({ page, pageSize }) {
|
||||
return API.get(`/api/user/?p=${page}&page_size=${pageSize}`);
|
||||
}
|
||||
|
||||
export function searchUsers({ page, pageSize, keyword, group }) {
|
||||
return API.get('/api/user/search', {
|
||||
params: { keyword, group, p: page, page_size: pageSize },
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
保留 URL 形式是为了不同时改变 GET 去重 key。service 不包装 AxiosError,不加 toast,不默认设置 skipErrorHandler,不捕获旧 API 实例。
|
||||
|
||||
Hook 继续负责:初次 `p=0`、修改页大小后回到第 1 页、空筛选回退、success 判断、数据格式化及 loading。分组接口可暂保留原调用并登记待迁移;不为两条查询强建通用 repository。
|
||||
|
||||
### 7.2 不扩大首批范围
|
||||
|
||||
新增/编辑用户弹窗、邀请列表、用户管理写操作、2FA/Passkey 重置另批迁移。完成本次试点只能说“用户查询接口已集中”,不能说“用户模块已完成 service 化”。
|
||||
|
||||
后续再评估统一领域返回值。若改为返回业务 data,必须说明业务失败如何表达、HTTP 错误是否保持、提示由谁负责,并一次迁移完整的一组消费者;不全局修改 Axios 拦截器。
|
||||
|
||||
### 7.3 既有问题单独登记
|
||||
|
||||
| 问题 | 处理原则 |
|
||||
| ----------------------------------- | --------------------------------------------- |
|
||||
| 全局拦截器与局部 catch 可能重复提示 | 单独定义错误所有权;首轮不新增提示层 |
|
||||
| 不同搜索请求的旧结果可能覆盖新结果 | 独立修复请求序号/取消策略,不能声称去重已解决 |
|
||||
| 去重 key 不含所有请求选项 | 不在抽 service 时擅自扩大取消和参数标准化范围 |
|
||||
| Hook 格式化会修改响应对象 | 独立评估共享响应的可变性,不混入纯搬迁 |
|
||||
| 部分写操作失败后的 loading 恢复 | 独立缺陷修复,避免扩成用户管理全量重写 |
|
||||
|
||||
这些是后续验证与治理项,不表示本次已复现线上故障。
|
||||
|
||||
## 8. 测试与验收门禁
|
||||
|
||||
### 8.1 先承认现有测试边界
|
||||
|
||||
当前 `npm test` 使用 Node 内置测试运行器。用户 Hook 测试通过转译和 VM/替身执行;分页测试不是浏览器测试;去重 key 测试不等于真实 Axios 并发行为测试。
|
||||
|
||||
抽取 service 后需同步调整 Hook harness,并增加 service 请求契约测试,不能把新 import 全部 mock 成固定成功结果,导致原参数测试失效。
|
||||
|
||||
路由组件测试建议补充 Vitest + React Testing Library/jsdom,作为独立脚本,不替换现有 Node 测试。引入时核对当前 Vite/React 的兼容版本,明确测试文件匹配范围,避免两个 runner 重复收集。测试设施应单独提交。
|
||||
|
||||
### 8.2 最低覆盖矩阵
|
||||
|
||||
| 测试层 | 必须验证 | 验证手段 |
|
||||
| -------- | ---------------------------------------------------------------- | ----------------------------------------- |
|
||||
| 纯策略 | 企业中心开/关、成员未加载/已加载、管理员例外、额外路径、前缀碰撞 | node:test,表驱动 |
|
||||
| 路由匹配 | 原路径完整、重复声明、具体路径优先于通配、未知路径 | 生产路由对象及 Router 匹配测试 |
|
||||
| 守卫渲染 | 游客、普通用户、role=10、role=100、非数字 role、缓存校验中 | MemoryRouter + 真实守卫 + fixture Context |
|
||||
| 特殊导航 | query/hash、replace、OAuth type、开关关闭后的目标 | 组件路由测试及浏览器核对 |
|
||||
| 生命周期 | 有 key 与无 key 的代表路径、参数变化、前进后退 | 挂载计数探针;真实页面观察 effect/请求 |
|
||||
| service | 方法、URL、参数编码、完整响应、原样 reject、API 实例替换 | 真实 service + 可控客户端替身 |
|
||||
| 用户查询 | 初始页、搜索、空搜索、页大小、刷新、业务失败、网络失败后状态复位 | 保留现有专项测试并补充 |
|
||||
| 浏览器 | 深链接刷新、回跳、侧栏/滚动/抽屉、请求次数 | 可复现人工步骤或自动化浏览器测试 |
|
||||
|
||||
不做所有维度的笛卡尔积;覆盖每条路由基础映射,对权限/动态策略做重点组合。特别要测“Context 有用户但 authChecked=false”与“仅缓存有用户”的区别。
|
||||
|
||||
### 8.3 每个 PR 的退出条件
|
||||
|
||||
- 迁移路径有旧/新契约对照,所有差异都有明确说明。
|
||||
- 修改文件格式检查、ESLint、定向测试通过。
|
||||
- 合并前运行 `npm run check` 和 `git diff --check`,记录命令、提交及结果。
|
||||
- 历史告警与新增告警分开记录,不能用历史通过记录替代本批测试。
|
||||
- 高风险身份路径通过浏览器验证;mock 验证与真实后端验证分开标注。
|
||||
- 若无真实测试账号,标记为“待联调”,不能验收权限相关发布。
|
||||
|
||||
`npm run lint` 在本项目中是全仓格式检查,不应误认为 ESLint。实施时以 package.json 实际脚本为准,不为了过格式门禁顺手格式化整个仓库。
|
||||
|
||||
## 9. 实施计划、成本和协作
|
||||
|
||||
以下是规划估算,不是交付承诺。假设一名实施开发者、一名熟悉业务的维护者参与评审,具备可用环境和角色账号;不含排队等待及未知缺陷修复。
|
||||
|
||||
| 批次 | 交付内容 | 估算人日 | 退出条件 |
|
||||
| ---- | ---------------------------------------------- | -------- | ---------------------------- |
|
||||
| P0 | 路由契约、账号/配置矩阵、风险清单 | 1.5~2 | 维护者确认关键访问规则 |
|
||||
| P1 | 路由测试设施、关键守卫/策略特征测试 | 1.5~2.5 | 重构前测试可复现当前行为 |
|
||||
| P2 | 企业策略原样提取、控制台试点、分批迁移顶层路由 | 3~4.5 | 每批契约一致,全量旧声明退出 |
|
||||
| P3 | 用户查询 service + Hook/test harness 迁移 | 1~1.5 | 查询请求和分页反馈不变 |
|
||||
| P4 | 联调、部署验证、文档与问题修复缓冲 | 1~2 | 发布门禁和新人演练完成 |
|
||||
|
||||
**合计约 8~12.5 人日。** 对刚入职且需要穿插业务需求的开发者,日历周期会更长;P0 后应依据未知规则和测试建设成本重新估算。
|
||||
|
||||
如果只能投入约一周,优先交付行为基线、测试设施、策略提取与控制台试点,不承诺全站迁移,更不要把布局重构塞入同一期。
|
||||
|
||||
建议 PR 边界:测试设施 → 行为基线测试 → 策略纯搬迁 → 路由出口适配 → 各业务路由模块 → 用户查询 service → 文档。测试和对应应用变更在可审查范围内配套提交;不把新增依赖、全仓格式化与业务行为修复混在一起。
|
||||
|
||||
### 协作责任
|
||||
|
||||
- 实施开发者:源码契约、迁移、测试与证据记录。
|
||||
- 熟悉业务的维护者:确认企业放行、角色边界、历史跳转等不是无意遗留。
|
||||
- 测试/产品:确认未知路径、布局差异等是否允许改变;首期默认不改变。
|
||||
- 后端/环境负责人:提供最小权限测试账号和配置样本,确认接口拒绝行为。
|
||||
|
||||
若缺少规则确认人或账号,先完成无行为变化的准备工作,不用个人经验替代业务决策。
|
||||
|
||||
## 10. 发布与回滚
|
||||
|
||||
1. 先测试环境,验证游客、普通用户、平台管理员、Root、org_only 员工及企业管理员。
|
||||
2. 发布前记录旧构建版本、源码提交和验证结果;保留可重新部署的旧产物。
|
||||
3. 首期不需要数据库或后端协议迁移,回滚以对应前端发布产物/独立提交为单位。
|
||||
4. 发布重点观察登录循环、错误跳转、页面加载失败、用户查询错误、会话校验与成员查询次数。
|
||||
5. 发现权限误放行、核心页面不可达、重定向循环,应立即撤回该批;不要线上临时关闭守卫止血。
|
||||
6. 回滚 HTML 与资源需配套,避免新 HTML 指向已删除 chunk;部署回退遵循现有静态资源保留策略。
|
||||
|
||||
不增加永久双路由开关。迁移中的旧声明适配仅是短期过渡,不是长期双轨系统。
|
||||
|
||||
## 11. 如何证明对新人真的有帮助
|
||||
|
||||
交付一份简短的“改功能导航”,回答:
|
||||
|
||||
- 新增页面到哪个路由模块?如何选择已有守卫?
|
||||
- 路由开关、企业放行和菜单显示分别在哪里?
|
||||
- 调整用户查询参数到哪里?哪些状态仍由 Hook 管?
|
||||
- 哪个命令验证路由、哪个验证分页、哪些需要浏览器?
|
||||
- 为什么本项目初次页码是 0、某些路径保留 key?
|
||||
|
||||
评审时做一次新人演练:给定 `/console/user`,要求开发者找到页面、权限、查询入口和专项测试;再用一个普通登录页面说明为何不能挂 Admin 父守卫。
|
||||
|
||||
建议验收指标:
|
||||
|
||||
1. 顶层旧路径迁移对照无遗漏,所有已知行为差异经显式批准。
|
||||
2. 企业策略可脱离浏览器以输入输出测试验证。
|
||||
3. 新增普通路由无需修改 App 的业务判断;若需特殊规则,应能定位到明确策略入口。
|
||||
4. 用户查询 URL 不再由 Hook 重复组装,原分页测试仍有效。
|
||||
5. 同一导航序列下,会话/成员/列表请求没有无解释的新增。
|
||||
6. 新维护者能在约 10 分钟内解释上述用户列表链路。该时间是建议目标,应通过实际演练校准,不是已测结果。
|
||||
|
||||
## 12. 后续演进
|
||||
|
||||
以下工作在顶层路由稳定后按需求独立立项,不计入首期验收。
|
||||
|
||||
### 12.1 布局与子路由
|
||||
|
||||
- 先保留用户中心和企业空间的后代 Routes 及父路径 `/*`。若未来统一为嵌套路由树,父布局需通过 Outlet 渲染 children。
|
||||
- 体验中心由 pathname.includes 改为明确子路由时,应单独确认默认页和未知路径行为;空内容改成 404 或重定向属于行为变更。
|
||||
- 先将 PageLayout 的路径判断提取为可测试规则,再评估路由元数据。不要自动将菜单、布局、权限合成同一张表。
|
||||
- 提取会话和站点初始化 Hook 时,保持挂载位置及生命周期,避免切页重复校验会话和请求配置。
|
||||
- `/` 与 `/home` 当前布局判断不同,是否统一需单独确认,不随目录整理修改。
|
||||
|
||||
### 12.2 HTTP 工具与领域接口
|
||||
|
||||
逐步拆分公共 HTTP 客户端、OAuth 服务、对话 payload/模型转换和错误解析。可由旧入口兼容 re-export,并保留 API 的 live binding;消费者迁移完成后再删除旧入口。
|
||||
|
||||
Axios、Fetch 与 SSE 保留各自传输适配器,只共享适用的地址、身份上下文和错误解析工具。用户写接口、大型业务 Hook 及请求竞态另行治理,不与纯接口搬迁混合。
|
||||
|
||||
### 12.3 可选能力的引入条件
|
||||
|
||||
- **TanStack Query**:仅在确有缓存、失效和请求生命周期管理需求时试点;query key 必须包含用户、组织、筛选和页码,并验证退出登录、组织切换、重试与现有错误提示的关系。
|
||||
- **进一步懒加载**:基于访问频率、chunk 和请求瀑布评估,不能以文件数量或代码行数证明性能提升。
|
||||
- **Data Router / TypeScript**:需有独立需求、迁移成本和验收依据,不作为模块化的隐含前置条件。
|
||||
|
||||
本方案的目标是降低理解成本、显式表达业务规则,并建立可验证的迭代方式。实施应从小范围试点开始,以行为一致和新人可定位问题作为验收依据,而不是追求一次完成全站终态设计。
|
||||
@@ -121,14 +121,14 @@ Monkey AI Web 是一个面向 AI 服务的 Web 前端,覆盖个人使用、企
|
||||
|
||||
## 2. 技术栈:使用什么,分别解决什么问题
|
||||
|
||||
下表列出 `package.json` 中声明的主要版本。声明值不等于本机已安装版本。当前 `bun.lock` 的根依赖记录与清单存在差异(包括 Vite、antd 等),不能将锁文件残留当作当前直接依赖;干净安装前需先由团队同步清单与锁文件。
|
||||
下表列出 package.json 中声明的主要版本;精确安装版本以 package-lock.json 为准。项目统一使用 npm,当前验证结果见 [维护性优化报告](./MAINTAINABILITY_REPORT.md)。
|
||||
|
||||
| 领域 | 技术与声明版本 | 在项目中的作用 |
|
||||
| --- | --- | --- |
|
||||
| 页面框架 | React、React DOM `^18.2.0` | 通过组件组织页面,使用 Hooks 管理交互和状态 |
|
||||
| 开发语言 | JavaScript、JSX、ES Modules | 主体代码为 `.js` 和 `.jsx`,使用 `import/export` |
|
||||
| 开发与构建 | Vite `5.1.0`、React 插件 | 本地热更新、开发代理、生产打包和资源拆分 |
|
||||
| 包管理 | Bun 锁文件 `bun.lock` | 固定依赖解析;部分脚本直接依赖 `bunx` |
|
||||
| 包管理 | npm / package-lock.json | npm ci 复现锁定依赖,脚本直接调用本地工具 |
|
||||
| 路由 | React Router DOM `^6.3.0` | 使用 BrowserRouter 和嵌套路由组织页面 |
|
||||
| 主 UI 组件库 | Semi UI `^2.69.1`、Semi Icons | 表格、表单、弹窗、布局、国际化组件文案等 |
|
||||
| 样式 | Tailwind CSS `^3`、PostCSS、Autoprefixer、CSS 变量 | 工具类、兼容处理、主题和品牌色 |
|
||||
@@ -145,10 +145,10 @@ Monkey AI Web 是一个面向 AI 服务的 Web 前端,覆盖个人使用、企
|
||||
|
||||
### 2.1 容易产生误解的依赖
|
||||
|
||||
1. **当前应用主体是 JavaScript/JSX,不是 TypeScript。** 当前 `package.json` 未直接声明 TypeScript,旧的 `typescript 4.4.2` 记录仍存在于 `bun.lock`。项目使用 `jsconfig.json`,`build` 没有独立类型检查步骤。
|
||||
1. **当前应用主体是 JavaScript/JSX,不是 TypeScript。** 清单未直接声明 TypeScript,使用 jsconfig.json,build 没有独立类型检查。
|
||||
2. **Semi UI 是当前代码中的主要组件库。** `antd ^5.23.0` 虽然列在依赖中,本次检索未发现 `src/` 中直接导入它的代码,不宜据此把项目描述成“双组件库全面混用”。新功能优先延续所属模块的现有组件。
|
||||
3. **存在多种请求方式是业务需要。** 普通管理接口主要使用 Axios;对话生成额外使用 Fetch 和 SSE。修改 Axios 拦截器不会自动改变 Fetch/SSE 行为。
|
||||
4. **锁文件中存在语言检测器记录,不代表当前直接依赖或启动流程在使用它。** 当前清单未声明 `i18next-browser-languagedetector`,语言选择主要由 `src/i18n/bootstrap.js` 等代码组织。
|
||||
4. **语言选择由应用自身控制。** 当前清单未声明 i18next-browser-languagedetector,启动逻辑主要由 src/i18n/bootstrap.js 组织。
|
||||
|
||||
## 3. 架构设计:如何理解代码之间的关系
|
||||
|
||||
@@ -158,7 +158,7 @@ Monkey AI Web 是一个面向 AI 服务的 Web 前端,覆盖个人使用、企
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[浏览器] --> B[index.html / config.js]
|
||||
A[浏览器] --> B[index.html]
|
||||
B --> C[index.jsx:语言初始化与全局 Provider]
|
||||
C --> D[PageLayout:全局布局、站点状态、会话校验]
|
||||
D --> E[App.jsx:顶层路由与访问控制]
|
||||
@@ -170,7 +170,7 @@ flowchart TD
|
||||
J --> G
|
||||
```
|
||||
|
||||
开发环境中,浏览器可以通过 Vite 代理访问后端;生产环境则由部署网关转发接口,或通过运行时配置连接独立后端域名。后端内部如何划分服务、使用何种数据库,不属于本仓库能够独立确认的内容。
|
||||
开发环境中,浏览器可以通过 Vite 代理访问后端;生产环境则由部署网关转发接口,或通过构建变量 `VITE_REACT_APP_SERVER_URL` 连接独立后端域名;未设置或为空时使用同源地址。后端内部如何划分服务、使用何种数据库,不属于本仓库能够独立确认的内容。
|
||||
|
||||
### 3.2 启动链路
|
||||
|
||||
@@ -178,7 +178,7 @@ flowchart TD
|
||||
|
||||
| 顺序 | 文件 | 负责什么 |
|
||||
| --- | --- | --- |
|
||||
| 1 | `index.html` | 提供 `root` 节点、启动占位画面;先加载 `/config.js`,再加载入口模块 |
|
||||
| 1 | `index.html` | 提供 `root` 节点、启动占位画面;直接加载入口模块,不再加载 `/config.js` |
|
||||
| 2 | `src/index.jsx` | 注入缓存主题,安装资源加载失败恢复处理,初始化语言并挂载 React |
|
||||
| 3 | `src/context/Status/`、`User/`、`Theme/` | 提供站点配置、登录状态及主题能力 |
|
||||
| 4 | `src/components/layout/PageLayout.jsx` | 组织全局布局,加载 `/api/status`,按缓存状态决定是否校验 `/api/user/self` |
|
||||
@@ -196,7 +196,7 @@ flowchart TD
|
||||
```text
|
||||
monkey-ai-web/
|
||||
├── docs/ 本项目分析等维护文档,不参与前端页面模块加载
|
||||
├── public/ 静态资源和运行时 config.js
|
||||
├── public/ 原样复制到构建目录的静态资源
|
||||
├── scripts/ 国际化提取、翻译整理等辅助脚本
|
||||
├── tests/ 部分 Node 测试
|
||||
├── src/
|
||||
@@ -205,8 +205,7 @@ monkey-ai-web/
|
||||
│ ├── pages/ 业务页面;部分包含自己的组件和子路由
|
||||
│ ├── components/ 公共组件及跨页面业务组件
|
||||
│ ├── hooks/ 按业务分类的数据、状态与交互逻辑
|
||||
│ ├── context/ User、Status、Theme、Org 等 Context 定义
|
||||
│ ├── contexts/ PlaygroundContext,现有独立目录
|
||||
│ ├── context/ User、Status、Theme、Org、Playground 等 Context 定义
|
||||
│ ├── services/ 会话、安全验证等可复用服务调用
|
||||
│ ├── helpers/ API、权限、配置、主题和工具函数
|
||||
│ ├── constants/ 接口地址、消息状态、菜单和业务常量
|
||||
@@ -215,7 +214,7 @@ monkey-ai-web/
|
||||
│ ├── styles/ 设计 token、主题预设和共享样式
|
||||
│ └── docs/ 供产品文档页使用的静态内容
|
||||
├── package.json 依赖与开发命令
|
||||
├── bun.lock 依赖锁文件
|
||||
├── package-lock.json 依赖锁文件
|
||||
└── vite.config.js 代理、别名、插件和生产构建配置
|
||||
```
|
||||
|
||||
@@ -371,9 +370,9 @@ GET 去重键考虑 URL、查询参数、组织、用户及显式授权信息,
|
||||
`fr.json`、`ru.json` 虽然存在,但未登记在当前运行时目录中;不能据文件存在就判断产品已支持法语和俄语。新增语言需同时检查语言包、目录、组件语言映射以及后端支持范围。
|
||||
|
||||
```bash
|
||||
bun run i18n:extract
|
||||
bun run i18n:status
|
||||
bun run i18n:lint
|
||||
npm run i18n:extract
|
||||
npm run i18n:status
|
||||
npm run i18n:lint
|
||||
```
|
||||
|
||||
提取、同步类命令可能修改语言文件,执行后检查 diff,避免把与本次功能无关的大批变动一起提交。
|
||||
@@ -386,7 +385,7 @@ bun run i18n:lint
|
||||
- 语言包按需加载,普通 GET 请求具有进行中请求去重。
|
||||
- 全局有 Chunk 加载失败识别、有限重载和错误边界,处理部署更新后旧页面引用过期资源的情况。
|
||||
|
||||
顶层懒加载不等于所有子页面都独立拆包;例如企业入口仍有多个静态导入。`PERFORMANCE_REPORT.md` 可以作为历史参考,其中的体积收益不能当作当前版本的实测结果。修改性能时应基于本次构建产物和浏览器数据判断。
|
||||
顶层懒加载不等于所有子页面都独立拆包;例如企业入口仍有多个静态导入。修改性能时应基于本次构建产物和浏览器数据判断,不把历史估算当作当前版本的实测结果。
|
||||
|
||||
## 7. 快速搭建本地开发环境
|
||||
|
||||
@@ -394,7 +393,7 @@ bun run i18n:lint
|
||||
|
||||
先获取可访问的后端地址、测试账号及权限、可用模型或渠道,以及需要联调的企业。仓库没有完整离线 Mock 和默认测试账号,前端依赖安装成功后仍需要这些条件才能验证真实业务。
|
||||
|
||||
仓库没有通过 `engines` 或版本文件强制固定运行时。建议团队统一 Node.js 22 LTS 或 24 LTS,以及兼容当前锁文件的 Bun 版本;现有 README 建议 Bun 1.3.x。本次测试环境为 Node.js `v22.23.3`,已有 `node_modules`,但未安装 Bun;未验证干净安装。
|
||||
项目通过 engines 要求 Node.js >=22.13.0、npm >=10;packageManager 记录 npm@10.9.9。本次在 Node.js 22.23.3 / npm 10.9.9 完成 npm ci、测试与生产构建。
|
||||
|
||||
### 7.2 按当前环境选择启动流程
|
||||
|
||||
@@ -402,48 +401,36 @@ bun run i18n:lint
|
||||
|
||||
```powershell
|
||||
node --version
|
||||
bun --version
|
||||
bun install --frozen-lockfile
|
||||
bun run dev
|
||||
npm --version
|
||||
npm ci
|
||||
npm run dev
|
||||
```
|
||||
|
||||
上述 Bun 流程适用于团队已同步依赖清单与锁文件的情况。当前二者不一致,不能保证 `--frozen-lockfile` 安装成功;遇到锁文件错误不要直接删除锁文件或取消冻结来掩盖问题。
|
||||
`npm ci` 按锁文件执行干净安装,会清理 node_modules;Windows 下先停止当前项目的开发服务,避免 esbuild 或 Rollup 文件被占用。
|
||||
|
||||
如果像本次环境一样已有可用的 `node_modules`、有 Node/npm 但没有 Bun,可以先用 `npm run dev` 启动已有依赖,用 `node --test` 运行测试;这不是经过验证的全新 npm 安装方案。部分 ESLint 和国际化脚本内部使用 `bunx`,仅把外层命令换成 npm 并不能绕过 Bun 依赖。
|
||||
更新依赖使用 npm install 并提交清单与锁文件;首次安装与 CI 使用 npm ci,不混用包管理器。
|
||||
|
||||
默认访问 `http://localhost:5173`;端口被占用时以终端输出为准。`--frozen-lockfile` 用于要求安装遵循锁文件,避免无意改写依赖解析。
|
||||
默认访问 `http://localhost:5173`;端口被占用时以终端输出为准。npm ci 不用于更新锁文件;清单与锁不一致时先定位差异。
|
||||
|
||||
如果需要配置前端开关,再创建本地环境文件:
|
||||
|
||||
```powershell
|
||||
Copy-Item .env.example .env.local
|
||||
```
|
||||
|
||||
`.env.local` 已被 Git 忽略。新增或更新依赖时,统一使用团队约定的包管理器,同步检查 `package.json` 与 `bun.lock`。
|
||||
开发命令自动加载 `.env.development`,生产构建自动加载 `.env.production`。个人覆盖配置使用 `.env.development.local` / `.env.production.local`,这些文件已被 Git 忽略。环境变量优先级和迁移说明见 [README](../README.md#3-后端联调与环境配置)。新增或更新依赖时,统一使用团队约定的包管理器,同步检查 `package.json` 与 `package-lock.json`。
|
||||
|
||||
### 7.3 推荐联调方式:浏览器同源请求
|
||||
|
||||
保持 `public/config.js` 中的 `SERVER_URL` 为空,且不设置 `VITE_REACT_APP_SERVER_URL`:
|
||||
不设置 `VITE_REACT_APP_SERVER_URL`(或设为空字符串),接口默认使用同源地址。
|
||||
|
||||
```js
|
||||
window.__APP_CONFIG__ = {
|
||||
SERVER_URL: '',
|
||||
};
|
||||
```
|
||||
|
||||
此时前端向当前域名发请求,由 Vite 将以下路径转发到 `vite.config.js` 中 `DEV_PROXY_TARGET` 指定的后端(当前为远程地址 `http://134.175.227.134:13000`,不是本机 3000 端口):
|
||||
此时前端向当前域名发请求,由 Vite 将以下路径转发到 `.env.development` 中 `DEV_PROXY_TARGET` 指定的后端(当前为远程地址 `http://134.175.227.134:13000`,不是本机 3000 端口):
|
||||
|
||||
```text
|
||||
/api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno
|
||||
```
|
||||
|
||||
切换联调环境时,修改 `vite.config.js` 中集中定义的 `DEV_PROXY_TARGET` 并重启开发服务;各代理前缀共享这一目标。使用前确认该环境已获授权且适合测试,不在未知或生产环境执行破坏性操作。当前没有专门读取代理目标的环境变量,`package.json` 的 `proxy` 字段也不是 Vite 代理的生效入口。
|
||||
切换联调环境时,修改 `.env.development` 或 `.env.development.local` 中的 `DEV_PROXY_TARGET` 并重启开发服务;各代理前缀共享这一目标。使用前确认该环境已获授权且适合测试,不在未知或生产环境执行破坏性操作。代理变量仅供 Vite 服务使用,不注入浏览器,`package.json` 的 `proxy` 字段也不是 Vite 代理的生效入口。
|
||||
|
||||
同源代理通常可以减少本地跨域联调问题,但代理本身不能替代后端账号、会话和业务配置。
|
||||
|
||||
### 7.4 可选联调方式:直接连接独立后端
|
||||
|
||||
可以在 `public/config.js` 中将 `SERVER_URL` 设为后端根地址,或者在 `.env.local` 中配置:
|
||||
在 `.env.development` / `.env.production` 或对应的 `.local` 文件中配置后端根地址(构建变量):
|
||||
|
||||
```dotenv
|
||||
VITE_REACT_APP_SERVER_URL=https://api.example.com
|
||||
@@ -452,15 +439,14 @@ VITE_CLOUD_BRAIN_UI_ENABLED=false
|
||||
|
||||
接口根地址优先级如下:
|
||||
|
||||
1. 非空的 `window.__APP_CONFIG__.SERVER_URL`。
|
||||
2. 非空的 `import.meta.env.VITE_REACT_APP_SERVER_URL`。
|
||||
3. 空字符串,使用当前页面域名。
|
||||
1. 非空的 `import.meta.env.VITE_REACT_APP_SERVER_URL`(构建变量)。
|
||||
2. 空字符串,使用当前页面域名(同源)。
|
||||
|
||||
地址填写后端根地址,不额外加 `/api`;具体请求自己包含路径。运行时地址为空时会继续回退至构建变量,不会强制覆盖为同源模式。
|
||||
地址填写后端根地址,不额外加 `/api`;具体请求自己包含路径。要使用同源模式,需确保构建变量未设置或为空。
|
||||
|
||||
直连独立域名时,请求不经过本地 Vite 代理,后端需要支持正确的 CORS、Cookie 和凭证策略。公共 Axios、对话 Fetch 与 SSE 都有各自的凭证配置,修改请求方式时需要分别核对。
|
||||
|
||||
`public/config.js` 会复制为 `dist/config.js`,部署后可修改并刷新页面;Vite 环境变量在构建时处理,开发时修改应重启服务,生产时修改应重新构建。前端配置对浏览器可见,只能存公开配置。
|
||||
已移除 `public/config.js` 及其入口脚本,不再支持部署后直接修改 `dist/config.js` 切换后端。旧部署如依赖它,需迁移到构建前设置 `VITE_REACT_APP_SERVER_URL`,或清空该变量后重新构建并配置同源反向代理。Vite 环境变量在构建时处理,开发时修改应重启服务,生产时修改应重新构建并发布;仅修改部署服务器环境变量或刷新页面不会改变已有产物。前端配置对浏览器可见,只能存公开配置。
|
||||
|
||||
### 7.5 按这个顺序确认环境可用
|
||||
|
||||
@@ -512,15 +498,15 @@ Vite 对 `src/` 中的 `.js` 配置了 JSX 转换,因此历史 `.js` 文件可
|
||||
|
||||
| 命令 | 实际作用 | 注意点 |
|
||||
| --- | --- | --- |
|
||||
| `bun run dev` | 启动 Vite 开发服务 | 默认前端 5173,代理目标见 `DEV_PROXY_TARGET` |
|
||||
| `bun run build` | 执行 `vite build` | 生成 `dist/`,不自动运行 ESLint、测试或独立类型检查 |
|
||||
| `bun run preview` | 预览生产构建 | 默认 4173,用于本地预览 |
|
||||
| `bun run test` | 执行 `node --test` | 测试分布于 `tests/` 和源码相邻位置 |
|
||||
| `bun run eslint` | 检查 JS/JSX | 脚本使用 `bunx eslint` |
|
||||
| `bun run eslint:fix` | 自动修复部分静态检查问题 | 执行后检查 diff |
|
||||
| `bun run lint` | 执行 Prettier 格式检查 | 这个命令不是 ESLint;当前配置有已知问题 |
|
||||
| `bun run lint:fix` | 执行全项目格式化 | 会批量修改文件,避免无关变动 |
|
||||
| `bun run i18n:sync` | 同步语言资源结构 | 可能修改多个语言包 |
|
||||
| `npm run dev` | 启动 Vite 开发服务 | 默认前端 5173,代理目标见 `DEV_PROXY_TARGET` |
|
||||
| `npm run build` | 执行 `vite build` | 生成 `dist/`,不自动运行 ESLint、测试或独立类型检查 |
|
||||
| `npm run preview` | 预览生产构建 | 默认 4173,用于本地预览 |
|
||||
| `npm run test` | 执行 `node --test` | 测试分布于 `tests/` 和源码相邻位置 |
|
||||
| `npm run eslint` | 检查 JS/JSX | 脚本使用本地 eslint |
|
||||
| `npm run eslint:fix` | 自动修复部分静态检查问题 | 执行后检查 diff |
|
||||
| `npm run lint` | 执行 Prettier 格式检查 | 这个命令不是 ESLint;当前配置有已知问题 |
|
||||
| `npm run lint:fix` | 执行全项目格式化 | 会批量修改文件,避免无关变动 |
|
||||
| `npm run i18n:sync` | 同步语言资源结构 | 可能修改多个语言包 |
|
||||
|
||||
现有测试使用 `node:test` 和 `node:assert`,覆盖请求去重、登录回跳、语言初始化、功能开关、会话流程、价格计算和部分 CSS 规则等。当前依赖与配置未体现完整的浏览器端到端测试方案;通过 Node 测试不能代替真实页面联调。
|
||||
|
||||
@@ -536,9 +522,9 @@ node --test src/hooks/playground/sessionFlow.test.js
|
||||
## 10. 构建与部署需要理解什么
|
||||
|
||||
```bash
|
||||
bun install --frozen-lockfile
|
||||
bun run build
|
||||
bun run preview
|
||||
npm ci
|
||||
npm run build
|
||||
npm run preview
|
||||
```
|
||||
|
||||
生产交付物为 `dist/`。部署时需保证以下行为:
|
||||
@@ -550,27 +536,27 @@ bun run preview
|
||||
| 正确区分页面与接口 | `/api` 等接口不能误回退到 HTML;带哈希的资源请求也应返回正确资源类型 |
|
||||
| 流式响应 | SSE 接口需要合理的超时与关闭响应缓冲,避免生成完毕才一次性显示 |
|
||||
| WebSocket | 使用时需配置连接升级转发;当前开发代理在 `/v1` 开启 `ws` |
|
||||
| 缓存策略 | `index.html`、`config.js` 应及时更新,带哈希资源可以长缓存 |
|
||||
| 缓存策略 | `index.html` 应及时更新,带哈希资源可以长缓存;后端地址变化需重建并发布配套 HTML 与资源,不再有独立 `config.js` 缓存 |
|
||||
| 部署根路径 | 当前资源和路由按域名根路径使用,子目录部署需检查 Vite `base`、路由及资源路径 |
|
||||
|
||||
`vercel.json` 当前仅配置 GitHub 通知静默,没有提供完整的路由回退和后端代理。不能把它当成已经验收过的部署方案。
|
||||
|
||||
## 11. 当前已确认的工程注意点
|
||||
|
||||
以下事项来自本次代码检查或实际命令结果,便于接手时安排处理优先级。本次仅修订分析文档,没有修改这些配置。
|
||||
以下事项来自代码检查或实际命令结果,便于接手时安排处理优先级。后续优化结果见 [维护性优化报告](./MAINTAINABILITY_REPORT.md)。
|
||||
|
||||
| 事项 | 当前证据 | 对开发的影响与建议 |
|
||||
| --- | --- | --- |
|
||||
| Prettier 配置无法按 ESM 正常加载 | `.prettierrc.mjs` 使用 `module.exports = require(...)`;Node 导入已复现 `require is not defined in ES module scope` | 运行格式检查前需统一为正确的 ESM 或 CJS 配置,避免格式检查成为阻塞项 |
|
||||
| Prettier 配置已统一 | `.prettierrc.mjs` 使用 ESM 导出,移除 package.json 的重复配置;忽略构建产物和缓存 | 全仓仍有历史格式差异,按改动范围渐进处理,不做无关全仓格式化 |
|
||||
| 构建目录已被忽略 | `.gitignore` 包含 `/dist/`、`/dist-ssr/` 和 `/build` | 原文“dist 未忽略”已过时;提交前仍检查 Git 状态 |
|
||||
| 压缩选项位置需要复核 | `drop: ['console', 'debugger']` 写在 `build.esbuild` 中 | Vite 5 的 `esbuild` 通常是顶层配置;不能仅凭此处注释确认日志已被移除,应调整并检查产物。本次未构建验证 |
|
||||
| 开发代理已集中配置 | `vite.config.js` 的 `DEV_PROXY_TARGET` 统一供多个前缀使用,当前指向远程后端 | 仍是源码常量,不是代理环境变量;切换后重启开发服务 |
|
||||
| 依赖清单与锁文件不一致 | `package.json` 与 `bun.lock` 根依赖记录的 Vite、antd 等声明不同,锁文件保留已移除依赖 | 由团队确认目标版本后同步锁文件,再验证冻结安装;本次不擅自重装或升级 |
|
||||
| 运行时版本未锁定 | 无 `engines` 等统一约束 | 团队应记录实际验证过的 Node 与 Bun 版本,减少环境差异 |
|
||||
| 依赖管理已统一 | 删除旧 Bun 锁并保留匹配清单的 npm 锁 | npm ci 已验证,依赖更新须同步提交锁文件 |
|
||||
| 运行时约束 | engines 与 packageManager 已声明 Node/npm 要求 | CI 应使用已验证版本 |
|
||||
| 部分说明落后于源码 | 体验中心子目录 README 仍使用 `web/src` 并描述图片、视频为占位功能 | 阅读时以当前入口、Hook 和接口调用为准 |
|
||||
| 分层与命名存在历史差异 | `context/` 与 `contexts/` 并存,部分页面直接请求接口 | 新改动保持局部一致,按业务收益渐进整理,避免无目标的大规模搬迁 |
|
||||
| 分层与命名存在历史差异 | Context 已统一至 `context/`,部分页面仍直接请求接口 | 新改动保持局部一致,按业务收益渐进整理,避免无目标的大规模搬迁 |
|
||||
|
||||
统计脚本也是一个配置细节:Vite 插件使用 `process.env.VITE_UMAMI_WEBSITE_ID`、`VITE_UMAMI_SCRIPT_URL`、`VITE_GOOGLE_ANALYTICS_ID`,没有显式调用 `loadEnv`。使用 Node/npm 运行时,不要假定仅写入 `.env.local` 就一定能被配置文件读取;应由启动环境或 CI 注入并检查构建 HTML。
|
||||
统计脚本由 Vite 的 `loadEnv` 按当前 mode 读取 `VITE_UMAMI_WEBSITE_ID`、`VITE_UMAMI_SCRIPT_URL`、`VITE_GOOGLE_ANALYTICS_ID`;支持开发/生产环境文件与本地覆盖文件,终端或 CI 的同名变量优先,ID 留空时禁用注入。
|
||||
|
||||
### 11.1 本次验证记录与结论边界
|
||||
|
||||
@@ -578,11 +564,11 @@ bun run preview
|
||||
| --- | --- |
|
||||
| 源码与配置分析 | 已检查依赖、入口、路由、请求、状态、企业权限、对话、国际化、主题及检查规则 |
|
||||
| Node 环境 | `v22.23.3` |
|
||||
| 现有测试 `node --test` | 128 项通过,0 项失败;包含之前因缺少 postcss 而加载失败的两个测试文件 |
|
||||
| Prettier 配置导入 | 已复现 ESM 加载错误 |
|
||||
| 安装、构建、完整 ESLint、浏览器联调 | 本次未执行;已有项目依赖但没有 Bun,未连接后端进行业务验收 |
|
||||
| 现有测试 `node --test` | 优化与验收修复后 179 项通过,0 项失败;包含偏好解析、筛选参数、用户列表控制器和 Semi 分页回调回归测试 |
|
||||
| Prettier 配置导入 | ESM 配置已修复;格式检查可执行,但全仓历史格式差异仍未统一 |
|
||||
| 浏览器验收 | Chrome 隔离环境下的分页、搜索、通知、跨标签页同步、移动端和错误恢复通过;接口使用测试 fixture,不代表真实后端验收 |
|
||||
|
||||
本次 Node 测试全部通过,但**不代表干净安装、生产构建、页面联调或发布验收已通过**。旧版“122 项通过、两个文件加载失败”的记录已被本次结果替代,不能继续作为当前环境结论。
|
||||
Node 测试和生产构建通过不等于后端业务或线上发布验收通过;具体结果与验证边界见 [维护性优化报告](./MAINTAINABILITY_REPORT.md)。
|
||||
|
||||
## 12. 常见问题排查表
|
||||
|
||||
@@ -594,11 +580,11 @@ bun run preview
|
||||
| 账号有权限,菜单却不显示 | 依次检查站点模块配置、企业功能、细分权限及构建开关 |
|
||||
| 菜单显示,点击后却跳回企业空间 | 检查 `org_only_mode`、`App.jsx` 的允许路径和企业页面守卫 |
|
||||
| 企业列表为空或数据范围不符 | 检查 `current_org_id`、显式 `orgId`、`X-Org-Id`、成员权限及业务响应 |
|
||||
| 修改环境变量未生效 | 检查运行时地址优先级、是否重启或重建、`config.js` 和浏览器缓存 |
|
||||
| 修改环境变量未生效 | 检查构建时的变量值、是否重启或重建并发布、HTML 与静态资源缓存 |
|
||||
| 流式回复在结束时一次性出现 | 检查 SSE 事件、网关缓冲、超时和后端输出方式 |
|
||||
| 线上刷新子页面 404 | 检查静态服务器的 SPA 路由回退 |
|
||||
| 模块资源加载失败 | 检查旧 HTML 与新资源是否版本不一致,确认发布和缓存策略 |
|
||||
| `lint` 报 `require` 未定义 | 检查 `.prettierrc.mjs` 的 ESM/CJS 配置冲突 |
|
||||
| `lint` 报 Code style issues | 历史格式差异仍存在,只格式化本次改动文件;当前 ESM 配置已修复 |
|
||||
| 测试报找不到 `postcss` | 先按锁文件安装依赖,再重跑对应测试 |
|
||||
|
||||
## 13. 建议的新成员学习路径
|
||||
@@ -622,7 +608,7 @@ bun run preview
|
||||
| 构建、代理与路径别名 | [vite.config.js](../vite.config.js)、[jsconfig.json](../jsconfig.json) |
|
||||
| React 启动与布局 | [index.jsx](../src/index.jsx)、[PageLayout.jsx](../src/components/layout/PageLayout.jsx) |
|
||||
| 顶层路由与权限 | [App.jsx](../src/App.jsx)、[auth.jsx](../src/helpers/auth.jsx) |
|
||||
| 共享请求与配置 | [api.js](../src/helpers/api.js)、[config.js](../src/helpers/config.js)、[运行时配置](../public/config.js) |
|
||||
| 共享请求与配置 | [api.js](../src/helpers/api.js)、[config.js](../src/helpers/config.js)、[开发环境](../.env.development)、[生产环境](../.env.production) |
|
||||
| 请求去重 | [requestDedupe.js](../src/helpers/requestDedupe.js)、[相关测试](../src/helpers/requestDedupe.test.js) |
|
||||
| 登录状态 | [User Provider](../src/context/User/index.jsx)、[User Reducer](../src/context/User/reducer.js) |
|
||||
| 企业入口与成员逻辑 | [Organization](../src/pages/Organization/index.jsx)、[useOrgMembers](../src/hooks/org/useOrgMembers.js) |
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
# 页面渲染、路由与 API 调用链分析
|
||||
|
||||
> 适用读者:熟悉 Vue 3 / Vue Router、正在接手本 React 项目的开发者。
|
||||
> 源码分析基准:`weiyuan` 分支、提交 `821577f`;文档整理日期:2026-10-27。源码行号和声明统计均以该基准为准。
|
||||
> 本文解释现有实现,不包含改造实施计划。目标结构、迁移步骤与验收要求统一见[前端模块化改造技术方案](./MODULAR_REFACTOR_TECHNICAL_PLAN.zh-CN.md)。
|
||||
|
||||
## 1. 先建立整体认识
|
||||
|
||||
本项目是基于 React 与 Vite 的客户端单页应用,已使用 React Router,并非自行实现路由。`react-router-dom` 的声明范围为 `^6.3.0`,分析基准的锁定版本为 **6.30.6**,二者不能混为一谈。
|
||||
|
||||
入口使用 `BrowserRouter`,顶层 `App` 使用 `Routes`、`Route` 和 `Navigate`;用户中心与企业空间内部还有各自的子路由。页面和业务状态已经分布在 pages、components、hooks 等目录,并非全部写在 App 中。
|
||||
|
||||
`App.jsx` 在分析基准中共 880 行,包含 64 个 Route、50 个 lazy 和 64 个 Suspense 声明。它主要集中管理页面懒加载、URL 映射、访问策略、功能开关和旧地址跳转。这些数字是源码声明数量,不是同时渲染的页面数量。
|
||||
|
||||
对 Vue 开发者而言,可先把 App 理解为“路由注册与访问策略入口”,把 PageLayout 理解为“全局布局与部分启动逻辑”。React Router 提供路由能力,但不会自动按业务拆分文件。
|
||||
|
||||
建议先阅读第 2 章建立启动流程,再沿第 3 章的用户列表实例跟踪一次请求;第 4、5 章用于查阅网络和权限边界。
|
||||
|
||||
## 2. 从浏览器打开页面到 React 渲染
|
||||
|
||||
### 2.1 实际入口顺序
|
||||
|
||||
```text
|
||||
浏览器访问 /console/user
|
||||
-> 开发服务器 / 生产静态服务返回 index.html
|
||||
-> index.html 直接加载入口模块并执行 src/index.jsx
|
||||
-> 注入缓存主题、安装 chunk 加载失败恢复处理
|
||||
-> bootstrapLanguage 决定首屏语言
|
||||
-> ReactDOM.createRoot(...).render(...)
|
||||
-> 全局 Provider + BrowserRouter
|
||||
-> PageLayout:外壳、会话恢复、站点状态、主题等
|
||||
-> App:访问策略与路由匹配
|
||||
-> AdminRoute:检查登录和角色
|
||||
-> Suspense + lazy:加载用户页模块
|
||||
-> User -> UsersTable -> useUsersData
|
||||
-> 接口结果写入 state -> React 更新表格
|
||||
```
|
||||
|
||||
这是 **Vite 构建的客户端单页应用(SPA)**。`/console/user` 是前端页面地址,`/api/user/` 是后端接口地址;二者不是同一个路由系统。
|
||||
|
||||
使用 `BrowserRouter` 意味着生产服务器需要对有效的前端深链接返回 `index.html`。否则“从首页点击能进,刷新 `/console/user` 却 404”。部署时应先处理真实静态资源和 API 转发,再做 SPA 回退,不能把接口请求错误地回退成 HTML。Vite 开发代理不会随构建产物自动部署到生产。
|
||||
|
||||
### 2.2 Provider 的实际嵌套
|
||||
|
||||
`src/index.jsx:83` 中的结构是:
|
||||
|
||||
```text
|
||||
StrictMode
|
||||
StatusProvider
|
||||
UserProvider
|
||||
BrowserRouter
|
||||
ThemeProvider
|
||||
SemiLocaleWrapper
|
||||
ChunkErrorBoundary
|
||||
PageLayout
|
||||
App
|
||||
```
|
||||
|
||||
| 层次 | 当前职责 | Vue 开发者可以怎样理解 |
|
||||
| -------------------- | ------------------------------------ | ----------------------------------------- |
|
||||
| `StatusProvider` | 共享站点状态、后台下发的模块配置等 | 站点配置 store / provide |
|
||||
| `UserProvider` | 用户信息、认证检查状态 | 登录态 store,但 Context 不等于完整 Pinia |
|
||||
| `BrowserRouter` | 浏览器 history、当前位置、导航上下文 | Vue Router 的浏览器 history 模式 |
|
||||
| `ThemeProvider` | 主题能力 | 全局主题状态与操作 |
|
||||
| `SemiLocaleWrapper` | 根据语言选择 Semi 组件文案 | UI 库的 locale provider |
|
||||
| `ChunkErrorBoundary` | 处理资源加载等相关错误边界 | 注意与“加载中”的 Suspense 区分 |
|
||||
| `PageLayout` | 全局外壳及启动副作用 | 布局组件 + 一部分应用初始化 |
|
||||
| `App` | 选择应渲染的页面 | 顶层路由出口与访问策略编排 |
|
||||
|
||||
注意:本项目是 `PageLayout` 包着 `App`,并非“App 里面放所有布局”。名字不决定组件层次。
|
||||
|
||||
### 2.3 初次渲染并非等所有接口返回后再显示
|
||||
|
||||
启动阶段有几类不同的等待:
|
||||
|
||||
- **语言初始化**发生在 React 首次渲染之前。有有效本地语言候选时可先使用本地结果;无有效本地候选时有限等待语言接口并支持回退。
|
||||
- **站点状态与用户校验**由 `PageLayout` 的 effect 发起,不是整个页面的一条串行阻塞流水线。
|
||||
- 有缓存用户时,`loadUser()` 调用 `/api/user/self`;没有缓存时直接标记认证检查完成,不无条件请求该接口。
|
||||
- `/api/user/self` 返回业务失败或 401/403 时清理用户状态;临时网络异常则保留缓存展示态。缓存不是服务端授权凭证。
|
||||
- 守卫的判断顺序不同:`PrivateRoute` 在 Context 已有用户时直接渲染,否则才检查缓存与认证等待;`AdminRoute`、`RootRoute` 优先检查“有缓存且认证未完成”,再判断用户和数字角色。`AuthRedirect` 与 PrivateRoute 一样先判断当前用户。
|
||||
- `SetupCheck` 在 effect 中发现 `status.setup === false` 时跳到 `/setup`,但自身直接返回 children。它**不是等待站点状态加载完成的阻塞守卫**。
|
||||
- `/api/status` 失败后当前实现回退到 `{ setup: true }`,而非一直卡在初始化中。
|
||||
|
||||
这些等待发生在不同层次,并不存在统一的全站 ready 状态。阅读启动逻辑时,应分别跟踪语言、站点状态和会话恢复。
|
||||
|
||||
### 2.4 点击导航时发生什么?
|
||||
|
||||
典型的 `Link` 或 `navigate()` 会更新浏览器 history,React Router 根据新位置重新匹配,渲染对应路由元素。通常不需要重新下载整份 HTML,也不会重建所有全局 Provider。
|
||||
|
||||
但有两个区别:
|
||||
|
||||
1. OAuth、401 失效处理、`SetupCheck` 等代码存在 `window.location.href`,这是整页导航,不是普通 SPA 内部切换。
|
||||
2. `App.jsx` 多处给 Suspense 设置 `key={location.pathname}`。路径变化会使这些边界及其子树重新挂载,影响局部 state、effect 和请求。没有设置 key 的分支又可能保留更多状态。
|
||||
|
||||
阅读页面状态与请求行为时,应同时检查路由的 key;同一页面组件不一定意味着相同的挂载生命周期。
|
||||
|
||||
## 3. 以你选中的 `/console/user` 为例读完整条链
|
||||
|
||||
### 3.1 文件与职责
|
||||
|
||||
| 顺序 | 文件位置 | 负责什么 |
|
||||
| ---- | ----------------------------------------- | ------------------------------------------------- |
|
||||
| 1 | `src/App.jsx:465` | 注册 `/console/user`,组合 AdminRoute 和 Suspense |
|
||||
| 2 | `src/helpers/auth.jsx:98` | AdminRoute:认证等待、登录回跳、数字角色 `>= 10` |
|
||||
| 3 | `src/pages/User/index.jsx:23` | 薄页面,只组织外层容器和 UsersTable |
|
||||
| 4 | `src/components/table/users/index.jsx:33` | 调用 useUsersData,接线筛选、表格、分页、弹窗 |
|
||||
| 5 | `src/hooks/users/useUsersData.jsx:26` | 用户列表状态、加载、搜索、分页和操作 |
|
||||
| 6 | `src/helpers/api.js:32` | Axios 实例、请求头、GET 在途去重、公共错误处理 |
|
||||
| 7 | `src/hooks/users/useUsersData.jsx:79` | 判断 success,读取 items/page/total,更新 state |
|
||||
|
||||
`User` 在 `App.jsx:72` 通过 `React.lazy(() => import('./pages/User'))` 声明。lazy 在模块顶层定义,真正渲染时才触发相关模块加载;不是每次 App 渲染都下载全部页面。
|
||||
|
||||
Suspense 处理懒加载等待;**它不会自动让 Hook 中普通 Axios 请求的 loading 交给 React Router 管理**。接口加载状态仍然由 `useUsersData` 管理。
|
||||
|
||||
### 3.2 首次加载与搜索
|
||||
|
||||
`useUsersData` 挂载时调用:
|
||||
|
||||
```text
|
||||
loadUsers(0, pageSize)
|
||||
-> GET /api/user/?p=0&page_size=...
|
||||
-> Axios response.data = { success, message, data }
|
||||
-> data.items / data.page / data.total
|
||||
-> setUsers / setActivePage / setUserCount
|
||||
-> 表格重新渲染
|
||||
```
|
||||
|
||||
同时还请求 `/api/group/`,用于筛选项。注意这里**首次请求沿用 `p=0` 的现有约定**,不要在提取 service 时顺手改成统一从 1 开始。
|
||||
|
||||
搜索走 `GET /api/user/search`,使用 Axios `params` 传 `keyword/group/p/page_size`。两个筛选项都为空时退回普通列表接口。翻页与修改条数复用 `refresh()`;修改条数重置第 1 页并保留筛选条件。
|
||||
|
||||
相关分页行为已有专项回归测试,可结合测试理解初始页码与分页交互的区别。
|
||||
|
||||
### 3.3 这说明现有项目已经具备什么?
|
||||
|
||||
当前已经有:
|
||||
|
||||
```text
|
||||
路由 -> 页面 -> 业务 UI 组件 -> 业务 Hook -> 公共 HTTP 客户端
|
||||
```
|
||||
|
||||
领域接口封装尚不统一:业务 Hook 和部分页面直接调用 API;已有 `services/playgroundConversation.js` 等封装,但并非所有 service 都返回相同结构。跟踪请求时,应以实际调用方和返回值为准,不能假定 service 已统一解包响应。
|
||||
|
||||
## 4. API 调用工具链到底提供了什么
|
||||
|
||||
### 4.1 地址选择与开发代理
|
||||
|
||||
删除前,`public/config.js` 会在 React 入口之前执行,向 `window.__APP_CONFIG__.SERVER_URL` 写入运行时值;[src/helpers/config.js](../src/helpers/config.js) 再从“运行时值 → Vite 构建变量 → 同源”逐级回退。仓库默认值一直是空字符串,但部署方可以在构建完成后直接修改 `dist/config.js`。
|
||||
|
||||
提交 `821577f` 删除了这条运行时分支:
|
||||
|
||||
- 删除 `public/config.js`。
|
||||
- 删除 `index.html` 中的 `<script src="/config.js"></script>`。
|
||||
- `getServerURL()` 不再访问 `window.__APP_CONFIG__`,只读取构建变量并回退到同源。
|
||||
- 环境配置提供后端地址(现使用 `.env.development` / `.env.production`,原 `.env.example` 已移除),`src/helpers/config.test.js` 覆盖缺省、空值、绝对地址以及 HTML 不再加载旧脚本。
|
||||
|
||||
现在的地址选择只有两级:
|
||||
|
||||
```text
|
||||
非空 import.meta.env.VITE_REACT_APP_SERVER_URL(构建变量)
|
||||
> ''(同源)
|
||||
```
|
||||
|
||||
等价源码为:
|
||||
|
||||
```js
|
||||
export function getServerURL() {
|
||||
return import.meta.env.VITE_REACT_APP_SERVER_URL || '';
|
||||
}
|
||||
```
|
||||
|
||||
| 配置 | 修改后何时生效 | 注意事项 |
|
||||
| -------------------------------------- | ------------------------------- | ---------------------------------------- |
|
||||
| `VITE_REACT_APP_SERVER_URL` | 开发服务重启 / 生产重新构建发布 | 会进入浏览器产物,不是服务端私密变量 |
|
||||
| `vite.config.js` 的 `DEV_PROXY_TARGET` | 开发服务重启 | 只服务本地 Vite 代理,不会打包成生产代理 |
|
||||
|
||||
现在支持两种部署方式:
|
||||
|
||||
1. **同源模式(推荐)**:不设置 `VITE_REACT_APP_SERVER_URL` 或设为空,浏览器请求 `/api/...`、`/pg/...` 等相对地址。本地由 Vite 代理,生产由 Nginx、网关等反向代理。
|
||||
2. **跨域直连模式**:构建前设置 `VITE_REACT_APP_SERVER_URL=https://api.example.com`,业务路径拼到该根地址后。生产修改地址必须重新构建和发布,并确认 CORS、Cookie 与 credentials 策略。
|
||||
|
||||
旧部署如果曾在发布后修改 `dist/config.js`,升级后必须迁移到上述方式之一。仅在部署服务器上修改环境变量、创建一个新的 `config.js` 或刷新浏览器都不会改变已经构建的 JS;Vite 会在构建阶段替换 `import.meta.env.VITE_*`。
|
||||
|
||||
这里还有一个容易混淆的点:`src/helpers/api.js` 中的 `updateAPI()` 仍可重新创建 Axios 实例,但它只会重新读取**已经编译进当前前端产物**的构建变量,不能像旧 `config.js` 一样在不重新构建的情况下切换后端。它不是运行时环境切换机制。此外,`loginFlow.js` 在登录后调用它重建实例,使新会话使用新的在途请求集合;这不会取消旧实例已经发出的请求。
|
||||
|
||||
发布时让 `index.html` 及时更新,带哈希的静态资源可长缓存;后端地址变化需重新构建并发布配套 HTML 与资源,不再有独立 `config.js` 缓存。
|
||||
|
||||
默认同源时,开发链路是“浏览器请求 Vite → Vite 代理 → 后端”。代理前缀包含 `/api`、`/v1`、`/v1beta`、`/mj`、`/pg`、`/dashboard`、`/kling`、`/jimeng`、`/suno`;`/v1` 启用 WebSocket 代理。
|
||||
|
||||
`package.json` 中虽有 `proxy` 字段,但本项目实际使用的是 `vite.config.js` 的代理配置。
|
||||
|
||||
### 4.2 普通请求:Axios 公共实例
|
||||
|
||||
核心实现位于 `src/helpers/api.js`:
|
||||
|
||||
| 能力 | 当前实现 | 边界 |
|
||||
| -------------- | -------------------------------------- | ------------------------------------------ |
|
||||
| 基础地址 | `baseURL: getServerURL()` | 实例创建时读取;`updateAPI()` 可重建 |
|
||||
| 跨域凭证 | 地址非空时 `withCredentials: true` | 不等于所有部署环境的 Cookie 都自动可用 |
|
||||
| 用户标识 | 请求拦截器添加 `New-API-User` | 不是 token,更不能替代后端会话鉴权 |
|
||||
| 企业标识 | `/api/org/` 前缀请求注入 `X-Org-Id` | 显式头优先,否则读 `current_org_id` |
|
||||
| 默认缓存请求头 | `Cache-Control: no-store` | 不等于前端实现了查询缓存 |
|
||||
| GET 合并 | 相同 key 的进行中请求共享 Promise | 仅封装的 `API.get`,完成即删除 |
|
||||
| 错误处理 | 拒绝响应默认调用 `showError` 再 reject | 不统一解包,也不处理所有业务 success=false |
|
||||
|
||||
正常响应仍是 Axios response,需要调用方读取 `res.data`。不能直接改拦截器为 `return response.data`,否则现有大量 `res.data.success` 调用会断裂。
|
||||
|
||||
### 4.3 两种“失败”一定要分清
|
||||
|
||||
**HTTP / 网络失败**:请求被拒绝、非成功 HTTP 状态等,进入 Axios 错误拦截器。`showError()` 对 Axios 401 会清理缓存、保存安全回跳地址,并整页跳转企业登录。
|
||||
|
||||
**业务失败**:HTTP 200,但响应为 `{ success: false, message: '...' }`。此时 Axios Promise 通常仍成功,Hook / service 需要检查 success 并决定展示方式。
|
||||
|
||||
`skipErrorHandler: true` 会跳过这一层全局错误处理,调用方需要承接相应责任。它不应被简单理解成“只关闭 toast”,因为当前全局错误函数还包含 401 跳转。
|
||||
|
||||
现有拦截器和部分 catch 都会提示错误,存在重复提示的结构性风险。排查时需要同时查看全局拦截器和调用方 catch,确认提示实际来自哪一层。
|
||||
|
||||
### 4.4 GET 去重不等于数据缓存,也不等于竞态治理
|
||||
|
||||
`src/helpers/requestDedupe.js:35` 的 key 由 URL、序列化 params、企业 ID、用户 ID、Authorization 组成。
|
||||
|
||||
需要知道的边界:
|
||||
|
||||
- 只在请求尚未结束时合并,不保留已完成结果,不提供缓存过期或写后失效。
|
||||
- 不覆盖 POST / PUT / DELETE,也不覆盖 Fetch / SSE。
|
||||
- `disableDuplicate: true` 的实际含义是**绕过去重,允许独立请求**,名字容易误读。
|
||||
- key 没有包含所有请求选项,例如 signal、responseType、其他 header、skipErrorHandler。
|
||||
- 搜索 A 和搜索 B 是不同请求,即使 GET 去重正确,A 晚返回仍可能覆盖 B;这是另一类状态竞态。
|
||||
|
||||
若后续给列表加入 AbortController,不能直接假设合并后的共享请求可由某个调用方随意取消。先定义取消与去重的关系,必要时对独立可取消请求绕过去重。多企业请求也应优先显式传组织 ID,避免把切换中的可变全局值当作稳定请求上下文。
|
||||
|
||||
### 4.5 为什么还有 Fetch / SSE?
|
||||
|
||||
对话接口有独立传输需求:
|
||||
|
||||
- `src/hooks/playground/useApiRequest.jsx:354` 使用 Fetch 发非流式请求,并管理取消与凭证。
|
||||
- 同文件 `:564` 使用 `sse.js` 创建流式请求,逐步接收数据。
|
||||
- `src/constants/playground.constants.js:79` 动态计算 `/pg/chat/completions` 地址。
|
||||
- `src/pages/CloudBrain/index.jsx:930` 还有自己的 SSE 路径。
|
||||
|
||||
它们**不经过 Axios 的请求头注入、去重和错误拦截器**,需要自行处理配置、凭证、取消和错误。
|
||||
|
||||
因此,排查网络问题时应先识别请求使用 Axios、Fetch 还是 SSE;只检查 Axios 拦截器无法覆盖全站网络行为。
|
||||
|
||||
## 5. 路由组织与访问规则
|
||||
|
||||
### 5.1 配置、策略、UI 包装混在一起
|
||||
|
||||
查看一条路由时,需要同时扫描 path、权限条件、懒加载、Loading、功能开关、跳转目标。新增一个页面往往复制十几行包装代码,难以一眼看到“URL → 页面 → 权限”。
|
||||
|
||||
其中企业员工限制尤其不只是路由表:它读取站点配置、企业成员身份、顶栏开关和目标路径,决定是否重定向。把这套规则放在 `App` 中,导致路由入口同时承担业务策略计算。
|
||||
|
||||
### 5.2 不同模块组织方式不一致
|
||||
|
||||
| 模块 | 当前组织方式 | 影响 |
|
||||
| -------- | --------------------------------------------------- | -------------------------------------- |
|
||||
| 控制台 | 大量平铺在 App 的顶层 Route | 查看同一业务域要扫长文件 |
|
||||
| 用户中心 | `/user-center/*` 下使用自己的 Routes | 已有模块化基础,不必推倒重来 |
|
||||
| 企业空间 | `/org/*` 下使用自己的 Routes,加本地角色/模块限制 | 应保留内部权限和初始化边界 |
|
||||
| 体验中心 | 通配入口后,主要靠 `pathname.includes()` 选择子页面 | 路径匹配、默认页和未知路径规则不够统一 |
|
||||
| 全局布局 | PageLayout 按路径字符串决定顶栏、侧栏和滚动 | 增加路由时容易漏掉布局配套调整 |
|
||||
|
||||
顶层页面懒加载也不代表每个子页面都单独懒加载。企业空间、体验中心存在子页面静态导入,是否进一步拆包需要结合访问频率和构建结果判断。
|
||||
|
||||
### 5.3 权限不是一个简单的 admin 布尔值
|
||||
|
||||
至少有这些维度:
|
||||
|
||||
- 是否登录,以及会话是否完成恢复。
|
||||
- 平台管理员 `role >= 10`、Root `role >= 100`。
|
||||
- 后台配置的模块是否要求登录。
|
||||
- 企业中心是否可用。
|
||||
- `org_only_mode` 用户是否只能访问企业区域,以及哪些入口例外放行。
|
||||
- 企业内部角色和细粒度权限。
|
||||
- 云脑等构建时功能开关。
|
||||
|
||||
**菜单可见性、前端路由可访问性、后端接口授权是三个不同问题。** 可以复用业务规则,但不能拿“菜单不显示”代替路由保护,也不能拿路由保护代替服务端鉴权。
|
||||
|
||||
### 5.4 App 之外也有值得整理的边界
|
||||
|
||||
- `PageLayout` 同时处理会话、站点加载、主题、路径布局、移动抽屉和弹窗。
|
||||
- `helpers/api.js` 除 HTTP 客户端外,还包含对话 payload、模型/分组转换、OAuth 跳转等业务函数。
|
||||
- `helpers/index.js` 是宽泛的聚合导出,新代码继续全部经它导入会使依赖关系难追踪。
|
||||
|
||||
这些文件是理解全局行为的重要入口,不能仅凭文件名判断其职责范围。
|
||||
|
||||
## 6. 建议阅读顺序与源码索引
|
||||
|
||||
第一次熟悉项目,按以下顺序即可,不必从 App 第一行一直背到最后一行:
|
||||
|
||||
1. [src/index.jsx](../src/index.jsx):认清全局 Provider 与 BrowserRouter。
|
||||
2. [PageLayout.jsx](../src/components/layout/PageLayout.jsx):区分应用外壳与启动请求。
|
||||
3. [App.jsx](../src/App.jsx):只读 `/console/user` 的声明和关联 lazy。
|
||||
4. [auth.jsx](../src/helpers/auth.jsx):理解 PrivateRoute / AdminRoute / RootRoute。
|
||||
5. [User 页面](../src/pages/User/index.jsx) → [用户表格](../src/components/table/users/index.jsx) → [useUsersData](../src/hooks/users/useUsersData.jsx):跟踪一次列表与搜索。
|
||||
6. [api.js](../src/helpers/api.js) → [requestDedupe.js](../src/helpers/requestDedupe.js) → [config.js](../src/helpers/config.js):对照 Network 看真实请求。
|
||||
7. 按需求再看 [企业空间](../src/pages/Organization/index.jsx)、[用户中心](../src/pages/UserCenter/index.jsx)、[体验中心](../src/pages/ExperienceCenter/index.jsx)。
|
||||
|
||||
配套文档:[项目分析与开发上手指南](./PROJECT_ANALYSIS.zh-CN.md)、[维护性优化报告](./MAINTAINABILITY_REPORT.md)、[README](../README.md)。
|
||||
@@ -356,7 +356,6 @@
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<script src="/config.js"></script>
|
||||
<script type="module" src="/src/index.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Generated
+17865
File diff suppressed because it is too large
Load Diff
+12
-10
@@ -55,13 +55,14 @@
|
||||
"test": "node --test",
|
||||
"lint": "prettier . --check",
|
||||
"lint:fix": "prettier . --write",
|
||||
"eslint": "bunx eslint \"**/*.{js,jsx}\" --cache",
|
||||
"eslint:fix": "bunx eslint \"**/*.{js,jsx}\" --fix --cache",
|
||||
"check": "npm run eslint && npm test && npm run build",
|
||||
"eslint": "eslint \"**/*.{js,jsx}\" --cache",
|
||||
"eslint:fix": "eslint \"**/*.{js,jsx}\" --fix --cache",
|
||||
"preview": "vite preview",
|
||||
"i18n:extract": "bunx i18next-cli extract",
|
||||
"i18n:status": "bunx i18next-cli status",
|
||||
"i18n:sync": "bunx i18next-cli sync",
|
||||
"i18n:lint": "bunx i18next-cli lint"
|
||||
"i18n:extract": "i18next-cli extract",
|
||||
"i18n:status": "i18next-cli status",
|
||||
"i18n:sync": "i18next-cli sync",
|
||||
"i18n:lint": "i18next-cli lint"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
@@ -91,9 +92,10 @@
|
||||
"tailwindcss": "^3",
|
||||
"vite": "5.1.0"
|
||||
},
|
||||
"prettier": {
|
||||
"singleQuote": true,
|
||||
"jsxSingleQuote": true
|
||||
"proxy": "http://localhost:3000",
|
||||
"engines": {
|
||||
"node": ">=22.13.0",
|
||||
"npm": ">=10"
|
||||
},
|
||||
"proxy": "http://localhost:3000"
|
||||
"packageManager": "npm@10.9.9"
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
// Runtime configuration - modify per deployment environment.
|
||||
// Monolith mode: leave SERVER_URL empty.
|
||||
// Separated mode: set to backend URL, e.g. 'https://api.example.com'
|
||||
window.__APP_CONFIG__ = {
|
||||
SERVER_URL: '',
|
||||
};
|
||||
@@ -496,4 +496,5 @@
|
||||
"更多操作": "その他の操作",
|
||||
"自定义对话参数": "対話パラメータをカスタマイズ",
|
||||
"选择 AI 模型": "AI モデルを選択",
|
||||
"实时显示AI回复内容": "AIの返信内容をリアルタイム表示"
|
||||
"实时显示AI回复内容": "AIの返信内容をリアルタイム表示"
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ import {
|
||||
selectFilter,
|
||||
countRounds,
|
||||
} from '../../helpers';
|
||||
import { usePlayground } from '../../contexts/PlaygroundContext';
|
||||
import { usePlayground } from '../../context/Playground';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
|
||||
const ChatArea = ({
|
||||
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
} from 'lucide-react';
|
||||
import { useSpeechRecognition } from '../../hooks/playground/useSpeechRecognition';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePlayground } from '../../contexts/PlaygroundContext';
|
||||
import { usePlayground } from '../../context/Playground';
|
||||
import {
|
||||
getExperienceCenterBool,
|
||||
getExperienceCenterPositiveInt,
|
||||
|
||||
@@ -41,7 +41,7 @@ import { useTranslation } from 'react-i18next';
|
||||
// 同名遮蔽在 Vite/terser 生产构建里会把两者缩成同一个变量名,触发 TDZ 错误:
|
||||
// "Cannot access 'Oe' before initialization"
|
||||
// 本地函数签名是 (content) 而非 helpers 里的 (message),调用时记得传 message.content。
|
||||
import { usePlayground } from '../../contexts/PlaygroundContext';
|
||||
import { usePlayground } from '../../context/Playground';
|
||||
import { useSpeechSynthesis } from '../../hooks/playground/useSpeechSynthesis';
|
||||
|
||||
const MessageContent = ({
|
||||
|
||||
@@ -110,6 +110,8 @@ const UsersPage = () => {
|
||||
total: usersData.userCount,
|
||||
onPageChange: usersData.handlePageChange,
|
||||
onPageSizeChange: usersData.handlePageSizeChange,
|
||||
// The size handler resets to page 1; skip Semi's automatic page callback.
|
||||
preventPageChangeOnPageSizeChange: true,
|
||||
isMobile: isMobile,
|
||||
t: usersData.t,
|
||||
})}
|
||||
|
||||
@@ -17,10 +17,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import { createContext, createElement, useContext } from 'react';
|
||||
|
||||
/**
|
||||
* Context for Playground component to share image handling functionality
|
||||
* Share Playground input, upload, search, and image generation functionality.
|
||||
*/
|
||||
const PlaygroundContext = createContext(null);
|
||||
|
||||
@@ -73,11 +73,7 @@ export const usePlayground = () => {
|
||||
* @returns {JSX.Element} Provider component
|
||||
*/
|
||||
export const PlaygroundProvider = ({ children, value }) => {
|
||||
return (
|
||||
<PlaygroundContext.Provider value={value}>
|
||||
{children}
|
||||
</PlaygroundContext.Provider>
|
||||
);
|
||||
return createElement(PlaygroundContext.Provider, { value }, children);
|
||||
};
|
||||
|
||||
export default PlaygroundContext;
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { parseStoredObject } from './storageJson.js';
|
||||
|
||||
// Resolve raw localStorage JSON without mutating defaults or performing I/O.
|
||||
export const resolveColumnVisibility = (
|
||||
defaults,
|
||||
savedColumns,
|
||||
hiddenKeys = [],
|
||||
) => {
|
||||
const resolved = { ...defaults };
|
||||
const preferences = parseStoredObject(savedColumns);
|
||||
|
||||
for (const key of Object.keys(defaults)) {
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(preferences, key) &&
|
||||
typeof preferences[key] === 'boolean'
|
||||
) {
|
||||
resolved[key] = preferences[key];
|
||||
}
|
||||
}
|
||||
|
||||
// Role restrictions take precedence over saved preferences.
|
||||
for (const key of hiddenKeys) {
|
||||
resolved[key] = false;
|
||||
}
|
||||
|
||||
return resolved;
|
||||
};
|
||||
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { resolveColumnVisibility } from './columnVisibility.js';
|
||||
|
||||
const defaults = Object.freeze({ time: true, model: true, channel: false });
|
||||
|
||||
test('missing or malformed saved JSON falls back to a fresh copy of defaults', () => {
|
||||
for (const saved of [
|
||||
undefined,
|
||||
null,
|
||||
'',
|
||||
'{',
|
||||
'not-json',
|
||||
'{"time":false,}',
|
||||
]) {
|
||||
const resolved = resolveColumnVisibility(defaults, saved);
|
||||
assert.deepEqual(resolved, defaults);
|
||||
assert.notStrictEqual(resolved, defaults);
|
||||
}
|
||||
});
|
||||
|
||||
test('null, arrays, and primitive JSON values are not preference maps', () => {
|
||||
for (const saved of [
|
||||
'null',
|
||||
'[]',
|
||||
'[false]',
|
||||
'"text"',
|
||||
'0',
|
||||
'true',
|
||||
'false',
|
||||
]) {
|
||||
assert.deepEqual(resolveColumnVisibility(defaults, saved), defaults);
|
||||
}
|
||||
});
|
||||
|
||||
test('non-string saved data is ignored without coercion or mutation', () => {
|
||||
const saved = Object.freeze({ time: false });
|
||||
for (const value of [saved, [false], 1, true]) {
|
||||
assert.deepEqual(resolveColumnVisibility(defaults, value), defaults);
|
||||
}
|
||||
assert.deepEqual(saved, { time: false });
|
||||
});
|
||||
|
||||
test('saved false and true values override defaults while new columns keep defaults', () => {
|
||||
assert.deepEqual(
|
||||
resolveColumnVisibility(defaults, '{"time":false,"channel":true}'),
|
||||
{ time: false, model: true, channel: true },
|
||||
);
|
||||
assert.deepEqual(resolveColumnVisibility(defaults, '{}'), defaults);
|
||||
});
|
||||
|
||||
test('invalid individual preferences keep defaults without discarding valid booleans', () => {
|
||||
for (const value of [null, 0, 1, '', 'false', [], {}]) {
|
||||
assert.deepEqual(
|
||||
resolveColumnVisibility(
|
||||
defaults,
|
||||
JSON.stringify({ time: value, channel: value, model: false }),
|
||||
),
|
||||
{ time: true, model: false, channel: false },
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('unknown and prototype-related saved keys do not enter the result', () => {
|
||||
const resolved = resolveColumnVisibility(
|
||||
defaults,
|
||||
'{"time":false,"removedColumn":true,"__proto__":{"polluted":true},"constructor":false,"toString":false}',
|
||||
);
|
||||
assert.deepEqual(resolved, { time: false, model: true, channel: false });
|
||||
assert.equal(Object.getPrototypeOf(resolved), Object.prototype);
|
||||
assert.equal(Object.hasOwn(resolved, '__proto__'), false);
|
||||
});
|
||||
|
||||
for (const [table, restrictedKeys] of [
|
||||
['usage logs', ['channel', 'username', 'retry']],
|
||||
['task logs', ['channel']],
|
||||
]) {
|
||||
for (const isAdmin of [true, false]) {
|
||||
test(`${table}: ${isAdmin ? 'admin' : 'non-admin'} preferences respect role restrictions`, () => {
|
||||
const roleDefaults = {
|
||||
model: true,
|
||||
...Object.fromEntries(restrictedKeys.map((key) => [key, isAdmin])),
|
||||
};
|
||||
const hiddenKeys = isAdmin ? [] : restrictedKeys;
|
||||
for (const checked of [true, false]) {
|
||||
const preferences = {
|
||||
model: false,
|
||||
...Object.fromEntries(restrictedKeys.map((key) => [key, checked])),
|
||||
};
|
||||
const resolved = resolveColumnVisibility(
|
||||
roleDefaults,
|
||||
JSON.stringify(preferences),
|
||||
hiddenKeys,
|
||||
);
|
||||
assert.equal(resolved.model, false);
|
||||
for (const key of restrictedKeys) {
|
||||
assert.equal(resolved[key], isAdmin && checked);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(
|
||||
resolveColumnVisibility(roleDefaults, null, hiddenKeys),
|
||||
roleDefaults,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('forced-hidden keys apply even when saved preferences are missing or invalid', () => {
|
||||
for (const saved of [null, '{', 'null', '[]', '{}', '{"time":true}']) {
|
||||
assert.deepEqual(resolveColumnVisibility(defaults, saved, ['time']), {
|
||||
time: false,
|
||||
model: true,
|
||||
channel: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('resolution never mutates defaults or hidden keys and returns independent results', () => {
|
||||
const hiddenKeys = Object.freeze(['channel']);
|
||||
const saved = '{"time":false,"channel":true}';
|
||||
const first = resolveColumnVisibility(defaults, saved, hiddenKeys);
|
||||
const second = resolveColumnVisibility(defaults, saved, hiddenKeys);
|
||||
|
||||
assert.notStrictEqual(first, second);
|
||||
first.model = false;
|
||||
assert.deepEqual(second, { time: false, model: true, channel: false });
|
||||
assert.deepEqual(defaults, { time: true, model: true, channel: false });
|
||||
assert.deepEqual(hiddenKeys, ['channel']);
|
||||
assert.equal(saved, '{"time":false,"channel":true}');
|
||||
});
|
||||
@@ -18,9 +18,5 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
export function getServerURL() {
|
||||
return (
|
||||
window.__APP_CONFIG__?.SERVER_URL ||
|
||||
import.meta.env.VITE_REACT_APP_SERVER_URL ||
|
||||
''
|
||||
);
|
||||
return import.meta.env.VITE_REACT_APP_SERVER_URL || '';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import test from 'node:test';
|
||||
import { transformWithEsbuild } from 'vite';
|
||||
|
||||
const source = await readFile(new URL('./config.js', import.meta.url), 'utf8');
|
||||
|
||||
async function loadConfig(env) {
|
||||
const { code } = await transformWithEsbuild(source, 'config.js', {
|
||||
loader: 'js',
|
||||
define: { 'import.meta.env': JSON.stringify(env) },
|
||||
});
|
||||
return import(
|
||||
`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`
|
||||
);
|
||||
}
|
||||
|
||||
for (const [name, env, expected] of [
|
||||
['missing backend URL uses same origin', {}, ''],
|
||||
['empty backend URL uses same origin', { VITE_REACT_APP_SERVER_URL: '' }, ''],
|
||||
[
|
||||
'configured backend URL works without a window global',
|
||||
{ VITE_REACT_APP_SERVER_URL: 'https://api.example.com' },
|
||||
'https://api.example.com',
|
||||
],
|
||||
]) {
|
||||
test(name, async () => {
|
||||
const { getServerURL } = await loadConfig(env);
|
||||
assert.equal(getServerURL(), expected);
|
||||
});
|
||||
}
|
||||
|
||||
test('HTML no longer loads the removed runtime configuration script', async () => {
|
||||
const html = await readFile(
|
||||
new URL('../../index.html', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.doesNotMatch(html, /<script\b[^>]*\bsrc=["']\/config\.js["']/i);
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { parseStoredArray, readStorageValue } from './storageJson.js';
|
||||
|
||||
export const NOTICE_READ_KEYS_KEY = 'notice_read_keys';
|
||||
|
||||
export const getAnnouncementKey = (announcement) =>
|
||||
`${announcement?.publishDate || ''}-${(announcement?.content || '').slice(0, 30)}`;
|
||||
|
||||
export function getUnreadAnnouncementKeys(announcements, readKeys) {
|
||||
const readSet = new Set(readKeys);
|
||||
return announcements
|
||||
.map(getAnnouncementKey)
|
||||
.filter((key) => !readSet.has(key));
|
||||
}
|
||||
|
||||
export function mergeAnnouncementReadKeys(announcements, readKeys) {
|
||||
return Array.from(
|
||||
new Set([...readKeys, ...announcements.map(getAnnouncementKey)]),
|
||||
);
|
||||
}
|
||||
|
||||
export function readNoticeReadKeys() {
|
||||
return parseStoredArray(readStorageValue(NOTICE_READ_KEYS_KEY));
|
||||
}
|
||||
|
||||
export function markAnnouncementsRead(announcements) {
|
||||
const mergedKeys = mergeAnnouncementReadKeys(
|
||||
announcements,
|
||||
readNoticeReadKeys(),
|
||||
);
|
||||
// Let write failures propagate so callers do not report unread items as saved.
|
||||
localStorage.setItem(NOTICE_READ_KEYS_KEY, JSON.stringify(mergedKeys));
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
/** Map the shared consumption filters without adding endpoint-specific options. */
|
||||
export function buildOrgLogFilters({
|
||||
userId,
|
||||
startTimestamp,
|
||||
endTimestamp,
|
||||
modelName,
|
||||
} = {}) {
|
||||
const params = {};
|
||||
// Preserve the API callers' existing omission of empty values (including zero).
|
||||
if (userId) params.user_id = userId;
|
||||
if (startTimestamp) params.start_timestamp = startTimestamp;
|
||||
if (endTimestamp) params.end_timestamp = endTimestamp;
|
||||
if (modelName) params.model_name = modelName;
|
||||
return params;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { buildOrgLogFilters } from './orgLogFilters.js';
|
||||
|
||||
test('consumption filters map to the existing API field names', () => {
|
||||
const filters = Object.freeze({
|
||||
userId: 42,
|
||||
startTimestamp: 1700000000,
|
||||
endTimestamp: 1700003600,
|
||||
modelName: 'example/model + preview',
|
||||
});
|
||||
assert.deepEqual(buildOrgLogFilters(filters), {
|
||||
user_id: 42,
|
||||
start_timestamp: 1700000000,
|
||||
end_timestamp: 1700003600,
|
||||
model_name: 'example/model + preview',
|
||||
});
|
||||
});
|
||||
|
||||
test('empty filters and existing falsy values are omitted', () => {
|
||||
assert.deepEqual(buildOrgLogFilters(), {});
|
||||
for (const value of [undefined, null, '', 0, false, NaN]) {
|
||||
assert.deepEqual(
|
||||
buildOrgLogFilters({
|
||||
userId: value,
|
||||
startTimestamp: value,
|
||||
endTimestamp: value,
|
||||
modelName: value,
|
||||
}),
|
||||
{},
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('partial filters preserve values without coercion', () => {
|
||||
assert.deepEqual(buildOrgLogFilters({ userId: '0', modelName: 'a&b' }), {
|
||||
user_id: '0',
|
||||
model_name: 'a&b',
|
||||
});
|
||||
});
|
||||
|
||||
test('endpoint-specific parameters cannot leak into shared filters', () => {
|
||||
const filters = Object.freeze({
|
||||
userId: 42,
|
||||
limit: 10,
|
||||
nocache: 1,
|
||||
p: 5,
|
||||
page_size: 20,
|
||||
memberId: 7,
|
||||
});
|
||||
const params = buildOrgLogFilters(filters);
|
||||
assert.deepEqual(params, { user_id: 42 });
|
||||
params.limit = 15;
|
||||
assert.deepEqual(buildOrgLogFilters(filters), { user_id: 42 });
|
||||
assert.equal(filters.limit, 10);
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
function parseStoredJson(json, isValid, fallback) {
|
||||
if (typeof json !== 'string') return fallback;
|
||||
try {
|
||||
const value = JSON.parse(json);
|
||||
return isValid(value) ? value : fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseStoredArray(json) {
|
||||
return parseStoredJson(json, Array.isArray, []);
|
||||
}
|
||||
|
||||
export function parseStoredObject(json) {
|
||||
return parseStoredJson(
|
||||
json,
|
||||
(value) =>
|
||||
value !== null && typeof value === 'object' && !Array.isArray(value),
|
||||
{},
|
||||
);
|
||||
}
|
||||
|
||||
export function readStorageValue(key) {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
parseStoredArray,
|
||||
parseStoredObject,
|
||||
readStorageValue,
|
||||
} from './storageJson.js';
|
||||
|
||||
import {
|
||||
getAnnouncementKey,
|
||||
getUnreadAnnouncementKeys,
|
||||
markAnnouncementsRead,
|
||||
mergeAnnouncementReadKeys,
|
||||
NOTICE_READ_KEYS_KEY,
|
||||
readNoticeReadKeys,
|
||||
} from './notificationReadState.js';
|
||||
import {
|
||||
getTableCompactMode,
|
||||
parseTableCompactMode,
|
||||
setTableCompactMode,
|
||||
} from './tableCompactMode.js';
|
||||
import { TABLE_COMPACT_MODES_KEY } from '../constants/common.constant.js';
|
||||
|
||||
function mockStorage(t, storage) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(
|
||||
globalThis,
|
||||
'localStorage',
|
||||
);
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
value: storage,
|
||||
});
|
||||
t.after(() => {
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, 'localStorage', descriptor);
|
||||
} else {
|
||||
delete globalThis.localStorage;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const invalidJson = [
|
||||
null,
|
||||
undefined,
|
||||
'',
|
||||
'{broken',
|
||||
'null',
|
||||
'true',
|
||||
'42',
|
||||
'"text"',
|
||||
];
|
||||
|
||||
test('stored arrays reject malformed JSON and non-array values', () => {
|
||||
for (const json of [...invalidJson, '{}', '{"0":"notice"}']) {
|
||||
assert.deepEqual(parseStoredArray(json), [], String(json));
|
||||
}
|
||||
});
|
||||
|
||||
test('stored objects reject malformed JSON and non-object values', () => {
|
||||
for (const json of [...invalidJson, '[]', '[true]']) {
|
||||
assert.deepEqual(parseStoredObject(json), {}, String(json));
|
||||
}
|
||||
});
|
||||
|
||||
test('valid stored containers keep their values without coercion or filtering', () => {
|
||||
const array = ['notice', 'notice', null, 1];
|
||||
const object = { global: true, tokens: false, other: 'yes' };
|
||||
assert.deepEqual(parseStoredArray(JSON.stringify(array)), array);
|
||||
assert.deepEqual(parseStoredObject(JSON.stringify(object)), object);
|
||||
});
|
||||
|
||||
test('fallback containers are fresh for each parse', () => {
|
||||
const array = parseStoredArray(null);
|
||||
const object = parseStoredObject(null);
|
||||
array.push('notice');
|
||||
object.global = true;
|
||||
assert.deepEqual(parseStoredArray(null), []);
|
||||
assert.deepEqual(parseStoredObject(null), {});
|
||||
});
|
||||
|
||||
test('storage reads return the original stored value', (t) => {
|
||||
mockStorage(t, {
|
||||
getItem(key) {
|
||||
assert.equal(key, 'preference');
|
||||
return 'stored';
|
||||
},
|
||||
});
|
||||
assert.equal(readStorageValue('preference'), 'stored');
|
||||
});
|
||||
|
||||
test('storage read failures fall back to null', (t) => {
|
||||
mockStorage(t, {
|
||||
getItem() {
|
||||
throw new Error('Storage blocked');
|
||||
},
|
||||
});
|
||||
assert.equal(readStorageValue('preference'), null);
|
||||
assert.deepEqual(readNoticeReadKeys(), []);
|
||||
assert.equal(getTableCompactMode(), false);
|
||||
});
|
||||
|
||||
test('announcement identity keeps the date and first 30 content characters', () => {
|
||||
assert.equal(
|
||||
getAnnouncementKey({ publishDate: '2025-01-01', content: 'a'.repeat(40) }),
|
||||
`2025-01-01-${'a'.repeat(30)}`,
|
||||
);
|
||||
assert.equal(getAnnouncementKey({}), '-');
|
||||
assert.equal(getAnnouncementKey(null), '-');
|
||||
});
|
||||
|
||||
const first = { publishDate: '2025-01-01', content: 'First' };
|
||||
const second = { publishDate: '2025-01-02', content: 'Second' };
|
||||
|
||||
test('unread keys preserve announcement order and duplicate counts', () => {
|
||||
const notices = [first, second, second];
|
||||
const readKeys = [getAnnouncementKey(first)];
|
||||
assert.deepEqual(getUnreadAnnouncementKeys(notices, readKeys), [
|
||||
getAnnouncementKey(second),
|
||||
getAnnouncementKey(second),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
getUnreadAnnouncementKeys(notices, []),
|
||||
notices.map(getAnnouncementKey),
|
||||
);
|
||||
assert.deepEqual(
|
||||
getUnreadAnnouncementKeys(notices, notices.map(getAnnouncementKey)),
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(getUnreadAnnouncementKeys([], readKeys), []);
|
||||
});
|
||||
|
||||
test('merging read keys retains history, deduplicates, and does not mutate inputs', () => {
|
||||
const notices = [first, second, first];
|
||||
const readKeys = ['old', getAnnouncementKey(first), 'old'];
|
||||
assert.deepEqual(mergeAnnouncementReadKeys(notices, readKeys), [
|
||||
'old',
|
||||
getAnnouncementKey(first),
|
||||
getAnnouncementKey(second),
|
||||
]);
|
||||
assert.deepEqual(readKeys, ['old', getAnnouncementKey(first), 'old']);
|
||||
assert.deepEqual(notices, [first, second, first]);
|
||||
});
|
||||
|
||||
test('notification persistence uses the existing key and merges the latest stored history', (t) => {
|
||||
let stored = '["old"]';
|
||||
mockStorage(t, {
|
||||
getItem(key) {
|
||||
assert.equal(key, 'notice_read_keys');
|
||||
return stored;
|
||||
},
|
||||
setItem(key, value) {
|
||||
assert.equal(key, NOTICE_READ_KEYS_KEY);
|
||||
stored = value;
|
||||
},
|
||||
});
|
||||
markAnnouncementsRead([first, first]);
|
||||
assert.deepEqual(JSON.parse(stored), ['old', getAnnouncementKey(first)]);
|
||||
stored = JSON.stringify([...JSON.parse(stored), 'another-tab']);
|
||||
markAnnouncementsRead([second]);
|
||||
assert.deepEqual(JSON.parse(stored), [
|
||||
'old',
|
||||
getAnnouncementKey(first),
|
||||
'another-tab',
|
||||
getAnnouncementKey(second),
|
||||
]);
|
||||
});
|
||||
|
||||
test('invalid notice storage is treated as unread and can be repaired on write', (t) => {
|
||||
let stored;
|
||||
mockStorage(t, {
|
||||
getItem: () => stored,
|
||||
setItem: (_key, value) => {
|
||||
stored = value;
|
||||
},
|
||||
});
|
||||
for (const json of [...invalidJson, '{}']) {
|
||||
stored = json;
|
||||
assert.deepEqual(readNoticeReadKeys(), []);
|
||||
assert.deepEqual(getUnreadAnnouncementKeys([first], readNoticeReadKeys()), [
|
||||
getAnnouncementKey(first),
|
||||
]);
|
||||
markAnnouncementsRead([first]);
|
||||
assert.deepEqual(JSON.parse(stored), [getAnnouncementKey(first)]);
|
||||
}
|
||||
});
|
||||
|
||||
test('notification write failures propagate instead of reporting a saved read state', (t) => {
|
||||
const failure = new Error('Quota exceeded');
|
||||
mockStorage(t, {
|
||||
getItem: () => '[]',
|
||||
setItem() {
|
||||
throw failure;
|
||||
},
|
||||
});
|
||||
assert.throws(
|
||||
() => markAnnouncementsRead([first]),
|
||||
(error) => error === failure,
|
||||
);
|
||||
});
|
||||
|
||||
test('compact parsing preserves global defaults, per-table selection and truthiness', () => {
|
||||
const json = '{"global":true,"tokens":false,"channels":"enabled","logs":0}';
|
||||
assert.equal(parseTableCompactMode(json), true);
|
||||
assert.equal(parseTableCompactMode(json, 'tokens'), false);
|
||||
assert.equal(parseTableCompactMode(json, 'channels'), true);
|
||||
assert.equal(parseTableCompactMode(json, 'logs'), false);
|
||||
assert.equal(parseTableCompactMode(json, 'missing'), false);
|
||||
});
|
||||
|
||||
test('compact storage-event payloads use the same fallback as initial reads', (t) => {
|
||||
let stored;
|
||||
mockStorage(t, { getItem: () => stored });
|
||||
for (const json of [...invalidJson, '[]', '[true]', '{"global":true}']) {
|
||||
stored = json;
|
||||
assert.equal(parseTableCompactMode(json), getTableCompactMode());
|
||||
}
|
||||
assert.equal(parseTableCompactMode(null), false);
|
||||
});
|
||||
|
||||
test('compact writes preserve other table preferences and the storage key', (t) => {
|
||||
let stored = '{"channels":true,"tokens":false}';
|
||||
mockStorage(t, {
|
||||
getItem(key) {
|
||||
assert.equal(key, 'table_compact_modes');
|
||||
return stored;
|
||||
},
|
||||
setItem(key, value) {
|
||||
assert.equal(key, TABLE_COMPACT_MODES_KEY);
|
||||
stored = value;
|
||||
},
|
||||
});
|
||||
assert.equal(setTableCompactMode(true), undefined);
|
||||
setTableCompactMode(true, 'tokens');
|
||||
assert.deepEqual(JSON.parse(stored), {
|
||||
channels: true,
|
||||
tokens: true,
|
||||
global: true,
|
||||
});
|
||||
setTableCompactMode(false, 'channels');
|
||||
assert.equal(getTableCompactMode('channels'), false);
|
||||
});
|
||||
|
||||
test('invalid compact preferences can be replaced by a valid object on write', (t) => {
|
||||
let stored;
|
||||
mockStorage(t, {
|
||||
getItem: () => stored,
|
||||
setItem: (_key, value) => {
|
||||
stored = value;
|
||||
},
|
||||
});
|
||||
for (const json of [...invalidJson, '[]', '[true]']) {
|
||||
stored = json;
|
||||
assert.equal(getTableCompactMode(), false);
|
||||
setTableCompactMode(true);
|
||||
assert.deepEqual(JSON.parse(stored), { global: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('compact write failures remain non-fatal', (t) => {
|
||||
mockStorage(t, {
|
||||
getItem: () => '{}',
|
||||
setItem() {
|
||||
throw new Error('Quota exceeded');
|
||||
},
|
||||
});
|
||||
assert.doesNotThrow(() => setTableCompactMode(true));
|
||||
});
|
||||
|
||||
test('blocked storage access is guarded for reads and compact writes but not notice writes', (t) => {
|
||||
mockStorage(t, undefined);
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
get() {
|
||||
throw new Error('Storage blocked');
|
||||
},
|
||||
});
|
||||
assert.deepEqual(readNoticeReadKeys(), []);
|
||||
assert.equal(getTableCompactMode(), false);
|
||||
assert.doesNotThrow(() => setTableCompactMode(true));
|
||||
assert.throws(() => markAnnouncementsRead([first]), /Storage blocked/);
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { TABLE_COMPACT_MODES_KEY } from '../constants/common.constant.js';
|
||||
import { parseStoredObject, readStorageValue } from './storageJson.js';
|
||||
|
||||
export function parseTableCompactMode(json, tableKey = 'global') {
|
||||
const modes = parseStoredObject(json);
|
||||
return !!modes[tableKey];
|
||||
}
|
||||
|
||||
export function getTableCompactMode(tableKey = 'global') {
|
||||
return parseTableCompactMode(
|
||||
readStorageValue(TABLE_COMPACT_MODES_KEY),
|
||||
tableKey,
|
||||
);
|
||||
}
|
||||
|
||||
export function setTableCompactMode(compact, tableKey = 'global') {
|
||||
const modes = parseStoredObject(readStorageValue(TABLE_COMPACT_MODES_KEY));
|
||||
modes[tableKey] = compact;
|
||||
try {
|
||||
localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes));
|
||||
} catch {
|
||||
// Compact mode remains usable in memory when preferences cannot be saved.
|
||||
}
|
||||
}
|
||||
+6
-28
@@ -26,7 +26,6 @@ import {
|
||||
THINK_TAG_REGEX,
|
||||
MESSAGE_ROLES,
|
||||
} from '../constants/playground.constants';
|
||||
import { TABLE_COMPACT_MODES_KEY } from '../constants';
|
||||
import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile';
|
||||
// 官方价折扣计算(纯函数):管理端与市场页共用
|
||||
import { buildOfficialComparison, formatDiscountLabel } from './officialPrice';
|
||||
@@ -735,33 +734,10 @@ export const formatDateTimeString = (date) => {
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}`;
|
||||
};
|
||||
|
||||
function readTableCompactModes() {
|
||||
try {
|
||||
const json = localStorage.getItem(TABLE_COMPACT_MODES_KEY);
|
||||
return json ? JSON.parse(json) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeTableCompactModes(modes) {
|
||||
try {
|
||||
localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export function getTableCompactMode(tableKey = 'global') {
|
||||
const modes = readTableCompactModes();
|
||||
return !!modes[tableKey];
|
||||
}
|
||||
|
||||
export function setTableCompactMode(compact, tableKey = 'global') {
|
||||
const modes = readTableCompactModes();
|
||||
modes[tableKey] = compact;
|
||||
writeTableCompactModes(modes);
|
||||
}
|
||||
export {
|
||||
getTableCompactMode,
|
||||
setTableCompactMode,
|
||||
} from './tableCompactMode.js';
|
||||
|
||||
// -------------------------------
|
||||
// Select 组件统一过滤逻辑
|
||||
@@ -1111,6 +1087,7 @@ export const createCardProPagination = ({
|
||||
isMobile = false,
|
||||
pageSizeOpts = [10, 20, 50, 100],
|
||||
showSizeChanger = true,
|
||||
preventPageChangeOnPageSizeChange = false,
|
||||
t = (key) => key,
|
||||
}) => {
|
||||
if (!total || total <= 0) return null;
|
||||
@@ -1140,6 +1117,7 @@ export const createCardProPagination = ({
|
||||
showSizeChanger={showSizeChanger}
|
||||
onPageSizeChange={onPageSizeChange}
|
||||
onPageChange={onPageChange}
|
||||
preventPageChangeOnPageSizeChange={preventPageChangeOnPageSizeChange}
|
||||
size={isMobile ? 'small' : 'default'}
|
||||
showQuickJumper={isMobile}
|
||||
showTotal
|
||||
|
||||
@@ -17,49 +17,31 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
getUnreadAnnouncementKeys,
|
||||
markAnnouncementsRead,
|
||||
readNoticeReadKeys,
|
||||
} from '../../helpers/notificationReadState.js';
|
||||
|
||||
const EMPTY_ANNOUNCEMENTS = [];
|
||||
|
||||
export const useNotifications = (statusState) => {
|
||||
const [noticeVisible, setNoticeVisible] = useState(false);
|
||||
const [unreadCount, setUnreadCount] = useState(0);
|
||||
|
||||
const announcements = statusState?.status?.announcements || [];
|
||||
const announcements =
|
||||
statusState?.status?.announcements || EMPTY_ANNOUNCEMENTS;
|
||||
|
||||
// Helper functions
|
||||
const getAnnouncementKey = (a) =>
|
||||
`${a?.publishDate || ''}-${(a?.content || '').slice(0, 30)}`;
|
||||
|
||||
const calculateUnreadCount = () => {
|
||||
if (!announcements.length) return 0;
|
||||
let readKeys = [];
|
||||
try {
|
||||
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
|
||||
} catch (_) {
|
||||
readKeys = [];
|
||||
}
|
||||
const readSet = new Set(readKeys);
|
||||
return announcements.filter((a) => !readSet.has(getAnnouncementKey(a)))
|
||||
.length;
|
||||
};
|
||||
|
||||
const getUnreadKeys = () => {
|
||||
const getUnreadKeys = useCallback(() => {
|
||||
if (!announcements.length) return [];
|
||||
let readKeys = [];
|
||||
try {
|
||||
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
|
||||
} catch (_) {
|
||||
readKeys = [];
|
||||
}
|
||||
const readSet = new Set(readKeys);
|
||||
return announcements
|
||||
.filter((a) => !readSet.has(getAnnouncementKey(a)))
|
||||
.map(getAnnouncementKey);
|
||||
};
|
||||
return getUnreadAnnouncementKeys(announcements, readNoticeReadKeys());
|
||||
}, [announcements]);
|
||||
|
||||
// Effects
|
||||
useEffect(() => {
|
||||
setUnreadCount(calculateUnreadCount());
|
||||
}, [announcements]);
|
||||
setUnreadCount(getUnreadKeys().length);
|
||||
}, [getUnreadKeys]);
|
||||
|
||||
// Actions
|
||||
const handleNoticeOpen = () => {
|
||||
@@ -69,16 +51,7 @@ export const useNotifications = (statusState) => {
|
||||
const handleNoticeClose = () => {
|
||||
setNoticeVisible(false);
|
||||
if (announcements.length) {
|
||||
let readKeys = [];
|
||||
try {
|
||||
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
|
||||
} catch (_) {
|
||||
readKeys = [];
|
||||
}
|
||||
const mergedKeys = Array.from(
|
||||
new Set([...readKeys, ...announcements.map(getAnnouncementKey)]),
|
||||
);
|
||||
localStorage.setItem('notice_read_keys', JSON.stringify(mergedKeys));
|
||||
markAnnouncementsRead(announcements);
|
||||
}
|
||||
setUnreadCount(0);
|
||||
};
|
||||
|
||||
@@ -18,8 +18,12 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { getTableCompactMode, setTableCompactMode } from '../../helpers';
|
||||
import { TABLE_COMPACT_MODES_KEY } from '../../constants';
|
||||
import {
|
||||
getTableCompactMode,
|
||||
parseTableCompactMode,
|
||||
setTableCompactMode,
|
||||
} from '../../helpers/tableCompactMode.js';
|
||||
import { TABLE_COMPACT_MODES_KEY } from '../../constants/common.constant.js';
|
||||
|
||||
/**
|
||||
* 自定义 Hook:管理表格紧凑/自适应模式
|
||||
@@ -42,12 +46,7 @@ export function useTableCompactMode(tableKey = 'global') {
|
||||
useEffect(() => {
|
||||
const handleStorage = (e) => {
|
||||
if (e.key === TABLE_COMPACT_MODES_KEY) {
|
||||
try {
|
||||
const modes = JSON.parse(e.newValue || '{}');
|
||||
setCompactModeState(!!modes[tableKey]);
|
||||
} catch {
|
||||
// ignore parse error
|
||||
}
|
||||
setCompactModeState(parseTableCompactMode(e.newValue, tableKey));
|
||||
}
|
||||
};
|
||||
window.addEventListener('storage', handleStorage);
|
||||
|
||||
+11
-28
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
import { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError } from '../../helpers';
|
||||
import { buildOrgLogFilters } from '../../helpers/orgLogFilters.js';
|
||||
|
||||
// 获取企业X-Org-Id header
|
||||
const getOrgHeaders = (orgId) => ({
|
||||
@@ -239,19 +240,15 @@ export function useOrgMemberLogs(orgId) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const fetch = useCallback(
|
||||
async (
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
{ userId, startTimestamp, endTimestamp, modelName } = {},
|
||||
) => {
|
||||
async (page = 1, pageSize = 20, filters = {}) => {
|
||||
if (!orgId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = { p: page, page_size: pageSize };
|
||||
if (userId) params.user_id = userId;
|
||||
if (startTimestamp) params.start_timestamp = startTimestamp;
|
||||
if (endTimestamp) params.end_timestamp = endTimestamp;
|
||||
if (modelName) params.model_name = modelName;
|
||||
const params = {
|
||||
p: page,
|
||||
page_size: pageSize,
|
||||
...buildOrgLogFilters(filters),
|
||||
};
|
||||
|
||||
const res = await API.get('/api/org/logs', {
|
||||
headers: getOrgHeaders(orgId),
|
||||
@@ -292,18 +289,11 @@ export function useOrgLogsStat(orgId) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const fetch = useCallback(
|
||||
async (
|
||||
{ userId, startTimestamp, endTimestamp, modelName } = {},
|
||||
noCache = false,
|
||||
) => {
|
||||
async (filters = {}, noCache = false) => {
|
||||
if (!orgId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = {};
|
||||
if (userId) params.user_id = userId;
|
||||
if (startTimestamp) params.start_timestamp = startTimestamp;
|
||||
if (endTimestamp) params.end_timestamp = endTimestamp;
|
||||
if (modelName) params.model_name = modelName;
|
||||
const params = buildOrgLogFilters(filters);
|
||||
if (noCache) params.nocache = 1;
|
||||
|
||||
const res = await API.get('/api/org/logs/stat', {
|
||||
@@ -346,18 +336,11 @@ export function useOrgMemberRanking(orgId) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const fetch = useCallback(
|
||||
async (
|
||||
{ userId, startTimestamp, endTimestamp, modelName, limit } = {},
|
||||
noCache = false,
|
||||
) => {
|
||||
async ({ limit, ...filters } = {}, noCache = false) => {
|
||||
if (!orgId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = {};
|
||||
if (userId) params.user_id = userId;
|
||||
if (startTimestamp) params.start_timestamp = startTimestamp;
|
||||
if (endTimestamp) params.end_timestamp = endTimestamp;
|
||||
if (modelName) params.model_name = modelName;
|
||||
const params = buildOrgLogFilters(filters);
|
||||
if (limit) params.limit = limit;
|
||||
if (noCache) params.nocache = 1;
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
timestamp2string,
|
||||
} from '../../helpers';
|
||||
import { EVENTS, emit } from '../../helpers/eventBus';
|
||||
import { resolveColumnVisibility } from '../../helpers/columnVisibility';
|
||||
import { ITEMS_PER_PAGE } from '../../constants';
|
||||
import { useTableCompactMode } from '../common/useTableCompactMode';
|
||||
|
||||
@@ -136,24 +137,13 @@ export const useTaskLogsData = () => {
|
||||
// Load saved column preferences from localStorage
|
||||
useEffect(() => {
|
||||
const savedColumns = localStorage.getItem(STORAGE_KEY);
|
||||
if (savedColumns) {
|
||||
try {
|
||||
const parsed = JSON.parse(savedColumns);
|
||||
const defaults = getDefaultColumnVisibility();
|
||||
const merged = { ...defaults, ...parsed };
|
||||
|
||||
// For non-admin users, force-hide admin-only columns (does not touch admin settings)
|
||||
if (!isAdminUser) {
|
||||
merged[COLUMN_KEYS.CHANNEL] = false;
|
||||
}
|
||||
setVisibleColumns(merged);
|
||||
} catch (e) {
|
||||
console.error('Failed to parse saved column preferences', e);
|
||||
initDefaultColumns();
|
||||
}
|
||||
} else {
|
||||
initDefaultColumns();
|
||||
}
|
||||
setVisibleColumns(
|
||||
resolveColumnVisibility(
|
||||
getDefaultColumnVisibility(),
|
||||
savedColumns,
|
||||
isAdminUser ? [] : [COLUMN_KEYS.CHANNEL],
|
||||
),
|
||||
);
|
||||
}, []);
|
||||
|
||||
// Get default column visibility based on user role
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
import { ITEMS_PER_PAGE } from '../../constants';
|
||||
import { useTableCompactMode } from '../common/useTableCompactMode';
|
||||
import { EVENTS, subscribe } from '../../helpers/eventBus';
|
||||
import { resolveColumnVisibility } from '../../helpers/columnVisibility';
|
||||
|
||||
export const useLogsData = () => {
|
||||
const { t } = useTranslation();
|
||||
@@ -191,26 +192,15 @@ export const useLogsData = () => {
|
||||
// Load saved column preferences from localStorage
|
||||
useEffect(() => {
|
||||
const savedColumns = localStorage.getItem(STORAGE_KEY);
|
||||
if (savedColumns) {
|
||||
try {
|
||||
const parsed = JSON.parse(savedColumns);
|
||||
const defaults = getDefaultColumnVisibility();
|
||||
const merged = { ...defaults, ...parsed };
|
||||
|
||||
// For non-admin users, force-hide admin-only columns (does not touch admin settings)
|
||||
if (!isAdminUser) {
|
||||
merged[COLUMN_KEYS.CHANNEL] = false;
|
||||
merged[COLUMN_KEYS.USERNAME] = false;
|
||||
merged[COLUMN_KEYS.RETRY] = false;
|
||||
}
|
||||
setVisibleColumns(merged);
|
||||
} catch (e) {
|
||||
console.error('Failed to parse saved column preferences', e);
|
||||
initDefaultColumns();
|
||||
}
|
||||
} else {
|
||||
initDefaultColumns();
|
||||
}
|
||||
setVisibleColumns(
|
||||
resolveColumnVisibility(
|
||||
getDefaultColumnVisibility(),
|
||||
savedColumns,
|
||||
isAdminUser
|
||||
? []
|
||||
: [COLUMN_KEYS.CHANNEL, COLUMN_KEYS.USERNAME, COLUMN_KEYS.RETRY],
|
||||
),
|
||||
);
|
||||
}, []);
|
||||
|
||||
// Get default column visibility based on user role
|
||||
|
||||
@@ -72,17 +72,22 @@ export const useUsersData = () => {
|
||||
// Load users data
|
||||
const loadUsers = async (startIdx, pageSize) => {
|
||||
setLoading(true);
|
||||
const res = await API.get(`/api/user/?p=${startIdx}&page_size=${pageSize}`);
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
const newPageData = data.items;
|
||||
setActivePage(data.page);
|
||||
setUserCount(data.total);
|
||||
setUserFormat(newPageData);
|
||||
} else {
|
||||
showError(message);
|
||||
try {
|
||||
const res = await API.get(
|
||||
`/api/user/?p=${startIdx}&page_size=${pageSize}`,
|
||||
);
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
const newPageData = data.items;
|
||||
setActivePage(data.page);
|
||||
setUserCount(data.total);
|
||||
setUserFormat(newPageData);
|
||||
} else {
|
||||
showError(message);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
// Search users with keyword and group
|
||||
@@ -100,24 +105,32 @@ export const useUsersData = () => {
|
||||
}
|
||||
|
||||
if (searchKeyword === '' && searchGroup === '') {
|
||||
// If keyword is blank, load files instead
|
||||
// If both filters are blank, load users instead
|
||||
await loadUsers(startIdx, pageSize);
|
||||
return;
|
||||
}
|
||||
setSearching(true);
|
||||
const res = await API.get(
|
||||
`/api/user/search?keyword=${searchKeyword}&group=${searchGroup}&p=${startIdx}&page_size=${pageSize}`,
|
||||
);
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
const newPageData = data.items;
|
||||
setActivePage(data.page);
|
||||
setUserCount(data.total);
|
||||
setUserFormat(newPageData);
|
||||
} else {
|
||||
showError(message);
|
||||
try {
|
||||
const res = await API.get('/api/user/search', {
|
||||
params: {
|
||||
keyword: searchKeyword,
|
||||
group: searchGroup,
|
||||
p: startIdx,
|
||||
page_size: pageSize,
|
||||
},
|
||||
});
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
const newPageData = data.items;
|
||||
setActivePage(data.page);
|
||||
setUserCount(data.total);
|
||||
setUserFormat(newPageData);
|
||||
} else {
|
||||
showError(message);
|
||||
}
|
||||
} finally {
|
||||
setSearching(false);
|
||||
}
|
||||
setSearching(false);
|
||||
};
|
||||
|
||||
// Manage user operations (promote, demote, enable, disable, delete)
|
||||
@@ -191,12 +204,9 @@ export const useUsersData = () => {
|
||||
// Handle page change
|
||||
const handlePageChange = (page) => {
|
||||
setActivePage(page);
|
||||
const { searchKeyword, searchGroup } = getFormValues();
|
||||
if (searchKeyword === '' && searchGroup === '') {
|
||||
loadUsers(page, pageSize).then();
|
||||
} else {
|
||||
searchUsers(page, pageSize, searchKeyword, searchGroup).then();
|
||||
}
|
||||
refresh(page).catch((reason) => {
|
||||
showError(reason);
|
||||
});
|
||||
};
|
||||
|
||||
// Handle page size change
|
||||
@@ -204,11 +214,9 @@ export const useUsersData = () => {
|
||||
localStorage.setItem('page-size', size + '');
|
||||
setPageSize(size);
|
||||
setActivePage(1);
|
||||
loadUsers(activePage, size)
|
||||
.then()
|
||||
.catch((reason) => {
|
||||
showError(reason);
|
||||
});
|
||||
await refresh(1, size).catch((reason) => {
|
||||
showError(reason);
|
||||
});
|
||||
};
|
||||
|
||||
// Handle table row styling for disabled/deleted users
|
||||
@@ -225,13 +233,8 @@ export const useUsersData = () => {
|
||||
};
|
||||
|
||||
// Refresh data
|
||||
const refresh = async (page = activePage) => {
|
||||
const { searchKeyword, searchGroup } = getFormValues();
|
||||
if (searchKeyword === '' && searchGroup === '') {
|
||||
await loadUsers(page, pageSize);
|
||||
} else {
|
||||
await searchUsers(page, pageSize, searchKeyword, searchGroup);
|
||||
}
|
||||
const refresh = async (page = activePage, size = pageSize) => {
|
||||
await searchUsers(page, size);
|
||||
};
|
||||
|
||||
// Fetch groups data
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import test from 'node:test';
|
||||
import { setImmediate } from 'node:timers/promises';
|
||||
import { runInNewContext } from 'node:vm';
|
||||
import axios from 'axios';
|
||||
import { transformWithEsbuild } from 'vite';
|
||||
|
||||
const filename = new URL('./useUsersData.jsx', import.meta.url);
|
||||
const { code } = await transformWithEsbuild(
|
||||
await readFile(filename, 'utf8'),
|
||||
filename.pathname,
|
||||
{ loader: 'jsx', format: 'cjs', target: 'node22' },
|
||||
);
|
||||
const defaultPageSize = 10;
|
||||
|
||||
// Execute the real exported hook with state snapshots and mount effects only.
|
||||
// This controller harness does not model React scheduling, StrictMode, DOM, or HTTP.
|
||||
async function createHarness() {
|
||||
const states = [];
|
||||
const effects = [];
|
||||
const requests = [];
|
||||
const errors = [];
|
||||
const storage = new Map();
|
||||
let cursor = 0;
|
||||
let mounting = true;
|
||||
let respond = (request) => {
|
||||
if (request.path === '/api/group/') {
|
||||
return { data: { data: ['default'] } };
|
||||
}
|
||||
return {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
page: Number(request.params.p),
|
||||
total: 1,
|
||||
items: [{ id: 42, username: 'test-user' }],
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
const modules = {
|
||||
react: {
|
||||
useState(initialValue) {
|
||||
const index = cursor++;
|
||||
if (mounting) {
|
||||
states[index] =
|
||||
typeof initialValue === 'function' ? initialValue() : initialValue;
|
||||
}
|
||||
return [
|
||||
states[index],
|
||||
(value) => {
|
||||
states[index] =
|
||||
typeof value === 'function' ? value(states[index]) : value;
|
||||
},
|
||||
];
|
||||
},
|
||||
useEffect(effect) {
|
||||
if (mounting) effects.push(effect);
|
||||
},
|
||||
},
|
||||
'react-i18next': { useTranslation: () => ({ t: (value) => value }) },
|
||||
'../../helpers': {
|
||||
API: {
|
||||
async get(url, config) {
|
||||
// Use Axios's actual serializer, but never send a network request.
|
||||
const parsed = new URL(
|
||||
axios.getUri({ ...config, url }),
|
||||
'https://example.test',
|
||||
);
|
||||
const request = {
|
||||
path: parsed.pathname,
|
||||
params: Object.fromEntries(parsed.searchParams),
|
||||
};
|
||||
requests.push(request);
|
||||
return respond(request);
|
||||
},
|
||||
},
|
||||
showError: (error) => errors.push(error),
|
||||
showSuccess: () => {},
|
||||
},
|
||||
'../../constants': { ITEMS_PER_PAGE: defaultPageSize },
|
||||
'../common/useTableCompactMode': {
|
||||
useTableCompactMode: () => [false, () => {}],
|
||||
},
|
||||
};
|
||||
const module = { exports: {} };
|
||||
runInNewContext(code, {
|
||||
module,
|
||||
exports: module.exports,
|
||||
require(name) {
|
||||
assert.ok(Object.hasOwn(modules, name), `Unexpected import: ${name}`);
|
||||
return modules[name];
|
||||
},
|
||||
localStorage: { setItem: (key, value) => storage.set(key, value) },
|
||||
});
|
||||
const render = () => {
|
||||
cursor = 0;
|
||||
return module.exports.useUsersData();
|
||||
};
|
||||
render();
|
||||
mounting = false;
|
||||
effects.forEach((effect) => effect());
|
||||
await setImmediate();
|
||||
return {
|
||||
render,
|
||||
requests,
|
||||
errors,
|
||||
storage,
|
||||
setResponder(next) {
|
||||
respond = next;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function assertRequest(request, page, size, filters = {}) {
|
||||
const keyword = filters.searchKeyword || '';
|
||||
const group = filters.searchGroup || '';
|
||||
assert.deepEqual(request, {
|
||||
path: keyword || group ? '/api/user/search' : '/api/user/',
|
||||
params: {
|
||||
...(keyword || group ? { keyword, group } : {}),
|
||||
p: String(page),
|
||||
page_size: String(size),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
test('mount keeps the initial page-zero fetch and formats returned users', async () => {
|
||||
const harness = await createHarness();
|
||||
assertRequest(harness.requests[0], 0, defaultPageSize);
|
||||
assert.equal(harness.requests[1].path, '/api/group/');
|
||||
const data = harness.render();
|
||||
assert.equal(data.loading, false);
|
||||
assert.equal(data.searching, false);
|
||||
assert.equal(data.activePage, 0);
|
||||
assert.equal(data.userCount, 1);
|
||||
assert.equal(data.users[0].key, 42);
|
||||
});
|
||||
|
||||
for (const [name, filters] of Object.entries({
|
||||
unfiltered: { searchKeyword: '', searchGroup: '' },
|
||||
keyword: { searchKeyword: 'alice', searchGroup: '' },
|
||||
group: { searchKeyword: '', searchGroup: 'staff' },
|
||||
'both filters with reserved characters': {
|
||||
searchKeyword: 'alice & bob+#?=user',
|
||||
searchGroup: 'staff&group=other +#',
|
||||
},
|
||||
})) {
|
||||
test(`page-size change from a later page uses page 1, new size, and live form values: ${name}`, async () => {
|
||||
const harness = await createHarness();
|
||||
let values = { searchKeyword: '', searchGroup: '' };
|
||||
harness.render().setFormApi({ getValues: () => values });
|
||||
harness.render().handlePageChange(4);
|
||||
await setImmediate();
|
||||
assert.equal(harness.render().activePage, 4);
|
||||
values = filters;
|
||||
harness.requests.length = 0;
|
||||
|
||||
const pending = harness.render().handlePageSizeChange(25);
|
||||
assert.equal(harness.render().activePage, 1);
|
||||
assert.equal(harness.render().pageSize, 25);
|
||||
await pending;
|
||||
|
||||
assert.equal(harness.requests.length, 1);
|
||||
assertRequest(harness.requests[0], 1, 25, filters);
|
||||
assert.equal(harness.storage.get('page-size'), '25');
|
||||
assert.equal(harness.render().activePage, 1);
|
||||
assert.equal(harness.render().loading, false);
|
||||
assert.equal(harness.render().searching, false);
|
||||
|
||||
harness.render().handlePageChange(3);
|
||||
await setImmediate();
|
||||
assertRequest(harness.requests[1], 3, 25, filters);
|
||||
await harness.render().refresh();
|
||||
assertRequest(harness.requests[2], 3, 25, filters);
|
||||
});
|
||||
}
|
||||
|
||||
test('form search still reads current filters and supports explicit filters and blank fallback', async () => {
|
||||
const harness = await createHarness();
|
||||
let values = { searchKeyword: 'form keyword', searchGroup: 'form group' };
|
||||
harness.render().setFormApi({ getValues: () => values });
|
||||
harness.requests.length = 0;
|
||||
|
||||
await harness.render().searchUsers(1, 20);
|
||||
assertRequest(harness.requests[0], 1, 20, values);
|
||||
await harness.render().searchUsers(2, 20, 'explicit', 'override');
|
||||
assertRequest(harness.requests[1], 2, 20, {
|
||||
searchKeyword: 'explicit',
|
||||
searchGroup: 'override',
|
||||
});
|
||||
values = {};
|
||||
await harness.render().searchUsers(1, 20);
|
||||
assertRequest(harness.requests[2], 1, 20);
|
||||
});
|
||||
|
||||
for (const action of ['loadUsers', 'searchUsers', 'blank search fallback']) {
|
||||
test(`${action} clears its pending flag and propagates request rejection`, async () => {
|
||||
const harness = await createHarness();
|
||||
const failure = new Error('request rejected');
|
||||
let rejectRequest;
|
||||
harness.setResponder(
|
||||
() => new Promise((resolve, reject) => (rejectRequest = reject)),
|
||||
);
|
||||
const data = harness.render();
|
||||
const pending =
|
||||
action === 'loadUsers'
|
||||
? data.loadUsers(2, 10)
|
||||
: data.searchUsers(2, 10, action === 'searchUsers' ? 'alice' : '', '');
|
||||
const flag = action === 'searchUsers' ? 'searching' : 'loading';
|
||||
assert.equal(harness.render()[flag], true);
|
||||
const rejected = assert.rejects(pending, (error) => error === failure);
|
||||
rejectRequest(failure);
|
||||
await rejected;
|
||||
assert.equal(harness.render().loading, false);
|
||||
assert.equal(harness.render().searching, false);
|
||||
});
|
||||
}
|
||||
|
||||
for (const handler of ['handlePageSizeChange', 'handlePageChange']) {
|
||||
for (const filtered of [false, true]) {
|
||||
test(`${handler} reports rejected ${filtered ? 'filtered' : 'unfiltered'} requests and clears flags`, async () => {
|
||||
const harness = await createHarness();
|
||||
harness.render().setFormApi({
|
||||
getValues: () => ({ searchKeyword: filtered ? 'alice' : '' }),
|
||||
});
|
||||
const failure = new Error('pagination request rejected');
|
||||
harness.setResponder(() => Promise.reject(failure));
|
||||
await harness.render()[handler](25);
|
||||
await setImmediate();
|
||||
assert.deepEqual(harness.errors, [failure]);
|
||||
assert.equal(harness.render().loading, false);
|
||||
assert.equal(harness.render().searching, false);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -95,7 +95,7 @@ import MessageSelectableWrapper from '../../components/playground/MessageSelecta
|
||||
import FloatingButtons from '../../components/playground/FloatingButtons';
|
||||
import SessionSidebar from '../../components/playground/SessionSidebar';
|
||||
import KeyboardShortcutsModal from '../../components/playground/KeyboardShortcutsModal';
|
||||
import { PlaygroundProvider } from '../../contexts/PlaygroundContext';
|
||||
import { PlaygroundProvider } from '../../context/Playground';
|
||||
|
||||
const Playground = ({ isExperienceMode = false }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import test from 'node:test';
|
||||
import { loadConfigFromFile, loadEnv, createServer } from 'vite';
|
||||
|
||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||
const html = '<!--umami--><!--Google Analytics-->';
|
||||
|
||||
async function fixture(run) {
|
||||
const dir = await mkdtemp(path.join(root, '.env-test-'));
|
||||
try {
|
||||
await writeFile(
|
||||
path.join(dir, 'vite.config.js'),
|
||||
await readFile(path.join(root, 'vite.config.js')),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(dir, '.env.development'),
|
||||
'DEV_PROXY_TARGET=http://localhost:13001\nVITE_REACT_APP_SERVER_URL=https://dev.example.com\nVITE_CLOUD_BRAIN_UI_ENABLED=true\nVITE_UMAMI_WEBSITE_ID=dev-id\nVITE_UMAMI_SCRIPT_URL=https://dev.example.com/script.js\n',
|
||||
);
|
||||
await writeFile(
|
||||
path.join(dir, '.env.production'),
|
||||
'VITE_REACT_APP_SERVER_URL=https://prod.example.com\nVITE_CLOUD_BRAIN_UI_ENABLED=false\nVITE_GOOGLE_ANALYTICS_ID=G-PROD\n',
|
||||
);
|
||||
await run(dir);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function config(dir, mode) {
|
||||
return (
|
||||
await loadConfigFromFile(
|
||||
{ command: mode === 'development' ? 'serve' : 'build', mode },
|
||||
path.join(dir, 'vite.config.js'),
|
||||
)
|
||||
).config;
|
||||
}
|
||||
|
||||
function analytics(config) {
|
||||
return config.plugins
|
||||
.find((plugin) => plugin.name === 'inject-analytics')
|
||||
.transformIndexHtml(html);
|
||||
}
|
||||
|
||||
test('development and production isolate API, feature flag and analytics settings', async () => {
|
||||
await fixture(async (dir) => {
|
||||
const dev = await config(dir, 'development');
|
||||
const prod = await config(dir, 'production');
|
||||
assert.match(analytics(dev), /dev-id/);
|
||||
assert.match(analytics(dev), /https:\/\/dev.example.com\/script.js/);
|
||||
assert.doesNotMatch(analytics(dev), /G-PROD/);
|
||||
assert.match(analytics(prod), /G-PROD/);
|
||||
assert.doesNotMatch(analytics(prod), /dev-id/);
|
||||
for (const proxy of Object.values(dev.server.proxy)) {
|
||||
assert.equal(proxy.target, 'http://localhost:13001');
|
||||
assert.equal(proxy.changeOrigin, true);
|
||||
}
|
||||
assert.equal(dev.server.proxy['/v1'].ws, true);
|
||||
for (const [mode, url, flag] of [
|
||||
['development', 'https://dev.example.com', 'true'],
|
||||
['production', 'https://prod.example.com', 'false'],
|
||||
]) {
|
||||
const env = loadEnv(mode, dir);
|
||||
assert.equal(env.VITE_REACT_APP_SERVER_URL, url);
|
||||
assert.equal(env.VITE_CLOUD_BRAIN_UI_ENABLED, flag);
|
||||
assert.equal(env.DEV_PROXY_TARGET, undefined);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('mode local overrides and CI variables reach the Vite plugins and proxy', async () => {
|
||||
await fixture(async (dir) => {
|
||||
await writeFile(
|
||||
path.join(dir, '.env.development.local'),
|
||||
'DEV_PROXY_TARGET=http://localhost:13002\nVITE_UMAMI_WEBSITE_ID=local-id\n',
|
||||
);
|
||||
assert.match(analytics(await config(dir, 'development')), /local-id/);
|
||||
assert.equal(
|
||||
(await config(dir, 'development')).server.proxy['/api'].target,
|
||||
'http://localhost:13002',
|
||||
);
|
||||
const previous = process.env.VITE_UMAMI_WEBSITE_ID;
|
||||
try {
|
||||
process.env.VITE_UMAMI_WEBSITE_ID = 'ci-id';
|
||||
assert.match(analytics(await config(dir, 'development')), /ci-id/);
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.VITE_UMAMI_WEBSITE_ID;
|
||||
else process.env.VITE_UMAMI_WEBSITE_ID = previous;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('checked-in defaults preserve same-origin behavior and disable analytics', async () => {
|
||||
for (const mode of ['development', 'production']) {
|
||||
const env = loadEnv(mode, root);
|
||||
assert.equal(env.VITE_REACT_APP_SERVER_URL, '');
|
||||
assert.equal(env.VITE_CLOUD_BRAIN_UI_ENABLED, 'false');
|
||||
assert.equal(analytics(await config(root, mode)), html);
|
||||
}
|
||||
});
|
||||
|
||||
test('development server transforms the HTML and runtime configuration modules', async () => {
|
||||
const server = await createServer({
|
||||
root,
|
||||
server: { middlewareMode: true },
|
||||
optimizeDeps: { noDiscovery: true, include: [] },
|
||||
});
|
||||
try {
|
||||
const output = await server.transformIndexHtml(
|
||||
'/',
|
||||
await readFile(path.join(root, 'index.html'), 'utf8'),
|
||||
);
|
||||
assert.match(output, /@vite\/client/);
|
||||
for (const url of [
|
||||
'/src/helpers/config.js',
|
||||
'/src/config/cloudBrainUi.js',
|
||||
]) {
|
||||
const transformed = await server.transformRequest(url);
|
||||
assert.match(transformed.code, /VITE_CLOUD_BRAIN_UI_ENABLED/);
|
||||
assert.doesNotMatch(transformed.code, /134\.175\.227\.134/);
|
||||
}
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
@@ -1,3 +1,22 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
@@ -1,3 +1,22 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
import test from 'node:test';
|
||||
import { runInNewContext } from 'node:vm';
|
||||
import React from 'react';
|
||||
import { transformWithEsbuild } from 'vite';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const PaginationFoundation =
|
||||
require('@douyinfe/semi-foundation/lib/cjs/pagination/foundation.js').default;
|
||||
|
||||
async function compile(relativePath) {
|
||||
const filename = new URL(relativePath, import.meta.url);
|
||||
const { code } = await transformWithEsbuild(
|
||||
await readFile(filename, 'utf8'),
|
||||
filename.pathname,
|
||||
{ loader: 'jsx', format: 'cjs', target: 'node22', jsx: 'transform' },
|
||||
);
|
||||
return (modules) => {
|
||||
const module = { exports: {} };
|
||||
runInNewContext(code, {
|
||||
module,
|
||||
exports: module.exports,
|
||||
window: { matchMedia: () => ({ matches: false }) },
|
||||
require(name) {
|
||||
assert.ok(Object.hasOwn(modules, name), `Unexpected import: ${name}`);
|
||||
return modules[name];
|
||||
},
|
||||
});
|
||||
return module.exports;
|
||||
};
|
||||
}
|
||||
|
||||
const loadUtils = await compile('../src/helpers/utils.jsx');
|
||||
const { createCardProPagination } = loadUtils({
|
||||
react: React,
|
||||
'@douyinfe/semi-ui': { Pagination: 'semi-pagination' },
|
||||
'../constants': { toastConstants: {} },
|
||||
'react-toastify': {},
|
||||
i18next: {},
|
||||
'../constants/playground.constants': {},
|
||||
'../hooks/common/useIsMobile': { MOBILE_BREAKPOINT: 768 },
|
||||
'./officialPrice': {},
|
||||
'./data': {},
|
||||
'./tableCompactMode.js': {},
|
||||
});
|
||||
const loadUsersPage = await compile('../src/components/table/users/index.jsx');
|
||||
|
||||
function paginationProps(element) {
|
||||
const pagination = React.Children.toArray(element.props.children).find(
|
||||
(child) => child.type === 'semi-pagination',
|
||||
);
|
||||
assert.ok(pagination, 'The helper must render Semi Pagination');
|
||||
return pagination.props;
|
||||
}
|
||||
|
||||
function foundationFor(props) {
|
||||
const state = {
|
||||
currentPage: props.currentPage,
|
||||
pageSize: props.pageSize,
|
||||
total: props.total,
|
||||
};
|
||||
// Keep the render snapshot during the event, as with React's batched updates.
|
||||
// Only view-state setters are stubbed; Semi's callback decisions run unchanged.
|
||||
return new PaginationFoundation({
|
||||
getProps: () => props,
|
||||
getStates: () => state,
|
||||
getState: (key) => state[key],
|
||||
updatePageSize: () => {},
|
||||
updateTotal: () => {},
|
||||
setCurrentPage: () => {},
|
||||
setDisabled: () => {},
|
||||
setPageList: () => {},
|
||||
notifyPageSizeChange: (size) => props.onPageSizeChange(size),
|
||||
notifyPageChange: (page) => props.onPageChange(page),
|
||||
notifyChange: () => {},
|
||||
});
|
||||
}
|
||||
|
||||
for (const option of [{}, { preventPageChangeOnPageSizeChange: false }]) {
|
||||
const mode = Object.hasOwn(option, 'preventPageChangeOnPageSizeChange')
|
||||
? 'explicit false'
|
||||
: 'default';
|
||||
test(`other tables retain Semi's resize page callback: ${mode}`, () => {
|
||||
const calls = [];
|
||||
const props = paginationProps(
|
||||
createCardProPagination({
|
||||
currentPage: 3,
|
||||
pageSize: 10,
|
||||
total: 100,
|
||||
onPageSizeChange: (size) => calls.push(['size', size]),
|
||||
onPageChange: (page) => calls.push(['page', page]),
|
||||
...option,
|
||||
}),
|
||||
);
|
||||
|
||||
foundationFor(props).changePageSize(20);
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
['size', 20],
|
||||
['page', 2],
|
||||
]);
|
||||
assert.equal(props.preventPageChangeOnPageSizeChange, false);
|
||||
});
|
||||
}
|
||||
|
||||
for (const isMobile of [false, true]) {
|
||||
test(`users resize emits only the size callback; navigation still works (${isMobile ? 'mobile' : 'desktop'})`, () => {
|
||||
const calls = [];
|
||||
const usersData = {
|
||||
activePage: 3,
|
||||
pageSize: 10,
|
||||
userCount: 100,
|
||||
handlePageSizeChange: (size) => calls.push(['size', size]),
|
||||
handlePageChange: (page) => calls.push(['page', page]),
|
||||
t: (key) => key,
|
||||
};
|
||||
const { default: UsersPage } = loadUsersPage({
|
||||
react: React,
|
||||
'../../common/ui/CardPro': 'card-pro',
|
||||
'./UsersTable': 'users-table',
|
||||
'./UsersActions': 'users-actions',
|
||||
'./UsersFilters': 'users-filters',
|
||||
'./UsersDescription': 'users-description',
|
||||
'./modals/AddUserModal': 'add-user-modal',
|
||||
'./modals/EditUserModal': 'edit-user-modal',
|
||||
'../../../hooks/users/useUsersData': { useUsersData: () => usersData },
|
||||
'../../../hooks/common/useIsMobile': { useIsMobile: () => isMobile },
|
||||
'../../../helpers/utils': { createCardProPagination },
|
||||
});
|
||||
const renderPagination = () => {
|
||||
const card = React.Children.toArray(UsersPage().props.children).find(
|
||||
(child) => child.type === 'card-pro',
|
||||
);
|
||||
assert.ok(card, 'UsersPage must pass pagination to CardPro');
|
||||
return paginationProps(card.props.paginationArea);
|
||||
};
|
||||
const props = renderPagination();
|
||||
|
||||
foundationFor(props).changePageSize(20);
|
||||
|
||||
assert.deepEqual(calls, [['size', 20]]);
|
||||
assert.equal(props.preventPageChangeOnPageSizeChange, true);
|
||||
assert.equal(props.onPageSizeChange, usersData.handlePageSizeChange);
|
||||
assert.equal(props.onPageChange, usersData.handlePageChange);
|
||||
assert.equal(props.size, isMobile ? 'small' : 'default');
|
||||
|
||||
// The hook owns the reset; verify navigation after its next render.
|
||||
usersData.activePage = 1;
|
||||
usersData.pageSize = 20;
|
||||
calls.length = 0;
|
||||
const nextProps = renderPagination();
|
||||
assert.equal(nextProps.currentPage, 1);
|
||||
assert.equal(nextProps.pageSize, 20);
|
||||
foundationFor(nextProps).goPage(2);
|
||||
assert.deepEqual(calls, [['page', 2]]);
|
||||
});
|
||||
}
|
||||
+79
-76
@@ -20,14 +20,13 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
import path from 'node:path';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import pkg from '@douyinfe/vite-plugin-semi';
|
||||
import { defineConfig, transformWithEsbuild } from 'vite';
|
||||
import { defineConfig, loadEnv, transformWithEsbuild } from 'vite';
|
||||
|
||||
// @douyinfe/vite-plugin-semi 是 CommonJS 包,具名导出挂在 default 上。
|
||||
const { vitePluginSemi } = pkg;
|
||||
|
||||
/**
|
||||
* 开发服务器代理统一指向的后端根地址。
|
||||
* 切换联调环境时只需改这一处,不必逐个前缀修改。
|
||||
* 未配置代理变量时保留原有联调地址,兼容自定义 mode。
|
||||
*/
|
||||
const DEV_PROXY_TARGET = 'http://134.175.227.134:13000';
|
||||
|
||||
@@ -118,19 +117,18 @@ function jsxInJsPlugin() {
|
||||
/**
|
||||
* 向 index.html 注入统计脚本。
|
||||
*
|
||||
* 变量在 transformIndexHtml 执行时才读取,以保持原有的生效时机:
|
||||
* 由启动终端或 CI 注入进程环境变量,未提供对应 ID 时不做任何替换。
|
||||
* 使用当前 mode 的环境变量;启动终端或 CI 的同名变量优先。
|
||||
* 未提供对应 ID 时不注入脚本。
|
||||
*/
|
||||
function analyticsPlugin() {
|
||||
function analyticsPlugin(env) {
|
||||
return {
|
||||
name: 'inject-analytics',
|
||||
transformIndexHtml(html) {
|
||||
let result = html;
|
||||
|
||||
const umamiId = process.env.VITE_UMAMI_WEBSITE_ID;
|
||||
const umamiId = env.VITE_UMAMI_WEBSITE_ID;
|
||||
const umamiUrl =
|
||||
process.env.VITE_UMAMI_SCRIPT_URL ||
|
||||
'https://analytics.umami.is/script.js';
|
||||
env.VITE_UMAMI_SCRIPT_URL || 'https://analytics.umami.is/script.js';
|
||||
if (umamiId) {
|
||||
result = result.replace(
|
||||
'<!--umami-->',
|
||||
@@ -138,7 +136,7 @@ function analyticsPlugin() {
|
||||
);
|
||||
}
|
||||
|
||||
const gaId = process.env.VITE_GOOGLE_ANALYTICS_ID;
|
||||
const gaId = env.VITE_GOOGLE_ANALYTICS_ID;
|
||||
if (gaId) {
|
||||
result = result.replace(
|
||||
'<!--Google Analytics-->',
|
||||
@@ -153,75 +151,80 @@ function analyticsPlugin() {
|
||||
}
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
'~': path.resolve(__dirname, 'node_modules'),
|
||||
'@douyinfe/semi-theme-default': path.resolve(
|
||||
__dirname,
|
||||
'node_modules/@douyinfe/semi-theme-default',
|
||||
),
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
jsxInJsPlugin(),
|
||||
react(),
|
||||
vitePluginSemi({
|
||||
cssLayer: true,
|
||||
}),
|
||||
analyticsPlugin(),
|
||||
],
|
||||
optimizeDeps: {
|
||||
// 强制重新预构建,避免依赖变更后命中陈旧的依赖缓存
|
||||
force: true,
|
||||
esbuildOptions: {
|
||||
loader: {
|
||||
'.js': 'jsx',
|
||||
'.json': 'json',
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, __dirname, ['VITE_', 'DEV_PROXY_']);
|
||||
const proxyTarget = env.DEV_PROXY_TARGET || DEV_PROXY_TARGET;
|
||||
|
||||
return {
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
'~': path.resolve(__dirname, 'node_modules'),
|
||||
'@douyinfe/semi-theme-default': path.resolve(
|
||||
__dirname,
|
||||
'node_modules/@douyinfe/semi-theme-default',
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
build: {
|
||||
// 使用 esbuild 压缩:速度远快于 terser,压缩率略低
|
||||
minify: 'esbuild',
|
||||
// 启用 CSS 代码分割
|
||||
cssCodeSplit: true,
|
||||
// chunk 体积告警阈值 (KB)
|
||||
chunkSizeWarningLimit: 1000,
|
||||
// 构建目标为 es2015,以换取更广的浏览器兼容性
|
||||
target: 'es2015',
|
||||
// 生产环境不需要 sourcemap
|
||||
sourcemap: false,
|
||||
// esbuild 压缩选项:移除调试语句与版权注释
|
||||
esbuild: {
|
||||
drop: ['console', 'debugger'],
|
||||
legalComments: 'none',
|
||||
},
|
||||
rollupOptions: {
|
||||
output: {
|
||||
// 文件名带内容 hash,便于浏览器长期缓存与增量更新
|
||||
chunkFileNames: 'assets/[name]-[hash].js',
|
||||
entryFileNames: 'assets/[name]-[hash].js',
|
||||
assetFileNames: 'assets/[name]-[hash].[ext]',
|
||||
manualChunks: resolveVendorChunk,
|
||||
plugins: [
|
||||
jsxInJsPlugin(),
|
||||
react(),
|
||||
vitePluginSemi({
|
||||
cssLayer: true,
|
||||
}),
|
||||
analyticsPlugin(env),
|
||||
],
|
||||
optimizeDeps: {
|
||||
// 强制重新预构建,避免依赖变更后命中陈旧的依赖缓存
|
||||
force: true,
|
||||
esbuildOptions: {
|
||||
loader: {
|
||||
'.js': 'jsx',
|
||||
'.json': 'json',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
server: {
|
||||
// 监听所有网卡,便于局域网与容器内访问
|
||||
host: '0.0.0.0',
|
||||
proxy: {
|
||||
// 以下前缀统一转发到同一个后端,其中 /v1 额外开启 WebSocket
|
||||
'/api': { target: DEV_PROXY_TARGET, changeOrigin: true },
|
||||
'/v1': { target: DEV_PROXY_TARGET, changeOrigin: true, ws: true },
|
||||
'/v1beta': { target: DEV_PROXY_TARGET, changeOrigin: true },
|
||||
'/mj': { target: DEV_PROXY_TARGET, changeOrigin: true },
|
||||
'/pg': { target: DEV_PROXY_TARGET, changeOrigin: true },
|
||||
'/dashboard': { target: DEV_PROXY_TARGET, changeOrigin: true },
|
||||
'/kling': { target: DEV_PROXY_TARGET, changeOrigin: true },
|
||||
'/jimeng': { target: DEV_PROXY_TARGET, changeOrigin: true },
|
||||
'/suno': { target: DEV_PROXY_TARGET, changeOrigin: true },
|
||||
build: {
|
||||
// 使用 esbuild 压缩:速度远快于 terser,压缩率略低
|
||||
minify: 'esbuild',
|
||||
// 启用 CSS 代码分割
|
||||
cssCodeSplit: true,
|
||||
// chunk 体积告警阈值 (KB)
|
||||
chunkSizeWarningLimit: 1000,
|
||||
// 构建目标为 es2015,以换取更广的浏览器兼容性
|
||||
target: 'es2015',
|
||||
// 生产环境不需要 sourcemap
|
||||
sourcemap: false,
|
||||
// esbuild 压缩选项:移除调试语句与版权注释
|
||||
esbuild: {
|
||||
drop: ['console', 'debugger'],
|
||||
legalComments: 'none',
|
||||
},
|
||||
rollupOptions: {
|
||||
output: {
|
||||
// 文件名带内容 hash,便于浏览器长期缓存与增量更新
|
||||
chunkFileNames: 'assets/[name]-[hash].js',
|
||||
entryFileNames: 'assets/[name]-[hash].js',
|
||||
assetFileNames: 'assets/[name]-[hash].[ext]',
|
||||
manualChunks: resolveVendorChunk,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
server: {
|
||||
// 监听所有网卡,便于局域网与容器内访问
|
||||
host: '0.0.0.0',
|
||||
proxy: {
|
||||
// 以下前缀统一转发到同一个后端,其中 /v1 额外开启 WebSocket
|
||||
'/api': { target: proxyTarget, changeOrigin: true },
|
||||
'/v1': { target: proxyTarget, changeOrigin: true, ws: true },
|
||||
'/v1beta': { target: proxyTarget, changeOrigin: true },
|
||||
'/mj': { target: proxyTarget, changeOrigin: true },
|
||||
'/pg': { target: proxyTarget, changeOrigin: true },
|
||||
'/dashboard': { target: proxyTarget, changeOrigin: true },
|
||||
'/kling': { target: proxyTarget, changeOrigin: true },
|
||||
'/jimeng': { target: proxyTarget, changeOrigin: true },
|
||||
'/suno': { target: proxyTarget, changeOrigin: true },
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user