cogsbox-state 0.5.465 → 0.5.467

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.
@@ -1,601 +1,596 @@
1
1
  "use client";
2
- import { jsx as ne, Fragment as Ne } from "react/jsx-runtime";
3
- import { memo as $e, useState as J, useRef as B, useCallback as ae, useEffect as q, useLayoutEffect as ie, useMemo as we, createElement as Me, startTransition as je } from "react";
4
- import { transformStateFunc as Fe, isFunction as X, isDeepEqual as oe, isArray as Le, getDifferences as xe } from "./utility.js";
5
- import { ValidationWrapper as _e } from "./Functions.jsx";
6
- import Re from "superjson";
7
- import { v4 as ee } from "uuid";
8
- import { getGlobalStore as I, formRefStore as Ie } from "./store.js";
9
- import { useCogsConfig as ke } from "./CogsStateClient.jsx";
10
- import { useInView as He } from "react-intersection-observer";
2
+ import { jsx as ie, Fragment as Ce } from "react/jsx-runtime";
3
+ import { useState as K, useRef as L, useEffect as W, useCallback as pe, useLayoutEffect as ce, useMemo as we, createElement as Ie, startTransition as De } from "react";
4
+ import { transformStateFunc as Ue, isFunction as z, isDeepEqual as ae, isArray as Fe, getDifferences as $e } from "./utility.js";
5
+ import { ValidationWrapper as Ne, FormElementWrapper as Oe, MemoizedCogsItemWrapper as je } from "./Components.jsx";
6
+ import xe from "superjson";
7
+ import { v4 as X } from "uuid";
8
+ import { getGlobalStore as T, formRefStore as Ee } from "./store.js";
9
+ import { useCogsConfig as Ve } from "./CogsStateClient.jsx";
11
10
  const {
12
11
  getInitialOptions: G,
13
- updateInitialStateGlobal: Pe,
12
+ updateInitialStateGlobal: ke,
14
13
  // ALIAS THE NEW FUNCTIONS TO THE OLD NAMES
15
- getShadowMetadata: D,
16
- setShadowMetadata: x,
17
- getShadowValue: F,
18
- initializeShadowState: ce,
19
- updateShadowAtPath: Be,
20
- insertShadowArrayElement: Ce,
21
- removeShadowArrayElement: We,
22
- getSelectedIndex: kt,
23
- setInitialStateOptions: de,
24
- setServerStateUpdate: qe,
25
- markAsDirty: fe,
26
- registerComponent: ze,
27
- unregisterComponent: Ge,
28
- addPathComponent: Je,
29
- clearSelectedIndexesForState: Ze,
30
- addStateLog: Ye,
31
- setSyncInfo: Qe,
32
- clearSelectedIndex: Xe,
33
- getSyncInfo: Ke,
34
- notifyPathSubscribers: De,
35
- subscribeToPath: et
14
+ getShadowMetadata: V,
15
+ setShadowMetadata: J,
16
+ getShadowValue: R,
17
+ initializeShadowState: oe,
18
+ updateShadowAtPath: Re,
19
+ insertShadowArrayElement: Le,
20
+ insertManyShadowArrayElements: qe,
21
+ removeShadowArrayElement: Be,
22
+ getSelectedIndex: Tt,
23
+ setInitialStateOptions: le,
24
+ setServerStateUpdate: We,
25
+ markAsDirty: ue,
26
+ registerComponent: It,
27
+ unregisterComponent: bt,
28
+ addPathComponent: Ge,
29
+ clearSelectedIndexesForState: He,
30
+ addStateLog: ze,
31
+ setSyncInfo: Je,
32
+ clearSelectedIndex: Ze,
33
+ getSyncInfo: Ye,
34
+ notifyPathSubscribers: Qe,
35
+ subscribeToPath: Et
36
36
  // Note: The old functions are no longer imported under their original names
37
- } = I.getState();
38
- function Z(e, t, c) {
39
- const n = D(e, t);
40
- if (!!!n?.arrayKeys)
41
- return { isArray: !1, value: I.getState().getShadowValue(e, t), keys: [] };
42
- const s = t.join("."), u = c?.arrayViews?.[s] ?? n.arrayKeys;
43
- return Array.isArray(u) && u.length === 0 ? { isArray: !0, value: [], keys: [] } : { isArray: !0, value: I.getState().getShadowValue(e, t, u), keys: u ?? [] };
37
+ } = T.getState();
38
+ function B(e, r, l) {
39
+ const a = V(e, r);
40
+ if (!!!a?.arrayKeys)
41
+ return { isArray: !1, value: T.getState().getShadowValue(e, r), keys: [] };
42
+ const s = r.length > 0 ? r.join(".") : "root", c = l?.arrayViews?.[s] ?? a.arrayKeys;
43
+ return Array.isArray(c) && c.length === 0 ? { isArray: !0, value: [], keys: [] } : { isArray: !0, value: T.getState().getShadowValue(e, r, c), keys: c ?? [] };
44
44
  }
