| 1 | |
| 2 | let windowStarted = 0; |
| 3 | let sent = 0; |
| 4 | const pending = []; |
| 5 | let sending = false; |
| 6 | let retryTimer; |
| 7 | async function flush() { |
| 8 | if (sending) return; |
| 9 | clearTimeout(retryTimer); |
| 10 | retryTimer = undefined; |
| 11 | sending = true; |
| 12 | try { |
| 13 | while (pending.length) { |
| 14 | const response = await fetch("/api/diagnostics/events", { |
| 15 | method: "POST", headers: { "Content-Type": "application/json" }, |
| 16 | body: JSON.stringify(pending[0]), |
| 17 | }); |
| 18 | if (!response.ok) break; |
| 19 | pending.shift(); |
| 20 | } |
| 21 | } catch { } |
| 22 | finally { |
| 23 | sending = false; |
| 24 | if (pending.length) { |
| 25 | retryTimer = setTimeout(flush, 5000); |
| 26 | retryTimer.unref?.(); |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | export function reportDiagnostic(source, error) { |
| 31 | const now = Date.now(); |
| 32 | if (now - windowStarted > 60_000) { windowStarted = now; sent = 0; } |
| 33 | if (sent >= 20 || pending.length >= 20) return; |
| 34 | sent++; |
| 35 | let message; |
| 36 | if (error instanceof Error) message = `${error.name}: ${error.message}\n${error.stack || ""}`; |
| 37 | else if (typeof error === "string") message = error; |
| 38 | else message = "异步操作发生异常,未收集原始对象"; |
| 39 | |
| 40 | pending.push({ source, level: "error", message: message.slice(0, 4096) }); |
| 41 | void flush(); |
| 42 | } |
| 43 | export function installDiagnostics(target = window) { |
| 44 | target.addEventListener("error", event => { |
| 45 | if (event.error) reportDiagnostic("frontend", event.error); |
| 46 | else reportDiagnostic("frontend", event.message || "界面资源加载失败"); |
| 47 | }); |
| 48 | target.addEventListener("unhandledrejection", event => reportDiagnostic("frontend", event.reason)); |
| 49 | } |