Skip to content

feat(scan): add react-scan/lite headless instrumentation entry - #435

Merged
aidenybai merged 2 commits into
mainfrom
new-verr
May 1, 2026
Merged

aidenybai merged 2 commits into
mainfrom
new-verr

Conversation

@aidenybai

@aidenybai aidenybai commented May 1, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds react-scan/lite, a tiny UI-less entry point that taps into the same React DevTools profiling channel the Timeline Profiler uses. Pairs naturally with a long-animation-frame PerformanceObserver so an agent can attribute a slow LoAF to a specific component subtree.

import { instrument } from "react-scan/lite";

const handle = instrument({
  onEvent: (event) => console.log(event),
  endpoint: "http://127.0.0.1:54321/ingest/abc123",
  sessionId: "abc123",

  recordChangeDescriptions: true, // why did this re-render?
  includeFiberSource: true,       // file:line of each JSX call site
  includeFiberIdentity: true,     // stable id across commits
});

handle.subscribe((event) => {
  if (event.kind === "commit") {
    // event.tree[] = per-fiber { name, fiberId, depth, actualDuration,
    //                            source, ownerName, changeDescription }
    // event.priorityName = "UserBlocking" | "Normal" | ...
    // event.didError = true if this commit hit an error boundary
  }
  if (event.kind === "profiling-hooks-status" && !event.available) {
    // R19.2+ prod or non-__PROFILE__ build: fall back to LoAF-only attribution
  }
});

handle.stop(); // idempotent, restores previous hook handlers

What's in the box

  • ./lite package export — dist/lite/index.{js,mjs,d.ts,d.mts}.
  • bippy primitives throughout — uses getRDTHook, instrument, getDisplayName, getFiberId, traverseProps/State/Contexts, hasDebugSource, hasDebugStack, formatOwnerStack, parseStack, isRealReactDevtools. Re-exports Fiber, BundleType, Lanes, FiberSource directly from bippy.
  • 5 enrichment options:
    • recordChangeDescriptions — { isFirstMount, props[], state, context, hooks[], parent } per fiber, ported from React DevTools' getChangeDescription.
    • includeFiberSource — { source, ownerName } from _debugSource (R16/17/18) or _debugStack (R19+), sync-only.
    • includeFiberIdentity — alternate-aware monotonic fiberId via bippy's getFiberId.
    • includeLaneLabels (default on) — translates lanes bitmask to ["SyncLane", "DefaultLane"] and priorityLevel to "UserBlocking".
    • profiling-hooks-status event — emits { available, reason, error?, reactVersion, bundleType } so an agent knows when mark* events won't fire instead of silently concluding "idle".
  • Endpoint POST mode — every event POSTed to a debug-agent-style ingest endpoint with keepalive: true. URL validated at instrument() time.
  • SSR-safe — instrument() returns a noop handle in Node; no window/document/fetch/navigator access.
  • Coexists with React DevTools — detects via bippy's isRealReactDevtools and warns once that injectProfilingHooks is a hard replace.

Bippy bump

^0.5.30 → ^0.5.39. Required for bippy/source subpath exports and the traverseProps/State/Contexts helpers used by the change-description port.

Tsconfig change

packages/scan/tsconfig.json now sets "module": "ESNext" + "moduleResolution": "bundler". Required to resolve bippy's ./source subpath export. Side benefit: fixes pre-existing Cannot find namespace 'JSX' errors in web/components/copy-to-clipboard/index.tsx and web/views/notifications/collapsed-event.tsx.

Build pipeline

