@buoy-gg/zustand 7.0.16 → 7.0.18

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 (31) hide show
  1. package/lib/commonjs/index.js +1 -0
  2. package/lib/commonjs/zustand/components/ZustandModal.js +35 -4
  3. package/lib/commonjs/zustand/components/ZustandStateDetailContent.js +3 -2
  4. package/lib/commonjs/zustand/components/ZustandStoreBrowser.js +11 -3
  5. package/lib/commonjs/zustand/sync/zustandSyncAdapter.js +178 -6
  6. package/lib/commonjs/zustand/utils/snapshotProvider.js +279 -0
  7. package/lib/commonjs/zustand/utils/zustandStateStore.js +105 -14
  8. package/lib/module/index.js +3 -0
  9. package/lib/module/zustand/components/ZustandModal.js +36 -5
  10. package/lib/module/zustand/components/ZustandStateDetailContent.js +3 -2
  11. package/lib/module/zustand/components/ZustandStoreBrowser.js +11 -3
  12. package/lib/module/zustand/sync/zustandSyncAdapter.js +177 -5
  13. package/lib/module/zustand/utils/snapshotProvider.js +278 -0
  14. package/lib/module/zustand/utils/zustandStateStore.js +105 -14
  15. package/lib/typescript/index.d.ts +1 -0
  16. package/lib/typescript/index.d.ts.map +1 -1
  17. package/lib/typescript/zustand/components/ZustandModal.d.ts +1 -1
  18. package/lib/typescript/zustand/components/ZustandModal.d.ts.map +1 -1
  19. package/lib/typescript/zustand/components/ZustandStateDetailContent.d.ts +4 -1
  20. package/lib/typescript/zustand/components/ZustandStateDetailContent.d.ts.map +1 -1
  21. package/lib/typescript/zustand/components/ZustandStoreBrowser.d.ts +3 -1
  22. package/lib/typescript/zustand/components/ZustandStoreBrowser.d.ts.map +1 -1
  23. package/lib/typescript/zustand/sync/zustandSyncAdapter.d.ts +71 -3
  24. package/lib/typescript/zustand/sync/zustandSyncAdapter.d.ts.map +1 -1
  25. package/lib/typescript/zustand/types/index.d.ts +26 -0
  26. package/lib/typescript/zustand/types/index.d.ts.map +1 -1
  27. package/lib/typescript/zustand/utils/snapshotProvider.d.ts +2 -0
  28. package/lib/typescript/zustand/utils/snapshotProvider.d.ts.map +1 -0
  29. package/lib/typescript/zustand/utils/zustandStateStore.d.ts +18 -0
  30. package/lib/typescript/zustand/utils/zustandStateStore.d.ts.map +1 -1
  31. package/package.json +7 -4
