cogsbox-state 0.5.201 → 0.5.202

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,16 +1,16 @@
1
1
  "use client";
2
2
  import { jsx as Se } from "react/jsx-runtime";
3
- import { useState as le, useRef as ee, useEffect as de, useLayoutEffect as ke, useMemo as $e, createElement as re, useSyncExternalStore as Te, startTransition as Ae } from "react";
4
- import { transformStateFunc as Ne, isDeepEqual as L, isFunction as Z, getNestedValue as q, getDifferences as he, debounce as Ve } from "./utility.js";
5
- import { pushFunc as se, updateFn as Q, cutFunc as K, ValidationWrapper as _e, FormControlComponent as Ce } from "./Functions.jsx";
3
+ import { useState as le, useRef as Q, useEffect as de, useLayoutEffect as pe, useMemo as ke, createElement as te, useSyncExternalStore as Ae, startTransition as Te } from "react";
4
+ import { transformStateFunc as Ne, isDeepEqual as M, isFunction as z, getNestedValue as W, getDifferences as he, debounce as Ve } from "./utility.js";
5
+ import { pushFunc as se, updateFn as Y, cutFunc as X, ValidationWrapper as _e, FormControlComponent as be } from "./Functions.jsx";
6
6
  import Pe from "superjson";
7
7
  import { v4 as ue } from "uuid";
8
8
  import "zod";