45
- function ve(e, t, c) {
46
- for (let n = 0; n < e.length; n++)
47
- if (c(e[n], n)) {
48
- const d = t[n];
49
- if (d)
50
- return { key: d, index: n, value: e[n] };
45
+ function he(e, r, l) {
46
+ for (let a = 0; a < e.length; a++)
47
+ if (l(e[a], a)) {
48
+ const S = r[a];
49
+ if (S)
50
+ return { key: S, index: a, value: e[a] };
51
51
  }
52
52
  return null;
53
53
  }
54
- function pe(e, t) {
55
- const c = G(e) || {};
56
- de(e, {
57
- ...c,
58
- ...t
54
+ function ve(e, r) {
55
+ const l = G(e) || {};
56
+ le(e, {
57
+ ...l,
58
+ ...r
59
59
  });
60
60
  }
61
- function Ee({
61
+ function Me({
62
62
  stateKey: e,
63
- options: t,
64
- initialOptionsPart: c
63
+ options: r,
64
+ initialOptionsPart: l
65
65
  }) {
66
- const n = G(e) || {}, s = { ...c[e] || {}, ...n };
67
- let u = !1;
68
- if (t)
69
- for (const i in t)
70
- s.hasOwnProperty(i) ? (i == "localStorage" && t[i] && s[i].key !== t[i]?.key && (u = !0, s[i] = t[i]), i == "defaultState" && t[i] && s[i] !== t[i] && !oe(s[i], t[i]) && (u = !0, s[i] = t[i])) : (u = !0, s[i] = t[i]);
71
- s.syncOptions && (!t || !t.hasOwnProperty("syncOptions")) && (u = !0), u && de(e, s);
66
+ const a = G(e) || {}, s = { ...l[e] || {}, ...a };
67
+ let c = !1;
68
+ if (r)
69
+ for (const i in r)
70
+ s.hasOwnProperty(i) ? (i == "localStorage" && r[i] && s[i].key !== r[i]?.key && (c = !0, s[i] = r[i]), i == "defaultState" && r[i] && s[i] !== r[i] && !ae(s[i], r[i]) && (c = !0, s[i] = r[i])) : (c = !0, s[i] = r[i]);
71
+ s.syncOptions && (!r || !r.hasOwnProperty("syncOptions")) && (c = !0), c && le(e, s);
72
72
  }
73
- function Pt(e, { formElements: t, validation: c }) {
74
- return { initialState: e, formElements: t, validation: c };
73
+ function Mt(e, { formElements: r, validation: l }) {
74
+ return { initialState: e, formElements: r, validation: l };
75
75
  }
76
- const tt = (e, t) => {
77
- let c = e;
78
- const [n, d] = Fe(c);
79
- t?.__fromSyncSchema && t?.__syncNotifications && I.getState().setInitialStateOptions("__notifications", t.__syncNotifications), t?.__fromSyncSchema && t?.__apiParamsMap && I.getState().setInitialStateOptions("__apiParamsMap", t.__apiParamsMap), Object.keys(n).forEach((i) => {
80
- let S = d[i] || {};
81
- const r = {
82
- ...S
76
+ const Xe = (e, r) => {
77
+ let l = e;
78
+ const [a, S] = Ue(l);
79
+ r?.__fromSyncSchema && r?.__syncNotifications && T.getState().setInitialStateOptions("__notifications", r.__syncNotifications), r?.__fromSyncSchema && r?.__apiParamsMap && T.getState().setInitialStateOptions("__apiParamsMap", r.__apiParamsMap), Object.keys(a).forEach((i) => {
80
+ let f = S[i] || {};
81
+ const t = {
82
+ ...f
83
83
  };
84
- if (t?.formElements && (r.formElements = {
85
- ...t.formElements,
86
- ...S.formElements || {}
87
- }), t?.validation && (r.validation = {
88
- ...t.validation,
89
- ...S.validation || {}
90
- }, t.validation.key && !S.validation?.key && (r.validation.key = `${t.validation.key}.${i}`)), t?.__syncSchemas?.[i]?.schemas?.validation && (r.validation = {
91
- zodSchemaV4: t.__syncSchemas[i].schemas.validation,
92
- ...S.validation
93
- }), Object.keys(r).length > 0) {
94
- const l = G(i);
95
- l ? de(i, {
96
- ...l,
97
- ...r
98
- }) : de(i, r);
84
+ if (r?.formElements && (t.formElements = {
85
+ ...r.formElements,
86
+ ...f.formElements || {}
87
+ }), r?.validation && (t.validation = {
88
+ ...r.validation,
89
+ ...f.validation || {}
90
+ }, r.validation.key && !f.validation?.key && (t.validation.key = `${r.validation.key}.${i}`)), r?.__syncSchemas?.[i]?.schemas?.validation && (t.validation = {
91
+ zodSchemaV4: r.__syncSchemas[i].schemas.validation,
92
+ ...f.validation
93
+ }), Object.keys(t).length > 0) {
94
+ const u = G(i);
95
+ u ? le(i, {
96
+ ...u,
97
+ ...t
98
+ }) : le(i, t);
99
99
  }
100
- }), Object.keys(n).forEach((i) => {
101
- ce(i, n[i]);
102
- }), console.log("new stateObject ", I.getState().shadowStateStore);
103
- const s = (i, S) => {
104
- const [r] = J(S?.componentId ?? ee());
105
- Ee({
100
+ }), Object.keys(a).forEach((i) => {
101
+ oe(i, a[i]);
102
+ });
103
+ const s = (i, f) => {
104
+ const [t] = K(f?.componentId ?? X());
105
+ Me({
106
106
  stateKey: i,
107
- options: S,
108
- initialOptionsPart: d
107
+ options: f,
108
+ initialOptionsPart: S
109
109
  });
110
- const l = F(i, []) || n[i], M = S?.modifyState ? S.modifyState(l) : l;
111
- return ft(M, {
110
+ const u = R(i, []) || a[i], I = f?.modifyState ? f.modifyState(u) : u;
111
+ return lt(I, {
112
112
  stateKey: i,
113
- syncUpdate: S?.syncUpdate,
114
- componentId: r,
115
- localStorage: S?.localStorage,
116
- middleware: S?.middleware,
117
- reactiveType: S?.reactiveType,
118
- reactiveDeps: S?.reactiveDeps,
119
- defaultState: S?.defaultState,
120
- dependencies: S?.dependencies,
121
- serverState: S?.serverState,
122
- syncOptions: S?.syncOptions,
123
- __useSync: t?.__useSync
113
+ syncUpdate: f?.syncUpdate,
114
+ componentId: t,
115
+ localStorage: f?.localStorage,
116
+ middleware: f?.middleware,
117
+ reactiveType: f?.reactiveType,
118
+ reactiveDeps: f?.reactiveDeps,
119
+ defaultState: f?.defaultState,
120
+ dependencies: f?.dependencies,
121
+ serverState: f?.serverState,
122
+ syncOptions: f?.syncOptions,
123
+ __useSync: r?.__useSync
124
124
  });
125
125
  };
126
- function u(i, S) {
127
- Ee({ stateKey: i, options: S, initialOptionsPart: d }), S.localStorage && nt(i, S), be(i);
126
+ function c(i, f) {
127
+ Me({ stateKey: i, options: f, initialOptionsPart: S }), f.localStorage && et(i, f), be(i);
128
128
  }
129
- return { useCogsState: s, setCogsOptions: u };
129
+ return { useCogsState: s, setCogsOptions: c };
130
130
  };
131
- function Ct(e, t) {
132
- const c = e.schemas, n = {}, d = {};
133
- for (const s in c) {
134
- const u = c[s];
135
- n[s] = u?.schemas?.defaultValues || {}, u?.api?.queryData?._paramType && (d[s] = u.api.queryData._paramType);
131
+ function At(e, r) {
132
+ const l = e.schemas, a = {}, S = {};
133
+ for (const s in l) {
134
+ const c = l[s];
135
+ a[s] = c?.schemas?.defaultValues || {}, c?.api?.queryData?._paramType && (S[s] = c.api.queryData._paramType);
136
136
  }
137
- return tt(n, {
137
+ return Xe(a, {
138
138
  __fromSyncSchema: !0,
139
139
  __syncNotifications: e.notifications,
140
- __apiParamsMap: d,
141
- __useSync: t,
142
- __syncSchemas: c
140
+ __apiParamsMap: S,
141
+ __useSync: r,
142
+ __syncSchemas: l
143
143
  });
144
144
  }
145
- const rt = (e, t, c, n, d) => {
146
- c?.log && console.log(
145
+ const Ke = (e, r, l, a, S) => {
146
+ l?.log && console.log(
147
147
  "saving to localstorage",
148
- t,
149
- c.localStorage?.key,
150
- n
148
+ r,
149
+ l.localStorage?.key,
150
+ a
151
151
  );
152
- const s = X(c?.localStorage?.key) ? c.localStorage?.key(e) : c?.localStorage?.key;
153
- if (s && n) {
154
- const u = `${n}-${t}-${s}`;
152
+ const s = z(l?.localStorage?.key) ? l.localStorage?.key(e) : l?.localStorage?.key;
153
+ if (s && a) {
154
+ const c = `${a}-${r}-${s}`;
155
155
  let i;
156
156
  try {
157
- i = me(u)?.lastSyncedWithServer;
157
+ i = Se(c)?.lastSyncedWithServer;
158
158
  } catch {
159
159
  }
160
- const S = D(t, []), r = {
160
+ const f = V(r, []), t = {
161
161
  state: e,
162
162
  lastUpdated: Date.now(),
163
163
  lastSyncedWithServer: i,
164
- stateSource: S?.stateSource,
165
- baseServerState: S?.baseServerState
166
- }, l = Re.serialize(r);
164
+ stateSource: f?.stateSource,
165
+ baseServerState: f?.baseServerState
166
+ }, u = xe.serialize(t);
167
167
  window.localStorage.setItem(
168
- u,
169
- JSON.stringify(l.json)
168
+ c,
169
+ JSON.stringify(u.json)
170
170
  );
171
171
  }
172
- }, me = (e) => {
172
+ }, Se = (e) => {
173
173
  if (!e) return null;
174
174
  try {
175
- const t = window.localStorage.getItem(e);
176
- return t ? JSON.parse(t) : null;
177
- } catch (t) {
178
- return console.error("Error loading from localStorage:", t), null;
175
+ const r = window.localStorage.getItem(e);
176
+ return r ? JSON.parse(r) : null;
177
+ } catch (r) {
178
+ return console.error("Error loading from localStorage:", r), null;
179
179
  }
180
- }, nt = (e, t) => {
181
- const c = F(e, []), { sessionId: n } = ke(), d = X(t?.localStorage?.key) ? t.localStorage.key(c) : t?.localStorage?.key;
182
- if (d && n) {
183
- const s = me(
184
- `${n}-${e}-${d}`
180
+ }, et = (e, r) => {
181
+ const l = R(e, []), { sessionId: a } = Ve(), S = z(r?.localStorage?.key) ? r.localStorage.key(l) : r?.localStorage?.key;
182
+ if (S && a) {
183
+ const s = Se(
184
+ `${a}-${e}-${S}`
185
185
  );
186
186
  if (s && s.lastUpdated > (s.lastSyncedWithServer || 0))
187
187
  return be(e), !0;
188
188
  }
189
189
  return !1;
190
190
  }, be = (e) => {
191
- const t = D(e, []);
192
- if (!t) return;
193
- const c = /* @__PURE__ */ new Set();
194
- t?.components?.forEach((n) => {
195
- (n ? Array.isArray(n.reactiveType) ? n.reactiveType : [n.reactiveType || "component"] : null)?.includes("none") || c.add(() => n.forceUpdate());
191
+ const r = V(e, []);
192
+ if (!r) return;
193
+ const l = /* @__PURE__ */ new Set();
194
+ r?.components?.forEach((a) => {
195
+ (a ? Array.isArray(a.reactiveType) ? a.reactiveType : [a.reactiveType || "component"] : null)?.includes("none") || l.add(() => a.forceUpdate());
196
196
  }), queueMicrotask(() => {
197
- c.forEach((n) => n());
197
+ l.forEach((a) => a());
198
198
  });
199
199
  };
200
- function ge(e, t, c, n) {
201
- const d = D(e, t);
202
- if (x(e, t, {
203
- ...d,
200
+ function de(e, r, l, a) {
201
+ const S = V(e, r);
202
+ if (J(e, r, {
203
+ ...S,
204
204
  isDirty: !1,
205
205
  stateSource: "server",
206
- lastServerSync: n || Date.now()
207
- }), Array.isArray(c)) {
208
- const s = D(e, t);
209
- s?.arrayKeys && s.arrayKeys.forEach((u, i) => {
210
- const S = [...t, u], r = c[i];
211
- r !== void 0 && ge(
206
+ lastServerSync: a || Date.now()
207
+ }), Array.isArray(l)) {
208
+ const s = V(e, r);
209
+ s?.arrayKeys && s.arrayKeys.forEach((c, i) => {
210
+ const f = [...r, c], t = l[i];
211
+ t !== void 0 && de(
212
212
  e,
213
- S,
214
- r,
215
- n
213
+ f,
214
+ t,
215
+ a
216
216
  );
217
217
  });
218
- } else c && typeof c == "object" && c.constructor === Object && Object.keys(c).forEach((s) => {
219
- const u = [...t, s], i = c[s];
220
- ge(e, u, i, n);
218
+ } else l && typeof l == "object" && l.constructor === Object && Object.keys(l).forEach((s) => {
219
+ const c = [...r, s], i = l[s];
220
+ de(e, c, i, a);
221
221
  });
222
222
  }
223
- let Se = [], Te = !1;
224
- function ot() {
225
- Te || (Te = !0, queueMicrotask(ut));
223
+ let fe = [], Te = !1;
224
+ function tt() {
225
+ Te || (Te = !0, queueMicrotask(it));
226
226
  }
227
- function at(e, t, c) {
228
- const n = I.getState().getShadowValue(e, t), d = X(c) ? c(n) : c;
229
- Be(e, t, d), fe(e, t, { bubble: !0 });
230
- const s = D(e, t);
227
+ function rt(e, r, l) {
228
+ const a = T.getState().getShadowValue(e, r), S = z(l) ? l(a) : l;
229
+ Re(e, r, S), ue(e, r, { bubble: !0 });
230
+ const s = V(e, r);
231
231
  return {
232
232
  type: "update",
233
- oldValue: n,
234
- newValue: d,
233
+ oldValue: a,
234
+ newValue: S,
235
235
  shadowMeta: s
236
236
  };
237
237
  }
238
- function st(e, t) {
239
- e?.signals?.length && e.signals.forEach(({ parentId: c, position: n, effect: d }) => {
240
- const s = document.querySelector(`[data-parent-id="${c}"]`);
238
+ function nt(e, r) {
239
+ e?.signals?.length && e.signals.forEach(({ parentId: l, position: a, effect: S }) => {
240
+ const s = document.querySelector(`[data-parent-id="${l}"]`);
241
241
  if (!s) return;
242
- const u = Array.from(s.childNodes);
243
- if (!u[n]) return;
244
- let i = t;
245
- if (d && t !== null)
242
+ const c = Array.from(s.childNodes);
243
+ if (!c[a]) return;
244
+ let i = r;
245
+ if (S && r !== null)
246
246
  try {
247
- i = new Function("state", `return (${d})(state)`)(
248
- t
247
+ i = new Function("state", `return (${S})(state)`)(
248
+ r
249
249
  );
250
- } catch (S) {
251
- console.error("Error evaluating effect function:", S);
250
+ } catch (f) {
251
+ console.error("Error evaluating effect function:", f);
252
252
  }
253
- i !== null && typeof i == "object" && (i = JSON.stringify(i)), u[n].textContent = String(i ?? "");
253
+ i !== null && typeof i == "object" && (i = JSON.stringify(i)), c[a].textContent = String(i ?? "");
254
254
  });
255
255
  }
256
- function it(e, t, c) {
257
- const n = D(e, []);
258
- if (!n?.components)
256
+ function at(e, r, l) {
257
+ const a = V(e, []);
258
+ if (!a?.components)
259
259
  return /* @__PURE__ */ new Set();
260
- const d = /* @__PURE__ */ new Set();
261
- if (c.type === "update") {
262
- let s = [...t];
260
+ const S = /* @__PURE__ */ new Set();
261
+ if (l.type === "update") {
262
+ let s = [...r];
263
263
  for (; ; ) {
264
- const u = D(e, s);
265
- if (u?.pathComponents && u.pathComponents.forEach((i) => {
266
- const S = n.components?.get(i);
267
- S && ((Array.isArray(S.reactiveType) ? S.reactiveType : [S.reactiveType || "component"]).includes("none") || d.add(S));
264
+ const c = V(e, s);
265
+ if (c?.pathComponents && c.pathComponents.forEach((i) => {
266
+ const f = a.components?.get(i);
267
+ f && ((Array.isArray(f.reactiveType) ? f.reactiveType : [f.reactiveType || "component"]).includes("none") || S.add(f));
268
268
  }), s.length === 0) break;
269
269
  s.pop();
270
270
  }
271
- c.newValue && typeof c.newValue == "object" && !Le(c.newValue) && xe(c.newValue, c.oldValue).forEach((i) => {
272
- const S = i.split("."), r = [...t, ...S], l = D(e, r);
273
- l?.pathComponents && l.pathComponents.forEach((M) => {
274
- const _ = n.components?.get(M);
275
- _ && ((Array.isArray(_.reactiveType) ? _.reactiveType : [_.reactiveType || "component"]).includes("none") || d.add(_));
271
+ l.newValue && typeof l.newValue == "object" && !Fe(l.newValue) && $e(l.newValue, l.oldValue).forEach((i) => {
272
+ const f = i.split("."), t = [...r, ...f], u = V(e, t);
273
+ u?.pathComponents && u.pathComponents.forEach((I) => {
274
+ const U = a.components?.get(I);
275
+ U && ((Array.isArray(U.reactiveType) ? U.reactiveType : [U.reactiveType || "component"]).includes("none") || S.add(U));
276
276
  });
277
277
  });
278
- } else if (c.type === "insert" || c.type === "cut") {
279
- const s = c.type === "insert" ? t : t.slice(0, -1), u = D(e, s);
280
- u?.pathComponents && u.pathComponents.forEach((i) => {
281
- const S = n.components?.get(i);
282
- S && d.add(S);
278
+ } else if (l.type === "insert" || l.type === "cut") {
279
+ const s = l.type === "insert" ? r : r.slice(0, -1), c = V(e, s);
280
+ c?.pathComponents && c.pathComponents.forEach((i) => {
281
+ const f = a.components?.get(i);
282
+ f && S.add(f);
283
283
  });
284
284
  }
285
- return n.components.forEach((s, u) => {
286
- if (d.has(s))
285
+ return a.components.forEach((s, c) => {
286
+ if (S.has(s))
287
287
  return;
288
288
  const i = Array.isArray(s.reactiveType) ? s.reactiveType : [s.reactiveType || "component"];
289
289
  if (i.includes("all"))
290
- d.add(s);
290
+ S.add(s);
291
291
  else if (i.includes("deps") && s.depsFunction) {
292
- const S = F(e, []), r = s.depsFunction(S);
293
- (r === !0 || Array.isArray(r) && !oe(s.prevDeps, r)) && (s.prevDeps = r, d.add(s));
292
+ const f = R(e, []), t = s.depsFunction(f);
293
+ (t === !0 || Array.isArray(t) && !ae(s.prevDeps, t)) && (s.prevDeps = t, S.add(s));
294
294
  }
295
- }), d;
295
+ }), S;
296
296
  }
297
- function ct(e, t, c) {
298
- let n;
299
- if (X(c)) {
300
- const { value: s } = K(e, t);
301
- n = c({ state: s, uuid: ee() });
297
+ function ot(e, r, l) {
298
+ let a;
299
+ if (z(l)) {
300
+ const { value: s } = Q(e, r);
301
+ a = l({ state: s, uuid: X() });
302
302
  } else
303
- n = c;
304
- Ce(e, t, n), fe(e, t, { bubble: !0 });
305
- const d = D(e, t);
306
- if (d?.arrayKeys) {
307
- const s = d.arrayKeys[d.arrayKeys.length - 1];
303
+ a = l;
304
+ Le(e, r, a), ue(e, r, { bubble: !0 });
305
+ const S = V(e, r);
306
+ if (S?.arrayKeys) {
307
+ const s = S.arrayKeys[S.arrayKeys.length - 1];
308
308
  if (s) {
309
- const u = s.split(".").slice(1);
310
- fe(e, u, { bubble: !1 });
309
+ const c = s.split(".").slice(1);
310
+ ue(e, c, { bubble: !1 });
311
311
  }
312
312
  }
313
- return { type: "insert", newValue: n, shadowMeta: d };
313
+ return { type: "insert", newValue: a, shadowMeta: S };
314
314
  }
315
- function lt(e, t) {
316
- const c = t.slice(0, -1), n = F(e, t);
317
- return We(e, t), fe(e, c, { bubble: !0 }), { type: "cut", oldValue: n, parentPath: c };
315
+ function st(e, r) {
316
+ const l = r.slice(0, -1), a = R(e, r);
317
+ return Be(e, r), ue(e, l, { bubble: !0 }), { type: "cut", oldValue: a, parentPath: l };
318
318
  }
319
- function ut() {
320
- const e = /* @__PURE__ */ new Set(), t = [], c = [];
321
- for (const n of Se) {
322
- if (n.status && n.updateType) {
323
- c.push(n);
319
+ function it() {
320
+ const e = /* @__PURE__ */ new Set(), r = [], l = [];
321
+ for (const a of fe) {
322
+ if (a.status && a.updateType) {
323
+ l.push(a);
324
324
  continue;
325
325
  }
326
- const d = n, s = d.type === "cut" ? null : d.newValue;
327
- d.shadowMeta?.signals?.length > 0 && t.push({ shadowMeta: d.shadowMeta, displayValue: s }), it(
328
- d.stateKey,
329
- d.path,
330
- d
326
+ const S = a, s = S.type === "cut" ? null : S.newValue;
327
+ S.shadowMeta?.signals?.length > 0 && r.push({ shadowMeta: S.shadowMeta, displayValue: s }), at(
328
+ S.stateKey,
329
+ S.path,
330
+ S
331
331
  ).forEach((i) => {
332
332
  e.add(i);
333
333
  });
334
334
  }
335
- c.length > 0 && Ye(c), t.forEach(({ shadowMeta: n, displayValue: d }) => {
336
- st(n, d);
337
- }), e.forEach((n) => {
338
- n.forceUpdate();
339
- }), Se = [], Te = !1;
335
+ l.length > 0 && ze(l), r.forEach(({ shadowMeta: a, displayValue: S }) => {
336
+ nt(a, S);
337
+ }), e.forEach((a) => {
338
+ a.forceUpdate();
339
+ }), fe = [], Te = !1;
340
340
  }
341
- function dt(e, t, c, n) {
342
- return (s, u, i, S) => {
343
- d(e, u, s, i);
341
+ function ct(e, r, l, a) {
342
+ return (s, c, i, f) => {
343
+ S(e, c, s, i);
344
344
  };
345
- function d(s, u, i, S) {
346
- let r;
347
- switch (S.updateType) {
345
+ function S(s, c, i, f) {
346
+ let t;
347
+ switch (f.updateType) {
348
348
  case "update":
349
- r = at(s, u, i);
349
+ t = rt(s, c, i);
350
350
  break;
351
351
  case "insert":
352
- r = ct(s, u, i);
352
+ t = ot(s, c, i);
353
353
  break;
354
354
  case "cut":
355
- r = lt(s, u);
355
+ t = st(s, c);
356
356
  break;
357
357
  }
358
- r.stateKey = s, r.path = u, Se.push(r), ot();
359
- const l = {
358
+ t.stateKey = s, t.path = c, fe.push(t), tt();
359
+ const u = {
360
360
  timeStamp: Date.now(),
361
361
  stateKey: s,
362
- path: u,
363
- updateType: S.updateType,
362
+ path: c,
363
+ updateType: f.updateType,
364
364
  status: "new",
365
- oldValue: r.oldValue,
366
- newValue: r.newValue ?? null
365
+ oldValue: t.oldValue,
366
+ newValue: t.newValue ?? null
367
367
  };
368
- Se.push(l), r.newValue !== void 0 && rt(
369
- r.newValue,
368
+ fe.push(u), t.newValue !== void 0 && Ke(
369
+ t.newValue,
370
370
  s,
371
- n.current,
372
- c
373
- ), n.current?.middleware && n.current.middleware({ update: l }), S.sync !== !1 && t.current?.connected && t.current.updateState({ operation: l });
371
+ a.current,
372
+ l
373
+ ), a.current?.middleware && a.current.middleware({ update: u }), f.sync !== !1 && r.current?.connected && r.current.updateState({ operation: u });
374
374
  }
375
375
  }
376
- function ft(e, {
377
- stateKey: t,
378
- localStorage: c,
379
- formElements: n,
380
- reactiveDeps: d,
376
+ function lt(e, {
377
+ stateKey: r,
378
+ localStorage: l,
379
+ formElements: a,
380
+ reactiveDeps: S,
381
381
  reactiveType: s,
382
- componentId: u,
382
+ componentId: c,
383
383
  defaultState: i,
384
- syncUpdate: S,
385
- dependencies: r,
386
- serverState: l,
387
- __useSync: M
384
+ syncUpdate: f,
385
+ dependencies: t,
386
+ serverState: u,
387
+ __useSync: I
388
388
  } = {}) {
389
- const [_, C] = J({}), { sessionId: U } = ke();
390
- let j = !t;
391
- const [w] = J(t ?? ee()), Y = B(u ?? ee()), f = B(
389
+ const [U, O] = K({}), { sessionId: F } = Ve();
390
+ let x = !r;
391
+ const [w] = K(r ?? X()), ee = L(c ?? X()), m = L(
392
392
  null
393
393
  );
394
- f.current = G(w) ?? null, q(() => {
395
- if (S && S.stateKey === w && S.path?.[0]) {
396
- const m = `${S.stateKey}:${S.path.join(".")}`;
397
- Qe(m, {
398
- timeStamp: S.timeStamp,
399
- userId: S.userId
394
+ m.current = G(w) ?? null, W(() => {
395
+ if (f && f.stateKey === w && f.path?.[0]) {
396
+ const g = `${f.stateKey}:${f.path.join(".")}`;
397
+ Je(g, {
398
+ timeStamp: f.timeStamp,
399
+ userId: f.userId
400
400
  });
401
401
  }
402
- }, [S]);
403
- const R = ae(
404
- (m) => {
405
- const p = m ? { ...G(w), ...m } : G(w), T = p?.defaultState || i || e;
402
+ }, [f]);
403
+ const te = pe(
404
+ (g) => {
405
+ const p = g ? { ...G(w), ...g } : G(w), b = p?.defaultState || i || e;
406
406
  if (p?.serverState?.status === "success" && p?.serverState?.data !== void 0)
407
407
  return {
408
408
  value: p.serverState.data,
409
409
  source: "server",
410
410
  timestamp: p.serverState.timestamp || Date.now()
411
411
  };
412
- if (p?.localStorage?.key && U) {
413
- const E = X(p.localStorage.key) ? p.localStorage.key(T) : p.localStorage.key, b = me(
414
- `${U}-${w}-${E}`
412
+ if (p?.localStorage?.key && F) {
413
+ const M = z(p.localStorage.key) ? p.localStorage.key(b) : p.localStorage.key, A = Se(
414
+ `${F}-${w}-${M}`
415
415
  );
416
- if (b && b.lastUpdated > (p?.serverState?.timestamp || 0))
416
+ if (A && A.lastUpdated > (p?.serverState?.timestamp || 0))
417
417
  return {
418
- value: b.state,
418
+ value: A.state,
419
419
  source: "localStorage",
420
- timestamp: b.lastUpdated
420
+ timestamp: A.lastUpdated
421
421
  };
422
422
  }
423
423
  return {
424
- value: T || e,
424
+ value: b || e,
425
425
  source: "default",
426
426
  timestamp: Date.now()
427
427
  };
428
428
  },
429
- [w, i, e, U]
429
+ [w, i, e, F]
430
430
  );
431
- q(() => {
432
- qe(w, l);
433
- }, [l, w]), q(() => I.getState().subscribeToPath(w, (h) => {
434
- if (h?.type === "SERVER_STATE_UPDATE") {
435
- const p = h.serverState;
431
+ W(() => {
432
+ We(w, u);
433
+ }, [u, w]), W(() => T.getState().subscribeToPath(w, (y) => {
434
+ if (y?.type === "SERVER_STATE_UPDATE") {
435
+ const p = y.serverState;
436
436
  if (p?.status !== "success" || p.data === void 0)
437
437
  return;
438
- console.log(
439
- " SERVER_STATE_UPDATE received with data:",
440
- p
441
- ), pe(w, { serverState: p });
442
- const T = typeof p.merge == "object" ? p.merge : p.merge === !0 ? { strategy: "append" } : null, A = F(w, []), E = p.data;
443
- if (T && T.strategy === "append" && "key" in T && // Type guard for key
444
- Array.isArray(A) && Array.isArray(E)) {
445
- const b = T.key;
446
- if (!b) {
438
+ ve(w, { serverState: p });
439
+ const b = typeof p.merge == "object" ? p.merge : p.merge === !0 ? { strategy: "append" } : null, _ = R(w, []), M = p.data;
440
+ if (b && b.strategy === "append" && "key" in b && // Type guard for key
441
+ Array.isArray(_) && Array.isArray(M)) {
442
+ const A = b.key;
443
+ if (!A) {
447
444
  console.error(
448
445
  "CogsState: Merge strategy 'append' requires a 'key' field."
449
446
  );
450
447
  return;
451
448
  }
452
- console.log("SERVER_STATE_UPDATE 2");
453
- const N = new Set(
454
- A.map((W) => W[b])
455
- ), V = E.filter(
456
- (W) => !N.has(W[b])
449
+ const D = new Set(
450
+ _.map((N) => N[A])
451
+ ), E = M.filter(
452
+ (N) => !D.has(N[A])
457
453
  );
458
- V.length > 0 && V.forEach((W) => {
459
- Ce(w, [], W);
460
- });
461
- const O = F(w, []);
462
- ge(
454
+ E.length > 0 && qe(w, [], E);
455
+ const k = R(w, []);
456
+ de(
463
457
  w,
464
458
  [],
465
- O,
459
+ k,
466
460
  p.timestamp
467
461
  );
468
462
  } else
469
- ce(w, E), ge(
463
+ oe(w, M), de(
470
464
  w,
471
465
  [],
472
- E,
466
+ M,
473
467
  p.timestamp
474
468
  );
475
469
  }
476
- }), [w, R]), q(() => {
477
- const m = I.getState().getShadowMetadata(w, []);
478
- if (m && m.stateSource)
470
+ }), [w, te]), W(() => {
471
+ const g = T.getState().getShadowMetadata(w, []);
472
+ if (g && g.stateSource)
479
473
  return;
480
- const h = G(w), p = {
481
- syncEnabled: !!v && !!y,
482
- validationEnabled: !!(h?.validation?.zodSchemaV4 || h?.validation?.zodSchemaV3),
483
- localStorageEnabled: !!h?.localStorage?.key
474
+ const y = G(w), p = {
475
+ syncEnabled: !!v && !!h,
476
+ validationEnabled: !!(y?.validation?.zodSchemaV4 || y?.validation?.zodSchemaV3),
477
+ localStorageEnabled: !!y?.localStorage?.key
484
478
  };
485
- if (x(w, [], {
486
- ...m,
479
+ if (J(w, [], {
480
+ ...g,
487
481
  features: p
488
- }), h?.defaultState !== void 0 || i !== void 0) {
489
- const T = h?.defaultState || i;
490
- h?.defaultState || pe(w, {
491
- defaultState: T
482
+ }), y?.defaultState !== void 0 || i !== void 0) {
483
+ const b = y?.defaultState || i;
484
+ y?.defaultState || ve(w, {
485
+ defaultState: b
492
486
  });
493
- const { value: A, source: E, timestamp: b } = R();
494
- ce(w, A), x(w, [], {
495
- stateSource: E,
496
- lastServerSync: E === "server" ? b : void 0,
487
+ const { value: _, source: M, timestamp: A } = te();
488
+ oe(w, _), J(w, [], {
489
+ stateSource: M,
490
+ lastServerSync: M === "server" ? A : void 0,
497
491
  isDirty: !1,
498
- baseServerState: E === "server" ? A : void 0
492
+ baseServerState: M === "server" ? _ : void 0
499
493
  }), be(w);
500
494
  }
501
- }, [w, ...r || []]), ie(() => {
502
- j && pe(w, {
503
- formElements: n,
495
+ }, [w, ...t || []]), ce(() => {
496
+ x && ve(w, {
497
+ formElements: a,
504
498
  defaultState: i,
505
- localStorage: c,
506
- middleware: f.current?.middleware
499
+ localStorage: l,
500
+ middleware: m.current?.middleware
507
501
  });
508
- const m = `${w}////${Y.current}`, h = D(w, []), p = h?.components || /* @__PURE__ */ new Map();
509
- return p.set(m, {
510
- forceUpdate: () => C({}),
502
+ const g = `${w}////${ee.current}`, y = V(w, []), p = y?.components || /* @__PURE__ */ new Map();
503
+ return p.set(g, {
504
+ forceUpdate: () => O({}),
511
505
  reactiveType: s ?? ["component"],
512
506
  paths: /* @__PURE__ */ new Set(),
513
- depsFunction: d || void 0,
514
- deps: d ? d(F(w, [])) : [],
515
- prevDeps: d ? d(F(w, [])) : []
516
- }), x(w, [], {
517
- ...h,
507
+ depsFunction: S || void 0,
508
+ deps: S ? S(R(w, [])) : [],
509
+ prevDeps: S ? S(R(w, [])) : []
510
+ }), J(w, [], {
511
+ ...y,
518
512
  components: p
519
- }), C({}), () => {
520
- const T = D(w, []), A = T?.components?.get(m);
521
- A?.paths && A.paths.forEach((E) => {
522
- const N = E.split(".").slice(1), V = I.getState().getShadowMetadata(w, N);
523
- V?.pathComponents && V.pathComponents.size === 0 && (delete V.pathComponents, I.getState().setShadowMetadata(w, N, V));
524
- }), T?.components && x(w, [], T);
513
+ }), O({}), () => {
514
+ const b = V(w, []), _ = b?.components?.get(g);
515
+ _?.paths && _.paths.forEach((M) => {
516
+ const D = M.split(".").slice(1), E = T.getState().getShadowMetadata(w, D);
517
+ E?.pathComponents && E.pathComponents.size === 0 && (delete E.pathComponents, T.getState().setShadowMetadata(w, D, E));
518
+ }), b?.components && J(w, [], b);
525
519
  };
526
520
  }, []);
527
- const a = B(null), o = dt(
521
+ const o = L(null), n = ct(
528
522
  w,
529
- a,
530
- U,
531
- f
523
+ o,
524
+ F,
525
+ m
532
526
  );
533
- I.getState().initialStateGlobal[w] || Pe(w, e);
534
- const g = we(() => Oe(
527
+ T.getState().initialStateGlobal[w] || ke(w, e);
528
+ const d = we(() => Pe(
535
529
  w,
536
- o,
537
- Y.current,
538
- U
539
- ), [w, U]), v = M, y = f.current?.syncOptions;
540
- return v && (a.current = v(
541
- g,
542
- y ?? {}
543
- )), g;
530
+ n,
531
+ ee.current,
532
+ F
533
+ ), [w, F]), v = I, h = m.current?.syncOptions;
534
+ return v && (o.current = v(
535
+ d,
536
+ h ?? {}
537
+ )), d;
544
538
  }
545
- const gt = (e, t, c) => {
546
- let n = D(e, t)?.arrayKeys || [];
547
- if (console.log("ids", n), !c || c.length === 0)
548
- return n;
549
- for (const d of c)
550
- if (d.type === "filter") {
551
- const s = [];
552
- n.forEach((u, i) => {
553
- const S = F(e, [...t, u]);
554
- d.fn(S, i) && s.push(u);
555
- }), n = s;
556
- } else d.type === "sort" && n.sort((s, u) => {
557
- const i = F(e, [...t, s]), S = F(e, [...t, u]);
558
- return d.fn(i, S);
539
+ const ut = (e, r, l) => {
540
+ let a = V(e, r)?.arrayKeys || [];
541
+ const S = l?.transforms;
542
+ if (!S || S.length === 0)
543
+ return a;
544
+ for (const s of S)
545
+ if (s.type === "filter") {
546
+ const c = [];
547
+ a.forEach((i, f) => {
548
+ const t = R(e, [...r, i]);
549
+ s.fn(t, f) && c.push(i);
550
+ }), a = c;
551
+ } else s.type === "sort" && a.sort((c, i) => {
552
+ const f = R(e, [...r, c]), t = R(e, [...r, i]);
553
+ return s.fn(f, t);
559
554
  });
560
- return n;
561
- }, Ve = (e, t, c) => {
562
- const n = `${e}////${t}`, s = D(e, [])?.components?.get(n);
563
- !s || s.reactiveType === "none" || !(Array.isArray(s.reactiveType) ? s.reactiveType : [s.reactiveType]).includes("component") || Je(e, c, n);
564
- }, ue = (e, t, c) => {
565
- const n = I.getState(), d = n.getShadowMetadata(e, []), s = /* @__PURE__ */ new Set();
566
- d?.components && d.components.forEach((i, S) => {
567
- (Array.isArray(i.reactiveType) ? i.reactiveType : [i.reactiveType || "component"]).includes("all") && (i.forceUpdate(), s.add(S));
568
- }), n.getShadowMetadata(e, [...t, "getSelected"])?.pathComponents?.forEach((i) => {
569
- d?.components?.get(i)?.forceUpdate();
555
+ return a;
556
+ }, Ae = (e, r, l) => {
557
+ const a = `${e}////${r}`, s = V(e, [])?.components?.get(a);
558
+ !s || s.reactiveType === "none" || !(Array.isArray(s.reactiveType) ? s.reactiveType : [s.reactiveType]).includes("component") || Ge(e, l, a);
559
+ }, ne = (e, r, l) => {
560
+ const a = V(e, []), S = /* @__PURE__ */ new Set();
561
+ a?.components && a.components.forEach((c, i) => {
562
+ (Array.isArray(c.reactiveType) ? c.reactiveType : [c.reactiveType || "component"]).includes("all") && (c.forceUpdate(), S.add(i));
563
+ }), V(e, [
564
+ ...r,
565
+ "getSelected"
566
+ ])?.pathComponents?.forEach((c) => {
567
+ a?.components?.get(c)?.forceUpdate();
570
568
  });
571
- const u = n.getShadowMetadata(e, t);
572
- for (let i of u?.arrayKeys || []) {
573
- const S = i + ".selected", r = n.getShadowMetadata(
574
- e,
575
- S.split(".").slice(1)
576
- );
577
- i == c && r?.pathComponents?.forEach((l) => {
578
- d?.components?.get(l)?.forceUpdate();
569
+ const s = V(e, r);
570
+ for (let c of s?.arrayKeys || []) {
571
+ const i = c + ".selected", f = V(e, i.split(".").slice(1));
572
+ c == l && f?.pathComponents?.forEach((t) => {
573
+ a?.components?.get(t)?.forceUpdate();
579
574
  });
580
575
  }
581
576
  };
582
- function K(e, t, c) {
583
- const n = D(e, t), d = t.join("."), s = c?.arrayViews?.[d];
577
+ function Q(e, r, l) {
578
+ const a = V(e, r), S = r.length > 0 ? r.join(".") : "root", s = l?.arrayViews?.[S];
584
579
  if (Array.isArray(s) && s.length === 0)
585
580
  return {
586
- shadowMeta: n,
581
+ shadowMeta: a,
587
582
  value: [],
588
- arrayKeys: n?.arrayKeys
583
+ arrayKeys: a?.arrayKeys
589
584
  };
590
- const u = F(e, t, s);
585
+ const c = R(e, r, s);
591
586
  return {
592
- shadowMeta: n,
593
- value: u,
594
- arrayKeys: n?.arrayKeys
587
+ shadowMeta: a,
588
+ value: c,
589
+ arrayKeys: a?.arrayKeys
595
590
  };
596
591
  }
597
- function Oe(e, t, c, n) {
598
- const d = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Set([
592
+ function Pe(e, r, l, a) {
593
+ const S = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Set([
599
594
  "sync",
600
595
  "getStatus",
601
596
  "removeStorage",
@@ -646,278 +641,276 @@ function Oe(e, t, c, n) {
646
641
  "formElement"
647
642
  // Add ANY other method names here
648
643
  ]);
649
- function u({
650
- path: r = [],
651
- meta: l,
652
- componentId: M
644
+ function c({
645
+ path: t = [],
646
+ meta: u,
647
+ componentId: I
653
648
  }) {
654
- const _ = l ? JSON.stringify(l.arrayViews || l.transforms) : "", C = r.join(".") + ":" + _;
655
- if (d.has(C))
656
- return d.get(C);
657
- const U = [e, ...r].join("."), j = {
658
- get(Y, f) {
659
- if (r.length === 0 && f in i)
660
- return i[f];
661
- if (!s.has(f)) {
662
- const a = [...r, f];
663
- return u({
664
- path: a,
665
- componentId: M,
666
- meta: l
649
+ const U = u ? JSON.stringify(u.arrayViews || u.transforms) : "", O = t.join(".") + ":" + U;
650
+ if (S.has(O))
651
+ return S.get(O);
652
+ const F = [e, ...t].join("."), x = {
653
+ get(ee, m) {
654
+ if (t.length === 0 && m in i)
655
+ return i[m];
656
+ if (!s.has(m)) {
657
+ const o = [...t, m];
658
+ return c({
659
+ path: o,
660
+ componentId: I,
661
+ meta: u
667
662
  });
668
663
  }
669
- if (f === "_rebuildStateShape")
670
- return u;
671
- if (f === "sync" && r.length === 0)
664
+ if (m === "_rebuildStateShape")
665
+ return c;
666
+ if (m === "sync" && t.length === 0)
672
667
  return async function() {
673
- const a = I.getState().getInitialOptions(e), o = a?.sync;
674
- if (!o)
668
+ const o = T.getState().getInitialOptions(e), n = o?.sync;
669
+ if (!n)
675
670
  return console.error(`No mutation defined for state key "${e}"`), { success: !1, error: "No mutation defined" };
676
- const g = I.getState().getShadowValue(e, []), v = a?.validation?.key;
671
+ const d = T.getState().getShadowValue(e, []), v = o?.validation?.key;
677
672
  try {
678
- const y = await o.action(g);
679
- if (y && !y.success && y.errors, y?.success) {
680
- const m = I.getState().getShadowMetadata(e, []);
681
- x(e, [], {
682
- ...m,
673
+ const h = await n.action(d);
674
+ if (h && !h.success && h.errors, h?.success) {
675
+ const g = T.getState().getShadowMetadata(e, []);
676
+ J(e, [], {
677
+ ...g,
683
678
  isDirty: !1,
684
679
  lastServerSync: Date.now(),
685
680
  stateSource: "server",
686
- baseServerState: g
681
+ baseServerState: d
687
682
  // Update base server state
688
- }), o.onSuccess && o.onSuccess(y.data);
689
- } else !y?.success && o.onError && o.onError(y.error);
690
- return y;
691
- } catch (y) {
692
- return o.onError && o.onError(y), { success: !1, error: y };
683
+ }), n.onSuccess && n.onSuccess(h.data);
684
+ } else !h?.success && n.onError && n.onError(h.error);
685
+ return h;
686
+ } catch (h) {
687
+ return n.onError && n.onError(h), { success: !1, error: h };
693
688
  }
694
689
  };
695
- if (f === "_status" || f === "getStatus") {
696
- const a = () => {
697
- const { shadowMeta: o, value: g } = K(e, r, l);
698
- return o?.isDirty === !0 ? "dirty" : o?.stateSource === "server" || o?.isDirty === !1 ? "synced" : o?.stateSource === "localStorage" ? "restored" : o?.stateSource === "default" || g !== void 0 && !o ? "fresh" : "unknown";
690
+ if (m === "_status" || m === "getStatus") {
691
+ const o = () => {
692
+ const { shadowMeta: n, value: d } = Q(e, t, u);
693
+ return n?.isDirty === !0 ? "dirty" : n?.stateSource === "server" || n?.isDirty === !1 ? "synced" : n?.stateSource === "localStorage" ? "restored" : n?.stateSource === "default" || d !== void 0 && !n ? "fresh" : "unknown";
699
694
  };
700
- return f === "_status" ? a() : a;
695
+ return m === "_status" ? o() : o;
701
696
  }
702
- if (f === "removeStorage")
697
+ if (m === "removeStorage")
703
698
  return () => {
704
- const a = I.getState().initialStateGlobal[e], o = G(e), g = X(o?.localStorage?.key) ? o.localStorage.key(a) : o?.localStorage?.key, v = `${n}-${e}-${g}`;
699
+ const o = T.getState().initialStateGlobal[e], n = G(e), d = z(n?.localStorage?.key) ? n.localStorage.key(o) : n?.localStorage?.key, v = `${a}-${e}-${d}`;
705
700
  v && localStorage.removeItem(v);
706
701
  };
707
- if (f === "showValidationErrors")
702
+ if (m === "showValidationErrors")
708
703
  return () => {
709
- const { shadowMeta: a } = K(e, r, l);
710
- return a?.validation?.status === "INVALID" && a.validation.errors.length > 0 ? a.validation.errors.filter((o) => o.severity === "error").map((o) => o.message) : [];
704
+ const { shadowMeta: o } = Q(e, t, u);
705
+ return o?.validation?.status === "INVALID" && o.validation.errors.length > 0 ? o.validation.errors.filter((n) => n.severity === "error").map((n) => n.message) : [];
711
706
  };
712
- if (f === "getSelected")
707
+ if (m === "getSelected")
713
708
  return () => {
714
- const a = [e, ...r].join(".");
715
- Ve(e, M, [
716
- ...r,
709
+ const o = [e, ...t].join(".");
710
+ Ae(e, I, [
711
+ ...t,
717
712
  "getSelected"
718
713
  ]);
719
- const o = I.getState().selectedIndicesMap.get(a);
720
- if (!o)
714
+ const n = T.getState().selectedIndicesMap.get(o);
715
+ if (!n)
721
716
  return;
722
- const g = r.join("."), v = l?.arrayViews?.[g], y = o.split(".").pop();
723
- if (!(v && !v.includes(y) || F(
717
+ const d = t.join("."), v = u?.arrayViews?.[d], h = n.split(".").pop();
718
+ if (!(v && !v.includes(h) || R(
724
719
  e,
725
- o.split(".").slice(1)
720
+ n.split(".").slice(1)
726
721
  ) === void 0))
727
- return u({
728
- path: o.split(".").slice(1),
729
- componentId: M,
730
- meta: l
722
+ return c({
723
+ path: n.split(".").slice(1),
724
+ componentId: I,
725
+ meta: u
731
726
  });
732
727
  };
733
- if (f === "getSelectedIndex")
728
+ if (m === "getSelectedIndex")
734
729
  return () => {
735
- const a = e + "." + r.join(".");
736
- r.join(".");
737
- const o = I.getState().selectedIndicesMap.get(a);
738
- if (!o)
730
+ const o = e + "." + t.join(".");
731
+ t.join(".");
732
+ const n = T.getState().selectedIndicesMap.get(o);
733
+ if (!n)
739
734
  return -1;
740
- const { keys: g } = Z(e, r, l);
741
- if (!g)
735
+ const { keys: d } = B(e, t, u);
736
+ if (!d)
742
737
  return -1;
743
- const v = o.split(".").pop();
744
- return g.indexOf(v);
738
+ const v = n.split(".").pop();
739
+ return d.indexOf(v);
745
740
  };
746
- if (f === "clearSelected")
747
- return ue(e, r), () => {
748
- Xe({
749
- arrayKey: e + "." + r.join(".")
741
+ if (m === "clearSelected")
742
+ return ne(e, t), () => {
743
+ Ze({
744
+ arrayKey: e + "." + t.join(".")
750
745
  });
751
746
  };
752
- if (f === "useVirtualView")
753
- return (a) => {
747
+ if (m === "useVirtualView")
748
+ return (o) => {
754
749
  const {
755
- itemHeight: o = 50,
756
- overscan: g = 6,
750
+ itemHeight: n = 50,
751
+ overscan: d = 6,
757
752
  stickToBottom: v = !1,
758
- scrollStickTolerance: y = 75
759
- } = a, m = B(null), [h, p] = J({
753
+ scrollStickTolerance: h = 75
754
+ } = o, g = L(null), [y, p] = K({
760
755
  startIndex: 0,
761
756
  endIndex: 10
762
- }), [T, A] = J({}), E = B(!0), b = B({
757
+ }), [b, _] = K({}), M = L(!0);
758
+ W(() => {
759
+ const C = setInterval(() => {
760
+ _({});
761
+ }, 1e3);
762
+ return () => clearInterval(C);
763
+ }, []);
764
+ const A = L({
763
765
  isUserScrolling: !1,
764
766
  lastScrollTop: 0,
765
767
  scrollUpCount: 0,
766
768
  isNearBottom: !0
767
- }), N = B(
769
+ }), D = L(
768
770
  /* @__PURE__ */ new Map()
769
- );
770
- ie(() => {
771
- if (!v || !m.current || b.current.isUserScrolling)
772
- return;
773
- const k = m.current;
774
- k.scrollTo({
775
- top: k.scrollHeight,
776
- behavior: E.current ? "instant" : "smooth"
771
+ ), { keys: E } = B(e, t, u);
772
+ W(() => {
773
+ const C = [e, ...t].join("."), P = T.getState().subscribeToPath(C, (j) => {
774
+ j.type !== "GET_SELECTED" && j.type;
777
775
  });
778
- }, [T, v]);
779
- const { arrayKeys: V = [] } = K(e, r, l), { totalHeight: O, itemOffsets: W } = we(() => {
780
- let k = 0;
781
- const P = /* @__PURE__ */ new Map();
782
- return (I.getState().getShadowMetadata(e, r)?.arrayKeys || []).forEach((L) => {
783
- const $ = L.split(".").slice(1), z = I.getState().getShadowMetadata(e, $)?.virtualizer?.itemHeight || o;
784
- P.set(L, {
785
- height: z,
786
- offset: k
787
- }), k += z;
788
- }), N.current = P, { totalHeight: k, itemOffsets: P };
789
- }, [V.length, o]);
790
- ie(() => {
791
- if (v && V.length > 0 && m.current && !b.current.isUserScrolling && E.current) {
792
- const k = m.current, P = () => {
793
- if (k.clientHeight > 0) {
794
- const H = Math.ceil(
795
- k.clientHeight / o
796
- ), L = V.length - 1, $ = Math.max(
776
+ return () => {
777
+ P();
778
+ };
779
+ }, [I, e, t.join(".")]), ce(() => {
780
+ if (v && E.length > 0 && g.current && !A.current.isUserScrolling && M.current) {
781
+ const C = g.current, P = () => {
782
+ if (C.clientHeight > 0) {
783
+ const j = Math.ceil(
784
+ C.clientHeight / n
785
+ ), q = E.length - 1, $ = Math.max(
797
786
  0,
798
- L - H - g
787
+ q - j - d
799
788
  );
800
- p({ startIndex: $, endIndex: L }), requestAnimationFrame(() => {
801
- te("instant"), E.current = !1;
789
+ p({ startIndex: $, endIndex: q }), requestAnimationFrame(() => {
790
+ Y("instant"), M.current = !1;
802
791
  });
803
792
  } else
804
793
  requestAnimationFrame(P);
805
794
  };
806
795
  P();
807
796
  }
808
- }, [V.length, v, o, g]);
809
- const le = ae(() => {
810
- const k = m.current;
811
- if (!k) return;
812
- const P = k.scrollTop, { scrollHeight: H, clientHeight: L } = k, $ = b.current, z = H - (P + L), se = $.isNearBottom;
813
- $.isNearBottom = z <= y, P < $.lastScrollTop ? ($.scrollUpCount++, $.scrollUpCount > 3 && se && ($.isUserScrolling = !0, console.log("User scrolled away from bottom"))) : $.isNearBottom && ($.isUserScrolling = !1, $.scrollUpCount = 0), $.lastScrollTop = P;
814
- let re = 0;
815
- for (let Q = 0; Q < V.length; Q++) {
816
- const ye = V[Q], he = N.current.get(ye);
817
- if (he && he.offset + he.height > P) {
818
- re = Q;
797
+ }, [E.length, v, n, d]);
798
+ const k = L(y);
799
+ ce(() => {
800
+ k.current = y;
801
+ }, [y]);
802
+ const N = L(E);
803
+ ce(() => {
804
+ N.current = E;
805
+ }, [E]);
806
+ const se = pe(() => {
807
+ const C = g.current;
808
+ if (!C) return;
809
+ const P = C.scrollTop, { scrollHeight: j, clientHeight: q } = C, $ = A.current, re = j - (P + q), ge = $.isNearBottom;
810
+ $.isNearBottom = re <= h, P < $.lastScrollTop ? ($.scrollUpCount++, $.scrollUpCount > 3 && ge && ($.isUserScrolling = !0, console.log("User scrolled away from bottom"))) : $.isNearBottom && ($.isUserScrolling = !1, $.scrollUpCount = 0), $.lastScrollTop = P;
811
+ let Z = 0;
812
+ for (let H = 0; H < E.length; H++) {
813
+ const ye = E[H], me = D.current.get(ye);
814
+ if (me && me.offset + me.height > P) {
815
+ Z = H;
819
816
  break;
820
817
  }
821
818
  }
822
- if (re !== h.startIndex) {
823
- const Q = Math.ceil(L / o);
819
+ if (console.log(
820
+ "hadnlescroll ",
821
+ D.current,
822
+ Z,
823
+ y
824
+ ), Z !== y.startIndex && y.startIndex != 0) {
825
+ const H = Math.ceil(q / n);
824
826
  p({
825
- startIndex: Math.max(0, re - g),
827
+ startIndex: Math.max(0, Z - d),
826
828
  endIndex: Math.min(
827
- V.length - 1,
828
- re + Q + g
829
+ E.length - 1,
830
+ Z + H + d
829
831
  )
830
832
  });
831
833
  }
832
834
  }, [
833
- V.length,
834
- h.startIndex,
835
- o,
836
- g,
837
- y
835
+ E.length,
836
+ y.startIndex,
837
+ n,
838
+ d,
839
+ h
838
840
  ]);
839
- q(() => {
840
- const k = m.current;
841
- if (!(!k || !v))
842
- return k.addEventListener("scroll", le, {
841
+ W(() => {
842
+ const C = g.current;
843
+ if (C)
844
+ return C.addEventListener("scroll", se, {
843
845
  passive: !0
844
846
  }), () => {
845
- k.removeEventListener("scroll", le);
847
+ C.removeEventListener("scroll", se);
846
848
  };
847
- }, [le, v]);
848
- const te = ae(
849
- (k = "smooth") => {
850
- const P = m.current;
849
+ }, [se, v]);
850
+ const Y = pe(
851
+ (C = "smooth") => {
852
+ const P = g.current;
851
853
  if (!P) return;
852
- b.current.isUserScrolling = !1, b.current.isNearBottom = !0, b.current.scrollUpCount = 0;
853
- const H = () => {
854
- const L = ($ = 0) => {
854
+ A.current.isUserScrolling = !1, A.current.isNearBottom = !0, A.current.scrollUpCount = 0;
855
+ const j = () => {
856
+ const q = ($ = 0) => {
855
857
  if ($ > 5) return;
856
- const z = P.scrollHeight, se = P.scrollTop, re = P.clientHeight;
857
- se + re >= z - 1 || (P.scrollTo({
858
- top: z,
859
- behavior: k
858
+ const re = P.scrollHeight, ge = P.scrollTop, Z = P.clientHeight;
859
+ ge + Z >= re - 1 || (P.scrollTo({
860
+ top: re,
861
+ behavior: C
860
862
  }), setTimeout(() => {
861
- const Q = P.scrollHeight, ye = P.scrollTop;
862
- (Q !== z || ye + re < Q - 1) && L($ + 1);
863
+ const H = P.scrollHeight, ye = P.scrollTop;
864
+ (H !== re || ye + Z < H - 1) && q($ + 1);
863
865
  }, 50));
864
866
  };
865
- L();
867
+ q();
866
868
  };
867
- "requestIdleCallback" in window ? requestIdleCallback(H, { timeout: 100 }) : requestAnimationFrame(() => {
868
- requestAnimationFrame(H);
869
+ "requestIdleCallback" in window ? requestIdleCallback(j, { timeout: 100 }) : requestAnimationFrame(() => {
870
+ requestAnimationFrame(j);
869
871
  });
870
872
  },
871
873
  []
872
874
  );
873
- return q(() => {
874
- if (!v || !m.current) return;
875
- const k = m.current, P = b.current;
876
- let H;
877
- const L = () => {
878
- clearTimeout(H), H = setTimeout(() => {
879
- !P.isUserScrolling && P.isNearBottom && te(
880
- E.current ? "instant" : "smooth"
875
+ return W(() => {
876
+ if (!v || !g.current) return;
877
+ const C = g.current, P = A.current;
878
+ let j;
879
+ const q = () => {
880
+ clearTimeout(j), j = setTimeout(() => {
881
+ !P.isUserScrolling && P.isNearBottom && Y(
882
+ M.current ? "instant" : "smooth"
881
883
  );
882
884
  }, 100);
883
885
  }, $ = new MutationObserver(() => {
884
- P.isUserScrolling || L();
886
+ P.isUserScrolling || q();
885
887
  });
886
- $.observe(k, {
888
+ return $.observe(C, {
887
889
  childList: !0,
888
890
  subtree: !0,
889
891
  attributes: !0,
890
892
  attributeFilter: ["style", "class"]
891
- // More specific than just 'height'
892
- });
893
- const z = (se) => {
894
- se.target instanceof HTMLImageElement && !P.isUserScrolling && L();
895
- };
896
- return k.addEventListener("load", z, !0), E.current ? setTimeout(() => {
897
- te("instant");
898
- }, 0) : L(), () => {
899
- clearTimeout(H), $.disconnect(), k.removeEventListener("load", z, !0);
893
+ }), M.current ? setTimeout(() => {
894
+ Y("instant");
895
+ }, 0) : q(), () => {
896
+ clearTimeout(j), $.disconnect();
900
897
  };
901
- }, [v, V.length, te]), {
898
+ }, [v, E.length, Y]), {
902
899
  virtualState: we(() => {
903
- const k = I.getState(), P = k.getShadowValue(e, r), H = k.getShadowMetadata(e, r)?.arrayKeys || [];
904
- P.slice(
905
- h.startIndex,
906
- h.endIndex + 1
907
- );
908
- const L = H.slice(
909
- h.startIndex,
910
- h.endIndex + 1
911
- ), $ = r.length > 0 ? r.join(".") : "root";
912
- return u({
913
- path: r,
914
- componentId: M,
915
- meta: { ...l, arrayViews: { [$]: L } }
900
+ const C = Array.isArray(E) ? E.slice(y.startIndex, y.endIndex + 1) : [], P = t.length > 0 ? t.join(".") : "root";
901
+ return c({
902
+ path: t,
903
+ componentId: I,
904
+ meta: {
905
+ ...u,
906
+ arrayViews: { [P]: C },
907
+ serverStateIsUpStream: !0
908
+ }
916
909
  });
917
- }, [h.startIndex, h.endIndex, V.length]),
910
+ }, [y.startIndex, y.endIndex, E, u]),
918
911
  virtualizerProps: {
919
912
  outer: {
920
- ref: m,
913
+ ref: g,
921
914
  style: {
922
915
  overflowY: "auto",
923
916
  height: "100%",
@@ -926,445 +919,436 @@ function Oe(e, t, c, n) {
926
919
  },
927
920
  inner: {
928
921
  style: {
929
- height: `${O}px`,
930
922
  position: "relative"
931
923
  }
932
924
  },
933
925
  list: {
934
926
  style: {
935
- transform: `translateY(${N.current.get(V[h.startIndex])?.offset || 0}px)`
927
+ transform: `translateY(${D.current.get(E[y.startIndex])?.offset || 0}px)`
936
928
  }
937
929
  }
938
930
  },
939
- scrollToBottom: te,
940
- scrollToIndex: (k, P = "smooth") => {
941
- if (m.current && V[k]) {
942
- const H = N.current.get(V[k])?.offset || 0;
943
- m.current.scrollTo({ top: H, behavior: P });
931
+ scrollToBottom: Y,
932
+ scrollToIndex: (C, P = "smooth") => {
933
+ if (g.current && E[C]) {
934
+ const j = D.current.get(E[C])?.offset || 0;
935
+ g.current.scrollTo({ top: j, behavior: P });
944
936
  }
945
937
  }
946
938
  };
947
939
  };
948
- if (f === "stateMap")
949
- return (a) => {
950
- const { value: o, keys: g } = Z(
940
+ if (m === "stateMap")
941
+ return (o) => {
942
+ const { value: n, keys: d } = B(
951
943
  e,
952
- r,
953
- l
944
+ t,
945
+ u
954
946
  );
955
- if (!g || !Array.isArray(o))
947
+ if (!d || !Array.isArray(n))
956
948
  return [];
957
- const v = u({
958
- path: r,
959
- componentId: M,
960
- meta: l
949
+ const v = c({
950
+ path: t,
951
+ componentId: I,
952
+ meta: u
961
953
  });
962
- return o.map((y, m) => {
963
- const h = g[m];
964
- if (!h) return;
965
- const p = [...r, h], T = u({
954
+ return n.map((h, g) => {
955
+ const y = d[g];
956
+ if (!y) return;
957
+ const p = [...t, y], b = c({
966
958
  path: p,
967
959
  // This now correctly points to the item in the shadow store.
968
- componentId: M,
969
- meta: l
960
+ componentId: I,
961
+ meta: u
970
962
  });
971
- return a(T, m, v);
963
+ return o(b, g, v);
972
964
  });
973
965
  };
974
- if (f === "stateFilter")
975
- return (a) => {
976
- const o = r.length > 0 ? r.join(".") : "root", { keys: g, value: v } = Z(
966
+ if (m === "stateFilter")
967
+ return (o) => {
968
+ const n = t.length > 0 ? t.join(".") : "root", { keys: d, value: v } = B(
977
969
  e,
978
- r,
979
- l
970
+ t,
971
+ u
980
972
  );
981
973
  if (!Array.isArray(v))
982
974
  throw new Error("stateFilter can only be used on arrays");
983
- const y = [];
984
- return v.forEach((m, h) => {
985
- if (a(m, h)) {
986
- const p = g[h];
987
- p && y.push(p);
975
+ const h = [];
976
+ return v.forEach((g, y) => {
977
+ if (o(g, y)) {
978
+ const p = d[y];
979
+ p && h.push(p);
988
980
  }
989
- }), u({
990
- path: r,
991
- componentId: M,
981
+ }), c({
982
+ path: t,
983
+ componentId: I,
992
984
  meta: {
993
- ...l,
985
+ ...u,
994
986
  arrayViews: {
995
- ...l?.arrayViews || {},
996
- [o]: y
987
+ ...u?.arrayViews || {},
988
+ [n]: h
997
989
  },
998
990
  transforms: [
999
- ...l?.transforms || [],
1000
- { type: "filter", fn: a, path: r }
991
+ ...u?.transforms || [],
992
+ { type: "filter", fn: o, path: t }
1001
993
  ]
1002
994
  }
1003
995
  });
1004
996
  };
1005
- if (f === "stateSort")
1006
- return (a) => {
1007
- const o = r.join("."), { value: g, keys: v } = Z(
997
+ if (m === "stateSort")
998
+ return (o) => {
999
+ const n = t.length > 0 ? t.join(".") : "root", { value: d, keys: v } = B(
1008
1000
  e,
1009
- r,
1010
- l
1001
+ t,
1002
+ u
1011
1003
  );
1012
- if (!Array.isArray(g) || !v)
1004
+ if (!Array.isArray(d) || !v)
1013
1005
  throw new Error("No array keys found for sorting");
1014
- const y = g.map((h, p) => ({
1015
- item: h,
1006
+ const h = d.map((y, p) => ({
1007
+ item: y,
1016
1008
  key: v[p]
1017
1009
  }));
1018
- y.sort((h, p) => a(h.item, p.item));
1019
- const m = y.map((h) => h.key);
1020
- return u({
1021
- path: r,
1022
- componentId: M,
1010
+ h.sort((y, p) => o(y.item, p.item));
1011
+ const g = h.map((y) => y.key);
1012
+ return c({
1013
+ path: t,
1014
+ componentId: I,
1023
1015
  meta: {
1024
- ...l,
1016
+ ...u,
1025
1017
  arrayViews: {
1026
- ...l?.arrayViews || {},
1027
- [o]: m
1018
+ ...u?.arrayViews || {},
1019
+ [n]: g
1028
1020
  },
1029
1021
  transforms: [
1030
- ...l?.transforms || [],
1031
- { type: "sort", fn: a, path: r }
1022
+ ...u?.transforms || [],
1023
+ { type: "sort", fn: o, path: t }
1032
1024
  ]
1033
1025
  }
1034
1026
  });
1035
1027
  };
1036
- if (f === "stream")
1037
- return function(a = {}) {
1028
+ if (m === "stream")
1029
+ return function(o = {}) {
1038
1030
  const {
1039
- bufferSize: o = 100,
1040
- flushInterval: g = 100,
1031
+ bufferSize: n = 100,
1032
+ flushInterval: d = 100,
1041
1033
  bufferStrategy: v = "accumulate",
1042
- store: y,
1043
- onFlush: m
1044
- } = a;
1045
- let h = [], p = !1, T = null;
1046
- const A = (O) => {
1034
+ store: h,
1035
+ onFlush: g
1036
+ } = o;
1037
+ let y = [], p = !1, b = null;
1038
+ const _ = (k) => {
1047
1039
  if (!p) {
1048
- if (v === "sliding" && h.length >= o)
1049
- h.shift();
1050
- else if (v === "dropping" && h.length >= o)
1040
+ if (v === "sliding" && y.length >= n)
1041
+ y.shift();
1042
+ else if (v === "dropping" && y.length >= n)
1051
1043
  return;
1052
- h.push(O), h.length >= o && E();
1044
+ y.push(k), y.length >= n && M();
1053
1045
  }
1054
- }, E = () => {
1055
- if (h.length === 0) return;
1056
- const O = [...h];
1057
- if (h = [], y) {
1058
- const W = y(O);
1059
- W !== void 0 && (Array.isArray(W) ? W : [W]).forEach((te) => {
1060
- t(te, r, {
1046
+ }, M = () => {
1047
+ if (y.length === 0) return;
1048
+ const k = [...y];
1049
+ if (y = [], h) {
1050
+ const N = h(k);
1051
+ N !== void 0 && (Array.isArray(N) ? N : [N]).forEach((Y) => {
1052
+ r(Y, t, {
1061
1053
  updateType: "insert"
1062
1054
  });
1063
1055
  });
1064
1056
  } else
1065
- O.forEach((W) => {
1066
- t(W, r, {
1057
+ k.forEach((N) => {
1058
+ r(N, t, {
1067
1059
  updateType: "insert"
1068
1060
  });
1069
1061
  });
1070
- m?.(O);
1062
+ g?.(k);
1071
1063
  };
1072
- g > 0 && (T = setInterval(E, g));
1073
- const b = ee(), N = D(e, r) || {}, V = N.streams || /* @__PURE__ */ new Map();
1074
- return V.set(b, { buffer: h, flushTimer: T }), x(e, r, {
1075
- ...N,
1076
- streams: V
1064
+ d > 0 && (b = setInterval(M, d));
1065
+ const A = X(), D = V(e, t) || {}, E = D.streams || /* @__PURE__ */ new Map();
1066
+ return E.set(A, { buffer: y, flushTimer: b }), J(e, t, {
1067
+ ...D,
1068
+ streams: E
1077
1069
  }), {
1078
- write: (O) => A(O),
1079
- writeMany: (O) => O.forEach(A),
1080
- flush: () => E(),
1070
+ write: (k) => _(k),
1071
+ writeMany: (k) => k.forEach(_),
1072
+ flush: () => M(),
1081
1073
  pause: () => {
1082
1074
  p = !0;
1083
1075
  },
1084
1076
  resume: () => {
1085
- p = !1, h.length > 0 && E();
1077
+ p = !1, y.length > 0 && M();
1086
1078
  },
1087
1079
  close: () => {
1088
- E(), T && clearInterval(T);
1089
- const O = I.getState().getShadowMetadata(e, r);
1090
- O?.streams && O.streams.delete(b);
1080
+ M(), b && clearInterval(b);
1081
+ const k = T.getState().getShadowMetadata(e, t);
1082
+ k?.streams && k.streams.delete(A);
1091
1083
  }
1092
1084
  };
1093
1085
  };
1094
- if (f === "stateList")
1095
- return (a) => (console.log("meta outside", JSON.stringify(l)), /* @__PURE__ */ ne(() => {
1096
- const g = B(/* @__PURE__ */ new Map()), [v, y] = J({});
1097
- console.log("updateTrigger updateTrigger updateTrigger");
1098
- const m = gt(
1099
- e,
1100
- r,
1101
- l?.transforms
1102
- ), h = r.length > 0 ? r.join(".") : "root", p = {
1103
- ...l,
1086
+ if (m === "stateList")
1087
+ return (o) => /* @__PURE__ */ ie(() => {
1088
+ const d = L(/* @__PURE__ */ new Map()), [v, h] = K({}), g = t.length > 0 ? t.join(".") : "root", y = ut(e, t, u), p = we(() => ({
1089
+ ...u,
1104
1090
  arrayViews: {
1105
- ...l?.arrayViews || {},
1106
- [h]: m
1107
- // Update the arrayViews with the new valid IDs
1091
+ ...u?.arrayViews || {},
1092
+ [g]: y
1108
1093
  }
1109
- }, { value: T } = Z(
1094
+ }), [u, g, y]), { value: b } = B(
1110
1095
  e,
1111
- r,
1096
+ t,
1112
1097
  p
1113
1098
  );
1114
- if (console.log("validIds", m), console.log("arrayValues", T), q(() => {
1115
- const E = I.getState().subscribeToPath(U, (b) => {
1116
- if (console.log("changed array statelist ", b), b.type === "GET_SELECTED")
1099
+ if (W(() => {
1100
+ const A = T.getState().subscribeToPath(F, (D) => {
1101
+ if (D.type === "GET_SELECTED")
1117
1102
  return;
1118
- const V = I.getState().getShadowMetadata(e, r)?.transformCaches;
1119
- if (V)
1120
- for (const O of V.keys())
1121
- O.startsWith(M) && V.delete(O);
1122
- (b.type === "INSERT" || b.type === "REMOVE" || b.type === "CLEAR_SELECTION") && y({});
1103
+ const k = T.getState().getShadowMetadata(e, t)?.transformCaches;
1104
+ if (k)
1105
+ for (const N of k.keys())
1106
+ N.startsWith(I) && k.delete(N);
1107
+ (D.type === "INSERT" || D.type === "INSERT_MANY" || D.type === "REMOVE" || D.type === "CLEAR_SELECTION" || D.type === "SERVER_STATE_UPDATE" && !u?.serverStateIsUpStream) && h({});
1123
1108
  });
1124
1109
  return () => {
1125
- E();
1110
+ A();
1126
1111
  };
1127
- }, [M, U]), !Array.isArray(T))
1112
+ }, [I, F]), !Array.isArray(b))
1128
1113
  return null;
1129
- const A = u({
1130
- path: r,
1131
- componentId: M,
1114
+ const _ = c({
1115
+ path: t,
1116
+ componentId: I,
1132
1117
  meta: p
1133
1118
  // Use updated meta here
1134
- });
1135
- return console.log("arrayValues", T), /* @__PURE__ */ ne(Ne, { children: T.map((E, b) => {
1136
- const N = m[b];
1137
- if (!N)
1119
+ }), M = b.map((A, D) => {
1120
+ const E = y[D];
1121
+ if (!E)
1138
1122
  return null;
1139
- let V = g.current.get(N);
1140
- V || (V = ee(), g.current.set(N, V));
1141
- const O = [...r, N];
1142
- return Me(mt, {
1143
- key: N,
1123
+ let k = d.current.get(E);
1124
+ k || (k = X(), d.current.set(E, k));
1125
+ const N = [...t, E];
1126
+ return Ie(je, {
1127
+ key: E,
1144
1128
  stateKey: e,
1145
- itemComponentId: V,
1146
- itemPath: O,
1147
- localIndex: b,
1148
- arraySetter: A,
1149
- rebuildStateShape: u,
1150
- renderFn: a
1129
+ itemComponentId: k,
1130
+ itemPath: N,
1131
+ localIndex: D,
1132
+ arraySetter: _,
1133
+ rebuildStateShape: c,
1134
+ renderFn: o
1151
1135
  });
1152
- }) });
1153
- }, {}));
1154
- if (f === "stateFlattenOn")
1155
- return (a) => {
1156
- const o = r.join("."), g = l?.arrayViews?.[o], v = I.getState().getShadowValue(e, r, g);
1157
- return Array.isArray(v) ? u({
1158
- path: [...r, "[*]", a],
1159
- componentId: M,
1160
- meta: l
1136
+ });
1137
+ return /* @__PURE__ */ ie(Ce, { children: M });
1138
+ }, {});
1139
+ if (m === "stateFlattenOn")
1140
+ return (o) => {
1141
+ const n = t.length > 0 ? t.join(".") : "root", d = u?.arrayViews?.[n], v = T.getState().getShadowValue(e, t, d);
1142
+ return Array.isArray(v) ? c({
1143
+ path: [...t, "[*]", o],
1144
+ componentId: I,
1145
+ meta: u
1161
1146
  }) : [];
1162
1147
  };
1163
- if (f === "index")
1164
- return (a) => {
1165
- const o = r.join("."), g = l?.arrayViews?.[o];
1166
- if (g) {
1167
- const m = g[a];
1168
- return m ? u({
1169
- path: [...r, m],
1170
- componentId: M,
1171
- meta: l
1148
+ if (m === "index")
1149
+ return (o) => {
1150
+ const n = t.length > 0 ? t.join(".") : "root", d = u?.arrayViews?.[n];
1151
+ if (d) {
1152
+ const g = d[o];
1153
+ return g ? c({
1154
+ path: [...t, g],
1155
+ componentId: I,
1156
+ meta: u
1172
1157
  }) : void 0;
1173
1158
  }
1174
- const v = D(e, r);
1159
+ const v = V(e, t);
1175
1160
  if (!v?.arrayKeys) return;
1176
- const y = v.arrayKeys[a];
1177
- if (y)
1178
- return u({
1179
- path: [...r, y],
1180
- componentId: M,
1181
- meta: l
1161
+ const h = v.arrayKeys[o];
1162
+ if (h)
1163
+ return c({
1164
+ path: [...t, h],
1165
+ componentId: I,
1166
+ meta: u
1182
1167
  });
1183
1168
  };
1184
- if (f === "last")
1169
+ if (m === "last")
1185
1170
  return () => {
1186
- const { keys: a } = Z(e, r, l);
1187
- if (!a || a.length === 0)
1171
+ const { keys: o } = B(e, t, u);
1172
+ if (!o || o.length === 0)
1188
1173
  return;
1189
- const o = a[a.length - 1];
1190
- if (!o)
1174
+ const n = o[o.length - 1];
1175
+ if (!n)
1191
1176
  return;
1192
- const g = [...r, o];
1193
- return u({
1194
- path: g,
1195
- componentId: M,
1196
- meta: l
1177
+ const d = [...t, n];
1178
+ return c({
1179
+ path: d,
1180
+ componentId: I,
1181
+ meta: u
1197
1182
  });
1198
1183
  };
1199
- if (f === "insert")
1200
- return (a, o) => {
1201
- t(a, r, { updateType: "insert" });
1184
+ if (m === "insert")
1185
+ return (o, n) => {
1186
+ r(o, t, { updateType: "insert" });
1202
1187
  };
1203
- if (f === "uniqueInsert")
1204
- return (a, o, g) => {
1205
- const { value: v } = K(
1188
+ if (m === "uniqueInsert")
1189
+ return (o, n, d) => {
1190
+ const { value: v } = Q(
1206
1191
  e,
1207
- r,
1208
- l
1209
- ), y = X(a) ? a(v) : a;
1210
- let m = null;
1192
+ t,
1193
+ u
1194
+ ), h = z(o) ? o(v) : o;
1195
+ let g = null;
1211
1196
  if (!v.some((p) => {
1212
- const T = o ? o.every(
1213
- (A) => oe(p[A], y[A])
1214
- ) : oe(p, y);
1215
- return T && (m = p), T;
1197
+ const b = n ? n.every(
1198
+ (_) => ae(p[_], h[_])
1199
+ ) : ae(p, h);
1200
+ return b && (g = p), b;
1216
1201
  }))
1217
- t(y, r, { updateType: "insert" });
1218
- else if (g && m) {
1219
- const p = g(m), T = v.map(
1220
- (A) => oe(A, m) ? p : A
1202
+ r(h, t, { updateType: "insert" });
1203
+ else if (d && g) {
1204
+ const p = d(g), b = v.map(
1205
+ (_) => ae(_, g) ? p : _
1221
1206
  );
1222
- t(T, r, {
1207
+ r(b, t, {
1223
1208
  updateType: "update"
1224
1209
  });
1225
1210
  }
1226
1211
  };
1227
- if (f === "cut")
1228
- return (a, o) => {
1229
- const g = D(e, r);
1230
- if (!g?.arrayKeys || g.arrayKeys.length === 0)
1212
+ if (m === "cut")
1213
+ return (o, n) => {
1214
+ const d = V(e, t);
1215
+ if (!d?.arrayKeys || d.arrayKeys.length === 0)
1231
1216
  return;
1232
- const v = a === -1 ? g.arrayKeys.length - 1 : a !== void 0 ? a : g.arrayKeys.length - 1, y = g.arrayKeys[v];
1233
- y && t(null, [...r, y], {
1217
+ const v = o === -1 ? d.arrayKeys.length - 1 : o !== void 0 ? o : d.arrayKeys.length - 1, h = d.arrayKeys[v];
1218
+ h && r(null, [...t, h], {
1234
1219
  updateType: "cut"
1235
1220
  });
1236
1221
  };
1237
- if (f === "cutSelected")
1222
+ if (m === "cutSelected")
1238
1223
  return () => {
1239
- const a = [e, ...r].join("."), { keys: o } = Z(e, r, l);
1240
- if (!o || o.length === 0)
1224
+ const o = [e, ...t].join("."), { keys: n } = B(e, t, u);
1225
+ if (!n || n.length === 0)
1241
1226
  return;
1242
- const g = I.getState().selectedIndicesMap.get(a);
1243
- if (!g)
1227
+ const d = T.getState().selectedIndicesMap.get(o);
1228
+ if (!d)
1244
1229
  return;
1245
- const v = g.split(".").pop();
1246
- if (!o.includes(v))
1230
+ const v = d.split(".").pop();
1231
+ if (!n.includes(v))
1247
1232
  return;
1248
- const y = g.split(".").slice(1);
1249
- I.getState().clearSelectedIndex({ arrayKey: a });
1250
- const m = y.slice(0, -1);
1251
- ue(e, m), t(null, y, {
1233
+ const h = d.split(".").slice(1);
1234
+ T.getState().clearSelectedIndex({ arrayKey: o });
1235
+ const g = h.slice(0, -1);
1236
+ ne(e, g), r(null, h, {
1252
1237
  updateType: "cut"
1253
1238
  });
1254
1239
  };
1255
- if (f === "cutByValue")
1256
- return (a) => {
1240
+ if (m === "cutByValue")
1241
+ return (o) => {
1257
1242
  const {
1258
- isArray: o,
1259
- value: g,
1243
+ isArray: n,
1244
+ value: d,
1260
1245
  keys: v
1261
- } = Z(e, r, l);
1262
- if (!o) return;
1263
- const y = ve(g, v, (m) => m === a);
1264
- y && t(null, [...r, y.key], {
1246
+ } = B(e, t, u);
1247
+ if (!n) return;
1248
+ const h = he(d, v, (g) => g === o);
1249
+ h && r(null, [...t, h.key], {
1265
1250
  updateType: "cut"
1266
1251
  });
1267
1252
  };
1268
- if (f === "toggleByValue")
1269
- return (a) => {
1253
+ if (m === "toggleByValue")
1254
+ return (o) => {
1270
1255
  const {
1271
- isArray: o,
1272
- value: g,
1256
+ isArray: n,
1257
+ value: d,
1273
1258
  keys: v
1274
- } = Z(e, r, l);
1275
- if (!o) return;
1276
- const y = ve(g, v, (m) => m === a);
1277
- if (y) {
1278
- const m = [...r, y.key];
1279
- t(null, m, {
1259
+ } = B(e, t, u);
1260
+ if (!n) return;
1261
+ const h = he(d, v, (g) => g === o);
1262
+ if (h) {
1263
+ const g = [...t, h.key];
1264
+ r(null, g, {
1280
1265
  updateType: "cut"
1281
1266
  });
1282
1267
  } else
1283
- t(a, r, { updateType: "insert" });
1268
+ r(o, t, { updateType: "insert" });
1284
1269
  };
1285
- if (f === "findWith")
1286
- return (a, o) => {
1287
- const { isArray: g, value: v, keys: y } = Z(e, r, l);
1288
- if (!g)
1270
+ if (m === "findWith")
1271
+ return (o, n) => {
1272
+ const { isArray: d, value: v, keys: h } = B(e, t, u);
1273
+ if (!d)
1289
1274
  throw new Error("findWith can only be used on arrays");
1290
- const m = ve(
1275
+ const g = he(
1291
1276
  v,
1292
- y,
1293
- (h) => h?.[a] === o
1277
+ h,
1278
+ (y) => y?.[o] === n
1294
1279
  );
1295
- return u(m ? {
1296
- path: [...r, m.key],
1297
- // e.g., ['itemInstances', 'inst-1', 'properties', 'prop-b']
1298
- componentId: M,
1299
- meta: l
1280
+ return c(g ? {
1281
+ path: [...t, g.key],
1282
+ componentId: I,
1283
+ meta: u
1300
1284
  } : {
1301
- path: [...r, `not_found_${ee()}`],
1302
- componentId: M,
1303
- meta: l
1285
+ path: [...t, `not_found_${X()}`],
1286
+ componentId: I,
1287
+ meta: u
1304
1288
  });
1305
1289
  };
1306
- if (f === "cutThis") {
1307
- const { value: a } = K(e, r, l);
1308
- return () => {
1309
- t(a, r, { updateType: "cut" });
1290
+ if (m === "cutThis") {
1291
+ const { value: o } = Q(e, t, u), n = t.slice(0, -1);
1292
+ return ne(e, n), () => {
1293
+ r(o, t, { updateType: "cut" });
1310
1294
  };
1311
1295
  }
1312
- if (f === "get")
1296
+ if (m === "get")
1313
1297
  return () => {
1314
- Ve(e, M, r);
1315
- const { value: a } = K(e, r, l);
1316
- return a;
1298
+ Ae(e, I, t);
1299
+ const { value: o } = Q(e, t, u);
1300
+ return o;
1317
1301
  };
1318
- if (f === "$derive")
1319
- return (a) => Ae({
1302
+ if (m === "$derive")
1303
+ return (o) => _e({
1320
1304
  _stateKey: e,
1321
- _path: r,
1322
- _effect: a.toString(),
1323
- _meta: l
1305
+ _path: t,
1306
+ _effect: o.toString(),
1307
+ _meta: u
1324
1308
  });
1325
- if (f === "$get")
1326
- return () => Ae({ _stateKey: e, _path: r, _meta: l });
1327
- if (f === "lastSynced") {
1328
- const a = `${e}:${r.join(".")}`;
1329
- return Ke(a);
1309
+ if (m === "$get")
1310
+ return () => _e({ _stateKey: e, _path: t, _meta: u });
1311
+ if (m === "lastSynced") {
1312
+ const o = `${e}:${t.join(".")}`;
1313
+ return Ye(o);
1330
1314
  }
1331
- if (f == "getLocalStorage")
1332
- return (a) => me(n + "-" + e + "-" + a);
1333
- if (f === "isSelected") {
1334
- const a = r.slice(0, -1);
1335
- if (D(e, a)?.arrayKeys) {
1336
- const g = e + "." + a.join("."), v = I.getState().selectedIndicesMap.get(g), y = e + "." + r.join(".");
1337
- return ue(e, a, void 0), v === y;
1315
+ if (m == "getLocalStorage")
1316
+ return (o) => Se(a + "-" + e + "-" + o);
1317
+ if (m === "isSelected") {
1318
+ const o = t.slice(0, -1);
1319
+ if (V(e, o)?.arrayKeys) {
1320
+ const d = e + "." + o.join("."), v = T.getState().selectedIndicesMap.get(d), h = e + "." + t.join(".");
1321
+ return v === h;
1338
1322
  }
1339
1323
  return;
1340
1324
  }
1341
- if (f === "setSelected")
1342
- return (a) => {
1343
- const o = r.slice(0, -1), g = e + "." + o.join("."), v = e + "." + r.join(".");
1344
- ue(e, o, void 0), I.getState().selectedIndicesMap.get(g), a && I.getState().setSelectedIndex(g, v);
1325
+ if (m === "setSelected")
1326
+ return (o) => {
1327
+ const n = t.slice(0, -1), d = e + "." + n.join("."), v = e + "." + t.join(".");
1328
+ ne(e, n, void 0), T.getState().selectedIndicesMap.get(d), o && T.getState().setSelectedIndex(d, v);
1345
1329
  };
1346
- if (f === "toggleSelected")
1330
+ if (m === "toggleSelected")
1347
1331
  return () => {
1348
- const a = r.slice(0, -1), o = e + "." + a.join("."), g = e + "." + r.join(".");
1349
- I.getState().selectedIndicesMap.get(o) === g ? I.getState().clearSelectedIndex({ arrayKey: o }) : I.getState().setSelectedIndex(o, g);
1332
+ const o = t.slice(0, -1), n = e + "." + o.join("."), d = e + "." + t.join(".");
1333
+ T.getState().selectedIndicesMap.get(n) === d ? T.getState().clearSelectedIndex({ arrayKey: n }) : T.getState().setSelectedIndex(n, d), ne(e, o);
1350
1334
  };
1351
- if (f === "_componentId")
1352
- return M;
1353
- if (r.length == 0) {
1354
- if (f === "addZodValidation")
1355
- return (a) => {
1356
- a.forEach((o) => {
1357
- const g = I.getState().getShadowMetadata(e, o.path) || {};
1358
- I.getState().setShadowMetadata(e, o.path, {
1359
- ...g,
1335
+ if (m === "_componentId")
1336
+ return I;
1337
+ if (t.length == 0) {
1338
+ if (m === "addZodValidation")
1339
+ return (o) => {
1340
+ o.forEach((n) => {
1341
+ const d = T.getState().getShadowMetadata(e, n.path) || {};
1342
+ T.getState().setShadowMetadata(e, n.path, {
1343
+ ...d,
1360
1344
  validation: {
1361
1345
  status: "INVALID",
1362
1346
  errors: [
1363
1347
  {
1364
1348
  source: "client",
1365
- message: o.message,
1349
+ message: n.message,
1366
1350
  severity: "error",
1367
- code: o.code
1351
+ code: n.code
1368
1352
  }
1369
1353
  ],
1370
1354
  lastValidated: Date.now(),
@@ -1373,13 +1357,13 @@ function Oe(e, t, c, n) {
1373
1357
  });
1374
1358
  });
1375
1359
  };
1376
- if (f === "clearZodValidation")
1377
- return (a) => {
1378
- if (!a)
1360
+ if (m === "clearZodValidation")
1361
+ return (o) => {
1362
+ if (!o)
1379
1363
  throw new Error("clearZodValidation requires a path");
1380
- const o = D(e, a) || {};
1381
- x(e, a, {
1382
- ...o,
1364
+ const n = V(e, o) || {};
1365
+ J(e, o, {
1366
+ ...n,
1383
1367
  validation: {
1384
1368
  status: "NOT_VALIDATED",
1385
1369
  errors: [],
@@ -1387,197 +1371,197 @@ function Oe(e, t, c, n) {
1387
1371
  }
1388
1372
  });
1389
1373
  };
1390
- if (f === "applyJsonPatch")
1391
- return (a) => {
1392
- const o = I.getState(), g = o.getShadowMetadata(e, []);
1393
- if (!g?.components) return;
1394
- const v = (m) => !m || m === "/" ? [] : m.split("/").slice(1).map((h) => h.replace(/~1/g, "/").replace(/~0/g, "~")), y = /* @__PURE__ */ new Set();
1395
- for (const m of a) {
1396
- const h = v(m.path);
1397
- switch (m.op) {
1374
+ if (m === "applyJsonPatch")
1375
+ return (o) => {
1376
+ const n = T.getState(), d = n.getShadowMetadata(e, []);
1377
+ if (!d?.components) return;
1378
+ const v = (g) => !g || g === "/" ? [] : g.split("/").slice(1).map((y) => y.replace(/~1/g, "/").replace(/~0/g, "~")), h = /* @__PURE__ */ new Set();
1379
+ for (const g of o) {
1380
+ const y = v(g.path);
1381
+ switch (g.op) {
1398
1382
  case "add":
1399
1383
  case "replace": {
1400
- const { value: p } = m;
1401
- o.updateShadowAtPath(e, h, p), o.markAsDirty(e, h, { bubble: !0 });
1402
- let T = [...h];
1384
+ const { value: p } = g;
1385
+ n.updateShadowAtPath(e, y, p), n.markAsDirty(e, y, { bubble: !0 });
1386
+ let b = [...y];
1403
1387
  for (; ; ) {
1404
- const A = o.getShadowMetadata(
1388
+ const _ = n.getShadowMetadata(
1405
1389
  e,
1406
- T
1390
+ b
1407
1391
  );
1408
- if (A?.pathComponents && A.pathComponents.forEach((E) => {
1409
- if (!y.has(E)) {
1410
- const b = g.components?.get(E);
1411
- b && (b.forceUpdate(), y.add(E));
1392
+ if (_?.pathComponents && _.pathComponents.forEach((M) => {
1393
+ if (!h.has(M)) {
1394
+ const A = d.components?.get(M);
1395
+ A && (A.forceUpdate(), h.add(M));
1412
1396
  }
1413
- }), T.length === 0) break;
1414
- T.pop();
1397
+ }), b.length === 0) break;
1398
+ b.pop();
1415
1399
  }
1416
1400
  break;
1417
1401
  }
1418
1402
  case "remove": {
1419
- const p = h.slice(0, -1);
1420
- o.removeShadowArrayElement(e, h), o.markAsDirty(e, p, { bubble: !0 });
1421
- let T = [...p];
1403
+ const p = y.slice(0, -1);
1404
+ n.removeShadowArrayElement(e, y), n.markAsDirty(e, p, { bubble: !0 });
1405
+ let b = [...p];
1422
1406
  for (; ; ) {
1423
- const A = o.getShadowMetadata(
1407
+ const _ = n.getShadowMetadata(
1424
1408
  e,
1425
- T
1409
+ b
1426
1410
  );
1427
- if (A?.pathComponents && A.pathComponents.forEach((E) => {
1428
- if (!y.has(E)) {
1429
- const b = g.components?.get(E);
1430
- b && (b.forceUpdate(), y.add(E));
1411
+ if (_?.pathComponents && _.pathComponents.forEach((M) => {
1412
+ if (!h.has(M)) {
1413
+ const A = d.components?.get(M);
1414
+ A && (A.forceUpdate(), h.add(M));
1431
1415
  }
1432
- }), T.length === 0) break;
1433
- T.pop();
1416
+ }), b.length === 0) break;
1417
+ b.pop();
1434
1418
  }
1435
1419
  break;
1436
1420
  }
1437
1421
  }
1438
1422
  }
1439
1423
  };
1440
- if (f === "getComponents")
1441
- return () => D(e, [])?.components;
1442
- if (f === "getAllFormRefs")
1443
- return () => Ie.getState().getFormRefsByStateKey(e);
1424
+ if (m === "getComponents")
1425
+ return () => V(e, [])?.components;
1426
+ if (m === "getAllFormRefs")
1427
+ return () => Ee.getState().getFormRefsByStateKey(e);
1444
1428
  }
1445
- if (f === "getFormRef")
1446
- return () => Ie.getState().getFormRef(e + "." + r.join("."));
1447
- if (f === "validationWrapper")
1429
+ if (m === "getFormRef")
1430
+ return () => Ee.getState().getFormRef(e + "." + t.join("."));
1431
+ if (m === "validationWrapper")
1448
1432
  return ({
1449
- children: a,
1450
- hideMessage: o
1451
- }) => /* @__PURE__ */ ne(
1452
- _e,
1433
+ children: o,
1434
+ hideMessage: n
1435
+ }) => /* @__PURE__ */ ie(
1436
+ Ne,
1453
1437
  {
1454
- formOpts: o ? { validation: { message: "" } } : void 0,
1455
- path: r,
1438
+ formOpts: n ? { validation: { message: "" } } : void 0,
1439
+ path: t,
1456
1440
  stateKey: e,
1457
- children: a
1441
+ children: o
1458
1442
  }
1459
1443
  );
1460
- if (f === "_stateKey") return e;
1461
- if (f === "_path") return r;
1462
- if (f === "update")
1463
- return (a) => (t(a, r, { updateType: "update" }), {
1444
+ if (m === "_stateKey") return e;
1445
+ if (m === "_path") return t;
1446
+ if (m === "update")
1447
+ return (o) => (r(o, t, { updateType: "update" }), {
1464
1448
  synced: () => {
1465
- const o = I.getState().getShadowMetadata(e, r);
1466
- x(e, r, {
1467
- ...o,
1449
+ const n = T.getState().getShadowMetadata(e, t);
1450
+ J(e, t, {
1451
+ ...n,
1468
1452
  isDirty: !1,
1469
1453
  stateSource: "server",
1470
1454
  lastServerSync: Date.now()
1471
1455
  });
1472
- const g = [e, ...r].join(".");
1473
- De(g, {
1456
+ const d = [e, ...t].join(".");
1457
+ Qe(d, {
1474
1458
  type: "SYNC_STATUS_CHANGE",
1475
1459
  isDirty: !1
1476
1460
  });
1477
1461
  }
1478
1462
  });
1479
- if (f === "toggle") {
1480
- const { value: a } = K(
1463
+ if (m === "toggle") {
1464
+ const { value: o } = Q(
1481
1465
  e,
1482
- r,
1483
- l
1466
+ t,
1467
+ u
1484
1468
  );
1485
- if (typeof a != "boolean")
1469
+ if (typeof o != "boolean")
1486
1470
  throw new Error("toggle() can only be used on boolean values");
1487
1471
  return () => {
1488
- t(!a, r, {
1472
+ r(!o, t, {
1489
1473
  updateType: "update"
1490
1474
  });
1491
1475
  };
1492
1476
  }
1493
- if (f === "formElement")
1494
- return (a, o) => /* @__PURE__ */ ne(
1495
- vt,
1477
+ if (m === "formElement")
1478
+ return (o, n) => /* @__PURE__ */ ie(
1479
+ Oe,
1496
1480
  {
1497
1481
  stateKey: e,
1498
- path: r,
1499
- rebuildStateShape: u,
1500
- setState: t,
1501
- formOpts: o,
1502
- renderFn: a
1482
+ path: t,
1483
+ rebuildStateShape: c,
1484
+ setState: r,
1485
+ formOpts: n,
1486
+ renderFn: o
1503
1487
  }
1504
1488
  );
1505
- const R = [...r, f];
1506
- return I.getState().getShadowValue(e, R), u({
1507
- path: R,
1508
- componentId: M,
1509
- meta: l
1489
+ const te = [...t, m];
1490
+ return T.getState().getShadowValue(e, te), c({
1491
+ path: te,
1492
+ componentId: I,
1493
+ meta: u
1510
1494
  });
1511
1495
  }
1512
- }, w = new Proxy({}, j);
1513
- return d.set(C, w), w;
1496
+ }, w = new Proxy({}, x);
1497
+ return S.set(O, w), w;
1514
1498
  }
1515
1499
  const i = {
1516
- revertToInitialState: (r) => {
1517
- const l = I.getState().getShadowMetadata(e, []);
1518
- l?.stateSource === "server" && l.baseServerState ? l.baseServerState : I.getState().initialStateGlobal[e];
1519
- const M = I.getState().initialStateGlobal[e];
1520
- Ze(e), ce(e, M), u({
1500
+ revertToInitialState: (t) => {
1501
+ const u = T.getState().getShadowMetadata(e, []);
1502
+ u?.stateSource === "server" && u.baseServerState ? u.baseServerState : T.getState().initialStateGlobal[e];
1503
+ const I = T.getState().initialStateGlobal[e];
1504
+ He(e), oe(e, I), c({
1521
1505
  path: [],
1522
- componentId: c
1506
+ componentId: l
1523
1507
  });
1524
- const _ = G(e), C = X(_?.localStorage?.key) ? _?.localStorage?.key(M) : _?.localStorage?.key, U = `${n}-${e}-${C}`;
1525
- U && localStorage.removeItem(U);
1526
- const j = I.getState().getShadowMetadata(e, []);
1527
- return j && j?.components?.forEach((w) => {
1508
+ const U = G(e), O = z(U?.localStorage?.key) ? U?.localStorage?.key(I) : U?.localStorage?.key, F = `${a}-${e}-${O}`;
1509
+ F && localStorage.removeItem(F);
1510
+ const x = T.getState().getShadowMetadata(e, []);
1511
+ return x && x?.components?.forEach((w) => {
1528
1512
  w.forceUpdate();
1529
- }), M;
1513
+ }), I;
1530
1514
  },
1531
- updateInitialState: (r) => {
1532
- const l = Oe(
1515
+ updateInitialState: (t) => {
1516
+ const u = Pe(
1533
1517
  e,
1534
- t,
1535
- c,
1536
- n
1537
- ), M = I.getState().initialStateGlobal[e], _ = G(e), C = X(_?.localStorage?.key) ? _?.localStorage?.key(M) : _?.localStorage?.key, U = `${n}-${e}-${C}`;
1538
- return localStorage.getItem(U) && localStorage.removeItem(U), je(() => {
1539
- Pe(e, r), ce(e, r);
1540
- const j = I.getState().getShadowMetadata(e, []);
1541
- j && j?.components?.forEach((w) => {
1518
+ r,
1519
+ l,
1520
+ a
1521
+ ), I = T.getState().initialStateGlobal[e], U = G(e), O = z(U?.localStorage?.key) ? U?.localStorage?.key(I) : U?.localStorage?.key, F = `${a}-${e}-${O}`;
1522
+ return localStorage.getItem(F) && localStorage.removeItem(F), De(() => {
1523
+ ke(e, t), oe(e, t);
1524
+ const x = T.getState().getShadowMetadata(e, []);
1525
+ x && x?.components?.forEach((w) => {
1542
1526
  w.forceUpdate();
1543
1527
  });
1544
1528
  }), {
1545
- fetchId: (j) => l.get()[j]
1529
+ fetchId: (x) => u.get()[x]
1546
1530
  };
1547
1531
  }
1548
1532
  };
1549
- return u({
1550
- componentId: c,
1533
+ return c({
1534
+ componentId: l,
1551
1535
  path: []
1552
1536
  });
1553
1537
  }
1554
- function Ae(e) {
1555
- return Me(St, { proxy: e });
1538
+ function _e(e) {
1539
+ return Ie(dt, { proxy: e });
1556
1540
  }
1557
- function St({
1541
+ function dt({
1558
1542
  proxy: e
1559
1543
  }) {
1560
- const t = B(null), c = B(null), n = B(!1), d = `${e._stateKey}-${e._path.join(".")}`, s = e._path.join("."), u = e._meta?.arrayViews?.[s], i = F(e._stateKey, e._path, u);
1561
- return q(() => {
1562
- const S = t.current;
1563
- if (!S || n.current) return;
1564
- const r = setTimeout(() => {
1565
- if (!S.parentElement) {
1566
- console.warn("Parent element not found for signal", d);
1544
+ const r = L(null), l = L(null), a = L(!1), S = `${e._stateKey}-${e._path.join(".")}`, s = e._path.length > 0 ? e._path.join(".") : "root", c = e._meta?.arrayViews?.[s], i = R(e._stateKey, e._path, c);
1545
+ return W(() => {
1546
+ const f = r.current;
1547
+ if (!f || a.current) return;
1548
+ const t = setTimeout(() => {
1549
+ if (!f.parentElement) {
1550
+ console.warn("Parent element not found for signal", S);
1567
1551
  return;
1568
1552
  }
1569
- const l = S.parentElement, _ = Array.from(l.childNodes).indexOf(S);
1570
- let C = l.getAttribute("data-parent-id");
1571
- C || (C = `parent-${crypto.randomUUID()}`, l.setAttribute("data-parent-id", C)), c.current = `instance-${crypto.randomUUID()}`;
1572
- const U = I.getState().getShadowMetadata(e._stateKey, e._path) || {}, j = U.signals || [];
1573
- j.push({
1574
- instanceId: c.current,
1575
- parentId: C,
1576
- position: _,
1553
+ const u = f.parentElement, U = Array.from(u.childNodes).indexOf(f);
1554
+ let O = u.getAttribute("data-parent-id");
1555
+ O || (O = `parent-${crypto.randomUUID()}`, u.setAttribute("data-parent-id", O)), l.current = `instance-${crypto.randomUUID()}`;
1556
+ const F = T.getState().getShadowMetadata(e._stateKey, e._path) || {}, x = F.signals || [];
1557
+ x.push({
1558
+ instanceId: l.current,
1559
+ parentId: O,
1560
+ position: U,
1577
1561
  effect: e._effect
1578
- }), I.getState().setShadowMetadata(e._stateKey, e._path, {
1579
- ...U,
1580
- signals: j
1562
+ }), T.getState().setShadowMetadata(e._stateKey, e._path, {
1563
+ ...F,
1564
+ signals: x
1581
1565
  });
1582
1566
  let w = i;
1583
1567
  if (e._effect)
@@ -1586,281 +1570,32 @@ function St({
1586
1570
  "state",
1587
1571
  `return (${e._effect})(state)`
1588
1572
  )(i);
1589
- } catch (f) {
1590
- console.error("Error evaluating effect function:", f);
1573
+ } catch (m) {
1574
+ console.error("Error evaluating effect function:", m);
1591
1575
  }
1592
1576
  w !== null && typeof w == "object" && (w = JSON.stringify(w));
1593
- const Y = document.createTextNode(String(w ?? ""));
1594
- S.replaceWith(Y), n.current = !0;
1577
+ const ee = document.createTextNode(String(w ?? ""));
1578
+ f.replaceWith(ee), a.current = !0;
1595
1579
  }, 0);
1596
1580
  return () => {
1597
- if (clearTimeout(r), c.current) {
1598
- const l = I.getState().getShadowMetadata(e._stateKey, e._path) || {};
1599
- l.signals && (l.signals = l.signals.filter(
1600
- (M) => M.instanceId !== c.current
1601
- ), I.getState().setShadowMetadata(e._stateKey, e._path, l));
1581
+ if (clearTimeout(t), l.current) {
1582
+ const u = T.getState().getShadowMetadata(e._stateKey, e._path) || {};
1583
+ u.signals && (u.signals = u.signals.filter(
1584
+ (I) => I.instanceId !== l.current
1585
+ ), T.getState().setShadowMetadata(e._stateKey, e._path, u));
1602
1586
  }
1603
1587
  };
1604
- }, []), Me("span", {
1605
- ref: t,
1588
+ }, []), Ie("span", {
1589
+ ref: r,
1606
1590
  style: { display: "contents" },
1607
- "data-signal-id": d
1591
+ "data-signal-id": S
1608
1592
  });
1609
1593
  }
1610
- const mt = $e(
1611
- ht,
1612
- (e, t) => e.itemPath.join(".") === t.itemPath.join(".") && e.stateKey === t.stateKey && e.itemComponentId === t.itemComponentId && e.localIndex === t.localIndex
1613
- ), yt = (e) => {
1614
- const [t, c] = J(!1);
1615
- return ie(() => {
1616
- if (!e.current) {
1617
- c(!0);
1618
- return;
1619
- }
1620
- const n = Array.from(e.current.querySelectorAll("img"));
1621
- if (n.length === 0) {
1622
- c(!0);
1623
- return;
1624
- }
1625
- let d = 0;
1626
- const s = () => {
1627
- d++, d === n.length && c(!0);
1628
- };
1629
- return n.forEach((u) => {
1630
- u.complete ? s() : (u.addEventListener("load", s), u.addEventListener("error", s));
1631
- }), () => {
1632
- n.forEach((u) => {
1633
- u.removeEventListener("load", s), u.removeEventListener("error", s);
1634
- });
1635
- };
1636
- }, [e.current]), t;
1637
- };
1638
- function ht({
1639
- stateKey: e,
1640
- itemComponentId: t,
1641
- itemPath: c,
1642
- localIndex: n,
1643
- arraySetter: d,
1644
- rebuildStateShape: s,
1645
- renderFn: u
1646
- }) {
1647
- const [, i] = J({}), { ref: S, inView: r } = He(), l = B(null), M = yt(l), _ = B(!1), C = [e, ...c].join(".");
1648
- Ue(e, t, i);
1649
- const U = ae(
1650
- (f) => {
1651
- l.current = f, S(f);
1652
- },
1653
- [S]
1654
- );
1655
- q(() => {
1656
- et(C, (f) => {
1657
- i({});
1658
- });
1659
- }, []), q(() => {
1660
- if (!r || !M || _.current)
1661
- return;
1662
- const f = l.current;
1663
- if (f && f.offsetHeight > 0) {
1664
- _.current = !0;
1665
- const R = f.offsetHeight;
1666
- x(e, c, {
1667
- virtualizer: {
1668
- itemHeight: R,
1669
- domRef: f
1670
- }
1671
- });
1672
- const a = c.slice(0, -1), o = [e, ...a].join(".");
1673
- De(o, {
1674
- type: "ITEMHEIGHT",
1675
- itemKey: c.join("."),
1676
- ref: l.current
1677
- });
1678
- }
1679
- }, [r, M, e, c]);
1680
- const j = F(e, c);
1681
- if (j === void 0)
1682
- return null;
1683
- const w = s({
1684
- currentState: j,
1685
- path: c,
1686
- componentId: t
1687
- }), Y = u(w, n, d);
1688
- return /* @__PURE__ */ ne("div", { ref: U, children: Y });
1689
- }
1690
- function vt({
1691
- stateKey: e,
1692
- path: t,
1693
- rebuildStateShape: c,
1694
- renderFn: n,
1695
- formOpts: d,
1696
- setState: s
1697
- }) {
1698
- const [u] = J(() => ee()), [, i] = J({}), S = [e, ...t].join(".");
1699
- Ue(e, u, i);
1700
- const r = F(e, t), [l, M] = J(r), _ = B(!1), C = B(null);
1701
- q(() => {
1702
- !_.current && !oe(r, l) && M(r);
1703
- }, [r]), q(() => {
1704
- const f = I.getState().subscribeToPath(S, (R) => {
1705
- !_.current && l !== R && i({});
1706
- });
1707
- return () => {
1708
- f(), C.current && (clearTimeout(C.current), _.current = !1);
1709
- };
1710
- }, []);
1711
- const U = ae(
1712
- (f) => {
1713
- typeof r === "number" && typeof f == "string" && (f = f === "" ? 0 : Number(f)), M(f), _.current = !0, C.current && clearTimeout(C.current);
1714
- const a = d?.debounceTime ?? 200;
1715
- C.current = setTimeout(() => {
1716
- if (_.current = !1, s(f, t, { updateType: "update" }), !I.getState().getShadowMetadata(e, [])?.features?.validationEnabled) return;
1717
- const g = G(e)?.validation, v = g?.zodSchemaV4 || g?.zodSchemaV3;
1718
- if (v) {
1719
- const y = F(e, []), m = v.safeParse(y), h = D(e, t) || {};
1720
- if (m.success)
1721
- x(e, t, {
1722
- ...h,
1723
- validation: {
1724
- status: "VALID",
1725
- errors: [],
1726
- lastValidated: Date.now(),
1727
- validatedValue: f
1728
- }
1729
- });
1730
- else {
1731
- const T = ("issues" in m.error ? m.error.issues : m.error.errors).filter(
1732
- (A) => JSON.stringify(A.path) === JSON.stringify(t)
1733
- );
1734
- T.length > 0 ? x(e, t, {
1735
- ...h,
1736
- validation: {
1737
- status: "INVALID",
1738
- errors: [
1739
- {
1740
- source: "client",
1741
- message: T[0]?.message,
1742
- severity: "warning"
1743
- // Gentle error during typing
1744
- }
1745
- ],
1746
- lastValidated: Date.now(),
1747
- validatedValue: f
1748
- }
1749
- }) : x(e, t, {
1750
- ...h,
1751
- validation: {
1752
- status: "VALID",
1753
- errors: [],
1754
- lastValidated: Date.now(),
1755
- validatedValue: f
1756
- }
1757
- });
1758
- }
1759
- }
1760
- }, a), i({});
1761
- },
1762
- [s, t, d?.debounceTime, e]
1763
- ), j = ae(async () => {
1764
- if (console.log("handleBlur triggered"), C.current && (clearTimeout(C.current), C.current = null, _.current = !1, s(l, t, { updateType: "update" })), !D(e, [])?.features?.validationEnabled) return;
1765
- const { getInitialOptions: R } = I.getState(), a = R(e)?.validation, o = a?.zodSchemaV4 || a?.zodSchemaV3;
1766
- if (!o) return;
1767
- const g = D(e, t);
1768
- x(e, t, {
1769
- ...g,
1770
- validation: {
1771
- status: "VALIDATING",
1772
- errors: [],
1773
- lastValidated: Date.now(),
1774
- validatedValue: l
1775
- }
1776
- });
1777
- const v = F(e, []), y = o.safeParse(v);
1778
- if (console.log("result ", y), y.success)
1779
- x(e, t, {
1780
- ...g,
1781
- validation: {
1782
- status: "VALID",
1783
- errors: [],
1784
- lastValidated: Date.now(),
1785
- validatedValue: l
1786
- }
1787
- });
1788
- else {
1789
- const m = "issues" in y.error ? y.error.issues : y.error.errors;
1790
- console.log("All validation errors:", m), console.log("Current blur path:", t);
1791
- const h = m.filter((p) => {
1792
- if (console.log("Processing error:", p), t.some((A) => A.startsWith("id:"))) {
1793
- console.log("Detected array path with ULID");
1794
- const A = t[0].startsWith("id:") ? [] : t.slice(0, -1);
1795
- console.log("Parent path:", A);
1796
- const E = I.getState().getShadowMetadata(e, A);
1797
- if (console.log("Array metadata:", E), E?.arrayKeys) {
1798
- const b = [e, ...t.slice(0, -1)].join("."), N = E.arrayKeys.indexOf(b);
1799
- console.log("Item key:", b, "Index:", N);
1800
- const V = [...A, N, ...t.slice(-1)], O = JSON.stringify(p.path) === JSON.stringify(V);
1801
- return console.log("Zod path comparison:", {
1802
- zodPath: V,
1803
- errorPath: p.path,
1804
- match: O
1805
- }), O;
1806
- }
1807
- }
1808
- const T = JSON.stringify(p.path) === JSON.stringify(t);
1809
- return console.log("Direct path comparison:", {
1810
- errorPath: p.path,
1811
- currentPath: t,
1812
- match: T
1813
- }), T;
1814
- });
1815
- console.log("Filtered path errors:", h), x(e, t, {
1816
- ...g,
1817
- validation: {
1818
- status: "INVALID",
1819
- errors: h.map((p) => ({
1820
- source: "client",
1821
- message: p.message,
1822
- severity: "error"
1823
- // Hard error on blur
1824
- })),
1825
- lastValidated: Date.now(),
1826
- validatedValue: l
1827
- }
1828
- });
1829
- }
1830
- i({});
1831
- }, [e, t, l, s]), w = c({
1832
- path: t,
1833
- componentId: u
1834
- }), Y = new Proxy(w, {
1835
- get(f, R) {
1836
- return R === "inputProps" ? {
1837
- value: l ?? "",
1838
- onChange: (a) => {
1839
- U(a.target.value);
1840
- },
1841
- // 5. Wire the new onBlur handler to the input props.
1842
- onBlur: j,
1843
- ref: Ie.getState().getFormRef(e + "." + t.join("."))
1844
- } : f[R];
1845
- }
1846
- });
1847
- return /* @__PURE__ */ ne(_e, { formOpts: d, path: t, stateKey: e, children: n(Y) });
1848
- }
1849
- function Ue(e, t, c) {
1850
- const n = `${e}////${t}`;
1851
- ie(() => (ze(e, n, {
1852
- forceUpdate: () => c({}),
1853
- paths: /* @__PURE__ */ new Set(),
1854
- reactiveType: ["component"]
1855
- }), () => {
1856
- Ge(e, n);
1857
- }), [e, n]);
1858
- }
1859
1594
  export {
1860
- Ae as $cogsSignal,
1861
- Pt as addStateOptions,
1862
- tt as createCogsState,
1863
- Ct as createCogsStateFromSync,
1864
- ft as useCogsStateFn
1595
+ _e as $cogsSignal,
1596
+ Mt as addStateOptions,
1597
+ Xe as createCogsState,
1598
+ At as createCogsStateFromSync,
1599
+ lt as useCogsStateFn
1865
1600
  };
1866
1601
  //# sourceMappingURL=CogsState.jsx.map