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