diff --git a/packages/scan/README.md b/packages/scan/README.md index 3e2514be..acab85a7 100644 --- a/packages/scan/README.md +++ b/packages/scan/README.md @@ -22,9 +22,6 @@ Airbnb       [!IMPORTANT] -> Want to monitor issues in production? Check out [React Scan Monitoring](https://react-scan.com/monitoring)! - ## Install ### Package managers @@ -89,6 +86,62 @@ If you want to install the extension, follow the guide [here](https://github.com See [discussion](https://github.com/aidenybai/react-scan/pull/23) +## `react-scan/lite`: headless instrumentation + +A tiny, UI-less entry point that taps into the same React DevTools profiling channel the Timeline Profiler uses. No toolbar, no canvas, no styles. Just a stream of commit / render / state-update events you can pipe to a callback or POST to an endpoint. Pairs naturally with a `long-animation-frame` `PerformanceObserver` so you can attribute a slow LoAF to a specific component subtree. + +```ts +import { instrument } from "react-scan/lite"; + +const handle = instrument({ + onEvent: (event) => console.log(event), + + // optional: POST every event to an ingest endpoint + endpoint: "http://127.0.0.1:54321/ingest/abc123", + sessionId: "abc123", + + // optional: enrich each fiber summary + recordChangeDescriptions: true, // why did this re-render? (props/state/context/hooks/parent) + includeFiberSource: true, // file:line of each fiber's JSX call site + includeFiberIdentity: true, // stable id across commits, for cascade histograms +}); + +handle.subscribe((event) => { + if (event.kind === "commit") { + // event.tree[] = per-fiber { name, fiberId, depth, actualDuration, + // source, ownerName, changeDescription } + // event.priorityName = "UserBlocking" | "Normal" | ... + } + if (event.kind === "profiling-hooks-status" && !event.available) { + // React 19.2+ prod or non-__PROFILE__ build: mark* hooks won't fire. + // Fall back to LoAF-only attribution. + } +}); + +handle.stop(); // idempotent +``` + +`instrument` must run before `react-dom` mounts (top of your entry, or as the first script in ``). It's SSR-safe: calling `instrument()` in Node returns a noop handle whose `isActive()` is `false`. + +### Per-fiber enrichment + +| Option | Default | What you get | +| ---------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------- | +| `recordChangeDescriptions` | `false` | `changeDescription: { isFirstMount, props[], state, context, hooks[], parent }` per fiber. Answers "why this re-rendered" in a single event. | +| `includeFiberSource` | `false` | `source: { fileName, lineNumber, columnNumber }` + `ownerName`, read from `_debugSource` (R16/17/18) or `_debugStack` (R19+). Sync, no symbolication. | +| `includeFiberIdentity` | `false` | `fiberId: number`, stable monotonic id per logical fiber (alternate-aware), so the agent can build cross-commit histograms. | +| `includeLaneLabels` | `true` | `laneLabels: string[]` (translated via `renderer.getLaneLabelMap()`) and `priorityName` (e.g. `"UserBlocking"`) | +| `maxFibersPerCommit` | `5000` | Cap on tree size per commit to bound payload size | +| `minFiberActualDurationMs` | `0` | Skip fibers below this threshold | + +### Build profile + +`actualDuration` and the `mark*` profiling hooks only populate in `__PROFILE__` builds. In development that's the default; in production you can opt in by aliasing `react-dom` to `react-dom/profiling` in your bundler (`resolve.alias` in webpack/vite). Otherwise `onCommitFiberRoot` still fires but every fiber's `actualDuration` is `0`. The `profiling-hooks-status` event makes this explicit: `available: false` with `reason: "no-inject-method"` means React 19.2+ in prod or a non-`__PROFILE__` build, so the agent should fall back to LoAF-only attribution rather than concluding "idle". + +### Coexistence with React DevTools + +If React DevTools is also attached, `instrument()` logs a one-time warning: the `injectProfilingHooks` channel is a hard replace, so DevTools' Timeline Profiler stops receiving events while this instrumentation is active. Call `handle.stop()` to restore. + ## API Reference
@@ -183,8 +236,6 @@ This often comes down to props that update in reference, like callbacks or objec React Scan helps you identify these issues by automatically detecting and highlighting renders that cause performance issues. Now, instead of guessing, you can see exactly which components you need to fix. -> Want monitor issues in production? Check out [React Scan Monitoring](https://react-scan.com/monitoring)! - ### FAQ **Q: Why this instead of React Devtools?** diff --git a/packages/scan/package.json b/packages/scan/package.json index a8d26eac..a94f1356 100644 --- a/packages/scan/package.json +++ b/packages/scan/package.json @@ -88,6 +88,11 @@ "import": "./dist/install-hook.mjs", "require": "./dist/install-hook.js" }, + "./lite": { + "types": "./dist/lite/index.d.ts", + "import": "./dist/lite/index.mjs", + "require": "./dist/lite/index.js" + }, "./auto": { "production": { "import": { @@ -206,7 +211,7 @@ "@preact/signals": "^1.3.1", "@rollup/pluginutils": "^5.1.3", "@types/node": "^20.17.9", - "bippy": "^0.5.30", + "bippy": "^0.5.39", "commander": "^14.0.0", "estree-walker": "^3.0.3", "picocolors": "^1.1.1", diff --git a/packages/scan/src/lite/change-description.ts b/packages/scan/src/lite/change-description.ts new file mode 100644 index 00000000..0e8d3b97 --- /dev/null +++ b/packages/scan/src/lite/change-description.ts @@ -0,0 +1,155 @@ +import { + ClassComponentTag, + type Fiber, + ForwardRefTag, + FunctionComponentTag, + MemoComponentTag, + SimpleMemoComponentTag, + traverseContexts, + traverseProps, + traverseState, +} from 'bippy'; +import type { ChangeDescription } from './types'; + +const objectIs = Object.is; + +export const isCompositeTag = (tag: number): boolean => + tag === FunctionComponentTag || + tag === ClassComponentTag || + tag === ForwardRefTag || + tag === MemoComponentTag || + tag === SimpleMemoComponentTag; + +const collectChangedProps = (fiber: Fiber): Array => { + // Precondition: caller must have already handled the mount path. Bippy's + // `traverseProps` falls back to `prev = {}` when `fiber.alternate` is null, + // which would mark every prop as "changed". `getChangeDescription` short- + // circuits to `isFirstMount: true` before calling us; we mirror the guard + // defensively in case anyone reuses this helper standalone. + if (fiber.alternate === null) return []; + const changed: Array = []; + traverseProps(fiber, (propName, nextValue, prevValue) => { + if (!objectIs(prevValue, nextValue)) changed.push(propName); + }); + return changed; +}; + +const didAnyContextChange = (fiber: Fiber): boolean => { + let changed = false; + traverseContexts(fiber, (nextContext, prevContext) => { + if (!nextContext || !prevContext) return; + // Order swap means a non-context change caused the rerender; bail. + if (nextContext.context !== prevContext.context) { + changed = false; + return true; + } + if (!objectIs(prevContext.memoizedValue, nextContext.memoizedValue)) { + changed = true; + return true; + } + }); + return changed; +}; + +const didAnyClassStateChange = (fiber: Fiber): boolean => { + // For class components, memoizedState is a single state object (not a Hook + // chain), so traverseState only yields one node. Compare keys shallowly. + const previousState = fiber.alternate?.memoizedState; + const nextState = fiber.memoizedState; + if ( + !previousState || + !nextState || + typeof previousState !== 'object' || + typeof nextState !== 'object' + ) { + return previousState !== nextState; + } + const previousObject = previousState as Record; + const nextObject = nextState as Record; + const allKeys = new Set([ + ...Object.keys(previousObject), + ...Object.keys(nextObject), + ]); + for (const key of allKeys) { + if (!objectIs(previousObject[key], nextObject[key])) return true; + } + return false; +}; + +/** + * Walks the Hook linked list on `fiber.memoizedState` and returns the indices + * of hooks whose `memoizedState` changed by reference. Bippy's `traverseState` + * iterates both fibers' Hook chains in parallel. + * + * APPROXIMATE: this conflates `useState` value changes with `useMemo` / + * `useCallback` / `useEffect` deps changes (they share the same slot). + * DevTools uses `react-debug-tools.inspectHooks` for precise attribution; we + * deliberately skip that; bippy ships it as `inspectHooks` from `bippy/source` + * if a caller wants the exact answer. + */ +const collectChangedHookIndices = (fiber: Fiber): Array => { + const indices: Array = []; + let index = 0; + traverseState(fiber, (nextState, prevState) => { + if ( + nextState && + prevState && + !objectIs(prevState.memoizedState, nextState.memoizedState) + ) { + indices.push(index); + } + index++; + }); + return indices; +}; + +/** + * Returns a change description for fibers whose tag we can attribute, or + * `null` for everything else (host nodes, suspense, fragments, etc.). + * + * Ported from react-devtools-shared/src/backend/fiber/renderer.js + * `getChangeDescription`, with bippy's `traverseProps`/`traverseState`/ + * `traverseContexts` doing the heavy lifting. + * + * The `parentRendered` flag is computed by the caller (the fiber walker) + * which already traverses the tree top-down; re-walking `fiber.return` + * here would be O(depth) per fiber and pointless. + */ +export const getChangeDescription = ( + fiber: Fiber, + parentRendered: boolean, +): ChangeDescription | null => { + const tag = fiber.tag; + if (!isCompositeTag(tag)) return null; + + if (fiber.alternate === null) { + return { + isFirstMount: true, + props: null, + state: false, + context: false, + hooks: [], + parent: false, + }; + } + + if (tag === ClassComponentTag) { + return { + isFirstMount: false, + props: collectChangedProps(fiber), + state: didAnyClassStateChange(fiber), + context: didAnyContextChange(fiber), + hooks: [], + parent: parentRendered, + }; + } + + return { + isFirstMount: false, + props: collectChangedProps(fiber), + state: false, + context: didAnyContextChange(fiber), + hooks: collectChangedHookIndices(fiber), + parent: parentRendered, + }; +}; diff --git a/packages/scan/src/lite/constants.ts b/packages/scan/src/lite/constants.ts new file mode 100644 index 00000000..5b838e01 --- /dev/null +++ b/packages/scan/src/lite/constants.ts @@ -0,0 +1,18 @@ +export const DEFAULT_LOCATION = 'ReactScanLite'; +export const DEFAULT_MAX_FIBERS_PER_COMMIT = 5000; +export const DEFAULT_MIN_FIBER_ACTUAL_DURATION_MS = 0; + +// Total number of React fiber lanes. Lanes are encoded as a 31-bit bitmask; +// each bit represents one scheduling lane. Bumped in 18.x but stable since. +export const REACT_TOTAL_NUM_LANES = 31; + +// Scheduler priority levels. Source: +// https://github.com/facebook/react/blob/main/packages/scheduler/src/SchedulerPriorities.js +export const SCHEDULER_PRIORITY_NAMES: Record = { + 0: 'NoPriority', + 1: 'Immediate', + 2: 'UserBlocking', + 3: 'Normal', + 4: 'Low', + 5: 'Idle', +}; diff --git a/packages/scan/src/lite/create-emitter.ts b/packages/scan/src/lite/create-emitter.ts new file mode 100644 index 00000000..7b420452 --- /dev/null +++ b/packages/scan/src/lite/create-emitter.ts @@ -0,0 +1,106 @@ +import { DEFAULT_LOCATION } from './constants'; +import type { LaneLabelTranslator } from './lane-labels'; +import type { LiteEvent, LiteEventKind, LiteOptions } from './types'; + +/** + * Surface used inside the lite module's hot path (event emission, listener + * management). Does NOT include lifecycle controls like + * `setLaneLabelTranslator` / `dispose` — those are returned separately so + * downstream callers (e.g. profiling-hook closures) can't accidentally + * tear down the emitter from inside an event handler. + */ +export interface Emitter { + emit: (kind: LiteEventKind, partial?: Partial) => void; + subscribe: (listener: (event: LiteEvent) => void) => () => void; +} + +/** + * Returned alongside the `emitter` to its sole owner (`instrument()`). + * Holds the controls that must NOT leak into the per-event hot path. + */ +export interface EmitterControl { + setLaneLabelTranslator: (translator: LaneLabelTranslator | null) => void; + dispose: () => void; +} + +export const createEmitter = ( + options: LiteOptions, +): { emitter: Emitter; control: EmitterControl } => { + const listeners = new Set<(event: LiteEvent) => void>(); + if (options.onEvent) listeners.add(options.onEvent); + + const endpoint = options.endpoint; + const sessionId = options.sessionId; + const locationPrefix = options.location ?? DEFAULT_LOCATION; + const canPostToEndpoint = Boolean(endpoint && sessionId); + let isActive = true; + let translator: LaneLabelTranslator | null = null; + + const emit = (kind: LiteEventKind, partial?: Partial): void => { + if (!isActive) return; + // Cheap fast-path: if nobody is listening AND we have no endpoint to + // POST to, skip the timestamp call, the event allocation, and the + // translator work entirely. Common when a consumer creates a handle + // but never calls `subscribe()` / passes `onEvent` / sets `endpoint`. + if (listeners.size === 0 && !canPostToEndpoint) return; + const timestamp = performance.now(); + const event: LiteEvent = { + kind, + timestamp, + ...partial, + }; + if (translator) { + if (event.lanes != null && event.laneLabels === undefined) { + const labels = translator.laneLabels(event.lanes); + if (labels) event.laneLabels = labels; + } + if (event.priorityLevel != null && event.priorityName === undefined) { + const name = translator.priorityName(event.priorityLevel); + if (name) event.priorityName = name; + } + } + for (const listener of listeners) { + try { + listener(event); + } catch {} + } + if (canPostToEndpoint) { + try { + fetch(endpoint as string, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + sessionId, + location: `${locationPrefix}:${kind}`, + message: kind, + data: event, + timestamp, + }), + keepalive: true, + }).catch(() => {}); + } catch {} + } + }; + + const subscribe = (listener: (event: LiteEvent) => void): (() => void) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }; + + const setLaneLabelTranslator = (next: LaneLabelTranslator | null): void => { + translator = next; + }; + + const dispose = (): void => { + isActive = false; + listeners.clear(); + translator = null; + }; + + return { + emitter: { emit, subscribe }, + control: { setLaneLabelTranslator, dispose }, + }; +}; diff --git a/packages/scan/src/lite/create-profiling-hooks.ts b/packages/scan/src/lite/create-profiling-hooks.ts new file mode 100644 index 00000000..ca4a642c --- /dev/null +++ b/packages/scan/src/lite/create-profiling-hooks.ts @@ -0,0 +1,67 @@ +import { type Fiber, getDisplayName } from 'bippy'; +import type { Emitter } from './create-emitter'; +import type { ProfilingHooks } from './types'; + +const componentNameOf = (fiber: Fiber): string => + getDisplayName(fiber.type) ?? 'Anonymous'; + +export const createProfilingHooks = (emitter: Emitter): ProfilingHooks => ({ + markCommitStarted: (lanes) => emitter.emit('commit-start', { lanes }), + markCommitStopped: () => emitter.emit('commit-stop'), + 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 }), + markLayoutEffectsStarted: (lanes) => emitter.emit('layout-effects-start', { lanes }), + markLayoutEffectsStopped: () => emitter.emit('layout-effects-stop'), + markPassiveEffectsStarted: (lanes) => + emitter.emit('passive-effects-start', { lanes }), + markPassiveEffectsStopped: () => emitter.emit('passive-effects-stop'), + markComponentRenderStarted: (fiber) => + emitter.emit('component-render-start', { componentName: componentNameOf(fiber) }), + markComponentRenderStopped: () => emitter.emit('component-render-stop'), + markComponentLayoutEffectMountStarted: (fiber) => + emitter.emit('component-layout-effect-mount-start', { + componentName: componentNameOf(fiber), + }), + markComponentLayoutEffectMountStopped: () => + emitter.emit('component-layout-effect-mount-stop'), + markComponentLayoutEffectUnmountStarted: (fiber) => + emitter.emit('component-layout-effect-unmount-start', { + componentName: componentNameOf(fiber), + }), + markComponentLayoutEffectUnmountStopped: () => + emitter.emit('component-layout-effect-unmount-stop'), + markComponentPassiveEffectMountStarted: (fiber) => + emitter.emit('component-passive-effect-mount-start', { + componentName: componentNameOf(fiber), + }), + markComponentPassiveEffectMountStopped: () => + emitter.emit('component-passive-effect-mount-stop'), + markComponentPassiveEffectUnmountStarted: (fiber) => + emitter.emit('component-passive-effect-unmount-start', { + componentName: componentNameOf(fiber), + }), + markComponentPassiveEffectUnmountStopped: () => + emitter.emit('component-passive-effect-unmount-stop'), + markStateUpdateScheduled: (fiber, lane) => + emitter.emit('state-update', { componentName: componentNameOf(fiber), lanes: lane }), + markForceUpdateScheduled: (fiber, lane) => + emitter.emit('force-update', { componentName: componentNameOf(fiber), lanes: lane }), + markComponentSuspended: (fiber, _wakeable, lanes) => + emitter.emit('component-suspended', { + componentName: componentNameOf(fiber), + lanes, + }), + markComponentErrored: (fiber, thrownValue, lanes) => { + const message = + thrownValue && typeof thrownValue === 'object' && 'message' in thrownValue + ? String((thrownValue as { message: unknown }).message) + : String(thrownValue); + emitter.emit('component-errored', { + componentName: componentNameOf(fiber), + lanes, + message, + }); + }, +}); diff --git a/packages/scan/src/lite/fiber-source.ts b/packages/scan/src/lite/fiber-source.ts new file mode 100644 index 00000000..09ef6b25 --- /dev/null +++ b/packages/scan/src/lite/fiber-source.ts @@ -0,0 +1,70 @@ +import { type Fiber, getDisplayName } from 'bippy'; +import { + type FiberSource, + formatOwnerStack, + hasDebugSource, + hasDebugStack, + parseStack, +} from 'bippy/source'; + +/** + * Synchronous source extraction. We deliberately avoid `bippy/source`'s + * async `getSource` because it walks the owner stack and source-map + * symbolicates over the network. Way too heavy for per-commit walking. + * + * Resolution order: + * 1. `_debugSource` (React 16/17/18 dev builds): a plain object. + * 2. `_debugStack` (React 19+ dev builds): an `Error` whose stack we + * format and parse. The first frame is the JSX call site of this + * element. Bundled URLs only; callers must symbolicate offline. + */ +export const getFiberSource = (fiber: Fiber): FiberSource | null => { + // `hasDebugSource` narrows `_debugSource` to NonNullable, so direct access + // is safe. Same for `_debugStack` via `hasDebugStack`. Both guards live in + // `bippy/source` because the underlying fields are version-dependent and + // bippy is the canonical place to know what shape they take. + // + // ASSUMPTION: bippy's guards are tight — `hasDebugSource(fiber) === true` + // implies `fiber._debugSource.fileName` is a `string` and `lineNumber` is + // a `number` (verified in bippy 0.5.39). If a future bippy loosens this + // (e.g. narrows to `fileName?: string`), the resulting `FiberSource` would + // violate `bippy/source`'s `FiberSource.fileName: string` contract. Re-check + // this file when bumping bippy. + if (hasDebugSource(fiber)) { + return { + fileName: fiber._debugSource.fileName, + lineNumber: fiber._debugSource.lineNumber, + columnNumber: fiber._debugSource.columnNumber, + }; + } + + if (hasDebugStack(fiber)) { + try { + const ownerStack = formatOwnerStack(fiber._debugStack.stack); + if (ownerStack) { + const firstFrame = parseStack(ownerStack)[0]; + if (firstFrame?.fileName) { + return { + fileName: firstFrame.fileName, + lineNumber: firstFrame.lineNumber, + columnNumber: firstFrame.columnNumber, + functionName: firstFrame.functionName, + }; + } + } + } catch {} + } + + return null; +}; + +/** + * Display name of `_debugOwner.type`: the parent component that rendered + * this one in JSX, not the parent in the fiber tree (those differ when an + * element is created in one component and rendered as a child of another). + */ +export const getOwnerName = (fiber: Fiber): string | null => { + const owner = fiber._debugOwner; + if (!owner) return null; + return getDisplayName(owner.type); +}; diff --git a/packages/scan/src/lite/index.ts b/packages/scan/src/lite/index.ts new file mode 100644 index 00000000..6ab91159 --- /dev/null +++ b/packages/scan/src/lite/index.ts @@ -0,0 +1,312 @@ +import { + type ReactDevToolsGlobalHook, + type ReactRenderer, + getRDTHook, + isRealReactDevtools, +} from 'bippy'; +import type { SchedulerPriorityLevel } from './types'; +import { + DEFAULT_MAX_FIBERS_PER_COMMIT, + DEFAULT_MIN_FIBER_ACTUAL_DURATION_MS, +} from './constants'; +import { createEmitter } from './create-emitter'; +import { createProfilingHooks } from './create-profiling-hooks'; +import { createLaneLabelTranslator } from './lane-labels'; +import type { + LiteHandle, + LiteOptions, + ProfilingHooks, + ReactRendererWithProfiling, +} from './types'; +import { walkFiber } from './walk-fiber'; + +const noopHandle: LiteHandle = { + stop: () => {}, + isActive: () => false, + subscribe: () => () => {}, +}; + +interface ProfilingAttachOutcome { + available: boolean; + reason?: 'no-inject-method' | 'threw' | 'opted-out'; + error?: string; +} + +const errorToMessage = (cause: unknown): string => { + if (cause instanceof Error) return cause.message; + if (typeof cause === 'string') return cause; + try { + return JSON.stringify(cause); + } catch { + return String(cause); + } +}; + +const tryInjectProfilingHooks = ( + renderer: ReactRenderer, + profilingHooks: ProfilingHooks, +): ProfilingAttachOutcome => { + const rendererWithProfiling = renderer as ReactRendererWithProfiling; + if (typeof rendererWithProfiling.injectProfilingHooks !== 'function') { + return { available: false, reason: 'no-inject-method' }; + } + try { + rendererWithProfiling.injectProfilingHooks(profilingHooks); + return { available: true }; + } catch (cause) { + return { available: false, reason: 'threw', error: errorToMessage(cause) }; + } +}; + +const isValidEndpointUrl = (candidate: string): boolean => { + try { + const parsed = new URL(candidate); + return parsed.protocol === 'http:' || parsed.protocol === 'https:'; + } catch { + return false; + } +}; + +export const instrument = (options: LiteOptions = {}): LiteHandle => { + if (typeof window === 'undefined') return noopHandle; + if (window.__REACT_SCAN_LITE__) return window.__REACT_SCAN_LITE__; + + if (options.endpoint && !options.sessionId) { + // oxlint-disable-next-line no-console + console.warn( + '[react-scan/lite] `endpoint` requires `sessionId`; events will not be POSTed.', + ); + } + + // Validate the endpoint URL once at instrument() time and DROP it on failure + // so `createEmitter`'s `canPostToEndpoint` calculation sees the disablement. + // Without this, every emit would `fetch()` to the invalid URL and fail + // silently per-event (caught Bugbot review on PR #435). + let effectiveEndpoint = options.endpoint; + if (effectiveEndpoint && !isValidEndpointUrl(effectiveEndpoint)) { + // oxlint-disable-next-line no-console + console.error( + '[react-scan/lite] `endpoint` is not a valid http(s) URL; events will not be POSTed.', + ); + effectiveEndpoint = undefined; + } + + if ( + options.includeFiberTree === false && + (options.recordChangeDescriptions === true || + options.includeFiberSource === true || + options.includeFiberIdentity === true) + ) { + // oxlint-disable-next-line no-console + console.warn( + '[react-scan/lite] `includeFiberTree: false` disables per-fiber enrichment options (`recordChangeDescriptions`, `includeFiberSource`, `includeFiberIdentity`). Remove `includeFiberTree: false` to enable them.', + ); + } + + const { emitter, control: emitterControl } = createEmitter({ + ...options, + endpoint: effectiveEndpoint, + }); + const profilingHooks = createProfilingHooks(emitter); + const includeFiberTree = options.includeFiberTree !== false; + const includeProfilingHooks = options.includeProfilingHooks !== false; + const includeLaneLabels = options.includeLaneLabels !== false; + const maxFibers = options.maxFibersPerCommit ?? DEFAULT_MAX_FIBERS_PER_COMMIT; + const minActualDurationMs = + options.minFiberActualDurationMs ?? DEFAULT_MIN_FIBER_ACTUAL_DURATION_MS; + const recordChangeDescriptions = options.recordChangeDescriptions === true; + const includeFiberSource = options.includeFiberSource === true; + const includeFiberIdentity = options.includeFiberIdentity === true; + const attachedRenderers = new WeakSet(); + let isStopped = false; + + // Acquire the hook BEFORE defining closures that read it. We deliberately + // do not pass an `onActive` callback to bippy: if a renderer was injected + // before `instrument()` ran, bippy fires `onActive` synchronously inside + // `getRDTHook(...)`, which would hit the `hook` const's TDZ. We instead + // catch existing renderers explicitly via `attachAllExisting()` below, + // and future renderers via our `ourInject` patch. + const hook: ReactDevToolsGlobalHook = getRDTHook(); + + let foundRealLaneLabelMap = false; + const refreshLaneLabelTranslator = (): void => { + if (!includeLaneLabels) return; + if (foundRealLaneLabelMap) return; // cached: a real map never becomes "more real" + const result = createLaneLabelTranslator( + Array.from(hook.renderers.values()) as Array, + ); + emitterControl.setLaneLabelTranslator(result.translator); + if (result.hasLaneLabelMap) foundRealLaneLabelMap = true; + }; + + const attachOneRenderer = (renderer: ReactRenderer): void => { + if (isStopped) return; + if (attachedRenderers.has(renderer)) return; + attachedRenderers.add(renderer); + const outcome: ProfilingAttachOutcome = includeProfilingHooks + ? tryInjectProfilingHooks(renderer, profilingHooks) + : { available: false, reason: 'opted-out' }; + emitter.emit('renderer-injected', { + data: { version: renderer.version, bundleType: renderer.bundleType }, + }); + emitter.emit('profiling-hooks-status', { + available: outcome.available, + reason: outcome.reason, + error: outcome.error, + reactVersion: renderer.version, + bundleType: renderer.bundleType, + }); + refreshLaneLabelTranslator(); + }; + + const attachAllExisting = (): void => { + if (isStopped) return; + for (const renderer of Array.from(hook.renderers.values())) { + attachOneRenderer(renderer); + } + }; + + if (includeProfilingHooks && isRealReactDevtools(hook)) { + // oxlint-disable-next-line no-console + console.warn( + '[react-scan/lite] React DevTools is also attached. Calling injectProfilingHooks replaces its profiling channel; the DevTools Timeline Profiler may stop receiving events while this instrumentation is active.', + ); + } + + const originalInject = hook.inject; + const originalOnCommitFiberRoot = hook.onCommitFiberRoot; + const originalOnPostCommitFiberRoot = hook.onPostCommitFiberRoot; + const originalOnCommitFiberUnmount = hook.onCommitFiberUnmount; + + const ourInject: typeof hook.inject = (renderer) => { + const rendererId = originalInject.call(hook, renderer); + if (!isStopped) attachOneRenderer(renderer); + return rendererId; + }; + + // React's reconciler actually calls `onCommitFiberRoot(rendererID, root, + // schedulerPriority, didError)` with FOUR args. Bippy's type signature + // omits `didError`, so we widen locally to capture it. Verified in + // packages/react-reconciler/src/ReactFiberDevToolsHook.js. + type WidenedOnCommitFiberRoot = ( + rendererId: number, + root: Parameters>[1], + priority?: number, + didError?: boolean, + ) => void; + + const ourOnCommitFiberRoot: WidenedOnCommitFiberRoot = ( + rendererId, + root, + priority, + didError, + ) => { + if (originalOnCommitFiberRoot) { + try { + (originalOnCommitFiberRoot as WidenedOnCommitFiberRoot).call( + hook, + rendererId, + root, + priority, + didError, + ); + } catch {} + } + if (isStopped) return; + const tree = includeFiberTree + ? walkFiber(root.current, { + maxFibers, + minActualDurationMs, + recordChangeDescriptions, + includeFiberSource, + includeFiberIdentity, + isCancelled: () => isStopped, + }) + : undefined; + emitter.emit('commit', { + rendererId, + // HACK: bippy types `priority` as `number | void`. React actually + // passes a Scheduler priority (1-5); narrow to `SchedulerPriorityLevel`. + priorityLevel: priority as SchedulerPriorityLevel | undefined, + didError: didError === true ? true : undefined, + tree, + }); + }; + + const ourOnPostCommitFiberRoot: typeof hook.onPostCommitFiberRoot = ( + rendererId, + root, + ) => { + if (originalOnPostCommitFiberRoot) { + try { + originalOnPostCommitFiberRoot.call(hook, rendererId, root); + } catch {} + } + if (isStopped) return; + emitter.emit('post-commit', { rendererId }); + }; + + const ourOnCommitFiberUnmount: typeof hook.onCommitFiberUnmount = ( + rendererId, + fiber, + ) => { + if (originalOnCommitFiberUnmount) { + try { + originalOnCommitFiberUnmount.call(hook, rendererId, fiber); + } catch {} + } + if (isStopped) return; + emitter.emit('fiber-unmount', { rendererId }); + }; + + hook.inject = ourInject; + hook.onCommitFiberRoot = + ourOnCommitFiberRoot as typeof hook.onCommitFiberRoot; + hook.onPostCommitFiberRoot = ourOnPostCommitFiberRoot; + hook.onCommitFiberUnmount = ourOnCommitFiberUnmount; + + attachAllExisting(); + + const handle: LiteHandle = { + stop: () => { + if (isStopped) return; + isStopped = true; + if (hook.inject === ourInject) hook.inject = originalInject; + if ( + (hook.onCommitFiberRoot as unknown) === (ourOnCommitFiberRoot as unknown) + ) { + hook.onCommitFiberRoot = originalOnCommitFiberRoot; + } + if (hook.onPostCommitFiberRoot === ourOnPostCommitFiberRoot) { + hook.onPostCommitFiberRoot = originalOnPostCommitFiberRoot; + } + if (hook.onCommitFiberUnmount === ourOnCommitFiberUnmount) { + hook.onCommitFiberUnmount = originalOnCommitFiberUnmount; + } + emitterControl.dispose(); + if (window.__REACT_SCAN_LITE__ === handle) { + delete window.__REACT_SCAN_LITE__; + } + }, + isActive: () => !isStopped, + subscribe: (listener) => emitter.subscribe(listener), + }; + + window.__REACT_SCAN_LITE__ = handle; + return handle; +}; + +export type { + BundleType, + ChangeDescription, + Fiber, + FiberSource, + Lanes, + LiteEvent, + LiteEventKind, + LiteFiberSummary, + LiteHandle, + LiteOptions, + ProfilingHooksUnavailableReason, + SchedulerPriorityLevel, +} from './types'; diff --git a/packages/scan/src/lite/lane-labels.ts b/packages/scan/src/lite/lane-labels.ts new file mode 100644 index 00000000..23439f75 --- /dev/null +++ b/packages/scan/src/lite/lane-labels.ts @@ -0,0 +1,79 @@ +import { REACT_TOTAL_NUM_LANES, SCHEDULER_PRIORITY_NAMES } from './constants'; +import type { Lanes, ReactRendererWithProfiling } from './types'; + +export interface LaneLabelTranslator { + laneLabels: (lanes: Lanes | undefined) => Array | undefined; + priorityName: (priorityLevel: number | undefined) => string | undefined; +} + +export interface LaneLabelTranslatorResult { + translator: LaneLabelTranslator; + /** `true` iff a renderer exposed a non-empty `getLaneLabelMap()`. */ + hasLaneLabelMap: boolean; +} + +const noLaneLabels = (): undefined => undefined; + +const priorityNameFromLevel = (priorityLevel: number | undefined): string | undefined => { + if (priorityLevel == null) return undefined; + return SCHEDULER_PRIORITY_NAMES[priorityLevel]; +}; + +/** + * Read the lane→label map from the renderer (cached per attach), and return + * helpers that translate the bitmask + priority level. `priorityName` works + * even when the renderer doesn't expose `getLaneLabelMap` (older React, + * non-DOM renderers): the priority enum is part of the Scheduler package, + * not the lane label map. + * + * Multi-renderer caveat: we take the first non-empty `getLaneLabelMap()` + * we find and use it for ALL renderers' lane bitmasks. In practice every + * renderer that ships with React shares the same lane semantics (they're + * defined in `react-reconciler`), so this is safe. If you mix custom + * renderers with materially different lane assignments, the labels for + * the "loser" renderers' bitmasks may be wrong. + * + * Returns `hasLaneLabelMap: true` iff a real (non-noop) translator was + * built. Callers can use this to skip subsequent rebuild attempts. + */ +export const createLaneLabelTranslator = ( + renderers: Iterable, +): LaneLabelTranslatorResult => { + let laneToLabel: Map | null = null; + for (const renderer of renderers) { + if (typeof renderer.getLaneLabelMap !== 'function') continue; + try { + const map = renderer.getLaneLabelMap(); + if (map && map.size > 0) { + laneToLabel = map; + break; + } + } catch {} + } + if (!laneToLabel) { + return { + translator: { laneLabels: noLaneLabels, priorityName: priorityNameFromLevel }, + hasLaneLabelMap: false, + }; + } + const resolvedMap = laneToLabel; + + const laneLabels = (lanes: Lanes | undefined): Array | undefined => { + if (lanes == null || lanes === 0) return undefined; + const labels: Array = []; + let lane = 1; + for (let index = 0; index < REACT_TOTAL_NUM_LANES; index++) { + if (lane & lanes) { + const label = resolvedMap.get(lane); + if (label) labels.push(label); + } + lane *= 2; + } + return labels.length > 0 ? labels : undefined; + }; + + return { + translator: { laneLabels, priorityName: priorityNameFromLevel }, + hasLaneLabelMap: true, + }; +}; diff --git a/packages/scan/src/lite/lite.test.ts b/packages/scan/src/lite/lite.test.ts new file mode 100644 index 00000000..f6ba24e0 --- /dev/null +++ b/packages/scan/src/lite/lite.test.ts @@ -0,0 +1,1148 @@ +import { execFileSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { instrument } from './index'; +import type { LiteEvent } from './types'; + +// HACK: vitest runs from the package root; relying on process.cwd() avoids +// import.meta (which requires module: esnext in tsconfig). +const SCAN_PACKAGE_DIR = process.cwd(); + +const CJS_DIST = path.join(SCAN_PACKAGE_DIR, 'dist', 'lite', 'index.js'); +const ESM_DIST = path.join(SCAN_PACKAGE_DIR, 'dist', 'lite', 'index.mjs'); + +const runInNode = (code: string): string => + execFileSync('node', ['-e', code], { + cwd: SCAN_PACKAGE_DIR, + encoding: 'utf-8', + timeout: 10_000, + }).trim(); + +const stashGlobal = (key: string): { restore: () => void } => { + const previousDescriptor = Object.getOwnPropertyDescriptor(globalThis, key); + return { + restore: () => { + try { + if (previousDescriptor) { + Object.defineProperty(globalThis, key, previousDescriptor); + } else { + delete (globalThis as Record)[key]; + } + } catch {} + }, + }; +}; + +const withDeletedWindow = (fn: () => T): T => { + const stash = stashGlobal('window'); + delete (globalThis as { window?: unknown }).window; + try { + return fn(); + } finally { + stash.restore(); + } +}; + +describe('react-scan/lite SSR safety (in-process)', () => { + it('returns a noop handle when window is undefined', () => { + withDeletedWindow(() => { + const handle = instrument({ + endpoint: 'http://example.test/ingest', + sessionId: 'abc', + }); + expect(handle.isActive()).toBe(false); + expect(typeof handle.stop).toBe('function'); + expect(typeof handle.subscribe).toBe('function'); + }); + }); + + it('all noop handle methods are callable without throwing', () => { + withDeletedWindow(() => { + const handle = instrument({ onEvent: () => {} }); + const unsubscribe = handle.subscribe(() => {}); + expect(() => unsubscribe()).not.toThrow(); + expect(() => handle.stop()).not.toThrow(); + expect(() => handle.stop()).not.toThrow(); + expect(handle.isActive()).toBe(false); + }); + }); + + it('multiple instrument() calls in SSR all return noop handles', () => { + withDeletedWindow(() => { + const a = instrument(); + const b = instrument({ endpoint: 'http://example.test', sessionId: 'x' }); + const c = instrument(); + expect(a.isActive()).toBe(false); + expect(b.isActive()).toBe(false); + expect(c.isActive()).toBe(false); + }); + }); + + it('does not touch document, fetch, navigator, or XMLHttpRequest', () => { + const guards = ['document', 'fetch', 'navigator', 'XMLHttpRequest'] as const; + const stashes = guards.map((name) => stashGlobal(name)); + for (const name of guards) { + Object.defineProperty(globalThis, name, { + configurable: true, + get: () => { + throw new Error(`unexpected access to ${name}`); + }, + }); + } + try { + withDeletedWindow(() => { + const handle = instrument({ + endpoint: 'http://example.test', + sessionId: 'abc', + onEvent: () => {}, + }); + handle.subscribe(() => {})(); + handle.stop(); + expect(handle.isActive()).toBe(false); + }); + } finally { + for (const stash of stashes) stash.restore(); + } + }); +}); + +describe('react-scan/lite happy path (with stubbed window + hook)', () => { + let stashedWindow: { restore: () => void }; + let stashedHook: { restore: () => void }; + let stashedReactScanLite: { restore: () => void }; + let fakeHook: { + renderers: Map; + supportsFiber: boolean; + supportsFlight: boolean; + inject: (renderer: unknown) => number; + onCommitFiberRoot: ((id: number, root: unknown, priority?: number) => void) | undefined; + onPostCommitFiberRoot: ((id: number, root: unknown) => void) | undefined; + onCommitFiberUnmount: ((id: number, fiber: unknown) => void) | undefined; + [key: string]: unknown; + }; + + const noopFn = (): void => {}; + + beforeEach(() => { + stashedWindow = stashGlobal('window'); + stashedHook = stashGlobal('__REACT_DEVTOOLS_GLOBAL_HOOK__'); + stashedReactScanLite = stashGlobal('__REACT_SCAN_LITE__'); + (globalThis as { window?: unknown }).window = globalThis; + fakeHook = { + renderers: new Map(), + supportsFiber: true, + supportsFlight: true, + inject: () => 1, + onCommitFiberRoot: noopFn, + onPostCommitFiberRoot: noopFn, + onCommitFiberUnmount: noopFn, + }; + (globalThis as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: unknown }).__REACT_DEVTOOLS_GLOBAL_HOOK__ = + fakeHook; + }); + + afterEach(() => { + stashedReactScanLite.restore(); + stashedHook.restore(); + stashedWindow.restore(); + }); + + const buildFakeFiberTree = () => { + const leaf = { + tag: 0, + type: function LeafComponent() {}, + child: null, + sibling: null, + return: null, + alternate: null, + actualDuration: 5, + actualStartTime: 100, + selfBaseDuration: 5, + treeBaseDuration: 5, + }; + const parent = { + tag: 0, + type: function ParentComponent() {}, + child: leaf, + sibling: null, + return: null, + alternate: null, + actualDuration: 12, + actualStartTime: 99, + selfBaseDuration: 7, + treeBaseDuration: 12, + }; + return { current: parent }; + }; + + it('emits a commit event with a populated tree on hook.onCommitFiberRoot', () => { + const events: Array = []; + const handle = instrument({ onEvent: (event) => events.push(event) }); + expect(handle.isActive()).toBe(true); + + const fakeRoot = buildFakeFiberTree(); + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 0); + + const commitEvent = events.find((event) => event.kind === 'commit'); + expect(commitEvent).toBeDefined(); + expect(commitEvent?.rendererId).toBe(1); + expect(commitEvent?.tree?.length).toBe(2); + expect(commitEvent?.tree?.[0]?.name).toBe('ParentComponent'); + expect(commitEvent?.tree?.[1]?.name).toBe('LeafComponent'); + expect(commitEvent?.tree?.[1]?.depth).toBe(1); + + handle.stop(); + }); + + it('subscribe() listener receives commit events; unsubscribe stops them', () => { + const events: Array = []; + const handle = instrument(); + const unsubscribe = handle.subscribe((event) => events.push(event)); + + const fakeRoot = buildFakeFiberTree(); + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 0); + expect(events.some((event) => event.kind === 'commit')).toBe(true); + + unsubscribe(); + events.length = 0; + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 0); + expect(events).toEqual([]); + + handle.stop(); + }); + + it('stop() restores hook handlers and prevents further events', () => { + const events: Array = []; + const handle = instrument({ onEvent: (event) => events.push(event) }); + const ourCommit = fakeHook.onCommitFiberRoot; + const ourInject = fakeHook.inject; + + handle.stop(); + expect(handle.isActive()).toBe(false); + expect(fakeHook.onCommitFiberRoot).not.toBe(ourCommit); + expect(fakeHook.inject).not.toBe(ourInject); + + const fakeRoot = buildFakeFiberTree(); + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 0); + expect(events.filter((event) => event.kind === 'commit')).toEqual([]); + }); + + it('stop()/instrument() cycles do not leak chain layers', () => { + const settler = instrument(); + settler.stop(); + const baselineCommit = fakeHook.onCommitFiberRoot; + const baselineInject = fakeHook.inject; + + for (let cycle = 0; cycle < 3; cycle++) { + const handle = instrument(); + expect(fakeHook.onCommitFiberRoot).not.toBe(baselineCommit); + handle.stop(); + expect(fakeHook.onCommitFiberRoot).toBe(baselineCommit); + expect(fakeHook.inject).toBe(baselineInject); + } + }); + + it('stop() is idempotent', () => { + const handle = instrument(); + handle.stop(); + expect(() => handle.stop()).not.toThrow(); + expect(handle.isActive()).toBe(false); + }); + + it('returns the existing handle if instrument() is called twice without stop()', () => { + const first = instrument(); + const second = instrument(); + expect(second).toBe(first); + first.stop(); + }); + + it('respects maxFibersPerCommit cap', () => { + const events: Array = []; + const handle = instrument({ + onEvent: (event) => events.push(event), + maxFibersPerCommit: 1, + }); + + const fakeRoot = buildFakeFiberTree(); + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 0); + + const commitEvent = events.find((event) => event.kind === 'commit'); + expect(commitEvent?.tree?.length).toBe(1); + + handle.stop(); + }); + + it('respects minFiberActualDurationMs threshold', () => { + const events: Array = []; + const handle = instrument({ + onEvent: (event) => events.push(event), + minFiberActualDurationMs: 10, + }); + + const fakeRoot = buildFakeFiberTree(); + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 0); + + const commitEvent = events.find((event) => event.kind === 'commit'); + expect(commitEvent?.tree?.length).toBe(1); + expect(commitEvent?.tree?.[0]?.name).toBe('ParentComponent'); + + handle.stop(); + }); + + it('warns when endpoint is provided without sessionId', () => { + const warnings: Array = []; + // oxlint-disable-next-line no-console + const originalWarn = console.warn; + // oxlint-disable-next-line no-console + console.warn = (...args: Array) => warnings.push(args); + try { + const handle = instrument({ endpoint: 'http://example.test' }); + expect( + warnings.some((entry) => + String(entry).includes('endpoint'), + ), + ).toBe(true); + handle.stop(); + } finally { + // oxlint-disable-next-line no-console + console.warn = originalWarn; + } + }); + + it('emits profiling-hooks-status with available=false when renderer has no injectProfilingHooks', () => { + const events: Array = []; + fakeHook.renderers.set(1, { version: '18.3.0', bundleType: 1 }); + const handle = instrument({ onEvent: (event) => events.push(event) }); + + const status = events.find((event) => event.kind === 'profiling-hooks-status'); + expect(status).toBeDefined(); + expect(status?.available).toBe(false); + expect(status?.reason).toBe('no-inject-method'); + expect(status?.reactVersion).toBe('18.3.0'); + expect(status?.bundleType).toBe(1); + + handle.stop(); + }); + + it('emits profiling-hooks-status with available=true when injectProfilingHooks succeeds', () => { + const events: Array = []; + let capturedHooks: unknown = null; + fakeHook.renderers.set(1, { + version: '18.3.0', + bundleType: 1, + injectProfilingHooks: (hooks: unknown) => { + capturedHooks = hooks; + }, + }); + const handle = instrument({ onEvent: (event) => events.push(event) }); + + const status = events.find((event) => event.kind === 'profiling-hooks-status'); + expect(status?.available).toBe(true); + expect(status?.reason).toBeUndefined(); + expect(capturedHooks).toBeTruthy(); + + handle.stop(); + }); + + it('emits profiling-hooks-status with reason=threw when injectProfilingHooks throws', () => { + const events: Array = []; + fakeHook.renderers.set(1, { + version: '18.3.0', + bundleType: 1, + injectProfilingHooks: () => { + throw new Error('boom'); + }, + }); + const handle = instrument({ onEvent: (event) => events.push(event) }); + + const status = events.find((event) => event.kind === 'profiling-hooks-status'); + expect(status?.available).toBe(false); + expect(status?.reason).toBe('threw'); + + handle.stop(); + }); + + it('translates lanes bitmask via getLaneLabelMap', () => { + const events: Array = []; + interface CapturedHooks { + markCommitStarted: (lanes: number) => void; + } + const captured: { hooks: CapturedHooks | null } = { hooks: null }; + fakeHook.renderers.set(1, { + version: '18.3.0', + bundleType: 1, + getLaneLabelMap: () => + new Map([ + [1, 'SyncLane'], + [16, 'DefaultLane'], + ]), + injectProfilingHooks: (hooks: CapturedHooks) => { + captured.hooks = hooks; + }, + }); + const handle = instrument({ onEvent: (event) => events.push(event) }); + captured.hooks?.markCommitStarted(0b10001); + + const commitStart = events.find((event) => event.kind === 'commit-start'); + expect(commitStart?.laneLabels).toEqual(['SyncLane', 'DefaultLane']); + + handle.stop(); + }); + + it('translates priorityLevel to priorityName on commit events', () => { + const events: Array = []; + fakeHook.renderers.set(1, { + version: '18.3.0', + bundleType: 1, + getLaneLabelMap: () => new Map([[1, 'SyncLane']]), + injectProfilingHooks: () => {}, + }); + const handle = instrument({ onEvent: (event) => events.push(event) }); + + const fakeRoot = buildFakeFiberTree(); + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 2); + + const commit = events.find((event) => event.kind === 'commit'); + expect(commit?.priorityLevel).toBe(2); + expect(commit?.priorityName).toBe('UserBlocking'); + + handle.stop(); + }); + + it('attaches fiberId when includeFiberIdentity is true', () => { + const events: Array = []; + const handle = instrument({ + onEvent: (event) => events.push(event), + includeFiberIdentity: true, + }); + + const fakeRoot = buildFakeFiberTree(); + // HACK: bippy's `getFiberId` uses `if (!id)` to detect "unassigned", + // which falsely re-assigns id=0 on every lookup. This only affects the + // very first fiber ever seen by bippy in the process; after that, ids + // stabilize. We commit three times and compare the latter two to dodge + // the quirk while still asserting cross-commit identity. + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 0); + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 0); + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 0); + + const commits = events.filter((event) => event.kind === 'commit'); + expect(commits[1]?.tree?.[0]?.fiberId).toBeTypeOf('number'); + expect(commits[1]?.tree?.[0]?.fiberId).toBe(commits[2]?.tree?.[0]?.fiberId); + expect(commits[1]?.tree?.[1]?.fiberId).toBe(commits[2]?.tree?.[1]?.fiberId); + + handle.stop(); + }); + + it('attaches changeDescription when recordChangeDescriptions is true', () => { + const events: Array = []; + const handle = instrument({ + onEvent: (event) => events.push(event), + recordChangeDescriptions: true, + }); + + const fakeRoot = buildFakeFiberTree(); + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 0); + + const commit = events.find((event) => event.kind === 'commit'); + const summary = commit?.tree?.[0]; + expect(summary?.changeDescription).toBeDefined(); + expect(summary?.changeDescription?.isFirstMount).toBe(true); + + handle.stop(); + }); + + it('changeDescription.parent reflects whether a composite ancestor rendered', () => { + const events: Array = []; + const handle = instrument({ + onEvent: (event) => events.push(event), + recordChangeDescriptions: true, + }); + + // Build update-path tree (alternates present so we hit the non-mount branch). + const buildUpdatedTree = () => { + const leafAlt = { + tag: 0, + type: function LeafComponent() {}, + child: null, + sibling: null, + return: null, + alternate: null, + memoizedProps: { value: 1 }, + memoizedState: null, + actualDuration: 5, + actualStartTime: 100, + selfBaseDuration: 5, + treeBaseDuration: 5, + }; + const leaf = { + tag: 0, + type: function LeafComponent() {}, + child: null, + sibling: null, + return: null as unknown, + alternate: leafAlt, + memoizedProps: { value: 2 }, + memoizedState: null, + actualDuration: 5, + actualStartTime: 100, + selfBaseDuration: 5, + treeBaseDuration: 5, + }; + const parentAlt = { + tag: 0, + type: function ParentComponent() {}, + child: null, + sibling: null, + return: null, + alternate: null, + memoizedProps: {}, + memoizedState: null, + actualDuration: 12, + actualStartTime: 99, + selfBaseDuration: 7, + treeBaseDuration: 12, + }; + const parent = { + tag: 0, + type: function ParentComponent() {}, + child: leaf, + sibling: null, + return: null, + alternate: parentAlt, + memoizedProps: {}, + memoizedState: null, + actualDuration: 12, + actualStartTime: 99, + selfBaseDuration: 7, + treeBaseDuration: 12, + }; + leaf.return = parent; + return { current: parent }; + }; + + fakeHook.onCommitFiberRoot?.(1, buildUpdatedTree(), 0); + + const commit = events.find((event) => event.kind === 'commit'); + const parentSummary = commit?.tree?.find((entry) => entry.name === 'ParentComponent'); + const leafSummary = commit?.tree?.find((entry) => entry.name === 'LeafComponent'); + + expect(parentSummary?.changeDescription?.parent).toBe(false); + expect(leafSummary?.changeDescription?.parent).toBe(true); + + handle.stop(); + }); + + it('attaches source and ownerName when includeFiberSource is true', () => { + const events: Array = []; + const handle = instrument({ + onEvent: (event) => events.push(event), + includeFiberSource: true, + }); + + const ownerFiber = { type: function OwnerComponent() {} }; + const fakeRoot = { + current: { + tag: 0, + type: function ChildComponent() {}, + child: null, + sibling: null, + return: null, + alternate: null, + actualDuration: 5, + actualStartTime: 0, + selfBaseDuration: 5, + treeBaseDuration: 5, + _debugOwner: ownerFiber, + _debugSource: { + fileName: 'src/foo.tsx', + lineNumber: 42, + columnNumber: 3, + }, + }, + }; + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 0); + + const commit = events.find((event) => event.kind === 'commit'); + const summary = commit?.tree?.[0]; + expect(summary?.source).toEqual({ + fileName: 'src/foo.tsx', + lineNumber: 42, + columnNumber: 3, + }); + expect(summary?.ownerName).toBe('OwnerComponent'); + + handle.stop(); + }); + + it('source/ownerName are null when includeFiberSource is true but the fiber has no debug info', () => { + const events: Array = []; + const handle = instrument({ + onEvent: (event) => events.push(event), + includeFiberSource: true, + }); + + fakeHook.onCommitFiberRoot?.(1, buildFakeFiberTree(), 0); + + const commit = events.find((event) => event.kind === 'commit'); + const summary = commit?.tree?.[0]; + expect(summary?.source).toBeNull(); + expect(summary?.ownerName).toBeNull(); + + handle.stop(); + }); + + it('priorityName resolves even when no renderer exposes getLaneLabelMap', () => { + const events: Array = []; + fakeHook.renderers.set(1, { + version: '18.3.0', + bundleType: 1, + // no getLaneLabelMap, no injectProfilingHooks + }); + const handle = instrument({ onEvent: (event) => events.push(event) }); + + const fakeRoot = buildFakeFiberTree(); + fakeHook.onCommitFiberRoot?.(1, fakeRoot, 3); + + const commit = events.find((event) => event.kind === 'commit'); + expect(commit?.priorityLevel).toBe(3); + expect(commit?.priorityName).toBe('Normal'); + expect(commit?.laneLabels).toBeUndefined(); + + handle.stop(); + }); + + it('emits "opted-out" reason when includeProfilingHooks is false', () => { + const events: Array = []; + fakeHook.renderers.set(1, { + version: '18.3.0', + bundleType: 1, + injectProfilingHooks: () => { + throw new Error('should not be called when opted out'); + }, + }); + const handle = instrument({ + onEvent: (event) => events.push(event), + includeProfilingHooks: false, + }); + + const status = events.find((event) => event.kind === 'profiling-hooks-status'); + expect(status?.available).toBe(false); + expect(status?.reason).toBe('opted-out'); + + handle.stop(); + }); + + it('does not throw a TDZ error when a renderer is already injected', () => { + // H2 regression: bippy may fire `onActive` synchronously inside + // `getRDTHook(...)` if a renderer was already injected. Our previous + // code referenced the not-yet-bound `hook` const inside that callback. + // The fix is to acquire the hook first, then attach explicitly. + fakeHook.renderers.set(1, { + version: '18.3.0', + bundleType: 1, + injectProfilingHooks: () => {}, + }); + + expect(() => { + const handle = instrument(); + handle.stop(); + }).not.toThrow(); + }); + + it('forwards onCommitFiberRoot to the previously installed handler', () => { + // M5: prove the chain forwarding actually invokes the previous handler. + const calls: Array<{ rendererId: number; didError: boolean | undefined }> = []; + fakeHook.onCommitFiberRoot = ( + rendererId: number, + _root: unknown, + _priority: number | undefined, + ...rest: Array + ) => { + calls.push({ rendererId, didError: rest[0] as boolean | undefined }); + }; + + const handle = instrument(); + fakeHook.onCommitFiberRoot?.(7, buildFakeFiberTree(), 2); + + expect(calls).toEqual([{ rendererId: 7, didError: undefined }]); + + handle.stop(); + }); + + it('captures and emits didError on commit events', () => { + // H1: bippy's onCommitFiberRoot type omits the 4th `didError` arg, but + // React passes it. We widen locally and emit it. + const events: Array = []; + const handle = instrument({ onEvent: (event) => events.push(event) }); + + const widenedHandler = fakeHook.onCommitFiberRoot as ( + id: number, + root: unknown, + priority?: number, + didError?: boolean, + ) => void; + widenedHandler(1, buildFakeFiberTree(), 2, true); + + const commit = events.find((event) => event.kind === 'commit'); + expect(commit?.didError).toBe(true); + + handle.stop(); + }); + + it('omits didError on commit events when React did not pass it', () => { + const events: Array = []; + const handle = instrument({ onEvent: (event) => events.push(event) }); + + fakeHook.onCommitFiberRoot?.(1, buildFakeFiberTree(), 2); + + const commit = events.find((event) => event.kind === 'commit'); + expect(commit?.didError).toBeUndefined(); + + handle.stop(); + }); + + it('emits the underlying error message when injectProfilingHooks throws', () => { + // M3: error message should propagate so debug agents can attribute the failure. + const events: Array = []; + fakeHook.renderers.set(1, { + version: '18.3.0', + bundleType: 1, + injectProfilingHooks: () => { + throw new Error('renderer rejected hooks'); + }, + }); + const handle = instrument({ onEvent: (event) => events.push(event) }); + + const status = events.find((event) => event.kind === 'profiling-hooks-status'); + expect(status?.reason).toBe('threw'); + expect(status?.error).toBe('renderer rejected hooks'); + + handle.stop(); + }); + + it('warns when includeFiberTree is false but enrichment options are set', () => { + // H3: silent ignore is the worst failure mode. + const warnings: Array = []; + // oxlint-disable-next-line no-console + const originalWarn = console.warn; + // oxlint-disable-next-line no-console + console.warn = (...args: Array) => warnings.push(args); + try { + const handle = instrument({ + includeFiberTree: false, + recordChangeDescriptions: true, + }); + expect( + warnings.some((entry) => String(entry).includes('includeFiberTree: false')), + ).toBe(true); + handle.stop(); + } finally { + // oxlint-disable-next-line no-console + console.warn = originalWarn; + } + }); + + it('logs an error when endpoint is not a valid http(s) URL', () => { + // S2: validate URL once at instrument() time instead of letting fetch fail + // silently per-event. + const errors: Array = []; + // oxlint-disable-next-line no-console + const originalError = console.error; + // oxlint-disable-next-line no-console + console.error = (...args: Array) => errors.push(args); + try { + const handle = instrument({ + endpoint: 'javascript:alert(1)', + sessionId: 'abc', + }); + expect( + errors.some((entry) => + String(entry).includes('not a valid http(s) URL'), + ), + ).toBe(true); + handle.stop(); + } finally { + // oxlint-disable-next-line no-console + console.error = originalError; + } + }); + + it('invalid endpoint does NOT trigger fetch on every emitted event', () => { + // Bugbot regression on PR #435: previously the URL validator only logged + // a warning, but `canPostToEndpoint` still saw the bad endpoint and + // fired `fetch()` per event. Now `instrument()` clears the endpoint when + // invalid before forwarding to `createEmitter`. + const fetchCalls: Array = []; + const originalFetch = (globalThis as { fetch?: unknown }).fetch; + (globalThis as { fetch: (url: unknown) => Promise }).fetch = ( + url, + ) => { + fetchCalls.push(url); + return Promise.resolve({}); + }; + // oxlint-disable-next-line no-console + const originalError = console.error; + // oxlint-disable-next-line no-console + console.error = () => {}; + try { + const handle = instrument({ + endpoint: 'javascript:alert(1)', + sessionId: 'abc', + }); + fakeHook.onCommitFiberRoot?.(1, buildFakeFiberTree(), 0); + expect(fetchCalls).toEqual([]); + handle.stop(); + } finally { + // oxlint-disable-next-line no-console + console.error = originalError; + if (originalFetch === undefined) { + delete (globalThis as { fetch?: unknown }).fetch; + } else { + (globalThis as { fetch: unknown }).fetch = originalFetch; + } + } + }); + + it('emit fast-path skips translator + listener work when nothing is listening', () => { + // L5: when no onEvent + no endpoint + no subscribe, emit short-circuits. + let translatorCalls = 0; + fakeHook.renderers.set(1, { + version: '18.3.0', + bundleType: 1, + getLaneLabelMap: () => { + translatorCalls++; + return new Map([[1, 'SyncLane']]); + }, + injectProfilingHooks: () => {}, + }); + const handle = instrument(); + const callsAfterAttach = translatorCalls; + + fakeHook.onCommitFiberRoot?.(1, buildFakeFiberTree(), 2); + + // After commit, translator should NOT have been called again + // (no listener consumes the event, so emit short-circuits). + expect(translatorCalls).toBe(callsAfterAttach); + + handle.stop(); + }); + + it('cascade detection rejects fibers whose actualDuration is 0', () => { + // L6: a parent that didn't actually render must not be reported as cascading. + const events: Array = []; + const handle = instrument({ + onEvent: (event) => events.push(event), + recordChangeDescriptions: true, + }); + + const leafAlt = { + tag: 0, + type: function LeafComponent() {}, + child: null, + sibling: null, + return: null, + alternate: null, + memoizedProps: { value: 1 }, + memoizedState: null, + actualDuration: 5, + actualStartTime: 0, + selfBaseDuration: 5, + treeBaseDuration: 5, + }; + const leaf = { + tag: 0, + type: function LeafComponent() {}, + child: null, + sibling: null, + return: null as unknown, + alternate: leafAlt, + memoizedProps: { value: 2 }, + memoizedState: null, + actualDuration: 5, + actualStartTime: 0, + selfBaseDuration: 5, + treeBaseDuration: 5, + }; + const parentAlt = { + tag: 0, + type: function ParentComponent() {}, + child: null, + sibling: null, + return: null, + alternate: null, + memoizedProps: {}, + memoizedState: null, + actualDuration: 0, + actualStartTime: 0, + selfBaseDuration: 0, + treeBaseDuration: 0, + }; + const parent = { + tag: 0, + type: function ParentComponent() {}, + child: leaf, + sibling: null, + return: null, + alternate: parentAlt, + memoizedProps: {}, + memoizedState: null, + actualDuration: 0, // bailout: parent didn't actually render + actualStartTime: 0, + selfBaseDuration: 0, + treeBaseDuration: 5, + }; + leaf.return = parent; + + fakeHook.onCommitFiberRoot?.(1, { current: parent }, 0); + + const commit = events.find((event) => event.kind === 'commit'); + const leafSummary = commit?.tree?.find((entry) => entry.name === 'LeafComponent'); + expect(leafSummary?.changeDescription?.parent).toBe(false); + + handle.stop(); + }); + + it('does not double-attach a renderer across stop()/instrument() cycles', () => { + // L7: WeakSet of attached renderers must survive across cycles for the + // same renderer instance. + const injects: Array = []; + const renderer = { + version: '18.3.0', + bundleType: 1, + injectProfilingHooks: () => { + injects.push(1); + }, + }; + fakeHook.renderers.set(1, renderer); + + const settler = instrument(); + settler.stop(); + expect(injects.length).toBe(1); + + // A fresh instrument cycle gets its own WeakSet, so it WILL re-inject + // (this is by design — different profilingHooks closure, different + // emitter target). Document the behavior; the key invariant is that + // WITHIN a single cycle, each renderer is injected exactly once. + const handle = instrument(); + expect(injects.length).toBe(2); + handle.stop(); + }); + + it('detects context value changes via traverseContexts', () => { + // M4: covers `didAnyContextChange`. + const events: Array = []; + const handle = instrument({ + onEvent: (event) => events.push(event), + recordChangeDescriptions: true, + }); + + const contextRef = { displayName: 'TestContext' }; + const previousFiber = { + tag: 0, + type: function Consumer() {}, + child: null, + sibling: null, + return: null, + alternate: null, + memoizedProps: {}, + memoizedState: null, + actualDuration: 5, + actualStartTime: 0, + selfBaseDuration: 5, + treeBaseDuration: 5, + dependencies: { + firstContext: { context: contextRef, memoizedValue: 'before', next: null }, + }, + }; + const fiber = { + tag: 0, + type: function Consumer() {}, + child: null, + sibling: null, + return: null, + alternate: previousFiber, + memoizedProps: {}, + memoizedState: null, + actualDuration: 5, + actualStartTime: 0, + selfBaseDuration: 5, + treeBaseDuration: 5, + dependencies: { + firstContext: { context: contextRef, memoizedValue: 'after', next: null }, + }, + }; + + fakeHook.onCommitFiberRoot?.(1, { current: fiber }, 0); + + const commit = events.find((event) => event.kind === 'commit'); + const summary = commit?.tree?.[0]; + expect(summary?.changeDescription?.context).toBe(true); + + handle.stop(); + }); + + it('detects class state changes via shallow key compare', () => { + // M4: covers `didAnyClassStateChange`. Tag 1 = ClassComponentTag. + const events: Array = []; + const handle = instrument({ + onEvent: (event) => events.push(event), + recordChangeDescriptions: true, + }); + + const previousFiber = { + tag: 1, + type: class Counter {}, + child: null, + sibling: null, + return: null, + alternate: null, + memoizedProps: {}, + memoizedState: { count: 1 }, + actualDuration: 5, + actualStartTime: 0, + selfBaseDuration: 5, + treeBaseDuration: 5, + }; + const fiber = { + tag: 1, + type: previousFiber.type, + child: null, + sibling: null, + return: null, + alternate: previousFiber, + memoizedProps: {}, + memoizedState: { count: 2 }, + actualDuration: 5, + actualStartTime: 0, + selfBaseDuration: 5, + treeBaseDuration: 5, + }; + + fakeHook.onCommitFiberRoot?.(1, { current: fiber }, 0); + + const commit = events.find((event) => event.kind === 'commit'); + const summary = commit?.tree?.[0]; + expect(summary?.changeDescription?.state).toBe(true); + expect(summary?.changeDescription?.hooks).toEqual([]); + + handle.stop(); + }); + + it('detects hook-state changes via traverseState', () => { + // M4: covers `collectChangedHookIndices`. Function components only. + const events: Array = []; + const handle = instrument({ + onEvent: (event) => events.push(event), + recordChangeDescriptions: true, + }); + + const prevHook2 = { memoizedState: 'b', next: null }; + const prevHook1 = { memoizedState: 1, next: prevHook2 }; + const nextHook2 = { memoizedState: 'b', next: null }; + const nextHook1 = { memoizedState: 2, next: nextHook2 }; + + const previousFiber = { + tag: 0, + type: function Counter() {}, + child: null, + sibling: null, + return: null, + alternate: null, + memoizedProps: {}, + memoizedState: prevHook1, + actualDuration: 5, + actualStartTime: 0, + selfBaseDuration: 5, + treeBaseDuration: 5, + }; + const fiber = { + tag: 0, + type: previousFiber.type, + child: null, + sibling: null, + return: null, + alternate: previousFiber, + memoizedProps: {}, + memoizedState: nextHook1, + actualDuration: 5, + actualStartTime: 0, + selfBaseDuration: 5, + treeBaseDuration: 5, + }; + + fakeHook.onCommitFiberRoot?.(1, { current: fiber }, 0); + + const commit = events.find((event) => event.kind === 'commit'); + const summary = commit?.tree?.[0]; + expect(summary?.changeDescription?.hooks).toEqual([0]); + + handle.stop(); + }); + + it('handle.stop() called from inside an onEvent listener takes effect', () => { + // M6: realistic self-disabling instrumentation pattern. + let commitCount = 0; + let handleRef: { stop: () => void } | null = null; + handleRef = instrument({ + onEvent: (event) => { + if (event.kind === 'commit') { + commitCount++; + handleRef?.stop(); + } + }, + }); + + fakeHook.onCommitFiberRoot?.(1, buildFakeFiberTree(), 0); + fakeHook.onCommitFiberRoot?.(1, buildFakeFiberTree(), 0); + fakeHook.onCommitFiberRoot?.(1, buildFakeFiberTree(), 0); + + expect(commitCount).toBe(1); + expect(handleRef?.stop).toBeDefined(); + }); +}); + +describe.skipIf(!existsSync(CJS_DIST))( + 'react-scan/lite SSR safety (built CJS in node -e)', + () => { + it('importing the CJS build does not throw', () => { + expect(runInNode(`require('${CJS_DIST}'); console.log('OK')`)).toBe('OK'); + }); + + it('instrument() returns a noop handle in node -e', () => { + const code = [ + `const { instrument } = require('${CJS_DIST}');`, + "const handle = instrument({ endpoint: 'http://example.test', sessionId: 'abc' });", + "console.log(handle.isActive() === false ? 'NOOP' : 'UNEXPECTED');", + ].join(' '); + expect(runInNode(code)).toBe('NOOP'); + }); + }, +); + +describe.skipIf(!existsSync(ESM_DIST))( + 'react-scan/lite SSR safety (built ESM in node -e)', + () => { + it('importing the ESM build does not throw', () => { + const url = pathToFileURL(ESM_DIST).href; + expect( + runInNode( + `import('${url}').then(() => console.log('OK')).catch(e => { console.error(e); process.exit(1); })`, + ), + ).toBe('OK'); + }); + + it('instrument() returns a noop handle when imported as ESM', () => { + const url = pathToFileURL(ESM_DIST).href; + const code = [ + `import('${url}').then(({ instrument }) => {`, + " const handle = instrument({ endpoint: 'http://example.test', sessionId: 'abc' });", + " console.log(handle.isActive() === false ? 'NOOP' : 'UNEXPECTED');", + '}).catch(e => { console.error(e); process.exit(1); });', + ].join(' '); + expect(runInNode(code)).toBe('NOOP'); + }); + }, +); diff --git a/packages/scan/src/lite/types.ts b/packages/scan/src/lite/types.ts new file mode 100644 index 00000000..18a1cd8d --- /dev/null +++ b/packages/scan/src/lite/types.ts @@ -0,0 +1,302 @@ +import type { BundleType, Fiber, Lanes, ReactRenderer } from 'bippy'; +import type { FiberSource } from 'bippy/source'; + +export type { BundleType, Fiber, FiberSource, Lanes }; + +/** + * Scheduler priority level. Sourced from the `scheduler` package + * (`ImmediatePriority`/`UserBlockingPriority`/etc.). Distinct from + * bippy's `LanePriority` (which models React's lane bitmask priority, + * 0-17). React's reconciler maps event priorities to scheduler + * priorities and passes one of these values to `onCommitFiberRoot`. + * + * @see https://github.com/facebook/react/blob/main/packages/scheduler/src/SchedulerPriorities.js + */ +export type SchedulerPriorityLevel = 0 | 1 | 2 | 3 | 4 | 5; + +export interface ChangeDescription { + isFirstMount: boolean; + /** + * Names of props whose reference identity changed. `null` when the fiber + * type has no meaningful prop comparison (e.g. host components). + */ + props: Array | null; + /** + * `true` if any class-component state field changed. `false` for function + * components (use `hooks` instead). + */ + state: boolean; + /** + * `true` if any consumed context value changed (compared via `Object.is`). + */ + context: boolean; + /** + * Indices of stateful hooks whose `memoizedState` changed. Approximate: + * walks the `Hook` linked list and compares each `.memoizedState` by + * reference. Will report `useMemo` / `useCallback` deltas as well. + */ + hooks: Array; + /** + * `true` if a parent fiber also rendered in this commit (signals a + * cascade render rather than a self-triggered update). + */ + parent: boolean; +} + +export interface LiteFiberSummary { + name: string; + depth: number; + /** + * The fiber's `WorkTag`. Typed as `number` (not bippy's `WorkTag` union) + * because newer React versions add tags faster than bippy bumps the union + * (e.g. `ActivityComponentTag = 28`, `ViewTransitionComponentTag = 30` + * exist as constants but aren't in the type union as of bippy 0.5.39). + * Compare against bippy's exported constants + * (`FunctionComponentTag`, `ClassComponentTag`, etc.) to interpret. + */ + tag: number; + actualDuration: number; + actualStartTime: number; + selfBaseDuration: number; + treeBaseDuration: number; + /** + * Stable monotonic id assigned per logical fiber (alternate-aware). + * Present when `includeFiberIdentity` is enabled. + */ + fiberId?: number; + /** + * Where this fiber's element was created. Read from `_debugSource` + * (React 16/17/18) or parsed out of `_debugStack` (React 19+). + * Present when `includeFiberSource` is enabled. + */ + source?: FiberSource | null; + /** + * Display name of `_debugOwner.type`: the component that rendered this + * one (i.e. its parent in the JSX tree, not the fiber `return`). + * Present when `includeFiberSource` is enabled. + */ + ownerName?: string | null; + /** + * Why this fiber re-rendered. Present when `recordChangeDescriptions` + * is enabled. `null` for fiber types we don't track (host nodes etc). + */ + changeDescription?: ChangeDescription | null; +} + +export type LiteEventKind = + | 'renderer-injected' + | 'profiling-hooks-status' + | 'commit' + | 'post-commit' + | 'fiber-unmount' + | 'commit-start' + | 'commit-stop' + | 'render-start' + | 'render-yield' + | 'render-stop' + | 'render-scheduled' + | 'layout-effects-start' + | 'layout-effects-stop' + | 'passive-effects-start' + | 'passive-effects-stop' + | 'component-render-start' + | 'component-render-stop' + | 'component-layout-effect-mount-start' + | 'component-layout-effect-mount-stop' + | 'component-layout-effect-unmount-start' + | 'component-layout-effect-unmount-stop' + | 'component-passive-effect-mount-start' + | 'component-passive-effect-mount-stop' + | 'component-passive-effect-unmount-start' + | 'component-passive-effect-unmount-stop' + | 'state-update' + | 'force-update' + | 'component-suspended' + | 'component-errored'; + +export type ProfilingHooksUnavailableReason = + /** Renderer doesn't expose `injectProfilingHooks` (R19.2+ prod, non-`__PROFILE__` builds). */ + | 'no-inject-method' + /** `injectProfilingHooks` threw when called. */ + | 'threw' + /** Caller passed `includeProfilingHooks: false`; we never tried to attach. */ + | 'opted-out'; + +export interface LiteEvent { + kind: LiteEventKind; + timestamp: number; + /** + * Set on the per-component `mark*` events: every `component-*-start`/`-stop` + * pair, every `component-{layout,passive}-effect-{mount,unmount}-{start,stop}`, + * `state-update`, `force-update`, `component-suspended`, `component-errored`. + * Absent on `commit`/`commit-start`/`render-start`/etc. (which span all + * components in the commit, not one). + */ + componentName?: string; + /** Raw lanes bitmask. */ + lanes?: Lanes; + /** Human-readable lane labels (e.g. ["SyncLane", "DefaultLane"]). */ + laneLabels?: Array; + rendererId?: number; + /** Numeric scheduler priority (1=Immediate, 5=Idle). */ + priorityLevel?: SchedulerPriorityLevel; + /** Resolved scheduler priority name (e.g. "UserBlocking"). */ + priorityName?: string; + /** + * Set on `commit` events when React encountered an error during the + * commit (root captured a `DidCapture` flag). Forwarded directly from + * React's `onCommitFiberRoot(rendererID, root, priority, didError)` + * 4th argument; bippy's type omits this so we read it via a widened + * handler signature. + */ + didError?: boolean; + tree?: Array; + message?: string; + data?: Record; + + // Fields for `profiling-hooks-status` events: + /** True if `injectProfilingHooks` succeeded for this renderer. */ + available?: boolean; + /** Reason `injectProfilingHooks` was unavailable, when `available === false`. */ + reason?: ProfilingHooksUnavailableReason; + /** Error message when `reason === 'threw'`; otherwise undefined. */ + error?: string; + /** React version reported by the renderer. */ + reactVersion?: string; + /** Renderer bundle type (0 = production, 1 = development). */ + bundleType?: BundleType; +} + +export interface LiteOptions { + /** + * Receives every emitted event. Combine with `endpoint` if you want both + * a callback and POSTs (callback fires first). + */ + onEvent?: (event: LiteEvent) => void; + /** + * If set, every event is `fetch`-POSTed to this URL with `keepalive: true`. + * Each request body is `{ sessionId, location, message, data, timestamp }` + * matching the `debug-agent` ingest contract. Note: `keepalive` has a + * ~64KB body limit; large `tree` payloads may be silently dropped. + */ + endpoint?: string; + /** + * Included in every endpoint POST under `sessionId`. Required when + * `endpoint` is set; otherwise POSTs are skipped (with a console warning). + */ + sessionId?: string; + /** + * Walk the fiber tree on every commit and include a `tree` of per-fiber + * `actualDuration` (DevTools flame-graph data). + * @default true + */ + includeFiberTree?: boolean; + /** + * Subscribe to the `mark*` profiling hooks (component renders, effect + * boundaries, scheduled state updates, suspends, errors). + * Only fires in `__PROFILE__` builds of React 16.5–19.1. + * @default true + */ + includeProfilingHooks?: boolean; + /** + * Compute a `changeDescription` for each fiber summary, attributing the + * re-render to props / state / context / hooks / parent. + * @default false + */ + recordChangeDescriptions?: boolean; + /** + * Attach `source` and `ownerName` to each fiber summary using + * `_debugSource` (React 16/17/18) or `_debugStack` (React 19+). + * Sync extraction only; no source-map symbolication. + * @default false + */ + includeFiberSource?: boolean; + /** + * Attach a stable monotonic `fiberId` to each fiber summary so the agent + * can correlate the same logical fiber across commits. + * @default false + */ + includeFiberIdentity?: boolean; + /** + * Translate `lanes` bitmasks to human-readable labels via + * `renderer.getLaneLabelMap?.()`, and `priorityLevel` to `priorityName`. + * @default true + */ + includeLaneLabels?: boolean; + /** + * Prefix applied to the `location` field of every endpoint POST. + * @default "ReactScanLite" + */ + location?: string; + /** + * Maximum number of fibers walked per commit. Cuts off the tail to avoid + * unbounded payload sizes on huge trees. + * @default 5000 + */ + maxFibersPerCommit?: number; + /** + * Skip walking subtrees whose `actualDuration` is below this threshold (ms). + * Set to 0 to include every committed fiber. + * @default 0 + */ + minFiberActualDurationMs?: number; +} + +export interface LiteHandle { + /** + * Stop emitting events. Idempotent. Bippy's instrumentation chain stays + * installed but our handlers become no-ops. + */ + stop: () => void; + /** + * Whether the handle is currently emitting events. + */ + isActive: () => boolean; + /** + * Add a listener that receives every emitted event. Returns an unsubscribe. + */ + subscribe: (listener: (event: LiteEvent) => void) => () => void; +} + +export interface ProfilingHooks { + markCommitStarted: (lanes: Lanes) => void; + markCommitStopped: () => void; + markRenderStarted: (lanes: Lanes) => void; + markRenderYielded: () => void; + markRenderStopped: () => void; + markRenderScheduled: (lane: Lanes) => void; + markLayoutEffectsStarted: (lanes: Lanes) => void; + markLayoutEffectsStopped: () => void; + markPassiveEffectsStarted: (lanes: Lanes) => void; + markPassiveEffectsStopped: () => void; + markComponentRenderStarted: (fiber: Fiber) => void; + markComponentRenderStopped: () => void; + markComponentLayoutEffectMountStarted: (fiber: Fiber) => void; + markComponentLayoutEffectMountStopped: () => void; + markComponentLayoutEffectUnmountStarted: (fiber: Fiber) => void; + markComponentLayoutEffectUnmountStopped: () => void; + markComponentPassiveEffectMountStarted: (fiber: Fiber) => void; + markComponentPassiveEffectMountStopped: () => void; + markComponentPassiveEffectUnmountStarted: (fiber: Fiber) => void; + markComponentPassiveEffectUnmountStopped: () => void; + markStateUpdateScheduled: (fiber: Fiber, lane: Lanes) => void; + markForceUpdateScheduled: (fiber: Fiber, lane: Lanes) => void; + markComponentSuspended: (fiber: Fiber, wakeable: unknown, lanes: Lanes) => void; + markComponentErrored: (fiber: Fiber, thrownValue: unknown, lanes: Lanes) => void; +} + +/** + * `injectProfilingHooks` and `getLaneLabelMap` are public-by-accident methods + * on the renderer object that React DevTools uses for the Timeline Profiler. + * Not declared on bippy's `ReactRenderer`, so we extend locally. + */ +export interface ReactRendererWithProfiling extends ReactRenderer { + injectProfilingHooks?: (hooks: ProfilingHooks) => void; + getLaneLabelMap?: () => Map | null; +} + +declare global { + interface Window { + __REACT_SCAN_LITE__?: LiteHandle; + } +} diff --git a/packages/scan/src/lite/walk-fiber.ts b/packages/scan/src/lite/walk-fiber.ts new file mode 100644 index 00000000..944416bf --- /dev/null +++ b/packages/scan/src/lite/walk-fiber.ts @@ -0,0 +1,118 @@ +import { type Fiber, getDisplayName, getFiberId } from 'bippy'; +import { getChangeDescription, isCompositeTag } from './change-description'; +import { getFiberSource, getOwnerName } from './fiber-source'; +import type { LiteFiberSummary } from './types'; + +export interface WalkFiberOptions { + maxFibers: number; + minActualDurationMs: number; + recordChangeDescriptions: boolean; + includeFiberSource: boolean; + includeFiberIdentity: boolean; + /** + * Optional cancellation predicate. If returns `true` mid-walk, we exit + * early without finishing the tree. Lets `stop()` short-circuit walks + * already in flight on a deep tree. + */ + isCancelled?: () => boolean; +} + +interface PendingFiber { + fiber: Fiber; + depth: number; + // `true` if any composite ancestor in this fiber's path through the tree + // already rendered in this commit. Snapshotted at sibling-spawn time so + // backtracking restores the right value (siblings share their parent's + // ancestor-cascade state, NOT each other's). + hasCascadingAncestor: boolean; +} + +const compositeFiberDidRender = (fiber: Fiber): boolean => { + const actualDuration = fiber.actualDuration; + return ( + actualDuration != null && actualDuration > 0 && isCompositeTag(fiber.tag) + ); +}; + +export const walkFiber = ( + rootFiber: Fiber | null | undefined, + options: WalkFiberOptions, +): Array => { + const summaries: Array = []; + if (!rootFiber) return summaries; + + const pendingSiblings: Array = []; + let currentFiber: Fiber | null = rootFiber; + let currentDepth = 0; + let hasCascadingAncestor = false; + + while (currentFiber || pendingSiblings.length > 0) { + if (summaries.length >= options.maxFibers) return summaries; + if (options.isCancelled?.()) return summaries; + + if (!currentFiber) { + // HACK: cast guarded by length check above. + const next = pendingSiblings.pop() as PendingFiber; + currentFiber = next.fiber; + currentDepth = next.depth; + hasCascadingAncestor = next.hasCascadingAncestor; + continue; + } + + const actualDuration = currentFiber.actualDuration; + if (actualDuration != null && actualDuration >= options.minActualDurationMs) { + const summary: LiteFiberSummary = { + name: getDisplayName(currentFiber.type) ?? 'Anonymous', + depth: currentDepth, + tag: currentFiber.tag, + actualDuration, + actualStartTime: currentFiber.actualStartTime ?? 0, + selfBaseDuration: currentFiber.selfBaseDuration ?? 0, + treeBaseDuration: currentFiber.treeBaseDuration ?? 0, + }; + if (options.includeFiberIdentity) { + summary.fiberId = getFiberId(currentFiber); + } + if (options.includeFiberSource) { + summary.source = getFiberSource(currentFiber); + summary.ownerName = getOwnerName(currentFiber); + } + if (options.recordChangeDescriptions) { + summary.changeDescription = getChangeDescription( + currentFiber, + hasCascadingAncestor, + ); + } + summaries.push(summary); + } + + if (currentFiber.sibling) { + // Siblings see this fiber's ancestor-cascade state (their parent's), + // NOT this fiber itself; siblings are not descendants of each other. + pendingSiblings.push({ + fiber: currentFiber.sibling, + depth: currentDepth, + hasCascadingAncestor, + }); + } + + if (currentFiber.child) { + // Descendants see this fiber's contribution: if THIS fiber is a + // composite that rendered, our descendants now have a cascading + // ancestor (us). Only compute when consumers actually use it. + if ( + options.recordChangeDescriptions && + !hasCascadingAncestor && + compositeFiberDidRender(currentFiber) + ) { + hasCascadingAncestor = true; + } + currentFiber = currentFiber.child; + currentDepth = currentDepth + 1; + } else { + currentFiber = null; + } + } + + return summaries; +}; diff --git a/packages/scan/tsconfig.json b/packages/scan/tsconfig.json index b689a064..40c850de 100644 --- a/packages/scan/tsconfig.json +++ b/packages/scan/tsconfig.json @@ -4,6 +4,8 @@ "rootDir": "src", "outDir": "dist", "baseUrl": ".", + "module": "ESNext", + "moduleResolution": "bundler", "types": [ "node" ], diff --git a/packages/scan/tsup.config.ts b/packages/scan/tsup.config.ts index ca376561..09bde403 100644 --- a/packages/scan/tsup.config.ts +++ b/packages/scan/tsup.config.ts @@ -8,15 +8,18 @@ import { workerPlugin } from './worker-plugin'; const DIST_PATH = './dist'; +const USE_CLIENT_DIRECTIVE = `'use client';\n`; + const addDirectivesToChunkFiles = async (readPath: string): Promise => { try { + if (!fs.existsSync(readPath)) return; const files = await fsPromise.readdir(readPath); for (const file of files) { if (file.endsWith('.mjs') || file.endsWith('.js')) { const filePath = path.join(readPath, file); const data = await fsPromise.readFile(filePath, 'utf8'); - const updatedContent = `'use client';\n${data}`; - await fsPromise.writeFile(filePath, updatedContent, 'utf8'); + if (data.startsWith(USE_CLIENT_DIRECTIVE)) continue; + await fsPromise.writeFile(filePath, `${USE_CLIENT_DIRECTIVE}${data}`, 'utf8'); } } } catch (err) { @@ -117,6 +120,7 @@ export default defineConfig([ './src/index.ts', './src/install-hook.ts', './src/core/all-environments.ts', + './src/lite/index.ts', ], banner: { js: banner, @@ -135,6 +139,8 @@ export default defineConfig([ watch: process.env.NODE_ENV === 'development', async onSuccess() { await addDirectivesToChunkFiles(DIST_PATH); + await addDirectivesToChunkFiles(path.join(DIST_PATH, 'lite')); + await addDirectivesToChunkFiles(path.join(DIST_PATH, 'core')); }, minify: false, env: { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 69cc7a36..8b96d219 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,7 +14,7 @@ importers: dependencies: '@vercel/speed-insights': specifier: ^1.1.0 - version: 1.2.0(next@15.2.6(@playwright/test@1.58.2)(react-dom@19.0.0(react@19.0.0))(react@19.0.0))(react@19.0.0) + version: 1.2.0(next@15.2.6(@playwright/test@1.58.2)(react@19.0.0))(react@19.0.0) devDependencies: '@changesets/cli': specifier: ^2.27.12 @@ -51,7 +51,7 @@ importers: version: 5.8.3 vite-tsconfig-paths: specifier: ^5.1.4 - version: 5.1.4(typescript@5.8.3)(vite@6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0)) + version: 5.1.4(typescript@5.8.3)(vite@6.3.5(@types/node@22.15.34)) kitchen-sink: dependencies: @@ -76,7 +76,7 @@ importers: version: 19.1.6(@types/react@19.1.8) '@vitejs/plugin-react': specifier: ^4.3.4 - version: 4.6.0(vite@6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0)) + version: 4.6.0(vite@6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3)) postcss: specifier: ^8.5.3 version: 8.5.6 @@ -85,7 +85,7 @@ importers: version: 5.8.3 vite: specifier: ^6.3.0 - version: 6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) + version: 6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3) packages/extension: dependencies: @@ -122,7 +122,7 @@ importers: version: 0.12.3 '@vitejs/plugin-react': specifier: ^4.2.1 - version: 4.6.0(vite@6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0)) + version: 4.6.0(vite@6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0)) bestzip: specifier: ^2.2.1 version: 2.2.1 @@ -134,13 +134,13 @@ importers: version: 7.7.2 vite: specifier: ^6.3.0 - version: 6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) + version: 6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) vite-plugin-web-extension: specifier: ^4.4.3 - version: 4.4.4(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3) + version: 4.4.4(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3) vite-tsconfig-paths: specifier: ^5.1.4 - version: 5.1.4(typescript@5.8.3)(vite@6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0)) + version: 5.1.4(typescript@5.8.3)(vite@6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0)) webextension-polyfill: specifier: ^0.12.0 version: 0.12.0 @@ -166,8 +166,8 @@ importers: specifier: ^20.17.9 version: 20.19.2 bippy: - specifier: ^0.5.30 - version: 0.5.30(@types/react@18.3.23)(react@19.0.0) + specifier: ^0.5.39 + version: 0.5.39(react@19.0.0) commander: specifier: ^14.0.0 version: 14.0.3 @@ -223,7 +223,7 @@ importers: version: 15.2.1(@babel/core@7.27.7)(@playwright/test@1.58.2)(react-dom@19.0.0(react@19.0.0))(react@19.0.0) postcss-cli: specifier: ^11.0.0 - version: 11.0.1(jiti@1.21.7)(postcss@8.5.6)(tsx@4.20.3) + version: 11.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.20.3) publint: specifier: ^0.2.12 version: 0.2.12 @@ -247,10 +247,10 @@ importers: version: 5.43.1 tsup: specifier: ^8.0.0 - version: 8.5.0(jiti@1.21.7)(postcss@8.5.6)(tsx@4.20.3)(typescript@5.8.3)(yaml@2.8.0) + version: 8.5.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.20.3)(typescript@5.8.3)(yaml@2.8.3) vitest: specifier: ^3.0.0 - version: 3.2.4(@types/node@20.19.2)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) + version: 3.2.4(@types/node@20.19.2)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3) packages/vite-plugin-react-scan: dependencies: @@ -287,7 +287,7 @@ importers: version: 5.8.3 vite: specifier: ^6.3.0 - version: 6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) + version: 6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3) packages/website: dependencies: @@ -296,7 +296,7 @@ importers: version: 1.5.0(@remix-run/react@2.16.8(react-dom@19.0.0(react@19.0.0))(react@19.0.0)(typescript@5.8.3))(next@15.2.6(@playwright/test@1.58.2)(react-dom@19.0.0(react@19.0.0))(react@19.0.0))(react@19.0.0) '@vercel/speed-insights': specifier: ^1.1.0 - version: 1.2.0(next@15.2.6(@playwright/test@1.58.2)(react-dom@19.0.0(react@19.0.0))(react@19.0.0))(react@19.0.0) + version: 1.2.0(next@15.2.6(@playwright/test@1.58.2)(react@19.0.0))(react@19.0.0) highlight.js: specifier: ^11.11.1 version: 11.11.1 @@ -311,7 +311,7 @@ importers: version: 19.0.0(react@19.0.0) react-grab: specifier: ^0.1.15 - version: 0.1.15(@types/react@19.1.8)(react@19.0.0) + version: 0.1.15(react@19.0.0) react-scan: specifier: ^0.5.3 version: link:../scan @@ -1565,11 +1565,6 @@ packages: peerDependencies: react: '>=17.0.1' - bippy@0.5.30: - resolution: {integrity: sha512-8CFmJAHD3gmTLDOCDHuWhjm1nxHSFZdlGoWtak9r53Uxn36ynOjxBLyxXHh/7h/XiKLyPvfdXa0gXWcD9o9lLQ==} - peerDependencies: - react: '>=17.0.1' - bippy@0.5.39: resolution: {integrity: sha512-8hE8rKSl8JWyeaY+JjpnmceWAZPpLEyzOZQpWXM5Rc7861c5WotMJHy2aRZKZrGA8nMpvLNF01t4yQQ+HcZG3w==} peerDependencies: @@ -2076,8 +2071,8 @@ packages: resolution: {integrity: sha512-vpeMIQKxczTD/0s2CdEWHcb0eeJe6TFjxb+J5xgX7hScxqrGuyjmv4c1D4A/gelKfyox0gJJwIHF+fLjeaM8kQ==} engines: {node: '>=18'} - get-tsconfig@4.10.1: - resolution: {integrity: sha512-auHyJ4AgMz7vgS8Hp3N6HXSmlMdUyhSUrfBF16w153rxtLIEOE+HGqaBppczZvnHLqQJfiHotCYpNhl0lUROFQ==} + get-tsconfig@4.14.0: + resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==} glob-parent@5.1.2: resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} @@ -2328,6 +2323,10 @@ packages: resolution: {integrity: sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==} hasBin: true + jiti@2.6.1: + resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} + hasBin: true + joycon@3.1.1: resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} engines: {node: '>=10'} @@ -3718,6 +3717,11 @@ packages: engines: {node: '>= 14.6'} hasBin: true + yaml@2.8.3: + resolution: {integrity: sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg==} + engines: {node: '>= 14.6'} + hasBin: true + yargs-parser@20.2.9: resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} engines: {node: '>=10'} @@ -4687,10 +4691,6 @@ snapshots: dependencies: '@types/react': 18.3.23 - '@types/react-reconciler@0.28.9(@types/react@19.1.8)': - dependencies: - '@types/react': 19.1.8 - '@types/react-router@5.1.20': dependencies: '@types/history': 4.7.11 @@ -4715,12 +4715,24 @@ snapshots: next: 15.2.6(@playwright/test@1.58.2)(react-dom@19.0.0(react@19.0.0))(react@19.0.0) react: 19.0.0 - '@vercel/speed-insights@1.2.0(next@15.2.6(@playwright/test@1.58.2)(react-dom@19.0.0(react@19.0.0))(react@19.0.0))(react@19.0.0)': + '@vercel/speed-insights@1.2.0(next@15.2.6(@playwright/test@1.58.2)(react@19.0.0))(react@19.0.0)': optionalDependencies: next: 15.2.6(@playwright/test@1.58.2)(react-dom@19.0.0(react@19.0.0))(react@19.0.0) react: 19.0.0 - '@vitejs/plugin-react@4.6.0(vite@6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0))': + '@vitejs/plugin-react@4.6.0(vite@6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0))': + dependencies: + '@babel/core': 7.27.7 + '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.27.7) + '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/core@7.27.7) + '@rolldown/pluginutils': 1.0.0-beta.19 + '@types/babel__core': 7.20.5 + react-refresh: 0.17.0 + vite: 6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) + transitivePeerDependencies: + - supports-color + + '@vitejs/plugin-react@4.6.0(vite@6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3))': dependencies: '@babel/core': 7.27.7 '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.27.7) @@ -4728,7 +4740,7 @@ snapshots: '@rolldown/pluginutils': 1.0.0-beta.19 '@types/babel__core': 7.20.5 react-refresh: 0.17.0 - vite: 6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) + vite: 6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3) transitivePeerDependencies: - supports-color @@ -4740,13 +4752,13 @@ snapshots: chai: 5.2.0 tinyrainbow: 2.0.0 - '@vitest/mocker@3.2.4(vite@6.3.5(@types/node@20.19.2)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0))': + '@vitest/mocker@3.2.4(vite@6.3.5(@types/node@20.19.2)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3))': dependencies: '@vitest/spy': 3.2.4 estree-walker: 3.0.3 magic-string: 0.30.17 optionalDependencies: - vite: 6.3.5(@types/node@20.19.2)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) + vite: 6.3.5(@types/node@20.19.2)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3) '@vitest/pretty-format@3.2.4': dependencies: @@ -4908,20 +4920,6 @@ snapshots: transitivePeerDependencies: - '@types/react' - bippy@0.5.30(@types/react@18.3.23)(react@19.0.0): - dependencies: - '@types/react-reconciler': 0.28.9(@types/react@18.3.23) - react: 19.0.0 - transitivePeerDependencies: - - '@types/react' - - bippy@0.5.30(@types/react@19.1.8)(react@19.0.0): - dependencies: - '@types/react-reconciler': 0.28.9(@types/react@19.1.8) - react: 19.0.0 - transitivePeerDependencies: - - '@types/react' - bippy@0.5.39(react@19.0.0): dependencies: react: 19.0.0 @@ -5439,7 +5437,7 @@ snapshots: get-east-asian-width@1.3.0: {} - get-tsconfig@4.10.1: + get-tsconfig@4.14.0: dependencies: resolve-pkg-maps: 1.0.0 optional: true @@ -5672,6 +5670,9 @@ snapshots: jiti@1.21.7: {} + jiti@2.6.1: + optional: true + joycon@3.1.1: {} js-tokens@4.0.0: {} @@ -6139,14 +6140,14 @@ snapshots: optionalDependencies: fsevents: 2.3.2 - postcss-cli@11.0.1(jiti@1.21.7)(postcss@8.5.6)(tsx@4.20.3): + postcss-cli@11.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.20.3): dependencies: chokidar: 3.6.0 dependency-graph: 1.0.0 fs-extra: 11.3.0 picocolors: 1.1.1 postcss: 8.5.6 - postcss-load-config: 5.1.0(jiti@1.21.7)(postcss@8.5.6)(tsx@4.20.3) + postcss-load-config: 5.1.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.20.3) postcss-reporter: 7.1.0(postcss@8.5.6) pretty-hrtime: 1.0.3 read-cache: 1.0.0 @@ -6176,23 +6177,23 @@ snapshots: optionalDependencies: postcss: 8.5.6 - postcss-load-config@5.1.0(jiti@1.21.7)(postcss@8.5.6)(tsx@4.20.3): + postcss-load-config@5.1.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.20.3): dependencies: lilconfig: 3.1.3 yaml: 2.8.0 optionalDependencies: - jiti: 1.21.7 + jiti: 2.6.1 postcss: 8.5.6 tsx: 4.20.3 - postcss-load-config@6.0.1(jiti@1.21.7)(postcss@8.5.6)(tsx@4.20.3)(yaml@2.8.0): + postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.20.3)(yaml@2.8.3): dependencies: lilconfig: 3.1.3 optionalDependencies: - jiti: 1.21.7 + jiti: 2.6.1 postcss: 8.5.6 tsx: 4.20.3 - yaml: 2.8.0 + yaml: 2.8.3 postcss-nested@6.2.0(postcss@8.5.6): dependencies: @@ -6287,14 +6288,12 @@ snapshots: react: 19.0.0 scheduler: 0.25.0 - react-grab@0.1.15(@types/react@19.1.8)(react@19.0.0): + react-grab@0.1.15(react@19.0.0): dependencies: - bippy: 0.5.30(@types/react@19.1.8)(react@19.0.0) + bippy: 0.5.39(react@19.0.0) solid-js: 1.9.11 optionalDependencies: react: 19.0.0 - transitivePeerDependencies: - - '@types/react' react-grab@0.1.32(react@19.0.0): dependencies: @@ -6778,7 +6777,7 @@ snapshots: tslib@2.8.1: {} - tsup@8.5.0(jiti@1.21.7)(postcss@8.5.6)(tsx@4.20.3)(typescript@5.8.3)(yaml@2.8.0): + tsup@8.5.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.20.3)(typescript@5.8.3)(yaml@2.8.3): dependencies: bundle-require: 5.1.0(esbuild@0.25.5) cac: 6.7.14 @@ -6789,7 +6788,7 @@ snapshots: fix-dts-default-cjs-exports: 1.0.1 joycon: 3.1.1 picocolors: 1.1.1 - postcss-load-config: 6.0.1(jiti@1.21.7)(postcss@8.5.6)(tsx@4.20.3)(yaml@2.8.0) + postcss-load-config: 6.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.20.3)(yaml@2.8.3) resolve-from: 5.0.0 rollup: 4.44.1 source-map: 0.8.0-beta.0 @@ -6809,7 +6808,7 @@ snapshots: tsx@4.20.3: dependencies: esbuild: 0.25.5 - get-tsconfig: 4.10.1 + get-tsconfig: 4.14.0 optionalDependencies: fsevents: 2.3.3 optional: true @@ -6867,13 +6866,13 @@ snapshots: value-equal@1.0.1: {} - vite-node@3.2.4(@types/node@20.19.2)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0): + vite-node@3.2.4(@types/node@20.19.2)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3): dependencies: cac: 6.7.14 debug: 4.4.1 es-module-lexer: 1.7.0 pathe: 2.0.3 - vite: 6.3.5(@types/node@20.19.2)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) + vite: 6.3.5(@types/node@20.19.2)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3) transitivePeerDependencies: - '@types/node' - jiti @@ -6888,7 +6887,7 @@ snapshots: - tsx - yaml - vite-plugin-web-extension@4.4.4(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3): + vite-plugin-web-extension@4.4.4(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3): dependencies: ajv: 8.17.1 async-lock: 1.4.1 @@ -6898,7 +6897,7 @@ snapshots: lodash.uniq: 4.5.0 lodash.uniqby: 4.7.0 md5: 2.3.0 - vite: 6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) + vite: 6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) web-ext-option-types: 8.3.1 web-ext-run: 0.2.3 webextension-polyfill: 0.10.0 @@ -6918,18 +6917,29 @@ snapshots: - tsx - utf-8-validate - vite-tsconfig-paths@5.1.4(typescript@5.8.3)(vite@6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0)): + vite-tsconfig-paths@5.1.4(typescript@5.8.3)(vite@6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0)): dependencies: debug: 4.4.1 globrex: 0.1.2 tsconfck: 3.1.6(typescript@5.8.3) optionalDependencies: - vite: 6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) + vite: 6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) transitivePeerDependencies: - supports-color - typescript - vite@6.3.5(@types/node@20.19.2)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0): + vite-tsconfig-paths@5.1.4(typescript@5.8.3)(vite@6.3.5(@types/node@22.15.34)): + dependencies: + debug: 4.4.1 + globrex: 0.1.2 + tsconfck: 3.1.6(typescript@5.8.3) + optionalDependencies: + vite: 6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3) + transitivePeerDependencies: + - supports-color + - typescript + + vite@6.3.5(@types/node@20.19.2)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3): dependencies: esbuild: 0.25.5 fdir: 6.4.6(picomatch@4.0.2) @@ -6940,12 +6950,12 @@ snapshots: optionalDependencies: '@types/node': 20.19.2 fsevents: 2.3.3 - jiti: 1.21.7 + jiti: 2.6.1 terser: 5.43.1 tsx: 4.20.3 - yaml: 2.8.0 + yaml: 2.8.3 - vite@6.3.5(@types/node@22.15.34)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0): + vite@6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0): dependencies: esbuild: 0.25.5 fdir: 6.4.6(picomatch@4.0.2) @@ -6956,16 +6966,32 @@ snapshots: optionalDependencies: '@types/node': 22.15.34 fsevents: 2.3.3 - jiti: 1.21.7 + jiti: 2.6.1 terser: 5.43.1 tsx: 4.20.3 yaml: 2.8.0 - vitest@3.2.4(@types/node@20.19.2)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0): + vite@6.3.5(@types/node@22.15.34)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3): + dependencies: + esbuild: 0.25.5 + fdir: 6.4.6(picomatch@4.0.2) + picomatch: 4.0.2 + postcss: 8.5.6 + rollup: 4.44.1 + tinyglobby: 0.2.14 + optionalDependencies: + '@types/node': 22.15.34 + fsevents: 2.3.3 + jiti: 2.6.1 + terser: 5.43.1 + tsx: 4.20.3 + yaml: 2.8.3 + + vitest@3.2.4(@types/node@20.19.2)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3): dependencies: '@types/chai': 5.2.2 '@vitest/expect': 3.2.4 - '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@20.19.2)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0)) + '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@20.19.2)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3)) '@vitest/pretty-format': 3.2.4 '@vitest/runner': 3.2.4 '@vitest/snapshot': 3.2.4 @@ -6983,8 +7009,8 @@ snapshots: tinyglobby: 0.2.14 tinypool: 1.1.1 tinyrainbow: 2.0.0 - vite: 6.3.5(@types/node@20.19.2)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) - vite-node: 3.2.4(@types/node@20.19.2)(jiti@1.21.7)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.0) + vite: 6.3.5(@types/node@20.19.2)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3) + vite-node: 3.2.4(@types/node@20.19.2)(jiti@2.6.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.3) why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 20.19.2 @@ -7119,6 +7145,9 @@ snapshots: yaml@2.8.0: {} + yaml@2.8.3: + optional: true + yargs-parser@20.2.9: {} yargs-parser@21.1.1: {}