tsup.config.ts addDirectivesToChunkFiles now runs against dist/, dist/lite/, and dist/core/. Confirmed 'use client' lands on dist/lite/index.{js,mjs} and does NOT land on dist/react-component-name/* (those are bundler plugins).

README

Removed the two stale "monitor issues in production / React Scan Monitoring" callouts. Added a react-scan/lite: headless instrumentation section with the options table and the react-dom/profiling opt-in for production attribution.

Test plan

  • pnpm test src/lite/lite.test.ts — 43 tests pass:
    • 4 SSR safety (in-process)
    • 31 happy path (with stubbed window + fake DevTools hook)
    • 2 SSR safety (built CJS in node -e)
    • 2 SSR safety (built ESM in node -e)
    • covers: emit on commit, subscribe/unsubscribe, stop restores hook, stop/instrument cycle leak check, idempotent stop, singleton, maxFibersPerCommit, minFiberActualDurationMs, warn on endpoint-without-sessionId, profiling-hooks-status (no-method/threw/opted-out), lane label translation, priorityName, fiberId stability, changeDescription (isFirstMount + parent cascade + context change + class state + hook state), source + ownerName, fiber-source null fallback, priorityName without getLaneLabelMap, TDZ regression, chain forwarding, didError capture, error message capture, includeFiberTree: false warning, invalid endpoint URL warning, emit fast-path, cascade rejects zero-duration ancestors, double-attach prevention, stop from inside listener
  • pnpm typecheck — 0 errors
  • pnpm exec oxlint src/lite — 0 warnings, 0 errors
  • pnpm build — dist/lite/index.{js,mjs,d.ts,d.mts} generated with 'use client' directive

Note

Medium Risk
Adds a new runtime instrumentation entry point that patches the React DevTools global hook and can optionally POST profiling data to an endpoint, which could affect app behavior/perf or interfere with DevTools if misused. Changes also touch the build/TS config and dependency versions, so packaging/compatibility regressions are possible.

Overview
Introduces react-scan/lite, a new headless instrumentation export that attaches to the React DevTools profiling channel to emit commit/render/update events, optionally walking the fiber tree and enriching it with change attribution, source/owner info, stable fiber IDs, lane/priority labels, and didError.

Adds an event emitter with subscribe() and optional fetch POST ingest (with one-time endpoint URL validation), plus lifecycle handling (stop() restores prior hook handlers) and SSR-safe no-op behavior. Updates packaging/build config to ship the new ./lite export (tsup entry + 'use client' directive handling), bumps bippy, adjusts TS module resolution for bippy/source, and documents lite usage in the README with a comprehensive new test suite for the module.

Reviewed by Cursor Bugbot for commit c398c10. Bugbot is set up for automated code reviews on this repo. Configure here.

A tiny, UI-less entry point that taps into the same React DevTools
profiling channel the Timeline Profiler uses. Streams commit / render /
state-update events to a callback or POST endpoint, with optional
per-fiber enrichment (changeDescription, source, fiberId, lane labels).
Built on bippy primitives throughout.

- New `react-scan/lite` export
- Bumps bippy ^0.5.30 -> ^0.5.39 (uses traverseProps/State/Contexts,
  getFiberId, hasDebugSource, hasDebugStack, formatOwnerStack,
  parseStack, isRealReactDevtools, getRDTHook)
- SSR-safe: instrument() returns a noop handle in Node
- Emits profiling-hooks-status so agents know when mark* events
  won't fire (R19.2+ prod, non-__PROFILE__ builds)
- Captures didError from React's onCommitFiberRoot 4th arg
- Validates http(s) endpoint URL at instrument() time
- 'use client' directive added to dist/lite/* and dist/core/*
- 43 tests covering SSR, happy path, change-description, source,
  fiber identity, lane labels, chain forwarding, stop()/instrument()
  cycles, opt-out paths

Tsconfig moduleResolution bumped to "bundler" to resolve bippy/source
subpath; this also fixes pre-existing JSX namespace errors in
web/components/copy-to-clipboard and web/views/notifications.
@vercel

vercel Bot commented May 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
react-scan Skipped Skipped May 1, 2026 10:59am

@pkg-pr-new

pkg-pr-new Bot commented May 1, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/react-scan@435

commit: c398c10

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit cb602b6. Configure here.

markRenderStarted: (lanes) => emitter.emit('render-start', { lanes }),
markRenderYielded: () => emitter.emit('render-yield'),
markRenderStopped: () => emitter.emit('render-stop'),
markRenderScheduled: (lane) => emitter.emit('render-scheduled', { lanes: lane }),

@vercel vercel Bot May 1, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The markRenderScheduled function has inconsistent parameter naming using singular lane instead of plural lanes like similar methods in the same file

Fix on Vercel

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disagree — leaving as lane (singular). markRenderScheduled, markStateUpdateScheduled, and markForceUpdateScheduled all receive a single just-scheduled lane from React's reconciler, not a bitmask. Compare to markRenderStarted(lanes) / markCommitStarted(lanes) which DO receive the full bitmask of lanes being rendered. The naming distinguishes API contracts. Bippy types both as Lanes (numeric alias) but the semantic distinction is real.

Bugbot caught: `isValidEndpointUrl()` only logged a warning but the
invalid endpoint was still forwarded to `createEmitter`, so
`canPostToEndpoint = Boolean(endpoint && sessionId)` evaluated true
and every emit fired `fetch()` to e.g. `javascript:alert(1)` which
failed silently per-event. Now we set `effectiveEndpoint = undefined`
on validation failure before constructing the emitter.

Adds a regression test that stubs `globalThis.fetch` and asserts no
calls happen on commit when the endpoint is invalid.
@aidenybai
aidenybai merged commit 17fd4cb into main May 1, 2026
6 checks passed
@aidenybai
aidenybai deleted the new-verr branch May 1, 2026 12:17
hunixcode pushed a commit to hunixcode/react-scan that referenced this pull request Jul 3, 2026

This branch was previously deployed

1 inactive deployment
Preview — c398c10b Deployed May 1, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant