bippy 0.2.19 → 0.2.21

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.
package/README.md DELETED
@@ -1,649 +0,0 @@
1
- > [!WARNING]
2
- > ⚠️⚠️⚠️ **this project may break production apps and cause unexpected behavior** ⚠️⚠️⚠️
3
- >
4
- > this project uses react internals, which can change at any time. it is not recommended to depend on internals unless you really, _really_ have to. by proceeding, you acknowledge the risk of breaking your own code or apps that use your code.
5
-
6
- # <img src="https://github.com/aidenybai/bippy/blob/main/.github/assets/bippy.png?raw=true" width="60" align="center" /> bippy
7
-
8
- [![size](https://img.shields.io/bundlephobia/minzip/bippy?label=gzip&style=flat&colorA=000000&colorB=000000)](https://bundlephobia.com/package/bippy)
9
- [![version](https://img.shields.io/npm/v/bippy?style=flat&colorA=000000&colorB=000000)](https://npmjs.com/package/bippy)
10
- [![downloads](https://img.shields.io/npm/dt/bippy.svg?style=flat&colorA=000000&colorB=000000)](https://npmjs.com/package/bippy)
11
-
12
- bippy is a toolkit to **hack into react internals**
13
-
14
- by default, you cannot access react internals. bippy bypasses this by "pretending" to be react devtools, giving you access to the fiber tree and other internals.
15
-
16
- - works outside of react – no react code modification needed
17
- - utility functions that work across modern react (v17-19)
18
- - no prior react source code knowledge required
19
-
20
- ```jsx
21
- import { onCommitFiberRoot, traverseFiber } from 'bippy';
22
-
23
- onCommitFiberRoot((root) => {
24
- traverseFiber(root.current, (fiber) => {
25
- // prints every fiber in the current React tree
26
- console.log('fiber:', fiber);
27
- });
28
- });
29
- ```
30
-
31
- or, use the `/inspect` subpackage to graphically visualize the fiber tree:
32
-
33
- ```jsx
34
- import { Inspector } from 'bippy/inspect';
35
-
36
- <Inspector enabled={true} />
37
- ```
38
-
39
- <table>
40
- <tbody>
41
- <tr>
42
- <td>
43
- <a href="https://bippy.dev"><b>open live demo ↗</b></a>
44
- </td>
45
- </tr>
46
- </tbody>
47
- </table>
48
-
49
- ## how it works & motivation
50
-
51
- bippy allows you to **access** and **use** react fibers **outside** of react components.
52
-
53
- a react fiber is a "unit of execution." this means react will do something based on the data in a fiber. each fiber either represents a composite (function/class component) or a host (dom element).
54
-
55
- > here is a [live visualization](https://jser.pro/ddir/rie?reactVersion=18.3.1&snippetKey=hq8jm2ylzb9u8eh468) of what the fiber tree looks like, and here is a [deep dive article](https://jser.dev/2023-07-18-how-react-rerenders/).
56
-
57
- fibers are useful because they contain information about the react app (component props, state, contexts, etc.). a simplified version of a fiber looks roughly like this:
58
-
59
- ```typescript
60
- interface Fiber {
61
- // component type (function/class)
62
- type: any;
63
-
64
- child: Fiber | null;
65
- sibling: Fiber | null;
66
-
67
- // stateNode is the host fiber (e.g. DOM element)
68
- stateNode: Node | null;
69
-
70
- // parent fiber
71
- return: Fiber | null;
72
-
73
- // the previous or current version of the fiber
74
- alternate: Fiber | null;
75
-
76
- // saved props input
77
- memoizedProps: any;
78
-
79
- // state (useState, useReducer, useSES, etc.)
80
- memoizedState: any;
81
-
82
- // contexts (useContext)
83
- dependencies: Dependencies | null;
84
-
85
- // effects (useEffect, useLayoutEffect, etc.)
86
- updateQueue: any;
87
- }
88
- ```
89
-
90
- here, the `child`, `sibling`, and `return` properties are pointers to other fibers in the tree.
91
-
92
- additionally, `memoizedProps`, `memoizedState`, and `dependencies` are the fiber's props, state, and contexts.
93
-
94
- while all of the information is there, it's not super easy to work with, and changes frequently across different versions of react. bippy simplifies this by providing utility functions like:
95
-
96
- - `traverseRenderedFibers` to detect renders and `traverseFiber` to traverse the overall fiber tree
97
- - _(instead of `child`, `sibling`, and `return` pointers)_
98
- - `traverseProps`, `traverseState`, and `traverseContexts` to traverse the fiber's props, state, and contexts
99
- - _(instead of `memoizedProps`, `memoizedState`, and `dependencies`)_
100
-
101
- however, fibers aren't directly accessible by the user. so, we have to hack our way around to accessing it.
102
-
103
- luckily, react [reads from a property](https://github.com/facebook/react/blob/6a4b46cd70d2672bc4be59dcb5b8dede22ed0cef/packages/react-reconciler/src/reactFiberDevToolsHook.js#L48) in the window object: `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` and runs handlers on it when certain events happen. this property must exist before react's bundle is executed. this is intended for react devtools, but we can use it to our advantage.
104
-
105
- here's what it roughly looks like:
106
-
107
- ```typescript
108
- interface __REACT_DEVTOOLS_GLOBAL_HOOK__ {
109
- // list of renderers (react-dom, react-native, etc.)
110
- renderers: Map<RendererID, reactRenderer>;
111
-
112
- // called when react has rendered everything for an update and the fiber tree is fully built and ready to
113
- // apply changes to the host tree (e.g. DOM mutations)
114
- onCommitFiberRoot: (
115
- rendererID: RendererID,
116
- root: FiberRoot,
117
- commitPriority?: number
118
- ) => void;
119
-
120
- // called when effects run
121
- onPostCommitFiberRoot: (rendererID: RendererID, root: FiberRoot) => void;
122
-
123
- // called when a specific fiber unmounts
124
- onCommitFiberUnmount: (rendererID: RendererID, fiber: Fiber) => void;
125
- }
126
- ```
127
-
128
- bippy works by monkey-patching `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` with our own custom handlers. bippy simplifies this by providing utility functions like:
129
-
130
- - `instrument` to safely patch `window.__REACT_DEVTOOLS_GLOBAL_HOOK__`
131
- - _(instead of directly mutating `onCommitFiberRoot`, ...)_
132
- - `secure` to wrap your handlers in a try/catch and determine if handlers are safe to run
133
- - _(instead of rawdogging `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` handlers, which may crash your app)_
134
- - `traverseRenderedFibers` to traverse the fiber tree and determine which fibers have actually rendered
135
- - _(instead of `child`, `sibling`, and `return` pointers)_
136
- - `traverseFiber` to traverse the fiber tree, regardless of whether it has rendered
137
- - _(instead of `child`, `sibling`, and `return` pointers)_
138
- - `setFiberId` / `getFiberId` to set and get a fiber's id
139
- - _(instead of anonymous fibers with no identity)_
140
-
141
- ## how to use
142
-
143
- you can either install via a npm (recommended) or a script tag.
144
-
145
- this package should be imported before a React app runs. this will add a special object to the global which is used by React for providing its internals to the tool for analysis (React Devtools does the same). as soon as React library is loaded and attached to the tool, bippy starts collecting data about what is going on in React's internals.
146
-
147
- ```shell
148
- npm install bippy
149
- ```
150
-
151
- or, use via script tag:
152
-
153
- ```html
154
- <script src="https://unpkg.com/bippy"></script>
155
- ```
156
-
157
- > this will cause bippy to be accessible under a `window.Bippy` global.
158
-
159
- next, you can use the api to get data about the fiber tree. below is a (useful) subset of the api. for the full api, read the [source code](https://github.com/aidenybai/bippy/blob/main/src/core.ts).
160
-
161
-
162
- ### onCommitFiberRoot
163
-
164
- a utility function that wraps the `instrument` function and sets the `onCommitFiberRoot` hook.
165
-
166
- ```typescript
167
- import { onCommitFiberRoot } from 'bippy';
168
-
169
- onCommitFiberRoot((root) => {
170
- console.log('root ready to commit', root);
171
- });
172
- ```
173
-
174
- ### instrument
175
-
176
- > the underlying implementation for the `onCommitFiberRoot()` function. this is optional, unless you want to plug into more less common, advanced functionality.
177
-
178
- patches `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` with your handlers. must be imported before react, and must be initialized to properly run any other methods.
179
-
180
- > use with the `secure` function to prevent uncaught errors from crashing your app.
181
-
182
- ```typescript
183
- import { instrument, secure } from 'bippy'; // must be imported BEFORE react
184
- import * as React from 'react';
185
-
186
- instrument(
187
- secure({
188
- onCommitFiberRoot(rendererID, root) {
189
- console.log('root ready to commit', root);
190
- },
191
- onPostCommitFiberRoot(rendererID, root) {
192
- console.log('root with effects committed', root);
193
- },
194
- onCommitFiberUnmount(rendererID, fiber) {
195
- console.log('fiber unmounted', fiber);
196
- },
197
- })
198
- );
199
- ```
200
-
201
- ### getRDTHook
202
-
203
- returns the `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` object. great for advanced use cases, such as accessing or modifying the `renderers` property.
204
-
205
- ```typescript
206
- import { getRDTHook } from 'bippy';
207
-
208
- const hook = getRDTHook();
209
- console.log(hook);
210
- ```
211
-
212
- ### traverseRenderedFibers
213
-
214
- not every fiber in the fiber tree renders. `traverseRenderedFibers` allows you to traverse the fiber tree and determine which fibers have actually rendered.
215
-
216
- ```typescript
217
- import { instrument, secure, traverseRenderedFibers } from 'bippy'; // must be imported BEFORE react
218
- import * as React from 'react';
219
-
220
- instrument(
221
- secure({
222
- onCommitFiberRoot(rendererID, root) {
223
- traverseRenderedFibers(root, (fiber) => {
224
- console.log('fiber rendered', fiber);
225
- });
226
- },
227
- })
228
- );
229
- ```
230
-
231
- ### traverseFiber
232
-
233
- calls a callback on every fiber in the fiber tree.
234
-
235
- ```typescript
236
- import { instrument, secure, traverseFiber } from 'bippy'; // must be imported BEFORE react
237
- import * as React from 'react';
238
-
239
- instrument(
240
- secure({
241
- onCommitFiberRoot(rendererID, root) {
242
- traverseFiber(root.current, (fiber) => {
243
- console.log(fiber);
244
- });
245
- },
246
- })
247
- );
248
- ```
249
-
250
- ### traverseProps
251
-
252
- traverses the props of a fiber.
253
-
254
- ```typescript
255
- import { traverseProps } from 'bippy';
256
-
257
- // ...
258
-
259
- traverseProps(fiber, (propName, next, prev) => {
260
- console.log(propName, next, prev);
261
- });
262
- ```
263
-
264
- ### traverseState
265
-
266
- traverses the state (useState, useReducer, etc.) and effects that set state of a fiber.
267
-
268
- ```typescript
269
- import { traverseState } from 'bippy';
270
-
271
- // ...
272
-
273
- traverseState(fiber, (next, prev) => {
274
- console.log(next, prev);
275
- });
276
- ```
277
-
278
- ### traverseEffects
279
-
280
- traverses the effects (useEffect, useLayoutEffect, etc.) of a fiber.
281
-
282
- ```typescript
283
- import { traverseEffects } from 'bippy';
284
-
285
- // ...
286
-
287
- traverseEffects(fiber, (effect) => {
288
- console.log(effect);
289
- });
290
- ```
291
-
292
- ### traverseContexts
293
-
294
- traverses the contexts (useContext) of a fiber.
295
-
296
- ```typescript
297
- import { traverseContexts } from 'bippy';
298
-
299
- // ...
300
-
301
- traverseContexts(fiber, (next, prev) => {
302
- console.log(next, prev);
303
- });
304
- ```
305
-
306
-
307
- ### setFiberId / getFiberId
308
-
309
- set and get a persistent identity for a fiber. by default, fibers are anonymous and have no identity.
310
-
311
- ```typescript
312
- import { setFiberId, getFiberId } from 'bippy';
313
-
314
- // ...
315
-
316
- setFiberId(fiber);
317
- console.log('unique id for fiber:', getFiberId(fiber));
318
- ```
319
-
320
- ### isHostFiber
321
-
322
- returns `true` if the fiber is a host fiber (e.g., a DOM node in react-dom).
323
-
324
- ```typescript
325
- import { isHostFiber } from 'bippy';
326
-
327
- if (isHostFiber(fiber)) {
328
- console.log('fiber is a host fiber');
329
- }
330
- ```
331
-
332
- ### isCompositeFiber
333
-
334
- returns `true` if the fiber is a composite fiber. composite fibers represent class components, function components, memoized components, and so on (anything that can actually render output).
335
-
336
- ```typescript
337
- import { isCompositeFiber } from 'bippy';
338
-
339
- if (isCompositeFiber(fiber)) {
340
- console.log('fiber is a composite fiber');
341
- }
342
- ```
343
-
344
- ### getDisplayName
345
-
346
- returns the display name of the fiber's component, falling back to the component's function or class name if available.
347
-
348
- ```typescript
349
- import { getDisplayName } from 'bippy';
350
-
351
- console.log(getDisplayName(fiber));
352
- ```
353
-
354
- ### getType
355
-
356
- returns the underlying type (the component definition) for a given fiber. for example, this could be a function component or class component.
357
-
358
- ```jsx
359
- import { getType } from 'bippy';
360
- import { memo } from 'react';
361
-
362
- const RealComponent = () => {
363
- return <div>hello</div>;
364
- };
365
- const MemoizedComponent = memo(() => {
366
- return <div>hello</div>;
367
- });
368
-
369
- console.log(getType(fiberForMemoizedComponent) === RealComponent);
370
- ```
371
-
372
- ### getNearestHostFiber / getNearestHostFibers
373
-
374
- getNearestHostFiber returns the closest host fiber above or below a given fiber. getNearestHostFibers(fiber) returns all host fibers associated with the provided fiber and its subtree.
375
-
376
- ```jsx
377
- import { getNearestHostFiber, getNearestHostFibers } from 'bippy';
378
-
379
- // ...
380
-
381
- function Component() {
382
- return (
383
- <>
384
- <div>hello</div>
385
- <div>world</div>
386
- </>
387
- );
388
- }
389
-
390
- console.log(getNearestHostFiber(fiberForComponent)); // <div>hello</div>
391
- console.log(getNearestHostFibers(fiberForComponent)); // [<div>hello</div>, <div>world</div>]
392
- ```
393
-
394
- ### getTimings
395
-
396
- returns the self and total render times for the fiber.
397
-
398
- ```typescript
399
- // timings don't exist in react production builds
400
- if (fiber.actualDuration !== undefined) {
401
- const { selfTime, totalTime } = getTimings(fiber);
402
- console.log(selfTime, totalTime);
403
- }
404
- ```
405
-
406
- ### getFiberStack
407
-
408
- returns an array representing the stack of fibers from the current fiber up to the root.
409
-
410
- ```typescript
411
- [fiber, fiber.return, fiber.return.return, ...]
412
- ```
413
-
414
- ### getMutatedHostFibers
415
-
416
- returns an array of all host fibers that have committed and rendered in the provided fiber's subtree.
417
-
418
- ```typescript
419
- import { getMutatedHostFibers } from 'bippy';
420
-
421
- console.log(getMutatedHostFibers(fiber));
422
- ```
423
-
424
- ### isValidFiber
425
-
426
- returns `true` if the given object is a valid React Fiber (i.e., has a tag, stateNode, return, child, sibling, etc.).
427
-
428
- ```typescript
429
- import { isValidFiber } from 'bippy';
430
-
431
- console.log(isValidFiber(fiber));
432
- ```
433
-
434
- ## examples
435
-
436
- the best way to understand bippy is to [read the source code](https://github.com/aidenybai/bippy/blob/main/src/core.ts). here are some examples of how you can use it:
437
-
438
- ### a mini react-scan
439
-
440
- here's a mini toy version of [`react-scan`](https://github.com/aidenybai/react-scan) that highlights renders in your app.
441
-
442
- ```javascript
443
- import {
444
- instrument,
445
- isHostFiber,
446
- getNearestHostFiber,
447
- traverseRenderedFibers,
448
- } from 'bippy'; // must be imported BEFORE react
449
-
450
- const highlightFiber = (fiber) => {
451
- if (!(fiber.stateNode instanceof HTMLElement)) return;
452
- // fiber.stateNode is a DOM element
453
- const rect = fiber.stateNode.getBoundingClientRect();
454
- const highlight = document.createElement('div');
455
- highlight.style.border = '1px solid red';
456
- highlight.style.position = 'fixed';
457
- highlight.style.top = `${rect.top}px`;
458
- highlight.style.left = `${rect.left}px`;
459
- highlight.style.width = `${rect.width}px`;
460
- highlight.style.height = `${rect.height}px`;
461
- highlight.style.zIndex = 999999999;
462
- document.documentElement.appendChild(highlight);
463
- setTimeout(() => {
464
- document.documentElement.removeChild(highlight);
465
- }, 100);
466
- };
467
-
468
- /**
469
- * `instrument` is a function that installs the react DevTools global
470
- * hook and allows you to set up custom handlers for react fiber events.
471
- */
472
- instrument(
473
- /**
474
- * `secure` is a function that wraps your handlers in a try/catch
475
- * and prevents it from crashing the app. it also prevents it from
476
- * running on unsupported react versions and during production.
477
- *
478
- * this is not required but highly recommended to provide "safeguards"
479
- * in case something breaks.
480
- */
481
- secure({
482
- /**
483
- * `onCommitFiberRoot` is a handler that is called when react is
484
- * ready to commit a fiber root. this means that react is has
485
- * rendered your entire app and is ready to apply changes to
486
- * the host tree (e.g. via DOM mutations).
487
- */
488
- onCommitFiberRoot(rendererID, root) {
489
- /**
490
- * `traverseRenderedFibers` traverses the fiber tree and determines which
491
- * fibers have actually rendered.
492
- *
493
- * A fiber tree contains many fibers that may have not rendered. this
494
- * can be because it bailed out (e.g. `useMemo`) or because it wasn't
495
- * actually rendered (if <Child> re-rendered, then <Parent> didn't
496
- * actually render, but exists in the fiber tree).
497
- */
498
- traverseRenderedFibers(root, (fiber) => {
499
- /**
500
- * `getNearestHostFiber` is a utility function that finds the
501
- * nearest host fiber to a given fiber.
502
- *
503
- * a host fiber for `react-dom` is a fiber that has a DOM element
504
- * as its `stateNode`.
505
- */
506
- const hostFiber = getNearestHostFiber(fiber);
507
- highlightFiber(hostFiber);
508
- });
509
- },
510
- })
511
- );
512
- ```
513
-
514
- ### a mini why-did-you-render
515
-
516
- here's a mini toy version of [`why-did-you-render`](https://github.com/welldone-software/why-did-you-render) that logs why components re-render.
517
-
518
- ```typescript
519
- import {
520
- instrument,
521
- isHostFiber,
522
- traverseRenderedFibers,
523
- isCompositeFiber,
524
- getDisplayName,
525
- traverseProps,
526
- traverseContexts,
527
- traverseState,
528
- } from 'bippy'; // must be imported BEFORE react
529
-
530
- instrument(
531
- secure({
532
- onCommitFiberRoot(rendererID, root) {
533
- traverseRenderedFibers(root, (fiber) => {
534
- /**
535
- * `isCompositeFiber` is a utility function that checks if a fiber is a composite fiber.
536
- * a composite fiber is a fiber that represents a function or class component.
537
- */
538
- if (!isCompositeFiber(fiber)) return;
539
-
540
- /**
541
- * `getDisplayName` is a utility function that gets the display name of a fiber.
542
- */
543
- const displayName = getDisplayName(fiber);
544
- if (!displayName) return;
545
-
546
- const changes = [];
547
-
548
- /**
549
- * `traverseProps` is a utility function that traverses the props of a fiber.
550
- */
551
- traverseProps(fiber, (propName, next, prev) => {
552
- if (next !== prev) {
553
- changes.push({
554
- name: `prop ${propName}`,
555
- prev,
556
- next,
557
- });
558
- }
559
- });
560
-
561
- let contextId = 0;
562
- /**
563
- * `traverseContexts` is a utility function that traverses the contexts of a fiber.
564
- * Contexts don't have a "name" like props, so we use an id to identify them.
565
- */
566
- traverseContexts(fiber, (next, prev) => {
567
- if (next !== prev) {
568
- changes.push({
569
- name: `context ${contextId}`,
570
- prev,
571
- next,
572
- contextId,
573
- });
574
- }
575
- contextId++;
576
- });
577
-
578
- let stateId = 0;
579
- /**
580
- * `traverseState` is a utility function that traverses the state of a fiber.
581
- *
582
- * State don't have a "name" like props, so we use an id to identify them.
583
- */
584
- traverseState(fiber, (value, prevValue) => {
585
- if (next !== prev) {
586
- changes.push({
587
- name: `state ${stateId}`,
588
- prev,
589
- next,
590
- });
591
- }
592
- stateId++;
593
- });
594
-
595
- console.group(
596
- `%c${displayName}`,
597
- 'background: hsla(0,0%,70%,.3); border-radius:3px; padding: 0 2px;'
598
- );
599
- for (const { name, prev, next } of changes) {
600
- console.log(`${name}:`, prev, '!==', next);
601
- }
602
- console.groupEnd();
603
- });
604
- },
605
- })
606
- );
607
- ```
608
-
609
- ## glossary
610
-
611
- - fiber: a "unit of execution" in react, representing a component or dom element
612
- - commit: the process of applying changes to the host tree (e.g. DOM mutations)
613
- - render: the process of building the fiber tree by executing component function/classes
614
- - host tree: the tree of UI elements that react mutates (e.g. DOM elements)
615
- - reconciler (or "renderer"): custom bindings for react, e.g. react-dom, react-native, react-three-fiber, etc to mutate the host tree
616
- - `rendererID`: the id of the reconciler, starting at 1 (can be from multiple reconciler instances)
617
- - `root`: a special `FiberRoot` type that contains the container fiber (the one you pass to `ReactDOM.createRoot`) in the `current` property
618
- - `onCommitFiberRoot`: called when react is ready to commit a fiber root
619
- - `onPostCommitFiberRoot`: called when react has committed a fiber root and effects have run
620
- - `onCommitFiberUnmount`: called when a fiber unmounts
621
-
622
- ## development
623
-
624
- we use a pnpm monorepo, get started by running:
625
-
626
- ```shell
627
- pnpm install
628
- # create dev builds
629
- pnpm run dev
630
- # run unit tests
631
- pnpm run test
632
- ```
633
-
634
- you can ad-hoc test by running `pnpm run dev` in the `/kitchen-sink` directory.
635
-
636
- ```shell
637
- cd kitchen-sink
638
- pnpm run dev
639
- ```
640
-
641
- ## misc
642
-
643
- we use this project internally in [react-scan](https://github.com/aidenybai/react-scan), which is deployed with proper safeguards to ensure it's only used in development or error-guarded in production.
644
-
645
- while i maintain this specifically for react-scan, those seeking more robust solutions might consider [its-fine](https://github.com/pmndrs/its-fine) for accessing fibers within react using hooks, or [react-devtools-inline](https://www.npmjs.com/package/react-devtools-inline) for a headful interface.
646
-
647
- if you plan to use this project beyond experimentation, please review [react-scan's source code](https://github.com/aidenybai/react-scan) to understand our safeguarding practices.
648
-
649
- the original bippy character is owned and created by [@dairyfreerice](https://www.instagram.com/dairyfreerice). this project is not related to the bippy brand, i just think the character is cute.