fix(web): 诊断 - 在没有 window.location 的环境不再抛错 (#559)

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 都探测,取不到就当没有地址(路由回落 "/")。
浏览器内的行为完全不变。
This commit is contained in:
AetherNo2332
2026-09-21 06:19:07 +08:00
committed by ddCat
parent 13d8f629bb
commit edcf7bc7c0

View File

@@ -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] || "/";