@capybara-devtools/core 0.4.0 → 0.5.1

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/dist/client.d.ts.map +1 -1
  2. package/dist/client.js +20 -2
  3. package/dist/client.js.map +1 -1
  4. package/dist/index.d.ts +8 -2
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +4 -1
  7. package/dist/index.js.map +1 -1
  8. package/dist/init.d.ts +40 -0
  9. package/dist/init.d.ts.map +1 -0
  10. package/dist/init.js +35 -0
  11. package/dist/init.js.map +1 -0
  12. package/dist/plugins/console.d.ts.map +1 -1
  13. package/dist/plugins/console.js +105 -9
  14. package/dist/plugins/console.js.map +1 -1
  15. package/dist/plugins/network/body.d.ts +9 -0
  16. package/dist/plugins/network/body.d.ts.map +1 -0
  17. package/dist/plugins/network/body.js +114 -0
  18. package/dist/plugins/network/body.js.map +1 -0
  19. package/dist/plugins/network/failure.d.ts +16 -0
  20. package/dist/plugins/network/failure.d.ts.map +1 -0
  21. package/dist/plugins/network/failure.js +73 -0
  22. package/dist/plugins/network/failure.js.map +1 -0
  23. package/dist/plugins/network/fetch.d.ts +12 -0
  24. package/dist/plugins/network/fetch.d.ts.map +1 -0
  25. package/dist/plugins/network/fetch.js +159 -0
  26. package/dist/plugins/network/fetch.js.map +1 -0
  27. package/dist/plugins/network/settings.d.ts +24 -0
  28. package/dist/plugins/network/settings.d.ts.map +1 -0
  29. package/dist/plugins/network/settings.js +26 -0
  30. package/dist/plugins/network/settings.js.map +1 -0
  31. package/dist/plugins/network/xhr.d.ts +4 -0
  32. package/dist/plugins/network/xhr.d.ts.map +1 -0
  33. package/dist/plugins/network/xhr.js +214 -0
  34. package/dist/plugins/network/xhr.js.map +1 -0
  35. package/dist/plugins/network.d.ts +2 -15
  36. package/dist/plugins/network.d.ts.map +1 -1
  37. package/dist/plugins/network.js +8 -497
  38. package/dist/plugins/network.js.map +1 -1
  39. package/dist/plugins/state/context-names.d.ts +13 -0
  40. package/dist/plugins/state/context-names.d.ts.map +1 -0
  41. package/dist/plugins/state/context-names.js +280 -0
  42. package/dist/plugins/state/context-names.js.map +1 -0
  43. package/dist/plugins/state/context.d.ts +0 -89
  44. package/dist/plugins/state/context.d.ts.map +1 -1
  45. package/dist/plugins/state/context.js +3 -474
  46. package/dist/plugins/state/context.js.map +1 -1
  47. package/dist/plugins/state/engine.d.ts +5 -0
  48. package/dist/plugins/state/engine.d.ts.map +1 -1
  49. package/dist/plugins/state/engine.js +12 -2
  50. package/dist/plugins/state/engine.js.map +1 -1
  51. package/dist/plugins/state/fibers.d.ts +75 -0
  52. package/dist/plugins/state/fibers.d.ts.map +1 -0
  53. package/dist/plugins/state/fibers.js +92 -0
  54. package/dist/plugins/state/fibers.js.map +1 -0
  55. package/dist/plugins/state/index.d.ts +5 -0
  56. package/dist/plugins/state/index.d.ts.map +1 -1
  57. package/dist/plugins/state/index.js.map +1 -1
  58. package/dist/plugins/state/mobx.d.ts +22 -0
  59. package/dist/plugins/state/mobx.d.ts.map +1 -0
  60. package/dist/plugins/state/mobx.js +69 -0
  61. package/dist/plugins/state/mobx.js.map +1 -0
  62. package/dist/plugins/state/react-hook.d.ts +19 -0
  63. package/dist/plugins/state/react-hook.d.ts.map +1 -0
  64. package/dist/plugins/state/react-hook.js +100 -0
  65. package/dist/plugins/state/react-hook.js.map +1 -0
  66. package/dist/plugins/state/redux.d.ts +2 -0
  67. package/dist/plugins/state/redux.d.ts.map +1 -1
  68. package/dist/plugins/state/redux.js +2 -2
  69. package/dist/plugins/state/redux.js.map +1 -1
  70. package/dist/plugins/state/xstate.d.ts +26 -0
  71. package/dist/plugins/state/xstate.d.ts.map +1 -0
  72. package/dist/plugins/state/xstate.js +85 -0
  73. package/dist/plugins/state/xstate.js.map +1 -0
  74. package/dist/plugins/storage.d.ts +1 -1
  75. package/dist/plugins/storage.d.ts.map +1 -1
  76. package/dist/plugins/storage.js +5 -7
  77. package/dist/plugins/storage.js.map +1 -1
  78. package/dist/serialize.d.ts.map +1 -1
  79. package/dist/serialize.js +1 -0
  80. package/dist/serialize.js.map +1 -1
  81. package/package.json +7 -5
  82. package/src/client.ts +19 -2
  83. package/src/index.ts +8 -2
  84. package/src/init.ts +66 -0
  85. package/src/plugins/console.ts +103 -10
  86. package/src/plugins/network/body.ts +114 -0
  87. package/src/plugins/network/failure.ts +79 -0
  88. package/src/plugins/network/fetch.ts +169 -0
  89. package/src/plugins/network/settings.ts +48 -0
  90. package/src/plugins/network/xhr.ts +223 -0
  91. package/src/plugins/network.ts +11 -545
  92. package/src/plugins/state/context-names.ts +265 -0
  93. package/src/plugins/state/context.ts +3 -532
  94. package/src/plugins/state/engine.ts +12 -2
  95. package/src/plugins/state/fibers.ts +160 -0
  96. package/src/plugins/state/index.ts +2 -0
  97. package/src/plugins/state/mobx.ts +80 -0
  98. package/src/plugins/state/react-hook.ts +98 -0
  99. package/src/plugins/state/redux.ts +2 -2
  100. package/src/plugins/state/xstate.ts +94 -0
  101. package/src/plugins/storage.ts +13 -8
  102. package/src/serialize.ts +2 -1
