-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
543 lines (488 loc) · 14.6 KB
/
index.js
File metadata and controls
543 lines (488 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import dotenv from "dotenv";
import mainRoutes from "./routes/main.js";
import dashboardRoutes from "./routes/dashboard.js";
import { engine } from "express-handlebars";
import Handlebars from "handlebars";
import minifyHTML from "express-minify-html";
import minify from "express-minify";
import compression from "compression";
import mbkAuthRouter from "mbkauthe";
import { renderError } from "mbkauthe";
dotenv.config();
const app = express();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const router = app;
router.use(express.json());
router.use(mbkAuthRouter);
router.use(compression());
router.use(minify());
router.use(
minifyHTML({
override: true,
htmlMinifier: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
minifyCSS: true,
minifyJS: true,
},
})
);
// Configure Handlebars
router.engine("handlebars", engine({
partialsDir: [
path.join(__dirname, "node_modules/mbkauthe/views"),
path.join(__dirname, "views/notice"),
path.join(__dirname, "views")
],
cache: false,
helpers: { // <-- ADD THIS helpers OBJECT
eq: function (a, b) { // <-- Move your helpers inside here
return a === b;
},
encodeURIComponent: function (str) {
return encodeURIComponent(str);
},
formatTimestamp: function (timestamp) {
return new Date(timestamp).toLocaleString();
},
jsonStringify: function (context) {
return JSON.stringify(context);
},
percentage: function (used, total) {
if (total === 0) return 0;
return Math.round((used / total) * 100);
}, formatDate: function (dateString) {
if (!dateString) return '';
const date = new Date(dateString);
return date.toLocaleString();
},
gt: function (a, b) {
return a > b;
},
lt: function (a, b) {
return a < b;
},
lte: function (a, b) {
return a <= b;
},
gte: function (a, b) {
return a >= b;
},
add: function (a, b) {
return a + b;
},
subtract: function (a, b) {
return a - b;
},
multiply: function (a, b) {
return a * b;
},
divide: function (a, b) {
if (b === 0) return 0;
return a / b;
},
jsonb_array_length: function (jsonArray) {
if (!jsonArray) return 0;
if (typeof jsonArray === 'string') {
try {
return JSON.parse(jsonArray).length;
} catch (e) {
return 0;
}
}
if (Array.isArray(jsonArray)) {
return jsonArray.length;
}
return 0;
},
includes: function (array, value) {
if (!array) return false;
if (Array.isArray(array)) {
return array.includes(value);
}
return false;
},
len: function (value) {
if (!value) return 0;
if (typeof value === 'string') return value.length;
if (Array.isArray(value)) return value.length;
if (typeof value === 'object') return Object.keys(value).length;
return 0;
},
isEmpty: function (value) {
if (!value) return true;
if (typeof value === 'string') return value.length === 0;
if (Array.isArray(value)) return value.length === 0;
if (typeof value === 'object') return Object.keys(value).length === 0;
return false;
},
isNotEmpty: function (value) {
return !this.isEmpty(value);
},
first: function (array) {
if (!array || !Array.isArray(array)) return null;
return array[0];
},
last: function (array) {
if (!array || !Array.isArray(array)) return null;
return array[array.length - 1];
},
slice: function (array, start, end) {
if (!array || !Array.isArray(array)) return [];
return array.slice(start, end);
},
join: function (array, separator) {
if (!array || !Array.isArray(array)) return '';
return array.join(separator || ',');
},
split: function (string, separator) {
if (!string || typeof string !== 'string') return [];
return string.split(separator || ',');
},
capitalize: function (str) {
if (!str || typeof str !== 'string') return '';
return str.charAt(0).toUpperCase() + str.slice(1);
},
uppercase: function (str) {
if (!str || typeof str !== 'string') return '';
return str.toUpperCase();
},
lowercase: function (str) {
if (!str || typeof str !== 'string') return '';
return str.toLowerCase();
},
concat: function (...args) {
// Remove the options object that is provided by Handlebars
const options = args.pop();
return args.join('');
},
default: function (value, defaultValue) {
return value || defaultValue;
},
or: function (...args) {
// Remove the options object that is provided by Handlebars
const options = args.pop();
return args.find(arg => !!arg) || false;
},
not: function (value) {
return !value;
},
mod: function (a, b) {
if (b === 0) return 0;
return a % b;
},
abs: function (value) {
return Math.abs(value);
},
round: function (value, precision) {
if (precision) {
return Math.round(value * Math.pow(10, precision)) / Math.pow(10, precision);
}
return Math.round(value);
},
floor: function (value) {
return Math.floor(value);
},
ceil: function (value) {
return Math.ceil(value);
},
min: function (...args) {
const options = args.pop();
return Math.min(...args);
},
max: function (...args) {
const options = args.pop();
return Math.max(...args);
},
formatNumber: function (num, decimals) {
if (typeof num !== 'number') return '0';
return num.toFixed(decimals || 0);
},
formatBytes: function (bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
},
formatDuration: function (seconds) {
if (!seconds) return '0s';
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
if (h > 0) return `${h}h ${m}m ${s}s`;
if (m > 0) return `${m}m ${s}s`;
return `${s}s`;
},
formatPercent: function (value, total) {
if (!total || total === 0) return '0%';
return Math.round((value / total) * 100) + '%';
},
range: function (start, end) {
const result = [];
for (let i = start; i <= end; i++) {
result.push(i);
}
return result;
},
formatTime: function (index) {
// Simple implementation - in a real app you might want actual timestamps
return `Message ${index + 1}`;
},
and: function (...args) {
// Remove the options object that is provided by Handlebars
const options = args.pop();
return args.every(Boolean);
},
neq: function (a, b, options) {
if (options && typeof options.fn === 'function') {
return a !== b ? options.fn(this) : options.inverse(this);
}
// Fallback for inline usage
return a !== b;
},
truncate: function (str, len) {
if (typeof str !== "string") return "";
// Default length = 50 if not provided
const limit = len || 50;
return str.length > limit ? str.substring(0, limit) + "..." : str;
},
formatUptime: function () { // <-- New helper
const uptime = process.uptime();
const h = Math.floor(uptime / 3600);
const m = Math.floor((uptime % 3600) / 60);
const s = Math.floor(uptime % 60);
return `${h}h ${m}m ${s}s`;
}
}
}));
Handlebars.registerHelper('divide', function (value, divisor, multiplier) {
if (divisor == 0) {
return 0;
}
return (value / divisor) * multiplier;
});
Handlebars.registerHelper('multiply', function (a, b) {
return a * b;
});
Handlebars.registerHelper('subtract', function (a, b) {
return a - b;
});
Handlebars.registerHelper('add', function (a, b) {
return a + b;
});
Handlebars.registerHelper('gte', function (a, b) {
return a >= b;
});
Handlebars.registerHelper('lte', function (a, b) {
return a <= b;
});
// Additional commonly used helpers
Handlebars.registerHelper('jsonb_array_length', function (jsonArray) {
if (!jsonArray) return 0;
if (typeof jsonArray === 'string') {
try {
return JSON.parse(jsonArray).length;
} catch (e) {
return 0;
}
}
if (Array.isArray(jsonArray)) {
return jsonArray.length;
}
return 0;
});
Handlebars.registerHelper('includes', function (array, value) {
if (!array) return false;
if (Array.isArray(array)) {
return array.includes(value);
}
return false;
});
Handlebars.registerHelper('len', function (value) {
if (!value) return 0;
if (typeof value === 'string') return value.length;
if (Array.isArray(value)) return value.length;
if (typeof value === 'object') return Object.keys(value).length;
return 0;
});
Handlebars.registerHelper('isEmpty', function (value) {
if (!value) return true;
if (typeof value === 'string') return value.length === 0;
if (Array.isArray(value)) return value.length === 0;
if (typeof value === 'object') return Object.keys(value).length === 0;
return false;
});
Handlebars.registerHelper('isNotEmpty', function (value) {
return !Handlebars.helpers.isEmpty(value);
});
Handlebars.registerHelper('or', function (...args) {
const options = args.pop();
return args.find(arg => !!arg) || false;
});
Handlebars.registerHelper('not', function (value) {
return !value;
});
Handlebars.registerHelper('concat', function (...args) {
const options = args.pop();
return args.join('');
});
Handlebars.registerHelper('default', function (value, defaultValue) {
return value || defaultValue;
});
Handlebars.registerHelper('capitalize', function (str) {
if (!str || typeof str !== 'string') return '';
return str.charAt(0).toUpperCase() + str.slice(1);
});
Handlebars.registerHelper('uppercase', function (str) {
if (!str || typeof str !== 'string') return '';
return str.toUpperCase();
});
Handlebars.registerHelper('lowercase', function (str) {
if (!str || typeof str !== 'string') return '';
return str.toLowerCase();
});
Handlebars.registerHelper('mod', function (a, b) {
if (b === 0) return 0;
return a % b;
});
Handlebars.registerHelper('abs', function (value) {
return Math.abs(value);
});
Handlebars.registerHelper('round', function (value, precision) {
if (precision) {
return Math.round(value * Math.pow(10, precision)) / Math.pow(10, precision);
}
return Math.round(value);
});
Handlebars.registerHelper('floor', function (value) {
return Math.floor(value);
});
Handlebars.registerHelper('ceil', function (value) {
return Math.ceil(value);
});
Handlebars.registerHelper('formatNumber', function (num, decimals) {
if (typeof num !== 'number') return '0';
return num.toFixed(decimals || 0);
});
Handlebars.registerHelper('formatBytes', function (bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
});
Handlebars.registerHelper('formatDuration', function (seconds) {
if (!seconds) return '0s';
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
if (h > 0) return `${h}h ${m}m ${s}s`;
if (m > 0) return `${m}m ${s}s`;
return `${s}s`;
});
Handlebars.registerHelper('formatPercent', function (value, total) {
if (!total || total === 0) return '0%';
return Math.round((value / total) * 100) + '%';
});
Handlebars.registerHelper('join', function (array, separator) {
if (!array || !Array.isArray(array)) return '';
return array.join(separator || ',');
});
Handlebars.registerHelper('split', function (string, separator) {
if (!string || typeof string !== 'string') return [];
return string.split(separator || ',');
});
Handlebars.registerHelper('first', function (array) {
if (!array || !Array.isArray(array)) return null;
return array[0];
});
Handlebars.registerHelper('last', function (array) {
if (!array || !Array.isArray(array)) return null;
return array[array.length - 1];
});
Handlebars.registerHelper('slice', function (array, start, end) {
if (!array || !Array.isArray(array)) return [];
return array.slice(start, end);
});
Handlebars.registerHelper('min', function (...args) {
const options = args.pop();
return Math.min(...args);
});
Handlebars.registerHelper('max', function (...args) {
const options = args.pop();
return Math.max(...args);
});
router.set("view engine", "handlebars");
router.set("views", [
path.join(__dirname, "views"),
path.join(__dirname, "node_modules/mbkauthe/views")
]);
// Serve static files
router.use(
"/Assets",
express.static(path.join(__dirname, "public/Assets"), {
setHeaders: (res, path) => {
if (path.endsWith(".css")) {
res.setHeader("Content-Type", "text/css");
}
},
})
);
router.use('/Assets/Images', express.static(path.join(__dirname, 'Assets'), {
maxAge: '1d' // Cache assets for 1 day
}));
router.get(["/", "/info/main"], (req, res) => {
return res.render("staticPage/index.handlebars", { layout: false });
});
router.get(["/home"], (req, res) => {
return res.redirect("/chatbot");
});
router.use(mbkAuthRouter);
router.use("/", mainRoutes);
router.use("/", dashboardRoutes);
router.get("/admin*", async (req, res) => {
res.redirect("/admin/dashboard");
});
router.get("/dashboard", async (req, res) => {
res.redirect("/admin/dashboard");
});
router.get('/simulate-error', (req, res, next) => {
next(new Error('Simulated router error'));
});
// 404 handler
router.use((req, res) => {
console.log(`Path not found: ${req.method} ${req.url}`);
return renderError(res, req, {
layout: false,
code: 404,
error: "Not Found",
message: "The requested page was not found.",
pagename: "Home",
page: "/",
});
});
// Error handler
router.use((err, req, res, next) => {
console.error(err.stack);
return renderError(res, req, {
layout: false,
code: 500,
error: "Internal app Error",
message: "An unexpected error occurred on the app.",
details: err.message,
pagename: "Home",
page: "/",
});
});
const port = 3030;
// Start the router
router.listen(port, () => {
console.log(`router running on http://localhost:${port}`);
});
export default router;