cogsbox-state 0.5.461 → 0.5.462

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1465 +1,1426 @@
1
1
  "use client";
2
- import { jsx as it, Fragment as Ot } from "react/jsx-runtime";
3
- import { memo as $t, useState as at, useRef as z, useCallback as lt, useEffect as et, useLayoutEffect as dt, useMemo as St, createElement as ut, startTransition as Ut } from "react";
4
- import { createRoot as Vt } from "react-dom/client";
5
- import { transformStateFunc as Rt, isFunction as rt, isArray as It, getDifferences as Et, isDeepEqual as ct } from "./utility.js";
6
- import { ValidationWrapper as At } from "./Functions.jsx";
7
- import Lt from "superjson";
8
- import { v4 as nt } from "uuid";
9
- import { getGlobalStore as e, formRefStore as ht } from "./store.js";
10
- import { useCogsConfig as _t } from "./CogsStateClient.jsx";
11
- import { useInView as Nt } from "react-intersection-observer";
12
- function mt(t, a) {
13
- const m = e.getState().getInitialOptions, g = e.getState().setInitialStateOptions, y = m(t) || {};
2
+ import { jsx as nt, Fragment as Pt } from "react/jsx-runtime";
3
+ import { memo as Dt, useState as X, useRef as z, useCallback as st, useEffect as Q, useLayoutEffect as ct, useMemo as dt, createElement as it, startTransition as kt } from "react";
4
+ import { createRoot as Mt } from "react-dom/client";
5
+ import { transformStateFunc as Ot, isFunction as tt, isArray as pt, getDifferences as Tt, isDeepEqual as ot } from "./utility.js";
6
+ import { ValidationWrapper as bt } from "./Functions.jsx";
7
+ import Ut from "superjson";
8
+ import { v4 as et } from "uuid";
9
+ import { getGlobalStore as a, formRefStore as St } from "./store.js";
10
+ import { useCogsConfig as Et } from "./CogsStateClient.jsx";
11
+ import { useInView as $t } from "react-intersection-observer";
12
+ function ft(t, r) {
13
+ const h = a.getState().getInitialOptions, g = a.getState().setInitialStateOptions, w = h(t) || {};
14
14
  g(t, {
15
- ...y,
16
- ...a
15
+ ...w,
16
+ ...r
17
17
  });
18
18
  }
19
- function Mt({
19
+ function vt({
20
20
  stateKey: t,
21
- options: a,
22
- initialOptionsPart: m
21
+ options: r,
22
+ initialOptionsPart: h
23
23
  }) {
24
- const g = ot(t) || {}, y = m[t] || {}, I = e.getState().setInitialStateOptions, T = { ...y, ...g };
25
- let s = !1;
26
- if (a)
27
- for (const l in a)
28
- T.hasOwnProperty(l) ? (l == "localStorage" && a[l] && T[l].key !== a[l]?.key && (s = !0, T[l] = a[l]), l == "defaultState" && a[l] && T[l] !== a[l] && !ct(T[l], a[l]) && (s = !0, T[l] = a[l])) : (s = !0, T[l] = a[l]);
29
- T.syncOptions && (!a || !a.hasOwnProperty("syncOptions")) && (s = !0), s && I(t, T);
24
+ const g = at(t) || {}, w = h[t] || {}, f = a.getState().setInitialStateOptions, b = { ...w, ...g };
25
+ let S = !1;
26
+ if (r)
27
+ for (const e in r)
28
+ b.hasOwnProperty(e) ? (e == "localStorage" && r[e] && b[e].key !== r[e]?.key && (S = !0, b[e] = r[e]), e == "defaultState" && r[e] && b[e] !== r[e] && !ot(b[e], r[e]) && (S = !0, b[e] = r[e])) : (S = !0, b[e] = r[e]);
29
+ b.syncOptions && (!r || !r.hasOwnProperty("syncOptions")) && (S = !0), S && f(t, b);
30
30
  }
31
- function se(t, { formElements: a, validation: m }) {
32
- return { initialState: t, formElements: a, validation: m };
31
+ function re(t, { formElements: r, validation: h }) {
32
+ return { initialState: t, formElements: r, validation: h };
33
33
  }
34
- const Ft = (t, a) => {
35
- let m = t;
36
- console.log("optsc", a?.__useSync);
37
- const [g, y] = Rt(m);
38
- a?.__fromSyncSchema && a?.__syncNotifications && e.getState().setInitialStateOptions("__notifications", a.__syncNotifications), a?.__fromSyncSchema && a?.__apiParamsMap && e.getState().setInitialStateOptions("__apiParamsMap", a.__apiParamsMap), Object.keys(g).forEach((s) => {
39
- let l = y[s] || {};
40
- const P = {
41
- ...l
34
+ const Rt = (t, r) => {
35
+ let h = t;
36
+ console.log("optsc", r?.__useSync);
37
+ const [g, w] = Ot(h);
38
+ r?.__fromSyncSchema && r?.__syncNotifications && a.getState().setInitialStateOptions("__notifications", r.__syncNotifications), r?.__fromSyncSchema && r?.__apiParamsMap && a.getState().setInitialStateOptions("__apiParamsMap", r.__apiParamsMap), Object.keys(g).forEach((S) => {
39
+ let e = w[S] || {};
40
+ const s = {
41
+ ...e
42
42
  };
43
- if (a?.formElements && (P.formElements = {
44
- ...a.formElements,
45
- ...l.formElements || {}
46
- }), a?.validation && (P.validation = {
47
- ...a.validation,
48
- ...l.validation || {}
49
- }, a.validation.key && !l.validation?.key && (P.validation.key = `${a.validation.key}.${s}`)), a?.__syncSchemas?.[s]?.schemas?.validation && (P.validation = {
50
- zodSchemaV4: a.__syncSchemas[s].schemas.validation,
51
- ...l.validation
52
- }), Object.keys(P).length > 0) {
53
- const b = ot(s);
54
- b ? e.getState().setInitialStateOptions(s, {
55
- ...b,
56
- ...P
57
- }) : e.getState().setInitialStateOptions(s, P);
43
+ if (r?.formElements && (s.formElements = {
44
+ ...r.formElements,
45
+ ...e.formElements || {}
46
+ }), r?.validation && (s.validation = {
47
+ ...r.validation,
48
+ ...e.validation || {}
49
+ }, r.validation.key && !e.validation?.key && (s.validation.key = `${r.validation.key}.${S}`)), r?.__syncSchemas?.[S]?.schemas?.validation && (s.validation = {
50
+ zodSchemaV4: r.__syncSchemas[S].schemas.validation,
51
+ ...e.validation
52
+ }), Object.keys(s).length > 0) {
53
+ const v = at(S);
54
+ v ? a.getState().setInitialStateOptions(S, {
55
+ ...v,
56
+ ...s
57
+ }) : a.getState().setInitialStateOptions(S, s);
58
58
  }
59
- }), Object.keys(g).forEach((s) => {
60
- e.getState().initializeShadowState(s, g[s]);
59
+ }), Object.keys(g).forEach((S) => {
60
+ a.getState().initializeShadowState(S, g[S]);
61
61
  });
62
- const I = (s, l) => {
63
- const [P] = at(l?.componentId ?? nt());
64
- Mt({
65
- stateKey: s,
66
- options: l,
67
- initialOptionsPart: y
62
+ const f = (S, e) => {
63
+ const [s] = X(e?.componentId ?? et());
64
+ vt({
65
+ stateKey: S,
66
+ options: e,
67
+ initialOptionsPart: w
68
68
  });
69
- const b = e.getState().getShadowValue(s) || g[s], o = l?.modifyState ? l.modifyState(b) : b;
70
- return xt(o, {
71
- stateKey: s,
72
- syncUpdate: l?.syncUpdate,
73
- componentId: P,
74
- localStorage: l?.localStorage,
75
- middleware: l?.middleware,
76
- reactiveType: l?.reactiveType,
77
- reactiveDeps: l?.reactiveDeps,
78
- defaultState: l?.defaultState,
79
- dependencies: l?.dependencies,
80
- serverState: l?.serverState,
81
- syncOptions: l?.syncOptions,
82
- __useSync: a?.__useSync
69
+ const v = a.getState().getShadowValue(S) || g[S], R = e?.modifyState ? e.modifyState(v) : v;
70
+ return Lt(R, {
71
+ stateKey: S,
72
+ syncUpdate: e?.syncUpdate,
73
+ componentId: s,
74
+ localStorage: e?.localStorage,
75
+ middleware: e?.middleware,
76
+ reactiveType: e?.reactiveType,
77
+ reactiveDeps: e?.reactiveDeps,
78
+ defaultState: e?.defaultState,
79
+ dependencies: e?.dependencies,
80
+ serverState: e?.serverState,
81
+ syncOptions: e?.syncOptions,
82
+ __useSync: r?.__useSync
83
83
  });
84
84
  };
85
- function T(s, l) {
86
- Mt({ stateKey: s, options: l, initialOptionsPart: y }), l.localStorage && Ht(s, l), vt(s);
85
+ function b(S, e) {
86
+ vt({ stateKey: S, options: e, initialOptionsPart: w }), e.localStorage && Ft(S, e), mt(S);
87
87
  }
88
- return { useCogsState: I, setCogsOptions: T };
88
+ return { useCogsState: f, setCogsOptions: b };
89
89
  };
90
- function ie(t, a) {
91
- const m = t.schemas, g = {}, y = {};
92
- for (const I in m) {
93
- const T = m[I];
94
- g[I] = T?.schemas?.defaultValues || {}, T?.api?.queryData?._paramType && (y[I] = T.api.queryData._paramType);
90
+ function ne(t, r) {
91
+ const h = t.schemas, g = {}, w = {};
92
+ for (const f in h) {
93
+ const b = h[f];
94
+ g[f] = b?.schemas?.defaultValues || {}, b?.api?.queryData?._paramType && (w[f] = b.api.queryData._paramType);
95
95
  }
96
- return Ft(g, {
96
+ return Rt(g, {
97
97
  __fromSyncSchema: !0,
98
98
  __syncNotifications: t.notifications,
99
- __apiParamsMap: y,
100
- __useSync: a,
101
- __syncSchemas: m
99
+ __apiParamsMap: w,
100
+ __useSync: r,
101
+ __syncSchemas: h
102
102
  });
103
103
  }
104
104
  const {
105
- getInitialOptions: ot,
106
- setStateLog: jt,
107
- updateInitialStateGlobal: Ct
108
- } = e.getState(), Wt = (t, a, m, g, y) => {
109
- m?.log && console.log(
105
+ getInitialOptions: at,
106
+ addStateLog: Nt,
107
+ updateInitialStateGlobal: Vt
108
+ } = a.getState(), jt = (t, r, h, g, w) => {
109
+ h?.log && console.log(
110
110
  "saving to localstorage",
111
- a,
112
- m.localStorage?.key,
111
+ r,
112
+ h.localStorage?.key,
113
113
  g
114
114
  );
115
- const I = rt(m?.localStorage?.key) ? m.localStorage?.key(t) : m?.localStorage?.key;
116
- if (I && g) {
117
- const T = `${g}-${a}-${I}`;
118
- let s;
115
+ const f = tt(h?.localStorage?.key) ? h.localStorage?.key(t) : h?.localStorage?.key;
116
+ if (f && g) {
117
+ const b = `${g}-${r}-${f}`;
118
+ let S;
119
119
  try {
120
- s = gt(T)?.lastSyncedWithServer;
120
+ S = ut(b)?.lastSyncedWithServer;
121
121
  } catch {
122
122
  }
123
- const l = e.getState().getShadowMetadata(a, []), P = {
123
+ const e = a.getState().getShadowMetadata(r, []), s = {
124
124
  state: t,
125
125
  lastUpdated: Date.now(),
126
- lastSyncedWithServer: s,
127
- stateSource: l?.stateSource,
128
- baseServerState: l?.baseServerState
129
- }, b = Lt.serialize(P);
126
+ lastSyncedWithServer: S,
127
+ stateSource: e?.stateSource,
128
+ baseServerState: e?.baseServerState
129
+ }, v = Ut.serialize(s);
130
130
  window.localStorage.setItem(
131
- T,
132
- JSON.stringify(b.json)
131
+ b,
132
+ JSON.stringify(v.json)
133
133
  );
134
134
  }
135
- }, gt = (t) => {
135
+ }, ut = (t) => {
136
136
  if (!t) return null;
137
137
  try {
138
- const a = window.localStorage.getItem(t);
139
- return a ? JSON.parse(a) : null;
140
- } catch (a) {
141
- return console.error("Error loading from localStorage:", a), null;
138
+ const r = window.localStorage.getItem(t);
139
+ return r ? JSON.parse(r) : null;
140
+ } catch (r) {
141
+ return console.error("Error loading from localStorage:", r), null;
142
142
  }
143
- }, Ht = (t, a) => {
144
- const m = e.getState().getShadowValue(t), { sessionId: g } = _t(), y = rt(a?.localStorage?.key) ? a.localStorage.key(m) : a?.localStorage?.key;
145
- if (y && g) {
146
- const I = gt(
147
- `${g}-${t}-${y}`
143
+ }, Ft = (t, r) => {
144
+ const h = a.getState().getShadowValue(t), { sessionId: g } = Et(), w = tt(r?.localStorage?.key) ? r.localStorage.key(h) : r?.localStorage?.key;
145
+ if (w && g) {
146
+ const f = ut(
147
+ `${g}-${t}-${w}`
148
148
  );
149
- if (I && I.lastUpdated > (I.lastSyncedWithServer || 0))
150
- return vt(t), !0;
149
+ if (f && f.lastUpdated > (f.lastSyncedWithServer || 0))
150
+ return mt(t), !0;
151
151
  }
152
152
  return !1;
153
- }, vt = (t) => {
154
- const a = e.getState().getShadowMetadata(t, []);
155
- if (!a) return;
156
- const m = /* @__PURE__ */ new Set();
157
- a?.components?.forEach((g) => {
158
- (g ? Array.isArray(g.reactiveType) ? g.reactiveType : [g.reactiveType || "component"] : null)?.includes("none") || m.add(() => g.forceUpdate());
153
+ }, mt = (t) => {
154
+ const r = a.getState().getShadowMetadata(t, []);
155
+ if (!r) return;
156
+ const h = /* @__PURE__ */ new Set();
157
+ r?.components?.forEach((g) => {
158
+ (g ? Array.isArray(g.reactiveType) ? g.reactiveType : [g.reactiveType || "component"] : null)?.includes("none") || h.add(() => g.forceUpdate());
159
159
  }), queueMicrotask(() => {
160
- m.forEach((g) => g());
160
+ h.forEach((g) => g());
161
161
  });
162
- }, ce = (t, a) => {
163
- const m = e.getState().getShadowMetadata(t, []);
164
- if (m) {
165
- const g = `${t}////${a}`, y = m?.components?.get(g);
166
- if ((y ? Array.isArray(y.reactiveType) ? y.reactiveType : [y.reactiveType || "component"] : null)?.includes("none"))
162
+ }, oe = (t, r) => {
163
+ const h = a.getState().getShadowMetadata(t, []);
164
+ if (h) {
165
+ const g = `${t}////${r}`, w = h?.components?.get(g);
166
+ if ((w ? Array.isArray(w.reactiveType) ? w.reactiveType : [w.reactiveType || "component"] : null)?.includes("none"))
167
167
  return;
168
- y && y.forceUpdate();
168
+ w && w.forceUpdate();
169
169
  }
170
170
  };
171
- function yt(t, a, m, g) {
172
- const y = e.getState(), I = y.getShadowMetadata(t, a);
173
- if (y.setShadowMetadata(t, a, {
174
- ...I,
171
+ function gt(t, r, h, g) {
172
+ const w = a.getState(), f = w.getShadowMetadata(t, r);
173
+ if (w.setShadowMetadata(t, r, {
174
+ ...f,
175
175
  isDirty: !1,
176
176
  stateSource: "server",
177
177
  lastServerSync: g || Date.now()
178
- }), Array.isArray(m)) {
179
- const T = y.getShadowMetadata(t, a);
180
- T?.arrayKeys && T.arrayKeys.forEach((s, l) => {
181
- const P = s.split(".").slice(1), b = m[l];
182
- b !== void 0 && yt(
178
+ }), Array.isArray(h)) {
179
+ const b = w.getShadowMetadata(t, r);
180
+ b?.arrayKeys && b.arrayKeys.forEach((S, e) => {
181
+ const s = S.split(".").slice(1), v = h[e];
182
+ v !== void 0 && gt(
183
183
  t,
184
- P,
185
- b,
184
+ s,
185
+ v,
186
186
  g
187
187
  );
188
188
  });
189
- } else m && typeof m == "object" && m.constructor === Object && Object.keys(m).forEach((T) => {
190
- const s = [...a, T], l = m[T];
191
- yt(t, s, l, g);
189
+ } else h && typeof h == "object" && h.constructor === Object && Object.keys(h).forEach((b) => {
190
+ const S = [...r, b], e = h[b];
191
+ gt(t, S, e, g);
192
192
  });
193
193
  }
194
- function xt(t, {
195
- stateKey: a,
196
- localStorage: m,
194
+ function Lt(t, {
195
+ stateKey: r,
196
+ localStorage: h,
197
197
  formElements: g,
198
- reactiveDeps: y,
199
- reactiveType: I,
200
- componentId: T,
201
- defaultState: s,
202
- syncUpdate: l,
203
- dependencies: P,
204
- serverState: b,
205
- __useSync: o,
206
- syncOptions: h
198
+ reactiveDeps: w,
199
+ reactiveType: f,
200
+ componentId: b,
201
+ defaultState: S,
202
+ syncUpdate: e,
203
+ dependencies: s,
204
+ serverState: v,
205
+ __useSync: R,
206
+ syncOptions: L
207
207
  } = {}) {
208
- const [_, x] = at({}), { sessionId: R } = _t();
209
- let B = !a;
210
- const [S] = at(a ?? nt()), W = e.getState().stateLog[S], q = z(/* @__PURE__ */ new Set()), p = z(T ?? nt()), Y = z(
208
+ const [k, W] = X({}), { sessionId: H } = Et();
209
+ let J = !r;
210
+ const [m] = X(r ?? et()), u = z(b ?? et()), j = z(
211
211
  null
212
212
  );
213
- Y.current = ot(S) ?? null, et(() => {
214
- if (l && l.stateKey === S && l.path?.[0]) {
215
- const d = `${l.stateKey}:${l.path.join(".")}`;
216
- e.getState().setSyncInfo(d, {
217
- timeStamp: l.timeStamp,
218
- userId: l.userId
213
+ j.current = at(m) ?? null, Q(() => {
214
+ if (e && e.stateKey === m && e.path?.[0]) {
215
+ const l = `${e.stateKey}:${e.path.join(".")}`;
216
+ a.getState().setSyncInfo(l, {
217
+ timeStamp: e.timeStamp,
218
+ userId: e.userId
219
219
  });
220
220
  }
221
- }, [l]);
222
- const tt = lt(
223
- (d) => {
224
- const f = d ? { ...ot(S), ...d } : ot(S), D = f?.defaultState || s || t;
225
- if (f?.serverState?.status === "success" && f?.serverState?.data !== void 0)
221
+ }, [e]);
222
+ const Y = st(
223
+ (l) => {
224
+ const y = l ? { ...at(m), ...l } : at(m), _ = y?.defaultState || S || t;
225
+ if (y?.serverState?.status === "success" && y?.serverState?.data !== void 0)
226
226
  return {
227
- value: f.serverState.data,
227
+ value: y.serverState.data,
228
228
  source: "server",
229
- timestamp: f.serverState.timestamp || Date.now()
229
+ timestamp: y.serverState.timestamp || Date.now()
230
230
  };
231
- if (f?.localStorage?.key && R) {
232
- const k = rt(f.localStorage.key) ? f.localStorage.key(D) : f.localStorage.key, V = gt(
233
- `${R}-${S}-${k}`
231
+ if (y?.localStorage?.key && H) {
232
+ const E = tt(y.localStorage.key) ? y.localStorage.key(_) : y.localStorage.key, A = ut(
233
+ `${H}-${m}-${E}`
234
234
  );
235
- if (V && V.lastUpdated > (f?.serverState?.timestamp || 0))
235
+ if (A && A.lastUpdated > (y?.serverState?.timestamp || 0))
236
236
  return {
237
- value: V.state,
237
+ value: A.state,
238
238
  source: "localStorage",
239
- timestamp: V.lastUpdated
239
+ timestamp: A.lastUpdated
240
240
  };
241
241
  }
242
242
  return {
243
- value: D || t,
243
+ value: _ || t,
244
244
  source: "default",
245
245
  timestamp: Date.now()
246
246
  };
247
247
  },
248
- [S, s, t, R]
248
+ [m, S, t, H]
249
249
  );
250
- et(() => {
251
- e.getState().setServerStateUpdate(S, b);
252
- }, [b, S]), et(() => e.getState().subscribeToPath(S, (c) => {
253
- if (c?.type === "SERVER_STATE_UPDATE") {
254
- const f = c.serverState;
255
- if (console.log("SERVER_STATE_UPDATE", c), f?.status === "success" && f.data !== void 0) {
256
- mt(S, { serverState: f });
257
- const M = typeof f.merge == "object" ? f.merge : f.merge === !0 ? {} : null, k = e.getState().getShadowValue(S), V = f.data;
258
- if (M && Array.isArray(k) && Array.isArray(V)) {
259
- const j = M.key, L = new Set(
260
- k.map((Z) => Z[j])
261
- ), G = V.filter((Z) => !L.has(Z[j]));
262
- G.length > 0 && G.forEach((Z) => {
263
- e.getState().insertShadowArrayElement(S, [], Z);
264
- const X = e.getState().getShadowMetadata(S, []);
265
- if (X?.arrayKeys) {
266
- const H = X.arrayKeys[X.arrayKeys.length - 1];
267
- if (H) {
268
- const O = H.split(".").slice(1);
269
- e.getState().setShadowMetadata(S, O, {
250
+ Q(() => {
251
+ a.getState().setServerStateUpdate(m, v);
252
+ }, [v, m]), Q(() => a.getState().subscribeToPath(m, (d) => {
253
+ if (d?.type === "SERVER_STATE_UPDATE") {
254
+ const y = d.serverState;
255
+ if (console.log("SERVER_STATE_UPDATE", d), y?.status === "success" && y.data !== void 0) {
256
+ ft(m, { serverState: y });
257
+ const M = typeof y.merge == "object" ? y.merge : y.merge === !0 ? {} : null, E = a.getState().getShadowValue(m), A = y.data;
258
+ if (M && Array.isArray(E) && Array.isArray(A)) {
259
+ const $ = M.key, x = new Set(
260
+ E.map((G) => G[$])
261
+ ), K = A.filter((G) => !x.has(G[$]));
262
+ K.length > 0 && K.forEach((G) => {
263
+ a.getState().insertShadowArrayElement(m, [], G);
264
+ const B = a.getState().getShadowMetadata(m, []);
265
+ if (B?.arrayKeys) {
266
+ const D = B.arrayKeys[B.arrayKeys.length - 1];
267
+ if (D) {
268
+ const I = D.split(".").slice(1);
269
+ a.getState().setShadowMetadata(m, I, {
270
270
  isDirty: !1,
271
271
  stateSource: "server",
272
- lastServerSync: f.timestamp || Date.now()
272
+ lastServerSync: y.timestamp || Date.now()
273
273
  });
274
- const v = e.getState().getShadowValue(H);
275
- v && typeof v == "object" && !Array.isArray(v) && Object.keys(v).forEach((w) => {
276
- const E = [...O, w];
277
- e.getState().setShadowMetadata(S, E, {
274
+ const T = a.getState().getShadowValue(D);
275
+ T && typeof T == "object" && !Array.isArray(T) && Object.keys(T).forEach((C) => {
276
+ const V = [...I, C];
277
+ a.getState().setShadowMetadata(m, V, {
278
278
  isDirty: !1,
279
279
  stateSource: "server",
280
- lastServerSync: f.timestamp || Date.now()
280
+ lastServerSync: y.timestamp || Date.now()
281
281
  });
282
282
  });
283
283
  }
284
284
  }
285
285
  });
286
286
  } else
287
- e.getState().initializeShadowState(S, V), yt(
288
- S,
287
+ a.getState().initializeShadowState(m, A), gt(
288
+ m,
289
289
  [],
290
- V,
291
- f.timestamp
290
+ A,
291
+ y.timestamp
292
292
  );
293
- const $ = e.getState().getShadowMetadata(S, []);
294
- e.getState().setShadowMetadata(S, [], {
295
- ...$,
293
+ const U = a.getState().getShadowMetadata(m, []);
294
+ a.getState().setShadowMetadata(m, [], {
295
+ ...U,
296
296
  stateSource: "server",
297
- lastServerSync: f.timestamp || Date.now(),
297
+ lastServerSync: y.timestamp || Date.now(),
298
298
  isDirty: !1
299
299
  });
300
300
  }
301
301
  }
302
- }), [S, tt]), et(() => {
303
- const d = e.getState().getShadowMetadata(S, []);
304
- if (d && d.stateSource)
302
+ }), [m, Y]), Q(() => {
303
+ const l = a.getState().getShadowMetadata(m, []);
304
+ if (l && l.stateSource)
305
305
  return;
306
- const c = ot(S);
307
- if (c?.defaultState !== void 0 || s !== void 0) {
308
- const f = c?.defaultState || s;
309
- c?.defaultState || mt(S, {
310
- defaultState: f
306
+ const d = at(m);
307
+ if (d?.defaultState !== void 0 || S !== void 0) {
308
+ const y = d?.defaultState || S;
309
+ d?.defaultState || ft(m, {
310
+ defaultState: y
311
311
  });
312
- const { value: D, source: M, timestamp: k } = tt();
313
- e.getState().initializeShadowState(S, D), e.getState().setShadowMetadata(S, [], {
312
+ const { value: _, source: M, timestamp: E } = Y();
313
+ a.getState().initializeShadowState(m, _), a.getState().setShadowMetadata(m, [], {
314
314
  stateSource: M,
315
- lastServerSync: M === "server" ? k : void 0,
315
+ lastServerSync: M === "server" ? E : void 0,
316
316
  isDirty: !1,
317
- baseServerState: M === "server" ? D : void 0
318
- }), vt(S);
317
+ baseServerState: M === "server" ? _ : void 0
318
+ }), mt(m);
319
319
  }
320
- }, [S, ...P || []]), dt(() => {
321
- B && mt(S, {
320
+ }, [m, ...s || []]), ct(() => {
321
+ J && ft(m, {
322
322
  formElements: g,
323
- defaultState: s,
324
- localStorage: m,
325
- middleware: Y.current?.middleware
323
+ defaultState: S,
324
+ localStorage: h,
325
+ middleware: j.current?.middleware
326
326
  });
327
- const d = `${S}////${p.current}`, c = e.getState().getShadowMetadata(S, []), f = c?.components || /* @__PURE__ */ new Map();
328
- return f.set(d, {
329
- forceUpdate: () => x({}),
330
- reactiveType: I ?? ["component", "deps"],
327
+ const l = `${m}////${u.current}`, d = a.getState().getShadowMetadata(m, []), y = d?.components || /* @__PURE__ */ new Map();
328
+ return y.set(l, {
329
+ forceUpdate: () => W({}),
330
+ reactiveType: f ?? ["component", "deps"],
331
331
  paths: /* @__PURE__ */ new Set(),
332
- depsFunction: y || void 0,
333
- deps: y ? y(e.getState().getShadowValue(S)) : [],
334
- prevDeps: y ? y(e.getState().getShadowValue(S)) : []
335
- }), e.getState().setShadowMetadata(S, [], {
336
- ...c,
337
- components: f
338
- }), x({}), () => {
339
- const D = e.getState().getShadowMetadata(S, []), M = D?.components?.get(d);
340
- M?.paths && M.paths.forEach((k) => {
341
- const $ = k.split(".").slice(1), j = e.getState().getShadowMetadata(S, $);
342
- j?.pathComponents && j.pathComponents.size === 0 && (delete j.pathComponents, e.getState().setShadowMetadata(S, $, j));
343
- }), D?.components && e.getState().setShadowMetadata(S, [], D);
332
+ depsFunction: w || void 0,
333
+ deps: w ? w(a.getState().getShadowValue(m)) : [],
334
+ prevDeps: w ? w(a.getState().getShadowValue(m)) : []
335
+ }), a.getState().setShadowMetadata(m, [], {
336
+ ...d,
337
+ components: y
338
+ }), W({}), () => {
339
+ const _ = a.getState().getShadowMetadata(m, []), M = _?.components?.get(l);
340
+ M?.paths && M.paths.forEach((E) => {
341
+ const U = E.split(".").slice(1), $ = a.getState().getShadowMetadata(m, U);
342
+ $?.pathComponents && $.pathComponents.size === 0 && (delete $.pathComponents, a.getState().setShadowMetadata(m, U, $));
343
+ }), _?.components && a.getState().setShadowMetadata(m, [], _);
344
344
  };
345
345
  }, []);
346
- const Q = z(null), r = (d, c, f) => {
347
- const D = [S, ...c].join(".");
348
- if (Array.isArray(c)) {
349
- const O = `${S}-${c.join(".")}`;
350
- q.current.add(O);
351
- }
352
- const M = e.getState(), k = M.getShadowMetadata(S, c), V = M.getShadowValue(D), $ = f.updateType === "insert" && rt(d) ? d({ state: V, uuid: nt() }) : rt(d) ? d(V) : d, L = {
346
+ const n = z(null), o = (l, d, y) => {
347
+ const _ = [m, ...d].join("."), M = a.getState(), E = M.getShadowMetadata(m, d), A = M.getShadowValue(_), U = y.updateType === "insert" && tt(l) ? l({ state: A, uuid: et() }) : tt(l) ? l(A) : l, x = {
353
348
  timeStamp: Date.now(),
354
- stateKey: S,
355
- path: c,
356
- updateType: f.updateType,
349
+ stateKey: m,
350
+ path: d,
351
+ updateType: y.updateType,
357
352
  status: "new",
358
- oldValue: V,
359
- newValue: $
353
+ oldValue: A,
354
+ newValue: U
360
355
  };
361
- switch (f.updateType) {
356
+ switch (y.updateType) {
362
357
  case "insert": {
363
- M.insertShadowArrayElement(S, c, L.newValue), M.markAsDirty(S, c, { bubble: !0 });
364
- const O = M.getShadowMetadata(S, c);
365
- if (O?.arrayKeys) {
366
- const v = O.arrayKeys[O.arrayKeys.length - 1];
367
- if (v) {
368
- const w = v.split(".").slice(1);
369
- M.markAsDirty(S, w, { bubble: !1 });
358
+ M.insertShadowArrayElement(m, d, x.newValue), M.markAsDirty(m, d, { bubble: !0 });
359
+ const D = M.getShadowMetadata(m, d);
360
+ if (D?.arrayKeys) {
361
+ const I = D.arrayKeys[D.arrayKeys.length - 1];
362
+ if (I) {
363
+ const T = I.split(".").slice(1);
364
+ M.markAsDirty(m, T, { bubble: !1 });
370
365
  }
371
366
  }
372
367
  break;
373
368
  }
374
369
  case "cut": {
375
- const O = c.slice(0, -1);
376
- M.removeShadowArrayElement(S, c), M.markAsDirty(S, O, { bubble: !0 });
370
+ const D = d.slice(0, -1);
371
+ M.removeShadowArrayElement(m, d), M.markAsDirty(m, D, { bubble: !0 });
377
372
  break;
378
373
  }
379
374
  case "update": {
380
- M.updateShadowAtPath(S, c, L.newValue), M.markAsDirty(S, c, { bubble: !0 });
375
+ M.updateShadowAtPath(m, d, x.newValue), M.markAsDirty(m, d, { bubble: !0 });
381
376
  break;
382
377
  }
383
378
  }
384
- if (f.sync !== !1 && Q.current && Q.current.connected && Q.current.updateState({ operation: L }), k?.signals && k.signals.length > 0) {
385
- const O = f.updateType === "cut" ? null : $;
386
- k.signals.forEach(({ parentId: v, position: w, effect: E }) => {
387
- const A = document.querySelector(`[data-parent-id="${v}"]`);
388
- if (A) {
389
- const C = Array.from(A.childNodes);
390
- if (C[w]) {
391
- let U = O;
392
- if (E && O !== null)
379
+ if (y.sync !== !1 && n.current && n.current.connected && n.current.updateState({ operation: x }), E?.signals && E.signals.length > 0) {
380
+ const D = y.updateType === "cut" ? null : U;
381
+ E.signals.forEach(({ parentId: I, position: T, effect: C }) => {
382
+ const V = document.querySelector(`[data-parent-id="${I}"]`);
383
+ if (V) {
384
+ const P = Array.from(V.childNodes);
385
+ if (P[T]) {
386
+ let O = D;
387
+ if (C && D !== null)
393
388
  try {
394
- U = new Function(
389
+ O = new Function(
395
390
  "state",
396
- `return (${E})(state)`
397
- )(O);
391
+ `return (${C})(state)`
392
+ )(D);
398
393
  } catch (N) {
399
394
  console.error("Error evaluating effect function:", N);
400
395
  }
401
- U != null && typeof U == "object" && (U = JSON.stringify(U)), C[w].textContent = String(U ?? "");
396
+ O != null && typeof O == "object" && (O = JSON.stringify(O)), P[T].textContent = String(O ?? "");
402
397
  }
403
398
  }
404
399
  });
405
400
  }
406
- if (f.updateType === "insert" && k?.mapWrappers && k.mapWrappers.length > 0) {
407
- const O = M.getShadowMetadata(S, c)?.arrayKeys || [], v = O[O.length - 1], w = M.getShadowValue(v), E = M.getShadowValue(
408
- [S, ...c].join(".")
401
+ if (y.updateType === "insert" && E?.mapWrappers && E.mapWrappers.length > 0) {
402
+ const D = M.getShadowMetadata(m, d)?.arrayKeys || [], I = D[D.length - 1], T = M.getShadowValue(I), C = M.getShadowValue(
403
+ [m, ...d].join(".")
409
404
  );
410
- if (!v || w === void 0) return;
411
- k.mapWrappers.forEach((A) => {
412
- let C = !0, U = -1;
413
- if (A.meta?.transforms && A.meta.transforms.length > 0) {
414
- for (const N of A.meta.transforms)
415
- if (N.type === "filter" && !N.fn(w, -1)) {
416
- C = !1;
405
+ if (!I || T === void 0) return;
406
+ E.mapWrappers.forEach((V) => {
407
+ let P = !0, O = -1;
408
+ if (V.meta?.transforms && V.meta.transforms.length > 0) {
409
+ for (const N of V.meta.transforms)
410
+ if (N.type === "filter" && !N.fn(T, -1)) {
411
+ P = !1;
417
412
  break;
418
413
  }
419
- if (C) {
420
- const N = pt(
421
- S,
422
- c,
423
- A.meta.transforms
424
- ), J = A.meta.transforms.find(
414
+ if (P) {
415
+ const N = ht(
416
+ m,
417
+ d,
418
+ V.meta.transforms
419
+ ), q = V.meta.transforms.find(
425
420
  (F) => F.type === "sort"
426
421
  );
427
- if (J) {
428
- const F = N.map((K) => ({
429
- key: K,
430
- value: M.getShadowValue(K)
422
+ if (q) {
423
+ const F = N.map((Z) => ({
424
+ key: Z,
425
+ value: M.getShadowValue(Z)
431
426
  }));
432
- F.push({ key: v, value: w }), F.sort((K, st) => J.fn(K.value, st.value)), U = F.findIndex(
433
- (K) => K.key === v
427
+ F.push({ key: I, value: T }), F.sort((Z, rt) => q.fn(Z.value, rt.value)), O = F.findIndex(
428
+ (Z) => Z.key === I
434
429
  );
435
430
  } else
436
- U = N.length;
431
+ O = N.length;
437
432
  }
438
433
  } else
439
- C = !0, U = O.length - 1;
440
- if (C && A.containerRef && A.containerRef.isConnected) {
434
+ P = !0, O = D.length - 1;
435
+ if (P && V.containerRef && V.containerRef.isConnected) {
441
436
  const N = document.createElement("div");
442
- N.setAttribute("data-item-path", v);
443
- const J = Array.from(A.containerRef.children);
444
- U >= 0 && U < J.length ? A.containerRef.insertBefore(
437
+ N.setAttribute("data-item-path", I);
438
+ const q = Array.from(V.containerRef.children);
439
+ O >= 0 && O < q.length ? V.containerRef.insertBefore(
445
440
  N,
446
- J[U]
447
- ) : A.containerRef.appendChild(N);
448
- const F = Vt(N), K = nt(), st = v.split(".").slice(1), kt = A.rebuildStateShape({
449
- path: A.path,
450
- currentState: E,
451
- componentId: A.componentId,
452
- meta: A.meta
441
+ q[O]
442
+ ) : V.containerRef.appendChild(N);
443
+ const F = Mt(N), Z = et(), rt = I.split(".").slice(1), Ct = V.rebuildStateShape({
444
+ path: V.path,
445
+ currentState: C,
446
+ componentId: V.componentId,
447
+ meta: V.meta
453
448
  });
454
449
  F.render(
455
- ut(wt, {
456
- stateKey: S,
457
- itemComponentId: K,
458
- itemPath: st,
459
- localIndex: U,
460
- arraySetter: kt,
461
- rebuildStateShape: A.rebuildStateShape,
462
- renderFn: A.mapFn
450
+ it(yt, {
451
+ stateKey: m,
452
+ itemComponentId: Z,
453
+ itemPath: rt,
454
+ localIndex: O,
455
+ arraySetter: Ct,
456
+ rebuildStateShape: V.rebuildStateShape,
457
+ renderFn: V.mapFn
463
458
  })
464
459
  );
465
460
  }
466
461
  });
467
462
  }
468
- if (f.updateType === "cut") {
469
- const O = c.slice(0, -1), v = M.getShadowMetadata(S, O);
470
- v?.mapWrappers && v.mapWrappers.length > 0 && v.mapWrappers.forEach((w) => {
471
- if (w.containerRef && w.containerRef.isConnected) {
472
- const E = w.containerRef.querySelector(
473
- `[data-item-path="${D}"]`
463
+ if (y.updateType === "cut") {
464
+ const D = d.slice(0, -1), I = M.getShadowMetadata(m, D);
465
+ I?.mapWrappers && I.mapWrappers.length > 0 && I.mapWrappers.forEach((T) => {
466
+ if (T.containerRef && T.containerRef.isConnected) {
467
+ const C = T.containerRef.querySelector(
468
+ `[data-item-path="${_}"]`
474
469
  );
475
- E && E.remove();
470
+ C && C.remove();
476
471
  }
477
472
  });
478
473
  }
479
- const Z = e.getState().getShadowValue(S), X = e.getState().getShadowMetadata(S, []), H = /* @__PURE__ */ new Set();
480
- if (!X?.components)
481
- return Z;
482
- if (f.updateType === "update") {
483
- let O = [...c];
484
- for (; ; ) {
485
- const v = M.getShadowMetadata(S, O);
486
- if (v?.pathComponents && v.pathComponents.forEach((w) => {
487
- if (H.has(w))
488
- return;
489
- const E = X.components?.get(w);
490
- E && ((Array.isArray(E.reactiveType) ? E.reactiveType : [E.reactiveType || "component"]).includes("none") || (E.forceUpdate(), H.add(w)));
491
- }), O.length === 0)
492
- break;
493
- O.pop();
494
- }
495
- $ && typeof $ == "object" && !It($) && V && typeof V == "object" && !It(V) && Et($, V).forEach((w) => {
496
- const E = w.split("."), A = [...c, ...E], C = M.getShadowMetadata(S, A);
497
- C?.pathComponents && C.pathComponents.forEach((U) => {
498
- if (H.has(U))
499
- return;
500
- const N = X.components?.get(U);
501
- N && ((Array.isArray(N.reactiveType) ? N.reactiveType : [N.reactiveType || "component"]).includes("none") || (N.forceUpdate(), H.add(U)));
474
+ const G = M.getShadowMetadata(m, []), B = /* @__PURE__ */ new Set();
475
+ if (G?.components) {
476
+ if (y.updateType === "update") {
477
+ let D = [...d];
478
+ for (; ; ) {
479
+ const I = M.getShadowMetadata(m, D);
480
+ if (I?.pathComponents && I.pathComponents.forEach((T) => {
481
+ if (B.has(T))
482
+ return;
483
+ const C = G.components?.get(T);
484
+ C && ((Array.isArray(C.reactiveType) ? C.reactiveType : [C.reactiveType || "component"]).includes("none") || (C.forceUpdate(), B.add(T)));
485
+ }), D.length === 0)
486
+ break;
487
+ D.pop();
488
+ }
489
+ U && typeof U == "object" && !pt(U) && A && typeof A == "object" && !pt(A) && Tt(U, A).forEach((T) => {
490
+ const C = T.split("."), V = [...d, ...C], P = M.getShadowMetadata(m, V);
491
+ P?.pathComponents && P.pathComponents.forEach((O) => {
492
+ if (B.has(O))
493
+ return;
494
+ const N = G.components?.get(O);
495
+ N && ((Array.isArray(N.reactiveType) ? N.reactiveType : [N.reactiveType || "component"]).includes("none") || (N.forceUpdate(), B.add(O)));
496
+ });
502
497
  });
503
- });
504
- } else if (f.updateType === "insert" || f.updateType === "cut") {
505
- const O = f.updateType === "insert" ? c : c.slice(0, -1), v = M.getShadowMetadata(S, O);
506
- if (v?.signals && v.signals.length > 0) {
507
- const w = [S, ...O].join("."), E = M.getShadowValue(w);
508
- v.signals.forEach(({ parentId: A, position: C, effect: U }) => {
509
- const N = document.querySelector(
510
- `[data-parent-id="${A}"]`
511
- );
512
- if (N) {
513
- const J = Array.from(N.childNodes);
514
- if (J[C]) {
515
- let F = E;
516
- if (U)
517
- try {
518
- F = new Function(
519
- "state",
520
- `return (${U})(state)`
521
- )(E);
522
- } catch (K) {
523
- console.error("Error evaluating effect function:", K), F = E;
524
- }
525
- F != null && typeof F == "object" && (F = JSON.stringify(F)), J[C].textContent = String(F ?? "");
498
+ } else if (y.updateType === "insert" || y.updateType === "cut") {
499
+ const D = y.updateType === "insert" ? d : d.slice(0, -1), I = M.getShadowMetadata(m, D);
500
+ if (I?.signals && I.signals.length > 0) {
501
+ const T = [m, ...D].join("."), C = M.getShadowValue(T);
502
+ I.signals.forEach(({ parentId: V, position: P, effect: O }) => {
503
+ const N = document.querySelector(
504
+ `[data-parent-id="${V}"]`
505
+ );
506
+ if (N) {
507
+ const q = Array.from(N.childNodes);
508
+ if (q[P]) {
509
+ let F = C;
510
+ if (O)
511
+ try {
512
+ F = new Function(
513
+ "state",
514
+ `return (${O})(state)`
515
+ )(C);
516
+ } catch (Z) {
517
+ console.error("Error evaluating effect function:", Z), F = C;
518
+ }
519
+ F != null && typeof F == "object" && (F = JSON.stringify(F)), q[P].textContent = String(F ?? "");
520
+ }
526
521
  }
522
+ });
523
+ }
524
+ I?.pathComponents && I.pathComponents.forEach((T) => {
525
+ if (!B.has(T)) {
526
+ const C = G.components?.get(T);
527
+ C && (C.forceUpdate(), B.add(T));
527
528
  }
528
529
  });
529
530
  }
530
- v?.pathComponents && v.pathComponents.forEach((w) => {
531
- if (!H.has(w)) {
532
- const E = X.components?.get(w);
533
- E && (E.forceUpdate(), H.add(w));
531
+ G.components.forEach((D, I) => {
532
+ if (B.has(I))
533
+ return;
534
+ const T = Array.isArray(D.reactiveType) ? D.reactiveType : [D.reactiveType || "component"];
535
+ if (T.includes("all")) {
536
+ D.forceUpdate(), B.add(I);
537
+ return;
538
+ }
539
+ if (T.includes("deps") && D.depsFunction) {
540
+ const C = M.getShadowValue(m), V = D.depsFunction(C);
541
+ let P = !1;
542
+ V === !0 ? P = !0 : Array.isArray(V) && (ot(D.prevDeps, V) || (D.prevDeps = V, P = !0)), P && (D.forceUpdate(), B.add(I));
534
543
  }
544
+ }), B.clear(), Nt(m, x), jt(
545
+ U,
546
+ m,
547
+ j.current,
548
+ H
549
+ ), j.current?.middleware && j.current.middleware({
550
+ update: x
535
551
  });
536
552
  }
537
- return X.components.forEach((O, v) => {
538
- if (H.has(v))
539
- return;
540
- const w = Array.isArray(O.reactiveType) ? O.reactiveType : [O.reactiveType || "component"];
541
- if (w.includes("all")) {
542
- O.forceUpdate(), H.add(v);
543
- return;
544
- }
545
- if (w.includes("deps") && O.depsFunction) {
546
- const E = M.getShadowValue(S), A = O.depsFunction(E);
547
- let C = !1;
548
- A === !0 ? C = !0 : Array.isArray(A) && (ct(O.prevDeps, A) || (O.prevDeps = A, C = !0)), C && (O.forceUpdate(), H.add(v));
549
- }
550
- }), H.clear(), jt(S, (O) => {
551
- const v = [...O ?? [], L], w = /* @__PURE__ */ new Map();
552
- return v.forEach((E) => {
553
- const A = `${E.stateKey}:${JSON.stringify(E.path)}`, C = w.get(A);
554
- C ? (C.timeStamp = Math.max(C.timeStamp, E.timeStamp), C.newValue = E.newValue, C.oldValue = C.oldValue ?? E.oldValue, C.updateType = E.updateType) : w.set(A, { ...E });
555
- }), Array.from(w.values());
556
- }), Wt(
557
- $,
558
- S,
559
- Y.current,
560
- R
561
- ), Y.current?.middleware && Y.current.middleware({
562
- updateLog: W,
563
- update: L
564
- }), Z;
565
553
  };
566
- e.getState().initialStateGlobal[S] || Ct(S, t);
567
- const n = St(() => Pt(
568
- S,
569
- r,
570
- p.current,
571
- R
572
- ), [S, R]), i = o, u = Y.current?.syncOptions;
573
- return i && (Q.current = i(
574
- n,
575
- u ?? {}
576
- )), n;
554
+ a.getState().initialStateGlobal[m] || Vt(m, t);
555
+ const i = dt(() => At(
556
+ m,
557
+ o,
558
+ u.current,
559
+ H
560
+ ), [m, H]), c = R, p = j.current?.syncOptions;
561
+ return c && (n.current = c(
562
+ i,
563
+ p ?? {}
564
+ )), i;
577
565
  }
578
- function Bt(t) {
566
+ function Wt(t) {
579
567
  return !t || t.length === 0 ? "" : t.map(
580
- (a) => (
568
+ (r) => (
581
569
  // Safely stringify dependencies. An empty array becomes '[]'.
582
- `${a.type}${JSON.stringify(a.dependencies || [])}`
570
+ `${r.type}${JSON.stringify(r.dependencies || [])}`
583
571
  )
584
572
  ).join("");
585
573
  }
586
- const pt = (t, a, m) => {
587
- let g = e.getState().getShadowMetadata(t, a)?.arrayKeys || [];
588
- if (!m || m.length === 0)
574
+ const ht = (t, r, h) => {
575
+ let g = a.getState().getShadowMetadata(t, r)?.arrayKeys || [];
576
+ if (!h || h.length === 0)
589
577
  return g;
590
- let y = g.map((I) => ({
591
- key: I,
592
- value: e.getState().getShadowValue(I)
578
+ let w = g.map((f) => ({
579
+ key: f,
580
+ value: a.getState().getShadowValue(f)
593
581
  }));
594
- for (const I of m)
595
- I.type === "filter" ? y = y.filter(
596
- ({ value: T }, s) => I.fn(T, s)
597
- ) : I.type === "sort" && y.sort((T, s) => I.fn(T.value, s.value));
598
- return y.map(({ key: I }) => I);
599
- }, Tt = (t, a, m) => {
600
- const g = `${t}////${a}`, { addPathComponent: y, getShadowMetadata: I } = e.getState(), s = I(t, [])?.components?.get(g);
601
- !s || s.reactiveType === "none" || !(Array.isArray(s.reactiveType) ? s.reactiveType : [s.reactiveType]).includes("component") || y(t, m, g);
602
- }, ft = (t, a, m) => {
603
- const g = e.getState(), y = g.getShadowMetadata(t, []), I = /* @__PURE__ */ new Set();
604
- y?.components && y.components.forEach((s, l) => {
605
- (Array.isArray(s.reactiveType) ? s.reactiveType : [s.reactiveType || "component"]).includes("all") && (s.forceUpdate(), I.add(l));
606
- }), g.getShadowMetadata(t, [...a, "getSelected"])?.pathComponents?.forEach((s) => {
607
- y?.components?.get(s)?.forceUpdate();
582
+ for (const f of h)
583
+ f.type === "filter" ? w = w.filter(
584
+ ({ value: b }, S) => f.fn(b, S)
585
+ ) : f.type === "sort" && w.sort((b, S) => f.fn(b.value, S.value));
586
+ return w.map(({ key: f }) => f);
587
+ }, wt = (t, r, h) => {
588
+ const g = `${t}////${r}`, { addPathComponent: w, getShadowMetadata: f } = a.getState(), S = f(t, [])?.components?.get(g);
589
+ !S || S.reactiveType === "none" || !(Array.isArray(S.reactiveType) ? S.reactiveType : [S.reactiveType]).includes("component") || w(t, h, g);
590
+ }, lt = (t, r, h) => {
591
+ const g = a.getState(), w = g.getShadowMetadata(t, []), f = /* @__PURE__ */ new Set();
592
+ w?.components && w.components.forEach((S, e) => {
593
+ (Array.isArray(S.reactiveType) ? S.reactiveType : [S.reactiveType || "component"]).includes("all") && (S.forceUpdate(), f.add(e));
594
+ }), g.getShadowMetadata(t, [...r, "getSelected"])?.pathComponents?.forEach((S) => {
595
+ w?.components?.get(S)?.forceUpdate();
608
596
  });
609
- const T = g.getShadowMetadata(t, a);
610
- for (let s of T?.arrayKeys || []) {
611
- const l = s + ".selected", P = g.getShadowMetadata(
597
+ const b = g.getShadowMetadata(t, r);
598
+ for (let S of b?.arrayKeys || []) {
599
+ const e = S + ".selected", s = g.getShadowMetadata(
612
600
  t,
613
- l.split(".").slice(1)
601
+ e.split(".").slice(1)
614
602
  );
615
- s == m && P?.pathComponents?.forEach((b) => {
616
- y?.components?.get(b)?.forceUpdate();
603
+ S == h && s?.pathComponents?.forEach((v) => {
604
+ w?.components?.get(v)?.forceUpdate();
617
605
  });
618
606
  }
619
607
  };
620
- function Pt(t, a, m, g) {
621
- const y = /* @__PURE__ */ new Map();
622
- let I = 0;
623
- const T = (b) => {
624
- const o = b.join(".");
625
- for (const [h] of y)
626
- (h === o || h.startsWith(o + ".")) && y.delete(h);
627
- I++;
628
- };
629
- function s({
630
- currentState: b,
631
- path: o = [],
632
- meta: h,
633
- componentId: _
608
+ function At(t, r, h, g) {
609
+ const w = /* @__PURE__ */ new Map();
610
+ function f({
611
+ path: e = [],
612
+ meta: s,
613
+ componentId: v
634
614
  }) {
635
- const x = o.map(String).join("."), R = [t, ...o].join(".");
636
- b = e.getState().getShadowValue(R, h?.validIds);
637
- const B = function() {
638
- return e().getShadowValue(t, o);
639
- }, S = {
640
- apply(q, p, Y) {
615
+ const R = s ? JSON.stringify(s.validIds || s.transforms) : "", L = e.join(".") + ":" + R, k = [t, ...e].join(".");
616
+ if (w.has(L))
617
+ return w.get(L);
618
+ const W = function() {
619
+ return a().getShadowValue(t, e);
620
+ }, H = {
621
+ apply(m, u, j) {
641
622
  },
642
- get(q, p) {
643
- if (p === "_rebuildStateShape")
644
- return s;
645
- if (Object.getOwnPropertyNames(l).includes(p) && o.length === 0)
646
- return l[p];
647
- if (p === "getDifferences")
623
+ get(m, u) {
624
+ if (u === "_rebuildStateShape")
625
+ return f;
626
+ if (Object.getOwnPropertyNames(b).includes(u) && e.length === 0)
627
+ return b[u];
628
+ if (u === "getDifferences")
648
629
  return () => {
649
- const r = e.getState().getShadowMetadata(t, []), n = e.getState().getShadowValue(t);
630
+ const n = a.getState().getShadowMetadata(t, []), o = a.getState().getShadowValue(t);
650
631
  let i;
651
- return r?.stateSource === "server" && r.baseServerState ? i = r.baseServerState : i = e.getState().initialStateGlobal[t], Et(n, i);
632
+ return n?.stateSource === "server" && n.baseServerState ? i = n.baseServerState : i = a.getState().initialStateGlobal[t], Tt(o, i);
652
633
  };
653
- if (p === "sync" && o.length === 0)
634
+ if (u === "sync" && e.length === 0)
654
635
  return async function() {
655
- const r = e.getState().getInitialOptions(t), n = r?.sync;
656
- if (!n)
636
+ const n = a.getState().getInitialOptions(t), o = n?.sync;
637
+ if (!o)
657
638
  return console.error(`No mutation defined for state key "${t}"`), { success: !1, error: "No mutation defined" };
658
- const i = e.getState().getShadowValue(t, []), u = r?.validation?.key;
639
+ const i = a.getState().getShadowValue(t, []), c = n?.validation?.key;
659
640
  try {
660
- const d = await n.action(i);
661
- if (d && !d.success && d.errors, d?.success) {
662
- const c = e.getState().getShadowMetadata(t, []);
663
- e.getState().setShadowMetadata(t, [], {
664
- ...c,
641
+ const p = await o.action(i);
642
+ if (p && !p.success && p.errors, p?.success) {
643
+ const l = a.getState().getShadowMetadata(t, []);
644
+ a.getState().setShadowMetadata(t, [], {
645
+ ...l,
665
646
  isDirty: !1,
666
647
  lastServerSync: Date.now(),
667
648
  stateSource: "server",
668
649
  baseServerState: i
669
650
  // Update base server state
670
- }), n.onSuccess && n.onSuccess(d.data);
671
- } else !d?.success && n.onError && n.onError(d.error);
672
- return d;
673
- } catch (d) {
674
- return n.onError && n.onError(d), { success: !1, error: d };
651
+ }), o.onSuccess && o.onSuccess(p.data);
652
+ } else !p?.success && o.onError && o.onError(p.error);
653
+ return p;
654
+ } catch (p) {
655
+ return o.onError && o.onError(p), { success: !1, error: p };
675
656
  }
676
657
  };
677
- if (p === "_status" || p === "getStatus") {
678
- const r = () => {
679
- const n = e.getState().getShadowMetadata(t, o), i = e.getState().getShadowValue(R);
680
- return n?.isDirty === !0 ? "dirty" : n?.isDirty === !1 || n?.stateSource === "server" ? "synced" : n?.stateSource === "localStorage" ? "restored" : n?.stateSource === "default" ? "fresh" : e.getState().getShadowMetadata(t, [])?.stateSource === "server" && !n?.isDirty ? "synced" : i !== void 0 && !n ? "fresh" : "unknown";
658
+ if (u === "_status" || u === "getStatus") {
659
+ const n = () => {
660
+ const o = a.getState().getShadowMetadata(t, e), i = a.getState().getShadowValue(k);
661
+ return o?.isDirty === !0 ? "dirty" : o?.isDirty === !1 || o?.stateSource === "server" ? "synced" : o?.stateSource === "localStorage" ? "restored" : o?.stateSource === "default" ? "fresh" : a.getState().getShadowMetadata(t, [])?.stateSource === "server" && !o?.isDirty ? "synced" : i !== void 0 && !o ? "fresh" : "unknown";
681
662
  };
682
- return p === "_status" ? r() : r;
663
+ return u === "_status" ? n() : n;
683
664
  }
684
- if (p === "removeStorage")
665
+ if (u === "removeStorage")
685
666
  return () => {
686
- const r = e.getState().initialStateGlobal[t], n = ot(t), i = rt(n?.localStorage?.key) ? n.localStorage.key(r) : n?.localStorage?.key, u = `${g}-${t}-${i}`;
687
- u && localStorage.removeItem(u);
667
+ const n = a.getState().initialStateGlobal[t], o = at(t), i = tt(o?.localStorage?.key) ? o.localStorage.key(n) : o?.localStorage?.key, c = `${g}-${t}-${i}`;
668
+ c && localStorage.removeItem(c);
688
669
  };
689
- if (p === "showValidationErrors")
670
+ if (u === "showValidationErrors")
690
671
  return () => {
691
- const r = e.getState().getShadowMetadata(t, o);
692
- return r?.validation?.status === "VALIDATION_FAILED" && r.validation.message ? [r.validation.message] : [];
672
+ const n = a.getState().getShadowMetadata(t, e);
673
+ return n?.validation?.status === "VALIDATION_FAILED" && n.validation.message ? [n.validation.message] : [];
693
674
  };
694
- if (Array.isArray(b)) {
695
- if (p === "getSelected")
696
- return () => {
697
- const r = t + "." + o.join(".");
698
- Tt(t, _, [
699
- ...o,
700
- "getSelected"
701
- ]);
702
- const n = e.getState().selectedIndicesMap;
703
- if (!n || !n.has(r))
704
- return;
705
- const i = n.get(r);
706
- if (h?.validIds && !h.validIds.includes(i))
707
- return;
708
- const u = e.getState().getShadowValue(i);
709
- if (u)
710
- return s({
711
- currentState: u,
712
- path: i.split(".").slice(1),
713
- componentId: _
714
- });
715
- };
716
- if (p === "getSelectedIndex")
717
- return () => e.getState().getSelectedIndex(
718
- t + "." + o.join("."),
719
- h?.validIds
675
+ if (u === "getSelected")
676
+ return () => {
677
+ const n = t + "." + e.join(".");
678
+ wt(t, v, [
679
+ ...e,
680
+ "getSelected"
681
+ ]);
682
+ const o = a.getState().selectedIndicesMap;
683
+ if (!o || !o.has(n))
684
+ return;
685
+ const i = o.get(n);
686
+ if (!(s?.validIds && !s.validIds.includes(i) || !a.getState().getShadowValue(i)))
687
+ return f({
688
+ path: i.split(".").slice(1),
689
+ componentId: v
690
+ });
691
+ };
692
+ if (u === "getSelectedIndex")
693
+ return () => a.getState().getSelectedIndex(
694
+ t + "." + e.join("."),
695
+ s?.validIds
696
+ );
697
+ if (u === "clearSelected")
698
+ return lt(t, e), () => {
699
+ a.getState().clearSelectedIndex({
700
+ arrayKey: t + "." + e.join(".")
701
+ });
702
+ };
703
+ if (u === "useVirtualView")
704
+ return (n) => {
705
+ const {
706
+ itemHeight: o = 50,
707
+ overscan: i = 6,
708
+ stickToBottom: c = !1,
709
+ scrollStickTolerance: p = 75
710
+ } = n, l = z(null), [d, y] = X({
711
+ startIndex: 0,
712
+ endIndex: 10
713
+ }), [_, M] = X({}), E = z(!0), A = z({
714
+ isUserScrolling: !1,
715
+ lastScrollTop: 0,
716
+ scrollUpCount: 0,
717
+ isNearBottom: !0
718
+ }), U = z(
719
+ /* @__PURE__ */ new Map()
720
720
  );
721
- if (p === "clearSelected")
722
- return ft(t, o), () => {
723
- e.getState().clearSelectedIndex({
724
- arrayKey: t + "." + o.join(".")
721
+ ct(() => {
722
+ if (!c || !l.current || A.current.isUserScrolling)
723
+ return;
724
+ const I = l.current;
725
+ I.scrollTo({
726
+ top: I.scrollHeight,
727
+ behavior: E.current ? "instant" : "smooth"
725
728
  });
726
- };
727
- if (p === "useVirtualView")
728
- return (r) => {
729
- const {
730
- itemHeight: n = 50,
731
- overscan: i = 6,
732
- stickToBottom: u = !1,
733
- scrollStickTolerance: d = 75
734
- } = r, c = z(null), [f, D] = at({
735
- startIndex: 0,
736
- endIndex: 10
737
- }), [M, k] = at({}), V = z(!0), $ = z({
738
- isUserScrolling: !1,
739
- lastScrollTop: 0,
740
- scrollUpCount: 0,
741
- isNearBottom: !0
742
- }), j = z(
743
- /* @__PURE__ */ new Map()
744
- );
745
- dt(() => {
746
- if (!u || !c.current || $.current.isUserScrolling)
747
- return;
748
- const v = c.current;
749
- v.scrollTo({
750
- top: v.scrollHeight,
751
- behavior: V.current ? "instant" : "smooth"
752
- });
753
- }, [M, u]);
754
- const L = e.getState().getShadowMetadata(t, o)?.arrayKeys || [], { totalHeight: G, itemOffsets: Z } = St(() => {
755
- let v = 0;
756
- const w = /* @__PURE__ */ new Map();
757
- return (e.getState().getShadowMetadata(t, o)?.arrayKeys || []).forEach((A) => {
758
- const C = A.split(".").slice(1), U = e.getState().getShadowMetadata(t, C)?.virtualizer?.itemHeight || n;
759
- w.set(A, {
760
- height: U,
761
- offset: v
762
- }), v += U;
763
- }), j.current = w, { totalHeight: v, itemOffsets: w };
764
- }, [L.length, n]);
765
- dt(() => {
766
- if (u && L.length > 0 && c.current && !$.current.isUserScrolling && V.current) {
767
- const v = c.current, w = () => {
768
- if (v.clientHeight > 0) {
769
- const E = Math.ceil(
770
- v.clientHeight / n
771
- ), A = L.length - 1, C = Math.max(
772
- 0,
773
- A - E - i
774
- );
775
- D({ startIndex: C, endIndex: A }), requestAnimationFrame(() => {
776
- H("instant"), V.current = !1;
777
- });
778
- } else
779
- requestAnimationFrame(w);
780
- };
781
- w();
782
- }
783
- }, [L.length, u, n, i]);
784
- const X = lt(() => {
785
- const v = c.current;
786
- if (!v) return;
787
- const w = v.scrollTop, { scrollHeight: E, clientHeight: A } = v, C = $.current, U = E - (w + A), N = C.isNearBottom;
788
- C.isNearBottom = U <= d, w < C.lastScrollTop ? (C.scrollUpCount++, C.scrollUpCount > 3 && N && (C.isUserScrolling = !0, console.log("User scrolled away from bottom"))) : C.isNearBottom && (C.isUserScrolling = !1, C.scrollUpCount = 0), C.lastScrollTop = w;
789
- let J = 0;
790
- for (let F = 0; F < L.length; F++) {
791
- const K = L[F], st = j.current.get(K);
792
- if (st && st.offset + st.height > w) {
793
- J = F;
794
- break;
795
- }
796
- }
797
- if (J !== f.startIndex) {
798
- const F = Math.ceil(A / n);
799
- D({
800
- startIndex: Math.max(0, J - i),
801
- endIndex: Math.min(
802
- L.length - 1,
803
- J + F + i
804
- )
805
- });
806
- }
807
- }, [
808
- L.length,
809
- f.startIndex,
810
- n,
811
- i,
812
- d
813
- ]);
814
- et(() => {
815
- const v = c.current;
816
- if (!(!v || !u))
817
- return v.addEventListener("scroll", X, {
818
- passive: !0
819
- }), () => {
820
- v.removeEventListener("scroll", X);
821
- };
822
- }, [X, u]);
823
- const H = lt(
824
- (v = "smooth") => {
825
- const w = c.current;
826
- if (!w) return;
827
- $.current.isUserScrolling = !1, $.current.isNearBottom = !0, $.current.scrollUpCount = 0;
828
- const E = () => {
829
- const A = (C = 0) => {
830
- if (C > 5) return;
831
- const U = w.scrollHeight, N = w.scrollTop, J = w.clientHeight;
832
- N + J >= U - 1 || (w.scrollTo({
833
- top: U,
834
- behavior: v
835
- }), setTimeout(() => {
836
- const F = w.scrollHeight, K = w.scrollTop;
837
- (F !== U || K + J < F - 1) && A(C + 1);
838
- }, 50));
839
- };
840
- A();
841
- };
842
- "requestIdleCallback" in window ? requestIdleCallback(E, { timeout: 100 }) : requestAnimationFrame(() => {
843
- requestAnimationFrame(E);
844
- });
845
- },
846
- []
847
- );
848
- return et(() => {
849
- if (!u || !c.current) return;
850
- const v = c.current, w = $.current;
851
- let E;
852
- const A = () => {
853
- clearTimeout(E), E = setTimeout(() => {
854
- !w.isUserScrolling && w.isNearBottom && H(
855
- V.current ? "instant" : "smooth"
729
+ }, [_, c]);
730
+ const $ = a.getState().getShadowMetadata(t, e)?.arrayKeys || [], { totalHeight: x, itemOffsets: K } = dt(() => {
731
+ let I = 0;
732
+ const T = /* @__PURE__ */ new Map();
733
+ return (a.getState().getShadowMetadata(t, e)?.arrayKeys || []).forEach((V) => {
734
+ const P = V.split(".").slice(1), O = a.getState().getShadowMetadata(t, P)?.virtualizer?.itemHeight || o;
735
+ T.set(V, {
736
+ height: O,
737
+ offset: I
738
+ }), I += O;
739
+ }), U.current = T, { totalHeight: I, itemOffsets: T };
740
+ }, [$.length, o]);
741
+ ct(() => {
742
+ if (c && $.length > 0 && l.current && !A.current.isUserScrolling && E.current) {
743
+ const I = l.current, T = () => {
744
+ if (I.clientHeight > 0) {
745
+ const C = Math.ceil(
746
+ I.clientHeight / o
747
+ ), V = $.length - 1, P = Math.max(
748
+ 0,
749
+ V - C - i
856
750
  );
857
- }, 100);
858
- }, C = new MutationObserver(() => {
859
- w.isUserScrolling || A();
860
- });
861
- C.observe(v, {
862
- childList: !0,
863
- subtree: !0,
864
- attributes: !0,
865
- attributeFilter: ["style", "class"]
866
- // More specific than just 'height'
751
+ y({ startIndex: P, endIndex: V }), requestAnimationFrame(() => {
752
+ B("instant"), E.current = !1;
753
+ });
754
+ } else
755
+ requestAnimationFrame(T);
756
+ };
757
+ T();
758
+ }
759
+ }, [$.length, c, o, i]);
760
+ const G = st(() => {
761
+ const I = l.current;
762
+ if (!I) return;
763
+ const T = I.scrollTop, { scrollHeight: C, clientHeight: V } = I, P = A.current, O = C - (T + V), N = P.isNearBottom;
764
+ P.isNearBottom = O <= p, T < P.lastScrollTop ? (P.scrollUpCount++, P.scrollUpCount > 3 && N && (P.isUserScrolling = !0, console.log("User scrolled away from bottom"))) : P.isNearBottom && (P.isUserScrolling = !1, P.scrollUpCount = 0), P.lastScrollTop = T;
765
+ let q = 0;
766
+ for (let F = 0; F < $.length; F++) {
767
+ const Z = $[F], rt = U.current.get(Z);
768
+ if (rt && rt.offset + rt.height > T) {
769
+ q = F;
770
+ break;
771
+ }
772
+ }
773
+ if (q !== d.startIndex) {
774
+ const F = Math.ceil(V / o);
775
+ y({
776
+ startIndex: Math.max(0, q - i),
777
+ endIndex: Math.min(
778
+ $.length - 1,
779
+ q + F + i
780
+ )
867
781
  });
868
- const U = (N) => {
869
- N.target instanceof HTMLImageElement && !w.isUserScrolling && A();
782
+ }
783
+ }, [
784
+ $.length,
785
+ d.startIndex,
786
+ o,
787
+ i,
788
+ p
789
+ ]);
790
+ Q(() => {
791
+ const I = l.current;
792
+ if (!(!I || !c))
793
+ return I.addEventListener("scroll", G, {
794
+ passive: !0
795
+ }), () => {
796
+ I.removeEventListener("scroll", G);
870
797
  };
871
- return v.addEventListener("load", U, !0), V.current ? setTimeout(() => {
872
- H("instant");
873
- }, 0) : A(), () => {
874
- clearTimeout(E), C.disconnect(), v.removeEventListener("load", U, !0);
798
+ }, [G, c]);
799
+ const B = st(
800
+ (I = "smooth") => {
801
+ const T = l.current;
802
+ if (!T) return;
803
+ A.current.isUserScrolling = !1, A.current.isNearBottom = !0, A.current.scrollUpCount = 0;
804
+ const C = () => {
805
+ const V = (P = 0) => {
806
+ if (P > 5) return;
807
+ const O = T.scrollHeight, N = T.scrollTop, q = T.clientHeight;
808
+ N + q >= O - 1 || (T.scrollTo({
809
+ top: O,
810
+ behavior: I
811
+ }), setTimeout(() => {
812
+ const F = T.scrollHeight, Z = T.scrollTop;
813
+ (F !== O || Z + q < F - 1) && V(P + 1);
814
+ }, 50));
815
+ };
816
+ V();
875
817
  };
876
- }, [u, L.length, H]), {
877
- virtualState: St(() => {
878
- const v = e.getState(), w = v.getShadowValue(
879
- [t, ...o].join(".")
880
- ), E = v.getShadowMetadata(t, o)?.arrayKeys || [], A = w.slice(
881
- f.startIndex,
882
- f.endIndex + 1
883
- ), C = E.slice(
884
- f.startIndex,
885
- f.endIndex + 1
818
+ "requestIdleCallback" in window ? requestIdleCallback(C, { timeout: 100 }) : requestAnimationFrame(() => {
819
+ requestAnimationFrame(C);
820
+ });
821
+ },
822
+ []
823
+ );
824
+ return Q(() => {
825
+ if (!c || !l.current) return;
826
+ const I = l.current, T = A.current;
827
+ let C;
828
+ const V = () => {
829
+ clearTimeout(C), C = setTimeout(() => {
830
+ !T.isUserScrolling && T.isNearBottom && B(
831
+ E.current ? "instant" : "smooth"
886
832
  );
887
- return s({
888
- currentState: A,
889
- path: o,
890
- componentId: _,
891
- meta: { ...h, validIds: C }
892
- });
893
- }, [f.startIndex, f.endIndex, L.length]),
894
- virtualizerProps: {
895
- outer: {
896
- ref: c,
897
- style: {
898
- overflowY: "auto",
899
- height: "100%",
900
- position: "relative"
901
- }
902
- },
903
- inner: {
904
- style: {
905
- height: `${G}px`,
906
- position: "relative"
907
- }
908
- },
909
- list: {
910
- style: {
911
- transform: `translateY(${j.current.get(
912
- L[f.startIndex]
913
- )?.offset || 0}px)`
914
- }
833
+ }, 100);
834
+ }, P = new MutationObserver(() => {
835
+ T.isUserScrolling || V();
836
+ });
837
+ P.observe(I, {
838
+ childList: !0,
839
+ subtree: !0,
840
+ attributes: !0,
841
+ attributeFilter: ["style", "class"]
842
+ // More specific than just 'height'
843
+ });
844
+ const O = (N) => {
845
+ N.target instanceof HTMLImageElement && !T.isUserScrolling && V();
846
+ };
847
+ return I.addEventListener("load", O, !0), E.current ? setTimeout(() => {
848
+ B("instant");
849
+ }, 0) : V(), () => {
850
+ clearTimeout(C), P.disconnect(), I.removeEventListener("load", O, !0);
851
+ };
852
+ }, [c, $.length, B]), {
853
+ virtualState: dt(() => {
854
+ const I = a.getState(), T = I.getShadowValue(
855
+ [t, ...e].join(".")
856
+ ), C = I.getShadowMetadata(t, e)?.arrayKeys || [];
857
+ T.slice(
858
+ d.startIndex,
859
+ d.endIndex + 1
860
+ );
861
+ const V = C.slice(
862
+ d.startIndex,
863
+ d.endIndex + 1
864
+ );
865
+ return f({
866
+ path: e,
867
+ componentId: v,
868
+ meta: { ...s, validIds: V }
869
+ });
870
+ }, [d.startIndex, d.endIndex, $.length]),
871
+ virtualizerProps: {
872
+ outer: {
873
+ ref: l,
874
+ style: {
875
+ overflowY: "auto",
876
+ height: "100%",
877
+ position: "relative"
915
878
  }
916
879
  },
917
- scrollToBottom: H,
918
- scrollToIndex: (v, w = "smooth") => {
919
- if (c.current && L[v]) {
920
- const E = j.current.get(L[v])?.offset || 0;
921
- c.current.scrollTo({ top: E, behavior: w });
880
+ inner: {
881
+ style: {
882
+ height: `${x}px`,
883
+ position: "relative"
922
884
  }
923
- }
924
- };
925
- };
926
- if (p === "stateMap")
927
- return (r) => {
928
- const [n, i] = at(
929
- h?.validIds ?? e.getState().getShadowMetadata(t, o)?.arrayKeys
930
- ), u = e.getState().getShadowValue(R, h?.validIds);
931
- if (!n)
932
- throw new Error("No array keys found for mapping");
933
- const d = s({
934
- currentState: u,
935
- path: o,
936
- componentId: _,
937
- meta: h
938
- });
939
- return u.map((c, f) => {
940
- const D = n[f]?.split(".").slice(1), M = s({
941
- currentState: c,
942
- path: D,
943
- componentId: _,
944
- meta: h
945
- });
946
- return r(
947
- M,
948
- f,
949
- d
950
- );
951
- });
952
- };
953
- if (p === "$stateMap")
954
- return (r) => ut(qt, {
955
- proxy: {
956
- _stateKey: t,
957
- _path: o,
958
- _mapFn: r,
959
- _meta: h
960
- },
961
- rebuildStateShape: s
962
- });
963
- if (p === "stateFind")
964
- return (r) => {
965
- const n = h?.validIds ?? e.getState().getShadowMetadata(t, o)?.arrayKeys;
966
- if (n)
967
- for (let i = 0; i < n.length; i++) {
968
- const u = n[i];
969
- if (!u) continue;
970
- const d = e.getState().getShadowValue(u);
971
- if (r(d, i)) {
972
- const c = u.split(".").slice(1);
973
- return s({
974
- currentState: d,
975
- path: c,
976
- componentId: _,
977
- meta: h
978
- // Pass along meta for potential further chaining
979
- });
885
+ },
886
+ list: {
887
+ style: {
888
+ transform: `translateY(${U.current.get($[d.startIndex])?.offset || 0}px)`
980
889
  }
981
890
  }
982
- };
983
- if (p === "stateFilter")
984
- return (r) => {
985
- const n = h?.validIds ?? e.getState().getShadowMetadata(t, o)?.arrayKeys;
986
- if (!n)
987
- throw new Error("No array keys found for filtering.");
988
- const i = [], u = b.filter(
989
- (d, c) => r(d, c) ? (i.push(n[c]), !0) : !1
990
- );
991
- return s({
992
- currentState: u,
993
- path: o,
994
- componentId: _,
995
- meta: {
996
- validIds: i,
997
- transforms: [
998
- ...h?.transforms || [],
999
- {
1000
- type: "filter",
1001
- fn: r
1002
- }
1003
- ]
891
+ },
892
+ scrollToBottom: B,
893
+ scrollToIndex: (I, T = "smooth") => {
894
+ if (l.current && $[I]) {
895
+ const C = U.current.get($[I])?.offset || 0;
896
+ l.current.scrollTo({ top: C, behavior: T });
1004
897
  }
1005
- });
898
+ }
1006
899
  };
1007
- if (p === "stateSort")
1008
- return (r) => {
1009
- const n = h?.validIds ?? e.getState().getShadowMetadata(t, o)?.arrayKeys;
1010
- if (!n)
1011
- throw new Error("No array keys found for sorting");
1012
- const i = b.map((u, d) => ({
1013
- item: u,
1014
- key: n[d]
1015
- }));
1016
- return i.sort((u, d) => r(u.item, d.item)).filter(Boolean), s({
1017
- currentState: i.map((u) => u.item),
1018
- path: o,
1019
- componentId: _,
1020
- meta: {
1021
- validIds: i.map((u) => u.key),
1022
- transforms: [
1023
- ...h?.transforms || [],
1024
- { type: "sort", fn: r }
1025
- ]
1026
- }
900
+ };
901
+ if (u === "stateMap")
902
+ return (n) => {
903
+ const [o, i] = X(
904
+ s?.validIds ?? a.getState().getShadowMetadata(t, e)?.arrayKeys
905
+ ), c = a.getState().getShadowValue(k, s?.validIds);
906
+ if (!o)
907
+ throw new Error("No array keys found for mapping");
908
+ const p = f({
909
+ path: e,
910
+ componentId: v,
911
+ meta: s
912
+ });
913
+ return c.map((l, d) => {
914
+ const y = o[d]?.split(".").slice(1), _ = f({
915
+ path: y,
916
+ componentId: v,
917
+ meta: s
1027
918
  });
1028
- };
1029
- if (p === "stream")
1030
- return function(r = {}) {
1031
- const {
1032
- bufferSize: n = 100,
1033
- flushInterval: i = 100,
1034
- bufferStrategy: u = "accumulate",
1035
- store: d,
1036
- onFlush: c
1037
- } = r;
1038
- let f = [], D = !1, M = null;
1039
- const k = (G) => {
1040
- if (!D) {
1041
- if (u === "sliding" && f.length >= n)
1042
- f.shift();
1043
- else if (u === "dropping" && f.length >= n)
1044
- return;
1045
- f.push(G), f.length >= n && V();
1046
- }
1047
- }, V = () => {
1048
- if (f.length === 0) return;
1049
- const G = [...f];
1050
- if (f = [], d) {
1051
- const Z = d(G);
1052
- Z !== void 0 && (Array.isArray(Z) ? Z : [Z]).forEach((H) => {
1053
- a(H, o, {
1054
- updateType: "insert"
1055
- });
1056
- });
1057
- } else
1058
- G.forEach((Z) => {
1059
- a(Z, o, {
1060
- updateType: "insert"
1061
- });
919
+ return n(
920
+ _,
921
+ d,
922
+ p
923
+ );
924
+ });
925
+ };
926
+ if (u === "$stateMap")
927
+ return (n) => it(Ht, {
928
+ proxy: {
929
+ _stateKey: t,
930
+ _path: e,
931
+ _mapFn: n,
932
+ _meta: s
933
+ },
934
+ rebuildStateShape: f
935
+ });
936
+ if (u === "stateFind")
937
+ return (n) => {
938
+ const o = s?.validIds ?? a.getState().getShadowMetadata(t, e)?.arrayKeys;
939
+ if (o)
940
+ for (let i = 0; i < o.length; i++) {
941
+ const c = o[i];
942
+ if (!c) continue;
943
+ const p = a.getState().getShadowValue(c);
944
+ if (n(p, i)) {
945
+ const l = c.split(".").slice(1);
946
+ return f({
947
+ path: l,
948
+ componentId: v,
949
+ meta: s
950
+ // Pass along meta for potential further chaining
1062
951
  });
1063
- c?.(G);
1064
- };
1065
- i > 0 && (M = setInterval(V, i));
1066
- const $ = nt(), j = e.getState().getShadowMetadata(t, o) || {}, L = j.streams || /* @__PURE__ */ new Map();
1067
- return L.set($, { buffer: f, flushTimer: M }), e.getState().setShadowMetadata(t, o, {
1068
- ...j,
1069
- streams: L
1070
- }), {
1071
- write: (G) => k(G),
1072
- writeMany: (G) => G.forEach(k),
1073
- flush: () => V(),
1074
- pause: () => {
1075
- D = !0;
1076
- },
1077
- resume: () => {
1078
- D = !1, f.length > 0 && V();
1079
- },
1080
- close: () => {
1081
- V(), M && clearInterval(M);
1082
- const G = e.getState().getShadowMetadata(t, o);
1083
- G?.streams && G.streams.delete($);
1084
952
  }
1085
- };
1086
- };
1087
- if (p === "stateList")
1088
- return (r) => /* @__PURE__ */ it(() => {
1089
- const i = z(/* @__PURE__ */ new Map()), u = h?.transforms && h.transforms.length > 0 ? `${_}-${Bt(h.transforms)}` : `${_}-base`, [d, c] = at({}), { validIds: f, arrayValues: D } = St(() => {
1090
- const k = e.getState().getShadowMetadata(t, o)?.transformCaches?.get(u);
1091
- let V;
1092
- k && k.validIds ? V = k.validIds : (V = pt(
1093
- t,
1094
- o,
1095
- h?.transforms
1096
- ), e.getState().setTransformCache(t, o, u, {
1097
- validIds: V,
1098
- computedAt: Date.now(),
1099
- transforms: h?.transforms || []
1100
- }));
1101
- const $ = e.getState().getShadowValue(R, V);
1102
- return {
1103
- validIds: V,
1104
- arrayValues: $ || []
1105
- };
1106
- }, [u, d]);
1107
- if (et(() => {
1108
- const k = e.getState().subscribeToPath(R, (V) => {
1109
- if (V.type === "GET_SELECTED")
1110
- return;
1111
- const j = e.getState().getShadowMetadata(t, o)?.transformCaches;
1112
- if (j)
1113
- for (const L of j.keys())
1114
- L.startsWith(_) && j.delete(L);
1115
- (V.type === "INSERT" || V.type === "REMOVE" || V.type === "CLEAR_SELECTION") && c({});
953
+ }
954
+ };
955
+ if (u === "stateFilter")
956
+ return (n) => {
957
+ const o = a.getState().getShadowValue([t, ...e].join("."), s?.validIds);
958
+ if (!Array.isArray(o)) return [];
959
+ const i = s?.validIds ?? a.getState().getShadowMetadata(t, e)?.arrayKeys;
960
+ if (!i)
961
+ throw new Error("No array keys found for filtering.");
962
+ const c = [];
963
+ return o.filter(
964
+ (p, l) => n(p, l) ? (c.push(i[l]), !0) : !1
965
+ ), f({
966
+ path: e,
967
+ componentId: v,
968
+ meta: {
969
+ validIds: c,
970
+ transforms: [
971
+ ...s?.transforms || [],
972
+ {
973
+ type: "filter",
974
+ fn: n
975
+ }
976
+ ]
977
+ }
978
+ });
979
+ };
980
+ if (u === "stateSort")
981
+ return (n) => {
982
+ const o = a.getState().getShadowValue([t, ...e].join("."), s?.validIds);
983
+ if (!Array.isArray(o)) return [];
984
+ const i = s?.validIds ?? a.getState().getShadowMetadata(t, e)?.arrayKeys;
985
+ if (!i)
986
+ throw new Error("No array keys found for sorting");
987
+ const c = o.map((p, l) => ({
988
+ item: p,
989
+ key: i[l]
990
+ }));
991
+ return c.sort((p, l) => n(p.item, l.item)).filter(Boolean), f({
992
+ path: e,
993
+ componentId: v,
994
+ meta: {
995
+ validIds: c.map((p) => p.key),
996
+ transforms: [
997
+ ...s?.transforms || [],
998
+ { type: "sort", fn: n }
999
+ ]
1000
+ }
1001
+ });
1002
+ };
1003
+ if (u === "stream")
1004
+ return function(n = {}) {
1005
+ const {
1006
+ bufferSize: o = 100,
1007
+ flushInterval: i = 100,
1008
+ bufferStrategy: c = "accumulate",
1009
+ store: p,
1010
+ onFlush: l
1011
+ } = n;
1012
+ let d = [], y = !1, _ = null;
1013
+ const M = (x) => {
1014
+ if (!y) {
1015
+ if (c === "sliding" && d.length >= o)
1016
+ d.shift();
1017
+ else if (c === "dropping" && d.length >= o)
1018
+ return;
1019
+ d.push(x), d.length >= o && E();
1020
+ }
1021
+ }, E = () => {
1022
+ if (d.length === 0) return;
1023
+ const x = [...d];
1024
+ if (d = [], p) {
1025
+ const K = p(x);
1026
+ K !== void 0 && (Array.isArray(K) ? K : [K]).forEach((B) => {
1027
+ r(B, e, {
1028
+ updateType: "insert"
1029
+ });
1116
1030
  });
1117
- return () => {
1118
- k();
1119
- };
1120
- }, [_, R]), !Array.isArray(D))
1121
- return null;
1122
- const M = s({
1123
- currentState: D,
1124
- path: o,
1125
- componentId: _,
1126
- meta: {
1127
- ...h,
1128
- validIds: f
1129
- }
1130
- });
1131
- return /* @__PURE__ */ it(Ot, { children: D.map((k, V) => {
1132
- const $ = f[V];
1133
- if (!$)
1134
- return null;
1135
- let j = i.current.get($);
1136
- j || (j = nt(), i.current.set($, j));
1137
- const L = $.split(".").slice(1);
1138
- return ut(wt, {
1139
- key: $,
1140
- stateKey: t,
1141
- itemComponentId: j,
1142
- itemPath: L,
1143
- localIndex: V,
1144
- arraySetter: M,
1145
- rebuildStateShape: s,
1146
- renderFn: r
1031
+ } else
1032
+ x.forEach((K) => {
1033
+ r(K, e, {
1034
+ updateType: "insert"
1035
+ });
1147
1036
  });
1148
- }) });
1149
- }, {});
1150
- if (p === "stateFlattenOn")
1151
- return (r) => {
1152
- const n = b;
1153
- y.clear(), I++;
1154
- const i = n.flatMap(
1155
- (u) => u[r] ?? []
1156
- );
1157
- return s({
1158
- currentState: i,
1159
- path: [...o, "[*]", r],
1160
- componentId: _,
1161
- meta: h
1162
- });
1037
+ l?.(x);
1163
1038
  };
1164
- if (p === "index")
1165
- return (r) => {
1166
- const i = e.getState().getShadowMetadata(t, o)?.arrayKeys?.filter(
1167
- (c) => !h?.validIds || h?.validIds && h?.validIds?.includes(c)
1168
- )?.[r];
1169
- if (!i) return;
1170
- const u = e.getState().getShadowValue(i, h?.validIds);
1171
- return s({
1172
- currentState: u,
1173
- path: i.split(".").slice(1),
1174
- componentId: _,
1175
- meta: h
1176
- });
1039
+ i > 0 && (_ = setInterval(E, i));
1040
+ const A = et(), U = a.getState().getShadowMetadata(t, e) || {}, $ = U.streams || /* @__PURE__ */ new Map();
1041
+ return $.set(A, { buffer: d, flushTimer: _ }), a.getState().setShadowMetadata(t, e, {
1042
+ ...U,
1043
+ streams: $
1044
+ }), {
1045
+ write: (x) => M(x),
1046
+ writeMany: (x) => x.forEach(M),
1047
+ flush: () => E(),
1048
+ pause: () => {
1049
+ y = !0;
1050
+ },
1051
+ resume: () => {
1052
+ y = !1, d.length > 0 && E();
1053
+ },
1054
+ close: () => {
1055
+ E(), _ && clearInterval(_);
1056
+ const x = a.getState().getShadowMetadata(t, e);
1057
+ x?.streams && x.streams.delete(A);
1058
+ }
1177
1059
  };
1178
- if (p === "last")
1179
- return () => {
1180
- const r = e.getState().getShadowValue(t, o);
1181
- if (r.length === 0) return;
1182
- const n = r.length - 1, i = r[n], u = [...o, n.toString()];
1183
- return s({
1184
- currentState: i,
1185
- path: u,
1186
- componentId: _,
1187
- meta: h
1060
+ };
1061
+ if (u === "stateList")
1062
+ return (n) => /* @__PURE__ */ nt(() => {
1063
+ const i = z(/* @__PURE__ */ new Map()), c = s?.transforms && s.transforms.length > 0 ? `${v}-${Wt(s.transforms)}` : `${v}-base`, [p, l] = X({}), { validIds: d, arrayValues: y } = dt(() => {
1064
+ const M = a.getState().getShadowMetadata(t, e)?.transformCaches?.get(c);
1065
+ let E;
1066
+ M && M.validIds ? E = M.validIds : (E = ht(
1067
+ t,
1068
+ e,
1069
+ s?.transforms
1070
+ ), a.getState().setTransformCache(t, e, c, {
1071
+ validIds: E,
1072
+ computedAt: Date.now(),
1073
+ transforms: s?.transforms || []
1074
+ }));
1075
+ const A = a.getState().getShadowValue(k, E);
1076
+ return {
1077
+ validIds: E,
1078
+ arrayValues: A || []
1079
+ };
1080
+ }, [c, p]);
1081
+ if (Q(() => {
1082
+ const M = a.getState().subscribeToPath(k, (E) => {
1083
+ if (E.type === "GET_SELECTED")
1084
+ return;
1085
+ const U = a.getState().getShadowMetadata(t, e)?.transformCaches;
1086
+ if (U)
1087
+ for (const $ of U.keys())
1088
+ $.startsWith(v) && U.delete($);
1089
+ (E.type === "INSERT" || E.type === "REMOVE" || E.type === "CLEAR_SELECTION") && l({});
1188
1090
  });
1189
- };
1190
- if (p === "insert")
1191
- return (r, n) => (a(r, o, { updateType: "insert" }), s({
1192
- currentState: e.getState().getShadowValue(t, o),
1193
- path: o,
1194
- componentId: _,
1195
- meta: h
1196
- }));
1197
- if (p === "uniqueInsert")
1198
- return (r, n, i) => {
1199
- const u = e.getState().getShadowValue(t, o), d = rt(r) ? r(u) : r;
1200
- let c = null;
1201
- if (!u.some((D) => {
1202
- const M = n ? n.every(
1203
- (k) => ct(D[k], d[k])
1204
- ) : ct(D, d);
1205
- return M && (c = D), M;
1206
- }))
1207
- T(o), a(d, o, { updateType: "insert" });
1208
- else if (i && c) {
1209
- const D = i(c), M = u.map(
1210
- (k) => ct(k, c) ? D : k
1211
- );
1212
- T(o), a(M, o, {
1213
- updateType: "update"
1214
- });
1091
+ return () => {
1092
+ M();
1093
+ };
1094
+ }, [v, k]), !Array.isArray(y))
1095
+ return null;
1096
+ const _ = f({
1097
+ path: e,
1098
+ componentId: v,
1099
+ meta: {
1100
+ ...s,
1101
+ validIds: d
1215
1102
  }
1216
- };
1217
- if (p === "cut")
1218
- return (r, n) => {
1219
- const i = h?.validIds ?? e.getState().getShadowMetadata(t, o)?.arrayKeys;
1220
- if (!i || i.length === 0) return;
1221
- const u = r == -1 ? i.length - 1 : r !== void 0 ? r : i.length - 1, d = i[u];
1222
- if (!d) return;
1223
- const c = d.split(".").slice(1);
1224
- a(b, c, {
1225
- updateType: "cut"
1103
+ });
1104
+ return /* @__PURE__ */ nt(Pt, { children: y.map((M, E) => {
1105
+ const A = d[E];
1106
+ if (!A)
1107
+ return null;
1108
+ let U = i.current.get(A);
1109
+ U || (U = et(), i.current.set(A, U));
1110
+ const $ = A.split(".").slice(1);
1111
+ return it(yt, {
1112
+ key: A,
1113
+ stateKey: t,
1114
+ itemComponentId: U,
1115
+ itemPath: $,
1116
+ localIndex: E,
1117
+ arraySetter: _,
1118
+ rebuildStateShape: f,
1119
+ renderFn: n
1226
1120
  });
1227
- };
1228
- if (p === "cutSelected")
1229
- return () => {
1230
- const r = pt(
1231
- t,
1232
- o,
1233
- h?.transforms
1234
- );
1235
- if (!r || r.length === 0) return;
1236
- const n = e.getState().selectedIndicesMap.get(R);
1237
- let i = r.findIndex(
1238
- (c) => c === n
1121
+ }) });
1122
+ }, {});
1123
+ if (u === "stateFlattenOn")
1124
+ return (n) => {
1125
+ const o = a.getState().getShadowValue([t, ...e].join("."), s?.validIds);
1126
+ return Array.isArray(o) ? (o.flatMap(
1127
+ (c) => c[n] ?? []
1128
+ ), f({
1129
+ path: [...e, "[*]", n],
1130
+ componentId: v,
1131
+ meta: s
1132
+ })) : [];
1133
+ };
1134
+ if (u === "index")
1135
+ return (n) => {
1136
+ const i = a.getState().getShadowMetadata(t, e)?.arrayKeys?.filter(
1137
+ (p) => !s?.validIds || s?.validIds && s?.validIds?.includes(p)
1138
+ )?.[n];
1139
+ return i ? (a.getState().getShadowValue(i, s?.validIds), f({
1140
+ path: i.split(".").slice(1),
1141
+ componentId: v,
1142
+ meta: s
1143
+ })) : void 0;
1144
+ };
1145
+ if (u === "last")
1146
+ return () => {
1147
+ const n = a.getState().getShadowValue(t, e);
1148
+ if (n.length === 0) return;
1149
+ const o = n.length - 1;
1150
+ n[o];
1151
+ const i = [...e, o.toString()];
1152
+ return f({
1153
+ path: i,
1154
+ componentId: v,
1155
+ meta: s
1156
+ });
1157
+ };
1158
+ if (u === "insert")
1159
+ return (n, o) => (r(n, e, { updateType: "insert" }), f({
1160
+ path: e,
1161
+ componentId: v,
1162
+ meta: s
1163
+ }));
1164
+ if (u === "uniqueInsert")
1165
+ return (n, o, i) => {
1166
+ const c = a.getState().getShadowValue(t, e), p = tt(n) ? n(c) : n;
1167
+ let l = null;
1168
+ if (!c.some((y) => {
1169
+ const _ = o ? o.every(
1170
+ (M) => ot(y[M], p[M])
1171
+ ) : ot(y, p);
1172
+ return _ && (l = y), _;
1173
+ }))
1174
+ r(p, e, { updateType: "insert" });
1175
+ else if (i && l) {
1176
+ const y = i(l), _ = c.map(
1177
+ (M) => ot(M, l) ? y : M
1239
1178
  );
1240
- const u = r[i == -1 ? r.length - 1 : i]?.split(".").slice(1);
1241
- e.getState().clearSelectedIndex({ arrayKey: R });
1242
- const d = u?.slice(0, -1);
1243
- ft(t, d), a(b, u, {
1244
- updateType: "cut"
1179
+ r(_, e, {
1180
+ updateType: "update"
1245
1181
  });
1246
- };
1247
- if (p === "cutByValue")
1248
- return (r) => {
1249
- const n = e.getState().getShadowMetadata(t, o), i = h?.validIds ?? n?.arrayKeys;
1250
- if (!i) return;
1251
- let u = null;
1252
- for (const d of i)
1253
- if (e.getState().getShadowValue(d) === r) {
1254
- u = d;
1255
- break;
1256
- }
1257
- if (u) {
1258
- const d = u.split(".").slice(1);
1259
- a(null, d, { updateType: "cut" });
1260
- }
1261
- };
1262
- if (p === "toggleByValue")
1263
- return (r) => {
1264
- const n = e.getState().getShadowMetadata(t, o), i = h?.validIds ?? n?.arrayKeys;
1265
- if (!i) return;
1266
- let u = null;
1267
- for (const d of i) {
1268
- const c = e.getState().getShadowValue(d);
1269
- if (console.log("itemValue sdasdasdasd", c), c === r) {
1270
- u = d;
1271
- break;
1272
- }
1182
+ }
1183
+ };
1184
+ if (u === "cut")
1185
+ return (n, o) => {
1186
+ const i = a.getState().getShadowValue([t, ...e].join("."), s?.validIds), c = s?.validIds ?? a.getState().getShadowMetadata(t, e)?.arrayKeys;
1187
+ if (!c || c.length === 0) return;
1188
+ const p = n == -1 ? c.length - 1 : n !== void 0 ? n : c.length - 1, l = c[p];
1189
+ if (!l) return;
1190
+ const d = l.split(".").slice(1);
1191
+ r(i, d, {
1192
+ updateType: "cut"
1193
+ });
1194
+ };
1195
+ if (u === "cutSelected")
1196
+ return () => {
1197
+ const n = ht(t, e, s?.transforms), o = a.getState().getShadowValue([t, ...e].join("."), s?.validIds);
1198
+ if (!n || n.length === 0) return;
1199
+ const i = a.getState().selectedIndicesMap.get(k);
1200
+ let c = n.findIndex(
1201
+ (d) => d === i
1202
+ );
1203
+ const p = n[c == -1 ? n.length - 1 : c]?.split(".").slice(1);
1204
+ a.getState().clearSelectedIndex({ arrayKey: k });
1205
+ const l = p?.slice(0, -1);
1206
+ lt(t, l), r(o, p, {
1207
+ updateType: "cut"
1208
+ });
1209
+ };
1210
+ if (u === "cutByValue")
1211
+ return (n) => {
1212
+ const o = a.getState().getShadowMetadata(t, e), i = s?.validIds ?? o?.arrayKeys;
1213
+ if (!i) return;
1214
+ let c = null;
1215
+ for (const p of i)
1216
+ if (a.getState().getShadowValue(p) === n) {
1217
+ c = p;
1218
+ break;
1273
1219
  }
1274
- if (console.log("itemValue keyToCut", u), u) {
1275
- const d = u.split(".").slice(1);
1276
- console.log("itemValue keyToCut", u), a(r, d, {
1277
- updateType: "cut"
1278
- });
1279
- } else
1280
- a(r, o, { updateType: "insert" });
1281
- };
1282
- if (p === "findWith")
1283
- return (r, n) => {
1284
- const i = e.getState().getShadowMetadata(t, o)?.arrayKeys;
1285
- if (!i)
1286
- throw new Error("No array keys found for sorting");
1287
- let u = null, d = [];
1288
- for (const c of i) {
1289
- let f = e.getState().getShadowValue(c, h?.validIds);
1290
- if (f && f[r] === n) {
1291
- u = f, d = c.split(".").slice(1);
1292
- break;
1293
- }
1220
+ if (c) {
1221
+ const p = c.split(".").slice(1);
1222
+ r(null, p, { updateType: "cut" });
1223
+ }
1224
+ };
1225
+ if (u === "toggleByValue")
1226
+ return (n) => {
1227
+ const o = a.getState().getShadowMetadata(t, e), i = s?.validIds ?? o?.arrayKeys;
1228
+ if (!i) return;
1229
+ let c = null;
1230
+ for (const p of i) {
1231
+ const l = a.getState().getShadowValue(p);
1232
+ if (console.log("itemValue sdasdasdasd", l), l === n) {
1233
+ c = p;
1234
+ break;
1294
1235
  }
1295
- return s({
1296
- currentState: u,
1297
- path: d,
1298
- componentId: _,
1299
- meta: h
1236
+ }
1237
+ if (console.log("itemValue keyToCut", c), c) {
1238
+ const p = c.split(".").slice(1);
1239
+ console.log("itemValue keyToCut", c), r(n, p, {
1240
+ updateType: "cut"
1300
1241
  });
1301
- };
1302
- }
1303
- if (p === "cut") {
1304
- let r = e.getState().getShadowValue(o.join("."));
1242
+ } else
1243
+ r(n, e, { updateType: "insert" });
1244
+ };
1245
+ if (u === "findWith")
1246
+ return (n, o) => {
1247
+ const i = a.getState().getShadowMetadata(t, e)?.arrayKeys;
1248
+ if (!i)
1249
+ throw new Error("No array keys found for sorting");
1250
+ let c = [];
1251
+ for (const p of i) {
1252
+ let l = a.getState().getShadowValue(p, s?.validIds);
1253
+ if (l && l[n] === o) {
1254
+ c = p.split(".").slice(1);
1255
+ break;
1256
+ }
1257
+ }
1258
+ return f({
1259
+ path: c,
1260
+ componentId: v,
1261
+ meta: s
1262
+ });
1263
+ };
1264
+ if (u === "cutThis") {
1265
+ let n = a.getState().getShadowValue(e.join("."));
1305
1266
  return () => {
1306
- a(r, o, { updateType: "cut" });
1267
+ r(n, e, { updateType: "cut" });
1307
1268
  };
1308
1269
  }
1309
- if (p === "get")
1310
- return () => (Tt(t, _, o), e.getState().getShadowValue(R, h?.validIds));
1311
- if (p === "getState")
1312
- return () => e.getState().getShadowValue(R, h?.validIds);
1313
- if (p === "$derive")
1314
- return (r) => bt({
1270
+ if (u === "get")
1271
+ return () => (wt(t, v, e), a.getState().getShadowValue(k, s?.validIds));
1272
+ if (u === "getState")
1273
+ return () => a.getState().getShadowValue(k, s?.validIds);
1274
+ if (u === "$derive")
1275
+ return (n) => It({
1315
1276
  _stateKey: t,
1316
- _path: o,
1317
- _effect: r.toString(),
1318
- _meta: h
1277
+ _path: e,
1278
+ _effect: n.toString(),
1279
+ _meta: s
1319
1280
  });
1320
- if (p === "$get")
1321
- return () => bt({ _stateKey: t, _path: o, _meta: h });
1322
- if (p === "lastSynced") {
1323
- const r = `${t}:${o.join(".")}`;
1324
- return e.getState().getSyncInfo(r);
1281
+ if (u === "$get")
1282
+ return () => It({ _stateKey: t, _path: e, _meta: s });
1283
+ if (u === "lastSynced") {
1284
+ const n = `${t}:${e.join(".")}`;
1285
+ return a.getState().getSyncInfo(n);
1325
1286
  }
1326
- if (p == "getLocalStorage")
1327
- return (r) => gt(g + "-" + t + "-" + r);
1328
- if (p === "isSelected") {
1329
- const r = [t, ...o].slice(0, -1);
1330
- if (ft(t, o, void 0), Array.isArray(
1331
- e.getState().getShadowValue(r.join("."), h?.validIds)
1287
+ if (u == "getLocalStorage")
1288
+ return (n) => ut(g + "-" + t + "-" + n);
1289
+ if (u === "isSelected") {
1290
+ const n = [t, ...e].slice(0, -1);
1291
+ if (lt(t, e, void 0), Array.isArray(
1292
+ a.getState().getShadowValue(n.join("."), s?.validIds)
1332
1293
  )) {
1333
- o[o.length - 1];
1334
- const n = r.join("."), i = e.getState().selectedIndicesMap.get(n), u = t + "." + o.join(".");
1335
- return i === u;
1294
+ e[e.length - 1];
1295
+ const o = n.join("."), i = a.getState().selectedIndicesMap.get(o), c = t + "." + e.join(".");
1296
+ return i === c;
1336
1297
  }
1337
1298
  return;
1338
1299
  }
1339
- if (p === "setSelected")
1340
- return (r) => {
1341
- const n = o.slice(0, -1), i = t + "." + n.join("."), u = t + "." + o.join(".");
1342
- ft(t, n, void 0), e.getState().selectedIndicesMap.get(i), r && e.getState().setSelectedIndex(i, u);
1300
+ if (u === "setSelected")
1301
+ return (n) => {
1302
+ const o = e.slice(0, -1), i = t + "." + o.join("."), c = t + "." + e.join(".");
1303
+ lt(t, o, void 0), a.getState().selectedIndicesMap.get(i), n && a.getState().setSelectedIndex(i, c);
1343
1304
  };
1344
- if (p === "toggleSelected")
1305
+ if (u === "toggleSelected")
1345
1306
  return () => {
1346
- const r = o.slice(0, -1), n = t + "." + r.join("."), i = t + "." + o.join(".");
1347
- e.getState().selectedIndicesMap.get(n) === i ? e.getState().clearSelectedIndex({ arrayKey: n }) : e.getState().setSelectedIndex(n, i);
1307
+ const n = e.slice(0, -1), o = t + "." + n.join("."), i = t + "." + e.join(".");
1308
+ a.getState().selectedIndicesMap.get(o) === i ? a.getState().clearSelectedIndex({ arrayKey: o }) : a.getState().setSelectedIndex(o, i);
1348
1309
  };
1349
- if (p === "_componentId")
1350
- return _;
1351
- if (o.length == 0) {
1352
- if (p === "addZodValidation")
1353
- return (r) => {
1354
- e.getState().getInitialOptions(t)?.validation, r.forEach((n) => {
1355
- const i = e.getState().getShadowMetadata(t, n.path) || {};
1356
- e.getState().setShadowMetadata(t, n.path, {
1310
+ if (u === "_componentId")
1311
+ return v;
1312
+ if (e.length == 0) {
1313
+ if (u === "addZodValidation")
1314
+ return (n) => {
1315
+ a.getState().getInitialOptions(t)?.validation, n.forEach((o) => {
1316
+ const i = a.getState().getShadowMetadata(t, o.path) || {};
1317
+ a.getState().setShadowMetadata(t, o.path, {
1357
1318
  ...i,
1358
1319
  validation: {
1359
1320
  status: "VALIDATION_FAILED",
1360
- message: n.message,
1321
+ message: o.message,
1361
1322
  validatedValue: void 0
1362
1323
  }
1363
- }), e.getState().notifyPathSubscribers(n.path, {
1324
+ }), a.getState().notifyPathSubscribers(o.path, {
1364
1325
  type: "VALIDATION_FAILED",
1365
- message: n.message,
1326
+ message: o.message,
1366
1327
  validatedValue: void 0
1367
1328
  });
1368
1329
  });
1369
1330
  };
1370
- if (p === "clearZodValidation")
1371
- return (r) => {
1372
- if (!r)
1331
+ if (u === "clearZodValidation")
1332
+ return (n) => {
1333
+ if (!n)
1373
1334
  throw new Error("clearZodValidation requires a path");
1374
- const n = e.getState().getShadowMetadata(t, r) || {};
1375
- n.validation && (e.getState().setShadowMetadata(t, r, {
1376
- ...n,
1335
+ const o = a.getState().getShadowMetadata(t, n) || {};
1336
+ o.validation && (a.getState().setShadowMetadata(t, n, {
1337
+ ...o,
1377
1338
  validation: void 0
1378
- }), e.getState().notifyPathSubscribers([t, ...r].join("."), {
1339
+ }), a.getState().notifyPathSubscribers([t, ...n].join("."), {
1379
1340
  type: "VALIDATION_CLEARED"
1380
1341
  }));
1381
1342
  };
1382
- if (p === "applyJsonPatch")
1383
- return (r) => {
1384
- const n = e.getState(), i = n.getShadowMetadata(t, []);
1343
+ if (u === "applyJsonPatch")
1344
+ return (n) => {
1345
+ const o = a.getState(), i = o.getShadowMetadata(t, []);
1385
1346
  if (!i?.components) return;
1386
- const u = (c) => !c || c === "/" ? [] : c.split("/").slice(1).map((f) => f.replace(/~1/g, "/").replace(/~0/g, "~")), d = /* @__PURE__ */ new Set();
1387
- for (const c of r) {
1388
- const f = u(c.path);
1389
- switch (c.op) {
1347
+ const c = (l) => !l || l === "/" ? [] : l.split("/").slice(1).map((d) => d.replace(/~1/g, "/").replace(/~0/g, "~")), p = /* @__PURE__ */ new Set();
1348
+ for (const l of n) {
1349
+ const d = c(l.path);
1350
+ switch (l.op) {
1390
1351
  case "add":
1391
1352
  case "replace": {
1392
- const { value: D } = c;
1393
- n.updateShadowAtPath(t, f, D), n.markAsDirty(t, f, { bubble: !0 });
1394
- let M = [...f];
1353
+ const { value: y } = l;
1354
+ o.updateShadowAtPath(t, d, y), o.markAsDirty(t, d, { bubble: !0 });
1355
+ let _ = [...d];
1395
1356
  for (; ; ) {
1396
- const k = n.getShadowMetadata(
1357
+ const M = o.getShadowMetadata(
1397
1358
  t,
1398
- M
1359
+ _
1399
1360
  );
1400
- if (k?.pathComponents && k.pathComponents.forEach((V) => {
1401
- if (!d.has(V)) {
1402
- const $ = i.components?.get(V);
1403
- $ && ($.forceUpdate(), d.add(V));
1361
+ if (M?.pathComponents && M.pathComponents.forEach((E) => {
1362
+ if (!p.has(E)) {
1363
+ const A = i.components?.get(E);
1364
+ A && (A.forceUpdate(), p.add(E));
1404
1365
  }
1405
- }), M.length === 0) break;
1406
- M.pop();
1366
+ }), _.length === 0) break;
1367
+ _.pop();
1407
1368
  }
1408
1369
  break;
1409
1370
  }
1410
1371
  case "remove": {
1411
- const D = f.slice(0, -1);
1412
- n.removeShadowArrayElement(t, f), n.markAsDirty(t, D, { bubble: !0 });
1413
- let M = [...D];
1372
+ const y = d.slice(0, -1);
1373
+ o.removeShadowArrayElement(t, d), o.markAsDirty(t, y, { bubble: !0 });
1374
+ let _ = [...y];
1414
1375
  for (; ; ) {
1415
- const k = n.getShadowMetadata(
1376
+ const M = o.getShadowMetadata(
1416
1377
  t,
1417
- M
1378
+ _
1418
1379
  );
1419
- if (k?.pathComponents && k.pathComponents.forEach((V) => {
1420
- if (!d.has(V)) {
1421
- const $ = i.components?.get(V);
1422
- $ && ($.forceUpdate(), d.add(V));
1380
+ if (M?.pathComponents && M.pathComponents.forEach((E) => {
1381
+ if (!p.has(E)) {
1382
+ const A = i.components?.get(E);
1383
+ A && (A.forceUpdate(), p.add(E));
1423
1384
  }
1424
- }), M.length === 0) break;
1425
- M.pop();
1385
+ }), _.length === 0) break;
1386
+ _.pop();
1426
1387
  }
1427
1388
  break;
1428
1389
  }
1429
1390
  }
1430
1391
  }
1431
1392
  };
1432
- if (p === "getComponents")
1433
- return () => e.getState().getShadowMetadata(t, [])?.components;
1434
- if (p === "getAllFormRefs")
1435
- return () => ht.getState().getFormRefsByStateKey(t);
1393
+ if (u === "getComponents")
1394
+ return () => a.getState().getShadowMetadata(t, [])?.components;
1395
+ if (u === "getAllFormRefs")
1396
+ return () => St.getState().getFormRefsByStateKey(t);
1436
1397
  }
1437
- if (p === "getFormRef")
1438
- return () => ht.getState().getFormRef(t + "." + o.join("."));
1439
- if (p === "validationWrapper")
1398
+ if (u === "getFormRef")
1399
+ return () => St.getState().getFormRef(t + "." + e.join("."));
1400
+ if (u === "validationWrapper")
1440
1401
  return ({
1441
- children: r,
1442
- hideMessage: n
1443
- }) => /* @__PURE__ */ it(
1444
- At,
1402
+ children: n,
1403
+ hideMessage: o
1404
+ }) => /* @__PURE__ */ nt(
1405
+ bt,
1445
1406
  {
1446
- formOpts: n ? { validation: { message: "" } } : void 0,
1447
- path: o,
1407
+ formOpts: o ? { validation: { message: "" } } : void 0,
1408
+ path: e,
1448
1409
  stateKey: t,
1449
- children: r
1410
+ children: n
1450
1411
  }
1451
1412
  );
1452
- if (p === "_stateKey") return t;
1453
- if (p === "_path") return o;
1454
- if (p === "update")
1455
- return (r) => (a(r, o, { updateType: "update" }), {
1413
+ if (u === "_stateKey") return t;
1414
+ if (u === "_path") return e;
1415
+ if (u === "update")
1416
+ return (n) => (r(n, e, { updateType: "update" }), {
1456
1417
  /**
1457
1418
  * Marks this specific item, which was just updated, as 'synced' (not dirty).
1458
1419
  */
1459
1420
  synced: () => {
1460
- const n = e.getState().getShadowMetadata(t, o);
1461
- e.getState().setShadowMetadata(t, o, {
1462
- ...n,
1421
+ const o = a.getState().getShadowMetadata(t, e);
1422
+ a.getState().setShadowMetadata(t, e, {
1423
+ ...o,
1463
1424
  isDirty: !1,
1464
1425
  // EXPLICITLY set to false, not just undefined
1465
1426
  stateSource: "server",
@@ -1467,460 +1428,453 @@ function Pt(t, a, m, g) {
1467
1428
  lastServerSync: Date.now()
1468
1429
  // Add timestamp
1469
1430
  });
1470
- const i = [t, ...o].join(".");
1471
- e.getState().notifyPathSubscribers(i, {
1431
+ const i = [t, ...e].join(".");
1432
+ a.getState().notifyPathSubscribers(i, {
1472
1433
  type: "SYNC_STATUS_CHANGE",
1473
1434
  isDirty: !1
1474
1435
  });
1475
1436
  }
1476
1437
  });
1477
- if (p === "toggle") {
1478
- const r = e.getState().getShadowValue([t, ...o].join("."));
1479
- if (console.log("currentValueAtPath", r), typeof b != "boolean")
1438
+ if (u === "toggle") {
1439
+ const n = a.getState().getShadowValue([t, ...e].join(".")), o = a.getState().getShadowValue([t, ...e].join("."), s?.validIds);
1440
+ if (console.log("currentValueAtPath", n), typeof o != "boolean")
1480
1441
  throw new Error("toggle() can only be used on boolean values");
1481
1442
  return () => {
1482
- a(!r, o, {
1443
+ r(!n, e, {
1483
1444
  updateType: "update"
1484
1445
  });
1485
1446
  };
1486
1447
  }
1487
- if (p === "formElement")
1488
- return (r, n) => /* @__PURE__ */ it(
1489
- Yt,
1448
+ if (u === "formElement")
1449
+ return (n, o) => /* @__PURE__ */ nt(
1450
+ qt,
1490
1451
  {
1491
1452
  stateKey: t,
1492
- path: o,
1493
- rebuildStateShape: s,
1494
- setState: a,
1495
- formOpts: n,
1496
- renderFn: r
1453
+ path: e,
1454
+ rebuildStateShape: f,
1455
+ setState: r,
1456
+ formOpts: o,
1457
+ renderFn: n
1497
1458
  }
1498
1459
  );
1499
- const tt = [...o, p], Q = e.getState().getShadowValue(t, tt);
1500
- return s({
1501
- currentState: Q,
1502
- path: tt,
1503
- componentId: _,
1504
- meta: h
1460
+ const Y = [...e, u];
1461
+ return a.getState().getShadowValue(t, Y), f({
1462
+ path: Y,
1463
+ componentId: v,
1464
+ meta: s
1505
1465
  });
1506
1466
  }
1507
- }, W = new Proxy(B, S);
1508
- return y.set(x, {
1509
- proxy: W,
1510
- stateVersion: I
1511
- }), W;
1467
+ }, J = new Proxy(W, H);
1468
+ return w.set(L, J), J;
1512
1469
  }
1513
- const l = {
1514
- revertToInitialState: (b) => {
1515
- e.getState().getInitialOptions(t)?.validation;
1516
- const o = e.getState().getShadowMetadata(t, []);
1517
- o?.stateSource === "server" && o.baseServerState ? o.baseServerState : e.getState().initialStateGlobal[t];
1518
- const h = e.getState().initialStateGlobal[t];
1519
- e.getState().clearSelectedIndexesForState(t), y.clear(), I++, e.getState().initializeShadowState(t, h), s({
1520
- currentState: h,
1470
+ const b = {
1471
+ revertToInitialState: (e) => {
1472
+ a.getState().getInitialOptions(t)?.validation;
1473
+ const s = a.getState().getShadowMetadata(t, []);
1474
+ s?.stateSource === "server" && s.baseServerState ? s.baseServerState : a.getState().initialStateGlobal[t];
1475
+ const v = a.getState().initialStateGlobal[t];
1476
+ a.getState().clearSelectedIndexesForState(t), a.getState().initializeShadowState(t, v), f({
1521
1477
  path: [],
1522
- componentId: m
1478
+ componentId: h
1523
1479
  });
1524
- const _ = ot(t), x = rt(_?.localStorage?.key) ? _?.localStorage?.key(h) : _?.localStorage?.key, R = `${g}-${t}-${x}`;
1525
- R && localStorage.removeItem(R);
1526
- const B = e.getState().getShadowMetadata(t, []);
1527
- return B && B?.components?.forEach((S) => {
1528
- S.forceUpdate();
1529
- }), h;
1480
+ const R = at(t), L = tt(R?.localStorage?.key) ? R?.localStorage?.key(v) : R?.localStorage?.key, k = `${g}-${t}-${L}`;
1481
+ k && localStorage.removeItem(k);
1482
+ const W = a.getState().getShadowMetadata(t, []);
1483
+ return W && W?.components?.forEach((H) => {
1484
+ H.forceUpdate();
1485
+ }), v;
1530
1486
  },
1531
- updateInitialState: (b) => {
1532
- y.clear(), I++;
1533
- const o = Pt(
1487
+ updateInitialState: (e) => {
1488
+ const s = At(
1534
1489
  t,
1535
- a,
1536
- m,
1490
+ r,
1491
+ h,
1537
1492
  g
1538
- ), h = e.getState().initialStateGlobal[t], _ = ot(t), x = rt(_?.localStorage?.key) ? _?.localStorage?.key(h) : _?.localStorage?.key, R = `${g}-${t}-${x}`;
1539
- return localStorage.getItem(R) && localStorage.removeItem(R), Ut(() => {
1540
- Ct(t, b), e.getState().initializeShadowState(t, b);
1541
- const B = e.getState().getShadowMetadata(t, []);
1542
- B && B?.components?.forEach((S) => {
1543
- S.forceUpdate();
1493
+ ), v = a.getState().initialStateGlobal[t], R = at(t), L = tt(R?.localStorage?.key) ? R?.localStorage?.key(v) : R?.localStorage?.key, k = `${g}-${t}-${L}`;
1494
+ return localStorage.getItem(k) && localStorage.removeItem(k), kt(() => {
1495
+ Vt(t, e), a.getState().initializeShadowState(t, e);
1496
+ const W = a.getState().getShadowMetadata(t, []);
1497
+ W && W?.components?.forEach((H) => {
1498
+ H.forceUpdate();
1544
1499
  });
1545
1500
  }), {
1546
- fetchId: (B) => o.get()[B]
1501
+ fetchId: (W) => s.get()[W]
1547
1502
  };
1548
1503
  }
1549
1504
  };
1550
- return s({
1551
- currentState: e.getState().getShadowValue(t, []),
1552
- componentId: m,
1505
+ return f({
1506
+ componentId: h,
1553
1507
  path: []
1554
1508
  });
1555
1509
  }
1556
- function bt(t) {
1557
- return ut(zt, { proxy: t });
1510
+ function It(t) {
1511
+ return it(xt, { proxy: t });
1558
1512
  }
1559
- function qt({
1513
+ function Ht({
1560
1514
  proxy: t,
1561
- rebuildStateShape: a
1515
+ rebuildStateShape: r
1562
1516
  }) {
1563
- const m = z(null), g = z(`map-${crypto.randomUUID()}`), y = z(!1), I = z(/* @__PURE__ */ new Map());
1564
- et(() => {
1565
- const s = m.current;
1566
- if (!s || y.current) return;
1567
- const l = setTimeout(() => {
1568
- const P = e.getState().getShadowMetadata(t._stateKey, t._path) || {}, b = P.mapWrappers || [];
1569
- b.push({
1517
+ const h = z(null), g = z(`map-${crypto.randomUUID()}`), w = z(!1), f = z(/* @__PURE__ */ new Map());
1518
+ Q(() => {
1519
+ const S = h.current;
1520
+ if (!S || w.current) return;
1521
+ const e = setTimeout(() => {
1522
+ const s = a.getState().getShadowMetadata(t._stateKey, t._path) || {}, v = s.mapWrappers || [];
1523
+ v.push({
1570
1524
  instanceId: g.current,
1571
1525
  mapFn: t._mapFn,
1572
- containerRef: s,
1573
- rebuildStateShape: a,
1526
+ containerRef: S,
1527
+ rebuildStateShape: r,
1574
1528
  path: t._path,
1575
1529
  componentId: g.current,
1576
1530
  meta: t._meta
1577
- }), e.getState().setShadowMetadata(t._stateKey, t._path, {
1578
- ...P,
1579
- mapWrappers: b
1580
- }), y.current = !0, T();
1531
+ }), a.getState().setShadowMetadata(t._stateKey, t._path, {
1532
+ ...s,
1533
+ mapWrappers: v
1534
+ }), w.current = !0, b();
1581
1535
  }, 0);
1582
1536
  return () => {
1583
- if (clearTimeout(l), g.current) {
1584
- const P = e.getState().getShadowMetadata(t._stateKey, t._path) || {};
1585
- P.mapWrappers && (P.mapWrappers = P.mapWrappers.filter(
1586
- (b) => b.instanceId !== g.current
1587
- ), e.getState().setShadowMetadata(t._stateKey, t._path, P));
1537
+ if (clearTimeout(e), g.current) {
1538
+ const s = a.getState().getShadowMetadata(t._stateKey, t._path) || {};
1539
+ s.mapWrappers && (s.mapWrappers = s.mapWrappers.filter(
1540
+ (v) => v.instanceId !== g.current
1541
+ ), a.getState().setShadowMetadata(t._stateKey, t._path, s));
1588
1542
  }
1589
- I.current.forEach((P) => P.unmount());
1543
+ f.current.forEach((s) => s.unmount());
1590
1544
  };
1591
1545
  }, []);
1592
- const T = () => {
1593
- const s = m.current;
1594
- if (!s) return;
1595
- const l = e.getState().getShadowValue(
1546
+ const b = () => {
1547
+ const S = h.current;
1548
+ if (!S) return;
1549
+ const e = a.getState().getShadowValue(
1596
1550
  [t._stateKey, ...t._path].join("."),
1597
1551
  t._meta?.validIds
1598
1552
  );
1599
- if (!Array.isArray(l)) return;
1600
- const P = t._meta?.validIds ?? e.getState().getShadowMetadata(t._stateKey, t._path)?.arrayKeys ?? [], b = a({
1601
- currentState: l,
1553
+ if (!Array.isArray(e)) return;
1554
+ const s = t._meta?.validIds ?? a.getState().getShadowMetadata(t._stateKey, t._path)?.arrayKeys ?? [], v = r({
1555
+ currentState: e,
1602
1556
  path: t._path,
1603
1557
  componentId: g.current,
1604
1558
  meta: t._meta
1605
1559
  });
1606
- l.forEach((o, h) => {
1607
- const _ = P[h];
1608
- if (!_) return;
1609
- const x = nt(), R = document.createElement("div");
1610
- R.setAttribute("data-item-path", _), s.appendChild(R);
1611
- const B = Vt(R);
1612
- I.current.set(_, B);
1613
- const S = _.split(".").slice(1);
1614
- B.render(
1615
- ut(wt, {
1560
+ e.forEach((R, L) => {
1561
+ const k = s[L];
1562
+ if (!k) return;
1563
+ const W = et(), H = document.createElement("div");
1564
+ H.setAttribute("data-item-path", k), S.appendChild(H);
1565
+ const J = Mt(H);
1566
+ f.current.set(k, J);
1567
+ const m = k.split(".").slice(1);
1568
+ J.render(
1569
+ it(yt, {
1616
1570
  stateKey: t._stateKey,
1617
- itemComponentId: x,
1618
- itemPath: S,
1619
- localIndex: h,
1620
- arraySetter: b,
1621
- rebuildStateShape: a,
1571
+ itemComponentId: W,
1572
+ itemPath: m,
1573
+ localIndex: L,
1574
+ arraySetter: v,
1575
+ rebuildStateShape: r,
1622
1576
  renderFn: t._mapFn
1623
1577
  })
1624
1578
  );
1625
1579
  });
1626
1580
  };
1627
- return /* @__PURE__ */ it("div", { ref: m, "data-map-container": g.current });
1581
+ return /* @__PURE__ */ nt("div", { ref: h, "data-map-container": g.current });
1628
1582
  }
1629
- function zt({
1583
+ function xt({
1630
1584
  proxy: t
1631
1585
  }) {
1632
- const a = z(null), m = z(null), g = z(!1), y = `${t._stateKey}-${t._path.join(".")}`, I = e.getState().getShadowValue(
1586
+ const r = z(null), h = z(null), g = z(!1), w = `${t._stateKey}-${t._path.join(".")}`, f = a.getState().getShadowValue(
1633
1587
  [t._stateKey, ...t._path].join("."),
1634
1588
  t._meta?.validIds
1635
1589
  );
1636
- return et(() => {
1637
- const T = a.current;
1638
- if (!T || g.current) return;
1639
- const s = setTimeout(() => {
1640
- if (!T.parentElement) {
1641
- console.warn("Parent element not found for signal", y);
1590
+ return Q(() => {
1591
+ const b = r.current;
1592
+ if (!b || g.current) return;
1593
+ const S = setTimeout(() => {
1594
+ if (!b.parentElement) {
1595
+ console.warn("Parent element not found for signal", w);
1642
1596
  return;
1643
1597
  }
1644
- const l = T.parentElement, b = Array.from(l.childNodes).indexOf(T);
1645
- let o = l.getAttribute("data-parent-id");
1646
- o || (o = `parent-${crypto.randomUUID()}`, l.setAttribute("data-parent-id", o)), m.current = `instance-${crypto.randomUUID()}`;
1647
- const h = e.getState().getShadowMetadata(t._stateKey, t._path) || {}, _ = h.signals || [];
1648
- _.push({
1649
- instanceId: m.current,
1650
- parentId: o,
1651
- position: b,
1598
+ const e = b.parentElement, v = Array.from(e.childNodes).indexOf(b);
1599
+ let R = e.getAttribute("data-parent-id");
1600
+ R || (R = `parent-${crypto.randomUUID()}`, e.setAttribute("data-parent-id", R)), h.current = `instance-${crypto.randomUUID()}`;
1601
+ const L = a.getState().getShadowMetadata(t._stateKey, t._path) || {}, k = L.signals || [];
1602
+ k.push({
1603
+ instanceId: h.current,
1604
+ parentId: R,
1605
+ position: v,
1652
1606
  effect: t._effect
1653
- }), e.getState().setShadowMetadata(t._stateKey, t._path, {
1654
- ...h,
1655
- signals: _
1607
+ }), a.getState().setShadowMetadata(t._stateKey, t._path, {
1608
+ ...L,
1609
+ signals: k
1656
1610
  });
1657
- let x = I;
1611
+ let W = f;
1658
1612
  if (t._effect)
1659
1613
  try {
1660
- x = new Function(
1614
+ W = new Function(
1661
1615
  "state",
1662
1616
  `return (${t._effect})(state)`
1663
- )(I);
1664
- } catch (B) {
1665
- console.error("Error evaluating effect function:", B);
1617
+ )(f);
1618
+ } catch (J) {
1619
+ console.error("Error evaluating effect function:", J);
1666
1620
  }
1667
- x !== null && typeof x == "object" && (x = JSON.stringify(x));
1668
- const R = document.createTextNode(String(x ?? ""));
1669
- T.replaceWith(R), g.current = !0;
1621
+ W !== null && typeof W == "object" && (W = JSON.stringify(W));
1622
+ const H = document.createTextNode(String(W ?? ""));
1623
+ b.replaceWith(H), g.current = !0;
1670
1624
  }, 0);
1671
1625
  return () => {
1672
- if (clearTimeout(s), m.current) {
1673
- const l = e.getState().getShadowMetadata(t._stateKey, t._path) || {};
1674
- l.signals && (l.signals = l.signals.filter(
1675
- (P) => P.instanceId !== m.current
1676
- ), e.getState().setShadowMetadata(t._stateKey, t._path, l));
1626
+ if (clearTimeout(S), h.current) {
1627
+ const e = a.getState().getShadowMetadata(t._stateKey, t._path) || {};
1628
+ e.signals && (e.signals = e.signals.filter(
1629
+ (s) => s.instanceId !== h.current
1630
+ ), a.getState().setShadowMetadata(t._stateKey, t._path, e));
1677
1631
  }
1678
1632
  };
1679
- }, []), ut("span", {
1680
- ref: a,
1633
+ }, []), it("span", {
1634
+ ref: r,
1681
1635
  style: { display: "contents" },
1682
- "data-signal-id": y
1636
+ "data-signal-id": w
1683
1637
  });
1684
1638
  }
1685
- const wt = $t(
1686
- Jt,
1687
- (t, a) => t.itemPath.join(".") === a.itemPath.join(".") && t.stateKey === a.stateKey && t.itemComponentId === a.itemComponentId && t.localIndex === a.localIndex
1688
- ), Gt = (t) => {
1689
- const [a, m] = at(!1);
1690
- return dt(() => {
1639
+ const yt = Dt(
1640
+ zt,
1641
+ (t, r) => t.itemPath.join(".") === r.itemPath.join(".") && t.stateKey === r.stateKey && t.itemComponentId === r.itemComponentId && t.localIndex === r.localIndex
1642
+ ), Bt = (t) => {
1643
+ const [r, h] = X(!1);
1644
+ return ct(() => {
1691
1645
  if (!t.current) {
1692
- m(!0);
1646
+ h(!0);
1693
1647
  return;
1694
1648
  }
1695
1649
  const g = Array.from(t.current.querySelectorAll("img"));
1696
1650
  if (g.length === 0) {
1697
- m(!0);
1651
+ h(!0);
1698
1652
  return;
1699
1653
  }
1700
- let y = 0;
1701
- const I = () => {
1702
- y++, y === g.length && m(!0);
1654
+ let w = 0;
1655
+ const f = () => {
1656
+ w++, w === g.length && h(!0);
1703
1657
  };
1704
- return g.forEach((T) => {
1705
- T.complete ? I() : (T.addEventListener("load", I), T.addEventListener("error", I));
1658
+ return g.forEach((b) => {
1659
+ b.complete ? f() : (b.addEventListener("load", f), b.addEventListener("error", f));
1706
1660
  }), () => {
1707
- g.forEach((T) => {
1708
- T.removeEventListener("load", I), T.removeEventListener("error", I);
1661
+ g.forEach((b) => {
1662
+ b.removeEventListener("load", f), b.removeEventListener("error", f);
1709
1663
  });
1710
1664
  };
1711
- }, [t.current]), a;
1665
+ }, [t.current]), r;
1712
1666
  };
1713
- function Jt({
1667
+ function zt({
1714
1668
  stateKey: t,
1715
- itemComponentId: a,
1716
- itemPath: m,
1669
+ itemComponentId: r,
1670
+ itemPath: h,
1717
1671
  localIndex: g,
1718
- arraySetter: y,
1719
- rebuildStateShape: I,
1720
- renderFn: T
1672
+ arraySetter: w,
1673
+ rebuildStateShape: f,
1674
+ renderFn: b
1721
1675
  }) {
1722
- const [, s] = at({}), { ref: l, inView: P } = Nt(), b = z(null), o = Gt(b), h = z(!1), _ = [t, ...m].join(".");
1723
- Dt(t, a, s);
1724
- const x = lt(
1725
- (q) => {
1726
- b.current = q, l(q);
1676
+ const [, S] = X({}), { ref: e, inView: s } = $t(), v = z(null), R = Bt(v), L = z(!1), k = [t, ...h].join(".");
1677
+ _t(t, r, S);
1678
+ const W = st(
1679
+ (j) => {
1680
+ v.current = j, e(j);
1727
1681
  },
1728
- [l]
1682
+ [e]
1729
1683
  );
1730
- et(() => {
1731
- e.getState().subscribeToPath(_, (q) => {
1732
- s({});
1684
+ Q(() => {
1685
+ a.getState().subscribeToPath(k, (j) => {
1686
+ S({});
1733
1687
  });
1734
- }, []), et(() => {
1735
- if (!P || !o || h.current)
1688
+ }, []), Q(() => {
1689
+ if (!s || !R || L.current)
1736
1690
  return;
1737
- const q = b.current;
1738
- if (q && q.offsetHeight > 0) {
1739
- h.current = !0;
1740
- const p = q.offsetHeight;
1741
- e.getState().setShadowMetadata(t, m, {
1691
+ const j = v.current;
1692
+ if (j && j.offsetHeight > 0) {
1693
+ L.current = !0;
1694
+ const Y = j.offsetHeight;
1695
+ a.getState().setShadowMetadata(t, h, {
1742
1696
  virtualizer: {
1743
- itemHeight: p,
1744
- domRef: q
1697
+ itemHeight: Y,
1698
+ domRef: j
1745
1699
  }
1746
1700
  });
1747
- const Y = m.slice(0, -1), tt = [t, ...Y].join(".");
1748
- e.getState().notifyPathSubscribers(tt, {
1701
+ const n = h.slice(0, -1), o = [t, ...n].join(".");
1702
+ a.getState().notifyPathSubscribers(o, {
1749
1703
  type: "ITEMHEIGHT",
1750
- itemKey: m.join("."),
1751
- ref: b.current
1704
+ itemKey: h.join("."),
1705
+ ref: v.current
1752
1706
  });
1753
1707
  }
1754
- }, [P, o, t, m]);
1755
- const R = [t, ...m].join("."), B = e.getState().getShadowValue(R);
1756
- if (B === void 0)
1708
+ }, [s, R, t, h]);
1709
+ const H = [t, ...h].join("."), J = a.getState().getShadowValue(H);
1710
+ if (J === void 0)
1757
1711
  return null;
1758
- const S = I({
1759
- currentState: B,
1760
- path: m,
1761
- componentId: a
1762
- }), W = T(S, g, y);
1763
- return /* @__PURE__ */ it("div", { ref: x, children: W });
1712
+ const m = f({
1713
+ currentState: J,
1714
+ path: h,
1715
+ componentId: r
1716
+ }), u = b(m, g, w);
1717
+ return /* @__PURE__ */ nt("div", { ref: W, children: u });
1764
1718
  }
1765
- function Yt({
1719
+ function qt({
1766
1720
  stateKey: t,
1767
- path: a,
1768
- rebuildStateShape: m,
1721
+ path: r,
1722
+ rebuildStateShape: h,
1769
1723
  renderFn: g,
1770
- formOpts: y,
1771
- setState: I
1724
+ formOpts: w,
1725
+ setState: f
1772
1726
  }) {
1773
- const [T] = at(() => nt()), [, s] = at({}), l = [t, ...a].join(".");
1774
- Dt(t, T, s);
1775
- const P = e.getState().getShadowValue(l), [b, o] = at(P), h = z(!1), _ = z(null);
1776
- et(() => {
1777
- !h.current && !ct(P, b) && o(P);
1778
- }, [P]), et(() => {
1779
- const W = e.getState().subscribeToPath(l, (q) => {
1780
- !h.current && b !== q && s({});
1727
+ const [b] = X(() => et()), [, S] = X({}), e = [t, ...r].join(".");
1728
+ _t(t, b, S);
1729
+ const s = a.getState().getShadowValue(e), [v, R] = X(s), L = z(!1), k = z(null);
1730
+ Q(() => {
1731
+ !L.current && !ot(s, v) && R(s);
1732
+ }, [s]), Q(() => {
1733
+ const u = a.getState().subscribeToPath(e, (j) => {
1734
+ !L.current && v !== j && S({});
1781
1735
  });
1782
1736
  return () => {
1783
- W(), _.current && (clearTimeout(_.current), h.current = !1);
1737
+ u(), k.current && (clearTimeout(k.current), L.current = !1);
1784
1738
  };
1785
1739
  }, []);
1786
- const x = lt(
1787
- (W) => {
1788
- typeof P === "number" && typeof W == "string" && (W = W === "" ? 0 : Number(W)), o(W), h.current = !0, _.current && clearTimeout(_.current);
1789
- const p = y?.debounceTime ?? 200;
1790
- _.current = setTimeout(() => {
1791
- h.current = !1, I(W, a, { updateType: "update" });
1792
- const { getInitialOptions: Y, setShadowMetadata: tt, getShadowMetadata: Q } = e.getState(), r = Y(t)?.validation, n = r?.zodSchemaV4 || r?.zodSchemaV3;
1793
- if (n) {
1794
- const i = e.getState().getShadowValue(t), u = n.safeParse(i), d = Q(t, a) || {};
1795
- if (u.success)
1796
- tt(t, a, {
1797
- ...d,
1740
+ const W = st(
1741
+ (u) => {
1742
+ typeof s === "number" && typeof u == "string" && (u = u === "" ? 0 : Number(u)), R(u), L.current = !0, k.current && clearTimeout(k.current);
1743
+ const Y = w?.debounceTime ?? 200;
1744
+ k.current = setTimeout(() => {
1745
+ L.current = !1, f(u, r, { updateType: "update" });
1746
+ const { getInitialOptions: n, setShadowMetadata: o, getShadowMetadata: i } = a.getState(), c = n(t)?.validation, p = c?.zodSchemaV4 || c?.zodSchemaV3;
1747
+ if (p) {
1748
+ const l = a.getState().getShadowValue(t), d = p.safeParse(l), y = i(t, r) || {};
1749
+ if (d.success)
1750
+ o(t, r, {
1751
+ ...y,
1798
1752
  validation: {
1799
1753
  status: "VALID_LIVE",
1800
- validatedValue: W,
1754
+ validatedValue: u,
1801
1755
  message: void 0
1802
1756
  }
1803
1757
  });
1804
1758
  else {
1805
- const f = ("issues" in u.error ? u.error.issues : u.error.errors).filter(
1806
- (D) => JSON.stringify(D.path) === JSON.stringify(a)
1759
+ const M = ("issues" in d.error ? d.error.issues : d.error.errors).filter(
1760
+ (E) => JSON.stringify(E.path) === JSON.stringify(r)
1807
1761
  );
1808
- f.length > 0 ? tt(t, a, {
1809
- ...d,
1762
+ M.length > 0 ? o(t, r, {
1763
+ ...y,
1810
1764
  validation: {
1811
1765
  status: "INVALID_LIVE",
1812
- message: f[0]?.message,
1813
- validatedValue: W
1766
+ message: M[0]?.message,
1767
+ validatedValue: u
1814
1768
  }
1815
- }) : tt(t, a, {
1816
- ...d,
1769
+ }) : o(t, r, {
1770
+ ...y,
1817
1771
  validation: {
1818
1772
  status: "VALID_LIVE",
1819
- validatedValue: W,
1773
+ validatedValue: u,
1820
1774
  message: void 0
1821
1775
  }
1822
1776
  });
1823
1777
  }
1824
1778
  }
1825
- }, p), s({});
1779
+ }, Y), S({});
1826
1780
  },
1827
- [I, a, y?.debounceTime, t]
1828
- ), R = lt(async () => {
1829
- console.log("handleBlur triggered"), _.current && (clearTimeout(_.current), _.current = null, h.current = !1, I(b, a, { updateType: "update" }));
1830
- const { getInitialOptions: W } = e.getState(), q = W(t)?.validation, p = q?.zodSchemaV4 || q?.zodSchemaV3;
1831
- if (!p) return;
1832
- const Y = e.getState().getShadowMetadata(t, a);
1833
- e.getState().setShadowMetadata(t, a, {
1834
- ...Y,
1781
+ [f, r, w?.debounceTime, t]
1782
+ ), H = st(async () => {
1783
+ console.log("handleBlur triggered"), k.current && (clearTimeout(k.current), k.current = null, L.current = !1, f(v, r, { updateType: "update" }));
1784
+ const { getInitialOptions: u } = a.getState(), j = u(t)?.validation, Y = j?.zodSchemaV4 || j?.zodSchemaV3;
1785
+ if (!Y) return;
1786
+ const n = a.getState().getShadowMetadata(t, r);
1787
+ a.getState().setShadowMetadata(t, r, {
1788
+ ...n,
1835
1789
  validation: {
1836
1790
  status: "DIRTY",
1837
- validatedValue: b
1791
+ validatedValue: v
1838
1792
  }
1839
1793
  });
1840
- const tt = e.getState().getShadowValue(t), Q = p.safeParse(tt);
1841
- if (console.log("result ", Q), Q.success)
1842
- e.getState().setShadowMetadata(t, a, {
1843
- ...Y,
1794
+ const o = a.getState().getShadowValue(t), i = Y.safeParse(o);
1795
+ if (console.log("result ", i), i.success)
1796
+ a.getState().setShadowMetadata(t, r, {
1797
+ ...n,
1844
1798
  validation: {
1845
1799
  status: "VALID_PENDING_SYNC",
1846
- validatedValue: b
1800
+ validatedValue: v
1847
1801
  }
1848
1802
  });
1849
1803
  else {
1850
- const r = "issues" in Q.error ? Q.error.issues : Q.error.errors;
1851
- console.log("All validation errors:", r), console.log("Current blur path:", a);
1852
- const n = r.filter((i) => {
1853
- if (console.log("Processing error:", i), a.some((d) => d.startsWith("id:"))) {
1804
+ const c = "issues" in i.error ? i.error.issues : i.error.errors;
1805
+ console.log("All validation errors:", c), console.log("Current blur path:", r);
1806
+ const p = c.filter((l) => {
1807
+ if (console.log("Processing error:", l), r.some((y) => y.startsWith("id:"))) {
1854
1808
  console.log("Detected array path with ULID");
1855
- const d = a[0].startsWith("id:") ? [] : a.slice(0, -1);
1856
- console.log("Parent path:", d);
1857
- const c = e.getState().getShadowMetadata(t, d);
1858
- if (console.log("Array metadata:", c), c?.arrayKeys) {
1859
- const f = [t, ...a.slice(0, -1)].join("."), D = c.arrayKeys.indexOf(f);
1860
- console.log("Item key:", f, "Index:", D);
1861
- const M = [...d, D, ...a.slice(-1)], k = JSON.stringify(i.path) === JSON.stringify(M);
1809
+ const y = r[0].startsWith("id:") ? [] : r.slice(0, -1);
1810
+ console.log("Parent path:", y);
1811
+ const _ = a.getState().getShadowMetadata(t, y);
1812
+ if (console.log("Array metadata:", _), _?.arrayKeys) {
1813
+ const M = [t, ...r.slice(0, -1)].join("."), E = _.arrayKeys.indexOf(M);
1814
+ console.log("Item key:", M, "Index:", E);
1815
+ const A = [...y, E, ...r.slice(-1)], U = JSON.stringify(l.path) === JSON.stringify(A);
1862
1816
  return console.log("Zod path comparison:", {
1863
- zodPath: M,
1864
- errorPath: i.path,
1865
- match: k
1866
- }), k;
1817
+ zodPath: A,
1818
+ errorPath: l.path,
1819
+ match: U
1820
+ }), U;
1867
1821
  }
1868
1822
  }
1869
- const u = JSON.stringify(i.path) === JSON.stringify(a);
1823
+ const d = JSON.stringify(l.path) === JSON.stringify(r);
1870
1824
  return console.log("Direct path comparison:", {
1871
- errorPath: i.path,
1872
- currentPath: a,
1873
- match: u
1874
- }), u;
1825
+ errorPath: l.path,
1826
+ currentPath: r,
1827
+ match: d
1828
+ }), d;
1875
1829
  });
1876
- console.log("Filtered path errors:", n), e.getState().setShadowMetadata(t, a, {
1877
- ...Y,
1830
+ console.log("Filtered path errors:", p), a.getState().setShadowMetadata(t, r, {
1831
+ ...n,
1878
1832
  validation: {
1879
1833
  status: "VALIDATION_FAILED",
1880
- message: n[0]?.message,
1881
- validatedValue: b
1834
+ message: p[0]?.message,
1835
+ validatedValue: v
1882
1836
  }
1883
1837
  });
1884
1838
  }
1885
- s({});
1886
- }, [t, a, b, I]), B = m({
1887
- currentState: P,
1888
- path: a,
1889
- componentId: T
1890
- }), S = new Proxy(B, {
1891
- get(W, q) {
1892
- return q === "inputProps" ? {
1893
- value: b ?? "",
1894
- onChange: (p) => {
1895
- x(p.target.value);
1839
+ S({});
1840
+ }, [t, r, v, f]), J = h({
1841
+ currentState: s,
1842
+ path: r,
1843
+ componentId: b
1844
+ }), m = new Proxy(J, {
1845
+ get(u, j) {
1846
+ return j === "inputProps" ? {
1847
+ value: v ?? "",
1848
+ onChange: (Y) => {
1849
+ W(Y.target.value);
1896
1850
  },
1897
1851
  // 5. Wire the new onBlur handler to the input props.
1898
- onBlur: R,
1899
- ref: ht.getState().getFormRef(t + "." + a.join("."))
1900
- } : W[q];
1852
+ onBlur: H,
1853
+ ref: St.getState().getFormRef(t + "." + r.join("."))
1854
+ } : u[j];
1901
1855
  }
1902
1856
  });
1903
- return /* @__PURE__ */ it(At, { formOpts: y, path: a, stateKey: t, children: g(S) });
1857
+ return /* @__PURE__ */ nt(bt, { formOpts: w, path: r, stateKey: t, children: g(m) });
1904
1858
  }
1905
- function Dt(t, a, m) {
1906
- const g = `${t}////${a}`;
1907
- dt(() => {
1908
- const { registerComponent: y, unregisterComponent: I } = e.getState();
1909
- return y(t, g, {
1910
- forceUpdate: () => m({}),
1859
+ function _t(t, r, h) {
1860
+ const g = `${t}////${r}`;
1861
+ ct(() => {
1862
+ const { registerComponent: w, unregisterComponent: f } = a.getState();
1863
+ return w(t, g, {
1864
+ forceUpdate: () => h({}),
1911
1865
  paths: /* @__PURE__ */ new Set(),
1912
1866
  reactiveType: ["component"]
1913
1867
  }), () => {
1914
- I(t, g);
1868
+ f(t, g);
1915
1869
  };
1916
1870
  }, [t, g]);
1917
1871
  }
1918
1872
  export {
1919
- bt as $cogsSignal,
1920
- se as addStateOptions,
1921
- Ft as createCogsState,
1922
- ie as createCogsStateFromSync,
1923
- ce as notifyComponent,
1924
- xt as useCogsStateFn
1873
+ It as $cogsSignal,
1874
+ re as addStateOptions,
1875
+ Rt as createCogsState,
1876
+ ne as createCogsStateFromSync,
1877
+ oe as notifyComponent,
1878
+ Lt as useCogsStateFn
1925
1879
  };
1926
1880
  //# sourceMappingURL=CogsState.jsx.map