cogsbox-state 0.5.471 → 0.5.472

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