@capybara-devtools/core 0.2.0 → 0.3.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 (52) hide show
  1. package/README.md +2 -2
  2. package/dist/client.d.ts +3 -2
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +9 -4
  5. package/dist/client.js.map +1 -1
  6. package/dist/index.d.ts +12 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +6 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/plugins/state/context.d.ts +102 -0
  11. package/dist/plugins/state/context.d.ts.map +1 -0
  12. package/dist/plugins/state/context.js +765 -0
  13. package/dist/plugins/state/context.js.map +1 -0
  14. package/dist/plugins/state/engine.d.ts +71 -0
  15. package/dist/plugins/state/engine.d.ts.map +1 -0
  16. package/dist/plugins/state/engine.js +710 -0
  17. package/dist/plugins/state/engine.js.map +1 -0
  18. package/dist/plugins/state/index.d.ts +59 -0
  19. package/dist/plugins/state/index.d.ts.map +1 -0
  20. package/dist/plugins/state/index.js +52 -0
  21. package/dist/plugins/state/index.js.map +1 -0
  22. package/dist/plugins/state/redux.d.ts +43 -0
  23. package/dist/plugins/state/redux.d.ts.map +1 -0
  24. package/dist/plugins/state/redux.js +580 -0
  25. package/dist/plugins/state/redux.js.map +1 -0
  26. package/dist/plugins/state/registry.d.ts +22 -0
  27. package/dist/plugins/state/registry.d.ts.map +1 -0
  28. package/dist/plugins/state/registry.js +109 -0
  29. package/dist/plugins/state/registry.js.map +1 -0
  30. package/dist/plugins/state/swr.d.ts +49 -0
  31. package/dist/plugins/state/swr.d.ts.map +1 -0
  32. package/dist/plugins/state/swr.js +359 -0
  33. package/dist/plugins/state/swr.js.map +1 -0
  34. package/dist/plugins/state/tanstack.d.ts +31 -0
  35. package/dist/plugins/state/tanstack.d.ts.map +1 -0
  36. package/dist/plugins/state/tanstack.js +461 -0
  37. package/dist/plugins/state/tanstack.js.map +1 -0
  38. package/dist/plugins/state/zustand.d.ts +21 -0
  39. package/dist/plugins/state/zustand.d.ts.map +1 -0
  40. package/dist/plugins/state/zustand.js +70 -0
  41. package/dist/plugins/state/zustand.js.map +1 -0
  42. package/package.json +11 -2
  43. package/src/client.ts +12 -6
  44. package/src/index.ts +19 -0
  45. package/src/plugins/state/context.ts +831 -0
  46. package/src/plugins/state/engine.ts +739 -0
  47. package/src/plugins/state/index.ts +112 -0
  48. package/src/plugins/state/redux.ts +609 -0
  49. package/src/plugins/state/registry.ts +126 -0
  50. package/src/plugins/state/swr.ts +375 -0
  51. package/src/plugins/state/tanstack.ts +488 -0
  52. package/src/plugins/state/zustand.ts +82 -0
@@ -0,0 +1,488 @@
1
+ import type { StateEntrySummary } from '@capybara-devtools/protocol';
2
+ import type { StoreDriver } from './index.js';
3
+ import { register, unregister } from './registry.js';
4
+
5
+ // `summarizeQuery`, `summarizeMutation` and `createQueryClientDriver` are self-contained, like the engine: the
6
+ // Metro bridge runs them from their source inside apps without the SDK, so they use nothing from module scope.
7
+ // TanStack Query v5 is the reference. v4 has the same cache events; where it differs, the code says so.
8
+
9
+ export interface WatchQueryClientOptions {
10
+ /** The client's label in the State tab; give each its own when the app has several. Default "QueryClient". */
11
+ name?: string;
12
+ }
13
+
14
+ /** What `watchQueryClient` checks for: a TanStack Query `QueryClient`, v5 or v4. */
15
+ export interface QueryClientLike {
16
+ getQueryCache(): unknown;
17
+ getMutationCache(): unknown;
18
+ }
19
+
20
+ export type SummarizeQueryFn = typeof summarizeQuery;
21
+ export type SummarizeMutationFn = typeof summarizeMutation;
22
+
23
+ interface QueryLike {
24
+ queryKey?: unknown;
25
+ queryHash: string;
26
+ /** v5 only; v4 infinite queries are told apart by their data. */
27
+ queryType?: unknown;
28
+ options?: { queryFn?: unknown; queryKeyHashFn?: unknown };
29
+ state: {
30
+ data?: unknown;
31
+ dataUpdatedAt?: number;
32
+ error?: unknown;
33
+ errorUpdatedAt?: number;
34
+ isInvalidated?: boolean;
35
+ /** v4 says 'loading' where v5 says 'pending'. */
36
+ status?: string;
37
+ fetchStatus?: string;
38
+ };
39
+ observers?: Array<{ options?: { queryFn?: unknown } } | undefined>;
40
+ getObserversCount?(): number;
41
+ isActive?(): boolean;
42
+ isDisabled?(): boolean;
43
+ isStale?(): boolean;
44
+ fetch?(): unknown;
45
+ }
46
+
47
+ interface MutationLike {
48
+ mutationId: number;
49
+ options?: { mutationKey?: unknown };
50
+ state: {
51
+ /** v4 says 'loading' where v5 says 'pending'. */
52
+ status?: string;
53
+ isPaused?: boolean;
54
+ /** v5 only. */
55
+ submittedAt?: number;
56
+ variables?: unknown;
57
+ data?: unknown;
58
+ context?: unknown;
59
+ error?: unknown;
60
+ };
61
+ }
62
+
63
+ type CacheEvent =
64
+ | { type?: unknown; query?: Partial<QueryLike> | null; mutation?: Partial<MutationLike> | null }
65
+ | null
66
+ | undefined;
67
+
68
+ interface CacheLike<T> {
69
+ subscribe(listener: (event: CacheEvent) => void): () => void;
70
+ getAll(): Array<T | undefined>;
71
+ get?(queryHash: string): T | undefined;
72
+ }
73
+
74
+ type ClientMethod = 'invalidateQueries' | 'resetQueries' | 'cancelQueries' | 'removeQueries';
75
+ type ClientFilter = { predicate(query: unknown): boolean };
76
+ type ClientLike = QueryClientLike & Partial<Record<ClientMethod, (filters: ClientFilter) => unknown>>;
77
+
78
+ /**
79
+ * Shows the client's queries and mutations in the State tab, where a query can be refetched, invalidated,
80
+ * reset, cancelled or removed. Returns a function that stops watching. Does nothing where there is no `window`.
81
+ */
82
+ export function watchQueryClient(client: QueryClientLike, options?: WatchQueryClientOptions): () => void {
83
+ if (typeof window === 'undefined') return () => {};
84
+ let id: string | undefined;
85
+ try {
86
+ const name = options?.name;
87
+ const label = typeof name === 'string' && name !== '' ? name : 'QueryClient';
88
+ const driver = createQueryClientDriver(client, label, summarizeQuery, summarizeMutation);
89
+ // A client registered before gets its id back, so calling this again adds nothing.
90
+ if (driver) id = register(driver, client);
91
+ } catch {
92
+ // never throw into the app
93
+ }
94
+ return () => {
95
+ const current = id;
96
+ id = undefined;
97
+ if (current === undefined) return;
98
+ try {
99
+ unregister(current);
100
+ } catch {
101
+ // never throw into the app
102
+ }
103
+ };
104
+ }
105
+
106
+ /**
107
+ * Reads a QueryClient for the state engine: queries keyed by `queryHash`, mutations by `m:<mutationId>`.
108
+ * Undefined for anything that is not a QueryClient.
109
+ */
110
+ export function createQueryClientDriver(
111
+ client: unknown,
112
+ label: string,
113
+ summarizeQuery: SummarizeQueryFn,
114
+ summarizeMutation: SummarizeMutationFn,
115
+ ): StoreDriver | undefined {
116
+ // The engine and the UI hold 1200 entries per store.
117
+ const MAX_QUERIES = 1_000;
118
+ const MAX_MUTATIONS = 200;
119
+ const REFETCH_TIMEOUT = 10_000;
120
+
121
+ const isCache = (value: unknown): boolean =>
122
+ value !== null &&
123
+ typeof value === 'object' &&
124
+ typeof (value as CacheLike<unknown>).subscribe === 'function' &&
125
+ typeof (value as CacheLike<unknown>).getAll === 'function';
126
+ const c = client as ClientLike | null;
127
+ if (c === null || typeof c !== 'object') return undefined;
128
+ if (typeof c.getQueryCache !== 'function' || typeof c.getMutationCache !== 'function') return undefined;
129
+ let queries: CacheLike<QueryLike>;
130
+ let mutations: CacheLike<MutationLike>;
131
+ try {
132
+ queries = c.getQueryCache() as CacheLike<QueryLike>;
133
+ mutations = c.getMutationCache() as CacheLike<MutationLike>;
134
+ } catch {
135
+ return undefined;
136
+ }
137
+ if (!isCache(queries) || typeof queries.get !== 'function' || !isCache(mutations)) return undefined;
138
+
139
+ const previews = new WeakMap<object, string>();
140
+ const message = (error: unknown): string => {
141
+ try {
142
+ return error instanceof Error ? error.message : String(error);
143
+ } catch {
144
+ return 'unknown error';
145
+ }
146
+ };
147
+ const queryOf = (key: string): QueryLike | undefined => {
148
+ const query = queries.get!(key);
149
+ return query !== null && typeof query === 'object' ? query : undefined;
150
+ };
151
+ const mutationOf = (key: string): MutationLike | undefined => {
152
+ if (!key.startsWith('m:')) return undefined;
153
+ const id = Number(key.slice(2));
154
+ for (const mutation of mutations.getAll()) if (mutation?.mutationId === id) return mutation;
155
+ return undefined;
156
+ };
157
+ const rank = (query: QueryLike): number => {
158
+ try {
159
+ const state = query.state;
160
+ if (state.fetchStatus === 'fetching' || state.fetchStatus === 'paused') return Infinity;
161
+ return Math.max(Number(state.dataUpdatedAt) || 0, Number(state.errorUpdatedAt) || 0);
162
+ } catch {
163
+ return 0;
164
+ }
165
+ };
166
+ const reply = (result: { done: boolean; note?: string }) => Promise.resolve(result);
167
+
168
+ const refetch = (query: QueryLike): Promise<{ done: boolean; note?: string }> => {
169
+ // Where `Query.fetch` takes its queryFn from, so a query it would reject is not put into an error state.
170
+ const own = query.options?.queryFn;
171
+ const queryFn = own || query.observers?.find((observer) => observer?.options?.queryFn)?.options?.queryFn;
172
+ if (typeof queryFn !== 'function' || typeof query.fetch !== 'function') {
173
+ return reply({ done: false, note: 'This query has no queryFn to refetch with' });
174
+ }
175
+ return new Promise((resolve) => {
176
+ const timer = setTimeout(
177
+ () => resolve({ done: false, note: `Still fetching after ${REFETCH_TIMEOUT / 1_000} s` }),
178
+ REFETCH_TIMEOUT,
179
+ );
180
+ const settle = (result: { done: boolean; note?: string }) => {
181
+ clearTimeout(timer);
182
+ resolve(result);
183
+ };
184
+ new Promise((fetched) => fetched(query.fetch!())).then(
185
+ () => settle({ done: true }),
186
+ (error: unknown) => settle({ done: false, note: `Refetch failed: ${message(error)}` }),
187
+ );
188
+ });
189
+ };
190
+ const viaClient = (query: QueryLike, method: ClientMethod): Promise<{ done: boolean; note?: string }> => {
191
+ const call = c[method];
192
+ if (typeof call !== 'function') return reply({ done: false, note: `This QueryClient has no ${method}` });
193
+ try {
194
+ // The filter is the query itself: a key rebuilt from JSON can hash differently.
195
+ const pending = call.call(c, { predicate: (other: unknown) => other === query });
196
+ // Settles once active queries have refetched; the change itself is already made.
197
+ Promise.resolve(pending).catch(() => {});
198
+ } catch (error) {
199
+ return reply({ done: false, note: message(error) });
200
+ }
201
+ return reply({ done: true });
202
+ };
203
+
204
+ return {
205
+ info: {
206
+ library: 'tanstack-query',
207
+ label,
208
+ via: 'client',
209
+ actions: false,
210
+ ops: ['refetch', 'invalidate', 'reset', 'cancel', 'remove'],
211
+ },
212
+ keys() {
213
+ const ranked: Array<{ key: string; rank: number; at: number }> = [];
214
+ queries.getAll().forEach((query, at) => {
215
+ if (typeof query?.queryHash === 'string') ranked.push({ key: query.queryHash, rank: rank(query), at });
216
+ });
217
+ // Fetching first, then the latest data or error; ties newest first. Two fetching give NaN, which falls through.
218
+ ranked.sort((a, b) => b.rank - a.rank || b.at - a.at);
219
+ const keys = ranked.slice(0, MAX_QUERIES).map((entry) => entry.key);
220
+ const ids: number[] = [];
221
+ for (const mutation of mutations.getAll()) {
222
+ if (typeof mutation?.mutationId === 'number') ids.push(mutation.mutationId);
223
+ }
224
+ ids.sort((a, b) => b - a);
225
+ for (const id of ids.slice(0, MAX_MUTATIONS)) keys.push(`m:${id}`);
226
+ return keys;
227
+ },
228
+ summarize(key) {
229
+ const query = queryOf(key);
230
+ if (query) return summarizeQuery(query, previews);
231
+ const mutation = mutationOf(key);
232
+ return mutation ? summarizeMutation(mutation) : undefined;
233
+ },
234
+ data(key) {
235
+ const query = queryOf(key);
236
+ if (query) return query.state?.data;
237
+ const state = mutationOf(key)?.state;
238
+ if (!state) return undefined;
239
+ const out: Record<string, unknown> = { variables: state.variables, data: state.data };
240
+ if (state.context !== undefined) out.context = state.context;
241
+ if (state.error !== null && state.error !== undefined) out.error = state.error;
242
+ return out;
243
+ },
244
+ act(key, op) {
245
+ const query = queryOf(key);
246
+ if (!query) {
247
+ const note = mutationOf(key)
248
+ ? 'Mutations only report what happened; there is nothing to run'
249
+ : 'This query is no longer in the cache';
250
+ return reply({ done: false, note });
251
+ }
252
+ switch (op) {
253
+ case 'refetch':
254
+ return refetch(query);
255
+ case 'invalidate':
256
+ return viaClient(query, 'invalidateQueries');
257
+ case 'reset':
258
+ return viaClient(query, 'resetQueries');
259
+ case 'cancel':
260
+ if (query.state?.fetchStatus === 'idle') return reply({ done: false, note: 'This query is not fetching' });
261
+ return viaClient(query, 'cancelQueries');
262
+ case 'remove':
263
+ return viaClient(query, 'removeQueries');
264
+ default:
265
+ return reply({ done: false, note: `Queries have no "${String(op)}" command` });
266
+ }
267
+ },
268
+ start(sink, id) {
269
+ // Events can come mid-render (hydration), so listeners only mark keys; the engine reads them later.
270
+ const low = (type: unknown) => type === 'observerResultsUpdated' || type === 'observerOptionsUpdated';
271
+ const stopQueries = queries.subscribe((event) => {
272
+ try {
273
+ const hash = event?.query?.queryHash;
274
+ if (typeof hash !== 'string') return;
275
+ if (event!.type === 'removed') sink.removed(id, hash);
276
+ else sink.dirty(id, hash, low(event!.type));
277
+ } catch {
278
+ // never throw into the app's cache
279
+ }
280
+ });
281
+ let stopMutations: () => void;
282
+ try {
283
+ stopMutations = mutations.subscribe((event) => {
284
+ try {
285
+ // `observerOptionsUpdated` comes without a mutation while an observer has none yet.
286
+ const mutationId = event?.mutation?.mutationId;
287
+ if (typeof mutationId !== 'number') return;
288
+ if (event!.type === 'removed') sink.removed(id, `m:${mutationId}`);
289
+ else sink.dirty(id, `m:${mutationId}`, low(event!.type));
290
+ } catch {
291
+ // never throw into the app's cache
292
+ }
293
+ });
294
+ } catch (error) {
295
+ stopQueries();
296
+ throw error;
297
+ }
298
+ return () => {
299
+ stopQueries();
300
+ stopMutations();
301
+ };
302
+ },
303
+ };
304
+ }
305
+
306
+ /**
307
+ * A query's summary, without its data. `previews` remembers the preview of each data object: TanStack keeps the
308
+ * same object until the data changes, while observer updates summarize the query again and again.
309
+ */
310
+ export function summarizeQuery(query: unknown, previews?: WeakMap<object, string>): StateEntrySummary | undefined {
311
+ const cut = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}…` : text);
312
+ const attempt = <T>(read: () => T): T | undefined => {
313
+ try {
314
+ return read();
315
+ } catch {
316
+ return undefined;
317
+ }
318
+ };
319
+ // The same as in summarizeMutation: each is run on its own.
320
+ const errorText = (error: unknown): string => {
321
+ let text = 'Error';
322
+ try {
323
+ const e = error as { name?: unknown; message?: unknown } | null;
324
+ if (typeof error === 'string') {
325
+ text = error;
326
+ } else if (e !== null && typeof e === 'object' && typeof e.message === 'string') {
327
+ const kind = typeof e.name === 'string' && e.name ? e.name : 'Error';
328
+ text = e.message ? `${kind}: ${e.message}` : kind;
329
+ } else if (e !== null && typeof e === 'object') {
330
+ // Not its fields, which may hold anything; a thrown response's status is what tells the most.
331
+ const kind = Object.prototype.toString.call(e).slice(8, -1);
332
+ const status = (e as { status?: unknown }).status;
333
+ text = typeof status === 'number' ? `${kind} ${status}` : kind;
334
+ } else {
335
+ text = String(error);
336
+ }
337
+ } catch {
338
+ // unreadable; keep the default
339
+ }
340
+ return cut(text, 300);
341
+ };
342
+ const typeName = (value: object): string => {
343
+ try {
344
+ const proto = Object.getPrototypeOf(value);
345
+ const name: unknown = proto === null ? 'Object' : proto.constructor?.name;
346
+ return typeof name === 'string' && name !== '' ? name : 'Object';
347
+ } catch {
348
+ return 'Object';
349
+ }
350
+ };
351
+ // The shape only, never a value: MCP shows previews as they are, and its redactor only sees key names.
352
+ const describe = (data: unknown): string => {
353
+ if (data === null) return 'null';
354
+ if (typeof data === 'string') return `string(${data.length})`;
355
+ if (typeof data !== 'object') return typeof data;
356
+ if (Array.isArray(data)) return `Array(${data.length})`;
357
+ if (data instanceof Map) return `Map(${data.size})`;
358
+ if (data instanceof Set) return `Set(${data.size})`;
359
+ if (data instanceof Date) return 'Date';
360
+ const name = typeName(data);
361
+ if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) return name;
362
+ const keys: string[] = [];
363
+ let length = 0;
364
+ let more = false;
365
+ try {
366
+ for (const key in data) {
367
+ if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
368
+ const shown = cut(key, 20);
369
+ if (keys.length > 0 && length + shown.length > 60) {
370
+ more = true;
371
+ break;
372
+ }
373
+ keys.push(shown);
374
+ length += shown.length + 2;
375
+ }
376
+ } catch {
377
+ // a proxy that will not list its keys
378
+ }
379
+ const body = `{${keys.join(', ')}${more ? ', …' : ''}}`;
380
+ return name === 'Object' ? body : `${name} ${body}`;
381
+ };
382
+
383
+ const q = query as QueryLike | null;
384
+ if (q === null || typeof q !== 'object' || typeof q.queryHash !== 'string') return undefined;
385
+ const state = q.state;
386
+ if (state === null || typeof state !== 'object') return undefined;
387
+ const data = state.data;
388
+ // The default hash is the key as JSON with sorted object keys, as TanStack's devtools show it; a custom one may be
389
+ // opaque, so then the key is shown.
390
+ const bigints = (_: string, value: unknown) => (typeof value === 'bigint' ? `${value}n` : value);
391
+ const custom = typeof q.options?.queryKeyHashFn === 'function';
392
+ const json = custom ? attempt(() => JSON.stringify(q.queryKey, bigints)) : undefined;
393
+ const pages =
394
+ data !== null &&
395
+ typeof data === 'object' &&
396
+ Array.isArray((data as { pages?: unknown }).pages) &&
397
+ Array.isArray((data as { pageParams?: unknown }).pageParams);
398
+ const status = state.status === 'loading' ? 'pending' : state.status;
399
+ const count = attempt(() => (q.getObserversCount ? q.getObserversCount() : q.observers?.length));
400
+ const observers = typeof count === 'number' && count > 0 ? count : 0;
401
+ const active = attempt(() => q.isActive?.());
402
+
403
+ const summary: StateEntrySummary = {
404
+ key: q.queryHash,
405
+ label: cut(json ?? q.queryHash, 1_024),
406
+ kind: q.queryType === 'infinite' || pages ? 'infinite' : 'query',
407
+ status: status === 'success' || status === 'error' ? status : 'pending',
408
+ fetching: state.fetchStatus === 'fetching',
409
+ };
410
+ if (state.fetchStatus === 'paused') summary.paused = true;
411
+ // Without observers there is no staleTime to judge by: TanStack's devtools call such a query inactive, nothing more.
412
+ if (observers > 0) {
413
+ const stale = attempt(() => q.isStale?.());
414
+ if (typeof stale === 'boolean') summary.stale = stale;
415
+ }
416
+ if (state.isInvalidated === true) summary.invalidated = true;
417
+ summary.active = typeof active === 'boolean' ? active : observers > 0;
418
+ if (attempt(() => q.isDisabled?.()) === true) summary.disabled = true;
419
+ summary.observers = observers;
420
+ // A query that only ever failed has no data time, so the error's time stands in.
421
+ const updatedAt = Math.max(Number(state.dataUpdatedAt) || 0, Number(state.errorUpdatedAt) || 0);
422
+ if (updatedAt > 0) summary.updatedAt = updatedAt;
423
+ if (state.error !== null && state.error !== undefined) summary.error = errorText(state.error);
424
+ if (data !== undefined) {
425
+ const keyed = data !== null && typeof data === 'object' ? data : undefined;
426
+ let preview = keyed ? previews?.get(keyed) : undefined;
427
+ if (preview === undefined) {
428
+ preview = describe(data);
429
+ if (keyed) previews?.set(keyed, preview);
430
+ }
431
+ summary.preview = preview;
432
+ }
433
+ return summary;
434
+ }
435
+
436
+ /** A mutation without its variables or data. */
437
+ export function summarizeMutation(mutation: unknown): StateEntrySummary | undefined {
438
+ // The same as in summarizeQuery: each is run on its own.
439
+ const errorText = (error: unknown): string => {
440
+ let text = 'Error';
441
+ try {
442
+ const e = error as { name?: unknown; message?: unknown } | null;
443
+ if (typeof error === 'string') {
444
+ text = error;
445
+ } else if (e !== null && typeof e === 'object' && typeof e.message === 'string') {
446
+ const kind = typeof e.name === 'string' && e.name ? e.name : 'Error';
447
+ text = e.message ? `${kind}: ${e.message}` : kind;
448
+ } else if (e !== null && typeof e === 'object') {
449
+ // Not its fields, which may hold anything; a thrown response's status is what tells the most.
450
+ const kind = Object.prototype.toString.call(e).slice(8, -1);
451
+ const status = (e as { status?: unknown }).status;
452
+ text = typeof status === 'number' ? `${kind} ${status}` : kind;
453
+ } else {
454
+ text = String(error);
455
+ }
456
+ } catch {
457
+ // unreadable; keep the default
458
+ }
459
+ return text.length > 300 ? `${text.slice(0, 300)}…` : text;
460
+ };
461
+
462
+ const m = mutation as MutationLike | null;
463
+ if (m === null || typeof m !== 'object' || typeof m.mutationId !== 'number') return undefined;
464
+ const state = m.state;
465
+ if (state === null || typeof state !== 'object') return undefined;
466
+ let name = 'mutation';
467
+ try {
468
+ const key = m.options?.mutationKey;
469
+ const bigints = (_: string, value: unknown) => (typeof value === 'bigint' ? `${value}n` : value);
470
+ const json = key === undefined ? undefined : JSON.stringify(key, bigints);
471
+ if (json) name = json.length > 1_024 ? `${json.slice(0, 1_024)}…` : json;
472
+ } catch {
473
+ // the id still tells it apart
474
+ }
475
+ const status = state.status === 'loading' ? 'pending' : state.status;
476
+ const summary: StateEntrySummary = {
477
+ key: `m:${m.mutationId}`,
478
+ // Every call of a mutation is its own entry, so the id tells calls with the same key apart.
479
+ label: `${name} #${m.mutationId}`,
480
+ kind: 'mutation',
481
+ status: status === 'pending' || status === 'success' || status === 'error' ? status : 'idle',
482
+ fetching: status === 'pending' && state.isPaused !== true,
483
+ };
484
+ if (state.isPaused === true) summary.paused = true;
485
+ if (typeof state.submittedAt === 'number' && state.submittedAt > 0) summary.updatedAt = state.submittedAt;
486
+ if (state.error !== null && state.error !== undefined) summary.error = errorText(state.error);
487
+ return summary;
488
+ }
@@ -0,0 +1,82 @@
1
+ import type { StoreDriver } from './index.js';
2
+ import { defaultLabel, reduxShimActive } from './redux.js';
3
+ import { register, unregister } from './registry.js';
4
+
5
+ /** What Capybara reads of a zustand store: one from `createStore`, or the hook `create` returns. Zustand 4.5 and later. */
6
+ export interface ZustandStoreLike {
7
+ getState(): unknown;
8
+ setState(...args: any[]): unknown;
9
+ subscribe(listener: (state: any, previousState: any) => void): () => void;
10
+ }
11
+
12
+ export interface WatchZustandOptions {
13
+ /** Shown in the State tab. Defaults to the name given to the persist middleware, then "zustand #n". */
14
+ name?: string;
15
+ /** Watch a devtools() store although the Redux DevTools shim shows it already, with action names. */
16
+ force?: boolean;
17
+ }
18
+
19
+ /** Stores watched, by `getState`, which the hook from `create` shares with its store. */
20
+ const watched = new WeakMap<object, { driver: StoreDriver; id: string | undefined }>();
21
+
22
+ /** Redux stores have getState and subscribe too, but replaceReducer instead of setState. */
23
+ export function isZustandLike(value: unknown): value is ZustandStoreLike {
24
+ const store = value as (Partial<ZustandStoreLike> & { replaceReducer?: unknown }) | null;
25
+ return (
26
+ store !== null &&
27
+ (typeof store === 'object' || typeof store === 'function') &&
28
+ typeof store.getState === 'function' &&
29
+ typeof store.setState === 'function' &&
30
+ typeof store.subscribe === 'function' &&
31
+ typeof store.replaceReducer !== 'function'
32
+ );
33
+ }
34
+
35
+ /**
36
+ * Shows a zustand store in the State tab, each change as a diff without an action name. Stores made with the
37
+ * devtools() middleware after `init()` show up on their own, with action names, so they are skipped here
38
+ * unless `force` is set. Returns a function that undoes this call.
39
+ */
40
+ export function watchZustand(store: ZustandStoreLike, options: WatchZustandOptions = {}): () => void {
41
+ if (typeof window === 'undefined' || !isZustandLike(store)) return () => {};
42
+ try {
43
+ // devtools() sets `devtools.cleanup` once connected. With the shim installed, that is taken to mean through it.
44
+ const devtools = (store as { devtools?: { cleanup?: unknown } }).devtools;
45
+ if (!options.force && typeof devtools?.cleanup === 'function' && reduxShimActive()) return () => {};
46
+ const key = store.getState;
47
+ const known = watched.get(key);
48
+ if (known) {
49
+ // The registry may have dropped it since, e.g. for a newer instance under the same label.
50
+ known.id = register(known.driver, key) ?? known.id;
51
+ return () => {};
52
+ }
53
+ const driver: StoreDriver = {
54
+ info: { library: 'zustand', label: labelOf(store, options), via: 'subscribe', actions: false },
55
+ getState: () => store.getState(),
56
+ start: (sink, id) => store.subscribe((state) => sink.record(id, state, undefined, 'set')),
57
+ };
58
+ const entry = { driver, id: undefined as string | undefined };
59
+ watched.set(key, entry);
60
+ entry.id = register(driver, key);
61
+ let undone = false;
62
+ return () => {
63
+ if (undone) return;
64
+ undone = true;
65
+ watched.delete(key);
66
+ if (entry.id !== undefined) unregister(entry.id);
67
+ };
68
+ } catch {
69
+ return () => {};
70
+ }
71
+ }
72
+
73
+ function labelOf(store: ZustandStoreLike, options: WatchZustandOptions): string {
74
+ if (typeof options.name === 'string' && options.name !== '') return options.name;
75
+ try {
76
+ const persisted = (store as { persist?: { getOptions?(): { name?: unknown } } }).persist?.getOptions?.().name;
77
+ if (typeof persisted === 'string' && persisted !== '') return persisted;
78
+ } catch {
79
+ // numbered instead
80
+ }
81
+ return defaultLabel('zustand', store.getState());
82
+ }