@oxog/reactscope 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +47 -15
  2. package/dist/{chunk-IFCS6ABF.cjs → chunk-33CBEAOF.cjs} +106 -32
  3. package/dist/chunk-33CBEAOF.cjs.map +1 -0
  4. package/dist/{chunk-JESQX3XO.js → chunk-3Q6YBIBW.js} +28 -2
  5. package/dist/chunk-3Q6YBIBW.js.map +1 -0
  6. package/dist/{chunk-6L3WUS6V.cjs → chunk-6ALDCO2Q.cjs} +28 -2
  7. package/dist/chunk-6ALDCO2Q.cjs.map +1 -0
  8. package/dist/{chunk-4TZAECHG.cjs → chunk-7MVKPUC4.cjs} +5 -21
  9. package/dist/chunk-7MVKPUC4.cjs.map +1 -0
  10. package/dist/chunk-ACLEEAEC.cjs +83 -0
  11. package/dist/chunk-ACLEEAEC.cjs.map +1 -0
  12. package/dist/{chunk-LZO35OCP.js → chunk-AZ6OARKV.js} +2 -2
  13. package/dist/{chunk-LZO35OCP.js.map → chunk-AZ6OARKV.js.map} +1 -1
  14. package/dist/{chunk-KCUWALXE.cjs → chunk-C3IBGU7L.cjs} +5 -2
  15. package/dist/chunk-C3IBGU7L.cjs.map +1 -0
  16. package/dist/{chunk-M65L55OT.js → chunk-C4LJVRF5.js} +11 -8
  17. package/dist/chunk-C4LJVRF5.js.map +1 -0
  18. package/dist/{chunk-MPOQNCGP.js → chunk-E4PZKXY7.js} +5 -21
  19. package/dist/chunk-E4PZKXY7.js.map +1 -0
  20. package/dist/chunk-E7W2FVWO.js +78 -0
  21. package/dist/chunk-E7W2FVWO.js.map +1 -0
  22. package/dist/{chunk-H4W4UBLZ.cjs → chunk-EUYOAT56.cjs} +11 -8
  23. package/dist/chunk-EUYOAT56.cjs.map +1 -0
  24. package/dist/{chunk-RYAIO3BO.js → chunk-F3KDHISM.js} +5 -4
  25. package/dist/chunk-F3KDHISM.js.map +1 -0
  26. package/dist/{chunk-I427KZYN.cjs → chunk-KRRXA4SI.cjs} +2 -2
  27. package/dist/{chunk-I427KZYN.cjs.map → chunk-KRRXA4SI.cjs.map} +1 -1
  28. package/dist/{chunk-U2OPUU5R.js → chunk-MBFJ6ULY.js} +40 -18
  29. package/dist/chunk-MBFJ6ULY.js.map +1 -0
  30. package/dist/chunk-OMETOKM7.cjs +86 -0
  31. package/dist/chunk-OMETOKM7.cjs.map +1 -0
  32. package/dist/chunk-QT2GSPHP.js +21 -0
  33. package/dist/chunk-QT2GSPHP.js.map +1 -0
  34. package/dist/{chunk-OJGWFS55.cjs → chunk-U3TL6KFZ.cjs} +41 -19
  35. package/dist/chunk-U3TL6KFZ.cjs.map +1 -0
  36. package/dist/chunk-UQFSIGZW.cjs +24 -0
  37. package/dist/chunk-UQFSIGZW.cjs.map +1 -0
  38. package/dist/{chunk-6LHJL6MV.js → chunk-W7SGZQRF.js} +106 -32
  39. package/dist/chunk-W7SGZQRF.js.map +1 -0
  40. package/dist/{chunk-ZTO5ZZVE.js → chunk-XWZXCGPY.js} +5 -2
  41. package/dist/chunk-XWZXCGPY.js.map +1 -0
  42. package/dist/chunk-YG5FHHRH.js +80 -0
  43. package/dist/chunk-YG5FHHRH.js.map +1 -0
  44. package/dist/{chunk-QYMRRTSN.cjs → chunk-YL2LJ27D.cjs} +6 -5
  45. package/dist/chunk-YL2LJ27D.cjs.map +1 -0
  46. package/dist/index.cjs +428 -369
  47. package/dist/index.cjs.map +1 -1
  48. package/dist/index.d.cts +33 -7
  49. package/dist/index.d.ts +33 -7
  50. package/dist/index.js +403 -343
  51. package/dist/index.js.map +1 -1
  52. package/dist/plugins/console-reporter/index.d.cts +1 -1
  53. package/dist/plugins/console-reporter/index.d.ts +1 -1
  54. package/dist/plugins/dashboard-ui/index.cjs +4 -3
  55. package/dist/plugins/dashboard-ui/index.d.cts +5 -1
  56. package/dist/plugins/dashboard-ui/index.d.ts +5 -1
  57. package/dist/plugins/dashboard-ui/index.js +2 -1
  58. package/dist/plugins/json-exporter/index.cjs +5 -3
  59. package/dist/plugins/json-exporter/index.d.cts +1 -1
  60. package/dist/plugins/json-exporter/index.d.ts +1 -1
  61. package/dist/plugins/json-exporter/index.js +3 -1
  62. package/dist/plugins/lifecycle-tracker/index.cjs +4 -3
  63. package/dist/plugins/lifecycle-tracker/index.d.cts +8 -1
  64. package/dist/plugins/lifecycle-tracker/index.d.ts +8 -1
  65. package/dist/plugins/lifecycle-tracker/index.js +2 -1
  66. package/dist/plugins/memory-tracker/index.d.cts +1 -1
  67. package/dist/plugins/memory-tracker/index.d.ts +1 -1
  68. package/dist/plugins/network-correlator/index.cjs +4 -4
  69. package/dist/plugins/network-correlator/index.d.cts +5 -1
  70. package/dist/plugins/network-correlator/index.d.ts +5 -1
  71. package/dist/plugins/network-correlator/index.js +2 -2
  72. package/dist/plugins/props-differ/index.cjs +4 -3
  73. package/dist/plugins/props-differ/index.d.cts +1 -1
  74. package/dist/plugins/props-differ/index.d.ts +1 -1
  75. package/dist/plugins/props-differ/index.js +2 -1
  76. package/dist/plugins/render-tracker/index.d.cts +1 -1
  77. package/dist/plugins/render-tracker/index.d.ts +1 -1
  78. package/dist/plugins/timeline-recorder/index.cjs +5 -4
  79. package/dist/plugins/timeline-recorder/index.d.cts +1 -1
  80. package/dist/plugins/timeline-recorder/index.d.ts +1 -1
  81. package/dist/plugins/timeline-recorder/index.js +3 -2
  82. package/dist/plugins/wasted-render-detector/index.cjs +4 -3
  83. package/dist/plugins/wasted-render-detector/index.d.cts +5 -8
  84. package/dist/plugins/wasted-render-detector/index.d.ts +5 -8
  85. package/dist/plugins/wasted-render-detector/index.js +2 -1
  86. package/dist/{types-DKPG_emi.d.ts → types-DNhmA1Tk.d.cts} +22 -1
  87. package/dist/{types-DKPG_emi.d.cts → types-DNhmA1Tk.d.ts} +22 -1
  88. package/package.json +20 -9
  89. package/dist/chunk-4TZAECHG.cjs.map +0 -1
  90. package/dist/chunk-6L3WUS6V.cjs.map +0 -1
  91. package/dist/chunk-6LHJL6MV.js.map +0 -1
  92. package/dist/chunk-H4W4UBLZ.cjs.map +0 -1
  93. package/dist/chunk-IFCS6ABF.cjs.map +0 -1
  94. package/dist/chunk-JESQX3XO.js.map +0 -1
  95. package/dist/chunk-KCUWALXE.cjs.map +0 -1
  96. package/dist/chunk-M65L55OT.js.map +0 -1
  97. package/dist/chunk-MPOQNCGP.js.map +0 -1
  98. package/dist/chunk-OJGWFS55.cjs.map +0 -1
  99. package/dist/chunk-QYMRRTSN.cjs.map +0 -1
  100. package/dist/chunk-RYAIO3BO.js.map +0 -1
  101. package/dist/chunk-U2OPUU5R.js.map +0 -1
  102. package/dist/chunk-ZTO5ZZVE.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,22 +1,25 @@
