@buoy-gg/zustand 7.0.35 → 7.0.38

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 (64) hide show
  1. package/README.md +27 -5
  2. package/lib/commonjs/index.js +1 -105
  3. package/lib/commonjs/preset.js +1 -102
  4. package/lib/commonjs/zustand/components/ZustandActionButton.js +1 -118
  5. package/lib/commonjs/zustand/components/ZustandDetailViewToggle.js +1 -48
  6. package/lib/commonjs/zustand/components/ZustandEventFilterView.js +1 -43
  7. package/lib/commonjs/zustand/components/ZustandIcon.js +1 -18
  8. package/lib/commonjs/zustand/components/ZustandModal.js +1 -772
  9. package/lib/commonjs/zustand/components/ZustandStateChangeItem.js +1 -117
  10. package/lib/commonjs/zustand/components/ZustandStateDetailContent.js +1 -372
  11. package/lib/commonjs/zustand/components/ZustandStateInfoView.js +1 -488
  12. package/lib/commonjs/zustand/components/ZustandStoreBrowser.js +1 -204
  13. package/lib/commonjs/zustand/components/ZustandStoreDetailContent.js +1 -471
  14. package/lib/commonjs/zustand/components/ZustandStoreEditorScreen.js +1 -393
  15. package/lib/commonjs/zustand/hooks/useZustandStateChanges.js +1 -72
  16. package/lib/commonjs/zustand/sync/zustandSyncAdapter.js +1 -219
  17. package/lib/commonjs/zustand/utils/buoyZustandMiddleware.js +1 -284
  18. package/lib/commonjs/zustand/utils/editableState.js +1 -139
  19. package/lib/commonjs/zustand/utils/snapshotProvider.js +1 -209
  20. package/lib/commonjs/zustand/utils/testIDs.js +1 -82
  21. package/lib/commonjs/zustand/utils/zustandStateStore.js +1 -375
  22. package/lib/module/index.js +1 -90
  23. package/lib/module/preset.js +1 -98
  24. package/lib/module/zustand/components/ZustandActionButton.js +1 -114
  25. package/lib/module/zustand/components/ZustandDetailViewToggle.js +1 -43
  26. package/lib/module/zustand/components/ZustandEventFilterView.js +1 -39
  27. package/lib/module/zustand/components/ZustandIcon.js +1 -11
  28. package/lib/module/zustand/components/ZustandModal.js +1 -767
  29. package/lib/module/zustand/components/ZustandStateChangeItem.js +1 -113
  30. package/lib/module/zustand/components/ZustandStateDetailContent.js +1 -368
  31. package/lib/module/zustand/components/ZustandStateInfoView.js +1 -483
  32. package/lib/module/zustand/components/ZustandStoreBrowser.js +1 -200
  33. package/lib/module/zustand/components/ZustandStoreDetailContent.js +1 -469
  34. package/lib/module/zustand/components/ZustandStoreEditorScreen.js +1 -389
  35. package/lib/module/zustand/hooks/useZustandStateChanges.js +1 -68
  36. package/lib/module/zustand/sync/zustandSyncAdapter.js +1 -216
  37. package/lib/module/zustand/utils/buoyZustandMiddleware.js +1 -278
  38. package/lib/module/zustand/utils/editableState.js +1 -131
  39. package/lib/module/zustand/utils/snapshotProvider.js +1 -209
  40. package/lib/module/zustand/utils/testIDs.js +1 -74
  41. package/lib/module/zustand/utils/zustandStateStore.js +1 -371
  42. package/lib/typescript/zustand/sync/zustandSyncAdapter.d.ts +33 -0
  43. package/package.json +4 -4
  44. package/lib/typescript/index.d.ts.map +0 -1
  45. package/lib/typescript/preset.d.ts.map +0 -1
  46. package/lib/typescript/zustand/components/ZustandActionButton.d.ts.map +0 -1
  47. package/lib/typescript/zustand/components/ZustandDetailViewToggle.d.ts.map +0 -1
  48. package/lib/typescript/zustand/components/ZustandEventFilterView.d.ts.map +0 -1
  49. package/lib/typescript/zustand/components/ZustandIcon.d.ts.map +0 -1
  50. package/lib/typescript/zustand/components/ZustandModal.d.ts.map +0 -1
  51. package/lib/typescript/zustand/components/ZustandStateChangeItem.d.ts.map +0 -1
  52. package/lib/typescript/zustand/components/ZustandStateDetailContent.d.ts.map +0 -1
  53. package/lib/typescript/zustand/components/ZustandStateInfoView.d.ts.map +0 -1
  54. package/lib/typescript/zustand/components/ZustandStoreBrowser.d.ts.map +0 -1
  55. package/lib/typescript/zustand/components/ZustandStoreDetailContent.d.ts.map +0 -1
  56. package/lib/typescript/zustand/components/ZustandStoreEditorScreen.d.ts.map +0 -1
  57. package/lib/typescript/zustand/hooks/useZustandStateChanges.d.ts.map +0 -1
  58. package/lib/typescript/zustand/sync/zustandSyncAdapter.d.ts.map +0 -1
  59. package/lib/typescript/zustand/types/index.d.ts.map +0 -1
  60. package/lib/typescript/zustand/utils/buoyZustandMiddleware.d.ts.map +0 -1
  61. package/lib/typescript/zustand/utils/editableState.d.ts.map +0 -1
  62. package/lib/typescript/zustand/utils/snapshotProvider.d.ts.map +0 -1
  63. package/lib/typescript/zustand/utils/testIDs.d.ts.map +0 -1
  64. package/lib/typescript/zustand/utils/zustandStateStore.d.ts.map +0 -1
@@ -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,createRestoreScope,emptyRestoreResult,failedRestore,registerStateSnapshotProvider,unionKeys}from"@buoy-gg/shared-ui";import{zustandStateStore}from"./zustandStateStore";import{isPlainObjectLike,stripFunctions,STRIP_MAX_DEPTH}from"./editableState";const MAX_DEPTH=STRIP_MAX_DEPTH;function graftFunctions(t,e,s,n){if(isPlainObjectLike(e)&&isPlainObjectLike(t)&&!(n>=MAX_DEPTH||s.has(e))){s.add(e);for(const[o,r]of Object.entries(e))if("function"==typeof r)t[o]=r;else if(isPlainObjectLike(r)){if(!isPlainObjectLike(t[o])){if(!containsFunction(r,new WeakSet,n+1))continue;t[o]={}}graftFunctions(t[o],r,s,n+1)}}}function containsFunction(t,e,s){if(s>=MAX_DEPTH||e.has(t))return!1;e.add(t);for(const n of Object.values(t)){if("function"==typeof n)return!0;if(isPlainObjectLike(n)&&containsFunction(n,e,s+1))return!0}return!1}function status(){return 0===zustandStateStore.getStores().length?{canCapture:!1,canRestore:!1,detail:"No Zustand stores registered — pass `zustandStores` to FloatingDevTools or add the buoyDevTools middleware"}:{canCapture:!0,canRestore:!0}}async function capture(){const t=[],e={};for(const s of zustandStateStore.getStores()){const n=[];let o;try{o=stripFunctions(s.api.getState(),"",n,new WeakSet,0)}catch(e){t.push(`store "${s.name}": capture failed (${String(e)})`);continue}e[s.name]={state:o,fnPaths:n}}return{data:{stores:e},warnings:t}}async function restore(t,e){const s=t,n=createRestoreScope(e),o=emptyRestoreResult();if(!s?.stores)return failedRestore("empty zustand snapshot");for(const[t,e]of Object.entries(s.stores)){if(!n.allows(t))continue;const s=zustandStateStore.getStore(t);if(s)try{const n=e.state;graftFunctions(n,s.api.getState(),new WeakSet,0),s.api.setState(n,!0),s.api.getState()===n?o.applied+=1:(o.warnings.push(`store "${t}": setState did not take effect`),o.ok=!1)}catch(e){o.skipped.push({id:t,reason:String(e)}),o.ok=!1}else o.skipped.push({id:t,reason:"store not registered (renamed, or created after snapshot?)"})}const r=n.excludedWarning("store(s)");return r&&o.warnings.push(r),o}async function previewItems(t,e){const s=t?.stores??{},n=void 0===e,o={};if(n)for(const t of zustandStateStore.getStores()){const e=[];try{o[t.name]={state:stripFunctions(t.api.getState(),"",e,new WeakSet,0),fnPaths:e}}catch{}}else Object.assign(o,e?.stores??{});const r=[],a=[];let i=0;for(const t of unionKeys(o,s)){const e=t in o;t in s?(i+=s[t].fnPaths?.length??0,!n||zustandStateStore.getStore(t)?r.push(classifyPreviewItem({key:t,label:t,oldValue:o[t]?.state,newValue:s[t].state,inOld:e,inNew:!0},{tooLargeReason:"store too large to render a diff — restore still applies it"})):r.push({key:t,label:t,verdict:"wont-apply",reason:"store not registered (renamed, or created after snapshot?)"})):n?a.push(`store "${t}" not in snapshot — untouched`):r.push({key:t,label:t,verdict:"removed",oldValue:o[t].state})}return i>0&&a.push(`${i} store action function${1===i?"":"s"} preserved on restore (not diffed)`),{items:r,notes:a}}registerStateSnapshotProvider({id:"zustand",label:"Zustand",status:status,capture:capture,restore:restore,previewItems:previewItems});
@@ -1,74 +1 @@
1
- "use strict";
2
-
3
- /**
4
- * Zustand tool test handles.
5
- *
6
- * Every tappable and every value the e2e suite reads back is addressed
7
- * `buoy-zustand-<thing>`. Two rules in here need explaining.
8
- *
9
- * **A change row's handle carries an ORDINAL, and it counts per STORE.** The
10
- * Events tool can address a row by what it is about, because an event is a
11
- * thing that happened to a named subject — one key, one URL, one atom. A
12
- * zustand state change is not: a store that a screen writes to fifty times
13
- * produces fifty separate, equally real rows. Addressing them by store name
14
- * alone would give fifty views one handle, and Detox fails a *matcher* that
15
- * hits more than one element — so a suite would break on `toExist()`, before
16
- * any assertion, with an error that says nothing about duplicate changes.
17
- *
18
- * So the handle is `buoy-zustand-row-<slug(storeName)>-<n>`, where n counts
19
- * back from the newest row of that store (1 = newest). Deliberately relative:
20
- * a state change has no identity a host could know in advance — `id` is a
21
- * timestamp plus a per-process counter whose value depends on how many
22
- * changes the app happened to make before the test looked. What a test CAN
23
- * know is "the set I just fired is the newest change to that store". Read and
24
- * tap in one beat: a row's ordinal moves the instant another change lands.
25
- *
26
- * **A store row's handle does NOT.** A store is registered once under a name
27
- * that is unique by construction (`zustandStateStore.registerStore` returns
28
- * early on a name it already holds), so `buoy-zustand-store-<slug(name)>` is
29
- * as stable as the store itself — and unlike a change, it is a thing the host
30
- * knows the name of before the app has booted.
31
- *
32
- * The suite mirrors these rules in CommonJS (`example-dev-build/utils/
33
- * zustandBench.js`) and asserts the two agree — Detox runs in Node on the host
34
- * and cannot import TypeScript.
35
- */
36
-
37
- /** Prefix every handle in this tool shares. */
38
- export const ZUSTAND_TEST_ID = "buoy-zustand";
39
-
40
- /** `zbenchWatch` → `zbenchwatch`. Shared with every Buoy tool. */
41
- export function slugForTestID(value) {
42
- return String(value ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "unknown";
43
- }
44
-
45
- /**
46
- * Handle for one change row: `buoy-zustand-row-zbenchwatch-1`.
47
- *
48
- * `ordinal` is 1-based and counts back from the newest row of this store.
49
- */
50
- export function changeRowTestID(storeName, ordinal) {
51
- return `${ZUSTAND_TEST_ID}-row-${slugForTestID(storeName)}-${ordinal}`;
52
- }
53
-
54
- /** Handle for one store row in the browser: `buoy-zustand-store-zbenchwatch`. */
55
- export function storeRowTestID(storeName) {
56
- return `${ZUSTAND_TEST_ID}-store-${slugForTestID(storeName)}`;
57
- }
58
-
59
- /**
60
- * Row handle per change id for one rendered list, newest-first.
61
- *
62
- * Built once for the whole list rather than per row, because an ordinal is a
63
- * fact about the list and a row cannot compute its own.
64
- */
65
- export function buildChangeRowTestIDs(changes) {
66
- const seen = new Map();
67
- const handles = new Map();
68
- for (const change of changes) {
69
- const ordinal = (seen.get(change.storeName) ?? 0) + 1;
70
- seen.set(change.storeName, ordinal);
71
- handles.set(change.id, changeRowTestID(change.storeName, ordinal));
72
- }
73
- return handles;
74
- }
1
+ "use strict";export const ZUSTAND_TEST_ID="buoy-zustand";export function slugForTestID(e){return String(e??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}export function changeRowTestID(e,t){return`buoy-zustand-row-${slugForTestID(e)}-${t}`}export function storeRowTestID(e){return`buoy-zustand-store-${slugForTestID(e)}`}export function buildChangeRowTestIDs(e){const t=new Map,o=new Map;for(const n of e){const e=(t.get(n.storeName)??0)+1;t.set(n.storeName,e),o.set(n.id,changeRowTestID(n.storeName,e))}return o}
@@ -1,371 +1 @@
1
- "use strict";
2
-
3
- /**
4
- * Zustand state store - captures and stores Zustand state changes
5
- *
6
- * The generic event-log half (ring buffer, listeners, clear-forwarding for
7
- * the desktop mirror, pause/suppress flags, hydrate-by-id) is the shared
8
- * `ChangeLog`; this file owns the zustand-specific half — the store registry,
9
- * snapshots, mirror rebuild, filters and stats.
10
- */
11
-
12
- import { ChangeLog, entityColor, formatValuePreview, shallowDiffSummary } from "@buoy-gg/shared-ui";
13
- // ============================================
14
- // Store Color Palette
15
- // ============================================
16
-
17
- const STORE_COLORS = {
18
- counter: "#10B981",
19
- // emerald
20
- auth: "#8B5CF6",
21
- // purple
22
- user: "#3B82F6",
23
- // blue
24
- cart: "#EC4899",
25
- // pink
26
- app: "#6366F1",
27
- // indigo
28
- ui: "#F59E0B",
29
- // amber
30
- settings: "#14B8A6",
31
- // teal
32
- theme: "#06B6D4",
33
- // cyan
34
- navigation: "#F97316",
35
- // orange
36
- form: "#EF4444" // red
37
- };
38
-
39
- /**
40
- * Get consistent color for a store based on its name
41
- */
42
- function getStoreColor(storeName) {
43
- return entityColor(storeName, STORE_COLORS);
44
- }
45
-
46
- /**
47
- * Format payload preview for display
48
- */
49
- function formatPartialPreview(partial, maxLength = 40) {
50
- return formatValuePreview(partial, {
51
- maxLength,
52
- undefinedLabel: "",
53
- functionLabel: "(updater fn)"
54
- });
55
- }
56
-
57
- // ============================================
58
- // Zustand State Store
59
- // ============================================
60
-
61
- class ZustandStateStore extends ChangeLog {
62
- stores = new Map();
63
- storeListeners = new Set();
64
- remoteSetStateHandler = null;
65
-
66
- // ---- State Change Tracking ----
67
-
68
- addStateChange(params) {
69
- if (!this.canRecord()) return;
70
- const {
71
- storeName,
72
- partial,
73
- replace,
74
- prevState,
75
- nextState,
76
- duration,
77
- category,
78
- isPersisted = false
79
- } = params;
80
- const hasStateChange = prevState !== nextState;
81
- // `changedCount` counts the keys in `changedKeys` and nothing else, so the
82
- // row's "N keys changed" and the detail page's CHANGED KEYS card agree —
83
- // including the persist-rehydrate case where the object is replaced
84
- // without any top-level value moving.
85
- const {
86
- summary,
87
- changedKeys,
88
- changedCount
89
- } = shallowDiffSummary(prevState, nextState);
90
- const partialPreview = formatPartialPreview(partial);
91
- const isSlowUpdate = (duration ?? 0) > 16;
92
- const resolvedCategory = category ?? (replace ? "replace" : "setState");
93
- const stateChange = {
94
- id: this.nextId(),
95
- storeName,
96
- timestamp: Date.now(),
97
- prevState,
98
- nextState,
99
- partial,
100
- duration,
101
- hasStateChange,
102
- replace,
103
- category: resolvedCategory,
104
- changedKeys,
105
- changedKeysCount: changedCount,
106
- diffSummary: summary,
107
- partialPreview,
108
- isSlowUpdate,
109
- isPersisted
110
- };
111
- this.push(stateChange);
112
-
113
- // Update store change count
114
- const storeInfo = this.stores.get(storeName);
115
- if (storeInfo) {
116
- storeInfo.stateChangeCount++;
117
- }
118
- this.notifyListeners();
119
- }
120
- getStateChanges() {
121
- return this.getAll();
122
- }
123
- getStateChangeById(id) {
124
- return this.getById(id);
125
- }
126
- clearStateChanges() {
127
- // Reset counts
128
- for (const store of this.stores.values()) {
129
- store.stateChangeCount = 0;
130
- }
131
- this.clear();
132
- }
133
-
134
- // ---- Remote Mirror Mode ----
135
-
136
- /**
137
- * Replace the change log without touching the store registry. Used when a
138
- * host keeps real registered stores (JUMP / RESET stay wired) but needs to
139
- * reseed the event list — the docs live tour, or any mirror that already
140
- * called `registerStore`. Does not fire `onClear`. Respects the enabled
141
- * flag so the UI's pause button freezes the reseed.
142
- */
143
- replaceStateChanges(changes) {
144
- if (!this.getEnabled()) return;
145
- for (const store of this.stores.values()) {
146
- store.stateChangeCount = 0;
147
- }
148
- const kept = changes.slice(0, this.max);
149
- for (const change of kept) {
150
- const store = this.stores.get(change.storeName);
151
- if (store) store.stateChangeCount++;
152
- }
153
- this.setItems(kept);
154
- this.notifyStoreListeners();
155
- }
156
-
157
- /**
158
- * Serializable snapshot of the tracked stores (registry metadata plus each
159
- * store's current state). Used by the sync adapter on the device side —
160
- * the live `api` handles can't go over the wire.
161
- */
162
- getStoreSnapshots() {
163
- return Array.from(this.stores.values()).map(store => {
164
- let currentState;
165
- try {
166
- currentState = store.api.getState();
167
- } catch {
168
- currentState = undefined;
169
- }
170
- return {
171
- name: store.name,
172
- stateChangeCount: store.stateChangeCount,
173
- isPersisted: store.isPersisted,
174
- persistName: store.persistName,
175
- // Persisted is not the same as re-readable: a store registered before
176
- // its persist middleware attached has a name but no handle. The
177
- // Storage tool needs the difference to decide between offering "apply"
178
- // and telling the user to restart.
179
- canRehydrate: typeof store.rehydrate === "function",
180
- color: store.color,
181
- currentState
182
- };
183
- });
184
- }
185
-
186
- /**
187
- * Handler invoked when the UI calls setState on a mirrored store (e.g.
188
- * time-travel from the dashboard). Forward it to the synced device.
189
- */
190
- setRemoteSetStateHandler(handler) {
191
- this.remoteSetStateHandler = handler;
192
- }
193
-
194
- /**
195
- * Replace the entire mirror contents from a synced device snapshot. The
196
- * rebuilt registry entries get stub `api` handles: getState() serves the
197
- * snapshotted state, setState() forwards to the remote handler. Respects
198
- * the enabled flag so the UI's pause button freezes the mirror.
199
- */
200
- replaceFromSnapshot(changes, storeSnapshots) {
201
- if (!this.getEnabled()) return;
202
-
203
- // Preserve trees a remote mirror already hydrated — wire-form snapshots
204
- // always carry markers, and a later snapshot must not blank the detail pane.
205
- const hydrated = new Map();
206
- for (const existing of this.items) {
207
- const prev = existing.prevState;
208
- if (!prev || prev.__buoyStateOnDevice !== true) {
209
- hydrated.set(existing.id, existing);
210
- }
211
- }
212
- const merged = changes.slice(0, this.max).map(change => {
213
- const kept = hydrated.get(change.id);
214
- const incoming = change.prevState;
215
- return kept && incoming?.__buoyStateOnDevice === true ? {
216
- ...change,
217
- prevState: kept.prevState,
218
- nextState: kept.nextState,
219
- partial: kept.partial
220
- } : change;
221
- });
222
-
223
- // Preserve currentState a remote mirror already hydrated — oversized
224
- // stores arrive as STATE_ON_DEVICE markers on every snapshot.
225
- const hydratedStores = new Map();
226
- for (const [name, store] of this.stores) {
227
- try {
228
- const state = store.api.getState();
229
- const marker = state;
230
- if (!marker || marker.__buoyStateOnDevice !== true) {
231
- hydratedStores.set(name, state);
232
- }
233
- } catch {
234
- // ignore
235
- }
236
- }
237
- this.stores = new Map(storeSnapshots.map(snapshot => {
238
- const incoming = snapshot.currentState;
239
- const kept = hydratedStores.get(snapshot.name);
240
- const currentState = kept !== undefined && incoming?.__buoyStateOnDevice === true ? kept : snapshot.currentState;
241
- return [snapshot.name, {
242
- name: snapshot.name,
243
- api: {
244
- getState: () => currentState,
245
- setState: (partial, replace) => {
246
- this.remoteSetStateHandler?.(snapshot.name, partial, replace);
247
- },
248
- subscribe: () => () => {}
249
- },
250
- stateChangeCount: snapshot.stateChangeCount,
251
- isPersisted: snapshot.isPersisted,
252
- persistName: snapshot.persistName,
253
- color: snapshot.color
254
- }];
255
- }));
256
- this.setItems(merged);
257
- this.notifyStoreListeners();
258
- }
259
-
260
- /**
261
- * Hydrate one mirrored change with real trees fetched on demand from the
262
- * device via the adapter's `getChangeDetail`. Remote-mirror (desktop) only.
263
- */
264
- hydrateChange(id, patch) {
265
- this.hydrateById(id, patch);
266
- }
267
-
268
- /**
269
- * Hydrate one mirrored store's currentState fetched on demand from the
270
- * device via the adapter's `getStoreState`. Remote-mirror (desktop) only.
271
- */
272
- hydrateStoreState(storeName, currentState) {
273
- const store = this.stores.get(storeName);
274
- if (!store) return;
275
- this.stores.set(storeName, {
276
- ...store,
277
- api: {
278
- ...store.api,
279
- getState: () => currentState
280
- }
281
- });
282
- this.notifyStoreListeners();
283
- }
284
-
285
- // ---- Store Registry ----
286
-
287
- registerStore(name, api, options) {
288
- if (this.stores.has(name)) return;
289
- const storeInfo = {
290
- name,
291
- api,
292
- stateChangeCount: 0,
293
- isPersisted: options?.isPersisted ?? false,
294
- persistName: options?.persistName,
295
- rehydrate: options?.rehydrate,
296
- color: getStoreColor(name)
297
- };
298
- this.stores.set(name, storeInfo);
299
- this.notifyStoreListeners();
300
- }
301
- unregisterStore(name) {
302
- this.stores.delete(name);
303
- this.notifyStoreListeners();
304
- }
305
- getStores() {
306
- return Array.from(this.stores.values());
307
- }
308
- getStore(name) {
309
- return this.stores.get(name);
310
- }
311
- getStoreColor(name) {
312
- return this.stores.get(name)?.color ?? getStoreColor(name);
313
- }
314
-
315
- // ---- Filtering ----
316
-
317
- filterStateChanges(filter) {
318
- let filtered = this.getAll();
319
- if (filter.searchText) {
320
- const search = filter.searchText.toLowerCase();
321
- filtered = filtered.filter(c => c.storeName.toLowerCase().includes(search) || c.partialPreview.toLowerCase().includes(search) || c.changedKeys.some(k => k.toLowerCase().includes(search)));
322
- }
323
- if (filter.storeNames && filter.storeNames.length > 0) {
324
- filtered = filtered.filter(c => filter.storeNames.includes(c.storeName));
325
- }
326
- if (filter.onlyWithChanges) {
327
- filtered = filtered.filter(c => c.hasStateChange);
328
- }
329
- return filtered;
330
- }
331
-
332
- // ---- Stats ----
333
-
334
- getStats() {
335
- const total = this.items.length;
336
- const withChanges = this.items.filter(c => c.hasStateChange).length;
337
- const storeCount = this.stores.size;
338
- const durations = this.items.filter(c => c.duration !== undefined).map(c => c.duration);
339
- const avgDuration = durations.length > 0 ? durations.reduce((sum, d) => sum + d, 0) / durations.length : 0;
340
- return {
341
- totalChanges: total,
342
- changesWithStateChange: withChanges,
343
- changesWithoutStateChange: total - withChanges,
344
- storeCount,
345
- averageDuration: Math.round(avgDuration * 100) / 100
346
- };
347
- }
348
- getUniqueStoreNames() {
349
- return Array.from(this.stores.keys()).sort();
350
- }
351
-
352
- // ---- Enable / Disable ----
353
-
354
- setMaxChanges(max) {
355
- this.setMax(max);
356
- }
357
-
358
- // ---- Subscriptions ----
359
-
360
- subscribeToStores(listener) {
361
- this.storeListeners.add(listener);
362
- return () => {
363
- this.storeListeners.delete(listener);
364
- };
365
- }
366
- notifyStoreListeners() {
367
- const stores = this.getStores();
368
- this.storeListeners.forEach(listener => listener(stores));
369
- }
370
- }
371
- export const zustandStateStore = new ZustandStateStore();
1
+ "use strict";import{ChangeLog,entityColor,formatValuePreview,shallowDiffSummary}from"@buoy-gg/shared-ui";const STORE_COLORS={counter:"#10B981",auth:"#8B5CF6",user:"#3B82F6",cart:"#EC4899",app:"#6366F1",ui:"#F59E0B",settings:"#14B8A6",theme:"#06B6D4",navigation:"#F97316",form:"#EF4444"};function getStoreColor(t){return entityColor(t,STORE_COLORS)}function formatPartialPreview(t,e=40){return formatValuePreview(t,{maxLength:e,undefinedLabel:"",functionLabel:"(updater fn)"})}class ZustandStateStore extends ChangeLog{stores=new Map;storeListeners=new Set;remoteSetStateHandler=null;addStateChange(t){if(!this.canRecord())return;const{storeName:e,partial:s,replace:r,prevState:a,nextState:o,duration:n,category:i,isPersisted:h=!1}=t,u=a!==o,{summary:S,changedKeys:c,changedCount:g}=shallowDiffSummary(a,o),l=formatPartialPreview(s),d=(n??0)>16,m=i??(r?"replace":"setState"),f={id:this.nextId(),storeName:e,timestamp:Date.now(),prevState:a,nextState:o,partial:s,duration:n,hasStateChange:u,replace:r,category:m,changedKeys:c,changedKeysCount:g,diffSummary:S,partialPreview:l,isSlowUpdate:d,isPersisted:h};this.push(f);const C=this.stores.get(e);C&&C.stateChangeCount++,this.notifyListeners()}getStateChanges(){return this.getAll()}getStateChangeById(t){return this.getById(t)}clearStateChanges(){for(const t of this.stores.values())t.stateChangeCount=0;this.clear(),this.notifyStoreListeners()}replaceStateChanges(t){if(!this.getEnabled())return;for(const t of this.stores.values())t.stateChangeCount=0;const e=t.slice(0,this.max);for(const t of e){const e=this.stores.get(t.storeName);e&&e.stateChangeCount++}this.setItems(e),this.notifyStoreListeners()}getStoreSnapshots(){return Array.from(this.stores.values()).map(t=>{let e;try{e=t.api.getState()}catch{e=void 0}return{name:t.name,stateChangeCount:t.stateChangeCount,isPersisted:t.isPersisted,persistName:t.persistName,canRehydrate:"function"==typeof t.rehydrate,color:t.color,currentState:e}})}setRemoteSetStateHandler(t){this.remoteSetStateHandler=t}replaceFromSnapshot(t,e){if(!this.getEnabled())return;const s=new Map;for(const t of this.items){const e=t.prevState;e&&!0===e.__buoyStateOnDevice||s.set(t.id,t)}const r=t.slice(0,this.max).map(t=>{const e=s.get(t.id),r=t.prevState;return e&&!0===r?.__buoyStateOnDevice?{...t,prevState:e.prevState,nextState:e.nextState,partial:e.partial}:t}),a=new Map;for(const[t,e]of this.stores)try{const s=e.api.getState();s&&!0===s.__buoyStateOnDevice||a.set(t,s)}catch{}this.stores=new Map(e.map(t=>{const e=t.currentState,s=a.get(t.name),r=void 0!==s&&!0===e?.__buoyStateOnDevice?s:t.currentState;return[t.name,{name:t.name,api:{getState:()=>r,setState:(e,s)=>{this.remoteSetStateHandler?.(t.name,e,s)},subscribe:()=>()=>{}},stateChangeCount:t.stateChangeCount,isPersisted:t.isPersisted,persistName:t.persistName,color:t.color}]})),this.setItems(r),this.notifyStoreListeners()}hydrateChange(t,e){this.hydrateById(t,e)}hydrateStoreState(t,e){const s=this.stores.get(t);s&&(this.stores.set(t,{...s,api:{...s.api,getState:()=>e}}),this.notifyStoreListeners())}registerStore(t,e,s){if(this.stores.has(t))return;const r={name:t,api:e,stateChangeCount:0,isPersisted:s?.isPersisted??!1,persistName:s?.persistName,rehydrate:s?.rehydrate,color:getStoreColor(t)};this.stores.set(t,r),this.notifyStoreListeners()}unregisterStore(t){this.stores.delete(t),this.notifyStoreListeners()}getStores(){return Array.from(this.stores.values())}getStore(t){return this.stores.get(t)}getStoreColor(t){return this.stores.get(t)?.color??getStoreColor(t)}filterStateChanges(t){let e=this.getAll();if(t.searchText){const s=t.searchText.toLowerCase();e=e.filter(t=>t.storeName.toLowerCase().includes(s)||t.partialPreview.toLowerCase().includes(s)||t.changedKeys.some(t=>t.toLowerCase().includes(s)))}return t.storeNames&&t.storeNames.length>0&&(e=e.filter(e=>t.storeNames.includes(e.storeName))),t.onlyWithChanges&&(e=e.filter(t=>t.hasStateChange)),e}getStats(){const t=this.items.length,e=this.items.filter(t=>t.hasStateChange).length,s=this.stores.size,r=this.items.filter(t=>void 0!==t.duration).map(t=>t.duration),a=r.length>0?r.reduce((t,e)=>t+e,0)/r.length:0;return{totalChanges:t,changesWithStateChange:e,changesWithoutStateChange:t-e,storeCount:s,averageDuration:Math.round(100*a)/100}}getUniqueStoreNames(){return Array.from(this.stores.keys()).sort()}setMaxChanges(t){this.setMax(t)}subscribeToStores(t){return this.storeListeners.add(t),()=>{this.storeListeners.delete(t)}}notifyStoreListeners(){const t=this.getStores();this.storeListeners.forEach(e=>e(t))}}export const zustandStateStore=new ZustandStateStore;