Repository navigation
feat(scan): add react-scan/lite headless instrumentation entry #435
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<string> => { | ||
| // 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<string> = []; | ||
| 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<string, unknown>; | ||
| const nextObject = nextState as Record<string, unknown>; | ||
| const allKeys = new Set<string>([ | ||
| ...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<number> => { | ||
| const indices: Array<number> = []; | ||
| 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, | ||
| }; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<number, string> = { | ||
| 0: 'NoPriority', | ||
| 1: 'Immediate', | ||
| 2: 'UserBlocking', | ||
| 3: 'Normal', | ||
| 4: 'Low', | ||
| 5: 'Idle', | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<LiteEvent>) => 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<LiteEvent>): 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 }, | ||
| }; | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.