@react-perfscope/core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +113 -0
- package/dist/index.cjs +1035 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +367 -0
- package/dist/index.d.ts +367 -0
- package/dist/index.js +990 -0
- package/dist/index.js.map +1 -0
- package/package.json +48 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/recorder.ts","../src/sourcemap.ts","../src/collectors/long-tasks.ts","../src/collectors/forced-reflow.ts","../src/collectors/layout-shift.ts","../src/collectors/network.ts","../src/collectors/web-vitals.ts","../src/collectors/heap.ts","../src/collectors/interaction.ts","../src/collectors/frames.ts","../src/collectors/self-profiling.ts"],"sourcesContent":["// Types\nexport * from './types'\n\n// Recorder\nexport { createRecorder } from './recorder'\n\n// Sourcemap utilities\nexport { parseStack, resolveFrame, attachLazyStack, createSourceMapResolver } from './sourcemap'\nexport type { FetchMap, SourceMapResolver, CreateSourceMapResolverOptions } from './sourcemap'\n\n// Collectors\nexport { createLongTasksCollector } from './collectors/long-tasks'\nexport { createForcedReflowCollector } from './collectors/forced-reflow'\nexport { createLayoutShiftCollector } from './collectors/layout-shift'\nexport { createNetworkCollector } from './collectors/network'\nexport { createWebVitalsCollector } from './collectors/web-vitals'\nexport { createHeapCollector, analyzeHeapTrend } from './collectors/heap'\nexport type { HeapCollector } from './collectors/heap'\nexport { createInteractionCollector } from './collectors/interaction'\nexport type { InteractionCollector } from './collectors/interaction'\nexport { createFrameCollector, analyzeFrames } from './collectors/frames'\nexport type { FrameCollector } from './collectors/frames'\nexport {\n createSelfProfilingCollector,\n attributeWindow,\n attributeLongTaskSignals,\n isUserResource,\n} from './collectors/self-profiling'\nexport type {\n ProfilerTrace,\n ProfilerFrame,\n ProfilerStack,\n ProfilerSample,\n} from './collectors/self-profiling'\n","import type { Collector, Recorder, RecordingResult, Signal } from './types'\n\nconst BUFFER_CAP = 10_000\n\nexport interface InternalRecorder extends Recorder {\n __push: (signal: Signal) => void\n}\n\nexport function createRecorder(): Recorder {\n let recording = false\n let startedAt = 0\n let buffer: Signal[] = []\n const subscribers = new Set<(s: Signal) => void>()\n const collectors: Collector[] = []\n\n function notify(signal: Signal) {\n for (const cb of subscribers) {\n try {\n cb(signal)\n } catch (err) {\n console.warn('[react-perfscope] subscriber threw:', err)\n }\n }\n }\n\n function push(signal: Signal) {\n if (!recording) return\n buffer.push(signal)\n if (buffer.length > BUFFER_CAP) {\n buffer.splice(0, buffer.length - BUFFER_CAP)\n }\n notify(signal)\n }\n\n const recorder: InternalRecorder = {\n start() {\n if (recording) return\n recording = true\n startedAt = performance.now()\n buffer = []\n for (const c of collectors) {\n try {\n c.activate(push)\n } catch (err) {\n console.warn(`[react-perfscope] collector ${c.kind} failed to activate:`, err)\n }\n }\n },\n stop(): RecordingResult {\n if (!recording) {\n return { signals: [], startedAt: 0, duration: 0 }\n }\n for (const c of collectors) {\n try {\n c.deactivate()\n } catch (err) {\n console.warn(`[react-perfscope] collector ${c.kind} failed to deactivate:`, err)\n }\n }\n const duration = performance.now() - startedAt\n const result: RecordingResult = {\n signals: buffer.slice(),\n startedAt,\n duration,\n }\n recording = false\n buffer = []\n return result\n },\n isRecording() {\n return recording\n },\n onSignal(cb) {\n subscribers.add(cb)\n return () => subscribers.delete(cb)\n },\n use(collector) {\n collectors.push(collector)\n },\n __push: push,\n }\n return recorder\n}\n","import { TraceMap, originalPositionFor, type SourceMapInput } from '@jridgewell/trace-mapping'\nimport type { StackFrame } from './types'\n\nconst CHROME_FRAME = /^\\s*at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?$/\nconst FIREFOX_FRAME = /^(.*?)@(.+?):(\\d+):(\\d+)$/\n\n/** A parsed source map (the JSON object), as returned by a FetchMap. */\nexport type RawSourceMap = SourceMapInput\n\nexport type FetchMap = (file: string) => Promise<RawSourceMap | null>\n\nexport async function resolveFrame(\n frame: StackFrame,\n fetchMap: FetchMap\n): Promise<StackFrame> {\n try {\n const map = await fetchMap(frame.file)\n if (!map) return frame\n // trace-mapping is pure JS (no wasm), so this works in the browser where\n // Mozilla's source-map SourceMapConsumer needs an explicitly-initialized\n // mappings.wasm. Columns are 0-based here, matching the captured frames.\n const tracer = new TraceMap(map)\n const pos = originalPositionFor(tracer, { line: frame.line, column: frame.col })\n if (pos.source == null || pos.line == null || pos.column == null) {\n return frame\n }\n const resolved: StackFrame = {\n file: pos.source,\n line: pos.line,\n col: pos.column,\n }\n if (pos.name) resolved.fnName = pos.name\n else if (frame.fnName) resolved.fnName = frame.fnName\n return resolved\n } catch (err) {\n console.warn('[react-perfscope] resolveFrame failed:', err)\n return frame\n }\n}\n\n/**\n * Attach a lazy `stack` getter to `target` that parses `raw` on first access\n * and memoizes the result. Use this from collectors to defer parseStack cost\n * until a consumer actually reads `signal.stack`.\n *\n * `skipTopFrames` drops the leading N parsed frames — useful for collectors\n * that wrap a patched function (the wrapper itself shows up as the topmost\n * frame, but it's noise from the user's perspective).\n */\nexport function attachLazyStack(\n target: object,\n raw: string | undefined,\n skipTopFrames = 0\n): void {\n let cached: StackFrame[] | null = null\n Object.defineProperty(target, 'stack', {\n enumerable: true,\n configurable: true,\n get() {\n if (cached === null) {\n const all = parseStack(raw)\n cached = skipTopFrames > 0 ? all.slice(skipTopFrames) : all\n }\n return cached\n },\n })\n}\n\nexport interface SourceMapResolver {\n /** Resolve a parsed StackFrame to its original source position. Falls back to the input frame on any failure. */\n resolve(frame: StackFrame): Promise<StackFrame>\n}\n\nexport interface CreateSourceMapResolverOptions {\n /** Override the global fetch. Useful for tests and non-browser environments. */\n fetch?: typeof globalThis.fetch\n}\n\n/**\n * Create a SourceMap resolver that fetches `.map` files from the live URL\n * referenced in each source file's `//# sourceMappingURL=` directive.\n * Caches the parsed source map per source URL so repeated resolves against\n * the same file are O(1) after the first.\n *\n * Returns the input frame on any failure (network error, missing map, etc.).\n */\nexport function createSourceMapResolver(opts: CreateSourceMapResolverOptions = {}): SourceMapResolver {\n const f = opts.fetch ?? (typeof fetch !== 'undefined' ? fetch.bind(globalThis) : null)\n const cache = new Map<string, Promise<RawSourceMap | null>>()\n\n function fetchMapFor(sourceUrl: string): Promise<RawSourceMap | null> {\n if (!f) return Promise.resolve(null)\n const existing = cache.get(sourceUrl)\n if (existing) return existing\n const promise = (async () => {\n try {\n const res = await f(sourceUrl)\n if (!res || !res.ok) return null\n const text = await res.text()\n const m = text.match(/\\/\\/[#@]\\s*sourceMappingURL=(.+?)\\s*$/m)\n if (!m) return null\n const ref = m[1]!.trim()\n if (ref.startsWith('data:')) {\n const commaIdx = ref.indexOf(',')\n if (commaIdx === -1) return null\n const header = ref.slice(0, commaIdx)\n const payload = ref.slice(commaIdx + 1)\n const decoded = header.includes('base64')\n ? typeof atob === 'function'\n ? atob(payload)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n : (globalThis as any).Buffer.from(payload, 'base64').toString('utf8')\n : decodeURIComponent(payload)\n return JSON.parse(decoded) as RawSourceMap\n }\n const mapUrl = new URL(ref, sourceUrl).href\n const mapRes = await f(mapUrl)\n if (!mapRes || !mapRes.ok) return null\n return (await mapRes.json()) as RawSourceMap\n } catch {\n return null\n }\n })()\n cache.set(sourceUrl, promise)\n return promise\n }\n\n return {\n async resolve(frame) {\n try {\n return await resolveFrame(frame, fetchMapFor)\n } catch {\n return frame\n }\n },\n }\n}\n\nexport function parseStack(raw: string | undefined): StackFrame[] {\n if (!raw) return []\n const frames: StackFrame[] = []\n for (const line of raw.split('\\n')) {\n const chromeMatch = line.match(CHROME_FRAME)\n if (chromeMatch) {\n const [, fnName, file, lineStr, colStr] = chromeMatch\n const frame: StackFrame = {\n file: file ?? '',\n line: Number(lineStr),\n col: Number(colStr),\n }\n if (fnName) frame.fnName = fnName\n frames.push(frame)\n continue\n }\n const firefoxMatch = line.match(FIREFOX_FRAME)\n if (firefoxMatch) {\n const [, fnName, file, lineStr, colStr] = firefoxMatch\n const frame: StackFrame = {\n file: file ?? '',\n line: Number(lineStr),\n col: Number(colStr),\n }\n if (fnName) frame.fnName = fnName\n frames.push(frame)\n }\n }\n return frames\n}\n","import type { Collector, LongTaskScript, Signal } from '../types'\n\nconst LOAF = 'long-animation-frame'\nconst LEGACY = 'longtask'\n\n/** A single script entry inside a Long Animation Frame. */\ninterface ScriptTiming {\n duration?: number\n invoker?: string\n invokerType?: string\n sourceURL?: string\n sourceFunctionName?: string\n sourceCharPosition?: number\n}\n\ninterface LoAFEntry extends PerformanceEntry {\n blockingDuration?: number\n scripts?: ScriptTiming[]\n}\n\nfunction supportsLoAF(): boolean {\n const PO = (globalThis as { PerformanceObserver?: { supportedEntryTypes?: readonly string[] } })\n .PerformanceObserver\n const types = PO?.supportedEntryTypes\n return Array.isArray(types) && types.includes(LOAF)\n}\n\nfunction mapScripts(scripts: ScriptTiming[]): LongTaskScript[] {\n return scripts.map((s) => ({\n invokerType: s.invokerType ?? 'unknown',\n invoker: s.invoker ?? '',\n sourceURL: s.sourceURL ?? '',\n sourceFunctionName: s.sourceFunctionName ?? '',\n charPosition: typeof s.sourceCharPosition === 'number' ? s.sourceCharPosition : -1,\n duration: typeof s.duration === 'number' ? s.duration : 0,\n }))\n}\n\nexport function createLongTasksCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'long-task',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; long-tasks disabled')\n return\n }\n active = true\n const useLoAF = supportsLoAF()\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const entry of list.getEntries()) {\n if (useLoAF) {\n const loaf = entry as LoAFEntry\n const scripts = Array.isArray(loaf.scripts) ? mapScripts(loaf.scripts) : []\n emit({\n kind: 'long-task',\n at: entry.startTime,\n duration: entry.duration,\n stack: [],\n scripts,\n ...(typeof loaf.blockingDuration === 'number'\n ? { blockingDuration: loaf.blockingDuration }\n : {}),\n })\n } else {\n emit({\n kind: 'long-task',\n at: entry.startTime,\n duration: entry.duration,\n stack: [],\n })\n }\n }\n })\n observer.observe({ type: useLoAF ? LOAF : LEGACY, buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] long-tasks collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import type { Collector, Signal } from '../types'\nimport { attachLazyStack } from '../sourcemap'\n\nconst LAYOUT_GETTERS = [\n 'offsetWidth',\n 'offsetHeight',\n 'offsetLeft',\n 'offsetTop',\n 'clientWidth',\n 'clientHeight',\n 'scrollWidth',\n 'scrollHeight',\n] as const\n\nconst LAYOUT_METHODS = ['getBoundingClientRect', 'getClientRects'] as const\n\ntype SavedDescriptor = {\n proto: object\n key: string\n descriptor: PropertyDescriptor\n}\n\nexport function createForcedReflowCollector(): Collector {\n let active = false\n let emit: (s: Signal) => void = () => {}\n const saved: SavedDescriptor[] = []\n let mutationObserver: MutationObserver | null = null\n\n function consumePendingMutations(): boolean {\n if (!mutationObserver) {\n // Fallback when MutationObserver isn't available: always treat as dirty\n // (Phase 1 over-report behavior).\n return true\n }\n return mutationObserver.takeRecords().length > 0\n }\n\n function patchGetter(proto: object, key: string) {\n if (typeof proto !== 'object' || proto === null) return\n const desc = Object.getOwnPropertyDescriptor(proto, key)\n if (!desc || !desc.get) return\n saved.push({ proto, key, descriptor: desc })\n const originalGet = desc.get\n Object.defineProperty(proto, key, {\n configurable: true,\n get(this: unknown) {\n if (active) {\n if (!consumePendingMutations()) {\n return originalGet.call(this)\n }\n const at = performance.now()\n const rawStack = new Error().stack\n const value = originalGet.call(this)\n const duration = performance.now() - at\n const signal = { kind: 'forced-reflow' as const, at, duration } as unknown as Signal\n attachLazyStack(signal, rawStack, 1)\n emit(signal)\n return value\n }\n return originalGet.call(this)\n },\n set: desc.set,\n })\n }\n\n function patchMethod(proto: object, key: string) {\n if (typeof proto !== 'object' || proto === null) return\n const desc = Object.getOwnPropertyDescriptor(proto, key)\n if (!desc || typeof desc.value !== 'function') return\n saved.push({ proto, key, descriptor: desc })\n const original = desc.value as (...args: unknown[]) => unknown\n Object.defineProperty(proto, key, {\n configurable: true,\n writable: true,\n value: function patchedLayoutMethod(this: unknown, ...args: unknown[]) {\n if (active) {\n if (!consumePendingMutations()) {\n return original.apply(this, args)\n }\n const at = performance.now()\n const rawStack = new Error().stack\n const value = original.apply(this, args)\n const duration = performance.now() - at\n const signal = { kind: 'forced-reflow' as const, at, duration } as unknown as Signal\n attachLazyStack(signal, rawStack, 1)\n emit(signal)\n return value\n }\n return original.apply(this, args)\n },\n })\n }\n\n return {\n kind: 'forced-reflow',\n activate(emitFn) {\n if (active) return\n emit = emitFn\n active = true\n\n if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {\n try {\n mutationObserver = new MutationObserver(() => {})\n mutationObserver.observe(document, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: true,\n })\n } catch (err) {\n console.warn('[react-perfscope] forced-reflow MutationObserver failed:', err)\n mutationObserver = null\n }\n }\n\n if (typeof HTMLElement !== 'undefined') {\n for (const key of LAYOUT_GETTERS) {\n patchGetter(HTMLElement.prototype, key)\n }\n }\n if (typeof Element !== 'undefined') {\n for (const key of LAYOUT_METHODS) {\n patchMethod(Element.prototype, key)\n }\n }\n },\n deactivate() {\n if (!active) return\n active = false\n if (mutationObserver) {\n try {\n mutationObserver.disconnect()\n } catch {\n // ignore\n }\n mutationObserver = null\n }\n for (const { proto, key, descriptor } of saved) {\n Object.defineProperty(proto, key, descriptor)\n }\n saved.length = 0\n },\n }\n}\n","import type { Collector, Signal } from '../types'\n\ninterface LayoutShiftSource {\n currentRect: DOMRect\n previousRect?: DOMRect\n node?: Node | null\n}\n\ninterface LayoutShiftEntryLike extends PerformanceEntry {\n value: number\n hadRecentInput: boolean\n sources?: LayoutShiftSource[]\n}\n\nconst PERFSCOPE_HOST_ATTR = 'data-perfscope-host'\n\nfunction rectsOverlap(a: DOMRect, b: DOMRect, tolerance = 0): boolean {\n return !(\n a.x + a.width < b.x - tolerance ||\n b.x + b.width < a.x - tolerance ||\n a.y + a.height < b.y - tolerance ||\n b.y + b.height < a.y - tolerance\n )\n}\n\n/**\n * Returns true when every source in the entry is part of our floating\n * widget. We want to ignore shifts caused by the perfscope UI itself.\n *\n * Detection has two paths:\n * 1. Node-based: walk up `source.node` looking for `[data-perfscope-host]`.\n * Works when the node is in light DOM.\n * 2. Rect-based fallback: compare `source.currentRect` against every host\n * element's bounding rect. This catches the Shadow-DOM case where the\n * browser doesn't expose the inner node (Shadow root boundary).\n */\nfunction collectPerfscopeRects(): DOMRect[] {\n const hosts = Array.from(document.querySelectorAll(`[${PERFSCOPE_HOST_ATTR}]`))\n const rects: DOMRect[] = []\n for (const h of hosts) {\n // The light-DOM host element usually has height 0 because Shadow DOM\n // content isn't part of its layout. We need to peek inside the shadow\n // root and collect bounds of any positioned children.\n const sr = (h as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot\n if (sr) {\n for (const child of Array.from(sr.children)) {\n const r = (child as Element).getBoundingClientRect()\n if (r.width > 0 && r.height > 0) rects.push(r)\n }\n } else {\n const r = h.getBoundingClientRect()\n if (r.width > 0 && r.height > 0) rects.push(r)\n }\n }\n return rects\n}\n\nfunction entryIsOnlyFromPerfscope(sources: LayoutShiftSource[]): boolean {\n if (sources.length === 0) return false\n if (typeof document === 'undefined') return false\n\n const hostRects = collectPerfscopeRects()\n if (hostRects.length === 0) return false\n\n for (const src of sources) {\n let matched = false\n const node = src.node as (Node & { closest?: (sel: string) => Element | null }) | null | undefined\n if (node) {\n // Node-based check\n if (typeof (node as { closest?: unknown }).closest === 'function') {\n if ((node as Element).closest(`[${PERFSCOPE_HOST_ATTR}]`)) matched = true\n } else {\n let parent: (Element | null) = (node as Node).parentElement as Element | null\n while (parent) {\n if (parent.hasAttribute(PERFSCOPE_HOST_ATTR)) { matched = true; break }\n parent = parent.parentElement\n }\n }\n }\n // Rect-based fallback (shadow DOM): if source rect overlaps any of our\n // host rects, consider it our widget. Tolerance covers the case where\n // the widget changes size during the shift (its previous/current bounds\n // differ but both sit in the same screen corner).\n if (!matched) {\n for (const hostRect of hostRects) {\n if (rectsOverlap(src.currentRect, hostRect, 24)) {\n matched = true\n break\n }\n }\n }\n if (!matched) return false\n }\n return true\n}\n\nexport function createLayoutShiftCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'layout-shift',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; layout-shift disabled')\n return\n }\n active = true\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const raw of list.getEntries()) {\n const entry = raw as LayoutShiftEntryLike\n // Note: production CLS metrics exclude shifts with hadRecentInput\n // (user-initiated movements are considered intentional). For a\n // dev tool, the user explicitly WANTS to see what their clicks\n // caused — so we report these too.\n const sources = entry.sources ?? []\n if (entryIsOnlyFromPerfscope(sources)) continue\n // Convert viewport-relative rects to document-relative coords so\n // overlays stay anchored to the shifted DOM position when the\n // user scrolls. Filter above runs first on viewport coords (our\n // widget is position:fixed, lives in viewport space).\n const sx = (typeof window !== 'undefined' && window.scrollX) || 0\n const sy = (typeof window !== 'undefined' && window.scrollY) || 0\n const toDocRect = (r: DOMRect) =>\n new DOMRect(r.x + sx, r.y + sy, r.width, r.height)\n const rects = sources.map((s) => toDocRect(s.currentRect))\n // previousRect is undefined when the element was newly inserted.\n // An \"empty\" rect (w=0, h=0) likewise means there was no prior\n // box — treat both as `null` so the overlay can decide not to\n // draw an arrow for these.\n const prevRects: (DOMRect | null)[] = sources.map((s) => {\n const pr = s.previousRect\n if (!pr) return null\n if (pr.width === 0 && pr.height === 0) return null\n return toDocRect(pr)\n })\n emit({\n kind: 'layout-shift',\n at: entry.startTime,\n value: entry.value,\n sources: rects,\n previousSources: prevRects,\n })\n }\n })\n observer.observe({ type: 'layout-shift', buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] layout-shift collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import type { Collector, Signal } from '../types'\n\ninterface ResourceTimingLike extends PerformanceEntry {\n transferSize?: number\n renderBlockingStatus?: 'blocking' | 'non-blocking'\n}\n\nexport function createNetworkCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'network',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; network disabled')\n return\n }\n active = true\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const raw of list.getEntries()) {\n const entry = raw as ResourceTimingLike\n emit({\n kind: 'network',\n url: entry.name,\n startedAt: entry.startTime,\n duration: entry.duration,\n size: entry.transferSize ?? 0,\n blocking: entry.renderBlockingStatus === 'blocking',\n })\n }\n })\n observer.observe({ type: 'resource', buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] network collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import { onLCP, onINP, onCLS, onFCP, onTTFB, type Metric } from 'web-vitals'\nimport type { Collector, Signal, WebVitalSignal } from '../types'\n\ntype VitalName = WebVitalSignal['name']\n\nexport function createWebVitalsCollector(): Collector {\n let active = false\n let subscribed = false\n let emit: (signal: Signal) => void = () => {}\n\n function makeHandler(name: VitalName) {\n return (metric: Metric) => {\n if (!active) return\n emit({ kind: 'web-vital', name, value: metric.value })\n }\n }\n\n return {\n kind: 'web-vital',\n activate(emitFn) {\n emit = emitFn\n active = true\n if (subscribed) return\n try {\n onLCP(makeHandler('LCP'))\n onINP(makeHandler('INP'))\n onCLS(makeHandler('CLS'))\n onFCP(makeHandler('FCP'))\n onTTFB(makeHandler('TTFB'))\n subscribed = true\n } catch (err) {\n console.warn('[react-perfscope] web-vitals collector failed to subscribe:', err)\n active = false\n }\n },\n deactivate() {\n // The web-vitals library does not expose unsubscribe. We keep the\n // handlers attached and gate emission via `active`. Re-activating\n // updates `emit` without re-subscribing.\n active = false\n },\n }\n}\n","import type {\n Collector,\n HeapSample,\n HeapTrend,\n HeapTrendClass,\n RecordingResult,\n} from '../types'\n\n/** How often to read heap usage while recording. Reading performance.memory\n * is cheap, so we sample at 4Hz: a 1s cadence is too coarse — short spikes fall\n * between samples and the line, drawn straight between sparse points, smooths\n * them into a ramp. 250ms localizes spikes without meaningful overhead. */\nconst SAMPLE_INTERVAL_MS = 250\n/** Cap on retained samples so a multi-hour session can't grow the array\n * unbounded. At 250ms this is ~83 min; past that, oldest samples drop. */\nconst MAX_SAMPLES = 20_000\n\n/** Below this, a trend can't be estimated reliably. */\nconst MIN_SAMPLES = 4\n/** How many contiguous segments to split the series into when estimating the\n * floor. Each segment contributes its minimum (the post-GC trough). */\nconst FLOOR_SEGMENTS = 8\n\nconst MB = 1024 * 1024\n/** Floor-growth thresholds, in bytes per minute. */\nconst GROWING_SLOPE = 1 * MB\nconst LEAK_SLOPE = 5 * MB\n/** A rate alone isn't enough: over a short recording, a sub-megabyte wobble in\n * the floor extrapolates to a huge MB/min and would false-positive. Require the\n * floor to have actually risen by at least this much across the window before\n * calling anything growing/leaking. */\nconst MIN_NET_GROWTH = 2 * MB\n\ninterface MemoryInfo {\n usedJSHeapSize: number\n totalJSHeapSize: number\n jsHeapSizeLimit: number\n}\n\nfunction readMemory(): MemoryInfo | null {\n const perf = (globalThis as { performance?: { memory?: MemoryInfo } }).performance\n const mem = perf?.memory\n if (!mem || typeof mem.usedJSHeapSize !== 'number') return null\n return mem\n}\n\n/**\n * Least-squares slope of points (x, y). Returns 0 when x has no spread\n * (vertical / single distinct x) to avoid a divide-by-zero blow-up.\n */\nfunction slope(points: { x: number; y: number }[]): number {\n const n = points.length\n if (n < 2) return 0\n let sx = 0\n let sy = 0\n let sxy = 0\n let sxx = 0\n for (const { x, y } of points) {\n sx += x\n sy += y\n sxy += x * y\n sxx += x * x\n }\n const denom = n * sxx - sx * sx\n if (denom === 0) return 0\n return (n * sxy - sx * sy) / denom\n}\n\n/**\n * Estimate whether memory is being retained across the recording.\n *\n * GC makes raw heap usage a sawtooth, so the peak is noisy. The reliable\n * signal is the *floor* — the post-GC troughs. We split the series into\n * contiguous segments, take the minimum of each (its trough), and regress\n * those minima against time.\n *\n * A rising overall slope is necessary but NOT sufficient: a one-time step\n * (heap warms up early, then plateaus) also regresses to a positive slope, and\n * flagging that as a leak is a false positive — the classic \"idle recording\n * reads abnormal\" bug. A real leak keeps climbing, so we additionally require\n * the *recent* half of the floor to still be rising. We also gate on a minimum\n * net growth, since over a short window a sub-MB wobble extrapolates to a steep\n * per-minute slope.\n *\n * Returns null when there are too few samples to say anything.\n */\nexport function analyzeHeapTrend(samples: HeapSample[]): HeapTrend | null {\n if (samples.length < MIN_SAMPLES) return null\n const t0 = samples[0]!.at\n const segSize = Math.max(1, Math.ceil(samples.length / FLOOR_SEGMENTS))\n const floorPoints: { x: number; y: number }[] = []\n for (let i = 0; i < samples.length; i += segSize) {\n const seg = samples.slice(i, i + segSize)\n let min = Infinity\n for (const s of seg) min = Math.min(min, s.used)\n const mid = seg[Math.floor(seg.length / 2)]!\n floorPoints.push({ x: (mid.at - t0) / 60000, y: min })\n }\n const slopeBytesPerMin = slope(floorPoints)\n const spanMin = (samples[samples.length - 1]!.at - t0) / 60000\n const projectedGrowth = slopeBytesPerMin * spanMin\n // Recent trend: is the floor still climbing in the latter half? Distinguishes\n // a sustained leak from a one-time step that has since plateaued.\n const recent = floorPoints.slice(Math.floor(floorPoints.length / 2))\n const recentSlope = recent.length >= 2 ? slope(recent) : slopeBytesPerMin\n\n let classification: HeapTrendClass = 'stable'\n const sustained = projectedGrowth >= MIN_NET_GROWTH && recentSlope >= GROWING_SLOPE\n if (sustained) {\n classification =\n slopeBytesPerMin >= LEAK_SLOPE && recentSlope >= LEAK_SLOPE ? 'leak-suspected' : 'growing'\n }\n return { classification, slopeBytesPerMin }\n}\n\nexport interface HeapCollector extends Collector {\n /** Attach the sampled heap series to the recording result. Returns the\n * input untouched when nothing was sampled (unsupported browser). */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Samples `performance.memory` on an interval for the duration of a recording\n * and attaches the series via `finalize`. It is a Collector so the recorder\n * drives its start/stop, but it emits no signals — the series is a separate\n * track (see RecordingResult.heapSamples), so a busy session's signal buffer\n * can't evict it. No-ops entirely when performance.memory is unavailable\n * (non-Chromium), leaving `heapSamples` absent so the UI can show a fallback.\n */\nexport function createHeapCollector(): HeapCollector {\n let samples: HeapSample[] = []\n let timer: ReturnType<typeof setInterval> | null = null\n\n function sample(): void {\n const mem = readMemory()\n if (!mem) return\n samples.push({ at: performance.now(), used: mem.usedJSHeapSize, total: mem.totalJSHeapSize })\n if (samples.length > MAX_SAMPLES) samples.splice(0, samples.length - MAX_SAMPLES)\n }\n\n return {\n kind: 'heap',\n activate() {\n samples = []\n if (!readMemory()) return // unsupported → never start the timer\n sample()\n timer = setInterval(sample, SAMPLE_INTERVAL_MS)\n },\n deactivate() {\n if (timer == null) return\n clearInterval(timer)\n timer = null\n sample() // one final reading at stop\n },\n finalize(result) {\n if (samples.length === 0) return result\n return { ...result, heapSamples: samples.slice() }\n },\n }\n}\n","import type { Collector, InteractionSignal, RecordingResult } from '../types'\n\n/** Event Timing only surfaces events at/over this duration (ms); 40ms keeps\n * trivial interactions out while still catching anything a user would feel. */\nconst DURATION_THRESHOLD = 40\n\ninterface EventTimingEntry extends PerformanceEntry {\n processingStart: number\n processingEnd: number\n interactionId?: number\n target?: unknown\n}\n\nfunction selectorFor(target: unknown): string | undefined {\n const el = target as { tagName?: string; id?: string; className?: unknown } | null\n if (!el || typeof el.tagName !== 'string') return undefined\n let s = el.tagName.toLowerCase()\n if (el.id) s += `#${el.id}`\n else if (typeof el.className === 'string' && el.className.trim()) {\n s += `.${el.className.trim().split(/\\s+/)[0]}`\n }\n return s\n}\n\nfunction supportsEventTiming(): boolean {\n const PO = (globalThis as { PerformanceObserver?: { supportedEntryTypes?: readonly string[] } })\n .PerformanceObserver\n const types = PO?.supportedEntryTypes\n // happy-dom / older browsers may not expose supportedEntryTypes; if the\n // observer exists at all we still try, and observe() throwing is caught.\n return !types || types.includes('event')\n}\n\nexport interface InteractionCollector extends Collector {\n /** Group buffered Event Timing entries into one interaction each and append\n * them to the result. Returns the input untouched when none qualified. */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Records Event Timing entries during a recording and, on finalize, turns each\n * user interaction (grouped by interactionId) into one signal carrying the INP\n * latency breakdown: input delay → processing → presentation. The longest\n * event in a group defines the interaction's latency (matching how INP is\n * attributed). Emits no live signals — interactions are assembled at finalize,\n * then the self-profiling collector attributes the processing window to the\n * developer's hot functions.\n */\nexport function createInteractionCollector(): InteractionCollector {\n let active = false\n let observer: PerformanceObserver | null = null\n let entries: EventTimingEntry[] = []\n\n return {\n kind: 'interaction',\n activate() {\n if (typeof PerformanceObserver === 'undefined' || !supportsEventTiming()) return\n active = true\n entries = []\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const e of list.getEntries()) entries.push(e as EventTimingEntry)\n })\n // `event` covers all interaction events; `first-input` guarantees the\n // first one even if it's under the duration threshold.\n observer.observe({ type: 'event', buffered: false, durationThreshold: DURATION_THRESHOLD } as PerformanceObserverInit)\n try {\n observer.observe({ type: 'first-input', buffered: false } as PerformanceObserverInit)\n } catch {\n // first-input not supported everywhere; the event stream is enough.\n }\n } catch (err) {\n console.warn('[react-perfscope] interaction collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n finalize(result) {\n const byId = new Map<number, EventTimingEntry[]>()\n for (const e of entries) {\n const id = e.interactionId\n if (!id) continue // 0 / undefined → not part of a discrete interaction\n const group = byId.get(id)\n if (group) group.push(e)\n else byId.set(id, [e])\n }\n const interactions: InteractionSignal[] = []\n for (const group of byId.values()) {\n // All events of one interaction (pointerdown/up/click) report the same\n // `duration` (the whole interaction latency), so the breakdown can't\n // come from a single event. Span the processing across the group:\n // earliest processingStart → latest processingEnd (matches web-vitals).\n // The \"defining\" event for label/target is the one with the most\n // processing — typically the click/keydown that actually ran handlers.\n let duration = 0\n let startTime = Infinity\n let processingStart = Infinity\n let processingEnd = -Infinity\n let defining = group[0]!\n let maxProcessing = -Infinity\n for (const e of group) {\n if (e.duration > duration) duration = e.duration\n if (e.startTime < startTime) startTime = e.startTime\n if (e.processingStart < processingStart) processingStart = e.processingStart\n if (e.processingEnd > processingEnd) processingEnd = e.processingEnd\n const proc = e.processingEnd - e.processingStart\n if (proc > maxProcessing) {\n maxProcessing = proc\n defining = e\n }\n }\n if (duration < DURATION_THRESHOLD) continue\n const inputDelay = Math.max(0, processingStart - startTime)\n const processing = Math.max(0, processingEnd - processingStart)\n const presentation = Math.max(0, startTime + duration - processingEnd)\n interactions.push({\n kind: 'interaction',\n at: startTime,\n eventType: defining.name,\n ...(selectorFor(defining.target) ? { target: selectorFor(defining.target) } : {}),\n duration,\n inputDelay,\n processing,\n presentation,\n })\n }\n if (interactions.length === 0) return result\n interactions.sort((a, b) => a.at - b.at)\n return { ...result, signals: [...result.signals, ...interactions] }\n },\n }\n}\n","import type { Collector, FpsSample, FrameStats, RecordingResult } from '../types'\n\n/** 60fps frame budget (ms). Gaps are scored against this to count drops. */\nconst FRAME_BUDGET = 1000 / 60\n/** Window for the FPS series; 500ms smooths per-frame noise while still showing\n * a scroll-jank dip. */\nconst BUCKET_MS = 500\n/** A trailing window shorter than this is too small to estimate FPS reliably. */\nconst MIN_BUCKET_SPAN = 100\n/** Below this we can't say anything useful. */\nconst MIN_FRAMES = 8\n/** Cap retained frames so a long session can't grow the array unbounded\n * (~5.5 min at 60fps); past that, oldest drop. */\nconst MAX_FRAMES = 20_000\n\n/**\n * Turn raw requestAnimationFrame timestamps into a frame-rate picture:\n * a windowed FPS series, the lowest sustained FPS, the worst single hitch,\n * and an approximate dropped-frame count. Long tasks (>50ms) show up here as\n * big gaps, but so does sustained scroll jank (30–50ms frames) that the\n * long-task collector's threshold misses.\n *\n * Returns null when there are too few frames to analyze.\n */\nexport function analyzeFrames(frames: number[]): FrameStats | null {\n if (frames.length < MIN_FRAMES) return null\n\n let longestFrameMs = 0\n let droppedFrames = 0\n for (let i = 1; i < frames.length; i++) {\n const gap = frames[i]! - frames[i - 1]!\n if (gap > longestFrameMs) longestFrameMs = gap\n const dropped = Math.round(gap / FRAME_BUDGET) - 1\n if (dropped > 0) droppedFrames += dropped\n }\n\n const t0 = frames[0]!\n const end = frames[frames.length - 1]!\n const series: FpsSample[] = []\n let minFps = Infinity\n let idx = 0\n for (let bStart = t0; bStart < end; bStart += BUCKET_MS) {\n const bEnd = Math.min(bStart + BUCKET_MS, end)\n const span = bEnd - bStart\n let count = 0\n while (idx < frames.length && frames[idx]! < bEnd) {\n count++\n idx++\n }\n if (span < MIN_BUCKET_SPAN) break // skip a tiny trailing window\n const fps = count / (span / 1000)\n series.push({ at: bStart + span / 2, fps })\n if (fps < minFps) minFps = fps\n }\n if (series.length === 0) return null\n return { series, minFps, longestFrameMs, droppedFrames }\n}\n\nexport interface FrameCollector extends Collector {\n /** Attach the captured frame timestamps to the result. Returns the input\n * untouched when too few frames were seen (or rAF was unavailable). */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Records requestAnimationFrame timestamps for the duration of a recording so\n * the UI can chart frame rate and surface jank. Emits no signals — the\n * timestamps are a side track attached at finalize. No-ops when\n * requestAnimationFrame is unavailable (non-DOM environments).\n */\nexport function createFrameCollector(): FrameCollector {\n let active = false\n let rafId: number | null = null\n let frames: number[] = []\n\n function loop(t: number): void {\n if (!active) return\n frames.push(t)\n if (frames.length > MAX_FRAMES) frames.splice(0, frames.length - MAX_FRAMES)\n rafId = requestAnimationFrame(loop)\n }\n\n return {\n kind: 'frame',\n activate() {\n if (typeof requestAnimationFrame === 'undefined') return\n active = true\n frames = []\n rafId = requestAnimationFrame(loop)\n },\n deactivate() {\n active = false\n if (rafId != null && typeof cancelAnimationFrame !== 'undefined') {\n try {\n cancelAnimationFrame(rafId)\n } catch {\n // ignore\n }\n }\n rafId = null\n },\n finalize(result) {\n if (frames.length < MIN_FRAMES) return result\n return { ...result, frames: frames.slice() }\n },\n }\n}\n","import type { Collector, LongTaskAttribution, RecordingResult, Signal, StackFrame } from '../types'\n\n/**\n * JS Self-Profiling API trace shape (the subset we consume).\n * @see https://wicg.github.io/js-self-profiling/\n */\nexport interface ProfilerFrame {\n name?: string\n resourceId?: number\n line?: number\n column?: number\n}\nexport interface ProfilerStack {\n frameId: number\n parentId?: number\n}\nexport interface ProfilerSample {\n /** DOMHighResTimeStamp, same clock as performance.now() / entry.startTime. */\n timestamp: number\n stackId?: number\n}\nexport interface ProfilerTrace {\n resources: string[]\n frames: ProfilerFrame[]\n stacks: ProfilerStack[]\n samples: ProfilerSample[]\n}\n\ninterface ProfilerInstance {\n stop(): Promise<ProfilerTrace>\n}\ninterface ProfilerCtor {\n new (opts: { sampleInterval: number; maxBufferSize: number }): ProfilerInstance\n}\n\n/** Default sampling cadence. The browser may coarsen this. */\nconst SAMPLE_INTERVAL_MS = 10\nconst MAX_BUFFER_SIZE = 100_000\n/** Keep the noisiest few; deeper tails rarely help the developer. */\nconst MAX_FRAMES_PER_TASK = 5\n\n/**\n * Whether a resource URL belongs to the developer's own source (vs. a\n * dependency or tooling shim). Dependency frames are noise when the question\n * is \"which of MY functions is slow\".\n */\nexport function isUserResource(url: string | undefined): boolean {\n if (!url) return false\n if (url.includes('/node_modules/')) return false\n // Vite/dev tooling virtual modules: /@vite/client, /@react-refresh, /@id/...\n try {\n const path = new URL(url).pathname\n if (path.startsWith('/@')) return false\n } catch {\n if (url.startsWith('/@')) return false\n }\n return true\n}\n\nfunction frameToStackFrame(trace: ProfilerTrace, frame: ProfilerFrame): StackFrame {\n const file = frame.resourceId != null ? (trace.resources[frame.resourceId] ?? '') : ''\n const sf: StackFrame = {\n file,\n line: frame.line ?? 0,\n col: frame.column ?? 0,\n }\n if (frame.name) sf.fnName = frame.name\n return sf\n}\n\n/**\n * Climb a sample's stack from the leaf toward the root, returning the first\n * (deepest) frame that lives in user source. That frame is where the\n * developer's own code was actually executing when the sample was taken.\n */\nfunction leafUserFrame(trace: ProfilerTrace, stackId: number | undefined): ProfilerFrame | null {\n let id = stackId\n let guard = 0\n while (id != null && guard++ < 1000) {\n const stack = trace.stacks[id]\n if (!stack) break\n const frame = trace.frames[stack.frameId]\n if (frame && isUserResource(trace.resources[frame.resourceId ?? -1])) {\n return frame\n }\n id = stack.parentId\n }\n return null\n}\n\n/**\n * Aggregate the hottest user-source frames among samples whose timestamp\n * falls in [start, end]. `selfRatio` is relative to ALL in-window samples\n * (including vendor-only ones), so it reflects the share of the task's\n * blocking time spent in that user function.\n */\nexport function attributeWindow(\n trace: ProfilerTrace,\n start: number,\n end: number\n): LongTaskAttribution[] {\n let total = 0\n const counts = new Map<string, { frame: StackFrame; count: number }>()\n for (const sample of trace.samples) {\n if (sample.timestamp < start || sample.timestamp > end) continue\n total++\n const frame = leafUserFrame(trace, sample.stackId)\n if (!frame) continue\n const sf = frameToStackFrame(trace, frame)\n const key = `${sf.file}:${sf.line}:${sf.col}:${sf.fnName ?? ''}`\n const entry = counts.get(key)\n if (entry) entry.count++\n else counts.set(key, { frame: sf, count: 1 })\n }\n if (total === 0) return []\n return [...counts.values()]\n .sort((a, b) => b.count - a.count)\n .slice(0, MAX_FRAMES_PER_TASK)\n .map(({ frame, count }) => ({ frame, selfRatio: count / total, sampleCount: count }))\n}\n\n/**\n * Return a copy of `signals` with each long-task signal enriched with the\n * hottest user frames sampled during its window. Long tasks with no in-window\n * user samples are left without `attribution`. Non-long-task signals pass\n * through by reference.\n */\nexport function attributeLongTaskSignals(trace: ProfilerTrace, signals: Signal[]): Signal[] {\n return signals.map((signal) => {\n if (signal.kind !== 'long-task') return signal\n const attribution = attributeWindow(trace, signal.at, signal.at + signal.duration)\n if (attribution.length === 0) return signal\n return { ...signal, attribution }\n })\n}\n\n/**\n * Like {@link attributeLongTaskSignals} but for interactions: attributes the\n * *processing* window (handlers running, `[at+inputDelay, +processing]`) to the\n * developer's hot functions — answering \"which of my code made this click\n * slow\". Input delay and presentation aren't JS-on-the-stack, so they're\n * excluded from the window.\n */\nexport function attributeInteractionSignals(trace: ProfilerTrace, signals: Signal[]): Signal[] {\n return signals.map((signal) => {\n if (signal.kind !== 'interaction') return signal\n const start = signal.at + signal.inputDelay\n const attribution = attributeWindow(trace, start, start + signal.processing)\n if (attribution.length === 0) return signal\n return { ...signal, attribution }\n })\n}\n\ninterface SelfProfilingCollector extends Collector {\n /** Stop the profiler (if running), await its trace, and return a result\n * with long-task signals enriched. Falls back to the input on any failure\n * or when the Profiler API / Document-Policy header is unavailable. */\n finalize(result: RecordingResult): Promise<RecordingResult>\n}\n\n/**\n * Collector that runs the JS Self-Profiling API across a recording and, on\n * finalize, attributes each long task to the developer's own hot functions —\n * something LoAF can't do for React-delegated events (it only sees React's\n * single root dispatcher).\n *\n * It reports `kind: 'long-task'` because it enriches that signal rather than\n * emitting its own. Requires Chromium + a `Document-Policy: js-profiling`\n * response header (the dev plugins inject it); degrades to a no-op otherwise.\n */\nexport function createSelfProfilingCollector(): SelfProfilingCollector {\n let profiler: ProfilerInstance | null = null\n let tracePromise: Promise<ProfilerTrace> | null = null\n\n return {\n kind: 'long-task',\n activate() {\n tracePromise = null\n const Ctor = (globalThis as { Profiler?: ProfilerCtor }).Profiler\n if (typeof Ctor !== 'function') return\n try {\n profiler = new Ctor({ sampleInterval: SAMPLE_INTERVAL_MS, maxBufferSize: MAX_BUFFER_SIZE })\n } catch (err) {\n // Thrown when the Document-Policy: js-profiling header is absent.\n console.warn(\n '[react-perfscope] self-profiling unavailable (needs Document-Policy: js-profiling header); long tasks keep LoAF-only attribution:',\n err\n )\n profiler = null\n }\n },\n deactivate() {\n if (!profiler) return\n try {\n tracePromise = profiler.stop()\n } catch (err) {\n console.warn('[react-perfscope] self-profiling stop failed:', err)\n tracePromise = null\n }\n profiler = null\n },\n async finalize(result: RecordingResult): Promise<RecordingResult> {\n if (!tracePromise) return result\n try {\n const trace = await tracePromise\n const signals = attributeInteractionSignals(trace, attributeLongTaskSignals(trace, result.signals))\n return { ...result, signals }\n } catch (err) {\n console.warn('[react-perfscope] self-profiling finalize failed:', err)\n return result\n } finally {\n tracePromise = null\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,IAAM,aAAa;AAMZ,SAAS,iBAA2B;AACzC,MAAI,YAAY;AAChB,MAAI,YAAY;AAChB,MAAI,SAAmB,CAAC;AACxB,QAAM,cAAc,oBAAI,IAAyB;AACjD,QAAM,aAA0B,CAAC;AAEjC,WAAS,OAAO,QAAgB;AAC9B,eAAW,MAAM,aAAa;AAC5B,UAAI;AACF,WAAG,MAAM;AAAA,MACX,SAAS,KAAK;AACZ,gBAAQ,KAAK,uCAAuC,GAAG;AAAA,MACzD;AAAA,IACF;AAAA,EACF;AAEA,WAAS,KAAK,QAAgB;AAC5B,QAAI,CAAC,UAAW;AAChB,WAAO,KAAK,MAAM;AAClB,QAAI,OAAO,SAAS,YAAY;AAC9B,aAAO,OAAO,GAAG,OAAO,SAAS,UAAU;AAAA,IAC7C;AACA,WAAO,MAAM;AAAA,EACf;AAEA,QAAM,WAA6B;AAAA,IACjC,QAAQ;AACN,UAAI,UAAW;AACf,kBAAY;AACZ,kBAAY,YAAY,IAAI;AAC5B,eAAS,CAAC;A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;AAElD,SAAO;AAAA,IACL,MAAM;AAAA,IACN,WAAW;AACT,qBAAe;AACf,YAAM,OAAQ,WAA2C;AACzD,UAAI,OAAO,SAAS,WAAY;AAChC,UAAI;AACF,mBAAW,IAAI,KAAK,EAAE,gBAAgBA,qBAAoB,eAAe,gBAAgB,CAAC;AAAA,MAC5F,SAAS,KAAK;AAEZ,gBAAQ;AAAA,UACN;AAAA,UACA;AAAA,QACF;AACA,mBAAW;AAAA,MACb;AAAA,IACF;AAAA,IACA,aAAa;AACX,UAAI,CAAC,SAAU;AACf,UAAI;AACF,uBAAe,SAAS,KAAK;AAAA,MAC/B,SAAS,KAAK;AACZ,gBAAQ,KAAK,iDAAiD,GAAG;AACjE,uBAAe;AAAA,MACjB;AACA,iBAAW;AAAA,IACb;AAAA,IACA,MAAM,SAAS,QAAmD;AAChE,UAAI,CAAC,aAAc,QAAO;AAC1B,UAAI;AACF,cAAM,QAAQ,MAAM;AACpB,cAAM,UAAU,4BAA4B,OAAO,yBAAyB,OAAO,OAAO,OAAO,CAAC;AAClG,eAAO,EAAE,GAAG,QAAQ,QAAQ;AAAA,MAC9B,SAAS,KAAK;AACZ,gBAAQ,KAAK,qDAAqD,GAAG;AACrE,eAAO;AAAA,MACT,UAAE;AACA,uBAAe;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;","names":["SAMPLE_INTERVAL_MS"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
/// <reference lib="es2015" />
|
|
2
|
+
/// <reference lib="dom" />
|
|
3
|
+
|
|
4
|
+
import { SourceMapInput } from '@jridgewell/trace-mapping';
|
|
5
|
+
|
|
6
|
+
type StackFrame = {
|
|
7
|
+
file: string;
|
|
8
|
+
line: number;
|
|
9
|
+
col: number;
|
|
10
|
+
fnName?: string;
|
|
11
|
+
};
|
|
12
|
+
type ForcedReflowSignal = {
|
|
13
|
+
kind: 'forced-reflow';
|
|
14
|
+
at: number;
|
|
15
|
+
duration: number;
|
|
16
|
+
stack: StackFrame[];
|
|
17
|
+
};
|
|
18
|
+
type LayoutShiftSignal = {
|
|
19
|
+
kind: 'layout-shift';
|
|
20
|
+
at: number;
|
|
21
|
+
value: number;
|
|
22
|
+
sources: DOMRect[];
|
|
23
|
+
/**
|
|
24
|
+
* Parallel array to `sources`. Each entry is the rect of the source node
|
|
25
|
+
* BEFORE the shift, in document coords. `null` when the source had no
|
|
26
|
+
* previous rect (newly inserted element). Lets consumers draw a "moved
|
|
27
|
+
* from → to" arrow during overlay rendering.
|
|
28
|
+
*/
|
|
29
|
+
previousSources?: (DOMRect | null)[];
|
|
30
|
+
};
|
|
31
|
+
type LongTaskScript = {
|
|
32
|
+
/** What kind of entry point ran this script: 'event-listener',
|
|
33
|
+
* 'user-callback', 'resolve-promise', 'reject-promise', 'classic-script',
|
|
34
|
+
* 'module-script', etc. (from the LoAF spec). */
|
|
35
|
+
invokerType: string;
|
|
36
|
+
/** Human-readable invoker, e.g. "BUTTON#go.onclick" or a callback name. */
|
|
37
|
+
invoker: string;
|
|
38
|
+
sourceURL: string;
|
|
39
|
+
sourceFunctionName: string;
|
|
40
|
+
/** Character offset of the function in its source, or -1 when unknown. */
|
|
41
|
+
charPosition: number;
|
|
42
|
+
/** Wall-clock ms this script occupied. */
|
|
43
|
+
duration: number;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* One hot user-source location inside a long task, derived from JS
|
|
47
|
+
* Self-Profiling samples. Answers "which of MY functions burned the time",
|
|
48
|
+
* which LoAF cannot do for React-delegated events (it only sees React's
|
|
49
|
+
* single root dispatcher). `frame` is the raw served-file position; resolve
|
|
50
|
+
* it through source maps for the original location.
|
|
51
|
+
*/
|
|
52
|
+
type LongTaskAttribution = {
|
|
53
|
+
frame: StackFrame;
|
|
54
|
+
/** Fraction (0..1) of this task's in-window samples whose leaf user frame
|
|
55
|
+
* was this one. */
|
|
56
|
+
selfRatio: number;
|
|
57
|
+
/** Number of in-window samples attributed to this frame. */
|
|
58
|
+
sampleCount: number;
|
|
59
|
+
};
|
|
60
|
+
type LongTaskSignal = {
|
|
61
|
+
kind: 'long-task';
|
|
62
|
+
at: number;
|
|
63
|
+
duration: number;
|
|
64
|
+
stack: StackFrame[];
|
|
65
|
+
/** Per-script attribution from the Long Animation Frame API. Absent when
|
|
66
|
+
* LoAF is unsupported (falls back to the legacy `longtask` entry, which
|
|
67
|
+
* gives duration only). */
|
|
68
|
+
scripts?: LongTaskScript[];
|
|
69
|
+
/** Main-thread blocking time reported by LoAF, when available. */
|
|
70
|
+
blockingDuration?: number;
|
|
71
|
+
/** Hottest user-source frames inside this task, from JS Self-Profiling.
|
|
72
|
+
* Sorted by sampleCount desc. Absent when self-profiling is unavailable
|
|
73
|
+
* (no Profiler API or missing Document-Policy header). */
|
|
74
|
+
attribution?: LongTaskAttribution[];
|
|
75
|
+
};
|
|
76
|
+
type WebVitalSignal = {
|
|
77
|
+
kind: 'web-vital';
|
|
78
|
+
name: 'LCP' | 'INP' | 'CLS' | 'FCP' | 'TTFB';
|
|
79
|
+
value: number;
|
|
80
|
+
};
|
|
81
|
+
type NetworkSignal = {
|
|
82
|
+
kind: 'network';
|
|
83
|
+
url: string;
|
|
84
|
+
startedAt: number;
|
|
85
|
+
duration: number;
|
|
86
|
+
size: number;
|
|
87
|
+
blocking: boolean;
|
|
88
|
+
};
|
|
89
|
+
type InteractionSignal = {
|
|
90
|
+
kind: 'interaction';
|
|
91
|
+
/** Event startTime — when the user input arrived. */
|
|
92
|
+
at: number;
|
|
93
|
+
/** Event type that defined the interaction latency (click, pointerup, keydown…). */
|
|
94
|
+
eventType: string;
|
|
95
|
+
/** Best-effort CSS-ish selector of the event target. */
|
|
96
|
+
target?: string;
|
|
97
|
+
/** Total interaction latency: input → handlers → next paint (ms). */
|
|
98
|
+
duration: number;
|
|
99
|
+
/** startTime → processingStart: main thread was busy before handlers ran. */
|
|
100
|
+
inputDelay: number;
|
|
101
|
+
/** processingStart → processingEnd: the event handlers themselves. */
|
|
102
|
+
processing: number;
|
|
103
|
+
/** processingEnd → next paint: re-render + paint after handlers. */
|
|
104
|
+
presentation: number;
|
|
105
|
+
/** Hottest user-source frames during the processing window, from JS
|
|
106
|
+
* Self-Profiling. Absent when self-profiling is unavailable or found none. */
|
|
107
|
+
attribution?: LongTaskAttribution[];
|
|
108
|
+
};
|
|
109
|
+
type RenderReason = 'mount' | 'state' | 'props' | 'parent';
|
|
110
|
+
type RenderSignal = {
|
|
111
|
+
kind: 'render';
|
|
112
|
+
at: number;
|
|
113
|
+
component: string;
|
|
114
|
+
reason: RenderReason;
|
|
115
|
+
duration: number;
|
|
116
|
+
/** Prop keys that changed since the previous render (reason === 'props'). */
|
|
117
|
+
changedProps?: string[];
|
|
118
|
+
/** Groups every render emitted from the same commit so the UI can show
|
|
119
|
+
* one cascade (root + the components it re-rendered) as a unit. */
|
|
120
|
+
commitId: number;
|
|
121
|
+
/** Fiber depth from the committed root — used to indent the cascade. */
|
|
122
|
+
depth: number;
|
|
123
|
+
};
|
|
124
|
+
type Signal = ForcedReflowSignal | LayoutShiftSignal | LongTaskSignal | WebVitalSignal | NetworkSignal | RenderSignal | InteractionSignal;
|
|
125
|
+
type SignalKind = Signal['kind'];
|
|
126
|
+
/** One heap-usage reading. `at` shares the performance.now() clock used by
|
|
127
|
+
* signal timestamps, so it lines up with the timeline x-axis. */
|
|
128
|
+
type HeapSample = {
|
|
129
|
+
at: number;
|
|
130
|
+
/** usedJSHeapSize — live JS objects, in bytes. */
|
|
131
|
+
used: number;
|
|
132
|
+
/** totalJSHeapSize — allocated heap, in bytes. */
|
|
133
|
+
total: number;
|
|
134
|
+
};
|
|
135
|
+
type HeapTrendClass = 'stable' | 'growing' | 'leak-suspected';
|
|
136
|
+
type HeapTrend = {
|
|
137
|
+
classification: HeapTrendClass;
|
|
138
|
+
/** Slope of the heap "floor" (post-GC troughs), in bytes per minute. A
|
|
139
|
+
* steadily rising floor is the signal that memory is being retained. */
|
|
140
|
+
slopeBytesPerMin: number;
|
|
141
|
+
};
|
|
142
|
+
/** One windowed frame-rate reading. */
|
|
143
|
+
type FpsSample = {
|
|
144
|
+
at: number;
|
|
145
|
+
fps: number;
|
|
146
|
+
};
|
|
147
|
+
type FrameStats = {
|
|
148
|
+
/** Windowed FPS series across the recording. */
|
|
149
|
+
series: FpsSample[];
|
|
150
|
+
/** Lowest windowed FPS — the worst sustained dip. */
|
|
151
|
+
minFps: number;
|
|
152
|
+
/** Longest single inter-frame gap (worst hitch), in ms. */
|
|
153
|
+
longestFrameMs: number;
|
|
154
|
+
/** Approximate frames dropped across the recording (vs a 60fps budget). */
|
|
155
|
+
droppedFrames: number;
|
|
156
|
+
};
|
|
157
|
+
interface RecordingResult {
|
|
158
|
+
signals: Signal[];
|
|
159
|
+
startedAt: number;
|
|
160
|
+
duration: number;
|
|
161
|
+
/** Heap-usage time series, present only when performance.memory is
|
|
162
|
+
* available (Chromium). Attached at finalize, not part of the signal buffer. */
|
|
163
|
+
heapSamples?: HeapSample[];
|
|
164
|
+
/** requestAnimationFrame timestamps captured during the recording, for
|
|
165
|
+
* frame-rate / jank analysis. Attached at finalize. */
|
|
166
|
+
frames?: number[];
|
|
167
|
+
}
|
|
168
|
+
/** Collectors are usually keyed by the SignalKind they emit. A few (heap,
|
|
169
|
+
* self-profiling) drive a side-channel instead of emitting signals; `'heap'`
|
|
170
|
+
* widens the kind for the heap sampler, which attaches a time series via
|
|
171
|
+
* finalize rather than pushing signals. */
|
|
172
|
+
type CollectorKind = SignalKind | 'heap' | 'frame';
|
|
173
|
+
interface Collector {
|
|
174
|
+
readonly kind: CollectorKind;
|
|
175
|
+
activate(emit: (signal: Signal) => void): void;
|
|
176
|
+
deactivate(): void;
|
|
177
|
+
}
|
|
178
|
+
interface Recorder {
|
|
179
|
+
start(): void;
|
|
180
|
+
stop(): RecordingResult;
|
|
181
|
+
isRecording(): boolean;
|
|
182
|
+
onSignal(cb: (signal: Signal) => void): () => void;
|
|
183
|
+
use(collector: Collector): void;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
declare function createRecorder(): Recorder;
|
|
187
|
+
|
|
188
|
+
/** A parsed source map (the JSON object), as returned by a FetchMap. */
|
|
189
|
+
type RawSourceMap = SourceMapInput;
|
|
190
|
+
type FetchMap = (file: string) => Promise<RawSourceMap | null>;
|
|
191
|
+
declare function resolveFrame(frame: StackFrame, fetchMap: FetchMap): Promise<StackFrame>;
|
|
192
|
+
/**
|
|
193
|
+
* Attach a lazy `stack` getter to `target` that parses `raw` on first access
|
|
194
|
+
* and memoizes the result. Use this from collectors to defer parseStack cost
|
|
195
|
+
* until a consumer actually reads `signal.stack`.
|
|
196
|
+
*
|
|
197
|
+
* `skipTopFrames` drops the leading N parsed frames — useful for collectors
|
|
198
|
+
* that wrap a patched function (the wrapper itself shows up as the topmost
|
|
199
|
+
* frame, but it's noise from the user's perspective).
|
|
200
|
+
*/
|
|
201
|
+
declare function attachLazyStack(target: object, raw: string | undefined, skipTopFrames?: number): void;
|
|
202
|
+
interface SourceMapResolver {
|
|
203
|
+
/** Resolve a parsed StackFrame to its original source position. Falls back to the input frame on any failure. */
|
|
204
|
+
resolve(frame: StackFrame): Promise<StackFrame>;
|
|
205
|
+
}
|
|
206
|
+
interface CreateSourceMapResolverOptions {
|
|
207
|
+
/** Override the global fetch. Useful for tests and non-browser environments. */
|
|
208
|
+
fetch?: typeof globalThis.fetch;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Create a SourceMap resolver that fetches `.map` files from the live URL
|
|
212
|
+
* referenced in each source file's `//# sourceMappingURL=` directive.
|
|
213
|
+
* Caches the parsed source map per source URL so repeated resolves against
|
|
214
|
+
* the same file are O(1) after the first.
|
|
215
|
+
*
|
|
216
|
+
* Returns the input frame on any failure (network error, missing map, etc.).
|
|
217
|
+
*/
|
|
218
|
+
declare function createSourceMapResolver(opts?: CreateSourceMapResolverOptions): SourceMapResolver;
|
|
219
|
+
declare function parseStack(raw: string | undefined): StackFrame[];
|
|
220
|
+
|
|
221
|
+
declare function createLongTasksCollector(): Collector;
|
|
222
|
+
|
|
223
|
+
declare function createForcedReflowCollector(): Collector;
|
|
224
|
+
|
|
225
|
+
declare function createLayoutShiftCollector(): Collector;
|
|
226
|
+
|
|
227
|
+
declare function createNetworkCollector(): Collector;
|
|
228
|
+
|
|
229
|
+
declare function createWebVitalsCollector(): Collector;
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Estimate whether memory is being retained across the recording.
|
|
233
|
+
*
|
|
234
|
+
* GC makes raw heap usage a sawtooth, so the peak is noisy. The reliable
|
|
235
|
+
* signal is the *floor* — the post-GC troughs. We split the series into
|
|
236
|
+
* contiguous segments, take the minimum of each (its trough), and regress
|
|
237
|
+
* those minima against time.
|
|
238
|
+
*
|
|
239
|
+
* A rising overall slope is necessary but NOT sufficient: a one-time step
|
|
240
|
+
* (heap warms up early, then plateaus) also regresses to a positive slope, and
|
|
241
|
+
* flagging that as a leak is a false positive — the classic "idle recording
|
|
242
|
+
* reads abnormal" bug. A real leak keeps climbing, so we additionally require
|
|
243
|
+
* the *recent* half of the floor to still be rising. We also gate on a minimum
|
|
244
|
+
* net growth, since over a short window a sub-MB wobble extrapolates to a steep
|
|
245
|
+
* per-minute slope.
|
|
246
|
+
*
|
|
247
|
+
* Returns null when there are too few samples to say anything.
|
|
248
|
+
*/
|
|
249
|
+
declare function analyzeHeapTrend(samples: HeapSample[]): HeapTrend | null;
|
|
250
|
+
interface HeapCollector extends Collector {
|
|
251
|
+
/** Attach the sampled heap series to the recording result. Returns the
|
|
252
|
+
* input untouched when nothing was sampled (unsupported browser). */
|
|
253
|
+
finalize(result: RecordingResult): RecordingResult;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Samples `performance.memory` on an interval for the duration of a recording
|
|
257
|
+
* and attaches the series via `finalize`. It is a Collector so the recorder
|
|
258
|
+
* drives its start/stop, but it emits no signals — the series is a separate
|
|
259
|
+
* track (see RecordingResult.heapSamples), so a busy session's signal buffer
|
|
260
|
+
* can't evict it. No-ops entirely when performance.memory is unavailable
|
|
261
|
+
* (non-Chromium), leaving `heapSamples` absent so the UI can show a fallback.
|
|
262
|
+
*/
|
|
263
|
+
declare function createHeapCollector(): HeapCollector;
|
|
264
|
+
|
|
265
|
+
interface InteractionCollector extends Collector {
|
|
266
|
+
/** Group buffered Event Timing entries into one interaction each and append
|
|
267
|
+
* them to the result. Returns the input untouched when none qualified. */
|
|
268
|
+
finalize(result: RecordingResult): RecordingResult;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Records Event Timing entries during a recording and, on finalize, turns each
|
|
272
|
+
* user interaction (grouped by interactionId) into one signal carrying the INP
|
|
273
|
+
* latency breakdown: input delay → processing → presentation. The longest
|
|
274
|
+
* event in a group defines the interaction's latency (matching how INP is
|
|
275
|
+
* attributed). Emits no live signals — interactions are assembled at finalize,
|
|
276
|
+
* then the self-profiling collector attributes the processing window to the
|
|
277
|
+
* developer's hot functions.
|
|
278
|
+
*/
|
|
279
|
+
declare function createInteractionCollector(): InteractionCollector;
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Turn raw requestAnimationFrame timestamps into a frame-rate picture:
|
|
283
|
+
* a windowed FPS series, the lowest sustained FPS, the worst single hitch,
|
|
284
|
+
* and an approximate dropped-frame count. Long tasks (>50ms) show up here as
|
|
285
|
+
* big gaps, but so does sustained scroll jank (30–50ms frames) that the
|
|
286
|
+
* long-task collector's threshold misses.
|
|
287
|
+
*
|
|
288
|
+
* Returns null when there are too few frames to analyze.
|
|
289
|
+
*/
|
|
290
|
+
declare function analyzeFrames(frames: number[]): FrameStats | null;
|
|
291
|
+
interface FrameCollector extends Collector {
|
|
292
|
+
/** Attach the captured frame timestamps to the result. Returns the input
|
|
293
|
+
* untouched when too few frames were seen (or rAF was unavailable). */
|
|
294
|
+
finalize(result: RecordingResult): RecordingResult;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Records requestAnimationFrame timestamps for the duration of a recording so
|
|
298
|
+
* the UI can chart frame rate and surface jank. Emits no signals — the
|
|
299
|
+
* timestamps are a side track attached at finalize. No-ops when
|
|
300
|
+
* requestAnimationFrame is unavailable (non-DOM environments).
|
|
301
|
+
*/
|
|
302
|
+
declare function createFrameCollector(): FrameCollector;
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* JS Self-Profiling API trace shape (the subset we consume).
|
|
306
|
+
* @see https://wicg.github.io/js-self-profiling/
|
|
307
|
+
*/
|
|
308
|
+
interface ProfilerFrame {
|
|
309
|
+
name?: string;
|
|
310
|
+
resourceId?: number;
|
|
311
|
+
line?: number;
|
|
312
|
+
column?: number;
|
|
313
|
+
}
|
|
314
|
+
interface ProfilerStack {
|
|
315
|
+
frameId: number;
|
|
316
|
+
parentId?: number;
|
|
317
|
+
}
|
|
318
|
+
interface ProfilerSample {
|
|
319
|
+
/** DOMHighResTimeStamp, same clock as performance.now() / entry.startTime. */
|
|
320
|
+
timestamp: number;
|
|
321
|
+
stackId?: number;
|
|
322
|
+
}
|
|
323
|
+
interface ProfilerTrace {
|
|
324
|
+
resources: string[];
|
|
325
|
+
frames: ProfilerFrame[];
|
|
326
|
+
stacks: ProfilerStack[];
|
|
327
|
+
samples: ProfilerSample[];
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Whether a resource URL belongs to the developer's own source (vs. a
|
|
331
|
+
* dependency or tooling shim). Dependency frames are noise when the question
|
|
332
|
+
* is "which of MY functions is slow".
|
|
333
|
+
*/
|
|
334
|
+
declare function isUserResource(url: string | undefined): boolean;
|
|
335
|
+
/**
|
|
336
|
+
* Aggregate the hottest user-source frames among samples whose timestamp
|
|
337
|
+
* falls in [start, end]. `selfRatio` is relative to ALL in-window samples
|
|
338
|
+
* (including vendor-only ones), so it reflects the share of the task's
|
|
339
|
+
* blocking time spent in that user function.
|
|
340
|
+
*/
|
|
341
|
+
declare function attributeWindow(trace: ProfilerTrace, start: number, end: number): LongTaskAttribution[];
|
|
342
|
+
/**
|
|
343
|
+
* Return a copy of `signals` with each long-task signal enriched with the
|
|
344
|
+
* hottest user frames sampled during its window. Long tasks with no in-window
|
|
345
|
+
* user samples are left without `attribution`. Non-long-task signals pass
|
|
346
|
+
* through by reference.
|
|
347
|
+
*/
|
|
348
|
+
declare function attributeLongTaskSignals(trace: ProfilerTrace, signals: Signal[]): Signal[];
|
|
349
|
+
interface SelfProfilingCollector extends Collector {
|
|
350
|
+
/** Stop the profiler (if running), await its trace, and return a result
|
|
351
|
+
* with long-task signals enriched. Falls back to the input on any failure
|
|
352
|
+
* or when the Profiler API / Document-Policy header is unavailable. */
|
|
353
|
+
finalize(result: RecordingResult): Promise<RecordingResult>;
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Collector that runs the JS Self-Profiling API across a recording and, on
|
|
357
|
+
* finalize, attributes each long task to the developer's own hot functions —
|
|
358
|
+
* something LoAF can't do for React-delegated events (it only sees React's
|
|
359
|
+
* single root dispatcher).
|
|
360
|
+
*
|
|
361
|
+
* It reports `kind: 'long-task'` because it enriches that signal rather than
|
|
362
|
+
* emitting its own. Requires Chromium + a `Document-Policy: js-profiling`
|
|
363
|
+
* response header (the dev plugins inject it); degrades to a no-op otherwise.
|
|
364
|
+
*/
|
|
365
|
+
declare function createSelfProfilingCollector(): SelfProfilingCollector;
|
|
366
|
+
|
|
367
|
+
export { type Collector, type CollectorKind, type CreateSourceMapResolverOptions, type FetchMap, type ForcedReflowSignal, type FpsSample, type FrameCollector, type FrameStats, type HeapCollector, type HeapSample, type HeapTrend, type HeapTrendClass, type InteractionCollector, type InteractionSignal, type LayoutShiftSignal, type LongTaskAttribution, type LongTaskScript, type LongTaskSignal, type NetworkSignal, type ProfilerFrame, type ProfilerSample, type ProfilerStack, type ProfilerTrace, type Recorder, type RecordingResult, type RenderReason, type RenderSignal, type Signal, type SignalKind, type SourceMapResolver, type StackFrame, type WebVitalSignal, analyzeFrames, analyzeHeapTrend, attachLazyStack, attributeLongTaskSignals, attributeWindow, createForcedReflowCollector, createFrameCollector, createHeapCollector, createInteractionCollector, createLayoutShiftCollector, createLongTasksCollector, createNetworkCollector, createRecorder, createSelfProfilingCollector, createSourceMapResolver, createWebVitalsCollector, isUserResource, parseStack, resolveFrame };
|