cogsbox-state 0.5.82 → 0.5.83
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.
- package/dist/CogsState.jsx +120 -120
- package/dist/CogsState.jsx.map +1 -1
- package/package.json +1 -1
package/dist/CogsState.jsx
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx as ct } from "react/jsx-runtime";
|
|
3
|
-
import { useState as et, useRef as
|
|
3
|
+
import { useState as et, useRef as Z, useEffect as nt, useLayoutEffect as It, useMemo as _t, createElement as Q, useSyncExternalStore as Et, startTransition as H } from "react";
|
|
4
4
|
import { transformStateFunc as $t, isFunction as L, getNestedValue as U, isDeepEqual as M, debounce as wt } from "./utility.js";
|
|
5
|
-
import { pushFunc as K, updateFn as
|
|
5
|
+
import { pushFunc as K, updateFn as B, cutFunc as J, ValidationWrapper as Nt, FormControlComponent as Vt } from "./Functions.jsx";
|
|
6
6
|
import "zod";
|
|
7
7
|
import { getGlobalStore as r, formRefStore as lt } from "./store.js";
|
|
8
8
|
import { useCogsConfig as At } from "./CogsStateClient.jsx";
|
|
@@ -19,7 +19,7 @@ function ut({
|
|
|
19
19
|
options: i,
|
|
20
20
|
initialOptionsPart: m
|
|
21
21
|
}) {
|
|
22
|
-
const y =
|
|
22
|
+
const y = q(t) || {}, g = m[t] || {}, $ = r.getState().setInitialStateOptions, _ = {
|
|
23
23
|
...g,
|
|
24
24
|
// Options from createCogsState
|
|
25
25
|
...y,
|
|
@@ -46,7 +46,7 @@ const zt = (t, i) => {
|
|
|
46
46
|
...i?.validation,
|
|
47
47
|
...g[v].formElements || {}
|
|
48
48
|
// State-specific overrides
|
|
49
|
-
}, r.getState().setInitialStateOptions(v, g[v]);
|
|
49
|
+
}, q(v) || r.getState().setInitialStateOptions(v, g[v]);
|
|
50
50
|
}), r.getState().setInitialStates(y);
|
|
51
51
|
const $ = (v, l) => {
|
|
52
52
|
const [f] = et(l?.componentId ?? rt());
|
|
@@ -55,7 +55,7 @@ const zt = (t, i) => {
|
|
|
55
55
|
options: l,
|
|
56
56
|
initialOptionsPart: g
|
|
57
57
|
});
|
|
58
|
-
const e = r.getState().cogsStateStore[v] || y[v], S = l?.modifyState ? l.modifyState(e) : e, [
|
|
58
|
+
const e = r.getState().cogsStateStore[v] || y[v], S = l?.modifyState ? l.modifyState(e) : e, [T, A] = Ot(
|
|
59
59
|
S,
|
|
60
60
|
{
|
|
61
61
|
stateKey: v,
|
|
@@ -77,16 +77,16 @@ const zt = (t, i) => {
|
|
|
77
77
|
}
|
|
78
78
|
return { useCogsState: $, setCogsOptions: _ };
|
|
79
79
|
}, {
|
|
80
|
-
setUpdaterState:
|
|
80
|
+
setUpdaterState: Y,
|
|
81
81
|
setState: D,
|
|
82
|
-
getInitialOptions:
|
|
82
|
+
getInitialOptions: q,
|
|
83
83
|
getKeyState: gt,
|
|
84
|
-
getValidationErrors:
|
|
85
|
-
setStateLog:
|
|
84
|
+
getValidationErrors: pt,
|
|
85
|
+
setStateLog: xt,
|
|
86
86
|
updateInitialStateGlobal: ot,
|
|
87
|
-
addValidationError:
|
|
87
|
+
addValidationError: Ct,
|
|
88
88
|
removeValidationError: P,
|
|
89
|
-
setServerSyncActions:
|
|
89
|
+
setServerSyncActions: Tt
|
|
90
90
|
} = r.getState(), ft = (t) => {
|
|
91
91
|
if (!t) return null;
|
|
92
92
|
try {
|
|
@@ -95,7 +95,7 @@ const zt = (t, i) => {
|
|
|
95
95
|
} catch (i) {
|
|
96
96
|
return console.error("Error loading from localStorage:", i), null;
|
|
97
97
|
}
|
|
98
|
-
},
|
|
98
|
+
}, ht = (t, i, m, y) => {
|
|
99
99
|
m?.log && console.log(
|
|
100
100
|
"saving to localstorage",
|
|
101
101
|
i,
|
|
@@ -112,7 +112,7 @@ const zt = (t, i) => {
|
|
|
112
112
|
}, _ = `${y}-${i}-${g}`;
|
|
113
113
|
window.localStorage.setItem(_, JSON.stringify($));
|
|
114
114
|
}
|
|
115
|
-
},
|
|
115
|
+
}, kt = (t, i, m, y, g, $) => {
|
|
116
116
|
const _ = {
|
|
117
117
|
initialState: i,
|
|
118
118
|
updaterState: X(
|
|
@@ -123,8 +123,8 @@ const zt = (t, i) => {
|
|
|
123
123
|
),
|
|
124
124
|
state: m
|
|
125
125
|
};
|
|
126
|
-
|
|
127
|
-
ot(t, _.initialState),
|
|
126
|
+
H(() => {
|
|
127
|
+
ot(t, _.initialState), Y(t, _.updaterState), D(t, _.state);
|
|
128
128
|
});
|
|
129
129
|
}, St = (t) => {
|
|
130
130
|
const i = r.getState().stateComponents.get(t);
|
|
@@ -133,7 +133,7 @@ const zt = (t, i) => {
|
|
|
133
133
|
i.components.forEach((y) => {
|
|
134
134
|
m.add(() => y.forceUpdate());
|
|
135
135
|
}), queueMicrotask(() => {
|
|
136
|
-
|
|
136
|
+
H(() => {
|
|
137
137
|
m.forEach((y) => y());
|
|
138
138
|
});
|
|
139
139
|
});
|
|
@@ -144,7 +144,7 @@ const zt = (t, i) => {
|
|
|
144
144
|
g && g.forceUpdate();
|
|
145
145
|
}
|
|
146
146
|
};
|
|
147
|
-
function
|
|
147
|
+
function Ot(t, {
|
|
148
148
|
stateKey: i,
|
|
149
149
|
serverSync: m,
|
|
150
150
|
localStorage: y,
|
|
@@ -157,10 +157,10 @@ function jt(t, {
|
|
|
157
157
|
syncUpdate: e,
|
|
158
158
|
dependencies: S
|
|
159
159
|
} = {}) {
|
|
160
|
-
const [
|
|
160
|
+
const [T, A] = et({}), { sessionId: h } = At();
|
|
161
161
|
let R = !i;
|
|
162
|
-
const [u] = et(i ?? rt()), s = r.getState().stateLog[u], G =
|
|
163
|
-
|
|
162
|
+
const [u] = et(i ?? rt()), s = r.getState().stateLog[u], G = Z(/* @__PURE__ */ new Set()), F = Z(l ?? rt()), x = Z(null);
|
|
163
|
+
x.current = q(u), nt(() => {
|
|
164
164
|
if (e && e.stateKey === u && e.path?.[0]) {
|
|
165
165
|
D(u, (o) => ({
|
|
166
166
|
...o,
|
|
@@ -176,21 +176,21 @@ function jt(t, {
|
|
|
176
176
|
dt(u, {
|
|
177
177
|
initialState: f
|
|
178
178
|
});
|
|
179
|
-
const c =
|
|
179
|
+
const c = x.current;
|
|
180
180
|
let o = null;
|
|
181
181
|
c?.log && console.log("newoptions", c);
|
|
182
182
|
const d = L(c?.localStorage?.key) ? c?.localStorage?.key(f) : c?.localStorage?.key;
|
|
183
|
-
d &&
|
|
184
|
-
|
|
183
|
+
d && h && (o = ft(
|
|
184
|
+
h + "-" + u + "-" + d
|
|
185
185
|
));
|
|
186
186
|
let E = null;
|
|
187
|
-
f && (E = f, o && o.lastUpdated > (o.lastSyncedWithServer || 0) && (E = o.state),
|
|
187
|
+
f && (E = f, o && o.lastUpdated > (o.lastSyncedWithServer || 0) && (E = o.state), kt(
|
|
188
188
|
u,
|
|
189
189
|
f,
|
|
190
190
|
E,
|
|
191
191
|
n,
|
|
192
|
-
|
|
193
|
-
|
|
192
|
+
F.current,
|
|
193
|
+
h
|
|
194
194
|
), St(u), A({}));
|
|
195
195
|
}, [f, ...S || []]), It(() => {
|
|
196
196
|
R && dt(u, {
|
|
@@ -200,7 +200,7 @@ function jt(t, {
|
|
|
200
200
|
localStorage: y,
|
|
201
201
|
middleware: $
|
|
202
202
|
});
|
|
203
|
-
const c = `${u}////${
|
|
203
|
+
const c = `${u}////${F.current}`, o = r.getState().stateComponents.get(u) || {
|
|
204
204
|
components: /* @__PURE__ */ new Map()
|
|
205
205
|
};
|
|
206
206
|
return o.components.set(c, {
|
|
@@ -210,35 +210,35 @@ function jt(t, {
|
|
|
210
210
|
depsFunction: _ || void 0,
|
|
211
211
|
reactiveType: v ?? ["component", "deps"]
|
|
212
212
|
}), r.getState().stateComponents.set(u, o), A({}), () => {
|
|
213
|
-
const d = `${u}////${
|
|
213
|
+
const d = `${u}////${F.current}`;
|
|
214
214
|
o && (o.components.delete(d), o.components.size === 0 && r.getState().stateComponents.delete(u));
|
|
215
215
|
};
|
|
216
216
|
}, []);
|
|
217
217
|
const n = (c, o, d, E) => {
|
|
218
218
|
if (Array.isArray(o)) {
|
|
219
|
-
const
|
|
220
|
-
G.current.add(
|
|
219
|
+
const k = `${u}-${o.join(".")}`;
|
|
220
|
+
G.current.add(k);
|
|
221
221
|
}
|
|
222
|
-
D(u, (
|
|
223
|
-
const N = L(c) ? c(
|
|
224
|
-
if (
|
|
225
|
-
let
|
|
222
|
+
D(u, (k) => {
|
|
223
|
+
const N = L(c) ? c(k) : c, j = `${u}-${o.join(".")}`;
|
|
224
|
+
if (j) {
|
|
225
|
+
let b = !1, I = r.getState().signalDomElements.get(j);
|
|
226
226
|
if ((!I || I.size === 0) && (d.updateType === "insert" || d.updateType === "cut")) {
|
|
227
|
-
const V = o.slice(0, -1),
|
|
228
|
-
if (Array.isArray(
|
|
229
|
-
|
|
227
|
+
const V = o.slice(0, -1), p = U(N, V);
|
|
228
|
+
if (Array.isArray(p)) {
|
|
229
|
+
b = !0;
|
|
230
230
|
const w = `${u}-${V.join(".")}`;
|
|
231
231
|
I = r.getState().signalDomElements.get(w);
|
|
232
232
|
}
|
|
233
233
|
}
|
|
234
234
|
if (I) {
|
|
235
|
-
const V =
|
|
236
|
-
I.forEach(({ parentId:
|
|
237
|
-
const
|
|
238
|
-
`[data-parent-id="${
|
|
235
|
+
const V = b ? U(N, o.slice(0, -1)) : U(N, o);
|
|
236
|
+
I.forEach(({ parentId: p, position: w, effect: W }) => {
|
|
237
|
+
const O = document.querySelector(
|
|
238
|
+
`[data-parent-id="${p}"]`
|
|
239
239
|
);
|
|
240
|
-
if (
|
|
241
|
-
const st = Array.from(
|
|
240
|
+
if (O) {
|
|
241
|
+
const st = Array.from(O.childNodes);
|
|
242
242
|
if (st[w]) {
|
|
243
243
|
const vt = W ? new Function("state", `return (${W})(state)`)(V) : V;
|
|
244
244
|
st[w].textContent = String(vt);
|
|
@@ -247,32 +247,32 @@ function jt(t, {
|
|
|
247
247
|
});
|
|
248
248
|
}
|
|
249
249
|
}
|
|
250
|
-
d.updateType === "update" && (E ||
|
|
251
|
-
(E ||
|
|
250
|
+
d.updateType === "update" && (E || x.current?.validationKey) && o && P(
|
|
251
|
+
(E || x.current?.validationKey) + "." + o.join(".")
|
|
252
252
|
);
|
|
253
|
-
const
|
|
254
|
-
d.updateType === "cut" &&
|
|
255
|
-
|
|
256
|
-
), d.updateType === "insert" &&
|
|
257
|
-
|
|
253
|
+
const C = o.slice(0, o.length - 1);
|
|
254
|
+
d.updateType === "cut" && x.current?.validationKey && P(
|
|
255
|
+
x.current?.validationKey + "." + C.join(".")
|
|
256
|
+
), d.updateType === "insert" && x.current?.validationKey && pt(
|
|
257
|
+
x.current?.validationKey + "." + C.join(".")
|
|
258
258
|
).filter(([I, V]) => {
|
|
259
|
-
let
|
|
260
|
-
if (I ==
|
|
261
|
-
let w = I + "." +
|
|
262
|
-
P(I),
|
|
259
|
+
let p = I?.split(".").length;
|
|
260
|
+
if (I == C.join(".") && p == C.length - 1) {
|
|
261
|
+
let w = I + "." + C;
|
|
262
|
+
P(I), Ct(w, V);
|
|
263
263
|
}
|
|
264
264
|
});
|
|
265
|
-
const
|
|
265
|
+
const z = U(k, o), mt = U(N, o), yt = d.updateType === "update" ? o.join(".") : [...o].slice(0, -1).join("."), at = r.getState().stateComponents.get(u);
|
|
266
266
|
if (at)
|
|
267
|
-
for (const [
|
|
267
|
+
for (const [b, I] of at.components.entries()) {
|
|
268
268
|
let V = !1;
|
|
269
|
-
const
|
|
270
|
-
if (!
|
|
271
|
-
if (
|
|
269
|
+
const p = Array.isArray(I.reactiveType) ? I.reactiveType : [I.reactiveType || "component"];
|
|
270
|
+
if (!p.includes("none")) {
|
|
271
|
+
if (p.includes("all")) {
|
|
272
272
|
I.forceUpdate();
|
|
273
273
|
continue;
|
|
274
274
|
}
|
|
275
|
-
if (
|
|
275
|
+
if (p.includes("component") && I.paths && (I.paths.has(yt) || I.paths.has("")) && (V = !0), !V && p.includes("deps") && I.depsFunction) {
|
|
276
276
|
const w = I.depsFunction(N);
|
|
277
277
|
typeof w == "boolean" ? w && (V = !0) : M(I.deps, w) || (I.deps = w, V = !0);
|
|
278
278
|
}
|
|
@@ -285,28 +285,28 @@ function jt(t, {
|
|
|
285
285
|
path: o,
|
|
286
286
|
updateType: d.updateType,
|
|
287
287
|
status: "new",
|
|
288
|
-
oldValue:
|
|
288
|
+
oldValue: z,
|
|
289
289
|
newValue: mt
|
|
290
290
|
};
|
|
291
|
-
if (
|
|
292
|
-
const V = [...
|
|
293
|
-
const W = `${w.stateKey}:${JSON.stringify(w.path)}`,
|
|
294
|
-
return
|
|
291
|
+
if (xt(u, (b) => {
|
|
292
|
+
const V = [...b ?? [], it].reduce((p, w) => {
|
|
293
|
+
const W = `${w.stateKey}:${JSON.stringify(w.path)}`, O = p.get(W);
|
|
294
|
+
return O ? (O.timeStamp = Math.max(O.timeStamp, w.timeStamp), O.newValue = w.newValue, O.oldValue = O.oldValue ?? w.oldValue, O.updateType = w.updateType) : p.set(W, { ...w }), p;
|
|
295
295
|
}, /* @__PURE__ */ new Map());
|
|
296
296
|
return Array.from(V.values());
|
|
297
|
-
}),
|
|
297
|
+
}), ht(
|
|
298
298
|
N,
|
|
299
299
|
u,
|
|
300
|
-
|
|
301
|
-
|
|
300
|
+
x.current,
|
|
301
|
+
h
|
|
302
302
|
), $ && $({
|
|
303
303
|
updateLog: s,
|
|
304
304
|
update: it
|
|
305
|
-
}),
|
|
306
|
-
const
|
|
307
|
-
|
|
305
|
+
}), x.current?.serverSync) {
|
|
306
|
+
const b = r.getState().serverState[u], I = x.current?.serverSync;
|
|
307
|
+
Tt(u, {
|
|
308
308
|
syncKey: typeof I.syncKey == "string" ? I.syncKey : I.syncKey({ state: N }),
|
|
309
|
-
rollBackState:
|
|
309
|
+
rollBackState: b,
|
|
310
310
|
actionTimeStamp: Date.now() + (I.debounce ?? 3e3),
|
|
311
311
|
status: "waiting"
|
|
312
312
|
});
|
|
@@ -314,20 +314,20 @@ function jt(t, {
|
|
|
314
314
|
return N;
|
|
315
315
|
});
|
|
316
316
|
};
|
|
317
|
-
r.getState().updaterState[u] || (
|
|
317
|
+
r.getState().updaterState[u] || (Y(
|
|
318
318
|
u,
|
|
319
319
|
X(
|
|
320
320
|
u,
|
|
321
321
|
n,
|
|
322
|
-
|
|
323
|
-
|
|
322
|
+
F.current,
|
|
323
|
+
h
|
|
324
324
|
)
|
|
325
325
|
), r.getState().cogsStateStore[u] || D(u, t), r.getState().initialStateGlobal[u] || ot(u, t));
|
|
326
326
|
const a = _t(() => X(
|
|
327
327
|
u,
|
|
328
328
|
n,
|
|
329
|
-
|
|
330
|
-
|
|
329
|
+
F.current,
|
|
330
|
+
h
|
|
331
331
|
), [u]);
|
|
332
332
|
return [gt(u), a];
|
|
333
333
|
}
|
|
@@ -348,9 +348,9 @@ function X(t, i, m, y) {
|
|
|
348
348
|
e?.key && P(e?.key), f?.validationKey && P(f.validationKey);
|
|
349
349
|
const S = r.getState().initialStateGlobal[t];
|
|
350
350
|
g.clear(), $++;
|
|
351
|
-
const
|
|
352
|
-
return R && localStorage.removeItem(R),
|
|
353
|
-
|
|
351
|
+
const T = l(S, []), A = q(t), h = L(A?.localStorage?.key) ? A?.localStorage?.key(S) : A?.localStorage?.key, R = `${y}-${t}-${h}`;
|
|
352
|
+
return R && localStorage.removeItem(R), H(() => {
|
|
353
|
+
Y(t, T), D(t, S);
|
|
354
354
|
const u = r.getState().stateComponents.get(t);
|
|
355
355
|
u && u.components.forEach((s) => {
|
|
356
356
|
s.forceUpdate();
|
|
@@ -365,11 +365,11 @@ function X(t, i, m, y) {
|
|
|
365
365
|
m,
|
|
366
366
|
y
|
|
367
367
|
);
|
|
368
|
-
return
|
|
369
|
-
ot(t, f),
|
|
368
|
+
return H(() => {
|
|
369
|
+
ot(t, f), Y(t, e), D(t, f);
|
|
370
370
|
const S = r.getState().stateComponents.get(t);
|
|
371
|
-
S && S.components.forEach((
|
|
372
|
-
|
|
371
|
+
S && S.components.forEach((T) => {
|
|
372
|
+
T.forceUpdate();
|
|
373
373
|
});
|
|
374
374
|
}), {
|
|
375
375
|
fetchId: (S) => e.get()[S]
|
|
@@ -384,15 +384,15 @@ function X(t, i, m, y) {
|
|
|
384
384
|
}
|
|
385
385
|
};
|
|
386
386
|
function l(f, e = [], S) {
|
|
387
|
-
const
|
|
388
|
-
g.get(
|
|
387
|
+
const T = e.map(String).join(".");
|
|
388
|
+
g.get(T);
|
|
389
389
|
const A = function() {
|
|
390
390
|
return r().getNestedState(t, e);
|
|
391
391
|
};
|
|
392
392
|
Object.keys(v).forEach((u) => {
|
|
393
393
|
A[u] = v[u];
|
|
394
394
|
});
|
|
395
|
-
const
|
|
395
|
+
const h = {
|
|
396
396
|
apply(u, s, G) {
|
|
397
397
|
return console.log(
|
|
398
398
|
`PROXY APPLY TRAP HIT: stateKey=${t}, path=${e.join(".")}`
|
|
@@ -420,7 +420,7 @@ function X(t, i, m, y) {
|
|
|
420
420
|
};
|
|
421
421
|
if (s === "removeStorage")
|
|
422
422
|
return () => {
|
|
423
|
-
const n = r.getState().initialStateGlobal[t], a =
|
|
423
|
+
const n = r.getState().initialStateGlobal[t], a = q(t), c = L(a?.localStorage?.key) ? a?.localStorage?.key(n) : a?.localStorage?.key, o = `${y}-${t}-${c}`;
|
|
424
424
|
console.log("removing storage", o), o && localStorage.removeItem(o);
|
|
425
425
|
};
|
|
426
426
|
if (s === "showValidationErrors")
|
|
@@ -462,14 +462,14 @@ function X(t, i, m, y) {
|
|
|
462
462
|
(o) => o.join(".") === e.join(".")
|
|
463
463
|
), c = a ? f : r.getState().getNestedState(t, e);
|
|
464
464
|
return s !== "stateMapNoRender" && (g.clear(), $++), c.map((o, d) => {
|
|
465
|
-
const E = a && o.__origIndex ? o.__origIndex : d,
|
|
465
|
+
const E = a && o.__origIndex ? o.__origIndex : d, k = l(
|
|
466
466
|
o,
|
|
467
467
|
[...e, E.toString()],
|
|
468
468
|
S
|
|
469
469
|
);
|
|
470
470
|
return n(
|
|
471
471
|
o,
|
|
472
|
-
|
|
472
|
+
k,
|
|
473
473
|
d,
|
|
474
474
|
f,
|
|
475
475
|
l(f, e, S)
|
|
@@ -477,7 +477,7 @@ function X(t, i, m, y) {
|
|
|
477
477
|
});
|
|
478
478
|
};
|
|
479
479
|
if (s === "$stateMap")
|
|
480
|
-
return (n) => Q(
|
|
480
|
+
return (n) => Q(jt, {
|
|
481
481
|
proxy: {
|
|
482
482
|
_stateKey: t,
|
|
483
483
|
_path: e,
|
|
@@ -526,35 +526,35 @@ function X(t, i, m, y) {
|
|
|
526
526
|
let E = null;
|
|
527
527
|
if (!o.some((N) => {
|
|
528
528
|
if (a) {
|
|
529
|
-
const
|
|
530
|
-
(
|
|
529
|
+
const C = a.every(
|
|
530
|
+
(z) => M(N[z], d[z])
|
|
531
531
|
);
|
|
532
|
-
return
|
|
532
|
+
return C && (E = N), C;
|
|
533
533
|
}
|
|
534
|
-
const
|
|
535
|
-
return
|
|
534
|
+
const j = M(N, d);
|
|
535
|
+
return j && (E = N), j;
|
|
536
536
|
}))
|
|
537
537
|
_(e), K(i, d, e, t);
|
|
538
538
|
else if (c && E) {
|
|
539
|
-
const N = c(E),
|
|
540
|
-
(
|
|
539
|
+
const N = c(E), j = o.map(
|
|
540
|
+
(C) => M(C, E) ? N : C
|
|
541
541
|
);
|
|
542
|
-
_(e),
|
|
542
|
+
_(e), B(i, j, e);
|
|
543
543
|
}
|
|
544
544
|
};
|
|
545
545
|
if (s === "cut")
|
|
546
546
|
return (n, a) => {
|
|
547
|
-
a?.waitForSync || (_(e),
|
|
547
|
+
a?.waitForSync || (_(e), J(i, e, t, n));
|
|
548
548
|
};
|
|
549
549
|
if (s === "cutByValue")
|
|
550
550
|
return (n) => {
|
|
551
551
|
for (let a = 0; a < f.length; a++)
|
|
552
|
-
f[a] === n &&
|
|
552
|
+
f[a] === n && J(i, e, t, a);
|
|
553
553
|
};
|
|
554
554
|
if (s === "toggleByValue")
|
|
555
555
|
return (n) => {
|
|
556
556
|
const a = f.findIndex((c) => c === n);
|
|
557
|
-
a > -1 ?
|
|
557
|
+
a > -1 ? J(i, e, t, a) : K(i, n, e, t);
|
|
558
558
|
};
|
|
559
559
|
if (s === "stateFilter")
|
|
560
560
|
return (n) => {
|
|
@@ -575,7 +575,7 @@ function X(t, i, m, y) {
|
|
|
575
575
|
if (!isNaN(Number(G))) {
|
|
576
576
|
const n = e.slice(0, -1), a = r.getState().getNestedState(t, n);
|
|
577
577
|
if (Array.isArray(a) && s === "cut")
|
|
578
|
-
return () =>
|
|
578
|
+
return () => J(
|
|
579
579
|
i,
|
|
580
580
|
n,
|
|
581
581
|
t,
|
|
@@ -616,7 +616,7 @@ function X(t, i, m, y) {
|
|
|
616
616
|
const a = e.slice(0, -1), c = Number(e[e.length - 1]), o = a.join(".");
|
|
617
617
|
n ? r.getState().setSelectedIndex(t, o, c) : r.getState().setSelectedIndex(t, o, void 0);
|
|
618
618
|
const d = r.getState().getNestedState(t, [...a]);
|
|
619
|
-
|
|
619
|
+
B(i, d, a), _(a);
|
|
620
620
|
};
|
|
621
621
|
if (e.length == 0) {
|
|
622
622
|
if (s === "validateZodSchema")
|
|
@@ -634,9 +634,9 @@ function X(t, i, m, y) {
|
|
|
634
634
|
E && E.startsWith(n.key) && P(E);
|
|
635
635
|
});
|
|
636
636
|
const d = n.zodSchema.safeParse(c);
|
|
637
|
-
return d.success ? !0 : (d.error.errors.forEach((
|
|
638
|
-
const N =
|
|
639
|
-
a(
|
|
637
|
+
return d.success ? !0 : (d.error.errors.forEach((k) => {
|
|
638
|
+
const N = k.path, j = k.message, C = [n.key, ...N].join(".");
|
|
639
|
+
a(C, j);
|
|
640
640
|
}), St(t), !1);
|
|
641
641
|
} catch (o) {
|
|
642
642
|
return console.error("Zod schema validation failed", o), !1;
|
|
@@ -682,12 +682,12 @@ function X(t, i, m, y) {
|
|
|
682
682
|
return (n, a) => {
|
|
683
683
|
if (a?.debounce)
|
|
684
684
|
wt(() => {
|
|
685
|
-
|
|
685
|
+
B(i, n, e, "");
|
|
686
686
|
const c = r.getState().getNestedState(t, e);
|
|
687
687
|
a?.afterUpdate && a.afterUpdate(c);
|
|
688
688
|
}, a.debounce);
|
|
689
689
|
else {
|
|
690
|
-
|
|
690
|
+
B(i, n, e, "");
|
|
691
691
|
const c = r.getState().getNestedState(t, e);
|
|
692
692
|
a?.afterUpdate && a.afterUpdate(c);
|
|
693
693
|
}
|
|
@@ -704,11 +704,11 @@ function X(t, i, m, y) {
|
|
|
704
704
|
formOpts: a
|
|
705
705
|
}
|
|
706
706
|
);
|
|
707
|
-
const
|
|
708
|
-
return l(
|
|
707
|
+
const F = [...e, s], x = r.getState().getNestedState(t, F);
|
|
708
|
+
return l(x, F, S);
|
|
709
709
|
}
|
|
710
|
-
}, R = new Proxy(A,
|
|
711
|
-
return g.set(
|
|
710
|
+
}, R = new Proxy(A, h);
|
|
711
|
+
return g.set(T, {
|
|
712
712
|
proxy: R,
|
|
713
713
|
stateVersion: $
|
|
714
714
|
}), R;
|
|
@@ -718,9 +718,9 @@ function X(t, i, m, y) {
|
|
|
718
718
|
);
|
|
719
719
|
}
|
|
720
720
|
function tt(t) {
|
|
721
|
-
return Q(
|
|
721
|
+
return Q(Ft, { proxy: t });
|
|
722
722
|
}
|
|
723
|
-
function
|
|
723
|
+
function jt({
|
|
724
724
|
proxy: t,
|
|
725
725
|
rebuildStateShape: i
|
|
726
726
|
}) {
|
|
@@ -732,10 +732,10 @@ function Ft({
|
|
|
732
732
|
(g, $, _, v, l) => t._mapFn(g, $, _, v, l)
|
|
733
733
|
) : null;
|
|
734
734
|
}
|
|
735
|
-
function
|
|
735
|
+
function Ft({
|
|
736
736
|
proxy: t
|
|
737
737
|
}) {
|
|
738
|
-
const i =
|
|
738
|
+
const i = Z(null), m = `${t._stateKey}-${t._path.join(".")}`;
|
|
739
739
|
return nt(() => {
|
|
740
740
|
const y = i.current;
|
|
741
741
|
if (!y || !y.parentElement) return;
|
|
@@ -763,8 +763,8 @@ function bt({
|
|
|
763
763
|
else
|
|
764
764
|
S = e;
|
|
765
765
|
S !== null && typeof S == "object" && (S = JSON.stringify(S));
|
|
766
|
-
const
|
|
767
|
-
y.replaceWith(
|
|
766
|
+
const T = document.createTextNode(String(S));
|
|
767
|
+
y.replaceWith(T);
|
|
768
768
|
}, [t._stateKey, t._path.join("."), t._effect]), Q("span", {
|
|
769
769
|
ref: i,
|
|
770
770
|
style: { display: "none" },
|
|
@@ -792,6 +792,6 @@ export {
|
|
|
792
792
|
qt as addStateOptions,
|
|
793
793
|
zt as createCogsState,
|
|
794
794
|
Bt as notifyComponent,
|
|
795
|
-
|
|
795
|
+
Ot as useCogsStateFn
|
|
796
796
|
};
|
|
797
797
|
//# sourceMappingURL=CogsState.jsx.map
|
package/dist/CogsState.jsx.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CogsState.jsx","sources":["../src/CogsState.tsx"],"sourcesContent":["\"use client\";\r\nimport {\r\n createElement,\r\n startTransition,\r\n useEffect,\r\n useLayoutEffect,\r\n useMemo,\r\n useRef,\r\n useState,\r\n useSyncExternalStore,\r\n type ReactNode,\r\n} from \"react\";\r\n\r\nimport {\r\n debounce,\r\n getDifferences,\r\n getNestedValue,\r\n isFunction,\r\n type GenericObject,\r\n} from \"./utility.js\";\r\nimport {\r\n cutFunc,\r\n FormControlComponent,\r\n pushFunc,\r\n updateFn,\r\n ValidationWrapper,\r\n} from \"./Functions.js\";\r\nimport { isDeepEqual, transformStateFunc } from \"./utility.js\";\r\nimport type { UseMutationResult } from \"@tanstack/react-query\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { ZodArray, ZodObject, type ZodRawShape } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\n\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\nexport type ServerSyncStatus = {\r\n isFresh: boolean;\r\n isFreshTime: number;\r\n isStale: boolean;\r\n isStaleTime: number;\r\n isSyncing: boolean;\r\n isSyncingTime: number;\r\n};\r\n\r\nexport type SyncInfo = {\r\n timeStamp: number;\r\n userId: number;\r\n};\r\n\r\nexport type FormElementParams<T> = {\r\n get: () => T;\r\n\r\n set: UpdateType<T>;\r\n syncStatus: (SyncInfo & { date: Date }) | null;\r\n path: string[];\r\n validationErrors: () => string[];\r\n addValidationError: (message?: string) => void;\r\n\r\n inputProps: {\r\n ref?: React.RefObject<any>;\r\n value?: T extends boolean ? never : T;\r\n onChange?: (\r\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\r\n ) => void;\r\n onBlur?: () => void;\r\n };\r\n};\r\n\r\nexport type StateKeys = string;\r\n\r\ntype findWithFuncType<U> = (\r\n thisKey: keyof U,\r\n thisValue: U[keyof U]\r\n) => EndType<U> & StateObject<U>;\r\nexport type PushArgs<U> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => void;\r\n\r\ntype CutFunctionType = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => void;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\n\r\nexport type ArrayEndType<TShape extends unknown> = {\r\n findWith: findWithFuncType<InferArrayElement<TShape>>;\r\n index: (index: number) => StateObject<InferArrayElement<TShape>> & {\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n cutByValue: (value: string | number | boolean) => void;\r\n toggleByValue: (value: string | number | boolean) => void;\r\n stateSort: (\r\n compareFn: (\r\n a: InferArrayElement<TShape>,\r\n b: InferArrayElement<TShape>\r\n ) => number\r\n ) => ArrayEndType<TShape>;\r\n\r\n stateMapNoRender: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n $stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateFlattenOn: <K extends keyof InferArrayElement<TShape>>(\r\n field: K\r\n ) => StateObject<InferArrayElement<InferArrayElement<TShape>[K]>[]>;\r\n uniqueInsert: (\r\n payload: UpdateArg<InferArrayElement<TShape>>,\r\n fields?: (keyof InferArrayElement<TShape>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => void;\r\n stateFilter: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => void\r\n ) => ArrayEndType<TShape>;\r\n getSelected: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n getSelectedIndex: () => number;\r\n} & EndType<TShape> & {\r\n [K in keyof (any[] extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<Prettify<T>>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\nexport type FormOptsType = {\r\n key?: string;\r\n validation?: {\r\n hideMessage?: boolean;\r\n message?: string;\r\n stretch?: boolean;\r\n props?: GenericObject;\r\n disable?: boolean;\r\n };\r\n formElements?: boolean;\r\n debounceTime?: number;\r\n stateServerDifferences?: string[][];\r\n};\r\n\r\nexport type FormControl<T> = (obj: FormElementParams<T>) => JSX.Element;\r\n\r\nexport type UpdateArg<S> = S | ((prevState: S) => S);\r\nexport type UpdateOpts<T> = {\r\n afterUpdate?: (state: T) => void;\r\n debounce?: number;\r\n};\r\nexport type ObjectEndType<T> = EndType<T> & {\r\n [K in keyof T]-?: ObjectEndType<T[K]>;\r\n} & {\r\n stateObject: (callbackfn: (value: T, setter: StateObject<T>) => void) => any;\r\n delete: () => void;\r\n};\r\ntype EffectFunction<T, R> = (state: T) => R;\r\nexport type EndType<T, IsArrayElement = false> = {\r\n update: UpdateType<T>;\r\n _path: string[];\r\n _stateKey: string;\r\n formElement: (control: FormControl<T>, opts?: FormOptsType) => JSX.Element;\r\n get: () => T;\r\n $get: () => T;\r\n $derive: <R>(fn: EffectFunction<T, R>) => R;\r\n _status: \"fresh\" | \"stale\" | \"synced\";\r\n getStatus: () => \"fresh\" | \"stale\";\r\n showValidationErrors: () => string[];\r\n setValidation: (ctx: string) => void;\r\n removeValidation: (ctx: string) => void;\r\n ignoreFields: (fields: string[]) => StateObject<T>;\r\n _selected: boolean;\r\n setSelected: (value: boolean) => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n validationWrapper: ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => JSX.Element;\r\n lastSynced?: SyncInfo;\r\n} & (IsArrayElement extends true ? { cut: () => void } : {}) & {\r\n [K in keyof (any extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type StateObject<T> = (T extends any[]\r\n ? ArrayEndType<T>\r\n : T extends Record<string, unknown> | object\r\n ? { [K in keyof T]-?: StateObject<T[K]> } & ObjectEndType<T>\r\n : T extends string | number | boolean | null\r\n ? T\r\n : never) &\r\n EndType<T, true> & {\r\n getAllFormRefs: () => Map<string, React.RefObject<any>>;\r\n _componentId: string | null;\r\n getComponents: () => ComponentsType;\r\n validateZodSchema: () => void;\r\n _initialState: T;\r\n updateInitialState: (newState: T | null) => {\r\n fetchId: (field: keyof T) => string | number;\r\n };\r\n _isLoading: boolean;\r\n _serverState: T;\r\n revertToInitialState: (obj?: { validationKey?: string }) => T;\r\n middleware: (\r\n middles: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void\r\n ) => void;\r\n _isServerSynced: () => boolean;\r\n getLocalStorage: (key: string) => LocalStorageData<T> | null;\r\n };\r\n\r\nexport type CogsUpdate<T extends unknown> = UpdateType<T>;\r\n\r\nexport type EffectiveSetState<TStateObject> = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"update\" | \"insert\" | \"cut\" },\r\n validationKey?: string,\r\n opts?: UpdateOpts<TStateObject>\r\n) => void;\r\n\r\nexport type UpdateTypeDetail = {\r\n timeStamp: number;\r\n stateKey: string;\r\n updateType: \"update\" | \"insert\" | \"cut\";\r\n path: string[];\r\n status: \"new\" | \"sent\" | \"synced\";\r\n oldValue: any;\r\n newValue: any;\r\n userId?: number;\r\n};\r\n\r\nexport type ActionsType<T> = {\r\n type: \"onChange\";\r\n action: ({ state, actionType }: { state: T; actionType: string }) => void;\r\n debounce?: number;\r\n}[];\r\n\r\ntype ArrayToObject<T extends string[]> = Record<T[number], string>;\r\ntype CookieType<T> = {\r\n timeStamp: number;\r\n value: T;\r\n cookieName: string;\r\n OnUnMountCookie?: Boolean;\r\n};\r\nexport type CogsCookiesType<T extends string[] = string[]> = CookieType<\r\n ArrayToObject<T>\r\n>;\r\nexport type ReactivityType = \"none\" | \"component\" | \"deps\" | \"all\";\r\n\r\ntype ValidationOptionsType = {\r\n key?: string;\r\n zodSchema?: ZodObject<ZodRawShape> | ZodArray<ZodObject<ZodRawShape>>;\r\n onBlur?: boolean;\r\n};\r\n\r\nexport type OptionsType<T extends unknown = unknown> = {\r\n log?: boolean;\r\n componentId?: string;\r\n serverSync?: ServerSyncType<T>;\r\n validation?: ValidationOptionsType;\r\n enableServerState?: boolean;\r\n middleware?: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void;\r\n\r\n modifyState?: (state: T) => T;\r\n localStorage?: { key: string | ((state: T) => string) };\r\n formElements?: FormsElementsType;\r\n enabledSync?: (state: T) => boolean;\r\n reactiveDeps?: (state: T) => any[] | true;\r\n reactiveType?: ReactivityType[] | ReactivityType;\r\n syncUpdate?: Partial<UpdateTypeDetail>;\r\n\r\n initialState?: T;\r\n dependencies?: any[]; // Just like useEffect dependencies\r\n};\r\nexport type ServerSyncType<T> = {\r\n testKey?: string;\r\n syncKey: (({ state }: { state: T }) => string) | string;\r\n syncFunction: ({ state }: { state: T }) => void;\r\n debounce?: number;\r\n mutation: UseMutationResult<any, unknown, any, unknown>;\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\n\r\nfunction setOptions<StateKey, Opt>({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n}: {\r\n stateKey: StateKey;\r\n options?: OptionsType<any>;\r\n initialOptionsPart: Record<string, any>;\r\n}) {\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n const initialOptionsPartState = initialOptionsPart[stateKey as string] || {};\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n // This is the key fix - merge in the correct order\r\n const mergedOptions = {\r\n ...initialOptionsPartState, // Options from createCogsState\r\n ...initialOptions, // Currently stored options\r\n ...options, // New options passed to useCogsState\r\n };\r\n\r\n // Set the merged options\r\n\r\n let needToAdd = false;\r\n if (options) {\r\n for (const key in options) {\r\n if (!mergedOptions.hasOwnProperty(key)) {\r\n needToAdd = true;\r\n\r\n mergedOptions[key] = options[key as keyof typeof options];\r\n } else {\r\n if (\r\n key == \"localStorage\" &&\r\n options[key] &&\r\n mergedOptions[key].key !== options[key]?.key\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n if (needToAdd) {\r\n setInitialStateOptions(stateKey as string, mergedOptions);\r\n }\r\n}\r\nexport function addStateOptions<T extends unknown>(\r\n initialState: T,\r\n { formElements, validation }: OptionsType<T>\r\n) {\r\n return { initialState: initialState, formElements, validation } as T;\r\n}\r\n\r\nexport const createCogsState = <State extends Record<string, unknown>>(\r\n initialState: State,\r\n opt?: { formElements?: FormsElementsType; validation?: ValidationOptionsType }\r\n) => {\r\n let newInitialState = initialState;\r\n\r\n // Extract state parts and options using transformStateFunc\r\n const [statePart, initialOptionsPart] =\r\n transformStateFunc<State>(newInitialState);\r\n\r\n // Apply global formElements as defaults to each state key's options\r\n if (opt?.formElements || opt?.validation) {\r\n Object.keys(initialOptionsPart).forEach((key) => {\r\n // Get the existing options for this state key\r\n initialOptionsPart[key] = initialOptionsPart[key] || {};\r\n\r\n initialOptionsPart[key].formElements = {\r\n ...opt.formElements, // Global defaults first\r\n ...opt?.validation,\r\n ...(initialOptionsPart[key].formElements || {}), // State-specific overrides\r\n };\r\n getGlobalStore\r\n .getState()\r\n .setInitialStateOptions(key, initialOptionsPart[key]);\r\n });\r\n }\r\n\r\n getGlobalStore.getState().setInitialStates(statePart);\r\n type StateKeys = keyof typeof statePart;\r\n\r\n const useCogsState = <StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options?: OptionsType<(typeof statePart)[StateKey]>\r\n ) => {\r\n const [componentId] = useState(options?.componentId ?? uuidv4());\r\n setOptions({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n });\r\n\r\n const thiState =\r\n getGlobalStore.getState().cogsStateStore[stateKey as string] ||\r\n statePart[stateKey as string];\r\n const partialState = options?.modifyState\r\n ? options.modifyState(thiState)\r\n : thiState;\r\n\r\n const [state, updater] = useCogsStateFn<(typeof statePart)[StateKey]>(\r\n partialState,\r\n {\r\n stateKey: stateKey as string,\r\n syncUpdate: options?.syncUpdate,\r\n componentId,\r\n localStorage: options?.localStorage,\r\n middleware: options?.middleware,\r\n enabledSync: options?.enabledSync,\r\n reactiveType: options?.reactiveType,\r\n reactiveDeps: options?.reactiveDeps,\r\n initialState: options?.initialState,\r\n dependencies: options?.dependencies,\r\n }\r\n );\r\n\r\n return updater;\r\n };\r\n\r\n function setCogsOptions<StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options: OptionsType<(typeof statePart)[StateKey]>\r\n ) {\r\n setOptions({ stateKey, options, initialOptionsPart });\r\n }\r\n\r\n return { useCogsState, setCogsOptions };\r\n};\r\n\r\nconst {\r\n setUpdaterState,\r\n setState,\r\n getInitialOptions,\r\n getKeyState,\r\n getValidationErrors,\r\n setStateLog,\r\n updateInitialStateGlobal,\r\n addValidationError,\r\n removeValidationError,\r\n setServerSyncActions,\r\n} = getGlobalStore.getState();\r\n\r\nconst loadFromLocalStorage = (localStorageKey: string) => {\r\n if (!localStorageKey) return null;\r\n\r\n try {\r\n const storedData = window.localStorage.getItem(localStorageKey);\r\n if (!storedData) return null;\r\n\r\n const parsedData = JSON.parse(storedData);\r\n\r\n return parsedData;\r\n } catch (error) {\r\n console.error(\"Error loading from localStorage:\", error);\r\n return null;\r\n }\r\n};\r\n\r\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string\r\n) => {\r\n if (currentInitialOptions?.log) {\r\n console.log(\r\n \"saving to localstorage\",\r\n thisKey,\r\n currentInitialOptions.localStorage?.key,\r\n sessionId\r\n );\r\n }\r\n const key = isFunction(currentInitialOptions?.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions?.localStorage?.key;\r\n if (key && sessionId) {\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer:\r\n getGlobalStore.getState().serverSyncLog[thisKey]?.[0]?.timeStamp,\r\n baseServerState: getGlobalStore.getState().serverState[thisKey],\r\n };\r\n\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n window.localStorage.setItem(storageKey, JSON.stringify(data));\r\n }\r\n};\r\n\r\ntype LocalStorageData<T> = {\r\n state: T;\r\n lastUpdated: number;\r\n lastSyncedWithServer?: number;\r\n baseServerState?: T; // Add this to track what server state our changes are based on\r\n};\r\n\r\nconst updateGlobalState = (\r\n thisKey: string,\r\n initialState: any,\r\n newState: any,\r\n effectiveSetState: EffectiveSetState<any>,\r\n componentId: string,\r\n sessionId?: string\r\n) => {\r\n // Update all global state at once\r\n const updates = {\r\n initialState: initialState,\r\n updaterState: createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n ),\r\n state: newState,\r\n };\r\n\r\n startTransition(() => {\r\n updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\r\n });\r\n};\r\n\r\nconst notifyComponents = (thisKey: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n if (!stateEntry) return;\r\n\r\n // Batch component updates\r\n const updates = new Set<() => void>();\r\n stateEntry.components.forEach((component) => {\r\n updates.add(() => component.forceUpdate());\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n startTransition(() => {\r\n updates.forEach((update) => update());\r\n });\r\n });\r\n};\r\n\r\nexport const notifyComponent = (stateKey: string, componentId: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Force an update to ensure the current value is saved\r\n\r\n component.forceUpdate();\r\n }\r\n }\r\n};\r\n\r\nexport function useCogsStateFn<TStateObject extends unknown>(\r\n stateObject: TStateObject,\r\n {\r\n stateKey,\r\n serverSync,\r\n localStorage,\r\n formElements,\r\n middleware,\r\n reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n } & OptionsType<TStateObject> = {}\r\n) {\r\n const [reactiveForce, forceUpdate] = useState({}); //this is the key to reactivity\r\n const { sessionId } = useCogsConfig();\r\n\r\n let noStateKey = stateKey ? false : true;\r\n const [thisKey] = useState(stateKey ?? uuidv4());\r\n const stateLog = getGlobalStore.getState().stateLog[thisKey];\r\n const componentUpdatesRef = useRef(new Set<string>());\r\n const componentIdRef = useRef(componentId ?? uuidv4());\r\n const latestInitialOptionsRef = useRef<any>(null);\r\n latestInitialOptionsRef.current = getInitialOptions(thisKey as string);\r\n\r\n useEffect(() => {\r\n if (syncUpdate && syncUpdate.stateKey === thisKey && syncUpdate.path?.[0]) {\r\n // Update the actual state value\r\n setState(thisKey, (prevState: any) => ({\r\n ...prevState,\r\n [syncUpdate.path![0]!]: syncUpdate.newValue,\r\n }));\r\n\r\n // Create combined key and update sync info\r\n const syncKey = `${syncUpdate.stateKey}:${syncUpdate.path.join(\".\")}`;\r\n getGlobalStore.getState().setSyncInfo(syncKey, {\r\n timeStamp: syncUpdate.timeStamp!,\r\n userId: syncUpdate.userId!,\r\n });\r\n }\r\n }, [syncUpdate]);\r\n\r\n useEffect(() => {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n const options = latestInitialOptionsRef.current;\r\n let localData = null;\r\n if (options?.log) {\r\n console.log(\"newoptions\", options);\r\n }\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options?.localStorage?.key(initialState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(\r\n sessionId + \"-\" + thisKey + \"-\" + localkey\r\n );\r\n }\r\n\r\n let newState = null;\r\n if (initialState) {\r\n newState = initialState;\r\n\r\n if (localData) {\r\n if (localData.lastUpdated > (localData.lastSyncedWithServer || 0)) {\r\n newState = localData.state;\r\n }\r\n }\r\n updateGlobalState(\r\n thisKey,\r\n initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n\r\n notifyComponents(thisKey);\r\n forceUpdate({});\r\n }\r\n }, [initialState, ...(dependencies || [])]);\r\n\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initialState,\r\n localStorage,\r\n middleware,\r\n });\r\n }\r\n\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(thisKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(depsKey, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set(),\r\n deps: [],\r\n depsFunction: reactiveDeps || undefined,\r\n reactiveType: reactiveType ?? [\"component\", \"deps\"],\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(thisKey, stateEntry);\r\n //need to force update to create the stateUpdates references\r\n forceUpdate({});\r\n return () => {\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n\r\n if (stateEntry) {\r\n stateEntry.components.delete(depsKey);\r\n if (stateEntry.components.size === 0) {\r\n getGlobalStore.getState().stateComponents.delete(thisKey);\r\n }\r\n }\r\n };\r\n }, []);\r\n\r\n const effectiveSetState = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"insert\" | \"cut\" | \"update\" },\r\n validationKey?: string\r\n ) => {\r\n if (Array.isArray(path)) {\r\n const pathKey = `${thisKey}-${path.join(\".\")}`;\r\n componentUpdatesRef.current.add(pathKey);\r\n }\r\n setState(thisKey, (prevValue: TStateObject) => {\r\n const payload = isFunction<TStateObject>(newStateOrFunction)\r\n ? newStateOrFunction(prevValue as TStateObject)\r\n : newStateOrFunction;\r\n\r\n const signalId = `${thisKey}-${path.join(\".\")}`;\r\n if (signalId) {\r\n let isArrayOperation = false;\r\n let elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(signalId);\r\n\r\n if (\r\n (!elements || elements.size === 0) &&\r\n (updateObj.updateType === \"insert\" || updateObj.updateType === \"cut\")\r\n ) {\r\n // Remove last segment (index) from path\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n // If it's an array, use that path for signal\r\n if (Array.isArray(arrayValue)) {\r\n isArrayOperation = true;\r\n const arraySignalId = `${thisKey}-${arrayPath.join(\".\")}`;\r\n elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(arraySignalId);\r\n }\r\n }\r\n\r\n if (elements) {\r\n const newValue = isArrayOperation\r\n ? getNestedValue(payload, path.slice(0, -1))\r\n : getNestedValue(payload, path);\r\n elements.forEach(({ parentId, position, effect }) => {\r\n const parent = document.querySelector(\r\n `[data-parent-id=\"${parentId}\"]`\r\n );\r\n if (parent) {\r\n const childNodes = Array.from(parent.childNodes);\r\n if (childNodes[position]) {\r\n const displayValue = effect\r\n ? new Function(\"state\", `return (${effect})(state)`)(newValue)\r\n : newValue;\r\n childNodes[position].textContent = String(displayValue);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n if (\r\n updateObj.updateType === \"update\" &&\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) +\r\n \".\" +\r\n path.join(\".\")\r\n );\r\n }\r\n const arrayWithoutIndex = path.slice(0, path.length - 1);\r\n if (\r\n updateObj.updateType === \"cut\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n\r\n //TODO this is untested its supposed to cahnge teh validation errors alreaady stored when a new entry is push\r\n\r\n getValidation.filter(([k, v]) => {\r\n let length = k?.split(\".\").length;\r\n\r\n if (\r\n k == arrayWithoutIndex.join(\".\") &&\r\n length == arrayWithoutIndex.length - 1\r\n ) {\r\n // console.log(length, pathWithoutIndex.length);\r\n let newKey = k + \".\" + arrayWithoutIndex;\r\n removeValidationError(k!);\r\n addValidationError(newKey, v!);\r\n }\r\n });\r\n }\r\n\r\n const oldValue = getNestedValue(prevValue, path);\r\n const newValue = getNestedValue(payload, path);\r\n const pathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : [...path].slice(0, -1).join(\".\");\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n\r\n if (stateEntry) {\r\n for (const [key, component] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes.includes(\"none\")) {\r\n continue;\r\n }\r\n\r\n // Force update if \"all\" is specified\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n\r\n continue;\r\n }\r\n\r\n // Check component-level path reactivity\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths &&\r\n (component.paths.has(pathToCheck) || component.paths.has(\"\"))\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n\r\n // Check dependency-based reactivity\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) {\r\n shouldUpdate = true;\r\n }\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n const timeStamp = Date.now();\r\n\r\n const newUpdate = {\r\n timeStamp,\r\n stateKey: thisKey,\r\n path,\r\n updateType: updateObj.updateType,\r\n status: \"new\" as const,\r\n oldValue,\r\n newValue,\r\n } satisfies UpdateTypeDetail;\r\n\r\n setStateLog(thisKey, (prevLogs) => {\r\n const logs = [...(prevLogs ?? []), newUpdate];\r\n\r\n // Aggregate the updates by stateKey and path\r\n const aggregatedLogs = logs.reduce((acc, log) => {\r\n const uniqueKey = `${log.stateKey}:${JSON.stringify(log.path)}`;\r\n const existing = acc.get(uniqueKey);\r\n\r\n if (existing) {\r\n // Update the existing entry with the most recent details\r\n existing.timeStamp = Math.max(existing.timeStamp, log.timeStamp);\r\n existing.newValue = log.newValue; // Overwrite with the latest value\r\n existing.oldValue = existing.oldValue ?? log.oldValue; // Retain the initial oldValue\r\n existing.updateType = log.updateType; // Update to the most recent type\r\n } else {\r\n // Add the log if no existing match is found\r\n acc.set(uniqueKey, { ...(log as any) });\r\n }\r\n\r\n return acc;\r\n }, new Map<string, typeof newUpdate>());\r\n\r\n // Convert the aggregated map back to an array\r\n return Array.from(aggregatedLogs.values());\r\n });\r\n\r\n saveToLocalStorage(\r\n payload,\r\n thisKey,\r\n latestInitialOptionsRef.current,\r\n sessionId\r\n );\r\n\r\n if (middleware) {\r\n middleware({\r\n updateLog: stateLog,\r\n update: newUpdate,\r\n });\r\n }\r\n if (latestInitialOptionsRef.current?.serverSync) {\r\n const serverStateStore = getGlobalStore.getState().serverState[thisKey];\r\n const serverSync = latestInitialOptionsRef.current?.serverSync;\r\n setServerSyncActions(thisKey, {\r\n syncKey:\r\n typeof serverSync.syncKey == \"string\"\r\n ? serverSync.syncKey\r\n : serverSync.syncKey({ state: payload }),\r\n rollBackState: serverStateStore,\r\n actionTimeStamp: Date.now() + (serverSync.debounce ?? 3000),\r\n status: \"waiting\",\r\n });\r\n }\r\n\r\n return payload;\r\n });\r\n };\r\n if (!getGlobalStore.getState().updaterState[thisKey]) {\r\n setUpdaterState(\r\n thisKey,\r\n createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n )\r\n );\r\n if (!getGlobalStore.getState().cogsStateStore[thisKey]) {\r\n setState(thisKey, stateObject);\r\n }\r\n if (!getGlobalStore.getState().initialStateGlobal[thisKey]) {\r\n updateInitialStateGlobal(thisKey, stateObject);\r\n }\r\n }\r\n\r\n const updaterFinal = useMemo(() => {\r\n // Create proxy with baseObject as target\r\n return createProxyHandler<TStateObject>(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n }, [thisKey]);\r\n\r\n return [getKeyState(thisKey), updaterFinal] as [\r\n TStateObject,\r\n StateObject<TStateObject>,\r\n ];\r\n}\r\n\r\nfunction createProxyHandler<T>(\r\n stateKey: string,\r\n effectiveSetState: EffectiveSetState<T>,\r\n componentId: string,\r\n sessionId?: string\r\n): StateObject<T> {\r\n // ADDED: Enhanced cache with versioning\r\n type CacheEntry = {\r\n proxy: any;\r\n stateVersion: number;\r\n };\r\n const shapeCache = new Map<string, CacheEntry>();\r\n let stateVersion = 0;\r\n\r\n // ADDED: Cache invalidation helper\r\n const invalidateCachePath = (path: string[]) => {\r\n const pathKey = path.join(\".\");\r\n for (const [key] of shapeCache) {\r\n if (key === pathKey || key.startsWith(pathKey + \".\")) {\r\n shapeCache.delete(key);\r\n }\r\n }\r\n stateVersion++;\r\n };\r\n\r\n const baseObj = {\r\n removeValidation: (obj?: { validationKey?: string }) => {\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n },\r\n\r\n revertToInitialState: (obj?: { validationKey?: string }) => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n if (init?.key) {\r\n removeValidationError(init?.key);\r\n }\r\n\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n\r\n // ADDED: Clear cache on revert\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newProxy = rebuildStateShape(initialState, []);\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n startTransition(() => {\r\n setUpdaterState(stateKey, newProxy);\r\n setState(stateKey, initialState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return initialState;\r\n },\r\n updateInitialState: (newState: T) => {\r\n // ADDED: Clear cache on initial state update\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newUpdaterState = createProxyHandler(\r\n stateKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n startTransition(() => {\r\n updateInitialStateGlobal(stateKey, newState);\r\n setUpdaterState(stateKey, newUpdaterState);\r\n setState(stateKey, newState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return {\r\n fetchId: (field: keyof T) => newUpdaterState.get()[field],\r\n };\r\n },\r\n _initialState: getGlobalStore.getState().initialStateGlobal[stateKey],\r\n _serverState: getGlobalStore.getState().serverState[stateKey],\r\n _isLoading: getGlobalStore.getState().isLoadingGlobal[stateKey],\r\n _isServerSynced: () => {\r\n const serverState = getGlobalStore.getState().serverState[stateKey];\r\n return Boolean(\r\n serverState && isDeepEqual(serverState, getKeyState(stateKey))\r\n );\r\n },\r\n };\r\n\r\n function rebuildStateShape(\r\n currentState: T,\r\n path: string[] = [],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ): any {\r\n const cacheKey = path.map(String).join(\".\");\r\n\r\n // MODIFIED: Cache check with version\r\n const cachedEntry = shapeCache.get(cacheKey);\r\n // if (cachedEntry?.stateVersion === stateVersion) {\r\n // return cachedEntry.proxy;\r\n // }\r\n type CallableStateObject<T> = {\r\n (): T;\r\n } & {\r\n [key: string]: any;\r\n };\r\n\r\n const baseFunction = function () {\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n } as unknown as CallableStateObject<T>;\r\n\r\n // Copy properties from baseObj to the function with type assertion\r\n Object.keys(baseObj).forEach((key) => {\r\n (baseFunction as any)[key] = (baseObj as any)[key];\r\n });\r\n\r\n const handler = {\r\n apply(target: any, thisArg: any, args: any[]) {\r\n console.log(\r\n `PROXY APPLY TRAP HIT: stateKey=${stateKey}, path=${path.join(\".\")}`\r\n ); // <--- ADD LOGGING\r\n console.trace(\"Apply trap stack trace\");\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n },\r\n\r\n get(target: any, prop: string) {\r\n if (\r\n prop !== \"then\" &&\r\n !prop.startsWith(\"$\") &&\r\n prop !== \"stateMapNoRender\"\r\n ) {\r\n const currentPath = path.join(\".\");\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Only add paths for non-root or specifically for get() at root\r\n if (path.length > 0 || prop === \"get\") {\r\n component.paths.add(currentPath);\r\n }\r\n } else {\r\n }\r\n }\r\n }\r\n if (prop === \"_status\") {\r\n // Get current state at this path (non-reactive version)\r\n const thisReactiveState = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n }\r\n if (prop === \"getStatus\") {\r\n return function () {\r\n // Get current state at this path (reactive version)\r\n const thisReactiveState = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n );\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n };\r\n }\r\n if (prop === \"removeStorage\") {\r\n return () => {\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n console.log(\"removing storage\", storageKey);\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n };\r\n }\r\n if (prop === \"showValidationErrors\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n const errors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key + \".\" + path.join(\".\"));\r\n\r\n return errors;\r\n };\r\n }\r\n if (Array.isArray(currentState)) {\r\n if (prop === \"getSelected\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n if (selectedIndex === undefined) return undefined;\r\n return rebuildStateShape(\r\n currentState[selectedIndex],\r\n [...path, selectedIndex.toString()],\r\n meta\r\n );\r\n };\r\n }\r\n if (prop === \"getSelectedIndex\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n\r\n return selectedIndex ?? -1;\r\n };\r\n }\r\n if (prop === \"stateSort\") {\r\n return (\r\n compareFn: (\r\n a: InferArrayElement<T>,\r\n b: InferArrayElement<T>\r\n ) => number\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n\r\n // Create a shallow copy with original indices\r\n const arrayCopy = currentArray.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n // Sort the copy using the provided compare function\r\n const sortedArray = [...arrayCopy].sort(compareFn);\r\n\r\n // ADDED: Clear cache for sort operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Return the sorted array with state objects\r\n return rebuildStateShape(sortedArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: sortedArray.map((item) =>\r\n parseInt(item.__origIndex as string)\r\n ),\r\n });\r\n };\r\n }\r\n if (prop === \"stateMap\" || prop === \"stateMapNoRender\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n if (prop !== \"stateMapNoRender\") {\r\n shapeCache.clear();\r\n stateVersion++;\r\n }\r\n\r\n return arrayToMap.map((val: any, index: number) => {\r\n const thisIndex =\r\n isFiltered && val.__origIndex ? val.__origIndex : index;\r\n const elementProxy = rebuildStateShape(\r\n val,\r\n [...path, thisIndex.toString()],\r\n meta\r\n );\r\n return callbackfn(\r\n val,\r\n elementProxy,\r\n index,\r\n currentState as any,\r\n rebuildStateShape(currentState as any, path, meta)\r\n );\r\n });\r\n };\r\n }\r\n if (prop === \"$stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n return createElement(SignalMapRenderer, {\r\n proxy: {\r\n _stateKey: stateKey,\r\n _path: path,\r\n _mapFn: callbackfn as any, // Pass the actual function, not string\r\n },\r\n\r\n rebuildStateShape,\r\n });\r\n };\r\n }\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n // ADDED: Clear shape cache for flattening operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any, index: number) => {\r\n return val[fieldName] ?? [];\r\n }\r\n );\r\n\r\n return rebuildStateShape(\r\n flattenedResults,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (\r\n thisKey: keyof InferArrayElement<T>,\r\n thisValue: InferArrayElement<T>[keyof InferArrayElement<T>]\r\n ) => {\r\n const foundIndex = currentState.findIndex(\r\n (obj: any) => obj[thisKey] === thisValue\r\n );\r\n if (foundIndex === -1) return undefined;\r\n const foundValue = currentState[foundIndex];\r\n const newPath = [...path, foundIndex.toString()];\r\n // console.log(\r\n // \"findWithfindWithfindWithfindWith\",\r\n // stateKey,\r\n // foundValue,\r\n // newPath,\r\n // );\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // ADDED: Clear cache for find operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n // Try returning without spread\r\n return rebuildStateShape(foundValue, newPath);\r\n };\r\n }\r\n\r\n if (prop === \"index\") {\r\n return (index: number) => {\r\n const indexValue = currentState[index];\r\n return rebuildStateShape(indexValue, [...path, index.toString()]);\r\n };\r\n }\r\n\r\n if (prop === \"insert\") {\r\n return (payload: UpdateArg<T>) => {\r\n // ADDED: Invalidate cache on insert\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, payload, path, stateKey);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n []\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"uniqueInsert\") {\r\n return (\r\n payload: UpdateArg<T>,\r\n fields?: (keyof InferArrayElement<T>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n const newValue = isFunction<T>(payload)\r\n ? payload(currentArray as any)\r\n : (payload as any);\r\n\r\n let matchedItem: any = null;\r\n const isUnique = !currentArray.some((item) => {\r\n if (fields) {\r\n const isMatch = fields.every((field) =>\r\n isDeepEqual(item[field], newValue[field])\r\n );\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n }\r\n const isMatch = isDeepEqual(item, newValue);\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n });\r\n\r\n if (isUnique) {\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, newValue, path, stateKey);\r\n } else if (onMatch && matchedItem) {\r\n const updatedItem = onMatch(matchedItem);\r\n const updatedArray = currentArray.map((item) =>\r\n isDeepEqual(item, matchedItem) ? updatedItem : item\r\n );\r\n invalidateCachePath(path);\r\n updateFn(effectiveSetState, updatedArray as any, path);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"cut\") {\r\n return (index: number, options?: { waitForSync?: boolean }) => {\r\n if (options?.waitForSync) return;\r\n // ADDED: Invalidate cache on cut\r\n invalidateCachePath(path);\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n };\r\n }\r\n if (prop === \"cutByValue\") {\r\n return (value: string | number | boolean) => {\r\n for (let index = 0; index < currentState.length; index++) {\r\n if (currentState[index] === value) {\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"toggleByValue\") {\r\n return (value: string | number | boolean) => {\r\n const index = currentState.findIndex((item) => item === value);\r\n if (index > -1) {\r\n // Value exists, so cut it\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n } else {\r\n // Value doesn't exist, so insert it\r\n pushFunc(effectiveSetState, value as any, path, stateKey);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"stateFilter\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const newVal = currentState.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n const validIndices: number[] = [];\r\n const filteredArray: Array<InferArrayElement<T>> = [];\r\n\r\n for (let i = 0; i < newVal.length; i++) {\r\n if (callbackfn(newVal[i], i)) {\r\n validIndices.push(i);\r\n filteredArray.push(newVal[i]);\r\n }\r\n }\r\n\r\n // ADDED: Clear cache for filter operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Always include validIndices, even if it's an empty array\r\n return rebuildStateShape(filteredArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: validIndices, // Always pass validIndices, even if empty\r\n });\r\n };\r\n }\r\n }\r\n const lastPathElement = path[path.length - 1];\r\n if (!isNaN(Number(lastPathElement))) {\r\n const parentPath = path.slice(0, -1);\r\n const parentValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n\r\n if (Array.isArray(parentValue) && prop === \"cut\") {\r\n return () =>\r\n cutFunc(\r\n effectiveSetState,\r\n parentPath,\r\n stateKey,\r\n Number(lastPathElement)\r\n );\r\n }\r\n }\r\n\r\n if (prop === \"get\") {\r\n return () => getGlobalStore.getState().getNestedState(stateKey, path);\r\n }\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$get\") {\r\n return () =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n });\r\n }\r\n if (prop === \"lastSynced\") {\r\n const syncKey = `${stateKey}:${path.join(\".\")}`;\r\n return getGlobalStore.getState().getSyncInfo(syncKey);\r\n }\r\n\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\r\n if (prop === \"_selected\") {\r\n const parentPath = path.slice(0, -1);\r\n const parentKey = parentPath.join(\".\");\r\n const parent = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n if (Array.isArray(parent)) {\r\n const currentIndex = Number(path[path.length - 1]);\r\n return (\r\n currentIndex ===\r\n getGlobalStore.getState().getSelectedIndex(stateKey, parentKey)\r\n );\r\n }\r\n return undefined;\r\n }\r\n if (prop === \"setSelected\") {\r\n return (value: boolean) => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n\r\n if (value) {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, thisIndex);\r\n } else {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, undefined);\r\n }\r\n\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n // Invalidate cache for this path\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"validateZodSchema\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n const addValidationError =\r\n getGlobalStore.getState().addValidationError;\r\n\r\n if (!init?.zodSchema) {\r\n throw new Error(\"Zod schema not found\");\r\n }\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n removeValidationError(init.key);\r\n const thisObject =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n\r\n try {\r\n // First clear any existing validation errors for this schema\r\n // This ensures we don't have stale errors\r\n const existingErrors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key);\r\n if (existingErrors && existingErrors.length > 0) {\r\n existingErrors.forEach(([errorPath]) => {\r\n if (errorPath && errorPath.startsWith(init.key!)) {\r\n removeValidationError(errorPath);\r\n }\r\n });\r\n }\r\n\r\n // Attempt to validate with Zod\r\n const result = init.zodSchema.safeParse(thisObject);\r\n\r\n if (!result.success) {\r\n // Process Zod errors and add them to the validation store\r\n const zodErrors = result.error.errors;\r\n\r\n zodErrors.forEach((error) => {\r\n const errorPath = error.path;\r\n const errorMessage = error.message;\r\n\r\n // Build the full path for the validation error\r\n // Format: validationKey.path.to.field\r\n const fullErrorPath = [init.key, ...errorPath].join(\".\");\r\n\r\n // Add the error to the store\r\n addValidationError(fullErrorPath, errorMessage);\r\n });\r\n\r\n notifyComponents(stateKey);\r\n\r\n return false;\r\n }\r\n\r\n return true;\r\n } catch (error) {\r\n console.error(\"Zod schema validation failed\", error);\r\n return false;\r\n }\r\n };\r\n }\r\n if (prop === \"_componentId\") return componentId;\r\n if (prop === \"getComponents\") {\r\n return () => getGlobalStore().stateComponents.get(stateKey);\r\n }\r\n if (prop === \"getAllFormRefs\") {\r\n return () => {\r\n return formRefStore.getState().getFormRefsByStateKey(stateKey);\r\n };\r\n }\r\n\r\n if (prop === \"_initialState\")\r\n return getGlobalStore.getState().initialStateGlobal[stateKey];\r\n if (prop === \"_serverState\")\r\n return getGlobalStore.getState().serverState[stateKey];\r\n if (prop === \"_isLoading\")\r\n return getGlobalStore.getState().isLoadingGlobal[stateKey];\r\n if (prop === \"revertToInitialState\")\r\n return baseObj.revertToInitialState;\r\n if (prop === \"updateInitialState\") return baseObj.updateInitialState;\r\n if (prop === \"removeValidation\") return baseObj.removeValidation;\r\n }\r\n if (prop === \"getFormRef\") {\r\n return () => {\r\n return formRefStore\r\n .getState()\r\n .getFormRef(stateKey + \".\" + path.join(\".\"));\r\n };\r\n }\r\n\r\n if (prop === \"validationWrapper\") {\r\n return ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => (\r\n <ValidationWrapper\r\n formOpts={\r\n hideMessage ? { validation: { message: \"\" } } : undefined\r\n }\r\n path={path}\r\n validationKey={\r\n getGlobalStore.getState().getInitialOptions(stateKey)\r\n ?.validation?.key || \"\"\r\n }\r\n stateKey={stateKey}\r\n validIndices={meta?.validIndices}\r\n >\r\n {children}\r\n </ValidationWrapper>\r\n );\r\n }\r\n\r\n if (prop === \"_stateKey\") return stateKey;\r\n if (prop === \"_path\") return path;\r\n if (prop === \"_isServerSynced\") return baseObj._isServerSynced;\r\n\r\n if (prop === \"update\") {\r\n return (payload: UpdateArg<T>, opts?: UpdateOpts<T>) => {\r\n // ADDED: Invalidate cache on update\r\n if (opts?.debounce) {\r\n debounce(() => {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }, opts.debounce);\r\n } else {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }\r\n invalidateCachePath(path);\r\n };\r\n }\r\n\r\n if (prop === \"formElement\") {\r\n return (child: FormControl<T>, formOpts?: FormOptsType) => {\r\n return (\r\n <FormControlComponent<T>\r\n setState={effectiveSetState}\r\n stateKey={stateKey}\r\n path={path}\r\n child={child}\r\n formOpts={formOpts}\r\n />\r\n );\r\n };\r\n }\r\n\r\n const nextPath = [...path, prop];\r\n const nextValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, nextPath);\r\n return rebuildStateShape(nextValue, nextPath, meta);\r\n },\r\n };\r\n\r\n const proxyInstance = new Proxy(baseFunction, handler);\r\n\r\n shapeCache.set(cacheKey, {\r\n proxy: proxyInstance,\r\n stateVersion: stateVersion,\r\n });\r\n\r\n return proxyInstance;\r\n }\r\n\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, [])\r\n );\r\n}\r\n\r\nexport function $cogsSignal(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n}) {\r\n return createElement(SignalRenderer, { proxy });\r\n}\r\n\r\nfunction SignalMapRenderer({\r\n proxy,\r\n\r\n rebuildStateShape,\r\n}: {\r\n proxy: {\r\n _stateKey: string;\r\n _path: string[];\r\n _mapFn: (\r\n value: any,\r\n setter: any,\r\n index: number,\r\n array: any[],\r\n arraySetter: any\r\n ) => ReactNode;\r\n };\r\n\r\n rebuildStateShape: (\r\n currentState: any,\r\n path: string[],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ) => any;\r\n}) {\r\n const value = getGlobalStore().getNestedState(proxy._stateKey, proxy._path);\r\n\r\n if (!Array.isArray(value)) {\r\n return null;\r\n }\r\n const arraySetter = rebuildStateShape(\r\n value,\r\n proxy._path\r\n ) as ArrayEndType<any>;\r\n // Use existing global state management\r\n return arraySetter.stateMapNoRender(\r\n (item, setter, index, value, arraysetter) => {\r\n // Execute map function in React context with existing state/proxies\r\n return proxy._mapFn(item, setter, index, value, arraysetter);\r\n }\r\n );\r\n}\r\nfunction SignalRenderer({\r\n proxy,\r\n}: {\r\n proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n };\r\n}) {\r\n const elementRef = useRef<HTMLSpanElement>(null);\r\n const signalId = `${proxy._stateKey}-${proxy._path.join(\".\")}`;\r\n\r\n useEffect(() => {\r\n const element = elementRef.current;\r\n if (!element || !element.parentElement) return;\r\n\r\n const parentElement = element.parentElement;\r\n const childNodes = Array.from(parentElement.childNodes);\r\n const position = childNodes.indexOf(element);\r\n\r\n let parentId = parentElement.getAttribute(\"data-parent-id\");\r\n if (!parentId) {\r\n parentId = `parent-${crypto.randomUUID()}`;\r\n parentElement.setAttribute(\"data-parent-id\", parentId);\r\n }\r\n\r\n const instanceId = `instance-${crypto.randomUUID()}`;\r\n const elementInfo = {\r\n instanceId,\r\n parentId,\r\n position,\r\n effect: proxy._effect,\r\n };\r\n\r\n getGlobalStore.getState().addSignalElement(signalId, elementInfo);\r\n\r\n // Get the raw value from the store\r\n const value = getGlobalStore\r\n .getState()\r\n .getNestedState(proxy._stateKey, proxy._path);\r\n\r\n let displayValue;\r\n if (proxy._effect) {\r\n try {\r\n displayValue = new Function(\r\n \"state\",\r\n `return (${proxy._effect})(state)`\r\n )(value);\r\n } catch (err) {\r\n console.error(\"Error evaluating effect function during mount:\", err);\r\n displayValue = value; // Fallback to raw value\r\n }\r\n } else {\r\n displayValue = value;\r\n }\r\n\r\n if (displayValue !== null && typeof displayValue === \"object\") {\r\n displayValue = JSON.stringify(displayValue);\r\n }\r\n\r\n const textNode = document.createTextNode(String(displayValue));\r\n element.replaceWith(textNode);\r\n }, [proxy._stateKey, proxy._path.join(\".\"), proxy._effect]);\r\n\r\n return createElement(\"span\", {\r\n ref: elementRef,\r\n style: { display: \"none\" },\r\n \"data-signal-id\": signalId,\r\n });\r\n}\r\nexport function $cogsSignalStore(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n}) {\r\n const value = useSyncExternalStore(\r\n (notify) => {\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(proxy._stateKey) || {\r\n components: new Map(),\r\n };\r\n stateEntry.components.set(proxy._stateKey, {\r\n forceUpdate: notify,\r\n paths: new Set([proxy._path.join(\".\")]),\r\n });\r\n return () => stateEntry.components.delete(proxy._stateKey);\r\n },\r\n () => getGlobalStore.getState().getNestedState(proxy._stateKey, proxy._path)\r\n );\r\n return createElement(\"text\", {}, String(value));\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","loadFromLocalStorage","localStorageKey","storedData","error","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","isFunction","data","storageKey","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","startTransition","notifyComponents","stateEntry","component","update","notifyComponent","fullComponentId","stateObject","serverSync","localStorage","middleware","reactiveDeps","reactiveType","syncUpdate","dependencies","reactiveForce","forceUpdate","useCogsConfig","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","localData","localkey","useLayoutEffect","depsKey","newStateOrFunction","path","updateObj","validationKey","pathKey","prevValue","payload","signalId","isArrayOperation","elements","arrayPath","arrayValue","getNestedValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","k","v","length","newKey","oldValue","pathToCheck","shouldUpdate","reactiveTypes","depsResult","isDeepEqual","newUpdate","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","field","serverState","currentState","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","currentPath","thisReactiveState","initialStateAtPath","selectedIndex","compareFn","sortedArray","i","item","callbackfn","isFiltered","p","arrayToMap","val","index","thisIndex","elementProxy","createElement","SignalMapRenderer","fieldName","flattenedResults","thisValue","foundIndex","foundValue","newPath","indexValue","pushFunc","fields","onMatch","currentArray","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","newVal","validIndices","filteredArray","lastPathElement","parentPath","parentValue","fn","$cogsSignal","parentKey","nested","thisObject","existingErrors","errorPath","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","jsx","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","setter","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify"],"mappings":";;;;;;;;;AAwYA,SAASA,GAAmBC,GAAkBC,GAA8B;AACpEC,QAAAA,IAAoBC,EAAe,SAAA,EAAW,mBAC9CC,IACJD,EAAe,SAAA,EAAW,wBAEtBE,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC;AAEjE,EAAAI,EAAuBJ,GAAoB;AAAA,IACzC,GAAGK;AAAA,IACH,GAAGJ;AAAA,EAAA,CACJ;AACH;AAEA,SAASK,GAA0B;AAAA,EACjC,UAAAN;AAAA,EACA,SAAAO;AAAA,EACA,oBAAAC;AACF,GAIG;AACD,QAAMH,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC,GAC3DS,IAA0BD,EAAmBR,CAAkB,KAAK,CAAC,GACrEI,IACJD,EAAe,SAAA,EAAW,wBAGtBO,IAAgB;AAAA,IACpB,GAAGD;AAAA;AAAA,IACH,GAAGJ;AAAA;AAAA,IACH,GAAGE;AAAA;AAAA,EACL;AAIA,MAAII,IAAY;AAChB,MAAIJ;AACF,eAAWK,KAAOL;AAChB,MAAKG,EAAc,eAAeE,CAAG,IAMjCA,KAAO,kBACPL,EAAQK,CAAG,KACXF,EAAcE,CAAG,EAAE,QAAQL,EAAQK,CAAG,GAAG,QAE7BD,IAAA,IACED,EAAAE,CAAG,IAAIL,EAAQK,CAAG,MAVtBD,IAAA,IAEED,EAAAE,CAAG,IAAIL,EAAQK,CAA2B;AAa9D,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AO;AAAA,UACxB9B,CAAK;AAAA,eACAsC,GAAK;AACJ,gBAAA,MAAM,kDAAkDA,CAAG,GACpDrH,IAAA+E;AAAA,MAAA;AAAA;AAGF,MAAA/E,IAAA+E;AAGjB,IAAI/E,MAAiB,QAAQ,OAAOA,KAAiB,aACpCA,IAAA,KAAK,UAAUA,CAAY;AAG5C,UAAMsH,IAAW,SAAS,eAAe,OAAOtH,CAAY,CAAC;AAC7D,IAAAkH,EAAQ,YAAYI,CAAQ;AAAA,EAAA,GAC3B,CAACT,EAAM,WAAWA,EAAM,MAAM,KAAK,GAAG,GAAGA,EAAM,OAAO,CAAC,GAEnDjD,EAAc,QAAQ;AAAA,IAC3B,KAAKqD;AAAA,IACL,OAAO,EAAE,SAAS,OAAO;AAAA,IACzB,kBAAkB9H;AAAA,EAAA,CACnB;AACH;AACO,SAASoI,GAAiBV,GAG9B;AACD,QAAM9B,IAAQyC;AAAA,IACZ,CAACC,MAAW;AACJ,YAAA1K,IAAaxD,EAChB,SAAS,EACT,gBAAgB,IAAIsN,EAAM,SAAS,KAAK;AAAA,QACzC,gCAAgB,IAAI;AAAA,MACtB;AACW,aAAA9J,EAAA,WAAW,IAAI8J,EAAM,WAAW;AAAA,QACzC,aAAaY;AAAA,QACb,2BAAW,IAAI,CAACZ,EAAM,MAAM,KAAK,GAAG,CAAC,CAAC;AAAA,MAAA,CACvC,GACM,MAAM9J,EAAW,WAAW,OAAO8J,EAAM,SAAS;AAAA,IAC3D;AAAA,IACA,MAAMtN,EAAe,WAAW,eAAesN,EAAM,WAAWA,EAAM,KAAK;AAAA,EAC7E;AACA,SAAOjD,EAAc,QAAQ,CAAI,GAAA,OAAOmB,CAAK,CAAC;AAChD;"}
|
|
1
|
+
{"version":3,"file":"CogsState.jsx","sources":["../src/CogsState.tsx"],"sourcesContent":["\"use client\";\r\nimport {\r\n createElement,\r\n startTransition,\r\n useEffect,\r\n useLayoutEffect,\r\n useMemo,\r\n useRef,\r\n useState,\r\n useSyncExternalStore,\r\n type ReactNode,\r\n} from \"react\";\r\n\r\nimport {\r\n debounce,\r\n getDifferences,\r\n getNestedValue,\r\n isFunction,\r\n type GenericObject,\r\n} from \"./utility.js\";\r\nimport {\r\n cutFunc,\r\n FormControlComponent,\r\n pushFunc,\r\n updateFn,\r\n ValidationWrapper,\r\n} from \"./Functions.js\";\r\nimport { isDeepEqual, transformStateFunc } from \"./utility.js\";\r\nimport type { UseMutationResult } from \"@tanstack/react-query\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { ZodArray, ZodObject, type ZodRawShape } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\n\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\nexport type ServerSyncStatus = {\r\n isFresh: boolean;\r\n isFreshTime: number;\r\n isStale: boolean;\r\n isStaleTime: number;\r\n isSyncing: boolean;\r\n isSyncingTime: number;\r\n};\r\n\r\nexport type SyncInfo = {\r\n timeStamp: number;\r\n userId: number;\r\n};\r\n\r\nexport type FormElementParams<T> = {\r\n get: () => T;\r\n\r\n set: UpdateType<T>;\r\n syncStatus: (SyncInfo & { date: Date }) | null;\r\n path: string[];\r\n validationErrors: () => string[];\r\n addValidationError: (message?: string) => void;\r\n\r\n inputProps: {\r\n ref?: React.RefObject<any>;\r\n value?: T extends boolean ? never : T;\r\n onChange?: (\r\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\r\n ) => void;\r\n onBlur?: () => void;\r\n };\r\n};\r\n\r\nexport type StateKeys = string;\r\n\r\ntype findWithFuncType<U> = (\r\n thisKey: keyof U,\r\n thisValue: U[keyof U]\r\n) => EndType<U> & StateObject<U>;\r\nexport type PushArgs<U> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => void;\r\n\r\ntype CutFunctionType = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => void;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\n\r\nexport type ArrayEndType<TShape extends unknown> = {\r\n findWith: findWithFuncType<InferArrayElement<TShape>>;\r\n index: (index: number) => StateObject<InferArrayElement<TShape>> & {\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>>;\r\n cut: CutFunctionType;\r\n cutByValue: (value: string | number | boolean) => void;\r\n toggleByValue: (value: string | number | boolean) => void;\r\n stateSort: (\r\n compareFn: (\r\n a: InferArrayElement<TShape>,\r\n b: InferArrayElement<TShape>\r\n ) => number\r\n ) => ArrayEndType<TShape>;\r\n\r\n stateMapNoRender: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n $stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateFlattenOn: <K extends keyof InferArrayElement<TShape>>(\r\n field: K\r\n ) => StateObject<InferArrayElement<InferArrayElement<TShape>[K]>[]>;\r\n uniqueInsert: (\r\n payload: UpdateArg<InferArrayElement<TShape>>,\r\n fields?: (keyof InferArrayElement<TShape>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => void;\r\n stateFilter: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => void\r\n ) => ArrayEndType<TShape>;\r\n getSelected: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n getSelectedIndex: () => number;\r\n} & EndType<TShape> & {\r\n [K in keyof (any[] extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<Prettify<T>>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\nexport type FormOptsType = {\r\n key?: string;\r\n validation?: {\r\n hideMessage?: boolean;\r\n message?: string;\r\n stretch?: boolean;\r\n props?: GenericObject;\r\n disable?: boolean;\r\n };\r\n formElements?: boolean;\r\n debounceTime?: number;\r\n stateServerDifferences?: string[][];\r\n};\r\n\r\nexport type FormControl<T> = (obj: FormElementParams<T>) => JSX.Element;\r\n\r\nexport type UpdateArg<S> = S | ((prevState: S) => S);\r\nexport type UpdateOpts<T> = {\r\n afterUpdate?: (state: T) => void;\r\n debounce?: number;\r\n};\r\nexport type ObjectEndType<T> = EndType<T> & {\r\n [K in keyof T]-?: ObjectEndType<T[K]>;\r\n} & {\r\n stateObject: (callbackfn: (value: T, setter: StateObject<T>) => void) => any;\r\n delete: () => void;\r\n};\r\ntype EffectFunction<T, R> = (state: T) => R;\r\nexport type EndType<T, IsArrayElement = false> = {\r\n update: UpdateType<T>;\r\n _path: string[];\r\n _stateKey: string;\r\n formElement: (control: FormControl<T>, opts?: FormOptsType) => JSX.Element;\r\n get: () => T;\r\n $get: () => T;\r\n $derive: <R>(fn: EffectFunction<T, R>) => R;\r\n _status: \"fresh\" | \"stale\" | \"synced\";\r\n getStatus: () => \"fresh\" | \"stale\";\r\n showValidationErrors: () => string[];\r\n setValidation: (ctx: string) => void;\r\n removeValidation: (ctx: string) => void;\r\n ignoreFields: (fields: string[]) => StateObject<T>;\r\n _selected: boolean;\r\n setSelected: (value: boolean) => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n validationWrapper: ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => JSX.Element;\r\n lastSynced?: SyncInfo;\r\n} & (IsArrayElement extends true ? { cut: () => void } : {}) & {\r\n [K in keyof (any extends infer T ? T : never)]: never;\r\n };\r\n\r\nexport type StateObject<T> = (T extends any[]\r\n ? ArrayEndType<T>\r\n : T extends Record<string, unknown> | object\r\n ? { [K in keyof T]-?: StateObject<T[K]> } & ObjectEndType<T>\r\n : T extends string | number | boolean | null\r\n ? T\r\n : never) &\r\n EndType<T, true> & {\r\n getAllFormRefs: () => Map<string, React.RefObject<any>>;\r\n _componentId: string | null;\r\n getComponents: () => ComponentsType;\r\n validateZodSchema: () => void;\r\n _initialState: T;\r\n updateInitialState: (newState: T | null) => {\r\n fetchId: (field: keyof T) => string | number;\r\n };\r\n _isLoading: boolean;\r\n _serverState: T;\r\n revertToInitialState: (obj?: { validationKey?: string }) => T;\r\n middleware: (\r\n middles: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void\r\n ) => void;\r\n _isServerSynced: () => boolean;\r\n getLocalStorage: (key: string) => LocalStorageData<T> | null;\r\n };\r\n\r\nexport type CogsUpdate<T extends unknown> = UpdateType<T>;\r\n\r\nexport type EffectiveSetState<TStateObject> = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"update\" | \"insert\" | \"cut\" },\r\n validationKey?: string,\r\n opts?: UpdateOpts<TStateObject>\r\n) => void;\r\n\r\nexport type UpdateTypeDetail = {\r\n timeStamp: number;\r\n stateKey: string;\r\n updateType: \"update\" | \"insert\" | \"cut\";\r\n path: string[];\r\n status: \"new\" | \"sent\" | \"synced\";\r\n oldValue: any;\r\n newValue: any;\r\n userId?: number;\r\n};\r\n\r\nexport type ActionsType<T> = {\r\n type: \"onChange\";\r\n action: ({ state, actionType }: { state: T; actionType: string }) => void;\r\n debounce?: number;\r\n}[];\r\n\r\ntype ArrayToObject<T extends string[]> = Record<T[number], string>;\r\ntype CookieType<T> = {\r\n timeStamp: number;\r\n value: T;\r\n cookieName: string;\r\n OnUnMountCookie?: Boolean;\r\n};\r\nexport type CogsCookiesType<T extends string[] = string[]> = CookieType<\r\n ArrayToObject<T>\r\n>;\r\nexport type ReactivityType = \"none\" | \"component\" | \"deps\" | \"all\";\r\n\r\ntype ValidationOptionsType = {\r\n key?: string;\r\n zodSchema?: ZodObject<ZodRawShape> | ZodArray<ZodObject<ZodRawShape>>;\r\n onBlur?: boolean;\r\n};\r\n\r\nexport type OptionsType<T extends unknown = unknown> = {\r\n log?: boolean;\r\n componentId?: string;\r\n serverSync?: ServerSyncType<T>;\r\n validation?: ValidationOptionsType;\r\n enableServerState?: boolean;\r\n middleware?: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void;\r\n\r\n modifyState?: (state: T) => T;\r\n localStorage?: { key: string | ((state: T) => string) };\r\n formElements?: FormsElementsType;\r\n enabledSync?: (state: T) => boolean;\r\n reactiveDeps?: (state: T) => any[] | true;\r\n reactiveType?: ReactivityType[] | ReactivityType;\r\n syncUpdate?: Partial<UpdateTypeDetail>;\r\n\r\n initialState?: T;\r\n dependencies?: any[]; // Just like useEffect dependencies\r\n};\r\nexport type ServerSyncType<T> = {\r\n testKey?: string;\r\n syncKey: (({ state }: { state: T }) => string) | string;\r\n syncFunction: ({ state }: { state: T }) => void;\r\n debounce?: number;\r\n mutation: UseMutationResult<any, unknown, any, unknown>;\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\n\r\nfunction setOptions<StateKey, Opt>({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n}: {\r\n stateKey: StateKey;\r\n options?: OptionsType<any>;\r\n initialOptionsPart: Record<string, any>;\r\n}) {\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n const initialOptionsPartState = initialOptionsPart[stateKey as string] || {};\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n // This is the key fix - merge in the correct order\r\n const mergedOptions = {\r\n ...initialOptionsPartState, // Options from createCogsState\r\n ...initialOptions, // Currently stored options\r\n ...options, // New options passed to useCogsState\r\n };\r\n\r\n // Set the merged options\r\n\r\n let needToAdd = false;\r\n if (options) {\r\n for (const key in options) {\r\n if (!mergedOptions.hasOwnProperty(key)) {\r\n needToAdd = true;\r\n\r\n mergedOptions[key] = options[key as keyof typeof options];\r\n } else {\r\n if (\r\n key == \"localStorage\" &&\r\n options[key] &&\r\n mergedOptions[key].key !== options[key]?.key\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n if (needToAdd) {\r\n setInitialStateOptions(stateKey as string, mergedOptions);\r\n }\r\n}\r\nexport function addStateOptions<T extends unknown>(\r\n initialState: T,\r\n { formElements, validation }: OptionsType<T>\r\n) {\r\n return { initialState: initialState, formElements, validation } as T;\r\n}\r\n\r\nexport const createCogsState = <State extends Record<string, unknown>>(\r\n initialState: State,\r\n opt?: { formElements?: FormsElementsType; validation?: ValidationOptionsType }\r\n) => {\r\n let newInitialState = initialState;\r\n\r\n // Extract state parts and options using transformStateFunc\r\n const [statePart, initialOptionsPart] =\r\n transformStateFunc<State>(newInitialState);\r\n\r\n // Apply global formElements as defaults to each state key's options\r\n if (opt?.formElements || opt?.validation) {\r\n Object.keys(initialOptionsPart).forEach((key) => {\r\n // Get the existing options for this state key\r\n initialOptionsPart[key] = initialOptionsPart[key] || {};\r\n\r\n initialOptionsPart[key].formElements = {\r\n ...opt.formElements, // Global defaults first\r\n ...opt?.validation,\r\n ...(initialOptionsPart[key].formElements || {}), // State-specific overrides\r\n };\r\n const existingOptions = getInitialOptions(key);\r\n if (!existingOptions) {\r\n getGlobalStore\r\n .getState()\r\n .setInitialStateOptions(key, initialOptionsPart[key]);\r\n }\r\n });\r\n }\r\n\r\n getGlobalStore.getState().setInitialStates(statePart);\r\n type StateKeys = keyof typeof statePart;\r\n\r\n const useCogsState = <StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options?: OptionsType<(typeof statePart)[StateKey]>\r\n ) => {\r\n const [componentId] = useState(options?.componentId ?? uuidv4());\r\n setOptions({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n });\r\n\r\n const thiState =\r\n getGlobalStore.getState().cogsStateStore[stateKey as string] ||\r\n statePart[stateKey as string];\r\n const partialState = options?.modifyState\r\n ? options.modifyState(thiState)\r\n : thiState;\r\n\r\n const [state, updater] = useCogsStateFn<(typeof statePart)[StateKey]>(\r\n partialState,\r\n {\r\n stateKey: stateKey as string,\r\n syncUpdate: options?.syncUpdate,\r\n componentId,\r\n localStorage: options?.localStorage,\r\n middleware: options?.middleware,\r\n enabledSync: options?.enabledSync,\r\n reactiveType: options?.reactiveType,\r\n reactiveDeps: options?.reactiveDeps,\r\n initialState: options?.initialState,\r\n dependencies: options?.dependencies,\r\n }\r\n );\r\n\r\n return updater;\r\n };\r\n\r\n function setCogsOptions<StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options: OptionsType<(typeof statePart)[StateKey]>\r\n ) {\r\n setOptions({ stateKey, options, initialOptionsPart });\r\n }\r\n\r\n return { useCogsState, setCogsOptions };\r\n};\r\n\r\nconst {\r\n setUpdaterState,\r\n setState,\r\n getInitialOptions,\r\n getKeyState,\r\n getValidationErrors,\r\n setStateLog,\r\n updateInitialStateGlobal,\r\n addValidationError,\r\n removeValidationError,\r\n setServerSyncActions,\r\n} = getGlobalStore.getState();\r\n\r\nconst loadFromLocalStorage = (localStorageKey: string) => {\r\n if (!localStorageKey) return null;\r\n\r\n try {\r\n const storedData = window.localStorage.getItem(localStorageKey);\r\n if (!storedData) return null;\r\n\r\n const parsedData = JSON.parse(storedData);\r\n\r\n return parsedData;\r\n } catch (error) {\r\n console.error(\"Error loading from localStorage:\", error);\r\n return null;\r\n }\r\n};\r\n\r\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string\r\n) => {\r\n if (currentInitialOptions?.log) {\r\n console.log(\r\n \"saving to localstorage\",\r\n thisKey,\r\n currentInitialOptions.localStorage?.key,\r\n sessionId\r\n );\r\n }\r\n const key = isFunction(currentInitialOptions?.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions?.localStorage?.key;\r\n if (key && sessionId) {\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer:\r\n getGlobalStore.getState().serverSyncLog[thisKey]?.[0]?.timeStamp,\r\n baseServerState: getGlobalStore.getState().serverState[thisKey],\r\n };\r\n\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n window.localStorage.setItem(storageKey, JSON.stringify(data));\r\n }\r\n};\r\n\r\ntype LocalStorageData<T> = {\r\n state: T;\r\n lastUpdated: number;\r\n lastSyncedWithServer?: number;\r\n baseServerState?: T; // Add this to track what server state our changes are based on\r\n};\r\n\r\nconst updateGlobalState = (\r\n thisKey: string,\r\n initialState: any,\r\n newState: any,\r\n effectiveSetState: EffectiveSetState<any>,\r\n componentId: string,\r\n sessionId?: string\r\n) => {\r\n // Update all global state at once\r\n const updates = {\r\n initialState: initialState,\r\n updaterState: createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n ),\r\n state: newState,\r\n };\r\n\r\n startTransition(() => {\r\n updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\r\n });\r\n};\r\n\r\nconst notifyComponents = (thisKey: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n if (!stateEntry) return;\r\n\r\n // Batch component updates\r\n const updates = new Set<() => void>();\r\n stateEntry.components.forEach((component) => {\r\n updates.add(() => component.forceUpdate());\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n startTransition(() => {\r\n updates.forEach((update) => update());\r\n });\r\n });\r\n};\r\n\r\nexport const notifyComponent = (stateKey: string, componentId: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Force an update to ensure the current value is saved\r\n\r\n component.forceUpdate();\r\n }\r\n }\r\n};\r\n\r\nexport function useCogsStateFn<TStateObject extends unknown>(\r\n stateObject: TStateObject,\r\n {\r\n stateKey,\r\n serverSync,\r\n localStorage,\r\n formElements,\r\n middleware,\r\n reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n } & OptionsType<TStateObject> = {}\r\n) {\r\n const [reactiveForce, forceUpdate] = useState({}); //this is the key to reactivity\r\n const { sessionId } = useCogsConfig();\r\n\r\n let noStateKey = stateKey ? false : true;\r\n const [thisKey] = useState(stateKey ?? uuidv4());\r\n const stateLog = getGlobalStore.getState().stateLog[thisKey];\r\n const componentUpdatesRef = useRef(new Set<string>());\r\n const componentIdRef = useRef(componentId ?? uuidv4());\r\n const latestInitialOptionsRef = useRef<any>(null);\r\n latestInitialOptionsRef.current = getInitialOptions(thisKey as string);\r\n\r\n useEffect(() => {\r\n if (syncUpdate && syncUpdate.stateKey === thisKey && syncUpdate.path?.[0]) {\r\n // Update the actual state value\r\n setState(thisKey, (prevState: any) => ({\r\n ...prevState,\r\n [syncUpdate.path![0]!]: syncUpdate.newValue,\r\n }));\r\n\r\n // Create combined key and update sync info\r\n const syncKey = `${syncUpdate.stateKey}:${syncUpdate.path.join(\".\")}`;\r\n getGlobalStore.getState().setSyncInfo(syncKey, {\r\n timeStamp: syncUpdate.timeStamp!,\r\n userId: syncUpdate.userId!,\r\n });\r\n }\r\n }, [syncUpdate]);\r\n\r\n useEffect(() => {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n const options = latestInitialOptionsRef.current;\r\n let localData = null;\r\n if (options?.log) {\r\n console.log(\"newoptions\", options);\r\n }\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options?.localStorage?.key(initialState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(\r\n sessionId + \"-\" + thisKey + \"-\" + localkey\r\n );\r\n }\r\n\r\n let newState = null;\r\n if (initialState) {\r\n newState = initialState;\r\n\r\n if (localData) {\r\n if (localData.lastUpdated > (localData.lastSyncedWithServer || 0)) {\r\n newState = localData.state;\r\n }\r\n }\r\n updateGlobalState(\r\n thisKey,\r\n initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n\r\n notifyComponents(thisKey);\r\n forceUpdate({});\r\n }\r\n }, [initialState, ...(dependencies || [])]);\r\n\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initialState,\r\n localStorage,\r\n middleware,\r\n });\r\n }\r\n\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(thisKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(depsKey, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set(),\r\n deps: [],\r\n depsFunction: reactiveDeps || undefined,\r\n reactiveType: reactiveType ?? [\"component\", \"deps\"],\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(thisKey, stateEntry);\r\n //need to force update to create the stateUpdates references\r\n forceUpdate({});\r\n return () => {\r\n const depsKey = `${thisKey}////${componentIdRef.current}`;\r\n\r\n if (stateEntry) {\r\n stateEntry.components.delete(depsKey);\r\n if (stateEntry.components.size === 0) {\r\n getGlobalStore.getState().stateComponents.delete(thisKey);\r\n }\r\n }\r\n };\r\n }, []);\r\n\r\n const effectiveSetState = (\r\n newStateOrFunction:\r\n | TStateObject\r\n | ((prevState: TStateObject) => TStateObject),\r\n path: string[],\r\n updateObj: { updateType: \"insert\" | \"cut\" | \"update\" },\r\n validationKey?: string\r\n ) => {\r\n if (Array.isArray(path)) {\r\n const pathKey = `${thisKey}-${path.join(\".\")}`;\r\n componentUpdatesRef.current.add(pathKey);\r\n }\r\n setState(thisKey, (prevValue: TStateObject) => {\r\n const payload = isFunction<TStateObject>(newStateOrFunction)\r\n ? newStateOrFunction(prevValue as TStateObject)\r\n : newStateOrFunction;\r\n\r\n const signalId = `${thisKey}-${path.join(\".\")}`;\r\n if (signalId) {\r\n let isArrayOperation = false;\r\n let elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(signalId);\r\n\r\n if (\r\n (!elements || elements.size === 0) &&\r\n (updateObj.updateType === \"insert\" || updateObj.updateType === \"cut\")\r\n ) {\r\n // Remove last segment (index) from path\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n // If it's an array, use that path for signal\r\n if (Array.isArray(arrayValue)) {\r\n isArrayOperation = true;\r\n const arraySignalId = `${thisKey}-${arrayPath.join(\".\")}`;\r\n elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(arraySignalId);\r\n }\r\n }\r\n\r\n if (elements) {\r\n const newValue = isArrayOperation\r\n ? getNestedValue(payload, path.slice(0, -1))\r\n : getNestedValue(payload, path);\r\n elements.forEach(({ parentId, position, effect }) => {\r\n const parent = document.querySelector(\r\n `[data-parent-id=\"${parentId}\"]`\r\n );\r\n if (parent) {\r\n const childNodes = Array.from(parent.childNodes);\r\n if (childNodes[position]) {\r\n const displayValue = effect\r\n ? new Function(\"state\", `return (${effect})(state)`)(newValue)\r\n : newValue;\r\n childNodes[position].textContent = String(displayValue);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n if (\r\n updateObj.updateType === \"update\" &&\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validationKey) +\r\n \".\" +\r\n path.join(\".\")\r\n );\r\n }\r\n const arrayWithoutIndex = path.slice(0, path.length - 1);\r\n if (\r\n updateObj.updateType === \"cut\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validationKey\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validationKey +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n\r\n //TODO this is untested its supposed to cahnge teh validation errors alreaady stored when a new entry is push\r\n\r\n getValidation.filter(([k, v]) => {\r\n let length = k?.split(\".\").length;\r\n\r\n if (\r\n k == arrayWithoutIndex.join(\".\") &&\r\n length == arrayWithoutIndex.length - 1\r\n ) {\r\n // console.log(length, pathWithoutIndex.length);\r\n let newKey = k + \".\" + arrayWithoutIndex;\r\n removeValidationError(k!);\r\n addValidationError(newKey, v!);\r\n }\r\n });\r\n }\r\n\r\n const oldValue = getNestedValue(prevValue, path);\r\n const newValue = getNestedValue(payload, path);\r\n const pathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : [...path].slice(0, -1).join(\".\");\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n\r\n if (stateEntry) {\r\n for (const [key, component] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes.includes(\"none\")) {\r\n continue;\r\n }\r\n\r\n // Force update if \"all\" is specified\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n\r\n continue;\r\n }\r\n\r\n // Check component-level path reactivity\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths &&\r\n (component.paths.has(pathToCheck) || component.paths.has(\"\"))\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n\r\n // Check dependency-based reactivity\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) {\r\n shouldUpdate = true;\r\n }\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n const timeStamp = Date.now();\r\n\r\n const newUpdate = {\r\n timeStamp,\r\n stateKey: thisKey,\r\n path,\r\n updateType: updateObj.updateType,\r\n status: \"new\" as const,\r\n oldValue,\r\n newValue,\r\n } satisfies UpdateTypeDetail;\r\n\r\n setStateLog(thisKey, (prevLogs) => {\r\n const logs = [...(prevLogs ?? []), newUpdate];\r\n\r\n // Aggregate the updates by stateKey and path\r\n const aggregatedLogs = logs.reduce((acc, log) => {\r\n const uniqueKey = `${log.stateKey}:${JSON.stringify(log.path)}`;\r\n const existing = acc.get(uniqueKey);\r\n\r\n if (existing) {\r\n // Update the existing entry with the most recent details\r\n existing.timeStamp = Math.max(existing.timeStamp, log.timeStamp);\r\n existing.newValue = log.newValue; // Overwrite with the latest value\r\n existing.oldValue = existing.oldValue ?? log.oldValue; // Retain the initial oldValue\r\n existing.updateType = log.updateType; // Update to the most recent type\r\n } else {\r\n // Add the log if no existing match is found\r\n acc.set(uniqueKey, { ...(log as any) });\r\n }\r\n\r\n return acc;\r\n }, new Map<string, typeof newUpdate>());\r\n\r\n // Convert the aggregated map back to an array\r\n return Array.from(aggregatedLogs.values());\r\n });\r\n\r\n saveToLocalStorage(\r\n payload,\r\n thisKey,\r\n latestInitialOptionsRef.current,\r\n sessionId\r\n );\r\n\r\n if (middleware) {\r\n middleware({\r\n updateLog: stateLog,\r\n update: newUpdate,\r\n });\r\n }\r\n if (latestInitialOptionsRef.current?.serverSync) {\r\n const serverStateStore = getGlobalStore.getState().serverState[thisKey];\r\n const serverSync = latestInitialOptionsRef.current?.serverSync;\r\n setServerSyncActions(thisKey, {\r\n syncKey:\r\n typeof serverSync.syncKey == \"string\"\r\n ? serverSync.syncKey\r\n : serverSync.syncKey({ state: payload }),\r\n rollBackState: serverStateStore,\r\n actionTimeStamp: Date.now() + (serverSync.debounce ?? 3000),\r\n status: \"waiting\",\r\n });\r\n }\r\n\r\n return payload;\r\n });\r\n };\r\n if (!getGlobalStore.getState().updaterState[thisKey]) {\r\n setUpdaterState(\r\n thisKey,\r\n createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n )\r\n );\r\n if (!getGlobalStore.getState().cogsStateStore[thisKey]) {\r\n setState(thisKey, stateObject);\r\n }\r\n if (!getGlobalStore.getState().initialStateGlobal[thisKey]) {\r\n updateInitialStateGlobal(thisKey, stateObject);\r\n }\r\n }\r\n\r\n const updaterFinal = useMemo(() => {\r\n // Create proxy with baseObject as target\r\n return createProxyHandler<TStateObject>(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n }, [thisKey]);\r\n\r\n return [getKeyState(thisKey), updaterFinal] as [\r\n TStateObject,\r\n StateObject<TStateObject>,\r\n ];\r\n}\r\n\r\nfunction createProxyHandler<T>(\r\n stateKey: string,\r\n effectiveSetState: EffectiveSetState<T>,\r\n componentId: string,\r\n sessionId?: string\r\n): StateObject<T> {\r\n // ADDED: Enhanced cache with versioning\r\n type CacheEntry = {\r\n proxy: any;\r\n stateVersion: number;\r\n };\r\n const shapeCache = new Map<string, CacheEntry>();\r\n let stateVersion = 0;\r\n\r\n // ADDED: Cache invalidation helper\r\n const invalidateCachePath = (path: string[]) => {\r\n const pathKey = path.join(\".\");\r\n for (const [key] of shapeCache) {\r\n if (key === pathKey || key.startsWith(pathKey + \".\")) {\r\n shapeCache.delete(key);\r\n }\r\n }\r\n stateVersion++;\r\n };\r\n\r\n const baseObj = {\r\n removeValidation: (obj?: { validationKey?: string }) => {\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n },\r\n\r\n revertToInitialState: (obj?: { validationKey?: string }) => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n if (init?.key) {\r\n removeValidationError(init?.key);\r\n }\r\n\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n\r\n // ADDED: Clear cache on revert\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newProxy = rebuildStateShape(initialState, []);\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n startTransition(() => {\r\n setUpdaterState(stateKey, newProxy);\r\n setState(stateKey, initialState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return initialState;\r\n },\r\n updateInitialState: (newState: T) => {\r\n // ADDED: Clear cache on initial state update\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newUpdaterState = createProxyHandler(\r\n stateKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n startTransition(() => {\r\n updateInitialStateGlobal(stateKey, newState);\r\n setUpdaterState(stateKey, newUpdaterState);\r\n setState(stateKey, newState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return {\r\n fetchId: (field: keyof T) => newUpdaterState.get()[field],\r\n };\r\n },\r\n _initialState: getGlobalStore.getState().initialStateGlobal[stateKey],\r\n _serverState: getGlobalStore.getState().serverState[stateKey],\r\n _isLoading: getGlobalStore.getState().isLoadingGlobal[stateKey],\r\n _isServerSynced: () => {\r\n const serverState = getGlobalStore.getState().serverState[stateKey];\r\n return Boolean(\r\n serverState && isDeepEqual(serverState, getKeyState(stateKey))\r\n );\r\n },\r\n };\r\n\r\n function rebuildStateShape(\r\n currentState: T,\r\n path: string[] = [],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ): any {\r\n const cacheKey = path.map(String).join(\".\");\r\n\r\n // MODIFIED: Cache check with version\r\n const cachedEntry = shapeCache.get(cacheKey);\r\n // if (cachedEntry?.stateVersion === stateVersion) {\r\n // return cachedEntry.proxy;\r\n // }\r\n type CallableStateObject<T> = {\r\n (): T;\r\n } & {\r\n [key: string]: any;\r\n };\r\n\r\n const baseFunction = function () {\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n } as unknown as CallableStateObject<T>;\r\n\r\n // Copy properties from baseObj to the function with type assertion\r\n Object.keys(baseObj).forEach((key) => {\r\n (baseFunction as any)[key] = (baseObj as any)[key];\r\n });\r\n\r\n const handler = {\r\n apply(target: any, thisArg: any, args: any[]) {\r\n console.log(\r\n `PROXY APPLY TRAP HIT: stateKey=${stateKey}, path=${path.join(\".\")}`\r\n ); // <--- ADD LOGGING\r\n console.trace(\"Apply trap stack trace\");\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n },\r\n\r\n get(target: any, prop: string) {\r\n if (\r\n prop !== \"then\" &&\r\n !prop.startsWith(\"$\") &&\r\n prop !== \"stateMapNoRender\"\r\n ) {\r\n const currentPath = path.join(\".\");\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Only add paths for non-root or specifically for get() at root\r\n if (path.length > 0 || prop === \"get\") {\r\n component.paths.add(currentPath);\r\n }\r\n } else {\r\n }\r\n }\r\n }\r\n if (prop === \"_status\") {\r\n // Get current state at this path (non-reactive version)\r\n const thisReactiveState = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n }\r\n if (prop === \"getStatus\") {\r\n return function () {\r\n // Get current state at this path (reactive version)\r\n const thisReactiveState = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n );\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n };\r\n }\r\n if (prop === \"removeStorage\") {\r\n return () => {\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n console.log(\"removing storage\", storageKey);\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n };\r\n }\r\n if (prop === \"showValidationErrors\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n const errors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key + \".\" + path.join(\".\"));\r\n\r\n return errors;\r\n };\r\n }\r\n if (Array.isArray(currentState)) {\r\n if (prop === \"getSelected\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n if (selectedIndex === undefined) return undefined;\r\n return rebuildStateShape(\r\n currentState[selectedIndex],\r\n [...path, selectedIndex.toString()],\r\n meta\r\n );\r\n };\r\n }\r\n if (prop === \"getSelectedIndex\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n\r\n return selectedIndex ?? -1;\r\n };\r\n }\r\n if (prop === \"stateSort\") {\r\n return (\r\n compareFn: (\r\n a: InferArrayElement<T>,\r\n b: InferArrayElement<T>\r\n ) => number\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n\r\n // Create a shallow copy with original indices\r\n const arrayCopy = currentArray.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n // Sort the copy using the provided compare function\r\n const sortedArray = [...arrayCopy].sort(compareFn);\r\n\r\n // ADDED: Clear cache for sort operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Return the sorted array with state objects\r\n return rebuildStateShape(sortedArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: sortedArray.map((item) =>\r\n parseInt(item.__origIndex as string)\r\n ),\r\n });\r\n };\r\n }\r\n if (prop === \"stateMap\" || prop === \"stateMapNoRender\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n if (prop !== \"stateMapNoRender\") {\r\n shapeCache.clear();\r\n stateVersion++;\r\n }\r\n\r\n return arrayToMap.map((val: any, index: number) => {\r\n const thisIndex =\r\n isFiltered && val.__origIndex ? val.__origIndex : index;\r\n const elementProxy = rebuildStateShape(\r\n val,\r\n [...path, thisIndex.toString()],\r\n meta\r\n );\r\n return callbackfn(\r\n val,\r\n elementProxy,\r\n index,\r\n currentState as any,\r\n rebuildStateShape(currentState as any, path, meta)\r\n );\r\n });\r\n };\r\n }\r\n if (prop === \"$stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n return createElement(SignalMapRenderer, {\r\n proxy: {\r\n _stateKey: stateKey,\r\n _path: path,\r\n _mapFn: callbackfn as any, // Pass the actual function, not string\r\n },\r\n\r\n rebuildStateShape,\r\n });\r\n };\r\n }\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const isFiltered = meta?.filtered?.some(\r\n (p) => p.join(\".\") === path.join(\".\")\r\n );\r\n const arrayToMap = isFiltered\r\n ? currentState\r\n : getGlobalStore.getState().getNestedState(stateKey, path);\r\n\r\n // ADDED: Clear shape cache for flattening operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any, index: number) => {\r\n return val[fieldName] ?? [];\r\n }\r\n );\r\n\r\n return rebuildStateShape(\r\n flattenedResults,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (\r\n thisKey: keyof InferArrayElement<T>,\r\n thisValue: InferArrayElement<T>[keyof InferArrayElement<T>]\r\n ) => {\r\n const foundIndex = currentState.findIndex(\r\n (obj: any) => obj[thisKey] === thisValue\r\n );\r\n if (foundIndex === -1) return undefined;\r\n const foundValue = currentState[foundIndex];\r\n const newPath = [...path, foundIndex.toString()];\r\n // console.log(\r\n // \"findWithfindWithfindWithfindWith\",\r\n // stateKey,\r\n // foundValue,\r\n // newPath,\r\n // );\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // ADDED: Clear cache for find operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n // Try returning without spread\r\n return rebuildStateShape(foundValue, newPath);\r\n };\r\n }\r\n\r\n if (prop === \"index\") {\r\n return (index: number) => {\r\n const indexValue = currentState[index];\r\n return rebuildStateShape(indexValue, [...path, index.toString()]);\r\n };\r\n }\r\n\r\n if (prop === \"insert\") {\r\n return (payload: UpdateArg<T>) => {\r\n // ADDED: Invalidate cache on insert\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, payload, path, stateKey);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n []\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"uniqueInsert\") {\r\n return (\r\n payload: UpdateArg<T>,\r\n fields?: (keyof InferArrayElement<T>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n const newValue = isFunction<T>(payload)\r\n ? payload(currentArray as any)\r\n : (payload as any);\r\n\r\n let matchedItem: any = null;\r\n const isUnique = !currentArray.some((item) => {\r\n if (fields) {\r\n const isMatch = fields.every((field) =>\r\n isDeepEqual(item[field], newValue[field])\r\n );\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n }\r\n const isMatch = isDeepEqual(item, newValue);\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n });\r\n\r\n if (isUnique) {\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, newValue, path, stateKey);\r\n } else if (onMatch && matchedItem) {\r\n const updatedItem = onMatch(matchedItem);\r\n const updatedArray = currentArray.map((item) =>\r\n isDeepEqual(item, matchedItem) ? updatedItem : item\r\n );\r\n invalidateCachePath(path);\r\n updateFn(effectiveSetState, updatedArray as any, path);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"cut\") {\r\n return (index: number, options?: { waitForSync?: boolean }) => {\r\n if (options?.waitForSync) return;\r\n // ADDED: Invalidate cache on cut\r\n invalidateCachePath(path);\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n };\r\n }\r\n if (prop === \"cutByValue\") {\r\n return (value: string | number | boolean) => {\r\n for (let index = 0; index < currentState.length; index++) {\r\n if (currentState[index] === value) {\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"toggleByValue\") {\r\n return (value: string | number | boolean) => {\r\n const index = currentState.findIndex((item) => item === value);\r\n if (index > -1) {\r\n // Value exists, so cut it\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n } else {\r\n // Value doesn't exist, so insert it\r\n pushFunc(effectiveSetState, value as any, path, stateKey);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"stateFilter\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const newVal = currentState.map((v: any, i: number) => ({\r\n ...v,\r\n __origIndex: i.toString(),\r\n }));\r\n\r\n const validIndices: number[] = [];\r\n const filteredArray: Array<InferArrayElement<T>> = [];\r\n\r\n for (let i = 0; i < newVal.length; i++) {\r\n if (callbackfn(newVal[i], i)) {\r\n validIndices.push(i);\r\n filteredArray.push(newVal[i]);\r\n }\r\n }\r\n\r\n // ADDED: Clear cache for filter operation\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n // Always include validIndices, even if it's an empty array\r\n return rebuildStateShape(filteredArray as any, path, {\r\n filtered: [...(meta?.filtered || []), path],\r\n validIndices: validIndices, // Always pass validIndices, even if empty\r\n });\r\n };\r\n }\r\n }\r\n const lastPathElement = path[path.length - 1];\r\n if (!isNaN(Number(lastPathElement))) {\r\n const parentPath = path.slice(0, -1);\r\n const parentValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n\r\n if (Array.isArray(parentValue) && prop === \"cut\") {\r\n return () =>\r\n cutFunc(\r\n effectiveSetState,\r\n parentPath,\r\n stateKey,\r\n Number(lastPathElement)\r\n );\r\n }\r\n }\r\n\r\n if (prop === \"get\") {\r\n return () => getGlobalStore.getState().getNestedState(stateKey, path);\r\n }\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$get\") {\r\n return () =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n });\r\n }\r\n if (prop === \"lastSynced\") {\r\n const syncKey = `${stateKey}:${path.join(\".\")}`;\r\n return getGlobalStore.getState().getSyncInfo(syncKey);\r\n }\r\n\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\r\n if (prop === \"_selected\") {\r\n const parentPath = path.slice(0, -1);\r\n const parentKey = parentPath.join(\".\");\r\n const parent = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n if (Array.isArray(parent)) {\r\n const currentIndex = Number(path[path.length - 1]);\r\n return (\r\n currentIndex ===\r\n getGlobalStore.getState().getSelectedIndex(stateKey, parentKey)\r\n );\r\n }\r\n return undefined;\r\n }\r\n if (prop === \"setSelected\") {\r\n return (value: boolean) => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n\r\n if (value) {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, thisIndex);\r\n } else {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, undefined);\r\n }\r\n\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n // Invalidate cache for this path\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"validateZodSchema\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n const addValidationError =\r\n getGlobalStore.getState().addValidationError;\r\n\r\n if (!init?.zodSchema) {\r\n throw new Error(\"Zod schema not found\");\r\n }\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n removeValidationError(init.key);\r\n const thisObject =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n\r\n try {\r\n // First clear any existing validation errors for this schema\r\n // This ensures we don't have stale errors\r\n const existingErrors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key);\r\n if (existingErrors && existingErrors.length > 0) {\r\n existingErrors.forEach(([errorPath]) => {\r\n if (errorPath && errorPath.startsWith(init.key!)) {\r\n removeValidationError(errorPath);\r\n }\r\n });\r\n }\r\n\r\n // Attempt to validate with Zod\r\n const result = init.zodSchema.safeParse(thisObject);\r\n\r\n if (!result.success) {\r\n // Process Zod errors and add them to the validation store\r\n const zodErrors = result.error.errors;\r\n\r\n zodErrors.forEach((error) => {\r\n const errorPath = error.path;\r\n const errorMessage = error.message;\r\n\r\n // Build the full path for the validation error\r\n // Format: validationKey.path.to.field\r\n const fullErrorPath = [init.key, ...errorPath].join(\".\");\r\n\r\n // Add the error to the store\r\n addValidationError(fullErrorPath, errorMessage);\r\n });\r\n\r\n notifyComponents(stateKey);\r\n\r\n return false;\r\n }\r\n\r\n return true;\r\n } catch (error) {\r\n console.error(\"Zod schema validation failed\", error);\r\n return false;\r\n }\r\n };\r\n }\r\n if (prop === \"_componentId\") return componentId;\r\n if (prop === \"getComponents\") {\r\n return () => getGlobalStore().stateComponents.get(stateKey);\r\n }\r\n if (prop === \"getAllFormRefs\") {\r\n return () => {\r\n return formRefStore.getState().getFormRefsByStateKey(stateKey);\r\n };\r\n }\r\n\r\n if (prop === \"_initialState\")\r\n return getGlobalStore.getState().initialStateGlobal[stateKey];\r\n if (prop === \"_serverState\")\r\n return getGlobalStore.getState().serverState[stateKey];\r\n if (prop === \"_isLoading\")\r\n return getGlobalStore.getState().isLoadingGlobal[stateKey];\r\n if (prop === \"revertToInitialState\")\r\n return baseObj.revertToInitialState;\r\n if (prop === \"updateInitialState\") return baseObj.updateInitialState;\r\n if (prop === \"removeValidation\") return baseObj.removeValidation;\r\n }\r\n if (prop === \"getFormRef\") {\r\n return () => {\r\n return formRefStore\r\n .getState()\r\n .getFormRef(stateKey + \".\" + path.join(\".\"));\r\n };\r\n }\r\n\r\n if (prop === \"validationWrapper\") {\r\n return ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => (\r\n <ValidationWrapper\r\n formOpts={\r\n hideMessage ? { validation: { message: \"\" } } : undefined\r\n }\r\n path={path}\r\n validationKey={\r\n getGlobalStore.getState().getInitialOptions(stateKey)\r\n ?.validation?.key || \"\"\r\n }\r\n stateKey={stateKey}\r\n validIndices={meta?.validIndices}\r\n >\r\n {children}\r\n </ValidationWrapper>\r\n );\r\n }\r\n\r\n if (prop === \"_stateKey\") return stateKey;\r\n if (prop === \"_path\") return path;\r\n if (prop === \"_isServerSynced\") return baseObj._isServerSynced;\r\n\r\n if (prop === \"update\") {\r\n return (payload: UpdateArg<T>, opts?: UpdateOpts<T>) => {\r\n // ADDED: Invalidate cache on update\r\n if (opts?.debounce) {\r\n debounce(() => {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }, opts.debounce);\r\n } else {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }\r\n invalidateCachePath(path);\r\n };\r\n }\r\n\r\n if (prop === \"formElement\") {\r\n return (child: FormControl<T>, formOpts?: FormOptsType) => {\r\n return (\r\n <FormControlComponent<T>\r\n setState={effectiveSetState}\r\n stateKey={stateKey}\r\n path={path}\r\n child={child}\r\n formOpts={formOpts}\r\n />\r\n );\r\n };\r\n }\r\n\r\n const nextPath = [...path, prop];\r\n const nextValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, nextPath);\r\n return rebuildStateShape(nextValue, nextPath, meta);\r\n },\r\n };\r\n\r\n const proxyInstance = new Proxy(baseFunction, handler);\r\n\r\n shapeCache.set(cacheKey, {\r\n proxy: proxyInstance,\r\n stateVersion: stateVersion,\r\n });\r\n\r\n return proxyInstance;\r\n }\r\n\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, [])\r\n );\r\n}\r\n\r\nexport function $cogsSignal(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n}) {\r\n return createElement(SignalRenderer, { proxy });\r\n}\r\n\r\nfunction SignalMapRenderer({\r\n proxy,\r\n\r\n rebuildStateShape,\r\n}: {\r\n proxy: {\r\n _stateKey: string;\r\n _path: string[];\r\n _mapFn: (\r\n value: any,\r\n setter: any,\r\n index: number,\r\n array: any[],\r\n arraySetter: any\r\n ) => ReactNode;\r\n };\r\n\r\n rebuildStateShape: (\r\n currentState: any,\r\n path: string[],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ) => any;\r\n}) {\r\n const value = getGlobalStore().getNestedState(proxy._stateKey, proxy._path);\r\n\r\n if (!Array.isArray(value)) {\r\n return null;\r\n }\r\n const arraySetter = rebuildStateShape(\r\n value,\r\n proxy._path\r\n ) as ArrayEndType<any>;\r\n // Use existing global state management\r\n return arraySetter.stateMapNoRender(\r\n (item, setter, index, value, arraysetter) => {\r\n // Execute map function in React context with existing state/proxies\r\n return proxy._mapFn(item, setter, index, value, arraysetter);\r\n }\r\n );\r\n}\r\nfunction SignalRenderer({\r\n proxy,\r\n}: {\r\n proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n };\r\n}) {\r\n const elementRef = useRef<HTMLSpanElement>(null);\r\n const signalId = `${proxy._stateKey}-${proxy._path.join(\".\")}`;\r\n\r\n useEffect(() => {\r\n const element = elementRef.current;\r\n if (!element || !element.parentElement) return;\r\n\r\n const parentElement = element.parentElement;\r\n const childNodes = Array.from(parentElement.childNodes);\r\n const position = childNodes.indexOf(element);\r\n\r\n let parentId = parentElement.getAttribute(\"data-parent-id\");\r\n if (!parentId) {\r\n parentId = `parent-${crypto.randomUUID()}`;\r\n parentElement.setAttribute(\"data-parent-id\", parentId);\r\n }\r\n\r\n const instanceId = `instance-${crypto.randomUUID()}`;\r\n const elementInfo = {\r\n instanceId,\r\n parentId,\r\n position,\r\n effect: proxy._effect,\r\n };\r\n\r\n getGlobalStore.getState().addSignalElement(signalId, elementInfo);\r\n\r\n // Get the raw value from the store\r\n const value = getGlobalStore\r\n .getState()\r\n .getNestedState(proxy._stateKey, proxy._path);\r\n\r\n let displayValue;\r\n if (proxy._effect) {\r\n try {\r\n displayValue = new Function(\r\n \"state\",\r\n `return (${proxy._effect})(state)`\r\n )(value);\r\n } catch (err) {\r\n console.error(\"Error evaluating effect function during mount:\", err);\r\n displayValue = value; // Fallback to raw value\r\n }\r\n } else {\r\n displayValue = value;\r\n }\r\n\r\n if (displayValue !== null && typeof displayValue === \"object\") {\r\n displayValue = JSON.stringify(displayValue);\r\n }\r\n\r\n const textNode = document.createTextNode(String(displayValue));\r\n element.replaceWith(textNode);\r\n }, [proxy._stateKey, proxy._path.join(\".\"), proxy._effect]);\r\n\r\n return createElement(\"span\", {\r\n ref: elementRef,\r\n style: { display: \"none\" },\r\n \"data-signal-id\": signalId,\r\n });\r\n}\r\nexport function $cogsSignalStore(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n}) {\r\n const value = useSyncExternalStore(\r\n (notify) => {\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(proxy._stateKey) || {\r\n components: new Map(),\r\n };\r\n stateEntry.components.set(proxy._stateKey, {\r\n forceUpdate: notify,\r\n paths: new Set([proxy._path.join(\".\")]),\r\n });\r\n return () => stateEntry.components.delete(proxy._stateKey);\r\n },\r\n () => getGlobalStore.getState().getNestedState(proxy._stateKey, proxy._path)\r\n );\r\n return createElement(\"text\", {}, String(value));\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","loadFromLocalStorage","localStorageKey","storedData","error","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","isFunction","data","storageKey","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","startTransition","notifyComponents","stateEntry","component","update","notifyComponent","fullComponentId","stateObject","serverSync","localStorage","middleware","reactiveDeps","reactiveType","syncUpdate","dependencies","reactiveForce","forceUpdate","useCogsConfig","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","localData","localkey","useLayoutEffect","depsKey","newStateOrFunction","path","updateObj","validationKey","pathKey","prevValue","payload","signalId","isArrayOperation","elements","arrayPath","arrayValue","getNestedValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","k","v","length","newKey","oldValue","pathToCheck","shouldUpdate","reactiveTypes","depsResult","isDeepEqual","newUpdate","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","field","serverState","currentState","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","currentPath","thisReactiveState","initialStateAtPath","selectedIndex","compareFn","sortedArray","i","item","callbackfn","isFiltered","p","arrayToMap","val","index","thisIndex","elementProxy","createElement","SignalMapRenderer","fieldName","flattenedResults","thisValue","foundIndex","foundValue","newPath","indexValue","pushFunc","fields","onMatch","currentArray","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","newVal","validIndices","filteredArray","lastPathElement","parentPath","parentValue","fn","$cogsSignal","parentKey","nested","thisObject","existingErrors","errorPath","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","jsx","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","setter","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify"],"mappings":";;;;;;;;;AAwYA,SAASA,GAAmBC,GAAkBC,GAA8B;AACpEC,QAAAA,IAAoBC,EAAe,SAAA,EAAW,mBAC9CC,IACJD,EAAe,SAAA,EAAW,wBAEtBE,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC;AAEjE,EAAAI,EAAuBJ,GAAoB;AAAA,IACzC,GAAGK;AAAA,IACH,GAAGJ;AAAA,EAAA,CACJ;AACH;A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