` 上的 `region`(moderate,仅切换组)。新出现的 critical / serious 一律按回归修复,不允许加进排除清单。
+- 无障碍:`e2e/a11y.spec.ts` 从既有传递依赖注入 axe-core(不新增依赖;因为 CSP 没有 `unsafe-inline`,改为同源 URL 注入),共跑 **27 例**,分三组——11 条路由 × 浅色(冷启动)、11 条路由 × realDark(冷启动)、以及 5 条路由(`/login`、`/`、`/ops/devices`、`/ops/alarms`、`/ops/tickets`)× realDark 且经**点击顶栏主题开关**到达。切换组存在的原因:umi 的 `setAntdConfig` 是深合并,而此前浅色与暗色 token 键集不对称,热切换会残留浅色种子值;现在两套键集都是同样的 13 个键,且实测切换路径与冷启动暗色在 17 个 CSS 变量上逐字节一致。命令 `pnpm exec playwright test e2e/a11y.spec.ts --workers=1`;门禁要求**全部用例 critical 与 serious 均为 0**,排除清单为空(没有排除任何规则、没有放宽阈值、没有重新分级)。这不等于「axe 无告警」:moderate / minor 结果照常输出但不作为门禁——ProLayout 头部的 `landmark-no-duplicate-banner`、`landmark-unique`(moderate,每路由 2 个),Calendar 的 `heading-order`(moderate),FullCalendar 内部的 `empty-table-header`(minor ×7),以及切换用例里 antd 在开关 tooltip 打开时创建的空 portal `
` 上的 `region`(moderate,仅切换组)。新出现的 critical / serious 一律按回归修复,不允许加进排除清单。
- 覆盖率:`pnpm test:coverage`——百分比统计的是 `vitest.config.ts` 的**选定域**(`src/utils`、`src/services`、`src/demo`、`src/pages/Login`、`src/pages/System/Users`、`src/pages/System/Roles`),不是全项目口径;阈值(statements 60 / branches 50 / functions 60 / lines 60)在 CI 上只对域内生效,不得下调。最终本机数字:54 个文件上 statements 79.38% / branches 74.48% / functions 75.55% / lines 81.51%(644 passed、5 skipped,skip 全部来自 `scripts/real-mode-artifact.test.ts` 的模式分支),同口径全项目 `src/**` 约 statements 47.87%
-- Lint:`react-hooks/exhaustive-deps` 已提到 error,未使用 disable 的上报已开启。disable 行必须在本行或上一行写明具体理由;`src/` 内仅剩 1 处 `exhaustive-deps` disable,在 `src/hooks/useApi.ts`(理由写在同一行:依赖数组由调用方提供,规则无法静态校验展开项)。
+- Lint:`react-hooks/exhaustive-deps` 已提到 error,未使用 disable 的上报已开启。disable 行必须在本行或上一行写明具体理由;`src/` 内现存 6 处 `exhaustive-deps` disable(`src/hooks/useApi.ts` 与五个 Cesium 场景页的时钟/纯函数 effect),理由均已写在同一行。
diff --git a/SECURITY.md b/SECURITY.md
index 9a4920b9..d15fb7fc 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -20,7 +20,7 @@ Please include: affected version/commit, reproduction steps, and impact assessme
## Quality gates
-- PR-stage CI: typecheck / strict lint (including `.mjs`; `react-hooks/exhaustive-deps` is an error and unused-disable reporting is on) / vitest / **coverage gate** (`pnpm test:coverage`, thresholds in `vitest.config.ts`) / both explicit demo builds plus the real-mode build (`build:real`, whose artifact is asserted to contain no demo code) / bundle budget & style coverage / **artifact secret scanning** (fingerprint-verified against declared public client tokens only) / full dependency advisories with verified source patches / Playwright (CSP violations caused by third parties are not ignored)
+- PR-stage CI: typecheck / strict lint (including `.mjs`; `react-hooks/exhaustive-deps` is an error and unused-disable reporting is on) / vitest / **coverage gate** (`pnpm test:coverage`, thresholds in `vitest.config.ts`) / both explicit demo builds plus the real-mode build (`build:real`, whose artifact is asserted to contain no demo code) / bundle budget & style coverage / **artifact secret scanning** (fingerprint-verified against declared public client tokens only) / tiered dependency advisories (runtime zero-ignore with verified source patches; build-chain-only advisories are reported as non-blocking warnings) / Playwright (CSP violations caused by third parties are not ignored)
- The coverage percentage is measured over the **selected include set** in `vitest.config.ts` — `src/utils/**`, `src/services/**`, `src/demo/**`, `src/pages/Login/**`, `src/pages/System/Users/**` and `src/pages/System/Roles/**` — not over the whole project. The final local figure is statements 79.38% / branches 74.48% / functions 75.55% / lines 81.51% over 54 files (`pnpm test:coverage`, 644 passed / 5 skipped, thresholds 60/50/60/60 unchanged); measuring whole-project `src/**` in a one-off run gives about 47.87% statements with the config untouched, so the gate figure must not be quoted as whole-project coverage. The 5 skips are the mode-conditional branches of `scripts/real-mode-artifact.test.ts` (a demo-mode artifact skips the real-mode assertions); CI sets `REAL_MODE_ARTIFACT_REQUIRED=1` on the `build:real` job, where they cannot silently skip
- Post-deploy: wait for the online `version.json` to switch to this commit, then run the `@smoke` cases against the live site
- Commit stage: pre-commit (lint-staged + typecheck)
@@ -50,7 +50,7 @@ The Vercel entry is fail-closed for `/api/*`: an explicit `/api/(.*)` rewrite ru
The Dockerfile declares no mutable `# syntax=docker/dockerfile:1` frontend — it uses only default-frontend instructions, and both base images are pinned by digest; if BuildKit-only syntax is ever required it must be pinned to an exact version or digest, which `scripts/dockerfile-frontend.test.ts` enforces.
-Real mode strips the browser demo backend through build-time aliases (`@/demo/adapter`, `@/demo/token`), but it is **not** demo-free: `umi-react-admin:demo-clock:v1` from `src/demo/clock.ts` still appears in three lazy route chunks (`Signature`, `Tickets`, `Alarms`) because `src/utils/now.ts` statically imports the demo clock. It is outside the entry chunk and outside the demo backend/generator/scenario/store, so the stripping criteria hold, but a frozen clock anchor left in localStorage on an origin previously used for the demo can make real-mode relative times wrong; adding a third build-time alias for `@/demo/clock` is the recommended fix.
+Real mode strips the browser demo backend through build-time aliases (`@/demo/adapter`, `@/demo/token`, `@/demo/clock` — the clock alias redirects `src/utils/now.ts` to `src/demo/clock.real.ts`, which always returns system time and throws on freeze/resume). The stub reads and writes no storage at all, so a frozen-clock anchor left in localStorage on an origin previously used for the demo is simply never consulted; `freeze`/`resume` throw so a misconfiguration surfaces immediately. `scripts/real-mode-artifact.test.ts` asserts the stub sentinel is present in real artifacts and that the demo clock's storage key is absent from async chunks.
The local preview server binds to 127.0.0.1 only and rejects directory traversal, escaping symlinks and abnormal encodings. It is for local verification; production should use an HTTPS static entry. nginx listens on intranet 8080 with TLS terminated at the deployment entry; HSTS only takes effect once the browser has seen an HTTPS response.
@@ -77,3 +77,5 @@ Honest residual limits: PDF.js exposes no decoded-resource accounting API, so th
Historical advisories are no longer recorded as accepted-without-fix. Real upgrades, removals or source patches are tracked in [THIRD-PARTY-NOTICES.md](./THIRD-PARTY-NOTICES.md). Raw `pnpm audit` may still flag locally patched packages by version number; the raw output is kept, and `pnpm audit:security` must additionally verify source hashes of every installed instance plus real attack regressions — new advisories and unproven instances fail. Gates must never be passed by ignoring advisories, faking version numbers, or assessing only unreachable paths.
+
+Advisory tiering (2026-11-01): advisories whose every installed path sits inside build/test/lint toolchain subtrees (bundlers, vite/mako/utoopack, the eslint and vitest families, Node-only build helpers — packages that never ship in `dist`) are reported as non-blocking warnings; anything with even one path into the shipped/runtime graph stays zero-ignore and blocking. The classification is deliberately conservative (any bypassing path keeps an advisory blocking), and `AUDIT_TOOLCHAIN_STRICT=1` restores full blocking for periodic manual sweeps. Rationale: upstream `@umijs/max` pins those transitive versions so the project cannot upgrade them, and GitHub advisory-database updates had kept every PR red from 2026-10-21 to 2026-11-01; the tier users actually run keeps its zero-ignore guarantee unchanged.
diff --git a/SECURITY.zh-CN.md b/SECURITY.zh-CN.md
index aad6c376..d5ed1fbe 100644
--- a/SECURITY.zh-CN.md
+++ b/SECURITY.zh-CN.md
@@ -20,7 +20,7 @@
## 质量门禁
-- PR 阶段 CI:typecheck / 严格 lint(含 .mjs;`react-hooks/exhaustive-deps` 为 error,未使用 disable 的上报已开启)/ vitest / **覆盖率门禁**(`pnpm test:coverage`,阈值见 `vitest.config.ts`)/ 两条显式演示构建 + 真实模式构建(`build:real`,其产物会被断言不含演示代码)/ 体积预算与样式覆盖 / **产物密钥扫描**(仅核对已声明的公开客户端 token 指纹)/ 全量依赖公告与真实补丁验证 / Playwright(包含第三方引起的 CSP 违规,不作忽略)
+- PR 阶段 CI:typecheck / 严格 lint(含 .mjs;`react-hooks/exhaustive-deps` 为 error,未使用 disable 的上报已开启)/ vitest / **覆盖率门禁**(`pnpm test:coverage`,阈值见 `vitest.config.ts`)/ 两条显式演示构建 + 真实模式构建(`build:real`,其产物会被断言不含演示代码)/ 体积预算与样式覆盖 / **产物密钥扫描**(仅核对已声明的公开客户端 token 指纹)/ 分层依赖公告(运行时零忽略 + 真实补丁验证;仅构建链可达的公告为非阻塞告警)/ Playwright(包含第三方引起的 CSP 违规,不作忽略)
- 覆盖率百分比统计的是 `vitest.config.ts` 里的**选定域**——`src/utils/**`、`src/services/**`、`src/demo/**`、`src/pages/Login/**`、`src/pages/System/Users/**`、`src/pages/System/Roles/**`——不是全项目口径。最终本机数字为 54 个文件上 statements 79.38% / branches 74.48% / functions 75.55% / lines 81.51%(`pnpm test:coverage`,644 passed / 5 skipped,阈值 60/50/60/60 未改动);另做一次全项目 `src/**` 统计约为 statements 47.87%(配置未改动),因此门禁数字不得作为全项目覆盖率引用。5 个 skip 全部是 `scripts/real-mode-artifact.test.ts` 中按模式分支的用例(演示模式产物会跳过真实模式断言);CI 的 `build:real` 作业设置 `REAL_MODE_ARTIFACT_REQUIRED=1`,在那里它们无法静默跳过
- 部署后:等待线上 `version.json` 切到本次提交,对线上地址跑 `@smoke` 用例
- 提交阶段:pre-commit(lint-staged + typecheck)
@@ -50,7 +50,7 @@ Vercel 产线的 `/api/*` 是闭合失败的:显式的 `/api/(.*)` rewrite 排
Dockerfile 不再声明可变的 `# syntax=docker/dockerfile:1` frontend——它只使用默认 frontend 支持的指令,且两个 base 镜像都按摘要固定;若将来确实需要 BuildKit 专属语法,必须固定到精确版本或摘要,由 `scripts/dockerfile-frontend.test.ts` 把关。
-真实模式通过构建期 alias(`@/demo/adapter`、`@/demo/token`)剥离浏览器内演示后端,但**并非**零演示代码:来自 `src/demo/clock.ts` 的 `umi-react-admin:demo-clock:v1` 仍出现在三个懒加载路由 chunk 中(`Signature`、`Tickets`、`Alarms`),因为 `src/utils/now.ts` 静态 import 了演示时钟。它不在入口 chunk,也不属于演示后端 / 生成器 / 场景 / 存储,因此既定剥离标准成立;但若某来源站曾用于演示,localStorage 里残留的冻结时钟锚点会让真实模式的相对时间出错。推荐的修法是给 `@/demo/clock` 加第三个构建期 alias。
+真实模式通过构建期 alias(`@/demo/adapter`、`@/demo/token`、`@/demo/clock`)剥离浏览器内演示后端——其中时钟 alias 把 `src/utils/now.ts` 重定向到 `src/demo/clock.real.ts`(恒返回系统时间;freeze/resume 直接抛错)。该替身完全不读不写任何存储,因此即便某来源站曾用于演示、localStorage 里残留冻结时钟锚点,真实模式也不会读到它;freeze/resume 抛错则保证配置错误第一时间暴露。`scripts/real-mode-artifact.test.ts` 断言真实产物含替身哨兵、且异步 chunk 中不含演示时钟的存储键。
本地 preview 默认仅监听 127.0.0.1,拒绝目录越界、逃逸符号链接及异常编码。它用于本机验证;生产应使用 HTTPS 静态服务入口。nginx 监听内网 8080,TLS 在部署入口终止;HSTS 只有浏览器收到 HTTPS 响应时才生效。
@@ -77,3 +77,5 @@ XLSX 在交给 ExcelJS 前校验 ZIP、实际解压量、XML、坐标、合并
历史公告不再登记为无修复的接受项。真实升级、移除或源码补丁见 [THIRD-PARTY-NOTICES.md](./THIRD-PARTY-NOTICES.md)。原始 `pnpm audit` 根据真实版本号仍可能命中本地已修补包;保留原始结果,`pnpm audit:security` 必须同时验证所有安装实例的源码哈希和真实攻击回归,新公告及未证明修补的实例均失败。不得通过忽略公告、伪造版本号或只评估不可达来让门禁通过。
+
+公告分层(2026-11-01):所有安装路径都只落在构建/测试/lint 工具链子树内(打包器、vite/mako/utoopack、eslint 与 vitest 家族、纯 Node 构建辅助——这些包不进 `dist`)的公告降为非阻塞告警;只要有任何一条路径可进产物/运行时图,仍按零忽略阻塞。判定从宽(存在旁路路径即维持阻塞),`AUDIT_TOOLCHAIN_STRICT=1` 可恢复全量阻塞用于周期性人工清点。理由:上游 `@umijs/max` 锁死了这些传递依赖的版本、仓库无法升格,而 GHSA 数据库的每次更新在 2026-10-21 至 2026-11-01 间把所有 PR 连续打红;用户真正运行的运行时层的零忽略保证保持不变。
diff --git a/api/[...path].js b/api/[...path].js
index deaf4d13..e794bb29 100644
--- a/api/[...path].js
+++ b/api/[...path].js
@@ -67,8 +67,9 @@ const resolveBackend = () => {
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
return { error: 'backend_misconfigured' };
}
- // 生产部署拒绝环回/私网/保留地址(与全站服务端请求约束一致):API_ORIGIN 被污染成内网地址时
- // 不得把函数变成内网探测跳板。本地/CI 测试用 127.0.0.1 起真实上游验证代理语义,故仅生产启用
+ // 公网部署(production 与 preview)拒绝环回/私网/保留地址(与全站服务端请求约束一致):
+ // API_ORIGIN 被污染成内网地址时不得把函数变成内网探测跳板。
+ // 本地/CI 测试用 127.0.0.1 起真实上游验证代理语义,故仅公网部署启用
const host = url.hostname.toLowerCase();
const isLoopback = host === 'localhost' || host === '::1' || host === '[::1]' || host.endsWith('.localhost');
const isPrivateIpv4 =
@@ -79,9 +80,14 @@ const resolveBackend = () => {
a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || a === 0 || a >= 224
);
})();
- const isLinkLocal =
- host.startsWith('169.254.') || host.startsWith('fe80:') || host.startsWith('fc') || host.startsWith('fd');
- const isProduction = process.env.VERCEL_ENV === 'production' || process.env.NODE_ENV === 'production';
+ // IPv6 ULA(fc00::/7)必然含 ':':此前用 startsWith('fc')/startsWith('fd') 会把
+ // fcms.example.com 这类公网域名误判成链路本地并拒绝
+ const isLinkLocal = host.startsWith('169.254.') || host.startsWith('fe80:') || /^f[cd][0-9a-f]*:/.test(host);
+ // preview 部署同样公网可达(此前只有 production 拒绝内网地址,preview 可被当内网探测跳板)
+ const isProduction =
+ process.env.VERCEL_ENV === 'production' ||
+ process.env.VERCEL_ENV === 'preview' ||
+ process.env.NODE_ENV === 'production';
if (isProduction && (isLoopback || isPrivateIpv4 || isLinkLocal)) {
return { error: 'backend_misconfigured' };
}
diff --git a/config/config.github.ts b/config/config.github.ts
index a9b3cbe8..902b4e6a 100644
--- a/config/config.github.ts
+++ b/config/config.github.ts
@@ -6,7 +6,7 @@ import { buildCsp } from './csp';
import { faviconLinks } from './favicons';
import { configureSplitChunks } from './splitChunks';
import { keepUrlAssetsVerbatim } from './urlAssets';
-// import { routes } from './routes';
+
const AUTH_CONFIG = resolveAuthConfig(process.env);
if (!AUTH_CONFIG.demoMode) {
throw new Error('GitHub Pages supports public demo only; backend mode needs a host with security headers');
@@ -22,7 +22,9 @@ export default defineConfig({
if (process.env.NODE_ENV === 'production') {
configureSplitChunks(config);
addChunkGraph(config);
- addVersionFile(config);
+ // 与 config.ts 对齐传入 demoMode:本文件入口已断言 demoMode 为真,避免仅靠
+ // UMI_APP_DEMO_MODE 环境变量兜底(两条产线参数源不同就会静默漂移)
+ addVersionFile(config, { demoMode: AUTH_CONFIG.demoMode });
}
},
// define 经 lodash.merge 逐键深合并(@umijs/core getUserConfig):这里只覆盖与主产线的
diff --git a/config/config.ts b/config/config.ts
index a36e9247..49692958 100644
--- a/config/config.ts
+++ b/config/config.ts
@@ -45,6 +45,10 @@ export default defineConfig({
* - '@/demo/token':services/auth.ts 顶层 import,调用点在 `if (DEMO_MODE)` 里;DEMO_MODE 经
* 模块命名空间读取(产物中是 `ne.G`),压缩器无法判定该分支为死代码,演示 token 模块
* (含 'demo.' 前缀字面量)因此留在真实模式入口 chunk,实测确认后才加的第二个替身。
+ * - '@/demo/clock':src/utils/now.ts 顶层 import。不加替身时 Signature / Tickets / Alarms 的
+ * 懒加载 chunk 会带上演示时钟与存储键 'umi-react-admin:demo-clock'——若同一 origin 冻结过
+ * 演示时钟,真实模式下 nowMs() 会继续返回旧锚点(SLA/持续时长按错误时间计算)。
+ * 替身恒返回系统时间(见 src/demo/clock.real.ts),哨兵由 real-mode-artifact.test.ts 断言。
*
* 键写成完整路径:preset-umi 的 configPlugins 把用户 alias 展开在内置 '@' 之前
* (memo.alias = { ...memo.alias, '@': absSrcPath }),完整键精确命中,不依赖前缀匹配顺序。
@@ -55,6 +59,7 @@ export default defineConfig({
: {
'@/demo/adapter': path.resolve(__dirname, '../src/demo/adapter.real.ts'),
'@/demo/token': path.resolve(__dirname, '../src/demo/token.real.ts'),
+ '@/demo/clock': path.resolve(__dirname, '../src/demo/clock.real.ts'),
},
chainWebpack(config) {
keepUrlAssetsVerbatim(config);
diff --git a/e2e/baseUrl.ts b/e2e/baseUrl.ts
new file mode 100644
index 00000000..dfd5be39
--- /dev/null
+++ b/e2e/baseUrl.ts
@@ -0,0 +1,5 @@
+/**
+ * 本地静态服务器的默认地址:playwright.config(webServer.url/baseURL)与 e2e/fixtures
+ * (navigate/version 探测)必须指向同一处——此前两处各写一份字面量,改端口会静默分叉。
+ */
+export const DEFAULT_BASE_URL = 'http://localhost:4173/umi-react-admin/';
diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts
index dc9782e2..700c0d66 100644
--- a/e2e/fixtures.ts
+++ b/e2e/fixtures.ts
@@ -1,4 +1,5 @@
import { test as base, expect, type Page } from '@playwright/test';
+import { DEFAULT_BASE_URL } from './baseUrl';
/** 第三方地图 / 影像 / 视频源的网络失败不算应用缺陷(CI 网络环境不可控) */
const THIRD_PARTY =
@@ -57,7 +58,7 @@ export const signIn = async (page: Page, { user = 'admin', locale = 'zh-CN' } =
await page.waitForURL((url) => !url.pathname.endsWith('/login'));
};
-export const BASE_URL = process.env.E2E_BASE_URL ?? 'http://localhost:4173/umi-react-admin/';
+export const BASE_URL = process.env.E2E_BASE_URL ?? DEFAULT_BASE_URL;
/** 站内跳转(不整页刷新,避开静态托管的 404 回退);path 为应用内路由(可带 query),如 /system/users */
export const navigate = async (page: Page, path: string) => {
diff --git a/e2e/flows.spec.ts b/e2e/flows.spec.ts
index 277bd27b..03b5bc3e 100644
--- a/e2e/flows.spec.ts
+++ b/e2e/flows.spec.ts
@@ -53,7 +53,9 @@ test('工作台 KPI 与明细口径一致:在线设备数等于设备台账筛
await signIn(page);
const kpi = page.locator('.ant-card').filter({ hasText: '在线设备' }).first();
await expect(kpi).toBeVisible();
- const online = Number((await kpi.locator('.text-3xl').first().innerText()).match(/\d+/)![0]);
+ // 千分位感知的解析(与 demo-mainline.spec.ts 同口径):/\d+/ 遇 "1,234" 只取到 1,
+ // 配合下方 toContainText 会让一致性断言空转
+ const online = Number((await kpi.locator('.text-3xl').first().innerText()).match(/[\d,]+/)![0].replace(/,/g, ''));
await navigate(page, '/ops/devices');
// 查询表单默认折叠,「状态」在展开后的第二行
await page.locator('.ant-pro-query-filter-collapse-button').click();
diff --git a/nginx/default.conf b/nginx/default.conf
index 8c1bfb80..b5099085 100644
--- a/nginx/default.conf
+++ b/nginx/default.conf
@@ -8,7 +8,8 @@ server {
gzip on;
gzip_min_length 1024;
- gzip_types text/plain text/css application/javascript application/json image/svg+xml;
+ # application/wasm:Cesium 第三方解码器;model/gltf-binary:public/assets 下的 glb 模型
+ gzip_types text/plain text/css application/javascript application/json image/svg+xml application/wasm model/gltf-binary;
# 静态镜像不实现 API;缺失后端时明确失败,不能把 SPA HTML 当成接口成功。
# 404 + JSON 与 scripts/serve-dist.mjs(GitHub Pages 等价本地服务器)、vercel.json 的 /api
diff --git a/package.json b/package.json
index cdff7590..554a9f92 100644
--- a/package.json
+++ b/package.json
@@ -57,8 +57,6 @@
"@fullcalendar/react": "^7.1.0",
"@pansy/amap-api-loader": "^0.4.10",
"@tinymce/tinymce-react": "^6.3.0",
- "@turf/helpers": "^7.2.0",
- "@turf/union": "^7.2.0",
"@umijs/max": "^4.7.22",
"antd": "^6.6.5",
"cesium": "^1.146.0",
@@ -66,7 +64,7 @@
"classnames": "^2.5.1",
"d3": "^7.9.0",
"dayjs": "^1.11.23",
- "dompurify": "^3.4.16",
+ "dompurify": "^3.4.17",
"exceljs": "^4.4.0",
"html2canvas": "^1.4.1",
"mgrs": "^2.2.0",
@@ -78,7 +76,7 @@
"react-pdf": "^11.0.0",
"signature_pad": "^5.1.4",
"temporal-polyfill": "^1.0.5",
- "tinymce": "^8.9.2",
+ "tinymce": "^8.9.3",
"tinymce-i18n": "^26.9.28",
"wavesurfer.js": "^8.0.1",
"xgplayer": "^3.0.26",
diff --git a/patches/decode-uri-component@0.2.2.patch b/patches/decode-uri-component@0.2.2.patch
index 527bc3e0..5a962477 100644
--- a/patches/decode-uri-component@0.2.2.patch
+++ b/patches/decode-uri-component@0.2.2.patch
@@ -1,11 +1,17 @@
diff --git a/index.js b/index.js
--- a/index.js
+++ b/index.js
-@@ -1,59 +1,144 @@
+@@ -1,93 +1,156 @@
'use strict';
-var token = '%[a-f0-9]{2}';
-var singleMatcher = new RegExp('(' + token + ')|([^%]+?)', 'gi');
-var multiMatcher = new RegExp('(' + token + ')+', 'gi');
++// Backport of upstream fa479dafeede7bedf04e5c89aa78f2a78c664005 (GHSA-vcc3-ghjq-m6fr)
++// plus the single-pass replacement of percent-encoded runs from 0.5.1 (GHSA-qr28-fpjm-wq7f).
++// Retain the 0.2.x CommonJS export and form-style plus decoding used by query-string.
++// Matches one or more consecutive percent-encoded bytes (e.g. `%C3%A5`).
++const token = '%[a-f0-9]{2}';
++const multiMatcher = new RegExp(`(${token})+`, 'gi');
-function decodeComponents(components, split) {
- try {
@@ -13,12 +19,6 @@ diff --git a/index.js b/index.js
- return [decodeURIComponent(components.join(''))];
- } catch (err) {
- // Do nothing
-+// Backport of upstream fa479dafeede7bedf04e5c89aa78f2a78c664005 (GHSA-vcc3-ghjq-m6fr).
-+// Retain the 0.2.x CommonJS export and form-style plus decoding used by query-string.
-+// Matches one or more consecutive percent-encoded bytes (e.g. `%C3%A5`).
-+const token = '%[a-f0-9]{2}';
-+const multiMatcher = new RegExp(`(${token})+`, 'gi');
-+
+const hexPair = /^[a-f\d]{2}$/i;
+
+// Read a `%XX` sequence at `position`, returning the byte value and where to continue scanning.
@@ -36,15 +36,12 @@ diff --git a/index.js b/index.js
}
- split = split || 1;
--
++ return {byte: Number.parseInt(digits, 16), next: position + 3};
++}
+
- // Split the array in 2 parts
- var left = components.slice(0, split);
- var right = components.slice(split);
--
-- return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
-+ return {byte: Number.parseInt(digits, 16), next: position + 3};
- }
-
+/**
+ * Return how many bytes a UTF-8 code point needs based on its lead byte.
+ * Returns 0 for continuation bytes and other invalid lead bytes.
@@ -53,7 +50,8 @@ diff --git a/index.js b/index.js
+ if (byte <= 0x7F) {
+ return 1;
+ }
-+
+
+- return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
+ // Start at 0xC2 to exclude overlong 2-byte encodings (0xC0/0xC1).
+ if (byte >= 0xC2 && byte <= 0xDF) {
+ return 2;
@@ -68,8 +66,8 @@ diff --git a/index.js b/index.js
+ }
+
+ return 0;
-+}
-+
+ }
+
+function isContinuationByte(byte) {
+ return byte >= 0x80 && byte <= 0xBF;
+}
@@ -97,35 +95,73 @@ diff --git a/index.js b/index.js
+ }
- tokens = input.match(singleMatcher) || [];
+- }
+ const firstByte = parsePercentByte(input, position);
-+
+
+- return input;
+- }
+-}
+ // `%` not followed by two hex digits (e.g. `%` or `%G`).
+ if (!firstByte) {
+ output += input.charAt(position);
+ position++;
+ continue;
+ }
-+
+
+-function customDecodeURIComponent(input) {
+- // Keep track of all the replacements and prefill the map with the `BOM`
+- var replaceMap = {
+- '%FE%FF': '\uFFFD\uFFFD',
+- '%FF%FE': '\uFFFD\uFFFD'
+- };
+ const sequenceLength = utf8SequenceLength(firstByte.byte);
-+
+
+- var match = multiMatcher.exec(input);
+- while (match) {
+- try {
+- // Decode as big chunks as possible
+- replaceMap[match[0]] = decodeURIComponent(match[0]);
+- } catch (err) {
+- var result = decode(match[0]);
+ // Continuation byte or invalid lead byte — emit one `%XX` literally.
+ if (sequenceLength === 0) {
++ const pair = input.slice(position, position + 6);
+
+- if (result !== match[0]) {
+- replaceMap[match[0]] = result;
++ // UTF-16 BOM byte pairs become two replacement characters.
++ if (pair === '%FE%FF' || pair === '%FF%FE') {
++ output += '\uFFFD\uFFFD';
++ position += 6;
++ continue;
++ }
++
+ output += input.slice(position, position + 3);
+ position += 3;
+ continue;
-+ }
-+
+ }
+- }
+
+- match = multiMatcher.exec(input);
+- }
+ let end = firstByte.next;
+ let validSequence = true;
-+
+
+- // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
+- replaceMap['%C2'] = '\uFFFD';
+ for (let index = 1; index < sequenceLength; index++) {
+ const nextByte = parsePercentByte(input, end);
-+
+
+- var entries = Object.keys(replaceMap);
+ if (!nextByte || !isContinuationByte(nextByte.byte)) {
+ validSequence = false;
+ break;
+ }
-+
+
+- for (var i = 0; i < entries.length; i++) {
+- // Replace all decoded components
+- var key = entries[i];
+- input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
+ end = nextByte.next;
+ }
+
@@ -142,54 +178,21 @@ diff --git a/index.js b/index.js
+ }
+
+ // Missing continuation bytes or decode failure — emit the first byte literally.
-+ output += input.slice(position, position + 3);
++ const literal = input.slice(position, position + 3);
++
++ // A truncated `%C2` becomes a replacement character.
++ output += literal === '%C2' ? '\uFFFD' : literal;
+ position += 3;
- }
-
-- return input;
-+ return output;
- }
- }
-
- function customDecodeURIComponent(input) {
- // Keep track of all the replacements and prefill the map with the `BOM`
-- var replaceMap = {
-+ const replaceMap = {
- '%FE%FF': '\uFFFD\uFFFD',
-- '%FF%FE': '\uFFFD\uFFFD'
-+ '%FF%FE': '\uFFFD\uFFFD',
- };
-
-- var match = multiMatcher.exec(input);
-+ // Find percent-encoded runs separated by literal text or lone `%` characters.
-+ let match = multiMatcher.exec(input);
++ }
+
- while (match) {
- try {
- // Decode as big chunks as possible
- replaceMap[match[0]] = decodeURIComponent(match[0]);
-- } catch (err) {
-- var result = decode(match[0]);
-+ } catch {
-+ const result = decode(match[0]);
-
- if (result !== match[0]) {
- replaceMap[match[0]] = result;
-@@ -66,29 +151,29 @@
- // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
- replaceMap['%C2'] = '\uFFFD';
-
-- var entries = Object.keys(replaceMap);
-+ const entries = Object.keys(replaceMap);
-
-- for (var i = 0; i < entries.length; i++) {
-+ for (const key of entries) {
- // Replace all decoded components
-- var key = entries[i];
- input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
++ return output;
}
++}
- return input;
+- return input;
++function customDecodeURIComponent(input) {
++ // Decode each percent-encoded run in place in a single pass. Decoded output is never rescanned.
++ return input.replace(multiMatcher, run => decode(run));
}
-module.exports = function (encodedURI) {
@@ -199,11 +202,11 @@ diff --git a/index.js b/index.js
+ throw new TypeError(`Expected \`encodedURI\` to be of type \`string\`, got \`${typeof encodedURI}\``);
}
-+ encodedURI = encodedURI.replace(/\+/g, ' ');
-+
- try {
+- try {
- encodedURI = encodedURI.replace(/\+/g, ' ');
--
++ encodedURI = encodedURI.replace(/\+/g, ' ');
+
++ try {
// Try the built in decoder first
return decodeURIComponent(encodedURI);
- } catch (err) {
@@ -211,5 +214,3 @@ diff --git a/index.js b/index.js
// Fallback to a more advanced decoder
return customDecodeURIComponent(encodedURI);
}
- };
-+
diff --git a/playwright.config.ts b/playwright.config.ts
index be5f4cc4..8ea54943 100644
--- a/playwright.config.ts
+++ b/playwright.config.ts
@@ -1,10 +1,11 @@
import { defineConfig, devices } from '@playwright/test';
+import { DEFAULT_BASE_URL } from './e2e/baseUrl';
/**
* 浏览器级冒烟:对 GitHub Pages 同构的静态产物(build:github:demo,子路径 /umi-react-admin/)逐路由验证。
* 设置 E2E_BASE_URL 时直接测线上地址(部署后冒烟),否则本地起静态服务器。
*/
-const BASE_URL = process.env.E2E_BASE_URL ?? 'http://localhost:4173/umi-react-admin/';
+const BASE_URL = process.env.E2E_BASE_URL ?? DEFAULT_BASE_URL;
export default defineConfig({
testDir: 'e2e',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 14effb89..6d9fdc13 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -19,10 +19,11 @@ overrides:
colord@<2.9.4: 2.9.4
compression@>=1.0.0 <1.8.2: 1.8.2
cross-spawn@>=7.0.0 <7.0.5: 7.0.6
- dompurify@>=3.0.0 <3.4.16: 3.4.16
+ dompurify@>=3.0.0 <3.4.17: 3.4.17
es5-ext@<0.10.63: 0.10.64
esbuild@<0.25.0: 0.25.12
fast-uri@>=3.0.0 <3.1.8: 3.1.8
+ follow-redirects@>=1.0.0 <1.16.2: 1.16.2
form-data@>=4.0.0 <4.0.6: 4.0.6
glob@>=10.2.0 <10.5.0: 10.5.0
hono@>=4.0.0 <4.13.7: 4.13.7
@@ -71,7 +72,7 @@ patchedDependencies:
'@umijs/preset-umi@4.7.22': 29e2cc1a26b0fdd8bb736ad6a779f06d610518b3a1c5fe358eeb560d6f0c89d5
'@umijs/renderer-react@4.7.22': 0f804f00cada7a343be7d9435b1cd0597bca52228c640ff90f906712018c58e7
braces@3.0.3: 18a4724cb117fb08010e0d8f8aa9684fbd706be3560a12dd4d0e4233d5834acd
- decode-uri-component@0.2.2: 4bd5a5e1ec0b95817e4d3a1266b29d7ff4d7065630ae4b35a1f0cdec0de579cc
+ decode-uri-component@0.2.2: 337cc9f69eb805a7555bdbcde5fca0a3e8f210e97c35338fa6f54c6bd2fd1bf9
exceljs@4.4.0: a02bd99ddda9857e9f25c127e09b6892421f3a7f6a45b0481cb16973fb9ac9f7
node-libs-browser-okam@2.2.5: 74add8ae00cc142e91994ae396ed350dd504d037fca3b8991a608dbe54704559
node-libs-browser@2.2.1: 54c014d704b5d3d291d99ccd2024ef61fc08e6fd4c4e409a47de257c4151a371
@@ -100,13 +101,7 @@ importers:
version: 0.4.10
'@tinymce/tinymce-react':
specifier: ^6.3.0
- version: 6.3.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(tinymce@8.9.2)
- '@turf/helpers':
- specifier: ^7.2.0
- version: 7.4.0
- '@turf/union':
- specifier: ^7.2.0
- version: 7.4.0
+ version: 6.3.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(tinymce@8.10.1)
'@umijs/max':
specifier: ^4.7.22
version: 4.7.22(@babel/core@7.29.6(supports-color@10.2.2))(@types/node@26.6.2)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(debug@4.4.3(supports-color@10.2.2))(dva@2.5.0-beta.2(encoding@0.1.13)(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(jiti@2.7.0)(lightningcss@1.32.0)(prettier@3.9.9)(rc-field-form@2.7.1(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(rollup@4.63.4)(sass@1.54.0)(styled-jsx@5.1.7(@babel/core@7.29.6(supports-color@10.2.2))(babel-plugin-macros@3.1.0)(react@19.3.0))(supports-color@10.2.2)(type-fest@1.4.0)(typescript@6.0.3)(webpack@5.104.1(clean-css@5.3.3)(csso@4.2.0)(esbuild@0.28.2)(html-minifier-terser@6.1.0)(lightningcss@1.32.0)(postcss@8.5.23))(yaml@2.8.3)
@@ -129,8 +124,8 @@ importers:
specifier: ^1.11.23
version: 1.11.23
dompurify:
- specifier: ^3.4.16
- version: 3.4.16
+ specifier: ^3.4.17
+ version: 3.4.17
exceljs:
specifier: ^4.4.0
version: 4.4.0(patch_hash=a02bd99ddda9857e9f25c127e09b6892421f3a7f6a45b0481cb16973fb9ac9f7)
@@ -165,8 +160,8 @@ importers:
specifier: ^1.0.5
version: 1.0.5
tinymce:
- specifier: ^8.9.2
- version: 8.9.2
+ specifier: ^8.9.3
+ version: 8.10.1
tinymce-i18n:
specifier: ^26.9.28
version: 26.9.28
@@ -906,15 +901,15 @@ packages:
'@esbuild-kit/cjs-loader@2.4.4':
resolution: {integrity: sha512-NfsJX4PdzhwSkfJukczyUiZGc7zNNWZcEAyqeISpDnn0PTfzMJR1aR8xAIPskBejIxBJbIgCCMzbaYa9SXepIg==}
- deprecated: 'Merged into tsx: https://tsx.hirok.io'
+ deprecated: 'Merged into tsx: https://tsx.is'
'@esbuild-kit/core-utils@3.3.2':
resolution: {integrity: sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ==}
- deprecated: 'Merged into tsx: https://tsx.hirok.io'
+ deprecated: 'Merged into tsx: https://tsx.is'
'@esbuild-kit/esm-loader@2.6.5':
resolution: {integrity: sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA==}
- deprecated: 'Merged into tsx: https://tsx.hirok.io'
+ deprecated: 'Merged into tsx: https://tsx.is'
'@esbuild/aix-ppc64@0.25.12':
resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==}
@@ -2352,15 +2347,6 @@ packages:
tinymce:
optional: true
- '@turf/helpers@7.4.0':
- resolution: {integrity: sha512-7PAwLZqOdRzTI5g9bHvUwlloAXPDH/mlajtryk0tw4ZwGMtmXsAyF4QundsAMfy4u48Fyd3AUqMXY0SMxqJGWg==}
-
- '@turf/meta@7.4.0':
- resolution: {integrity: sha512-3cLUvlEyDuSnMSzrjhaLAEiYR8xhbfWyTVQlrlEw40xL81d4KF4PqUWbjTXKpXZStdYbet2GCurl79KMypNw6g==}
-
- '@turf/union@7.4.0':
- resolution: {integrity: sha512-SYVtsCW9IznTyKlcGWxssRrf90p/hdpch1UeIcZc31pkSVdmeLOyuzPx0ef3UPmaF//fgXAphMph6JWA/FpKbA==}
-
'@tweenjs/tween.js@25.0.0':
resolution: {integrity: sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==}
@@ -2499,9 +2485,6 @@ packages:
'@types/express@5.0.6':
resolution: {integrity: sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==}
- '@types/geojson@7946.0.16':
- resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==}
-
'@types/geojson@7946.0.8':
resolution: {integrity: sha512-1rkryxURpr6aWP7R786/UQOkJ3PcpQiWkAXBmdWc7ryFWqN6a4xfK7BtjXvFBKO9LjQ+MWQSWxYeZX1OApnArA==}
@@ -3342,9 +3325,6 @@ packages:
big.js@5.2.2:
resolution: {integrity: sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==}
- bignumber.js@9.3.1:
- resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==}
-
binary-extensions@2.2.0:
resolution: {integrity: sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==}
engines: {node: '>=8'}
@@ -4178,8 +4158,8 @@ packages:
cpu: [x64]
os: [win32]
- dompurify@3.4.16:
- resolution: {integrity: sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==}
+ dompurify@3.4.17:
+ resolution: {integrity: sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==}
domutils@2.8.0:
resolution: {integrity: sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==}
@@ -4630,8 +4610,8 @@ packages:
resolution: {integrity: sha512-kWyh8ADvHBFz6ua5xYOPnUroZTT/bwWfrCeL0Wj1dzG4/YOmOcfJ99W8dOVyyynJN35rZ9aCOtHChqQovV7yog==}
engines: {node: '>=6'}
- follow-redirects@1.16.0:
- resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}
+ follow-redirects@1.16.2:
+ resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
@@ -6241,9 +6221,6 @@ packages:
point-in-polygon@1.1.0:
resolution: {integrity: sha512-3ojrFwjnnw8Q9242TzgXuTD+eKiutbzyslcq1ydfu82Db2y+Ogbmyrkpv0Hgj31qwT3lbS9+QAAO/pIQM35XRw==}
- polyclip-ts@0.16.8:
- resolution: {integrity: sha512-JPtKbDRuPEuAjuTdhR62Gph7Is2BS1Szx69CFOO3g71lpJDFo78k4tFyi+qFOMVPePEzdSKkpGU3NBXPHHjvKQ==}
-
possible-typed-array-names@1.1.0:
resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==}
engines: {node: '>= 0.4'}
@@ -7506,9 +7483,6 @@ packages:
resolution: {integrity: sha512-1klA3Gi5PD1Wv9Q0wUoOQN1IWAuPu0D1U03ThXTr0cJ20+/iq2tHSDnK7Kk/0LXJ1ztUB2/1Os0wKmfyNgUQfg==}
hasBin: true
- splaytree-ts@1.0.2:
- resolution: {integrity: sha512-0kGecIZNIReCSiznK3uheYB8sbstLjCZLiwcQwbmLhgHJj2gz6OnSPkVzJQCMnmEz1BQ4gPK59ylhBoEWOhGNA==}
-
split-on-first@1.1.0:
resolution: {integrity: sha512-43ZssAJaMusuKWL8sKUBQXHWOpq8d6CfN/u1p4gUzfJkM05C8rxTmYrkIPTXapZpORA6LkkzcUulJ8FqA7Uudw==}
engines: {node: '>=6'}
@@ -7882,8 +7856,8 @@ packages:
tinymce-i18n@26.9.28:
resolution: {integrity: sha512-VOMMyvzji7veYm1+8gYpf05A70G308Cc1UCTCqwAgyx+jDqYOKsqssEm1RpdRQlKuPliVHgNg8lkm3jD0Y5gjg==}
- tinymce@8.9.2:
- resolution: {integrity: sha512-Qh6ADSC0x1F/KsrupfResNJFAaINJQBtfVjx5zxxWJ0ZrGtaKldtAXDMI6uEA57s2n+0rEtXmtbitiU4zV7+0Q==}
+ tinymce@8.10.1:
+ resolution: {integrity: sha512-Mgdnx8HuEPRlLqKTyHcy7+JJn9reXH7b7L/1ywPCzKAyjaq8fzEPE+CYBLW42GgBlaaoIOd0dTOcYHUlPZyV2A==}
tinyrainbow@3.1.1:
resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==}
@@ -9179,7 +9153,7 @@ snapshots:
'@zip.js/zip.js': 2.17.0
autolinker: 4.1.5
bitmap-sdf: 1.0.4
- dompurify: 3.4.16
+ dompurify: 3.4.17
draco3d: 1.5.7
earcut: 3.0.2
grapheme-splitter: 1.0.4
@@ -10670,32 +10644,13 @@ snapshots:
optionalDependencies:
react-dom: 19.3.0(react@19.3.0)
- '@tinymce/tinymce-react@6.3.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(tinymce@8.9.2)':
+ '@tinymce/tinymce-react@6.3.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(tinymce@8.10.1)':
dependencies:
prop-types: 15.8.1
react: 19.3.0
react-dom: 19.3.0(react@19.3.0)
optionalDependencies:
- tinymce: 8.9.2
-
- '@turf/helpers@7.4.0':
- dependencies:
- '@types/geojson': 7946.0.16
- tslib: 2.8.1
-
- '@turf/meta@7.4.0':
- dependencies:
- '@turf/helpers': 7.4.0
- '@types/geojson': 7946.0.16
- tslib: 2.8.1
-
- '@turf/union@7.4.0':
- dependencies:
- '@turf/helpers': 7.4.0
- '@turf/meta': 7.4.0
- '@types/geojson': 7946.0.16
- polyclip-ts: 0.16.8
- tslib: 2.8.1
+ tinymce: 8.10.1
'@tweenjs/tween.js@25.0.0': {}
@@ -10880,8 +10835,6 @@ snapshots:
'@types/express-serve-static-core': 5.1.3
'@types/serve-static': 2.2.0
- '@types/geojson@7946.0.16': {}
-
'@types/geojson@7946.0.8': {}
'@types/hapi__joi@17.1.9': {}
@@ -12218,7 +12171,7 @@ snapshots:
axios@1.20.0(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2):
dependencies:
- follow-redirects: 1.16.0(debug@4.4.3(supports-color@10.2.2))
+ follow-redirects: 1.16.2(debug@4.4.3(supports-color@10.2.2))
form-data: 4.0.6
https-proxy-agent: 5.0.1(supports-color@10.2.2)
proxy-from-env: 2.1.0
@@ -12280,8 +12233,6 @@ snapshots:
big.js@5.2.2: {}
- bignumber.js@9.3.1: {}
-
binary-extensions@2.2.0: {}
binary@0.3.0:
@@ -13002,7 +12953,7 @@ snapshots:
decimal.js@10.6.0: {}
- decode-uri-component@0.2.2(patch_hash=4bd5a5e1ec0b95817e4d3a1266b29d7ff4d7065630ae4b35a1f0cdec0de579cc): {}
+ decode-uri-component@0.2.2(patch_hash=337cc9f69eb805a7555bdbcde5fca0a3e8f210e97c35338fa6f54c6bd2fd1bf9): {}
deep-is@0.1.4: {}
@@ -13135,7 +13086,7 @@ snapshots:
domparser-win32-x64-msvc@0.0.7:
optional: true
- dompurify@3.4.16:
+ dompurify@3.4.17:
optionalDependencies:
'@types/trusted-types': 2.0.7
@@ -13900,7 +13851,7 @@ snapshots:
flru@1.0.2: {}
- follow-redirects@1.16.0(debug@4.4.3(supports-color@10.2.2)):
+ follow-redirects@1.16.2(debug@4.4.3(supports-color@10.2.2)):
optionalDependencies:
debug: 4.4.3(supports-color@10.2.2)
@@ -15510,11 +15461,6 @@ snapshots:
point-in-polygon@1.1.0: {}
- polyclip-ts@0.16.8:
- dependencies:
- bignumber.js: 9.3.1
- splaytree-ts: 1.0.2
-
possible-typed-array-names@1.1.0: {}
postcss-attribute-case-insensitive@5.0.2(postcss@8.5.23):
@@ -15872,7 +15818,7 @@ snapshots:
query-string@6.14.1:
dependencies:
- decode-uri-component: 0.2.2(patch_hash=4bd5a5e1ec0b95817e4d3a1266b29d7ff4d7065630ae4b35a1f0cdec0de579cc)
+ decode-uri-component: 0.2.2(patch_hash=337cc9f69eb805a7555bdbcde5fca0a3e8f210e97c35338fa6f54c6bd2fd1bf9)
filter-obj: 1.1.0
split-on-first: 1.1.0
strict-uri-encode: 2.0.0
@@ -16978,8 +16924,6 @@ snapshots:
specificity@0.4.1: {}
- splaytree-ts@1.0.2: {}
-
split-on-first@1.1.0: {}
split2@4.2.0: {}
@@ -17432,7 +17376,7 @@ snapshots:
tinymce-i18n@26.9.28: {}
- tinymce@8.9.2: {}
+ tinymce@8.10.1: {}
tinyrainbow@3.1.1: {}
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 439d284d..deeb95f5 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -30,10 +30,11 @@ overrides:
'colord@<2.9.4': '2.9.4'
'compression@>=1.0.0 <1.8.2': '1.8.2'
'cross-spawn@>=7.0.0 <7.0.5': '7.0.6'
- 'dompurify@>=3.0.0 <3.4.16': '3.4.16'
+ 'dompurify@>=3.0.0 <3.4.17': '3.4.17'
'es5-ext@<0.10.63': '0.10.64'
'esbuild@<0.25.0': '0.25.12'
'fast-uri@>=3.0.0 <3.1.8': '3.1.8'
+ 'follow-redirects@>=1.0.0 <1.16.2': '1.16.2'
'form-data@>=4.0.0 <4.0.6': '4.0.6'
'glob@>=10.2.0 <10.5.0': '10.5.0'
'hono@>=4.0.0 <4.13.7': '4.13.7'
diff --git a/scripts/check-bundle-size.mjs b/scripts/check-bundle-size.mjs
index 48bbbdef..d1417f35 100644
--- a/scripts/check-bundle-size.mjs
+++ b/scripts/check-bundle-size.mjs
@@ -124,6 +124,12 @@ if (!existsSync(chunkGraphPath)) {
continue;
}
const files = [...new Set(groups.flatMap((g) => graph[g]))].filter((f) => /\.m?js$/.test(f));
+ const missingChunks = files.filter((f) => !existsSync(join(distDir, f)));
+ // 静默跳过缺失 chunk 会少算总量(chunk 清单过期/产物被裁剪时门禁形同虚设),
+ // 与上方入口同步脚本的处理同口径:缺失即记 failure
+ if (missingChunks.length) {
+ failures.push(`路由 ${route} 首屏的 chunk 在产物中不存在(体积合计会少算):${missingChunks.join(', ')}`);
+ }
const total = files.reduce(
(acc, f) => {
const file = join(distDir, f);
diff --git a/scripts/check-dist-secrets.mjs b/scripts/check-dist-secrets.mjs
index b1a4bd3f..91185cf7 100644
--- a/scripts/check-dist-secrets.mjs
+++ b/scripts/check-dist-secrets.mjs
@@ -66,8 +66,12 @@ const SECRET_PATTERNS = [
[/ghp_[A-Za-z0-9]{36}/, 'GitHub PAT(ghp_)'],
[/gho_[A-Za-z0-9]{36}/, 'GitHub OAuth token(gho_)'],
[/github_pat_[A-Za-z0-9_]{22,}/, 'GitHub fine-grained PAT'],
- [/sk-[A-Za-z0-9]{20,}/, 'sk- 前缀 API key'],
+ // sk- 的字符类不含 '-',会漏掉 sk-ant-(Anthropic)这类带内嵌连字符的前缀
+ [/sk-(?:ant-)?[A-Za-z0-9-]{20,}/, 'sk- 前缀 API key(含 sk-ant-)'],
+ [/glpat-[A-Za-z0-9_-]{20,}/, 'GitLab PAT(glpat-)'],
+ [/npm_[A-Za-z0-9]{36}/, 'npm access token(npm_)'],
[/xox[bp]-[A-Za-z0-9-]{10,}/, 'Slack token'],
+ [/AIza[0-9A-Za-z_-]{35}/, 'Google API key(AIza)'],
[/-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----/, 'PEM 私钥块'],
];
diff --git a/scripts/dependency-audit.mjs b/scripts/dependency-audit.mjs
index 068a2f7f..eee34b42 100644
--- a/scripts/dependency-audit.mjs
+++ b/scripts/dependency-audit.mjs
@@ -8,8 +8,63 @@ const projectRoot = fileURLToPath(new URL('..', import.meta.url));
const severities = ['info', 'low', 'moderate', 'high', 'critical'];
const patchedAdvisories = {
'GHSA-vfj7-8cjw-p6xm': { name: 'braces', version: '3.0.3' },
+ // 同一份回移源码同时覆盖 0.5.0 的线性扫描(fa479da)与 0.5.1 的单遍替换:
+ // 两者的修复都已在 patches/decode-uri-component@0.2.2.patch 里,proof 按安装源 SHA 验证
'GHSA-vcc3-ghjq-m6fr': { name: 'decode-uri-component', version: '0.2.2' },
+ 'GHSA-qr28-fpjm-wq7f': { name: 'decode-uri-component', version: '0.2.2' },
};
+
+/**
+ * 构建链根:只出现在这些子树下的依赖不进 dist 产物(打包器/编译器/测试与 lint 工具链)。
+ * 分层规则(2026-11-01):进产物的运行时依赖公告保持零忽略、阻塞;构建链传递依赖的公告
+ * 降为非阻塞告警——上游(@umijs/max)锁死版本、仓库无法升格,而 GHSA 数据库每次更新都会
+ * 把这类公告塞进来,2026-10-21 起已把所有 PR 的 check 连续打红。AUDIT_TOOLCHAIN_STRICT=1
+ * 可恢复全量阻塞(用于周期性人工清点)。
+ * 判定从宽:一条公告的所有路径都必须命中构建链标记才算构建链;有任何一条旁路即按运行时阻塞。
+ */
+const buildChainSegments = [
+ // 打包器/编译器子树
+ '@umijs/bundler-vite',
+ '@umijs/bundler-webpack',
+ '@umijs/bundler-mako',
+ '@umijs/bundler-utoopack',
+ '@utoo/pack',
+ '@umijs/mako',
+ '@tailwindcss/webpack',
+ // 测试与 lint 工具链(vitest/jsdom/eslint/stylelint 家族,只在本机与 CI 运行)
+ 'vitest',
+ '@vitest/coverage-v8',
+ '@vitest/eslint-plugin',
+ 'jsdom',
+ 'stylelint',
+ 'eslint',
+ 'eslint-plugin-react-hooks',
+ 'eslint-plugin-react',
+ 'eslint-plugin-jsx-a11y',
+ 'typescript-eslint',
+ '@typescript-eslint/parser',
+ '@typescript-eslint/eslint-plugin',
+ '@typescript-eslint/type-utils',
+ '@typescript-eslint/utils',
+ '@typescript-eslint/typescript-estree',
+ '@eslint/config-array',
+ '@eslint/eslintrc',
+ '@humanwhocodes/config-array',
+ // 纯 Node 的构建辅助(fsync/临时目录/文件匹配),不存在浏览器形态
+ 'file-entry-cache',
+ 'flat-cache',
+ 'rimraf',
+ 'glob',
+ // exceljs 的 Node 侧流式插件:浏览器入口已被改到 lib/exceljs.bare.js
+ // (dependency-security.test.ts 断言 manifest.browser),这些子树不进产物
+ 'archiver',
+ 'archiver-utils',
+ 'zip-stream',
+ 'readdir-glob',
+ 'unzipper',
+ 'fstream',
+];
+
const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
/** Reject endpoint/schema failures and retain all severities; an empty or partial response is not success. */
@@ -106,9 +161,25 @@ export const verifyInstalledPatches = (root = projectRoot, proof) => {
return verified;
};
-export const assessAdvisories = (audit, verified) => {
+/** 公告分层:每一条安装路径都只经过构建链子树的公告归入 toolchain,其余(含混合路径)归入 runtime。 */
+export const classifyAdvisories = (audit) => {
+ const toolchain = [];
+ const runtime = [];
+ for (const advisory of Object.values(audit.advisories)) {
+ // 从宽判定:只要存在任何一条绕开构建链标记的路径,整条公告就按运行时阻塞处理
+ const onlyBuildChain = advisory.findings.every((finding) =>
+ finding.paths.every((path) => path.split('>').some((segment) => buildChainSegments.includes(segment))),
+ );
+ (onlyBuildChain ? toolchain : runtime).push(advisory);
+ }
+ return { toolchain, runtime };
+};
+
+export const assessAdvisories = (audit, verified, { toolchainStrict = false } = {}) => {
const proven = [];
const blocked = [];
+ const toolchain = [];
+ const toolchainIds = new Set(classifyAdvisories(audit).toolchain.map((advisory) => advisory.github_advisory_id));
for (const advisory of Object.values(audit.advisories)) {
const expected = patchedAdvisories[advisory.github_advisory_id];
if (
@@ -118,11 +189,13 @@ export const assessAdvisories = (audit, verified) => {
advisory.findings.every((finding) => finding.version === expected.version)
) {
proven.push(advisory.github_advisory_id);
+ } else if (toolchainIds.has(advisory.github_advisory_id) && !toolchainStrict) {
+ toolchain.push(advisory.github_advisory_id);
} else {
blocked.push(advisory.github_advisory_id);
}
}
- return { proven, blocked };
+ return { proven, blocked, toolchain };
};
const run = () => {
@@ -153,10 +226,25 @@ const run = () => {
},
);
if (regression.error || regression.status !== 0) throw new Error('Installed dependency attack regressions failed');
- const assessment = assessAdvisories(audit, verified);
+ const assessment = assessAdvisories(audit, verified, {
+ toolchainStrict: process.env.AUDIT_TOOLCHAIN_STRICT === '1',
+ });
for (const id of assessment.proven) console.log(`Source repair verified; upstream version match retained: ${id}`);
+ const toolchainAdvisories = Object.values(audit.advisories).filter((advisory) =>
+ assessment.toolchain.includes(advisory.github_advisory_id),
+ );
+ for (const advisory of toolchainAdvisories) {
+ console.warn(
+ `Build-chain advisory (non-blocking): ${advisory.github_advisory_id} ${advisory.module_name}@${advisory.findings
+ .map((finding) => finding.version)
+ .join(',')} [${advisory.severity}] — 不进产物;AUDIT_TOOLCHAIN_STRICT=1 可恢复阻塞`,
+ );
+ }
+ if (toolchainAdvisories.length) {
+ console.warn(`Build-chain advisories total: ${toolchainAdvisories.length} (non-blocking)`);
+ }
if (assessment.blocked.length) throw new Error(`Unrepaired advisories: ${assessment.blocked.join(', ')}`);
- console.log('Dependency gate passed: no advisories without a verified source repair');
+ console.log('Dependency gate passed: no runtime advisories without a verified source repair');
};
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
diff --git a/scripts/dependency-audit.test.ts b/scripts/dependency-audit.test.ts
index 721c8d8a..480bdad1 100644
--- a/scripts/dependency-audit.test.ts
+++ b/scripts/dependency-audit.test.ts
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
-import { assessAdvisories, parseAudit, verifyInstalledPatches } from './dependency-audit.mjs';
+import { assessAdvisories, classifyAdvisories, parseAudit, verifyInstalledPatches } from './dependency-audit.mjs';
const report = (overrides: Record
= {}) => ({
advisories: {
@@ -28,10 +28,15 @@ describe('依赖审计必须保留原始公告并证明全部实际实例', () =
it('源码修补只适用于同一公告、模块和版本,未证明时失败', () => {
const audit = parseAudit(JSON.stringify(report()));
- expect(assessAdvisories(audit, new Map())).toEqual({ proven: [], blocked: ['GHSA-vfj7-8cjw-p6xm'] });
+ expect(assessAdvisories(audit, new Map())).toEqual({
+ proven: [],
+ blocked: ['GHSA-vfj7-8cjw-p6xm'],
+ toolchain: [],
+ });
expect(assessAdvisories(audit, new Map([['braces', '3.0.3']]))).toEqual({
proven: ['GHSA-vfj7-8cjw-p6xm'],
blocked: [],
+ toolchain: [],
});
const otherVersion = parseAudit(JSON.stringify(report({ findings: [{ version: '3.0.2', paths: ['.>braces'] }] })));
expect(assessAdvisories(otherVersion, new Map([['braces', '3.0.3']])).blocked).toHaveLength(1);
@@ -39,7 +44,7 @@ describe('依赖审计必须保留原始公告并证明全部实际实例', () =
expect(assessAdvisories(otherModule, new Map([['braces', '3.0.3']])).blocked).toHaveLength(1);
});
- it.each(['low', 'moderate', 'high', 'critical'])('任何新 %s 公告都阻断', (severity) => {
+ it.each(['low', 'moderate', 'high', 'critical'])('任何新的运行时 %s 公告都阻断', (severity) => {
const input = report({ github_advisory_id: 'GHSA-new1-new2-new3', severity });
input.metadata.vulnerabilities.high = 0;
input.metadata.vulnerabilities[severity as 'low' | 'moderate' | 'high' | 'critical'] = 1;
@@ -90,3 +95,70 @@ describe('依赖审计必须保留原始公告并证明全部实际实例', () =
expect(() => verifyInstalledPatches(root, proof)).toThrow(/differs/);
});
});
+
+describe('审计分层:构建链告警不阻塞,运行时零忽略(2026-11-01 政策)', () => {
+ const one = (id: string, moduleName: string, paths: string[], version = '1.0.0') => ({
+ github_advisory_id: id,
+ module_name: moduleName,
+ severity: 'moderate',
+ findings: [{ version, paths }],
+ });
+ const auditOf = (...advisories: ReturnType[]) =>
+ parseAudit(
+ JSON.stringify({
+ advisories: Object.fromEntries(advisories.map((item, index) => [index, item])),
+ metadata: {
+ vulnerabilities: { info: 0, low: 0, moderate: advisories.length, high: 0, critical: 0 },
+ },
+ }),
+ );
+
+ it('所有路径都只经过构建链子树的公告归入 toolchain', () => {
+ const tiers = classifyAdvisories(
+ auditOf(
+ one('GHSA-vite', 'vite', [
+ '.>@umijs/max>umi>@umijs/preset-umi>@umijs/bundler-vite>vite',
+ '.>@umijs/preset-umi>@umijs/bundler-vite>@vitejs/plugin-react>vite',
+ ]),
+ one('GHSA-undici', 'undici', ['.>@vitest/coverage-v8>vitest>jsdom>undici']),
+ ),
+ );
+ expect(tiers.toolchain.map((item) => item.github_advisory_id)).toEqual(['GHSA-vite', 'GHSA-undici']);
+ expect(tiers.runtime).toEqual([]);
+ });
+
+ it('任一路径绕开构建链(可进产物或混合可达)即归入 runtime —— 判定从宽', () => {
+ const tiers = classifyAdvisories(
+ auditOf(
+ one('GHSA-mixed', 'minimatch', ['.>eslint>minimatch', '.>some-runtime-lib>minimatch']),
+ one('GHSA-cesium', 'dompurify', ['.>cesium>@cesium/engine>dompurify']),
+ ),
+ );
+ expect(tiers.runtime.map((item) => item.github_advisory_id)).toEqual(['GHSA-mixed', 'GHSA-cesium']);
+ expect(tiers.toolchain).toEqual([]);
+ });
+
+ it('构建链公告默认不阻塞,AUDIT_TOOLCHAIN_STRICT 恢复阻塞语义', () => {
+ const audit = auditOf(
+ one('GHSA-runtime', 'tinymce', ['.>tinymce']),
+ one('GHSA-toolchain', 'hono', ['.>@umijs/bundler-utoopack>@utoo/pack>hono']),
+ );
+ const lenient = assessAdvisories(audit, new Map());
+ expect(lenient.blocked).toEqual(['GHSA-runtime']);
+ expect(lenient.toolchain).toEqual(['GHSA-toolchain']);
+ const strict = assessAdvisories(audit, new Map(), { toolchainStrict: true });
+ expect(strict.blocked).toEqual(['GHSA-runtime', 'GHSA-toolchain']);
+ expect(strict.toolchain).toEqual([]);
+ });
+
+ it('已证明源码修复的公告进 proven,与层级无关', () => {
+ const audit = auditOf(
+ one('GHSA-vcc3-ghjq-m6fr', 'decode-uri-component', [
+ '.>@umijs/history>query-string>decode-uri-component',
+ ], '0.2.2'),
+ );
+ const assessment = assessAdvisories(audit, new Map([['decode-uri-component', '0.2.2']]));
+ expect(assessment.proven).toEqual(['GHSA-vcc3-ghjq-m6fr']);
+ expect(assessment.blocked).toEqual([]);
+ });
+});
diff --git a/scripts/dependency-patch-proof.json b/scripts/dependency-patch-proof.json
index a8dd25e8..ff9d171a 100644
--- a/scripts/dependency-patch-proof.json
+++ b/scripts/dependency-patch-proof.json
@@ -22,7 +22,7 @@
"decode-uri-component": {
"version": "0.2.2",
"files": {
- "index.js": "5112ff71759fadbfd485235d26e80573eb2837bf15cc3cd8597cf14e9b6c27b5",
+ "index.js": "90bebf25138e46944409e42263b176eac3005bd2be3b6e55548e84e76b55a87e",
"package.json": "8f2e9784337b3b4fa69359f88f75a2847e0aa17776f062cb518d008d8d408bca"
}
},
diff --git a/scripts/dependency-security.test.ts b/scripts/dependency-security.test.ts
index f9e0305b..8718afd1 100644
--- a/scripts/dependency-security.test.ts
+++ b/scripts/dependency-security.test.ts
@@ -229,6 +229,24 @@ describe('decode-uri-component 的官方回移', () => {
expect(source).toContain('while (position < input.length)');
expect(source).not.toContain('decodeComponents');
});
+
+ it('GHSA-qr28:百分号编码串单遍替换,不再有二次方 replaceMap 循环', () => {
+ // 上游 0.5.1 的两个特例随单遍扫描落在 decode() 内:UTF-16 BOM 与截断的 %C2
+ expect(decode('%FE%FF')).toBe('\uFFFD\uFFFD');
+ expect(decode('%FF%FE')).toBe('\uFFFD\uFFFD');
+ expect(decode('%C2')).toBe('\uFFFD');
+ expect(decode('a%C2b')).toBe('a\uFFFDb');
+ const source = read(join(installed(name, '0.2.2'), 'index.js'));
+ expect(source).toContain('input.replace(multiMatcher');
+ expect(source).not.toContain('replaceMap');
+ // 大量互不相同的编码串(旧实现的 replaceMap 逐 key 全串扫描是二次方)单遍正确解码
+ const big = Array.from({ length: 4000 }, (_, index) => `%${(0x41 + (index % 26)).toString(16)}${index % 10}`).join(
+ '',
+ );
+ const decoded = decode(big);
+ expect(decoded).not.toContain('%41');
+ expect(decoded.length).toBeLessThanOrEqual(big.length);
+ });
});
describe('Excel 的真实浏览器工作簿与密码保护', () => {
diff --git a/scripts/real-mode-artifact.test.ts b/scripts/real-mode-artifact.test.ts
index c4246c65..3788da84 100644
--- a/scripts/real-mode-artifact.test.ts
+++ b/scripts/real-mode-artifact.test.ts
@@ -21,6 +21,11 @@ const DEMO_DATA_MARKERS = [
const STUB_SENTINEL = '__REAL_MODE_ADAPTER_STUB__';
/** token 替身哨兵:第二个 alias(src/demo/token.real.ts)同样要有正控制 */
const TOKEN_STUB_SENTINEL = '__REAL_MODE_TOKEN_STUB__';
+/**
+ * clock 替身哨兵:第三个 alias(src/demo/clock.real.ts)。now.ts 只被页面引用,
+ * 该哨兵只会出现在异步 chunk,因此它的正控制扫描整个 dist 而不只是入口。
+ */
+const CLOCK_STUB_SENTINEL = '__REAL_MODE_CLOCK_STUB__';
/**
* 门禁上下文(CI 的 build:real 作业)用 REAL_MODE_ARTIFACT_REQUIRED=1 声明「这里必须是真实模式产物」:
@@ -134,6 +139,23 @@ const entryChunksContaining = (marker: string) =>
expect(hits, `以下产物仍含演示数据标记: ${hits.join(', ')}`).toEqual([]);
});
+ /**
+ * 第三个正控制:clock 替身哨兵。alias 换掉的是懒加载 chunk 里的 '@/demo/clock',
+ * 只扫入口必然漏报 —— 扫全部 .js,出现即证明第三个 alias 真的生效;
+ * 顺带断言演示时钟存储键在异步 chunk 里也消失(这正是加该替身的动机)。
+ */
+ it.skipIf(demoMode !== false)('真实模式产物含 clock 替身哨兵,且异步 chunk 无演示时钟存储键', () => {
+ const jsFiles = readdirSync(distDir).filter((name) => name.endsWith('.js'));
+ const withSentinel = jsFiles.filter((name) =>
+ readFileSync(join(distDir, name), 'utf8').includes(CLOCK_STUB_SENTINEL),
+ );
+ expect(withSentinel, '产物未出现 clock 替身哨兵(第三个 alias 未生效)').not.toEqual([]);
+ const withClockKey = jsFiles.filter((name) =>
+ readFileSync(join(distDir, name), 'utf8').includes('umi-react-admin:demo-clock'),
+ );
+ expect(withClockKey, '以下异步 chunk 仍含演示时钟存储键').toEqual([]);
+ });
+
/** 真实模式残留面:demo 时钟存储键(旧 adapter → clock 链)与 demo token 前缀都不该出现在入口 */
it.skipIf(demoMode !== false)('真实模式入口 chunk 不含 demo 时钟存储键与 demo token 前缀', () => {
expect(entryChunksContaining('umi-react-admin:demo-clock')).toEqual([]);
@@ -163,4 +185,12 @@ const entryChunksContaining = (marker: string) =>
expect(entryChunksContaining('ALM-SCN').length).toBeGreaterThan(0);
expect(entryChunksContaining('umi-react-admin:demo-store').length).toBeGreaterThan(0);
});
+
+ /** 反向断言的异步面:演示构建走真实 clock,clock 替身哨兵不得出现在任何 chunk */
+ it.skipIf(demoMode !== true)('演示模式产物不含 clock 替身哨兵', () => {
+ const hits = readdirSync(distDir)
+ .filter((name) => name.endsWith('.js'))
+ .filter((name) => readFileSync(join(distDir, name), 'utf8').includes(CLOCK_STUB_SENTINEL));
+ expect(hits, '演示产物不应出现真实模式 clock 替身').toEqual([]);
+ });
});
diff --git a/src/app.tsx b/src/app.tsx
index 67ae4a1e..5359438c 100644
--- a/src/app.tsx
+++ b/src/app.tsx
@@ -8,6 +8,7 @@ import ErrorBoundary from '@/components/ErrorBoundary';
import GroupNav from '@/components/GroupNav';
import GuideTour from '@/components/GuideTour';
import PageTransition from '@/components/PageTransition';
+import { REPO_URL as REPO } from '@/constants/repo';
import { syncColorScheme } from '@/hooks/useThemeMode';
import RightContent from '@/layouts/RightContent';
import Forbidden from '@/pages/Exception/403';
@@ -115,8 +116,6 @@ const AccessFallback = () => {
return ;
};
-import { REPO_URL as REPO } from '@/constants/repo';
-
/** 左上角应用列表:项目相关链接(图标用内置图标,不再热链第三方图片,CSP 随之收紧) */
const appList = () => {
const t = (id: string) => getIntl().formatMessage({ id });
diff --git a/src/components/CommandPalette/index.tsx b/src/components/CommandPalette/index.tsx
index 5f3e55b9..525a527c 100644
--- a/src/components/CommandPalette/index.tsx
+++ b/src/components/CommandPalette/index.tsx
@@ -1,3 +1,4 @@
+import { isMac } from '@/utils/platform';
import { canAccessRoute, type NavRoute } from '@/utils/routeNav';
import { SearchOutlined } from '@ant-design/icons';
import { history, useAccess, useAppData, useIntl } from '@umijs/max';
@@ -35,8 +36,6 @@ export const filterEntries = (entries: NavEntry[], query: string, labelOf: (entr
return entries.filter((entry) => labelOf(entry).toLowerCase().includes(q) || entry.path.toLowerCase().includes(q));
};
-const isMac = () => /Mac|iPhone|iPad/.test(navigator.platform);
-
/**
* ⌘K / Ctrl+K 命令面板:全站页面按名直达,弥补宽信息架构下「目标页在哪个分组」的记忆成本,
* 也是窄屏页签横滚之外的补救路径。键盘优先(↑↓ 选、Enter 开、Esc 关),权限过滤与菜单同口径。
diff --git a/src/demo/generate.test.ts b/src/demo/generate.test.ts
index c5acd5b4..ca0819ca 100644
--- a/src/demo/generate.test.ts
+++ b/src/demo/generate.test.ts
@@ -183,7 +183,9 @@ describe('工单', () => {
expect(data.tickets.filter((x) => x.resolvedAt && t(x.resolvedAt) > since).length).toBeGreaterThan(5);
});
- it('两周内任意时刻,「处理中」都不少于 5 张(拖拽演示不至于只剩一两张卡)', () => {
+ // 56 次全量 generateDataset 单跑约 2.1s;并发负载下会顶爆 5s 默认超时(2026-10-31 实测 flaky),
+ // 用例本身是固定种子、完全确定性——显式放宽超时只影响等待上限,不放松断言
+ it('两周内任意时刻,「处理中」都不少于 5 张(拖拽演示不至于只剩一两张卡)', { timeout: 20_000 }, () => {
const counts = Array.from({ length: 14 }, (_, d) =>
[3, 10, 15, 21].map(
(hour) =>
diff --git a/src/demo/generate.ts b/src/demo/generate.ts
index 0bbe3da2..6fc8ca61 100644
--- a/src/demo/generate.ts
+++ b/src/demo/generate.ts
@@ -387,7 +387,9 @@ const generateAlarmsAndTickets = (locale: DemoLocale, now: Date, devices: Device
draft.resolve *= scale;
}
} else if (draft.closeAfter > remaining - MINUTE) {
- draft.closeAfter = Math.max(5_000, remaining * 0.5);
+ // 钳到剩余时间内:remaining < 5s 时 5000ms 下限会越过 now,告警滞留为 active,
+ // 违反「在线设备不带未恢复阻断告警」的 P3-1 不变式
+ draft.closeAfter = Math.min(Math.max(5_000, remaining * 0.5), remaining);
}
}
const id = `ALM-${key}-${String(index + 1).padStart(3, '0')}`;
diff --git a/src/demo/manifest.test.ts b/src/demo/manifest.test.ts
index d90f4c67..7f808fbb 100644
--- a/src/demo/manifest.test.ts
+++ b/src/demo/manifest.test.ts
@@ -10,6 +10,14 @@ import { STORE_KEY, STORE_VERSION } from './store';
*/
const MANIFEST_PATH = new URL('../../docs/demo/demo-scenarios.json', import.meta.url);
+/** 体验账号 → 角色 key(与 scenarios.ts 的种子角色同一映射;查表取代四层嵌套三元) */
+const ROLE_KEY: Record = {
+ admin: 'admin',
+ lead: 'lead',
+ operator: 'operator',
+ analyst: 'analyst',
+};
+
const buildManifest = () => ({
// 与存储版本同源:升 STORE_VERSION 时清单随之变化,提醒重新生成
version: STORE_VERSION,
@@ -18,16 +26,7 @@ const buildManifest = () => ({
accounts: DEMO_ACCOUNTS.map((username) => ({
username,
password: 'demo',
- roleKey:
- username === 'admin'
- ? 'admin'
- : username === 'lead'
- ? 'lead'
- : username === 'operator'
- ? 'operator'
- : username === 'analyst'
- ? 'analyst'
- : 'viewer',
+ roleKey: ROLE_KEY[username] ?? 'viewer',
})),
clock: {
live: '跟随真实时间;演示后端每请求检查,跨过 60 秒即按当前时钟重建基础数据(补丁保留)',
diff --git a/src/demo/scenarios.ts b/src/demo/scenarios.ts
index 89b74750..061018e4 100644
--- a/src/demo/scenarios.ts
+++ b/src/demo/scenarios.ts
@@ -676,7 +676,11 @@ export const verifyScenarios = (dataset: Dataset, now: Date): string[] => {
const rework = byId(dataset.tickets, SCENARIO_IDS.reworkTicket);
if (rework && !rework.acceptance?.signature)
problems.push('rework ticket must carry a pre-seeded acceptance signature');
- if (rework && new Date(rework.acceptance!.signedAt).getTime() < new Date(rework.resolvedAt!).getTime()) {
+ // 验收可能缺席(上一条只记录 problem):这里必须可空链,否则 verifyScenarios 自己先 TypeError
+ if (
+ rework?.acceptance?.signedAt &&
+ new Date(rework.acceptance.signedAt).getTime() < new Date(rework.resolvedAt!).getTime()
+ ) {
problems.push('rework acceptance must be signed after resolution');
}
[SCENARIO_IDS.accept1, SCENARIO_IDS.accept2].forEach((id) => {
diff --git a/src/demo/server/index.ts b/src/demo/server/index.ts
index d298fa4b..398544d1 100644
--- a/src/demo/server/index.ts
+++ b/src/demo/server/index.ts
@@ -8,7 +8,7 @@ import { DemoStore, type StorageLike } from '../store';
import { verifyDemoToken } from '../token';
import { BizFailure, HttpError, type DemoRequest, type DemoResponse } from './http';
import { message } from './messages';
-import { resolvePermissions, routes, type Route, type Session } from './routes';
+import { PROTECTED_USERNAMES, resolvePermissions, routes, type Route, type Session } from './routes';
export type { DemoRequest, DemoResponse } from './http';
@@ -49,8 +49,10 @@ export const createDemoServer = (options: { locale: DemoLocale; storage?: Storag
const payload = matched ? verifyDemoToken(matched[1]) : null;
if (!payload) return undefined;
const user = store.dataset.users.find((u) => u.username.toLowerCase() === payload.name.toLowerCase());
- // 种子用户被停用后,已签发的 token 随之失效
+ // 种子用户被停用后,已签发的 token 随之失效;被删除同理——否则 admin 种子账号删除后
+ // 其 token 会走「无用户记录」路径,继续保留 admin 角色全部权限
if (user && user.status !== 'active') return undefined;
+ if (!user && PROTECTED_USERNAMES.has(payload.name.toLowerCase())) return undefined;
return {
username: payload.name,
role: payload.role,
@@ -59,6 +61,15 @@ export const createDemoServer = (options: { locale: DemoLocale; storage?: Storag
};
};
+ /** 路径参数解码:畸形百分号编码(如 /tickets/%E4%25)按 400 响应,而不是抛裸 URIError 逃过异常分类 */
+ const decodeParam = (value: string): string => {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ throw new HttpError(400, message('notFound', locale));
+ }
+ };
+
const handle = (request: DemoRequest): DemoResponse => {
const method = request.method.toUpperCase();
const url = new URL(request.url, 'http://demo.local');
@@ -68,7 +79,7 @@ export const createDemoServer = (options: { locale: DemoLocale; storage?: Storag
// 时钟推进检查(F09):live 模式下跨过阈值按当前时间重建基础数据(补丁保留);受控模式时钟冻结不会触发
store.refreshIfStale();
const values = url.pathname.match(route.pattern)!.slice(1);
- const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(values[i])]));
+ const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeParam(values[i])]));
const query = { ...Object.fromEntries(url.searchParams), ...(request.params ?? {}) };
const session = resolveSession(request.headers?.Authorization ?? request.headers?.authorization);
if (route.access !== 'public' && !session) throw new HttpError(401, message('unauthorized', locale));
diff --git a/src/demo/server/messages.ts b/src/demo/server/messages.ts
index 6784fe66..506297cb 100644
--- a/src/demo/server/messages.ts
+++ b/src/demo/server/messages.ts
@@ -74,6 +74,10 @@ const MESSAGES = {
zh: '导入请求结构不合法,未写入任何数据',
en: 'The import request is malformed; nothing was written',
},
+ actionInvalid: {
+ zh: '操作类型不在支持范围内',
+ en: 'The action is not one of the supported kinds',
+ },
} as const;
export type MessageKey = keyof typeof MESSAGES;
diff --git a/src/demo/server/routes.ts b/src/demo/server/routes.ts
index f03aedc8..f605e8d6 100644
--- a/src/demo/server/routes.ts
+++ b/src/demo/server/routes.ts
@@ -77,7 +77,8 @@ const DEPARTMENT_KEYS = DEPARTMENTS.map((d) => d.key);
const USER_STATUSES: UserStatus[] = ['active', 'disabled', 'locked'];
const EVENT_TYPES: EventType[] = ['duty', 'inspection', 'review', 'training', 'maintenance', 'release'];
/** 受保护账号:五种快捷体验账号不能被停用/删除/改名,避免演示自断入口 */
-const PROTECTED_USERNAMES = new Set(['admin', 'guest', 'lead', 'operator', 'analyst']);
+/** 体验/种子账号名:既是受保护账号,也是「删除后 token 必须失效」的判定集合(见 server/index.ts) */
+export const PROTECTED_USERNAMES = new Set(['admin', 'guest', 'lead', 'operator', 'analyst']);
const BOARD_DONE_DAYS = 3;
/** 批量用户动作 → 操作日志 action(与单条 DELETE/PUT 保持同一套命名,便于按 action 过滤) */
@@ -109,9 +110,13 @@ let logSeq = 0;
/** 把演示后端里发生的写操作记进操作日志(日志页能看到自己的操作) */
const writeLog = (ctx: RouteContext, action: LogAction, target: string, result: OperationLog['result'] = 'success') => {
const now = ctx.store.now();
- logSeq += 1;
ctx.store.create('logs', {
- id: `LOG-${now.getTime().toString(36).toUpperCase()}-${logSeq}`,
+ // 时间基 + 进程序号在冻结时钟/重载下都会撞号(锚点相同、logSeq 归零):补随机后缀保证唯一,
+ // 日志页按 id 渲染 key,撞号会破坏受控场景里「跨重载保持」的补丁数据
+ id: `LOG-${now.getTime().toString(36).toUpperCase()}-${(logSeq++).toString(36).toUpperCase()}-${Math.random()
+ .toString(36)
+ .slice(2, 6)
+ .toUpperCase()}`,
actorId: ctx.session?.user?.id ?? '',
actorName: ctx.session?.user?.name ?? ctx.session?.username ?? '',
action,
@@ -270,7 +275,8 @@ const USER_WRITE_KEYS = ['name', 'username', 'email', 'department', 'status'] as
const pickUserInput = (ctx: RouteContext, body: Record) => {
const input: Partial = {};
USER_WRITE_KEYS.forEach((key) => {
- if (body[key] !== undefined) (input as Record)[key] = body[key];
+ // null 不在「未传」语义里:曾绕过校验(String(null)='null' 过正则)后经 store 落成字段删除
+ if (body[key] !== undefined && body[key] !== null) (input as Record)[key] = body[key];
});
if (typeof input.username === 'string') input.username = input.username.trim().toLowerCase();
if (typeof input.name === 'string') input.name = input.name.trim();
@@ -519,6 +525,8 @@ export const routes: Route[] = [
handle: (ctx) => {
const ids = Array.isArray(ctx.body.ids) ? (ctx.body.ids as string[]) : [];
const action = ctx.body.action as UserBatchAction;
+ // 枚举先行:任意值曾被 `as` 直通,'banana' 之类会静默把整批用户禁用并写出无 action 的日志
+ if (!BATCH_LOG_ACTION[action]) failWith(ctx, 400, 'actionInvalid');
if (action === 'delete') requirePermission(ctx, 'system.user.delete');
const users = ids.map((id) => findUser(ctx, id));
// 整批判定、先于任何写入:混入一个 admin / lead 账号整批 403,不会先处理前面的普通账号(启用同样算)
@@ -752,6 +760,10 @@ export const routes: Route[] = [
const alarm = data(ctx).alarms.find((a) => a.id === ctx.params.id) ?? notFound(ctx);
if (alarm.status !== 'active') fail(ctx, 'alarmClosed');
const action = ctx.body.action as AlarmHandleAction;
+ // 枚举校验:未知值曾被 else 分支一律按「误报」关单并写 misleading 日志
+ if (action !== 'ticket' && action !== 'recover' && action !== 'falsePositive') {
+ failWith(ctx, 400, 'actionInvalid');
+ }
const now = nowIso(ctx);
if (action === 'ticket') {
const device = data(ctx).devices.find((d) => d.id === alarm.deviceId)!;
@@ -924,9 +936,34 @@ export const routes: Route[] = [
handle: (ctx) => {
const event = data(ctx).events.find((e) => e.id === ctx.params.id) ?? notFound(ctx);
const changes: Partial = {};
- (['title', 'type', 'start', 'end', 'allDay'] as const).forEach((key) => {
- if (key in ctx.body) (changes as Record)[key] = ctx.body[key] ?? undefined;
- });
+ const body = ctx.body;
+ const hasValue = (value: unknown): value is NonNullable => value !== undefined && value !== null;
+ // 部分更新复用 POST 的校验口径(修复前 PUT 直通:{title:null} 删标题、'garbage' 也能当日期)。
+ // title/type/start 不可清空:出现即必须是合法值;end 允许显式清空(去掉结束时间)。
+ if ('title' in body) {
+ const { title } = body;
+ if (typeof title !== 'string' || !title.trim()) fail(ctx, 'titleRequired');
+ changes.title = (title as string).trim();
+ }
+ if ('type' in body && hasValue(body.type)) {
+ if (!EVENT_TYPES.includes(body.type as EventType)) fail(ctx, 'notFound');
+ changes.type = body.type as EventType;
+ }
+ if ('start' in body && hasValue(body.start)) {
+ if (Number.isNaN(new Date(String(body.start)).getTime())) fail(ctx, 'notFound');
+ changes.start = String(body.start);
+ }
+ if ('end' in body && hasValue(body.end)) {
+ if (Number.isNaN(new Date(String(body.end)).getTime())) fail(ctx, 'notFound');
+ changes.end = String(body.end);
+ } else if ('end' in body) {
+ changes.end = undefined;
+ }
+ if ('allDay' in body && hasValue(body.allDay)) changes.allDay = !!body.allDay;
+ const effectiveStart = changes.start !== undefined ? new Date(changes.start) : new Date(event.start);
+ const effectiveEnd =
+ changes.end !== undefined ? new Date(changes.end) : event.end ? new Date(event.end) : undefined;
+ if (effectiveEnd && effectiveStart.getTime() > effectiveEnd.getTime()) fail(ctx, 'notFound');
const updated = ctx.store.update('events', event.id, changes);
writeLog(ctx, 'scheduleUpdate', event.id);
return updated;
diff --git a/src/demo/server/server.test.ts b/src/demo/server/server.test.ts
index 21cf4656..8a698ec0 100644
--- a/src/demo/server/server.test.ts
+++ b/src/demo/server/server.test.ts
@@ -219,6 +219,21 @@ describe('工单与告警', () => {
const again = call('POST', `/api/v1/alarms/${alarm.id}/handle`, { token, body: { action: 'recover' } });
expect(again.body.success).toBe(false);
});
+
+ it('未知的处置/批量动作返回 400,不再静默按误报/停用处理', () => {
+ const token = loginAs('admin');
+ const alarm = server.store.dataset.alarms.find((a) => a.status === 'active')!;
+ // 修复前:未知 action 走 else 分支,一律按误报关单并写日志
+ const bad = call('POST', `/api/v1/alarms/${alarm.id}/handle`, { token, body: { action: 'banana' } });
+ expect(bad.status).toBe(400);
+ expect(server.store.dataset.alarms.find((a) => a.id === alarm.id)).toMatchObject({ status: 'active' });
+
+ const target = server.store.dataset.users.find((u) => u.username === 'guest')!;
+ // 修复前:未知批量 action 会把整批用户 disable
+ const batch = call('POST', '/api/v1/users/batch', { token, body: { ids: [target.id], action: 'banana' } });
+ expect(batch.status).toBe(400);
+ expect(server.store.dataset.users.find((u) => u.id === target.id)).toMatchObject({ status: 'active' });
+ });
});
describe('演示数据存储', () => {
diff --git a/src/demo/store.ts b/src/demo/store.ts
index 5878f6c6..28935976 100644
--- a/src/demo/store.ts
+++ b/src/demo/store.ts
@@ -44,8 +44,12 @@ const emptyPatch = (): CollectionPatch => ({ created: [], updated: {}, deleted:
* 字段为 undefined 表示「清除该字段」(如工单退回处理中要清掉完成时间)。
* JSON 会丢掉 undefined,所以补丁里记成 null,应用补丁时 null 同样视为删除。
*/
+const UNSAFE_PATCH_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
const applyChanges = (target: Record, changes: Record) => {
Object.entries(changes).forEach(([key, value]) => {
+ // JSON.parse 会把 "__proto__" 造成自有属性,Object.entries 能枚举到;
+ // 赋值则走 Object.prototype 的 setter 直接改写记录原型(持久化补丁不可信时的原型污染)
+ if (UNSAFE_PATCH_KEYS.has(key)) return;
if (value === undefined || value === null) {
delete target[key];
} else {
diff --git a/src/layouts/RightContent.tsx b/src/layouts/RightContent.tsx
index a47b5e9c..35b54e68 100644
--- a/src/layouts/RightContent.tsx
+++ b/src/layouts/RightContent.tsx
@@ -7,6 +7,7 @@ import { logout } from '@/services/auth';
import { getDemoClock, resetDemoData, switchDemoScenario } from '@/services/system';
import { avatarColor, avatarText } from '@/utils/avatar';
import { formatDateTime } from '@/utils/format';
+import { isMac } from '@/utils/platform';
import {
DownOutlined,
FieldTimeOutlined,
@@ -148,7 +149,7 @@ const RightContent = () => {
{ mode: t(dark ? 'header.themeLight' : 'header.themeDark') },
);
// ⌘K / Ctrl+K 随平台显示(与命令面板内部判定同一口径)
- const searchLabel = `${t('header.search')} (${/Mac|iPhone|iPad/.test(navigator.platform) ? '⌘K' : 'Ctrl+K'})`;
+ const searchLabel = `${t('header.search')} (${isMac() ? '⌘K' : 'Ctrl+K'})`;
return (
// backgroundColor 内联写死:ProLayout 会给 actions 容器的这个直接子元素刷一层淡底(hover 时
diff --git a/src/pages/Components/Calendar/index.tsx b/src/pages/Components/Calendar/index.tsx
index 7448f340..9bfe373e 100644
--- a/src/pages/Components/Calendar/index.tsx
+++ b/src/pages/Components/Calendar/index.tsx
@@ -182,7 +182,13 @@ export default function Calendar() {
refetch();
};
- /** 拖动 / 拉伸改期:写回接口,失败则还原 */
+ // validateFields 对「标题为空」的拒绝会以字段错误形式展示:onPressEnter / onOk 直接挂
+ // 原函数会把该拒绝变成 unhandled rejection(弹窗保持打开是期望行为,吞掉即可)
+ const handleCreateSafe = () => {
+ void handleCreate().catch(() => undefined);
+ };
+
+ /** 拖动 / 拉伸改期:写回接口,失败则还原;成功后 refetch(「接下来」侧栏此前一直滞留旧时段) */
const handleChange = async ({ event, revert }: EventChangeInfo) => {
try {
await updateEvent(event.id, {
@@ -191,6 +197,7 @@ export default function Calendar() {
allDay: event.allDay,
});
message.success(t('calendar.saved'));
+ refetch();
} catch {
revert();
}
@@ -205,6 +212,13 @@ export default function Calendar() {
viewing.remove();
setViewing(undefined);
message.success(t('common.deleted'));
+ // 侧栏「接下来」此前不随删除刷新,被删日程一直挂到下一次新建
+ refetch();
+ };
+
+ // Popconfirm 的 onConfirm 也会丢弃返回的 promise(antd v6 无加载契约):失败就地吞掉
+ const handleDeleteSafe = () => {
+ void handleDelete().catch(() => undefined);
};
return (
@@ -315,7 +329,7 @@ export default function Calendar() {
key="delete"
title={t('calendar.deleteConfirm', { title: viewing?.title ?? '' })}
okButtonProps={{ danger: true }}
- onConfirm={handleDelete}
+ onConfirm={handleDeleteSafe}
>
{t('common.delete')}
,
@@ -337,13 +351,13 @@ export default function Calendar() {
setDraft(undefined)}
destroyOnHidden
>
-
+
diff --git a/src/pages/Components/RichText/index.tsx b/src/pages/Components/RichText/index.tsx
index 0c06332c..e62e3671 100644
--- a/src/pages/Components/RichText/index.tsx
+++ b/src/pages/Components/RichText/index.tsx
@@ -6,7 +6,7 @@ import { getDashboardOverview } from '@/services/ops';
import { EyeOutlined } from '@ant-design/icons';
import { Editor } from '@tinymce/tinymce-react';
import { useIntl } from '@umijs/max';
-import { Button, Card, Skeleton, Typography } from 'antd';
+import { Button, Card, Result, Skeleton, Typography } from 'antd';
import DOMPurify from 'dompurify';
import { useRef, useState } from 'react';
import type { Editor as TinyMCEEditor } from 'tinymce';
@@ -32,7 +32,7 @@ export default function RichText() {
const { dark } = useChartTheme();
const editorRef = useRef(null);
const [preview, setPreview] = useState('');
- const { data } = useApi(loadDraft);
+ const { data, error, loading, reload } = useApi(loadDraft);
// 皮肤只能在初始化时指定:切换主题时按 key 重建编辑器。重建前(本次渲染、旧编辑器尚未卸载)
// 直接从旧实例取最新内容作为新编辑器的初始值——不依赖 change/keyup 事件是否已触发
@@ -64,31 +64,44 @@ export default function RichText() {
}
>
-
- (editorRef.current = editor)}
- initialValue={draftRef.current}
- init={{
- height: 560,
- menubar: false,
- // 界面语言跟随 umi locale:zh-CN 语言包已在 tinymceBundle.ts 注册(addI18n),en 为内置默认
- language: intl.locale === 'zh-CN' ? 'zh-CN' : 'en',
- skin: dark ? 'oxide-dark' : 'oxide',
- content_css: dark ? 'dark' : 'default',
- plugins: ['advlist', 'autolink', 'lists', 'link', 'table', 'charmap', 'searchreplace', 'wordcount'],
- toolbar:
- 'undo redo | blocks | bold italic forecolor | alignleft aligncenter alignright | ' +
- 'bullist numlist outdent indent | table link | removeformat',
- // 段落格式下拉的显示名以项目文案为准(语言包只覆盖控件文字)
- block_formats: t('richText.blockFormats'),
- // 正文限宽居中,像一页文档:满宽的长行不好读
- content_style:
- 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; font-size: 14px; line-height: 1.7; max-width: 800px; margin: 16px auto; padding: 0 16px }',
- }}
+ {/* 周报数据拉取失败给失败态与重试:否则骨架会永久转圈(data 永不到位,初稿永远不生成) */}
+ {error ? (
+
+ {t('common.retry')}
+
+ }
/>
-
+ ) : (
+
+ (editorRef.current = editor)}
+ initialValue={draftRef.current}
+ init={{
+ height: 560,
+ menubar: false,
+ // 界面语言跟随 umi locale:zh-CN 语言包已在 tinymceBundle.ts 注册(addI18n),en 为内置默认
+ language: intl.locale === 'zh-CN' ? 'zh-CN' : 'en',
+ skin: dark ? 'oxide-dark' : 'oxide',
+ content_css: dark ? 'dark' : 'default',
+ plugins: ['advlist', 'autolink', 'lists', 'link', 'table', 'charmap', 'searchreplace', 'wordcount'],
+ toolbar:
+ 'undo redo | blocks | bold italic forecolor | alignleft aligncenter alignright | ' +
+ 'bullist numlist outdent indent | table link | removeformat',
+ // 段落格式下拉的显示名以项目文案为准(语言包只覆盖控件文字)
+ block_formats: t('richText.blockFormats'),
+ // 正文限宽居中,像一页文档:满宽的长行不好读
+ content_style:
+ 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; font-size: 14px; line-height: 1.7; max-width: 800px; margin: 16px auto; padding: 0 16px }',
+ }}
+ />
+
+ )}
{preview && (
diff --git a/src/pages/Components/Screenshot/index.tsx b/src/pages/Components/Screenshot/index.tsx
index 93fed928..71ee7fa3 100644
--- a/src/pages/Components/Screenshot/index.tsx
+++ b/src/pages/Components/Screenshot/index.tsx
@@ -8,7 +8,21 @@ import type { Device } from '@/services/types';
import { formatDateTime } from '@/utils/format';
import { CameraOutlined, DownloadOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
-import { App, Button, Card, Descriptions, Image, Modal, Select, Skeleton, Space, Tag, Typography } from 'antd';
+import {
+ App,
+ Button,
+ Card,
+ Descriptions,
+ Empty,
+ Image,
+ Modal,
+ Result,
+ Select,
+ Skeleton,
+ Space,
+ Tag,
+ Typography,
+} from 'antd';
import html2canvas from 'html2canvas';
import { useRef, useState } from 'react';
@@ -24,6 +38,8 @@ const loadCard = async (deviceId?: string) => {
}
const { list } = await listAlarms({ level: 'critical', pageSize: 1 });
const alarm = list[0] ?? (await listAlarms({ pageSize: 1 })).list[0];
+ // 全库无告警时不再解引用 alarm.deviceId(此前在 useApi 里抛错,页面卡死在骨架屏)
+ if (!alarm) return { alarm: undefined, device: undefined };
const device = await getDevice(alarm.deviceId);
return { alarm, device };
};
@@ -39,7 +55,7 @@ export default function Screenshot() {
// 截图对象可选(E07:主线演示时选「演示 · 主线故障站」);默认继承最近严重告警的设备
const [deviceId, setDeviceId] = useState();
const { data: devices } = useApi(() => listAllDevices().then((list) => list.slice(0, 300)));
- const { data, loading } = useApi(() => loadCard(deviceId), [deviceId]);
+ const { data, loading, error, reload } = useApi(() => loadCard(deviceId), [deviceId]);
const deviceOptions = (devices ?? []).map((device: Device) => ({
value: device.id,
label: `${device.name} · ${device.id}`,
@@ -69,11 +85,11 @@ export default function Screenshot() {
if (!url) return;
const link = document.createElement('a');
link.href = url;
- link.download = `${data?.alarm.id ?? 'screenshot'}.png`;
+ link.download = `${data?.alarm?.id ?? 'screenshot'}.png`;
link.click();
};
- const recent = data?.device.recentAlarms ?? [];
+ const recent = data?.device?.recentAlarms ?? [];
return (
{intl.formatMessage({ id: `alarmLevel.${data.alarm.level}` })}
)
}
>
-
- {data && (
+ {/* 失败态优先于「无告警」空态:否则拉取失败会被误读成没有告警(骨架在 error 时也不再无限转) */}
+
+ {error ? (
+
+ {t('common.retry')}
+
+ }
+ />
+ ) : data?.alarm ? (
<>
{/* 类型是主信息(大号),告警编号是辅助信息(小号灰字),不再与标题、级别标签挤在卡片头 */}
@@ -172,6 +199,8 @@ export default function Screenshot() {
)}
>
+ ) : (
+ !loading &&
)}
diff --git a/src/pages/Components/Signature/index.tsx b/src/pages/Components/Signature/index.tsx
index e55ea98c..ed7c3c7a 100644
--- a/src/pages/Components/Signature/index.tsx
+++ b/src/pages/Components/Signature/index.tsx
@@ -84,7 +84,7 @@ export default function Signature() {
const [signedCount, setSignedCount] = useState(0);
const [saving, setSaving] = useState(false);
const [empty, setEmpty] = useState(true);
- const { data: pending, loading, reload } = useApi(loadPending);
+ const { data: pending, loading, error, reload } = useApi(loadPending);
const ticket = pending?.find((item) => item.id === ticketId);
useEffect(() => {
@@ -203,8 +203,19 @@ export default function Signature() {
- {/* 有候选才渲染选择器;签完最后一张(pending 清空)落到 allDone 完成空态(复查 P2-1) */}
- {pending?.length ? (
+ {/* 失败态优先于空态:否则拉取失败会显示「无待签工单」,操作员会误判无事可签 */}
+ {error ? (
+
+ {t('common.retry')}
+
+ }
+ />
+ ) : /* 有候选才渲染选择器;签完最后一张(pending 清空)落到 allDone 完成空态(复查 P2-1) */
+ pending?.length ? (
<>
diff --git a/src/pages/Dashboard/components/RegionOnline.tsx b/src/pages/Dashboard/components/RegionOnline.tsx
index a5062cd3..e6616c9d 100644
--- a/src/pages/Dashboard/components/RegionOnline.tsx
+++ b/src/pages/Dashboard/components/RegionOnline.tsx
@@ -10,7 +10,8 @@ export default function RegionOnline({ data, height }: { data: DashboardOverview
const rows = data
.map((row) => ({
region: intl.formatMessage({ id: `region.${row.region}` }),
- rate: Math.round((row.online / row.total) * 1000) / 10,
+ // total 为 0 的大区此前会算出 NaN%(NaN 还会污染按 rate 的排序):按 0 处理
+ rate: row.total ? Math.round((row.online / row.total) * 1000) / 10 : 0,
detail: intl.formatMessage({ id: 'dashboard.regions.online' }, { online: row.online, total: row.total }),
}))
.sort((a, b) => b.rate - a.rate);
diff --git a/src/pages/Document/Pdf/pdfPreflight.test.ts b/src/pages/Document/Pdf/pdfPreflight.test.ts
index 6e34f223..64318887 100644
--- a/src/pages/Document/Pdf/pdfPreflight.test.ts
+++ b/src/pages/Document/Pdf/pdfPreflight.test.ts
@@ -183,6 +183,25 @@ describe('解码放大预算', () => {
expect(report.stats.estimatedFilterStreams).toBe(1);
expect(report.violations[0].code).toBe('decodedBytes');
});
+
+ it('Flate 首层后再挂放大层(双层 Flate)也保守估算,不绕过预算', HEAVY, () => {
+ // /Filter [/FlateDecode /FlateDecode]:我们只能解出第一层的字节数,第二层 Flate 的
+ // 展开无从计量——修复前这里按 kind:'flate' 计账,双层 Flate 炸弹可绕过解码预算。
+ const payload = incompressible(3 * 1024 * 1024);
+ const report = preflightPdf(flateContentPdf(payload, '/Filter [/FlateDecode /FlateDecode]'));
+ expect(report.ok).toBe(false);
+ expect(report.stats.estimatedFilterStreams).toBe(1);
+ expect(report.violations[0].code).toBe('decodedBytes');
+ });
+
+ it('Flate 首层后是缩小编码时仍按真实解码计数(不过度拒绝)', HEAVY, () => {
+ const report = preflightPdf(
+ flateContentPdf(new Uint8Array(2 * 1024 * 1024), '/Filter [/FlateDecode /ASCIIHexDecode]'),
+ );
+ expect(report.ok).toBe(true);
+ expect(report.stats.decodedStreamBytes).toBe(2 * 1024 * 1024);
+ expect(report.stats.estimatedFilterStreams).toBe(0);
+ });
});
describe('页树放大预算', () => {
diff --git a/src/pages/Document/Pdf/pdfPreflight.ts b/src/pages/Document/Pdf/pdfPreflight.ts
index dc06b6b7..e7d25797 100644
--- a/src/pages/Document/Pdf/pdfPreflight.ts
+++ b/src/pages/Document/Pdf/pdfPreflight.ts
@@ -1258,8 +1258,15 @@ class Preflight {
}
if (names.length === 0) return { kind: 'plain', estimated: raw };
const [firstDecoder] = names;
- if (FLATE_FILTERS.has(firstDecoder)) return { kind: 'flate' };
const amplifying = (name: string) => !NON_AMPLIFYING.has(name) && !IMAGE_CODERS.has(name);
+ if (FLATE_FILTERS.has(firstDecoder)) {
+ // [/FlateDecode /FlateDecode] 这类链:第一层我们只解出其输出字节数,其后若还有
+ // 放大层(第二个 Flate、LZW、RunLength…),其展开无法计量——与缩小编码分支同口径,
+ // 按倍数保守估算,宁可多算不可漏计(曾只看 firstDecoder,双层 Flate 可绕过预算)。
+ return names.slice(1).some(amplifying)
+ ? { kind: 'amplifying', estimated: raw * this.budgets.unknownFilterAmplification }
+ : { kind: 'flate' };
+ }
if (IMAGE_CODERS.has(firstDecoder)) return { kind: 'plain', estimated: raw };
if (NON_AMPLIFYING.has(firstDecoder)) {
// 盔甲/缩小编码本身不放大;只有其后确实还有放大层时才保守估算,
diff --git a/src/pages/Map/Amap/index.tsx b/src/pages/Map/Amap/index.tsx
index 03ef7caf..372fb842 100644
--- a/src/pages/Map/Amap/index.tsx
+++ b/src/pages/Map/Amap/index.tsx
@@ -43,6 +43,17 @@ export default function Amap() {
const mapRef = useRef(undefined);
const markersRef = useRef<{ device: Device; marker: AMap.CircleMarker }[]>([]);
const [filter, setFilter] = useState('all');
+ // 地图(含 marker)是异步重建的:重建后必须重放当前过滤,并把 filter effect 的依赖指向
+ // 新一代 marker(否则暗色切换重建地图后,已有的状态过滤被静默丢弃)
+ const [mapEpoch, setMapEpoch] = useState(0);
+ const filterRef = useRef(filter);
+ filterRef.current = filter;
+ const applyFilter = () => {
+ const current = filterRef.current;
+ markersRef.current.forEach(({ device, marker }) =>
+ current === 'all' || device.status === current ? marker.show() : marker.hide(),
+ );
+ };
const [loadError, setLoadError] = useState();
const [selected, setSelected] = useState();
const infoWindowRef = useRef(undefined);
@@ -97,6 +108,9 @@ export default function Amap() {
map.add(marker);
return { device, marker };
});
+ // marker 是异步创建的:filter effect 首轮跑在它之前,这里补一次当前过滤的落地
+ applyFilter();
+ setMapEpoch((n) => n + 1);
})
.catch((error: unknown) => !disposed && setLoadError(error instanceof Error ? error.message : String(error)));
return () => {
@@ -118,7 +132,7 @@ export default function Amap() {
markersRef.current.forEach(({ device, marker }) =>
filter === 'all' || device.status === filter ? marker.show() : marker.hide(),
);
- }, [filter, devices]);
+ }, [filter, mapEpoch]);
return (
(undefined);
const devicesRef = useRef([]);
+ // 提交图形层(start/clear 会整层清空)与预览实体分离:橡皮筋/预览边/圆预览/测量线
+ // 若与提交图形同层,首次 start() 的 removeAll() 就会把它们移出可视化管线,之后
+ // show=true 全部作用在已脱管实体上——四种实时预览静默失效
const layerRef = useRef(null);
+ const previewsRef = useRef([]);
const highlightRef = useRef(null);
// 各工具的进行时状态(不进 React state,避免每帧渲染)
const boxDragRef = useRef<{ start?: [number, number]; current?: [number, number] }>({});
@@ -63,8 +67,13 @@ export default function BoxSelect() {
const measureRef = useRef<[number, number][]>([]);
devicesRef.current = devices ?? [];
toolRef.current = tool;
+ // fmtLen 被 onReady 里的 CallbackProperty/标签闭包长期持有,直接读 state 会冻结在首次渲染的
+ // 单位上(切 km→nmi 后侧板变了、圆半径与量测标签不变):走 ref 取当前值
+ const unitsRef = useRef(units);
+ unitsRef.current = units;
- const fmtLen = (km: number) => (units === 'km' ? `${km.toFixed(1)} km` : `${(km * NMI_PER_KM).toFixed(1)} nmi`);
+ const fmtLen = (km: number) =>
+ unitsRef.current === 'km' ? `${km.toFixed(1)} km` : `${(km * NMI_PER_KM).toFixed(1)} nmi`;
const { containerRef, viewer, error, basemapFailed, retry } = useCesiumViewer({
home: [108, 35, 4_600_000],
@@ -73,13 +82,16 @@ export default function BoxSelect() {
const layer = new Cesium.CustomDataSource('select');
instance.dataSources.add(layer);
layerRef.current = layer;
+ // 预览实体专层:从不清空,仅靠 show 开关(见上方 previewsRef 注释)
+ const previewLayer = new Cesium.CustomDataSource('select-preview');
+ instance.dataSources.add(previewLayer);
const cursor = (next?: Tool) => {
(instance.container as HTMLElement).style.cursor = next ? 'crosshair' : '';
};
/* 矩形:按住拖拽(LEFT_DOWN 起点、MOUSE_MOVE 橡皮筋、LEFT_UP 定选) */
- const rubberBand = layer.entities.add({
+ const rubberBand = previewLayer.entities.add({
rectangle: {
coordinates: new Cesium.CallbackProperty(() => {
const { start, current } = boxDragRef.current;
@@ -100,7 +112,7 @@ export default function BoxSelect() {
/* 多边形:点击加点 + 指向光标的预览边;双击收口(光标点存闭包变量,每帧变不值 setState) */
let polygonCursor: [number, number] | undefined;
- const previewLine = layer.entities.add({
+ const previewLine = previewLayer.entities.add({
polyline: {
positions: new Cesium.CallbackProperty(() => {
const points = polygonRef.current;
@@ -122,7 +134,7 @@ export default function BoxSelect() {
const { center, edge } = circleRef.current;
return center && edge ? distanceKm(center, edge) : 0;
};
- const circlePreview = layer.entities.add({
+ const circlePreview = previewLayer.entities.add({
ellipse: {
semiMajorAxis: new Cesium.CallbackProperty(() => circleRadiusKm() * 1000, false),
semiMinorAxis: new Cesium.CallbackProperty(() => circleRadiusKm() * 1000, false),
@@ -146,7 +158,7 @@ export default function BoxSelect() {
circlePreview.show = false;
/* 量测:多段折线 + 逐段标注 + 累计 */
- const measureLine = layer.entities.add({
+ const measureLine = previewLayer.entities.add({
polyline: {
positions: new Cesium.CallbackProperty(() => {
const seq = measureRef.current.flatMap((p) => [p[0], p[1]]);
@@ -158,6 +170,7 @@ export default function BoxSelect() {
},
});
measureLine.show = false;
+ previewsRef.current = [rubberBand, previewLine, circlePreview, measureLine];
const finishMeasure = () => {
const points = measureRef.current;
@@ -310,7 +323,11 @@ export default function BoxSelect() {
return () => {
handler.destroy();
polygonCursor = undefined;
- if (!instance.isDestroyed()) instance.dataSources.remove(layer, true);
+ previewsRef.current = [];
+ if (!instance.isDestroyed()) {
+ instance.dataSources.remove(previewLayer, true);
+ instance.dataSources.remove(layer, true);
+ }
};
},
});
@@ -337,27 +354,29 @@ export default function BoxSelect() {
});
}, [viewer, hoverDevice]);
- const start = (next: Tool) => {
+ // 只清提交图形层;预览实体在专层上常驻,随工具状态重置一并隐藏
+ const resetShapes = () => {
layerRef.current?.entities.removeAll();
+ previewsRef.current.forEach((entity) => {
+ entity.show = false;
+ });
boxDragRef.current = {};
polygonRef.current = [];
circleRef.current = {};
measureRef.current = [];
setSelected(undefined);
setMeasureTotal(undefined);
+ };
+
+ const start = (next: Tool) => {
+ resetShapes();
setTool(next);
// viewer 未就绪(首帧、底图重试换实例的空窗)时只切工具状态,不碰光标
if (viewer) (viewer.container as HTMLElement).style.cursor = 'crosshair';
};
const clear = () => {
- layerRef.current?.entities.removeAll();
- boxDragRef.current = {};
- polygonRef.current = [];
- circleRef.current = {};
- measureRef.current = [];
- setSelected(undefined);
- setMeasureTotal(undefined);
+ resetShapes();
setTool(undefined);
if (viewer) (viewer.container as HTMLElement).style.cursor = '';
};
diff --git a/src/pages/Map/Cesium/Direction.tsx b/src/pages/Map/Cesium/Direction.tsx
index 787da045..19a8652b 100644
--- a/src/pages/Map/Cesium/Direction.tsx
+++ b/src/pages/Map/Cesium/Direction.tsx
@@ -261,7 +261,7 @@ export default function Direction() {
return () => {
if (!viewer.isDestroyed()) viewer.clock.onTick.removeEventListener(onTick);
};
- // eslint-disable-next-line react-hooks/exhaustive-deps
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- epoch 挂载时冻结进 ref、TARGETS 为模块常量;省略的只有 t(整页重载稳定)
}, [viewer]);
// 模式切换:覆盖带与波束各自显隐
@@ -272,6 +272,16 @@ export default function Direction() {
if (sweepRef.current) sweepRef.current.show = mode !== 'bands';
}, [mode, viewer]);
+ // TimeDeck 播放/暂停与倍速必须同步到 viewer.clock(与 Heatmap/Trajectory/Situation 同一模式);
+ // 此前只在 onReady 里设过一次,导致播放控制与 ×1/×4/×16 按钮完全失效
+ useEffect(() => {
+ if (viewer && !viewer.isDestroyed()) viewer.clock.shouldAnimate = playing;
+ }, [viewer, playing]);
+
+ useEffect(() => {
+ if (viewer && !viewer.isDestroyed()) viewer.clock.multiplier = speed;
+ }, [viewer, speed]);
+
const stats = useMemo(() => CAPABILITIES.map((capability) => ({ capability, ...capabilityStats(capability) })), []);
const interceptStats = stats.find((row) => row.capability === 'intercept');
const radarData = useMemo(
@@ -284,7 +294,7 @@ export default function Direction() {
rangeKm: p.rangeKm,
})),
),
- // eslint-disable-next-line react-hooks/exhaustive-deps
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- polarPattern/CAPABILITIES 为纯模块函数;唯一捕获 t,切语言整页重载
[],
);
diff --git a/src/pages/Map/Cesium/GeoHash.tsx b/src/pages/Map/Cesium/GeoHash.tsx
index f08233a0..a41b3826 100644
--- a/src/pages/Map/Cesium/GeoHash.tsx
+++ b/src/pages/Map/Cesium/GeoHash.tsx
@@ -36,6 +36,7 @@ export default function GeoHashPage() {
const [hovered, setHovered] = useState();
const [tilted, setTilted] = useState(false);
const layerRef = useRef(null);
+ const highlightRef = useRef(null);
const pointsRef = useRef(null);
const freezeTimerRef = useRef(undefined);
const fleet = useMemo(() => buildStationFleet(8000), []);
@@ -56,10 +57,23 @@ export default function GeoHashPage() {
// handler 只在 onReady 建一次,必须用回调参数 instance:闭包里的 state viewer 首帧是 null,
// 底图重试后则是已销毁的旧实例
const handler = new Cesium.ScreenSpaceEventHandler(instance.scene.canvas);
+ // scene.pick 是一次完整的 pick 渲染 pass,而 MOUSE_MOVE 频率高于帧率——rAF 合帧,每帧最多 pick 一次
+ //(同 CesiumViewer HUD 的做法);缓存最新落点,帧回调里统一消费
+ let pickQueued: Cesium.Cartesian2 | undefined;
+ let pickRaf: number | undefined;
handler.setInputAction((movement: { endPosition: Cesium.Cartesian2 }) => {
- const picked = instance.scene.pick(movement.endPosition);
- const cell = picked?.id?.properties?.cell?.getValue(Cesium.JulianDate.now());
- setHovered(cell ?? undefined);
+ pickQueued = movement.endPosition;
+ if (pickRaf === undefined) {
+ pickRaf = window.requestAnimationFrame(() => {
+ pickRaf = undefined;
+ const position = pickQueued;
+ pickQueued = undefined;
+ if (!position || instance.isDestroyed()) return;
+ const picked = instance.scene.pick(position);
+ const cell = picked?.id?.properties?.cell?.getValue(Cesium.JulianDate.now());
+ setHovered(cell ?? undefined);
+ });
+ }
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
handler.setInputAction((click: { position: Cesium.Cartesian2 }) => {
const picked = instance.scene.pick(click.position);
@@ -77,7 +91,10 @@ export default function GeoHashPage() {
});
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
- return () => handler.destroy();
+ return () => {
+ if (pickRaf !== undefined) window.cancelAnimationFrame(pickRaf);
+ handler.destroy();
+ };
},
});
@@ -106,9 +123,9 @@ export default function GeoHashPage() {
/* 聚合:按精度编码 → 计数 → 色带格柱(带生长动画,动画结束后冻结为常量高度) */
useEffect(() => {
const layer = layerRef.current;
- if (!viewer || !layer || stations.length === 0) return;
+ if (!viewer || !layer || stations.length === 0) return undefined;
layer.entities.removeAll();
- window.clearTimeout(freezeTimerRef.current);
+ highlightRef.current = null;
const counts = new Map();
stations.forEach((s) => {
const hash = centerGeoHash(s.lat, s.lng, precision);
@@ -135,7 +152,11 @@ export default function GeoHashPage() {
const growStart = performance.now();
const entityHeights: [Cesium.Entity, number][] = [];
- list.forEach((cell, i) => {
+ // 精度 5 × 8000 站会产出 5–7k 格:实体(各自走异步三角化队列)封顶在几百格的量级,
+ // 按计数降序取前 N 渲染;直方图 / Top 列表 / KPI 仍用完整统计。标签同理只挂在大格上
+ const RENDER_CAP = 800;
+ const LABEL_RATIO = 0.1;
+ list.slice(0, RENDER_CAP).forEach((cell, i) => {
const b = geohashBounds(cell.hash);
if (!b) return;
const target = cellHeight(cell.ratio);
@@ -153,12 +174,15 @@ export default function GeoHashPage() {
outlineColor: Cesium.Color.WHITE.withAlpha(0.5),
},
position: Cesium.Cartesian3.fromDegrees(cell.center[0], cell.center[1], target),
- label: {
- ...tagLabel({ font: '11px ui-monospace, Menlo, monospace' }),
- text: `${cell.count}`,
- showBackground: cell.ratio > 0.5,
- disableDepthTestDistance: Number.POSITIVE_INFINITY,
- },
+ label:
+ cell.ratio >= LABEL_RATIO
+ ? {
+ ...tagLabel({ font: '11px ui-monospace, Menlo, monospace' }),
+ text: `${cell.count}`,
+ showBackground: cell.ratio > 0.5,
+ disableDepthTestDistance: Number.POSITIVE_INFINITY,
+ }
+ : undefined,
properties: { cell },
});
entityHeights.push([entity, target]);
@@ -170,6 +194,8 @@ export default function GeoHashPage() {
});
}, 1900);
setCells(list);
+ // 卸载 / 换参时取消冻结定时器:1.9s 后 viewer 可能已销毁,别再碰它的实体
+ return () => window.clearTimeout(freezeTimerRef.current);
}, [viewer, stations, precision]);
/** 俯视 ↔ 侧视:侧视才能看出挤出高度的数据差异,这是这页的「定妆镜头」 */
@@ -199,7 +225,9 @@ export default function GeoHashPage() {
const hash = centerGeoHash(lat, lng, precision);
const b = geohashBounds(hash);
if (b) {
- layerRef.current.entities.add({
+ // 中心高亮只保留最近一个:连续点按旧实体不移除会无限累积
+ if (highlightRef.current) layerRef.current.entities.remove(highlightRef.current);
+ highlightRef.current = layerRef.current.entities.add({
rectangle: {
coordinates: Cesium.Rectangle.fromDegrees(b.longitudeMin, b.latitudeMin, b.longitudeMax, b.latitudeMax),
material: cesiumColor('#fa8c16', 0.5),
@@ -213,6 +241,7 @@ export default function GeoHashPage() {
const clear = () => {
layerRef.current?.entities.removeAll();
+ highlightRef.current = null;
setCells([]);
setHovered(undefined);
};
@@ -221,7 +250,9 @@ export default function GeoHashPage() {
const histogram = useMemo(() => {
if (cells.length === 0) return undefined;
const max = cells[0].count;
- const binOf = (count: number) => Math.min(9, Math.floor((Math.log10(count) / Math.log10(max || 1)) * 10));
+ // max === 1(所有格子 count=1)时分母 log10(1)=0 → NaN 档位:全部落第 0 档
+ const binOf = (count: number) =>
+ max <= 1 ? 0 : Math.min(9, Math.floor((Math.log10(count) / Math.log10(max)) * 10));
const bins = new Array(10).fill(0) as number[];
cells.forEach((cell) => {
bins[binOf(cell.count)] += 1;
@@ -258,7 +289,7 @@ export default function GeoHashPage() {
|