@@ -0,0 +1,160 @@
1
+ // React Context is read from React's own fibers, through the global hook React DevTools uses. Fibers are React
2
+ // internals; what is read here (tags, `child`, `sibling`, `alternate`, `memoizedProps`) is the same in React 18
3
+ // and 19, which were checked. Nothing is ever written to a fiber: React prevents extensions to them in development.
4
+
5
+ /** A React fiber, as far as Capybara reads one. */
6
+ export interface Fiber {
7
+ tag: number;
8
+ key?: string | null;
9
+ type: any;
10
+ /** memo() keeps the wrapper here and the function in `type`. */
11
+ elementType?: any;
12
+ return: Fiber | null;
13
+ child: Fiber | null;
14
+ sibling: Fiber | null;
15
+ alternate: Fiber | null;
16
+ memoizedProps: any;
17
+ memoizedState?: any;
18
+ /** Children this fiber removed in the commit that made it. */
19
+ deletions?: Fiber[] | null;
20
+ _debugOwner?: unknown;
21
+ /** React 19: where the element was created. */
22
+ _debugStack?: unknown;
23
+ /** React 18 with the JSX source transform. */
24
+ _debugSource?: unknown;
25
+ }
26
+
27
+ /** What React hands `onCommitFiberRoot`; `current` is the HostRoot fiber of the tree just committed. */
28
+ export interface FiberRoot {
29
+ current: Fiber;
30
+ }
31
+
32
+ /** Where a walk cut short by its budget goes on from. */
33
+ export interface WalkCursor {
34
+ top: Fiber;
35
+ node: Fiber;
36
+ /** Ancestors of `node` below `top`, outermost first. */
37
+ stack: Fiber[];
38
+ }
39
+
40
+ export interface ProviderHit {
41
+ fiber: Fiber;
42
+ /** The context object, the same for every provider of one context. */
43
+ context: unknown;
44
+ value: unknown;
45
+ /** Neither this fiber nor its alternate was in `seen` before. */
46
+ first: boolean;
47
+ }
48
+
49
+ export interface WalkProvidersOptions {
50
+ /**
51
+ * Right after a commit: go only into subtrees whose children changed in it, and report known providers whose
52
+ * value changed too. Without it, every fiber is visited and only providers missing from `seen` are reported.
53
+ */
54
+ changed?: boolean;
55
+ /** Return after about this many milliseconds, with `next` to go on from. Default: no limit. */
56
+ budget?: number;
57
+ /** Return once this many providers are reported, with `next` to go on from. Default: no limit. */
58
+ limit?: number;
59
+ from?: WalkCursor | null;
60
+ /** Called on every fiber visited, e.g. to look for stores in hooks. */
61
+ visit?: (fiber: Fiber) => void;
62
+ /** Clock for `budget`. Default `performance.now`, else `Date.now`. */
63
+ now?: () => number;
64
+ }
65
+
66
+ export interface WalkProvidersResult {
67
+ providers: ProviderHit[];
68
+ visited: number;
69
+ /** With `changed`: a fiber visited removed children in the commit, so some provider may be gone. */
70
+ removed: boolean;
71
+ /** Set when the budget ran out first. */
72
+ next: WalkCursor | null;
73
+ }
74
+
75
+ /**
76
+ * Finds context providers (tag 10) under `root`, a FiberRoot or a fiber. `seen` maps each provider fiber, and its
77
+ * alternate, to the last value reported, and is updated as providers are reported.
78
+ *
79
+ * Self-contained, like the engine: the Metro bridge runs it from its source inside apps without the SDK. Iterative
80
+ * with a stack of its own rather than `return` pointers, which may lead to the other copy of a parent.
81
+ */
82
+ export function walkProviders(root: object, seen: WeakMap<object, unknown>, options: WalkProvidersOptions = {}): WalkProvidersResult {
83
+ const PROVIDER = 10;
84
+ const changed = options.changed === true;
85
+ const visit = typeof options.visit === 'function' ? options.visit : undefined;
86
+ const clock =
87
+ typeof options.now === 'function'
88
+ ? options.now
89
+ : typeof performance === 'object' && performance !== null && typeof performance.now === 'function'
90
+ ? () => performance.now()
91
+ : () => Date.now();
92
+ const budget = typeof options.budget === 'number' && options.budget >= 0 ? options.budget : Infinity;
93
+ const deadline = budget === Infinity ? Infinity : clock() + budget;
94
+ const limit = typeof options.limit === 'number' && options.limit > 0 ? options.limit : Infinity;
95
+ const from = options.from;
96
+ const top: Fiber | null = from ? from.top : 'current' in root ? (root as FiberRoot).current : (root as Fiber);
97
+ const stack: Fiber[] = from ? from.stack.slice() : [];
98
+ const providers: ProviderHit[] = [];
99
+ let visited = 0;
100
+ let removed = false;
101
+ let node: Fiber | null = from ? from.node : top;
102
+
103
+ while (node != null) {
104
+ visited++;
105
+ if (node.tag === PROVIDER) {
106
+ const type = node.type;
107
+ // React 19 renders the context itself; React 18 renders `context.Provider`, which points back to it.
108
+ const context = type != null && typeof type === 'object' && type._context != null ? type._context : type;
109
+ const props = node.memoizedProps;
110
+ const value = props != null && typeof props === 'object' ? props.value : undefined;
111
+ const alternate = node.alternate;
112
+ const own = seen.has(node);
113
+ if (!own && (alternate == null || !seen.has(alternate))) {
114
+ providers.push({ fiber: node, context, value, first: true });
115
+ seen.set(node, value);
116
+ if (alternate != null) seen.set(alternate, value);
117
+ } else if (changed) {
118
+ const last = own ? seen.get(node) : seen.get(alternate as Fiber);
119
+ if (!(last === value || (last !== last && value !== value))) {
120
+ providers.push({ fiber: node, context, value, first: false });
121
+ seen.set(node, value);
122
+ if (alternate != null) seen.set(alternate, value);
123
+ } else if (!own) {
124
+ seen.set(node, value);
125
+ }
126
+ }
127
+ }
128
+ if (changed && !removed && node.deletions != null && node.deletions.length > 0) removed = true;
129
+ if (visit) visit(node);
130
+
131
+ let child: Fiber | null = node.child;
132
+ // A subtree that bailed out keeps its child fiber, so nothing under it changed in this commit.
133
+ if (changed && child != null && node.alternate != null && node.alternate.child === child) child = null;
134
+ if (child != null) {
135
+ stack.push(node);
136
+ node = child;
137
+ } else {
138
+ let next: Fiber | null = null;
139
+ while (node != null && node !== top) {
140
+ if (node.sibling != null) {
141
+ next = node.sibling;
142
+ break;
143
+ }
144
+ node = stack.length > 0 ? stack.pop()! : null;
145
+ }
146
+ node = next;
147
+ }
148
+ if (
149
+ node != null &&
150
+ top != null &&
151
+ (providers.length >= limit || (deadline !== Infinity && (visited & 127) === 0 && clock() >= deadline))
152
+ ) {
153
+ return { providers, visited, removed, next: { top, node, stack } };
154
+ }
155
+ }
156
+ return { providers, visited, removed, next: null };
157
+ }
158
+
159
+ /** Fiber tag of a root. */
160
+ export const HOST_ROOT = 3;
@@ -57,6 +57,8 @@ export interface StatePluginOptions {
57
57
  /** Runs before a state is diffed or read, e.g. to blank out tokens; only what it returns leaves the app. */
58
58
  sanitizeState?: (state: unknown, store: StateStoreInfo) => unknown;
59
59
  sanitizeAction?: (action: unknown, store: StateStoreInfo) => unknown;
60
+ /** Runs before the data of a TanStack Query or SWR entry is read; only what it returns leaves the app. */
61
+ sanitizeEntry?: (data: unknown, entry: { store: StateStoreInfo; key: string }) => unknown;
60
62
  /** Leave out keys that hold functions, such as Zustand actions. Default true. */
61
63
  hideFunctions?: boolean;
62
64
  /**
@@ -0,0 +1,80 @@
1
+ import type { StoreDriver } from './index.js';
2
+ import { defaultLabel } from './redux.js';
3
+ import { register, unregister } from './registry.js';
4
+
5
+ /** The functions of the `mobx` module Capybara uses, passed in so the SDK does not depend on MobX. */
6
+ export interface MobxLike {
7
+ reaction(expression: () => unknown, effect: (value: any) => void): () => void;
8
+ toJS(value: unknown): unknown;
9
+ // Loose enough for the mobx module itself: in change events, `name` is the key of an object or a map, of any type.
10
+ spy?(listener: (event: { type: string; name?: unknown; spyReportStart?: boolean; spyReportEnd?: boolean }) => void): () => void;
11
+ }
12
+
13
+ export interface WatchMobXOptions {
14
+ /** Shown in the State tab. Defaults to "MobX store #n". */
15
+ name?: string;
16
+ }
17
+
18
+ const watched = new WeakMap<object, { driver: StoreDriver; id: string | undefined }>();
19
+
20
+ /**
21
+ * Shows a MobX observable, such as a store made with makeAutoObservable, in the State tab: each change as a diff,
22
+ * named after the action that made it. Pass the mobx module, e.g. `import * as mobx from 'mobx'`. Returns a function
23
+ * that undoes this call.
24
+ */
25
+ export function watchMobX(store: object, mobx: MobxLike, options: WatchMobXOptions = {}): () => void {
26
+ if (typeof window === 'undefined' || store === null || typeof store !== 'object') return () => {};
27
+ if (typeof mobx?.reaction !== 'function' || typeof mobx.toJS !== 'function') return () => {};
28
+ try {
29
+ const known = watched.get(store);
30
+ if (known) {
31
+ known.id = register(known.driver, store) ?? known.id;
32
+ return () => {};
33
+ }
34
+ const spy = typeof mobx.spy === 'function' ? mobx.spy : undefined;
35
+ const driver: StoreDriver = {
36
+ info: {
37
+ library: 'mobx',
38
+ label: typeof options.name === 'string' && options.name !== '' ? options.name : defaultLabel('mobx', mobx.toJS(store)),
39
+ via: 'subscribe',
40
+ actions: spy !== undefined,
41
+ },
42
+ getState: () => mobx.toJS(store),
43
+ start(sink, id) {
44
+ // The outermost action running. Reactions run when it ends, still inside its spy report.
45
+ let action: string | undefined;
46
+ let depth = 0;
47
+ const stopSpy = spy?.((event) => {
48
+ if (event.type === 'action' && depth === 0 && typeof event.name === 'string' && event.name !== '' && event.name !== '<unnamed action>') {
49
+ action = event.name;
50
+ }
51
+ if (event.spyReportStart) depth++;
52
+ if (event.spyReportEnd) {
53
+ depth = Math.max(0, depth - 1);
54
+ if (depth === 0) action = undefined;
55
+ }
56
+ });
57
+ const stopReaction = mobx.reaction(
58
+ () => mobx.toJS(store),
59
+ (state) => sink.record(id, state, action === undefined ? undefined : { type: action }, action === undefined ? 'set' : 'action'),
60
+ );
61
+ return () => {
62
+ stopReaction();
63
+ stopSpy?.();
64
+ };
65
+ },
66
+ };
67
+ const entry = { driver, id: undefined as string | undefined };
68
+ watched.set(store, entry);
69
+ entry.id = register(driver, store);
70
+ let undone = false;
71
+ return () => {
72
+ if (undone) return;
73
+ undone = true;
74
+ watched.delete(store);
75
+ if (entry.id !== undefined) unregister(entry.id);
76
+ };
77
+ } catch {
78
+ return () => {};
79
+ }
80
+ }
@@ -0,0 +1,98 @@
1
+ import type { FiberRoot } from './fibers.js';
2
+
3
+ const HOOK = '__REACT_DEVTOOLS_GLOBAL_HOOK__';
4
+
5
+ /** React DevTools' global hook, as far as Capybara uses it. */
6
+ export interface ReactHook {
7
+ isDisabled?: unknown;
8
+ renderers?: unknown;
9
+ getFiberRoots?: (rendererID: unknown) => Iterable<unknown>;
10
+ onCommitFiberRoot?: unknown;
11
+ }
12
+
13
+ /**
14
+ * Has `onCommit` called after each commit React reports to the React DevTools global hook. An existing hook keeps
15
+ * its object, which React holds on to: only its `onCommitFiberRoot` property is wrapped, the original called
16
+ * first. Without a hook, installs a minimal one, which only works when this runs before react-dom loads.
17
+ * Returns the undo, which leaves a wrapper someone else wrapped since in place, passing calls on.
18
+ */
19
+ export function installReactHook(onCommit: (root: FiberRoot) => void): { hook: ReactHook | undefined; undo: () => void } {
20
+ const none = { hook: undefined, undo: () => {} };
21
+ if (typeof window === 'undefined') return none;
22
+ try {
23
+ // Where React looks the hook up; the same object as `window` in browsers and React Native.
24
+ const scope = globalThis as Record<string, unknown>;
25
+ let hook = scope[HOOK] as ReactHook | null | undefined;
26
+ if (hook === undefined) {
27
+ hook = minimalHook();
28
+ Object.defineProperty(scope, HOOK, { value: hook, configurable: true, writable: true, enumerable: false });
29
+ if (scope[HOOK] !== hook) return none;
30
+ }
31
+ // `isDisabled` opts out of DevTools; React then never calls the hook, so there is nothing to wrap.
32
+ if (hook === null || typeof hook !== 'object' || hook.isDisabled) return none;
33
+ const target = hook;
34
+ const original = target.onCommitFiberRoot;
35
+ let active = true;
36
+ const wrapper = function (this: unknown, ...args: unknown[]) {
37
+ try {
38
+ if (typeof original === 'function') return original.apply(this, args);
39
+ } finally {
40
+ if (active) {
41
+ try {
42
+ onCommit(args[1] as FiberRoot);
43
+ } catch {
44
+ // never throw into React's commit
45
+ }
46
+ }
47
+ }
48
+ };
49
+ target.onCommitFiberRoot = wrapper;
50
+ if (target.onCommitFiberRoot !== wrapper) return none;
51
+ return {
52
+ hook: target,
53
+ undo: () => {
54
+ active = false;
55
+ try {
56
+ if (target.onCommitFiberRoot === wrapper) target.onCommitFiberRoot = original;
57
+ } catch {
58
+ // a hook frozen since keeps the wrapper, which now only passes calls on
59
+ }
60
+ },
61
+ };
62
+ } catch {
63
+ return none;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * What React needs of the hook, plus what React Refresh and DevTools read when they load later: `renderers`
69
+ * filled by `inject`, and `getFiberRoots`. No `checkDCE`, so React still suggests installing DevTools.
70
+ */
71
+ function minimalHook(): ReactHook {
72
+ const renderers = new Map<number, unknown>();
73
+ const roots = new Map<number, Set<FiberRoot>>();
74
+ let nextId = 0;
75
+ const getFiberRoots = (id: number) => {
76
+ let mounted = roots.get(id);
77
+ if (!mounted) roots.set(id, (mounted = new Set()));
78
+ return mounted;
79
+ };
80
+ return {
81
+ renderers,
82
+ supportsFiber: true,
83
+ inject: (renderer: unknown) => {
84
+ const id = ++nextId;
85
+ renderers.set(id, renderer);
86
+ return id;
87
+ },
88
+ getFiberRoots,
89
+ // Keeps mounted roots the way React DevTools does, so a client started later finds them.
90
+ onCommitFiberRoot: (id: number, root: FiberRoot) => {
91
+ const state = root?.current?.memoizedState as { element?: unknown } | null | undefined;
92
+ if (state == null || state.element == null) getFiberRoots(id).delete(root);
93
+ else getFiberRoots(id).add(root);
94
+ },
95
+ onCommitFiberUnmount: () => {},
96
+ onPostCommitFiberRoot: () => {},
97
+ } as ReactHook;
98
+ }
@@ -70,7 +70,7 @@ const EXPLICIT = Symbol.for('capybara.reduxEnhancer');
70
70
  const MAX_SENT = 20;
71
71
  /** On the stack while `replaceReducer` runs: its `@@redux/REPLACE` goes around the wrapped dispatch. */
72
72
  const REPLACING = {};
73
- const LABELS = { redux: 'Redux store', zustand: 'zustand' } as const;
73
+ const LABELS = { redux: 'Redux store', zustand: 'zustand', xstate: 'XState actor', mobx: 'MobX store' } as const;
74
74
 
75
75
  /**
76
76
  * Stores being watched, by `getState`. Redux Toolkit and the enhancers further out pass that function on as it
@@ -503,7 +503,7 @@ function filtersOf(options: unknown): Filters | undefined {
503
503
  hidden(action, state) {
504
504
  const type = typeOf(action);
505
505
  try {
506
- return (allow !== undefined && !allow.test(type)) || (deny !== undefined && deny.test(type)) || (predicate !== undefined && !predicate(state, action));
506
+ return (allow !== undefined && !allow.test(type)) || deny?.test(type) || (predicate !== undefined && !predicate(state, action));
507
507
  } catch {
508
508
  return false;
509
509
  }
@@ -0,0 +1,94 @@
1
+ import type { StoreDriver } from './index.js';
2
+ import { defaultLabel } from './redux.js';
3
+ import { register, unregister } from './registry.js';
4
+
5
+ /** What Capybara reads of an XState actor, the one `createActor(machine)` returns. XState 5. */
6
+ export interface XStateActorLike {
7
+ getSnapshot(): unknown;
8
+ send(event: any): void;
9
+ subscribe(listener: (snapshot: any) => void): { unsubscribe(): void };
10
+ system?: { inspect?(observer: (event: any) => void): { unsubscribe(): void } | undefined };
11
+ logic?: { id?: unknown };
12
+ }
13
+
14
+ export interface WatchXStateOptions {
15
+ /** Shown in the State tab. Defaults to the machine's id, then "XState actor #n". */
16
+ name?: string;
17
+ }
18
+
19
+ const watched = new WeakMap<object, { driver: StoreDriver; id: string | undefined }>();
20
+
21
+ function isActorLike(value: unknown): value is XStateActorLike {
22
+ const actor = value as Partial<XStateActorLike> | null;
23
+ return (
24
+ actor !== null &&
25
+ typeof actor === 'object' &&
26
+ typeof actor.getSnapshot === 'function' &&
27
+ typeof actor.send === 'function' &&
28
+ typeof actor.subscribe === 'function'
29
+ );
30
+ }
31
+
32
+ /** What a snapshot says about the machine: the state it is in, its context, and how it ended. */
33
+ function stateOf(snapshot: unknown): unknown {
34
+ const s = snapshot as { value?: unknown; context?: unknown; status?: unknown; output?: unknown; error?: unknown } | null;
35
+ if (s === null || typeof s !== 'object') return s;
36
+ const state: Record<string, unknown> = { value: s.value, context: s.context, status: s.status };
37
+ if (s.output !== undefined) state.output = s.output;
38
+ if (s.error !== undefined) state.error = s.error;
39
+ return state;
40
+ }
41
+
42
+ /**
43
+ * Shows an XState actor in the State tab: each transition with the event that caused it, and its state value,
44
+ * context and status. Returns a function that undoes this call.
45
+ */
46
+ export function watchXState(actor: XStateActorLike, options: WatchXStateOptions = {}): () => void {
47
+ if (typeof window === 'undefined' || !isActorLike(actor)) return () => {};
48
+ try {
49
+ const known = watched.get(actor);
50
+ if (known) {
51
+ known.id = register(known.driver, actor) ?? known.id;
52
+ return () => {};
53
+ }
54
+ // The inspection API names the event behind each snapshot; subscribe() only gives the snapshot.
55
+ const inspect = typeof actor.system?.inspect === 'function';
56
+ const driver: StoreDriver = {
57
+ info: { library: 'xstate', label: labelOf(actor, options), via: 'subscribe', actions: inspect },
58
+ getState: () => stateOf(actor.getSnapshot()),
59
+ start(sink, id) {
60
+ if (inspect) {
61
+ const subscription = actor.system!.inspect!((event) => {
62
+ if (event?.type !== '@xstate.snapshot' || event.actorRef !== actor) return;
63
+ const cause = event.event as { type?: unknown } | undefined;
64
+ if (typeof cause?.type === 'string' && cause.type !== 'xstate.init') sink.record(id, stateOf(event.snapshot), cause, 'action');
65
+ else sink.record(id, stateOf(event.snapshot), undefined, 'set');
66
+ });
67
+ return () => subscription?.unsubscribe();
68
+ }
69
+ const subscription = actor.subscribe((snapshot) => sink.record(id, stateOf(snapshot), undefined, 'set'));
70
+ return () => subscription.unsubscribe();
71
+ },
72
+ };
73
+ const entry = { driver, id: undefined as string | undefined };
74
+ watched.set(actor, entry);
75
+ entry.id = register(driver, actor);
76
+ let undone = false;
77
+ return () => {
78
+ if (undone) return;
79
+ undone = true;
80
+ watched.delete(actor);
81
+ if (entry.id !== undefined) unregister(entry.id);
82
+ };
83
+ } catch {
84
+ return () => {};
85
+ }
86
+ }
87
+
88
+ function labelOf(actor: XStateActorLike, options: WatchXStateOptions): string {
89
+ if (typeof options.name === 'string' && options.name !== '') return options.name;
90
+ const id = actor.logic?.id;
91
+ // XState names machines without an id "(machine)".
92
+ if (typeof id === 'string' && id !== '' && id !== '(machine)') return id;
93
+ return defaultLabel('xstate', (stateOf(actor.getSnapshot()) as { context?: unknown } | null)?.context);
94
+ }
@@ -1,4 +1,12 @@
1
- import type { StorageAdapterInfo, StorageEntries, StorageEntry, StorageOp } from '@capybara-devtools/protocol';
1
+ import {
2
+ MAX_STORAGE_KEYS,
3
+ STORAGE_PREVIEW_LENGTH,
4
+ STORAGE_VALUE_LENGTH,
5
+ type StorageAdapterInfo,
6
+ type StorageEntries,
7
+ type StorageEntry,
8
+ type StorageOp,
9
+ } from '@capybara-devtools/protocol';
2
10
  import type { Plugin } from '../client.js';
3
11
  import { utf8Length } from '../utils.js';
4
12
 
@@ -21,10 +29,6 @@ export interface StorageAdapter {
21
29
  note?: string;
22
30
  }
23
31
 
24
- /** Keeps a listing of a huge storage from becoming one multi-megabyte message. */
25
- const MAX_ENTRIES = 1_000;
26
- const PREVIEW_CHARS = 2_000;
27
- const VALUE_CHARS = 1_000_000;
28
32
 
29
33
  export function storagePlugin(adapters: readonly StorageAdapter[]): Plugin {
30
34
  const find = (id: string): StorageAdapter => {
@@ -54,16 +58,17 @@ export function storagePlugin(adapters: readonly StorageAdapter[]): Plugin {
54
58
  entries: async ({ adapter }: { adapter: string }): Promise<StorageEntries> => {
55
59
  const a = find(adapter);
56
60
  const keys = [...(await a.keys())].sort();
57
- const shown = keys.slice(0, MAX_ENTRIES);
61
+ // Keeps a listing of a huge storage from becoming one multi-megabyte message.
62
+ const shown = keys.slice(0, MAX_STORAGE_KEYS);
58
63
  const pairs = a.getMany
59
64
  ? await a.getMany(shown)
60
65
  : await Promise.all(shown.map(async (key) => [key, await a.get(key)] as const));
61
- return { entries: pairs.map(([key, value]) => toEntry(key, value ?? null, PREVIEW_CHARS)), total: keys.length };
66
+ return { entries: pairs.map(([key, value]) => toEntry(key, value ?? null, STORAGE_PREVIEW_LENGTH)), total: keys.length };
62
67
  },
63
68
 
64
69
  get: async ({ adapter, key }: { adapter: string; key: string }): Promise<StorageEntry | null> => {
65
70
  const value = await find(adapter).get(key);
66
- return value === undefined || value === null ? null : toEntry(key, value, VALUE_CHARS);
71
+ return value === undefined || value === null ? null : toEntry(key, value, STORAGE_VALUE_LENGTH);
67
72
  },
68
73
 
69
74
  set: async ({ adapter, key, value }: { adapter: string; key: string; value: string }) => {
package/src/serialize.ts CHANGED
@@ -18,6 +18,7 @@ export function serialize(value: unknown, options?: SerializeOptions): Serialize
18
18
  maxDepth: 6,
19
19
  maxKeys: 100,
20
20
  maxItems: 100,
21
+ // MAX_STRING_LENGTH, written out since this function cannot import it.
21
22
  maxString: 10_000,
22
23
  maxNodes: 2_000,
23
24
  };
@@ -176,7 +177,7 @@ export function serialize(value: unknown, options?: SerializeOptions): Serialize
176
177
  }
177
178
  }
178
179
 
179
- function functionName(fn: Function): string {
180
+ function functionName(fn: { name: string }): string {
180
181
  try {
181
182
  return fn.name || 'anonymous';
182
183
  } catch {