cogsbox-state 0.5.191 → 0.5.192

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