1
- export { TimelineRecorderPlugin, createTimelineRecorderPlugin } from './chunk-RYAIO3BO.js';
1
+ export { TimelineRecorderPlugin, createTimelineRecorderPlugin } from './chunk-F3KDHISM.js';
2
2
  export { MemoryTrackerPlugin, createMemoryTrackerPlugin } from './chunk-MVK2UT4Z.js';
3
- export { NetworkCorrelatorPlugin, createNetworkCorrelatorPlugin } from './chunk-U2OPUU5R.js';
4
- import { uid } from './chunk-LZO35OCP.js';
5
- export { createIdGenerator, uid } from './chunk-LZO35OCP.js';
3
+ export { NetworkCorrelatorPlugin, createNetworkCorrelatorPlugin } from './chunk-MBFJ6ULY.js';
4
+ import { uid } from './chunk-AZ6OARKV.js';
5
+ export { createIdGenerator, uid } from './chunk-AZ6OARKV.js';
6
6
  import { createRenderTrackerPlugin } from './chunk-MTCOZBRI.js';
7
7
  export { RenderTrackerPlugin, createRenderTrackerPlugin } from './chunk-MTCOZBRI.js';
8
- import { createPropsDifferPlugin } from './chunk-ZTO5ZZVE.js';
9
- export { PropsDifferPlugin, createPropsDifferPlugin, deepEqual } from './chunk-ZTO5ZZVE.js';
10
- import { createWastedRenderDetectorPlugin } from './chunk-MPOQNCGP.js';
11
- export { WastedRenderDetectorPlugin, createWastedRenderDetectorPlugin } from './chunk-MPOQNCGP.js';
12
- import { createLifecycleTrackerPlugin } from './chunk-JESQX3XO.js';
13
- export { LifecycleTrackerPlugin, createLifecycleTrackerPlugin } from './chunk-JESQX3XO.js';
14
- export { DashboardUIPlugin, createDashboardUIPlugin, throttle } from './chunk-6LHJL6MV.js';
8
+ import { createPropsDifferPlugin } from './chunk-XWZXCGPY.js';
9
+ export { PropsDifferPlugin, createPropsDifferPlugin, deepEqual } from './chunk-XWZXCGPY.js';
10
+ import { createWastedRenderDetectorPlugin } from './chunk-E4PZKXY7.js';
11
+ export { WastedRenderDetectorPlugin, createWastedRenderDetectorPlugin } from './chunk-E4PZKXY7.js';
12
+ import { createLifecycleTrackerPlugin } from './chunk-3Q6YBIBW.js';
13
+ export { LifecycleTrackerPlugin, createLifecycleTrackerPlugin } from './chunk-3Q6YBIBW.js';
14
+ import './chunk-QT2GSPHP.js';
15
+ export { DashboardUIPlugin, createDashboardUIPlugin, throttle } from './chunk-W7SGZQRF.js';
15
16
  export { ConsoleReporterPlugin, createConsoleReporterPlugin } from './chunk-XNNGOQH2.js';
16
17
  export { formatBytes, formatDuration, formatNumber, formatPercentage, formatRelativeTime, formatTimestamp } from './chunk-E4MB5KJQ.js';
17
- export { JSONExporterPlugin, createJSONExporterPlugin } from './chunk-M65L55OT.js';
18
- import React2, { createContext, useContext, useRef, useEffect, useState, useCallback, Profiler, forwardRef } from 'react';
19
- import { jsx } from 'react/jsx-runtime';
18
+ import { JSONExporterPlugin } from './chunk-C4LJVRF5.js';
19
+ export { JSONExporterPlugin, createJSONExporterPlugin } from './chunk-C4LJVRF5.js';
20
+ import './chunk-YG5FHHRH.js';
21
+ import { createTree, findNode, removeNode, createNode, addChild, setSubtreeDepth, getRootNodes } from './chunk-E7W2FVWO.js';
22
+ import React2, { createContext, useContext, useState, useRef, useEffect, useLayoutEffect, useCallback, Profiler, forwardRef } from 'react';
20
23
 
