/** * Dev-only long-task watchdog. * * The `[Violation] Forced reflow` line tells you a task was fat but not who * ate it. Long Task attribution reports the task's start time (same clock as * `performance.now()`, so it lines up with the `[harvest]`/`[library]` logs) * and, when the browser can pin it down, the responsible script/layout phase. * Prints nothing until a task actually crosses 50ms. */ let started = false; /** One script's share of a long animation frame, as Chrome reports it. */ export interface LoafScript { name?: string; duration?: number; sourceURL?: string; sourceFunctionName?: string; sourceLocationLineNumber?: number; } /** The frame itself, plus the fields `long-animation-frame` adds over `PerformanceEntry`. */ export interface LoafEntry extends PerformanceEntry { blockingDuration?: number; styleAndLayoutStart?: number; renderStart?: number; scripts?: LoafScript[]; } /** * `http://localhost:5173/src/lib/player/media.ts?t=17` → `src/lib/player/media.ts`. * * The dev server's query strings and origin are noise in a log line somebody is reading against a * timeline; the path under `/src/` is the half that names the file. */ function shortSource(url: string | undefined, fallback: string): string { if (!url) return fallback; const bare = url.split("?")[0].split("#")[0]; const src = bare.indexOf("/src/"); return src >= 0 ? bare.slice(src + 1) : bare.replace(/^https?:\/\/[^/]+/, ""); } /** * The frame's scripts, folded by where they ran and read biggest first. * * This is the whole reason for watching `long-animation-frame` instead of `longtask`: a longtask * entry says a task crossed 50 ms and — outside a profiler session — attributes it to * `unknown/window`, which is a log line that must be re-measured with a profiler attached before it * means anything. A long frame says *which script*, by URL, because in dev the modules are served by * path. A storm of `[perf] longtask … unknown/window` is the symptom this turns into a file name. */ export function describeLongFrame(scripts: readonly LoafScript[] | undefined): string { const byWhere = new Map(); for (const s of scripts ?? []) { const where = `${shortSource(s.sourceURL, s.name ?? "unknown")}${ s.sourceFunctionName ? `:${s.sourceFunctionName}` : "" }${s.sourceLocationLineNumber ? `:${s.sourceLocationLineNumber}` : ""}`; byWhere.set(where, (byWhere.get(where) ?? 0) + (s.duration ?? 0)); } const top = [...byWhere.entries()] .sort((a, b) => b[1] - a[1]) .slice(0, 3) .map(([where, ms]) => `${where} ${ms.toFixed(0)}ms`); // Empty is itself the answer, and it is worth saying in words: a long frame with no script in it // was spent in the browser rather than in this code — collecting garbage, draining microtasks, or // an extension's content script on the same thread. return top.length ? top.join(" · ") : "no script attributed (gc, microtasks, or an extension)"; } /** * How the frame split between script and the browser's own style/layout, or nothing when the script * half is the whole story. Layout time is what a `Forced reflow` violation would have pointed at, and * it is the half that tells you to go and look at the DOM rather than at the code that ran. */ export function describeFrameSplit(entry: LoafEntry): string { if (entry.styleAndLayoutStart === undefined) return ""; const layout = entry.duration - (entry.styleAndLayoutStart - entry.startTime); return layout >= 8 ? ` · style/layout ${layout.toFixed(0)}ms` : ""; } export function startPerfLogging(): void { if (started || !import.meta.env.DEV || typeof PerformanceObserver === "undefined") return; started = true; const supported = PerformanceObserver.supportedEntryTypes ?? []; // One observer per capability, and only one of them: both report the same frames, and printing the // same 118 ms twice per frame makes the console unreadable. if (supported.includes("long-animation-frame")) { try { const po = new PerformanceObserver((list) => { for (const e of list.getEntries() as LoafEntry[]) { if (e.duration < 50) continue; console.debug( `[perf] longframe ${Math.round(e.duration)}ms @${Math.round(e.startTime)}ms — ` + `${describeLongFrame(e.scripts)}${describeFrameSplit(e)}`, ); } }); po.observe({ entryTypes: ["long-animation-frame"] }); return; } catch { /* fall through to longtask, which every browser that supports this supports */ } } try { const po = new PerformanceObserver((list) => { for (const e of list.getEntries() as (PerformanceEntry & { attribution?: { name: string; containerType?: string }[]; })[]) { const attr = e.attribution ?.map((a) => `${a.name}${a.containerType ? `/${a.containerType}` : ""}`) .join(", "); console.debug( `[perf] longtask ${Math.round(e.duration)}ms @${Math.round(e.startTime)}ms — ${attr || "unattributed"}`, ); } }); po.observe({ entryTypes: ["longtask"] }); } catch { /* longtask timing unsupported — the violation lines will have to do */ } } startPerfLogging(); /** * Layout-thrash probe. A "Forced reflow while executing JavaScript" violation * shows up as a *slow layout-property read* — patch the getters, time each * read, and print a stack when a read pays for the layout the previous writes * dirtied. Content scripts from extensions read the real DOM through the same * bindings, so their forced reflows get caught here too. */ const SLOW_MS = 16; let budget = 30; function describe(el: Element): string { const cls = typeof el.className === "string" ? el.className.split(" ")[0] : ""; return `${el.tagName.toLowerCase()}${cls ? `.${cls}` : ""}${el.id ? `#${el.id}` : ""}`; } function report(what: string, owner: Element, ms: number): void { if (budget-- <= 0) return; console.debug( `[thrash] slow ${what} on ${describe(owner)} took ${ms.toFixed(0)}ms\n` + new Error().stack, ); } export function startLayoutProbe(): void { if (!import.meta.env.DEV || typeof Element === "undefined") return; for (const prop of [ "offsetHeight", "offsetWidth", "offsetTop", "offsetLeft", "clientHeight", "clientWidth", "scrollHeight", "scrollWidth", "scrollTop", ] as const) { const d = Object.getOwnPropertyDescriptor(Element.prototype, prop); if (!d?.get) continue; Object.defineProperty(Element.prototype, prop, { ...d, get(this: Element) { const t = performance.now(); const v = d.get!.call(this) as number; const ms = performance.now() - t; if (ms > SLOW_MS) report(prop, this, ms); return v; }, }); } const gbr = Element.prototype.getBoundingClientRect; Element.prototype.getBoundingClientRect = function (this: Element) { const t = performance.now(); const r = gbr.call(this); const ms = performance.now() - t; if (ms > SLOW_MS) report("getBoundingClientRect", this, ms); return r; }; } startLayoutProbe(); /** * Dev-only ResizeObserver wrapper: reports each callback's duration and the * live element count at that moment — distinguishing "layout of a bounded * window (~hundreds of nodes) somehow costs 750ms" from "something rendered * far more than the virtualizer should allow". */ export function startResizeObserverTrace(): void { if (!import.meta.env.DEV || typeof ResizeObserver === "undefined") return; const Original = ResizeObserver; let budget = 40; window.ResizeObserver = class ResizeObserver extends Original { constructor(callback: ResizeObserverCallback) { super((entries, observer) => { const t = performance.now(); callback(entries, observer); const d = performance.now() - t; if (budget-- > 0 && d > 8) { const targets = entries.map((e) => describe(e.target)).join(", "); console.debug( `[perf] RO callback (${targets}) took ${d.toFixed(0)}ms — nodes=${document.querySelectorAll("*").length} @${t.toFixed(0)}`, ); } }); } }; } startResizeObserverTrace();