@buoy-gg/highlight-updates 2.1.9 → 2.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/lib/commonjs/highlight-updates/HighlightUpdatesOverlay.js +285 -1
  2. package/lib/commonjs/highlight-updates/components/HighlightFilterView.js +1371 -1
  3. package/lib/commonjs/highlight-updates/components/HighlightUpdatesModal.js +591 -1
  4. package/lib/commonjs/highlight-updates/components/IdentifierBadge.js +267 -1
  5. package/lib/commonjs/highlight-updates/components/IsolatedRenderList.js +178 -1
  6. package/lib/commonjs/highlight-updates/components/ModalHeaderContent.js +303 -1
  7. package/lib/commonjs/highlight-updates/components/RenderCauseBadge.js +500 -1
  8. package/lib/commonjs/highlight-updates/components/RenderDetailView.js +830 -1
  9. package/lib/commonjs/highlight-updates/components/RenderHistoryViewer.js +894 -1
  10. package/lib/commonjs/highlight-updates/components/RenderListItem.js +220 -1
  11. package/lib/commonjs/highlight-updates/components/StatsDisplay.js +70 -1
  12. package/lib/commonjs/highlight-updates/components/index.js +97 -1
  13. package/lib/commonjs/highlight-updates/utils/HighlightUpdatesController.js +1435 -1
  14. package/lib/commonjs/highlight-updates/utils/PerformanceLogger.js +359 -1
  15. package/lib/commonjs/highlight-updates/utils/ProfilerInterceptor.js +371 -1
  16. package/lib/commonjs/highlight-updates/utils/RenderCauseDetector.js +1828 -1
  17. package/lib/commonjs/highlight-updates/utils/RenderTracker.js +903 -1
  18. package/lib/commonjs/highlight-updates/utils/ViewTypeMapper.js +264 -1
  19. package/lib/commonjs/highlight-updates/utils/renderExportFormatter.js +58 -1
  20. package/lib/commonjs/index.js +311 -1
  21. package/lib/commonjs/preset.js +278 -1
  22. package/lib/module/highlight-updates/HighlightUpdatesOverlay.js +278 -1
  23. package/lib/module/highlight-updates/components/HighlightFilterView.js +1365 -1
  24. package/lib/module/highlight-updates/components/HighlightUpdatesModal.js +585 -1
  25. package/lib/module/highlight-updates/components/IdentifierBadge.js +259 -1
  26. package/lib/module/highlight-updates/components/IsolatedRenderList.js +174 -1
  27. package/lib/module/highlight-updates/components/ModalHeaderContent.js +298 -1
  28. package/lib/module/highlight-updates/components/RenderCauseBadge.js +491 -1
  29. package/lib/module/highlight-updates/components/RenderDetailView.js +826 -1
  30. package/lib/module/highlight-updates/components/RenderHistoryViewer.js +888 -1
  31. package/lib/module/highlight-updates/components/RenderListItem.js +215 -1
  32. package/lib/module/highlight-updates/components/StatsDisplay.js +67 -1
  33. package/lib/module/highlight-updates/components/index.js +16 -1
  34. package/lib/module/highlight-updates/utils/HighlightUpdatesController.js +1431 -1
  35. package/lib/module/highlight-updates/utils/PerformanceLogger.js +353 -1
  36. package/lib/module/highlight-updates/utils/ProfilerInterceptor.js +358 -1
  37. package/lib/module/highlight-updates/utils/RenderCauseDetector.js +1818 -1
  38. package/lib/module/highlight-updates/utils/RenderTracker.js +900 -1
  39. package/lib/module/highlight-updates/utils/ViewTypeMapper.js +255 -1
  40. package/lib/module/highlight-updates/utils/renderExportFormatter.js +54 -1
  41. package/lib/module/index.js +71 -1
  42. package/lib/module/preset.js +272 -1
  43. package/lib/typescript/highlight-updates/HighlightUpdatesOverlay.d.ts.map +1 -0
  44. package/lib/typescript/highlight-updates/components/HighlightFilterView.d.ts.map +1 -0
  45. package/lib/typescript/highlight-updates/components/HighlightUpdatesModal.d.ts.map +1 -0
  46. package/lib/typescript/highlight-updates/components/IdentifierBadge.d.ts.map +1 -0
  47. package/lib/typescript/highlight-updates/components/IsolatedRenderList.d.ts.map +1 -0
  48. package/lib/typescript/highlight-updates/components/ModalHeaderContent.d.ts.map +1 -0
  49. package/lib/typescript/highlight-updates/components/RenderCauseBadge.d.ts.map +1 -0
  50. package/lib/typescript/highlight-updates/components/RenderDetailView.d.ts.map +1 -0
  51. package/lib/typescript/highlight-updates/components/RenderHistoryViewer.d.ts.map +1 -0
  52. package/lib/typescript/highlight-updates/components/RenderListItem.d.ts.map +1 -0
  53. package/lib/typescript/highlight-updates/components/StatsDisplay.d.ts.map +1 -0
  54. package/lib/typescript/highlight-updates/components/index.d.ts.map +1 -0
  55. package/lib/typescript/highlight-updates/utils/HighlightUpdatesController.d.ts.map +1 -0
  56. package/lib/typescript/highlight-updates/utils/PerformanceLogger.d.ts.map +1 -0
  57. package/lib/typescript/highlight-updates/utils/ProfilerInterceptor.d.ts.map +1 -0
  58. package/lib/typescript/highlight-updates/utils/RenderCauseDetector.d.ts.map +1 -0
  59. package/lib/typescript/highlight-updates/utils/RenderTracker.d.ts.map +1 -0
  60. package/lib/typescript/highlight-updates/utils/ViewTypeMapper.d.ts.map +1 -0
  61. package/lib/typescript/highlight-updates/utils/renderExportFormatter.d.ts.map +1 -0
  62. package/lib/typescript/index.d.ts.map +1 -0
  63. package/lib/typescript/preset.d.ts.map +1 -0
  64. package/package.json +16 -16
  65. package/LICENSE +0 -58