21
24
  // src/kernel/event-bus.ts
22
25
  var EventBusImpl = class {
@@ -152,60 +155,6 @@ function createEventBus() {
152
155
  return new EventBusImpl();
153
156
  }
154
157
 
155
- // src/utils/tree.ts
156
- function createTree() {
157
- return {
158
- root: null,
159
- nodeMap: /* @__PURE__ */ new Map()
160
- };
161
- }
162
- function createNode(id, name, metrics = null, depth = 0) {
163
- return {
164
- id,
165
- name,
166
- children: [],
167
- metrics,
168
- depth,
169
- isExpanded: true
170
- };
171
- }
172
- function addChild(parent, child) {
173
- const existingIndex = parent.children.findIndex((c) => c.id === child.id);
174
- if (existingIndex !== -1) {
175
- parent.children[existingIndex] = child;
176
- } else {
177
- parent.children.push(child);
178
- }
179
- child.depth = parent.depth + 1;
180
- }
181
- function removeNode(tree, nodeId) {
182
- const node = tree.nodeMap.get(nodeId);
183
- if (!node) {
184
- return false;
185
- }
186
- for (const potentialParent of tree.nodeMap.values()) {
187
- const childIndex = potentialParent.children.findIndex((c) => c.id === nodeId);
188
- if (childIndex !== -1) {
189
- potentialParent.children.splice(childIndex, 1);
190
- break;
191
- }
192
- }
193
- if (tree.root?.id === nodeId) {
194
- tree.root = null;
195
- }
196
- const removeDescendants = (n) => {
197
- tree.nodeMap.delete(n.id);
198
- for (const child of n.children) {
199
- removeDescendants(child);
200
- }
201
- };
202
- removeDescendants(node);
203
- return true;
204
- }
205
- function findNode(tree, nodeId) {
206
- return tree.nodeMap.get(nodeId);
207
- }
208
-
209
158
  // src/kernel/metrics-store.ts
210
159
  function createDefaultMetrics(componentId, componentName) {
211
160
  return {
@@ -302,6 +251,10 @@ var MetricsStoreImpl = class {
302
251
  }
303
252
  /**
304
253
  * Update the component tree with a new component.
254
+ *
255
+ * React commits children before their parents, so a child can be reported
256
+ * before its parent node exists. Such children are kept as top-level nodes
257
+ * and adopted as soon as the parent is added.
305
258
  */
306
259
  updateTree(componentId, componentName, parentId) {
307
260
  let node = findNode(this.tree, componentId);
@@ -313,25 +266,48 @@ var MetricsStoreImpl = class {
313
266
  node.name = componentName;
314
267
  node.metrics = metrics;
315
268
  }
316
- if (parentId) {
269
+ if (parentId && parentId !== componentId) {
317
270
  const parentNode = findNode(this.tree, parentId);
318
271
  if (parentNode) {
319
- addChild(parentNode, node);
320
- const componentMetrics = this.components.get(componentId);
321
- if (componentMetrics) {
322
- componentMetrics.parentId = parentId;
323
- const parentMetrics = this.components.get(parentId);
324
- if (parentMetrics && !parentMetrics.childIds.includes(componentId)) {
325
- parentMetrics.childIds.push(componentId);
326
- }
327
- }
272
+ this.attach(parentNode, node);
328
273
  }
329
- } else if (!this.tree.root) {
330
- this.tree.root = node;
331
- node.depth = 0;
332
274
  }
275
+ for (const childMetrics of this.components.values()) {
276
+ if (childMetrics.parentId !== componentId || childMetrics.componentId === componentId) continue;
277
+ const childNode = findNode(this.tree, childMetrics.componentId);
278
+ if (childNode && !node.children.includes(childNode)) {
279
+ this.attach(node, childNode);
280
+ }
281
+ }
282
+ this.refreshRoot();
333
283
  this.lastUpdate = Date.now();
334
284
  }
285
+ attach(parentNode, node) {
286
+ addChild(parentNode, node);
287
+ setSubtreeDepth(node, parentNode.depth + 1);
288
+ const componentMetrics = this.components.get(node.id);
289
+ if (componentMetrics) {
290
+ componentMetrics.parentId = parentNode.id;
291
+ }
292
+ const parentMetrics = this.components.get(parentNode.id);
293
+ if (parentMetrics && !parentMetrics.childIds.includes(node.id)) {
294
+ parentMetrics.childIds.push(node.id);
295
+ }
296
+ }
297
+ /**
298
+ * Keep `tree.root` pointing at a top-level node that is still in the tree.
299
+ */
300
+ refreshRoot() {
301
+ const root = this.tree.root;
302
+ if (root && this.tree.nodeMap.get(root.id) === root && root.depth === 0) {
303
+ return;
304
+ }
305
+ const first = getRootNodes(this.tree)[0] ?? null;
306
+ if (first) {
307
+ setSubtreeDepth(first, 0);
308
+ }
309
+ this.tree.root = first;
310
+ }
335
311
  /**
336
312
  * Remove a component from the tree.
337
313
  */
@@ -344,6 +320,7 @@ var MetricsStoreImpl = class {
344
320
  }
345
321
  }
346
322
  removeNode(this.tree, componentId);
323
+ this.refreshRoot();
347
324
  this.lastUpdate = Date.now();
348
325
  }
349
326
  /**
@@ -545,6 +522,13 @@ var DEFAULT_OPTIONS = {
545
522
  sampleRate: 1,
546
523
  maxHistorySize: 1e3
547
524
  };
525
+ function toTimelineData(event) {
526
+ if (event.type === "metrics-update") {
527
+ const { renderHistory: _renderHistory, ...metrics } = event.metrics;
528
+ return { ...event, metrics };
529
+ }
530
+ return event;
531
+ }
548
532
  var KernelImpl = class {
549
533
  constructor(options = {}) {
550
534
  this.destroyed = false;
@@ -608,7 +592,7 @@ var KernelImpl = class {
608
592
  id: uid(),
609
593
  type: eventType,
610
594
  timestamp: event.timestamp,
611
- data: event
595
+ data: toTimelineData(event)
612
596
  });
613
597
  });
614
598
  }
@@ -781,6 +765,9 @@ function getKernel() {
781
765
  }
782
766
  return globalKernel;
783
767
  }
768
+ function getGlobalKernelIfSet() {
769
+ return globalKernel;
770
+ }
784
771
  function setGlobalKernel(kernel) {
785
772
  globalKernel = kernel;
786
773
  }
@@ -802,6 +789,100 @@ function useScopeContextSafe() {
802
789
  return useContext(ScopeContext);
803
790
  }
804
791
  ScopeContext.displayName = "ScopeContext";
792
+ var ParentScopeContext = createContext(null);
793
+ ParentScopeContext.displayName = "ReactScopeParent";
794
+ var canUseDOM = typeof window !== "undefined" && typeof window.document !== "undefined";
795
+ var useIsomorphicLayoutEffect = canUseDOM ? useLayoutEffect : useEffect;
796
+ var now = typeof performance !== "undefined" && typeof performance.now === "function" ? () => performance.now() : () => Date.now();
797
+ var scheduleMicrotask = typeof queueMicrotask === "function" ? queueMicrotask : (fn) => void Promise.resolve().then(fn);
798
+ var pendingUnmounts = /* @__PURE__ */ new Map();
799
+ function useMountTracking(kernel, componentId, componentName, parentId) {
800
+ useIsomorphicLayoutEffect(() => {
801
+ if (!kernel) return;
802
+ const pending = pendingUnmounts.get(componentId);
803
+ if (pending && pending.kernel === kernel) {
804
+ pendingUnmounts.delete(componentId);
805
+ } else {
806
+ const mountEvent = {
807
+ type: "mount",
808
+ timestamp: Date.now(),
809
+ componentId,
810
+ componentName,
811
+ parentId
812
+ };
813
+ kernel.emit(mountEvent);
814
+ }
815
+ return () => {
816
+ const entry = {
817
+ kernel,
818
+ emit: () => {
819
+ if (pendingUnmounts.get(componentId) !== entry) return;
820
+ pendingUnmounts.delete(componentId);
821
+ const unmountEvent = {
822
+ type: "unmount",
823
+ timestamp: Date.now(),
824
+ componentId,
825
+ componentName
826
+ };
827
+ kernel.emit(unmountEvent);
828
+ }
829
+ };
830
+ pendingUnmounts.get(componentId)?.emit();
831
+ pendingUnmounts.set(componentId, entry);
832
+ scheduleMicrotask(entry.emit);
833
+ };
834
+ }, [kernel, componentId, componentName, parentId]);
835
+ }
836
+ var SUBSCRIPTION_INTERVAL_MS = 100;
837
+ function sameSnapshot(a, b) {
838
+ if (Object.is(a, b)) return true;
839
+ if (!(a instanceof Map) || !(b instanceof Map) || a.size !== b.size) return false;
840
+ for (const [key, value] of a) {
841
+ if (b.get(key) !== value) return false;
842
+ }
843
+ return true;
844
+ }
845
+ function useThrottledMetrics(kernel, read, matches, deps) {
846
+ const [value, setValue] = useState(read);
847
+ const readRef = useRef(read);
848
+ const matchesRef = useRef(matches);
849
+ readRef.current = read;
850
+ matchesRef.current = matches;
851
+ useEffect(() => {
852
+ if (!kernel) return;
853
+ let timer = null;
854
+ let lastFlush = 0;
855
+ let active = true;
856
+ const flush = () => {
857
+ timer = null;
858
+ if (!active) return;
859
+ lastFlush = Date.now();
860
+ setValue(readRef.current());
861
+ };
862
+ const latest = readRef.current();
863
+ setValue((previous) => sameSnapshot(previous, latest) ? previous : latest);
864
+ const unsubscribe = kernel.on("metrics-update", (event) => {
865
+ if (timer !== null || !matchesRef.current(event.componentId)) return;
866
+ const wait = Math.max(0, lastFlush + SUBSCRIPTION_INTERVAL_MS - Date.now());
867
+ timer = setTimeout(flush, wait);
868
+ });
869
+ return () => {
870
+ active = false;
871
+ unsubscribe();
872
+ if (timer !== null) clearTimeout(timer);
873
+ };
874
+ }, [kernel, ...deps]);
875
+ return value;
876
+ }
877
+
878
+ // src/react/provider.tsx
879
+ function registerAll(kernel, plugins) {
880
+ for (const plugin of plugins) {
881
+ if (kernel.getPlugin(plugin.name) !== plugin) {
882
+ kernel.register(plugin);
883
+ }
884
+ }
885
+ }
805
886
  function ReactScopeProvider({
806
887
  children,
807
888
  enabled = true,
@@ -809,24 +890,47 @@ function ReactScopeProvider({
809
890
  onReady,
810
891
  options = {}
811
892
  }) {
812
- const kernelRef = useRef(null);
813
- const initializedRef = useRef(false);
814
- if (!kernelRef.current) {
815
- const k = createKernel({
816
- enabled,
817
- ...options
818
- });
819
- k.register(createRenderTrackerPlugin());
820
- k.register(createPropsDifferPlugin());
821
- k.register(createWastedRenderDetectorPlugin());
822
- k.register(createLifecycleTrackerPlugin());
823
- for (const plugin of plugins) {
824
- k.register(plugin);
825
- }
826
- kernelRef.current = k;
827
- setGlobalKernel(k);
828
- }
829
- const kernel = kernelRef.current;
893
+ const [state] = useState(() => {
894
+ const kernel2 = createKernel({ enabled, ...options });
895
+ const core = [
896
+ createRenderTrackerPlugin(),
897
+ createPropsDifferPlugin(),
898
+ createWastedRenderDetectorPlugin(),
899
+ createLifecycleTrackerPlugin()
900
+ ];
901
+ registerAll(kernel2, core);
902
+ return { kernel: kernel2, plugins: core };
903
+ });
904
+ const { kernel } = state;
905
+ const userPluginsRef = useRef(null);
906
+ if (userPluginsRef.current === null) {
907
+ userPluginsRef.current = [...plugins];
908
+ registerAll(kernel, userPluginsRef.current);
909
+ }
910
+ const readyRef = useRef(false);
911
+ const teardownRef = useRef(null);
912
+ useEffect(() => {
913
+ teardownRef.current = null;
914
+ const all = [...state.plugins, ...userPluginsRef.current ?? []];
915
+ registerAll(kernel, all);
916
+ setGlobalKernel(kernel);
917
+ return () => {
918
+ const teardown = () => {
919
+ if (teardownRef.current !== teardown) return;
920
+ teardownRef.current = null;
921
+ for (const plugin of [...all].reverse()) {
922
+ if (kernel.getPlugin(plugin.name) === plugin) {
923
+ kernel.unregister(plugin.name);
924
+ }
925
+ }
926
+ if (getGlobalKernelIfSet() === kernel) {
927
+ setGlobalKernel(null);
928
+ }
929
+ };
930
+ teardownRef.current = teardown;
931
+ scheduleMicrotask(teardown);
932
+ };
933
+ }, [kernel, state]);
830
934
  useEffect(() => {
831
935
  if (enabled) {
832
936
  kernel.enable();
@@ -834,86 +938,158 @@ function ReactScopeProvider({
834
938
  kernel.disable();
835
939
  }
836
940
  }, [enabled, kernel]);
941
+ const { sampleRate, maxHistorySize, trackAllComponents } = options;
837
942
  useEffect(() => {
838
- kernel.configure(options);
839
- }, [kernel, options]);
943
+ const next = {};
944
+ if (sampleRate !== void 0) next.sampleRate = sampleRate;
945
+ if (maxHistorySize !== void 0) next.maxHistorySize = maxHistorySize;
946
+ if (trackAllComponents !== void 0) next.trackAllComponents = trackAllComponents;
947
+ kernel.configure(next);
948
+ }, [kernel, sampleRate, maxHistorySize, trackAllComponents]);
840
949
  useEffect(() => {
841
- if (onReady && !initializedRef.current) {
842
- initializedRef.current = true;
950
+ if (!readyRef.current && onReady) {
951
+ readyRef.current = true;
843
952
  onReady(kernel);
844
953
  }
845
954
  }, [kernel, onReady]);
846
- return /* @__PURE__ */ jsx(ScopeContext.Provider, { value: kernel, children });
955
+ return React2.createElement(ScopeContext.Provider, { value: kernel }, children);
847
956
  }
848
957
  ReactScopeProvider.displayName = "ReactScopeProvider";
958
+
959
+ // src/utils/shallow-equal.ts
960
+ function shallowEqual(a, b) {
961
+ if (Object.is(a, b)) {
962
+ return true;
963
+ }
964
+ if (a == null || b == null) {
965
+ return a === b;
966
+ }
967
+ if (typeof a !== "object" || typeof b !== "object") {
968
+ return a === b;
969
+ }
970
+ if (Array.isArray(a) && Array.isArray(b)) {
971
+ if (a.length !== b.length) {
972
+ return false;
973
+ }
974
+ for (let i = 0; i < a.length; i++) {
975
+ if (!Object.is(a[i], b[i])) {
976
+ return false;
977
+ }
978
+ }
979
+ return true;
980
+ }
981
+ if (Array.isArray(a) !== Array.isArray(b)) {
982
+ return false;
983
+ }
984
+ const keysA = Object.keys(a);
985
+ const keysB = Object.keys(b);
986
+ if (keysA.length !== keysB.length) {
987
+ return false;
988
+ }
989
+ const objA = a;
990
+ const objB = b;
991
+ for (const key of keysA) {
992
+ if (!Object.prototype.hasOwnProperty.call(objB, key) || !Object.is(objA[key], objB[key])) {
993
+ return false;
994
+ }
995
+ }
996
+ return true;
997
+ }
998
+
999
+ // src/react/props.ts
1000
+ function diffProps(prev, next) {
1001
+ const changes = [];
1002
+ const keys = /* @__PURE__ */ new Set([...Object.keys(prev), ...Object.keys(next)]);
1003
+ for (const key of keys) {
1004
+ const prevValue = prev[key];
1005
+ const nextValue = next[key];
1006
+ if (!Object.is(prevValue, nextValue)) {
1007
+ changes.push({
1008
+ key,
1009
+ prev: prevValue,
1010
+ next: nextValue,
1011
+ isDeepEqual: shallowEqual(prevValue, nextValue)
1012
+ });
1013
+ }
1014
+ }
1015
+ return changes;
1016
+ }
1017
+
1018
+ // src/react/hooks/use-scope.ts
849
1019
  function useScope(name, options = {}) {
850
1020
  const kernel = useScopeContextSafe();
1021
+ const parentId = useContext(ParentScopeContext);
851
1022
  const componentIdRef = useRef(null);
852
1023
  const renderCountRef = useRef(0);
853
- const mountTimeRef = useRef(null);
854
- const isMetricsUpdateRef = useRef(false);
855
- const lastTrackedRenderRef = useRef(0);
856
- if (!componentIdRef.current) {
1024
+ const committedRenderRef = useRef(null);
1025
+ const prevPropsRef = useRef(null);
1026
+ const optionsRef = useRef(options);
1027
+ if (componentIdRef.current === null) {
857
1028
  componentIdRef.current = uid();
858
1029
  }
859
1030
  const componentId = componentIdRef.current;
860
- const [metrics, setMetrics] = useState(null);
861
- useEffect(() => {
862
- if (!kernel) return;
863
- const now = Date.now();
864
- mountTimeRef.current = now;
865
- if (!kernel.getMetrics().get(componentId)) {
866
- const defaultMetrics = createDefaultMetrics(componentId, name);
867
- kernel.getMetrics().set(componentId, defaultMetrics);
868
- }
869
- isMetricsUpdateRef.current = true;
870
- setMetrics(kernel.getMetrics().get(componentId) ?? null);
871
- const unsubscribe = kernel.on("metrics-update", (event) => {
872
- if (event.componentId === componentId) {
873
- isMetricsUpdateRef.current = true;
874
- setMetrics(event.metrics);
875
- }
876
- });
877
- const mountEvent = {
878
- type: "mount",
879
- timestamp: now,
1031
+ const renderToken = {};
1032
+ const renderStart = now();
1033
+ useMountTracking(kernel, componentId, name, parentId);
1034
+ const readMetrics = () => kernel?.getMetrics().get(componentId);
1035
+ useIsomorphicLayoutEffect(() => {
1036
+ optionsRef.current = options;
1037
+ if (!kernel || committedRenderRef.current === renderToken) return;
1038
+ committedRenderRef.current = renderToken;
1039
+ const phase = renderCountRef.current === 0 ? "mount" : "update";
1040
+ renderCountRef.current++;
1041
+ const renderEvent = {
1042
+ type: "render",
1043
+ timestamp: Date.now(),
880
1044
  componentId,
881
1045
  componentName: name,
882
- parentId: null
883
- };
884
- kernel.emit(mountEvent);
885
- return () => {
886
- unsubscribe();
887
- const unmountEvent = {
888
- type: "unmount",
889
- timestamp: Date.now(),
890
- componentId,
891
- componentName: name
892
- };
893
- kernel.emit(unmountEvent);
1046
+ duration: now() - renderStart,
1047
+ phase
894
1048
  };
895
- }, [kernel, componentId, name]);
1049
+ kernel.emit(renderEvent);
1050
+ if (options.trackProps && options.props) {
1051
+ const prevProps = prevPropsRef.current;
1052
+ prevPropsRef.current = { ...options.props };
1053
+ if (prevProps) {
1054
+ const changes = diffProps(prevProps, options.props);
1055
+ if (changes.length > 0) {
1056
+ kernel.emit({
1057
+ type: "props-change",
1058
+ timestamp: Date.now(),
1059
+ componentId,
1060
+ componentName: name,
1061
+ changes
1062
+ });
1063
+ }
1064
+ }
1065
+ }
1066
+ if (options.onRender) {
1067
+ const metrics = kernel.getMetrics().get(componentId);
1068
+ if (metrics) {
1069
+ options.onRender(metrics);
1070
+ }
1071
+ }
1072
+ });
896
1073
  const trackRender = useCallback(
897
1074
  (duration, phase) => {
898
1075
  if (!kernel) return;
899
- renderCountRef.current++;
900
- const renderEvent = {
1076
+ kernel.emit({
901
1077
  type: "render",
902
1078
  timestamp: Date.now(),
903
1079
  componentId,
904
1080
  componentName: name,
905
1081
  duration,
906
1082
  phase
907
- };
908
- kernel.emit(renderEvent);
909
- if (options.onRender) {
1083
+ });
1084
+ const onRender = optionsRef.current.onRender;
1085
+ if (onRender) {
910
1086
  const currentMetrics = kernel.getMetrics().get(componentId);
911
1087
  if (currentMetrics) {
912
- options.onRender(currentMetrics);
1088
+ onRender(currentMetrics);
913
1089
  }
914
1090
  }
915
1091
  },
916
- [kernel, componentId, name, options]
1092
+ [kernel, componentId, name]
917
1093
  );
918
1094
  const trackPropsChange = useCallback(
919
1095
  (changes) => {
@@ -928,45 +1104,21 @@ function useScope(name, options = {}) {
928
1104
  },
929
1105
  [kernel, componentId, name]
930
1106
  );
931
- useEffect(() => {
932
- if (isMetricsUpdateRef.current) {
933
- isMetricsUpdateRef.current = false;
934
- return;
935
- }
936
- const currentRender = ++lastTrackedRenderRef.current;
937
- const startTime = performance.now();
938
- const phase = renderCountRef.current === 0 ? "mount" : "update";
939
- if (typeof requestIdleCallback !== "undefined") {
940
- requestIdleCallback(() => {
941
- if (currentRender === lastTrackedRenderRef.current) {
942
- const duration = performance.now() - startTime;
943
- trackRender(duration, phase);
944
- }
945
- });
946
- } else {
947
- setTimeout(() => {
948
- if (currentRender === lastTrackedRenderRef.current) {
949
- const duration = performance.now() - startTime;
950
- trackRender(duration, phase);
951
- }
952
- }, 0);
953
- }
954
- });
955
- const handle = {
1107
+ return {
956
1108
  get componentId() {
957
1109
  return componentId;
958
1110
  },
959
1111
  get renderCount() {
960
- return metrics?.renderCount ?? 0;
1112
+ return readMetrics()?.renderCount ?? 0;
961
1113
  },
962
1114
  get lastRenderTime() {
963
- return metrics?.lastRenderTime ?? 0;
1115
+ return readMetrics()?.lastRenderTime ?? 0;
964
1116
  },
965
1117
  get averageRenderTime() {
966
- return metrics?.averageRenderTime ?? 0;
1118
+ return readMetrics()?.averageRenderTime ?? 0;
967
1119
  },
968
1120
  get wastedRenders() {
969
- return metrics?.wastedRenderCount ?? 0;
1121
+ return readMetrics()?.wastedRenderCount ?? 0;
970
1122
  },
971
1123
  get isTracking() {
972
1124
  return kernel !== null && kernel.isEnabled();
@@ -974,44 +1126,27 @@ function useScope(name, options = {}) {
974
1126
  trackRender,
975
1127
  trackPropsChange
976
1128
  };
977
- return handle;
978
1129
  }
1130
+
1131
+ // src/react/hooks/use-scope-metrics.ts
1132
+ var matchAll = () => true;
979
1133
  function useScopeMetrics(componentId) {
980
1134
  const kernel = useScopeContextSafe();
981
- const [metrics, setMetrics] = useState(() => {
982
- return kernel?.getMetrics().get(componentId);
983
- });
984
- const updateMetrics = useCallback(() => {
985
- if (kernel) {
986
- setMetrics(kernel.getMetrics().get(componentId));
987
- }
988
- }, [kernel, componentId]);
989
- useEffect(() => {
990
- if (!kernel) return;
991
- updateMetrics();
992
- const unsubscribe = kernel.on("metrics-update", (event) => {
993
- if (event.componentId === componentId) {
994
- setMetrics(event.metrics);
995
- }
996
- });
997
- return unsubscribe;
998
- }, [kernel, componentId, updateMetrics]);
999
- return metrics;
1135
+ return useThrottledMetrics(
1136
+ kernel,
1137
+ () => kernel?.getMetrics().get(componentId),
1138
+ (id) => id === componentId,
1139
+ [componentId]
1140
+ );
1000
1141
  }
1001
1142
  function useAllScopeMetrics() {
1002
1143
  const kernel = useScopeContextSafe();
1003
- const [metrics, setMetrics] = useState(() => {
1004
- return kernel?.getMetrics().getAll() ?? /* @__PURE__ */ new Map();
1005
- });
1006
- useEffect(() => {
1007
- if (!kernel) return;
1008
- setMetrics(kernel.getMetrics().getAll());
1009
- const unsubscribe = kernel.on("metrics-update", () => {
1010
- setMetrics(new Map(kernel.getMetrics().getAll()));
1011
- });
1012
- return unsubscribe;
1013
- }, [kernel]);
1014
- return metrics;
1144
+ return useThrottledMetrics(
1145
+ kernel,
1146
+ () => kernel?.getMetrics().getAll() ?? /* @__PURE__ */ new Map(),
1147
+ matchAll,
1148
+ []
1149
+ );
1015
1150
  }
1016
1151
  function useScopeSummary() {
1017
1152
  const metrics = useAllScopeMetrics();
@@ -1030,174 +1165,87 @@ function useScopeSummary() {
1030
1165
  averageRenderTime: totalRenders > 0 ? totalRenderTime / totalRenders : 0
1031
1166
  };
1032
1167
  }
1033
- function Scope({
1034
- children,
1035
- name,
1036
- onRender,
1037
- trackProps: _trackProps = true
1038
- }) {
1168
+ function Scope({ children, name, onRender }) {
1039
1169
  const kernel = useScopeContextSafe();
1170
+ const parentId = useContext(ParentScopeContext);
1040
1171
  const componentIdRef = useRef(null);
1041
- const mountedRef = useRef(false);
1042
- if (!componentIdRef.current) {
1172
+ const onRenderRef = useRef(onRender);
1173
+ onRenderRef.current = onRender;
1174
+ if (componentIdRef.current === null) {
1043
1175
  componentIdRef.current = uid();
1044
1176
  }
1045
1177
  const componentId = componentIdRef.current;
1046
1178
  const componentName = name ?? "Scope";
1179
+ useMountTracking(kernel, componentId, componentName, parentId);
1047
1180
  const handleRender = useCallback(
1048
- (_id, phase, actualDuration, _baseDuration, _startTime, _commitTime) => {
1181
+ (_id, phase, actualDuration) => {
1049
1182
  if (!kernel || !kernel.isEnabled()) return;
1050
- if (!mountedRef.current) {
1051
- mountedRef.current = true;
1052
- const mountEvent = {
1053
- type: "mount",
1054
- timestamp: Date.now(),
1055
- componentId,
1056
- componentName,
1057
- parentId: null
1058
- };
1059
- kernel.emit(mountEvent);
1060
- }
1061
- const renderPhase = phase === "mount" ? "mount" : "update";
1062
1183
  const renderEvent = {
1063
1184
  type: "render",
1064
1185
  timestamp: Date.now(),
1065
1186
  componentId,
1066
1187
  componentName,
1067
1188
  duration: actualDuration,
1068
- phase: renderPhase
1189
+ phase: phase === "mount" ? "mount" : "update"
1069
1190
  };
1070
1191
  kernel.emit(renderEvent);
1071
- if (onRender) {
1192
+ const callback = onRenderRef.current;
1193
+ if (callback) {
1072
1194
  const metrics = kernel.getMetrics().get(componentId);
1073
1195
  if (metrics) {
1074
- onRender(metrics);
1196
+ callback(metrics);
1075
1197
  }
1076
1198
  }
1077
1199
  },
1078
- [kernel, componentId, componentName, onRender]
1200
+ [kernel, componentId, componentName]
1201
+ );
1202
+ return React2.createElement(
1203
+ ParentScopeContext.Provider,
1204
+ { value: componentId },
1205
+ React2.createElement(Profiler, { id: componentId, onRender: handleRender }, children)
1079
1206
  );
1080
- React2.useEffect(() => {
1081
- return () => {
1082
- if (kernel && mountedRef.current) {
1083
- const unmountEvent = {
1084
- type: "unmount",
1085
- timestamp: Date.now(),
1086
- componentId,
1087
- componentName
1088
- };
1089
- kernel.emit(unmountEvent);
1090
- }
1091
- };
1092
- }, [kernel, componentId, componentName]);
1093
- return /* @__PURE__ */ jsx(Profiler, { id: componentId, onRender: handleRender, children });
1094
1207
  }
1095
1208
  Scope.displayName = "Scope";
1096
-
1097
- // src/utils/shallow-equal.ts
1098
- function shallowEqual(a, b) {
1099
- if (Object.is(a, b)) {
1100
- return true;
1101
- }
1102
- if (a == null || b == null) {
1103
- return a === b;
1104
- }
1105
- if (typeof a !== "object" || typeof b !== "object") {
1106
- return a === b;
1107
- }
1108
- if (Array.isArray(a) && Array.isArray(b)) {
1109
- if (a.length !== b.length) {
1110
- return false;
1111
- }
1112
- for (let i = 0; i < a.length; i++) {
1113
- if (!Object.is(a[i], b[i])) {
1114
- return false;
1115
- }
1116
- }
1117
- return true;
1118
- }
1119
- if (Array.isArray(a) !== Array.isArray(b)) {
1120
- return false;
1121
- }
1122
- const keysA = Object.keys(a);
1123
- const keysB = Object.keys(b);
1124
- if (keysA.length !== keysB.length) {
1125
- return false;
1126
- }
1127
- const objA = a;
1128
- const objB = b;
1129
- for (const key of keysA) {
1130
- if (!Object.prototype.hasOwnProperty.call(objB, key) || !Object.is(objA[key], objB[key])) {
1131
- return false;
1132
- }
1133
- }
1134
- return true;
1135
- }
1136
1209
  function withScope(WrappedComponent, options = {}) {
1137
- const displayName = options.name ?? WrappedComponent.displayName ?? WrappedComponent.name ?? "Component";
1210
+ const displayName = options.name || WrappedComponent.displayName || WrappedComponent.name || "Component";
1138
1211
  const WithScopeComponent = forwardRef((props, ref) => {
1139
1212
  const kernel = useScopeContextSafe();
1213
+ const parentId = useContext(ParentScopeContext);
1140
1214
  const componentIdRef = useRef(null);
1141
- const mountedRef = useRef(false);
1215
+ const committedRenderRef = useRef(null);
1142
1216
  const prevPropsRef = useRef(null);
1143
- const renderStartRef = useRef(0);
1144
- if (!componentIdRef.current) {
1217
+ if (componentIdRef.current === null) {
1145
1218
  componentIdRef.current = uid();
1146
1219
  }
1147
1220
  const componentId = componentIdRef.current;
1148
- renderStartRef.current = performance.now();
1149
- useEffect(() => {
1150
- if (!kernel || !kernel.isEnabled()) return;
1151
- if (!mountedRef.current) {
1152
- mountedRef.current = true;
1153
- const mountEvent = {
1154
- type: "mount",
1155
- timestamp: Date.now(),
1156
- componentId,
1157
- componentName: displayName,
1158
- parentId: null
1159
- };
1160
- kernel.emit(mountEvent);
1161
- }
1162
- return () => {
1163
- const unmountEvent = {
1164
- type: "unmount",
1165
- timestamp: Date.now(),
1166
- componentId,
1167
- componentName: displayName
1168
- };
1169
- kernel.emit(unmountEvent);
1170
- };
1171
- }, [kernel, componentId]);
1172
- useEffect(() => {
1173
- if (!kernel || !kernel.isEnabled()) return;
1174
- const duration = performance.now() - renderStartRef.current;
1175
- const phase = prevPropsRef.current === null ? "mount" : "update";
1221
+ const renderToken = {};
1222
+ const renderStart = now();
1223
+ useMountTracking(kernel, componentId, displayName, parentId);
1224
+ useIsomorphicLayoutEffect(() => {
1225
+ if (!kernel || !kernel.isEnabled() || committedRenderRef.current === renderToken) return;
1226
+ committedRenderRef.current = renderToken;
1227
+ const currentProps = props;
1228
+ const prevProps = prevPropsRef.current;
1229
+ prevPropsRef.current = { ...currentProps };
1176
1230
  const renderEvent = {
1177
1231
  type: "render",
1178
1232
  timestamp: Date.now(),
1179
1233
  componentId,
1180
1234
  componentName: displayName,
1181
- duration,
1182
- phase
1235
+ duration: now() - renderStart,
1236
+ phase: prevProps === null ? "mount" : "update"
1183
1237
  };
1184
1238
  kernel.emit(renderEvent);
1185
- if (options.trackProps && prevPropsRef.current !== null) {
1186
- const prevProps = prevPropsRef.current;
1187
- const changes = [];
1188
- for (const key of Object.keys(props)) {
1189
- const prev = prevProps[key];
1190
- const next = props[key];
1191
- if (!Object.is(prev, next)) {
1192
- changes.push({
1193
- key,
1194
- prev,
1195
- next,
1196
- isDeepEqual: shallowEqual(prev, next)
1197
- });
1198
- }
1199
- }
1200
- if (changes.length > 0) {
1239
+ if (prevProps !== null) {
1240
+ const changes = diffProps(prevProps, currentProps);
1241
+ if (changes.length === 0) {
1242
+ const detector = kernel.getPlugin("wasted-render-detector");
1243
+ detector?.api.markAsWasted(
1244
+ componentId,
1245
+ "props-unchanged",
1246
+ "Re-rendered with identical props; React.memo would have skipped this render"
1247
+ );
1248
+ } else if (options.trackProps) {
1201
1249
  kernel.emit({
1202
1250
  type: "props-change",
1203
1251
  timestamp: Date.now(),
@@ -1213,9 +1261,12 @@ function withScope(WrappedComponent, options = {}) {
1213
1261
  options.onRender(metrics);
1214
1262
  }
1215
1263
  }
1216
- prevPropsRef.current = { ...props };
1217
1264
  });
1218
- return /* @__PURE__ */ jsx(WrappedComponent, { ...props, ref });
1265
+ return React2.createElement(
1266
+ ParentScopeContext.Provider,
1267
+ { value: componentId },
1268
+ React2.createElement(WrappedComponent, { ...props, ref })
1269
+ );
1219
1270
  });
1220
1271
  WithScopeComponent.displayName = `withScope(${displayName})`;
1221
1272
  return WithScopeComponent;
@@ -1368,8 +1419,17 @@ function getMetrics() {
1368
1419
  }
1369
1420
  function exportMetrics() {
1370
1421
  const kernel = getKernel();
1371
- const plugin = kernel?.getPlugin("json-exporter");
1372
- return plugin?.api?.exportAll?.() ?? "{}";
1422
+ const plugin = kernel.getPlugin("json-exporter");
1423
+ if (plugin) {
1424
+ return plugin.api.exportAll();
1425
+ }
1426
+ const exporter = new JSONExporterPlugin();
1427
+ exporter.install(kernel);
1428
+ try {
1429
+ return exporter.api.exportAll();
1430
+ } finally {
1431
+ exporter.uninstall();
1432
+ }
1373
1433
  }
1374
1434
  function clearMetrics() {
1375
1435
  const kernel = getKernel();