baraqex 1.0.76 → 2.0.1

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.
Files changed (182) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +268 -315
  3. package/bin/baraqex.js +150 -12
  4. package/dist/browser.d.ts +1 -1
  5. package/dist/browser.d.ts.map +1 -1
  6. package/dist/browser.js +2319 -205
  7. package/dist/browser.js.map +4 -4
  8. package/dist/core/batch.d.ts +10 -0
  9. package/dist/core/batch.d.ts.map +1 -0
  10. package/dist/core/component.d.ts +69 -0
  11. package/dist/core/component.d.ts.map +1 -0
  12. package/dist/core/context.d.ts +22 -0
  13. package/dist/core/context.d.ts.map +1 -0
  14. package/dist/core/errors.d.ts +125 -0
  15. package/dist/core/errors.d.ts.map +1 -0
  16. package/dist/core/event-bus.d.ts +29 -0
  17. package/dist/core/event-bus.d.ts.map +1 -0
  18. package/dist/core/forms.d.ts +128 -0
  19. package/dist/core/forms.d.ts.map +1 -0
  20. package/dist/core/hooks.d.ts +84 -0
  21. package/dist/core/hooks.d.ts.map +1 -0
  22. package/dist/core/index.d.ts +23 -0
  23. package/dist/core/index.d.ts.map +1 -0
  24. package/dist/core/jsx-runtime.d.ts +45 -0
  25. package/dist/core/jsx-runtime.d.ts.map +1 -0
  26. package/dist/core/lifecycle-events.d.ts +71 -0
  27. package/dist/core/lifecycle-events.d.ts.map +1 -0
  28. package/dist/core/renderer.d.ts +39 -0
  29. package/dist/core/renderer.d.ts.map +1 -0
  30. package/dist/core/router.d.ts +108 -0
  31. package/dist/core/router.d.ts.map +1 -0
  32. package/dist/core/server-renderer.d.ts +26 -0
  33. package/dist/core/server-renderer.d.ts.map +1 -0
  34. package/dist/core/store.d.ts +102 -0
  35. package/dist/core/store.d.ts.map +1 -0
  36. package/dist/core/types.d.ts +66 -0
  37. package/dist/core/types.d.ts.map +1 -0
  38. package/dist/core/utils.d.ts +153 -0
  39. package/dist/core/utils.d.ts.map +1 -0
  40. package/dist/core/vdom.d.ts +29 -0
  41. package/dist/core/vdom.d.ts.map +1 -0
  42. package/dist/index.d.ts +39 -35
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +2596 -508
  45. package/dist/index.js.map +4 -4
  46. package/dist/server/auth.d.ts +8 -3
  47. package/dist/server/auth.d.ts.map +1 -1
  48. package/dist/server/index.d.ts +2 -2
  49. package/dist/server/index.d.ts.map +1 -1
  50. package/dist/server/index.js +173 -112
  51. package/dist/server/index.js.map +4 -4
  52. package/dist/server/middleware.d.ts +10 -1
  53. package/dist/server/middleware.d.ts.map +1 -1
  54. package/package.json +224 -124
  55. package/templates/basic-app/src/main.jsx +336 -0
  56. package/templates/complete-app/api/hello.js +0 -0
  57. package/templates/complete-app/client.js +58 -0
  58. package/templates/complete-app/lib/frontend-hamroun.js +182 -0
  59. package/templates/complete-app/package.json +18 -0
  60. package/templates/complete-app/pages/about.js +119 -0
  61. package/templates/complete-app/pages/about.jsx +0 -0
  62. package/templates/complete-app/pages/index.js +157 -0
  63. package/templates/complete-app/pages/index.jsx +0 -0
  64. package/templates/complete-app/pages/wasm-demo.js +290 -0
  65. package/templates/complete-app/pages/wasm-demo.jsx +0 -0
  66. package/templates/complete-app/public/client.js +89 -0
  67. package/templates/complete-app/public/index.html +118 -0
  68. package/templates/complete-app/public/styles.css +76 -0
  69. package/templates/complete-app/readme.md +188 -0
  70. package/templates/complete-app/server.js +226 -0
  71. package/templates/complete-app/server.ts +275 -0
  72. package/templates/complete-app/src/App.tsx +59 -0
  73. package/templates/complete-app/src/client.ts +61 -0
  74. package/templates/complete-app/src/client.tsx +18 -0
  75. package/templates/complete-app/src/pages/index.tsx +51 -0
  76. package/templates/complete-app/src/server.ts +218 -0
  77. package/templates/complete-app/tsconfig.json +22 -0
  78. package/templates/complete-app/tsconfig.server.json +19 -0
  79. package/templates/complete-app/vite.config.js +57 -0
  80. package/templates/complete-app/vite.config.ts +30 -0
  81. package/templates/complete-app/wasm/build.bat +0 -0
  82. package/templates/complete-app/wasm/build.sh +0 -0
  83. package/templates/complete-app/wasm/example.go +0 -0
  84. package/templates/fullstack-app/README.md +37 -0
  85. package/templates/fullstack-app/api/hello.js +11 -0
  86. package/templates/fullstack-app/api/hello.ts +18 -0
  87. package/templates/fullstack-app/api/users/[id].ts +73 -0
  88. package/templates/fullstack-app/api/users/index.ts +32 -0
  89. package/templates/fullstack-app/build/main.css +874 -0
  90. package/templates/fullstack-app/build/main.css.map +7 -0
  91. package/templates/fullstack-app/build/main.js +967 -0
  92. package/templates/fullstack-app/build/main.js.map +7 -0
  93. package/templates/fullstack-app/build.ts +210 -0
  94. package/templates/fullstack-app/index.html +36 -0
  95. package/templates/fullstack-app/package.json +35 -0
  96. package/templates/fullstack-app/postcss.config.js +6 -0
  97. package/templates/fullstack-app/process-tailwind.js +45 -0
  98. package/templates/fullstack-app/public/_redirects +1 -0
  99. package/templates/fullstack-app/public/route-handler.js +47 -0
  100. package/templates/fullstack-app/public/spa-fix.html +17 -0
  101. package/templates/fullstack-app/public/styles.css +975 -0
  102. package/templates/fullstack-app/public/tailwind.css +15 -0
  103. package/templates/fullstack-app/server.js +267 -0
  104. package/templates/fullstack-app/server.ts +474 -0
  105. package/templates/fullstack-app/src/README.md +55 -0
  106. package/templates/fullstack-app/src/client.js +87 -0
  107. package/templates/fullstack-app/src/components/ClientHome.tsx +0 -0
  108. package/templates/fullstack-app/src/components/ErrorBoundary.tsx +36 -0
  109. package/templates/fullstack-app/src/components/Layout.tsx +42 -0
  110. package/templates/fullstack-app/src/components/StateDemo.tsx +207 -0
  111. package/templates/fullstack-app/src/components/UserList.tsx +44 -0
  112. package/templates/fullstack-app/src/config.ts +42 -0
  113. package/templates/fullstack-app/src/data/api.ts +206 -0
  114. package/templates/fullstack-app/src/main.tsx +155 -0
  115. package/templates/fullstack-app/src/middleware.ts +28 -0
  116. package/templates/fullstack-app/src/pages/404.tsx +28 -0
  117. package/templates/fullstack-app/src/pages/[id].tsx +0 -0
  118. package/templates/fullstack-app/src/pages/_app.tsx +11 -0
  119. package/templates/fullstack-app/src/pages/_document.tsx +25 -0
  120. package/templates/fullstack-app/src/pages/_error.tsx +45 -0
  121. package/templates/fullstack-app/src/pages/about/index.tsx +67 -0
  122. package/templates/fullstack-app/src/pages/about.tsx +71 -0
  123. package/templates/fullstack-app/src/pages/api/users/[id].ts +73 -0
  124. package/templates/fullstack-app/src/pages/api/users/index.ts +43 -0
  125. package/templates/fullstack-app/src/pages/index.tsx +110 -0
  126. package/templates/fullstack-app/src/pages/users/[id].tsx +153 -0
  127. package/templates/fullstack-app/src/pages/users.tsx +60 -0
  128. package/templates/fullstack-app/src/pages/wasm-demo.tsx +1 -0
  129. package/templates/fullstack-app/src/router.ts +255 -0
  130. package/templates/fullstack-app/src/styles.css +5 -0
  131. package/templates/fullstack-app/tailwind.config.js +11 -0
  132. package/templates/fullstack-app/tsconfig.json +18 -0
  133. package/templates/fullstack-app/vite.config.js +87 -0
  134. package/templates/go/build.bat +36 -0
  135. package/templates/go/build.sh +43 -0
  136. package/templates/go/example.go +205 -0
  137. package/templates/go-wasm-app/README.md +38 -0
  138. package/templates/go-wasm-app/babel.config.js +21 -0
  139. package/templates/go-wasm-app/build-client.js +49 -0
  140. package/templates/go-wasm-app/build-wasm.js +237 -0
  141. package/templates/go-wasm-app/build.config.js +62 -0
  142. package/templates/go-wasm-app/build.js +218 -0
  143. package/templates/go-wasm-app/package.json +32 -0
  144. package/templates/go-wasm-app/public/index.html +128 -0
  145. package/templates/go-wasm-app/public/styles.css +197 -0
  146. package/templates/go-wasm-app/public/wasm/example.wasm +0 -0
  147. package/templates/go-wasm-app/public/wasm/wasm_exec.js +561 -0
  148. package/templates/go-wasm-app/public/wasm/wasm_exec_node.js +39 -0
  149. package/templates/go-wasm-app/server.js +70 -0
  150. package/templates/go-wasm-app/src/App.jsx +38 -0
  151. package/templates/go-wasm-app/src/app.js +173 -0
  152. package/templates/go-wasm-app/src/client.js +57 -0
  153. package/templates/go-wasm-app/src/components/Footer.jsx +13 -0
  154. package/templates/go-wasm-app/src/components/Header.jsx +19 -0
  155. package/templates/go-wasm-app/src/components/WasmDemo.jsx +120 -0
  156. package/templates/go-wasm-app/src/main.jsx +12 -0
  157. package/templates/go-wasm-app/src/wasm/example.go +75 -0
  158. package/templates/go-wasm-app/tsconfig.server.json +18 -0
  159. package/templates/go-wasm-app/vite.config.js +45 -0
  160. package/dist/forms/index.d.ts +0 -2
  161. package/dist/forms/index.d.ts.map +0 -1
  162. package/dist/forms/types.d.ts +0 -2
  163. package/dist/forms/types.d.ts.map +0 -1
  164. package/dist/frontend/components/WasmLoader.d.ts +0 -2
  165. package/dist/frontend/components/WasmLoader.d.ts.map +0 -1
  166. package/dist/frontend/hooks/useWasm.d.ts +0 -2
  167. package/dist/frontend/hooks/useWasm.d.ts.map +0 -1
  168. package/dist/frontend/index.d.ts +0 -2
  169. package/dist/frontend/index.d.ts.map +0 -1
  170. package/dist/router/index.d.ts +0 -2
  171. package/dist/router/index.d.ts.map +0 -1
  172. package/dist/router/types.d.ts +0 -2
  173. package/dist/router/types.d.ts.map +0 -1
  174. package/dist/store/index.d.ts +0 -2
  175. package/dist/store/index.d.ts.map +0 -1
  176. package/dist/store/types.d.ts +0 -2
  177. package/dist/store/types.d.ts.map +0 -1
  178. package/templates/basic-app/package-lock.json +0 -7173
  179. package/templates/fullstack-template/package-lock.json +0 -3558
  180. package/templates/ssr-template/package-lock.json +0 -5380
  181. package/templates/wasm/package-lock.json +0 -5347
  182. package/templates/wasm/public/example.wasm +0 -0
package/dist/browser.js CHANGED
@@ -1,206 +1,360 @@
1
- // node_modules/frontend-hamroun/dist/index.mjs
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+
8
+ // src/core/batch.ts
2
9
  var isBatching = false;
