frontend-hamroun 1.2.16 → 1.2.17

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 (158) hide show
  1. package/README.md +4 -0
  2. package/bin/cli.js +673 -0
  3. package/dist/component.d.ts +1 -1
  4. package/dist/context.d.ts +4 -3
  5. package/dist/index.client.d.ts +11 -0
  6. package/dist/index.d.ts +9 -89
  7. package/dist/index.js +396 -67
  8. package/dist/index.js.map +1 -0
  9. package/dist/index.mjs +392 -0
  10. package/dist/index.mjs.map +1 -0
  11. package/dist/jsx-runtime/jsx-runtime.d.ts +0 -1
  12. package/dist/jsx-runtime.d.ts +1 -1
  13. package/dist/renderer.d.ts +0 -10
  14. package/dist/server-renderer.d.ts +0 -3
  15. package/dist/server-types.d.ts +42 -0
  16. package/package.json +69 -41
  17. package/templates/basic-app/index.html +6 -6
  18. package/templates/basic-app/package.json +18 -7
  19. package/templates/basic-app/postcss.config.js +0 -1
  20. package/templates/basic-app/src/main.tsx +1 -10
  21. package/templates/basic-app/tailwind.config.js +2 -23
  22. package/templates/basic-app/tsconfig.json +4 -17
  23. package/templates/basic-app/vite.config.ts +3 -54
  24. package/templates/fullstack-app/api/hello.ts +18 -0
  25. package/templates/fullstack-app/api/users/[id].ts +73 -0
  26. package/templates/fullstack-app/api/users/index.ts +32 -0
  27. package/templates/fullstack-app/package.json +31 -0
  28. package/templates/fullstack-app/server.ts +46 -0
  29. package/templates/fullstack-app/src/pages/index.tsx +59 -0
  30. package/templates/ssr-template/vite.config.ts +1 -11
  31. package/bin/cli.cjs +0 -16
  32. package/bin/cli.mjs +0 -237
  33. package/dist/backend/api-utils.d.ts +0 -38
  34. package/dist/backend/api-utils.js +0 -135
  35. package/dist/backend/auth.d.ts +0 -134
  36. package/dist/backend/auth.js +0 -387
  37. package/dist/backend/database.d.ts +0 -27
  38. package/dist/backend/database.js +0 -91
  39. package/dist/backend/model.d.ts +0 -43
  40. package/dist/backend/model.js +0 -178
  41. package/dist/backend/router.d.ts +0 -27
  42. package/dist/backend/router.js +0 -137
  43. package/dist/backend/server.d.ts +0 -19
  44. package/dist/backend/server.js +0 -268
  45. package/dist/backend/types.d.ts +0 -217
  46. package/dist/backend/types.js +0 -1
  47. package/dist/batch.js +0 -22
  48. package/dist/cli/index.d.ts +0 -2
  49. package/dist/cli/index.js +0 -215
  50. package/dist/component.js +0 -84
  51. package/dist/components/Counter.js +0 -2
  52. package/dist/context.js +0 -18
  53. package/dist/frontend-hamroun.es.js +0 -1378
  54. package/dist/frontend-hamroun.umd.js +0 -66
  55. package/dist/hooks.js +0 -164
  56. package/dist/jsx-runtime/index.d.ts +0 -11
  57. package/dist/jsx-runtime/index.js +0 -19
  58. package/dist/jsx-runtime/jsx-dev-runtime.js +0 -1
  59. package/dist/jsx-runtime/jsx-runtime.js +0 -95
  60. package/dist/jsx-runtime.js +0 -192
  61. package/dist/renderer.js +0 -51
  62. package/dist/server-renderer.js +0 -102
  63. package/dist/types.js +0 -1
  64. package/dist/vdom.js +0 -27
  65. package/scripts/build-cli.js +0 -1199
  66. package/scripts/generate.js +0 -134
  67. package/src/backend/api-utils.ts +0 -178
  68. package/src/backend/auth.ts +0 -544
  69. package/src/backend/database.ts +0 -104
  70. package/src/backend/model.ts +0 -198
  71. package/src/backend/router.ts +0 -176
  72. package/src/backend/server.ts +0 -330
  73. package/src/backend/types.ts +0 -257
  74. package/src/batch.ts +0 -24
  75. package/src/cli/index.js +0 -554
  76. package/src/cli/index.ts +0 -257
  77. package/src/component.ts +0 -98
  78. package/src/components/Counter.tsx +0 -4
  79. package/src/context.ts +0 -29
  80. package/src/hooks.ts +0 -211
  81. package/src/index.ts +0 -144
  82. package/src/jsx-runtime/index.ts +0 -27
  83. package/src/jsx-runtime/jsx-dev-runtime.ts +0 -0
  84. package/src/jsx-runtime/jsx-runtime.ts +0 -104
  85. package/src/jsx-runtime.ts +0 -226
  86. package/src/renderer.ts +0 -55
  87. package/src/server-renderer.ts +0 -114
  88. package/src/shims.d.ts +0 -20
  89. package/src/types/bcrypt.d.ts +0 -30
  90. package/src/types/jsonwebtoken.d.ts +0 -55
  91. package/src/types.d.ts +0 -26
  92. package/src/types.ts +0 -21
  93. package/src/vdom.ts +0 -34
  94. package/templates/basic/.eslintignore +0 -5
  95. package/templates/basic/.eslintrc.json +0 -25
  96. package/templates/basic/docs/rapport_pfe.aux +0 -27
  97. package/templates/basic/docs/rapport_pfe.log +0 -399
  98. package/templates/basic/docs/rapport_pfe.out +0 -10
  99. package/templates/basic/docs/rapport_pfe.pdf +0 -0
  100. package/templates/basic/docs/rapport_pfe.tex +0 -68
  101. package/templates/basic/docs/rapport_pfe.toc +0 -14
  102. package/templates/basic/index.html +0 -12
  103. package/templates/basic/jsconfig.json +0 -14
  104. package/templates/basic/package.json +0 -18
  105. package/templates/basic/postcss.config.js +0 -7
  106. package/templates/basic/src/App.js +0 -105
  107. package/templates/basic/src/App.tsx +0 -65
  108. package/templates/basic/src/api.ts +0 -58
  109. package/templates/basic/src/components/Counter.tsx +0 -26
  110. package/templates/basic/src/components/Header.tsx +0 -9
  111. package/templates/basic/src/components/TodoList.tsx +0 -90
  112. package/templates/basic/src/main.css +0 -3
  113. package/templates/basic/src/main.js +0 -11
  114. package/templates/basic/src/main.ts +0 -20
  115. package/templates/basic/src/main.tsx +0 -144
  116. package/templates/basic/src/server.ts +0 -99
  117. package/templates/basic/tailwind.config.js +0 -32
  118. package/templates/basic/tsconfig.json +0 -20
  119. package/templates/basic/tsconfig.node.json +0 -10
  120. package/templates/basic/vite.config.js +0 -18
  121. package/templates/basic/vite.config.ts +0 -86
  122. package/templates/basic-app/src/App.js +0 -105
  123. package/templates/basic-app/src/App.tsx +0 -143
  124. package/templates/basic-app/src/api.ts +0 -58
  125. package/templates/basic-app/src/components/Counter.tsx +0 -26
  126. package/templates/basic-app/src/components/Header.tsx +0 -9
  127. package/templates/basic-app/src/components/TodoList.tsx +0 -90
  128. package/templates/basic-app/src/main.js +0 -10
  129. package/templates/basic-app/src/main.ts +0 -21
  130. package/templates/basic-app/src/react/index.ts +0 -35
  131. package/templates/basic-app/src/react/jsx-dev-runtime.ts +0 -13
  132. package/templates/basic-app/src/react/jsx-runtime.ts +0 -12
  133. package/templates/basic-app/src/server.ts +0 -99
  134. package/templates/basic-app/src/shims.ts +0 -9
  135. package/templates/basic-app/tsconfig.node.json +0 -10
  136. package/templates/basic-app/vite.config.js +0 -22
  137. package/templates/full-stack/.env.example +0 -11
  138. package/templates/full-stack/README.md +0 -51
  139. package/templates/full-stack/index.html +0 -12
  140. package/templates/full-stack/jsconfig.json +0 -14
  141. package/templates/full-stack/package.json +0 -21
  142. package/templates/full-stack/src/App.js +0 -105
  143. package/templates/full-stack/src/client/App.tsx +0 -50
  144. package/templates/full-stack/src/client/components/Header.tsx +0 -42
  145. package/templates/full-stack/src/client/components/UserList.tsx +0 -29
  146. package/templates/full-stack/src/client/main.tsx +0 -5
  147. package/templates/full-stack/src/main.css +0 -3
  148. package/templates/full-stack/src/main.js +0 -11
  149. package/templates/full-stack/src/main.ts +0 -20
  150. package/templates/full-stack/src/server/index.ts +0 -99
  151. package/templates/full-stack/src/server/routes/auth.ts +0 -39
  152. package/templates/full-stack/src/server/routes/users.ts +0 -48
  153. package/templates/full-stack/src/shims.ts +0 -9
  154. package/templates/full-stack/tsconfig.json +0 -20
  155. package/templates/full-stack/tsconfig.node.json +0 -10
  156. package/templates/full-stack/tsconfig.server.json +0 -15
  157. package/templates/full-stack/vite.config.js +0 -18
  158. package/templates/full-stack/vite.config.ts +0 -85
