@buoy-gg/zustand 7.0.41 → 7.0.43
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 +11 -76
- package/lib/commonjs/index.js +1 -105
- package/lib/commonjs/preset.js +1 -102
- package/lib/commonjs/zustand/components/ZustandActionButton.js +1 -118
- package/lib/commonjs/zustand/components/ZustandDetailViewToggle.js +1 -48
- package/lib/commonjs/zustand/components/ZustandEventFilterView.js +1 -43
- package/lib/commonjs/zustand/components/ZustandIcon.js +1 -18
- package/lib/commonjs/zustand/components/ZustandModal.js +1 -772
- package/lib/commonjs/zustand/components/ZustandStateChangeItem.js +1 -117
- package/lib/commonjs/zustand/components/ZustandStateDetailContent.js +1 -372
- package/lib/commonjs/zustand/components/ZustandStateInfoView.js +1 -488
- package/lib/commonjs/zustand/components/ZustandStoreBrowser.js +1 -204
- package/lib/commonjs/zustand/components/ZustandStoreDetailContent.js +1 -471
- package/lib/commonjs/zustand/hooks/useZustandStateChanges.js +1 -74
- package/lib/commonjs/zustand/sync/zustandSyncAdapter.js +1 -418
- package/lib/commonjs/zustand/types/index.js +1 -1
- package/lib/commonjs/zustand/utils/buoyZustandMiddleware.js +1 -284
- package/lib/commonjs/zustand/utils/editableState.js +1 -146
- package/lib/commonjs/zustand/utils/snapshotProvider.js +1 -209
- package/lib/commonjs/zustand/utils/testIDs.js +1 -82
- package/lib/commonjs/zustand/utils/zustandStateStore.js +1 -379
- package/lib/module/index.js +1 -90
- package/lib/module/preset.js +1 -98
- package/lib/module/zustand/components/ZustandActionButton.js +1 -114
- package/lib/module/zustand/components/ZustandDetailViewToggle.js +1 -43
- package/lib/module/zustand/components/ZustandEventFilterView.js +1 -39
- package/lib/module/zustand/components/ZustandIcon.js +1 -11
- package/lib/module/zustand/components/ZustandModal.js +1 -767
- package/lib/module/zustand/components/ZustandStateChangeItem.js +1 -113
- package/lib/module/zustand/components/ZustandStateDetailContent.js +1 -368
- package/lib/module/zustand/components/ZustandStateInfoView.js +1 -483
- package/lib/module/zustand/components/ZustandStoreBrowser.js +1 -200
- package/lib/module/zustand/components/ZustandStoreDetailContent.js +1 -469
- package/lib/module/zustand/hooks/useZustandStateChanges.js +1 -70
- package/lib/module/zustand/sync/zustandSyncAdapter.js +1 -415
- package/lib/module/zustand/types/index.js +1 -1
- package/lib/module/zustand/utils/buoyZustandMiddleware.js +1 -278
- package/lib/module/zustand/utils/editableState.js +1 -138
- package/lib/module/zustand/utils/snapshotProvider.js +1 -209
- package/lib/module/zustand/utils/testIDs.js +1 -74
- package/lib/module/zustand/utils/zustandStateStore.js +1 -375
- package/lib/web/index.mjs +2 -3
- package/package.json +4 -7
- package/lib/typescript/index.d.ts.map +0 -1
- package/lib/typescript/preset.d.ts.map +0 -1
- package/lib/typescript/zustand/components/ZustandActionButton.d.ts.map +0 -1
- package/lib/typescript/zustand/components/ZustandDetailViewToggle.d.ts.map +0 -1
- package/lib/typescript/zustand/components/ZustandEventFilterView.d.ts.map +0 -1
- package/lib/typescript/zustand/components/ZustandIcon.d.ts.map +0 -1
- package/lib/typescript/zustand/components/ZustandModal.d.ts.map +0 -1
- package/lib/typescript/zustand/components/ZustandStateChangeItem.d.ts.map +0 -1
- package/lib/typescript/zustand/components/ZustandStateDetailContent.d.ts.map +0 -1
- package/lib/typescript/zustand/components/ZustandStateInfoView.d.ts.map +0 -1
- package/lib/typescript/zustand/components/ZustandStoreBrowser.d.ts.map +0 -1
- package/lib/typescript/zustand/components/ZustandStoreDetailContent.d.ts.map +0 -1
- package/lib/typescript/zustand/hooks/useZustandStateChanges.d.ts.map +0 -1
- package/lib/typescript/zustand/sync/zustandSyncAdapter.d.ts.map +0 -1
- package/lib/typescript/zustand/types/index.d.ts.map +0 -1
- package/lib/typescript/zustand/utils/buoyZustandMiddleware.d.ts.map +0 -1
- package/lib/typescript/zustand/utils/editableState.d.ts.map +0 -1
- package/lib/typescript/zustand/utils/snapshotProvider.d.ts.map +0 -1
- package/lib/typescript/zustand/utils/testIDs.d.ts.map +0 -1
- package/lib/typescript/zustand/utils/zustandStateStore.d.ts.map +0 -1
|
@@ -1,278 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Buoy Zustand DevTools — Store instrumentation
|
|
5
|
-
*
|
|
6
|
-
* Two approaches, from easiest to most detailed:
|
|
7
|
-
*
|
|
8
|
-
* 1. watchStores() — RECOMMENDED. One line, zero store modifications.
|
|
9
|
-
* Uses store.subscribe() externally. Never touches setState.
|
|
10
|
-
* Safe to add/remove — cannot break your stores even if our code has bugs.
|
|
11
|
-
*
|
|
12
|
-
* 2. buoyDevTools() — Opt-in middleware for advanced use.
|
|
13
|
-
* Wraps setState to capture the partial argument and timing.
|
|
14
|
-
* Requires modifying each store's create() call.
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
import { zustandStateStore } from "./zustandStateStore";
|
|
18
|
-
/** Symbol to mark stores that have been watched/instrumented */
|
|
19
|
-
const WATCHED_SYMBOL = Symbol.for("@@buoy-zustand/watched");
|
|
20
|
-
|
|
21
|
-
/** The slice of zustand's persist API this module uses. */
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Detect if a store is using the persist middleware by checking for persist API
|
|
25
|
-
*/
|
|
26
|
-
function detectPersist(store) {
|
|
27
|
-
const persist = store.persist;
|
|
28
|
-
if (persist && typeof persist.getOptions === "function") {
|
|
29
|
-
const options = persist.getOptions();
|
|
30
|
-
return {
|
|
31
|
-
isPersisted: true,
|
|
32
|
-
persistName: options?.name,
|
|
33
|
-
persistApi: persist
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
return {
|
|
37
|
-
isPersisted: false
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// =============================================================================
|
|
42
|
-
// watchStores — Primary, non-intrusive approach
|
|
43
|
-
// =============================================================================
|
|
44
|
-
|
|
45
|
-
/** Minimal store shape — what Zustand's create() returns */
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Watch multiple Zustand stores for state changes.
|
|
49
|
-
*
|
|
50
|
-
* This is the recommended, non-intrusive approach. It uses each store's
|
|
51
|
-
* `.subscribe()` method to observe changes from the outside — it never
|
|
52
|
-
* modifies `setState` or any store internals.
|
|
53
|
-
*
|
|
54
|
-
* **Safe by design:** Even if our listener code has a bug, it cannot break
|
|
55
|
-
* your stores. All listener code is wrapped in try/catch.
|
|
56
|
-
*
|
|
57
|
-
* @example
|
|
58
|
-
* ```tsx
|
|
59
|
-
* // In your _layout.tsx or App.tsx — ONE line:
|
|
60
|
-
* import { watchStores } from '@buoy-gg/zustand';
|
|
61
|
-
* import { useCounterStore } from './stores/counter';
|
|
62
|
-
* import { useAuthStore } from './stores/auth';
|
|
63
|
-
* import { useCartStore } from './stores/cart';
|
|
64
|
-
*
|
|
65
|
-
* watchStores({
|
|
66
|
-
* counterStore: useCounterStore,
|
|
67
|
-
* authStore: useAuthStore,
|
|
68
|
-
* cartStore: useCartStore,
|
|
69
|
-
* });
|
|
70
|
-
* ```
|
|
71
|
-
*
|
|
72
|
-
* @param stores - Object mapping store names to Zustand store hooks
|
|
73
|
-
* @returns Cleanup function that removes all subscriptions
|
|
74
|
-
*/
|
|
75
|
-
export function watchStores(stores) {
|
|
76
|
-
const cleanups = [];
|
|
77
|
-
for (const [name, store] of Object.entries(stores)) {
|
|
78
|
-
// Skip if already watched
|
|
79
|
-
const storeAny = store;
|
|
80
|
-
if (storeAny[WATCHED_SYMBOL]) continue;
|
|
81
|
-
storeAny[WATCHED_SYMBOL] = true;
|
|
82
|
-
const {
|
|
83
|
-
isPersisted,
|
|
84
|
-
persistName,
|
|
85
|
-
persistApi
|
|
86
|
-
} = detectPersist(store);
|
|
87
|
-
|
|
88
|
-
// Register the store for overview
|
|
89
|
-
zustandStateStore.registerStore(name, {
|
|
90
|
-
getState: store.getState,
|
|
91
|
-
getInitialState: store.getInitialState,
|
|
92
|
-
setState: store.setState,
|
|
93
|
-
subscribe: store.subscribe
|
|
94
|
-
}, {
|
|
95
|
-
isPersisted,
|
|
96
|
-
persistName,
|
|
97
|
-
// Was detected and thrown away. Without it nothing can re-read the
|
|
98
|
-
// saved copy after an outside edit — see ZustandStoreInfo.rehydrate.
|
|
99
|
-
rehydrate: typeof persistApi?.rehydrate === "function" ? () => persistApi.rehydrate() : undefined
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
// The rehydration is a state change nobody's code asked for — the store
|
|
103
|
-
// simply becomes what the disk said, seconds into the process. Drawn as an
|
|
104
|
-
// ordinary setState it is the most surprising row in the list and the one
|
|
105
|
-
// that looks most like a bug, so it gets its own category. Recognised
|
|
106
|
-
// rather than announced: `hasHydrated()` is still false while the
|
|
107
|
-
// rehydrating `set` is running, and this listener runs inside it.
|
|
108
|
-
let sawHydration = false;
|
|
109
|
-
|
|
110
|
-
// Subscribe to state changes — completely external, never touches setState
|
|
111
|
-
const unsubscribe = store.subscribe((state, prevState) => {
|
|
112
|
-
try {
|
|
113
|
-
let category;
|
|
114
|
-
if (!sawHydration && isPersisted) {
|
|
115
|
-
let hydrating = false;
|
|
116
|
-
try {
|
|
117
|
-
hydrating = persistApi?.hasHydrated?.() === false;
|
|
118
|
-
} catch {
|
|
119
|
-
// An older persist API without hasHydrated — no worse than before.
|
|
120
|
-
}
|
|
121
|
-
if (hydrating) {
|
|
122
|
-
sawHydration = true;
|
|
123
|
-
category = "persist";
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
zustandStateStore.addStateChange({
|
|
127
|
-
storeName: name,
|
|
128
|
-
partial: undefined,
|
|
129
|
-
// Not available in subscribe-only mode
|
|
130
|
-
replace: false,
|
|
131
|
-
prevState,
|
|
132
|
-
nextState: state,
|
|
133
|
-
duration: undefined,
|
|
134
|
-
// Not available in subscribe-only mode
|
|
135
|
-
category,
|
|
136
|
-
isPersisted
|
|
137
|
-
});
|
|
138
|
-
} catch {
|
|
139
|
-
// Silently catch — our bug must never propagate into the store
|
|
140
|
-
}
|
|
141
|
-
});
|
|
142
|
-
cleanups.push(() => {
|
|
143
|
-
unsubscribe();
|
|
144
|
-
delete store[WATCHED_SYMBOL];
|
|
145
|
-
zustandStateStore.unregisterStore(name);
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
return () => {
|
|
149
|
-
cleanups.forEach(fn => fn());
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
// =============================================================================
|
|
154
|
-
// buoyDevTools — Opt-in middleware (advanced, more detail)
|
|
155
|
-
// =============================================================================
|
|
156
|
-
|
|
157
|
-
/** Auto-incrementing store name counter for unnamed stores */
|
|
158
|
-
let unnamedCounter = 0;
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* Zustand middleware that instruments a store for Buoy DevTools.
|
|
162
|
-
*
|
|
163
|
-
* This is the advanced approach — it wraps setState to capture:
|
|
164
|
-
* - The partial argument passed to setState
|
|
165
|
-
* - Precise timing of each setState call
|
|
166
|
-
*
|
|
167
|
-
* Use this when you want maximum detail. For most cases, `watchStores()`
|
|
168
|
-
* is simpler and safer.
|
|
169
|
-
*
|
|
170
|
-
* @example
|
|
171
|
-
* ```tsx
|
|
172
|
-
* import { create } from 'zustand';
|
|
173
|
-
* import { buoyDevTools } from '@buoy-gg/zustand';
|
|
174
|
-
*
|
|
175
|
-
* const useCounterStore = create(
|
|
176
|
-
* buoyDevTools(
|
|
177
|
-
* (set) => ({
|
|
178
|
-
* count: 0,
|
|
179
|
-
* increment: () => set((s) => ({ count: s.count + 1 })),
|
|
180
|
-
* }),
|
|
181
|
-
* { name: 'counterStore' }
|
|
182
|
-
* )
|
|
183
|
-
* );
|
|
184
|
-
* ```
|
|
185
|
-
*/
|
|
186
|
-
/**
|
|
187
|
-
* Zustand's own `set` shape (v5 types): with `replace: true` the argument must
|
|
188
|
-
* be a FULL state, so a single `(partial, replace?: boolean)` signature is
|
|
189
|
-
* incompatible in both directions — zustand's set is not assignable to it,
|
|
190
|
-
* which made `create(buoyDevTools(...))` fail to typecheck for every strict-TS
|
|
191
|
-
* user. Mirroring the overloads keeps buoyDevTools a drop-in for `create()`.
|
|
192
|
-
*/
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* The store api object zustand hands a middleware, described structurally so
|
|
196
|
-
* this package never has to import zustand's own types (which differ between
|
|
197
|
-
* v4 and v5). `Record<string, unknown>` was wrong here: `StoreApi<T>` has no
|
|
198
|
-
* index signature, so `create(buoyDevTools(...))` failed to typecheck.
|
|
199
|
-
*/
|
|
200
|
-
|
|
201
|
-
export function buoyDevTools(config, options) {
|
|
202
|
-
return (set, get, api) => {
|
|
203
|
-
const storeName = options?.name ?? `store-${++unnamedCounter}`;
|
|
204
|
-
const enabled = options?.enabled !== false;
|
|
205
|
-
|
|
206
|
-
// Forwarding a plain `replace?: boolean` through the overloads needs one
|
|
207
|
-
// widening cast; runtime behavior is unchanged.
|
|
208
|
-
const rawSet = set;
|
|
209
|
-
const instrumentedSet = (partial, replace) => {
|
|
210
|
-
if (!enabled) {
|
|
211
|
-
return rawSet(partial, replace);
|
|
212
|
-
}
|
|
213
|
-
const startTime = performance.now();
|
|
214
|
-
const prevState = get();
|
|
215
|
-
rawSet(partial, replace);
|
|
216
|
-
const nextState = get();
|
|
217
|
-
const duration = performance.now() - startTime;
|
|
218
|
-
const resolvedPartial = typeof partial === "function" ? "(updater fn)" : partial;
|
|
219
|
-
zustandStateStore.addStateChange({
|
|
220
|
-
storeName,
|
|
221
|
-
partial: resolvedPartial,
|
|
222
|
-
replace: replace ?? false,
|
|
223
|
-
prevState,
|
|
224
|
-
nextState,
|
|
225
|
-
duration,
|
|
226
|
-
// Read back off the registry rather than hardcoded false. Persistence
|
|
227
|
-
// is a property of the STORE, and this middleware can be wrapped
|
|
228
|
-
// around a persisted one — every change on such a store used to be
|
|
229
|
-
// drawn as un-persisted, which is the opposite of what the badge is
|
|
230
|
-
// for. Registration happens a tick after creation, so a set fired in
|
|
231
|
-
// that first tick still reports false; the alternative is re-sniffing
|
|
232
|
-
// `api.persist` on every set.
|
|
233
|
-
isPersisted: zustandStateStore.getStore(storeName)?.isPersisted ?? false
|
|
234
|
-
});
|
|
235
|
-
};
|
|
236
|
-
const result = config(instrumentedSet, get, api);
|
|
237
|
-
|
|
238
|
-
// Register the store after creation
|
|
239
|
-
setTimeout(() => {
|
|
240
|
-
if (api[WATCHED_SYMBOL]) return;
|
|
241
|
-
api[WATCHED_SYMBOL] = true;
|
|
242
|
-
const {
|
|
243
|
-
isPersisted,
|
|
244
|
-
persistName
|
|
245
|
-
} = detectPersist(api);
|
|
246
|
-
zustandStateStore.registerStore(storeName, {
|
|
247
|
-
getState: get,
|
|
248
|
-
getInitialState: api.getInitialState,
|
|
249
|
-
// The INSTRUMENTED set, not the raw one.
|
|
250
|
-
//
|
|
251
|
-
// This handle is what the tool's own JUMP and RESET STORE call, and
|
|
252
|
-
// registering the raw `set` here made both of them invisible: the
|
|
253
|
-
// store changed, the app re-rendered, and nothing appeared in the
|
|
254
|
-
// log — so the newest row's "state after change" no longer described
|
|
255
|
-
// the store, and the next diff compared against a state the device
|
|
256
|
-
// had never been in. The watch path never had this problem, because
|
|
257
|
-
// it observes the store from outside and cannot be gone around.
|
|
258
|
-
setState: instrumentedSet,
|
|
259
|
-
subscribe: api.subscribe
|
|
260
|
-
}, {
|
|
261
|
-
isPersisted,
|
|
262
|
-
persistName
|
|
263
|
-
});
|
|
264
|
-
}, 0);
|
|
265
|
-
return result;
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
// =============================================================================
|
|
270
|
-
// Utility
|
|
271
|
-
// =============================================================================
|
|
272
|
-
|
|
273
|
-
/**
|
|
274
|
-
* Check if a store is being watched/instrumented
|
|
275
|
-
*/
|
|
276
|
-
export function isStoreInstrumented(store) {
|
|
277
|
-
return store[WATCHED_SYMBOL] === true;
|
|
278
|
-
}
|
|
1
|
+
"use strict";import{zustandStateStore as c}from"./zustandStateStore";const d=Symbol.for("@@buoy-zustand/watched");function m(o){const e=o.persist;if(e&&typeof e.getOptions==="function"){const s=e.getOptions();return{isPersisted:true,persistName:s?.name,persistApi:e}}return{isPersisted:false}}export function watchStores(o){const e=[];for(const[s,t]of Object.entries(o)){const r=t;if(r[d])continue;r[d]=true;const{isPersisted:i,persistName:p,persistApi:u}=m(t);c.registerStore(s,{getState:t.getState,getInitialState:t.getInitialState,setState:t.setState,subscribe:t.subscribe},{isPersisted:i,persistName:p,rehydrate:typeof u?.rehydrate==="function"?()=>u.rehydrate():void 0});let f=false;const b=t.subscribe((n,a)=>{try{let S;if(!f&&i){let l=false;try{l=u?.hasHydrated?.()===false}catch{}if(l){f=true;S="persist"}}c.addStateChange({storeName:s,partial:void 0,replace:false,prevState:a,nextState:n,duration:void 0,category:S,isPersisted:i})}catch{}});e.push(()=>{b();delete t[d];c.unregisterStore(s)})}return()=>{e.forEach(s=>s())}}let P=0;export function buoyDevTools(o,e){return(s,t,r)=>{const i=e?.name??`store-${++P}`;const p=e?.enabled!==false;const u=s;const f=(n,a)=>{if(!p){return u(n,a)}const S=performance.now();const l=t();u(n,a);const y=t();const g=performance.now()-S;const h=typeof n==="function"?"(updater fn)":n;c.addStateChange({storeName:i,partial:h,replace:a??false,prevState:l,nextState:y,duration:g,isPersisted:c.getStore(i)?.isPersisted??false})};const b=o(f,t,r);setTimeout(()=>{if(r[d])return;r[d]=true;const{isPersisted:n,persistName:a}=m(r);c.registerStore(i,{getState:t,getInitialState:r.getInitialState,setState:f,subscribe:r.subscribe},{isPersisted:n,persistName:a})},0);return b}}export function isStoreInstrumented(o){return o[d]===true}
|
|
@@ -1,138 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* What of a zustand store's state can be EDITED, and how an edit is written.
|
|
5
|
-
*
|
|
6
|
-
* The two zustand facts every rule here follows from:
|
|
7
|
-
*
|
|
8
|
-
* 1. Stores conventionally keep their action functions IN state
|
|
9
|
-
* (`increment: () => …`). Functions can't be typed into a tree editor and
|
|
10
|
-
* don't survive serialization, so the editor works on a function-free view
|
|
11
|
-
* of state.
|
|
12
|
-
* 2. `setState` is either a TOP-LEVEL SHALLOW MERGE (`Object.assign({}, state,
|
|
13
|
-
* partial)`) or a full replace that deletes every key not present — actions
|
|
14
|
-
* included. So the editor writes merge-only, always: every edit, however
|
|
15
|
-
* deep, is expressed as "replace the top-level key(s) that contain it"
|
|
16
|
-
* ({@link computeMergePartial}), and the two edits a merge cannot express —
|
|
17
|
-
* removing or renaming a top-level key — are refused rather than silently
|
|
18
|
-
* not happening.
|
|
19
|
-
*
|
|
20
|
-
* `stripFunctions` lives here (the Time Machine snapshot provider imports it)
|
|
21
|
-
* because capture and editing need the identical answer to "what is this
|
|
22
|
-
* store's data".
|
|
23
|
-
*/
|
|
24
|
-
|
|
25
|
-
/** Bounds every recursive walk over store state. */
|
|
26
|
-
export const STRIP_MAX_DEPTH = 8;
|
|
27
|
-
export function isPlainObjectLike(v) {
|
|
28
|
-
// Only objects whose own enumerable keys ARE their data. A Map, Set, Date,
|
|
29
|
-
// RegExp or typed array has none, so walking it with Object.entries turns
|
|
30
|
-
// it into `{}` — which is how a restored store once got `{}` where the app
|
|
31
|
-
// kept a Map and crashed on `.values()`. Those go through as-is; the vault's
|
|
32
|
-
// superjson knows how to carry them.
|
|
33
|
-
if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
|
|
34
|
-
const proto = Object.getPrototypeOf(v);
|
|
35
|
-
return proto === Object.prototype || proto === null;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** Clone `value` without functions, recording their paths. */
|
|
39
|
-
export function stripFunctions(value, path, fnPaths, seen, depth) {
|
|
40
|
-
if (typeof value === "function") {
|
|
41
|
-
fnPaths.push(path);
|
|
42
|
-
return undefined;
|
|
43
|
-
}
|
|
44
|
-
if (typeof value !== "object" || value === null || depth >= STRIP_MAX_DEPTH) {
|
|
45
|
-
return value;
|
|
46
|
-
}
|
|
47
|
-
if (seen.has(value)) return undefined; // cycle — drop the back-reference
|
|
48
|
-
seen.add(value);
|
|
49
|
-
if (Array.isArray(value)) {
|
|
50
|
-
return value.map((item, i) => typeof item === "function" ? (fnPaths.push(`${path}[${i}]`), null) : stripFunctions(item, `${path}[${i}]`, fnPaths, seen, depth + 1));
|
|
51
|
-
}
|
|
52
|
-
if (!isPlainObjectLike(value)) return value; // Date/Map/Set/etc. — superjson handles
|
|
53
|
-
const out = {};
|
|
54
|
-
for (const [k, v] of Object.entries(value)) {
|
|
55
|
-
if (typeof v === "function") {
|
|
56
|
-
fnPaths.push(path ? `${path}.${k}` : k);
|
|
57
|
-
continue;
|
|
58
|
-
}
|
|
59
|
-
out[k] = stripFunctions(v, path ? `${path}.${k}` : k, fnPaths, seen, depth + 1);
|
|
60
|
-
}
|
|
61
|
-
return out;
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* The editor's view of one store's state, with the reasons it may refuse.
|
|
65
|
-
*
|
|
66
|
-
* - A remote mirror that hasn't hydrated yet holds a marker, not state — the
|
|
67
|
-
* real value is one `getStoreState` round trip away, so "wait" rather than
|
|
68
|
-
* "can't".
|
|
69
|
-
* - Non-object state (`create(() => 5)`) has no top-level keys, so a merge
|
|
70
|
-
* write cannot address any part of it. Editing it would require a replace,
|
|
71
|
-
* which is the destructive path this editor exists to avoid.
|
|
72
|
-
* - A function nested BELOW the top level (rare — the convention keeps actions
|
|
73
|
-
* at the top) sits inside the very key an edit would rewrite, and a merge
|
|
74
|
-
* write of that key would silently drop it. Refusing the whole store is
|
|
75
|
-
* blunt but honest; per-key locks can come later if this ever bites.
|
|
76
|
-
*/
|
|
77
|
-
export function editableStateOf(state) {
|
|
78
|
-
if (isPlainObjectLike(state) && state.__buoyStateOnDevice === true) {
|
|
79
|
-
return {
|
|
80
|
-
data: null,
|
|
81
|
-
fnPaths: [],
|
|
82
|
-
blockedReason: "Store state hasn't synced from the device yet."
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
if (!isPlainObjectLike(state)) {
|
|
86
|
-
return {
|
|
87
|
-
data: null,
|
|
88
|
-
fnPaths: [],
|
|
89
|
-
blockedReason: "Only stores whose state is a plain object can be edited — " + "a merge write has nothing to address in " + (Array.isArray(state) ? "an array" : `a ${typeof state}`) + "."
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
const fnPaths = [];
|
|
93
|
-
const data = stripFunctions(state, "", fnPaths, new WeakSet(), 0);
|
|
94
|
-
const nested = fnPaths.filter(p => p.includes(".") || p.includes("["));
|
|
95
|
-
if (nested.length > 0) {
|
|
96
|
-
return {
|
|
97
|
-
data: null,
|
|
98
|
-
fnPaths,
|
|
99
|
-
blockedReason: `State keeps a function inside "${nested[0]}" — a merge write of ` + "that key would drop it, so this store can't be edited here."
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
return {
|
|
103
|
-
data,
|
|
104
|
-
fnPaths,
|
|
105
|
-
blockedReason: null
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Diff an edited draft against the state it was seeded from, as a `setState`
|
|
111
|
-
* MERGE partial: only the top-level keys whose contents changed.
|
|
112
|
-
*
|
|
113
|
-
* Diffed against the SEED, not the live state at save time, on purpose — the
|
|
114
|
-
* partial then carries exactly what the user changed, so a key the app wrote
|
|
115
|
-
* while the editor was open and the user never touched keeps the app's value
|
|
116
|
-
* (per-key last-write-wins, the same contract the draft's own dirtiness uses).
|
|
117
|
-
*
|
|
118
|
-
* Throws on the two edits a merge cannot express, naming the key: a draft
|
|
119
|
-
* that dropped a top-level key (which is also what a raw-JSON rename produces
|
|
120
|
-
* — the old key dropped, a new one added), because `setState(partial, false)`
|
|
121
|
-
* would leave it exactly as it was while the editor showed it gone.
|
|
122
|
-
*/
|
|
123
|
-
export function computeMergePartial(seed, draft) {
|
|
124
|
-
if (!isPlainObjectLike(draft)) {
|
|
125
|
-
throw new Error("The store's state must stay an object.");
|
|
126
|
-
}
|
|
127
|
-
const dropped = Object.keys(seed).filter(k => !(k in draft));
|
|
128
|
-
if (dropped.length > 0) {
|
|
129
|
-
throw new Error(`Can't remove top-level ${dropped.length === 1 ? "key" : "keys"} ` + `${dropped.map(k => `"${k}"`).join(", ")} — zustand merge writes ` + "can't delete. Edit the value instead.");
|
|
130
|
-
}
|
|
131
|
-
const partial = {};
|
|
132
|
-
for (const key of Object.keys(draft)) {
|
|
133
|
-
if (!(key in seed) || JSON.stringify(draft[key]) !== JSON.stringify(seed[key])) {
|
|
134
|
-
partial[key] = draft[key];
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
return partial;
|
|
138
|
-
}
|
|
1
|
+
"use strict";export const STRIP_MAX_DEPTH=8;export function isPlainObjectLike(e){if(typeof e!=="object"||e===null||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}export function stripFunctions(e,t,r,o,n){if(typeof e==="function"){r.push(t);return void 0}if(typeof e!=="object"||e===null||n>=STRIP_MAX_DEPTH){return e}if(o.has(e))return void 0;o.add(e);if(Array.isArray(e)){return e.map((i,s)=>typeof i==="function"?(r.push(`${t}[${s}]`),null):stripFunctions(i,`${t}[${s}]`,r,o,n+1))}if(!isPlainObjectLike(e))return e;const c={};for(const[i,s]of Object.entries(e)){if(typeof s==="function"){r.push(t?`${t}.${i}`:i);continue}c[i]=stripFunctions(s,t?`${t}.${i}`:i,r,o,n+1)}return c}export function editableStateOf(e){if(isPlainObjectLike(e)&&e.__buoyStateOnDevice===true){return{data:null,fnPaths:[],blockedReason:"Store state hasn't synced from the device yet."}}if(!isPlainObjectLike(e)){return{data:null,fnPaths:[],blockedReason:"Only stores whose state is a plain object can be edited \u2014 a merge write has nothing to address in "+(Array.isArray(e)?"an array":`a ${typeof e}`)+"."}}const t=[];const r=stripFunctions(e,"",t,new WeakSet,0);const o=t.filter(n=>n.includes(".")||n.includes("["));if(o.length>0){return{data:null,fnPaths:t,blockedReason:`State keeps a function inside "${o[0]}" \u2014 a merge write of that key would drop it, so this store can't be edited here.`}}return{data:r,fnPaths:t,blockedReason:null}}export function computeMergePartial(e,t){if(!isPlainObjectLike(t)){throw new Error("The store's state must stay an object.")}const r=Object.keys(e).filter(n=>!(n in t));if(r.length>0){throw new Error(`Can't remove top-level ${r.length===1?"key":"keys"} ${r.map(n=>`"${n}"`).join(", ")} \u2014 zustand merge writes can't delete. Edit the value instead.`)}const o={};for(const n of Object.keys(t)){if(!(n in e)||JSON.stringify(t[n])!==JSON.stringify(e[n])){o[n]=t[n]}}return o}
|
|
@@ -1,209 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Time Machine snapshot provider for Zustand.
|
|
5
|
-
*
|
|
6
|
-
* Registered into @buoy-gg/shared-ui's stateSnapshotRegistry at module init;
|
|
7
|
-
* consumed by @buoy-gg/time-machine. Neither package imports the other.
|
|
8
|
-
*
|
|
9
|
-
* The Zustand-specific hazard: stores conventionally keep their action
|
|
10
|
-
* functions IN state (`increment: () => ...`). Functions don't survive
|
|
11
|
-
* serialization, and a full `setState(snapshot, true)` replace would wipe
|
|
12
|
-
* them, breaking every `useStore(s => s.increment)` call site. So capture
|
|
13
|
-
* strips functions (recording where they were), and restore re-grafts the
|
|
14
|
-
* LIVE store's functions onto the snapshot before replacing.
|
|
15
|
-
*/
|
|
16
|
-
import { classifyPreviewItem, createRestoreScope, emptyRestoreResult, failedRestore, registerStateSnapshotProvider, unionKeys } from "@buoy-gg/shared-ui";
|
|
17
|
-
import { zustandStateStore } from "./zustandStateStore";
|
|
18
|
-
import { isPlainObjectLike, stripFunctions, STRIP_MAX_DEPTH } from "./editableState";
|
|
19
|
-
|
|
20
|
-
// The function-stripping walk is shared with the store editor (editableState
|
|
21
|
-
// .ts) — capture and editing must agree on what a store's "data" is.
|
|
22
|
-
const MAX_DEPTH = STRIP_MAX_DEPTH;
|
|
23
|
-
/**
|
|
24
|
-
* Copy every function-valued property from the LIVE state onto the restored
|
|
25
|
-
* snapshot (creating containers as needed), so store actions keep working
|
|
26
|
-
* after a full replace.
|
|
27
|
-
*/
|
|
28
|
-
function graftFunctions(target, live, seen, depth) {
|
|
29
|
-
if (!isPlainObjectLike(live) || !isPlainObjectLike(target)) return;
|
|
30
|
-
if (depth >= MAX_DEPTH || seen.has(live)) return;
|
|
31
|
-
seen.add(live);
|
|
32
|
-
for (const [k, v] of Object.entries(live)) {
|
|
33
|
-
if (typeof v === "function") {
|
|
34
|
-
target[k] = v;
|
|
35
|
-
} else if (isPlainObjectLike(v)) {
|
|
36
|
-
if (!isPlainObjectLike(target[k])) {
|
|
37
|
-
// Branch missing from the snapshot — only recreate it if it holds
|
|
38
|
-
// functions somewhere; otherwise the snapshot's absence wins.
|
|
39
|
-
if (!containsFunction(v, new WeakSet(), depth + 1)) continue;
|
|
40
|
-
target[k] = {};
|
|
41
|
-
}
|
|
42
|
-
graftFunctions(target[k], v, seen, depth + 1);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
function containsFunction(value, seen, depth) {
|
|
47
|
-
if (depth >= MAX_DEPTH || seen.has(value)) return false;
|
|
48
|
-
seen.add(value);
|
|
49
|
-
for (const v of Object.values(value)) {
|
|
50
|
-
if (typeof v === "function") return true;
|
|
51
|
-
if (isPlainObjectLike(v) && containsFunction(v, seen, depth + 1)) return true;
|
|
52
|
-
}
|
|
53
|
-
return false;
|
|
54
|
-
}
|
|
55
|
-
function status() {
|
|
56
|
-
const count = zustandStateStore.getStores().length;
|
|
57
|
-
if (count === 0) {
|
|
58
|
-
return {
|
|
59
|
-
canCapture: false,
|
|
60
|
-
canRestore: false,
|
|
61
|
-
detail: "No Zustand stores registered — pass `zustandStores` to FloatingDevTools or add the buoyDevTools middleware"
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
return {
|
|
65
|
-
canCapture: true,
|
|
66
|
-
canRestore: true
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
async function capture() {
|
|
70
|
-
const warnings = [];
|
|
71
|
-
const stores = {};
|
|
72
|
-
for (const info of zustandStateStore.getStores()) {
|
|
73
|
-
const fnPaths = [];
|
|
74
|
-
let state;
|
|
75
|
-
try {
|
|
76
|
-
state = stripFunctions(info.api.getState(), "", fnPaths, new WeakSet(), 0);
|
|
77
|
-
} catch (e) {
|
|
78
|
-
warnings.push(`store "${info.name}": capture failed (${String(e)})`);
|
|
79
|
-
continue;
|
|
80
|
-
}
|
|
81
|
-
stores[info.name] = {
|
|
82
|
-
state,
|
|
83
|
-
fnPaths
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
return {
|
|
87
|
-
data: {
|
|
88
|
-
stores
|
|
89
|
-
},
|
|
90
|
-
warnings
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
async function restore(data, options) {
|
|
94
|
-
const snapshot = data;
|
|
95
|
-
const scope = createRestoreScope(options);
|
|
96
|
-
const result = emptyRestoreResult();
|
|
97
|
-
if (!snapshot?.stores) {
|
|
98
|
-
return failedRestore("empty zustand snapshot");
|
|
99
|
-
}
|
|
100
|
-
for (const [name, envelope] of Object.entries(snapshot.stores)) {
|
|
101
|
-
if (!scope.allows(name)) continue;
|
|
102
|
-
const info = zustandStateStore.getStore(name);
|
|
103
|
-
if (!info) {
|
|
104
|
-
result.skipped.push({
|
|
105
|
-
id: name,
|
|
106
|
-
reason: "store not registered (renamed, or created after snapshot?)"
|
|
107
|
-
});
|
|
108
|
-
continue;
|
|
109
|
-
}
|
|
110
|
-
try {
|
|
111
|
-
const next = envelope.state;
|
|
112
|
-
graftFunctions(next, info.api.getState(), new WeakSet(), 0);
|
|
113
|
-
info.api.setState(next, true);
|
|
114
|
-
if (info.api.getState() === next) {
|
|
115
|
-
result.applied += 1;
|
|
116
|
-
} else {
|
|
117
|
-
result.warnings.push(`store "${name}": setState did not take effect`);
|
|
118
|
-
result.ok = false;
|
|
119
|
-
}
|
|
120
|
-
} catch (e) {
|
|
121
|
-
result.skipped.push({
|
|
122
|
-
id: name,
|
|
123
|
-
reason: String(e)
|
|
124
|
-
});
|
|
125
|
-
result.ok = false;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
const excludedWarning = scope.excludedWarning("store(s)");
|
|
129
|
-
if (excludedWarning) result.warnings.push(excludedWarning);
|
|
130
|
-
return result;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Per-store restore preview. Both sides are function-stripped through the
|
|
135
|
-
* SAME depth-8 normalizer as capture — diffing snapshot-vs-RAW-live would
|
|
136
|
-
* report every stripped function and every beyond-depth subtree as removed.
|
|
137
|
-
*/
|
|
138
|
-
async function previewItems(target, base) {
|
|
139
|
-
const targetStores = target?.stores ?? {};
|
|
140
|
-
const liveMode = base === undefined;
|
|
141
|
-
const baseStores = {};
|
|
142
|
-
if (liveMode) {
|
|
143
|
-
for (const info of zustandStateStore.getStores()) {
|
|
144
|
-
const fnPaths = [];
|
|
145
|
-
try {
|
|
146
|
-
baseStores[info.name] = {
|
|
147
|
-
state: stripFunctions(info.api.getState(), "", fnPaths, new WeakSet(), 0),
|
|
148
|
-
fnPaths
|
|
149
|
-
};
|
|
150
|
-
} catch {
|
|
151
|
-
// unreadable live store — treated as absent
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
} else {
|
|
155
|
-
Object.assign(baseStores, base?.stores ?? {});
|
|
156
|
-
}
|
|
157
|
-
const items = [];
|
|
158
|
-
const notes = [];
|
|
159
|
-
let preservedFns = 0;
|
|
160
|
-
for (const name of unionKeys(baseStores, targetStores)) {
|
|
161
|
-
const inTarget = name in targetStores;
|
|
162
|
-
const inBase = name in baseStores;
|
|
163
|
-
if (!inTarget) {
|
|
164
|
-
// Restore never touches stores the snapshot doesn't know about.
|
|
165
|
-
if (liveMode) notes.push(`store "${name}" not in snapshot — untouched`);else items.push({
|
|
166
|
-
key: name,
|
|
167
|
-
label: name,
|
|
168
|
-
verdict: "removed",
|
|
169
|
-
oldValue: baseStores[name].state
|
|
170
|
-
});
|
|
171
|
-
continue;
|
|
172
|
-
}
|
|
173
|
-
preservedFns += targetStores[name].fnPaths?.length ?? 0;
|
|
174
|
-
if (liveMode && !zustandStateStore.getStore(name)) {
|
|
175
|
-
items.push({
|
|
176
|
-
key: name,
|
|
177
|
-
label: name,
|
|
178
|
-
verdict: "wont-apply",
|
|
179
|
-
reason: "store not registered (renamed, or created after snapshot?)"
|
|
180
|
-
});
|
|
181
|
-
continue;
|
|
182
|
-
}
|
|
183
|
-
items.push(classifyPreviewItem({
|
|
184
|
-
key: name,
|
|
185
|
-
label: name,
|
|
186
|
-
oldValue: baseStores[name]?.state,
|
|
187
|
-
newValue: targetStores[name].state,
|
|
188
|
-
inOld: inBase,
|
|
189
|
-
inNew: true
|
|
190
|
-
}, {
|
|
191
|
-
tooLargeReason: "store too large to render a diff — restore still applies it"
|
|
192
|
-
}));
|
|
193
|
-
}
|
|
194
|
-
if (preservedFns > 0) {
|
|
195
|
-
notes.push(`${preservedFns} store action function${preservedFns === 1 ? "" : "s"} preserved on restore (not diffed)`);
|
|
196
|
-
}
|
|
197
|
-
return {
|
|
198
|
-
items,
|
|
199
|
-
notes
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
registerStateSnapshotProvider({
|
|
203
|
-
id: "zustand",
|
|
204
|
-
label: "Zustand",
|
|
205
|
-
status,
|
|
206
|
-
capture,
|
|
207
|
-
restore,
|
|
208
|
-
previewItems
|
|
209
|
-
});
|
|
1
|
+
"use strict";import{classifyPreviewItem as m,createRestoreScope as y,emptyRestoreResult as k,failedRestore as w,registerStateSnapshotProvider as b,unionKeys as v}from"@buoy-gg/shared-ui";import{zustandStateStore as u}from"./zustandStateStore";import{isPlainObjectLike as d,stripFunctions as l,STRIP_MAX_DEPTH as P}from"./editableState";const p=P;function S(n,r,s,o){if(!d(r)||!d(n))return;if(o>=p||s.has(r))return;s.add(r);for(const[e,a]of Object.entries(r)){if(typeof a==="function"){n[e]=a}else if(d(a)){if(!d(n[e])){if(!g(a,new WeakSet,o+1))continue;n[e]={}}S(n[e],a,s,o+1)}}}function g(n,r,s){if(s>=p||r.has(n))return false;r.add(n);for(const o of Object.values(n)){if(typeof o==="function")return true;if(d(o)&&g(o,r,s+1))return true}return false}function R(){const n=u.getStores().length;if(n===0){return{canCapture:false,canRestore:false,detail:"No Zustand stores registered \u2014 pass `zustandStores` to FloatingDevTools or add the buoyDevTools middleware"}}return{canCapture:true,canRestore:true}}async function O(){const n=[];const r={};for(const s of u.getStores()){const o=[];let e;try{e=l(s.api.getState(),"",o,new WeakSet,0)}catch(a){n.push(`store "${s.name}": capture failed (${String(a)})`);continue}r[s.name]={state:e,fnPaths:o}}return{data:{stores:r},warnings:n}}async function T(n,r){const s=n;const o=y(r);const e=k();if(!s?.stores){return w("empty zustand snapshot")}for(const[c,f]of Object.entries(s.stores)){if(!o.allows(c))continue;const t=u.getStore(c);if(!t){e.skipped.push({id:c,reason:"store not registered (renamed, or created after snapshot?)"});continue}try{const i=f.state;S(i,t.api.getState(),new WeakSet,0);t.api.setState(i,true);if(t.api.getState()===i){e.applied+=1}else{e.warnings.push(`store "${c}": setState did not take effect`);e.ok=false}}catch(i){e.skipped.push({id:c,reason:String(i)});e.ok=false}}const a=o.excludedWarning("store(s)");if(a)e.warnings.push(a);return e}async function W(n,r){const s=n?.stores??{};const o=r===void 0;const e={};if(o){for(const t of u.getStores()){const i=[];try{e[t.name]={state:l(t.api.getState(),"",i,new WeakSet,0),fnPaths:i}}catch{}}}else{Object.assign(e,r?.stores??{})}const a=[];const c=[];let f=0;for(const t of v(e,s)){const i=t in s;const h=t in e;if(!i){if(o)c.push(`store "${t}" not in snapshot \u2014 untouched`);else a.push({key:t,label:t,verdict:"removed",oldValue:e[t].state});continue}f+=s[t].fnPaths?.length??0;if(o&&!u.getStore(t)){a.push({key:t,label:t,verdict:"wont-apply",reason:"store not registered (renamed, or created after snapshot?)"});continue}a.push(m({key:t,label:t,oldValue:e[t]?.state,newValue:s[t].state,inOld:h,inNew:true},{tooLargeReason:"store too large to render a diff \u2014 restore still applies it"}))}if(f>0){c.push(`${f} store action function${f===1?"":"s"} preserved on restore (not diffed)`)}return{items:a,notes:c}}b({id:"zustand",label:"Zustand",status:R,capture:O,restore:T,previewItems:W});
|