cogsbox-state 0.5.214 → 0.5.216

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