cogsbox-state 0.5.464 → 0.5.466

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