cogsbox-state 0.5.19 → 0.5.20

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,362 +1,362 @@
1
1
  "use client";
2
- import { jsx as ot } from "react/jsx-runtime";
3
- import { useState as X, useRef as z, useEffect as Y, useLayoutEffect as It, useMemo as Et, createElement as H, useSyncExternalStore as _t, startTransition as J } from "react";
4
- import { transformStateFunc as pt, isFunction as ut, getNestedValue as k, isDeepEqual as G, debounce as wt } from "./utility.js";
5
- import { pushFunc as it, updateFn as q, cutFunc as st, ValidationWrapper as $t, FormControlComponent as Vt } from "./Functions.jsx";
2
+ import { jsx as it } from "react/jsx-runtime";
3
+ import { useState as Y, useRef as J, useEffect as K, useLayoutEffect as It, useMemo as Et, createElement as Q, useSyncExternalStore as _t, startTransition as B } from "react";
4
+ import { transformStateFunc as pt, isFunction as ft, getNestedValue as G, isDeepEqual as W, debounce as wt } from "./utility.js";
5
+ import { pushFunc as st, updateFn as z, cutFunc as ct, ValidationWrapper as $t, FormControlComponent as Vt } from "./Functions.jsx";
6
6
  import "zod";
7
- import { getGlobalStore as r, formRefStore as ct } from "./store.js";
7
+ import { getGlobalStore as r, formRefStore as lt } from "./store.js";
8
8
  import { useCogsConfig as Nt } from "./CogsStateClient.jsx";