@@ -276,6 +276,27 @@ class ZustandStateStore {
276
276
 
277
277
  // ---- Remote Mirror Mode ----
278
278
 
279
+ /**
280
+ * Replace the change log without touching the store registry. Used when a
281
+ * host keeps real registered stores (JUMP / RESET stay wired) but needs to
282
+ * reseed the event list — the docs live tour, or any mirror that already
283
+ * called `registerStore`. Does not fire `onClear`. Respects the enabled
284
+ * flag so the UI's pause button freezes the reseed.
285
+ */
286
+ replaceStateChanges(changes) {
287
+ if (!this.isEnabled) return;
288
+ this.stateChanges = changes.slice(0, this.maxChanges);
289
+ for (const store of this.stores.values()) {
290
+ store.stateChangeCount = 0;
291
+ }
292
+ for (const change of this.stateChanges) {
293
+ const store = this.stores.get(change.storeName);
294
+ if (store) store.stateChangeCount++;
295
+ }
296
+ this.notifyListeners();
297
+ this.notifyStoreListeners();
298
+ }
299
+
279
300
  /**
280
301
  * Permanently suppress local capture. Use when this store acts as a mirror
281
302
  * of a remote device's state changes (e.g. the desktop dashboard): data
@@ -330,22 +351,92 @@ class ZustandStateStore {
330
351
  */
331
352
  replaceFromSnapshot(changes, storeSnapshots) {
332
353
  if (!this.isEnabled) return;
333
- this.stateChanges = changes.slice(0, this.maxChanges);
334
- this.stores = new Map(storeSnapshots.map(snapshot => [snapshot.name, {
335
- name: snapshot.name,
336
- api: {
337
- getState: () => snapshot.currentState,
338
- setState: (partial, replace) => {
339
- this.remoteSetStateHandler?.(snapshot.name, partial, replace);
354
+
355
+ // Preserve trees a remote mirror already hydrated — wire-form snapshots
356
+ // always carry markers, and a later snapshot must not blank the detail pane.
357
+ const hydrated = new Map();
358
+ for (const existing of this.stateChanges) {
359
+ const prev = existing.prevState;
360
+ if (!prev || prev.__buoyStateOnDevice !== true) {
361
+ hydrated.set(existing.id, existing);
362
+ }
363
+ }
364
+ this.stateChanges = changes.slice(0, this.maxChanges).map(change => {
365
+ const kept = hydrated.get(change.id);
366
+ const incoming = change.prevState;
367
+ return kept && incoming?.__buoyStateOnDevice === true ? {
368
+ ...change,
369
+ prevState: kept.prevState,
370
+ nextState: kept.nextState,
371
+ partial: kept.partial
372
+ } : change;
373
+ });
374
+
375
+ // Preserve currentState a remote mirror already hydrated — oversized
376
+ // stores arrive as STATE_ON_DEVICE markers on every snapshot.
377
+ const hydratedStores = new Map();
378
+ for (const [name, store] of this.stores) {
379
+ try {
380
+ const state = store.api.getState();
381
+ const marker = state;
382
+ if (!marker || marker.__buoyStateOnDevice !== true) {
383
+ hydratedStores.set(name, state);
384
+ }
385
+ } catch {
386
+ // ignore
387
+ }
388
+ }
389
+ this.stores = new Map(storeSnapshots.map(snapshot => {
390
+ const incoming = snapshot.currentState;
391
+ const kept = hydratedStores.get(snapshot.name);
392
+ const currentState = kept !== undefined && incoming?.__buoyStateOnDevice === true ? kept : snapshot.currentState;
393
+ return [snapshot.name, {
394
+ name: snapshot.name,
395
+ api: {
396
+ getState: () => currentState,
397
+ setState: (partial, replace) => {
398
+ this.remoteSetStateHandler?.(snapshot.name, partial, replace);
399
+ },
400
+ subscribe: () => () => {}
340
401
  },
341
- subscribe: () => () => {}
342
- },
343
- stateChangeCount: snapshot.stateChangeCount,
344
- isPersisted: snapshot.isPersisted,
345
- persistName: snapshot.persistName,
346
- color: snapshot.color
347
- }]));
402
+ stateChangeCount: snapshot.stateChangeCount,
403
+ isPersisted: snapshot.isPersisted,
404
+ persistName: snapshot.persistName,
405
+ color: snapshot.color
406
+ }];
407
+ }));
408
+ this.notifyListeners();
409
+ this.notifyStoreListeners();
410
+ }
411
+
412
+ /**
413
+ * Hydrate one mirrored change with real trees fetched on demand from the
414
+ * device via the adapter's `getChangeDetail`. Remote-mirror (desktop) only.
415
+ */
416
+ hydrateChange(id, patch) {
417
+ const index = this.stateChanges.findIndex(c => c.id === id);
418
+ if (index === -1) return;
419
+ this.stateChanges = [...this.stateChanges.slice(0, index), {
420
+ ...this.stateChanges[index],
421
+ ...patch
422
+ }, ...this.stateChanges.slice(index + 1)];
348
423
  this.notifyListeners();
424
+ }
425
+
426
+ /**
427
+ * Hydrate one mirrored store's currentState fetched on demand from the
428
+ * device via the adapter's `getStoreState`. Remote-mirror (desktop) only.
429
+ */
430
+ hydrateStoreState(storeName, currentState) {
431
+ const store = this.stores.get(storeName);
432
+ if (!store) return;
433
+ this.stores.set(storeName, {
434
+ ...store,
435
+ api: {
436
+ ...store.api,
437
+ getState: () => currentState
438
+ }
439
+ });
349
440
  this.notifyStoreListeners();
350
441
  }
351
442
 
@@ -37,6 +37,9 @@
37
37
  * ```
38
38
  */
39
39
 
40
+ // Side-effect: registers the Time Machine snapshot provider
41
+ import "./zustand/utils/snapshotProvider";
42
+
40
43
  // =============================================================================
41
44
  // PRESET (Primary entry point for FloatingDevTools)
42
45
  // =============================================================================
@@ -8,7 +8,7 @@
8
8
  * - Events tab: Live state change monitoring with diffs
9
9
  */
10
10
 
11
- import { useState, useMemo, useRef, useCallback } from "react";
11
+ import { useState, useMemo, useRef, useCallback, useEffect } from "react";
12
12
  import { View, Text, StyleSheet, FlatList, TextInput, TouchableOpacity } from "react-native";
13
13
  import { JsModal, ModalHeader, TabSelector, macOSColors, buoyColors, Search, Filter, Power, X, Lock, Box, devToolsStorageKeys, ProUpgradeModal, PowerToggleButton, ToolbarCopyButton, ToolbarClearButton, truncatePayload, TickProvider } from "@buoy-gg/shared-ui";
14
14
  import { useIsPro } from "@buoy-gg/license";
@@ -44,11 +44,16 @@ export function ZustandModal({
44
44
  onMinimize,
45
45
  enableSharedModalDimensions = false,
46
46
  inline = false,
47
- storesLoading = false
47
+ storesLoading = false,
48
+ initialTab = "stores",
49
+ initialSelectedChangeId,
50
+ initialDetailView,
51
+ onChangeSelect,
52
+ onStoreExpand
48
53
  }) {
49
54
  const isPro = useIsPro();
50
55
  const [showProModal, setShowProModal] = useState(false);
51
- const [activeTab, setActiveTab] = useState("stores");
56
+ const [activeTab, setActiveTab] = useState(initialTab);
52
57
  const [selectedHistoryStore, setSelectedHistoryStore] = useState(null);
53
58
  const [showFilters, setShowFilters] = useState(false);
54
59
  const [ignoredPatterns, setIgnoredPatterns] = useState(new Set());
@@ -103,6 +108,30 @@ export function ZustandModal({
103
108
  }, [selectedChangeId, activeChanges]);
104
109
  const selectedChange = selectedChangeIndex !== null ? activeChanges[selectedChangeIndex] : null;
105
110
 
111
+ // Notify the host on selection (keyed by change id so re-renders with the
112
+ // same selection don't re-fire; remote mirrors fetch state trees here).
113
+ const lastNotifiedSelectionRef = useRef(null);
114
+ useEffect(() => {
115
+ if (!onChangeSelect) return;
116
+ const id = selectedChange?.id ?? null;
117
+ if (id === null || id === lastNotifiedSelectionRef.current) return;
118
+ lastNotifiedSelectionRef.current = id;
119
+ onChangeSelect(selectedChange);
120
+ }, [selectedChange, onChangeSelect]);
121
+
122
+ // Deep link into a change's detail (see initialSelectedChangeId). Applied
123
+ // at most once per id, so the list re-rendering — or the user pressing Back
124
+ // — never re-opens it.
125
+ const appliedInitialSelectionRef = useRef(null);
126
+ useEffect(() => {
127
+ if (!initialSelectedChangeId) return;
128
+ if (appliedInitialSelectionRef.current === initialSelectedChangeId) return;
129
+ const exists = activeChanges.some(c => c.id === initialSelectedChangeId);
130
+ if (!exists) return;
131
+ appliedInitialSelectionRef.current = initialSelectedChangeId;
132
+ setSelectedChangeId(initialSelectedChangeId);
133
+ }, [initialSelectedChangeId, activeChanges]);
134
+
106
135
  // Search state — shared across tabs
107
136
  const [searchText, setSearchText] = useState("");
108
137
  const [isSearchActive, setIsSearchActive] = useState(false);
@@ -365,7 +394,8 @@ export function ZustandModal({
365
394
  changes: activeChanges,
366
395
  selectedIndex: selectedChangeIndex,
367
396
  onIndexChange: handleIndexChange,
368
- disableInternalFooter: true
397
+ disableInternalFooter: true,
398
+ initialView: initialDetailView
369
399
  });
370
400
  }
371
401
 
@@ -403,7 +433,8 @@ export function ZustandModal({
403
433
  stores: displayedStores,
404
434
  searchQuery: searchText,
405
435
  onViewHistory: handleViewHistory,
406
- isLoading: storesLoading
436
+ isLoading: storesLoading,
437
+ onStoreExpand: onStoreExpand
407
438
  });
408
439
  }
409
440
 
@@ -62,9 +62,10 @@ export function ZustandStateDetailContent({
62
62
  changes,
63
63
  selectedIndex,
64
64
  onIndexChange,
65
- disableInternalFooter = false
65
+ disableInternalFooter = false,
66
+ initialView = "change"
66
67
  }) {
67
- const [activeView, setActiveView] = useState("change");
68
+ const [activeView, setActiveView] = useState(initialView);
68
69
  const [diffMode, setDiffMode] = useState("tree");
69
70
  const totalChanges = changes.length;
70
71
  const changeColor = getChangeColor(change);
@@ -22,6 +22,9 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
22
22
  function getKeysPreview(store) {
23
23
  try {
24
24
  const state = store.api.getState();
25
+ if (state && typeof state === "object" && state.__buoyStateOnDevice === true) {
26
+ return "on device";
27
+ }
25
28
  if (state && typeof state === "object") {
26
29
  const keys = Object.keys(state);
27
30
  const dataKeys = keys.filter(k => {
@@ -142,7 +145,8 @@ export function ZustandStoreBrowser({
142
145
  stores,
143
146
  searchQuery,
144
147
  onViewHistory,
145
- isLoading = false
148
+ isLoading = false,
149
+ onStoreExpand
146
150
  }) {
147
151
  const [expandedStore, setExpandedStore] = useState(null);
148
152
 
@@ -153,8 +157,12 @@ export function ZustandStoreBrowser({
153
157
  return stores.filter(s => s.name.toLowerCase().includes(search) || s.persistName && s.persistName.toLowerCase().includes(search));
154
158
  }, [stores, searchQuery]);
155
159
  const handleStorePress = useCallback(store => {
156
- setExpandedStore(prev => prev === store.name ? null : store.name);
157
- }, []);
160
+ setExpandedStore(prev => {
161
+ const next = prev === store.name ? null : store.name;
162
+ if (next) onStoreExpand?.(store.name);
163
+ return next;
164
+ });
165
+ }, [onStoreExpand]);
158
166
  if (filteredStores.length === 0 && !searchQuery) {
159
167
  return isLoading ? /*#__PURE__*/_jsx(LoadingBrowserState, {}) : /*#__PURE__*/_jsx(EmptyBrowserState, {});
160
168
  }
@@ -1,10 +1,82 @@
1
1
  "use strict";
2
2
 
3
3
  import { zustandStateStore } from "../utils/zustandStateStore";
4
+ /**
5
+ * Sentinel used in WIRE-FORM snapshots in place of raw prevState/nextState.
6
+ * Same hazard as redux: up to 200 changes × 2 full trees on every snapshot
7
+ * freeze/OOM-killed large apps. Dashboards fetch trees via `getChangeDetail`.
8
+ */
9
+ export const STATE_ON_DEVICE = Object.freeze({
10
+ __buoyStateOnDevice: true,
11
+ note: "State trees stay on the device — fetched on demand via getChangeDetail / getStoreState."
12
+ });
13
+
14
+ /** Wire-form sentinel for an oversized `partial` (replace can carry a whole tree). */
15
+ export const PAYLOAD_ON_DEVICE = Object.freeze({
16
+ __buoyPayloadOnDevice: true,
17
+ note: "Partial stays on the device — fetched on demand via getChangeDetail."
18
+ });
19
+ const MAX_CHANGE_DETAIL_BYTES = 8 * 1024 * 1024;
20
+ const MAX_WIRE_PAYLOAD_BYTES = 16 * 1024;
21
+ function jsonLongerThan(value, limit) {
22
+ let bytes = 0;
23
+ const stack = [value];
24
+ const seen = new Set();
25
+ while (stack.length > 0) {
26
+ if (bytes > limit) return true;
27
+ const v = stack.pop();
28
+ if (v === null || v === undefined) bytes += 4;else if (typeof v === "string") bytes += v.length + 2;else if (typeof v === "number") bytes += 8;else if (typeof v === "boolean") bytes += 5;else if (typeof v === "object") {
29
+ if (seen.has(v)) continue;
30
+ seen.add(v);
31
+ if (Array.isArray(v)) {
32
+ bytes += 2 + v.length;
33
+ for (let i = 0; i < v.length; i++) stack.push(v[i]);
34
+ } else {
35
+ bytes += 2;
36
+ for (const k in v) {
37
+ bytes += k.length + 4;
38
+ stack.push(v[k]);
39
+ }
40
+ }
41
+ } else bytes += 4;
42
+ }
43
+ return bytes > limit;
44
+ }
4
45
  /** Top-level keys of an object state, for the compact (no-values) view. */
5
46
  function topLevelKeys(state) {
6
47
  return state && typeof state === "object" && !Array.isArray(state) ? Object.keys(state) : undefined;
7
48
  }
49
+ function toWireChange(change) {
50
+ return {
51
+ ...change,
52
+ prevState: STATE_ON_DEVICE,
53
+ nextState: STATE_ON_DEVICE,
54
+ partial: toWirePartial(change.partial)
55
+ };
56
+ }
57
+ function toWirePartial(value) {
58
+ if (value === undefined) return value;
59
+ try {
60
+ JSON.stringify(value);
61
+ } catch {
62
+ return PAYLOAD_ON_DEVICE;
63
+ }
64
+ if (jsonLongerThan(value, MAX_WIRE_PAYLOAD_BYTES)) {
65
+ return PAYLOAD_ON_DEVICE;
66
+ }
67
+ return value;
68
+ }
69
+ function toWireState(value) {
70
+ try {
71
+ JSON.stringify(value);
72
+ } catch {
73
+ return STATE_ON_DEVICE;
74
+ }
75
+ if (jsonLongerThan(value, MAX_WIRE_PAYLOAD_BYTES)) {
76
+ return STATE_ON_DEVICE;
77
+ }
78
+ return value;
79
+ }
8
80
 
9
81
  /**
10
82
  * Sync adapter for the zustand tool, consumed by @buoy-gg/external-sync's
@@ -17,13 +89,21 @@ function topLevelKeys(state) {
17
89
  * change timeline and the store registry (with each store's current state)
18
90
  * so the dashboard can render the store browser.
19
91
  *
92
+ * v2: change-log prevState/nextState are replaced with on-device markers
93
+ * (see STATE_ON_DEVICE). Dashboards fetch trees via `getChangeDetail`.
94
+ * Oversized / unserializable `stores[].currentState` uses the same marker
95
+ * and is fetched via `getStoreState`.
96
+ *
20
97
  * The `setState` action powers remote time-travel/reset from the dashboard.
21
98
  */
22
99
  export const zustandSyncAdapter = {
23
- version: 1,
100
+ version: 2,
24
101
  getSnapshot: () => ({
25
- changes: zustandStateStore.getStateChanges(),
26
- stores: zustandStateStore.getStoreSnapshots()
102
+ changes: zustandStateStore.getStateChanges().map(toWireChange),
103
+ stores: zustandStateStore.getStoreSnapshots().map(store => ({
104
+ ...store,
105
+ currentState: toWireState(store.currentState)
106
+ }))
27
107
  }),
28
108
  subscribe: onChange => {
29
109
  const unsubscribeChanges = zustandStateStore.subscribe(onChange);
@@ -37,6 +117,86 @@ export const zustandSyncAdapter = {
37
117
  clearEvents: () => {
38
118
  zustandStateStore.clearStateChanges();
39
119
  },
120
+ /**
121
+ * On-demand detail: one change's real prevState/nextState/partial.
122
+ * The per-snapshot stream stays tree-free; this is the explicit,
123
+ * size-guarded channel for the detail pane.
124
+ */
125
+ getChangeDetail: params => {
126
+ const {
127
+ id
128
+ } = params ?? {};
129
+ if (!id) return {
130
+ found: false,
131
+ reason: "missing id"
132
+ };
133
+ const change = zustandStateStore.getStateChangeById(id);
134
+ if (!change) return {
135
+ found: false,
136
+ reason: "unknown id"
137
+ };
138
+ const cappedNote = {
139
+ __buoyTruncated: true,
140
+ note: `Exceeds the ${MAX_CHANGE_DETAIL_BYTES / (1024 * 1024)}MB detail limit — inspect it on-device.`
141
+ };
142
+ const cap = value => {
143
+ try {
144
+ JSON.stringify(value);
145
+ } catch {
146
+ return cappedNote;
147
+ }
148
+ return jsonLongerThan(value, MAX_CHANGE_DETAIL_BYTES) ? cappedNote : value;
149
+ };
150
+ return {
151
+ found: true,
152
+ id,
153
+ prevState: cap(change.prevState),
154
+ nextState: cap(change.nextState),
155
+ partial: cap(change.partial)
156
+ };
157
+ },
158
+ /**
159
+ * On-demand current state for one store. Wire-form snapshots replace
160
+ * oversized / unserializable `currentState` with STATE_ON_DEVICE.
161
+ */
162
+ getStoreState: params => {
163
+ const {
164
+ storeName
165
+ } = params ?? {};
166
+ if (!storeName) return {
167
+ found: false,
168
+ reason: "missing storeName"
169
+ };
170
+ const store = zustandStateStore.getStore(storeName);
171
+ if (!store) return {
172
+ found: false,
173
+ reason: "unknown storeName"
174
+ };
175
+ let currentState;
176
+ try {
177
+ currentState = store.api.getState();
178
+ } catch {
179
+ currentState = undefined;
180
+ }
181
+ const cappedNote = {
182
+ __buoyTruncated: true,
183
+ note: `Exceeds the ${MAX_CHANGE_DETAIL_BYTES / (1024 * 1024)}MB detail limit — inspect it on-device.`
184
+ };
185
+ try {
186
+ JSON.stringify(currentState);
187
+ } catch {
188
+ return {
189
+ found: true,
190
+ storeName,
191
+ currentState: STATE_ON_DEVICE
192
+ };
193
+ }
194
+ return {
195
+ found: true,
196
+ storeName,
197
+ currentState: jsonLongerThan(currentState, MAX_CHANGE_DETAIL_BYTES) ? cappedNote : currentState
198
+ };
199
+ },
40
200
  /**
41
201
  * Compact current-state reader for a remote driver (MCP/LLM): the registered
42
202
  * stores with light metadata; each store's full `currentState` object stays
@@ -73,8 +233,20 @@ export const zustandSyncAdapter = {
73
233
  storeName,
74
234
  state,
75
235
  replace
76
- } = params;
77
- zustandStateStore.getStore(storeName)?.api.setState(state, replace ?? true);
236
+ } = params ?? {};
237
+ if (!storeName) return {
238
+ ok: false,
239
+ error: "Missing storeName."
240
+ };
241
+ const store = zustandStateStore.getStore(storeName);
242
+ if (!store) return {
243
+ ok: false,
244
+ error: `No store named "${storeName}".`
245
+ };
246
+ store.api.setState(state, replace ?? true);
247
+ return {
248
+ ok: true
249
+ };
78
250
  }
79
251
  }
80
252
  };