From edcf7bc7c0a13e385415c3fa7c6b620baeb59d9a Mon Sep 17 00:00:00 2001 From: AetherNo2332 <130164460+AetherNo2332@users.noreply.github.com> Date: Mon, 21 Sep 2026 06:19:07 +0800 Subject: [PATCH] =?UTF-8?q?fix(web):=20=E8=AF=8A=E6=96=AD=20-=20=E5=9C=A8?= =?UTF-8?q?=E6=B2=A1=E6=9C=89=20window.location=20=E7=9A=84=E7=8E=AF?= =?UTF-8?q?=E5=A2=83=E4=B8=8D=E5=86=8D=E6=8A=9B=E9=94=99=20(#559)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Original-Commit: cdb07ca9cbdd74e63d8e80659f3bdbd6d49b3dff fix(web): 诊断 - 在没有 window.location 的环境不再抛错 recordDiagnosticEvent / normalizeRoute 用 `typeof window !== "undefined"` 判断"在浏览器里", 但 bun 的测试环境里 window 存在、window.location 不存在,于是每次记录诊断事件都抛 `TypeError: undefined is not an object (evaluating 'window.location.pathname')`, director-diagnostics-recorder 的 9 条基线用例因此全红。 改成 browserLocation():window 与 window.location 都探测,取不到就当没有地址(路由回落 "/")。 浏览器内的行为完全不变。 --- web/src/services/diagnostics/client-diagnostics.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/web/src/services/diagnostics/client-diagnostics.ts b/web/src/services/diagnostics/client-diagnostics.ts index f4c37e0d0..8a71b35d1 100644 --- a/web/src/services/diagnostics/client-diagnostics.ts +++ b/web/src/services/diagnostics/client-diagnostics.ts @@ -124,7 +124,7 @@ export function recordDiagnosticEvent(input: DiagnosticEventInput) { category: input.category, code: redactClientText(input.code), message: redactClientText(input.message) || "未命名诊断事件", - route: normalizeRoute(input.route || (typeof window !== "undefined" ? window.location.pathname : "")), + route: normalizeRoute(input.route || browserLocation()?.pathname || ""), durationMs: input.durationMs === undefined ? undefined : clampNumber(input.durationMs, 0, 86_400_000), httpStatus: input.httpStatus === undefined ? undefined : clampNumber(input.httpStatus, 0, 599), requestId: safeDiagnosticId(input.requestId), @@ -177,11 +177,17 @@ function readHeader(headers: unknown, key: string) { return typeof value === "string" ? value : undefined; } +// 诊断只在真实浏览器里有地址。测试与 SSR 环境里 `window` 可能存在但 `window.location` 不存在 +// (bun test 就是这样),所以两个都要探测,不能只看 typeof window。 +function browserLocation(): Location | undefined { + return typeof window !== "undefined" && window.location ? window.location : undefined; +} + function normalizeRoute(value?: string) { const raw = String(value || "").trim(); - if (!raw) return typeof window !== "undefined" ? window.location.pathname : "/"; + if (!raw) return browserLocation()?.pathname || "/"; try { - const parsed = new URL(raw, typeof window !== "undefined" ? window.location.origin : "http://localhost"); + const parsed = new URL(raw, browserLocation()?.origin || "http://localhost"); return parsed.pathname || "/"; } catch { return raw.split(/[?#]/, 1)[0] || "/";