9
- import K from "./node_modules/uuid/dist/esm-browser/v4.js";
10
- function lt(t, o) {
11
- const g = r.getState().getInitialOptions, S = r.getState().setInitialStateOptions, l = g(t) || {};
12
- S(t, {
13
- ...l,
14
- ...o
9
+ import tt from "./node_modules/uuid/dist/esm-browser/v4.js";
10
+ function dt(t, i) {
11
+ const f = r.getState().getInitialOptions, g = r.getState().setInitialStateOptions, d = f(t) || {};
12
+ g(t, {
13
+ ...d,
14
+ ...i
15
15
  });
16
16
  }
17
- function dt({
17
+ function ut({
18
18
  stateKey: t,
19
- options: o,
20
- initialOptionsPart: g
19
+ options: i,
20
+ initialOptionsPart: f
21
21
  }) {
22
- const S = tt(t) || {}, l = g[t] || {}, E = r.getState().setInitialStateOptions, _ = { ...l, ...S };
22
+ const g = et(t) || {}, d = f[t] || {}, E = r.getState().setInitialStateOptions, _ = { ...d, ...g };
23
23
  let v = !1;
24
- if (o)
25
- for (const m in o)
26
- _.hasOwnProperty(m) || (v = !0, _[m] = o[m]);
24
+ if (i)
25
+ for (const S in i)
26
+ _.hasOwnProperty(S) || (v = !0, _[S] = i[S]);
27
27
  v && E(t, _);
28
28
  }
29
- function qt(t, { formElements: o, validation: g }) {
30
- return { initialState: t, formElements: o, validation: g };
29
+ function qt(t, { formElements: i, validation: f }) {
30
+ return { initialState: t, formElements: i, validation: f };
31
31
  }
32
- const zt = (t, o) => {
33
- let g = t;
34
- const [S, l] = pt(g);
35
- (o?.formElements || o?.validation) && Object.keys(l).forEach((v) => {
36
- l[v] = l[v] || {}, l[v].formElements = {
37
- ...o.formElements,
32
+ const zt = (t, i) => {
33
+ let f = t;
34
+ const [g, d] = pt(f);
35
+ (i?.formElements || i?.validation) && Object.keys(d).forEach((v) => {
36
+ d[v] = d[v] || {}, d[v].formElements = {
37
+ ...i.formElements,
38
38
  // Global defaults first
39
- ...o?.validation,
40
- ...l[v].formElements || {}
39
+ ...i?.validation,
40
+ ...d[v].formElements || {}
41
41
  // State-specific overrides
42
42
  };
43
- }), r.getState().setInitialStates(S);
44
- const E = (v, m) => {
45
- const [p] = X(m?.componentId ?? K());
46
- dt({
43
+ }), r.getState().setInitialStates(g);
44
+ const E = (v, S) => {
45
+ const [w] = Y(S?.componentId ?? tt());
46
+ ut({
47
47
  stateKey: v,
48
- options: m,
49
- initialOptionsPart: l
48
+ options: S,
49
+ initialOptionsPart: d
50
50
  });
51
- const d = r.getState().cogsStateStore[v] || S[v], e = m?.modifyState ? m.modifyState(d) : d, [I, h] = Ot(
51
+ const u = r.getState().cogsStateStore[v] || g[v], e = S?.modifyState ? S.modifyState(u) : u, [I, N] = Ot(
52
52
  e,
53
53
  {
54
54
  stateKey: v,
55
- syncUpdate: m?.syncUpdate,
56
- componentId: p,
57
- localStorage: m?.localStorage,
58
- middleware: m?.middleware,
59
- enabledSync: m?.enabledSync,
60
- reactiveType: m?.reactiveType,
61
- reactiveDeps: m?.reactiveDeps,
62
- initState: m?.initState,
63
- localStorageKey: m?.localStorageKey
55
+ syncUpdate: S?.syncUpdate,
56
+ componentId: w,
57
+ localStorage: S?.localStorage,
58
+ middleware: S?.middleware,
59
+ enabledSync: S?.enabledSync,
60
+ reactiveType: S?.reactiveType,
61
+ reactiveDeps: S?.reactiveDeps,
62
+ initState: S?.initState,
63
+ localStorageKey: S?.localStorageKey
64
64
  }
65
65
  );
66
- return h;
66
+ return N;
67
67
  };
68
- function _(v, m) {
69
- dt({ stateKey: v, options: m, initialOptionsPart: l });
68
+ function _(v, S) {
69
+ ut({ stateKey: v, options: S, initialOptionsPart: d });
70
70
  }
71
71
  return { useCogsState: E, setCogsOptions: _ };
72
72
  }, {
73
- setUpdaterState: B,
74
- setState: x,
75
- getInitialOptions: tt,
76
- getKeyState: ft,
73
+ setUpdaterState: Z,
74
+ setState: D,
75
+ getInitialOptions: et,
76
+ getKeyState: gt,
77
77
  getValidationErrors: ht,
78
78
  setStateLog: At,
79
- updateInitialStateGlobal: et,
79
+ updateInitialStateGlobal: nt,
80
80
  addValidationError: Ct,
81
- removeValidationError: R,
81
+ removeValidationError: P,
82
82
  setServerSyncActions: Tt
83
- } = r.getState(), gt = (t) => {
83
+ } = r.getState(), St = (t) => {
84
84
  if (!t) return null;
85
85
  try {
86
- const o = window.localStorage.getItem(t);
87
- return o ? JSON.parse(o) : null;
88
- } catch (o) {
89
- return console.error("Error loading from localStorage:", o), null;
86
+ const i = window.localStorage.getItem(t);
87
+ return i ? JSON.parse(i) : null;
88
+ } catch (i) {
89
+ return console.error("Error loading from localStorage:", i), null;
90
90
  }
91
- }, Ft = (t, o, g, S) => {
92
- if (g.localStorageKey) {
93
- const l = {
91
+ }, Ft = (t, i, f, g) => {
92
+ if (f.localStorageKey) {
93
+ const d = {
94
94
  state: t,
95
95
  lastUpdated: Date.now(),
96
- lastSyncedWithServer: r.getState().serverSyncLog[o]?.[0]?.timeStamp,
97
- baseServerState: r.getState().serverState[o]
98
- }, E = g.initState ? `${S}-${o}-${g.localStorageKey}` : o;
99
- window.localStorage.setItem(E, JSON.stringify(l));
96
+ lastSyncedWithServer: r.getState().serverSyncLog[i]?.[0]?.timeStamp,
97
+ baseServerState: r.getState().serverState[i]
98
+ }, E = f.initState ? `${g}-${i}-${f.localStorageKey}` : i;
99
+ window.localStorage.setItem(E, JSON.stringify(d));
100
100
  }
101
- }, jt = (t, o, g, S, l, E) => {
101
+ }, jt = (t, i, f, g, d, E) => {
102
102
  const _ = {
103
- initialState: o,
104
- updaterState: Z(
103
+ initialState: i,
104
+ updaterState: H(
105
105
  t,
106
- S,
107
- l,
106
+ g,
107
+ d,
108
108
  E
109
109
  ),
110
- state: g
110
+ state: f
111
111
  };
112
- J(() => {
113
- et(t, _.initialState), B(t, _.updaterState), x(t, _.state);
112
+ B(() => {
113
+ nt(t, _.initialState), Z(t, _.updaterState), D(t, _.state);
114
114
  });
115
- }, St = (t) => {
116
- const o = r.getState().stateComponents.get(t);
117
- if (!o) return;
118
- const g = /* @__PURE__ */ new Set();
119
- o.components.forEach((S) => {
120
- g.add(() => S.forceUpdate());
115
+ }, mt = (t) => {
116
+ const i = r.getState().stateComponents.get(t);
117
+ if (!i) return;
118
+ const f = /* @__PURE__ */ new Set();
119
+ i.components.forEach((g) => {
120
+ f.add(() => g.forceUpdate());
121
121
  }), queueMicrotask(() => {
122
- J(() => {
123
- g.forEach((S) => S());
122
+ B(() => {
123
+ f.forEach((g) => g());
124
124
  });
125
125
  });
126
- }, Jt = (t, o) => {
127
- const g = r.getState().stateComponents.get(t);
128
- if (g) {
129
- const S = `${t}////${o}`, l = g.components.get(S);
130
- l && l.forceUpdate();
126
+ }, Jt = (t, i) => {
127
+ const f = r.getState().stateComponents.get(t);
128
+ if (f) {
129
+ const g = `${t}////${i}`, d = f.components.get(g);
130
+ d && d.forceUpdate();
131
131
  }
132
132
  };
133
133
  function Ot(t, {
134
- stateKey: o,
135
- serverSync: g,
136
- localStorage: S,
137
- formElements: l,
134
+ stateKey: i,
135
+ serverSync: f,
136
+ localStorage: g,
137
+ formElements: d,
138
138
  middleware: E,
139
139
  reactiveDeps: _,
140
140
  reactiveType: v,
141
- componentId: m,
142
- localStorageKey: p,
143
- initState: d,
141
+ componentId: S,
142
+ localStorageKey: w,
143
+ initState: u,
144
144
  syncUpdate: e
145
145
  } = {}) {
146
- const [I, h] = X({}), { sessionId: F } = Nt();
147
- let b = !o;
148
- const [u] = X(o ?? K()), i = r.getState().stateLog[u], D = z(/* @__PURE__ */ new Set()), U = z(m ?? K()), T = z(null);
149
- T.current = tt(u), Y(() => {
150
- if (e && e.stateKey === u && e.path?.[0]) {
151
- x(u, (a) => ({
152
- ...a,
146
+ const [I, N] = Y({}), { sessionId: F } = Nt();
147
+ let R = !i;
148
+ const [l] = Y(i ?? tt()), x = r.getState().stateLog[l], s = J(/* @__PURE__ */ new Set()), M = J(S ?? tt()), C = J(null);
149
+ C.current = et(l), K(() => {
150
+ if (e && e.stateKey === l && e.path?.[0]) {
151
+ D(l, (o) => ({
152
+ ...o,
153
153
  [e.path[0]]: e.newValue
154
154
  }));
155
- const c = `${e.stateKey}:${e.path.join(".")}`;
156
- r.getState().setSyncInfo(c, {
155
+ const a = `${e.stateKey}:${e.path.join(".")}`;
156
+ r.getState().setSyncInfo(a, {
157
157
  timeStamp: e.timeStamp,
158
158
  userId: e.userId
159
159
  });
160
160
  }
161
- }, [e]), Y(() => {
162
- lt(u, {
163
- initState: d
161
+ }, [e]), K(() => {
162
+ dt(l, {
163
+ initState: u
164
164
  });
165
- let c = null;
166
- p && (c = gt(
167
- F + "-" + u + "-" + p
168
- ));
169
165
  let a = null;
170
- d?.initialState && (a = d?.initialState, c && c.lastUpdated > (c.lastSyncedWithServer || 0) && (a = c.state), jt(
171
- u,
172
- d?.initialState,
173
- a,
174
- n,
175
- U.current,
166
+ w && (a = St(
167
+ F + "-" + l + "-" + w
168
+ ));
169
+ let o = null;
170
+ u?.initialState && (o = u?.initialState, a && a.lastUpdated > (a.lastSyncedWithServer || 0) && (o = a.state), jt(
171
+ l,
172
+ u?.initialState,
173
+ o,
174
+ L,
175
+ M.current,
176
176
  F
177
- ), console.log("newState222", a), St(u), h({}));
178
- }, [p, ...d?.dependencies || []]), It(() => {
179
- b && lt(u, {
180
- serverSync: g,
181
- formElements: l,
182
- initState: d,
183
- localStorage: S,
177
+ ), console.log("newState222", o), mt(l), N({}));
178
+ }, [w, ...u?.dependencies || []]), It(() => {
179
+ R && dt(l, {
180
+ serverSync: f,
181
+ formElements: d,
182
+ initState: u,
183
+ localStorage: g,
184
184
  middleware: E
185
185
  });
186
- const c = `${u}////${U.current}`, a = r.getState().stateComponents.get(u) || {
186
+ const a = `${l}////${M.current}`, o = r.getState().stateComponents.get(l) || {
187
187
  components: /* @__PURE__ */ new Map()
188
188
  };
189
- return a.components.set(c, {
190
- forceUpdate: () => h({}),
189
+ return o.components.set(a, {
190
+ forceUpdate: () => N({}),
191
191
  paths: /* @__PURE__ */ new Set(),
192
192
  deps: [],
193
193
  depsFunction: _ || void 0,
194
194
  reactiveType: v ?? ["component", "deps"]
195
- }), r.getState().stateComponents.set(u, a), h({}), () => {
196
- const f = `${u}////${U.current}`;
197
- a && (a.components.delete(f), a.components.size === 0 && r.getState().stateComponents.delete(u));
195
+ }), r.getState().stateComponents.set(l, o), N({}), () => {
196
+ const c = `${l}////${M.current}`;
197
+ o && (o.components.delete(c), o.components.size === 0 && r.getState().stateComponents.delete(l));
198
198
  };
199
199
  }, []);
200
- const n = (c, a, f, w) => {
201
- if (Array.isArray(a)) {
202
- const j = `${u}-${a.join(".")}`;
203
- D.current.add(j);
200
+ const L = (a, o, c, m) => {
201
+ if (Array.isArray(o)) {
202
+ const p = `${l}-${o.join(".")}`;
203
+ s.current.add(p);
204
204
  }
205
- x(u, (j) => {
206
- const V = ut(c) ? c(j) : c, O = `${u}-${a.join(".")}`;
207
- if (O) {
208
- let P = !1, y = r.getState().signalDomElements.get(O);
209
- if ((!y || y.size === 0) && (f.updateType === "insert" || f.updateType === "cut")) {
210
- const N = a.slice(0, -1), C = k(V, N);
211
- if (Array.isArray(C)) {
212
- P = !0;
213
- const $ = `${u}-${N.join(".")}`;
205
+ D(l, (p) => {
206
+ const h = ft(a) ? a(p) : a, j = `${l}-${o.join(".")}`;
207
+ if (j) {
208
+ let U = !1, y = r.getState().signalDomElements.get(j);
209
+ if ((!y || y.size === 0) && (c.updateType === "insert" || c.updateType === "cut")) {
210
+ const V = o.slice(0, -1), A = G(h, V);
211
+ if (Array.isArray(A)) {
212
+ U = !0;
213
+ const $ = `${l}-${V.join(".")}`;
214
214
  y = r.getState().signalDomElements.get($);
215
215
  }
216
216
  }
217
217
  if (y) {
218
- const N = P ? k(V, a.slice(0, -1)) : k(V, a);
219
- y.forEach(({ parentId: C, position: $, effect: L }) => {
220
- const M = document.querySelector(
221
- `[data-parent-id="${C}"]`
218
+ const V = U ? G(h, o.slice(0, -1)) : G(h, o);
219
+ y.forEach(({ parentId: A, position: $, effect: k }) => {
220
+ const b = document.querySelector(
221
+ `[data-parent-id="${A}"]`
222
222
  );
223
- if (M) {
224
- const at = Array.from(M.childNodes);
225
- if (at[$]) {
226
- const vt = L ? new Function("state", `return (${L})(state)`)(N) : N;
227
- at[$].textContent = String(vt);
223
+ if (b) {
224
+ const ot = Array.from(b.childNodes);
225
+ if (ot[$]) {
226
+ const vt = k ? new Function("state", `return (${k})(state)`)(V) : V;
227
+ ot[$].textContent = String(vt);
228
228
  }
229
229
  }
230
230
  });
231
231
  }
232
232
  }
233
- f.updateType === "update" && (w || T.current?.validationKey) && a && R(
234
- (w || T.current?.validationKey) + "." + a.join(".")
233
+ c.updateType === "update" && (m || C.current?.validationKey) && o && P(
234
+ (m || C.current?.validationKey) + "." + o.join(".")
235
235
  );
236
- const A = a.slice(0, a.length - 1);
237
- f.updateType === "cut" && T.current?.validationKey && R(
238
- T.current?.validationKey + "." + A.join(".")
239
- ), f.updateType === "insert" && T.current?.validationKey && ht(
240
- T.current?.validationKey + "." + A.join(".")
241
- ).filter(([y, N]) => {
242
- let C = y?.split(".").length;
243
- if (y == A.join(".") && C == A.length - 1) {
244
- let $ = y + "." + A;
245
- R(y), Ct($, N);
236
+ const T = o.slice(0, o.length - 1);
237
+ c.updateType === "cut" && C.current?.validationKey && P(
238
+ C.current?.validationKey + "." + T.join(".")
239
+ ), c.updateType === "insert" && C.current?.validationKey && ht(
240
+ C.current?.validationKey + "." + T.join(".")
241
+ ).filter(([y, V]) => {
242
+ let A = y?.split(".").length;
243
+ if (y == T.join(".") && A == T.length - 1) {
244
+ let $ = y + "." + T;
245
+ P(y), Ct($, V);
246
246
  }
247
247
  });
248
- const W = k(j, a), mt = k(V, a), yt = f.updateType === "update" ? a.join(".") : [...a].slice(0, -1).join("."), nt = r.getState().stateComponents.get(u);
249
- if (nt)
250
- for (const [P, y] of nt.components.entries()) {
251
- let N = !1;
252
- const C = Array.isArray(y.reactiveType) ? y.reactiveType : [y.reactiveType || "component"];
253
- if (!C.includes("none")) {
254
- if (C.includes("all")) {
248
+ const O = G(p, o), q = G(h, o), yt = c.updateType === "update" ? o.join(".") : [...o].slice(0, -1).join("."), rt = r.getState().stateComponents.get(l);
249
+ if (rt)
250
+ for (const [U, y] of rt.components.entries()) {
251
+ let V = !1;
252
+ const A = Array.isArray(y.reactiveType) ? y.reactiveType : [y.reactiveType || "component"];
253
+ if (!A.includes("none")) {
254
+ if (A.includes("all")) {
255
255
  y.forceUpdate();
256
256
  continue;
257
257
  }
258
- if (C.includes("component") && y.paths && (y.paths.has(yt) || y.paths.has("")) && (N = !0), !N && C.includes("deps") && y.depsFunction) {
259
- const $ = y.depsFunction(V);
260
- typeof $ == "boolean" ? $ && (N = !0) : G(y.deps, $) || (y.deps = $, N = !0);
258
+ if (A.includes("component") && y.paths && (y.paths.has(yt) || y.paths.has("")) && (V = !0), !V && A.includes("deps") && y.depsFunction) {
259
+ const $ = y.depsFunction(h);
260
+ typeof $ == "boolean" ? $ && (V = !0) : W(y.deps, $) || (y.deps = $, V = !0);
261
261
  }
262
- N && y.forceUpdate();
262
+ V && y.forceUpdate();
263
263
  }
264
264
  }
265
- const rt = {
265
+ const at = {
266
266
  timeStamp: Date.now(),
267
- stateKey: u,
268
- path: a,
269
- updateType: f.updateType,
267
+ stateKey: l,
268
+ path: o,
269
+ updateType: c.updateType,
270
270
  status: "new",
271
- oldValue: W,
272
- newValue: mt
271
+ oldValue: O,
272
+ newValue: q
273
273
  };
274
- if (At(u, (P) => {
275
- const N = [...P ?? [], rt].reduce((C, $) => {
276
- const L = `${$.stateKey}:${JSON.stringify($.path)}`, M = C.get(L);
277
- return M ? (M.timeStamp = Math.max(M.timeStamp, $.timeStamp), M.newValue = $.newValue, M.oldValue = M.oldValue ?? $.oldValue, M.updateType = $.updateType) : C.set(L, { ...$ }), C;
274
+ if (At(l, (U) => {
275
+ const V = [...U ?? [], at].reduce((A, $) => {
276
+ const k = `${$.stateKey}:${JSON.stringify($.path)}`, b = A.get(k);
277
+ return b ? (b.timeStamp = Math.max(b.timeStamp, $.timeStamp), b.newValue = $.newValue, b.oldValue = b.oldValue ?? $.oldValue, b.updateType = $.updateType) : A.set(k, { ...$ }), A;
278
278
  }, /* @__PURE__ */ new Map());
279
- return Array.from(N.values());
279
+ return Array.from(V.values());
280
280
  }), Ft(
281
- V,
282
- u,
283
- T.current,
281
+ h,
282
+ l,
283
+ C.current,
284
284
  F
285
285
  ), E && E({
286
- updateLog: i,
287
- update: rt
288
- }), T.current?.serverSync) {
289
- const P = r.getState().serverState[u], y = T.current?.serverSync;
290
- Tt(u, {
291
- syncKey: typeof y.syncKey == "string" ? y.syncKey : y.syncKey({ state: V }),
292
- rollBackState: P,
286
+ updateLog: x,
287
+ update: at
288
+ }), C.current?.serverSync) {
289
+ const U = r.getState().serverState[l], y = C.current?.serverSync;
290
+ Tt(l, {
291
+ syncKey: typeof y.syncKey == "string" ? y.syncKey : y.syncKey({ state: h }),
292
+ rollBackState: U,
293
293
  actionTimeStamp: Date.now() + (y.debounce ?? 3e3),
294
294
  status: "waiting"
295
295
  });
296
296
  }
297
- return V;
297
+ return h;
298
298
  });
299
299
  };
300
- r.getState().updaterState[u] || (B(
301
- u,
302
- Z(
303
- u,
304
- n,
305
- U.current,
300
+ r.getState().updaterState[l] || (Z(
301
+ l,
302
+ H(
303
+ l,
304
+ L,
305
+ M.current,
306
306
  F
307
307
  )
308
- ), r.getState().cogsStateStore[u] || x(u, t), r.getState().initialStateGlobal[u] || et(u, t));
309
- const s = Et(() => Z(
310
- u,
311
- n,
312
- U.current,
308
+ ), r.getState().cogsStateStore[l] || D(l, t), r.getState().initialStateGlobal[l] || nt(l, t));
309
+ const n = Et(() => H(
310
+ l,
311
+ L,
312
+ M.current,
313
313
  F
314
- ), [u]);
315
- return [ft(u), s];
314
+ ), [l]);
315
+ return [gt(l), n];
316
316
  }
317
- function Z(t, o, g, S) {
318
- const l = /* @__PURE__ */ new Map();
317
+ function H(t, i, f, g) {
318
+ const d = /* @__PURE__ */ new Map();
319
319
  let E = 0;
320
- const _ = (d) => {
321
- const e = d.join(".");
322
- for (const [I] of l)
323
- (I === e || I.startsWith(e + ".")) && l.delete(I);
320
+ const _ = (u) => {
321
+ const e = u.join(".");
322
+ for (const [I] of d)
323
+ (I === e || I.startsWith(e + ".")) && d.delete(I);
324
324
  E++;
325
- }, v = /* @__PURE__ */ new Map(), m = {
326
- removeValidation: (d) => {
327
- d?.validationKey && R(d.validationKey);
325
+ }, v = /* @__PURE__ */ new Map(), S = {
326
+ removeValidation: (u) => {
327
+ u?.validationKey && P(u.validationKey);
328
328
  },
329
- revertToInitialState: (d) => {
329
+ revertToInitialState: (u) => {
330
330
  const e = r.getState().getInitialOptions(t)?.validation;
331
- e?.key && R(e?.key), d?.validationKey && R(d.validationKey);
331
+ e?.key && P(e?.key), u?.validationKey && P(u.validationKey);
332
332
  const I = r.getState().initialStateGlobal[t];
333
- l.clear(), E++;
334
- const h = p(I, []);
335
- J(() => {
336
- B(t, h), x(t, I);
333
+ d.clear(), E++;
334
+ const N = w(I, []);
335
+ B(() => {
336
+ Z(t, N), D(t, I);
337
337
  const F = r.getState().stateComponents.get(t);
338
- F && F.components.forEach((u) => {
339
- u.forceUpdate();
338
+ F && F.components.forEach((l) => {
339
+ l.forceUpdate();
340
340
  });
341
- const b = tt(t);
342
- b?.localStorageKey && localStorage.removeItem(
343
- b?.initState ? S + "-" + t + "-" + b?.localStorageKey : t
341
+ const R = et(t);
342
+ R?.localStorageKey && localStorage.removeItem(
343
+ R?.initState ? g + "-" + t + "-" + R?.localStorageKey : t
344
344
  ), localStorage.removeItem(t);
345
345
  });
346
346
  },
347
- updateInitialState: (d) => {
348
- l.clear(), E++;
349
- const e = Z(
347
+ updateInitialState: (u) => {
348
+ d.clear(), E++;
349
+ const e = H(
350
350
  t,
351
- o,
352
- g,
353
- S
351
+ i,
352
+ f,
353
+ g
354
354
  );
355
- return J(() => {
356
- et(t, d), B(t, e), x(t, d);
355
+ return B(() => {
356
+ nt(t, u), Z(t, e), D(t, u);
357
357
  const I = r.getState().stateComponents.get(t);
358
- I && I.components.forEach((h) => {
359
- h.forceUpdate();
358
+ I && I.components.forEach((N) => {
359
+ N.forceUpdate();
360
360
  }), localStorage.removeItem(t);
361
361
  }), {
362
362
  fetchId: (I) => e.get()[I]
@@ -366,247 +366,253 @@ function Z(t, o, g, S) {
366
366
  _serverState: r.getState().serverState[t],
367
367
  _isLoading: r.getState().isLoadingGlobal[t],
368
368
  _isServerSynced: () => {
369
- const d = r.getState().serverState[t];
370
- return !!(d && G(d, ft(t)));
369
+ const u = r.getState().serverState[t];
370
+ return !!(u && W(u, gt(t)));
371
371
  }
372
372
  };
373
- function p(d, e = [], I) {
374
- const h = e.map(String).join(".");
375
- l.get(h);
376
- const F = {
377
- apply(u, i, D) {
373
+ function w(u, e = [], I) {
374
+ const N = e.map(String).join(".");
375
+ d.get(N);
376
+ const F = function() {
377
+ return r().getNestedState(t, e);
378
+ };
379
+ Object.keys(S).forEach((x) => {
380
+ F[x] = S[x];
381
+ });
382
+ const R = {
383
+ apply(x, s, M) {
378
384
  return r().getNestedState(t, e);
379
385
  },
380
- get(u, i) {
381
- if (i !== "then" && !i.startsWith("$") && i !== "stateMapNoRender") {
382
- const n = e.join("."), s = `${t}////${g}`, c = r.getState().stateComponents.get(t);
383
- if (c) {
384
- const a = c.components.get(s);
385
- a && (e.length > 0 || i === "get") && a.paths.add(n);
386
+ get(x, s) {
387
+ if (s !== "then" && !s.startsWith("$") && s !== "stateMapNoRender") {
388
+ const n = e.join("."), a = `${t}////${f}`, o = r.getState().stateComponents.get(t);
389
+ if (o) {
390
+ const c = o.components.get(a);
391
+ c && (e.length > 0 || s === "get") && c.paths.add(n);
386
392
  }
387
393
  }
388
- if (i === "showValidationErrors")
394
+ if (s === "showValidationErrors")
389
395
  return () => {
390
396
  const n = r.getState().getInitialOptions(t)?.validation;
391
397
  if (!n?.key)
392
398
  throw new Error("Validation key not found");
393
399
  return r.getState().getValidationErrors(n.key + "." + e.join("."));
394
400
  };
395
- if (Array.isArray(d)) {
396
- if (i === "getSelected")
401
+ if (Array.isArray(u)) {
402
+ if (s === "getSelected")
397
403
  return () => {
398
404
  const n = v.get(e.join("."));
399
405
  if (n !== void 0)
400
- return p(
401
- d[n],
406
+ return w(
407
+ u[n],
402
408
  [...e, n.toString()],
403
409
  I
404
410
  );
405
411
  };
406
- if (i === "stateMap" || i === "stateMapNoRender")
412
+ if (s === "stateMap" || s === "stateMapNoRender")
407
413
  return (n) => {
408
- const s = I?.filtered?.some(
409
- (a) => a.join(".") === e.join(".")
410
- ), c = s ? d : r.getState().getNestedState(t, e);
411
- return i !== "stateMapNoRender" && (l.clear(), E++), c.map((a, f) => {
412
- const w = s && a.__origIndex ? a.__origIndex : f, j = p(
413
- a,
414
- [...e, w.toString()],
414
+ const a = I?.filtered?.some(
415
+ (c) => c.join(".") === e.join(".")
416
+ ), o = a ? u : r.getState().getNestedState(t, e);
417
+ return s !== "stateMapNoRender" && (d.clear(), E++), o.map((c, m) => {
418
+ const p = a && c.__origIndex ? c.__origIndex : m, h = w(
419
+ c,
420
+ [...e, p.toString()],
415
421
  I
416
422
  );
417
423
  return n(
418
- a,
419
- j,
420
- f,
421
- d,
422
- p(d, e, I)
424
+ c,
425
+ h,
426
+ m,
427
+ u,
428
+ w(u, e, I)
423
429
  );
424
430
  });
425
431
  };
426
- if (i === "$stateMap")
427
- return (n) => H(Mt, {
432
+ if (s === "$stateMap")
433
+ return (n) => Q(bt, {
428
434
  proxy: {
429
435
  _stateKey: t,
430
436
  _path: e,
431
437
  _mapFn: n
432
438
  // Pass the actual function, not string
433
439
  },
434
- rebuildStateShape: p
440
+ rebuildStateShape: w
435
441
  });
436
- if (i === "stateFlattenOn")
442
+ if (s === "stateFlattenOn")
437
443
  return (n) => {
438
- const c = I?.filtered?.some(
439
- (f) => f.join(".") === e.join(".")
440
- ) ? d : r.getState().getNestedState(t, e);
441
- l.clear(), E++;
442
- const a = c.flatMap(
443
- (f, w) => f[n] ?? []
444
+ const o = I?.filtered?.some(
445
+ (m) => m.join(".") === e.join(".")
446
+ ) ? u : r.getState().getNestedState(t, e);
447
+ d.clear(), E++;
448
+ const c = o.flatMap(
449
+ (m, p) => m[n] ?? []
444
450
  );
445
- return p(
446
- a,
451
+ return w(
452
+ c,
447
453
  [...e, "[*]", n],
448
454
  I
449
455
  );
450
456
  };
451
- if (i === "findWith")
452
- return (n, s) => {
453
- const c = d.findIndex(
454
- (w) => w[n] === s
457
+ if (s === "findWith")
458
+ return (n, a) => {
459
+ const o = u.findIndex(
460
+ (p) => p[n] === a
455
461
  );
456
- if (c === -1) return;
457
- const a = d[c], f = [...e, c.toString()];
458
- return l.clear(), E++, l.clear(), E++, p(a, f);
462
+ if (o === -1) return;
463
+ const c = u[o], m = [...e, o.toString()];
464
+ return d.clear(), E++, d.clear(), E++, w(c, m);
459
465
  };
460
- if (i === "index")
466
+ if (s === "index")
461
467
  return (n) => {
462
- const s = d[n];
463
- return p(s, [...e, n.toString()]);
468
+ const a = u[n];
469
+ return w(a, [...e, n.toString()]);
464
470
  };
465
- if (i === "insert")
466
- return (n) => (_(e), it(o, n, e, t), p(
471
+ if (s === "insert")
472
+ return (n) => (_(e), st(i, n, e, t), w(
467
473
  r.getState().cogsStateStore[t],
468
474
  []
469
475
  ));
470
- if (i === "uniqueInsert")
471
- return (n, s, c) => {
472
- const a = r.getState().getNestedState(t, e), f = ut(n) ? n(a) : n;
473
- let w = null;
474
- if (!a.some((V) => {
475
- if (s) {
476
- const A = s.every(
477
- (W) => G(V[W], f[W])
476
+ if (s === "uniqueInsert")
477
+ return (n, a, o) => {
478
+ const c = r.getState().getNestedState(t, e), m = ft(n) ? n(c) : n;
479
+ let p = null;
480
+ if (!c.some((j) => {
481
+ if (a) {
482
+ const O = a.every(
483
+ (q) => W(j[q], m[q])
478
484
  );
479
- return A && (w = V), A;
485
+ return O && (p = j), O;
480
486
  }
481
- const O = G(V, f);
482
- return O && (w = V), O;
487
+ const T = W(j, m);
488
+ return T && (p = j), T;
483
489
  }))
484
- _(e), it(o, f, e, t);
485
- else if (c && w) {
486
- const V = c(w), O = a.map(
487
- (A) => G(A, w) ? V : A
490
+ _(e), st(i, m, e, t);
491
+ else if (o && p) {
492
+ const j = o(p), T = c.map(
493
+ (O) => W(O, p) ? j : O
488
494
  );
489
- _(e), q(o, O, e);
495
+ _(e), z(i, T, e);
490
496
  }
491
497
  };
492
- if (i === "cut")
493
- return (n, s) => {
494
- s?.waitForSync || (_(e), st(o, e, t, n));
498
+ if (s === "cut")
499
+ return (n, a) => {
500
+ a?.waitForSync || (_(e), ct(i, e, t, n));
495
501
  };
496
- if (i === "stateFilter")
502
+ if (s === "stateFilter")
497
503
  return (n) => {
498
- const s = d.map((f, w) => ({
499
- ...f,
500
- __origIndex: w.toString()
501
- })), c = [], a = [];
502
- for (let f = 0; f < s.length; f++)
503
- n(s[f], f) && (c.push(f), a.push(s[f]));
504
- return l.clear(), E++, p(a, e, {
504
+ const a = u.map((m, p) => ({
505
+ ...m,
506
+ __origIndex: p.toString()
507
+ })), o = [], c = [];
508
+ for (let m = 0; m < a.length; m++)
509
+ n(a[m], m) && (o.push(m), c.push(a[m]));
510
+ return d.clear(), E++, w(c, e, {
505
511
  filtered: [...I?.filtered || [], e],
506
- validIndices: c
512
+ validIndices: o
507
513
  // Pass through the meta
508
514
  });
509
515
  };
510
516
  }
511
- const D = e[e.length - 1];
512
- if (!isNaN(Number(D))) {
513
- const n = e.slice(0, -1), s = r.getState().getNestedState(t, n);
514
- if (Array.isArray(s) && i === "cut")
515
- return () => st(
516
- o,
517
+ const M = e[e.length - 1];
518
+ if (!isNaN(Number(M))) {
519
+ const n = e.slice(0, -1), a = r.getState().getNestedState(t, n);
520
+ if (Array.isArray(a) && s === "cut")
521
+ return () => ct(
522
+ i,
517
523
  n,
518
524
  t,
519
- Number(D)
525
+ Number(M)
520
526
  );
521
527
  }
522
- if (i === "get")
528
+ if (s === "get")
523
529
  return () => r.getState().getNestedState(t, e);
524
- if (i === "$derive")
525
- return (n) => Q({
530
+ if (s === "$derive")
531
+ return (n) => X({
526
532
  _stateKey: t,
527
533
  _path: e,
528
534
  _effect: n.toString()
529
535
  });
530
- if (i === "$derive")
531
- return (n) => Q({
536
+ if (s === "$derive")
537
+ return (n) => X({
532
538
  _stateKey: t,
533
539
  _path: e,
534
540
  _effect: n.toString()
535
541
  });
536
- if (i === "$get")
537
- return () => Q({
542
+ if (s === "$get")
543
+ return () => X({
538
544
  _stateKey: t,
539
545
  _path: e
540
546
  });
541
- if (i === "lastSynced") {
547
+ if (s === "lastSynced") {
542
548
  const n = `${t}:${e.join(".")}`;
543
549
  return r.getState().getSyncInfo(n);
544
550
  }
545
- if (i === "_selected") {
546
- const n = e.slice(0, -1), s = n.join("."), c = r.getState().getNestedState(t, n);
547
- return Array.isArray(c) ? Number(e[e.length - 1]) === v.get(s) : void 0;
551
+ if (s === "_selected") {
552
+ const n = e.slice(0, -1), a = n.join("."), o = r.getState().getNestedState(t, n);
553
+ return Array.isArray(o) ? Number(e[e.length - 1]) === v.get(a) : void 0;
548
554
  }
549
- if (i == "getLocalStorage")
550
- return (n) => gt(S + "-" + t + "-" + n);
551
- if (i === "setSelected")
555
+ if (s == "getLocalStorage")
556
+ return (n) => St(g + "-" + t + "-" + n);
557
+ if (s === "setSelected")
552
558
  return (n) => {
553
- const s = e.slice(0, -1), c = Number(e[e.length - 1]), a = s.join(".");
554
- n ? v.set(a, c) : v.delete(a);
555
- const f = r.getState().getNestedState(t, [...s]);
556
- q(o, f, s), _(s);
559
+ const a = e.slice(0, -1), o = Number(e[e.length - 1]), c = a.join(".");
560
+ n ? v.set(c, o) : v.delete(c);
561
+ const m = r.getState().getNestedState(t, [...a]);
562
+ z(i, m, a), _(a);
557
563
  };
558
564
  if (e.length == 0) {
559
- if (i === "validateZodSchema")
565
+ if (s === "validateZodSchema")
560
566
  return () => {
561
- const n = r.getState().getInitialOptions(t)?.validation, s = r.getState().addValidationError;
567
+ const n = r.getState().getInitialOptions(t)?.validation, a = r.getState().addValidationError;
562
568
  if (!n?.zodSchema)
563
569
  throw new Error("Zod schema not found");
564
570
  if (!n?.key)
565
571
  throw new Error("Validation key not found");
566
- R(n.key);
567
- const c = r.getState().cogsStateStore[t];
572
+ P(n.key);
573
+ const o = r.getState().cogsStateStore[t];
568
574
  try {
569
- const a = r.getState().getValidationErrors(n.key);
570
- a && a.length > 0 && a.forEach(([w]) => {
571
- w && w.startsWith(n.key) && R(w);
575
+ const c = r.getState().getValidationErrors(n.key);
576
+ c && c.length > 0 && c.forEach(([p]) => {
577
+ p && p.startsWith(n.key) && P(p);
572
578
  });
573
- const f = n.zodSchema.safeParse(c);
574
- return f.success ? !0 : (f.error.errors.forEach((j) => {
575
- const V = j.path, O = j.message, A = [n.key, ...V].join(".");
576
- s(A, O), console.log(
577
- `Validation error at ${A}: ${O}`
579
+ const m = n.zodSchema.safeParse(o);
580
+ return m.success ? !0 : (m.error.errors.forEach((h) => {
581
+ const j = h.path, T = h.message, O = [n.key, ...j].join(".");
582
+ a(O, T), console.log(
583
+ `Validation error at ${O}: ${T}`
578
584
  );
579
- }), St(t), !1);
580
- } catch (a) {
581
- return console.error("Zod schema validation failed", a), !1;
585
+ }), mt(t), !1);
586
+ } catch (c) {
587
+ return console.error("Zod schema validation failed", c), !1;
582
588
  }
583
589
  };
584
- if (i === "_componentId") return g;
585
- if (i === "getComponents")
590
+ if (s === "_componentId") return f;
591
+ if (s === "getComponents")
586
592
  return () => r().stateComponents.get(t);
587
- if (i === "getAllFormRefs")
588
- return () => ct.getState().getFormRefsByStateKey(t);
589
- if (i === "_initialState")
593
+ if (s === "getAllFormRefs")
594
+ return () => lt.getState().getFormRefsByStateKey(t);
595
+ if (s === "_initialState")
590
596
  return r.getState().initialStateGlobal[t];
591
- if (i === "_serverState")
597
+ if (s === "_serverState")
592
598
  return r.getState().serverState[t];
593
- if (i === "_isLoading")
599
+ if (s === "_isLoading")
594
600
  return r.getState().isLoadingGlobal[t];
595
- if (i === "revertToInitialState")
596
- return m.revertToInitialState;
597
- if (i === "updateInitialState") return m.updateInitialState;
598
- if (i === "removeValidation") return m.removeValidation;
601
+ if (s === "revertToInitialState")
602
+ return S.revertToInitialState;
603
+ if (s === "updateInitialState") return S.updateInitialState;
604
+ if (s === "removeValidation") return S.removeValidation;
599
605
  }
600
- if (i === "getFormRef")
601
- return () => ct.getState().getFormRef(t + "." + e.join("."));
602
- if (i === "validationWrapper")
606
+ if (s === "getFormRef")
607
+ return () => lt.getState().getFormRef(t + "." + e.join("."));
608
+ if (s === "validationWrapper")
603
609
  return ({
604
610
  children: n,
605
- hideMessage: s
606
- }) => /* @__PURE__ */ ot(
611
+ hideMessage: a
612
+ }) => /* @__PURE__ */ it(
607
613
  $t,
608
614
  {
609
- formOpts: s ? { validation: { message: "" } } : void 0,
615
+ formOpts: a ? { validation: { message: "" } } : void 0,
610
616
  path: e,
611
617
  validationKey: r.getState().getInitialOptions(t)?.validation?.key || "",
612
618
  stateKey: t,
@@ -614,119 +620,119 @@ function Z(t, o, g, S) {
614
620
  children: n
615
621
  }
616
622
  );
617
- if (i === "_stateKey") return t;
618
- if (i === "_path") return e;
619
- if (i === "_isServerSynced") return m._isServerSynced;
620
- if (i === "update")
621
- return (n, s) => {
622
- if (s?.debounce)
623
+ if (s === "_stateKey") return t;
624
+ if (s === "_path") return e;
625
+ if (s === "_isServerSynced") return S._isServerSynced;
626
+ if (s === "update")
627
+ return (n, a) => {
628
+ if (a?.debounce)
623
629
  wt(() => {
624
- q(o, n, e, "");
625
- const c = r.getState().getNestedState(t, e);
626
- s?.afterUpdate && s.afterUpdate(c);
627
- }, s.debounce);
630
+ z(i, n, e, "");
631
+ const o = r.getState().getNestedState(t, e);
632
+ a?.afterUpdate && a.afterUpdate(o);
633
+ }, a.debounce);
628
634
  else {
629
- q(o, n, e, "");
630
- const c = r.getState().getNestedState(t, e);
631
- s?.afterUpdate && s.afterUpdate(c);
635
+ z(i, n, e, "");
636
+ const o = r.getState().getNestedState(t, e);
637
+ a?.afterUpdate && a.afterUpdate(o);
632
638
  }
633
639
  _(e);
634
640
  };
635
- if (i === "formElement")
636
- return (n, s) => /* @__PURE__ */ ot(
641
+ if (s === "formElement")
642
+ return (n, a) => /* @__PURE__ */ it(
637
643
  Vt,
638
644
  {
639
- setState: o,
645
+ setState: i,
640
646
  stateKey: t,
641
647
  path: e,
642
648
  child: n,
643
- formOpts: s
649
+ formOpts: a
644
650
  }
645
651
  );
646
- const U = [...e, i], T = r.getState().getNestedState(t, U);
647
- return p(T, U, I);
652
+ const C = [...e, s], L = r.getState().getNestedState(t, C);
653
+ return w(L, C, I);
648
654
  }
649
- }, b = new Proxy(m, F);
650
- return l.set(h, {
651
- proxy: b,
655
+ }, l = new Proxy(F, R);
656
+ return d.set(N, {
657
+ proxy: l,
652
658
  stateVersion: E
653
- }), b;
659
+ }), l;
654
660
  }
655
- return p(
661
+ return w(
656
662
  r.getState().getNestedState(t, [])
657
663
  );
658
664
  }
659
- function Q(t) {
660
- return H(bt, { proxy: t });
665
+ function X(t) {
666
+ return Q(Mt, { proxy: t });
661
667
  }
662
- function Mt({
668
+ function bt({
663
669
  proxy: t,
664
- rebuildStateShape: o
670
+ rebuildStateShape: i
665
671
  }) {
666
- const g = r().getNestedState(t._stateKey, t._path);
667
- return console.log("value", g), Array.isArray(g) ? o(
668
- g,
672
+ const f = r().getNestedState(t._stateKey, t._path);
673
+ return console.log("value", f), Array.isArray(f) ? i(
674
+ f,
669
675
  t._path
670
676
  ).stateMapNoRender(
671
- (l, E, _, v, m) => t._mapFn(l, E, _, v, m)
677
+ (d, E, _, v, S) => t._mapFn(d, E, _, v, S)
672
678
  ) : null;
673
679
  }
674
- function bt({
680
+ function Mt({
675
681
  proxy: t
676
682
  }) {
677
- const o = z(null), g = `${t._stateKey}-${t._path.join(".")}`;
678
- return Y(() => {
679
- const S = o.current;
680
- if (!S || !S.parentElement) return;
681
- const l = S.parentElement, _ = Array.from(l.childNodes).indexOf(S);
682
- let v = l.getAttribute("data-parent-id");
683
- v || (v = `parent-${crypto.randomUUID()}`, l.setAttribute("data-parent-id", v));
684
- const p = {
683
+ const i = J(null), f = `${t._stateKey}-${t._path.join(".")}`;
684
+ return K(() => {
685
+ const g = i.current;
686
+ if (!g || !g.parentElement) return;
687
+ const d = g.parentElement, _ = Array.from(d.childNodes).indexOf(g);
688
+ let v = d.getAttribute("data-parent-id");
689
+ v || (v = `parent-${crypto.randomUUID()}`, d.setAttribute("data-parent-id", v));
690
+ const w = {
685
691
  instanceId: `instance-${crypto.randomUUID()}`,
686
692
  parentId: v,
687
693
  position: _,
688
694
  effect: t._effect
689
695
  };
690
- r.getState().addSignalElement(g, p);
691
- const d = r.getState().getNestedState(t._stateKey, t._path);
696
+ r.getState().addSignalElement(f, w);
697
+ const u = r.getState().getNestedState(t._stateKey, t._path);
692
698
  let e;
693
699
  if (t._effect)
694
700
  try {
695
701
  e = new Function(
696
702
  "state",
697
703
  `return (${t._effect})(state)`
698
- )(d);
699
- } catch (h) {
700
- console.error("Error evaluating effect function during mount:", h), e = d;
704
+ )(u);
705
+ } catch (N) {
706
+ console.error("Error evaluating effect function during mount:", N), e = u;
701
707
  }
702
708
  else
703
- e = d;
709
+ e = u;
704
710
  e !== null && typeof e == "object" && (e = JSON.stringify(e));
705
711
  const I = document.createTextNode(String(e));
706
- S.replaceWith(I);
707
- }, [t._stateKey, t._path.join("."), t._effect]), H("span", {
708
- ref: o,
712
+ g.replaceWith(I);
713
+ }, [t._stateKey, t._path.join("."), t._effect]), Q("span", {
714
+ ref: i,
709
715
  style: { display: "none" },
710
- "data-signal-id": g
716
+ "data-signal-id": f
711
717
  });
712
718
  }
713
719
  function Bt(t) {
714
- const o = _t(
715
- (g) => {
716
- const S = r.getState().stateComponents.get(t._stateKey) || {
720
+ const i = _t(
721
+ (f) => {
722
+ const g = r.getState().stateComponents.get(t._stateKey) || {
717
723
  components: /* @__PURE__ */ new Map()
718
724
  };
719
- return S.components.set(t._stateKey, {
720
- forceUpdate: g,
725
+ return g.components.set(t._stateKey, {
726
+ forceUpdate: f,
721
727
  paths: /* @__PURE__ */ new Set([t._path.join(".")])
722
- }), () => S.components.delete(t._stateKey);
728
+ }), () => g.components.delete(t._stateKey);
723
729
  },
724
730
  () => r.getState().getNestedState(t._stateKey, t._path)
725
731
  );
726
- return H("text", {}, String(o));
732
+ return Q("text", {}, String(i));
727
733
  }
728
734
  export {
729
- Q as $cogsSignal,
735
+ X as $cogsSignal,
730
736
  Bt as $cogsSignalStore,
731
737
  qt as addStateOptions,
732
738
  zt as createCogsState,