3
- var queue = [];
4
- function batchUpdates(fn) {
10
+ var syncQueue = [];
11
+ var asyncQueue = [];
12
+ async function batchUpdates(fn) {
5
13
  if (isBatching) {
6
- queue.push(fn);
14
+ if (fn.constructor.name === "AsyncFunction") {
15
+ asyncQueue.push(fn);
16
+ } else {
17
+ syncQueue.push(fn);
18
+ }
7
19
  return;
8
20
  }
9
21
  isBatching = true;
10
22
  try {
11
- fn();
12
- while (queue.length > 0) {
13
- const nextFn = queue.shift();
14
- nextFn == null ? void 0 : nextFn();
23
+ const result = fn();
24
+ if (result instanceof Promise) {
25
+ await result;
26
+ }
27
+ while (syncQueue.length > 0) {
28
+ const nextFn = syncQueue.shift();
29
+ nextFn();
30
+ }
31
+ while (asyncQueue.length > 0) {
32
+ const nextFn = asyncQueue.shift();
33
+ await nextFn();
15
34
  }
16
35
  } finally {
17
36
  isBatching = false;
18
37
  }
19
38
  }
20
- var currentRender = 0;
21
- var states = /* @__PURE__ */ new Map();
22
- var stateIndices = /* @__PURE__ */ new Map();
23
- var effects = /* @__PURE__ */ new Map();
24
- var memos = /* @__PURE__ */ new Map();
25
- var refs = /* @__PURE__ */ new Map();
26
- var globalRenderCallback = null;
27
- var globalContainer = null;
28
- var currentElement = null;
29
- var isServer = typeof window === "undefined";
30
- var serverStates = /* @__PURE__ */ new Map();
31
- function setRenderCallback(callback, element, container) {
32
- globalRenderCallback = callback;
33
- globalContainer = container;
34
- currentElement = element;
39
+ function getIsBatching() {
40
+ return isBatching;
41
+ }
42
+
43
+ // src/core/context.ts
44
+ var contextStacks = /* @__PURE__ */ new Map();
45
+ function createContext(defaultValue) {
46
+ const id = Symbol("context");
47
+ contextStacks.set(id, []);
48
+ const context = {
49
+ Provider: ({ value, children }) => {
50
+ const stack = contextStacks.get(id);
51
+ stack.push(value);
52
+ const result = children;
53
+ stack.pop();
54
+ return result;
55
+ },
56
+ Consumer: ({ children }) => {
57
+ const stack = contextStacks.get(id);
58
+ const value = stack && stack.length > 0 ? stack[stack.length - 1] : defaultValue;
59
+ return children(value);
60
+ },
61
+ _id: id,
62
+ _defaultValue: defaultValue,
63
+ useSelector: (selector) => {
64
+ const stack = contextStacks.get(id);
65
+ const value = stack && stack.length > 0 ? stack[stack.length - 1] : defaultValue;
66
+ return selector(value);
67
+ }
68
+ };
69
+ return context;
70
+ }
71
+ function useContext(context) {
72
+ const stack = contextStacks.get(context._id);
73
+ if (stack && stack.length > 0) {
74
+ return stack[stack.length - 1];
75
+ }
76
+ return context._defaultValue;
77
+ }
78
+ function getContextValue(context) {
79
+ return useContext(context);
35
80
  }
36
- function prepareRender() {
37
- currentRender++;
38
- stateIndices.set(currentRender, 0);
39
- return currentRender;
81
+
82
+ // src/core/hooks.ts
83
+ var rootIdCounter = 0;
84
+ function createRootState() {
85
+ return {
86
+ id: ++rootIdCounter,
87
+ components: /* @__PURE__ */ new Map(),
88
+ nextComponentId: 0,
89
+ renderCallback: null,
90
+ container: null,
91
+ currentElement: null
92
+ };
93
+ }
94
+ var currentRoot = null;
95
+ var currentComponentId = null;
96
+ var hookIndex = 0;
97
+ var isServer = typeof window === "undefined";
98
+ function prepareRender(root, componentId) {
99
+ if (root) {
100
+ currentRoot = root;
101
+ }
102
+ if (componentId !== void 0) {
103
+ currentComponentId = componentId;
104
+ } else if (currentRoot) {
105
+ currentComponentId = ++currentRoot.nextComponentId;
106
+ }
107
+ hookIndex = 0;
108
+ return currentComponentId || 0;
40
109
  }
41
110
  function finishRender() {
42
- if (isServer) {
43
- serverStates.delete(currentRender);
111
+ currentComponentId = null;
112
+ }
113
+ function getCurrentRoot() {
114
+ return currentRoot;
115
+ }
116
+ function setCurrentRoot(root) {
117
+ currentRoot = root;
118
+ }
119
+ function getComponentState(root, compId) {
120
+ let state = root.components.get(compId);
121
+ if (!state) {
122
+ state = { states: [], effects: [], memos: [], refs: [] };
123
+ root.components.set(compId, state);
44
124
  }
45
- currentRender = 0;
125
+ return state;
126
+ }
127
+ function setRenderCallback(callback, element, container) {
128
+ if (!currentRoot)
129
+ return;
130
+ currentRoot.renderCallback = callback;
131
+ currentRoot.currentElement = element;
132
+ currentRoot.container = container;
46
133
  }
47
134
  function useState(initial) {
48
- if (!currentRender) {
49
- throw new Error("useState must be called within a render");
50
- }
51
- if (isServer) {
52
- if (!serverStates.has(currentRender)) {
53
- serverStates.set(currentRender, /* @__PURE__ */ new Map());
135
+ const root = currentRoot;
136
+ const compId = currentComponentId;
137
+ if (!root || compId === null) {
138
+ if (isServer) {
139
+ return [initial, () => {
140
+ }];
54
141
  }
55
- const componentState = serverStates.get(currentRender);
56
- const index2 = stateIndices.get(currentRender) || 0;
57
- if (!componentState.has(index2)) {
58
- componentState.set(index2, initial);
59
- }
60
- const state2 = componentState.get(index2);
61
- const setState2 = (newValue) => {
62
- };
63
- stateIndices.set(currentRender, index2 + 1);
64
- return [state2, setState2];
142
+ console.warn("useState called outside of render context");
143
+ return [initial, () => {
144
+ }];
65
145
  }
66
- if (!states.has(currentRender)) {
67
- states.set(currentRender, []);
146
+ const compState = getComponentState(root, compId);
147
+ const currentIndex = hookIndex;
148
+ hookIndex++;
149
+ if (currentIndex >= compState.states.length) {
150
+ compState.states.push(initial);
68
151
  }
69
- const componentStates = states.get(currentRender);
70
- const index = stateIndices.get(currentRender);
71
- if (index >= componentStates.length) {
72
- componentStates.push(initial);
73
- }
74
- const state = componentStates[index];
152
+ const state = compState.states[currentIndex];
75
153
  const setState = (newValue) => {
76
- const nextValue = typeof newValue === "function" ? newValue(componentStates[index]) : newValue;
77
- if (componentStates[index] === nextValue)
154
+ const currentState = compState.states[currentIndex];
155
+ const value = typeof newValue === "function" ? newValue(currentState) : newValue;
156
+ if (Object.is(currentState, value))
78
157
  return;
79
- componentStates[index] = nextValue;
80
- if (isBatching) {
81
- batchUpdates(() => rerender(currentRender));
82
- } else {
83
- rerender(currentRender);
158
+ compState.states[currentIndex] = value;
159
+ if (root.renderCallback && root.container && root.currentElement) {
160
+ root.renderCallback(root.currentElement, root.container);
84
161
  }
85
162
  };
86
- stateIndices.set(currentRender, index + 1);
87
163
  return [state, setState];
88
164
  }
89
165
  function useEffect(callback, deps) {
90
- if (!currentRender)
91
- throw new Error("useEffect must be called within a render");
92
- const effectIndex = stateIndices.get(currentRender);
93
- if (!effects.has(currentRender)) {
94
- effects.set(currentRender, []);
95
- }
96
- const componentEffects = effects.get(currentRender);
97
- const prevEffect = componentEffects[effectIndex];
98
- if (!prevEffect || !deps || !prevEffect.deps || deps.some((dep, i) => dep !== prevEffect.deps[i])) {
99
- if (prevEffect == null ? void 0 : prevEffect.cleanup) {
166
+ const root = currentRoot;
167
+ const compId = currentComponentId;
168
+ if (!root || compId === null || isServer)
169
+ return;
170
+ const compState = getComponentState(root, compId);
171
+ const currentIndex = hookIndex;
172
+ hookIndex++;
173
+ const prevEffect = compState.effects[currentIndex];
174
+ const shouldRun = !prevEffect || !deps || !prevEffect.deps || deps.some((dep, i) => !Object.is(dep, prevEffect.deps?.[i]));
175
+ if (shouldRun) {
176
+ if (prevEffect?.cleanup) {
100
177
  prevEffect.cleanup();
101
178
  }
102
179
  queueMicrotask(() => {
103
- const cleanup = callback() || void 0;
104
- componentEffects[effectIndex] = { cleanup, deps };
180
+ const cleanup = callback();
181
+ compState.effects[currentIndex] = {
182
+ callback,
183
+ deps,
184
+ cleanup: typeof cleanup === "function" ? cleanup : void 0
185
+ };
105
186
  });
106
187
  }
107
- stateIndices.set(currentRender, effectIndex + 1);
188
+ if (!prevEffect) {
189
+ compState.effects.push({ callback, deps });
190
+ }
191
+ }
192
+ function useLayoutEffect(callback, deps) {
193
+ if (isServer)
194
+ return;
195
+ const root = currentRoot;
196
+ const compId = currentComponentId;
197
+ if (!root || compId === null)
198
+ return;
199
+ const compState = getComponentState(root, compId);
200
+ const currentIndex = hookIndex;
201
+ hookIndex++;
202
+ const prevEffect = compState.effects[currentIndex];
203
+ const shouldRun = !prevEffect || !deps || !prevEffect.deps || deps.some((dep, i) => !Object.is(dep, prevEffect.deps?.[i]));
204
+ if (shouldRun) {
205
+ if (prevEffect?.cleanup) {
206
+ prevEffect.cleanup();
207
+ }
208
+ const cleanup = callback();
209
+ compState.effects[currentIndex] = {
210
+ callback,
211
+ deps,
212
+ cleanup: typeof cleanup === "function" ? cleanup : void 0
213
+ };
214
+ }
215
+ if (!prevEffect) {
216
+ compState.effects.push({ callback, deps });
217
+ }
108
218
  }
109
219
  function useMemo(factory, deps) {
110
- if (!currentRender)
111
- throw new Error("useMemo must be called within a render");
112
- const memoIndex = stateIndices.get(currentRender);
113
- if (!memos.has(currentRender)) {
114
- memos.set(currentRender, []);
115
- }
116
- const componentMemos = memos.get(currentRender);
117
- const prevMemo = componentMemos[memoIndex];
118
- if (!prevMemo || deps && deps.some((dep, i) => !Object.is(dep, prevMemo.deps[i]))) {
220
+ const root = currentRoot;
221
+ const compId = currentComponentId;
222
+ if (!root || compId === null) {
223
+ return factory();
224
+ }
225
+ const compState = getComponentState(root, compId);
226
+ const currentIndex = hookIndex;
227
+ hookIndex++;
228
+ const prevMemo = compState.memos[currentIndex];
229
+ const shouldRecalculate = !prevMemo || !deps || !prevMemo.deps || deps.some((dep, i) => !Object.is(dep, prevMemo.deps?.[i]));
230
+ if (shouldRecalculate) {
119
231
  const value = factory();
120
- componentMemos[memoIndex] = { value, deps };
121
- stateIndices.set(currentRender, memoIndex + 1);
232
+ compState.memos[currentIndex] = { value, deps };
122
233
  return value;
123
234
  }
124
- stateIndices.set(currentRender, memoIndex + 1);
125
235
  return prevMemo.value;
126
236
  }
237
+ function useCallback(callback, deps) {
238
+ return useMemo(() => callback, deps);
239
+ }
127
240
  function useRef(initial) {
128
- if (!currentRender)
129
- throw new Error("useRef must be called within a render");
130
- const refIndex = stateIndices.get(currentRender);
131
- if (!refs.has(currentRender)) {
132
- refs.set(currentRender, []);
133
- }
134
- const componentRefs = refs.get(currentRender);
135
- if (refIndex >= componentRefs.length) {
136
- const ref2 = { current: initial };
137
- componentRefs.push(ref2);
138
- stateIndices.set(currentRender, refIndex + 1);
139
- return ref2;
140
- }
141
- const ref = componentRefs[refIndex];
142
- stateIndices.set(currentRender, refIndex + 1);
143
- return ref;
144
- }
145
- async function rerender(rendererId) {
146
- try {
147
- const componentEffects = effects.get(rendererId);
148
- if (componentEffects) {
149
- componentEffects.forEach((effect) => {
150
- if (effect.cleanup)
151
- effect.cleanup();
152
- });
153
- effects.set(rendererId, []);
154
- }
155
- if (globalRenderCallback && globalContainer && currentElement) {
156
- await globalRenderCallback(currentElement, globalContainer);
157
- }
158
- } catch (error) {
159
- console.error("Error during rerender:", error);
241
+ const root = currentRoot;
242
+ const compId = currentComponentId;
243
+ if (!root || compId === null) {
244
+ return { current: initial };
245
+ }
246
+ const compState = getComponentState(root, compId);
247
+ const currentIndex = hookIndex;
248
+ hookIndex++;
249
+ if (compState.refs[currentIndex] === void 0) {
250
+ compState.refs[currentIndex] = { current: initial };
160
251
  }
252
+ return compState.refs[currentIndex];
253
+ }
254
+ function useReducer(reducer, initialState) {
255
+ const [state, setState] = useState(initialState);
256
+ const dispatch = (action) => {
257
+ setState((prevState) => reducer(prevState, action));
258
+ };
259
+ return [state, dispatch];
161
260
  }
162
261
  function useErrorBoundary() {
163
262
  const [error, setError] = useState(null);
164
- return [error, () => setError(null)];
263
+ const resetError = () => setError(null);
264
+ return [error, resetError];
165
265
  }
166
- function createContext(defaultValue) {
167
- const context = {
168
- Provider: ({ value, children }) => {
169
- return children;
170
- },
171
- Consumer: ({ children }) => {
172
- return children(defaultValue);
173
- },
174
- _id: Symbol(),
175
- useSelector: (selector) => {
176
- return selector(defaultValue);
177
- }
178
- };
179
- return context;
266
+ var idCounter = 0;
267
+ function useId() {
268
+ const ref = useRef(null);
269
+ if (ref.current === null) {
270
+ ref.current = `baraqex-id-${++idCounter}`;
271
+ }
272
+ return ref.current;
180
273
  }
181
- function useContext(context) {
182
- return context;
274
+ function cleanupHooks(root, compId) {
275
+ const compState = root.components.get(compId);
276
+ if (compState) {
277
+ compState.effects.forEach((effect) => {
278
+ if (effect.cleanup)
279
+ effect.cleanup();
280
+ });
281
+ root.components.delete(compId);
282
+ }
283
+ }
284
+ function cleanupRoot(root) {
285
+ root.components.forEach((compState) => {
286
+ compState.effects.forEach((effect) => {
287
+ if (effect.cleanup)
288
+ effect.cleanup();
289
+ });
290
+ });
291
+ root.components.clear();
183
292
  }
184
- function jsx(type, props) {
185
- console.log("JSX Transform:", { type, props });
293
+
294
+ // src/core/jsx-runtime.ts
295
+ var isBrowser = typeof document !== "undefined";
296
+ function jsx(type, props, key) {
186
297
  const processedProps = { ...props };
187
- if (arguments.length > 2) {
188
- processedProps.children = Array.prototype.slice.call(arguments, 2);
298
+ if (key !== void 0) {
299
+ processedProps.key = key;
300
+ }
301
+ if (arguments.length > 3) {
302
+ processedProps.children = Array.prototype.slice.call(arguments, 3);
189
303
  }
190
- return { type, props: processedProps };
304
+ return { type, props: processedProps, key: processedProps.key };
305
+ }
306
+ var jsxs = jsx;
307
+ function jsxDEV(type, props, key, _isStaticChildren, _source, _self) {
308
+ return jsx(type, props, key);
191
309
  }
192
310
  var Fragment = ({ children }) => children;
193
- async function createElement(vnode) {
194
- var _a;
195
- console.log("Creating element from:", vnode);
196
- if (vnode == null) {
197
- return document.createTextNode("");
311
+ function assertBrowser(method) {
312
+ if (!isBrowser) {
313
+ throw new Error(
314
+ `[baraqex] ${method}() can only be called in a browser environment. Use renderToString() for server-side rendering.`
315
+ );
316
+ }
317
+ }
318
+ function createTextNode(text) {
319
+ return document.createTextNode(text);
320
+ }
321
+ function applyProps(element, props) {
322
+ for (const [key, value] of Object.entries(props)) {
323
+ if (key === "children")
324
+ continue;
325
+ if (key === "className") {
326
+ element.setAttribute("class", String(value));
327
+ } else if (key === "htmlFor") {
328
+ element.setAttribute("for", String(value));
329
+ } else if (key.startsWith("on") && typeof value === "function") {
330
+ const eventName = key.slice(2).toLowerCase();
331
+ element.addEventListener(eventName, value);
332
+ } else if (key === "style" && typeof value === "object") {
333
+ Object.assign(element.style, value);
334
+ } else if (key === "dangerouslySetInnerHTML" && value && value.__html) {
335
+ element.innerHTML = value.__html;
336
+ } else if (key === "ref") {
337
+ if (typeof value === "function") {
338
+ value(element);
339
+ } else if (value && typeof value === "object" && "current" in value) {
340
+ value.current = element;
341
+ }
342
+ } else if (value !== false && value != null) {
343
+ if (value === true) {
344
+ element.setAttribute(key, "");
345
+ } else {
346
+ element.setAttribute(key, String(value));
347
+ }
348
+ }
198
349
  }
199
- if (typeof vnode === "boolean") {
200
- return document.createTextNode("");
350
+ }
351
+ async function createElement(vnode) {
352
+ assertBrowser("createElement");
353
+ if (vnode == null || typeof vnode === "boolean") {
354
+ return createTextNode("");
201
355
  }
202
356
  if (typeof vnode === "number" || typeof vnode === "string") {
203
- return document.createTextNode(String(vnode));
357
+ return createTextNode(String(vnode));
204
358
  }
205
359
  if (Array.isArray(vnode)) {
206
360
  const fragment = document.createDocumentFragment();
@@ -210,47 +364,29 @@ async function createElement(vnode) {
210
364
  }
211
365
  return fragment;
212
366
  }
213
- if ("type" in vnode && vnode.props !== void 0) {
367
+ if (typeof vnode === "object" && "type" in vnode && vnode.props !== void 0) {
214
368
  const { type, props } = vnode;
215
369
  if (typeof type === "function") {
370
+ if (type === Fragment) {
371
+ const children2 = props?.children;
372
+ if (children2 == null)
373
+ return createTextNode("");
374
+ return createElement(children2);
375
+ }
376
+ const root = getCurrentRoot() ?? void 0;
377
+ const renderId = prepareRender(root);
216
378
  try {
217
- const result = await type(props || {});
218
- const node = await createElement(result);
219
- if (node instanceof Element) {
220
- node.setAttribute("data-component-id", type.name || type.toString());
221
- }
222
- return node;
223
- } catch (error) {
224
- console.error("Error rendering component:", error);
225
- return document.createTextNode("");
379
+ const result = type(props || {});
380
+ return await createElement(result);
381
+ } finally {
382
+ finishRender();
226
383
  }
227
384
  }
228
385
  const element = document.createElement(type);
229
- for (const [key, value] of Object.entries(props || {})) {
230
- if (key === "children")
231
- continue;
232
- if (key.startsWith("on") && typeof value === "function") {
233
- const eventName = key.toLowerCase().slice(2);
234
- const existingHandler = (_a = element.__events) == null ? void 0 : _a[eventName];
235
- if (existingHandler) {
236
- element.removeEventListener(eventName, existingHandler);
237
- }
238
- element.addEventListener(eventName, value);
239
- if (!element.__events) {
240
- element.__events = {};
241
- }
242
- element.__events[eventName] = value;
243
- } else if (key === "style" && typeof value === "object") {
244
- Object.assign(element.style, value);
245
- } else if (key === "className") {
246
- element.setAttribute("class", String(value));
247
- } else if (key !== "key" && key !== "ref") {
248
- element.setAttribute(key, String(value));
249
- }
250
- }
251
- const children = props == null ? void 0 : props.children;
386
+ applyProps(element, props || {});
387
+ const children = props?.children;
252
388
  if (children != null) {
253
- const childArray = Array.isArray(children) ? children.flat() : [children];
389
+ const childArray = Array.isArray(children) ? children : [children];
254
390
  for (const child of childArray) {
255
391
  const childNode = await createElement(child);
256
392
  element.appendChild(childNode);
@@ -258,39 +394,1893 @@ async function createElement(vnode) {
258
394
  }
259
395
  return element;
260
396
  }
261
- return document.createTextNode(String(vnode));
397
+ return createTextNode(String(vnode));
262
398
  }
263
- var isHydrating = false;
264
- async function hydrate(element, container) {
265
- isHydrating = true;
266
- try {
267
- await render(element, container);
268
- } finally {
269
- isHydrating = false;
399
+ function createElementSync(vnode) {
400
+ assertBrowser("createElementSync");
401
+ if (vnode == null || typeof vnode === "boolean") {
402
+ return createTextNode("");
403
+ }
404
+ if (typeof vnode === "number" || typeof vnode === "string") {
405
+ return createTextNode(String(vnode));
406
+ }
407
+ if (Array.isArray(vnode)) {
408
+ const fragment = document.createDocumentFragment();
409
+ for (const child of vnode) {
410
+ fragment.appendChild(createElementSync(child));
411
+ }
412
+ return fragment;
413
+ }
414
+ if (typeof vnode === "object" && "type" in vnode) {
415
+ const { type, props } = vnode;
416
+ if (typeof type === "function") {
417
+ if (type === Fragment) {
418
+ return createElementSync(props?.children);
419
+ }
420
+ const result = type(props || {});
421
+ return createElementSync(result);
422
+ }
423
+ const element = document.createElement(type);
424
+ applyProps(element, props || {});
425
+ const children = props?.children;
426
+ if (children != null) {
427
+ const childArray = Array.isArray(children) ? children : [children];
428
+ for (const child of childArray) {
429
+ element.appendChild(createElementSync(child));
430
+ }
431
+ }
432
+ return element;
270
433
  }
434
+ return createTextNode(String(vnode));
271
435
  }
436
+
437
+ // src/core/renderer.ts
438
+ var isBrowser2 = typeof document !== "undefined";
439
+ var rootMap = /* @__PURE__ */ new WeakMap();
272
440
  async function render(element, container) {
273
- console.log("Rendering to:", container.id);
274
- batchUpdates(async () => {
275
- const rendererId = prepareRender();
441
+ if (!isBrowser2) {
442
+ throw new Error(
443
+ "[baraqex] render() can only be called in a browser. Use renderToString() for server-side rendering."
444
+ );
445
+ }
446
+ if (!container) {
447
+ throw new Error("[baraqex] render() requires a container element");
448
+ }
449
+ let root = rootMap.get(container);
450
+ if (!root) {
451
+ root = createRootState();
452
+ rootMap.set(container, root);
453
+ }
454
+ await batchUpdates(async () => {
455
+ prepareRender(root);
276
456
  try {
277
457
  setRenderCallback(render, element, container);
278
458
  const domNode = await createElement(element);
279
- if (!isHydrating) {
280
- container.innerHTML = "";
281
- }
459
+ container.textContent = "";
282
460
  container.appendChild(domNode);
283
461
  } finally {
284
462
  finishRender();
285
463
  }
286
464
  });
287
465
  }
288
- var server = {
289
- async getServer() {
290
- throw new Error("Server module can only be used in Node.js environment");
466
+ async function hydrate(element, container) {
467
+ await render(element, container);
468
+ }
469
+ function createRoot(container) {
470
+ const root = createRootState();
471
+ rootMap.set(container, root);
472
+ return {
473
+ render: (element) => render(element, container),
474
+ unmount: () => {
475
+ cleanupRoot(root);
476
+ rootMap.delete(container);
477
+ container.textContent = "";
478
+ }
479
+ };
480
+ }
481
+ function hasRoot(container) {
482
+ return rootMap.has(container);
483
+ }
484
+
485
+ // src/core/server-renderer.ts
486
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
487
+ "area",
488
+ "base",
489
+ "br",
490
+ "col",
491
+ "embed",
492
+ "hr",
493
+ "img",
494
+ "input",
495
+ "link",
496
+ "meta",
497
+ "param",
498
+ "source",
499
+ "track",
500
+ "wbr"
501
+ ]);
502
+ function renderToString(vnode) {
503
+ prepareRender();
504
+ try {
505
+ return renderNodeToString(vnode);
506
+ } finally {
507
+ finishRender();
508
+ }
509
+ }
510
+ function renderToStringWithData(vnode) {
511
+ const html = renderToString(vnode);
512
+ return { html, data: {} };
513
+ }
514
+ async function* renderToStream(vnode) {
515
+ yield renderToString(vnode);
516
+ }
517
+ function renderNodeToString(vnode) {
518
+ if (vnode === null || vnode === void 0)
519
+ return "";
520
+ if (typeof vnode === "boolean")
521
+ return "";
522
+ if (typeof vnode === "number" || typeof vnode === "string")
523
+ return escapeHtml(String(vnode));
524
+ if (Array.isArray(vnode)) {
525
+ return vnode.map((child) => renderNodeToString(child)).join("");
526
+ }
527
+ if (typeof vnode !== "object" || vnode.type === void 0) {
528
+ return escapeHtml(String(vnode));
529
+ }
530
+ const { type, props } = vnode;
531
+ if (typeof type === "function") {
532
+ if (type.name === "Fragment" || type === Symbol.for("react.fragment")) {
533
+ const children = props?.children;
534
+ if (children == null)
535
+ return "";
536
+ return Array.isArray(children) ? children.map((child) => renderNodeToString(child)).join("") : renderNodeToString(children);
537
+ }
538
+ const Component2 = type;
539
+ try {
540
+ const renderedNode = Component2(props || {});
541
+ return renderNodeToString(renderedNode);
542
+ } catch (error) {
543
+ console.error("Error rendering component:", error);
544
+ return `<!-- Error rendering component: ${escapeHtml(String(error))} -->`;
545
+ }
546
+ }
547
+ if (typeof type === "string") {
548
+ const tag = type;
549
+ let attrs = "";
550
+ if (props) {
551
+ for (const [key, value] of Object.entries(props)) {
552
+ if (key === "children")
553
+ continue;
554
+ if (key === "dangerouslySetInnerHTML")
555
+ continue;
556
+ if (key === "ref")
557
+ continue;
558
+ if (value === void 0 || value === null || value === false)
559
+ continue;
560
+ let attrName = key;
561
+ let attrValue = value;
562
+ if (key === "className")
563
+ attrName = "class";
564
+ else if (key === "htmlFor")
565
+ attrName = "for";
566
+ else if (key === "tabIndex")
567
+ attrName = "tabindex";
568
+ if (attrName.startsWith("on") && typeof value === "function")
569
+ continue;
570
+ if (attrName === "style" && typeof value === "object") {
571
+ attrValue = Object.entries(value).map(([prop, val]) => {
572
+ const cssProperty = prop.replace(/([A-Z])/g, "-$1").toLowerCase();
573
+ return `${cssProperty}: ${val}`;
574
+ }).join("; ");
575
+ }
576
+ if (value === true) {
577
+ attrs += ` ${attrName}`;
578
+ } else {
579
+ attrs += ` ${attrName}="${escapeHtml(String(attrValue))}"`;
580
+ }
581
+ }
582
+ }
583
+ if (VOID_ELEMENTS.has(tag)) {
584
+ return `<${tag}${attrs} />`;
585
+ }
586
+ if (props?.dangerouslySetInnerHTML?.__html) {
587
+ return `<${tag}${attrs}>${props.dangerouslySetInnerHTML.__html}</${tag}>`;
588
+ }
589
+ let children = "";
590
+ const childrenArray = props?.children ? Array.isArray(props.children) ? props.children : [props.children] : [];
591
+ for (const child of childrenArray) {
592
+ children += renderNodeToString(child);
593
+ }
594
+ return `<${tag}${attrs}>${children}</${tag}>`;
595
+ }
596
+ if (type === Symbol.for("react.fragment")) {
597
+ const children = props?.children;
598
+ if (children == null)
599
+ return "";
600
+ return Array.isArray(children) ? children.map((child) => renderNodeToString(child)).join("") : renderNodeToString(children);
601
+ }
602
+ console.warn("Unknown vnode type:", type);
603
+ return "";
604
+ }
605
+ function escapeHtml(text) {
606
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
607
+ }
608
+
609
+ // src/core/vdom.ts
610
+ var isBrowser3 = typeof document !== "undefined";
611
+ function arePropsEqual(oldProps, newProps) {
612
+ const oldKeys = Object.keys(oldProps || {}).filter((k) => k !== "children");
613
+ const newKeys = Object.keys(newProps || {}).filter((k) => k !== "children");
614
+ if (oldKeys.length !== newKeys.length)
615
+ return false;
616
+ return oldKeys.every((key) => Object.is(oldProps[key], newProps[key]));
617
+ }
618
+ function diff(oldNode, newNode) {
619
+ if (oldNode == null || newNode == null) {
620
+ return oldNode !== newNode;
621
+ }
622
+ if (typeof oldNode !== typeof newNode)
623
+ return true;
624
+ if (typeof newNode === "string" || typeof newNode === "number") {
625
+ return oldNode !== newNode;
626
+ }
627
+ if (Array.isArray(oldNode) && Array.isArray(newNode)) {
628
+ if (oldNode.length !== newNode.length)
629
+ return true;
630
+ return oldNode.some((child, i) => diff(child, newNode[i]));
631
+ }
632
+ if (typeof oldNode === "object" && typeof newNode === "object") {
633
+ if (newNode.type !== oldNode.type)
634
+ return true;
635
+ if (newNode.key !== oldNode.key)
636
+ return true;
637
+ return !arePropsEqual(oldNode.props, newNode.props);
638
+ }
639
+ return oldNode !== newNode;
640
+ }
641
+ function shouldComponentUpdate(oldProps, newProps) {
642
+ return !arePropsEqual(oldProps, newProps);
643
+ }
644
+ function calculatePatches(oldNode, newNode) {
645
+ if (oldNode == null && newNode != null) {
646
+ return { type: "CREATE", node: newNode };
647
+ }
648
+ if (oldNode != null && newNode == null) {
649
+ return { type: "REMOVE" };
650
+ }
651
+ if (oldNode == null && newNode == null) {
652
+ return null;
653
+ }
654
+ if (typeof oldNode !== typeof newNode) {
655
+ return { type: "REPLACE", node: newNode };
656
+ }
657
+ if (typeof newNode === "string" || typeof newNode === "number") {
658
+ if (oldNode !== newNode) {
659
+ return { type: "REPLACE", node: newNode };
660
+ }
661
+ return null;
662
+ }
663
+ if (typeof oldNode === "object" && typeof newNode === "object" && "type" in newNode) {
664
+ if (oldNode.type !== newNode.type) {
665
+ return { type: "REPLACE", node: newNode };
666
+ }
667
+ const propPatches = {};
668
+ let hasChanges = false;
669
+ const newProps = newNode.props || {};
670
+ const oldProps = oldNode.props || {};
671
+ for (const key of Object.keys(newProps)) {
672
+ if (key === "children")
673
+ continue;
674
+ if (!Object.is(newProps[key], oldProps[key])) {
675
+ propPatches[key] = newProps[key];
676
+ hasChanges = true;
677
+ }
678
+ }
679
+ for (const key of Object.keys(oldProps)) {
680
+ if (key === "children")
681
+ continue;
682
+ if (!(key in newProps)) {
683
+ propPatches[key] = void 0;
684
+ hasChanges = true;
685
+ }
686
+ }
687
+ const oldChildren = normalizeChildren(oldProps.children);
688
+ const newChildren = normalizeChildren(newProps.children);
689
+ const childPatches = diffChildren(oldChildren, newChildren);
690
+ if (childPatches.length > 0) {
691
+ hasChanges = true;
692
+ }
693
+ if (hasChanges) {
694
+ return {
695
+ type: "UPDATE",
696
+ props: propPatches,
697
+ children: childPatches.length > 0 ? childPatches : void 0
698
+ };
699
+ }
700
+ return null;
701
+ }
702
+ return null;
703
+ }
704
+ function normalizeChildren(children) {
705
+ if (children == null)
706
+ return [];
707
+ return Array.isArray(children) ? children : [children];
708
+ }
709
+ function diffChildren(oldChildren, newChildren) {
710
+ const patches = [];
711
+ const oldKeyMap = /* @__PURE__ */ new Map();
712
+ oldChildren.forEach((child, i) => {
713
+ if (child && typeof child === "object" && child.key != null) {
714
+ oldKeyMap.set(child.key, i);
715
+ }
716
+ });
717
+ const newKeyMap = /* @__PURE__ */ new Map();
718
+ newChildren.forEach((child, i) => {
719
+ if (child && typeof child === "object" && child.key != null) {
720
+ newKeyMap.set(child.key, i);
721
+ }
722
+ });
723
+ const maxLen = Math.max(oldChildren.length, newChildren.length);
724
+ for (let i = 0; i < maxLen; i++) {
725
+ const oldChild = i < oldChildren.length ? oldChildren[i] : null;
726
+ const newChild = i < newChildren.length ? newChildren[i] : null;
727
+ const patch = calculatePatches(oldChild, newChild);
728
+ if (patch) {
729
+ patches.push(patch);
730
+ }
731
+ }
732
+ return patches;
733
+ }
734
+ function applyPatches(element, patch) {
735
+ if (!isBrowser3)
736
+ return element;
737
+ switch (patch.type) {
738
+ case "REMOVE":
739
+ element.parentNode?.removeChild(element);
740
+ return null;
741
+ case "REPLACE": {
742
+ if (!patch.node)
743
+ return element;
744
+ const newNode = patch.node;
745
+ if (typeof newNode === "string" || typeof newNode === "number") {
746
+ const textNode = document.createTextNode(String(newNode));
747
+ element.parentNode?.replaceChild(textNode, element);
748
+ return null;
749
+ }
750
+ element.textContent = "";
751
+ return element;
752
+ }
753
+ case "UPDATE": {
754
+ if (patch.props) {
755
+ for (const [key, value] of Object.entries(patch.props)) {
756
+ if (value === void 0) {
757
+ const attrName = key === "className" ? "class" : key;
758
+ element.removeAttribute(attrName);
759
+ } else if (key === "className") {
760
+ element.setAttribute("class", String(value));
761
+ } else if (key === "style" && typeof value === "object") {
762
+ const htmlEl = element;
763
+ for (const [prop, val] of Object.entries(value)) {
764
+ htmlEl.style[prop] = val;
765
+ }
766
+ } else if (key.startsWith("on") && typeof value === "function") {
767
+ const eventName = key.slice(2).toLowerCase();
768
+ const attrName = `data-baraqex-listener-${eventName}`;
769
+ const oldHandler = element.__baraqexHandlers?.[eventName];
770
+ if (oldHandler) {
771
+ element.removeEventListener(eventName, oldHandler);
772
+ }
773
+ element.addEventListener(eventName, value);
774
+ if (!element.__baraqexHandlers) {
775
+ element.__baraqexHandlers = {};
776
+ }
777
+ element.__baraqexHandlers[eventName] = value;
778
+ } else if (key === "ref") {
779
+ if (typeof value === "function") {
780
+ value(element);
781
+ } else if (value && typeof value === "object" && "current" in value) {
782
+ value.current = element;
783
+ }
784
+ } else {
785
+ if (value === true) {
786
+ element.setAttribute(key, "");
787
+ } else {
788
+ element.setAttribute(key, String(value));
789
+ }
790
+ }
791
+ }
792
+ }
793
+ return element;
794
+ }
795
+ default:
796
+ return element;
797
+ }
798
+ }
799
+
800
+ // src/core/component.ts
801
+ var Component = class {
802
+ constructor(props) {
803
+ __publicField(this, "props");
804
+ __publicField(this, "state");
805
+ __publicField(this, "element", null);
806
+ __publicField(this, "_mounted", false);
807
+ __publicField(this, "_pendingState", null);
808
+ this.props = props;
809
+ this.state = {};
810
+ }
811
+ /**
812
+ * Called after the component is mounted to the DOM
813
+ */
814
+ componentDidMount() {
815
+ }
816
+ /**
817
+ * Called before the component is unmounted from the DOM
818
+ */
819
+ componentWillUnmount() {
820
+ }
821
+ /**
822
+ * Called when the component receives new props
823
+ */
824
+ componentDidUpdate(_prevProps, _prevState) {
825
+ }
826
+ /**
827
+ * Determine if the component should re-render
828
+ */
829
+ shouldComponentUpdate(_nextProps, _nextState) {
830
+ return true;
831
+ }
832
+ /**
833
+ * Update component state and trigger re-render
834
+ */
835
+ setState(newState) {
836
+ const prevState = { ...this.state };
837
+ const stateUpdate = typeof newState === "function" ? newState(this.state, this.props) : newState;
838
+ this.state = { ...this.state, ...stateUpdate };
839
+ if (this._mounted) {
840
+ if (this.shouldComponentUpdate(this.props, this.state)) {
841
+ this._update();
842
+ this.componentDidUpdate(this.props, prevState);
843
+ }
844
+ }
845
+ }
846
+ /**
847
+ * Force a re-render without checking shouldComponentUpdate
848
+ */
849
+ forceUpdate() {
850
+ this._update();
851
+ }
852
+ /**
853
+ * Internal update method
854
+ */
855
+ async _update() {
856
+ const vdom = this.render();
857
+ if (!vdom || !this.element?.parentNode)
858
+ return;
859
+ const newElement = await createElement(vdom);
860
+ if (newElement instanceof HTMLElement) {
861
+ this.element.parentNode.replaceChild(newElement, this.element);
862
+ this.element = newElement;
863
+ }
864
+ }
865
+ /**
866
+ * Mount the component to a container
867
+ */
868
+ async mount(container) {
869
+ const vdom = this.render();
870
+ if (!vdom)
871
+ return;
872
+ const element = await createElement(vdom);
873
+ if (element instanceof HTMLElement) {
874
+ this.element = element;
875
+ container.appendChild(element);
876
+ this._mounted = true;
877
+ this.componentDidMount();
878
+ }
879
+ }
880
+ /**
881
+ * Unmount the component
882
+ */
883
+ unmount() {
884
+ if (this.element?.parentNode) {
885
+ this.componentWillUnmount();
886
+ this.element.parentNode.removeChild(this.element);
887
+ this._mounted = false;
888
+ this.element = null;
889
+ }
890
+ }
891
+ };
892
+ function createClassComponent(ComponentClass) {
893
+ return (props) => {
894
+ const instance = new ComponentClass(props);
895
+ return instance.render();
896
+ };
897
+ }
898
+ var PureComponent = class extends Component {
899
+ shouldComponentUpdate(nextProps, nextState) {
900
+ const propsKeys = Object.keys(this.props);
901
+ const nextPropsKeys = Object.keys(nextProps);
902
+ if (propsKeys.length !== nextPropsKeys.length)
903
+ return true;
904
+ for (const key of propsKeys) {
905
+ if (!Object.is(this.props[key], nextProps[key]))
906
+ return true;
907
+ }
908
+ const stateKeys = Object.keys(this.state);
909
+ const nextStateKeys = Object.keys(nextState);
910
+ if (stateKeys.length !== nextStateKeys.length)
911
+ return true;
912
+ for (const key of stateKeys) {
913
+ if (!Object.is(this.state[key], nextState[key]))
914
+ return true;
915
+ }
916
+ return false;
291
917
  }
292
918
  };
293
919
 
920
+ // src/core/event-bus.ts
921
+ function createEventBus() {
922
+ const events = /* @__PURE__ */ new Map();
923
+ const onceHandlers = /* @__PURE__ */ new WeakMap();
924
+ const on = (event, handler) => {
925
+ if (!events.has(event)) {
926
+ events.set(event, /* @__PURE__ */ new Set());
927
+ }
928
+ events.get(event).add(handler);
929
+ return () => off(event, handler);
930
+ };
931
+ const once = (event, handler) => {
932
+ const onceWrapper = (...args) => {
933
+ handler(...args);
934
+ off(event, onceWrapper);
935
+ };
936
+ onceHandlers.set(handler, onceWrapper);
937
+ return on(event, onceWrapper);
938
+ };
939
+ const off = (event, handler) => {
940
+ if (!handler) {
941
+ events.delete(event);
942
+ return;
943
+ }
944
+ const handlers = events.get(event);
945
+ if (!handlers)
946
+ return;
947
+ handlers.delete(handler);
948
+ const onceWrapper = onceHandlers.get(handler);
949
+ if (onceWrapper) {
950
+ handlers.delete(onceWrapper);
951
+ onceHandlers.delete(handler);
952
+ }
953
+ if (handlers.size === 0) {
954
+ events.delete(event);
955
+ }
956
+ };
957
+ const emit = (event, ...args) => {
958
+ const handlers = events.get(event);
959
+ if (!handlers)
960
+ return;
961
+ const handlersCopy = Array.from(handlers);
962
+ for (const handler of handlersCopy) {
963
+ try {
964
+ handler(...args);
965
+ } catch (error) {
966
+ console.error(`Error in event handler for "${event}":`, error);
967
+ }
968
+ }
969
+ };
970
+ const clear = (event) => {
971
+ if (event) {
972
+ events.delete(event);
973
+ } else {
974
+ events.clear();
975
+ }
976
+ };
977
+ return { on, once, off, emit, clear };
978
+ }
979
+ var eventBus = createEventBus();
980
+ function useEvent(event, handler, options = {}) {
981
+ return options.once ? eventBus.once(event, handler) : eventBus.on(event, handler);
982
+ }
983
+
984
+ // src/core/router.ts
985
+ var RouterContext = createContext({
986
+ pathname: "/",
987
+ search: "",
988
+ hash: "",
989
+ params: {},
990
+ query: {},
991
+ navigate: () => {
992
+ },
993
+ back: () => {
994
+ },
995
+ forward: () => {
996
+ },
997
+ match: () => false
998
+ });
999
+ function parseQuery(search) {
1000
+ const query = {};
1001
+ const params = new URLSearchParams(search);
1002
+ params.forEach((value, key) => {
1003
+ query[key] = value;
1004
+ });
1005
+ return query;
1006
+ }
1007
+ function matchPath(pathname, pattern, exact = false) {
1008
+ const params = {};
1009
+ const patternParts = pattern.split("/").filter(Boolean);
1010
+ const pathParts = pathname.split("/").filter(Boolean);
1011
+ if (exact && patternParts.length !== pathParts.length) {
1012
+ return { match: false, params };
1013
+ }
1014
+ if (patternParts.length > pathParts.length) {
1015
+ return { match: false, params };
1016
+ }
1017
+ for (let i = 0; i < patternParts.length; i++) {
1018
+ const patternPart = patternParts[i];
1019
+ const pathPart = pathParts[i];
1020
+ if (patternPart.startsWith(":")) {
1021
+ const paramName = patternPart.slice(1);
1022
+ params[paramName] = decodeURIComponent(pathPart);
1023
+ } else if (patternPart === "*") {
1024
+ params["*"] = pathParts.slice(i).join("/");
1025
+ return { match: true, params };
1026
+ } else if (patternPart !== pathPart) {
1027
+ return { match: false, params };
1028
+ }
1029
+ }
1030
+ return { match: true, params };
1031
+ }
1032
+ function RouterProvider({
1033
+ children
1034
+ }) {
1035
+ const [location, setLocation] = useState((() => {
1036
+ if (typeof window === "undefined") {
1037
+ return { pathname: "/", search: "", hash: "", params: {}, query: {} };
1038
+ }
1039
+ return {
1040
+ pathname: window.location.pathname,
1041
+ search: window.location.search,
1042
+ hash: window.location.hash,
1043
+ params: {},
1044
+ query: parseQuery(window.location.search)
1045
+ };
1046
+ })());
1047
+ useEffect(() => {
1048
+ if (typeof window === "undefined")
1049
+ return;
1050
+ const handlePopState = () => {
1051
+ setLocation({
1052
+ pathname: window.location.pathname,
1053
+ search: window.location.search,
1054
+ hash: window.location.hash,
1055
+ params: {},
1056
+ query: parseQuery(window.location.search)
1057
+ });
1058
+ };
1059
+ window.addEventListener("popstate", handlePopState);
1060
+ return () => window.removeEventListener("popstate", handlePopState);
1061
+ }, []);
1062
+ const navigate = (to, options = {}) => {
1063
+ if (typeof window === "undefined")
1064
+ return;
1065
+ const url = new URL(to, window.location.origin);
1066
+ if (options.replace) {
1067
+ window.history.replaceState(options.state || null, "", url.href);
1068
+ } else {
1069
+ window.history.pushState(options.state || null, "", url.href);
1070
+ }
1071
+ setLocation({
1072
+ pathname: url.pathname,
1073
+ search: url.search,
1074
+ hash: url.hash,
1075
+ params: {},
1076
+ query: parseQuery(url.search)
1077
+ });
1078
+ };
1079
+ const back = () => {
1080
+ if (typeof window !== "undefined") {
1081
+ window.history.back();
1082
+ }
1083
+ };
1084
+ const forward = () => {
1085
+ if (typeof window !== "undefined") {
1086
+ window.history.forward();
1087
+ }
1088
+ };
1089
+ const match = (pattern) => {
1090
+ return matchPath(location.pathname, pattern).match;
1091
+ };
1092
+ const contextValue = {
1093
+ ...location,
1094
+ navigate,
1095
+ back,
1096
+ forward,
1097
+ match
1098
+ };
1099
+ return jsx(RouterContext.Provider, { value: contextValue, children });
1100
+ }
1101
+ function Router({ routes }) {
1102
+ const { pathname, params: existingParams } = useContext(RouterContext);
1103
+ for (const route of routes) {
1104
+ const { match, params } = matchPath(pathname, route.path, route.exact);
1105
+ if (match) {
1106
+ const Component2 = route.component;
1107
+ return jsx(Component2, { ...params, ...existingParams });
1108
+ }
1109
+ }
1110
+ return null;
1111
+ }
1112
+ function Route({
1113
+ path,
1114
+ component: Component2,
1115
+ exact = false
1116
+ }) {
1117
+ const { pathname } = useContext(RouterContext);
1118
+ const { match, params } = matchPath(pathname, path, exact);
1119
+ if (match) {
1120
+ return jsx(Component2, params);
1121
+ }
1122
+ return null;
1123
+ }
1124
+ function Switch({ children }) {
1125
+ const { pathname } = useContext(RouterContext);
1126
+ const routes = Array.isArray(children) ? children : [children];
1127
+ for (const child of routes) {
1128
+ if (child?.props?.path) {
1129
+ const exact = child.props.exact ?? false;
1130
+ const { match } = matchPath(pathname, child.props.path, exact);
1131
+ if (match) {
1132
+ return child;
1133
+ }
1134
+ }
1135
+ }
1136
+ return null;
1137
+ }
1138
+ function Link({
1139
+ to,
1140
+ children,
1141
+ replace = false,
1142
+ className = "",
1143
+ activeClassName = "",
1144
+ ...rest
1145
+ }) {
1146
+ const { pathname, navigate } = useContext(RouterContext);
1147
+ const isActive = pathname === to || pathname.startsWith(to + "/");
1148
+ const handleClick = (e) => {
1149
+ e.preventDefault();
1150
+ navigate(to, { replace });
1151
+ };
1152
+ const combinedClassName = isActive && activeClassName ? `${className} ${activeClassName}`.trim() : className;
1153
+ return jsx("a", {
1154
+ href: to,
1155
+ onClick: handleClick,
1156
+ className: combinedClassName || void 0,
1157
+ ...rest,
1158
+ children
1159
+ });
1160
+ }
1161
+ function Redirect({
1162
+ to,
1163
+ replace = true
1164
+ }) {
1165
+ const { navigate } = useContext(RouterContext);
1166
+ useEffect(() => {
1167
+ navigate(to, { replace });
1168
+ }, [to, replace]);
1169
+ return null;
1170
+ }
1171
+ function NavLink({
1172
+ to,
1173
+ children,
1174
+ activeClassName = "active",
1175
+ className = "",
1176
+ exact = false,
1177
+ ...rest
1178
+ }) {
1179
+ const { pathname, navigate } = useContext(RouterContext);
1180
+ const { match } = matchPath(pathname, to, exact);
1181
+ const isActive = match;
1182
+ const combinedClassName = isActive ? `${className} ${activeClassName}`.trim() : className;
1183
+ const handleClick = (e) => {
1184
+ e.preventDefault();
1185
+ navigate(to);
1186
+ };
1187
+ return jsx("a", {
1188
+ href: to,
1189
+ onClick: handleClick,
1190
+ className: combinedClassName || void 0,
1191
+ "aria-current": isActive ? "page" : void 0,
1192
+ ...rest,
1193
+ children
1194
+ });
1195
+ }
1196
+ function useRouter() {
1197
+ return useContext(RouterContext);
1198
+ }
1199
+ function useLocation() {
1200
+ const { pathname, search, hash, params, query } = useContext(RouterContext);
1201
+ return { pathname, search, hash, params, query };
1202
+ }
1203
+ function useParams() {
1204
+ const { params } = useContext(RouterContext);
1205
+ return params;
1206
+ }
1207
+ function useNavigate() {
1208
+ const { navigate } = useContext(RouterContext);
1209
+ return navigate;
1210
+ }
1211
+ function useSearchParams() {
1212
+ const { search, navigate, pathname } = useContext(RouterContext);
1213
+ const searchParams = new URLSearchParams(search);
1214
+ const setSearchParams = (newParams) => {
1215
+ navigate(`${pathname}?${newParams.toString()}`);
1216
+ };
1217
+ return [searchParams, setSearchParams];
1218
+ }
1219
+ function useMatch(pattern) {
1220
+ const { pathname } = useContext(RouterContext);
1221
+ const { match, params } = matchPath(pathname, pattern);
1222
+ return match ? params : null;
1223
+ }
1224
+
1225
+ // src/core/forms.ts
1226
+ function validateFieldValue(value, rules, allValues) {
1227
+ if (rules.required) {
1228
+ const isEmpty2 = value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0;
1229
+ if (isEmpty2) {
1230
+ return typeof rules.required === "string" ? rules.required : "This field is required";
1231
+ }
1232
+ }
1233
+ if (value === void 0 || value === null || value === "") {
1234
+ return void 0;
1235
+ }
1236
+ if (rules.minLength !== void 0) {
1237
+ const minLength = typeof rules.minLength === "object" ? rules.minLength.value : rules.minLength;
1238
+ const message = typeof rules.minLength === "object" ? rules.minLength.message : `Minimum length is ${minLength}`;
1239
+ if (String(value).length < minLength) {
1240
+ return message;
1241
+ }
1242
+ }
1243
+ if (rules.maxLength !== void 0) {
1244
+ const maxLength = typeof rules.maxLength === "object" ? rules.maxLength.value : rules.maxLength;
1245
+ const message = typeof rules.maxLength === "object" ? rules.maxLength.message : `Maximum length is ${maxLength}`;
1246
+ if (String(value).length > maxLength) {
1247
+ return message;
1248
+ }
1249
+ }
1250
+ if (rules.min !== void 0) {
1251
+ const min = typeof rules.min === "object" ? rules.min.value : rules.min;
1252
+ const message = typeof rules.min === "object" ? rules.min.message : `Minimum value is ${min}`;
1253
+ if (Number(value) < min) {
1254
+ return message;
1255
+ }
1256
+ }
1257
+ if (rules.max !== void 0) {
1258
+ const max = typeof rules.max === "object" ? rules.max.value : rules.max;
1259
+ const message = typeof rules.max === "object" ? rules.max.message : `Maximum value is ${max}`;
1260
+ if (Number(value) > max) {
1261
+ return message;
1262
+ }
1263
+ }
1264
+ if (rules.pattern !== void 0) {
1265
+ const pattern = rules.pattern instanceof RegExp ? rules.pattern : rules.pattern.value;
1266
+ const message = rules.pattern instanceof RegExp ? "Invalid format" : rules.pattern.message;
1267
+ if (!pattern.test(String(value))) {
1268
+ return message;
1269
+ }
1270
+ }
1271
+ if (rules.validate) {
1272
+ const result = rules.validate(value, allValues);
1273
+ if (result === false) {
1274
+ return "Invalid value";
1275
+ }
1276
+ if (typeof result === "string") {
1277
+ return result;
1278
+ }
1279
+ }
1280
+ return void 0;
1281
+ }
1282
+ function useForm(options) {
1283
+ const {
1284
+ initialValues,
1285
+ validate,
1286
+ validationRules,
1287
+ onSubmit,
1288
+ validateOnChange = true,
1289
+ validateOnBlur = true
1290
+ } = options;
1291
+ const [values, setValuesState] = useState(initialValues);
1292
+ const [errors, setErrorsState] = useState({});
1293
+ const [touched, setTouched] = useState({});
1294
+ const [dirty, setDirty] = useState({});
1295
+ const [isSubmitting, setIsSubmitting] = useState(false);
1296
+ const [submitCount, setSubmitCount] = useState(0);
1297
+ const initialValuesRef = useRef(initialValues);
1298
+ const isValid = Object.keys(errors).length === 0;
1299
+ const isDirty = Object.values(dirty).some(Boolean);
1300
+ const validateField = useCallback((field) => {
1301
+ const value = values[field];
1302
+ if (validationRules && validationRules[field]) {
1303
+ return validateFieldValue(value, validationRules[field], values);
1304
+ }
1305
+ if (validate) {
1306
+ const allErrors = validate(values);
1307
+ return allErrors[field];
1308
+ }
1309
+ return void 0;
1310
+ }, [values, validate, validationRules]);
1311
+ const validateForm = useCallback(() => {
1312
+ const newErrors = {};
1313
+ if (validationRules) {
1314
+ for (const field in validationRules) {
1315
+ const error = validateFieldValue(values[field], validationRules[field], values);
1316
+ if (error) {
1317
+ newErrors[field] = error;
1318
+ }
1319
+ }
1320
+ }
1321
+ if (validate) {
1322
+ const customErrors = validate(values);
1323
+ Object.assign(newErrors, customErrors);
1324
+ }
1325
+ return newErrors;
1326
+ }, [values, validate, validationRules]);
1327
+ useEffect(() => {
1328
+ if (validateOnChange) {
1329
+ const newErrors = validateForm();
1330
+ setErrorsState(newErrors);
1331
+ }
1332
+ }, [values, validateOnChange, validateForm]);
1333
+ const handleChange = useCallback((e) => {
1334
+ const { name, value, type, checked } = e.target;
1335
+ const fieldValue = type === "checkbox" ? checked : value;
1336
+ setValuesState((prev) => ({ ...prev, [name]: fieldValue }));
1337
+ setDirty((prev) => ({ ...prev, [name]: true }));
1338
+ }, []);
1339
+ const handleBlur = useCallback((e) => {
1340
+ const { name } = e.target;
1341
+ setTouched((prev) => ({ ...prev, [name]: true }));
1342
+ if (validateOnBlur) {
1343
+ const error = validateField(name);
1344
+ setErrorsState((prev) => {
1345
+ if (error) {
1346
+ return { ...prev, [name]: error };
1347
+ }
1348
+ const { [name]: _, ...rest } = prev;
1349
+ return rest;
1350
+ });
1351
+ }
1352
+ }, [validateOnBlur, validateField]);
1353
+ const handleSubmit = useCallback(async (e) => {
1354
+ if (e?.preventDefault) {
1355
+ e.preventDefault();
1356
+ }
1357
+ setSubmitCount((prev) => prev + 1);
1358
+ const allTouched = {};
1359
+ for (const key in values) {
1360
+ allTouched[key] = true;
1361
+ }
1362
+ setTouched(allTouched);
1363
+ const formErrors = validateForm();
1364
+ setErrorsState(formErrors);
1365
+ if (Object.keys(formErrors).length > 0) {
1366
+ return;
1367
+ }
1368
+ if (onSubmit) {
1369
+ setIsSubmitting(true);
1370
+ try {
1371
+ await onSubmit(values, formConfig);
1372
+ } finally {
1373
+ setIsSubmitting(false);
1374
+ }
1375
+ }
1376
+ }, [values, validateForm, onSubmit]);
1377
+ const setFieldValue = useCallback((field, value) => {
1378
+ setValuesState((prev) => ({ ...prev, [field]: value }));
1379
+ setDirty((prev) => ({ ...prev, [field]: true }));
1380
+ }, []);
1381
+ const setFieldError = useCallback((field, error) => {
1382
+ setErrorsState((prev) => ({ ...prev, [field]: error }));
1383
+ }, []);
1384
+ const setFieldTouched = useCallback((field, isTouched = true) => {
1385
+ setTouched((prev) => ({ ...prev, [field]: isTouched }));
1386
+ }, []);
1387
+ const setValues = useCallback((newValues) => {
1388
+ setValuesState((prev) => ({ ...prev, ...newValues }));
1389
+ }, []);
1390
+ const setErrors = useCallback((newErrors) => {
1391
+ setErrorsState(newErrors);
1392
+ }, []);
1393
+ const resetForm = useCallback((nextValues) => {
1394
+ setValuesState(nextValues ? { ...initialValuesRef.current, ...nextValues } : initialValuesRef.current);
1395
+ setErrorsState({});
1396
+ setTouched({});
1397
+ setDirty({});
1398
+ setSubmitCount(0);
1399
+ }, []);
1400
+ const getFieldProps = useCallback((field) => ({
1401
+ name: field,
1402
+ value: values[field] ?? "",
1403
+ onChange: handleChange,
1404
+ onBlur: handleBlur
1405
+ }), [values, handleChange, handleBlur]);
1406
+ const formConfig = {
1407
+ values,
1408
+ errors,
1409
+ touched,
1410
+ dirty,
1411
+ isValid,
1412
+ isDirty,
1413
+ isSubmitting,
1414
+ submitCount,
1415
+ handleChange,
1416
+ handleBlur,
1417
+ handleSubmit,
1418
+ setFieldValue,
1419
+ setFieldError,
1420
+ setFieldTouched,
1421
+ setValues,
1422
+ setErrors,
1423
+ resetForm,
1424
+ validateField,
1425
+ validateForm,
1426
+ getFieldProps,
1427
+ register: getFieldProps
1428
+ };
1429
+ return formConfig;
1430
+ }
1431
+ function useField(name, form) {
1432
+ return {
1433
+ field: form.getFieldProps(name),
1434
+ meta: {
1435
+ touched: form.touched[name] || false,
1436
+ error: form.errors[name],
1437
+ dirty: form.dirty[name] || false
1438
+ },
1439
+ helpers: {
1440
+ setValue: (value) => form.setFieldValue(name, value),
1441
+ setError: (error) => form.setFieldError(name, error),
1442
+ setTouched: (touched) => form.setFieldTouched(name, touched)
1443
+ }
1444
+ };
1445
+ }
1446
+ var patterns = {
1447
+ email: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
1448
+ phone: /^\+?[1-9]\d{1,14}$/,
1449
+ url: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
1450
+ alphanumeric: /^[a-zA-Z0-9]+$/,
1451
+ numeric: /^\d+$/,
1452
+ password: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/
1453
+ };
1454
+
1455
+ // src/core/store.ts
1456
+ function createStore(reducer, initialState, middlewares = []) {
1457
+ let state = initialState;
1458
+ let listeners = /* @__PURE__ */ new Set();
1459
+ let currentReducer = reducer;
1460
+ const getState = () => state;
1461
+ const subscribe = (listener) => {
1462
+ listeners.add(listener);
1463
+ return () => {
1464
+ listeners.delete(listener);
1465
+ };
1466
+ };
1467
+ let dispatch = (action) => {
1468
+ state = currentReducer(state, action);
1469
+ listeners.forEach((listener) => listener());
1470
+ };
1471
+ if (middlewares.length > 0) {
1472
+ const store = { getState, dispatch, subscribe, replaceReducer: () => {
1473
+ } };
1474
+ const chain = middlewares.map((middleware) => middleware(store));
1475
+ dispatch = chain.reduceRight(
1476
+ (next, middleware) => middleware(next),
1477
+ dispatch
1478
+ );
1479
+ }
1480
+ const replaceReducer = (nextReducer) => {
1481
+ currentReducer = nextReducer;
1482
+ };
1483
+ dispatch({ type: "@@INIT" });
1484
+ return {
1485
+ getState,
1486
+ dispatch,
1487
+ subscribe,
1488
+ replaceReducer
1489
+ };
1490
+ }
1491
+ function combineReducers(reducers) {
1492
+ return (state, action) => {
1493
+ const nextState = {};
1494
+ let hasChanged = false;
1495
+ for (const key in reducers) {
1496
+ const reducer = reducers[key];
1497
+ const previousStateForKey = state[key];
1498
+ const nextStateForKey = reducer(previousStateForKey, action);
1499
+ nextState[key] = nextStateForKey;
1500
+ hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
1501
+ }
1502
+ return hasChanged ? nextState : state;
1503
+ };
1504
+ }
1505
+ var StoreContext = createContext({
1506
+ store: {
1507
+ getState: () => ({}),
1508
+ dispatch: () => {
1509
+ },
1510
+ subscribe: () => () => {
1511
+ },
1512
+ replaceReducer: () => {
1513
+ }
1514
+ },
1515
+ state: {}
1516
+ });
1517
+ function StoreProvider({
1518
+ store,
1519
+ children
1520
+ }) {
1521
+ const [state, setState] = useState(store.getState());
1522
+ useEffect(() => {
1523
+ const unsubscribe = store.subscribe(() => {
1524
+ setState(store.getState());
1525
+ });
1526
+ return unsubscribe;
1527
+ }, [store]);
1528
+ return jsx(StoreContext.Provider, {
1529
+ value: { store, state },
1530
+ children
1531
+ });
1532
+ }
1533
+ function useSelector(selector) {
1534
+ const { state } = useContext(StoreContext);
1535
+ return selector(state);
1536
+ }
1537
+ function useDispatch() {
1538
+ const { store } = useContext(StoreContext);
1539
+ return store.dispatch;
1540
+ }
1541
+ function useStore() {
1542
+ const { store } = useContext(StoreContext);
1543
+ return store;
1544
+ }
1545
+ var logger = (store) => (next) => (action) => {
1546
+ console.group(`Action: ${action.type}`);
1547
+ console.log("Payload:", action.payload);
1548
+ console.log("Previous State:", store.getState());
1549
+ const result = next(action);
1550
+ console.log("Next State:", store.getState());
1551
+ console.groupEnd();
1552
+ return result;
1553
+ };
1554
+ var thunk = (store) => (next) => (action) => {
1555
+ if (typeof action === "function") {
1556
+ return action(store.dispatch, store.getState);
1557
+ }
1558
+ return next(action);
1559
+ };
1560
+ var devTools = (store) => (next) => (action) => {
1561
+ if (typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__) {
1562
+ const devToolsExtension = window.__REDUX_DEVTOOLS_EXTENSION__;
1563
+ devToolsExtension.send(action, store.getState());
1564
+ }
1565
+ return next(action);
1566
+ };
1567
+ function createAction(type) {
1568
+ const actionCreator = (payload) => ({ type, payload });
1569
+ actionCreator.type = type;
1570
+ actionCreator.match = (action) => action.type === type;
1571
+ return actionCreator;
1572
+ }
1573
+ function createSlice(config) {
1574
+ const { name, initialState, reducers } = config;
1575
+ const actions = {};
1576
+ for (const key in reducers) {
1577
+ const type = `${name}/${key}`;
1578
+ actions[key] = (payload) => ({ type, payload });
1579
+ }
1580
+ const reducer = (state = initialState, action) => {
1581
+ for (const key in reducers) {
1582
+ const type = `${name}/${key}`;
1583
+ if (action.type === type) {
1584
+ return reducers[key](state, action);
1585
+ }
1586
+ }
1587
+ return state;
1588
+ };
1589
+ return {
1590
+ name,
1591
+ reducer,
1592
+ actions
1593
+ };
1594
+ }
1595
+
1596
+ // src/core/lifecycle-events.ts
1597
+ var LifecycleEvents = /* @__PURE__ */ ((LifecycleEvents2) => {
1598
+ LifecycleEvents2["APP_INIT"] = "app:init";
1599
+ LifecycleEvents2["APP_MOUNTED"] = "app:mounted";
1600
+ LifecycleEvents2["APP_UPDATED"] = "app:updated";
1601
+ LifecycleEvents2["APP_ERROR"] = "app:error";
1602
+ LifecycleEvents2["APP_DESTROYED"] = "app:destroyed";
1603
+ LifecycleEvents2["COMPONENT_CREATED"] = "component:created";
1604
+ LifecycleEvents2["COMPONENT_MOUNTED"] = "component:mounted";
1605
+ LifecycleEvents2["COMPONENT_UPDATED"] = "component:updated";
1606
+ LifecycleEvents2["COMPONENT_ERROR"] = "component:error";
1607
+ LifecycleEvents2["COMPONENT_UNMOUNTED"] = "component:unmounted";
1608
+ LifecycleEvents2["ROUTER_BEFORE_CHANGE"] = "router:before-change";
1609
+ LifecycleEvents2["ROUTER_AFTER_CHANGE"] = "router:after-change";
1610
+ LifecycleEvents2["ROUTER_ERROR"] = "router:error";
1611
+ LifecycleEvents2["STORE_INITIALIZED"] = "store:initialized";
1612
+ LifecycleEvents2["STORE_BEFORE_ACTION"] = "store:before-action";
1613
+ LifecycleEvents2["STORE_AFTER_ACTION"] = "store:after-action";
1614
+ LifecycleEvents2["STORE_ERROR"] = "store:error";
1615
+ return LifecycleEvents2;
1616
+ })(LifecycleEvents || {});
1617
+ function emitAppInit(data) {
1618
+ eventBus.emit("app:init" /* APP_INIT */, data);
1619
+ }
1620
+ function emitAppMounted(rootElement) {
1621
+ eventBus.emit("app:mounted" /* APP_MOUNTED */, rootElement);
1622
+ }
1623
+ function emitAppUpdated() {
1624
+ eventBus.emit("app:updated" /* APP_UPDATED */);
1625
+ }
1626
+ function emitAppError(error) {
1627
+ eventBus.emit("app:error" /* APP_ERROR */, error);
1628
+ }
1629
+ function emitAppDestroyed() {
1630
+ eventBus.emit("app:destroyed" /* APP_DESTROYED */);
1631
+ }
1632
+ function emitComponentCreated(info) {
1633
+ eventBus.emit("component:created" /* COMPONENT_CREATED */, info);
1634
+ }
1635
+ function emitComponentMounted(info, element) {
1636
+ eventBus.emit("component:mounted" /* COMPONENT_MOUNTED */, info, element);
1637
+ }
1638
+ function emitComponentUpdated(info, prevProps, newProps) {
1639
+ eventBus.emit("component:updated" /* COMPONENT_UPDATED */, info, prevProps, newProps);
1640
+ }
1641
+ function emitComponentError(info, error) {
1642
+ eventBus.emit("component:error" /* COMPONENT_ERROR */, info, error);
1643
+ }
1644
+ function emitComponentUnmounted(info) {
1645
+ eventBus.emit("component:unmounted" /* COMPONENT_UNMOUNTED */, info);
1646
+ }
1647
+ function emitRouterBeforeChange(info) {
1648
+ return new Promise((resolve) => {
1649
+ let prevented = false;
1650
+ const prevent = () => {
1651
+ prevented = true;
1652
+ };
1653
+ eventBus.emit("router:before-change" /* ROUTER_BEFORE_CHANGE */, info, prevent);
1654
+ resolve(!prevented);
1655
+ });
1656
+ }
1657
+ function emitRouterAfterChange(info) {
1658
+ eventBus.emit("router:after-change" /* ROUTER_AFTER_CHANGE */, info);
1659
+ }
1660
+ function emitRouterError(error, info) {
1661
+ eventBus.emit("router:error" /* ROUTER_ERROR */, error, info);
1662
+ }
1663
+ function emitStoreInitialized(state) {
1664
+ eventBus.emit("store:initialized" /* STORE_INITIALIZED */, state);
1665
+ }
1666
+ function emitStoreBeforeAction(actionType, payload, state) {
1667
+ eventBus.emit("store:before-action" /* STORE_BEFORE_ACTION */, actionType, payload, state);
1668
+ }
1669
+ function emitStoreAfterAction(info) {
1670
+ eventBus.emit("store:after-action" /* STORE_AFTER_ACTION */, info);
1671
+ }
1672
+ function emitStoreError(error, actionType, payload) {
1673
+ eventBus.emit("store:error" /* STORE_ERROR */, error, actionType, payload);
1674
+ }
1675
+ function onAppInit(handler) {
1676
+ return eventBus.on("app:init" /* APP_INIT */, handler);
1677
+ }
1678
+ function onAppMounted(handler) {
1679
+ return eventBus.on("app:mounted" /* APP_MOUNTED */, handler);
1680
+ }
1681
+ function onAppUpdated(handler) {
1682
+ return eventBus.on("app:updated" /* APP_UPDATED */, handler);
1683
+ }
1684
+ function onAppError(handler) {
1685
+ return eventBus.on("app:error" /* APP_ERROR */, handler);
1686
+ }
1687
+ function onAppDestroyed(handler) {
1688
+ return eventBus.on("app:destroyed" /* APP_DESTROYED */, handler);
1689
+ }
1690
+ function onComponentCreated(handler) {
1691
+ return eventBus.on("component:created" /* COMPONENT_CREATED */, handler);
1692
+ }
1693
+ function onComponentMounted(handler) {
1694
+ return eventBus.on("component:mounted" /* COMPONENT_MOUNTED */, handler);
1695
+ }
1696
+ function onComponentUpdated(handler) {
1697
+ return eventBus.on("component:updated" /* COMPONENT_UPDATED */, handler);
1698
+ }
1699
+ function onComponentError(handler) {
1700
+ return eventBus.on("component:error" /* COMPONENT_ERROR */, handler);
1701
+ }
1702
+ function onComponentUnmounted(handler) {
1703
+ return eventBus.on("component:unmounted" /* COMPONENT_UNMOUNTED */, handler);
1704
+ }
1705
+ function onRouterBeforeChange(handler) {
1706
+ return eventBus.on("router:before-change" /* ROUTER_BEFORE_CHANGE */, handler);
1707
+ }
1708
+ function onRouterAfterChange(handler) {
1709
+ return eventBus.on("router:after-change" /* ROUTER_AFTER_CHANGE */, handler);
1710
+ }
1711
+ function onRouterError(handler) {
1712
+ return eventBus.on("router:error" /* ROUTER_ERROR */, handler);
1713
+ }
1714
+ function onStoreInitialized(handler) {
1715
+ return eventBus.on("store:initialized" /* STORE_INITIALIZED */, handler);
1716
+ }
1717
+ function onStoreBeforeAction(handler) {
1718
+ return eventBus.on("store:before-action" /* STORE_BEFORE_ACTION */, handler);
1719
+ }
1720
+ function onStoreAfterAction(handler) {
1721
+ return eventBus.on("store:after-action" /* STORE_AFTER_ACTION */, handler);
1722
+ }
1723
+ function onStoreError(handler) {
1724
+ return eventBus.on("store:error" /* STORE_ERROR */, handler);
1725
+ }
1726
+
1727
+ // src/core/utils.ts
1728
+ function debounce(func, wait, options = {}) {
1729
+ let timeoutId = null;
1730
+ let lastArgs = null;
1731
+ let lastThis = null;
1732
+ let result;
1733
+ let lastCallTime;
1734
+ let lastInvokeTime = 0;
1735
+ const { leading = false, trailing = true } = options;
1736
+ const invokeFunc = (time) => {
1737
+ const args = lastArgs;
1738
+ const thisArg = lastThis;
1739
+ lastArgs = null;
1740
+ lastThis = null;
1741
+ lastInvokeTime = time;
1742
+ result = func.apply(thisArg, args);
1743
+ return result;
1744
+ };
1745
+ const shouldInvoke = (time) => {
1746
+ const timeSinceLastCall = lastCallTime === void 0 ? 0 : time - lastCallTime;
1747
+ const timeSinceLastInvoke = time - lastInvokeTime;
1748
+ return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || timeSinceLastInvoke >= wait;
1749
+ };
1750
+ const trailingEdge = (time) => {
1751
+ timeoutId = null;
1752
+ if (trailing && lastArgs) {
1753
+ return invokeFunc(time);
1754
+ }
1755
+ lastArgs = null;
1756
+ lastThis = null;
1757
+ return result;
1758
+ };
1759
+ const remainingWait = (time) => {
1760
+ const timeSinceLastCall = lastCallTime === void 0 ? 0 : time - lastCallTime;
1761
+ const timeSinceLastInvoke = time - lastInvokeTime;
1762
+ const timeWaiting = wait - timeSinceLastCall;
1763
+ return timeWaiting;
1764
+ };
1765
+ const timerExpired = () => {
1766
+ const time = Date.now();
1767
+ if (shouldInvoke(time)) {
1768
+ return trailingEdge(time);
1769
+ }
1770
+ timeoutId = setTimeout(timerExpired, remainingWait(time));
1771
+ return result;
1772
+ };
1773
+ const debounced = function(...args) {
1774
+ const time = Date.now();
1775
+ const isInvoking = shouldInvoke(time);
1776
+ lastArgs = args;
1777
+ lastThis = this;
1778
+ lastCallTime = time;
1779
+ if (isInvoking) {
1780
+ if (timeoutId === null) {
1781
+ lastInvokeTime = time;
1782
+ timeoutId = setTimeout(timerExpired, wait);
1783
+ if (leading) {
1784
+ return invokeFunc(time);
1785
+ }
1786
+ }
1787
+ }
1788
+ if (timeoutId === null) {
1789
+ timeoutId = setTimeout(timerExpired, wait);
1790
+ }
1791
+ return result;
1792
+ };
1793
+ debounced.cancel = () => {
1794
+ if (timeoutId !== null) {
1795
+ clearTimeout(timeoutId);
1796
+ }
1797
+ lastInvokeTime = 0;
1798
+ lastArgs = null;
1799
+ lastThis = null;
1800
+ lastCallTime = void 0;
1801
+ timeoutId = null;
1802
+ };
1803
+ debounced.flush = () => {
1804
+ if (timeoutId !== null) {
1805
+ return trailingEdge(Date.now());
1806
+ }
1807
+ return result;
1808
+ };
1809
+ return debounced;
1810
+ }
1811
+ function throttle(func, wait, options = {}) {
1812
+ let timeoutId = null;
1813
+ let lastArgs = null;
1814
+ let lastThis = null;
1815
+ let result;
1816
+ let lastCallTime = 0;
1817
+ const { leading = true, trailing = true } = options;
1818
+ const invokeFunc = () => {
1819
+ const args = lastArgs;
1820
+ const thisArg = lastThis;
1821
+ lastArgs = null;
1822
+ lastThis = null;
1823
+ lastCallTime = Date.now();
1824
+ result = func.apply(thisArg, args);
1825
+ return result;
1826
+ };
1827
+ const throttled = function(...args) {
1828
+ const now = Date.now();
1829
+ const remaining = wait - (now - lastCallTime);
1830
+ lastArgs = args;
1831
+ lastThis = this;
1832
+ if (remaining <= 0 || remaining > wait) {
1833
+ if (timeoutId) {
1834
+ clearTimeout(timeoutId);
1835
+ timeoutId = null;
1836
+ }
1837
+ if (leading || lastCallTime !== 0) {
1838
+ return invokeFunc();
1839
+ }
1840
+ }
1841
+ if (!timeoutId && trailing) {
1842
+ timeoutId = setTimeout(() => {
1843
+ timeoutId = null;
1844
+ if (trailing && lastArgs) {
1845
+ invokeFunc();
1846
+ }
1847
+ }, remaining);
1848
+ }
1849
+ return result;
1850
+ };
1851
+ throttled.cancel = () => {
1852
+ if (timeoutId !== null) {
1853
+ clearTimeout(timeoutId);
1854
+ }
1855
+ timeoutId = null;
1856
+ lastArgs = null;
1857
+ lastThis = null;
1858
+ lastCallTime = 0;
1859
+ };
1860
+ return throttled;
1861
+ }
1862
+ function deepClone(obj) {
1863
+ if (obj === null || typeof obj !== "object") {
1864
+ return obj;
1865
+ }
1866
+ if (obj instanceof Date) {
1867
+ return new Date(obj.getTime());
1868
+ }
1869
+ if (obj instanceof RegExp) {
1870
+ return new RegExp(obj.source, obj.flags);
1871
+ }
1872
+ if (Array.isArray(obj)) {
1873
+ return obj.map((item) => deepClone(item));
1874
+ }
1875
+ if (obj instanceof Map) {
1876
+ const clonedMap = /* @__PURE__ */ new Map();
1877
+ obj.forEach((value, key) => {
1878
+ clonedMap.set(deepClone(key), deepClone(value));
1879
+ });
1880
+ return clonedMap;
1881
+ }
1882
+ if (obj instanceof Set) {
1883
+ const clonedSet = /* @__PURE__ */ new Set();
1884
+ obj.forEach((value) => {
1885
+ clonedSet.add(deepClone(value));
1886
+ });
1887
+ return clonedSet;
1888
+ }
1889
+ const clonedObj = {};
1890
+ for (const key in obj) {
1891
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
1892
+ clonedObj[key] = deepClone(obj[key]);
1893
+ }
1894
+ }
1895
+ return clonedObj;
1896
+ }
1897
+ function deepMerge(target, ...sources) {
1898
+ if (!sources.length)
1899
+ return target;
1900
+ const source = sources.shift();
1901
+ if (source === void 0)
1902
+ return target;
1903
+ for (const key in source) {
1904
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
1905
+ const sourceValue = source[key];
1906
+ const targetValue = target[key];
1907
+ if (sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && targetValue !== null && typeof targetValue === "object" && !Array.isArray(targetValue)) {
1908
+ target[key] = deepMerge(targetValue, sourceValue);
1909
+ } else {
1910
+ target[key] = deepClone(sourceValue);
1911
+ }
1912
+ }
1913
+ }
1914
+ return deepMerge(target, ...sources);
1915
+ }
1916
+ function memoize(fn, options = {}) {
1917
+ const { maxSize = 100, keyGenerator = (...args) => JSON.stringify(args) } = options;
1918
+ const cache = /* @__PURE__ */ new Map();
1919
+ const memoized = function(...args) {
1920
+ const key = keyGenerator(...args);
1921
+ if (cache.has(key)) {
1922
+ return cache.get(key);
1923
+ }
1924
+ const result = fn(...args);
1925
+ if (cache.size >= maxSize) {
1926
+ const firstKey = cache.keys().next().value;
1927
+ if (firstKey !== void 0) {
1928
+ cache.delete(firstKey);
1929
+ }
1930
+ }
1931
+ cache.set(key, result);
1932
+ return result;
1933
+ };
1934
+ memoized.cache = cache;
1935
+ memoized.clear = () => cache.clear();
1936
+ return memoized;
1937
+ }
1938
+ function uuid() {
1939
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
1940
+ return crypto.randomUUID();
1941
+ }
1942
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1943
+ const r = Math.random() * 16 | 0;
1944
+ const v = c === "x" ? r : r & 3 | 8;
1945
+ return v.toString(16);
1946
+ });
1947
+ }
1948
+ function formatDate(date, format = "YYYY-MM-DD HH:mm:ss") {
1949
+ const d = date instanceof Date ? date : new Date(date);
1950
+ if (isNaN(d.getTime())) {
1951
+ return "Invalid Date";
1952
+ }
1953
+ const pad = (n, len = 2) => String(n).padStart(len, "0");
1954
+ const tokens = {
1955
+ "YYYY": String(d.getFullYear()),
1956
+ "YY": String(d.getFullYear()).slice(-2),
1957
+ "MM": pad(d.getMonth() + 1),
1958
+ "M": String(d.getMonth() + 1),
1959
+ "DD": pad(d.getDate()),
1960
+ "D": String(d.getDate()),
1961
+ "HH": pad(d.getHours()),
1962
+ "H": String(d.getHours()),
1963
+ "hh": pad(d.getHours() % 12 || 12),
1964
+ "h": String(d.getHours() % 12 || 12),
1965
+ "mm": pad(d.getMinutes()),
1966
+ "m": String(d.getMinutes()),
1967
+ "ss": pad(d.getSeconds()),
1968
+ "s": String(d.getSeconds()),
1969
+ "SSS": pad(d.getMilliseconds(), 3),
1970
+ "A": d.getHours() < 12 ? "AM" : "PM",
1971
+ "a": d.getHours() < 12 ? "am" : "pm"
1972
+ };
1973
+ let result = format;
1974
+ for (const token in tokens) {
1975
+ result = result.replace(new RegExp(token, "g"), tokens[token]);
1976
+ }
1977
+ return result;
1978
+ }
1979
+ function shallowEqual(a, b) {
1980
+ if (a === b)
1981
+ return true;
1982
+ if (!a || !b)
1983
+ return false;
1984
+ if (typeof a !== "object" || typeof b !== "object")
1985
+ return false;
1986
+ const keysA = Object.keys(a);
1987
+ const keysB = Object.keys(b);
1988
+ if (keysA.length !== keysB.length)
1989
+ return false;
1990
+ for (const key of keysA) {
1991
+ if (a[key] !== b[key])
1992
+ return false;
1993
+ }
1994
+ return true;
1995
+ }
1996
+ function deepEqual(a, b) {
1997
+ if (a === b)
1998
+ return true;
1999
+ if (a === null || b === null)
2000
+ return false;
2001
+ if (typeof a !== typeof b)
2002
+ return false;
2003
+ if (typeof a !== "object")
2004
+ return false;
2005
+ if (Array.isArray(a) !== Array.isArray(b))
2006
+ return false;
2007
+ if (Array.isArray(a)) {
2008
+ if (a.length !== b.length)
2009
+ return false;
2010
+ return a.every((item, index) => deepEqual(item, b[index]));
2011
+ }
2012
+ if (a instanceof Date && b instanceof Date) {
2013
+ return a.getTime() === b.getTime();
2014
+ }
2015
+ if (a instanceof RegExp && b instanceof RegExp) {
2016
+ return a.source === b.source && a.flags === b.flags;
2017
+ }
2018
+ const keysA = Object.keys(a);
2019
+ const keysB = Object.keys(b);
2020
+ if (keysA.length !== keysB.length)
2021
+ return false;
2022
+ return keysA.every((key) => deepEqual(a[key], b[key]));
2023
+ }
2024
+ function escapeHtml2(str) {
2025
+ const htmlEscapes = {
2026
+ "&": "&amp;",
2027
+ "<": "&lt;",
2028
+ ">": "&gt;",
2029
+ '"': "&quot;",
2030
+ "'": "&#39;"
2031
+ };
2032
+ return str.replace(/[&<>"']/g, (char) => htmlEscapes[char]);
2033
+ }
2034
+ function unescapeHtml(str) {
2035
+ const htmlUnescapes = {
2036
+ "&amp;": "&",
2037
+ "&lt;": "<",
2038
+ "&gt;": ">",
2039
+ "&quot;": '"',
2040
+ "&#39;": "'"
2041
+ };
2042
+ return str.replace(/&(?:amp|lt|gt|quot|#39);/g, (entity) => htmlUnescapes[entity] || entity);
2043
+ }
2044
+ function capitalize(str) {
2045
+ return str.charAt(0).toUpperCase() + str.slice(1);
2046
+ }
2047
+ function camelCase(str) {
2048
+ return str.replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^(.)/, (char) => char.toLowerCase());
2049
+ }
2050
+ function kebabCase(str) {
2051
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
2052
+ }
2053
+ function sleep(ms) {
2054
+ return new Promise((resolve) => setTimeout(resolve, ms));
2055
+ }
2056
+ async function retry(fn, options = {}) {
2057
+ const { retries = 3, delay = 1e3, backoff = 2, onRetry } = options;
2058
+ let lastError;
2059
+ for (let attempt = 0; attempt <= retries; attempt++) {
2060
+ try {
2061
+ return await fn();
2062
+ } catch (error) {
2063
+ lastError = error;
2064
+ if (attempt < retries) {
2065
+ if (onRetry) {
2066
+ onRetry(lastError, attempt + 1);
2067
+ }
2068
+ await sleep(delay * Math.pow(backoff, attempt));
2069
+ }
2070
+ }
2071
+ }
2072
+ throw lastError;
2073
+ }
2074
+ function deferred() {
2075
+ let resolve;
2076
+ let reject;
2077
+ const promise = new Promise((res, rej) => {
2078
+ resolve = res;
2079
+ reject = rej;
2080
+ });
2081
+ return { promise, resolve, reject };
2082
+ }
2083
+ function pick(obj, keys) {
2084
+ const result = {};
2085
+ for (const key of keys) {
2086
+ if (key in obj) {
2087
+ result[key] = obj[key];
2088
+ }
2089
+ }
2090
+ return result;
2091
+ }
2092
+ function omit(obj, keys) {
2093
+ const result = { ...obj };
2094
+ for (const key of keys) {
2095
+ delete result[key];
2096
+ }
2097
+ return result;
2098
+ }
2099
+ function groupBy(array, key) {
2100
+ return array.reduce((result, item) => {
2101
+ const groupKey = typeof key === "function" ? key(item) : String(item[key]);
2102
+ if (!result[groupKey]) {
2103
+ result[groupKey] = [];
2104
+ }
2105
+ result[groupKey].push(item);
2106
+ return result;
2107
+ }, {});
2108
+ }
2109
+ function isEmpty(value) {
2110
+ if (value === null || value === void 0)
2111
+ return true;
2112
+ if (typeof value === "string")
2113
+ return value.trim() === "";
2114
+ if (Array.isArray(value))
2115
+ return value.length === 0;
2116
+ if (value instanceof Map || value instanceof Set)
2117
+ return value.size === 0;
2118
+ if (typeof value === "object")
2119
+ return Object.keys(value).length === 0;
2120
+ return false;
2121
+ }
2122
+ function clamp(value, min, max) {
2123
+ return Math.min(Math.max(value, min), max);
2124
+ }
2125
+ function get(obj, path, defaultValue) {
2126
+ const keys = Array.isArray(path) ? path : path.split(".");
2127
+ let result = obj;
2128
+ for (const key of keys) {
2129
+ if (result === null || result === void 0) {
2130
+ return defaultValue;
2131
+ }
2132
+ result = result[key];
2133
+ }
2134
+ return result === void 0 ? defaultValue : result;
2135
+ }
2136
+ function set(obj, path, value) {
2137
+ const keys = Array.isArray(path) ? path : path.split(".");
2138
+ let current = obj;
2139
+ for (let i = 0; i < keys.length - 1; i++) {
2140
+ const key = keys[i];
2141
+ if (!(key in current) || typeof current[key] !== "object") {
2142
+ current[key] = {};
2143
+ }
2144
+ current = current[key];
2145
+ }
2146
+ current[keys[keys.length - 1]] = value;
2147
+ return obj;
2148
+ }
2149
+
2150
+ // src/core/errors.ts
2151
+ var BaraqexError = class extends Error {
2152
+ constructor(message, options) {
2153
+ super(message);
2154
+ __publicField(this, "code");
2155
+ __publicField(this, "hint");
2156
+ __publicField(this, "docs");
2157
+ __publicField(this, "originalCause");
2158
+ this.name = "BaraqexError";
2159
+ this.code = options.code;
2160
+ this.hint = options.hint;
2161
+ this.docs = options.docs;
2162
+ this.originalCause = options.cause;
2163
+ Error.captureStackTrace?.(this, this.constructor);
2164
+ }
2165
+ /**
2166
+ * Format error for console output with helpful hints
2167
+ */
2168
+ format() {
2169
+ let output = `
2170
+ \u274C ${this.name}: ${this.message}
2171
+ `;
2172
+ output += ` Code: ${this.code}
2173
+ `;
2174
+ if (this.hint) {
2175
+ output += ` \u{1F4A1} Hint: ${this.hint}
2176
+ `;
2177
+ }
2178
+ if (this.docs) {
2179
+ output += ` \u{1F4DA} Docs: ${this.docs}
2180
+ `;
2181
+ }
2182
+ return output;
2183
+ }
2184
+ };
2185
+ var ConfigError = class extends BaraqexError {
2186
+ constructor(message, options) {
2187
+ super(message, {
2188
+ code: "CONFIG_ERROR",
2189
+ hint: options?.hint || "Check your baraqex.config.js or server configuration",
2190
+ docs: "https://baraqex.tech/docs/configuration",
2191
+ cause: options?.cause
2192
+ });
2193
+ this.name = "ConfigError";
2194
+ }
2195
+ };
2196
+ var DatabaseError = class extends BaraqexError {
2197
+ constructor(message, options) {
2198
+ super(message, {
2199
+ code: "DATABASE_ERROR",
2200
+ hint: options?.hint || "Verify your database connection string and credentials",
2201
+ docs: "https://baraqex.tech/docs/database",
2202
+ cause: options?.cause
2203
+ });
2204
+ __publicField(this, "dbType");
2205
+ this.name = "DatabaseError";
2206
+ this.dbType = options?.dbType;
2207
+ }
2208
+ };
2209
+ var AuthError = class extends BaraqexError {
2210
+ constructor(message, options) {
2211
+ super(message, {
2212
+ code: "AUTH_ERROR",
2213
+ hint: options?.hint || "Check your JWT secret and token configuration",
2214
+ docs: "https://baraqex.tech/docs/authentication",
2215
+ cause: options?.cause
2216
+ });
2217
+ this.name = "AuthError";
2218
+ }
2219
+ };
2220
+ var WasmError = class extends BaraqexError {
2221
+ constructor(message, options) {
2222
+ super(message, {
2223
+ code: "WASM_ERROR",
2224
+ hint: options?.hint || "Ensure your .wasm file is accessible and properly compiled",
2225
+ docs: "https://baraqex.tech/docs/webassembly",
2226
+ cause: options?.cause
2227
+ });
2228
+ this.name = "WasmError";
2229
+ }
2230
+ };
2231
+ var RouterError = class extends BaraqexError {
2232
+ constructor(message, options) {
2233
+ super(message, {
2234
+ code: "ROUTER_ERROR",
2235
+ hint: options?.hint || "Check your API route file structure and exports",
2236
+ docs: "https://baraqex.tech/docs/routing",
2237
+ cause: options?.cause
2238
+ });
2239
+ this.name = "RouterError";
2240
+ }
2241
+ };
2242
+ var ValidationError = class extends BaraqexError {
2243
+ constructor(message, options) {
2244
+ super(message, {
2245
+ code: "VALIDATION_ERROR",
2246
+ hint: options?.hint,
2247
+ cause: options?.cause
2248
+ });
2249
+ __publicField(this, "field");
2250
+ __publicField(this, "value");
2251
+ this.name = "ValidationError";
2252
+ this.field = options?.field;
2253
+ this.value = options?.value;
2254
+ }
2255
+ };
2256
+ function formatError(error) {
2257
+ if (error instanceof BaraqexError) {
2258
+ return error.format();
2259
+ }
2260
+ if (error instanceof Error) {
2261
+ return `
2262
+ \u274C Error: ${error.message}
2263
+ `;
2264
+ }
2265
+ return `
2266
+ \u274C Unknown error: ${String(error)}
2267
+ `;
2268
+ }
2269
+ function withErrorHandling(fn, errorHandler2) {
2270
+ return async (...args) => {
2271
+ try {
2272
+ return await fn(...args);
2273
+ } catch (error) {
2274
+ if (errorHandler2) {
2275
+ errorHandler2(error);
2276
+ } else {
2277
+ console.error(formatError(error));
2278
+ }
2279
+ throw error;
2280
+ }
2281
+ };
2282
+ }
2283
+
294
2284
  // src/wasm.ts
295
2285
  async function loadGoWasm(wasmUrl, options = {}) {
296
2286
  if (typeof window === "undefined") {
@@ -402,7 +2392,7 @@ var generateToken = (length = 32) => {
402
2392
  var generateDocument = (content, options = {}) => `<!DOCTYPE html><html><head><title>${options.title || "App"}</title></head><body>${content}</body></html>`;
403
2393
  var generateErrorPage = (code, message) => `<div>Error ${code}: ${message}</div>`;
404
2394
  var generateLoadingPage = (message = "Loading...") => `<div>${message}</div>`;
405
- var renderToString = (component) => {
2395
+ var renderToString2 = (component) => {
406
2396
  try {
407
2397
  if (typeof component === "function") {
408
2398
  const result = component();
@@ -445,58 +2435,182 @@ var writeJsonFile = null;
445
2435
  var readJsonFile = null;
446
2436
  var baraqexRenderToString = null;
447
2437
  var renderComponent = null;
448
- console.log("Baraqex - Browser build loaded");
449
2438
  export {
450
2439
  ApiRouter,
2440
+ AuthError,
451
2441
  AuthService,
2442
+ BaraqexError,
452
2443
  BaraqexServer,
2444
+ Component,
2445
+ ConfigError,
453
2446
  Database,
2447
+ DatabaseError,
454
2448
  Fragment,
2449
+ LifecycleEvents,
2450
+ Link,
2451
+ NavLink,
2452
+ PureComponent,
2453
+ Redirect,
2454
+ Route,
2455
+ Router,
2456
+ RouterContext,
2457
+ RouterError,
2458
+ RouterProvider,
2459
+ StoreContext,
2460
+ StoreProvider,
2461
+ Switch,
2462
+ ValidationError,
2463
+ WasmError,
2464
+ applyPatches,
455
2465
  baraqexRenderToString,
456
2466
  batchUpdates,
2467
+ calculatePatches,
457
2468
  callWasmFunction,
2469
+ camelCase,
2470
+ capitalize,
2471
+ clamp,
2472
+ cleanupHooks,
2473
+ cleanupRoot,
2474
+ combineReducers,
2475
+ createAction,
2476
+ createClassComponent,
458
2477
  createContext,
459
2478
  createDevServer,
2479
+ createElement,
2480
+ createElementSync,
2481
+ createEventBus,
460
2482
  createProductionServer,
2483
+ createRoot,
2484
+ createRootState,
461
2485
  createServer,
2486
+ createSlice,
2487
+ createStore,
2488
+ debounce,
2489
+ deepClone,
2490
+ deepEqual,
2491
+ deepMerge,
2492
+ deferred,
2493
+ devTools,
2494
+ diff,
2495
+ emitAppDestroyed,
2496
+ emitAppError,
2497
+ emitAppInit,
2498
+ emitAppMounted,
2499
+ emitAppUpdated,
2500
+ emitComponentCreated,
2501
+ emitComponentError,
2502
+ emitComponentMounted,
2503
+ emitComponentUnmounted,
2504
+ emitComponentUpdated,
2505
+ emitRouterAfterChange,
2506
+ emitRouterBeforeChange,
2507
+ emitRouterError,
2508
+ emitStoreAfterAction,
2509
+ emitStoreBeforeAction,
2510
+ emitStoreError,
2511
+ emitStoreInitialized,
462
2512
  ensureDirectory,
463
2513
  errorHandler,
2514
+ escapeHtml2 as escapeHtml,
2515
+ eventBus,
2516
+ finishRender,
2517
+ formatDate,
464
2518
  generateDocument,
465
2519
  generateErrorPage,
466
2520
  generateLoadingPage,
467
2521
  generateToken,
2522
+ get,
2523
+ getContextValue,
2524
+ getCurrentRoot,
468
2525
  getEnvironmentInfo,
2526
+ getIsBatching,
469
2527
  getPagination,
470
2528
  getWasmFunctions,
2529
+ groupBy,
2530
+ hasRoot,
471
2531
  hashString,
472
2532
  hydrate,
473
2533
  initNodeWasm,
474
2534
  isDirectoryEmpty,
2535
+ isEmpty,
475
2536
  isWasmReady,
476
2537
  jsx,
477
- jsx as jsxs,
2538
+ jsxDEV,
2539
+ jsxs,
2540
+ kebabCase,
478
2541
  loadGoWasm,
479
2542
  loadGoWasmFromFile,
2543
+ logger,
2544
+ memoize,
480
2545
  notFoundHandler,
2546
+ omit,
2547
+ onAppDestroyed,
2548
+ onAppError,
2549
+ onAppInit,
2550
+ onAppMounted,
2551
+ onAppUpdated,
2552
+ onComponentCreated,
2553
+ onComponentError,
2554
+ onComponentMounted,
2555
+ onComponentUnmounted,
2556
+ onComponentUpdated,
2557
+ onRouterAfterChange,
2558
+ onRouterBeforeChange,
2559
+ onRouterError,
2560
+ onStoreAfterAction,
2561
+ onStoreBeforeAction,
2562
+ onStoreError,
2563
+ onStoreInitialized,
2564
+ patterns,
2565
+ pick,
2566
+ prepareRender,
481
2567
  rateLimit,
482
2568
  readJsonFile,
483
2569
  render,
484
2570
  renderComponent,
485
- renderToString,
2571
+ renderToStream,
2572
+ renderToString2 as renderToString,
2573
+ renderToStringWithData,
486
2574
  requestLogger,
2575
+ retry,
487
2576
  safeJsonParse,
488
2577
  sendError,
489
2578
  sendSuccess,
490
- server,
2579
+ set,
2580
+ setCurrentRoot,
2581
+ shallowEqual,
2582
+ shouldComponentUpdate,
2583
+ sleep,
2584
+ throttle,
2585
+ thunk,
2586
+ unescapeHtml,
2587
+ useCallback,
491
2588
  useContext,
2589
+ useDispatch,
492
2590
  useEffect,
493
2591
  useErrorBoundary,
2592
+ useEvent,
2593
+ useField,
2594
+ useForm,
494
2595
  useGoWasm,
2596
+ useId,
2597
+ useLayoutEffect,
2598
+ useLocation,
2599
+ useMatch,
495
2600
  useMemo,
2601
+ useNavigate,
2602
+ useParams,
2603
+ useReducer,
496
2604
  useRef,
2605
+ useRouter,
2606
+ useSearchParams,
2607
+ useSelector,
497
2608
  useState,
2609
+ useStore,
2610
+ uuid,
498
2611
  validateFields,
499
2612
  validateFileUpload,
2613
+ withErrorHandling,
500
2614
  writeJsonFile
501
2615
  };
502
2616
  //# sourceMappingURL=browser.js.map