@@ -1 +1,1431 @@
1
- "use strict";import{installProfilerInterceptor,uninstallProfilerInterceptor,setComparisonCallback}from"./ProfilerInterceptor";import{RenderTracker}from"./RenderTracker";import{PerformanceLogger,markEventReceived}from"./PerformanceLogger";import{detectRenderCause,clearRenderCauseState}from"./RenderCauseDetector";import{notifySubscriberCountChange}from"@buoy-gg/shared-ui";let globalEnabled=!1,backgroundTrackingEnabled=!1,initialized=!1,hook=null,highlightCallback=null,badgePressCallback=null,traceUpdatesUnsubscribe=null,isProcessing=!1,isFrozen=!1;const freezeListeners=new Set,stateListeners=new Set,nodeRenderCounts=new Map,COLORS=["#37afa9","#63b19e","#80b393","#97b488","#abb67d","#beb771","#cfb965","#dfba57","#efbb49","#febc38"],DEBUG=!1;function debugLog(e,n){}function getPublicInstance(e){if(!e)return null;const n=e;return n.canonical?.publicInstance?n.canonical.publicInstance:n.canonical&&"function"==typeof n.canonical.measure?n.canonical:"function"==typeof n.measure?n:null}function getNativeTag(e){if(null==e)return null;const n=e;if(null!=n.__nativeTag)return n.__nativeTag;if(null!=n._nativeTag)return n._nativeTag;if(null!=n.nativeTag)return n.nativeTag;if(n.canonical){if(null!=n.canonical.__nativeTag)return n.canonical.__nativeTag;if(null!=n.canonical._nativeTag)return n.canonical._nativeTag}return null}function extractComponentInfo(e){const n=e,t={viewType:"Unknown"};n?.canonical?.viewConfig?.uiViewClassName?t.viewType=n.canonical.viewConfig.uiViewClassName:n?.viewConfig?.uiViewClassName&&(t.viewType=n.viewConfig.uiViewClassName);const i=n?.canonical?.internalInstanceHandle||n?._internalInstanceHandle||n?._internalFiberInstanceHandleDEV,a=n?.canonical?.currentProps,r=n?.canonical?.pendingProps,o=i?.pendingProps,s=i?.memoizedProps;return t.testID=a?.testID||r?.testID||o?.testID||s?.testID||void 0,t.nativeID=a?.nativeID||r?.nativeID||o?.nativeID||s?.nativeID||void 0,t.accessibilityLabel=a?.accessibilityLabel||r?.accessibilityLabel||o?.accessibilityLabel||s?.accessibilityLabel||void 0,t.componentName=getOwningComponentName(i)||void 0,t}function describeNodeForLog(e){const n=e,t=getPublicInstance(e),i={nativeTag:(getNativeTag(e)||getNativeTag(t))??"unknown",type:n?.canonical?"Fabric":"Legacy",hasMeasure:"function"==typeof t?.measure};if(n){if(i.stateNodeKeys=Object.keys(n).slice(0,20),n.node&&(i.nodeKeys=Object.keys(n.node).slice(0,20)),n.viewConfig&&(i.viewConfig={uiViewClassName:n.viewConfig.uiViewClassName,validAttributes:n.viewConfig.validAttributes?Object.keys(n.viewConfig.validAttributes).slice(0,10):void 0}),n.canonical){const e=n.canonical;if(i.canonicalKeys=Object.keys(e).slice(0,20),e.viewConfig&&(i.canonicalViewConfig={uiViewClassName:e.viewConfig.uiViewClassName}),null!=e.nativeTag&&(i.canonicalNativeTag=e.nativeTag),e.internalInstanceHandle){const n=e.internalInstanceHandle;if(i.fiberKeys=Object.keys(n).slice(0,30),n.type&&(i.fiberType="function"==typeof n.type?n.type.name||n.type.displayName||"function":n.type),n.elementType&&(i.fiberElementType="function"==typeof n.elementType?n.elementType.name||n.elementType.displayName||"function":n.elementType),n._debugOwner){const e=n._debugOwner;i.fiberDebugOwner=e.type?.name||e.type?.displayName||e.elementType?.name||"unknown"}n._debugSource&&(i.fiberDebugSource=n._debugSource),null!=n.tag&&(i.fiberTag=n.tag),n.pendingProps&&(n.pendingProps.nativeID&&(i.fiberPendingNativeID=n.pendingProps.nativeID),n.pendingProps.testID&&(i.fiberPendingTestID=n.pendingProps.testID)),n.memoizedProps&&(n.memoizedProps.nativeID&&(i.fiberMemoizedNativeID=n.memoizedProps.nativeID),n.memoizedProps.testID&&(i.fiberMemoizedTestID=n.memoizedProps.testID))}if(e.publicInstance){const n=e.publicInstance;i.publicInstanceKeys=Object.keys(n).slice(0,20),null!=n.nativeID&&(i.nativeID=n.nativeID),null!=n._nativeID&&(i._nativeID=n._nativeID),n.props&&(i.publicInstanceProps=Object.keys(n.props).slice(0,15),n.props.nativeID&&(i.propsNativeID=n.props.nativeID),n.props.testID&&(i.propsTestID=n.props.testID),n.props.accessibilityLabel&&(i.accessibilityLabel=n.props.accessibilityLabel))}e.currentProps&&(i.currentPropsKeys=Object.keys(e.currentProps).slice(0,15),null!=e.currentProps.nativeID&&(i.currentPropsNativeID=e.currentProps.nativeID),null!=e.currentProps.testID&&(i.currentPropsTestID=e.currentProps.testID),null!=e.currentProps.accessibilityLabel&&(i.currentPropsAccessLabel=e.currentProps.accessibilityLabel)),e.pendingProps&&(i.pendingPropsKeys=Object.keys(e.pendingProps).slice(0,15),null!=e.pendingProps.nativeID&&(i.pendingPropsNativeID=e.pendingProps.nativeID),null!=e.pendingProps.testID&&(i.pendingPropsTestID=e.pendingProps.testID))}if(n._debugOwner){const e=n._debugOwner;i.debugOwnerType=e.type?.name||e.type?.displayName||typeof e.type}n._debugSource&&(i.debugSource=n._debugSource)}return i}const DEBUG_LOGGING=!1;let renderingLock=!1,renderingLockTimeout=null;const RENDER_LOCK_DURATION=350,renderedOverlayTags=new Set;function isOurOverlayTag(e){return null!=e&&renderedOverlayTags.has(e)}const HIGHLIGHT_OVERLAY_COMPONENTS=new Set(["HighlightUpdatesOverlay","HighlightUpdatesModal","HighlightFilterView","RenderDetailView","RenderListItem","RenderListItemInner","RenderHistoryViewer","RenderHistoryFooter","RenderCauseBadge","TwoLevelCauseBadge","EnhancedCauseDisplay","IsolatedRenderList","IsolatedRenderListInner","StatsDisplay","StatsDisplayInner","CurrentStateView","EventStepperFooter","EventsModal","UnifiedEventList","UnifiedEventItem","UnifiedEventDetail","UnifiedEventFilters","UnifiedEventViewer","ReactQueryEventDetail","EventsCopySettingsView"]),HIGHLIGHT_OVERLAY_NATIVE_IDS=new Set(["highlight-updates-overlay","__rn_buoy__highlight-modal"]),HIGHLIGHT_OVERLAY_PREFIXES=["HighlightUpdates","RenderList","RenderDetail","RenderHistory","RenderCause","EventStepper","UnifiedEvent","EventsModal","EventsCopy"],OTHER_DEV_TOOLS_COMPONENTS=new Set(["JsModalComponent","JsModal","TypePicker","PatternInput","PatternChip","DetectedItemsSection","DetectedCategoryBadge","IdentifierBadge","CategoryBadge","AppRenderer","AppOverlay","FloatingTools","DialDevTools","DevToolsVisibilityProvider","AppHostProvider","MinimizedToolsProvider","ModalHeader","TabSelector","SectionHeader","DraggableHeader","WindowControls","TreeDiffViewer","DataViewer","SplitDiffViewer","VirtualizedDataExplorer","DiffSummary","TypeLegend","IndentGuides","IndentGuidesOverlay","CyberpunkInput","DiffView","AnswerCard","DetailsSection","DetailRow","QuickActionsSection","FilterOptionCard","SearchSection","SearchSectionInner","HeaderActions","HeaderActionsInner","MainListHeader","FilterViewHeader","DetailViewHeader","FloatingMenu","FloatingDevTools","MinimizedToolsStack","MinimizedToolsContext","GlitchToolButton","ExpandablePopover","CollapsedPeek","ExpandedWrapper","DialIcon","DialMenu","DialIconItem","OnboardingTooltip","MenuLauncherIcon","DevToolsSettingsModal","SettingsModal","ToolCard","ToolIcon","GripVerticalIcon","UserStatus","Divider","ChevronDown","ChevronUp","ChevronLeft","ChevronRight","ChevronDownIcon","ChevronUpIcon","ChevronLeftIcon","ChevronRightIcon","LogBox","LogBoxLog","LogBoxLogNotification","LogBoxNotificationContainer","_LogBoxNotificationContainer","LogBoxInspector","LogBoxInspectorContainer","LogBoxInspectorHeader","LogBoxInspectorBody","LogBoxInspectorFooter","LogBoxInspectorMessageHeader","LogBoxInspectorStackFrame","LogBoxInspectorSection","LogBoxButton","LogBoxMessage"]),OTHER_DEV_TOOLS_PREFIXES=["JsModal","TreeDiff","DataViewer","DiffView","DiffSummary","Virtualized","Floating","Minimized","Dial","Expandable","Chevron","Glitch","Settings","Onboarding","DevTools"],OTHER_DEV_TOOLS_NATIVE_IDS=new Set(["jsmodal-root","logbox_inspector","logbox"]),devToolsNodeCache=new Map,CACHE_MAX_SIZE=500;function clearDevToolsCache(){devToolsNodeCache.clear()}function isHighlightOverlayNativeID(e){return!(!e||!HIGHLIGHT_OVERLAY_NATIVE_IDS.has(e)&&!e.startsWith("__highlight_"))}function isOtherDevToolsNativeID(e){if(!e)return!1;if(OTHER_DEV_TOOLS_NATIVE_IDS.has(e))return!0;const n=e.charCodeAt(0);return!(95!==n||!e.startsWith("__rn_buoy__"))||!(108!==n||!e.startsWith("logbox"))}function getComponentName(e){if(!e)return null;const n=e.type;if(n){if("string"==typeof n)return n;if(n.name)return n.name;if(n.displayName)return n.displayName}const t=e.elementType;if(t){if(t.name)return t.name;if(t.displayName)return t.displayName}return null}const INTERNAL_COMPONENT_NAMES=new Set(["View","Text","TextImpl","Image","ScrollView","FlatList","SectionList","TouchableOpacity","TouchableHighlight","TouchableWithoutFeedback","Pressable","TextInput","Switch","ActivityIndicator","Modal","StatusBar","KeyboardAvoidingView","AnimatedComponent","AnimatedComponentWrapper","ScreenContainer","ScreenStack","Screen","ScreenContentWrapper","Svg","G","Path","Rect","Circle","Line","Polygon","Polyline","Ellipse","Text as SVGText","TSpan","TextPath","Use","Symbol","Defs","ClipPath","LinearGradient","RadialGradient","Stop","Mask","Pattern","Image as SVGImage","SafeAreaProvider","SafeAreaView","SafeAreaListener","GestureHandlerRootView","GestureDetector","ReanimatedView","ReanimatedText","ReanimatedImage","ReanimatedScrollView","Fragment","Suspense","Provider","Consumer","Context","ForwardRef"]);function isInternalComponent(e){return!e||!!INTERNAL_COMPONENT_NAMES.has(e)||"Unknown"===e||"Component"===e||!!e.startsWith("Animated")}function getOwningComponentName(e){if(!e)return null;let n=e._debugOwner||e.return,t=0,i=null;for(;n&&t<30;){const e=getComponentName(n);if(e&&"string"!=typeof n.type&&(i||(i=e),!isInternalComponent(e)))return e;n=n.return,t++}return i}function isOurOverlayNode(e){const n=e,t=n?.canonical?.internalInstanceHandle||n?._internalInstanceHandle||n?._internalFiberInstanceHandleDEV,i=getNativeTag(e)||getNativeTag(n?.canonical?.publicInstance),a=RenderTracker.getSettings().excludeDevTools;if(null!=i&&a){const e=devToolsNodeCache.get(i);if(void 0!==e)return e}let r=!1;const o=t?.pendingProps?.nativeID||t?.memoizedProps?.nativeID||n?.canonical?.currentProps?.nativeID||null;if((isHighlightOverlayNativeID(o)||a&&isOtherDevToolsNativeID(o))&&(r=!0),!r&&t){let e=t,n=0;for(;e&&n<30;){const t=getComponentName(e);if(t){if(HIGHLIGHT_OVERLAY_COMPONENTS.has(t)){r=!0;break}for(const e of HIGHLIGHT_OVERLAY_PREFIXES)if(t.startsWith(e)){r=!0;break}if(r)break;if(a){if(OTHER_DEV_TOOLS_COMPONENTS.has(t)){r=!0;break}for(const e of OTHER_DEV_TOOLS_PREFIXES)if(t.startsWith(e)){r=!0;break}if(r)break}}const i=e.pendingProps?.nativeID||e.memoizedProps?.nativeID;if(isHighlightOverlayNativeID(i)){r=!0;break}if(a&&isOtherDevToolsNativeID(i)){r=!0;break}e=e.return,n++}}if(r&&null!=i&&a){if(devToolsNodeCache.size>=500){const e=Array.from(devToolsNodeCache.keys());for(let n=0;n<250;n++)devToolsNodeCache.delete(e[n])}devToolsNodeCache.set(i,r)}return r}function getColorForRenderCount(e){const n=Math.min(e-1,COLORS.length-1);return COLORS[Math.max(0,n)]}function handleTraceUpdates(e){if(0===e.size)return;if(!globalEnabled&&!backgroundTrackingEnabled)return;if(RenderTracker.getState().isPaused)return;PerformanceLogger.isEnabled()&&markEventReceived();const n=RenderTracker.getBatchSize(),t=PerformanceLogger.startBatch(e.size,n),i=[];let a=0,r=0;const o=RenderTracker.hasActiveFilters();for(const n of e)if(n&&"object"==typeof n)try{if(isOurOverlayNode(n)){a++;continue}const e=getPublicInstance(n),t=getNativeTag(n)||getNativeTag(e);if(null==t)continue;const s=extractComponentInfo(n);if(o&&!RenderTracker.passesFilters(s)){r++;continue}let l,c;RenderTracker.getSettings().showRenderCount?(l=(nodeRenderCounts.get(t)||0)+1,nodeRenderCounts.set(t,l),c=getColorForRenderCount(l)):(l=0,c=COLORS[0]),i.push({node:n,color:c,count:l})}catch{}if(t.markFilteringComplete(a+r,i.length),0===i.length)return void t.finish();const s=RenderTracker.getRenderEventCallbackCount()>0;if(!highlightCallback&&!s)return void(isProcessing=!1);t.markMeasurementStart();const l=i.slice(0,n).map(({node:e,color:n,count:t})=>new Promise(i=>{const a=getPublicInstance(e);if(!a)return void i({rect:null,stateNode:e,color:n,count:t});const r=getNativeTag(e)||getNativeTag(a);if(null!=r)try{a.measure((a,o,s,l,c,d)=>{i(null!=c&&null!=d&&null!=s&&null!=l?{rect:{id:r,x:c,y:d,width:s,height:l,color:n,count:t},stateNode:e,color:n,count:t}:{rect:null,stateNode:e,color:n,count:t})})}catch(a){i({rect:null,stateNode:e,color:n,count:t})}else i({rect:null,stateNode:e,color:n,count:t})}));Promise.all(l).then(e=>{const n=e.filter(e=>null!==e.rect),i=n.map(e=>e.rect);t.markMeasurementComplete(n.length,e.length-n.length);const a=RenderTracker.getSettings(),r=a.trackRenderCauses&&a.showRenderCount;let o=null;if(r){o=new Set;for(const{rect:e}of n)e&&o.add(e.id)}if(globalEnabled){RenderTracker.startBatch();for(const{rect:e,stateNode:t,color:i,count:s}of n)if(e){const n=extractComponentInfo(t);let l;if(r&&o){const n=t,i=n?.canonical?.internalInstanceHandle;l=detectRenderCause(e.id,i,o,a.debugLogLevel)}RenderTracker.trackRender({nativeTag:e.id,viewType:n.viewType,testID:n.testID,nativeID:n.nativeID,accessibilityLabel:n.accessibilityLabel,componentName:n.componentName,measurements:{x:e.x,y:e.y,width:e.width,height:e.height},color:i,count:s,renderCause:l})}RenderTracker.endBatch()}else for(const{rect:e,stateNode:t,color:i,count:s}of n)if(e){const n=extractComponentInfo(t);let l;if(r&&o){const n=t,i=n?.canonical?.internalInstanceHandle;l=detectRenderCause(e.id,i,o,a.debugLogLevel)}RenderTracker.emitRenderEvent({nativeTag:e.id,viewType:n.viewType,testID:n.testID,nativeID:n.nativeID,accessibilityLabel:n.accessibilityLabel,componentName:n.componentName,measurements:{x:e.x,y:e.y,width:e.width,height:e.height},color:i,count:s,renderCause:l})}t.markTrackingComplete(),i.length>0&&highlightCallback&&globalEnabled&&highlightCallback(i),t.markCallbackComplete(),t.finish()}).catch(e=>{console.error("[HighlightUpdates] Error in measurement pipeline:",e),t.finish()})}function setTraceUpdatesOnRenderers(e){if(!hook?.rendererInterfaces)return void debugLog("No rendererInterfaces available");let n=0;if(hook.rendererInterfaces.forEach((t,i)=>{if("function"==typeof t.setTraceUpdatesEnabled)try{t.setTraceUpdatesEnabled(e),n++,debugLog(`Renderer ${i}: setTraceUpdatesEnabled(${e})`)}catch(e){debugLog(`Renderer ${i}: error setting trace updates`,e)}else debugLog(`Renderer ${i}: no setTraceUpdatesEnabled method`)}),debugLog(`Set trace updates ${e?"enabled":"disabled"} on ${n} renderer(s)`),hook.reactDevtoolsAgent?.setTraceUpdatesEnabled)try{hook.reactDevtoolsAgent.setTraceUpdatesEnabled(e),debugLog("Also set trace updates on agent")}catch(e){debugLog("Error setting trace updates on agent",e)}}function subscribeToTraceUpdates(){hook&&(traceUpdatesUnsubscribe||(debugLog("Subscribing to traceUpdates event"),"function"==typeof hook.sub?(traceUpdatesUnsubscribe=hook.sub("traceUpdates",handleTraceUpdates),debugLog("Subscribed using hook.sub()")):debugLog("hook.sub not available, traceUpdates may not work"),setTraceUpdatesOnRenderers(!0)))}function unsubscribeFromTraceUpdates(){setTraceUpdatesOnRenderers(!1),traceUpdatesUnsubscribe&&(traceUpdatesUnsubscribe(),traceUpdatesUnsubscribe=null,debugLog("Unsubscribed from traceUpdates event"))}function setHighlightCallback(e){highlightCallback=e,debugLog("Highlight callback "+(e?"set":"cleared"))}function setBadgePressCallback(e){badgePressCallback=e,debugLog("Badge press callback "+(e?"set":"cleared"))}function getBadgePressCallback(){return badgePressCallback}function handleBadgePress(e){badgePressCallback&&badgePressCallback(e)}let spotlightCallback=null,currentSpotlightTag=null;function setSpotlightCallback(e){spotlightCallback=e,e&&null!==currentSpotlightTag&&e(currentSpotlightTag)}function setSpotlight(e){currentSpotlightTag=e,spotlightCallback&&spotlightCallback(e)}function getSpotlight(){return currentSpotlightTag}function notifyStateListeners(){stateListeners.forEach(e=>{try{e(globalEnabled)}catch(e){console.error("[HighlightUpdates] Error in state listener:",e)}})}function subscribe(e){return stateListeners.add(e),e(globalEnabled),()=>{stateListeners.delete(e)}}function initialize(){if("undefined"!=typeof __DEV__&&!__DEV__)return debugLog("Only available in development builds"),!1;if(initialized)return!0;if(hook=window?.__REACT_DEVTOOLS_GLOBAL_HOOK__||null,!hook)return debugLog("React DevTools hook not found"),!1;if(debugLog("Hook found"),debugLog(`Hook has sub: ${"function"==typeof hook.sub}`),debugLog(`Hook has on: ${"function"==typeof hook.on}`),debugLog(`Hook has emit: ${"function"==typeof hook.emit}`),installProfilerInterceptor(),hook.rendererInterfaces&&hook.rendererInterfaces.size>0)return initialized=!0,debugLog(`Initialized with ${hook.rendererInterfaces.size} renderer(s)`),exposeGlobally(),!0;const e=setInterval(()=>{hook?.rendererInterfaces&&hook.rendererInterfaces.size>0&&(clearInterval(e),initialized=!0,debugLog(`Initialized with ${hook.rendererInterfaces.size} renderer(s) (delayed)`),exposeGlobally())},100);return setTimeout(()=>clearInterval(e),1e4),!1}function exposeGlobally(){"undefined"!=typeof window&&(window.__HIGHLIGHT_UPDATES_CONTROLLER__={enable:enable,disable:disable,toggle:toggle,isEnabled:isEnabled,setEnabled:setEnabled,subscribe:subscribe,initialize:initialize,destroy:destroy,isInitialized:()=>initialized,setHighlightCallback:setHighlightCallback})}function enable(){("undefined"==typeof __DEV__||__DEV__)&&(initialized||initialize(),globalEnabled||(debugLog("Enabling highlights"),backgroundTrackingEnabled||subscribeToTraceUpdates(),RenderTracker.start(),globalEnabled=!0,notifyStateListeners(),notifySubscriberCountChange("render")))}function disable(){("undefined"==typeof __DEV__||__DEV__)&&globalEnabled&&(debugLog("Disabling highlights"),renderingLock=!1,isProcessing=!1,renderingLockTimeout&&(clearTimeout(renderingLockTimeout),renderingLockTimeout=null),renderedOverlayTags.clear(),devToolsNodeCache.clear(),clearRenderCauseState(),backgroundTrackingEnabled||unsubscribeFromTraceUpdates(),RenderTracker.stop(),globalEnabled=!1,notifyStateListeners(),notifySubscriberCountChange("render"))}function enableBackgroundTracking(){("undefined"==typeof __DEV__||__DEV__)&&(backgroundTrackingEnabled||(initialized||initialize(),debugLog("Enabling background tracking"),globalEnabled||subscribeToTraceUpdates(),backgroundTrackingEnabled=!0))}function disableBackgroundTracking(){("undefined"==typeof __DEV__||__DEV__)&&backgroundTrackingEnabled&&(debugLog("Disabling background tracking"),backgroundTrackingEnabled=!1,globalEnabled||unsubscribeFromTraceUpdates())}function isBackgroundTrackingEnabled(){return backgroundTrackingEnabled}function toggle(){("undefined"==typeof __DEV__||__DEV__)&&(globalEnabled?disable():enable())}function clearRenderCounts(){nodeRenderCounts.clear(),RenderTracker.clear(),debugLog("Cleared render counts")}function isEnabled(){return globalEnabled}function setEnabled(e){e?enable():disable()}function isInitialized(){return initialized}function notifyFreezeListeners(){freezeListeners.forEach(e=>{try{e(isFrozen)}catch(e){console.error("[HighlightUpdates] Error in freeze listener:",e)}})}function subscribeToFreeze(e){return freezeListeners.add(e),e(isFrozen),()=>{freezeListeners.delete(e)}}function freeze(){("undefined"==typeof __DEV__||__DEV__)&&(isFrozen||(isFrozen=!0,debugLog("Freeze mode enabled"),notifyFreezeListeners()))}function unfreeze(){("undefined"==typeof __DEV__||__DEV__)&&isFrozen&&(isFrozen=!1,debugLog("Freeze mode disabled"),highlightCallback&&highlightCallback([]),notifyFreezeListeners())}function toggleFreeze(){isFrozen?unfreeze():freeze()}function getFrozen(){return isFrozen}function destroy(){initialized&&(unsubscribeFromTraceUpdates(),uninstallProfilerInterceptor(),setComparisonCallback(null),isFrozen=!1,freezeListeners.clear(),globalEnabled=!1,hook=null,highlightCallback=null,initialized=!1,"undefined"!=typeof window&&delete window.__HIGHLIGHT_UPDATES_CONTROLLER__,debugLog("Destroyed"))}const HighlightUpdatesController={subscribe:subscribe,enable:enable,disable:disable,toggle:toggle,isEnabled:isEnabled,setEnabled:setEnabled,initialize:initialize,destroy:destroy,isInitialized:isInitialized,setHighlightCallback:setHighlightCallback,clearRenderCounts:clearRenderCounts,freeze:freeze,unfreeze:unfreeze,toggleFreeze:toggleFreeze,getFrozen:getFrozen,subscribeToFreeze:subscribeToFreeze,setBadgePressCallback:setBadgePressCallback,getBadgePressCallback:getBadgePressCallback,handleBadgePress:handleBadgePress,setSpotlightCallback:setSpotlightCallback,setSpotlight:setSpotlight,getSpotlight:getSpotlight,clearDevToolsCache:clearDevToolsCache,enableBackgroundTracking:enableBackgroundTracking,disableBackgroundTracking:disableBackgroundTracking,isBackgroundTrackingEnabled:isBackgroundTrackingEnabled};export default HighlightUpdatesController;
1
+ /**
2
+ * Highlight Updates Controller
3
+ *
4
+ * Standalone implementation that replicates React DevTools' "Highlight updates
5
+ * when components render" feature WITHOUT requiring DevTools to be connected.
6
+ *
7
+ * Architecture:
8
+ * This controller directly enables the DevTools backend's traceUpdates feature
9
+ * by calling setTraceUpdatesEnabled(true) on each renderer interface. This is
10
+ * the same function that DevTools' frontend calls when you check the
11
+ * "Highlight updates when components render" checkbox.
12
+ *
13
+ * Key insight: The rendererInterfaces are available on the global hook even
14
+ * without DevTools frontend connected. We just need to enable tracing directly.
15
+ *
16
+ * Flow:
17
+ * 1. User enables highlights via toggle()
18
+ * 2. We call rendererInterface.setTraceUpdatesEnabled(true) on all renderers
19
+ * 3. DevTools backend now tracks renders and emits 'traceUpdates' events
20
+ * 4. We subscribe to 'traceUpdates' via hook.sub()
21
+ * 5. When components re-render, we receive the Set of host stateNodes
22
+ * 6. We measure each node and render colored border highlights
23
+ *
24
+ * This gives us 100% accuracy with DevTools behavior because we're using the
25
+ * exact same detection code - we're just enabling it programmatically.
26
+ */
27
+
28
+ "use strict";
29
+
30
+ import { installProfilerInterceptor, uninstallProfilerInterceptor, setComparisonCallback } from "./ProfilerInterceptor";
31
+ import { RenderTracker } from "./RenderTracker";
32
+ import { PerformanceLogger, markEventReceived } from "./PerformanceLogger";
33
+ import { detectRenderCause, clearRenderCauseState } from "./RenderCauseDetector";
34
+ import { notifySubscriberCountChange } from "@buoy-gg/shared-ui";
35
+ // State
36
+ let globalEnabled = false; // User-controlled toggle for visual highlights
37
+ let backgroundTrackingEnabled = false; // Auto-enabled when event callbacks exist (Events tool)
38
+ let initialized = false;
39
+ let hook = null;
40
+ let highlightCallback = null;
41
+ let badgePressCallback = null;
42
+ let traceUpdatesUnsubscribe = null;
43
+ let isProcessing = false;
44
+
45
+ // Freeze frame state
46
+ let isFrozen = false;
47
+ const freezeListeners = new Set();
48
+ const stateListeners = new Set();
49
+
50
+ // Track render counts per node (for color assignment like DevTools)
51
+ // Map from nativeTag to render count - nativeTag is stable across re-renders
52
+ const nodeRenderCounts = new Map();
53
+
54
+ // Color palette for highlights (same as DevTools)
55
+ // From: react-devtools-core/dist/backend.js line 6361
56
+ const COLORS = ["#37afa9", "#63b19e", "#80b393", "#97b488", "#abb67d", "#beb771", "#cfb965", "#dfba57", "#efbb49", "#febc38"];
57
+
58
+ // Set to true for verbose debugging of our implementation
59
+ // Disabled for now to focus on profiler logs only
60
+ const DEBUG = false;
61
+ function debugLog(message, data) {
62
+ if (!DEBUG) return;
63
+ if (data !== undefined) {
64
+ console.log(`[HighlightUpdates] ${message}`, data);
65
+ } else {
66
+ console.log(`[HighlightUpdates] ${message}`);
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Get the public instance from a stateNode (the node passed in traceUpdates)
72
+ */
73
+ function getPublicInstance(stateNode) {
74
+ if (!stateNode) return null;
75
+ const node = stateNode;
76
+
77
+ // Fabric: stateNode.canonical.publicInstance
78
+ if (node.canonical?.publicInstance) {
79
+ return node.canonical.publicInstance;
80
+ }
81
+
82
+ // Legacy Fabric: stateNode.canonical with measure
83
+ if (node.canonical && typeof node.canonical.measure === "function") {
84
+ return node.canonical;
85
+ }
86
+
87
+ // Legacy renderer: stateNode has measure directly
88
+ if (typeof node.measure === "function") {
89
+ return node;
90
+ }
91
+ return null;
92
+ }
93
+
94
+ /**
95
+ * Get native tag from public instance or stateNode
96
+ */
97
+ function getNativeTag(instance) {
98
+ if (instance == null) return null;
99
+ const inst = instance;
100
+
101
+ // Try direct properties
102
+ if (inst.__nativeTag != null) return inst.__nativeTag;
103
+ if (inst._nativeTag != null) return inst._nativeTag;
104
+ if (inst.nativeTag != null) return inst.nativeTag;
105
+
106
+ // Try canonical
107
+ if (inst.canonical) {
108
+ if (inst.canonical.__nativeTag != null) return inst.canonical.__nativeTag;
109
+ if (inst.canonical._nativeTag != null) return inst.canonical._nativeTag;
110
+ }
111
+ return null;
112
+ }
113
+
114
+ /**
115
+ * Extract component info from a stateNode for RenderTracker
116
+ */
117
+ function extractComponentInfo(stateNode) {
118
+ const node = stateNode;
119
+ const info = {
120
+ viewType: "Unknown"
121
+ };
122
+
123
+ // Get viewType from viewConfig
124
+ if (node?.canonical?.viewConfig?.uiViewClassName) {
125
+ info.viewType = node.canonical.viewConfig.uiViewClassName;
126
+ } else if (node?.viewConfig?.uiViewClassName) {
127
+ info.viewType = node.viewConfig.uiViewClassName;
128
+ }
129
+
130
+ // Try to get props from various locations
131
+ // Fabric: canonical.internalInstanceHandle, Paper: _internalInstanceHandle, RN CLI DEV: _internalFiberInstanceHandleDEV
132
+ const fiber = node?.canonical?.internalInstanceHandle || node?._internalInstanceHandle || node?._internalFiberInstanceHandleDEV;
133
+ const currentProps = node?.canonical?.currentProps;
134
+ const pendingProps = node?.canonical?.pendingProps;
135
+ const fiberPendingProps = fiber?.pendingProps;
136
+ const fiberMemoizedProps = fiber?.memoizedProps;
137
+
138
+ // Extract testID
139
+ info.testID = currentProps?.testID || pendingProps?.testID || fiberPendingProps?.testID || fiberMemoizedProps?.testID || undefined;
140
+
141
+ // Extract nativeID
142
+ info.nativeID = currentProps?.nativeID || pendingProps?.nativeID || fiberPendingProps?.nativeID || fiberMemoizedProps?.nativeID || undefined;
143
+
144
+ // Extract accessibilityLabel
145
+ info.accessibilityLabel = currentProps?.accessibilityLabel || pendingProps?.accessibilityLabel || fiberPendingProps?.accessibilityLabel || fiberMemoizedProps?.accessibilityLabel || undefined;
146
+
147
+ // Extract componentName - use getOwningComponentName to get the React component
148
+ // that rendered this host component
149
+ info.componentName = getOwningComponentName(fiber) || undefined;
150
+ return info;
151
+ }
152
+
153
+ /**
154
+ * Describe a node for logging (extensive version for debugging)
155
+ */
156
+ function describeNodeForLog(stateNode) {
157
+ const node = stateNode;
158
+ const publicInstance = getPublicInstance(stateNode);
159
+ const nativeTag = getNativeTag(stateNode) || getNativeTag(publicInstance);
160
+ const info = {
161
+ nativeTag: nativeTag ?? "unknown",
162
+ type: node?.canonical ? "Fabric" : "Legacy",
163
+ hasMeasure: typeof publicInstance?.measure === "function"
164
+ };
165
+
166
+ // Extract as much info as possible from the stateNode
167
+ if (node) {
168
+ // Direct properties on stateNode
169
+ info.stateNodeKeys = Object.keys(node).slice(0, 20);
170
+
171
+ // Check the 'node' property (might have useful info)
172
+ if (node.node) {
173
+ info.nodeKeys = Object.keys(node.node).slice(0, 20);
174
+ }
175
+
176
+ // Check for viewConfig (contains component type info)
177
+ if (node.viewConfig) {
178
+ info.viewConfig = {
179
+ uiViewClassName: node.viewConfig.uiViewClassName,
180
+ validAttributes: node.viewConfig.validAttributes ? Object.keys(node.viewConfig.validAttributes).slice(0, 10) : undefined
181
+ };
182
+ }
183
+
184
+ // Check canonical structure (Fabric)
185
+ if (node.canonical) {
186
+ const canonical = node.canonical;
187
+ info.canonicalKeys = Object.keys(canonical).slice(0, 20);
188
+ if (canonical.viewConfig) {
189
+ info.canonicalViewConfig = {
190
+ uiViewClassName: canonical.viewConfig.uiViewClassName
191
+ };
192
+ }
193
+ if (canonical.nativeTag != null) {
194
+ info.canonicalNativeTag = canonical.nativeTag;
195
+ }
196
+
197
+ // Check internalInstanceHandle (THE FIBER!)
198
+ if (canonical.internalInstanceHandle) {
199
+ const fiber = canonical.internalInstanceHandle;
200
+ info.fiberKeys = Object.keys(fiber).slice(0, 30);
201
+
202
+ // Component type info
203
+ if (fiber.type) {
204
+ info.fiberType = typeof fiber.type === "function" ? fiber.type.name || fiber.type.displayName || "function" : fiber.type;
205
+ }
206
+ if (fiber.elementType) {
207
+ info.fiberElementType = typeof fiber.elementType === "function" ? fiber.elementType.name || fiber.elementType.displayName || "function" : fiber.elementType;
208
+ }
209
+
210
+ // Debug info on fiber
211
+ if (fiber._debugOwner) {
212
+ const owner = fiber._debugOwner;
213
+ info.fiberDebugOwner = owner.type?.name || owner.type?.displayName || owner.elementType?.name || "unknown";
214
+ }
215
+ if (fiber._debugSource) {
216
+ info.fiberDebugSource = fiber._debugSource;
217
+ }
218
+
219
+ // Fiber tag (tells us what kind of fiber it is)
220
+ if (fiber.tag != null) {
221
+ info.fiberTag = fiber.tag;
222
+ }
223
+
224
+ // pendingProps on fiber might have testID/nativeID
225
+ if (fiber.pendingProps) {
226
+ if (fiber.pendingProps.nativeID) info.fiberPendingNativeID = fiber.pendingProps.nativeID;
227
+ if (fiber.pendingProps.testID) info.fiberPendingTestID = fiber.pendingProps.testID;
228
+ }
229
+ if (fiber.memoizedProps) {
230
+ if (fiber.memoizedProps.nativeID) info.fiberMemoizedNativeID = fiber.memoizedProps.nativeID;
231
+ if (fiber.memoizedProps.testID) info.fiberMemoizedTestID = fiber.memoizedProps.testID;
232
+ }
233
+ }
234
+
235
+ // Check publicInstance
236
+ if (canonical.publicInstance) {
237
+ const pub = canonical.publicInstance;
238
+ info.publicInstanceKeys = Object.keys(pub).slice(0, 20);
239
+
240
+ // Look for nativeID
241
+ if (pub.nativeID != null) info.nativeID = pub.nativeID;
242
+ if (pub._nativeID != null) info._nativeID = pub._nativeID;
243
+
244
+ // Look for props
245
+ if (pub.props) {
246
+ info.publicInstanceProps = Object.keys(pub.props).slice(0, 15);
247
+ if (pub.props.nativeID) info.propsNativeID = pub.props.nativeID;
248
+ if (pub.props.testID) info.propsTestID = pub.props.testID;
249
+ if (pub.props.accessibilityLabel) info.accessibilityLabel = pub.props.accessibilityLabel;
250
+ }
251
+ }
252
+
253
+ // Check for currentProps - log actual VALUES
254
+ if (canonical.currentProps) {
255
+ info.currentPropsKeys = Object.keys(canonical.currentProps).slice(0, 15);
256
+ // Log actual values of identifying props
257
+ if (canonical.currentProps.nativeID != null) info.currentPropsNativeID = canonical.currentProps.nativeID;
258
+ if (canonical.currentProps.testID != null) info.currentPropsTestID = canonical.currentProps.testID;
259
+ if (canonical.currentProps.accessibilityLabel != null) info.currentPropsAccessLabel = canonical.currentProps.accessibilityLabel;
260
+ }
261
+
262
+ // Check for pendingProps
263
+ if (canonical.pendingProps) {
264
+ info.pendingPropsKeys = Object.keys(canonical.pendingProps).slice(0, 15);
265
+ if (canonical.pendingProps.nativeID != null) info.pendingPropsNativeID = canonical.pendingProps.nativeID;
266
+ if (canonical.pendingProps.testID != null) info.pendingPropsTestID = canonical.pendingProps.testID;
267
+ }
268
+ }
269
+
270
+ // Check for fiber reference directly on node
271
+ if (node._debugOwner) {
272
+ const owner = node._debugOwner;
273
+ info.debugOwnerType = owner.type?.name || owner.type?.displayName || typeof owner.type;
274
+ }
275
+ if (node._debugSource) {
276
+ info.debugSource = node._debugSource;
277
+ }
278
+ }
279
+ return info;
280
+ }
281
+
282
+ // Set to true to enable debug logging
283
+ const DEBUG_LOGGING = false;
284
+
285
+ // Lock to prevent infinite loops when rendering our overlay
286
+ let renderingLock = false;
287
+ let renderingLockTimeout = null;
288
+
289
+ // How long to ignore new events after starting a render (ms)
290
+ // Should match HIGHLIGHT_DURATION in the overlay to prevent false triggers
291
+ const RENDER_LOCK_DURATION = 350;
292
+
293
+ // Track nativeTags of components we're currently highlighting
294
+ // This helps us identify (and skip) our own overlay Views if they re-render
295
+ const renderedOverlayTags = new Set();
296
+
297
+ /**
298
+ * Check if a nativeTag belongs to our overlay (was rendered by us previously)
299
+ */
300
+ function isOurOverlayTag(nativeTag) {
301
+ if (nativeTag == null) return false;
302
+ return renderedOverlayTags.has(nativeTag);
303
+ }
304
+
305
+ // ============================================================================
306
+ // OPTIMIZED DEV TOOLS DETECTION
307
+ // ============================================================================
308
+ // Performance optimizations applied:
309
+ // 1. Result caching by nativeTag (same tag = same result)
310
+ // 2. Set-based O(1) lookups instead of multiple string comparisons
311
+ // 3. Component name check FIRST (appears early in tree, ~depth 5-8)
312
+ // 4. Early exit on first match
313
+ // 5. Cached property access to avoid repeated traversal
314
+ // ============================================================================
315
+
316
+ // Components that MUST always be excluded to prevent infinite loops.
317
+ // Includes the Highlight Updates overlay AND the Events tool (which subscribes
318
+ // to render callbacks via RenderTracker.onRenderEvent - tracking its renders
319
+ // would create an infinite callback loop).
320
+ const HIGHLIGHT_OVERLAY_COMPONENTS = new Set([
321
+ // Highlight Updates overlay components
322
+ "HighlightUpdatesOverlay", "HighlightUpdatesModal", "HighlightFilterView", "RenderDetailView", "RenderListItem", "RenderListItemInner", "RenderHistoryViewer", "RenderHistoryFooter", "RenderCauseBadge", "TwoLevelCauseBadge", "EnhancedCauseDisplay", "IsolatedRenderList", "IsolatedRenderListInner", "StatsDisplay", "StatsDisplayInner", "CurrentStateView", "EventStepperFooter",
323
+ // Events tool components - subscribes to onRenderEvent, tracking these causes infinite loops
324
+ "EventsModal", "UnifiedEventList", "UnifiedEventItem", "UnifiedEventDetail", "UnifiedEventFilters", "UnifiedEventViewer", "ReactQueryEventDetail", "EventsCopySettingsView"]);
325
+
326
+ // Native IDs that MUST always be excluded (highlight overlay)
327
+ const HIGHLIGHT_OVERLAY_NATIVE_IDS = new Set(["highlight-updates-overlay", "__rn_buoy__highlight-modal"]);
328
+
329
+ // Prefixes for always-excluded components (highlight overlay + events tool)
330
+ const HIGHLIGHT_OVERLAY_PREFIXES = ["HighlightUpdates", "RenderList", "RenderDetail", "RenderHistory", "RenderCause", "EventStepper",
331
+ // Events tool - subscribes to onRenderEvent, must always be excluded
332
+ "UnifiedEvent", "EventsModal", "EventsCopy"];
333
+
334
+ // Other dev tools components - can be toggled via excludeDevTools setting
335
+ const OTHER_DEV_TOOLS_COMPONENTS = new Set([
336
+ // React Buoy devtools components
337
+ "JsModalComponent", "JsModal", "TypePicker", "PatternInput", "PatternChip", "DetectedItemsSection", "DetectedCategoryBadge", "IdentifierBadge", "CategoryBadge", "AppRenderer", "AppOverlay", "FloatingTools", "DialDevTools", "DevToolsVisibilityProvider", "AppHostProvider", "MinimizedToolsProvider",
338
+ // Shared UI components used in modals
339
+ "ModalHeader", "TabSelector", "SectionHeader", "DraggableHeader", "WindowControls",
340
+ // Shared UI data viewer components (JSON diff viewers, etc.)
341
+ "TreeDiffViewer", "DataViewer", "SplitDiffViewer", "VirtualizedDataExplorer", "DiffSummary", "TypeLegend", "IndentGuides", "IndentGuidesOverlay", "CyberpunkInput", "DiffView", "AnswerCard", "DetailsSection", "DetailRow", "QuickActionsSection", "FilterOptionCard",
342
+ // Modal header sub-components
343
+ "SearchSection", "SearchSectionInner", "HeaderActions", "HeaderActionsInner", "MainListHeader", "FilterViewHeader", "DetailViewHeader",
344
+ // Floating menu components (minimized tools, dial, etc.)
345
+ "FloatingMenu", "FloatingDevTools", "MinimizedToolsStack", "MinimizedToolsContext", "GlitchToolButton", "ExpandablePopover", "CollapsedPeek", "ExpandedWrapper", "DialIcon", "DialMenu", "DialIconItem", "OnboardingTooltip", "MenuLauncherIcon", "DevToolsSettingsModal", "SettingsModal",
346
+ // Image Overlay components
347
+ "ImageOverlayModal", "ImageOverlayStandalone", "ToolCard", "ToolIcon", "GripVerticalIcon", "UserStatus", "Divider",
348
+ // Shared UI icon components (Chevrons, etc.)
349
+ "ChevronDown", "ChevronUp", "ChevronLeft", "ChevronRight", "ChevronDownIcon", "ChevronUpIcon", "ChevronLeftIcon", "ChevronRightIcon",
350
+ // React Native LogBox components (shown on reload/errors)
351
+ "LogBox", "LogBoxLog", "LogBoxLogNotification", "LogBoxNotificationContainer", "_LogBoxNotificationContainer", "LogBoxInspector", "LogBoxInspectorContainer", "LogBoxInspectorHeader", "LogBoxInspectorBody", "LogBoxInspectorFooter", "LogBoxInspectorMessageHeader", "LogBoxInspectorStackFrame", "LogBoxInspectorSection", "LogBoxButton", "LogBoxMessage"]);
352
+
353
+ // Other dev tools prefixes - can be toggled via excludeDevTools setting
354
+ const OTHER_DEV_TOOLS_PREFIXES = ["JsModal", "TreeDiff", "DataViewer", "DiffView", "DiffSummary", "Virtualized",
355
+ // Floating menu prefixes
356
+ "Floating", "Minimized", "Dial", "Expandable", "Chevron", "Glitch", "Settings", "Onboarding", "DevTools", "ImageOverlay"];
357
+
358
+ // Other dev tools native IDs - can be toggled
359
+ const OTHER_DEV_TOOLS_NATIVE_IDS = new Set(["jsmodal-root", "image-overlay-standalone",
360
+ // LogBox native IDs
361
+ "logbox_inspector", "logbox"]);
362
+
363
+ // Cache: nativeTag -> isDevTools (avoid re-walking tree for same node)
364
+ const devToolsNodeCache = new Map();
365
+ const CACHE_MAX_SIZE = 500;
366
+
367
+ /**
368
+ * Clear the devtools node cache.
369
+ * Call this when the excludeDevTools setting changes to re-evaluate all nodes.
370
+ */
371
+ function clearDevToolsCache() {
372
+ devToolsNodeCache.clear();
373
+ }
374
+
375
+ /**
376
+ * Check if a nativeID belongs to highlight overlay (always excluded)
377
+ */
378
+ function isHighlightOverlayNativeID(nativeID) {
379
+ if (!nativeID) return false;
380
+ // Direct Set lookup (O(1))
381
+ if (HIGHLIGHT_OVERLAY_NATIVE_IDS.has(nativeID)) return true;
382
+ // Prefix check for highlight overlay
383
+ if (nativeID.startsWith("__highlight_")) return true;
384
+ return false;
385
+ }
386
+
387
+ /**
388
+ * Check if a nativeID belongs to other dev tools (optionally excluded)
389
+ */
390
+ function isOtherDevToolsNativeID(nativeID) {
391
+ if (!nativeID) return false;
392
+ // Direct Set lookup (O(1))
393
+ if (OTHER_DEV_TOOLS_NATIVE_IDS.has(nativeID)) return true;
394
+ // Prefix checks for other devtools nativeIDs
395
+ const firstChar = nativeID.charCodeAt(0);
396
+ if (firstChar === 95) {
397
+ // '_' = 95
398
+ if (nativeID.startsWith("__rn_buoy__")) return true;
399
+ }
400
+ // Check for LogBox nativeIDs (start with 'l')
401
+ if (firstChar === 108 && nativeID.startsWith("logbox")) {
402
+ // 'l' = 108
403
+ return true;
404
+ }
405
+ return false;
406
+ }
407
+
408
+ /**
409
+ * Get component name from fiber (cached property access pattern)
410
+ * For host components (RCTView, RCTText), returns the native type.
411
+ * Use getOwningComponentName to get the React component that rendered it.
412
+ */
413
+ function getComponentName(fiber) {
414
+ if (!fiber) return null;
415
+ // Most common: type.name
416
+ const type = fiber.type;
417
+ if (type) {
418
+ if (typeof type === 'string') return type;
419
+ if (type.name) return type.name;
420
+ if (type.displayName) return type.displayName;
421
+ }
422
+ // Fallback: elementType
423
+ const elementType = fiber.elementType;
424
+ if (elementType) {
425
+ if (elementType.name) return elementType.name;
426
+ if (elementType.displayName) return elementType.displayName;
427
+ }
428
+ return null;
429
+ }
430
+
431
+ // Common React Native internal component names to skip when finding user components
432
+ const INTERNAL_COMPONENT_NAMES = new Set([
433
+ // React Native core
434
+ 'View', 'Text', 'TextImpl', 'Image', 'ScrollView', 'FlatList', 'SectionList', 'TouchableOpacity', 'TouchableHighlight', 'TouchableWithoutFeedback', 'Pressable', 'TextInput', 'Switch', 'ActivityIndicator', 'Modal', 'StatusBar', 'KeyboardAvoidingView',
435
+ // Animated components
436
+ 'AnimatedComponent', 'AnimatedComponentWrapper',
437
+ // React Navigation / Screens
438
+ 'ScreenContainer', 'ScreenStack', 'Screen', 'ScreenContentWrapper',
439
+ // SVG components
440
+ 'Svg', 'G', 'Path', 'Rect', 'Circle', 'Line', 'Polygon', 'Polyline', 'Ellipse', 'Text as SVGText', 'TSpan', 'TextPath', 'Use', 'Symbol', 'Defs', 'ClipPath', 'LinearGradient', 'RadialGradient', 'Stop', 'Mask', 'Pattern', 'Image as SVGImage',
441
+ // SafeArea
442
+ 'SafeAreaProvider', 'SafeAreaView', 'SafeAreaListener',
443
+ // Gesture Handler
444
+ 'GestureHandlerRootView', 'GestureDetector',
445
+ // Reanimated
446
+ 'ReanimatedView', 'ReanimatedText', 'ReanimatedImage', 'ReanimatedScrollView',
447
+ // Common wrapper names
448
+ 'Fragment', 'Suspense', 'Provider', 'Consumer', 'Context', 'ForwardRef']);
449
+
450
+ /**
451
+ * Check if a component name is an internal/wrapper component that should be skipped
452
+ */
453
+ function isInternalComponent(name) {
454
+ if (!name) return true;
455
+ if (INTERNAL_COMPONENT_NAMES.has(name)) return true;
456
+ // Skip anonymous components and common patterns
457
+ if (name === 'Unknown' || name === 'Component') return true;
458
+ // Skip Animated.* wrappers
459
+ if (name.startsWith('Animated')) return true;
460
+ return false;
461
+ }
462
+
463
+ /**
464
+ * Get the owning React component name for a host fiber.
465
+ * Walks up the fiber tree to find the first user-defined component,
466
+ * skipping React Native internal components.
467
+ */
468
+ function getOwningComponentName(fiber) {
469
+ if (!fiber) return null;
470
+
471
+ // Walk up the fiber tree looking for a user-defined component
472
+ let current = fiber._debugOwner || fiber.return;
473
+ let depth = 0;
474
+ let firstNonHostName = null;
475
+ while (current && depth < 30) {
476
+ const name = getComponentName(current);
477
+
478
+ // Skip host components (their type is a string like "RCTView")
479
+ if (name && typeof current.type !== 'string') {
480
+ // Remember the first non-host component as fallback
481
+ if (!firstNonHostName) {
482
+ firstNonHostName = name;
483
+ }
484
+ // Return this component if it's not an internal wrapper
485
+ if (!isInternalComponent(name)) {
486
+ return name;
487
+ }
488
+ }
489
+ current = current.return;
490
+ depth++;
491
+ }
492
+
493
+ // Fallback to first non-host component found (even if internal)
494
+ return firstNonHostName;
495
+ }
496
+
497
+ /**
498
+ * Check if a stateNode belongs to our dev tools.
499
+ *
500
+ * OPTIMIZED: Uses caching, O(1) Set lookups, and early exit patterns.
501
+ * Walks up fiber tree checking component names (fast) before nativeIDs.
502
+ *
503
+ * When excludeDevTools setting is false, only the Highlight Updates overlay
504
+ * is excluded (to prevent infinite loops). Other dev tools will be highlighted.
505
+ */
506
+ function isOurOverlayNode(stateNode) {
507
+ const node = stateNode;
508
+ // Fabric: fiber is at canonical.internalInstanceHandle
509
+ // Paper/Legacy: fiber is at _internalInstanceHandle directly on stateNode
510
+ // RN CLI DEV: fiber is at _internalFiberInstanceHandleDEV
511
+ const fiber = node?.canonical?.internalInstanceHandle || node?._internalInstanceHandle || node?._internalFiberInstanceHandleDEV;
512
+
513
+ // Get nativeTag for caching
514
+ const nativeTag = getNativeTag(stateNode) || getNativeTag(node?.canonical?.publicInstance);
515
+
516
+ // Check if we should exclude all dev tools or just highlight overlay
517
+ const excludeDevTools = RenderTracker.getSettings().excludeDevTools;
518
+
519
+ // Check cache first (O(1)) - but only for the current excludeDevTools setting
520
+ // When excludeDevTools is false, skip cache to re-evaluate all nodes
521
+ if (nativeTag != null && excludeDevTools) {
522
+ const cached = devToolsNodeCache.get(nativeTag);
523
+ if (cached !== undefined) {
524
+ return cached;
525
+ }
526
+ }
527
+ let result = false;
528
+
529
+ // Fast path: check direct nativeID
530
+ const directNativeID = fiber?.pendingProps?.nativeID || fiber?.memoizedProps?.nativeID || node?.canonical?.currentProps?.nativeID || null;
531
+
532
+ // Always check highlight overlay nativeIDs first (must always be excluded)
533
+ if (isHighlightOverlayNativeID(directNativeID)) {
534
+ result = true;
535
+ } else if (excludeDevTools && isOtherDevToolsNativeID(directNativeID)) {
536
+ // Only check other dev tools if excludeDevTools is enabled
537
+ result = true;
538
+ }
539
+ if (!result && fiber) {
540
+ // Walk up fiber tree - check component names FIRST (they appear early)
541
+ let current = fiber;
542
+ let depth = 0;
543
+
544
+ // Reduced max depth - component names appear by depth 15 typically
545
+ while (current && depth < 30) {
546
+ // Component name check FIRST (faster, appears earlier in tree)
547
+ const name = getComponentName(current);
548
+ if (name) {
549
+ // Always check highlight overlay components (must always be excluded)
550
+ if (HIGHLIGHT_OVERLAY_COMPONENTS.has(name)) {
551
+ result = true;
552
+ break;
553
+ }
554
+ // Check highlight overlay prefixes
555
+ for (const prefix of HIGHLIGHT_OVERLAY_PREFIXES) {
556
+ if (name.startsWith(prefix)) {
557
+ result = true;
558
+ break;
559
+ }
560
+ }
561
+ if (result) break;
562
+
563
+ // Only check other dev tools if excludeDevTools is enabled
564
+ if (excludeDevTools) {
565
+ if (OTHER_DEV_TOOLS_COMPONENTS.has(name)) {
566
+ result = true;
567
+ break;
568
+ }
569
+ // Check other dev tools prefixes
570
+ for (const prefix of OTHER_DEV_TOOLS_PREFIXES) {
571
+ if (name.startsWith(prefix)) {
572
+ result = true;
573
+ break;
574
+ }
575
+ }
576
+ if (result) break;
577
+ }
578
+ }
579
+
580
+ // NativeID check (only if component name didn't match)
581
+ const nativeID = current.pendingProps?.nativeID || current.memoizedProps?.nativeID;
582
+ if (isHighlightOverlayNativeID(nativeID)) {
583
+ result = true;
584
+ break;
585
+ }
586
+ if (excludeDevTools && isOtherDevToolsNativeID(nativeID)) {
587
+ result = true;
588
+ break;
589
+ }
590
+ current = current.return;
591
+ depth++;
592
+ }
593
+ }
594
+
595
+ // Only cache positive results when excludeDevTools is true (default mode)
596
+ // Don't cache when excludeDevTools is false to avoid complex cache invalidation
597
+ if (result && nativeTag != null && excludeDevTools) {
598
+ if (devToolsNodeCache.size >= CACHE_MAX_SIZE) {
599
+ // Clear oldest entries (simple strategy - clear half)
600
+ const entries = Array.from(devToolsNodeCache.keys());
601
+ for (let i = 0; i < CACHE_MAX_SIZE / 2; i++) {
602
+ devToolsNodeCache.delete(entries[i]);
603
+ }
604
+ }
605
+ devToolsNodeCache.set(nativeTag, result);
606
+ }
607
+ return result;
608
+ }
609
+
610
+ /**
611
+ * Get color based on render count (same algorithm as DevTools)
612
+ * More renders = warmer color (cyan → yellow)
613
+ */
614
+ function getColorForRenderCount(count) {
615
+ // Clamp to color array bounds
616
+ const index = Math.min(count - 1, COLORS.length - 1);
617
+ return COLORS[Math.max(0, index)];
618
+ }
619
+
620
+ /**
621
+ * Handle traceUpdates event from DevTools backend
622
+ * This is called with a Set of stateNodes that should be highlighted
623
+ *
624
+ * Strategy to prevent infinite loops:
625
+ * 1. Use a rendering lock while rendering highlights
626
+ * 2. Use an isProcessing flag to prevent concurrent processing
627
+ * 3. If Chrome DevTools agent is available, use native overlay (faster, no React)
628
+ * 4. Otherwise, use our React overlay with locks to prevent cascading renders
629
+ */
630
+ function handleTraceUpdates(nodes) {
631
+ if (nodes.size === 0) {
632
+ return;
633
+ }
634
+
635
+ // Skip if neither visual toggle nor background tracking is enabled
636
+ if (!globalEnabled && !backgroundTrackingEnabled) {
637
+ return;
638
+ }
639
+
640
+ // Skip processing when paused - don't count renders or show highlights
641
+ const trackerState = RenderTracker.getState();
642
+ if (trackerState.isPaused) {
643
+ return;
644
+ }
645
+
646
+ // Mark event received for end-to-end timing
647
+ if (PerformanceLogger.isEnabled()) {
648
+ markEventReceived();
649
+ }
650
+
651
+ // Start performance timing
652
+ const batchSize = RenderTracker.getBatchSize();
653
+ const perfTimer = PerformanceLogger.startBatch(nodes.size, batchSize);
654
+
655
+ // NOTE: Lock-based skipping disabled - relying on nativeID filtering instead
656
+ // If nativeID filtering doesn't work, re-enable this:
657
+ //
658
+ // if (renderingLock || isProcessing) {
659
+ // if (DEBUG_LOGGING) {
660
+ // console.log(`[HighlightUpdates] SKIPPED - lock:${renderingLock} processing:${isProcessing}`);
661
+ // }
662
+ // return;
663
+ // }
664
+ // isProcessing = true;
665
+
666
+ // Process nodes: track render counts and assign colors
667
+ // Filter out our own overlay nodes to prevent infinite loop
668
+ // Also apply user-defined filters to both overlay AND tracking
669
+ const nodesToDraw = [];
670
+ let skippedOverlayCount = 0;
671
+ let skippedByFilterCount = 0;
672
+ const hasActiveFilters = RenderTracker.hasActiveFilters();
673
+ for (const stateNode of nodes) {
674
+ if (stateNode && typeof stateNode === "object") {
675
+ try {
676
+ // Skip our own overlay nodes (identified by nativeID)
677
+ if (isOurOverlayNode(stateNode)) {
678
+ skippedOverlayCount++;
679
+ continue;
680
+ }
681
+
682
+ // Get nativeTag for tracking render counts
683
+ const publicInstance = getPublicInstance(stateNode);
684
+ const nativeTag = getNativeTag(stateNode) || getNativeTag(publicInstance);
685
+ if (nativeTag == null) {
686
+ continue;
687
+ }
688
+
689
+ // Extract component info for filtering
690
+ const componentInfo = extractComponentInfo(stateNode);
691
+
692
+ // Apply user-defined filters - skip components that don't pass filters
693
+ // This affects BOTH the overlay highlights AND the render list
694
+ if (hasActiveFilters && !RenderTracker.passesFilters(componentInfo)) {
695
+ skippedByFilterCount++;
696
+ continue;
697
+ }
698
+
699
+ // Check if render counting is enabled
700
+ const showRenderCount = RenderTracker.getSettings().showRenderCount;
701
+ let newCount;
702
+ let color;
703
+ if (showRenderCount) {
704
+ // Get current render count and increment (using nativeTag as stable key)
705
+ const currentCount = nodeRenderCounts.get(nativeTag) || 0;
706
+ newCount = currentCount + 1;
707
+ nodeRenderCounts.set(nativeTag, newCount);
708
+ // Assign color based on render count
709
+ color = getColorForRenderCount(newCount);
710
+ } else {
711
+ // Skip counting - use fixed color and count of 0
712
+ newCount = 0;
713
+ color = COLORS[0]; // Use first color (cyan)
714
+ }
715
+ nodesToDraw.push({
716
+ node: stateNode,
717
+ color,
718
+ count: newCount
719
+ });
720
+ } catch {
721
+ // Skip nodes from custom renderers (e.g. React Native Skia) that have
722
+ // non-standard stateNode structures
723
+ }
724
+ }
725
+ }
726
+
727
+ // Mark filtering phase complete (includes both overlay nodes and user-filtered nodes)
728
+ perfTimer.markFilteringComplete(skippedOverlayCount + skippedByFilterCount, nodesToDraw.length);
729
+
730
+ // Only log if there are real updates (not just overlay re-renders)
731
+ if (nodesToDraw.length === 0) {
732
+ // All nodes were overlay nodes - silently skip
733
+ perfTimer.finish(); // Still log the batch even if empty
734
+ return;
735
+ }
736
+
737
+ // Log actual component updates
738
+ if (DEBUG_LOGGING) {
739
+ console.log(`[HighlightUpdates] ${nodesToDraw.length} component(s) re-rendered`);
740
+ }
741
+
742
+ // NOTE: We prefer our React overlay for standalone operation.
743
+ // The native overlay only works when Chrome DevTools profiler is actively enabled.
744
+ // Uncomment below to use native overlay when available:
745
+ //
746
+ // const agent = hook?.reactDevtoolsAgent;
747
+ // if (agent?.emit) {
748
+ // if (DEBUG_LOGGING) {
749
+ // console.log(`[HighlightUpdates] Using native overlay (agent available)`);
750
+ // }
751
+ // agent.emit("drawTraceUpdates", nodesToDraw);
752
+ // isProcessing = false;
753
+ // return;
754
+ // }
755
+
756
+ // Check if we should process - either we have a visual callback OR event callbacks
757
+ const hasEventCallbacks = RenderTracker.getRenderEventCallbackCount() > 0;
758
+ if (!highlightCallback && !hasEventCallbacks) {
759
+ if (DEBUG_LOGGING) {
760
+ console.log(`[HighlightUpdates] No highlightCallback and no event callbacks - skipping render`);
761
+ }
762
+ isProcessing = false;
763
+ return;
764
+ }
765
+
766
+ // NOTE: Lock disabled - relying on nativeID filtering instead
767
+
768
+ // Measure each node and call the highlight callback
769
+ // Use batch size from RenderTracker settings (default: 150)
770
+ // Note: batchSize already retrieved above for perfTimer
771
+ perfTimer.markMeasurementStart();
772
+ const measurePromises = nodesToDraw.slice(0, batchSize).map(({
773
+ node: stateNode,
774
+ color,
775
+ count
776
+ }) => new Promise(resolve => {
777
+ const publicInstance = getPublicInstance(stateNode);
778
+ if (!publicInstance) {
779
+ resolve({
780
+ rect: null,
781
+ stateNode,
782
+ color,
783
+ count
784
+ });
785
+ return;
786
+ }
787
+ const nativeTag = getNativeTag(stateNode) || getNativeTag(publicInstance);
788
+ if (nativeTag == null) {
789
+ resolve({
790
+ rect: null,
791
+ stateNode,
792
+ color,
793
+ count
794
+ });
795
+ return;
796
+ }
797
+ try {
798
+ publicInstance.measure((x, y, width, height, pageX, pageY) => {
799
+ if (pageX == null || pageY == null || width == null || height == null) {
800
+ resolve({
801
+ rect: null,
802
+ stateNode,
803
+ color,
804
+ count
805
+ });
806
+ return;
807
+ }
808
+ resolve({
809
+ rect: {
810
+ id: nativeTag,
811
+ x: pageX,
812
+ y: pageY,
813
+ width,
814
+ height,
815
+ color,
816
+ count
817
+ },
818
+ stateNode,
819
+ color,
820
+ count
821
+ });
822
+ });
823
+ } catch (error) {
824
+ resolve({
825
+ rect: null,
826
+ stateNode,
827
+ color,
828
+ count
829
+ });
830
+ }
831
+ }));
832
+ Promise.all(measurePromises).then(results => {
833
+ const validResults = results.filter(r => r.rect !== null);
834
+ const rects = validResults.map(r => r.rect);
835
+
836
+ // Mark measurement phase complete
837
+ perfTimer.markMeasurementComplete(validResults.length, results.length - validResults.length);
838
+
839
+ // Track renders - behavior differs based on what's enabled:
840
+ // - globalEnabled (visual tool): full tracking with storage and list updates
841
+ // - backgroundTrackingEnabled only (Events tool): emit events only, no storage
842
+ const settings = RenderTracker.getSettings();
843
+ const trackCauses = settings.trackRenderCauses && settings.showRenderCount;
844
+ let batchNativeTags = null;
845
+ if (trackCauses) {
846
+ batchNativeTags = new Set();
847
+ for (const {
848
+ rect
849
+ } of validResults) {
850
+ if (rect) {
851
+ batchNativeTags.add(rect.id);
852
+ }
853
+ }
854
+ }
855
+ if (globalEnabled) {
856
+ // Visual tool is on - full tracking with storage and list notifications
857
+ RenderTracker.startBatch();
858
+ for (const {
859
+ rect,
860
+ stateNode,
861
+ color,
862
+ count
863
+ } of validResults) {
864
+ if (rect) {
865
+ const componentInfo = extractComponentInfo(stateNode);
866
+ let renderCause;
867
+ if (trackCauses && batchNativeTags) {
868
+ const node = stateNode;
869
+ const fiber = node?.canonical?.internalInstanceHandle;
870
+ renderCause = detectRenderCause(rect.id, fiber, batchNativeTags, settings.debugLogLevel);
871
+ }
872
+ RenderTracker.trackRender({
873
+ nativeTag: rect.id,
874
+ viewType: componentInfo.viewType,
875
+ testID: componentInfo.testID,
876
+ nativeID: componentInfo.nativeID,
877
+ accessibilityLabel: componentInfo.accessibilityLabel,
878
+ componentName: componentInfo.componentName,
879
+ measurements: {
880
+ x: rect.x,
881
+ y: rect.y,
882
+ width: rect.width,
883
+ height: rect.height
884
+ },
885
+ color,
886
+ count,
887
+ renderCause
888
+ });
889
+ }
890
+ }
891
+ RenderTracker.endBatch();
892
+ } else {
893
+ // Only background tracking (Events tool) - emit events without storage
894
+ for (const {
895
+ rect,
896
+ stateNode,
897
+ color,
898
+ count
899
+ } of validResults) {
900
+ if (rect) {
901
+ const componentInfo = extractComponentInfo(stateNode);
902
+ let renderCause;
903
+ if (trackCauses && batchNativeTags) {
904
+ const node = stateNode;
905
+ const fiber = node?.canonical?.internalInstanceHandle;
906
+ renderCause = detectRenderCause(rect.id, fiber, batchNativeTags, settings.debugLogLevel);
907
+ }
908
+ RenderTracker.emitRenderEvent({
909
+ nativeTag: rect.id,
910
+ viewType: componentInfo.viewType,
911
+ testID: componentInfo.testID,
912
+ nativeID: componentInfo.nativeID,
913
+ accessibilityLabel: componentInfo.accessibilityLabel,
914
+ componentName: componentInfo.componentName,
915
+ measurements: {
916
+ x: rect.x,
917
+ y: rect.y,
918
+ width: rect.width,
919
+ height: rect.height
920
+ },
921
+ color,
922
+ count,
923
+ renderCause
924
+ });
925
+ }
926
+ }
927
+ }
928
+
929
+ // Mark tracking phase complete
930
+ perfTimer.markTrackingComplete();
931
+
932
+ // Only show visual highlights when the visual tool is enabled (not just background tracking)
933
+ if (rects.length > 0 && highlightCallback && globalEnabled) {
934
+ highlightCallback(rects);
935
+ }
936
+
937
+ // Mark callback phase complete and finish timing
938
+ perfTimer.markCallbackComplete();
939
+ perfTimer.finish();
940
+ }).catch(error => {
941
+ console.error("[HighlightUpdates] Error in measurement pipeline:", error);
942
+ perfTimer.finish(); // Still log timing even on error
943
+ });
944
+ }
945
+
946
+ /**
947
+ * Enable or disable trace updates on all renderer interfaces.
948
+ * This is the key function that makes standalone tracing work!
949
+ *
950
+ * The rendererInterfaces map contains the renderer backend for each React root.
951
+ * Each renderer has a setTraceUpdatesEnabled function that controls whether
952
+ * it emits 'traceUpdates' events when components re-render.
953
+ *
954
+ * See: react-devtools-core/dist/backend.js line 15487-15489
955
+ */
956
+ function setTraceUpdatesOnRenderers(enabled) {
957
+ if (!hook?.rendererInterfaces) {
958
+ debugLog("No rendererInterfaces available");
959
+ return;
960
+ }
961
+ let count = 0;
962
+ hook.rendererInterfaces.forEach((rendererInterface, rendererId) => {
963
+ if (typeof rendererInterface.setTraceUpdatesEnabled === "function") {
964
+ try {
965
+ rendererInterface.setTraceUpdatesEnabled(enabled);
966
+ count++;
967
+ debugLog(`Renderer ${rendererId}: setTraceUpdatesEnabled(${enabled})`);
968
+ } catch (error) {
969
+ debugLog(`Renderer ${rendererId}: error setting trace updates`, error);
970
+ }
971
+ } else {
972
+ debugLog(`Renderer ${rendererId}: no setTraceUpdatesEnabled method`);
973
+ }
974
+ });
975
+ debugLog(`Set trace updates ${enabled ? "enabled" : "disabled"} on ${count} renderer(s)`);
976
+
977
+ // Also try the agent if available (in case DevTools is connected)
978
+ if (hook.reactDevtoolsAgent?.setTraceUpdatesEnabled) {
979
+ try {
980
+ hook.reactDevtoolsAgent.setTraceUpdatesEnabled(enabled);
981
+ debugLog("Also set trace updates on agent");
982
+ } catch (error) {
983
+ debugLog("Error setting trace updates on agent", error);
984
+ }
985
+ }
986
+ }
987
+
988
+ /**
989
+ * Subscribe to the traceUpdates event from the hook
990
+ */
991
+ function subscribeToTraceUpdates() {
992
+ if (!hook) return;
993
+ if (traceUpdatesUnsubscribe) return; // Already subscribed
994
+
995
+ debugLog("Subscribing to traceUpdates event");
996
+
997
+ // The hook uses EventEmitter pattern with 'sub' method
998
+ // See: react-devtools-core/dist/backend.js line 17526
999
+ // hook.sub('traceUpdates', agent.onTraceUpdates)
1000
+ if (typeof hook.sub === "function") {
1001
+ traceUpdatesUnsubscribe = hook.sub("traceUpdates", handleTraceUpdates);
1002
+ debugLog("Subscribed using hook.sub()");
1003
+ } else {
1004
+ debugLog("hook.sub not available, traceUpdates may not work");
1005
+ }
1006
+
1007
+ // CRITICAL: Enable trace updates on all renderers
1008
+ // Without this, the renderers won't emit traceUpdates events
1009
+ setTraceUpdatesOnRenderers(true);
1010
+ }
1011
+
1012
+ /**
1013
+ * Unsubscribe from the traceUpdates event
1014
+ */
1015
+ function unsubscribeFromTraceUpdates() {
1016
+ // Disable trace updates on renderers first
1017
+ setTraceUpdatesOnRenderers(false);
1018
+ if (traceUpdatesUnsubscribe) {
1019
+ traceUpdatesUnsubscribe();
1020
+ traceUpdatesUnsubscribe = null;
1021
+ debugLog("Unsubscribed from traceUpdates event");
1022
+ }
1023
+ }
1024
+
1025
+ /**
1026
+ * Set the callback for rendering highlights
1027
+ */
1028
+ function setHighlightCallback(callback) {
1029
+ highlightCallback = callback;
1030
+ debugLog(`Highlight callback ${callback ? "set" : "cleared"}`);
1031
+ }
1032
+
1033
+ /**
1034
+ * Set the callback for when a badge is pressed.
1035
+ * This is used to navigate to the detail view when a user taps a render count badge.
1036
+ */
1037
+ function setBadgePressCallback(callback) {
1038
+ badgePressCallback = callback;
1039
+ debugLog(`Badge press callback ${callback ? "set" : "cleared"}`);
1040
+ }
1041
+
1042
+ /**
1043
+ * Get the current badge press callback.
1044
+ * Used by the overlay to check if badge presses should be handled.
1045
+ */
1046
+ function getBadgePressCallback() {
1047
+ return badgePressCallback;
1048
+ }
1049
+
1050
+ /**
1051
+ * Handle a badge press event.
1052
+ * Calls the registered callback with the nativeTag of the component.
1053
+ */
1054
+ function handleBadgePress(nativeTag) {
1055
+ if (badgePressCallback) {
1056
+ badgePressCallback(nativeTag);
1057
+ }
1058
+ }
1059
+
1060
+ // Spotlight highlight state - for showing which component is being viewed in detail
1061
+
1062
+ let spotlightCallback = null;
1063
+ let currentSpotlightTag = null;
1064
+
1065
+ /**
1066
+ * Set the callback for spotlight highlighting.
1067
+ * Used by the overlay to show a special highlight for the component being viewed.
1068
+ */
1069
+ function setSpotlightCallback(callback) {
1070
+ spotlightCallback = callback;
1071
+ // If there's an existing spotlight, notify the new callback
1072
+ if (callback && currentSpotlightTag !== null) {
1073
+ callback(currentSpotlightTag);
1074
+ }
1075
+ }
1076
+
1077
+ /**
1078
+ * Set a spotlight highlight on a specific component.
1079
+ * This is used when viewing a component's detail to show which one it is.
1080
+ */
1081
+ function setSpotlight(nativeTag) {
1082
+ currentSpotlightTag = nativeTag;
1083
+ if (spotlightCallback) {
1084
+ spotlightCallback(nativeTag);
1085
+ }
1086
+ }
1087
+
1088
+ /**
1089
+ * Get the current spotlight nativeTag.
1090
+ */
1091
+ function getSpotlight() {
1092
+ return currentSpotlightTag;
1093
+ }
1094
+ function notifyStateListeners() {
1095
+ stateListeners.forEach(listener => {
1096
+ try {
1097
+ listener(globalEnabled);
1098
+ } catch (error) {
1099
+ console.error("[HighlightUpdates] Error in state listener:", error);
1100
+ }
1101
+ });
1102
+ }
1103
+ function subscribe(listener) {
1104
+ stateListeners.add(listener);
1105
+ listener(globalEnabled);
1106
+ return () => {
1107
+ stateListeners.delete(listener);
1108
+ };
1109
+ }
1110
+ function initialize() {
1111
+ if (typeof __DEV__ !== "undefined" && !__DEV__) {
1112
+ debugLog("Only available in development builds");
1113
+ return false;
1114
+ }
1115
+ if (initialized) {
1116
+ return true;
1117
+ }
1118
+ hook = window?.__REACT_DEVTOOLS_GLOBAL_HOOK__ || null;
1119
+ if (!hook) {
1120
+ debugLog("React DevTools hook not found");
1121
+ return false;
1122
+ }
1123
+ debugLog("Hook found");
1124
+ debugLog(`Hook has sub: ${typeof hook.sub === "function"}`);
1125
+ debugLog(`Hook has on: ${typeof hook.on === "function"}`);
1126
+ debugLog(`Hook has emit: ${typeof hook.emit === "function"}`);
1127
+
1128
+ // Install profiler interceptor to capture what DevTools detects
1129
+ // This allows us to compare profiler data with our detection
1130
+ installProfilerInterceptor();
1131
+
1132
+ // Comparison callback available for future use when we re-enable our implementation
1133
+ // setComparisonCallback((profilerNodes: Set<unknown>) => {
1134
+ // debugLog(`[COMPARISON] Profiler detected ${profilerNodes.size} nodes`);
1135
+ // });
1136
+
1137
+ if (hook.rendererInterfaces && hook.rendererInterfaces.size > 0) {
1138
+ initialized = true;
1139
+ debugLog(`Initialized with ${hook.rendererInterfaces.size} renderer(s)`);
1140
+ exposeGlobally();
1141
+ return true;
1142
+ }
1143
+
1144
+ // Wait for renderer to be available
1145
+ const checkInterval = setInterval(() => {
1146
+ if (hook?.rendererInterfaces && hook.rendererInterfaces.size > 0) {
1147
+ clearInterval(checkInterval);
1148
+ initialized = true;
1149
+ debugLog(`Initialized with ${hook.rendererInterfaces.size} renderer(s) (delayed)`);
1150
+ exposeGlobally();
1151
+ }
1152
+ }, 100);
1153
+ setTimeout(() => clearInterval(checkInterval), 10000);
1154
+ return false;
1155
+ }
1156
+ function exposeGlobally() {
1157
+ if (typeof window !== "undefined") {
1158
+ window.__HIGHLIGHT_UPDATES_CONTROLLER__ = {
1159
+ enable,
1160
+ disable,
1161
+ toggle,
1162
+ isEnabled,
1163
+ setEnabled,
1164
+ subscribe,
1165
+ initialize,
1166
+ destroy,
1167
+ isInitialized: () => initialized,
1168
+ setHighlightCallback
1169
+ };
1170
+ }
1171
+ }
1172
+ function enable() {
1173
+ if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1174
+ if (!initialized) {
1175
+ initialize();
1176
+ }
1177
+ if (globalEnabled) {
1178
+ return;
1179
+ }
1180
+ debugLog("Enabling highlights");
1181
+
1182
+ // Only subscribe if not already subscribed via background tracking
1183
+ if (!backgroundTrackingEnabled) {
1184
+ subscribeToTraceUpdates();
1185
+ }
1186
+
1187
+ // Start tracking renders
1188
+ RenderTracker.start();
1189
+
1190
+ // Note: profiler logging disabled for normal operation
1191
+ // enableProfilerLogging();
1192
+
1193
+ globalEnabled = true;
1194
+ notifyStateListeners();
1195
+ notifySubscriberCountChange('render');
1196
+ }
1197
+ function disable() {
1198
+ if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1199
+ if (!globalEnabled) {
1200
+ return;
1201
+ }
1202
+ debugLog("Disabling highlights");
1203
+
1204
+ // Clear any pending locks/state
1205
+ renderingLock = false;
1206
+ isProcessing = false;
1207
+ if (renderingLockTimeout) {
1208
+ clearTimeout(renderingLockTimeout);
1209
+ renderingLockTimeout = null;
1210
+ }
1211
+ renderedOverlayTags.clear();
1212
+ devToolsNodeCache.clear(); // Clear detection cache
1213
+ clearRenderCauseState(); // Clear render cause state to prevent memory leaks
1214
+
1215
+ // Only unsubscribe if background tracking doesn't need it
1216
+ if (!backgroundTrackingEnabled) {
1217
+ unsubscribeFromTraceUpdates();
1218
+ }
1219
+
1220
+ // Stop tracking renders
1221
+ RenderTracker.stop();
1222
+
1223
+ // Note: profiler logging disabled for normal operation
1224
+ // disableProfilerLogging();
1225
+
1226
+ globalEnabled = false;
1227
+ notifyStateListeners();
1228
+ notifySubscriberCountChange('render');
1229
+ }
1230
+
1231
+ /**
1232
+ * Enable background render tracking (for Events tool).
1233
+ * This enables render interception WITHOUT affecting the visual toggle state.
1234
+ * The visual highlight toggle remains independent.
1235
+ */
1236
+ function enableBackgroundTracking() {
1237
+ if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1238
+ if (backgroundTrackingEnabled) {
1239
+ return;
1240
+ }
1241
+ if (!initialized) {
1242
+ initialize();
1243
+ }
1244
+ debugLog("Enabling background tracking");
1245
+
1246
+ // Only subscribe if not already subscribed via main toggle
1247
+ if (!globalEnabled) {
1248
+ subscribeToTraceUpdates();
1249
+ }
1250
+ backgroundTrackingEnabled = true;
1251
+ }
1252
+
1253
+ /**
1254
+ * Disable background render tracking (for Events tool).
1255
+ * Only actually unsubscribes if the main toggle is also off.
1256
+ */
1257
+ function disableBackgroundTracking() {
1258
+ if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1259
+ if (!backgroundTrackingEnabled) {
1260
+ return;
1261
+ }
1262
+ debugLog("Disabling background tracking");
1263
+ backgroundTrackingEnabled = false;
1264
+
1265
+ // Only unsubscribe if main toggle is also off
1266
+ if (!globalEnabled) {
1267
+ unsubscribeFromTraceUpdates();
1268
+ }
1269
+ }
1270
+
1271
+ /**
1272
+ * Check if background tracking is enabled (for debugging)
1273
+ */
1274
+ function isBackgroundTrackingEnabled() {
1275
+ return backgroundTrackingEnabled;
1276
+ }
1277
+ function toggle() {
1278
+ if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1279
+ if (globalEnabled) {
1280
+ disable();
1281
+ } else {
1282
+ enable();
1283
+ }
1284
+ }
1285
+
1286
+ /**
1287
+ * Clear all render counts and tracked data
1288
+ */
1289
+ function clearRenderCounts() {
1290
+ nodeRenderCounts.clear();
1291
+ RenderTracker.clear();
1292
+ debugLog("Cleared render counts");
1293
+ }
1294
+ function isEnabled() {
1295
+ return globalEnabled;
1296
+ }
1297
+ function setEnabled(enabled) {
1298
+ if (enabled) enable();else disable();
1299
+ }
1300
+ function isInitialized() {
1301
+ return initialized;
1302
+ }
1303
+
1304
+ // ============================================================================
1305
+ // FREEZE FRAME MODE
1306
+ // ============================================================================
1307
+
1308
+ /**
1309
+ * Notify all freeze state listeners of a change
1310
+ */
1311
+ function notifyFreezeListeners() {
1312
+ freezeListeners.forEach(listener => {
1313
+ try {
1314
+ listener(isFrozen);
1315
+ } catch (error) {
1316
+ console.error("[HighlightUpdates] Error in freeze listener:", error);
1317
+ }
1318
+ });
1319
+ }
1320
+
1321
+ /**
1322
+ * Subscribe to freeze state changes
1323
+ */
1324
+ function subscribeToFreeze(listener) {
1325
+ freezeListeners.add(listener);
1326
+ listener(isFrozen);
1327
+ return () => {
1328
+ freezeListeners.delete(listener);
1329
+ };
1330
+ }
1331
+
1332
+ /**
1333
+ * Freeze highlights - prevents highlights from fading away.
1334
+ * New renders are still captured but old highlights don't clear.
1335
+ */
1336
+ function freeze() {
1337
+ if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1338
+ if (isFrozen) return;
1339
+ isFrozen = true;
1340
+ debugLog("Freeze mode enabled");
1341
+ notifyFreezeListeners();
1342
+ }
1343
+
1344
+ /**
1345
+ * Unfreeze highlights - resumes normal cleanup behavior.
1346
+ * Clears all current highlights when unfreezing.
1347
+ */
1348
+ function unfreeze() {
1349
+ if (typeof __DEV__ !== "undefined" && !__DEV__) return;
1350
+ if (!isFrozen) return;
1351
+ isFrozen = false;
1352
+ debugLog("Freeze mode disabled");
1353
+
1354
+ // Clear all current highlights when unfreezing
1355
+ if (highlightCallback) {
1356
+ highlightCallback([]);
1357
+ }
1358
+ notifyFreezeListeners();
1359
+ }
1360
+
1361
+ /**
1362
+ * Toggle freeze state
1363
+ */
1364
+ function toggleFreeze() {
1365
+ if (isFrozen) {
1366
+ unfreeze();
1367
+ } else {
1368
+ freeze();
1369
+ }
1370
+ }
1371
+
1372
+ /**
1373
+ * Check if freeze mode is active
1374
+ */
1375
+ function getFrozen() {
1376
+ return isFrozen;
1377
+ }
1378
+ function destroy() {
1379
+ if (!initialized) return;
1380
+ unsubscribeFromTraceUpdates();
1381
+
1382
+ // Uninstall profiler interceptor
1383
+ uninstallProfilerInterceptor();
1384
+ setComparisonCallback(null);
1385
+
1386
+ // Reset freeze state
1387
+ isFrozen = false;
1388
+ freezeListeners.clear();
1389
+ globalEnabled = false;
1390
+ hook = null;
1391
+ highlightCallback = null;
1392
+ initialized = false;
1393
+ if (typeof window !== "undefined") {
1394
+ delete window.__HIGHLIGHT_UPDATES_CONTROLLER__;
1395
+ }
1396
+ debugLog("Destroyed");
1397
+ }
1398
+ const HighlightUpdatesController = {
1399
+ subscribe,
1400
+ enable,
1401
+ disable,
1402
+ toggle,
1403
+ isEnabled,
1404
+ setEnabled,
1405
+ initialize,
1406
+ destroy,
1407
+ isInitialized,
1408
+ setHighlightCallback,
1409
+ clearRenderCounts,
1410
+ // Freeze frame mode
1411
+ freeze,
1412
+ unfreeze,
1413
+ toggleFreeze,
1414
+ getFrozen,
1415
+ subscribeToFreeze,
1416
+ // Badge press callback for "Click Overlay Badge → Jump to Detail"
1417
+ setBadgePressCallback,
1418
+ getBadgePressCallback,
1419
+ handleBadgePress,
1420
+ // Spotlight highlight for detail view
1421
+ setSpotlightCallback,
1422
+ setSpotlight,
1423
+ getSpotlight,
1424
+ // Cache management for excludeDevTools toggle
1425
+ clearDevToolsCache,
1426
+ // Background tracking for Events tool (separate from visual toggle)
1427
+ enableBackgroundTracking,
1428
+ disableBackgroundTracking,
1429
+ isBackgroundTrackingEnabled
1430
+ };
1431
+ export default HighlightUpdatesController;