frontend-hamroun 1.2.4 → 1.2.5

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