cogsbox-state 0.5.210 → 0.5.211

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