9
- import { getGlobalStore as t, formRefStore as me } from "./store.js";
10
- import { useCogsConfig as pe } from "./CogsStateClient.jsx";
11
- import { applyPatch as be } from "fast-json-patch";
9
+ import { getGlobalStore as n, formRefStore as me } from "./store.js";
10
+ import { useCogsConfig as we } from "./CogsStateClient.jsx";
11
+ import { applyPatch as Ce } from "fast-json-patch";
12
12
  function ye(e, i) {
13
- const S = t.getState().getInitialOptions, u = t.getState().setInitialStateOptions, f = S(e) || {};
13
+ const m = n.getState().getInitialOptions, u = n.getState().setInitialStateOptions, f = m(e) || {};
14
14
  u(e, {
15
15
  ...f,
16
16
  ...i
@@ -19,22 +19,22 @@ function ye(e, i) {
19
19
  function ve({
20
20
  stateKey: e,
21
21
  options: i,
22
- initialOptionsPart: S
22
+ initialOptionsPart: m
23
23
  }) {
24
- const u = H(e) || {}, f = S[e] || {}, k = t.getState().setInitialStateOptions, h = { ...f, ...u };
24
+ const u = Z(e) || {}, f = m[e] || {}, A = n.getState().setInitialStateOptions, p = { ...f, ...u };
25
25
  let v = !1;
26
26
  if (i)
27
27
  for (const s in i)
28
- h.hasOwnProperty(s) ? (s == "localStorage" && i[s] && h[s].key !== i[s]?.key && (v = !0, h[s] = i[s]), s == "initialState" && i[s] && h[s] !== i[s] && // Different references
29
- !L(h[s], i[s]) && (v = !0, h[s] = i[s])) : (v = !0, h[s] = i[s]);
30
- v && k(e, h);
28
+ p.hasOwnProperty(s) ? (s == "localStorage" && i[s] && p[s].key !== i[s]?.key && (v = !0, p[s] = i[s]), s == "initialState" && i[s] && p[s] !== i[s] && // Different references
29
+ !M(p[s], i[s]) && (v = !0, p[s] = i[s])) : (v = !0, p[s] = i[s]);
30
+ v && A(e, p);
31
31
  }
32
- function Qe(e, { formElements: i, validation: S }) {
33
- return { initialState: e, formElements: i, validation: S };
32
+ function Qe(e, { formElements: i, validation: m }) {
33
+ return { initialState: e, formElements: i, validation: m };
34
34
  }
35
35
  const Ke = (e, i) => {
36
- let S = e;
37
- const [u, f] = Ne(S);
36
+ let m = e;
37
+ const [u, f] = Ne(m);
38
38
  (Object.keys(f).length > 0 || i && Object.keys(i).length > 0) && Object.keys(f).forEach((v) => {
39
39
  f[v] = f[v] || {}, f[v].formElements = {
40
40
  ...i?.formElements,
@@ -42,21 +42,21 @@ const Ke = (e, i) => {
42
42
  ...i?.validation,
43
43
  ...f[v].formElements || {}
44
44
  // State-specific overrides
45
- }, H(v) || t.getState().setInitialStateOptions(v, f[v]);
46
- }), t.getState().setInitialStates(u), t.getState().setCreatedState(u);
47
- const k = (v, s) => {
48
- const [m] = le(s?.componentId ?? ue());
45
+ }, Z(v) || n.getState().setInitialStateOptions(v, f[v]);
46
+ }), n.getState().setInitialStates(u), n.getState().setCreatedState(u);
47
+ const A = (v, s) => {
48
+ const [y] = le(s?.componentId ?? ue());
49
49
  ve({
50
50
  stateKey: v,
51
51
  options: s,
52
52
  initialOptionsPart: f
53
53
  });
54
- const n = t.getState().cogsStateStore[v] || u[v], I = s?.modifyState ? s.modifyState(n) : n, [M, _] = Me(
54
+ const t = n.getState().cogsStateStore[v] || u[v], I = s?.modifyState ? s.modifyState(t) : t, [j, V] = De(
55
55
  I,
56
56
  {
57
57
  stateKey: v,
58
58
  syncUpdate: s?.syncUpdate,
59
- componentId: m,
59
+ componentId: y,
60
60
  localStorage: s?.localStorage,
61
61
  middleware: s?.middleware,
62
62
  enabledSync: s?.enabledSync,
@@ -67,49 +67,49 @@ const Ke = (e, i) => {
67
67
  serverState: s?.serverState
68
68
  }
69
69
  );
70
- return _;
70
+ return V;
71
71
  };
72
- function h(v, s) {
73
- ve({ stateKey: v, options: s, initialOptionsPart: f }), s.localStorage && je(v, s), oe(v);
72
+ function p(v, s) {
73
+ ve({ stateKey: v, options: s, initialOptionsPart: f }), s.localStorage && Re(v, s), re(v);
74
74
  }
75
- return { useCogsState: k, setCogsOptions: h };
75
+ return { useCogsState: A, setCogsOptions: p };
76
76
  }, {
77
- setUpdaterState: te,
78
- setState: Y,
79
- getInitialOptions: H,
80
- getKeyState: we,
77
+ setUpdaterState: K,
78
+ setState: J,
79
+ getInitialOptions: Z,
80
+ getKeyState: Ee,
81
81
  getValidationErrors: xe,
82
82
  setStateLog: Oe,
83
83
  updateInitialStateGlobal: ge,
84
84
  addValidationError: Fe,
85
- removeValidationError: B,
86
- setServerSyncActions: Re
87
- } = t.getState(), Ie = (e, i, S, u, f) => {
88
- S?.log && console.log(
85
+ removeValidationError: q,
86
+ setServerSyncActions: je
87
+ } = n.getState(), Ie = (e, i, m, u, f) => {
88
+ m?.log && console.log(
89
89
  "saving to localstorage",
90
90
  i,
91
- S.localStorage?.key,
91
+ m.localStorage?.key,
92
92
  u
93
93
  );
94
- const k = Z(S?.localStorage?.key) ? S.localStorage?.key(e) : S?.localStorage?.key;
95
- if (k && u) {
96
- const h = `${u}-${i}-${k}`;
94
+ const A = z(m?.localStorage?.key) ? m.localStorage?.key(e) : m?.localStorage?.key;
95
+ if (A && u) {
96
+ const p = `${u}-${i}-${A}`;
97
97
  let v;
98
98
  try {
99
- v = ae(h)?.lastSyncedWithServer;
99
+ v = ne(p)?.lastSyncedWithServer;
100
100
  } catch {
101
101
  }
102
102
  const s = {
103
103
  state: e,
104
104
  lastUpdated: Date.now(),
105
105
  lastSyncedWithServer: f ?? v
106
- }, m = Pe.serialize(s);
106
+ }, y = Pe.serialize(s);
107
107
  window.localStorage.setItem(
108
- h,
109
- JSON.stringify(m.json)
108
+ p,
109
+ JSON.stringify(y.json)
110
110
  );
111
111
  }
112
- }, ae = (e) => {
112
+ }, ne = (e) => {
113
113
  if (!e) return null;
114
114
  try {
115
115
  const i = window.localStorage.getItem(e);
@@ -117,61 +117,61 @@ const Ke = (e, i) => {
117
117
  } catch (i) {
118
118
  return console.error("Error loading from localStorage:", i), null;
119
119
  }
120
- }, je = (e, i) => {
121
- const S = t.getState().cogsStateStore[e], { sessionId: u } = pe(), f = Z(i?.localStorage?.key) ? i.localStorage.key(S) : i?.localStorage?.key;
120
+ }, Re = (e, i) => {
121
+ const m = n.getState().cogsStateStore[e], { sessionId: u } = we(), f = z(i?.localStorage?.key) ? i.localStorage.key(m) : i?.localStorage?.key;
122
122
  if (f && u) {
123
- const k = ae(
123
+ const A = ne(
124
124
  `${u}-${e}-${f}`
125
125
  );
126
- if (k && k.lastUpdated > (k.lastSyncedWithServer || 0))
127
- return Y(e, k.state), oe(e), !0;
126
+ if (A && A.lastUpdated > (A.lastSyncedWithServer || 0))
127
+ return J(e, A.state), re(e), !0;
128
128
  }
129
129
  return !1;
130
- }, Ee = (e, i, S, u, f, k) => {
131
- const h = {
130
+ }, $e = (e, i, m, u, f, A) => {
131
+ const p = {
132
132
  initialState: i,
133
- updaterState: ne(
133
+ updaterState: ee(
134
134
  e,
135
135
  u,
136
136
  f,
137
- k
137
+ A
138
138
  ),
139
- state: S
139
+ state: m
140
140
  };
141
- ge(e, h.initialState), te(e, h.updaterState), Y(e, h.state);
142
- }, oe = (e) => {
143
- const i = t.getState().stateComponents.get(e);
141
+ ge(e, p.initialState), K(e, p.updaterState), J(e, p.state);
142
+ }, re = (e) => {
143
+ const i = n.getState().stateComponents.get(e);
144
144
  if (!i) return;
145
- const S = /* @__PURE__ */ new Set();
145
+ const m = /* @__PURE__ */ new Set();
146
146
  i.components.forEach((u) => {
147
- (u ? Array.isArray(u.reactiveType) ? u.reactiveType : [u.reactiveType || "component"] : null)?.includes("none") || S.add(() => u.forceUpdate());
147
+ (u ? Array.isArray(u.reactiveType) ? u.reactiveType : [u.reactiveType || "component"] : null)?.includes("none") || m.add(() => u.forceUpdate());
148
148
  }), queueMicrotask(() => {
149
- S.forEach((u) => u());
149
+ m.forEach((u) => u());
150
150
  });
151
151
  }, et = (e, i) => {
152
- const S = t.getState().stateComponents.get(e);
153
- if (S) {
154
- const u = `${e}////${i}`, f = S.components.get(u);
152
+ const m = n.getState().stateComponents.get(e);
153
+ if (m) {
154
+ const u = `${e}////${i}`, f = m.components.get(u);
155
155
  if ((f ? Array.isArray(f.reactiveType) ? f.reactiveType : [f.reactiveType || "component"] : null)?.includes("none"))
156
156
  return;
157
157
  f && f.forceUpdate();
158
158
  }
159
- }, Ue = (e, i, S, u) => {
159
+ }, Ue = (e, i, m, u) => {
160
160
  switch (e) {
161
161
  case "update":
162
162
  return {
163
- oldValue: q(i, u),
164
- newValue: q(S, u)
163
+ oldValue: W(i, u),
164
+ newValue: W(m, u)
165
165
  };
166
166
  case "insert":
167
167
  return {
168
168
  oldValue: null,
169
169
  // or undefined
170
- newValue: q(S, u)
170
+ newValue: W(m, u)
171
171
  };
172
172
  case "cut":
173
173
  return {
174
- oldValue: q(i, u),
174
+ oldValue: W(i, u),
175
175
  newValue: null
176
176
  // or undefined
177
177
  };
@@ -179,830 +179,825 @@ const Ke = (e, i) => {
179
179
  return { oldValue: null, newValue: null };
180
180
  }
181
181
  };
182
- function Me(e, {
182
+ function De(e, {
183
183
  stateKey: i,
184
- serverSync: S,
184
+ serverSync: m,
185
185
  localStorage: u,
186
186
  formElements: f,
187
- reactiveDeps: k,
188
- reactiveType: h,
187
+ reactiveDeps: A,
188
+ reactiveType: p,
189
189
  componentId: v,
190
190
  initialState: s,
191
- syncUpdate: m,
192
- dependencies: n,
191
+ syncUpdate: y,
192
+ dependencies: t,
193
193
  serverState: I
194
194
  } = {}) {
195
- const [M, _] = le({}), { sessionId: C } = pe();
196
- let D = !i;
197
- const [g] = le(i ?? ue()), l = t.getState().stateLog[g], X = ee(/* @__PURE__ */ new Set()), J = ee(v ?? ue()), P = ee(
195
+ const [j, V] = le({}), { sessionId: _ } = we();
196
+ let R = !i;
197
+ const [g] = le(i ?? ue()), c = n.getState().stateLog[g], H = Q(/* @__PURE__ */ new Set()), L = Q(v ?? ue()), b = Q(
198
198
  null
199
199
  );
200
- P.current = H(g) ?? null, de(() => {
201
- if (m && m.stateKey === g && m.path?.[0]) {
202
- Y(g, (a) => ({
200
+ b.current = Z(g) ?? null, de(() => {
201
+ if (y && y.stateKey === g && y.path?.[0]) {
202
+ J(g, (a) => ({
203
203
  ...a,
204
- [m.path[0]]: m.newValue
204
+ [y.path[0]]: y.newValue
205
205
  }));
206
- const o = `${m.stateKey}:${m.path.join(".")}`;
207
- t.getState().setSyncInfo(o, {
208
- timeStamp: m.timeStamp,
209
- userId: m.userId
206
+ const o = `${y.stateKey}:${y.path.join(".")}`;
207
+ n.getState().setSyncInfo(o, {
208
+ timeStamp: y.timeStamp,
209
+ userId: y.userId
210
210
  });
211
211
  }
212
- }, [m]), de(() => {
212
+ }, [y]), de(() => {
213
213
  if (s) {
214
214
  ye(g, {
215
215
  initialState: s
216
216
  });
217
- const o = P.current, c = o?.serverState?.id !== void 0 && o?.serverState?.status === "success" && o?.serverState?.data, p = t.getState().initialStateGlobal[g];
218
- if (!(p && !L(p, s) || !p) && !c)
217
+ const o = b.current, d = o?.serverState?.id !== void 0 && o?.serverState?.status === "success" && o?.serverState?.data, w = n.getState().initialStateGlobal[g];
218
+ if (!(w && !M(w, s) || !w) && !d)
219
219
  return;
220
- let w = null;
221
- const $ = Z(o?.localStorage?.key) ? o?.localStorage?.key(s) : o?.localStorage?.key;
222
- $ && C && (w = ae(`${C}-${g}-${$}`));
223
- let A = s, T = !1;
224
- const V = c ? Date.now() : 0, R = w?.lastUpdated || 0, b = w?.lastSyncedWithServer || 0;
225
- c && V > R ? (A = o.serverState.data, T = !0) : w && R > b && (A = w.state, o?.localStorage?.onChange && o?.localStorage?.onChange(A)), Ee(
220
+ let h = null;
221
+ const E = z(o?.localStorage?.key) ? o?.localStorage?.key(s) : o?.localStorage?.key;
222
+ E && _ && (h = ne(`${_}-${g}-${E}`));
223
+ let $ = s, N = !1;
224
+ const P = d ? Date.now() : 0, B = h?.lastUpdated || 0, ae = h?.lastSyncedWithServer || 0;
225
+ d && P > B ? ($ = o.serverState.data, N = !0) : h && B > ae && ($ = h.state, o?.localStorage?.onChange && o?.localStorage?.onChange($)), $e(
226
226
  g,
227
227
  s,
228
- A,
229
- d,
230
- J.current,
231
- C
232
- ), T && $ && C && Ie(A, g, o, C, Date.now()), oe(g), (Array.isArray(h) ? h : [h || "component"]).includes("none") || _({});
228
+ $,
229
+ l,
230
+ L.current,
231
+ _
232
+ ), N && E && _ && Ie($, g, o, _, Date.now()), re(g), (Array.isArray(p) ? p : [p || "component"]).includes("none") || V({});
233
233
  }
234
234
  }, [
235
235
  s,
236
236
  I?.status,
237
237
  I?.data,
238
- ...n || []
239
- ]), ke(() => {
240
- D && ye(g, {
241
- serverSync: S,
238
+ ...t || []
239
+ ]), pe(() => {
240
+ R && ye(g, {
241
+ serverSync: m,
242
242
  formElements: f,
243
243
  initialState: s,
244
244
  localStorage: u,
245
- middleware: P.current?.middleware
245
+ middleware: b.current?.middleware
246
246
  });
247
- const o = `${g}////${J.current}`, a = t.getState().stateComponents.get(g) || {
247
+ const o = `${g}////${L.current}`, a = n.getState().stateComponents.get(g) || {
248
248
  components: /* @__PURE__ */ new Map()
249
249
  };
250
250
  return a.components.set(o, {
251
- forceUpdate: () => _({}),
251
+ forceUpdate: () => V({}),
252
252
  paths: /* @__PURE__ */ new Set(),
253
253
  deps: [],
254
- depsFunction: k || void 0,
255
- reactiveType: h ?? ["component", "deps"]
256
- }), t.getState().stateComponents.set(g, a), _({}), () => {
257
- const c = `${g}////${J.current}`;
258
- a && (a.components.delete(c), a.components.size === 0 && t.getState().stateComponents.delete(g));
254
+ depsFunction: A || void 0,
255
+ reactiveType: p ?? ["component", "deps"]
256
+ }), n.getState().stateComponents.set(g, a), V({}), () => {
257
+ const d = `${g}////${L.current}`;
258
+ a && (a.components.delete(d), a.components.size === 0 && n.getState().stateComponents.delete(g));
259
259
  };
260
260
  }, []);
261
- const d = (o, a, c, p) => {
261
+ const l = (o, a, d, w) => {
262
262
  if (Array.isArray(a)) {
263
- const y = `${g}-${a.join(".")}`;
264
- X.current.add(y);
263
+ const S = `${g}-${a.join(".")}`;
264
+ H.current.add(S);
265
265
  }
266
- Y(g, (y) => {
267
- const w = Z(o) ? o(y) : o, $ = `${g}-${a.join(".")}`;
268
- if ($) {
269
- let G = !1, N = t.getState().signalDomElements.get($);
270
- if ((!N || N.size === 0) && (c.updateType === "insert" || c.updateType === "cut")) {
271
- const j = a.slice(0, -1), W = q(w, j);
272
- if (Array.isArray(W)) {
273
- G = !0;
274
- const E = `${g}-${j.join(".")}`;
275
- N = t.getState().signalDomElements.get(E);
266
+ J(g, (S) => {
267
+ const h = z(o) ? o(S) : o, E = `${g}-${a.join(".")}`;
268
+ if (E) {
269
+ let D = !1, T = n.getState().signalDomElements.get(E);
270
+ if ((!T || T.size === 0) && (d.updateType === "insert" || d.updateType === "cut")) {
271
+ const O = a.slice(0, -1), U = W(h, O);
272
+ if (Array.isArray(U)) {
273
+ D = !0;
274
+ const k = `${g}-${O.join(".")}`;
275
+ T = n.getState().signalDomElements.get(k);
276
276
  }
277
277
  }
278
- if (N) {
279
- const j = G ? q(w, a.slice(0, -1)) : q(w, a);
280
- N.forEach(({ parentId: W, position: E, effect: F }) => {
281
- const O = document.querySelector(
282
- `[data-parent-id="${W}"]`
278
+ if (T) {
279
+ const O = D ? W(h, a.slice(0, -1)) : W(h, a);
280
+ T.forEach(({ parentId: U, position: k, effect: x }) => {
281
+ const C = document.querySelector(
282
+ `[data-parent-id="${U}"]`
283
283
  );
284
- if (O) {
285
- const z = Array.from(O.childNodes);
286
- if (z[E]) {
287
- const U = F ? new Function("state", `return (${F})(state)`)(j) : j;
288
- z[E].textContent = String(U);
284
+ if (C) {
285
+ const G = Array.from(C.childNodes);
286
+ if (G[k]) {
287
+ const F = x ? new Function("state", `return (${x})(state)`)(O) : O;
288
+ G[k].textContent = String(F);
289
289
  }
290
290
  }
291
291
  });
292
292
  }
293
293
  }
294
- c.updateType === "update" && (p || P.current?.validation?.key) && a && B(
295
- (p || P.current?.validation?.key) + "." + a.join(".")
294
+ d.updateType === "update" && (w || b.current?.validation?.key) && a && q(
295
+ (w || b.current?.validation?.key) + "." + a.join(".")
296
296
  );
297
- const A = a.slice(0, a.length - 1);
298
- c.updateType === "cut" && P.current?.validation?.key && B(
299
- P.current?.validation?.key + "." + A.join(".")
300
- ), c.updateType === "insert" && P.current?.validation?.key && xe(
301
- P.current?.validation?.key + "." + A.join(".")
302
- ).filter(([N, j]) => {
303
- let W = N?.split(".").length;
304
- if (N == A.join(".") && W == A.length - 1) {
305
- let E = N + "." + A;
306
- B(N), Fe(E, j);
297
+ const $ = a.slice(0, a.length - 1);
298
+ d.updateType === "cut" && b.current?.validation?.key && q(
299
+ b.current?.validation?.key + "." + $.join(".")
300
+ ), d.updateType === "insert" && b.current?.validation?.key && xe(
301
+ b.current?.validation?.key + "." + $.join(".")
302
+ ).filter(([T, O]) => {
303
+ let U = T?.split(".").length;
304
+ if (T == $.join(".") && U == $.length - 1) {
305
+ let k = T + "." + $;
306
+ q(T), Fe(k, O);
307
307
  }
308
308
  });
309
- const T = t.getState().stateComponents.get(g);
310
- if (T) {
311
- const G = he(y, w), N = new Set(G), j = c.updateType === "update" ? a.join(".") : a.slice(0, -1).join(".") || "";
309
+ const N = n.getState().stateComponents.get(g);
310
+ if (N) {
311
+ const D = he(S, h), T = new Set(D), O = d.updateType === "update" ? a.join(".") : a.slice(0, -1).join(".") || "";
312
312
  for (const [
313
- W,
314
- E
315
- ] of T.components.entries()) {
316
- let F = !1;
317
- const O = Array.isArray(E.reactiveType) ? E.reactiveType : [E.reactiveType || "component"];
318
- if (!O.includes("none")) {
319
- if (O.includes("all")) {
320
- E.forceUpdate();
313
+ U,
314
+ k
315
+ ] of N.components.entries()) {
316
+ let x = !1;
317
+ const C = Array.isArray(k.reactiveType) ? k.reactiveType : [k.reactiveType || "component"];
318
+ if (!C.includes("none")) {
319
+ if (C.includes("all")) {
320
+ k.forceUpdate();
321
321
  continue;
322
322
  }
323
- if (O.includes("component") && ((E.paths.has(j) || E.paths.has("")) && (F = !0), !F))
324
- for (const z of N) {
325
- let U = z;
323
+ if (C.includes("component") && ((k.paths.has(O) || k.paths.has("")) && (x = !0), !x))
324
+ for (const G of T) {
325
+ let F = G;
326
326
  for (; ; ) {
327
- if (E.paths.has(U)) {
328
- F = !0;
327
+ if (k.paths.has(F)) {
328
+ x = !0;
329
329
  break;
330
330
  }
331
- const ie = U.lastIndexOf(".");
331
+ const ie = F.lastIndexOf(".");
332
332
  if (ie !== -1) {
333
- const fe = U.substring(
333
+ const fe = F.substring(
334
334
  0,
335
335
  ie
336
336
  );
337
337
  if (!isNaN(
338
- Number(U.substring(ie + 1))
339
- ) && E.paths.has(fe)) {
340
- F = !0;
338
+ Number(F.substring(ie + 1))
339
+ ) && k.paths.has(fe)) {
340
+ x = !0;
341
341
  break;
342
342
  }
343
- U = fe;
343
+ F = fe;
344
344
  } else
345
- U = "";
346
- if (U === "")
345
+ F = "";
346
+ if (F === "")
347
347
  break;
348
348
  }
349
- if (F) break;
349
+ if (x) break;
350
350
  }
351
- if (!F && O.includes("deps") && E.depsFunction) {
352
- const z = E.depsFunction(w);
353
- let U = !1;
354
- typeof z == "boolean" ? z && (U = !0) : L(E.deps, z) || (E.deps = z, U = !0), U && (F = !0);
351
+ if (!x && C.includes("deps") && k.depsFunction) {
352
+ const G = k.depsFunction(h);
353
+ let F = !1;
354
+ typeof G == "boolean" ? G && (F = !0) : M(k.deps, G) || (k.deps = G, F = !0), F && (x = !0);
355
355
  }
356
- F && E.forceUpdate();
356
+ x && k.forceUpdate();
357
357
  }
358
358
  }
359
359
  }
360
- const V = Date.now();
361
- a = a.map((G, N) => {
362
- const j = a.slice(0, -1), W = q(w, j);
363
- return N === a.length - 1 && ["insert", "cut"].includes(c.updateType) ? (W.length - 1).toString() : G;
360
+ const P = Date.now();
361
+ a = a.map((D, T) => {
362
+ const O = a.slice(0, -1), U = W(h, O);
363
+ return T === a.length - 1 && ["insert", "cut"].includes(d.updateType) ? (U.length - 1).toString() : D;
364
364
  }), console.log(
365
365
  "mmmmmmmmmmmmmmmmm22222222222222",
366
- c.updateType,
367
- y,
368
- w,
366
+ d.updateType,
367
+ S,
368
+ h,
369
369
  a
370
370
  );
371
- const { oldValue: R, newValue: b } = Ue(
372
- c.updateType,
373
- y,
374
- w,
371
+ const { oldValue: B, newValue: ae } = Ue(
372
+ d.updateType,
373
+ S,
374
+ h,
375
375
  a
376
- ), x = {
377
- timeStamp: V,
376
+ ), oe = {
377
+ timeStamp: P,
378
378
  stateKey: g,
379
379
  path: a,
380
- updateType: c.updateType,
380
+ updateType: d.updateType,
381
381
  status: "new",
382
- oldValue: R,
383
- newValue: b
382
+ oldValue: B,
383
+ newValue: ae
384
384
  };
385
- if (Oe(g, (G) => {
386
- const j = [...G ?? [], x].reduce((W, E) => {
387
- const F = `${E.stateKey}:${JSON.stringify(E.path)}`, O = W.get(F);
388
- return O ? (O.timeStamp = Math.max(O.timeStamp, E.timeStamp), O.newValue = E.newValue, O.oldValue = O.oldValue ?? E.oldValue, O.updateType = E.updateType) : W.set(F, { ...E }), W;
385
+ if (Oe(g, (D) => {
386
+ const O = [...D ?? [], oe].reduce((U, k) => {
387
+ const x = `${k.stateKey}:${JSON.stringify(k.path)}`, C = U.get(x);
388
+ return C ? (C.timeStamp = Math.max(C.timeStamp, k.timeStamp), C.newValue = k.newValue, C.oldValue = C.oldValue ?? k.oldValue, C.updateType = k.updateType) : U.set(x, { ...k }), U;
389
389
  }, /* @__PURE__ */ new Map());
390
- return Array.from(j.values());
390
+ return Array.from(O.values());
391
391
  }), Ie(
392
- w,
392
+ h,
393
393
  g,
394
- P.current,
395
- C
396
- ), P.current?.middleware && P.current.middleware({
397
- updateLog: l,
398
- update: x
399
- }), P.current?.serverSync) {
400
- const G = t.getState().serverState[g], N = P.current?.serverSync;
401
- Re(g, {
402
- syncKey: typeof N.syncKey == "string" ? N.syncKey : N.syncKey({ state: w }),
403
- rollBackState: G,
404
- actionTimeStamp: Date.now() + (N.debounce ?? 3e3),
394
+ b.current,
395
+ _
396
+ ), b.current?.middleware && b.current.middleware({
397
+ updateLog: c,
398
+ update: oe
399
+ }), b.current?.serverSync) {
400
+ const D = n.getState().serverState[g], T = b.current?.serverSync;
401
+ je(g, {
402
+ syncKey: typeof T.syncKey == "string" ? T.syncKey : T.syncKey({ state: h }),
403
+ rollBackState: D,
404
+ actionTimeStamp: Date.now() + (T.debounce ?? 3e3),
405
405
  status: "waiting"
406
406
  });
407
407
  }
408
- return w;
408
+ return h;
409
409
  });
410
410
  };
411
- t.getState().updaterState[g] || (te(
411
+ n.getState().updaterState[g] || (K(
412
412
  g,
413
- ne(
413
+ ee(
414
414
  g,
415
- d,
416
- J.current,
417
- C
415
+ l,
416
+ L.current,
417
+ _
418
418
  )
419
- ), t.getState().cogsStateStore[g] || Y(g, e), t.getState().initialStateGlobal[g] || ge(g, e));
420
- const r = $e(() => ne(
419
+ ), n.getState().cogsStateStore[g] || J(g, e), n.getState().initialStateGlobal[g] || ge(g, e));
420
+ const r = ke(() => ee(
421
421
  g,
422
- d,
423
- J.current,
424
- C
422
+ l,
423
+ L.current,
424
+ _
425
425
  ), [g]);
426
- return [we(g), r];
426
+ return [Ee(g), r];
427
427
  }
428
- function ne(e, i, S, u) {
428
+ function ee(e, i, m, u) {
429
429
  const f = /* @__PURE__ */ new Map();
430
- let k = 0;
431
- const h = (m) => {
432
- const n = m.join(".");
430
+ let A = 0;
431
+ const p = (y) => {
432
+ const t = y.join(".");
433
433
  for (const [I] of f)
434
- (I === n || I.startsWith(n + ".")) && f.delete(I);
435
- k++;
434
+ (I === t || I.startsWith(t + ".")) && f.delete(I);
435
+ A++;
436
436
  }, v = {
437
- removeValidation: (m) => {
438
- m?.validationKey && B(m.validationKey);
437
+ removeValidation: (y) => {
438
+ y?.validationKey && q(y.validationKey);
439
439
  },
440
- revertToInitialState: (m) => {
441
- const n = t.getState().getInitialOptions(e)?.validation;
442
- n?.key && B(n?.key), m?.validationKey && B(m.validationKey);
443
- const I = t.getState().initialStateGlobal[e];
444
- t.getState().clearSelectedIndexesForState(e), f.clear(), k++;
445
- const M = s(I, []), _ = H(e), C = Z(_?.localStorage?.key) ? _?.localStorage?.key(I) : _?.localStorage?.key, D = `${u}-${e}-${C}`;
446
- D && localStorage.removeItem(D), te(e, M), Y(e, I);
447
- const g = t.getState().stateComponents.get(e);
448
- return g && g.components.forEach((l) => {
449
- l.forceUpdate();
440
+ revertToInitialState: (y) => {
441
+ const t = n.getState().getInitialOptions(e)?.validation;
442
+ t?.key && q(t?.key), y?.validationKey && q(y.validationKey);
443
+ const I = n.getState().initialStateGlobal[e];
444
+ n.getState().clearSelectedIndexesForState(e), f.clear(), A++;
445
+ const j = s(I, []), V = Z(e), _ = z(V?.localStorage?.key) ? V?.localStorage?.key(I) : V?.localStorage?.key, R = `${u}-${e}-${_}`;
446
+ R && localStorage.removeItem(R), K(e, j), J(e, I);
447
+ const g = n.getState().stateComponents.get(e);
448
+ return g && g.components.forEach((c) => {
449
+ c.forceUpdate();
450
450
  }), I;
451
451
  },
452
- updateInitialState: (m) => {
453
- f.clear(), k++;
454
- const n = ne(
452
+ updateInitialState: (y) => {
453
+ f.clear(), A++;
454
+ const t = ee(
455
455
  e,
456
456
  i,
457
- S,
457
+ m,
458
458
  u
459
- ), I = t.getState().initialStateGlobal[e], M = H(e), _ = Z(M?.localStorage?.key) ? M?.localStorage?.key(I) : M?.localStorage?.key, C = `${u}-${e}-${_}`;
460
- return console.log("removing storage", C), localStorage.getItem(C) && localStorage.removeItem(C), Ae(() => {
461
- ge(e, m), te(e, n), Y(e, m);
462
- const D = t.getState().stateComponents.get(e);
463
- D && D.components.forEach((g) => {
459
+ ), I = n.getState().initialStateGlobal[e], j = Z(e), V = z(j?.localStorage?.key) ? j?.localStorage?.key(I) : j?.localStorage?.key, _ = `${u}-${e}-${V}`;
460
+ return console.log("removing storage", _), localStorage.getItem(_) && localStorage.removeItem(_), Te(() => {
461
+ ge(e, y), K(e, t), J(e, y);
462
+ const R = n.getState().stateComponents.get(e);
463
+ R && R.components.forEach((g) => {
464
464
  g.forceUpdate();
465
465
  });
466
466
  }), {
467
- fetchId: (D) => n.get()[D]
467
+ fetchId: (R) => t.get()[R]
468
468
  };
469
469
  },
470
- _initialState: t.getState().initialStateGlobal[e],
471
- _serverState: t.getState().serverState[e],
472
- _isLoading: t.getState().isLoadingGlobal[e],
470
+ _initialState: n.getState().initialStateGlobal[e],
471
+ _serverState: n.getState().serverState[e],
472
+ _isLoading: n.getState().isLoadingGlobal[e],
473
473
  _isServerSynced: () => {
474
- const m = t.getState().serverState[e];
475
- return !!(m && L(m, we(e)));
474
+ const y = n.getState().serverState[e];
475
+ return !!(y && M(y, Ee(e)));
476
476
  }
477
477
  };
478
- function s(m, n = [], I) {
479
- const M = n.map(String).join(".");
480
- f.get(M);
481
- const _ = function() {
482
- return t().getNestedState(e, n);
478
+ function s(y, t = [], I) {
479
+ const j = t.map(String).join(".");
480
+ f.get(j);
481
+ const V = function() {
482
+ return n().getNestedState(e, t);
483
483
  };
484
484
  Object.keys(v).forEach((g) => {
485
- _[g] = v[g];
485
+ V[g] = v[g];
486
486
  });
487
- const C = {
488
- apply(g, l, X) {
487
+ const _ = {
488
+ apply(g, c, H) {
489
489
  return console.log(
490
- `PROXY APPLY TRAP HIT: stateKey=${e}, path=${n.join(".")}`
491
- ), console.trace("Apply trap stack trace"), t().getNestedState(e, n);
490
+ `PROXY APPLY TRAP HIT: stateKey=${e}, path=${t.join(".")}`
491
+ ), console.trace("Apply trap stack trace"), n().getNestedState(e, t);
492
492
  },
493
- get(g, l) {
494
- if (l !== "then" && !l.startsWith("$") && l !== "stateMapNoRender") {
495
- const d = n.join("."), r = `${e}////${S}`, o = t.getState().stateComponents.get(e);
493
+ get(g, c) {
494
+ if (c !== "then" && !c.startsWith("$") && c !== "stateMapNoRender") {
495
+ const l = t.join("."), r = `${e}////${m}`, o = n.getState().stateComponents.get(e);
496
496
  if (o) {
497
497
  const a = o.components.get(r);
498
- a && (n.length > 0 || l === "get") && a.paths.add(d);
498
+ a && (t.length > 0 || c === "get") && a.paths.add(l);
499
499
  }
500
500
  }
501
- if (l === "getDifferences")
501
+ if (c === "getDifferences")
502
502
  return () => he(
503
- t.getState().cogsStateStore[e],
504
- t.getState().initialStateGlobal[e]
503
+ n.getState().cogsStateStore[e],
504
+ n.getState().initialStateGlobal[e]
505
505
  );
506
- if (l === "sync" && n.length === 0)
506
+ if (c === "sync" && t.length === 0)
507
507
  return async function() {
508
- const d = t.getState().getInitialOptions(e), r = d?.sync;
508
+ const l = n.getState().getInitialOptions(e), r = l?.sync;
509
509
  if (!r)
510
510
  return console.error(`No mutation defined for state key "${e}"`), { success: !1, error: "No mutation defined" };
511
- const o = t.getState().getNestedState(e, []), a = d?.validation?.key;
511
+ const o = n.getState().getNestedState(e, []), a = l?.validation?.key;
512
512
  try {
513
- const c = await r.action(o);
514
- if (c && !c.success && c.errors && a) {
515
- t.getState().removeValidationError(a), c.errors.forEach((y) => {
516
- const w = [a, ...y.path].join(".");
517
- t.getState().addValidationError(w, y.message);
513
+ const d = await r.action(o);
514
+ if (d && !d.success && d.errors && a) {
515
+ n.getState().removeValidationError(a), d.errors.forEach((S) => {
516
+ const h = [a, ...S.path].join(".");
517
+ n.getState().addValidationError(h, S.message);
518
518
  });
519
- const p = t.getState().stateComponents.get(e);
520
- p && p.components.forEach((y) => {
521
- y.forceUpdate();
519
+ const w = n.getState().stateComponents.get(e);
520
+ w && w.components.forEach((S) => {
521
+ S.forceUpdate();
522
522
  });
523
523
  }
524
- return c?.success && r.onSuccess ? r.onSuccess(c.data) : !c?.success && r.onError && r.onError(c.error), c;
525
- } catch (c) {
526
- return r.onError && r.onError(c), { success: !1, error: c };
524
+ return d?.success && r.onSuccess ? r.onSuccess(d.data) : !d?.success && r.onError && r.onError(d.error), d;
525
+ } catch (d) {
526
+ return r.onError && r.onError(d), { success: !1, error: d };
527
527
  }
528
528
  };
529
- if (l === "_status") {
530
- const d = t.getState().getNestedState(e, n), r = t.getState().initialStateGlobal[e], o = q(r, n);
531
- return L(d, o) ? "fresh" : "stale";
529
+ if (c === "_status") {
530
+ const l = n.getState().getNestedState(e, t), r = n.getState().initialStateGlobal[e], o = W(r, t);
531
+ return M(l, o) ? "fresh" : "stale";
532
532
  }
533
- if (l === "getStatus")
533
+ if (c === "getStatus")
534
534
  return function() {
535
- const d = t().getNestedState(
535
+ const l = n().getNestedState(
536
536
  e,
537
- n
538
- ), r = t.getState().initialStateGlobal[e], o = q(r, n);
539
- return L(d, o) ? "fresh" : "stale";
537
+ t
538
+ ), r = n.getState().initialStateGlobal[e], o = W(r, t);
539
+ return M(l, o) ? "fresh" : "stale";
540
540
  };
541
- if (l === "removeStorage")
541
+ if (c === "removeStorage")
542
542
  return () => {
543
- const d = t.getState().initialStateGlobal[e], r = H(e), o = Z(r?.localStorage?.key) ? r?.localStorage?.key(d) : r?.localStorage?.key, a = `${u}-${e}-${o}`;
543
+ const l = n.getState().initialStateGlobal[e], r = Z(e), o = z(r?.localStorage?.key) ? r?.localStorage?.key(l) : r?.localStorage?.key, a = `${u}-${e}-${o}`;
544
544
  console.log("removing storage", a), a && localStorage.removeItem(a);
545
545
  };
546
- if (l === "showValidationErrors")
546
+ if (c === "showValidationErrors")
547
547
  return () => {
548
- const d = t.getState().getInitialOptions(e)?.validation;
549
- if (!d?.key)
548
+ const l = n.getState().getInitialOptions(e)?.validation;
549
+ if (!l?.key)
550
550
  throw new Error("Validation key not found");
551
- return t.getState().getValidationErrors(d.key + "." + n.join("."));
551
+ return n.getState().getValidationErrors(l.key + "." + t.join("."));
552
552
  };
553
- if (Array.isArray(m)) {
554
- const d = () => I?.validIndices ? m.map((o, a) => ({
553
+ if (Array.isArray(y)) {
554
+ const l = () => I?.validIndices ? y.map((o, a) => ({
555
555
  item: o,
556
556
  originalIndex: I.validIndices[a]
557
- })) : t.getState().getNestedState(e, n).map((o, a) => ({
557
+ })) : n.getState().getNestedState(e, t).map((o, a) => ({
558
558
  item: o,
559
559
  originalIndex: a
560
560
  }));
561
- if (l === "getSelected")
561
+ if (c === "getSelected")
562
562
  return () => {
563
- const r = t.getState().getSelectedIndex(e, n.join("."));
563
+ const r = n.getState().getSelectedIndex(e, t.join("."));
564
564
  if (r !== void 0)
565
565
  return s(
566
- m[r],
567
- [...n, r.toString()],
566
+ y[r],
567
+ [...t, r.toString()],
568
568
  I
569
569
  );
570
570
  };
571
- if (l === "clearSelected")
571
+ if (c === "clearSelected")
572
572
  return () => {
573
- t.getState().clearSelectedIndex({ stateKey: e, path: n });
573
+ n.getState().clearSelectedIndex({ stateKey: e, path: t });
574
574
  };
575
- if (l === "getSelectedIndex")
576
- return () => t.getState().getSelectedIndex(e, n.join(".")) ?? -1;
577
- if (l === "stateSort")
575
+ if (c === "getSelectedIndex")
576
+ return () => n.getState().getSelectedIndex(e, t.join(".")) ?? -1;
577
+ if (c === "stateSort")
578
578
  return (r) => {
579
- const a = [...d()].sort(
580
- (y, w) => r(y.item, w.item)
581
- ), c = a.map(({ item: y }) => y), p = {
579
+ const a = [...l()].sort(
580
+ (S, h) => r(S.item, h.item)
581
+ ), d = a.map(({ item: S }) => S), w = {
582
582
  ...I,
583
583
  validIndices: a.map(
584
- ({ originalIndex: y }) => y
584
+ ({ originalIndex: S }) => S
585
585
  )
586
586
  };
587
- return s(c, n, p);
587
+ return s(d, t, w);
588
588
  };
589
- if (l === "stateFilter")
589
+ if (c === "stateFilter")
590
590
  return (r) => {
591
- const a = d().filter(
592
- ({ item: y }, w) => r(y, w)
593
- ), c = a.map(({ item: y }) => y), p = {
591
+ const a = l().filter(
592
+ ({ item: S }, h) => r(S, h)
593
+ ), d = a.map(({ item: S }) => S), w = {
594
594
  ...I,
595
595
  validIndices: a.map(
596
- ({ originalIndex: y }) => y
596
+ ({ originalIndex: S }) => S
597
597
  )
598
598
  };
599
- return s(c, n, p);
599
+ return s(d, t, w);
600
600
  };
601
- if (l === "stateMap" || l === "stateMapNoRender")
602
- return (r) => m.map((a, c) => {
603
- let p;
604
- I?.validIndices && I.validIndices[c] !== void 0 ? p = I.validIndices[c] : p = c;
605
- const y = [...n, p.toString()], w = s(a, y, I);
601
+ if (c === "stateMap" || c === "stateMapNoRender")
602
+ return (r) => y.map((a, d) => {
603
+ let w;
604
+ I?.validIndices && I.validIndices[d] !== void 0 ? w = I.validIndices[d] : w = d;
605
+ const S = [...t, w.toString()], h = s(a, S, I);
606
606
  return r(
607
607
  a,
608
- w,
609
- c,
610
- m,
611
- s(m, n, I)
608
+ h,
609
+ d,
610
+ y,
611
+ s(y, t, I)
612
612
  );
613
613
  });
614
- if (l === "$stateMap")
615
- return (r) => re(De, {
614
+ if (c === "$stateMap")
615
+ return (r) => te(Me, {
616
616
  proxy: {
617
617
  _stateKey: e,
618
- _path: n,
618
+ _path: t,
619
619
  _mapFn: r
620
620
  // Pass the actual function, not string
621
621
  },
622
622
  rebuildStateShape: s
623
623
  });
624
- if (l === "stateFlattenOn")
624
+ if (c === "stateFlattenOn")
625
625
  return (r) => {
626
- const o = m;
627
- f.clear(), k++;
626
+ const o = y;
627
+ f.clear(), A++;
628
628
  const a = o.flatMap(
629
- (c) => c[r] ?? []
629
+ (d) => d[r] ?? []
630
630
  );
631
631
  return s(
632
632
  a,
633
- [...n, "[*]", r],
633
+ [...t, "[*]", r],
634
634
  I
635
635
  );
636
636
  };
637
- if (l === "index")
637
+ if (c === "index")
638
638
  return (r) => {
639
- const o = m[r];
640
- return s(o, [...n, r.toString()]);
639
+ const o = y[r];
640
+ return s(o, [...t, r.toString()]);
641
641
  };
642
- if (l === "last")
642
+ if (c === "last")
643
643
  return () => {
644
- const r = t.getState().getNestedState(e, n);
644
+ const r = n.getState().getNestedState(e, t);
645
645
  if (r.length === 0) return;
646
- const o = r.length - 1, a = r[o], c = [...n, o.toString()];
647
- return s(a, c);
646
+ const o = r.length - 1, a = r[o], d = [...t, o.toString()];
647
+ return s(a, d);
648
648
  };
649
- if (l === "insert")
650
- return (r) => (h(n), se(i, r, n, e), s(
651
- t.getState().getNestedState(e, n),
652
- n
649
+ if (c === "insert")
650
+ return (r) => (p(t), se(i, r, t, e), s(
651
+ n.getState().getNestedState(e, t),
652
+ t
653
653
  ));
654
- if (l === "uniqueInsert")
654
+ if (c === "uniqueInsert")
655
655
  return (r, o, a) => {
656
- const c = t.getState().getNestedState(e, n), p = Z(r) ? r(c) : r;
657
- let y = null;
658
- if (!c.some(($) => {
656
+ const d = n.getState().getNestedState(e, t), w = z(r) ? r(d) : r;
657
+ let S = null;
658
+ if (!d.some((E) => {
659
659
  if (o) {
660
- const T = o.every(
661
- (V) => L($[V], p[V])
660
+ const N = o.every(
661
+ (P) => M(E[P], w[P])
662
662
  );
663
- return T && (y = $), T;
663
+ return N && (S = E), N;
664
664
  }
665
- const A = L($, p);
666
- return A && (y = $), A;
665
+ const $ = M(E, w);
666
+ return $ && (S = E), $;
667
667
  }))
668
- h(n), se(i, p, n, e);
669
- else if (a && y) {
670
- const $ = a(y), A = c.map(
671
- (T) => L(T, y) ? $ : T
668
+ p(t), se(i, w, t, e);
669
+ else if (a && S) {
670
+ const E = a(S), $ = d.map(
671
+ (N) => M(N, S) ? E : N
672
672
  );
673
- h(n), Q(i, A, n);
673
+ p(t), Y(i, $, t);
674
674
  }
675
675
  };
676
- if (l === "cut")
676
+ if (c === "cut")
677
677
  return (r, o) => {
678
678
  if (!o?.waitForSync)
679
- return h(n), K(i, n, e, r), s(
680
- t.getState().getNestedState(e, n),
681
- n
679
+ return p(t), X(i, t, e, r), s(
680
+ n.getState().getNestedState(e, t),
681
+ t
682
682
  );
683
683
  };
684
- if (l === "cutByValue")
684
+ if (c === "cutByValue")
685
685
  return (r) => {
686
- for (let o = 0; o < m.length; o++)
687
- m[o] === r && K(i, n, e, o);
686
+ for (let o = 0; o < y.length; o++)
687
+ y[o] === r && X(i, t, e, o);
688
688
  };
689
- if (l === "toggleByValue")
689
+ if (c === "toggleByValue")
690
690
  return (r) => {
691
- const o = m.findIndex((a) => a === r);
692
- o > -1 ? K(i, n, e, o) : se(i, r, n, e);
691
+ const o = y.findIndex((a) => a === r);
692
+ o > -1 ? X(i, t, e, o) : se(i, r, t, e);
693
693
  };
694
- if (l === "stateFind")
694
+ if (c === "stateFind")
695
695
  return (r) => {
696
- const a = d().find(
697
- ({ item: p }, y) => r(p, y)
696
+ const a = l().find(
697
+ ({ item: w }, S) => r(w, S)
698
698
  );
699
699
  if (!a) return;
700
- const c = [...n, a.originalIndex.toString()];
701
- return s(a.item, c, I);
700
+ const d = [...t, a.originalIndex.toString()];
701
+ return s(a.item, d, I);
702
702
  };
703
- if (l === "findWith")
703
+ if (c === "findWith")
704
704
  return (r, o) => {
705
- const c = d().find(
706
- ({ item: y }) => y[r] === o
705
+ const d = l().find(
706
+ ({ item: S }) => S[r] === o
707
707
  );
708
- if (!c) return;
709
- const p = [...n, c.originalIndex.toString()];
710
- return s(c.item, p, I);
708
+ if (!d) return;
709
+ const w = [...t, d.originalIndex.toString()];
710
+ return s(d.item, w, I);
711
711
  };
712
712
  }
713
- const X = n[n.length - 1];
714
- if (!isNaN(Number(X))) {
715
- const d = n.slice(0, -1), r = t.getState().getNestedState(e, d);
716
- if (Array.isArray(r) && l === "cut")
717
- return () => K(
713
+ const H = t[t.length - 1];
714
+ if (!isNaN(Number(H))) {
715
+ const l = t.slice(0, -1), r = n.getState().getNestedState(e, l);
716
+ if (Array.isArray(r) && c === "cut")
717
+ return () => X(
718
718
  i,
719
- d,
719
+ l,
720
720
  e,
721
- Number(X)
721
+ Number(H)
722
722
  );
723
723
  }
724
- if (l === "get")
725
- return () => t.getState().getNestedState(e, n);
726
- if (l === "$derive")
727
- return (d) => ce({
724
+ if (c === "get")
725
+ return () => n.getState().getNestedState(e, t);
726
+ if (c === "$derive")
727
+ return (l) => ce({
728
728
  _stateKey: e,
729
- _path: n,
730
- _effect: d.toString()
729
+ _path: t,
730
+ _effect: l.toString()
731
731
  });
732
- if (l === "$derive")
733
- return (d) => ce({
732
+ if (c === "$derive")
733
+ return (l) => ce({
734
734
  _stateKey: e,
735
- _path: n,
736
- _effect: d.toString()
735
+ _path: t,
736
+ _effect: l.toString()
737
737
  });
738
- if (l === "$get")
738
+ if (c === "$get")
739
739
  return () => ce({
740
740
  _stateKey: e,
741
- _path: n
741
+ _path: t
742
742
  });
743
- if (l === "lastSynced") {
744
- const d = `${e}:${n.join(".")}`;
745
- return t.getState().getSyncInfo(d);
743
+ if (c === "lastSynced") {
744
+ const l = `${e}:${t.join(".")}`;
745
+ return n.getState().getSyncInfo(l);
746
746
  }
747
- if (l == "getLocalStorage")
748
- return (d) => ae(u + "-" + e + "-" + d);
749
- if (l === "_selected") {
750
- const d = n.slice(0, -1), r = d.join("."), o = t.getState().getNestedState(e, d);
751
- return Array.isArray(o) ? Number(n[n.length - 1]) === t.getState().getSelectedIndex(e, r) : void 0;
747
+ if (c == "getLocalStorage")
748
+ return (l) => ne(u + "-" + e + "-" + l);
749
+ if (c === "_selected") {
750
+ const l = t.slice(0, -1), r = l.join("."), o = n.getState().getNestedState(e, l);
751
+ return Array.isArray(o) ? Number(t[t.length - 1]) === n.getState().getSelectedIndex(e, r) : void 0;
752
752
  }
753
- if (l === "setSelected")
754
- return (d) => {
755
- const r = n.slice(0, -1), o = Number(n[n.length - 1]), a = r.join(".");
756
- d ? t.getState().setSelectedIndex(e, a, o) : t.getState().setSelectedIndex(e, a, void 0);
757
- const c = t.getState().getNestedState(e, [...r]);
758
- Q(i, c, r), h(r);
753
+ if (c === "setSelected")
754
+ return (l) => {
755
+ const r = t.slice(0, -1), o = Number(t[t.length - 1]), a = r.join(".");
756
+ l ? n.getState().setSelectedIndex(e, a, o) : n.getState().setSelectedIndex(e, a, void 0);
757
+ const d = n.getState().getNestedState(e, [...r]);
758
+ Y(i, d, r), p(r);
759
759
  };
760
- if (l === "toggleSelected")
760
+ if (c === "toggleSelected")
761
761
  return () => {
762
- const d = n.slice(0, -1), r = Number(n[n.length - 1]), o = d.join("."), a = t.getState().getSelectedIndex(e, o);
763
- t.getState().setSelectedIndex(
762
+ const l = t.slice(0, -1), r = Number(t[t.length - 1]), o = l.join("."), a = n.getState().getSelectedIndex(e, o);
763
+ n.getState().setSelectedIndex(
764
764
  e,
765
765
  o,
766
766
  a === r ? void 0 : r
767
767
  );
768
- const c = t.getState().getNestedState(e, [...d]);
769
- Q(i, c, d), h(d);
768
+ const d = n.getState().getNestedState(e, [...l]);
769
+ Y(i, d, l), p(l);
770
770
  };
771
- if (n.length == 0) {
772
- if (l === "applyJsonPatch")
773
- return (d) => {
774
- const r = t.getState().cogsStateStore[e], a = be(r, d).newDocument, c = H(e), p = c?.middleware, y = t.getState().setInitialStateOptions;
775
- c && p && y(e, {
776
- ...c,
777
- middleware: void 0
778
- }), Ee(
771
+ if (t.length == 0) {
772
+ if (c === "applyJsonPatch")
773
+ return (l) => {
774
+ const r = n.getState().cogsStateStore[e], a = Ce(r, l).newDocument;
775
+ $e(
779
776
  e,
780
- t.getState().initialStateGlobal[e],
777
+ n.getState().initialStateGlobal[e],
781
778
  a,
782
779
  i,
783
- S,
780
+ m,
784
781
  u
785
- ), c && p && y(e, {
786
- ...c,
787
- middleware: p
788
- });
789
- const w = t.getState().stateComponents.get(e);
790
- if (console.log("component update logic stateEntry", w), !w) return;
791
- const $ = /* @__PURE__ */ new Set();
792
- console.log("component update logic pathsToCheck", $), Array.isArray(r) && Array.isArray(a) && r.length !== a.length && $.add(""), console.log("component update logic pathsToCheck", $), d.forEach((A) => {
793
- const V = A.path.slice(1).split("/");
794
- if (A.op === "add" || A.op === "remove") {
795
- const b = V[V.length - 1];
796
- if (!isNaN(parseInt(b))) {
797
- const x = V.slice(0, -1).join(".");
798
- $.add(x), x === "" && $.add("");
799
- }
800
- }
801
- let R = "";
802
- V.forEach((b, x) => {
803
- x > 0 && (R += "."), R += b, $.add(R);
804
- }), $.add("");
782
+ );
783
+ const d = n.getState().stateComponents.get(e);
784
+ if (!d) return;
785
+ const w = /* @__PURE__ */ new Set(), S = (h, E) => {
786
+ w.add(h), Array.isArray(E) ? E.forEach(($, N) => {
787
+ S(`${h}.${N}`, $);
788
+ }) : typeof E == "object" && E !== null && Object.keys(E).forEach(($) => {
789
+ S(`${h}.${$}`, E[$]);
790
+ });
791
+ };
792
+ l.forEach((h) => {
793
+ const E = h.path.slice(1).replace(/\//g, ".");
794
+ w.add(E);
795
+ let $ = E;
796
+ for (; $.includes("."); )
797
+ $ = $.substring(
798
+ 0,
799
+ $.lastIndexOf(".")
800
+ ), w.add($);
801
+ w.add(""), (h.op === "add" || h.op === "replace") && h.value && S(E, h.value);
805
802
  });
806
803
  for (const [
807
- A,
808
- T
809
- ] of w.components.entries()) {
810
- console.log("component update logic component", T);
811
- let V = !1;
812
- const R = Array.isArray(T.reactiveType) ? T.reactiveType : [T.reactiveType || "component"];
813
- if (!R.includes("none")) {
814
- if (R.includes("all")) {
815
- T.forceUpdate();
804
+ h,
805
+ E
806
+ ] of d.components.entries()) {
807
+ let $ = !1;
808
+ const N = Array.isArray(E.reactiveType) ? E.reactiveType : [E.reactiveType || "component"];
809
+ if (!N.includes("none")) {
810
+ if (N.includes("all")) {
811
+ E.forceUpdate();
816
812
  continue;
817
813
  }
818
- if (R.includes("component"))
819
- for (const b of T.paths) {
820
- if ($.has(b)) {
821
- V = !0;
814
+ if (N.includes("component"))
815
+ for (const P of E.paths) {
816
+ if (w.has(P)) {
817
+ $ = !0;
822
818
  break;
823
819
  }
824
- for (const x of $)
825
- if (x.startsWith(b + ".") || b === "" && x !== "") {
826
- V = !0;
820
+ for (const B of w)
821
+ if (P.startsWith(B + ".")) {
822
+ $ = !0;
827
823
  break;
828
824
  }
829
- if (V) break;
825
+ if ($) break;
830
826
  }
831
- if (!V && R.includes("deps") && T.depsFunction) {
832
- const b = T.depsFunction(a);
833
- let x = !1;
834
- typeof b == "boolean" ? b && (x = !0) : L(T.deps, b) || (T.deps = b, x = !0), x && (V = !0);
827
+ if (!$ && N.includes("deps") && E.depsFunction) {
828
+ const P = E.depsFunction(a);
829
+ (typeof P == "boolean" ? P : !M(E.deps, P)) && (E.deps = Array.isArray(P) ? P : [], $ = !0);
835
830
  }
836
- V && T.forceUpdate();
831
+ $ && E.forceUpdate();
837
832
  }
838
833
  }
839
834
  };
840
- if (l === "validateZodSchema")
835
+ if (c === "validateZodSchema")
841
836
  return () => {
842
- const d = t.getState().getInitialOptions(e)?.validation, r = t.getState().addValidationError;
843
- if (!d?.zodSchema)
837
+ const l = n.getState().getInitialOptions(e)?.validation, r = n.getState().addValidationError;
838
+ if (!l?.zodSchema)
844
839
  throw new Error("Zod schema not found");
845
- if (!d?.key)
840
+ if (!l?.key)
846
841
  throw new Error("Validation key not found");
847
- B(d.key);
848
- const o = t.getState().cogsStateStore[e];
842
+ q(l.key);
843
+ const o = n.getState().cogsStateStore[e];
849
844
  try {
850
- const a = t.getState().getValidationErrors(d.key);
851
- a && a.length > 0 && a.forEach(([p]) => {
852
- p && p.startsWith(d.key) && B(p);
845
+ const a = n.getState().getValidationErrors(l.key);
846
+ a && a.length > 0 && a.forEach(([w]) => {
847
+ w && w.startsWith(l.key) && q(w);
853
848
  });
854
- const c = d.zodSchema.safeParse(o);
855
- return c.success ? !0 : (c.error.errors.forEach((y) => {
856
- const w = y.path, $ = y.message, A = [d.key, ...w].join(".");
857
- r(A, $);
858
- }), oe(e), !1);
849
+ const d = l.zodSchema.safeParse(o);
850
+ return d.success ? !0 : (d.error.errors.forEach((S) => {
851
+ const h = S.path, E = S.message, $ = [l.key, ...h].join(".");
852
+ r($, E);
853
+ }), re(e), !1);
859
854
  } catch (a) {
860
855
  return console.error("Zod schema validation failed", a), !1;
861
856
  }
862
857
  };
863
- if (l === "_componentId") return S;
864
- if (l === "getComponents")
865
- return () => t().stateComponents.get(e);
866
- if (l === "getAllFormRefs")
858
+ if (c === "_componentId") return m;
859
+ if (c === "getComponents")
860
+ return () => n().stateComponents.get(e);
861
+ if (c === "getAllFormRefs")
867
862
  return () => me.getState().getFormRefsByStateKey(e);
868
- if (l === "_initialState")
869
- return t.getState().initialStateGlobal[e];
870
- if (l === "_serverState")
871
- return t.getState().serverState[e];
872
- if (l === "_isLoading")
873
- return t.getState().isLoadingGlobal[e];
874
- if (l === "revertToInitialState")
863
+ if (c === "_initialState")
864
+ return n.getState().initialStateGlobal[e];
865
+ if (c === "_serverState")
866
+ return n.getState().serverState[e];
867
+ if (c === "_isLoading")
868
+ return n.getState().isLoadingGlobal[e];
869
+ if (c === "revertToInitialState")
875
870
  return v.revertToInitialState;
876
- if (l === "updateInitialState") return v.updateInitialState;
877
- if (l === "removeValidation") return v.removeValidation;
871
+ if (c === "updateInitialState") return v.updateInitialState;
872
+ if (c === "removeValidation") return v.removeValidation;
878
873
  }
879
- if (l === "getFormRef")
880
- return () => me.getState().getFormRef(e + "." + n.join("."));
881
- if (l === "validationWrapper")
874
+ if (c === "getFormRef")
875
+ return () => me.getState().getFormRef(e + "." + t.join("."));
876
+ if (c === "validationWrapper")
882
877
  return ({
883
- children: d,
878
+ children: l,
884
879
  hideMessage: r
885
880
  }) => /* @__PURE__ */ Se(
886
881
  _e,
887
882
  {
888
883
  formOpts: r ? { validation: { message: "" } } : void 0,
889
- path: n,
890
- validationKey: t.getState().getInitialOptions(e)?.validation?.key || "",
884
+ path: t,
885
+ validationKey: n.getState().getInitialOptions(e)?.validation?.key || "",
891
886
  stateKey: e,
892
887
  validIndices: I?.validIndices,
893
- children: d
888
+ children: l
894
889
  }
895
890
  );
896
- if (l === "_stateKey") return e;
897
- if (l === "_path") return n;
898
- if (l === "_isServerSynced") return v._isServerSynced;
899
- if (l === "update")
900
- return (d, r) => {
891
+ if (c === "_stateKey") return e;
892
+ if (c === "_path") return t;
893
+ if (c === "_isServerSynced") return v._isServerSynced;
894
+ if (c === "update")
895
+ return (l, r) => {
901
896
  if (r?.debounce)
902
897
  Ve(() => {
903
- Q(i, d, n, "");
904
- const o = t.getState().getNestedState(e, n);
898
+ Y(i, l, t, "");
899
+ const o = n.getState().getNestedState(e, t);
905
900
  r?.afterUpdate && r.afterUpdate(o);
906
901
  }, r.debounce);
907
902
  else {
908
- Q(i, d, n, "");
909
- const o = t.getState().getNestedState(e, n);
903
+ Y(i, l, t, "");
904
+ const o = n.getState().getNestedState(e, t);
910
905
  r?.afterUpdate && r.afterUpdate(o);
911
906
  }
912
- h(n);
907
+ p(t);
913
908
  };
914
- if (l === "formElement")
915
- return (d, r) => /* @__PURE__ */ Se(
916
- Ce,
909
+ if (c === "formElement")
910
+ return (l, r) => /* @__PURE__ */ Se(
911
+ be,
917
912
  {
918
913
  setState: i,
919
914
  stateKey: e,
920
- path: n,
921
- child: d,
915
+ path: t,
916
+ child: l,
922
917
  formOpts: r
923
918
  }
924
919
  );
925
- const J = [...n, l], P = t.getState().getNestedState(e, J);
926
- return s(P, J, I);
920
+ const L = [...t, c], b = n.getState().getNestedState(e, L);
921
+ return s(b, L, I);
927
922
  }
928
- }, D = new Proxy(_, C);
929
- return f.set(M, {
930
- proxy: D,
931
- stateVersion: k
932
- }), D;
923
+ }, R = new Proxy(V, _);
924
+ return f.set(j, {
925
+ proxy: R,
926
+ stateVersion: A
927
+ }), R;
933
928
  }
934
929
  return s(
935
- t.getState().getNestedState(e, [])
930
+ n.getState().getNestedState(e, [])
936
931
  );
937
932
  }
938
933
  function ce(e) {
939
- return re(We, { proxy: e });
934
+ return te(We, { proxy: e });
940
935
  }
941
- function De({
936
+ function Me({
942
937
  proxy: e,
943
938
  rebuildStateShape: i
944
939
  }) {
945
- const S = t().getNestedState(e._stateKey, e._path);
946
- return Array.isArray(S) ? i(
947
- S,
940
+ const m = n().getNestedState(e._stateKey, e._path);
941
+ return Array.isArray(m) ? i(
942
+ m,
948
943
  e._path
949
944
  ).stateMapNoRender(
950
- (f, k, h, v, s) => e._mapFn(f, k, h, v, s)
945
+ (f, A, p, v, s) => e._mapFn(f, A, p, v, s)
951
946
  ) : null;
952
947
  }
953
948
  function We({
954
949
  proxy: e
955
950
  }) {
956
- const i = ee(null), S = `${e._stateKey}-${e._path.join(".")}`;
951
+ const i = Q(null), m = `${e._stateKey}-${e._path.join(".")}`;
957
952
  return de(() => {
958
953
  const u = i.current;
959
954
  if (!u || !u.parentElement) return;
960
- const f = u.parentElement, h = Array.from(f.childNodes).indexOf(u);
955
+ const f = u.parentElement, p = Array.from(f.childNodes).indexOf(u);
961
956
  let v = f.getAttribute("data-parent-id");
962
957
  v || (v = `parent-${crypto.randomUUID()}`, f.setAttribute("data-parent-id", v));
963
- const m = {
958
+ const y = {
964
959
  instanceId: `instance-${crypto.randomUUID()}`,
965
960
  parentId: v,
966
- position: h,
961
+ position: p,
967
962
  effect: e._effect
968
963
  };
969
- t.getState().addSignalElement(S, m);
970
- const n = t.getState().getNestedState(e._stateKey, e._path);
964
+ n.getState().addSignalElement(m, y);
965
+ const t = n.getState().getNestedState(e._stateKey, e._path);
971
966
  let I;
972
967
  if (e._effect)
973
968
  try {
974
969
  I = new Function(
975
970
  "state",
976
971
  `return (${e._effect})(state)`
977
- )(n);
978
- } catch (_) {
979
- console.error("Error evaluating effect function during mount:", _), I = n;
972
+ )(t);
973
+ } catch (V) {
974
+ console.error("Error evaluating effect function during mount:", V), I = t;
980
975
  }
981
976
  else
982
- I = n;
977
+ I = t;
983
978
  I !== null && typeof I == "object" && (I = JSON.stringify(I));
984
- const M = document.createTextNode(String(I));
985
- u.replaceWith(M);
986
- }, [e._stateKey, e._path.join("."), e._effect]), re("span", {
979
+ const j = document.createTextNode(String(I));
980
+ u.replaceWith(j);
981
+ }, [e._stateKey, e._path.join("."), e._effect]), te("span", {
987
982
  ref: i,
988
983
  style: { display: "none" },
989
- "data-signal-id": S
984
+ "data-signal-id": m
990
985
  });
991
986
  }
992
987
  function tt(e) {
993
- const i = Te(
994
- (S) => {
995
- const u = t.getState().stateComponents.get(e._stateKey) || {
988
+ const i = Ae(
989
+ (m) => {
990
+ const u = n.getState().stateComponents.get(e._stateKey) || {
996
991
  components: /* @__PURE__ */ new Map()
997
992
  };
998
993
  return u.components.set(e._stateKey, {
999
- forceUpdate: S,
994
+ forceUpdate: m,
1000
995
  paths: /* @__PURE__ */ new Set([e._path.join(".")])
1001
996
  }), () => u.components.delete(e._stateKey);
1002
997
  },
1003
- () => t.getState().getNestedState(e._stateKey, e._path)
998
+ () => n.getState().getNestedState(e._stateKey, e._path)
1004
999
  );
1005
- return re("text", {}, String(i));
1000
+ return te("text", {}, String(i));
1006
1001
  }
1007
1002
  export {
1008
1003
  ce as $cogsSignal,
@@ -1010,6 +1005,6 @@ export {
1010
1005
  Qe as addStateOptions,
1011
1006
  Ke as createCogsState,
1012
1007
  et as notifyComponent,
1013
- Me as useCogsStateFn
1008
+ De as useCogsStateFn
1014
1009
  };
1015
1010
  //# sourceMappingURL=CogsState.jsx.map