@@ -1,1378 +0,0 @@
1
- import O, { Router as me } from "express";
2
- import de from "path";
3
- import Ne from "compression";
4
- import Oe from "helmet";
5
- import De from "morgan";
6
- import j from "mongoose";
7
- import Pe from "fs";
8
- import "bcrypt";
9
- const fe = globalThis || void 0 || self;
10
- function Me(r) {
11
- return r && r.__esModule && Object.prototype.hasOwnProperty.call(r, "default") ? r.default : r;
12
- }
13
- var ye = { exports: {} }, m = ye.exports = {}, k, v;
14
- function re() {
15
- throw new Error("setTimeout has not been defined");
16
- }
17
- function se() {
18
- throw new Error("clearTimeout has not been defined");
19
- }
20
- (function() {
21
- try {
22
- typeof setTimeout == "function" ? k = setTimeout : k = re;
23
- } catch {
24
- k = re;
25
- }
26
- try {
27
- typeof clearTimeout == "function" ? v = clearTimeout : v = se;
28
- } catch {
29
- v = se;
30
- }
31
- })();
32
- function ge(r) {
33
- if (k === setTimeout)
34
- return setTimeout(r, 0);
35
- if ((k === re || !k) && setTimeout)
36
- return k = setTimeout, setTimeout(r, 0);
37
- try {
38
- return k(r, 0);
39
- } catch {
40
- try {
41
- return k.call(null, r, 0);
42
- } catch {
43
- return k.call(this, r, 0);
44
- }
45
- }
46
- }
47
- function Fe(r) {
48
- if (v === clearTimeout)
49
- return clearTimeout(r);
50
- if ((v === se || !v) && clearTimeout)
51
- return v = clearTimeout, clearTimeout(r);
52
- try {
53
- return v(r);
54
- } catch {
55
- try {
56
- return v.call(null, r);
57
- } catch {
58
- return v.call(this, r);
59
- }
60
- }
61
- }
62
- var x = [], P = !1, _, B = -1;
63
- function Le() {
64
- !P || !_ || (P = !1, _.length ? x = _.concat(x) : B = -1, x.length && we());
65
- }
66
- function we() {
67
- if (!P) {
68
- var r = ge(Le);
69
- P = !0;
70
- for (var t = x.length; t; ) {
71
- for (_ = x, x = []; ++B < t; )
72
- _ && _[B].run();
73
- B = -1, t = x.length;
74
- }
75
- _ = null, P = !1, Fe(r);
76
- }
77
- }
78
- m.nextTick = function(r) {
79
- var t = new Array(arguments.length - 1);
80
- if (arguments.length > 1)
81
- for (var e = 1; e < arguments.length; e++)
82
- t[e - 1] = arguments[e];
83
- x.push(new Ee(r, t)), x.length === 1 && !P && ge(we);
84
- };
85
- function Ee(r, t) {
86
- this.fun = r, this.array = t;
87
- }
88
- Ee.prototype.run = function() {
89
- this.fun.apply(null, this.array);
90
- };
91
- m.title = "browser";
92
- m.browser = !0;
93
- m.env = {};
94
- m.argv = [];
95
- m.version = "";
96
- m.versions = {};
97
- function A() {
98
- }
99
- m.on = A;
100
- m.addListener = A;
101
- m.once = A;
102
- m.off = A;
103
- m.removeListener = A;
104
- m.removeAllListeners = A;
105
- m.emit = A;
106
- m.prependListener = A;
107
- m.prependOnceListener = A;
108
- m.listeners = function(r) {
109
- return [];
110
- };
111
- m.binding = function(r) {
112
- throw new Error("process.binding is not supported");
113
- };
114
- m.cwd = function() {
115
- return "/";
116
- };
117
- m.chdir = function(r) {
118
- throw new Error("process.chdir is not supported");
119
- };
120
- m.umask = function() {
121
- return 0;
122
- };
123
- var Ve = ye.exports;
124
- const w = /* @__PURE__ */ Me(Ve), $ = typeof window < "u" ? window : typeof fe < "u" ? fe : {};
125
- function J(r, t, e) {
126
- return {
127
- type: r,
128
- props: t || {},
129
- key: e
130
- };
131
- }
132
- function be(r, t, e) {
133
- return J(r, t, e);
134
- }
135
- function ne(r) {
136
- if (typeof r == "string" || typeof r == "number")
137
- return document.createTextNode(String(r));
138
- if (typeof r.type == "function") {
139
- const e = r.type(r.props);
140
- return ne(e);
141
- }
142
- const t = document.createElement(r.type);
143
- return Object.entries(r.props || {}).forEach(([e, s]) => {
144
- if (e === "children")
145
- (Array.isArray(s) ? s : [s]).forEach((i) => {
146
- if (i != null) {
147
- const o = ne(i);
148
- w.env.NODE_ENV === "test" && typeof window < "u" && ($.__renderStats || ($.__renderStats = {
149
- elementsCreated: 0,
150
- textNodesCreated: 0,
151
- eventsAttached: 0,
152
- renderTime: 0
153
- }, typeof afterAll == "function" && afterAll(() => {
154
- try {
155
- const c = require("fs"), d = require("path").resolve(w.cwd(), "jsx-runtime-stats.json");
156
- c.writeFileSync(d, JSON.stringify($.__renderStats, null, 2)), console.log(`JSX runtime stats written to ${d}`);
157
- } catch (c) {
158
- console.error("Failed to write stats file:", c);
159
- }
160
- })), o instanceof Text ? $.__renderStats.textNodesCreated++ : $.__renderStats.elementsCreated++), t.appendChild(o);
161
- }
162
- });
163
- else if (e.startsWith("on")) {
164
- const n = e.toLowerCase().substring(2);
165
- t.addEventListener(n, s), w.env.NODE_ENV === "test" && typeof window < "u" && $.__renderStats && $.__renderStats.eventsAttached++;
166
- } else e === "className" ? t.setAttribute("class", s) : e === "style" && typeof s == "object" ? Object.entries(s).forEach(([n, i]) => {
167
- t.style[n] = String(i);
168
- }) : t.setAttribute(e, s);
169
- }), t;
170
- }
171
- const Te = Symbol("Fragment"), ke = J;
172
- typeof window < "u" && (window.jsx = J, window.jsxs = be, window.jsxDEV = ke, window.Fragment = Te);
173
- const Be = typeof window < "u" && typeof document < "u";
174
- async function C(r) {
175
- var t;
176
- if (console.log("Creating element from:", r), !Be) {
177
- if (r == null)
178
- return { nodeType: 3, textContent: "" };
179
- if (typeof r == "boolean")
180
- return { nodeType: 3, textContent: "" };
181
- if (typeof r == "number" || typeof r == "string")
182
- return { nodeType: 3, textContent: String(r) };
183
- if (Array.isArray(r)) {
184
- const e = { nodeType: 11, childNodes: [] };
185
- for (const s of r) {
186
- const n = await C(s);
187
- e.childNodes.push(n);
188
- }
189
- return e;
190
- }
191
- if ("type" in r && r.props !== void 0) {
192
- const { type: e, props: s } = r;
193
- if (typeof e == "function")
194
- try {
195
- const o = await e(s || {});
196
- return await C(o);
197
- } catch (o) {
198
- return console.error("Error rendering component:", o), { nodeType: 3, textContent: "" };
199
- }
200
- const n = {
201
- nodeType: 1,
202
- tagName: e,
203
- attributes: {},
204
- style: {},
205
- childNodes: [],
206
- setAttribute: function(o, c) {
207
- this.attributes[o] = c;
208
- },
209
- appendChild: function(o) {
210
- this.childNodes.push(o);
211
- }
212
- };
213
- for (const [o, c] of Object.entries(s || {}))
214
- if (o !== "children")
215
- if (o.startsWith("on") && typeof c == "function") {
216
- const a = o.toLowerCase().slice(2);
217
- n.__events || (n.__events = {}), n.__events[a] = c;
218
- } else o === "style" && typeof c == "object" ? Object.assign(n.style, c) : o === "className" ? n.setAttribute("class", String(c)) : o !== "key" && o !== "ref" && n.setAttribute(o, String(c));
219
- const i = s == null ? void 0 : s.children;
220
- if (i != null) {
221
- const o = Array.isArray(i) ? i.flat() : [i];
222
- for (const c of o) {
223
- const a = await C(c);
224
- n.appendChild(a);
225
- }
226
- }
227
- return n;
228
- }
229
- return { nodeType: 3, textContent: String(r) };
230
- }
231
- if (r == null || typeof r == "boolean")
232
- return document.createTextNode("");
233
- if (typeof r == "number" || typeof r == "string")
234
- return document.createTextNode(String(r));
235
- if (Array.isArray(r)) {
236
- const e = document.createDocumentFragment();
237
- for (const s of r) {
238
- const n = await C(s);
239
- e.appendChild(n);
240
- }
241
- return e;
242
- }
243
- if ("type" in r && r.props !== void 0) {
244
- const { type: e, props: s } = r;
245
- if (typeof e == "function")
246
- try {
247
- const o = await e(s || {}), c = await C(o);
248
- return c instanceof Element && c.setAttribute("data-component-id", e.name || e.toString()), c;
249
- } catch (o) {
250
- return console.error("Error rendering component:", o), document.createTextNode("");
251
- }
252
- const n = document.createElement(e);
253
- for (const [o, c] of Object.entries(s || {}))
254
- if (o !== "children")
255
- if (o.startsWith("on") && typeof c == "function") {
256
- const a = o.toLowerCase().slice(2), d = (t = n.__events) == null ? void 0 : t[a];
257
- d && n.removeEventListener(a, d), n.addEventListener(a, c), n.__events || (n.__events = {}), n.__events[a] = c;
258
- } else o === "style" && typeof c == "object" ? Object.assign(n.style, c) : o === "className" ? n.setAttribute("class", String(c)) : o !== "key" && o !== "ref" && n.setAttribute(o, String(c));
259
- const i = s == null ? void 0 : s.children;
260
- if (i != null) {
261
- const o = Array.isArray(i) ? i.flat() : [i];
262
- for (const c of o) {
263
- const a = await C(c);
264
- n.appendChild(a);
265
- }
266
- }
267
- return n;
268
- }
269
- return document.createTextNode(String(r));
270
- }
271
- class He {
272
- constructor(t = {}) {
273
- this.state = {}, this.element = null, this._mounted = !1, this.props = t;
274
- }
275
- componentDidMount() {
276
- }
277
- async setState(t) {
278
- const e = { ...this.state };
279
- this.state = { ...e, ...t }, console.log(`${this.constructor.name} state updated:`, {
280
- prev: e,
281
- next: this.state
282
- }), await Promise.resolve(), this._mounted ? await this.update() : await this.update();
283
- }
284
- _replayEvents(t, e) {
285
- const s = t.__events || {};
286
- Object.entries(s).forEach(([n, i]) => {
287
- e.addEventListener(n, i);
288
- }), e.__events = s;
289
- }
290
- _deepCloneWithEvents(t) {
291
- const e = t.cloneNode(!1), s = t.__events || {};
292
- return e.__events = s, Object.entries(s).forEach(([n, i]) => {
293
- e.addEventListener(n, i);
294
- }), Array.from(t.childNodes).forEach((n) => {
295
- n instanceof HTMLElement ? e.appendChild(this._deepCloneWithEvents(n)) : e.appendChild(n.cloneNode(!0));
296
- }), e;
297
- }
298
- async update() {
299
- const t = this.render();
300
- if (!t) return document.createTextNode("");
301
- const e = await C(t);
302
- if (e instanceof HTMLElement)
303
- return this._updateElement(e);
304
- const s = document.createElement("div");
305
- return s.appendChild(e), this._updateElement(s);
306
- }
307
- async _updateElement(t) {
308
- const e = this._deepCloneWithEvents(t);
309
- return e.__instance = this, this.element ? this.element.parentNode && (this.element.parentNode.replaceChild(e, this.element), this.element = e) : (this.element = e, this._mounted || (this._mounted = !0, queueMicrotask(() => this.componentDidMount()))), this.element;
310
- }
311
- render() {
312
- throw new Error("Component must implement render() method");
313
- }
314
- }
315
- let H = !1;
316
- const X = [];
317
- function ae(r) {
318
- if (H) {
319
- X.push(r);
320
- return;
321
- }
322
- H = !0;
323
- try {
324
- for (r(); X.length > 0; ) {
325
- const t = X.shift();
326
- t == null || t();
327
- }
328
- } finally {
329
- H = !1;
330
- }
331
- }
332
- let u = 0;
333
- const Z = /* @__PURE__ */ new Map(), b = /* @__PURE__ */ new Map(), L = /* @__PURE__ */ new Map(), K = /* @__PURE__ */ new Map(), ee = /* @__PURE__ */ new Map();
334
- let oe = null, ie = null, ce = null;
335
- const ve = typeof window > "u", W = /* @__PURE__ */ new Map();
336
- function Se(r, t, e) {
337
- oe = r, ie = e, ce = t;
338
- }
339
- function U() {
340
- return u++, b.set(u, 0), u;
341
- }
342
- function q() {
343
- ve && W.delete(u), u = 0;
344
- }
345
- function xe(r) {
346
- if (!u)
347
- throw new Error("useState must be called within a render");
348
- if (ve) {
349
- W.has(u) || W.set(u, /* @__PURE__ */ new Map());
350
- const i = W.get(u), o = b.get(u) || 0;
351
- i.has(o) || i.set(o, r);
352
- const c = i.get(o), a = (d) => {
353
- };
354
- return b.set(u, o + 1), [c, a];
355
- }
356
- Z.has(u) || Z.set(u, []);
357
- const t = Z.get(u), e = b.get(u);
358
- e >= t.length && t.push(r);
359
- const s = t[e], n = (i) => {
360
- const o = typeof i == "function" ? i(t[e]) : i;
361
- t[e] !== o && (t[e] = o, H ? ae(() => he(u)) : he(u));
362
- };
363
- return b.set(u, e + 1), [s, n];
364
- }
365
- function We(r, t) {
366
- if (!u) throw new Error("useEffect must be called within a render");
367
- const e = b.get(u);
368
- L.has(u) || L.set(u, []);
369
- const s = L.get(u), n = s[e];
370
- (!n || !t || !n.deps || t.some((i, o) => i !== n.deps[o])) && (n != null && n.cleanup && n.cleanup(), queueMicrotask(() => {
371
- const i = r() || void 0;
372
- s[e] = { cleanup: i, deps: t };
373
- })), b.set(u, e + 1);
374
- }
375
- function Ue(r, t) {
376
- if (!u) throw new Error("useMemo must be called within a render");
377
- const e = b.get(u);
378
- K.has(u) || K.set(u, []);
379
- const s = K.get(u), n = s[e];
380
- if (!n || t && t.some((i, o) => !Object.is(i, n.deps[o]))) {
381
- const i = r();
382
- return s[e] = { value: i, deps: t }, b.set(u, e + 1), i;
383
- }
384
- return b.set(u, e + 1), n.value;
385
- }
386
- function qe(r) {
387
- if (!u) throw new Error("useRef must be called within a render");
388
- const t = b.get(u);
389
- ee.has(u) || ee.set(u, []);
390
- const e = ee.get(u);
391
- if (t >= e.length) {
392
- const n = { current: r };
393
- return e.push(n), b.set(u, t + 1), n;
394
- }
395
- const s = e[t];
396
- return b.set(u, t + 1), s;
397
- }
398
- async function he(r) {
399
- try {
400
- const t = L.get(r);
401
- t && (t.forEach((e) => {
402
- e.cleanup && e.cleanup();
403
- }), L.set(r, [])), oe && ie && ce && await oe(ce, ie);
404
- } catch (t) {
405
- console.error("Error during rerender:", t);
406
- }
407
- }
408
- function Ge() {
409
- const [r, t] = xe(null);
410
- return [r, () => t(null)];
411
- }
412
- let G = !1;
413
- async function Je(r, t) {
414
- G = !0;
415
- try {
416
- await ue(r, t);
417
- } finally {
418
- G = !1;
419
- }
420
- }
421
- async function ue(r, t) {
422
- console.log("Rendering to:", t.id || "unnamed-container"), ae(async () => {
423
- const e = U();
424
- try {
425
- Se(ue, r, t);
426
- const s = await C(r);
427
- G || (t.innerHTML = ""), G && t.firstChild ? console.log("Hydrating existing DOM") : t.appendChild(s);
428
- } finally {
429
- q();
430
- }
431
- });
432
- }
433
- async function D(r) {
434
- U(), Se(() => {
435
- }, r, null);
436
- try {
437
- if (r == null || typeof r == "boolean") return "";
438
- if (typeof r == "number" || typeof r == "string")
439
- return V(String(r));
440
- if (Array.isArray(r))
441
- return (await Promise.all(r.map(D))).join("");
442
- if ("type" in r && r.props !== void 0) {
443
- const { type: t, props: e } = r;
444
- if (typeof t == "function")
445
- try {
446
- U();
447
- const i = await t(e || {}), o = await D(i);
448
- return q(), o;
449
- } catch (i) {
450
- return console.error("Error rendering component:", i), "";
451
- }
452
- if (t === Symbol.for("react.fragment") || t.name === "Fragment") {
453
- if (e.children) {
454
- const i = Array.isArray(e.children) ? e.children : [e.children];
455
- return (await Promise.all(i.map(D))).join("");
456
- }
457
- return "";
458
- }
459
- let s = `<${t}`;
460
- for (const [i, o] of Object.entries(e || {}))
461
- i === "children" || i === "key" || (i === "className" ? s += ` class="${V(String(o))}"` : i === "style" && typeof o == "object" ? s += ` style="${Qe(o || {})}"` : i.startsWith("on") || (s += ` ${i}="${V(String(o))}"`));
462
- if ((/* @__PURE__ */ new Set([
463
- "area",
464
- "base",
465
- "br",
466
- "col",
467
- "embed",
468
- "hr",
469
- "img",
470
- "input",
471
- "link",
472
- "meta",
473
- "param",
474
- "source",
475
- "track",
476
- "wbr"
477
- ])).has(t))
478
- return s + "/>";
479
- if (s += ">", e != null && e.children) {
480
- const i = Array.isArray(e.children) ? e.children : [e.children];
481
- for (const o of i)
482
- s += await D(o);
483
- }
484
- return s + `</${t}>`;
485
- }
486
- return V(String(r));
487
- } finally {
488
- q();
489
- }
490
- }
491
- function V(r) {
492
- return r.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
493
- }
494
- function Qe(r) {
495
- return Object.entries(r).map(([t, e]) => `${Ye(t)}:${e}`).join(";");
496
- }
497
- function Ye(r) {
498
- return r.replace(/[A-Z]/g, (t) => "-" + t.toLowerCase());
499
- }
500
- function ze(r) {
501
- const t = {
502
- _currentValue: r,
503
- Provider: function({ value: s, children: n }) {
504
- return t._currentValue = s, n;
505
- },
506
- Consumer: function({ children: s }) {
507
- return s(t._currentValue);
508
- }
509
- };
510
- return t;
511
- }
512
- function Xe(r) {
513
- return r._currentValue;
514
- }
515
- class Ae {
516
- // Renamed from isConnected to _connected
517
- constructor(t) {
518
- this.connection = null, this._connected = !1, this.options = {
519
- retryAttempts: 3,
520
- retryDelay: 1e3,
521
- connectionTimeout: 1e4,
522
- autoIndex: !0,
523
- ...t
524
- };
525
- }
526
- /**
527
- * Connect to the database
528
- */
529
- async connect() {
530
- try {
531
- if (this._connected && this.connection)
532
- return this.connection;
533
- j.set("strictQuery", !0);
534
- let t = 0;
535
- for (; t < (this.options.retryAttempts || 3); )
536
- try {
537
- await j.connect(this.options.uri, {
538
- dbName: this.options.name,
539
- connectTimeoutMS: this.options.connectionTimeout,
540
- autoIndex: this.options.autoIndex,
541
- ...this.options.options
542
- });
543
- break;
544
- } catch (e) {
545
- if (t++, t >= (this.options.retryAttempts || 3))
546
- throw e;
547
- console.log(`Connection attempt ${t} failed. Retrying in ${this.options.retryDelay}ms...`), await new Promise((s) => setTimeout(s, this.options.retryDelay));
548
- }
549
- return this.connection = j.connection, this._connected = !0, console.log(`Connected to MongoDB at ${this.options.uri}/${this.options.name}`), this.connection.on("error", (e) => {
550
- console.error("MongoDB connection error:", e), this._connected = !1;
551
- }), this.connection.on("disconnected", () => {
552
- console.log("MongoDB disconnected"), this._connected = !1;
553
- }), this.connection;
554
- } catch (t) {
555
- throw console.error("Failed to connect to MongoDB:", t), t;
556
- }
557
- }
558
- /**
559
- * Disconnect from the database
560
- */
561
- async disconnect() {
562
- this.connection && (await j.disconnect(), this._connected = !1, this.connection = null, console.log("Disconnected from MongoDB"));
563
- }
564
- /**
565
- * Check if connected to the database
566
- */
567
- isConnected() {
568
- return this._connected;
569
- }
570
- /**
571
- * Get the mongoose connection
572
- */
573
- getConnection() {
574
- return this.connection;
575
- }
576
- }
577
- function Ze(r = {}) {
578
- const t = O(), {
579
- port: e = 3e3,
580
- staticDir: s = "public",
581
- enableCors: n = !0,
582
- apiPrefix: i = "/api",
583
- ssrEnabled: o = !0,
584
- middlewares: c = [],
585
- enableCompression: a = !0,
586
- enableHelmet: d = !0,
587
- logFormat: h = "dev",
588
- trustProxy: E = !1,
589
- showErrorDetails: S = w.env.NODE_ENV !== "production"
590
- } = r;
591
- if (E && t.set("trust proxy", E), t.use(O.json()), t.use(O.urlencoded({ extended: !0 })), a && t.use(Ne()), d && t.use(Oe({
592
- contentSecurityPolicy: r.disableCSP ? !1 : void 0
593
- })), h && t.use(De(h)), n && t.use((l, p, f) => {
594
- if (p.header("Access-Control-Allow-Origin", "*"), p.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"), p.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"), l.method === "OPTIONS")
595
- return p.sendStatus(200);
596
- f();
597
- }), c.forEach((l) => t.use(l)), s) {
598
- const l = de.resolve(w.cwd(), s);
599
- Pe.existsSync(l) ? (t.use(O.static(l, {
600
- maxAge: r.staticCacheAge || "1d",
601
- etag: !0
602
- })), console.log(`📂 Serving static files from: ${l}`)) : console.warn(`⚠️ Static directory not found: ${l}`);
603
- }
604
- let y = null;
605
- t.connectToDatabase = async (l) => {
606
- try {
607
- return y && y.isConnected() ? (console.log("✅ Using existing database connection"), y) : (y = new Ae(l), await y.connect(), console.log("✅ Database connected successfully"), w.on("SIGTERM", async () => {
608
- y && y.isConnected() && (await y.disconnect(), console.log("Database connection closed"));
609
- }), y);
610
- } catch (p) {
611
- throw console.error("❌ Failed to connect to database:", p), p;
612
- }
613
- };
614
- const I = {}, Q = {};
615
- return t.registerApi = (l, p, f = {}) => {
616
- try {
617
- const { prefix: g = i } = f, T = de.posix.join(g, l).replace(/\\/g, "/");
618
- t.use(T, p), I[T] = { router: p, options: f }, console.log(`🔌 API registered: ${T}`);
619
- } catch (g) {
620
- console.error(`❌ Failed to register API at ${l}:`, g);
621
- }
622
- return t;
623
- }, t.registerSSR = (l, p, f = {}) => o ? (Q[l] = { component: p, options: f }, t.get(l, async (g, T, Y) => {
624
- try {
625
- if (g.query.nossr === "true")
626
- return Y();
627
- const z = {
628
- req: g,
629
- res: T,
630
- params: g.params,
631
- query: g.query,
632
- user: g.user,
633
- ...f.props
634
- }, _e = await D(p(z));
635
- T.send(`
636
- <!DOCTYPE html>
637
- <html lang="${f.lang || "en"}">
638
- <head>
639
- <meta charset="UTF-8">
640
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
641
- <title>${f.title || "Frontend Hamroun App"}</title>
642
- ${f.meta ? f.meta.map((F) => `<meta ${Object.entries(F).map(([Ie, Re]) => `${Ie}="${Re}"`).join(" ")}>`).join(`
643
- `) : ""}
644
- ${f.head || ""}
645
- ${f.styles ? `<style>${f.styles}</style>` : ""}
646
- ${f.styleSheets ? f.styleSheets.map((F) => `<link rel="stylesheet" href="${F}">`).join(`
647
- `) : ""}
648
- </head>
649
- <body ${f.bodyAttributes || ""}>
650
- <div id="${f.rootId || "root"}">${_e}</div>
651
- <script>
652
- window.__INITIAL_DATA__ = ${JSON.stringify(f.initialData || {})};
653
- <\/script>
654
- ${f.scripts ? f.scripts.map((F) => `<script src="${F}"><\/script>`).join(`
655
- `) : ""}
656
- </body>
657
- </html>
658
- `);
659
- } catch (z) {
660
- if (console.error("SSR Error:", z), f.fallback)
661
- return Y();
662
- T.status(500).send("Server rendering error");
663
- }
664
- }), console.log(`🖥️ SSR registered: ${l}`), t) : (console.log(`⚠️ SSR disabled: skipping registration of ${l}`), t), t.use((l, p, f, g) => {
665
- console.error("Server error:", l);
666
- const T = l.statusCode || l.status || 500;
667
- p.path.startsWith(i) ? f.status(T).json({
668
- success: !1,
669
- error: S ? l.message : "Internal Server Error",
670
- stack: S ? l.stack : void 0
671
- }) : f.status(T).send(`
672
- <!DOCTYPE html>
673
- <html>
674
- <head>
675
- <title>Error - ${T}</title>
676
- <style>
677
- body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
678
- .error { background: #f8d7da; border: 1px solid #f5c6cb; padding: 1rem; border-radius: 4px; }
679
- .stack { background: #f8f9fa; padding: 1rem; border-radius: 4px; overflow: auto; }
680
- </style>
681
- </head>
682
- <body>
683
- <h1>Error ${T}</h1>
684
- <div class="error">${S ? l.message : "Internal Server Error"}</div>
685
- ${S && l.stack ? `<pre class="stack">${l.stack}</pre>` : ""}
686
- </body>
687
- </html>
688
- `);
689
- }), t.use((l, p) => {
690
- l.path.startsWith(i) ? p.status(404).json({ success: !1, error: "Not Found" }) : p.status(404).send(`
691
- <!DOCTYPE html>
692
- <html>
693
- <head>
694
- <title>404 - Not Found</title>
695
- <style>
696
- body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
697
- </style>
698
- </head>
699
- <body>
700
- <h1>404 - Not Found</h1>
701
- <p>The requested resource was not found on this server.</p>
702
- <p><a href="/">Return to homepage</a></p>
703
- </body>
704
- </html>
705
- `);
706
- }), t.start = (l) => {
707
- const p = t.listen(e, () => {
708
- console.log(`
709
- 🚀 Frontend Hamroun server running at http://localhost:${e}
710
- ${Object.keys(I).length > 0 ? `
711
- 📡 Registered API Routes:
712
- ${Object.keys(I).map((g) => ` ${g}`).join(`
713
- `)}` : ""}
714
- ${Object.keys(Q).length > 0 ? `
715
- 🖥️ Registered SSR Routes:
716
- ${Object.keys(Q).map((g) => ` ${g}`).join(`
717
- `)}` : ""}
718
- `), l && l();
719
- }), f = async (g) => {
720
- console.log(`${g} signal received: closing HTTP server and cleaning up`), p.close(async () => {
721
- console.log("HTTP server closed"), y && y.isConnected() && (await y.disconnect(), console.log("Database connection closed")), w.exit(0);
722
- }), setTimeout(() => {
723
- console.error("Could not close connections in time, forcefully shutting down"), w.exit(1);
724
- }, 1e4);
725
- };
726
- return w.on("SIGTERM", () => f("SIGTERM")), w.on("SIGINT", () => f("SIGINT")), p;
727
- }, t;
728
- }
729
- const te = require("jsonwebtoken"), pe = require("bcrypt"), Ke = require("crypto");
730
- class et {
731
- constructor(t) {
732
- if (this.loginAttempts = /* @__PURE__ */ new Map(), this.login = async (e, s) => {
733
- try {
734
- const { username: n, password: i } = e.body, o = e.ip || e.connection.remoteAddress || "";
735
- if (!this.checkRateLimit(o)) {
736
- s.status(429).json({
737
- success: !1,
738
- message: "Too many login attempts. Please try again later."
739
- });
740
- return;
741
- }
742
- if (!n || !i) {
743
- s.status(400).json({
744
- success: !1,
745
- message: "Username and password are required"
746
- });
747
- return;
748
- }
749
- if (!this.options.findUser) {
750
- s.status(500).json({
751
- success: !1,
752
- message: "User finder function not configured"
753
- });
754
- return;
755
- }
756
- const c = await this.options.findUser(n);
757
- if (!c) {
758
- s.status(401).json({
759
- success: !1,
760
- message: "Invalid credentials"
761
- });
762
- return;
763
- }
764
- if (!await this.options.verifyPassword(
765
- i,
766
- c.password
767
- )) {
768
- s.status(401).json({
769
- success: !1,
770
- message: "Invalid credentials"
771
- });
772
- return;
773
- }
774
- const d = { ...c };
775
- delete d.password;
776
- const h = this.generateTokenPair({
777
- id: c.id || c._id,
778
- username: c.username,
779
- role: c.role || "user"
780
- });
781
- if (this.options.saveRefreshToken) {
782
- const E = /* @__PURE__ */ new Date();
783
- E.setSeconds(E.getSeconds() + this.getExpirationSeconds(this.options.refreshExpiration || "7d")), await this.options.saveRefreshToken(
784
- c.id || c._id,
785
- h.refreshToken,
786
- E
787
- );
788
- }
789
- e.body.useCookies && this.setAuthCookies(s, h), s.json({
790
- success: !0,
791
- message: "Authentication successful",
792
- tokens: h,
793
- user: d
794
- });
795
- } catch (n) {
796
- console.error("Authentication error:", n), s.status(500).json({
797
- success: !1,
798
- message: "Authentication failed",
799
- error: w.env.NODE_ENV !== "production" ? n.message : void 0
800
- });
801
- }
802
- }, this.refreshToken = async (e, s) => {
803
- var n, i;
804
- try {
805
- const o = ((n = e.cookies) == null ? void 0 : n.refreshToken) || e.body.refreshToken;
806
- if (!o) {
807
- s.status(401).json({
808
- success: !1,
809
- message: "Refresh token required"
810
- });
811
- return;
812
- }
813
- const c = this.verifyToken(o, "refresh");
814
- if (this.options.verifyRefreshToken && !await this.options.verifyRefreshToken(c.id, o)) {
815
- this.clearAuthCookies(s), s.status(401).json({
816
- success: !1,
817
- message: "Invalid refresh token"
818
- });
819
- return;
820
- }
821
- const a = this.generateTokenPair({
822
- id: c.id,
823
- // We need to fetch the user data again for complete payload
824
- ...this.options.findUser ? await this.options.findUser(c.id) : {}
825
- });
826
- if (this.options.saveRefreshToken) {
827
- const h = /* @__PURE__ */ new Date();
828
- h.setSeconds(h.getSeconds() + this.getExpirationSeconds(this.options.refreshExpiration || "7d")), await this.options.saveRefreshToken(
829
- c.id,
830
- a.refreshToken,
831
- h
832
- );
833
- }
834
- (((i = e.cookies) == null ? void 0 : i.accessToken) || e.body.useCookies) && this.setAuthCookies(s, a), s.json({
835
- success: !0,
836
- message: "Token refreshed successfully",
837
- tokens: a
838
- });
839
- } catch (o) {
840
- this.clearAuthCookies(s), s.status(401).json({
841
- success: !1,
842
- message: "Invalid or expired refresh token",
843
- error: w.env.NODE_ENV !== "production" ? o.message : void 0
844
- });
845
- }
846
- }, this.logout = async (e, s) => {
847
- var n;
848
- try {
849
- this.clearAuthCookies(s);
850
- const i = ((n = e.cookies) == null ? void 0 : n.refreshToken) || e.body.refreshToken;
851
- if (i && this.options.saveRefreshToken)
852
- try {
853
- const o = this.verifyToken(i, "refresh");
854
- typeof this.options.saveRefreshToken == "function" && await this.options.saveRefreshToken(o.id, "", /* @__PURE__ */ new Date());
855
- } catch {
856
- }
857
- s.json({ success: !0, message: "Logged out successfully" });
858
- } catch (i) {
859
- console.error("Logout error:", i), s.status(500).json({ success: !1, message: "Logout failed", error: i.message });
860
- }
861
- }, this.authenticate = (e, s, n) => {
862
- var i;
863
- try {
864
- let o = (i = e.cookies) == null ? void 0 : i.accessToken;
865
- if (!o) {
866
- const a = e.headers.authorization;
867
- a && a.startsWith("Bearer ") && (o = a.split(" ")[1]);
868
- }
869
- if (!o) {
870
- s.status(401).json({
871
- success: !1,
872
- message: "Authentication required"
873
- });
874
- return;
875
- }
876
- const c = this.verifyToken(o, "access");
877
- e.user = c, n();
878
- } catch (o) {
879
- s.status(401).json({
880
- success: !1,
881
- message: "Invalid or expired token",
882
- error: w.env.NODE_ENV !== "production" ? o.message : void 0
883
- });
884
- }
885
- }, this.hasRole = (e) => (s, n, i) => {
886
- const o = s.user;
887
- if (!o) {
888
- n.status(401).json({
889
- success: !1,
890
- message: "Authentication required"
891
- });
892
- return;
893
- }
894
- (Array.isArray(e) ? e : [e]).includes(o.role) ? i() : n.status(403).json({
895
- success: !1,
896
- message: "Insufficient permissions"
897
- });
898
- }, this.options = {
899
- tokenExpiration: "15m",
900
- refreshExpiration: "7d",
901
- saltRounds: 10,
902
- secureCookies: w.env.NODE_ENV === "production",
903
- httpOnlyCookies: !0,
904
- rateLimit: !0,
905
- ...t,
906
- refreshSecret: t.refreshSecret || t.jwtSecret
907
- }, !t.jwtSecret)
908
- throw new Error("JWT secret is required for authentication");
909
- this.options.verifyPassword || (this.options.verifyPassword = this.verifyPasswordWithBcrypt);
910
- }
911
- /**
912
- * Hash a password using bcrypt
913
- */
914
- async hashPassword(t) {
915
- return await pe.hash(t, this.options.saltRounds || 10);
916
- }
917
- /**
918
- * Verify a password against a hash using bcrypt
919
- */
920
- async verifyPasswordWithBcrypt(t, e) {
921
- return await pe.compare(t, e);
922
- }
923
- /**
924
- * Generate a cryptographically secure random token
925
- */
926
- generateSecureToken(t = 32) {
927
- return Ke.randomBytes(t).toString("hex");
928
- }
929
- /**
930
- * Generate token pair (access token + refresh token)
931
- */
932
- generateTokenPair(t) {
933
- const e = this.getExpirationSeconds(this.options.tokenExpiration || "15m"), s = te.sign(
934
- { ...t, type: "access" },
935
- this.options.jwtSecret,
936
- { expiresIn: this.options.tokenExpiration }
937
- ), n = te.sign(
938
- { id: t.id, type: "refresh" },
939
- this.options.refreshSecret,
940
- { expiresIn: this.options.refreshExpiration }
941
- );
942
- return {
943
- accessToken: s,
944
- refreshToken: n,
945
- expiresIn: e
946
- };
947
- }
948
- /**
949
- * Convert JWT expiration time to seconds
950
- */
951
- getExpirationSeconds(t) {
952
- const e = t.charAt(t.length - 1), s = parseInt(t.slice(0, -1));
953
- switch (e) {
954
- case "s":
955
- return s;
956
- case "m":
957
- return s * 60;
958
- case "h":
959
- return s * 60 * 60;
960
- case "d":
961
- return s * 60 * 60 * 24;
962
- default:
963
- return 3600;
964
- }
965
- }
966
- /**
967
- * Verify a JWT token
968
- */
969
- verifyToken(t, e = "access") {
970
- try {
971
- const s = e === "access" ? this.options.jwtSecret : this.options.refreshSecret, n = te.verify(t, s);
972
- if (typeof n == "object" && n.type !== e)
973
- throw new Error("Invalid token type");
974
- return n;
975
- } catch {
976
- throw new Error("Invalid or expired token");
977
- }
978
- }
979
- /**
980
- * Set authentication cookies
981
- */
982
- setAuthCookies(t, e) {
983
- t.cookie("accessToken", e.accessToken, {
984
- httpOnly: this.options.httpOnlyCookies,
985
- secure: this.options.secureCookies,
986
- domain: this.options.cookieDomain,
987
- sameSite: "strict",
988
- maxAge: e.expiresIn * 1e3
989
- });
990
- const s = this.getExpirationSeconds(this.options.refreshExpiration || "7d");
991
- t.cookie("refreshToken", e.refreshToken, {
992
- httpOnly: !0,
993
- // Always HTTP only for refresh tokens
994
- secure: this.options.secureCookies,
995
- domain: this.options.cookieDomain,
996
- sameSite: "strict",
997
- maxAge: s * 1e3,
998
- path: "/api/auth/refresh"
999
- // Restrict to refresh endpoint
1000
- });
1001
- }
1002
- /**
1003
- * Clear authentication cookies
1004
- */
1005
- clearAuthCookies(t) {
1006
- t.clearCookie("accessToken"), t.clearCookie("refreshToken", { path: "/api/auth/refresh" });
1007
- }
1008
- /**
1009
- * Check and handle rate limiting
1010
- */
1011
- checkRateLimit(t) {
1012
- if (!this.options.rateLimit)
1013
- return !0;
1014
- const e = Date.now(), s = this.loginAttempts.get(t);
1015
- return s ? e > s.resetTime ? (this.loginAttempts.set(t, { count: 1, resetTime: e + 36e5 }), !0) : s.count >= 5 ? !1 : (s.count++, this.loginAttempts.set(t, s), !0) : (this.loginAttempts.set(t, { count: 1, resetTime: e + 36e5 }), !0);
1016
- }
1017
- }
1018
- function tt(r) {
1019
- return new et(r);
1020
- }
1021
- function rt(r, t) {
1022
- const e = j.model(r, t);
1023
- return {
1024
- getAll: async (s) => {
1025
- try {
1026
- const { page: n = 1, limit: i = 10, sort: o = "_id", order: c = "desc" } = s || {}, a = (n - 1) * i, d = c === "asc" ? 1 : -1, h = { [o]: d }, [E, S] = await Promise.all([
1027
- e.find().sort(h).skip(a).limit(i).exec(),
1028
- e.countDocuments().exec()
1029
- ]), y = Math.ceil(S / i);
1030
- return {
1031
- data: E,
1032
- pagination: {
1033
- total: S,
1034
- totalPages: y,
1035
- currentPage: n,
1036
- limit: i,
1037
- hasNextPage: n < y,
1038
- hasPrevPage: n > 1
1039
- }
1040
- };
1041
- } catch (n) {
1042
- throw console.error(`Error in ${r}.getAll:`, n), new Error(`Failed to retrieve ${r} records: ${n.message}`);
1043
- }
1044
- },
1045
- getById: async (s) => {
1046
- try {
1047
- return j.isValidObjectId(s) ? await e.findById(s).exec() : null;
1048
- } catch (n) {
1049
- throw console.error(`Error in ${r}.getById:`, n), new Error(`Failed to retrieve ${r} by ID: ${n.message}`);
1050
- }
1051
- },
1052
- create: async (s) => {
1053
- try {
1054
- return await new e(s).save();
1055
- } catch (n) {
1056
- throw console.error(`Error in ${r}.create:`, n), new Error(`Failed to create ${r}: ${n.message}`);
1057
- }
1058
- },
1059
- createMany: async (s) => {
1060
- try {
1061
- return await e.insertMany(s);
1062
- } catch (n) {
1063
- throw console.error(`Error in ${r}.createMany:`, n), new Error(`Failed to create multiple ${r} records: ${n.message}`);
1064
- }
1065
- },
1066
- update: async (s, n) => {
1067
- try {
1068
- return j.isValidObjectId(s) ? await e.findByIdAndUpdate(
1069
- s,
1070
- { $set: n },
1071
- { new: !0, runValidators: !0 }
1072
- ).exec() : null;
1073
- } catch (i) {
1074
- throw console.error(`Error in ${r}.update:`, i), new Error(`Failed to update ${r}: ${i.message}`);
1075
- }
1076
- },
1077
- delete: async (s) => {
1078
- try {
1079
- return j.isValidObjectId(s) ? await e.findByIdAndDelete(s).exec() !== null : !1;
1080
- } catch (n) {
1081
- throw console.error(`Error in ${r}.delete:`, n), new Error(`Failed to delete ${r}: ${n.message}`);
1082
- }
1083
- },
1084
- find: async (s, n) => {
1085
- try {
1086
- const { page: i = 1, limit: o = 10, sort: c = "_id", order: a = "desc" } = n || {}, d = (i - 1) * o, h = a === "asc" ? 1 : -1, E = { [c]: h }, [S, y] = await Promise.all([
1087
- e.find(s).sort(E).skip(d).limit(o).exec(),
1088
- e.countDocuments(s).exec()
1089
- ]), I = Math.ceil(y / o);
1090
- return {
1091
- data: S,
1092
- pagination: {
1093
- total: y,
1094
- totalPages: I,
1095
- currentPage: i,
1096
- limit: o,
1097
- hasNextPage: i < I,
1098
- hasPrevPage: i > 1
1099
- }
1100
- };
1101
- } catch (i) {
1102
- throw console.error(`Error in ${r}.find:`, i), new Error(`Failed to find ${r} records: ${i.message}`);
1103
- }
1104
- },
1105
- count: async (s) => {
1106
- try {
1107
- return await e.countDocuments(s || {}).exec();
1108
- } catch (n) {
1109
- throw console.error(`Error in ${r}.count:`, n), new Error(`Failed to count ${r} records: ${n.message}`);
1110
- }
1111
- },
1112
- findOne: async (s) => {
1113
- try {
1114
- return await e.findOne(s).exec();
1115
- } catch (n) {
1116
- throw console.error(`Error in ${r}.findOne:`, n), new Error(`Failed to find ${r} record: ${n.message}`);
1117
- }
1118
- }
1119
- };
1120
- }
1121
- const st = {
1122
- String: { type: String },
1123
- Number: { type: Number },
1124
- Boolean: { type: Boolean },
1125
- Date: { type: Date },
1126
- ObjectId: { type: String },
1127
- // Fallback to String instead of using Schema.Types.ObjectId
1128
- // Helper functions for common field patterns
1129
- Required: (r) => ({ ...r, required: !0 }),
1130
- Unique: (r) => ({ ...r, unique: !0 }),
1131
- Ref: (r) => ({
1132
- type: String,
1133
- // Fallback to String type for tests
1134
- ref: r
1135
- }),
1136
- Enum: (r) => ({ type: String, enum: r }),
1137
- Default: (r, t) => ({ ...r, default: t }),
1138
- // Array field type
1139
- Array: (r) => ({ type: [r] })
1140
- }, Ce = (r, { res: t }) => {
1141
- console.error("API Error:", r);
1142
- const e = r.status || r.statusCode || 500, s = r.message || "Internal server error";
1143
- t.status(e).json({
1144
- success: !1,
1145
- error: s,
1146
- stack: w.env.NODE_ENV !== "production" ? r.stack : void 0
1147
- });
1148
- };
1149
- function nt(r, t = {}) {
1150
- const e = O.Router(), { middleware: s = [], errorHandler: n = Ce } = t;
1151
- s.forEach((o) => e.use(o));
1152
- const i = (o) => async (c, a, d) => {
1153
- try {
1154
- const h = { req: c, res: a, next: d, params: c.params, query: c.query, body: c.body };
1155
- return await o(h);
1156
- } catch (h) {
1157
- const E = { req: c, res: a, next: d, params: c.params, query: c.query, body: c.body };
1158
- return n(h, E);
1159
- }
1160
- };
1161
- return e.get("/", i(async ({ req: o, res: c }) => {
1162
- const a = o.pagination || { page: 1, limit: 10 }, d = await r.getAll(a);
1163
- c.json({
1164
- success: !0,
1165
- ...d
1166
- });
1167
- })), e.get("/:id", i(async ({ params: o, res: c }) => {
1168
- const a = await r.getById(o.id);
1169
- if (!a) {
1170
- c.status(404).json({
1171
- success: !1,
1172
- error: "Item not found"
1173
- });
1174
- return;
1175
- }
1176
- c.json({
1177
- success: !0,
1178
- data: a
1179
- });
1180
- })), e.post("/", i(async ({ body: o, res: c }) => {
1181
- const a = await r.create(o);
1182
- c.status(201).json({
1183
- success: !0,
1184
- data: a,
1185
- message: "Item created successfully"
1186
- });
1187
- })), e.put("/:id", i(async ({ params: o, body: c, res: a }) => {
1188
- const d = await r.update(o.id, c);
1189
- if (!d) {
1190
- a.status(404).json({
1191
- success: !1,
1192
- error: "Item not found"
1193
- });
1194
- return;
1195
- }
1196
- a.json({
1197
- success: !0,
1198
- data: d,
1199
- message: "Item updated successfully"
1200
- });
1201
- })), e.delete("/:id", i(async ({ params: o, res: c }) => {
1202
- if (!await r.delete(o.id)) {
1203
- c.status(404).json({
1204
- success: !1,
1205
- error: "Item not found"
1206
- });
1207
- return;
1208
- }
1209
- c.json({
1210
- success: !0,
1211
- message: "Item deleted successfully"
1212
- });
1213
- })), e;
1214
- }
1215
- function ot(r, t = {}) {
1216
- const e = O.Router(), { middleware: s = [], errorHandler: n = Ce } = t;
1217
- s.forEach((o) => e.use(o));
1218
- const i = (o) => async (c, a, d) => {
1219
- try {
1220
- const h = { req: c, res: a, next: d, params: c.params, query: c.query, body: c.body };
1221
- return a.headersSent ? void 0 : await o(h);
1222
- } catch (h) {
1223
- if (a.headersSent) {
1224
- console.error("Error occurred after response was sent:", h);
1225
- return;
1226
- }
1227
- const E = { req: c, res: a, next: d, params: c.params, query: c.query, body: c.body };
1228
- return n(h, E);
1229
- }
1230
- };
1231
- return Object.entries(r).forEach(([o, c]) => {
1232
- const { method: a, handler: d } = c;
1233
- e[a](o, i(d));
1234
- }), e;
1235
- }
1236
- function le(r, t, e, s, n) {
1237
- const i = { success: r };
1238
- return t !== void 0 && (i.data = t), e && (i.message = e), s && (i.error = s), n && (i.meta = n), i;
1239
- }
1240
- function R(r, t, e, s = 200, n) {
1241
- r.status(s).json(le(!0, t, e, void 0, n));
1242
- }
1243
- function M(r, t, e = 400, s) {
1244
- const n = t instanceof Error ? t.message : t;
1245
- r.status(e).json(le(!1, void 0, void 0, n, s));
1246
- }
1247
- function je(r) {
1248
- const t = parseInt(r.query.page) || 1, e = parseInt(r.query.limit) || 10, s = r.query.sort || "createdAt", n = r.query.order === "asc" ? "asc" : "desc";
1249
- return { page: t, limit: e, sort: s, order: n };
1250
- }
1251
- function $e(r, t, e) {
1252
- r.pagination = je(r), e();
1253
- }
1254
- function it(r) {
1255
- return (t, e, s) => {
1256
- try {
1257
- const { error: n, value: i } = r.validate(t.body);
1258
- if (n) {
1259
- M(e, `Validation error: ${n.message}`, 400);
1260
- return;
1261
- }
1262
- t.body = i, s();
1263
- } catch {
1264
- M(e, "Validation error", 400);
1265
- }
1266
- };
1267
- }
1268
- function ct(r = {}, t) {
1269
- const e = me();
1270
- return r.requireAuth && t && (e.use(t.authenticate), r.requiredRole && e.use(t.hasRole(r.requiredRole))), r.rateLimit && console.warn("Rate limiting is disabled: express-rate-limit dependency is not installed"), e;
1271
- }
1272
- function N(r) {
1273
- return (t, e, s) => {
1274
- r(t, e, s).catch(s);
1275
- };
1276
- }
1277
- function at(r) {
1278
- const t = me();
1279
- return t.get("/", $e, N(async (e, s) => {
1280
- const n = await r.getAll(e.pagination);
1281
- R(s, n);
1282
- })), t.get("/:id", N(async (e, s) => {
1283
- const n = await r.getById(e.params.id);
1284
- if (!n)
1285
- return M(s, "Item not found", 404);
1286
- R(s, n);
1287
- })), t.post("/", N(async (e, s) => {
1288
- const n = await r.create(e.body);
1289
- R(s, n, "Item created successfully", 201);
1290
- })), t.put("/:id", N(async (e, s) => {
1291
- const n = await r.update(e.params.id, e.body);
1292
- if (!n)
1293
- return M(s, "Item not found", 404);
1294
- R(s, n, "Item updated successfully");
1295
- })), t.delete("/:id", N(async (e, s) => {
1296
- if (!await r.delete(e.params.id))
1297
- return M(s, "Item not found", 404);
1298
- R(s, null, "Item deleted successfully");
1299
- })), t;
1300
- }
1301
- const gt = {
1302
- // Frontend
1303
- jsx: J,
1304
- jsxs: be,
1305
- jsxDEV: ke,
1306
- // Add to default export
1307
- createElement: ne,
1308
- Fragment: Te,
1309
- Component: He,
1310
- useState: xe,
1311
- useEffect: We,
1312
- useRef: qe,
1313
- useMemo: Ue,
1314
- useErrorBoundary: Ge,
1315
- render: ue,
1316
- hydrate: Je,
1317
- renderToString: D,
1318
- prepareRender: U,
1319
- finishRender: q,
1320
- batchUpdates: ae,
1321
- createContext: ze,
1322
- useContext: Xe,
1323
- // Backend
1324
- createServer: Ze,
1325
- createAuth: tt,
1326
- createModel: rt,
1327
- FieldTypes: st,
1328
- createModelRouter: nt,
1329
- createCustomRouter: ot,
1330
- createApiRouter: ct,
1331
- sendSuccess: R,
1332
- sendError: M,
1333
- apiResponse: le,
1334
- getPaginationParams: je,
1335
- paginationMiddleware: $e,
1336
- validateRequest: it,
1337
- asyncHandler: N,
1338
- createRestEndpoints: at,
1339
- DatabaseConnector: Ae
1340
- };
1341
- export {
1342
- He as Component,
1343
- Ae as DatabaseConnector,
1344
- st as FieldTypes,
1345
- Te as Fragment,
1346
- le as apiResponse,
1347
- N as asyncHandler,
1348
- ae as batchUpdates,
1349
- ct as createApiRouter,
1350
- tt as createAuth,
1351
- ze as createContext,
1352
- ot as createCustomRouter,
1353
- ne as createElement,
1354
- rt as createModel,
1355
- nt as createModelRouter,
1356
- at as createRestEndpoints,
1357
- Ze as createServer,
1358
- gt as default,
1359
- q as finishRender,
1360
- je as getPaginationParams,
1361
- Je as hydrate,
1362
- J as jsx,
1363
- ke as jsxDEV,
1364
- be as jsxs,
1365
- $e as paginationMiddleware,
1366
- U as prepareRender,
1367
- ue as render,
1368
- D as renderToString,
1369
- M as sendError,
1370
- R as sendSuccess,
1371
- Xe as useContext,
1372
- We as useEffect,
1373
- Ge as useErrorBoundary,
1374
- Ue as useMemo,
1375
- qe as useRef,
1376
- xe as useState,
1377
- it as validateRequest
1378
- };